Trac Macros

Trac macros are plugins to extend the Trac engine with custom 'functions' written in Python. A macro inserts dynamic HTML data in any context supporting WikiFormatting. Its syntax is [[macro-name(optional-arguments)]].

The WikiProcessors are another kind of macros. They typically deal with alternate markup formats and transformation of larger "blocks" of information, like source code highlighting. They are used for processing the multiline {{{#!wiki-processor-name ... }}} blocks.

Using Macros

Macro calls are enclosed in two square brackets [[..]]. Like Python functions, macros can also have arguments, a comma separated list within parentheses [[..(,)]].

Getting Detailed Help

The list of available macros and the full help can be obtained using the MacroList macro, as seen below.

A brief list can be obtained via [[MacroList(*)]] or [[?]].

Detailed help on a specific macro can be obtained by passing it as an argument to MacroList, e.g. [[MacroList(MacroList)]], or, more conveniently, by appending a question mark (?) to the macro's name, like in [[MacroList?]].

Example

A list of the 3 most recently changed wiki pages starting with 'Trac':

Wiki Markup Display
[[RecentChanges(Trac,3)]]

[[RecentChanges?(Trac,3)]]

[[RecentChanges]]

最近更新されたすべてのページを最後に変更した日付でグループ化し、リストします。

このマクロは、 2 つの引数をとります。最初の引数はプレフィックスの文字列です: プレフィックスが指定された場合、結果のリストにはそのプレフィックスで始まるページのみが 含まれます。この引数が省略された場合は、すべてのページがリストされます。

2番目の引数は結果リストに表示するページの数を制限するために使用します。 例えば 5 に制限すると指定した場合、最近更新されたページのうち、新しいもの 5 件がリストに含まれます。

[[?]]

[[Image]]

Embed an image in wiki-formatted text. The first argument is the file …

[[InterTrac]]

Provide a list of known InterTrac prefixes.

[[InterWiki]]

Provide a description list for the known InterWiki prefixes.

[[KnownMimeTypes]]

List all known mime-types which can be used as WikiProcessors. Can be …

etc.

Available Macros

Note that the following list will only contain the macro documentation if you've not enabled -OO optimizations, or not set the PythonOptimize option for mod_python.

[[InterTrac]]

Provide a list of known InterTrac prefixes.

[[TitleIndex]]

すべての Wiki ページをアルファベットのリスト形式で出力に挿入します。

引数として、接頭辞となる文字列を許容します: 指定された場合、 生成されるリストにはページ名が接頭辞で始まるものだけが含まれます。 すべてのページがリストされます。 接頭辞が与えられた上で、第二引数に 'hideprefix' が与えられた場合、 出力からは接頭辞が除外されます。

この他、 format および depth などを名前付き引数として指定できます:

  • format=compact: ページ名をカンマ区切りのリストとして表示します。
  • format=group: 共通の接頭辞を持つページでリストを生成します。 また min=n の引数を使用することができ、 n にはリストを生成するページの最小数を指定します。
  • format=hierarchy: ページ名をパスとした階層構造で表示します。 このフォーマットでも min=n の引数を使用することができ、 n には階層を生成するページの最小数を指定します。
  • depth=n: リストするページの階層数を指定します。 0を指定した場合、トップレベルのページのみ表示され、 1を指定した場合、1代目の子ページが表示されます。 何も指定しない場合か、-1を指定した場合、 全てのページが階層構造により表示されます。

[[RecentChanges]]

最近更新されたすべてのページを最後に変更した日付でグループ化し、リストします。

このマクロは、 2 つの引数をとります。最初の引数はプレフィックスの文字列です: プレフィックスが指定された場合、結果のリストにはそのプレフィックスで始まるページのみが 含まれます。この引数が省略された場合は、すべてのページがリストされます。

2番目の引数は結果リストに表示するページの数を制限するために使用します。 例えば 5 に制限すると指定した場合、最近更新されたページのうち、新しいもの 5 件がリストに含まれます。

[[PageOutline]]

現在の Wiki ページの構造的なアウトラインを表示します。 アウトラインのそれぞれの項目は一致する表題へのリンクとなります。

このマクロは 3 つの任意のパラメータをとります:

  • 1 番目の引数はアウトラインに含まれる表題の範囲 (レベル) を設定することができ、 数または数の範囲をとります。 例えば、 "1" と指定した場合、アウトラインにはトップレベルの表題のみが表示されます。 "2-3" と指定した場合、アウトラインには、レベル 2 とレベル 3 のすべての表題が ネストしたリストとして表示されます。 デフォルトでは、すべてのレベルの表題が表示されます。
  • 2 番目の引数は、タイトルを特定するのに使われます。 (デフォルトはタイトルなし)
  • 3 番目の引数はアウトラインのスタイルを指定します。 inline または pullout を指定することができます (後者がデフォルトです) 。 inline スタイルでは、アウトラインをコンテンツの一部として整形しますが、 pullout スタイルでは、アウトラインをフローティングボックスに整形し、 コンテンツの右側に配置します。

[[Image]]

画像を Wiki 形式のテキストに組み込みます。

1 番目の引数は、ファイル名を指定します。ファイルの指定は添付ファイルなど 3つの指定方法があります:

  • module:id:file: module に wiki または ticket が指定すると、 その Wiki ページまたはチケットの添付ファイルで file とファイル名が ついているものを参照します。
  • id:file: 上記と同様ですが、 id はチケットの短い記述方法か、 Wiki ページ名を指定します。
  • file: 'file' というローカルの添付ファイルを指します。これはファイルが 添付されている Wiki ページまたはチケットの中でのみ使用できます。

またファイルはリポジトリのファイルも指定できます。 source:file シンタックスを使用します。 (source:file@rev も可能です)

直接 URL を記述することもできます; /file と記述すると、プロジェクトの ディレクトリからの相対パスになり、 //file と記述すると、サーバルートからの パスになります。また、 http://server/file ではファイルの絶対パスになります。

残りの引数は任意で、 <img> 要素を組み立てる際の属性を設定します:

  • 数字と単位は画像のサイズと解釈されます。 (ex. 120, 25%)
  • right, left, center, top, bottom, middle は画像の配置として 解釈されます。 (right, left, centeralign=... でも指定でき、 top, bottom, middlevalign=... でも指定できます)
  • link=some TracLinks... を指定すると、画像のソースへのリンクが、 TracLinks に置き換えられます。値なしで引数が指定された場合、 リンクは単に削除されます。
  • nolink は画像のソースへのリンクを作成しません。 (非推奨, link= を使用してください)
  • key=value スタイルは画像の HTML 属性または CSS スタイルの

指示として解釈されます。有効なキーは以下の通りです:

  • align, valign, border, width, height, alt, title, longdesc, class, margin, margin-(left,right,top,bottom), id, usemap
  • border, margin, margin-* は数値での指定のみ可能です。
  • margincenter によって自動計算されたマージンを上書きします。

例:

    [[Image(photo.jpg)]]                           # シンプルな指定方法
    [[Image(photo.jpg, 120px)]]                    # 画像の幅サイズ指定
    [[Image(photo.jpg, right)]]                    # キーワードによる配置指定
    [[Image(photo.jpg, nolink)]]                   # ソースへのリンクなし
    [[Image(photo.jpg, align=right)]]              # 属性による配置指定

他の wiki ページ、チケット、モジュールの画像を使用することができます。

    [[Image(OtherPage:foo.bmp)]]    # 現在のモジュールが Wiki の場合
    [[Image(base/sub:bar.bmp)]]     # 下位の Wiki ページから
    [[Image(#3:baz.bmp)]]           # #3というチケットを指している場合
    [[Image(ticket:36:boo.jpg)]]
    [[Image(source:/images/bee.jpg)]] # リポジトリから直接指定する!
    [[Image(htdocs:foo/bar.png)]]   # プロジェクトの htdocs ディレクトリにあるファイル

このマクロは Shun-ichi Goto <gotoh@…> さんが作成した Image.py が 元になっています

[[MacroList]]

インストールされている、すべての Wiki マクロをリストします。 もし利用可能ならばドキュメントも含みます。

非必須オプションとして、特定のマクロの名前を引数として渡すことが出来ます。 この場合、指定されたマクロのドキュメントだけを表示します。

Note: このマクロは mod_python の PythonOptimize オプションが有効になっている 場合は、マクロのドキュメントを表示することが出来ません!

[[TracIni]]

Trac の設定ファイルのドキュメントを生成します。

通常、このマクロは Wiki ページ TracIni の中で使用されます。 省略可能な引数にはコンフィグのセクションのフィルタ、 コンフィグのオプション名のフィルタを指定できます: フィルタで指定された文字列 で始まるコンフィグのセクションとオプション名のみが出力されます。

[[KnownMimeTypes]]

WikiProcessors で処理できる既知の mime-type を表示します。

引数が与えられた場合は、 mime-type へのフィルタとして作用します。

[[TracGuideToc]]

Trac ガイドの目次を表示する。

このマクロは Help/Guide の目次 (ToC) を簡単かつ荒っぽく作成します。 この目次には Trac* と WikiFormatting のページが含まれていますが、 カスタマイズはできません。目次をカスタマイズしたい場合は、 TocMacro を探してください。

[[TicketQuery]]

指定された条件にマッチするチケットを一覧表示します。

このマクロの引数はカンマ区切りのリストにした、 "key=value" 形式の キー付きパラメータを使用します。

key がフィールド名であった場合、 value は TracQuery#QueryLanguage で 定義されているような、フィルタを指定するシンタックスでなければなりません。 ? の文字で始まる query: リンク向けの簡素化した URL シンタックス とは 異なります 。フィールドの値としてカンマ (,) そのものを含む場合は バックスラッシュ (,) でエスケープする必要があります。

引数 or で区切られたフィルタのグループは、 OR 条件で結合されます。

このほか、フィルタとしていくつか名前付きパラメータを使用できます。 これらは検索結果をどのように表示するかを制御できます。すべて非必須です。

format はチケットのリストがどのように表示されるかを決定します:

  • list -- デフォルトの表示形式です。チケット ID と概要 (Summary) を 一覧表示します。 1 行ごとに 1 つのチケットを表示します。
  • compact -- チケット ID の一覧をカンマ区切りで 表示します。
  • count -- 条件に当てはまるチケットの件数のみが表示されます。
  • table -- カスタムクエリービューと似た形式で表示されます (ただし コントロールは表示されません)。

max は表示されるチケット数の上限値を指定します (デフォルトは 0 です。これは無制限を意味します)。

order はチケットを整列する列を指定します (デフォルトは id となっています)。

desc はチケットの整列を逆順に行うか指定します。 (デフォルトは false です)。

group はチケットをグループ化を指定します (デフォルトは何も設定されていません)。

groupdesc はグループの表示を逆順とするかを指定します (デフォルトは false となっています)。

verbose を true に設定すると、リストされたチケットの 各行にチケットの説明を表示します。これは table format 専用です。 このパラメータは廃止予定です。代わりに rows を使用してください。

rows パラメータは1行使って表示するフィールドを指定します。 rows=description|summary のように使用します。

Trac 0.10 との互換性のため、マクロは最終引数にキーなし引数が与えられた場合 format として解釈します。 また、フィールドセパレータに使用する "&" は (order を除いて) 現時点では動作しますが、この機能は廃止予定です。

[[QueryChart]]

Draw Chart from Query.

 {{{
[[QueryChart(args1,args2,...)]]
 }}}

args:

 * query: Search condition of ticket. The following three kinds of can be described.
   * [http://trac.edgewall.org/wiki/TracQuery#QueryLanguage Query language] notation of TicketQuery macro:[[BR]]
     Write the condition without applying ? to the head. 
     Refer to the [http://trac.edgewall.org/wiki/TracQuery#QueryLanguage Query language] for details.[[BR]]
     !query:status=new|assigned&version;^=1.0
   * Notation displayed in URL with custom query:[[BR]]
     Write conditions delimited by & applying ? (Without forgetting :) to the head as follows. It might be 
     good to put the part of URL specifying the condition on the screen of custom query.[[BR]]
     !query:?status=new&status;=assigned&version;=^1.0
   * Omitte:[[BR]]
     It is possible to omit it only when putting it on the column the explanation of the report made from 
     custom query (which displayed in address field of a browser). It becomes a search condition specified the 
     omission on the screen. Please omit this item (query:...) when omitting it.
 * col: Targeted item. Please describe by col=xxx, col=yyy, and switching off the comma district when you 
   specify the plural. The item name can specify both the field name (name of the field in Trac) and the label 
   (displayed item name).
 * per:(=day,week,free) Unit of total. Default is week.
 * start: Day in left end of graph. If it is unspecification, it is the most past day of the ticket. yyyy/mm/dd form
 * end: Day on right edge in graph. If it is unspecification, it is the most recent day of the ticket. yyyy/mm/dd form
 * width: Width in graph. It specifies it by the unit of px. If it is unspecification, it is 536px.
 * height: Height of graph. It specifies it by the unit of px. If it is unspecification,    [[BR]]it is 300px.
 * upper: The improvement chart is written (bug settling curve etc.). Down chart when not specifying it.

[[AddComment]]

A macro to add comments to a page. Usage:

[[AddComment]]

The macro accepts one optional argument that allows appending to the wiki page even though user may not have modify permission:

[[AddComment(appendonly)]]

[[RepositoryIndex]]

リポジトリ一覧を表示します。

下記の名前付きの引数を使用することができます:

format
レンダリングするフォーマットを選択します:
  • compact はリポジトリのプレフィックスの名前をカンマ区切りの リストで表示します ( デフォルト )
  • list はリポジトリのプレフィックスの名前を、通常の記述のリストで表示します
  • table はリポジトリブラウザのトップページと同様の形式で 表形式で表示します
glob
リポジトリ名に対する glob 形式のフィルタとして作用します (デフォルトは '*' です)
order
引数で指定されたカラムでリポジトリを並べ替えます。 ( "name", "date" または、 "author" のいずれかを使用できます )
desc
1 を設定すると、降順に並べ替えます。

(0.12 以降)

[[Branches]]

Render a list of available branches.

[[TracAdminHelp]]

trac-admin コマンドのヘルプを表示します。

例:

[[TracAdminHelp]]               # 全てのコマンド
[[TracAdminHelp(wiki)]]         # 全ての wiki コマンド
[[TracAdminHelp(wiki export)]]  # "wiki export" コマンド
[[TracAdminHelp(upgrade)]]      # upgrade コマンド

[[ReportInclude]]

以下のようにWikiにマクロを記載することで、TracReportで定義されているレポートを表示します。 また、オプションを設定することで、レポートの表からグラフを生成することもできます。

[[ReportInclude(args1,args2,...)]]

args:

  • 表示したいTracReportのIDを指定します。必ず第1引数に指定する必要があります。
  • title: レポート、グラフのタイトル文字列を指定することができます。コロンに続けてタイトル文字列を指定します。未指定の場合は、TracReportのタイトル文字列が自動的に使用されます。
  • graph: グラフも合わせて表示する場合に指定します。コロンに続けて、以下の記載が可能です。
    • lines
      折れ線グラフを表示します。
    • bars
      棒グラフを表示します。
  • stack: グラフ表示時に、スタック(積み上げ)グラフとするかどうか指定します。コロンに続けて、以下の記載が可能です。
    • true
      スタック(積み上げ)グラフとして表示します。
    • false
      スタック(積み上げ)グラフとして表示しません。
  • legendLoc: グラフの凡例の表示位置を指定します。コロンに続けて、方角を示す nw, n, ne, e, se, s, sw, w のいずれかを指定します。
  • legendXOffset: グラフの凡例位置の横方向のオフセットを指定します。未指定の場合は12となります。
  • legendYOffset: グラフの凡例位置の縦方向のオフセットを指定します。未指定の場合は12となります。
  • dateFormat: X軸の値を日付としてグラフ表示する場合の、日付フォーマットを指定します。コロンに続けて、yyyy/MM/dd のように指定します。未指定の場合は、デフォルト値としてyyyy-MM-ddを使用します。
  • width: グラフの幅をpx単位で指定します。未指定の場合は536pxとなります。
  • height: グラフの高さをpx単位で指定します。未指定の場合は300pxとなります。
  • table: TracReportのテーブルを出力を制御できます。コロンに続けて、以下の記載が可能です。
    • hide
      テーブルを表示しません。グラフのみを表示する場合に使用します。
  • async: 非同期でレポート、グラフを描画するかどうか指定します。コロンに続けて、以下の記載が可能です。未指定の場合は、trueとなります。
    • true
      非同期で描画します。
    • false
      非同期で描画しません。
  • xaxisFormatString: X軸のラベルのフォーマットを指定します。X軸が数値か日付によって指定方法が異なります。
    • 数値の場合。未指定の場合は、%.1fとなります。以下のように整数値、少数値の指定が可能です。
      • %d
        整数値で表示します。
      • %.1f
        小数点1桁までで表示します。
    • 日付の場合。未指定の場合は、%Y/%m/%dとなります。
  • yaxisFormatString: Y軸のラベルのフォーマットを指定します。指定可能な値は、上記のX軸の数値と同じです。
  • xaxisMin: X軸の最小値を指定します。指定しない場合は、グラフデータより自動的に計算されます。
  • xaxisMax: X軸の最大値を指定します。指定しない場合は、グラフデータより自動的に計算されます。
  • yaxisMin: Y軸の最小値を指定します。指定しない場合は、グラフデータより自動的に計算されます。
  • yaxisMax: Y軸の最大値を指定します。指定しない場合は、グラフデータより自動的に計算されます。

表からグラフの生成は、以下のルールに従って行われます。

  • 一番左の列が、X軸の値になります。
    • デフォルトではyyyy-MM-dd形式の場合は日付と見なして、時系列データとして扱います。
  • 2列目以降がグラフのデータとなります。
  • ヘッダ行の値がラベルになります。

例:

  • report:1 を表示する。
    [[ReportInclude(1)]]
    
  • report:9 を棒グラフととともに表示する。
    [[ReportInclude(9,graph:bars)]]
    
  • report:14 を折れ線グラフで表示する。テーブルは表示しない。
    [[ReportInclude(14,graph:lines,table:hide)]]
    

[[RssEmbed]]

RSS Embedding Macro.

Will embed any rss feed supported by feedparser into the wiki page in the same manner as the tickets macro.

Useful for adding output form other trac instances to the wiki.

Used with a single parameter of the RSS URL.

[[InterWiki]]

Provide a description list for the known InterWiki prefixes.

[[TracJSGanttChart]]

Sorry, no documentation found

[[CommitTicketReference]]

Insert a changeset message into the output.

This macro must be called using wiki processor syntax as follows:

{{{
#!CommitTicketReference repository="reponame" revision="rev"
}}}

where the arguments are the following:

  • repository: the repository containing the changeset
  • revision: the revision of the desired changeset

[[UserProfilesList]]

Returns project's team roster. Usage:

[[UserProfilesList]]                                    # Without arguments returns current active user profiles (with enabled='1')
[[UserProfilesList(role='developer', enabled='1')]]     # Returns all userProfiles with role='developer' and enabled='1'
[[UserProfilesList(name='%someName%')]]                 # Returns all userProfiles with name like 'someName' 
[[UserProfilesList({id='cbalan'},{role='%arh%'})]]      # Returns cbalan's profile and user profiles with role='%arh%' 
[[UserProfilesList(|class=someCSS_Class, style=border:1px solid green;padding:12px)]] # Adds style and class attributes to box layout 

[[TeamRoster]]

Returns project's team roster. Usage:

[[TeamRoster]]                                    # Without arguments returns current active user profiles (with enabled='1')
[[TeamRoster(role='developer', enabled='1')]]     # Returns all userProfiles with role='developer' and enabled='1'
[[TeamRoster(name='%someName%')]]                 # Returns all userProfiles with name like 'someName' 
[[TeamRoster({id='cbalan'},{role='%arh%'})]]      # Returns cbalan's profile and user profiles with role='%arh%' 
[[TeamRoster(|class=someCSS_Class, style=border:1px solid green;padding:12px)]] # Adds style and class attributes to box layout 

Please use UserProfilesList? macro insted of TeamRoster? macro. Keeping this for backward compatibility with TeamRosterPlugin.

Macros from around the world

The  Trac Hacks site provides a wide collection of macros and other Trac plugins contributed by the Trac community. If you are looking for new macros, or have written one that you would like to share with the world, don't hesitate to visit that site.

Developing Custom Macros

Macros, like Trac itself, are written in the  Python programming language and are developed as part of TracPlugins.

For more information about developing macros, see the  development resources on the main project site.

Here are 2 simple examples showing how to create a Macro. Also, have a look at  Timestamp.py for an example that shows the difference between old style and new style macros and at the  macros/README which provides a little more insight about the transition.

Macro without arguments

To test the following code, you should saved it in a timestamp_sample.py file located in the TracEnvironment's plugins/ directory.

from datetime import datetime
# Note: since Trac 0.11, datetime objects are used internally

from genshi.builder import tag

from trac.util.datefmt import format_datetime, utc
from trac.wiki.macros import WikiMacroBase

class TimeStampMacro(WikiMacroBase):
    """Inserts the current time (in seconds) into the wiki page."""

    revision = "$Rev$"
    url = "$URL$"

    def expand_macro(self, formatter, name, text):
        t = datetime.now(utc)
        return tag.strong(format_datetime(t, '%c'))

Macro with arguments

To test the following code, you should save it in a helloworld_sample.py file located in the TracEnvironment's plugins/ directory.

from genshi.core import Markup

from trac.wiki.macros import WikiMacroBase

class HelloWorldMacro(WikiMacroBase):
    """Simple HelloWorld macro.

    Note that the name of the class is meaningful:
     - it must end with "Macro"
     - what comes before "Macro" ends up being the macro name

    The documentation of the class (i.e. what you're reading)
    will become the documentation of the macro, as shown by
    the !MacroList macro (usually used in the WikiMacros page).
    """

    revision = "$Rev$"
    url = "$URL$"

    def expand_macro(self, formatter, name, text, args):
        """Return some output that will be displayed in the Wiki content.

        `name` is the actual name of the macro (no surprise, here it'll be
        `'HelloWorld'`),
        `text` is the text enclosed in parenthesis at the call of the macro.
          Note that if there are ''no'' parenthesis (like in, e.g.
          [[HelloWorld]]), then `text` is `None`.
        `args` are the arguments passed when HelloWorld is called using a
        `#!HelloWorld` code block.
        """
        return 'Hello World, text = %s, args = %s' % \
            (Markup.escape(text), Markup.escape(repr(args)))

Note that expand_macro optionally takes a 4th parameter args. When the macro is called as a WikiProcessor, it's also possible to pass key=value processor parameters. If given, those are stored in a dictionary and passed in this extra args parameter. On the contrary, when called as a macro, args is None. (since 0.12).

For example, when writing:

{{{#!HelloWorld style="polite" -silent verbose
<Hello World!>
}}}

{{{#!HelloWorld
<Hello World!>
}}}

[[HelloWorld(<Hello World!>)]]

One should get:

Hello World, text = <Hello World!> , args = {'style': u'polite', 'silent': False, 'verbose': True}
Hello World, text = <Hello World!> , args = {}
Hello World, text = <Hello World!> , args = None

Note that the return value of expand_macro is not HTML escaped. Depending on the expected result, you should escape it by yourself (using return Markup.escape(result)) or, if this is indeed HTML, wrap it in a Markup object (return Markup(result)) with Markup coming from Genshi, (from genshi.core import Markup).

You can also recursively use a wiki Formatter (from trac.wiki import Formatter) to process the text as wiki markup:

from genshi.core import Markup
from trac.wiki.macros import WikiMacroBase
from trac.wiki import Formatter
import StringIO

class HelloWorldMacro(WikiMacroBase):
        def expand_macro(self, formatter, name, text, args):
                text = "whatever '''wiki''' markup you want, even containing other macros"
                # Convert Wiki markup to HTML, new style
                out = StringIO.StringIO()
                Formatter(self.env, formatter.context).format(text, out)
                return Markup(out.getvalue())