= Trac Macros

[[PageOutline]]

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 [#AvailableMacros 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 =||
{{{#!td
  {{{
  [[RecentChanges(Trac,3)]]
  }}}
}}}
{{{#!td style="padding-left: 2em;"
[[RecentChanges(Trac,3)]]
}}}
|-----------------------------------
{{{#!td
  {{{
  [[RecentChanges?(Trac,3)]]
  }}}
}}}
{{{#!td style="padding-left: 2em;"
[[RecentChanges?(Trac,3)]]
}}}
|-----------------------------------
{{{#!td
  {{{
  [[?]]
  }}}
}}}
{{{#!td style="padding-left: 2em"
{{{#!html 
<div style="font-size: 80%" class="trac-macrolist">
<h3><code>[[Image]]</code></h3>Embed an image in wiki-formatted text.

The first argument is the file …
<h3><code>[[InterTrac]]</code></h3>Provide a list of known <a class="wiki" href="/wiki/InterTrac">InterTrac</a> prefixes.
<h3><code>[[InterWiki]]</code></h3>Provide a description list for the known <a class="wiki" href="/wiki/InterWiki">InterWiki</a> prefixes.
<h3><code>[[KnownMimeTypes]]</code></h3>List all known mime-types which can be used as <a class="wiki" href="/wiki/WikiProcessors">WikiProcessors</a>.
Can be …</div>
}}}
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 [wiki:TracModPython mod_python].''

[[MacroList]]

== Macros from around the world

The [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 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 [http://python.org/ Python programming language] and are developed as part of TracPlugins.

For more information about developing macros, see the [trac:TracDev development resources] on the main project site.

Here are 2 simple examples showing how to create a Macro. Also, have a look at [trac:source:tags/trac-1.0.2/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.

=== 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.
{{{
#!python
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.
{{{
#!python
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 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'').

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:

{{{
#!python
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())
}}}