Restructuredtext

Adding images to a csv-table in restructured text

Anyone who has tried to add images using the csv-table directive in restructured text may have come to the following conclusion: it can’t be done. Well certainly not using any of the existing attributes or syntax for tables (an oversight?), but it can be done with the replacement directive.

Firstly, a csv-table in restructured text looks like this:

Currently Held Records
No Category Details Record Date Photo
1 Somersaulting Longest continuous distance 12 miles 390 yards Apr 1986 green_face.jpg

And would created with the following code:

.. csv-table:: Currently Held Records
  :header: "No", "Category", "Details", "Record", "Date", "Photo"
  :widths: 42, 270, 270, 220, 119, 119

  1, "**Somersaulting**", "Longest continuous distance", "12 miles 390 yards", "Apr 1986", |green_face.jpg|

Ignore the first three lines—it’s the table structure info, similar to the way you would define an image, but instead defining table column titles and widths. Should be pretty obvious how to change anything there, but in case not, let’s recap a few csv-table fundamentals, as it is important in restructed text that formatting is followed precisely—right down to the space and comma:

  • a single space after each comma—no other spaces
  • bold text like **this**
  • all text inside "quote marks"
  • numbers don’t need to be in quote marks, unless together with text: "12 miles 390 yards"
  • return at the end of the line

The last line is an example of a row of the table, and more importantly contains the image:

1, "**Somersaulting**", "Longest continuous distance", "12 miles 390 yards", "Apr 1986", |green_face.jpg|

The image is the complex, for “|green_face.jpg|” (without quotes) is actually a “replacement” for the image definition, somewhat akin to an ID in css or a variable in pretty much any programming language you could name.

The image url, link and any other image parametres pointed to by the replacement id then get defined below the table (ie at the bottom of your reSt document):

.. |green_face.jpg| image:: green_face.jpg
  :target: green_face.jpg

Note:

  • The spaces are important as usual, as is putting the info on two lines
  • the name of the replacement/id can be anything, but it makes sense to me to use the image name
  • you can use the same image two times (or more) but only define the replacement once.

Example

You can view an example of a resturctured text csv-table including images here: Ashrita.com

Two directives: sidebar and figure pt.2

Sidebars

We recently covered the use here of two very handy features of reStructured Text (reST): namely the sidebar and figure directives. Sidebars and figures are very useful features for adding additional content styles to documents using reST, for example web diaries created using the EasyBlog product…

As demonstrated in this very article, a sidebar is an area for highlighted content which floats to the right of the actual article. The code for a sidebar in reST is as follows:

.. sidebar:: Sidebar Title
   :subtitle: Optional Sidebar Subtitle

   The sidebar content text would go here.

   .. image:: image.jpg (an optional image)

Those who would like their sidebars to float to the left or middle are out of luck—it’s to the right only for reasons of taste and aesthetics.

And for those interested in such things, the sidebar directive makes use of the following CSS:

.documentContent .sidebar {
       float: right;
       margin: 0 0 10px 20px;
       padding: 15px;
       width: 250px;
       border: &dtml-borderWidth; &dtml-borderStyle; &dtml-globalBorderColor;;
       overflow: hidden;
       }

.documentContent p.sidebar-title {
       font: normal 150%/150% <dtml-var headingFontFamily> !important;;
       background-color: &dtml-globalBackgroundColor;;
       padding: 4px 15px 2px 15px;
       margin: -15px -15px 10px -15px;
       border-bottom: <dtml-var globalBorderColor> solid 1px;
       }

p.sidebar-subtitle {
       font: normal 110%/110% <dtml-var fontFamily> !important;;
       padding: 0;
       margin: 0 0 4px 0;
       }

.documentContent .sidebar img {
       border: none !important;;
       }

#vs-scheme1 .documentContent p.sidebar-title, #vs-scheme1 .documentContent p.sidebar-subtitle {
       color: &dtml-vsScheme1;;
       }

#vs-scheme2 .documentContent p.sidebar-title, #vs-scheme2 .documentContent p.sidebar-subtitle {
       color: &dtml-vsScheme2;;
       }

#vs-scheme3 .documentContent p.sidebar-title, #vs-scheme3 .documentContent p.sidebar-subtitle {
       color: &dtml-vsScheme3;;
       }

#vs-scheme4 .documentContent p.sidebar-title, #vs-scheme4 .documentContent p.sidebar-subtitle {
       color: &dtml-vsScheme4;;
       }

#vs-scheme5 .documentContent p.sidebar-title, #vs-scheme5 .documentContent p.sidebar-subtitle {
       color: &dtml-vsScheme5;;
       }

#vs-scheme6 .documentContent p.sidebar-title, #vs-scheme6 .documentContent p.sidebar-subtitle {
       color: &dtml-vsScheme6;;
       }

#vs-scheme7 .documentContent p.sidebar-title, #vs-scheme7 .documentContent p.sidebar-subtitle {
       color: &dtml-vsScheme7;;
       }

Close observers of the above will note there are several optional dtml calls in this CSS. The dtml in this particular example is designed to work in conjunction with the vsCore product default stylesheet, alongside ploneDefault base_properties.doc, both of which we have modified to create customisable portal_tab colours. The dtml above acquires the colour values of the portal_tab active in a particular location, changing the sidebar title and subtitle colour to match. The sidebar would of course work equally well with a single "hard-wired" title and subtitle colour value for an entire site.

Figure floats

float-left

Floated to the left.

CSS styles have also been created to combine image float styles with the figure directive. There are now three CSS classes which can be applied to the figure directive: float-right, float-left, and float-centre, and what they do should be fairly self-evident—floating an image to the right, left and centre respectively. Keen observers of CSS will point out that there is no such thing as a float-centre command, which is quite correct, but in this case it seemed more consistent to name the class "float-centre" for the sake of users.

float-right

Floated to the right.

While the reST figure directive has always allowed a caption to be added along with an image, with a little additional CSS trickery the captions here have not only been styled with a little font-sizing and colour, but have also been positioned in a more aesthetically pleasing way at the bottom left corner of the images, without using the depracated align="left" html tag, which is the default method in reST.

float-centre

Floated to the centre.

The reST code for these styles is as follows:

.. figure:: image.jpg
   :alt: float-left
   :figclass: float-left

   An image floated to the left.

.. figure:: image.jpg
   :alt: float-right
   :figclass: float-right

   An image floated to the right

.. figure:: image.jpg
   :alt: float-centre
   :figclass: float-centre

   An image floated to the centre

And the CSS employed is as follows:

.float-right {
     position: relative;
     float: right;
     text-align: left;
     border: &dtml-borderWidth; &dtml-borderStyle; &dtml-globalBorderColor;;
     margin: 0 0 23px 20px;
     padding: 0;
     clear: right;
     }

.float-left {
     position: relative;
     float: left;
     text-align: left;
     border: &dtml-borderWidth; &dtml-borderStyle; &dtml-globalBorderColor;;
     margin: 0 20px 23px 0;
     padding: 0;
     clear: left;
     }

.float-centre {
     position: relative;
     text-align: center;
     border: none;
     margin: 0 0 23px 0;
     padding: 0;
     clear: both;
     }

.documentContent .float-right p.caption, .documentContent .float-left p.caption {
     margin: 0 0 -18px 0;
     padding: 3px 0 0 0;
     bottom: 0;
     left: 0;
     font: normal 11px/13px Arial, Helvetica, sans-serif !important;;
     color: #000;
     }

.documentContent .float-centre p.caption {
     margin: 3px 0 0 0;
     padding: 0;
     font: normal 11px/13px Arial, Helvetica, sans-serif !important;;
     color: #000;
     }

Note that a small amount of dtml is again used to style the images with the border colour, width and style, as defined in the site base_properties doc—thereby matching the border around your floated images with the style of your portlets etc. Of course it may be more appropriate in some cases to hardwire this value.

Also of note is the fact that the floated-centre image doesn’t have a border, for the reason that without a fixed width defined the image container is via the block properties of CSS defaulting to 100% width, giving you a border that expands to the full width of your content column no matter the size of the image. Should there be a way to get the border to match the size of the image (the CSS attributes display, width and margin: auto were of no avail) the class will be updated to have a border.

Polaroid effect using css and reST

Those who are not familiar restructured text may initially bemoan it’s lack of power and flexibility when compared to XHTML, but as often the case in life, initial appearances can be deceiving.

Although the use of CSS for styling and presentation is "best practice" in XHTML, it is not yet mandatory, which allows anyone with knowledge of such "deprecated" tags as "align=center" or "font", to illegally wreck havoc with your beautiful CMS-based site.

Outside of a mandatory 2 month course in basic XHTML and CSS, one solution which desperate webmasters have often deployed is to force site editors and contributors to work with WYSIWYG editors configured to strip out any and all illegal tags. Not only is this a somewhat draconian solution, and immensely frustrating from a user point of view, but it still doesn’t bring your site any closer to being beautifully or correctly formatted. Just not illegally so.

And don’t get me started on tables…

Restructured text on the other hand forces compliance to XHTML best practise precisely because it is not XHTML. By allowing users to work in an environment much closer to the simple text notepad which almost everybody is familiar with, and without a single (more often than not forgotten) tag in sight, the simplicity of ReST leaves the site contributor the concentrate on content, as God would have intended it, and takes care of the parsing of said content into strict XHTML for them.

But that’s not all. Presentation is still possible via CSS—also as God intends it—yet much to the relief of the site designer and webmaster—outside of the control of a user whose obsession with "beautifying" one little plant can be to the detriment of the wellbeing of the entire garden.

And not just the presentation of your basic paragraph and heading tags, but, watching closely, the ReST figure directive, which in combination with a little CSS jiggery-pokery detailed below is capable of deploying some quite remarkable effects.

The Polaroid Effect

Through deployment solely of the class "float-right-360" to the figure directive below, it is possible to add a polaroid effect to a photograph in the following manner:

As reStructuredText:

.. figure:: /images/the_moon.jpg
   :alt: the moon
   :figclass: float-right-360

    The moon during a lunar-eclipse. Pretty!

To produce the following image and caption:

the moon

The moon during a lunar-eclipse. Pretty!

Which is achieved with the following css:

.float-right-360 {
       position: relative;
       float: right;
       text-align: left;
       background-image: url(polaroid_360_270.png);
       background-repeat: no-repeat;
       margin: 10px 0 10px 20px;
       padding: 1px 8px 8px 1px;
       border: none;
       }

.float-right-360 img {
       border: #fff 7px solid;
       border-bottom: #fff 36px solid;
       width: 247px;
       height: 308px;
       }

.float-right-360 p.caption {
       position: absolute;
       font: normal 11px/13px Arial, Helvetica, sans-serif !important;;
       color: #000;
       margin: 0;
       padding: 0 10px 0 0;
       top: 321px;
       left: 10px;
       }

Note there is one limitation to this effect—the image used must be exactly 308px H by 247px W, because there simply aren’t enough "hooks" inside the figure directive to deploy the necessary number of background images to allow scaling.

As a work around to this limitation, one could create a variety of classes for pre-determined image sizes and orientations, which would also have the added benefit of forcing your users to stick to creating images in sizes complimentary to the overall site design.

Which raises another sore point about CMS’s which don’t employ image-sizing engines—but that would be another topic…

Editing old pages in reSt

One problem with changing from HTML (or a content editor) to reStructured Text in Plone is that the text editor doesnt convert your old HTML docs to reStructured Text.

However, my experience so far is that if you copy the text of the page (not the code), click on the edit tab, delete the HTML code and paste the content of the page back in, it does a pretty good job of keeping the layout of the page. Paragraphs, bullet points and numbered lists are largely mantained. Of course, links images and preformatted text all have to be put back, but what can you do…

A reStructuredText Primer

This is an on-going post. Please forgive the "work-in-progress" feel.

The text below contains links that look like "(quickref)". These
are relative links that point to the Quick reStructuredText user
reference. If these links don’t work, please refer to the master
quick reference
document.

Structure

From the outset, let me say that "Structured Text" is probably a bit
of a misnomer. It’s more like "Relaxed Text" that uses certain
consistent patterns. These patterns are interpreted by a HTML
converter to produce "Very Structured Text" that can be used by a web
browser.

The most basic pattern recognised is a paragraph (quickref).
That’s a chunk of text that is separated by blank lines (one is
enough). Paragraphs must have the same indentation — that is, line
up at their left edge. Paragraphs that start indented will result in
indented quote paragraphs. For example:

This is a paragraph.  It's quite
short.

   This paragraph will result in an indented block of
   text, typically used for quoting other text.

This is another one.

Results in:

This is a paragraph. It’s quite
short.

This paragraph will result in an indented block of
text, typically used for quoting other text.

This is another one.

Text styles

(quickref)

Inside paragraphs and other bodies of text, you may additionally mark
text for italics with "*italics*" or bold with
"**bold**".

If you want something to appear as a fixed-space literal, use
"``double back-quotes``". Note that no further fiddling is done
inside the double back-quotes — so asterisks "*" etc. are left
alone.

If you find that you want to use one of the "special" characters in
text, it will generally be OK — reStructuredText is pretty smart.
For example, this * asterisk is handled just fine. If you actually
want text *surrounded by asterisks* to not be italicised, then
you need to indicate that the asterisk is not special. You do this by
placing a backslash just before it, like so "\*" (quickref), or
by enclosing it in double back-quotes (inline literals), like this:

``\*``

Lists

Lists of items come in three main flavours: enumerated,
bulleted and definitions. In all list cases, you may have as
many paragraphs, sublists, etc. as you want, as long as the left-hand
side of the paragraph or whatever aligns with the first line of text
in the list item.

Lists must always start a new paragraph — that is, they must appear
after a blank line.

bulleted lists (quickref)

Just like enumerated lists, start the line off with a bullet point
character – either "-", "+" or "*":

* a bullet point using "*"

  - a sub-list using "-"

    + yet another sub-list

  - another item

Results in:

  • a bullet point using "*"
    • a sub-list using "-"
      • yet another sub-list
    • another item
definition lists (quickref)

Unlike the other two, the definition lists consist of a term, and
the definition of that term. The format of a definition list is:

what
  Definition lists associate a term with a definition.

*how*
  The term is a one-line phrase, and the definition is one or more
  paragraphs or body elements, indented relative to the term.
  Blank lines are not allowed between term and definition.

Results in:

what
Definition lists associate a term with a definition.
how
The term is a one-line phrase, and the definition is one or more
paragraphs or body elements, indented relative to the term.
Blank lines are not allowed between term and definition.

Preformatting (code samples)

(quickref)

To just include a chunk of preformatted, never-to-be-fiddled-with
text, finish the prior paragraph with "::". The preformatted
block is finished when the text falls back to the same indentation
level as a paragraph prior to the preformatted block. For example:

An example::

    Whitespace, newlines, blank lines, and all kinds of markup
      (like *this* or \this) is preserved by literal blocks.
  Lookie here, I've dropped an indentation level
  (but not far enough)

no more example

Results in:

An example:

  Whitespace, newlines, blank lines, and all kinds of markup
    (like *this* or \this) is preserved by literal blocks.
Lookie here, I've dropped an indentation level
(but not far enough)

no more example

Note that if a paragraph consists only of "::", then it’s removed
from the output:

::

    This is preformatted text, and the
    last "::" paragraph is removed

Results in:

This is preformatted text, and the
last "::" paragraph is removed

Sections

(quickref)

To break longer text up into sections, you use section headers.
These are a single line of text (one or more words) with adornment: an
underline alone, or an underline and an overline together, in dashes
"-----", equals "======", tildes "~~~~~~" or any of the
non-alphanumeric characters = - ` : ' " ~ ^ _ * + # < > that you
feel comfortable with. An underline-only adornment is distinct from
an overline-and-underline adornment using the same character. The
underline/overline must be at least as long as the title text. Be
consistent, since all sections marked with the same adornment style
are deemed to be at the same level:

Chapter 1 Title
===============

Section 1.1 Title
-----------------

Subsection 1.1.1 Title
~~~~~~~~~~~~~~~~~~~~~~

Section 1.2 Title
-----------------

Chapter 2 Title
===============

This results in the following structure, illustrated by simplified
pseudo-XML:

<section>
    <title>
        Chapter 1 Title
    <section>
        <title>
            Section 1.1 Title
        <section>
            <title>
                Subsection 1.1.1 Title
    <section>
        <title>
            Section 1.2 Title
<section>
    <title>
        Chapter 2 Title

(Pseudo-XML uses indentation for nesting and has no end-tags. It’s
not possible to show actual processed output, as in the other
examples, because sections cannot exist inside block quotes. For a
concrete example, compare the section structure of this document’s
source text and processed output.)

Note that section headers are available as link targets, just using
their name. To link to the Lists heading, I write "Lists_". If
the heading has a space in it like text styles, we need to quote
the heading "`text styles`_".

Document Title / Subtitle

The title of the whole document is distinct from section titles and
may be formatted somewhat differently (e.g. the HTML writer by default
shows it as a centered heading).

To indicate the document title in reStructuredText, use a unique adornment
style at the beginning of the document. To indicate the document subtitle,
use another unique adornment style immediately after the document title. For
example:

================
 Document Title
================
----------
 Subtitle
----------

Section Title
=============

...

Note that "Document Title" and "Section Title" above both use equals
signs, but are distict and unrelated styles. The text of
overline-and-underlined titles (but not underlined-only) may be inset
for aesthetics.

Images

(quickref)

To include an image in your document, you use the the image directive.
For example:

.. image:: /images/vasudevaserver.gif

results in:

/images/vasudevaserver.gif

The images/biohazard.png part indicates the filename of the image
you wish to appear in the document. There’s no restriction placed on
the image (format, size etc). If the image is to appear in HTML and
you wish to supply additional information, you may:

.. image:: /images/vasudevaserver.gif
   :height: 100
   :width: 200
   :scale: 50
   :alt: alternate text

See the full image directive documentation for more info.

What Next?

This primer introduces the most common features of reStructuredText,
but there are a lot more to explore. The Quick reStructuredText
user reference is a good place to go next. For complete details, the
reStructuredText Markup Specification is the place to go [1].

Users who have questions or need assistance with Docutils or
reStructuredText should post a message to the Docutils-Users
mailing list
. The Docutils project web site has more
information.

[1] If that relative link doesn’t work, try the master document:
http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html.

reStructeredText (ReST) default type on Vasudevaservice.com

reStructeredText (ReST) is now the default content format for all the standard ATCT objects (Pages, News, Events) and EasyBlog, for all sites on this server.

For now, if you still have Kupu as your editor then the default will be overriden by Kupu to html.

Be aware though, that since we are going to use Vasudevaservice.com as testbed for reStructuredText, Kupu has been uninstalled there.

Two directives: sidebar and figure

ReStructuredtext has a "sidebar" directive. See a good example of a sidebar here: http://en.wikipedia.org/wiki/Gorbachev

Sidebars are like miniature, parallel documents that occur inside other documents, providing related or reference material. A sidebar is typically offset by a border and "floats" to the side of the page; the document’s main text may flow around it. Sidebars can also be likened to super-footnotes; their content is outside of the flow of the document’s main text.

Sidebars may occur anywhere a section or transition may occur. Body elements (including sidebars) may not contain nested sidebars.

If you would have the following css inside your Plone skin:

.sidebar
{
color: red;
font-weight: bold;
float: right;
width: 10em;
}

The following code:

.. sidebar:: Sidebar Title
   :subtitle: Optional Sidebar Subtitle

   Subsequent indented lines comprise
   the body of the sidebar, and are
   interpreted as body elements...

   .. image::  /images/vasudevaserver.gif

Would be rendered as a sidebar of text floating on the right.

Now, for what concerns images, reStructuredText has a wonderful directive, "figure", which also support a "class" attribute.

Let’s assume we also have this css:

.float-right
{
float: right;
border-style: dashed;
border-width: 1px;
border-color: red;
}

The following reStructuredText:

.. figure:: /images/vasudevaserver.gif
   :alt: logo
   :figwidth: image
   :figclass: float-right
   :align: right

    This is the caption.

Would produce the following:

logo

This is the caption.

That is for today! We saw how easy it is to employ the two powerful directives "sidebar" and "figure".

See you next time!