Trac マクロとは、 Python で書かれた 'カスタム関数' によって Trac の Wiki エンジンを拡張するプラグインです。 WikiFormatting エンジンが利用可能なあらゆるコンテキストにおいて、マクロを使用することによって、動的な HTML データが挿入されます。
もう 1 種類のマクロは WikiProcessors です。これは通常、 Wiki 以外のマークアップ形式と表示を取り扱うために使用し、多くは、 (ソースコードハイライトのような) より大きいブロックに使用します。
マクロ呼び出しは、二つの 角括弧 (square brackets) で括られた箇所です。 Python 関数のように、マクロは引数を取ることができ、括弧 (parenthesis) の中に、カンマで区切ったリストで表記します。
Trac マクロは、 TracPlugins としても作成することができます。 TracPlugins として Trac マクロを作成することで「直接 HTTP リクエストにアクセスする。」といった通常の Trac マクロでは実現できない機能を実装することができます。
'Trac' で始まる Wiki ページの最近の変更履歴 3 件分を表示するマクロです:
[[RecentChanges(Trac,3)]]
は、以下のように表示されます:
2012/10/20
Note: 以下に示すリストはマクロドキュメントを含むものだけです。 -OO による最適化や、 mod_python での PythonOptimize オプションが設定されていると表示されません。
[[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)]]
[[ChangeLog]]
Write repository change log to output.
The ChangeLog macro writes a log of the last changes of a repository at a given path. Following variants are possible to use:
1. [[ChangeLog([reponame:]path)]] 2. [[ChangeLog([reponame:]path@rev)]] 3. [[ChangeLog([reponame:]path@rev, limit)]] 4. [[ChangeLog([reponame:]path@from-to)]] 5. [[ChangeLog([reponame:]path, limit, rev)]]
[[ChangeLog(/)]]To show the last five changes of the trunk folder in a named repo:
[[ChangeLog(otherrepo:/trunk)]]
[[ChangeLog(otherrepo:/trunk@99)]]
[[ChangeLog(otherrepo:/trunk@99, 10)]]
[[ChangeLog(otherrepo:/trunk@90-99)]]To lists all changes:
[[ChangeLog(otherrepo:/trunk@1-HEAD)]]HEAD can be left out:
[[ChangeLog(otherrepo:/trunk@1-)]]
[[ChangeLog(otherrepo:/trunk, 10, 99)]]
limit and rev may be keyword arguments.
[[ChangeLog(otherrepo:/trunk, limit=10, rev=99)]]
[[ExtractUrl]]
Provides test macro for the tracextracturl.extract_url function.
This macro is intended for code testing by the developers of the above function and has no real usage for normal Trac users.
Macro usage: [[ExtractUrl(traclink)]]
Result: The URL extracted by extract_url
$Id: macro.py 8545 2010-08-30 21:57:33Z martin_s $
Extracts an URL from an Wiki link, e.g. to used in macro produced HTML code.
Website: http://trac-hacks.org/wiki/ExtractUrlPlugin
$Id: extracturl.py 8545 2010-08-30 21:57:33Z martin_s $
Returns an (possible relative) URL which can be used in HTML code.
If raw is true the returned link will point to a downloadable version of the linked resource otherwise the same link is returned which would be used in the resulting Wiki page.
The raw links are also usable as online resouces, e.g. if the link target is to be used as input for a flash application etc.
General:
from tracextracturl import extract_url # ... url = extract_url (env, context, wikilink, raw=False)
Inside WikiMacros:
from tracextracturl import extract_url def MyMacro(WikiMacroBase): def expand_macro (self, formatter, name, content): # e.g. wikilink = 'wiki:WikiStart' or 'attachment:file.ext' url = extract_url(self.env, formatter.context, wikilink) rawurl = extract_url(self.env, formatter.context, wikilink, True)
Inside a Trac macro called from the wiki page 'ExamplePage' of project 'project1' on a multi-project trac server:
extract_url(self.env, formatter, 'attachment:file.js', True)
will return /project1/raw-attachment/wiki/ExamplePage/file.js, which could be directly accessed by the browser inside some javascript or flash HTML object code produced by the macro.
[[FootNote]]
Collates and generates foot-notes. Call the macro with the foot-note content as the only argument:
[[FootNote(This is a footnote)]]
Foot-notes are numbered by the order in which they appear. To create a reference to an existing foot-note, pass the footnote number as argument to the macro:
[[FootNote(1)]]
In addition, identical foot-notes are coalesced into one entry. The following will generate one footnote entry with two references:
Some text[[FootNote(A footnote)]] and some more text [[FootNote(A footnote)]].
A list of footnotes generated by one or more of the above commands is produced by calling the macro without arguments:
[[FootNote]]
Once a set of footnotes has been displayed, a complete new set of footnotes can be created. This allows multiple sets of footnotes per page.
[[Image]]
Wiki 形式のテキストに画像を埋め込むことができます。
最初の引数にはファイル名を指定します。ファイルの指定には3つの方法で添付ファイルを参照することができます。
また、source:file 形式 (source:file@rev でも) を使ってリポジトリのファイルを参照することもできます。
直接 URL を記述してアクセスすることもできます。/file はプロジェクトの相対 URL、//file はサーバの相対 URL、http://server/file はファイルの完全 URL となります。
残りの引数は省略可能で表示する <img> 要素の属性とスタイルを設定することができます。
例:
[[Image(photo.jpg)]] # 単純な形式 [[Image(photo.jpg, 120px)]] # 画像サイズ付き [[Image(photo.jpg, right)]] # キーワードでの整列 [[Image(photo.jpg, nolink)]] # 元ファイルへのリンクなし [[Image(photo.jpg, align=right)]] # 属性での整列
他のページやチケット、他のモジュールの画像を使うことができます。
[[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 マクロが元になっています。
[[InterTrac]]
設定済みの InterTrac プレフィックスの一覧です。
[[InterWiki]]
設定済みの InterWiki プレフィックスの一覧です。
[[KnownMimeTypes]]
WikiProcessors として使用できる mime-type の一覧です。
引数を指定すると mime-type をフィルタリングすることができます。
[[Lineno]]
Wiki processor that prints line numbers for code blocks.
Example:
{{{ #!Lineno #!java class A { public static void main(String[] args) { } } }}}
行 | |
---|---|
1 | class A { |
2 | public static void main(String[] args) { |
3 | } |
4 | } |
[[ListPage]]
現在のページ、または指定されたページのサブページの一覧を表示します。
使い方:
[[ListPage([ベースページ[, 深さ[, タイトルの使用]]])]]
引数:
例:
[[ListPage]] [[ListPage(/,1)]]
[[ListTagged]]
タグ付けされているリソースを表示します。
使用方法:
[[ListTagged(query)]]
クエリの構文については tags のドキュメントを参照してください。
[[MacroList]]
インストールされている Wiki マクロの一覧と利用可能ならドキュメントも表示します。
マクロの名前を引数に指定することができ、この場合はそのマクロのドキュメントだけを表示します。
※ このマクロは mod_python の PythonOptimize オプションを有効にしているとマクロのドキュメントを表示できません。
[[MilestonDescription]]
指定したマイルストーンの説明を表示します。
使い方:
[[MilestonDescription(マイルストーン)]]
引数:
例:
[[MilestonDescription(1.0)]]
[[MilestoneCompact]]
Adds a wiki macro [[MilestoneCompact]] which lists and describes the project's milestones in a compact form.
[[MindMap]]
エイリアス: [[Mindmap]]
Website: http://trac-hacks.org/wiki/MindMapMacro
$Id: macro.py 9152 2010-09-26 20:59:50Z martin_s $
[[PageName]]
現在のページ名を表示します。
使い方:
[[PageName([フルパスかどうか])]]
引数:
例:
[[PageName]] [[PageName(False)]]
[[PageOutline]]
現在の Wiki ページのアウトライン構造を表示します。アウトラインの各項目は対応する見出しへのリンクとなります。
このマクロは4つの省略可能なパラメータを受け取ります。
[[ProgressMeter]]
Progress meter wiki macro plugin for Trac
Usage instructions are available at:
[[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.
[[RecentChanges]]
最近更新されたページを最終更新の日付でグループ化して一覧表示します。
このマクロは2つのパラメータと1つの名前付き引数を受け取ります。名前付き引数は、任意の順番で指定することができます。
1つ目はプレフィックス文字列で、指定している場合、その結果はそのプレフィックスで始まるページ名のみとなります。このパラメータを省略した場合はすべてのページを表示します。
2つ目のパラメータは、結果のページ数に対する上限値になります。
group パラメータによって一覧をどのように表示を行うかが決まります。
ヒント: プレフィックス文字列でフィルタを行わずに項目の最大数のみを指定したい場合には、1つ目のパラメータを空にします。例えば [[RecentChanges(,10,group=none)]] とします。
[[RepositoryIndex]]
利用可能なリポジトリの一覧を表示します。
次の名前付き引数を指定できます。
(0.12 以降)
[[TagCloud]]
タグクラウドを表示します。
クエリに該当するリソースからタグクラウドを表示します。
使用方法:
[[TagCloud(query,caseless_sort=<bool>,mincount=<n>)]]
クエリの構文については tags のドキュメントを参照してください。
[[TicketQuery]]
Wiki macro listing tickets that match certain criteria.
このマクロの引数はカンマ区切りのリストにした、 "key=value" 形式の キー付きパラメータを使用します。
key がフィールド名であった場合、 value は TracQuery#QueryLanguage で 定義されているような、フィルタを指定するシンタックスでなければなりません。 ? の文字で始まる query: リンク向けの簡素化した URL シンタックス とは 異なります 。フィールドの値としてカンマ (,) そのものを含む場合は バックスラッシュ (,) でエスケープする必要があります。
引数 or で区切られたフィルタのグループは、 OR 条件で結合されます。
このほか、フィルタとしていくつか名前付きパラメータを使用できます。 これらは検索結果をどのように表示するかを制御できます。すべて非必須です。
format はチケットのリストがどのように表示されるかを決定します:
max は表示されるチケット数の上限値を指定します (デフォルトは 0 です。これは無制限を意味します)。
order はチケットを整列する列を指定します (デフォルトは id となっています)。
desc はチケットの整列を逆順に行うか指定します。 (デフォルトは false です)。
group はチケットをグループ化を指定します (デフォルトは何も設定されていません)。
groupdesc はグループの表示を逆順とするかを指定します (デフォルトは false となっています)。
verbose を true に設定すると、リストされたチケットの 各行にチケットの説明を表示します。これは table format 専用です。 このパラメータは廃止予定です。代わりに rows を使用してください。
rows パラメータは1行使って表示するフィールドを指定します。 rows=description|summary のように使用します。
Trac 0.10 との互換性のため、マクロは最終引数にキーなし引数が与えられた場合 format として解釈します。 また、フィールドセパレータに使用する "&" は (order を除いて) 現時点では動作しますが、この機能は廃止予定です。
[[TitleIndex]]
Wiki ページの一覧をアルファベット順で出力します。
引数としてプレフィックスになる文字列を受け取ります: 指定した場合、一覧はプレフィックスで始まるページ名だけになります。引数を省略した場合、すべてのページを表示します。プレフィックスを指定している場合、さらに2番目の引数 hideprefix が指定でき、出力からそのプレフィックスのものが取り除かれます。
format と depth という名前のパラメータを指定することができます。
include と exclude はシェル形式のパターンを受け付けます。
[[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 ページで使います。引数を指定するとセクションとオプションの名前のフィルタになり、そのフィルタの内容で始まるセクションとオプションのみを出力します。
[[Tsvn]]
TortoiseSVN 用のリンクを表示します。
使い方:
[[Tsvn(リポジトリのURL)]]
引数:
例:
[[Tsvn(http://yourhost/svn/project)]]
[[WorkTimeReport]]
以下のようにWikiにマクロを記載することで、作業時間のレポートを表示します。 また、オプションを設定することで、レポートの表からグラフを生成することもできます。
[[WorkTimeReport(args1,args2,...)]]
args:
例:
[[WorkTimeReport(fromDay:2009-11-01,toDay:2009-11-30)]]
[[WorkTimeReport(fromDay:2009-11-01,toDay:2009-11-30,graph:bars,stack:true)]]
[[Workflow]]
ワークフローを描画します。
このマクロは TracWorkflow 設定を受け取って有向グラフの状態と遷移を描画します。 パラメータを指定しない場合は、現在のワークフローを描画します。 Wiki プロセッサモードでは width と height を引数に指定することができます。
(デフォルト: 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 }}}
[[graphviz]]
The GraphvizPlugin (http://trac-hacks.org/wiki/GraphvizPlugin) provides a plugin for Trac to render graphviz (http://www.graphviz.org/) graph layouts within a Trac wiki page.
[[graphviz.dot/png]]
エイリアス: [[graphviz.dot/jpg]]
[[graphviz.dot/gif]]
[[graphviz.dot/svg]]
[[graphviz.dot/svgz]]
[[graphviz.dot]]
[[graphviz.neato/png]]
[[graphviz.neato/jpg]]
[[graphviz.neato/gif]]
[[graphviz.neato/svg]]
[[graphviz.neato/svgz]]
[[graphviz.neato]]
[[graphviz.twopi/png]]
[[graphviz.twopi/jpg]]
[[graphviz.twopi/gif]]
[[graphviz.twopi/svg]]
[[graphviz.twopi/svgz]]
[[graphviz.twopi]]
[[graphviz.circo/png]]
[[graphviz.circo/jpg]]
[[graphviz.circo/gif]]
[[graphviz.circo/svg]]
[[graphviz.circo/svgz]]
[[graphviz.circo]]
[[graphviz.fdp/png]]
[[graphviz.fdp/jpg]]
[[graphviz.fdp/gif]]
[[graphviz.fdp/svg]]
[[graphviz.fdp/svgz]]
[[graphviz.fdp]]
[[graphviz/png]]
[[graphviz/jpg]]
[[graphviz/gif]]
[[graphviz/svg]]
[[graphviz/svgz]]
[[plantuml]]
エイリアス: [[PlantUml]]
[[PlantUML]]
A wiki processor that renders PlantUML diagrams in wiki text.
Example:
{{{ #!PlantUML @startuml Alice -> Bob: Authentication Reque st Bob --> Alice: Authentication Response Alice -> Bob: Another authentication Request Alice <-- Bob: another authentication Response @enduml }}}
Results in:
Trac Hacks というサイトは、コミュニティに寄稿されたマクロと プラグイン を収集し提供しています。新しいマクロを探している、共有したいマクロを作成した、などの場合は遠慮なく Trac Hacks のサイトを訪問してください。
マクロは、 Trac 自身と同じように Python で書かれています。
マクロの開発についての詳しい情報は リソースの開発 を参照してください。
Trac 0.11 でマクロを作成する 2 つの単純な例を紹介します。古いマクロと新しいマクロの違いを示す例は Timestamp.py を参照してください。また古いマクロから新しいマクロに移行するための情報は README を参照してください。
Trac は マクロ名としてモジュール名を使用するので以下は TimeStamp.py という名前で保存しなければなりません。
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, args): t = datetime.now(utc) return tag.b(format_datetime(t, '%c'))
Trac は マクロ名としてモジュール名を使用するので以下は HelloWorld.py という名前で (plugins/ ディレクトリ内に ) 保存しなければなりません。
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, 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'`), `args` 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 `args` is `None`. """ return 'Hello World, args = ' + unicode(args) # Note that there's no need to HTML escape the returned data, # as the template engine (Genshi) will do it for us.
訳注 重要:
Wiki マクロが引数を持つ場合、引数は必ずサニタイズしてください。 expand_macro の戻り値は <script> タグやイベントハンドラなどもそのまま出力するので、入力をチェックせずに、そのまま戻り値に使用するのは極めて危険です。 Genshi の tag オブジェクトにラップすれば、エスケープ機構が働きますので、通常はこれを使うとよいでしょう。 HelloWorld.py は、以下の通り書き直すことができます:
from trac.wiki.macros import WikiMacroBase from genshi.builder import tag class HelloWorldMacro(WikiMacroBase): def expand_macro(self, formatter, name, args): return tag.div(u'Hello World, args = ', unicode(args))
expand_macro は HTML として解釈できる単純な文字列か Markup オブジェクト (from trac.util.html import Markup を使用する ) のどちらかを返さなければなりません。 Markup(string) はそのまま string を解釈するので、 HTML 文字列はエスケープされずに、そのとおり表示されます。 Wiki フォーマッタを使用した場合は from trac.wiki import Formatter のように import してください。
マクロで HTML ではなく Wiki マークアップを使用したい場合、以下のように HTML に変換します:
text = "whatever wiki markup you want, even containing other macros" # Convert Wiki markup to HTML, new style out = StringIO() Formatter(self.env, formatter.context).format(text, out) return Markup(out.getvalue())