wiki:WikiMacros

バージョン 1 (更新者 trac、2014/11/09 19:58:15) (diff)

--

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.

Another kind of macros are WikiProcessors. They typically deal with alternate markup formats and representation of larger blocks of information (like source code highlighting).

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 3 most recently changed wiki pages starting with 'Trac':

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

[[RecentChanges?(Trac,3)]]

[[RecentChanges]]

最近更新されたページを最終更新の日付でグループ化して一覧表示します。

このマクロは2つのパラメータと1つの名前付き引数を受け取ります。名前付き引数は、任意の順番で指定することができます。

1つ目はプレフィックス文字列で、指定している場合、その結果はそのプレフィックスで始まるページ名のみとなります。このパラメータを省略した場合はすべてのページを表示します。

2つ目のパラメータは、結果のページ数に対する上限値になります。

group パラメータによって一覧をどのように表示を行うかが決まります。

group=date
ページを日付ごとに箇条書きで表示します (デフォルト)。
group=none
ページを1つの箇条書きにて表示します。

ヒント: プレフィックス文字列でフィルタを行わずに項目の最大数のみを指定したい場合には、1つ目のパラメータを空にします。例えば [[RecentChanges(,10,group=none)]] とします。

[[?]]

[[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.

[[Image]]

Wiki 形式のテキストに画像を埋め込むことができます。

最初の引数にはファイル名を指定します。ファイルの指定には3つの方法で添付ファイルを参照することができます。

  • module:id:file の場合は、module には wikiticket のどちらかを指定でき、指定している Wiki ページやチケットにある file という名前の添付ファイルを参照します。
  • id:file: 上記と同じですが、id にはチケットの省略形式、もしくは Wiki ページ名のどちらかになります。
  • file の場合は、ローカルの 'file' という名前の添付ファイルを参照します。これは Wiki ページやチケットでだけ機能します。

また、source:file 形式 (source:file@rev でも) を使ってリポジトリのファイルを参照することもできます。

直接 URL を記述してアクセスすることもできます。/file はプロジェクトの相対 URL、//file はサーバの相対 URL、http://server/file はファイルの完全 URL となります。URL を引用符で囲むことで rfc2397data URL スキームも使用できます。

残りの引数は省略可能で表示する <img> 要素の属性とスタイルを設定することができます。

  • 数値と単位付きの数値は画像に対するサイズだと解釈します (例 120px, 25%)。
  • rightleftcentertopbottommiddle は画像の位置合わせに使います。(別の方法としては、最初の3つは align=... を使って、最後の3つは valign=... を使って指定することができます)
  • link=some TracLinks...TracLinks を使って指定のリンクで画像へのリンクを置き換えることができます。値を指定していない場合は、単にリンクを削除します。
  • inline を指定するとインライン XHTML 要素として生成します。デフォルトでは、インライン要素を生成しません。つまり、セクションヘッダなどの1行の内容のところでは画像を描画しません。
  • nolink は画像へのリンクなしを意味します (非推奨、link= を使ってください)。
  • key=value 形式は HTML 属性または CSS スタイルの指定だと解釈します。有効なキーは次のものです。
    • align、valign、border、width、height、alt、title、longdesc、class、margin、margin-(left,right,top,bottom)、id、usemap
    • bordermarginmargin-* には1つの数値だけが指定できます。(単位はピクセルとなります)
    • margincenter がマージンとして使う auto より優先します。

例:

[[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)]]           # チケットから
[[Image(ticket:36:boo.jpg)]]    # チケットから (長い形式)
[[Image(source:/img/bee.jpg)]]  # リポジトリから
[[Image(htdocs:foo/bar.png)]]   # プロジェクトの htdocs ディレクトリから
[[Image(shared:foo/bar.png)]]   # 共有している htdocs ディレクトリから (1.0.2 以降)

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

[[InterTrac]]

設定済みの InterTrac プレフィックスの一覧です。

[[InterWiki]]

設定済みの InterWiki プレフィックスの一覧です。

[[KnownMimeTypes]]

WikiProcessors として使用できる mime-type の一覧です。

引数を指定すると mime-type をフィルタリングすることができます。

[[MacroList]]

インストールされている Wiki マクロの一覧と利用可能ならドキュメントも表示します。

マクロの名前を引数に指定することができ、この場合はそのマクロのドキュメントだけを表示します。

※ このマクロは mod_python の PythonOptimize オプションを有効にしているとマクロのドキュメントを表示できません。

[[PageOutline]]

現在の Wiki ページのアウトライン構造を表示します。アウトラインの各項目は対応する見出しへのリンクとなります。

このマクロは4つの省略可能なパラメータを受け取ります。

  • 1つ目は、数値または数値の範囲でアウトラインに表示する見出しの最小レベルと最大レベルを設定できます。 例えば、"1" を指定するとアウトラインにはトップレベルの見出しだけになります。 "2-3" を指定するとレベル2と3のすべての見出しがアウトラインに含まれるようになります。
  • 2つ目のパラメータは、タイトルを指定することができます (デフォルトではタイトルはなしです)。
  • 3つ目のパラメータは、アウトラインのスタイルを選択します。 inline または pullout のどちらかにすることができます (後者がデフォルトです)。 inline スタイルは通常のコンテンツの一部としてアウトラインを表示しますが、 pullout ではデフォルトでコンテンツの右にフロートしているボックスの中にアウトラインを表示します。
  • 4つ目のパラメータはアウトラインを番号付きにするかどうかを指定します。numbered または unnumbered のどちらかにすることができます (前者がデフォルトです)。このパラメータは inline スタイルでのみ効果があります。

[[RecentChanges]]

最近更新されたページを最終更新の日付でグループ化して一覧表示します。

このマクロは2つのパラメータと1つの名前付き引数を受け取ります。名前付き引数は、任意の順番で指定することができます。

1つ目はプレフィックス文字列で、指定している場合、その結果はそのプレフィックスで始まるページ名のみとなります。このパラメータを省略した場合はすべてのページを表示します。

2つ目のパラメータは、結果のページ数に対する上限値になります。

group パラメータによって一覧をどのように表示を行うかが決まります。

group=date
ページを日付ごとに箇条書きで表示します (デフォルト)。
group=none
ページを1つの箇条書きにて表示します。

ヒント: プレフィックス文字列でフィルタを行わずに項目の最大数のみを指定したい場合には、1つ目のパラメータを空にします。例えば [[RecentChanges(,10,group=none)]] とします。

[[RepositoryIndex]]

利用可能なリポジトリの一覧を表示します。

次の名前付き引数を指定できます。

format
表示するフォーマットを選択します。
  • compact はリポジトリのプレフィックス名をカンマ区切りで表示します (デフォルト)
  • list はリポジトリのプレフィックス名を一覧表示します
  • tableリポジトリブラウザページのものと同じようなテーブル形式で表示します
glob
リポジトリ名に対して glob 形式のフィルタリングを行います (デフォルトは '*' です)
order
リポジトリを指定のカラム順で並べます ("name", "date" または "author" の1つ)
desc
1を指定すると降順で並べます

(0.12 以降)

[[TicketQuery]]

条件に該当するチケットの一覧を表示する Wiki マクロです。

このマクロはパラメータを "key=value" 形式のカンマ区切りリストで受け取ります。

キーがフィールド名の場合、その値は TracQuery#QueryLanguage で定義されているフィルタ構文で指定しなければなりません。 注意: これは ? 文字付きの query: リンクで使う簡易 URL シンタックスとは違うものです。 カンマ (,) はバックスラッシュ (\) でエスケープすることでフィールド値に含めることができます。

フィールド条件のグループは or リテラル引数により OR 条件で分割することができます。

フィルタに加えて、他のいくつかのパラメータ名はフィルタ結果の表示方法を制御するのに使います。これらはすべてオプションです。

format パラメータはチケット一覧の表示方法を決めます。

  • list -- デフォルトの表示方法で、チケットIDと概要が各行に1チケットの一覧になります。
  • compact -- カンマ区切りでチケットIDのリストを表示します。
  • count -- 該当するチケットの件数のみを表示します。
  • table -- カスタムクエリと同じような表示です (フォームはありません)
  • progress -- マイルストーンの進捗バーに似た表示です

max パラメータは表示されるチケットの件数を制限するのに使います (デフォルトは 0 でつまり最大値なしです)。

order パラメータはチケットの順番に使います (デフォルトは id です)。

desc パラメータはチケットの順番を逆順にするように指示します (デフォルトは false です)。

group パラメータはチケットのグループ化に使用するフィールドを設定します (デフォルトは設定なしです)。

groupdesc パラメータはグループの順番を逆順にするように指示します (デフォルトは false です)。

verbose パラメータはチケット一覧で詳細を得るのに true 値を設定することができます。table フォーマットでのみ使えます。rows パラメータが好ましいため、非推奨となっています。

rows パラメータは1行に表示するフィールドを指定することができます。 例: rows=description|summary

col パラメータは列に表示するフィールドを指定することができます。 table フォーマットでのみ使えます。

Trac 0.10 との互換性のため、マクロの最後に位置にする引数は format パラメータとして使います。また、フィールドのセパレータとして "&" を使ってもまだ機能しますが非推奨です (order パラメータを除く)。

[[TitleIndex]]

Wiki ページの一覧をアルファベット順で出力します。

引数としてプレフィックスになる文字列を受け取ります: 指定した場合、一覧はプレフィックスで始まるページ名だけになります。引数を省略した場合、すべてのページを表示します。プレフィックスを指定している場合、さらに2番目の引数 hideprefix が指定でき、出力からそのプレフィックスのものが取り除かれます。

formatdepth という名前のパラメータを指定することができます。

  • format=compact: カンマ区切りのリンクでページ一覧を表示します。
  • format=group: 共通のプレフィックスによりグループ化を行ってページ一覧を表示します。 またこのフォーマットは min=n 引数をサポートしており、グループに対する最小ページ数になります。
  • format=hierarchy: ページ名の階層により構造化を行ってページ一覧を表示します。 またこのフォーマットは min=n 引数をサポートしており、n 以上の階層がフラットになります。
  • depth=n: ページ一覧の深さを制限します。 0を指定した場合はトップレベルのページだけを表示し、 1を指定した場合は直接の子になるページまでを表示するなどとなります。 指定なし、または-1を指定した場合は、すべてのページを階層化して表示を行います。
  • include=page1:page*2: コロン区切りで並べたページ名に該当するものだけになります。 リストが空、または include 引数がない場合はすべてのページを含みます。
  • exclude=page1:page*2: コロン区切りで並べたページ名に該当するものは除くようになります。

includeexclude はシェル形式のパターンを受け付けます。

[[TracAdminHelp]]

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

例:

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

[[TracGuideToc]]

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

このマクロはやっつけな方法で Help/Guide の目次を作成します。 目次は Trac* と WikiFormatting ページを含んでいてカスタマイズできません。 目次のカスタマイズには TocMacro を参照してください。

[[TracIni]]

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

これは通常 TracIni ページで使います。引数を指定するとセクションとオプションの名前のフィルタになり、そのフィルタの内容で始まるセクションとオプションのみを出力します。

[[Workflow]]

ワークフローを描画します。

このマクロは TracWorkflow 設定を受け取って有向グラフの状態と遷移を描画します。 パラメータを指定しない場合は、現在のワークフローを描画します。 Wiki プロセッサモードでは widthheight を引数に指定することができます。

(デフォルト: width = 800, heigth = 600)

例:

    [[Workflow()]]

    [[Workflow(go = here -> there; return = there -> here)]]

    {{{
    #!Workflow width=700 height=700
    leave = * -> *
    leave.operations = leave_status
    leave.default = 1

    accept = new,assigned,accepted,reopened -> accepted
    accept.permissions = TICKET_MODIFY
    accept.operations = set_owner_to_self

    resolve = new,assigned,accepted,reopened -> closed
    resolve.permissions = TICKET_MODIFY
    resolve.operations = set_resolution

    reassign = new,assigned,accepted,reopened -> assigned
    reassign.permissions = TICKET_MODIFY
    reassign.operations = set_owner

    reopen = closed -> reopened
    reopen.permissions = TICKET_CREATE
    reopen.operations = del_resolution
    }}}

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're looking for new macros, or have written one that you'd like to share with the world, please 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 with Trac 0.11.

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.b(format_datetime(t, '%c'))

Macro with arguments

To test the following code, you should saved 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"
<Hello World!>
}}}

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

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

One should get:

Hello World, text = <Hello World!> , args = {'style': u'polite'}
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, for example by doing:

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())