$$ \newcommand{\beqa}{\begin{eqnarray}} \newcommand{\eeqa}{\end{eqnarray}} \newcommand{\ep}{\thinspace . } \newcommand{\uvec}{\vec u} \newcommand{\Q}{\pmb{Q}} $$

 

 

 

Example: Extending Tables to Handle Figures

DocOnce tables cannot contain figures, since figures must appear on a single line with the special syntax FIGURE: [file, ...]. What if you want a table of thumbnail figures with hyperlinks?

Solution for LaTeX and HTML

We first restrict the attention to LaTeX and HTML. In those cases we can create an ordinary table and insert a call to a Mako function in cells in the table to return the proper LaTeX or HTML code for displaying a figure.

The Mako call syntax in a cell is decided to be ${tfig('080')}, which insert the figure mov/wave_frames/frame_0080.png. A 3x3 table of figures then look like

|-------------------------------------------------|
|               |                |                |
|-------c---------------c----------------c--------|
|${tfig('080')} | ${tfig('085')} | ${tfig('090')} |
|${tfig('095')} | ${tfig('100')} | ${tfig('105')} |
|${tfig('110')} | ${tfig('115')} | ${tfig('120')} |
|-------------------------------------------------|

We do not want a heading, just a grid of figures, but a heading is required in DocOnce figures, so the solution is to provide empty column names in the heading. This solution gives acceptable results in HTML and LaTeX.

The Mako function can be a plain Python function:

<%
def tfig(fileno):
    p = 'mov/wave_frames/frame_0' + fileno + '.png'  # path
    if FORMAT in ("latex", "pdflatex"):
        text = r'\includegraphics[width=2cm]{%s}' % p
    elif FORMAT == "html":
        text = '<a href="%s"><img src="%s" width="300"></a>' % (p, p)
    else:
        text = '"`%s`": "%s"' % (fileno, p)  # plain link
    return text
%>

Note that for other formats than LaTeX and HTML we just return a link to the figure.

Notice. A corresponding solution for Sphinx will not work because inline figures in Sphinx has a syntax with pipe symbols ('|') that interfer with the column separator in tables in DocOnce. Returning the HTML code in case of Sphinx will just display that HTML code in the cells, not the rendered HTML code. A solution that includes Sphinx is provided later.

The resulting table is displayed below.

Generating the Entire Table

The specific structure of this table also suggest using Mako to generate the entire table:

<%
def generate_table(start, end, step, no_of_columns):
    # Heading
    text = ''
    horizontal_rule = '|----|\n'
    text += horizontal_rule
    text += '|  '*no_of_columns + '|\n'
    text += horizontal_rule
    fig_counter = 0
    for counter in range(start, end+1, step):
        fig_counter += 1
        text += '| ' + tfig('%03d' % counter) + ' '
        if fig_counter % no_of_columns == 0:
            text += '|\n'
    text += horizontal_rule
    return text
%>

${generate_table(80, 120, 5, 3)}

The result is a table like the one above, except that the horizontal rules and the heading are very short lines (but this is legal syntax - it just does not look appealing in the DocOnce source).

Generating the Entire Table in a Native Format via Mako

To allow Sphinx and other formats, it is best to generate the entire table. This can be done either by a Mako function or as a post process after DocOnce has created the output file. We show the Mako solution here.

Tip. A pure Python function Mako is easiest to develop in a seperate Python program file because Python has better error messages than Mako. Also, Python has debugging facilities that make the development of the code much more efficient than writing in Mako. When the Python function works, it can be inserted in the DocOnce file inside the Mako directives <% and %>.

The Mako function for generating the entire table in LaTeX, HTML, and Sphinx format goes as follows.

<%
def generate_native_table(start, end, step, no_of_columns):
    text = ''
    # Heading
    if FORMAT in ("latex", "pdflatex"):
        text += r"""\begin{quote}\begin{tabular}{%s}
\hline
 \\
\hline
""" % ('c'*no_of_columns)
    elif FORMAT in ("sphinx", "rst", "html"):
        text += '<p><table border="1">\n<tr>'
    fig_counter = 0
    latex_columns = []
    for counter in range(start, end+1, step):
        fig_counter += 1
        if FORMAT in ("latex", "pdflatex"):
            latex_columns.append(r'\includegraphics[width=2cm]'\
                    '{mov/wave_frames/frame_%04d.png}\n' % counter)
        elif FORMAT in ("sphinx", "rst", "html"):
            text += '<td align="center"> '\
            '<a href="mov/wave_frames/frame_%04d.png">'\
            '<img src="mov/wave_frames/frame_%04d.png" width="300">'\
            '</a> </td>\n' % (counter, counter)

        if fig_counter % no_of_columns == 0:  # new row
            if FORMAT in ("latex", "pdflatex"):
                text += '   ' + ' & '.join(latex_columns)
                if counter != end:
                    text += r'\\' + '\n'
                latex_columns = []
            elif FORMAT in ("sphinx", "rst", "html"):
                text += '</tr>\n'
                if counter != end:
                    text += '<tr>\n'  # begin new row
    # Footer
    if FORMAT in ("latex", "pdflatex"):
        text += r"""\hline
\end{tabular}\end{quote}
"""
    elif FORMAT in ("sphinx", "rst", "html"):
        text += '</table>\n'
    if FORMAT in ("sphinx", "rst"):
        # Wrap raw HTML code
        lines = text.splitlines()
        text = '\n.. raw:: html\n\n'
        for line in lines:
            text += '    ' + line + '\n'
        text += '\n'
    return text
%>

## Example on call in DocOnce source
${generate_native_table(80, 120, 5, 3)}

One can easily add support for various other formats, such as pandoc, gwiki, mwiki, etc. The output in format the current format is as above.

Generating the Entire Table in a Native Format as a Post Process

Instead of using Mako as shown above, we can invent our own syntax line for the table with figures and apply a script to the DocOnce output file to replace the special line with proper native code. We use the same generate_native_table function as above, but this time in a Python script. In the DocOnce source we place a line

@@@FIGTABLE 80 120 5 3

which is meant to generate a table with figures where the numbers correspond to arguments in the generative_native_table function.

Suppose we have run

Terminal> doconce format sphinx mydoc

In the resulting mydoc.rst file we have the magic line @@@FIGTABLE .... Such lines can now be processed in our Python script:

# read mydoc.rst into the string filestr
pattern = r'@@@FIGTABLE (.+)'
def replacement(m):
    # m is a MatchObject
    args = m.group(1)
    # Convert args to a tuple of words with right type
    args = [eval(arg) for arg in args.split()]
    text = generate_native_table(*args)

filestr = re.sub(pattern, filestr, replacement)
# write filestr back to manual.rst

This code makes use of a function for creating the replacement string for the re.sub command and demands a knowledge of regular expression syntax and the workings or re.sub. A more plain Python version goes like this:

# read mydoc.rst into the string filestr
lines = filestr.splitsplines()
for i in range(len(lines)):
    if lines[i].startswith('@@@FIGTABLE'):
        args = lines[i][10:].strip()
        # Convert args to a tuple of words with right type
        args = [eval(arg) for arg in args.split()]
        text = generate_native_table(*args)
        lines[i] = text
filestr = '\n'.join(lines)  # make one string from all separate lines
# write filestr back to manual.rst

Recommendation. This latter way of inserting specialized native text after DocOnce has generated the output file is easier than using Mako and usually also safer.

Lesson Learned. The above examples show different techniques for extending the DocOnce capabilities. The ideas are not restricted to DocOnce: using Mako as a preprocessing step or inserting "magic" lines that you can later substitute by a script is possible in all types of ASCII-based documents, e.g., LaTeX, Sphinx, and Markdown.