"""Preprocessor Highlight ShellExample."""
from trac.util import escape
import re

regexp = re.compile(
        '^(?P<path>~ |~?/[^ ]+ )?(?P<cli>[#$] )(?P<input>.*)$'
        '|^(?P<comment>\(.*\))$'
        , re.M)

def execute(hdf, txt, env):
    # args will be null if the macro is called without parenthesis.
    css = ''
    if hdf:
        if not hdf.has_key("macro.ShellExample.outputcss"):
            hdf["macro.ShellExample.outputcss"] = True
            css = '''<style type="text/css">
.code-input            {color:blue}
.code-input            {color:blue}
.code-root             {color:red;}
/*.code-comment          {color:#d80000;} */
.code-path, .code-user {color:#449999; font-weight: bold}
</style>'''
    txt = txt and escape(txt) or ''
    def callback(match):
        m = match.group('cli')
        if m:
            path = match.group('path')
            if path:
                line = '<span class="code-path">' + path + '</span>'
            else:
                line = ''

            input = '<span class="code-input">' + match.group('input') + '</span>'
            if m == '# ':
                line = line + '<span class="code-root">' + m + input + '</span>'
            else:
                line = line + '<span class="code-user">' + m + input + '</span>'
            return line
        m = match.group('comment')
        if m:
            return '<span class="code-comment">' + m + '</span>'
        return match.group(0)
    return css + '<pre><div class="code">' + regexp.sub(callback, txt)+ '</div></pre>';
