Welcome to rstview’s documentation!

This is a simple Django application around docutils to parse reStructuredText markup.

Warning

Version 0.3.0 have major backward changes, see details in documentation changelogs.

Features

  • Either Html4 or Htmls5 writers available;
  • Custom reporter to validate source;
  • Dedicated view to make a page from a rst source;
  • Template tag to parse reStructuredText markup;
  • Comes with unittests;

Dependancies

  • Django >= 1.7;
  • docutils >= 0.7;
  • Optionnaly (but recommended): Pygments >= 1.2.x to have highlighted syntax in your sourcecode blocks;

User’s Guide

Install

pip install rstview

Then register the app in your project settings like this :

INSTALLED_APPS = (
    ...
    'rstview',
    ...
)

Also you can overrides some default settings from your project settings file.

Once done, your project can use rstview template tags and views.

App default settings

Default settings rstviews needs. You can override them in your project settings file.

rstview.settings.RSTVIEW_ERROR_TEMPLATE = u'Line {lineno} : {message}'

Template string used to format error from rst.viewreporter.SourceReporter.

rstview.settings.RSTVIEW_PARSER_ENABLE_FILE_INSERTION = False

Enable unsafe file insertion directives, enable it at your own risk.

rstview.settings.RSTVIEW_PARSER_ENABLE_RAW_INSERTION = False

Enable unsafe raw insertion directives, enable it at your own risk.

rstview.settings.RSTVIEW_PARSER_FILTER_SETTINGS = {'default': {'initial_header_level': 3, 'doctitle_xform': False, 'footnote_references': 'superscript', 'language_code': 'en', 'file_insertion_enabled': False, 'raw_enabled': False}}

Available parser options sets.

These are options only for docutils parser, see Docutils Configuration.

Default entry default must allways be present.

rstview.settings.RSTVIEW_PARSER_LANGUAGE_CODE = 'en'

Locale code for document. Docutils parser don’t support the common pattern xx_XX, only the first part xx.

rstview.settings.RSTVIEW_PARSER_SECURITY = {'enable_exit': 0, 'halt_level': 6}

Some parse options you should not change. They’re automatically appended to each used parser options set.

rstview.settings.RSTVIEW_PARSER_SILENT = False

Default value for silent mode on parser

Silent means errors and warnings are totally ignored in opposed to un-silent where errors and warnings can be inserted into rendered source and also push to standard output.

rstview.settings.RSTVIEW_PARSER_WRITER = 'html5'

The docutils writer to use, can be html4 (suitable for xhtml too) or html5.

rstview.settings.RSTVIEW_PYGMENTS_CONTAINER_CLASSPREFIX = 'pygments'

CSS class prefix for generated Pygments elements when not using inline styles.

rstview.settings.RSTVIEW_PYGMENTS_INLINESTYLES = False

Enable usage of inline CSS styles in HTML generated by Pygments.

This will fill your HTML with a lot of inline styles. Disabled by default, the recommended way is to style it yourself, because there is not so much to do once.

Parser

Some helpers around docutils parser to easily parse reStructuredText markup with some options.

Note

This module try to load the pygment directive if available, so you don’t need to load it from your code if you want to use Pygment to highlight code blocks.

class rstview.parser.RstBasicRenderer(*args, **kwargs)[source]

Bases: object

Basic interface around docutils to parse and render reStructuredText markup.

This follows the legacy behaviors of docutils parser, that means:

  • Parser errors and warnings are inserted inside the rendered source;
  • Errors and warnings are pushed to the standard output;

Example

1
2
3
4
>>> from rstview.parser import RstBasicRenderer
>>> renderer = RstBasicRenderer()
>>> renderer.parse("Lorem **ipsum** salace")
<p>Lorem <strong>ipsum</strong> salace</p>
get_options(name, initial_header_level=None, silent=False)[source]

Load the given option set name and possibly update some option from given keyword arguments.

Parameters:

name (string) – Name of an option set from settings.RSTVIEW_PARSER_FILTER_SETTINGS.

Keyword Arguments:
 
  • initial_header (int) – To modify option initial_header_level.
  • silent (string) – If True, will push the parser reporter level to the lowest verbosiy so errors and warnings are ignored. Default value is the same as settings.RSTVIEW_PARSER_SILENT.
Returns:

Options to give to Docutils parser.

Return type:

dict

get_writer_option()[source]

Get the writer option for parser config depending it’s html4 or html5.

Returns:A dict containing the right writer option name and value.
Return type:dict
parse(source, setting_key='default', body_only=True, **kwargs)[source]

Parse reStructuredText source with given options.

Parameters:
  • source (string) – reStructuredText source to parse.
  • **kwargs – Arbitrary keyword arguments to give as options to RstBasicRenderer.get_options().
Keyword Arguments:
 
  • setting_key (string) – Name of option set to use from settings.RSTVIEW_PARSER_FILTER_SETTINGS.
  • body_only (string) – If True, parser will only return the rendered content else it will return the full dict from Docutils parser. This dict contains many datas about parsing. Default is True.
Returns:

Depending from body_only, it will be a rendered content as a string or a dict containing datas about parsing (rendered content, styles, messages, title, etc..).

Return type:

string or dict

class rstview.parser.RstExtendedRenderer(*args, **kwargs)[source]

Bases: rstview.parser.RstBasicRenderer

Extended interface for next generation usage

This promotes the extended behaviors:

  • Parser can be used to validate markup out of rendered document;
  • Nothing is printed out on standard output;

docutils parser is a bit touchy to use programatically, so we need to apply some monkey patchs before and after parsing.

Example

1
2
3
4
5
6
7
8
>>> from rstview.parser import RstExtendedRenderer
>>> renderer = RstExtendedRenderer()
>>> renderer.parse("Lorem **ipsum** salace")
<p>Lorem <strong>ipsum</strong> salace</p>
>>> rendered.is_valid()
True
>>> rendered.get_messages()
[]
format_parsing_error(error)[source]

Format error message datas to a message line.

Parameters:error (tuple) – Message error returned by reporter contain four elements: line number, error code and message.
Returns:Formatted message.
Return type:string
get_messages()[source]

Get a list of formatted messages

Returns:A list of messages.
is_valid()[source]

Only to be used after parsing

Returns:True if no errors, else False
Return type:bool
parse(*args, **kwargs)[source]

Proceed to parsing for validation

We apply monkey patchs on two docutils methods, parse source then unmonkey.

Everytime validation is processed, messages are reseted so it should be safe enough to use the RstExtendedRenderer instance for many documents.

Once done you can access raw error messages datas from instance attribute messages or use RstExtendedRenderer.get_messages to have formatted message lines.

Returns:Depending from body_only, it will be a rendered content as a string or a dict containing datas about parsing (rendered content, styles, messages, title, etc..).
Return type:string or dict
rstview.parser.build_output(source, output_filepath, **kwargs)[source]

Very basic shortcut helper to build a file from rendered reStructuredText source.

Parameters:
  • source (string) – reStructuredText source to parse and render.
  • output_filepath (string) – File path where to write rendered source.
  • **kwargs – Arbitrary keyword arguments to give as options to rstview.parser.SourceParser.

Views

class rstview.views.RSTFileView(**kwargs)[source]

Parse and render a reStructuredText file from given path.

Example

from django.conf.urls import url

from rstview.views import RSTFileView

urlpatterns = [
    url(r'^basic/$', RSTFileView.as_view(
        doc_path="/home/foo/basic/input.rst",
        doc_title="Basic sample"
    ), name='sample-view-basic'),
]
template_name

string

Template file to render. Default to rstview/fileview.html.

doc_title

string

Optionnal document title. Default to None.

doc_path

string

Path to a reStructuredText file, it is recommended you use an absolute path.

This is the only required argument you must allways define.

Default to None.

doc_parser_class

object

A parser class from rstview.parser. Default is rstview.parser.RstExtendedRenderer.

doc_parser_silent

bool

Enable to override default silent mode behavior. Default value is the same as settings.RSTVIEW_PARSER_SILENT.

doc_parser_bodyonly

bool

If True, parser will only return the rendered content, this is the default behavior. Default is False.

doc_parser_opts_name

string

Name of an option set from rstview.settings.RSTVIEW_PARSER_FILTER_SETTINGS. Default to default.

doc_parser_class

alias of RstExtendedRenderer

get_context_data(**kwargs)[source]

Expand template context with some document related variables:

doc_title
The given document title.
doc_source
Source from given filepath.
doc_html
Rendered source from parser.
doc_parser_opts_name
Name of an option set from settings.RSTVIEW_PARSER_FILTER_SETTINGS.
Returns:Context variables expanded with variables.
Return type:dict
get_document_title()[source]

Get document title from RSTFileView.doc_title

Returns:Document title.
Return type:string
get_parser_opts()[source]

Return parser options.

Returns:Options to give to parser.SourceParser:
  • setting_key: from class attribute RSTFileView.doc_parser_opts_name;
  • silent: from class attribute RSTFileView.doc_parser_silent;
  • body_only: from class attribute RSTFileView.doc_parser_bodyonly;
Return type:dict
get_source()[source]

Return file source from given path in RSTFileView.doc_path.

Raises:rstview.views.RstViewInvalidException – If RSTFileView.doc_path is not defined.
Returns:File content.
Return type:string
render_source(source)[source]

Parse given source and return result as safe for django template.

Use RSTFileView.get_parser_opts() to get and give options to parser.

Parameters:source (string) – reStructuredText markup to parse.
Returns:Rendered source from parser.
Return type:string
template_name = 'rstview/fileview.html'

Default template

exception rstview.views.RstViewInvalidException[source]

Excepion to be raised when RSTFileView usage is incorrect.

Template tags

rstview.templatetags.rstview_tags.rst_render(source, *args, **kwargs)[source]

Parse and render given string source using given parser option set.

Examples

Basic usage:

{% load rstview_tags %}

{% rst_render SOURCE_STRING %}

Using a specific config set:

{% load rstview_tags %}

{% rst_render SOURCE_STRING config='myconfig' %}

Muting error and warning from parser:

{% load rstview_tags %}

{% rst_render SOURCE_STRING silent=True %}

Everything joined:

{% load rstview_tags %}

{% rst_render SOURCE_STRING config='myconfig' silent=True %}

Tag signature:

{% rst_render SOURCE_STRING [config='default'] [silent=True] %}
Parameters:

source (string) – reStructuredText markup to parse.

Keyword Arguments:
 
  • config (string) – Name of an option set from settings.RSTVIEW_PARSER_FILTER_SETTINGS.
  • silent (bool) – Enable to override default silent mode behavior. Default value is the same as settings.RSTVIEW_PARSER_SILENT.
Returns:

Rendered source from parser.

Return type:

string

Html5 writer

Original code is from ‘Bradley Wright’ on Github :

https://github.com/bradleywright/rst-to-semantic-html5

Stealed and modified because i wanted to keep <section/> behavior but not to follow the same way than ‘rst-to-semantic-html5’.

class rstview.html5writer.SemanticHTML5Translator(document)[source]

This is a translator class for the docutils system. It will produce a minimal set of html output. (No extra divs, classes over ids.)

It also aims to produce HTML5 (section etc.)

visit_literal_block(node)[source]

No classes please

class rstview.html5writer.SemanticHTML5Writer[source]

This docutils writer will use the SemanticHTML5Translator class below.

class rstview.html5writer.abbreviation(rawsource='', text='', *children, **attributes)[source]

Node for abbreviations with explanations.

class rstview.html5writer.kbd(rawsource='', text='', *children, **attributes)[source]

Node for kbd element

Developer’s Guide

Development

Development requirement

rstview is developed with:

  • Test Development Driven (TDD) using Pytest;
  • Respecting flake and pip8 rules using Flake8;
  • Sphinx for documentation with enabled Napoleon extension (using only the Google style);
  • tox to test again different Python and Django versions;

Every requirement is available in file dev_requirements.txt (except for tox).

Install for development

First ensure you have pip and virtualenv installed, then in your console terminal type this:

mkdir rstview-dev
cd rstview-dev
virtualenv --system-site-packages .
source bin/activate
pip install -r https://raw.githubusercontent.com/sveetch/rstview/master/requirements/dev.txt

rstview will be installed in editable mode from the last commit on master branch.

Unittests

Unittests are made to works on Pytest, a shortcut in Makefile is available to start them on your current development install:

make tests
Tox

To ease development again multiple Python and Django versions, a tox configuration has been added. You are strongly encouraged to use it to test your pull requests.

Before using it you will need to install tox, it is recommended to install it at your system level so dependancy is not in tests requirements file:

sudo pip install tox

Then go in the rstview module directory, where the setup.py and tox.ini live and execute tox:

tox

Changelog

Version 0.3.2 - 2016/07/26

  • Fixed tests settings and conftest so tests can run correctly through tox;
  • Added Django 1.7, Django 1.8, Django 1.9 support since these versions have passed tests through tox;

Version 0.3.1 - 2016/07/26

  • First try to use tox for tests;

Version 0.3.0 - 2016/07/24

  • Added unittests with Py.test and a dummy project for tests;
  • Added better documentation using Sphinx+Autodoc+Napoleon;
  • Now require for Django==1.8;
  • Major changes in modules and structure:
    • rstview.parser has been refactored to contain everything in two classes;
    • Improved view rstview.views.RSTFileView to be more flexible;
    • Default shipped view template now inherits from skeleton.html instead of base.html;
    • Template filter source_render has been dropped in profit of template tag rst_render which has more options;
    • Dropped old sample rstview/rst_sample.rst;
    • rstview.views.RSTFileView now raise an exception if doc_path attributed is empty;

Version 0.2.1 - 2014/08/17

Minor update for README.

Version 0.2.0 - 2014/08/16

  • Added source_render template filter;
  • Updated README;