Edgewall Software

Changes between Initial Version and Version 1 of 0.13/WikiMacros


Ignore:
Timestamp:
May 11, 2011, 10:51:31 AM (13 years ago)
Author:
Christian Boos
Comment:

copied from WikiMacros@39

Legend:

Unmodified
Added
Removed
Modified
  • 0.13/WikiMacros

    v1 v1  
     1** Note: this page documents the 0.12 version of Trac, see [[0.11/WikiMacros]] if you need the previous version **
     2= Trac Macros =
     3
     4[[PageOutline]]
     5[[TranslatedPages]]
     6
     7Trac 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.
     8
     9Another kind of macros are WikiProcessors. They typically deal with alternate markup formats and representation of larger blocks of information (like source code highlighting).
     10
     11== Using Macros ==
     12
     13Macro calls are enclosed in two ''square brackets''. Like Python functions, macros can also have arguments, a comma separated list within parentheses.
     14
     15=== Getting Detailed Help ===
     16The list of available macros and the full help can be obtained using the !MacroList macro, as seen [#AvailableMacros below].
     17
     18A brief list can be obtained via ![[MacroList(*)]] or ![[?]].
     19
     20Detailed 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?]].
     21
     22
     23
     24=== Example ===
     25
     26A list of 3 most recently changed wiki pages starting with 'Trac':
     27
     28||= Wiki Markup =||= Display =||
     29{{{#!td
     30  {{{
     31  [[RecentChanges(Trac,3)]]
     32  }}}
     33}}}
     34{{{#!td style="padding-left: 2em;"
     35[[RecentChanges(Trac,3)]]
     36}}}
     37|-----------------------------------
     38{{{#!td
     39  {{{
     40  [[RecentChanges?(Trac,3)]]
     41  }}}
     42}}}
     43{{{#!td style="padding-left: 2em;"
     44[[RecentChanges?(Trac,3)]]
     45}}}
     46|-----------------------------------
     47{{{#!td
     48  {{{
     49  [[?]]
     50  }}}
     51}}}
     52{{{#!td style="padding-left: 2em"
     53{{{#!html
     54<div style="font-size: 80%" class="trac-macrolist">
     55<h3><code>[[Image]]</code></h3>Embed an image in wiki-formatted text.
     56
     57The first argument is the file …
     58<h3><code>[[InterTrac]]</code></h3>Provide a list of known <a class="wiki" href="/wiki/InterTrac">InterTrac</a> prefixes.
     59<h3><code>[[InterWiki]]</code></h3>Provide a description list for the known <a class="wiki" href="/wiki/InterWiki">InterWiki</a> prefixes.
     60<h3><code>[[KnownMimeTypes]]</code></h3>List all known mime-types which can be used as <a class="wiki" href="/wiki/WikiProcessors">WikiProcessors</a>.
     61Can be …</div>
     62}}}
     63etc.
     64}}}
     65
     66== Available Macros ==
     67
     68''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 [wiki:TracModPython mod_python].''
     69
     70[[MacroList]]
     71
     72== Macros from around the world ==
     73
     74The [http://trac-hacks.org/ Trac Hacks] site provides a wide collection of macros and other Trac [TracPlugins 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.
     75
     76== Developing Custom Macros ==
     77Macros, like Trac itself, are written in the [http://python.org/ Python programming language] and are developed as part of TracPlugins.
     78
     79For more information about developing macros, see the [trac:TracDev development resources] on the main project site.
     80
     81
     82Here are 2 simple examples showing how to create a Macro with Trac 0.11.
     83
     84Also, have a look at [trac:source:tags/trac-0.11/sample-plugins/Timestamp.py Timestamp.py] for an example that shows the difference between old style and new style macros and at the [trac:source:tags/trac-0.11/wiki-macros/README macros/README] which provides a little more insight about the transition.
     85
     86=== Macro without arguments ===
     87To test the following code, you should saved it in a `timestamp_sample.py` file located in the TracEnvironment's `plugins/` directory.
     88{{{
     89#!python
     90from datetime import datetime
     91# Note: since Trac 0.11, datetime objects are used internally
     92
     93from genshi.builder import tag
     94
     95from trac.util.datefmt import format_datetime, utc
     96from trac.wiki.macros import WikiMacroBase
     97
     98class TimeStampMacro(WikiMacroBase):
     99    """Inserts the current time (in seconds) into the wiki page."""
     100
     101    revision = "$Rev$"
     102    url = "$URL$"
     103
     104    def expand_macro(self, formatter, name, text):
     105        t = datetime.now(utc)
     106        return tag.b(format_datetime(t, '%c'))
     107}}}
     108
     109=== Macro with arguments ===
     110To test the following code, you should saved it in a `helloworld_sample.py` file located in the TracEnvironment's `plugins/` directory.
     111{{{
     112#!python
     113from genshi.core import Markup
     114
     115from trac.wiki.macros import WikiMacroBase
     116
     117class HelloWorldMacro(WikiMacroBase):
     118    """Simple HelloWorld macro.
     119
     120    Note that the name of the class is meaningful:
     121     - it must end with "Macro"
     122     - what comes before "Macro" ends up being the macro name
     123
     124    The documentation of the class (i.e. what you're reading)
     125    will become the documentation of the macro, as shown by
     126    the !MacroList macro (usually used in the WikiMacros page).
     127    """
     128
     129    revision = "$Rev$"
     130    url = "$URL$"
     131
     132    def expand_macro(self, formatter, name, text, args):
     133        """Return some output that will be displayed in the Wiki content.
     134
     135        `name` is the actual name of the macro (no surprise, here it'll be
     136        `'HelloWorld'`),
     137        `text` is the text enclosed in parenthesis at the call of the macro.
     138          Note that if there are ''no'' parenthesis (like in, e.g.
     139          [[HelloWorld]]), then `text` is `None`.
     140        `args` are the arguments passed when HelloWorld is called using a
     141        `#!HelloWorld` code block.
     142        """
     143        return 'Hello World, text = %s, args = %s' % \
     144            (Markup.escape(text), Markup.escape(repr(args)))
     145
     146}}}
     147
     148Note that `expand_macro` optionally takes a 4^th^ parameter ''`args`''. When the macro is called as a [WikiProcessors WikiProcessor], it's also possible to pass `key=value` [WikiProcessors#UsingProcessors 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'').
     149
     150For example, when writing:
     151{{{
     152{{{#!HelloWorld style="polite"
     153<Hello World!>
     154}}}
     155
     156{{{#!HelloWorld
     157<Hello World!>
     158}}}
     159
     160[[HelloWorld(<Hello World!>)]]
     161}}}
     162One should get:
     163{{{
     164Hello World, text = <Hello World!> , args = {'style': u'polite'}
     165Hello World, text = <Hello World!> , args = {}
     166Hello World, text = <Hello World!> , args = None
     167}}}
     168
     169Note 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`). 
     170
     171You can also recursively use a wiki Formatter (`from trac.wiki import Formatter`) to process the `text` as wiki markup, for example by doing:
     172
     173{{{
     174#!python
     175from genshi.core import Markup
     176from trac.wiki.macros import WikiMacroBase
     177from trac.wiki import Formatter
     178import StringIO
     179
     180class HelloWorldMacro(WikiMacroBase):
     181        def expand_macro(self, formatter, name, text, args):
     182                text = "whatever '''wiki''' markup you want, even containing other macros"
     183                # Convert Wiki markup to HTML, new style
     184                out = StringIO.StringIO()
     185                Formatter(self.env, formatter.context).format(text, out)
     186                return Markup(out.getvalue())
     187}}}