docutils-0.12/0000775000175000017500000000000012356234260015227 5ustar engelbertengelbert00000000000000docutils-0.12/tools/0000775000175000017500000000000012356234260016367 5ustar engelbertengelbert00000000000000docutils-0.12/tools/buildhtml.py0000775000175000017500000002335612070265616020743 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: buildhtml.py 7579 2012-12-31 10:40:14Z grubert $ # Author: David Goodger # Copyright: This module has been placed in the public domain. """ Generates .html from all the .txt files in a directory. Ordinary .txt files are understood to be standalone reStructuredText. Files named ``pep-*.txt`` are interpreted as reStructuredText PEPs. """ # Once PySource is here, build .html from .py as well. __docformat__ = 'reStructuredText' try: import locale locale.setlocale(locale.LC_ALL, '') except: pass import sys import os import os.path import copy from fnmatch import fnmatch import docutils from docutils import ApplicationError from docutils import core, frontend, utils from docutils.utils.error_reporting import ErrorOutput, ErrorString from docutils.parsers import rst from docutils.readers import standalone, pep from docutils.writers import html4css1, pep_html usage = '%prog [options] [ ...]' description = ('Generates .html from all the reStructuredText .txt files ' '(including PEPs) in each ' '(default is the current directory).') class SettingsSpec(docutils.SettingsSpec): """ Runtime settings & command-line options for the front end. """ prune_default = ['.hg', '.bzr', '.git', '.svn', 'CVS'] # Can't be included in OptionParser below because we don't want to # override the base class. settings_spec = ( 'Build-HTML Options', None, (('Recursively scan subdirectories for files to process. This is ' 'the default.', ['--recurse'], {'action': 'store_true', 'default': 1, 'validator': frontend.validate_boolean}), ('Do not scan subdirectories for files to process.', ['--local'], {'dest': 'recurse', 'action': 'store_false'}), ('Do not process files in (shell globbing patterns, ' 'separated by colons). This option may be used ' 'more than once to specify multiple directories. Default: "%s".' % ':'.join(prune_default), ['--prune'], {'metavar': '', 'action': 'append', 'validator': frontend.validate_colon_separated_string_list, 'default': prune_default,}), ('Recursively ignore files matching any of the given ' 'wildcard (shell globbing) patterns (separated by colons).', ['--ignore'], {'metavar': '', 'action': 'append', 'default': [], 'validator': frontend.validate_colon_separated_string_list}), ('Work silently (no progress messages). Independent of "--quiet".', ['--silent'], {'action': 'store_true', 'validator': frontend.validate_boolean}), ('Do not process files, show files that would be processed.', ['--dry-run'], {'action': 'store_true', 'validator': frontend.validate_boolean}),)) relative_path_settings = ('prune',) config_section = 'buildhtml application' config_section_dependencies = ('applications',) class OptionParser(frontend.OptionParser): """ Command-line option processing for the ``buildhtml.py`` front end. """ def check_values(self, values, args): frontend.OptionParser.check_values(self, values, args) values._source = None return values def check_args(self, args): source = destination = None if args: self.values._directories = args else: self.values._directories = [os.getcwd()] return source, destination class Struct: """Stores data attributes for dotted-attribute access.""" def __init__(self, **keywordargs): self.__dict__.update(keywordargs) class Builder: def __init__(self): self.publishers = { '': Struct(components=(pep.Reader, rst.Parser, pep_html.Writer, SettingsSpec)), '.txt': Struct(components=(rst.Parser, standalone.Reader, html4css1.Writer, SettingsSpec), reader_name='standalone', writer_name='html'), 'PEPs': Struct(components=(rst.Parser, pep.Reader, pep_html.Writer, SettingsSpec), reader_name='pep', writer_name='pep_html')} """Publisher-specific settings. Key '' is for the front-end script itself. ``self.publishers[''].components`` must contain a superset of all components used by individual publishers.""" self.setup_publishers() def setup_publishers(self): """ Manage configurations for individual publishers. Each publisher (combination of parser, reader, and writer) may have its own configuration defaults, which must be kept separate from those of the other publishers. Setting defaults are combined with the config file settings and command-line options by `self.get_settings()`. """ for name, publisher in self.publishers.items(): option_parser = OptionParser( components=publisher.components, read_config_files=1, usage=usage, description=description) publisher.option_parser = option_parser publisher.setting_defaults = option_parser.get_default_values() frontend.make_paths_absolute(publisher.setting_defaults.__dict__, option_parser.relative_path_settings) publisher.config_settings = ( option_parser.get_standard_config_settings()) self.settings_spec = self.publishers[''].option_parser.parse_args( values=frontend.Values()) # no defaults; just the cmdline opts self.initial_settings = self.get_settings('') def get_settings(self, publisher_name, directory=None): """ Return a settings object, from multiple sources. Copy the setting defaults, overlay the startup config file settings, then the local config file settings, then the command-line options. Assumes the current directory has been set. """ publisher = self.publishers[publisher_name] settings = frontend.Values(publisher.setting_defaults.__dict__) settings.update(publisher.config_settings, publisher.option_parser) if directory: local_config = publisher.option_parser.get_config_file_settings( os.path.join(directory, 'docutils.conf')) frontend.make_paths_absolute( local_config, publisher.option_parser.relative_path_settings, directory) settings.update(local_config, publisher.option_parser) settings.update(self.settings_spec.__dict__, publisher.option_parser) return settings def run(self, directory=None, recurse=1): recurse = recurse and self.initial_settings.recurse if directory: self.directories = [directory] elif self.settings_spec._directories: self.directories = self.settings_spec._directories else: self.directories = [os.getcwd()] for directory in self.directories: for root, dirs, files in os.walk(directory): # os.walk by default this recurses down the tree, # influence by modifying dirs. if not recurse: del dirs[:] self.visit(root, files, dirs) def visit(self, directory, names, subdirectories): settings = self.get_settings('', directory) errout = ErrorOutput(encoding=settings.error_encoding) if settings.prune and (os.path.abspath(directory) in settings.prune): errout.write('/// ...Skipping directory (pruned): %s\n' % directory) sys.stderr.flush() del subdirectories[:] return if not self.initial_settings.silent: errout.write('/// Processing directory: %s\n' % directory) sys.stderr.flush() # settings.ignore grows many duplicate entries as we recurse # if we add patterns in config files or on the command line. for pattern in utils.uniq(settings.ignore): for i in range(len(names) - 1, -1, -1): if fnmatch(names[i], pattern): # Modify in place! del names[i] for name in names: if name.endswith('.txt'): self.process_txt(directory, name) def process_txt(self, directory, name): if name.startswith('pep-'): publisher = 'PEPs' else: publisher = '.txt' settings = self.get_settings(publisher, directory) errout = ErrorOutput(encoding=settings.error_encoding) pub_struct = self.publishers[publisher] settings._source = os.path.normpath(os.path.join(directory, name)) settings._destination = settings._source[:-4]+'.html' if not self.initial_settings.silent: errout.write(' ::: Processing: %s\n' % name) sys.stderr.flush() try: if not settings.dry_run: core.publish_file(source_path=settings._source, destination_path=settings._destination, reader_name=pub_struct.reader_name, parser_name='restructuredtext', writer_name=pub_struct.writer_name, settings=settings) except ApplicationError: error = sys.exc_info()[1] # get exception in Python <2.6 and 3.x errout.write(' %s\n' % ErrorString(error)) if __name__ == "__main__": Builder().run() docutils-0.12/tools/editors/0000775000175000017500000000000012356234260020040 5ustar engelbertengelbert00000000000000docutils-0.12/tools/editors/emacs/0000775000175000017500000000000012356234260021130 5ustar engelbertengelbert00000000000000docutils-0.12/tools/editors/emacs/rst.el0000664000175000017500000044753512026705225022302 0ustar engelbertengelbert00000000000000;;; rst.el --- Mode for viewing and editing reStructuredText-documents. ;; Copyright (C) 2003-2012 Free Software Foundation, Inc. ;; Maintainer: Stefan Merten ;; Author: Stefan Merten , ;; Martin Blais , ;; David Goodger , ;; Wei-Wei Guo ;; This file is part of GNU Emacs. ;; GNU Emacs is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; GNU Emacs is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs. If not, see . ;;; Commentary: ;; This package provides major mode rst-mode, which supports documents marked ;; up using the reStructuredText format. Support includes font locking as well ;; as a lot of convenience functions for editing. It does this by defining a ;; Emacs major mode: rst-mode (ReST). This mode is derived from text-mode. ;; This package also contains: ;; ;; - Functions to automatically adjust and cycle the section underline ;; adornments; ;; - A mode that displays the table of contents and allows you to jump anywhere ;; from it; ;; - Functions to insert and automatically update a TOC in your source ;; document; ;; - Function to insert list, processing item bullets and enumerations ;; automatically; ;; - Font-lock highlighting of most reStructuredText structures; ;; - Indentation and filling according to reStructuredText syntax; ;; - Cursor movement according to reStructuredText syntax; ;; - Some other convenience functions. ;; ;; See the accompanying document in the docutils documentation about ;; the contents of this package and how to use it. ;; ;; For more information about reStructuredText, see ;; http://docutils.sourceforge.net/rst.html ;; ;; For full details on how to use the contents of this file, see ;; http://docutils.sourceforge.net/docs/user/emacs.html ;; ;; ;; There are a number of convenient key bindings provided by rst-mode. ;; For more on bindings, see rst-mode-map below. There are also many variables ;; that can be customized, look for defcustom in this file. ;; ;; If you use the table-of-contents feature, you may want to add a hook to ;; update the TOC automatically every time you adjust a section title:: ;; ;; (add-hook 'rst-adjust-hook 'rst-toc-update) ;; ;; Syntax highlighting: font-lock is enabled by default. If you want to turn ;; off syntax highlighting to rst-mode, you can use the following:: ;; ;; (setq font-lock-global-modes '(not rst-mode ...)) ;; ;; ;; ;; Customization is done by customizable variables contained in customization ;; group "rst" and subgroups. Group "rst" is contained in the "wp" group. ;; ;;; DOWNLOAD ;; The latest release of this file lies in the docutils source code repository: ;; http://docutils.svn.sourceforge.net/svnroot/docutils/trunk/docutils/tools/editors/emacs/rst.el ;;; INSTALLATION ;; Add the following lines to your init file: ;; ;; (require 'rst) ;; ;; If you are using `.txt' as a standard extension for reST files as ;; http://docutils.sourceforge.net/FAQ.html#what-s-the-standard-filename-extension-for-a-restructuredtext-file ;; suggests you may use one of the `Local Variables in Files' mechanism Emacs ;; provides to set the major mode automatically. For instance you may use:: ;; ;; .. -*- mode: rst -*- ;; ;; in the very first line of your file. The following code is useful if you ;; want automatically enter rst-mode from any file with compatible extensions: ;; ;; (setq auto-mode-alist ;; (append '(("\\.txt\\'" . rst-mode) ;; ("\\.rst\\'" . rst-mode) ;; ("\\.rest\\'" . rst-mode)) auto-mode-alist)) ;; ;;; Code: ;; FIXME: Check through major mode conventions again. ;; FIXME: Add proper ";;;###autoload" comments. ;; FIXME: When 24.1 is common place remove use of `lexical-let' and put "-*- ;; lexical-binding: t -*-" in the first line. ;; FIXME: Use `testcover'. ;; FIXME: The adornment classification often called `ado' should be a ;; `defstruct'. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for `testcover' (when (boundp 'testcover-1value-functions) ;; Below `lambda' is used in a loop with varying parameters and is thus not ;; 1valued. (setq testcover-1value-functions (delq 'lambda testcover-1value-functions)) (add-to-list 'testcover-compose-functions 'lambda)) (defun rst-testcover-defcustom () "Remove all customized variables from `testcover-module-constants'. This seems to be a bug in `testcover': `defcustom' variables are considered constants. Revert it with this function after each `defcustom'." (when (boundp 'testcover-module-constants) (setq testcover-module-constants (delq nil (mapcar (lambda (sym) (if (not (plist-member (symbol-plist sym) 'standard-value)) sym)) testcover-module-constants))))) (defun rst-testcover-add-compose (fun) "Add FUN to `testcover-compose-functions'." (when (boundp 'testcover-compose-functions) (add-to-list 'testcover-compose-functions fun))) (defun rst-testcover-add-1value (fun) "Add FUN to `testcover-1value-functions'." (when (boundp 'testcover-1value-functions) (add-to-list 'testcover-1value-functions fun))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Common Lisp stuff ;; Only use of macros is allowed - may be replaced by `cl-lib' some time. (eval-when-compile (require 'cl)) ;; Redefine some functions from `cl.el' in a proper namespace until they may be ;; used from there. (defun rst-signum (x) "Return 1 if X is positive, -1 if negative, 0 if zero." (cond ((> x 0) 1) ((< x 0) -1) (t 0))) (defun rst-some (seq &optional pred) "Return non-nil if any element of SEQ yields non-nil when PRED is applied. Apply PRED to each element of list SEQ until the first non-nil result is yielded and return this result. PRED defaults to `identity'." (unless pred (setq pred 'identity)) (catch 'rst-some (dolist (elem seq) (let ((r (funcall pred elem))) (when r (throw 'rst-some r)))))) (defun rst-position-if (pred seq) "Return position of first element satisfying PRED in list SEQ or nil." (catch 'rst-position-if (let ((i 0)) (dolist (elem seq) (when (funcall pred elem) (throw 'rst-position-if i)) (incf i))))) (defun rst-position (elem seq) "Return position of ELEM in list SEQ or nil. Comparison done with `equal'." ;; Create a closure containing `elem' so the `lambda' always sees our ;; parameter instead of an `elem' which may be in dynamic scope at the time ;; of execution of the `lambda'. (lexical-let ((elem elem)) (rst-position-if (function (lambda (e) (equal elem e))) seq))) ;; FIXME: Embed complicated `defconst's in `eval-when-compile'. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Versions ;; testcover: ok. (defun rst-extract-version (delim-re head-re re tail-re var &optional default) "Extract the version from a variable according to the given regexes. Return the version after regex DELIM-RE and HEAD-RE matching RE and before TAIL-RE and DELIM-RE in VAR or DEFAULT for no match." (if (string-match (concat delim-re head-re "\\(" re "\\)" tail-re delim-re) var) (match-string 1 var) default)) ;; Use CVSHeader to really get information from CVS and not other version ;; control systems. (defconst rst-cvs-header "$CVSHeader: sm/rst_el/rst.el,v 1.326 2012-09-20 21:28:04 stefan Exp $") (defconst rst-cvs-rev (rst-extract-version "\\$" "CVSHeader: \\S + " "[0-9]+\\(?:\\.[0-9]+\\)+" " .*" rst-cvs-header "0.0") "The CVS revision of this file. CVS revision is the development revision.") (defconst rst-cvs-timestamp (rst-extract-version "\\$" "CVSHeader: \\S + \\S + " "[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+" " .*" rst-cvs-header "1970-01-01 00:00:00") "The CVS time stamp of this file.") ;; Use LastChanged... to really get information from SVN. (defconst rst-svn-rev (rst-extract-version "\\$" "LastChangedRevision: " "[0-9]+" " " "$LastChangedRevision: 7515 $") "The SVN revision of this file. SVN revision is the upstream (docutils) revision.") (defconst rst-svn-timestamp (rst-extract-version "\\$" "LastChangedDate: " ".+?+" " " "$LastChangedDate: 2012-09-20 23:28:53 +0200 (Don, 20. Sep 2012) $") "The SVN time stamp of this file.") ;; Maintained by the release process. (defconst rst-official-version (rst-extract-version "%" "OfficialVersion: " "[0-9]+\\(?:\\.[0-9]+\\)+" " " "%OfficialVersion: 1.4.0 %") "Official version of the package.") (defconst rst-official-cvs-rev (rst-extract-version "[%$]" "Revision: " "[0-9]+\\(?:\\.[0-9]+\\)+" " " "$Revision: 7515 $") "CVS revision of this file in the official version.") (defconst rst-version (if (equal rst-official-cvs-rev rst-cvs-rev) rst-official-version (format "%s (development %s [%s])" rst-official-version rst-cvs-rev rst-cvs-timestamp)) "The version string. Starts with the current official version. For developer versions in parentheses follows the development revision and the time stamp.") (defconst rst-package-emacs-version-alist '(("1.0.0" . "24.3") ("1.1.0" . "24.3") ("1.2.0" . "24.3") ("1.2.1" . "24.3") ("1.3.0" . "24.3") ("1.3.1" . "24.3") ("1.4.0" . "24.3") )) (unless (assoc rst-official-version rst-package-emacs-version-alist) (error "Version %s not listed in `rst-package-emacs-version-alist'" rst-version)) (add-to-list 'customize-package-emacs-version-alist (cons 'ReST rst-package-emacs-version-alist)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Initialize customization (defgroup rst nil "Support for reStructuredText documents." :group 'wp :version "23.1" :link '(url-link "http://docutils.sourceforge.net/rst.html")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Facilities for regular expressions used everywhere ;; The trailing numbers in the names give the number of referenceable regex ;; groups contained in the regex. ;; Used to be customizable but really is not customizable but fixed by the reST ;; syntax. (defconst rst-bullets ;; Sorted so they can form a character class when concatenated. '(?- ?* ?+ ?\u2022 ?\u2023 ?\u2043) "List of all possible bullet characters for bulleted lists.") (defconst rst-uri-schemes '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https" "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero" "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais") "Supported URI schemes.") (defconst rst-adornment-chars ;; Sorted so they can form a character class when concatenated. '(?\] ?! ?\" ?# ?$ ?% ?& ?' ?\( ?\) ?* ?+ ?, ?. ?/ ?: ?\; ?< ?= ?> ?? ?@ ?\[ ?\\ ?^ ?_ ?` ?{ ?| ?} ?~ ?-) "Characters which may be used in adornments for sections and transitions.") (defconst rst-max-inline-length 1000 "Maximum length of inline markup to recognize.") (defconst rst-re-alist-def ;; `*-beg' matches * at the beginning of a line. ;; `*-end' matches * at the end of a line. ;; `*-prt' matches a part of *. ;; `*-tag' matches *. ;; `*-sta' matches the start of * which may be followed by respective content. ;; `*-pfx' matches the delimiter left of *. ;; `*-sfx' matches the delimiter right of *. ;; `*-hlp' helper for *. ;; ;; A trailing number says how many referenceable groups are contained. `( ;; Horizontal white space (`hws') (hws-prt "[\t ]") (hws-tag hws-prt "*") ; Optional sequence of horizontal white space. (hws-sta hws-prt "+") ; Mandatory sequence of horizontal white space. ;; Lines (`lin') (lin-beg "^" hws-tag) ; Beginning of a possibly indented line. (lin-end hws-tag "$") ; End of a line with optional trailing white space. (linemp-tag "^" hws-tag "$") ; Empty line with optional white space. ;; Various tags and parts (ell-tag "\\.\\.\\.") ; Ellipsis (bul-tag ,(concat "[" rst-bullets "]")) ; A bullet. (ltr-tag "[a-zA-Z]") ; A letter enumerator tag. (num-prt "[0-9]") ; A number enumerator part. (num-tag num-prt "+") ; A number enumerator tag. (rom-prt "[IVXLCDMivxlcdm]") ; A roman enumerator part. (rom-tag rom-prt "+") ; A roman enumerator tag. (aut-tag "#") ; An automatic enumerator tag. (dcl-tag "::") ; Double colon. ;; Block lead in (`bli') (bli-sfx (:alt hws-sta "$")) ; Suffix of a block lead-in with *optional* ; immediate content. ;; Various starts (bul-sta bul-tag bli-sfx) ; Start of a bulleted item. ;; Explicit markup tag (`exm') (exm-tag "\\.\\.") (exm-sta exm-tag hws-sta) (exm-beg lin-beg exm-sta) ;; Counters in enumerations (`cnt') (cntany-tag (:alt ltr-tag num-tag rom-tag aut-tag)) ; An arbitrary counter. (cntexp-tag (:alt ltr-tag num-tag rom-tag)) ; An arbitrary explicit counter. ;; Enumerator (`enm') (enmany-tag (:alt (:seq cntany-tag "\\.") (:seq "(?" cntany-tag ")"))) ; An arbitrary enumerator. (enmexp-tag (:alt (:seq cntexp-tag "\\.") (:seq "(?" cntexp-tag ")"))) ; An arbitrary explicit ; enumerator. (enmaut-tag (:alt (:seq aut-tag "\\.") (:seq "(?" aut-tag ")"))) ; An automatic enumerator. (enmany-sta enmany-tag bli-sfx) ; An arbitrary enumerator start. (enmexp-sta enmexp-tag bli-sfx) ; An arbitrary explicit enumerator start. (enmexp-beg lin-beg enmexp-sta) ; An arbitrary explicit enumerator start ; at the beginning of a line. ;; Items may be enumerated or bulleted (`itm') (itmany-tag (:alt enmany-tag bul-tag)) ; An arbitrary item tag. (itmany-sta-1 (:grp itmany-tag) bli-sfx) ; An arbitrary item start, group ; is the item tag. (itmany-beg-1 lin-beg itmany-sta-1) ; An arbitrary item start at the ; beginning of a line, group is the ; item tag. ;; Inline markup (`ilm') (ilm-pfx (:alt "^" hws-prt "[-'\"([{<\u2018\u201c\u00ab\u2019/:]")) (ilm-sfx (:alt "$" hws-prt "[]-'\")}>\u2019\u201d\u00bb/:.,;!?\\]")) ;; Inline markup content (`ilc') (ilcsgl-tag "\\S ") ; A single non-white character. (ilcast-prt (:alt "[^*\\]" "\\\\.")) ; Part of non-asterisk content. (ilcbkq-prt (:alt "[^`\\]" "\\\\.")) ; Part of non-backquote content. (ilcbkqdef-prt (:alt "[^`\\\n]" "\\\\.")) ; Part of non-backquote ; definition. (ilcbar-prt (:alt "[^|\\]" "\\\\.")) ; Part of non-vertical-bar content. (ilcbardef-prt (:alt "[^|\\\n]" "\\\\.")) ; Part of non-vertical-bar ; definition. (ilcast-sfx "[^\t *\\]") ; Suffix of non-asterisk content. (ilcbkq-sfx "[^\t `\\]") ; Suffix of non-backquote content. (ilcbar-sfx "[^\t |\\]") ; Suffix of non-vertical-bar content. (ilcrep-hlp ,(format "\\{0,%d\\}" rst-max-inline-length)) ; Repeat count. (ilcast-tag (:alt ilcsgl-tag (:seq ilcsgl-tag ilcast-prt ilcrep-hlp ilcast-sfx))) ; Non-asterisk content. (ilcbkq-tag (:alt ilcsgl-tag (:seq ilcsgl-tag ilcbkq-prt ilcrep-hlp ilcbkq-sfx))) ; Non-backquote content. (ilcbkqdef-tag (:alt ilcsgl-tag (:seq ilcsgl-tag ilcbkqdef-prt ilcrep-hlp ilcbkq-sfx))) ; Non-backquote definition. (ilcbar-tag (:alt ilcsgl-tag (:seq ilcsgl-tag ilcbar-prt ilcrep-hlp ilcbar-sfx))) ; Non-vertical-bar content. (ilcbardef-tag (:alt ilcsgl-tag (:seq ilcsgl-tag ilcbardef-prt ilcrep-hlp ilcbar-sfx))) ; Non-vertical-bar definition. ;; Fields (`fld') (fldnam-prt (:alt "[^:\n]" "\\\\:")) ; Part of a field name. (fldnam-tag fldnam-prt "+") ; A field name. (fld-tag ":" fldnam-tag ":") ; A field marker. ;; Options (`opt') (optsta-tag (:alt "[-+/]" "--")) ; Start of an option. (optnam-tag "\\sw" (:alt "-" "\\sw") "*") ; Name of an option. (optarg-tag (:shy "[ =]\\S +")) ; Option argument. (optsep-tag (:shy "," hws-prt)) ; Separator between options. (opt-tag (:shy optsta-tag optnam-tag optarg-tag "?")) ; A complete option. ;; Footnotes and citations (`fnc') (fncnam-prt "[^\]\n]") ; Part of a footnote or citation name. (fncnam-tag fncnam-prt "+") ; A footnote or citation name. (fnc-tag "\\[" fncnam-tag "]") ; A complete footnote or citation tag. (fncdef-tag-2 (:grp exm-sta) (:grp fnc-tag)) ; A complete footnote or citation definition ; tag. First group is the explicit markup ; start, second group is the footnote / ; citation tag. (fnc-sta-2 fncdef-tag-2 bli-sfx) ; Start of a footnote or citation ; definition. First group is the explicit ; markup start, second group is the ; footnote / citation tag. ;; Substitutions (`sub') (sub-tag "|" ilcbar-tag "|") ; A complete substitution tag. (subdef-tag "|" ilcbardef-tag "|") ; A complete substitution definition ; tag. ;; Symbol (`sym') (sym-prt "[-+.:_]") ; Non-word part of a symbol. (sym-tag (:shy "\\sw+" (:shy sym-prt "\\sw+") "*")) ;; URIs (`uri') (uri-tag (:alt ,@rst-uri-schemes)) ;; Adornment (`ado') (ado-prt "[" ,(concat rst-adornment-chars) "]") (adorep3-hlp "\\{3,\\}") ; There must be at least 3 characters because ; otherwise explicit markup start would be ; recognized. (adorep2-hlp "\\{2,\\}") ; As `adorep3-hlp' but when the first of three ; characters is matched differently. (ado-tag-1-1 (:grp ado-prt) "\\1" adorep2-hlp) ; A complete adornment, group is the first ; adornment character and MUST be the FIRST ; group in the whole expression. (ado-tag-1-2 (:grp ado-prt) "\\2" adorep2-hlp) ; A complete adornment, group is the first ; adornment character and MUST be the ; SECOND group in the whole expression. (ado-beg-2-1 "^" (:grp ado-tag-1-2) lin-end) ; A complete adornment line; first group is the whole ; adornment and MUST be the FIRST group in the whole ; expression; second group is the first adornment ; character. ;; Titles (`ttl') (ttl-tag "\\S *\\w\\S *") ; A title text. (ttl-beg lin-beg ttl-tag) ; A title text at the beginning of a line. ;; Directives and substitution definitions (`dir') (dir-tag-3 (:grp exm-sta) (:grp (:shy subdef-tag hws-sta) "?") (:grp sym-tag dcl-tag)) ; A directive or substitution definition ; tag. First group is explicit markup ; start, second group is a possibly ; empty substitution tag, third group is ; the directive tag including the double ; colon. (dir-sta-3 dir-tag-3 bli-sfx) ; Start of a directive or substitution ; definition. Groups are as in dir-tag-3. ;; Literal block (`lit') (lit-sta-2 (:grp (:alt "[^.\n]" "\\.[^.\n]") ".*") "?" (:grp dcl-tag) "$") ; Start of a literal block. First group is ; any text before the double colon tag which ; may not exist, second group is the double ; colon tag. ;; Comments (`cmt') (cmt-sta-1 (:grp exm-sta) "[^\[|_\n]" (:alt "[^:\n]" (:seq ":" (:alt "[^:\n]" "$"))) "*$") ; Start of a comment block; first group is explicit markup ; start. ;; Paragraphs (`par') (par-tag- (:alt itmany-tag fld-tag opt-tag fncdef-tag-2 dir-tag-3 exm-tag) ) ; Tag at the beginning of a paragraph; there may be groups in ; certain cases. ) "Definition alist of relevant regexes. Each entry consists of the symbol naming the regex and an argument list for `rst-re'.") (defvar rst-re-alist) ; Forward declare to use it in `rst-re'. ;; FIXME: Use `sregex` or `rx` instead of re-inventing the wheel. (rst-testcover-add-compose 'rst-re) ;; testcover: ok. (defun rst-re (&rest args) "Interpret ARGS as regular expressions and return a regex string. Each element of ARGS may be one of the following: A string which is inserted unchanged. A character which is resolved to a quoted regex. A symbol which is resolved to a string using `rst-re-alist-def'. A list with a keyword in the car. Each element of the cdr of such a list is recursively interpreted as ARGS. The results of this interpretation are concatenated according to the keyword. For the keyword `:seq' the results are simply concatenated. For the keyword `:shy' the results are concatenated and surrounded by a shy-group (\"\\(?:...\\)\"). For the keyword `:alt' the results form an alternative (\"\\|\") which is shy-grouped (\"\\(?:...\\)\"). For the keyword `:grp' the results are concatenated and form a referenceable group (\"\\(...\\)\"). After interpretation of ARGS the results are concatenated as for `:seq'." (apply 'concat (mapcar (lambda (re) (cond ((stringp re) re) ((symbolp re) (cadr (assoc re rst-re-alist))) ((characterp re) (regexp-quote (char-to-string re))) ((listp re) (let ((nested (mapcar (lambda (elt) (rst-re elt)) (cdr re)))) (cond ((eq (car re) :seq) (mapconcat 'identity nested "")) ((eq (car re) :shy) (concat "\\(?:" (mapconcat 'identity nested "") "\\)")) ((eq (car re) :grp) (concat "\\(" (mapconcat 'identity nested "") "\\)")) ((eq (car re) :alt) (concat "\\(?:" (mapconcat 'identity nested "\\|") "\\)")) (t (error "Unknown list car: %s" (car re)))))) (t (error "Unknown object type for building regex: %s" re)))) args))) ;; FIXME: Remove circular dependency between `rst-re' and `rst-re-alist'. (with-no-warnings ; Silence byte-compiler about this construction. (defconst rst-re-alist ;; Shadow global value we are just defining so we can construct it step by ;; step. (let (rst-re-alist) (dolist (re rst-re-alist-def rst-re-alist) (setq rst-re-alist (nconc rst-re-alist (list (list (car re) (apply 'rst-re (cdr re)))))))) "Alist mapping symbols from `rst-re-alist-def' to regex strings.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Mode definition ;; testcover: ok. (defun rst-define-key (keymap key def &rest deprecated) "Bind like `define-key' but add deprecated key definitions. KEYMAP, KEY, and DEF are as in `define-key'. DEPRECATED key definitions should be in vector notation. These are defined as well but give an additional message." (define-key keymap key def) (dolist (dep-key deprecated) (define-key keymap dep-key `(lambda () ,(format "Deprecated binding for %s, use \\[%s] instead." def def) (interactive) (call-interactively ',def) (message "[Deprecated use of key %s; use key %s instead]" (key-description (this-command-keys)) (key-description ,key)))))) ;; Key bindings. (defvar rst-mode-map (let ((map (make-sparse-keymap))) ;; \C-c is the general keymap. (rst-define-key map [?\C-c ?\C-h] 'describe-prefix-bindings) ;; ;; Section Adornments ;; ;; The adjustment function that adorns or rotates a section title. (rst-define-key map [?\C-c ?\C-=] 'rst-adjust [?\C-c ?\C-a t]) (rst-define-key map [?\C-=] 'rst-adjust) ; Does not work on the Mac OSX and ; on consoles. ;; \C-c \C-a is the keymap for adornments. (rst-define-key map [?\C-c ?\C-a ?\C-h] 'describe-prefix-bindings) ;; Another binding which works with all types of input. (rst-define-key map [?\C-c ?\C-a ?\C-a] 'rst-adjust) ;; Display the hierarchy of adornments implied by the current document ;; contents. (rst-define-key map [?\C-c ?\C-a ?\C-d] 'rst-display-adornments-hierarchy) ;; Homogenize the adornments in the document. (rst-define-key map [?\C-c ?\C-a ?\C-s] 'rst-straighten-adornments [?\C-c ?\C-s]) ;; ;; Section Movement and Selection ;; ;; Mark the subsection where the cursor is. (rst-define-key map [?\C-\M-h] 'rst-mark-section ;; Same as mark-defun sgml-mark-current-element. [?\C-c ?\C-m]) ;; Move backward/forward between section titles. ;; FIXME: Also bind similar to outline mode. (rst-define-key map [?\C-\M-a] 'rst-backward-section ;; Same as beginning-of-defun. [?\C-c ?\C-n]) (rst-define-key map [?\C-\M-e] 'rst-forward-section ;; Same as end-of-defun. [?\C-c ?\C-p]) ;; ;; Operating on regions ;; ;; \C-c \C-r is the keymap for regions. (rst-define-key map [?\C-c ?\C-r ?\C-h] 'describe-prefix-bindings) ;; Makes region a line-block. (rst-define-key map [?\C-c ?\C-r ?\C-l] 'rst-line-block-region [?\C-c ?\C-d]) ;; Shift region left or right according to tabs. (rst-define-key map [?\C-c ?\C-r tab] 'rst-shift-region [?\C-c ?\C-r t] [?\C-c ?\C-l t]) ;; ;; Operating on lists ;; ;; \C-c \C-l is the keymap for lists. (rst-define-key map [?\C-c ?\C-l ?\C-h] 'describe-prefix-bindings) ;; Makes paragraphs in region as a bullet list. (rst-define-key map [?\C-c ?\C-l ?\C-b] 'rst-bullet-list-region [?\C-c ?\C-b]) ;; Makes paragraphs in region as a enumeration. (rst-define-key map [?\C-c ?\C-l ?\C-e] 'rst-enumerate-region [?\C-c ?\C-e]) ;; Converts bullets to an enumeration. (rst-define-key map [?\C-c ?\C-l ?\C-c] 'rst-convert-bullets-to-enumeration [?\C-c ?\C-v]) ;; Make sure that all the bullets in the region are consistent. (rst-define-key map [?\C-c ?\C-l ?\C-s] 'rst-straighten-bullets-region [?\C-c ?\C-w]) ;; Insert a list item. (rst-define-key map [?\C-c ?\C-l ?\C-i] 'rst-insert-list) ;; ;; Table-of-Contents Features ;; ;; \C-c \C-t is the keymap for table of contents. (rst-define-key map [?\C-c ?\C-t ?\C-h] 'describe-prefix-bindings) ;; Enter a TOC buffer to view and move to a specific section. (rst-define-key map [?\C-c ?\C-t ?\C-t] 'rst-toc) ;; Insert a TOC here. (rst-define-key map [?\C-c ?\C-t ?\C-i] 'rst-toc-insert [?\C-c ?\C-i]) ;; Update the document's TOC (without changing the cursor position). (rst-define-key map [?\C-c ?\C-t ?\C-u] 'rst-toc-update [?\C-c ?\C-u]) ;; Go to the section under the cursor (cursor must be in TOC). (rst-define-key map [?\C-c ?\C-t ?\C-j] 'rst-goto-section [?\C-c ?\C-f]) ;; ;; Converting Documents from Emacs ;; ;; \C-c \C-c is the keymap for compilation. (rst-define-key map [?\C-c ?\C-c ?\C-h] 'describe-prefix-bindings) ;; Run one of two pre-configured toolset commands on the document. (rst-define-key map [?\C-c ?\C-c ?\C-c] 'rst-compile [?\C-c ?1]) (rst-define-key map [?\C-c ?\C-c ?\C-a] 'rst-compile-alt-toolset [?\C-c ?2]) ;; Convert the active region to pseudo-xml using the docutils tools. (rst-define-key map [?\C-c ?\C-c ?\C-x] 'rst-compile-pseudo-region [?\C-c ?3]) ;; Convert the current document to PDF and launch a viewer on the results. (rst-define-key map [?\C-c ?\C-c ?\C-p] 'rst-compile-pdf-preview [?\C-c ?4]) ;; Convert the current document to S5 slides and view in a web browser. (rst-define-key map [?\C-c ?\C-c ?\C-s] 'rst-compile-slides-preview [?\C-c ?5]) map) "Keymap for reStructuredText mode commands. This inherits from Text mode.") ;; Abbrevs. (define-abbrev-table 'rst-mode-abbrev-table (mapcar (lambda (x) (append x '(nil 0 system))) '(("contents" ".. contents::\n..\n ") ("con" ".. contents::\n..\n ") ("cont" "[...]") ("skip" "\n\n[...]\n\n ") ("seq" "\n\n[...]\n\n ") ;; FIXME: Add footnotes, links, and more. )) "Abbrev table used while in `rst-mode'.") ;; Syntax table. (defvar rst-mode-syntax-table (let ((st (copy-syntax-table text-mode-syntax-table))) (modify-syntax-entry ?$ "." st) (modify-syntax-entry ?% "." st) (modify-syntax-entry ?& "." st) (modify-syntax-entry ?' "." st) (modify-syntax-entry ?* "." st) (modify-syntax-entry ?+ "." st) (modify-syntax-entry ?- "." st) (modify-syntax-entry ?/ "." st) (modify-syntax-entry ?< "." st) (modify-syntax-entry ?= "." st) (modify-syntax-entry ?> "." st) (modify-syntax-entry ?\\ "\\" st) (modify-syntax-entry ?_ "." st) (modify-syntax-entry ?| "." st) (modify-syntax-entry ?\u00ab "." st) (modify-syntax-entry ?\u00bb "." st) (modify-syntax-entry ?\u2018 "." st) (modify-syntax-entry ?\u2019 "." st) (modify-syntax-entry ?\u201c "." st) (modify-syntax-entry ?\u201d "." st) st) "Syntax table used while in `rst-mode'.") (defcustom rst-mode-hook nil "Hook run when `rst-mode' is turned on. The hook for `text-mode' is run before this one." :group 'rst :type '(hook)) (rst-testcover-defcustom) ;; Pull in variable definitions silencing byte-compiler. (require 'newcomment) ;; Use rst-mode for *.rst and *.rest files. Many ReStructured-Text files ;; use *.txt, but this is too generic to be set as a default. ;;;###autoload (add-to-list 'auto-mode-alist (purecopy '("\\.re?st\\'" . rst-mode))) ;;;###autoload (define-derived-mode rst-mode text-mode "ReST" "Major mode for editing reStructuredText documents. \\ Turning on `rst-mode' calls the normal hooks `text-mode-hook' and `rst-mode-hook'. This mode also supports font-lock highlighting. \\{rst-mode-map}" :abbrev-table rst-mode-abbrev-table :syntax-table rst-mode-syntax-table :group 'rst ;; Paragraph recognition. (set (make-local-variable 'paragraph-separate) (rst-re '(:alt "\f" lin-end))) (set (make-local-variable 'paragraph-start) (rst-re '(:alt "\f" lin-end (:seq hws-tag par-tag- bli-sfx)))) ;; Indenting and filling. (set (make-local-variable 'indent-line-function) 'rst-indent-line) (set (make-local-variable 'adaptive-fill-mode) t) (set (make-local-variable 'adaptive-fill-regexp) (rst-re 'hws-tag 'par-tag- "?" 'hws-tag)) (set (make-local-variable 'adaptive-fill-function) 'rst-adaptive-fill) (set (make-local-variable 'fill-paragraph-handle-comment) nil) ;; Comments. (set (make-local-variable 'comment-start) ".. ") (set (make-local-variable 'comment-start-skip) (rst-re 'lin-beg 'exm-tag 'bli-sfx)) (set (make-local-variable 'comment-continue) " ") (set (make-local-variable 'comment-multi-line) t) (set (make-local-variable 'comment-use-syntax) nil) ;; reStructuredText has not really a comment ender but nil is not really a ;; permissible value. (set (make-local-variable 'comment-end) "") (set (make-local-variable 'comment-end-skip) nil) ;; Commenting in reStructuredText is very special so use our own set of ;; functions. (set (make-local-variable 'comment-line-break-function) 'rst-comment-line-break) (set (make-local-variable 'comment-indent-function) 'rst-comment-indent) (set (make-local-variable 'comment-insert-comment-function) 'rst-comment-insert-comment) (set (make-local-variable 'comment-region-function) 'rst-comment-region) (set (make-local-variable 'uncomment-region-function) 'rst-uncomment-region) ;; Imenu and which function. ;; FIXME: Check documentation of `which-function' for alternative ways to ;; determine the current function name. (set (make-local-variable 'imenu-create-index-function) 'rst-imenu-create-index) ;; Font lock. (set (make-local-variable 'font-lock-defaults) '(rst-font-lock-keywords t nil nil nil (font-lock-multiline . t) (font-lock-mark-block-function . mark-paragraph))) (add-hook 'font-lock-extend-region-functions 'rst-font-lock-extend-region t) ;; Text after a changed line may need new fontification. (set (make-local-variable 'jit-lock-contextually) t)) ;;;###autoload (define-minor-mode rst-minor-mode "Toggle ReST minor mode. With a prefix argument ARG, enable ReST minor mode if ARG is positive, and disable it otherwise. If called from Lisp, enable the mode if ARG is omitted or nil. When ReST minor mode is enabled, the ReST mode keybindings are installed on top of the major mode bindings. Use this for modes derived from Text mode, like Mail mode." ;; The initial value. nil ;; The indicator for the mode line. " ReST" ;; The minor mode bindings. rst-mode-map :group 'rst) ;; FIXME: can I somehow install these too? ;; :abbrev-table rst-mode-abbrev-table ;; :syntax-table rst-mode-syntax-table ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Section Adornment Adjustment ;; ============================ ;; ;; The following functions implement a smart automatic title sectioning feature. ;; The idea is that with the cursor sitting on a section title, we try to get as ;; much information from context and try to do the best thing automatically. ;; This function can be invoked many times and/or with prefix argument to rotate ;; between the various sectioning adornments. ;; ;; Definitions: the two forms of sectioning define semantically separate section ;; levels. A sectioning ADORNMENT consists in: ;; ;; - a CHARACTER ;; ;; - a STYLE which can be either of 'simple' or 'over-and-under'. ;; ;; - an INDENT (meaningful for the over-and-under style only) which determines ;; how many characters and over-and-under style is hanging outside of the ;; title at the beginning and ending. ;; ;; Here are two examples of adornments (| represents the window border, column ;; 0): ;; ;; | ;; 1. char: '-' e |Some Title ;; style: simple |---------- ;; | ;; 2. char: '=' |============== ;; style: over-and-under | Some Title ;; indent: 2 |============== ;; | ;; ;; Some notes: ;; ;; - The underlining character that is used depends on context. The file is ;; scanned to find other sections and an appropriate character is selected. ;; If the function is invoked on a section that is complete, the character is ;; rotated among the existing section adornments. ;; ;; Note that when rotating the characters, if we come to the end of the ;; hierarchy of adornments, the variable rst-preferred-adornments is ;; consulted to propose a new underline adornment, and if continued, we cycle ;; the adornments all over again. Set this variable to nil if you want to ;; limit the underlining character propositions to the existing adornments in ;; the file. ;; ;; - An underline/overline that is not extended to the column at which it should ;; be hanging is dubbed INCOMPLETE. For example:: ;; ;; |Some Title ;; |------- ;; ;; Examples of default invocation: ;; ;; |Some Title ---> |Some Title ;; | |---------- ;; ;; |Some Title ---> |Some Title ;; |----- |---------- ;; ;; | |------------ ;; | Some Title ---> | Some Title ;; | |------------ ;; ;; In over-and-under style, when alternating the style, a variable is ;; available to select how much default indent to use (it can be zero). Note ;; that if the current section adornment already has an indent, we don't ;; adjust it to the default, we rather use the current indent that is already ;; there for adjustment (unless we cycle, in which case we use the indent ;; that has been found previously). (defgroup rst-adjust nil "Settings for adjustment and cycling of section title adornments." :group 'rst :version "21.1") (define-obsolete-variable-alias 'rst-preferred-decorations 'rst-preferred-adornments "1.0.0") (defcustom rst-preferred-adornments '((?= over-and-under 1) (?= simple 0) (?- simple 0) (?~ simple 0) (?+ simple 0) (?` simple 0) (?# simple 0) (?@ simple 0)) "Preferred hierarchy of section title adornments. A list consisting of lists of the form (CHARACTER STYLE INDENT). CHARACTER is the character used. STYLE is one of the symbols OVER-AND-UNDER or SIMPLE. INDENT is an integer giving the wanted indentation for STYLE OVER-AND-UNDER. CHARACTER and STYLE are always used when a section adornment is described. In other places t instead of a list stands for a transition. This sequence is consulted to offer a new adornment suggestion when we rotate the underlines at the end of the existing hierarchy of characters, or when there is no existing section title in the file. Set this to an empty list to use only the adornment found in the file." :group 'rst-adjust :type `(repeat (group :tag "Adornment specification" (choice :tag "Adornment character" ,@(mapcar (lambda (char) (list 'const :tag (char-to-string char) char)) rst-adornment-chars)) (radio :tag "Adornment type" (const :tag "Overline and underline" over-and-under) (const :tag "Underline only" simple)) (integer :tag "Indentation for overline and underline type" :value 0)))) (rst-testcover-defcustom) (defcustom rst-default-indent 1 "Number of characters to indent the section title. This is used for when toggling adornment styles, when switching from a simple adornment style to a over-and-under adornment style." :group 'rst-adjust :type '(integer)) (rst-testcover-defcustom) (defun rst-compare-adornments (ado1 ado2) "Compare adornments. Return true if both ADO1 and ADO2 adornments are equal, according to restructured text semantics (only the character and the style are compared, the indentation does not matter)." (and (eq (car ado1) (car ado2)) (eq (cadr ado1) (cadr ado2)))) (defun rst-get-adornment-match (hier ado) "Return the index (level) in hierarchy HIER of adornment ADO. This basically just searches for the item using the appropriate comparison and returns the index. Return nil if the item is not found." (let ((cur hier)) (while (and cur (not (rst-compare-adornments (car cur) ado))) (setq cur (cdr cur))) cur)) ;; testcover: FIXME: Test with `rst-preferred-adornments' == nil. Add test ;; `rst-adjust-no-preference'. (defun rst-suggest-new-adornment (allados &optional prev) "Suggest a new, different adornment from all that have been seen. ALLADOS is the set of all adornments, including the line numbers. PREV is the optional previous adornment, in order to suggest a better match." ;; For all the preferred adornments... (let* ( ;; If 'prev' is given, reorder the list to start searching after the ;; match. (fplist (cdr (rst-get-adornment-match rst-preferred-adornments prev))) ;; List of candidates to search. (curpotential (append fplist rst-preferred-adornments))) (while ;; For all the adornments... (let ((cur allados) found) (while (and cur (not found)) (if (rst-compare-adornments (car cur) (car curpotential)) ;; Found it! (setq found (car curpotential)) (setq cur (cdr cur)))) found) (setq curpotential (cdr curpotential))) (copy-sequence (car curpotential)))) (defun rst-delete-entire-line () "Delete the entire current line without using the `kill-ring'." (delete-region (line-beginning-position) (line-beginning-position 2))) (defun rst-update-section (char style &optional indent) "Unconditionally update the style of a section adornment. Do this using the given character CHAR, with STYLE 'simple or 'over-and-under, and with indent INDENT. If the STYLE is 'simple, whitespace before the title is removed (indent is always assumed to be 0). If there are existing overline and/or underline from the existing adornment, they are removed before adding the requested adornment." (end-of-line) (let ((marker (point-marker)) len) ;; Fixup whitespace at the beginning and end of the line. (if (or (null indent) (eq style 'simple)) ;; testcover: ok. (setq indent 0)) (beginning-of-line) (delete-horizontal-space) (insert (make-string indent ? )) (end-of-line) (delete-horizontal-space) ;; Set the current column, we're at the end of the title line. (setq len (+ (current-column) indent)) ;; Remove previous line if it is an adornment. (save-excursion (forward-line -1) ;; testcover: FIXME: Doesn't work when in first line ;; of buffer. (if (and (looking-at (rst-re 'ado-beg-2-1)) ;; Avoid removing the underline of a title right above us. (save-excursion (forward-line -1) (not (looking-at (rst-re 'ttl-beg))))) (rst-delete-entire-line))) ;; Remove following line if it is an adornment. (save-excursion (forward-line +1) ;; testcover: FIXME: Doesn't work when in last line ;; of buffer. (if (looking-at (rst-re 'ado-beg-2-1)) (rst-delete-entire-line)) ;; Add a newline if we're at the end of the buffer, for the subsequence ;; inserting of the underline. (if (= (point) (buffer-end 1)) (newline 1))) ;; Insert overline. (if (eq style 'over-and-under) (save-excursion (beginning-of-line) (open-line 1) (insert (make-string len char)))) ;; Insert underline. (1value ;; Line has been inserted above. (forward-line +1)) (open-line 1) (insert (make-string len char)) (1value ;; Line has been inserted above. (forward-line +1)) (goto-char marker))) (defun rst-classify-adornment (adornment end) "Classify adornment for section titles and transitions. ADORNMENT is the complete adornment string as found in the buffer with optional trailing whitespace. END is the point after the last character of ADORNMENT. Return a list. The first entry is t for a transition or a cons (CHARACTER . STYLE). Check `rst-preferred-adornments' for the meaning of CHARACTER and STYLE. The remaining list forms four match groups as returned by `match-data'. Match group 0 matches the whole construct. Match group 1 matches the overline adornment if present. Match group 2 matches the section title text or the transition. Match group 3 matches the underline adornment. Return nil if no syntactically valid adornment is found." (save-excursion (save-match-data (when (string-match (rst-re 'ado-beg-2-1) adornment) (goto-char end) (let* ((ado-ch (string-to-char (match-string 2 adornment))) (ado-re (rst-re ado-ch 'adorep3-hlp)) (end-pnt (point)) (beg-pnt (progn (1value ;; No lines may be left to move. (forward-line 0)) (point))) (nxt-emp ; Next line nonexistent or empty (save-excursion (or (not (zerop (forward-line 1))) ;; testcover: FIXME: Add test classifying at the end of ;; buffer. (looking-at (rst-re 'lin-end))))) (prv-emp ; Previous line nonexistent or empty (save-excursion (or (not (zerop (forward-line -1))) (looking-at (rst-re 'lin-end))))) (ttl-blw ; Title found below starting here. (save-excursion (and (zerop (forward-line 1)) ;; testcover: FIXME: Add test ;; classifying at the end of ;; buffer. (looking-at (rst-re 'ttl-beg)) (point)))) (ttl-abv ; Title found above starting here. (save-excursion (and (zerop (forward-line -1)) (looking-at (rst-re 'ttl-beg)) (point)))) (und-fnd ; Matching underline found starting here. (save-excursion (and ttl-blw (zerop (forward-line 2)) ;; testcover: FIXME: Add test ;; classifying at the end of ;; buffer. (looking-at (rst-re ado-re 'lin-end)) (point)))) (ovr-fnd ; Matching overline found starting here. (save-excursion (and ttl-abv (zerop (forward-line -2)) (looking-at (rst-re ado-re 'lin-end)) (point)))) key beg-ovr end-ovr beg-txt end-txt beg-und end-und) (cond ((and nxt-emp prv-emp) ;; A transition. (setq key t beg-txt beg-pnt end-txt end-pnt)) ((or und-fnd ovr-fnd) ;; An overline with an underline. (setq key (cons ado-ch 'over-and-under)) (let (;; Prefer overline match over underline match. (und-pnt (if ovr-fnd beg-pnt und-fnd)) (ovr-pnt (if ovr-fnd ovr-fnd beg-pnt)) (txt-pnt (if ovr-fnd ttl-abv ttl-blw))) (goto-char ovr-pnt) (setq beg-ovr (point) end-ovr (line-end-position)) (goto-char txt-pnt) (setq beg-txt (point) end-txt (line-end-position)) (goto-char und-pnt) (setq beg-und (point) end-und (line-end-position)))) (ttl-abv ;; An underline. (setq key (cons ado-ch 'simple) beg-und beg-pnt end-und end-pnt) (goto-char ttl-abv) (setq beg-txt (point) end-txt (line-end-position))) (t ;; Invalid adornment. (setq key nil))) (if key (list key (or beg-ovr beg-txt) (or end-und end-txt) beg-ovr end-ovr beg-txt end-txt beg-und end-und))))))) (defun rst-find-title-line () "Find a section title line around point and return its characteristics. If the point is on an adornment line find the respective title line. If the point is on an empty line check previous or next line whether it is a suitable title line and use it if so. If point is on a suitable title line use it. If no title line is found return nil. Otherwise return as `rst-classify-adornment' does. However, if the title line has no syntactically valid adornment STYLE is nil in the first element. If there is no adornment around the title CHARACTER is also nil and match groups for overline and underline are nil." (save-excursion (1value ;; No lines may be left to move. (forward-line 0)) (let ((orig-pnt (point)) (orig-end (line-end-position))) (cond ((looking-at (rst-re 'ado-beg-2-1)) (let ((char (string-to-char (match-string-no-properties 2))) (r (rst-classify-adornment (match-string-no-properties 0) (match-end 0)))) (cond ((not r) ;; Invalid adornment - check whether this is an incomplete overline. (if (and (zerop (forward-line 1)) (looking-at (rst-re 'ttl-beg))) (list (cons char nil) orig-pnt (line-end-position) orig-pnt orig-end (point) (line-end-position) nil nil))) ((consp (car r)) ;; A section title - not a transition. r)))) ((looking-at (rst-re 'lin-end)) (or (save-excursion (if (and (zerop (forward-line -1)) (looking-at (rst-re 'ttl-beg))) (list (cons nil nil) (point) (line-end-position) nil nil (point) (line-end-position) nil nil))) (save-excursion (if (and (zerop (forward-line 1)) (looking-at (rst-re 'ttl-beg))) (list (cons nil nil) (point) (line-end-position) nil nil (point) (line-end-position) nil nil))))) ((looking-at (rst-re 'ttl-beg)) ;; Try to use the underline. (let ((r (rst-classify-adornment (buffer-substring-no-properties (line-beginning-position 2) (line-end-position 2)) (line-end-position 2)))) (if r r ;; No valid adornment found. (list (cons nil nil) (point) (line-end-position) nil nil (point) (line-end-position) nil nil)))))))) ;; The following function and variables are used to maintain information about ;; current section adornment in a buffer local cache. Thus they can be used for ;; font-locking and manipulation commands. (defvar rst-all-sections nil "All section adornments in the buffer as found by `rst-find-all-adornments'. t when no section adornments were found.") (make-variable-buffer-local 'rst-all-sections) ;; FIXME: If this variable is set to a different value font-locking of section ;; headers is wrong. (defvar rst-section-hierarchy nil "Section hierarchy in the buffer as determined by `rst-get-hierarchy'. t when no section adornments were found. Value depends on `rst-all-sections'.") (make-variable-buffer-local 'rst-section-hierarchy) (rst-testcover-add-1value 'rst-reset-section-caches) (defun rst-reset-section-caches () "Reset all section cache variables. Should be called by interactive functions which deal with sections." (setq rst-all-sections nil rst-section-hierarchy nil)) (defun rst-find-all-adornments () "Return all the section adornments in the current buffer. Return a list of (LINE . ADORNMENT) with ascending LINE where LINE is the line containing the section title. ADORNMENT consists of a (CHARACTER STYLE INDENT) triple as described for `rst-preferred-adornments'. Uses and sets `rst-all-sections'." (unless rst-all-sections (let (positions) ;; Iterate over all the section titles/adornments in the file. (save-excursion (goto-char (point-min)) (while (re-search-forward (rst-re 'ado-beg-2-1) nil t) (let ((ado-data (rst-classify-adornment (match-string-no-properties 0) (point)))) (when (and ado-data (consp (car ado-data))) ; Ignore transitions. (set-match-data (cdr ado-data)) (goto-char (match-beginning 2)) ; Goto the title start. (push (cons (1+ (count-lines (point-min) (point))) (list (caar ado-data) (cdar ado-data) (current-indentation))) positions) (goto-char (match-end 0))))) ; Go beyond the whole thing. (setq positions (nreverse positions)) (setq rst-all-sections (or positions t))))) (if (eq rst-all-sections t) nil rst-all-sections)) (defun rst-infer-hierarchy (adornments) "Build a hierarchy of adornments using the list of given ADORNMENTS. ADORNMENTS is a list of (CHARACTER STYLE INDENT) adornment specifications, in order that they appear in a file, and will infer a hierarchy of section levels by removing adornments that have already been seen in a forward traversal of the adornments, comparing just CHARACTER and STYLE. Similarly returns a list of (CHARACTER STYLE INDENT), where each list element should be unique." (let (hierarchy-alist) (dolist (x adornments) (let ((char (car x)) (style (cadr x))) (unless (assoc (cons char style) hierarchy-alist) (push (cons (cons char style) x) hierarchy-alist)))) (mapcar 'cdr (nreverse hierarchy-alist)))) (defun rst-get-hierarchy (&optional ignore) "Return the hierarchy of section titles in the file. Return a list of adornments that represents the hierarchy of section titles in the file. Each element consists of (CHARACTER STYLE INDENT) as described for `rst-find-all-adornments'. If the line number in IGNORE is specified, a possibly adornment found on that line is not taken into account when building the hierarchy. Uses and sets `rst-section-hierarchy' unless IGNORE is given." (if (and (not ignore) rst-section-hierarchy) (if (eq rst-section-hierarchy t) nil rst-section-hierarchy) (let ((r (rst-infer-hierarchy (mapcar 'cdr (assq-delete-all ignore (rst-find-all-adornments)))))) (setq rst-section-hierarchy (if ignore ;; Clear cache reflecting that a possible update is not ;; reflected. nil (or r t))) r))) (defun rst-get-adornments-around () "Return the adornments around point. Return a list of the previous and next adornments." (let* ((all (rst-find-all-adornments)) (curline (line-number-at-pos)) prev next (cur all)) ;; Search for the adornments around the current line. (while (and cur (< (caar cur) curline)) (setq prev cur cur (cdr cur))) ;; 'cur' is the following adornment. (if (and cur (caar cur)) (setq next (if (= curline (caar cur)) (cdr cur) cur))) (mapcar 'cdar (list prev next)))) (defun rst-adornment-complete-p (ado) "Return true if the adornment ADO around point is complete." ;; Note: we assume that the detection of the overline as being the underline ;; of a preceding title has already been detected, and has been eliminated ;; from the adornment that is given to us. ;; There is some sectioning already present, so check if the current ;; sectioning is complete and correct. (let* ((char (car ado)) (style (cadr ado)) (indent (caddr ado)) (endcol (save-excursion (end-of-line) (current-column)))) (if char (let ((exps (rst-re "^" char (format "\\{%d\\}" (+ endcol indent)) "$"))) (and (save-excursion (forward-line +1) (beginning-of-line) (looking-at exps)) (or (not (eq style 'over-and-under)) (save-excursion (forward-line -1) (beginning-of-line) (looking-at exps)))))))) (defun rst-get-next-adornment (curado hier &optional suggestion reverse-direction) "Get the next adornment for CURADO, in given hierarchy HIER. If suggesting, suggest for new adornment SUGGESTION. REVERSE-DIRECTION is used to reverse the cycling order." (let* ( (char (car curado)) (style (cadr curado)) ;; Build a new list of adornments for the rotation. (rotados (append hier ;; Suggest a new adornment. (list suggestion ;; If nothing to suggest, use first adornment. (car hier)))) ) (or ;; Search for next adornment. (cadr (let ((cur (if reverse-direction rotados (reverse rotados)))) (while (and cur (not (and (eq char (caar cur)) (eq style (cadar cur))))) (setq cur (cdr cur))) cur)) ;; If not found, take the first of all adornments. suggestion))) ;; FIXME: A line "``/`` full" is not accepted as a section title. (defun rst-adjust (pfxarg) "Auto-adjust the adornment around point. Adjust/rotate the section adornment for the section title around point or promote/demote the adornments inside the region, depending on if the region is active. This function is meant to be invoked possibly multiple times, and can vary its behavior with a positive PFXARG (toggle style), or with a negative PFXARG (alternate behavior). This function is a bit of a swiss knife. It is meant to adjust the adornments of a section title in reStructuredText. It tries to deal with all the possible cases gracefully and to do `the right thing' in all cases. See the documentations of `rst-adjust-adornment-work' and `rst-promote-region' for full details. Prefix Arguments ================ The method can take either (but not both) of a. a (non-negative) prefix argument, which means to toggle the adornment style. Invoke with a prefix argument for example; b. a negative numerical argument, which generally inverts the direction of search in the file or hierarchy. Invoke with C-- prefix for example." (interactive "P") (let* (;; Save our original position on the current line. (origpt (point-marker)) (reverse-direction (and pfxarg (< (prefix-numeric-value pfxarg) 0))) (toggle-style (and pfxarg (not reverse-direction)))) (if (use-region-p) ;; Adjust adornments within region. (rst-promote-region (and pfxarg t)) ;; Adjust adornment around point. (rst-adjust-adornment-work toggle-style reverse-direction)) ;; Run the hooks to run after adjusting. (run-hooks 'rst-adjust-hook) ;; Make sure to reset the cursor position properly after we're done. (goto-char origpt))) (defcustom rst-adjust-hook nil "Hooks to be run after running `rst-adjust'." :group 'rst-adjust :type '(hook) :package-version '(rst . "1.1.0")) (rst-testcover-defcustom) (defcustom rst-new-adornment-down nil "Controls level of new adornment for section headers." :group 'rst-adjust :type '(choice (const :tag "Same level as previous one" nil) (const :tag "One level down relative to the previous one" t)) :package-version '(rst . "1.1.0")) (rst-testcover-defcustom) (defun rst-adjust-adornment (pfxarg) "Call `rst-adjust-adornment-work' interactively. Keep this for compatibility for older bindings (are there any?). Argument PFXARG has the same meaning as for `rst-adjust'." (interactive "P") (let* ((reverse-direction (and pfxarg (< (prefix-numeric-value pfxarg) 0))) (toggle-style (and pfxarg (not reverse-direction)))) (rst-adjust-adornment-work toggle-style reverse-direction))) (defun rst-adjust-adornment-work (toggle-style reverse-direction) "Adjust/rotate the section adornment for the section title around point. This function is meant to be invoked possibly multiple times, and can vary its behavior with a true TOGGLE-STYLE argument, or with a REVERSE-DIRECTION argument. General Behavior ================ The next action it takes depends on context around the point, and it is meant to be invoked possibly more than once to rotate among the various possibilities. Basically, this function deals with: - adding a adornment if the title does not have one; - adjusting the length of the underline characters to fit a modified title; - rotating the adornment in the set of already existing sectioning adornments used in the file; - switching between simple and over-and-under styles. You should normally not have to read all the following, just invoke the method and it will do the most obvious thing that you would expect. Adornment Definitions ===================== The adornments consist in 1. a CHARACTER 2. a STYLE which can be either of 'simple' or 'over-and-under'. 3. an INDENT (meaningful for the over-and-under style only) which determines how many characters and over-and-under style is hanging outside of the title at the beginning and ending. See source code for mode details. Detailed Behavior Description ============================= Here are the gory details of the algorithm (it seems quite complicated, but really, it does the most obvious thing in all the particular cases): Before applying the adornment change, the cursor is placed on the closest line that could contain a section title. Case 1: No Adornment -------------------- If the current line has no adornment around it, - search backwards for the last previous adornment, and apply the adornment one level lower to the current line. If there is no defined level below this previous adornment, we suggest the most appropriate of the `rst-preferred-adornments'. If REVERSE-DIRECTION is true, we simply use the previous adornment found directly. - if there is no adornment found in the given direction, we use the first of `rst-preferred-adornments'. TOGGLE-STYLE forces a toggle of the prescribed adornment style. Case 2: Incomplete Adornment ---------------------------- If the current line does have an existing adornment, but the adornment is incomplete, that is, the underline/overline does not extend to exactly the end of the title line (it is either too short or too long), we simply extend the length of the underlines/overlines to fit exactly the section title. If TOGGLE-STYLE we toggle the style of the adornment as well. REVERSE-DIRECTION has no effect in this case. Case 3: Complete Existing Adornment ----------------------------------- If the adornment is complete (i.e. the underline (overline) length is already adjusted to the end of the title line), we search/parse the file to establish the hierarchy of all the adornments (making sure not to include the adornment around point), and we rotate the current title's adornment from within that list (by default, going *down* the hierarchy that is present in the file, i.e. to a lower section level). This is meant to be used potentially multiple times, until the desired adornment is found around the title. If we hit the boundary of the hierarchy, exactly one choice from the list of preferred adornments is suggested/chosen, the first of those adornment that has not been seen in the file yet (and not including the adornment around point), and the next invocation rolls over to the other end of the hierarchy (i.e. it cycles). This allows you to avoid having to set which character to use. If REVERSE-DIRECTION is true, the effect is to change the direction of rotation in the hierarchy of adornments, thus instead going *up* the hierarchy. However, if TOGGLE-STYLE, we do not rotate the adornment, but instead simply toggle the style of the current adornment (this should be the most common way to toggle the style of an existing complete adornment). Point Location ============== The invocation of this function can be carried out anywhere within the section title line, on an existing underline or overline, as well as on an empty line following a section title. This is meant to be as convenient as possible. Indented Sections ================= Indented section titles such as :: My Title -------- are invalid in reStructuredText and thus not recognized by the parser. This code will thus not work in a way that would support indented sections (it would be ambiguous anyway). Joint Sections ============== Section titles that are right next to each other may not be treated well. More work might be needed to support those, and special conditions on the completeness of existing adornments might be required to make it non-ambiguous. For now we assume that the adornments are disjoint, that is, there is at least a single line between the titles/adornment lines." (rst-reset-section-caches) (let ((ttl-fnd (rst-find-title-line)) (orig-pnt (point))) (when ttl-fnd (set-match-data (cdr ttl-fnd)) (goto-char (match-beginning 2)) (let* ((moved (- (line-number-at-pos) (line-number-at-pos orig-pnt))) (char (caar ttl-fnd)) (style (cdar ttl-fnd)) (indent (current-indentation)) (curado (list char style indent)) char-new style-new indent-new) (cond ;;------------------------------------------------------------------- ;; Case 1: No valid adornment ((not style) (let ((prev (car (rst-get-adornments-around))) cur (hier (rst-get-hierarchy))) ;; Advance one level down. (setq cur (if prev (if (or (and rst-new-adornment-down reverse-direction) (and (not rst-new-adornment-down) (not reverse-direction))) prev (or (cadr (rst-get-adornment-match hier prev)) (rst-suggest-new-adornment hier prev))) (copy-sequence (car rst-preferred-adornments)))) ;; Invert the style if requested. (if toggle-style (setcar (cdr cur) (if (eq (cadr cur) 'simple) 'over-and-under 'simple)) ) (setq char-new (car cur) style-new (cadr cur) indent-new (caddr cur)))) ;;------------------------------------------------------------------- ;; Case 2: Incomplete Adornment ((not (rst-adornment-complete-p curado)) ;; Invert the style if requested. (if toggle-style (setq style (if (eq style 'simple) 'over-and-under 'simple))) (setq char-new char style-new style indent-new indent)) ;;------------------------------------------------------------------- ;; Case 3: Complete Existing Adornment (t (if toggle-style ;; Simply switch the style of the current adornment. (setq char-new char style-new (if (eq style 'simple) 'over-and-under 'simple) indent-new rst-default-indent) ;; Else, we rotate, ignoring the adornment around the current ;; line... (let* ((hier (rst-get-hierarchy (line-number-at-pos))) ;; Suggestion, in case we need to come up with something new. (suggestion (rst-suggest-new-adornment hier (car (rst-get-adornments-around)))) (nextado (rst-get-next-adornment curado hier suggestion reverse-direction))) ;; Indent, if present, always overrides the prescribed indent. (setq char-new (car nextado) style-new (cadr nextado) indent-new (caddr nextado)))))) ;; Override indent with present indent! (setq indent-new (if (> indent 0) indent indent-new)) (if (and char-new style-new) (rst-update-section char-new style-new indent-new)) ;; Correct the position of the cursor to more accurately reflect where ;; it was located when the function was invoked. (unless (zerop moved) (forward-line (- moved)) (end-of-line)))))) ;; Maintain an alias for compatibility. (defalias 'rst-adjust-section-title 'rst-adjust) (defun rst-promote-region (demote) "Promote the section titles within the region. With argument DEMOTE or a prefix argument, demote the section titles instead. The algorithm used at the boundaries of the hierarchy is similar to that used by `rst-adjust-adornment-work'." (interactive "P") (rst-reset-section-caches) (let* ((cur (rst-find-all-adornments)) (hier (rst-get-hierarchy)) (suggestion (rst-suggest-new-adornment hier)) (region-begin-line (line-number-at-pos (region-beginning))) (region-end-line (line-number-at-pos (region-end))) marker-list) ;; Skip the markers that come before the region beginning. (while (and cur (< (caar cur) region-begin-line)) (setq cur (cdr cur))) ;; Create a list of markers for all the adornments which are found within ;; the region. (save-excursion (let (line) (while (and cur (< (setq line (caar cur)) region-end-line)) (goto-char (point-min)) (forward-line (1- line)) (push (list (point-marker) (cdar cur)) marker-list) (setq cur (cdr cur)) )) ;; Apply modifications. (dolist (p marker-list) ;; Go to the adornment to promote. (goto-char (car p)) ;; Update the adornment. (apply 'rst-update-section ;; Rotate the next adornment. (rst-get-next-adornment (cadr p) hier suggestion demote)) ;; Clear marker to avoid slowing down the editing after we're done. (set-marker (car p) nil)) (setq deactivate-mark nil)))) (defun rst-display-adornments-hierarchy (&optional adornments) "Display the current file's section title adornments hierarchy. This function expects a list of (CHARACTER STYLE INDENT) triples in ADORNMENTS." (interactive) (rst-reset-section-caches) (if (not adornments) (setq adornments (rst-get-hierarchy))) (with-output-to-temp-buffer "*rest section hierarchy*" (let ((level 1)) (with-current-buffer standard-output (dolist (x adornments) (insert (format "\nSection Level %d" level)) (apply 'rst-update-section x) (goto-char (point-max)) (insert "\n") (incf level)))))) (defun rst-straighten-adornments () "Redo all the adornments in the current buffer. This is done using our preferred set of adornments. This can be used, for example, when using somebody else's copy of a document, in order to adapt it to our preferred style." (interactive) (rst-reset-section-caches) (save-excursion (let (;; Get a list of pairs of (level . marker). (levels-and-markers (mapcar (lambda (ado) (cons (rst-position (cdr ado) (rst-get-hierarchy)) (progn (goto-char (point-min)) (forward-line (1- (car ado))) (point-marker)))) (rst-find-all-adornments)))) (dolist (lm levels-and-markers) ;; Go to the appropriate position. (goto-char (cdr lm)) ;; Apply the new style. (apply 'rst-update-section (nth (car lm) rst-preferred-adornments)) ;; Reset the marker to avoid slowing down editing until it gets GC'ed. (set-marker (cdr lm) nil))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Insert list items ;; ================= ;================================================= ; Borrowed from a2r.el (version 1.3), by Lawrence Mitchell . ; I needed to make some tiny changes to the functions, so I put it here. ; -- Wei-Wei Guo (defconst rst-arabic-to-roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD") (100 . "C") (90 . "XC") (50 . "L") (40 . "XL") (10 . "X") (9 . "IX") (5 . "V") (4 . "IV") (1 . "I")) "List of maps between Arabic numbers and their Roman numeral equivalents.") (defun rst-arabic-to-roman (num &optional arg) "Convert Arabic number NUM to its Roman numeral representation. Obviously, NUM must be greater than zero. Don't blame me, blame the Romans, I mean \"what have the Romans ever _done_ for /us/?\" (with apologies to Monty Python). If optional prefix ARG is non-nil, insert in current buffer." (let ((map rst-arabic-to-roman) res) (while (and map (> num 0)) (if (or (= num (caar map)) (> num (caar map))) (setq res (concat res (cdar map)) num (- num (caar map))) (setq map (cdr map)))) res)) (defun rst-roman-to-arabic (string &optional arg) "Convert STRING of Roman numerals to an Arabic number. If STRING contains a letter which isn't a valid Roman numeral, the rest of the string from that point onwards is ignored. Hence: MMD == 2500 and MMDFLXXVI == 2500. If optional ARG is non-nil, insert in current buffer." (let ((res 0) (map rst-arabic-to-roman)) (while map (if (string-match (concat "^" (cdar map)) string) (setq res (+ res (caar map)) string (replace-match "" nil t string)) (setq map (cdr map)))) res)) ;================================================= (defun rst-find-pfx-in-region (beg end pfx-re) "Find all the positions of prefixes in region between BEG and END. This is used to find bullets and enumerated list items. PFX-RE is a regular expression for matching the lines after indentation with items. Returns a list of cons cells consisting of the point and the column of the point." (let ((pfx ())) (save-excursion (goto-char beg) (while (< (point) end) (back-to-indentation) (when (and (looking-at pfx-re) ; pfx found and... (let ((pfx-col (current-column))) (save-excursion (forward-line -1) ; ...previous line is... (back-to-indentation) (or (looking-at (rst-re 'lin-end)) ; ...empty, (> (current-column) pfx-col) ; ...deeper level, or (and (= (current-column) pfx-col) (looking-at pfx-re)))))) ; ...pfx at same level. (push (cons (point) (current-column)) pfx)) (forward-line 1))) (nreverse pfx))) (defun rst-insert-list-pos (newitem) "Arrange relative position of a newly inserted list item of style NEWITEM. Adding a new list might consider three situations: (a) Current line is a blank line. (b) Previous line is a blank line. (c) Following line is a blank line. When (a) and (b), just add the new list at current line. when (a) and not (b), a blank line is added before adding the new list. When not (a), first forward point to the end of the line, and add two blank lines, then add the new list. Other situations are just ignored and left to users themselves." (if (save-excursion (beginning-of-line) (looking-at (rst-re 'lin-end))) (if (save-excursion (forward-line -1) (looking-at (rst-re 'lin-end))) (insert newitem " ") (insert "\n" newitem " ")) (end-of-line) (insert "\n\n" newitem " "))) ;; FIXME: Isn't this a `defconst'? (defvar rst-initial-enums (let (vals) (dolist (fmt '("%s." "(%s)" "%s)")) (dolist (c '("1" "a" "A" "I" "i")) (push (format fmt c) vals))) (cons "#." (nreverse vals))) "List of initial enumerations.") ;; FIXME: Isn't this a `defconst'? (defvar rst-initial-items (append (mapcar 'char-to-string rst-bullets) rst-initial-enums) "List of initial items. It's collection of bullets and enumerations.") (defun rst-insert-list-new-item () "Insert a new list item. User is asked to select the item style first, for example (a), i), +. Use TAB for completion and choices. If user selects bullets or #, it's just added with position arranged by `rst-insert-list-pos'. If user selects enumerations, a further prompt is given. User need to input a starting item, for example 'e' for 'A)' style. The position is also arranged by `rst-insert-list-pos'." (interactive) ;; FIXME: Make this comply to `interactive' standards. (let* ((itemstyle (completing-read "Select preferred item style [#.]: " rst-initial-items nil t nil nil "#.")) (cnt (if (string-match (rst-re 'cntexp-tag) itemstyle) (match-string 0 itemstyle))) (no (save-match-data ;; FIXME: Make this comply to `interactive' standards. (cond ((equal cnt "a") (let ((itemno (read-string "Give starting value [a]: " nil nil "a"))) (downcase (substring itemno 0 1)))) ((equal cnt "A") (let ((itemno (read-string "Give starting value [A]: " nil nil "A"))) (upcase (substring itemno 0 1)))) ((equal cnt "I") (let ((itemno (read-number "Give starting value [1]: " 1))) (rst-arabic-to-roman itemno))) ((equal cnt "i") (let ((itemno (read-number "Give starting value [1]: " 1))) (downcase (rst-arabic-to-roman itemno)))) ((equal cnt "1") (let ((itemno (read-number "Give starting value [1]: " 1))) (number-to-string itemno))))))) (if no (setq itemstyle (replace-match no t t itemstyle))) (rst-insert-list-pos itemstyle))) (defcustom rst-preferred-bullets '(?* ?- ?+) "List of favorite bullets." :group 'rst :type `(repeat (choice ,@(mapcar (lambda (char) (list 'const :tag (char-to-string char) char)) rst-bullets))) :package-version '(rst . "1.1.0")) (rst-testcover-defcustom) (defun rst-insert-list-continue (curitem prefer-roman) "Insert a list item with list start CURITEM including its indentation level. If PREFER-ROMAN roman numbering is preferred over using letters." (end-of-line) (insert "\n" ; FIXME: Separating lines must be possible. (cond ((string-match (rst-re '(:alt enmaut-tag bul-tag)) curitem) curitem) ((string-match (rst-re 'num-tag) curitem) (replace-match (number-to-string (1+ (string-to-number (match-string 0 curitem)))) nil nil curitem)) ((and (string-match (rst-re 'rom-tag) curitem) (save-match-data (if (string-match (rst-re 'ltr-tag) curitem) ; Also a letter tag. (save-excursion ;; FIXME: Assumes one line list items without separating ;; empty lines. (if (and (zerop (forward-line -1)) (looking-at (rst-re 'enmexp-beg))) (string-match (rst-re 'rom-tag) (match-string 0)) ; Previous was a roman tag. prefer-roman)) ; Don't know - use flag. t))) ; Not a letter tag. (replace-match (let* ((old (match-string 0 curitem)) (new (save-match-data (rst-arabic-to-roman (1+ (rst-roman-to-arabic (upcase old))))))) (if (equal old (upcase old)) (upcase new) (downcase new))) t nil curitem)) ((string-match (rst-re 'ltr-tag) curitem) (replace-match (char-to-string (1+ (string-to-char (match-string 0 curitem)))) nil nil curitem))))) (defun rst-insert-list (&optional prefer-roman) "Insert a list item at the current point. The command can insert a new list or a continuing list. When it is called at a non-list line, it will promote to insert new list. When it is called at a list line, it will insert a list with the same list style. 1. When inserting a new list: User is asked to select the item style first, for example (a), i), +. Use TAB for completion and choices. (a) If user selects bullets or #, it's just added. (b) If user selects enumerations, a further prompt is given. User needs to input a starting item, for example 'e' for 'A)' style. The position of the new list is arranged according to whether or not the current line and the previous line are blank lines. 2. When continuing a list, one thing need to be noticed: List style alphabetical list, such as 'a.', and roman numerical list, such as 'i.', have some overlapping items, for example 'v.' The function can deal with the problem elegantly in most situations. But when those overlapped list are preceded by a blank line, it is hard to determine which type to use automatically. The function uses alphabetical list by default. If you want roman numerical list, just use a prefix to set PREFER-ROMAN." (interactive "P") (beginning-of-line) (if (looking-at (rst-re 'itmany-beg-1)) (rst-insert-list-continue (match-string 0) prefer-roman) (rst-insert-list-new-item))) (defun rst-straighten-bullets-region (beg end) "Make all the bulleted list items in the region consistent. The region is specified between BEG and END. You can use this after you have merged multiple bulleted lists to make them use the same/correct/consistent bullet characters. See variable `rst-preferred-bullets' for the list of bullets to adjust. If bullets are found on levels beyond the `rst-preferred-bullets' list, they are not modified." (interactive "r") (let ((bullets (rst-find-pfx-in-region beg end (rst-re 'bul-sta))) (levtable (make-hash-table :size 4))) ;; Create a map of levels to list of positions. (dolist (x bullets) (let ((key (cdr x))) (puthash key (append (gethash key levtable (list)) (list (car x))) levtable))) ;; Sort this map and create a new map of prefix char and list of positions. (let ((poslist ())) ; List of (indent . positions). (maphash (lambda (x y) (push (cons x y) poslist)) levtable) (let ((bullets rst-preferred-bullets)) (dolist (x (sort poslist 'car-less-than-car)) (when bullets ;; Apply the characters. (dolist (pos (cdr x)) (goto-char pos) (delete-char 1) (insert (string (car bullets)))) (setq bullets (cdr bullets)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Table of contents ;; ================= ;; FIXME: Return value should be a `defstruct'. (defun rst-section-tree () "Return the hierarchical tree of section titles. A tree entry looks like ((TITLE MARKER) CHILD...). TITLE is the stripped text of the section title. MARKER is a marker for the beginning of the title text. For the top node or a missing section level node TITLE is nil and MARKER points to the title text of the first child. Each CHILD is another tree entry. The CHILD list may be empty." (let ((hier (rst-get-hierarchy)) (ch-sty2level (make-hash-table :test 'equal :size 10)) lev-ttl-mrk-l) (let ((lev 0)) (dolist (ado hier) ;; Compare just the character and indent in the hash table. (puthash (cons (car ado) (cadr ado)) lev ch-sty2level) (incf lev))) ;; Create a list that contains (LEVEL TITLE MARKER) for each adornment. (save-excursion (setq lev-ttl-mrk-l (mapcar (lambda (ado) (goto-char (point-min)) (1value ;; This should really succeed. (forward-line (1- (car ado)))) (list (gethash (cons (cadr ado) (caddr ado)) ch-sty2level) ;; Get title. (save-excursion (if (re-search-forward (rst-re "\\S .*\\S ") (line-end-position) t) (buffer-substring-no-properties (match-beginning 0) (match-end 0)) "")) (point-marker))) (rst-find-all-adornments)))) (cdr (rst-section-tree-rec lev-ttl-mrk-l -1)))) ;; FIXME: Return value should be a `defstruct'. (defun rst-section-tree-rec (remaining lev) "Process the first entry of REMAINING expected to be on level LEV. REMAINING is the remaining list of adornments consisting of (LEVEL TITLE MARKER) entries. Return (UNPROCESSED (TITLE MARKER) CHILD...) for the first entry of REMAINING where TITLE is nil if the expected level is not matched. UNPROCESSED is the list of still unprocessed entries. Each CHILD is a child of this entry in the same format but without UNPROCESSED." (let ((cur (car remaining)) (unprocessed remaining) ttl-mrk children) ;; If the current adornment matches expected level. (when (and cur (= (car cur) lev)) ;; Consume the current entry and create the current node with it. (setq unprocessed (cdr remaining)) (setq ttl-mrk (cdr cur))) ;; Build the child nodes as long as they have deeper level. (while (and unprocessed (> (caar unprocessed) lev)) (let ((rem-children (rst-section-tree-rec unprocessed (1+ lev)))) (setq children (cons (cdr rem-children) children)) (setq unprocessed (car rem-children)))) (setq children (reverse children)) (cons unprocessed (cons (or ttl-mrk ;; Node on this level missing - use nil as text and the ;; marker of the first child. (cons nil (cdaar children))) children)))) (defun rst-section-tree-point (tree &optional point) "Return section containing POINT by returning the closest node in TREE. TREE is a section tree as returned by `rst-section-tree' consisting of (NODE CHILD...) entries. POINT defaults to the current point. A NODE must have the structure (IGNORED MARKER ...). Return (PATH NODE CHILD...). NODE is the node where POINT is in if any. PATH is a list of nodes from the top of the tree down to and including NODE. List of CHILD are the children of NODE if any." (setq point (or point (point))) (let ((cur (car tree)) (children (cdr tree))) ;; Point behind current node? (if (and (cadr cur) (>= point (cadr cur))) ;; Iterate all the children, looking for one that might contain the ;; current section. (let (found) (while (and children (>= point (cadaar children))) (setq found children children (cdr children))) (if found ;; Found section containing point in children. (let ((sub (rst-section-tree-point (car found) point))) ;; Extend path with current node and return NODE CHILD... from ;; sub. (cons (cons cur (car sub)) (cdr sub))) ;; Point in this section: Start a new path with current node and ;; return current NODE CHILD... (cons (list cur) tree))) ;; Current node behind point: start a new path with current node and ;; no NODE CHILD... (list (list cur))))) (defgroup rst-toc nil "Settings for reStructuredText table of contents." :group 'rst :version "21.1") (defcustom rst-toc-indent 2 "Indentation for table-of-contents display. Also used for formatting insertion, when numbering is disabled." :group 'rst-toc) (rst-testcover-defcustom) (defcustom rst-toc-insert-style 'fixed "Insertion style for table-of-contents. Set this to one of the following values to determine numbering and indentation style: - plain: no numbering (fixed indentation) - fixed: numbering, but fixed indentation - aligned: numbering, titles aligned under each other - listed: numbering, with dashes like list items (EXPERIMENTAL)" :group 'rst-toc) (rst-testcover-defcustom) (defcustom rst-toc-insert-number-separator " " "Separator that goes between the TOC number and the title." :group 'rst-toc) (rst-testcover-defcustom) ;; This is used to avoid having to change the user's mode. (defvar rst-toc-insert-click-keymap (let ((map (make-sparse-keymap))) (define-key map [mouse-1] 'rst-toc-mode-mouse-goto) map) "(Internal) What happens when you click on propertized text in the TOC.") (defcustom rst-toc-insert-max-level nil "If non-nil, maximum depth of the inserted TOC." :group 'rst-toc) (rst-testcover-defcustom) (defun rst-toc-insert (&optional pfxarg) "Insert a simple text rendering of the table of contents. By default the top level is ignored if there is only one, because we assume that the document will have a single title. If a numeric prefix argument PFXARG is given, insert the TOC up to the specified level. The TOC is inserted indented at the current column." (interactive "P") (rst-reset-section-caches) (let* (;; Check maximum level override. (rst-toc-insert-max-level (if (and (integerp pfxarg) (> (prefix-numeric-value pfxarg) 0)) (prefix-numeric-value pfxarg) rst-toc-insert-max-level)) ;; Get the section tree for the current cursor point. (sectree-pair (rst-section-tree-point (rst-section-tree))) ;; Figure out initial indent. (initial-indent (make-string (current-column) ? )) (init-point (point))) (when (cddr sectree-pair) (rst-toc-insert-node (cdr sectree-pair) 0 initial-indent "") ;; Fixup for the first line. (delete-region init-point (+ init-point (length initial-indent))) ;; Delete the last newline added. (delete-char -1)))) (defun rst-toc-insert-node (node level indent pfx) "Insert tree node NODE in table-of-contents. Recursive function that does printing of the inserted toc. LEVEL is the depth level of the sections in the tree. INDENT is the indentation string. PFX is the prefix numbering, that includes the alignment necessary for all the children of level to align." ;; Note: we do child numbering from the parent, so we start number the ;; children one level before we print them. (let ((do-print (> level 0)) (count 1)) (when do-print (insert indent) (let ((b (point))) (unless (equal rst-toc-insert-style 'plain) (insert pfx rst-toc-insert-number-separator)) (insert (or (caar node) "[missing node]")) ;; Add properties to the text, even though in normal text mode it ;; won't be doing anything for now. Not sure that I want to change ;; mode stuff. At least the highlighting gives the idea that this ;; is generated automatically. (put-text-property b (point) 'mouse-face 'highlight) (put-text-property b (point) 'rst-toc-target (cadar node)) (put-text-property b (point) 'keymap rst-toc-insert-click-keymap)) (insert "\n") ;; Prepare indent for children. (setq indent (cond ((eq rst-toc-insert-style 'plain) (concat indent (make-string rst-toc-indent ? ))) ((eq rst-toc-insert-style 'fixed) (concat indent (make-string rst-toc-indent ? ))) ((eq rst-toc-insert-style 'aligned) (concat indent (make-string (+ (length pfx) 2) ? ))) ((eq rst-toc-insert-style 'listed) (concat (substring indent 0 -3) (concat (make-string (+ (length pfx) 2) ? ) " - ")))))) (if (or (eq rst-toc-insert-max-level nil) (< level rst-toc-insert-max-level)) (let ((do-child-numbering (>= level 0)) fmt) (if do-child-numbering (progn ;; Add a separating dot if there is already a prefix. (when (> (length pfx) 0) (string-match (rst-re "[ \t\n]*\\'") pfx) (setq pfx (concat (replace-match "" t t pfx) "."))) ;; Calculate the amount of space that the prefix will require ;; for the numbers. (if (cdr node) (setq fmt (format "%%-%dd" (1+ (floor (log10 (length (cdr node)))))))))) (dolist (child (cdr node)) (rst-toc-insert-node child (1+ level) indent (if do-child-numbering (concat pfx (format fmt count)) pfx)) (incf count)))))) (defun rst-toc-update () "Automatically find the contents section of a document and update. Updates the inserted TOC if present. You can use this in your file-write hook to always make it up-to-date automatically." (interactive) (save-excursion ;; Find and delete an existing comment after the first contents directive. ;; Delete that region. (goto-char (point-min)) ;; We look for the following and the following only (in other words, if your ;; syntax differs, this won't work.). ;; ;; .. contents:: [...anything here...] ;; [:field: value]... ;; .. ;; XXXXXXXX ;; XXXXXXXX ;; [more lines] (let ((beg (re-search-forward (rst-re "^" 'exm-sta "contents" 'dcl-tag ".*\n" "\\(?:" 'hws-sta 'fld-tag ".*\n\\)*" 'exm-tag) nil t)) last-real) (when beg ;; Look for the first line that starts at the first column. (forward-line 1) (while (and (< (point) (point-max)) (or (if (looking-at (rst-re 'hws-sta "\\S ")) ; indented content. (setq last-real (point))) (looking-at (rst-re 'lin-end)))) ; empty line. (forward-line 1)) (if last-real (progn (goto-char last-real) (end-of-line) (delete-region beg (point))) (goto-char beg)) (insert "\n ") (rst-toc-insert)))) ;; Note: always return nil, because this may be used as a hook. nil) ;; Note: we cannot bind the TOC update on file write because it messes with ;; undo. If we disable undo, since it adds and removes characters, the ;; positions in the undo list are not making sense anymore. Dunno what to do ;; with this, it would be nice to update when saving. ;; ;; (add-hook 'write-contents-hooks 'rst-toc-update-fun) ;; (defun rst-toc-update-fun () ;; ;; Disable undo for the write file hook. ;; (let ((buffer-undo-list t)) (rst-toc-update) )) (defalias 'rst-toc-insert-update 'rst-toc-update) ; backwards compat. ;;------------------------------------------------------------------------------ (defun rst-toc-node (node level) "Recursive function that does insert NODE at LEVEL in the table-of-contents." (if (> level 0) (let ((b (point))) ;; Insert line text. (insert (make-string (* rst-toc-indent (1- level)) ? )) (insert (or (caar node) "[missing node]")) ;; Highlight lines. (put-text-property b (point) 'mouse-face 'highlight) ;; Add link on lines. (put-text-property b (point) 'rst-toc-target (cadar node)) (insert "\n"))) (dolist (child (cdr node)) (rst-toc-node child (1+ level)))) (defun rst-toc-count-lines (node target-node) "Count the number of lines from NODE to the TARGET-NODE node. This recursive function returns a cons of the number of additional lines that have been counted for its node and children, and t if the node has been found." (let ((count 1) found) (if (eq node target-node) (setq found t) (let ((child (cdr node))) (while (and child (not found)) (let ((cl (rst-toc-count-lines (car child) target-node))) (setq count (+ count (car cl)) found (cdr cl) child (cdr child)))))) (cons count found))) (defvar rst-toc-buffer-name "*Table of Contents*" "Name of the Table of Contents buffer.") (defvar rst-toc-return-wincfg nil "Window configuration to which to return when leaving the TOC.") (defun rst-toc () "Display a table-of-contents. Finds all the section titles and their adornments in the file, and displays a hierarchically-organized list of the titles, which is essentially a table-of-contents of the document. The Emacs buffer can be navigated, and selecting a section brings the cursor in that section." (interactive) (rst-reset-section-caches) (let* ((curbuf (list (current-window-configuration) (point-marker))) (sectree (rst-section-tree)) (our-node (cdr (rst-section-tree-point sectree))) line ;; Create a temporary buffer. (buf (get-buffer-create rst-toc-buffer-name))) (with-current-buffer buf (let ((inhibit-read-only t)) (rst-toc-mode) (delete-region (point-min) (point-max)) (insert (format "Table of Contents: %s\n" (or (caar sectree) ""))) (put-text-property (point-min) (point) 'face (list '(background-color . "gray"))) (rst-toc-node sectree 0) ;; Count the lines to our found node. (let ((linefound (rst-toc-count-lines sectree our-node))) (setq line (if (cdr linefound) (car linefound) 0))))) (display-buffer buf) (pop-to-buffer buf) ;; Save the buffer to return to. (set (make-local-variable 'rst-toc-return-wincfg) curbuf) ;; Move the cursor near the right section in the TOC. (goto-char (point-min)) (forward-line (1- line)))) (defun rst-toc-mode-find-section () "Get the section from text property at point." (let ((pos (get-text-property (point) 'rst-toc-target))) (unless pos (error "No section on this line")) (unless (buffer-live-p (marker-buffer pos)) (error "Buffer for this section was killed")) pos)) ;; FIXME: Cursor before or behind the list must be handled properly; before the ;; list should jump to the top and behind the list to the last normal ;; paragraph. (defun rst-goto-section (&optional kill) "Go to the section the current line describes. If KILL a toc buffer is destroyed." (interactive) (let ((pos (rst-toc-mode-find-section))) (when kill ;; FIXME: This should rather go to `rst-toc-mode-goto-section'. (set-window-configuration (car rst-toc-return-wincfg)) (kill-buffer (get-buffer rst-toc-buffer-name))) (pop-to-buffer (marker-buffer pos)) (goto-char pos) ;; FIXME: make the recentering conditional on scroll. (recenter 5))) (defun rst-toc-mode-goto-section () "Go to the section the current line describes and kill the TOC buffer." (interactive) (rst-goto-section t)) (defun rst-toc-mode-mouse-goto (event) "In `rst-toc' mode, go to the occurrence whose line you click on. EVENT is the input event." (interactive "e") (let ((pos (with-current-buffer (window-buffer (posn-window (event-end event))) (save-excursion (goto-char (posn-point (event-end event))) (rst-toc-mode-find-section))))) (pop-to-buffer (marker-buffer pos)) (goto-char pos) (recenter 5))) (defun rst-toc-mode-mouse-goto-kill (event) "Same as `rst-toc-mode-mouse-goto', but kill TOC buffer as well. EVENT is the input event." (interactive "e") (call-interactively 'rst-toc-mode-mouse-goto event) (kill-buffer (get-buffer rst-toc-buffer-name))) (defun rst-toc-quit-window () "Leave the current TOC buffer." (interactive) (let ((retbuf rst-toc-return-wincfg)) (set-window-configuration (car retbuf)) (goto-char (cadr retbuf)))) (defvar rst-toc-mode-map (let ((map (make-sparse-keymap))) (define-key map [mouse-1] 'rst-toc-mode-mouse-goto-kill) (define-key map [mouse-2] 'rst-toc-mode-mouse-goto) (define-key map "\C-m" 'rst-toc-mode-goto-section) (define-key map "f" 'rst-toc-mode-goto-section) (define-key map "q" 'rst-toc-quit-window) (define-key map "z" 'kill-this-buffer) map) "Keymap for `rst-toc-mode'.") (put 'rst-toc-mode 'mode-class 'special) ;; Could inherit from the new `special-mode'. (define-derived-mode rst-toc-mode nil "ReST-TOC" "Major mode for output from \\[rst-toc], the table-of-contents for the document." (setq buffer-read-only t)) ;; Note: use occur-mode (replace.el) as a good example to complete missing ;; features. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Section movement commands ;; ========================= (defun rst-forward-section (&optional offset) "Skip to the next reStructuredText section title. OFFSET specifies how many titles to skip. Use a negative OFFSET to move backwards in the file (default is to use 1)." (interactive) (rst-reset-section-caches) (let* (;; Default value for offset. (offset (or offset 1)) ;; Get all the adornments in the file, with their line numbers. (allados (rst-find-all-adornments)) ;; Get the current line. (curline (line-number-at-pos)) (cur allados) (idx 0)) ;; Find the index of the "next" adornment w.r.t. to the current line. (while (and cur (< (caar cur) curline)) (setq cur (cdr cur)) (incf idx)) ;; 'cur' is the adornment on or following the current line. (if (and (> offset 0) cur (= (caar cur) curline)) (incf idx)) ;; Find the final index. (setq idx (+ idx (if (> offset 0) (- offset 1) offset))) (setq cur (nth idx allados)) ;; If the index is positive, goto the line, otherwise go to the buffer ;; boundaries. (if (and cur (>= idx 0)) (progn (goto-char (point-min)) (forward-line (1- (car cur)))) (if (> offset 0) (goto-char (point-max)) (goto-char (point-min)))))) (defun rst-backward-section () "Like `rst-forward-section', except move back one title." (interactive) (rst-forward-section -1)) ;; FIXME: What is `allow-extend' for? (defun rst-mark-section (&optional count allow-extend) "Select COUNT sections around point. Mark following sections for positive COUNT or preceding sections for negative COUNT." ;; Cloned from mark-paragraph. (interactive "p\np") (unless count (setq count 1)) (when (zerop count) (error "Cannot mark zero sections")) (cond ((and allow-extend (or (and (eq last-command this-command) (mark t)) (use-region-p))) (set-mark (save-excursion (goto-char (mark)) (rst-forward-section count) (point)))) (t (rst-forward-section count) (push-mark nil t t) (rst-forward-section (- count))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Functions to work on item lists (e.g. indent/dedent, enumerate), which are ;; always 2 or 3 characters apart horizontally with rest. (defun rst-find-leftmost-column (beg end) "Return the leftmost column in region BEG to END." (let (mincol) (save-excursion (goto-char beg) (while (< (point) end) (back-to-indentation) (unless (looking-at (rst-re 'lin-end)) (setq mincol (if mincol (min mincol (current-column)) (current-column)))) (forward-line 1))) mincol)) ;; FIXME: This definition is old and deprecated. We need to move to the newer ;; version below. (defmacro rst-iterate-leftmost-paragraphs (beg end first-only body-consequent body-alternative) ;; FIXME: The following comment is pretty useless. "Call FUN at the beginning of each line, with an argument that specifies whether we are at the first line of a paragraph that starts at the leftmost column of the given region BEG and END. Set FIRST-ONLY to true if you want to callback on the first line of each paragraph only." `(save-excursion (let ((leftcol (rst-find-leftmost-column ,beg ,end)) (endm (copy-marker ,end))) (do* (;; Iterate lines. (l (progn (goto-char ,beg) (back-to-indentation)) (progn (forward-line 1) (back-to-indentation))) (previous nil valid) (curcol (current-column) (current-column)) (valid (and (= curcol leftcol) (not (looking-at (rst-re 'lin-end)))) (and (= curcol leftcol) (not (looking-at (rst-re 'lin-end)))))) ((>= (point) endm)) (if (if ,first-only (and valid (not previous)) valid) ,body-consequent ,body-alternative))))) ;; FIXME: This needs to be refactored. Probably this is simply a function ;; applying BODY rather than a macro. (defmacro rst-iterate-leftmost-paragraphs-2 (spec &rest body) "Evaluate BODY for each line in region defined by BEG END. LEFTMOST is set to true if the line is one of the leftmost of the entire paragraph. PARABEGIN is set to true if the line is the first of a paragraph." (declare (indent 1) (debug (sexp body))) (destructuring-bind (beg end parabegin leftmost isleftmost isempty) spec `(save-excursion (let ((,leftmost (rst-find-leftmost-column ,beg ,end)) (endm (copy-marker ,end))) (do* (;; Iterate lines. (l (progn (goto-char ,beg) (back-to-indentation)) (progn (forward-line 1) (back-to-indentation))) (empty-line-previous nil ,isempty) (,isempty (looking-at (rst-re 'lin-end)) (looking-at (rst-re 'lin-end))) (,parabegin (not ,isempty) (and empty-line-previous (not ,isempty))) (,isleftmost (and (not ,isempty) (= (current-column) ,leftmost)) (and (not ,isempty) (= (current-column) ,leftmost)))) ((>= (point) endm)) (progn ,@body)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Indentation ;; FIXME: At the moment only block comments with leading empty comment line are ;; supported. Comment lines with leading comment markup should be also ;; supported. May be a customizable option could control which style to ;; prefer. (defgroup rst-indent nil "Settings for indentation in reStructuredText. In reStructuredText indentation points are usually determined by preceding lines. Sometimes the syntax allows arbitrary indentation points such as where to start the first line following a directive. These indentation widths can be customized here." :group 'rst :package-version '(rst . "1.1.0")) (define-obsolete-variable-alias 'rst-shift-basic-offset 'rst-indent-width "1.0.0") (defcustom rst-indent-width 2 "Indentation when there is no more indentation point given." :group 'rst-indent :type '(integer)) (rst-testcover-defcustom) (defcustom rst-indent-field 3 "Indentation for first line after a field or 0 to always indent for content." :group 'rst-indent :type '(integer)) (rst-testcover-defcustom) (defcustom rst-indent-literal-normal 3 "Default indentation for literal block after a markup on an own line." :group 'rst-indent :type '(integer)) (rst-testcover-defcustom) (defcustom rst-indent-literal-minimized 2 "Default indentation for literal block after a minimized markup." :group 'rst-indent :type '(integer)) (rst-testcover-defcustom) (defcustom rst-indent-comment 3 "Default indentation for first line of a comment." :group 'rst-indent :type '(integer)) (rst-testcover-defcustom) ;; FIXME: Must consider other tabs: ;; * Line blocks ;; * Definition lists ;; * Option lists (defun rst-line-tabs () "Return tabs of the current line or nil for no tab. The list is sorted so the tab where writing continues most likely is the first one. Each tab is of the form (COLUMN . INNER). COLUMN is the column of the tab. INNER is non-nil if this is an inner tab. I.e. a tab which does come from the basic indentation and not from inner alignment points." (save-excursion (forward-line 0) (save-match-data (unless (looking-at (rst-re 'lin-end)) (back-to-indentation) ;; Current indentation is always the least likely tab. (let ((tabs (list (list (point) 0 nil)))) ; (POINT OFFSET INNER) ;; Push inner tabs more likely to continue writing. (cond ;; Item. ((looking-at (rst-re '(:grp itmany-tag hws-sta) '(:grp "\\S ") "?")) (when (match-string 2) (push (list (match-beginning 2) 0 t) tabs))) ;; Field. ((looking-at (rst-re '(:grp fld-tag) '(:grp hws-tag) '(:grp "\\S ") "?")) (unless (zerop rst-indent-field) (push (list (match-beginning 1) rst-indent-field t) tabs)) (if (match-string 3) (push (list (match-beginning 3) 0 t) tabs) (if (zerop rst-indent-field) (push (list (match-end 2) (if (string= (match-string 2) "") 1 0) t) tabs)))) ;; Directive. ((looking-at (rst-re 'dir-sta-3 '(:grp "\\S ") "?")) (push (list (match-end 1) 0 t) tabs) (unless (string= (match-string 2) "") (push (list (match-end 2) 0 t) tabs)) (when (match-string 4) (push (list (match-beginning 4) 0 t) tabs))) ;; Footnote or citation definition. ((looking-at (rst-re 'fnc-sta-2 '(:grp "\\S ") "?")) (push (list (match-end 1) 0 t) tabs) (when (match-string 3) (push (list (match-beginning 3) 0 t) tabs))) ;; Comment. ((looking-at (rst-re 'cmt-sta-1)) (push (list (point) rst-indent-comment t) tabs))) ;; Start of literal block. (when (looking-at (rst-re 'lit-sta-2)) (let ((tab0 (first tabs))) (push (list (first tab0) (+ (second tab0) (if (match-string 1) rst-indent-literal-minimized rst-indent-literal-normal)) t) tabs))) (mapcar (lambda (tab) (goto-char (first tab)) (cons (+ (current-column) (second tab)) (third tab))) tabs)))))) (defun rst-compute-tabs (pt) "Build the list of possible tabs for all lines above. Search backwards from point PT to build the list of possible tabs. Return a list of tabs sorted by likeliness to continue writing like `rst-line-tabs'. Nearer lines have generally a higher likeliness than farther lines. Return nil if no tab is found in the text above." (save-excursion (goto-char pt) (let (leftmost ; Leftmost column found so far. innermost ; Leftmost column for inner tab. tablist) (while (and (zerop (forward-line -1)) (or (not leftmost) (> leftmost 0))) (let* ((tabs (rst-line-tabs)) (leftcol (if tabs (apply 'min (mapcar 'car tabs))))) (when tabs ;; Consider only lines indented less or same if not INNERMOST. (when (or (not leftmost) (< leftcol leftmost) (and (not innermost) (= leftcol leftmost))) (dolist (tab tabs) (let ((inner (cdr tab)) (newcol (car tab))) (when (and (or (and (not inner) (or (not leftmost) (< newcol leftmost))) (and inner (or (not innermost) (< newcol innermost)))) (not (memq newcol tablist))) (push newcol tablist)))) (setq innermost (if (rst-some (mapcar 'cdr tabs)) ; Has inner. leftcol innermost)) (setq leftmost leftcol))))) (nreverse tablist)))) (defun rst-indent-line (&optional dflt) "Indent current line to next best reStructuredText tab. The next best tab is taken from the tab list returned by `rst-compute-tabs' which is used in a cyclic manner. If the current indentation does not end on a tab use the first one. If the current indentation is on a tab use the next tab. This allows a repeated use of \\[indent-for-tab-command] to cycle through all possible tabs. If no indentation is possible return `noindent' or use DFLT. Return the indentation indented to. When point is in indentation it ends up at its end. Otherwise the point is kept relative to the content." (let* ((pt (point-marker)) (cur (current-indentation)) (clm (current-column)) (tabs (rst-compute-tabs (point))) (fnd (rst-position cur tabs)) ind) (if (and (not tabs) (not dflt)) 'noindent (if (not tabs) (setq ind dflt) (if (not fnd) (setq fnd 0) (setq fnd (1+ fnd)) (if (>= fnd (length tabs)) (setq fnd 0))) (setq ind (nth fnd tabs))) (indent-line-to ind) (if (> clm cur) (goto-char pt)) (set-marker pt nil) ind))) (defun rst-shift-region (beg end cnt) "Shift region BEG to END by CNT tabs. Shift by one tab to the right (CNT > 0) or left (CNT < 0) or remove all indentation (CNT = 0). A tab is taken from the text above. If no suitable tab is found `rst-indent-width' is used." (interactive "r\np") (let ((tabs (sort (rst-compute-tabs beg) (lambda (x y) (<= x y)))) (leftmostcol (rst-find-leftmost-column beg end))) (when (or (> leftmostcol 0) (> cnt 0)) ;; Apply the indent. (indent-rigidly beg end (if (zerop cnt) (- leftmostcol) ;; Find the next tab after the leftmost column. (let* ((cmp (if (> cnt 0) '> '<)) (tabs (if (> cnt 0) tabs (reverse tabs))) (len (length tabs)) (dir (rst-signum cnt)) ; Direction to take. (abs (abs cnt)) ; Absolute number of steps to take. ;; Get the position of the first tab beyond leftmostcol. (fnd (lexical-let ((cmp cmp) (leftmostcol leftmostcol)) ; Create closure. (rst-position-if (lambda (elt) (funcall cmp elt leftmostcol)) tabs))) ;; Virtual position of tab. (pos (+ (or fnd len) (1- abs))) (tab (if (< pos len) ;; Tab exists - use it. (nth pos tabs) ;; Column needs to be computed. (let ((col (+ (or (car (last tabs)) leftmostcol) ;; Base on last known column. (* (- pos (1- len)) ; Distance left. dir ; Direction to take. rst-indent-width)))) (if (< col 0) 0 col))))) (- tab leftmostcol))))))) ;; FIXME: A paragraph with an (incorrectly) indented second line is not filled ;; correctly:: ;; ;; Some start ;; continued wrong (defun rst-adaptive-fill () "Return fill prefix found at point. Value for `adaptive-fill-function'." (let ((fnd (if (looking-at adaptive-fill-regexp) (match-string-no-properties 0)))) (if (save-match-data (not (string-match comment-start-skip fnd))) ;; An non-comment prefix is fine. fnd ;; Matches a comment - return whitespace instead. (make-string (- (save-excursion (goto-char (match-end 0)) (current-column)) (save-excursion (goto-char (match-beginning 0)) (current-column))) ? )))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Comments (defun rst-comment-line-break (&optional soft) "Break line and indent, continuing reStructuredText comment if within one. Value for `comment-line-break-function'. If SOFT use soft newlines as mandated by `comment-line-break-function'." (if soft (insert-and-inherit ?\n) (newline 1)) (save-excursion (forward-char -1) (delete-horizontal-space)) (delete-horizontal-space) (let ((tabs (rst-compute-tabs (point)))) (when tabs (indent-line-to (car tabs))))) (defun rst-comment-indent () "Return indentation for current comment line." (car (rst-compute-tabs (point)))) (defun rst-comment-insert-comment () "Insert a comment in the current line." (rst-indent-line 0) (insert comment-start)) (defun rst-comment-region (beg end &optional arg) "Comment or uncomment the current region. Region is from from BEG to END. Uncomment if ARG." (save-excursion (if (consp arg) (rst-uncomment-region beg end arg) (goto-char beg) (let ((ind (current-indentation)) bol) (forward-line 0) (setq bol (point)) (indent-rigidly bol end rst-indent-comment) (goto-char bol) (open-line 1) (indent-line-to ind) (insert (comment-string-strip comment-start t t)))))) (defun rst-uncomment-region (beg end &optional arg) "Uncomment the current region. Region is from BEG to END. ARG is ignored" (save-excursion (let (bol eol) (goto-char beg) (forward-line 0) (setq bol (point)) (forward-line 1) (setq eol (point)) (indent-rigidly eol end (- rst-indent-comment)) (delete-region bol eol)))) ;;------------------------------------------------------------------------------ ;; FIXME: These next functions should become part of a larger effort to redo ;; the bullets in bulleted lists. The enumerate would just be one of ;; the possible outputs. ;; ;; FIXME: We need to do the enumeration removal as well. (defun rst-enumerate-region (beg end all) "Add enumeration to all the leftmost paragraphs in the given region. The region is specified between BEG and END. With ALL, do all lines instead of just paragraphs." (interactive "r\nP") (let ((count 0) (last-insert-len nil)) (rst-iterate-leftmost-paragraphs beg end (not all) (let ((ins-string (format "%d. " (incf count)))) (setq last-insert-len (length ins-string)) (insert ins-string)) (insert (make-string last-insert-len ?\ ))))) (defun rst-bullet-list-region (beg end all) "Add bullets to all the leftmost paragraphs in the given region. The region is specified between BEG and END. With ALL, do all lines instead of just paragraphs." (interactive "r\nP") (rst-iterate-leftmost-paragraphs beg end (not all) (insert (car rst-preferred-bullets) " ") (insert " "))) ;; FIXME: Does not deal with a varying number of digits appropriately. ;; FIXME: Does not deal with multiple levels independently. ;; FIXME: Does not indent a multiline item correctly. (defun rst-convert-bullets-to-enumeration (beg end) "Convert the bulleted and enumerated items in the region to enumerated lists. Renumber as necessary. Region is from BEG to END." (interactive "r") (let* (;; Find items and convert the positions to markers. (items (mapcar (lambda (x) (cons (copy-marker (car x)) (cdr x))) (rst-find-pfx-in-region beg end (rst-re 'itmany-sta-1)))) (count 1)) (save-excursion (dolist (x items) (goto-char (car x)) (looking-at (rst-re 'itmany-beg-1)) (replace-match (format "%d." count) nil nil nil 1) (incf count))))) ;;------------------------------------------------------------------------------ (defun rst-line-block-region (rbeg rend &optional pfxarg) "Toggle line block prefixes for a region. Region is from RBEG to REND. With PFXARG set the empty lines too." (interactive "r\nP") (let ((comment-start "| ") (comment-end "") (comment-start-skip "| ") (comment-style 'indent) (force (not (not pfxarg)))) (rst-iterate-leftmost-paragraphs-2 (rbeg rend parbegin leftmost isleft isempty) (when (or force (not isempty)) (move-to-column leftmost force) (delete-region (point) (+ (point) (- (current-indentation) leftmost))) (insert "| "))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Font lock ;; ========= (require 'font-lock) ;; FIXME: The obsolete variables need to disappear. ;; The following versions have been done inside Emacs and should not be ;; replaced by `:package-version' attributes until a change. (defgroup rst-faces nil "Faces used in Rst Mode." :group 'rst :group 'faces :version "21.1") (defface rst-block '((t :inherit font-lock-keyword-face)) "Face used for all syntax marking up a special block." :version "24.1" :group 'rst-faces) (defcustom rst-block-face 'rst-block "All syntax marking up a special block." :version "24.1" :group 'rst-faces :type '(face)) (rst-testcover-defcustom) (make-obsolete-variable 'rst-block-face "customize the face `rst-block' instead." "24.1") (defface rst-external '((t :inherit font-lock-type-face)) "Face used for field names and interpreted text." :version "24.1" :group 'rst-faces) (defcustom rst-external-face 'rst-external "Field names and interpreted text." :version "24.1" :group 'rst-faces :type '(face)) (rst-testcover-defcustom) (make-obsolete-variable 'rst-external-face "customize the face `rst-external' instead." "24.1") (defface rst-definition '((t :inherit font-lock-function-name-face)) "Face used for all other defining constructs." :version "24.1" :group 'rst-faces) (defcustom rst-definition-face 'rst-definition "All other defining constructs." :version "24.1" :group 'rst-faces :type '(face)) (rst-testcover-defcustom) (make-obsolete-variable 'rst-definition-face "customize the face `rst-definition' instead." "24.1") ;; XEmacs compatibility (?). (defface rst-directive (if (boundp 'font-lock-builtin-face) '((t :inherit font-lock-builtin-face)) '((t :inherit font-lock-preprocessor-face))) "Face used for directives and roles." :version "24.1" :group 'rst-faces) (defcustom rst-directive-face 'rst-directive "Directives and roles." :group 'rst-faces :type '(face)) (rst-testcover-defcustom) (make-obsolete-variable 'rst-directive-face "customize the face `rst-directive' instead." "24.1") (defface rst-comment '((t :inherit font-lock-comment-face)) "Face used for comments." :version "24.1" :group 'rst-faces) (defcustom rst-comment-face 'rst-comment "Comments." :version "24.1" :group 'rst-faces :type '(face)) (rst-testcover-defcustom) (make-obsolete-variable 'rst-comment-face "customize the face `rst-comment' instead." "24.1") (defface rst-emphasis1 '((t :inherit italic)) "Face used for simple emphasis." :version "24.1" :group 'rst-faces) (defcustom rst-emphasis1-face 'rst-emphasis1 "Simple emphasis." :version "24.1" :group 'rst-faces :type '(face)) (rst-testcover-defcustom) (make-obsolete-variable 'rst-emphasis1-face "customize the face `rst-emphasis1' instead." "24.1") (defface rst-emphasis2 '((t :inherit bold)) "Face used for double emphasis." :version "24.1" :group 'rst-faces) (defcustom rst-emphasis2-face 'rst-emphasis2 "Double emphasis." :group 'rst-faces :type '(face)) (rst-testcover-defcustom) (make-obsolete-variable 'rst-emphasis2-face "customize the face `rst-emphasis2' instead." "24.1") (defface rst-literal '((t :inherit font-lock-string-face)) "Face used for literal text." :version "24.1" :group 'rst-faces) (defcustom rst-literal-face 'rst-literal "Literal text." :version "24.1" :group 'rst-faces :type '(face)) (rst-testcover-defcustom) (make-obsolete-variable 'rst-literal-face "customize the face `rst-literal' instead." "24.1") (defface rst-reference '((t :inherit font-lock-variable-name-face)) "Face used for references to a definition." :version "24.1" :group 'rst-faces) (defcustom rst-reference-face 'rst-reference "References to a definition." :version "24.1" :group 'rst-faces :type '(face)) (rst-testcover-defcustom) (make-obsolete-variable 'rst-reference-face "customize the face `rst-reference' instead." "24.1") (defface rst-transition '((t :inherit font-lock-keyword-face)) "Face used for a transition." :package-version '(rst . "1.3.0") :group 'rst-faces) (defface rst-adornment '((t :inherit font-lock-keyword-face)) "Face used for the adornment of a section header." :package-version '(rst . "1.3.0") :group 'rst-faces) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (dolist (var '(rst-level-face-max rst-level-face-base-color rst-level-face-base-light rst-level-face-format-light rst-level-face-step-light rst-level-1-face rst-level-2-face rst-level-3-face rst-level-4-face rst-level-5-face rst-level-6-face)) (make-obsolete-variable var "customize the faces `rst-level-*' instead." "24.3")) ;; Define faces for the first 6 levels. More levels are possible, however. (defface rst-level-1 '((((background light)) (:background "grey85")) (((background dark)) (:background "grey15"))) "Default face for section title text at level 1." :package-version '(rst . "1.4.0")) (defface rst-level-2 '((((background light)) (:background "grey78")) (((background dark)) (:background "grey22"))) "Default face for section title text at level 2." :package-version '(rst . "1.4.0")) (defface rst-level-3 '((((background light)) (:background "grey71")) (((background dark)) (:background "grey29"))) "Default face for section title text at level 3." :package-version '(rst . "1.4.0")) (defface rst-level-4 '((((background light)) (:background "grey64")) (((background dark)) (:background "grey36"))) "Default face for section title text at level 4." :package-version '(rst . "1.4.0")) (defface rst-level-5 '((((background light)) (:background "grey57")) (((background dark)) (:background "grey43"))) "Default face for section title text at level 5." :package-version '(rst . "1.4.0")) (defface rst-level-6 '((((background light)) (:background "grey50")) (((background dark)) (:background "grey50"))) "Default face for section title text at level 6." :package-version '(rst . "1.4.0")) (defcustom rst-adornment-faces-alist '((t . rst-transition) (nil . rst-adornment) (1 . rst-level-1) (2 . rst-level-2) (3 . rst-level-3) (4 . rst-level-4) (5 . rst-level-5) (6 . rst-level-6)) "Faces for the various adornment types. Key is a number (for the section title text of that level starting with 1), t (for transitions) or nil (for section title adornment). if you need levels beyond 6 you have to define faces of your own." :group 'rst-faces :type '(alist :key-type (choice (integer :tag "Section level") (const :tag "transitions" t) (const :tag "section title adornment" nil)) :value-type (face))) (rst-testcover-defcustom) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar rst-font-lock-keywords ;; The reST-links in the comments below all relate to sections in ;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html. `(;; FIXME: Block markup is not recognized in blocks after explicit markup ;; start. ;; Simple `Body Elements`_ ;; `Bullet Lists`_ ;; FIXME: A bullet directly after a field name is not recognized. (,(rst-re 'lin-beg '(:grp bul-sta)) 1 rst-block-face) ;; `Enumerated Lists`_ (,(rst-re 'lin-beg '(:grp enmany-sta)) 1 rst-block-face) ;; `Definition Lists`_ ;; FIXME: missing. ;; `Field Lists`_ (,(rst-re 'lin-beg '(:grp fld-tag) 'bli-sfx) 1 rst-external-face) ;; `Option Lists`_ (,(rst-re 'lin-beg '(:grp opt-tag (:shy optsep-tag opt-tag) "*") '(:alt "$" (:seq hws-prt "\\{2\\}"))) 1 rst-block-face) ;; `Line Blocks`_ ;; Only for lines containing no more bar - to distinguish from tables. (,(rst-re 'lin-beg '(:grp "|" bli-sfx) "[^|\n]*$") 1 rst-block-face) ;; `Tables`_ ;; FIXME: missing ;; All the `Explicit Markup Blocks`_ ;; `Footnotes`_ / `Citations`_ (,(rst-re 'lin-beg 'fnc-sta-2) (1 rst-definition-face) (2 rst-definition-face)) ;; `Directives`_ / `Substitution Definitions`_ (,(rst-re 'lin-beg 'dir-sta-3) (1 rst-directive-face) (2 rst-definition-face) (3 rst-directive-face)) ;; `Hyperlink Targets`_ (,(rst-re 'lin-beg '(:grp exm-sta "_" (:alt (:seq "`" ilcbkqdef-tag "`") (:seq (:alt "[^:\\\n]" "\\\\.") "+")) ":") 'bli-sfx) 1 rst-definition-face) (,(rst-re 'lin-beg '(:grp "__") 'bli-sfx) 1 rst-definition-face) ;; All `Inline Markup`_ ;; Most of them may be multiline though this is uninteresting. ;; FIXME: Condition 5 preventing fontification of e.g. "*" not implemented ;; `Strong Emphasis`_. (,(rst-re 'ilm-pfx '(:grp "\\*\\*" ilcast-tag "\\*\\*") 'ilm-sfx) 1 rst-emphasis2-face) ;; `Emphasis`_ (,(rst-re 'ilm-pfx '(:grp "\\*" ilcast-tag "\\*") 'ilm-sfx) 1 rst-emphasis1-face) ;; `Inline Literals`_ (,(rst-re 'ilm-pfx '(:grp "``" ilcbkq-tag "``") 'ilm-sfx) 1 rst-literal-face) ;; `Inline Internal Targets`_ (,(rst-re 'ilm-pfx '(:grp "_`" ilcbkq-tag "`") 'ilm-sfx) 1 rst-definition-face) ;; `Hyperlink References`_ ;; FIXME: `Embedded URIs`_ not considered. ;; FIXME: Directly adjacent marked up words are not fontified correctly ;; unless they are not separated by two spaces: foo_ bar_. (,(rst-re 'ilm-pfx '(:grp (:alt (:seq "`" ilcbkq-tag "`") (:seq "\\sw" (:alt "\\sw" "-") "+\\sw")) "__?") 'ilm-sfx) 1 rst-reference-face) ;; `Interpreted Text`_ (,(rst-re 'ilm-pfx '(:grp (:shy ":" sym-tag ":") "?") '(:grp "`" ilcbkq-tag "`") '(:grp (:shy ":" sym-tag ":") "?") 'ilm-sfx) (1 rst-directive-face) (2 rst-external-face) (3 rst-directive-face)) ;; `Footnote References`_ / `Citation References`_ (,(rst-re 'ilm-pfx '(:grp fnc-tag "_") 'ilm-sfx) 1 rst-reference-face) ;; `Substitution References`_ ;; FIXME: References substitutions like |this|_ or |this|__ are not ;; fontified correctly. (,(rst-re 'ilm-pfx '(:grp sub-tag) 'ilm-sfx) 1 rst-reference-face) ;; `Standalone Hyperlinks`_ ;; FIXME: This takes it easy by using a whitespace as delimiter. (,(rst-re 'ilm-pfx '(:grp uri-tag ":\\S +") 'ilm-sfx) 1 rst-definition-face) (,(rst-re 'ilm-pfx '(:grp sym-tag "@" sym-tag ) 'ilm-sfx) 1 rst-definition-face) ;; Do all block fontification as late as possible so 'append works. ;; Sections_ / Transitions_ ;; For sections this is multiline. (,(rst-re 'ado-beg-2-1) (rst-font-lock-handle-adornment-matcher (rst-font-lock-handle-adornment-pre-match-form (match-string-no-properties 1) (match-end 1)) nil (1 (cdr (assoc nil rst-adornment-faces-alist)) append t) (2 (cdr (assoc rst-font-lock-adornment-level rst-adornment-faces-alist)) append t) (3 (cdr (assoc nil rst-adornment-faces-alist)) append t))) ;; FIXME: FACESPEC could be used instead of ordinary faces to set ;; properties on comments and literal blocks so they are *not* ;; inline fontified. See (elisp)Search-based Fontification. ;; FIXME: And / or use `syntax-propertize` functions as in `octave-mod.el` ;; and other V24 modes. May make `font-lock-extend-region` ;; superfluous. ;; `Comments`_ ;; This is multiline. (,(rst-re 'lin-beg 'cmt-sta-1) (1 rst-comment-face) (rst-font-lock-find-unindented-line-match (rst-font-lock-find-unindented-line-limit (match-end 1)) nil (0 rst-comment-face append))) (,(rst-re 'lin-beg '(:grp exm-tag) '(:grp hws-tag) "$") (1 rst-comment-face) (2 rst-comment-face) (rst-font-lock-find-unindented-line-match (rst-font-lock-find-unindented-line-limit 'next) nil (0 rst-comment-face append))) ;; FIXME: This is not rendered as comment:: ;; .. .. list-table:: ;; :stub-columns: 1 ;; :header-rows: 1 ;; FIXME: This is rendered wrong:: ;; ;; xxx yyy:: ;; ;; ----|> KKKKK <|---- ;; / \ ;; -|> AAAAAAAAAAPPPPPP <|- -|> AAAAAAAAAABBBBBBB <|- ;; | | | | ;; | | | | ;; PPPPPP PPPPPPDDDDDDD BBBBBBB PPPPPPBBBBBBB ;; ;; Indentation needs to be taken from the line with the ``::`` and not from ;; the first content line. ;; `Indented Literal Blocks`_ ;; This is multiline. (,(rst-re 'lin-beg 'lit-sta-2) (2 rst-block-face) (rst-font-lock-find-unindented-line-match (rst-font-lock-find-unindented-line-limit t) nil (0 rst-literal-face append))) ;; FIXME: `Quoted Literal Blocks`_ missing. ;; This is multiline. ;; `Doctest Blocks`_ ;; FIXME: This is wrong according to the specification: ;; ;; Doctest blocks are text blocks which begin with ">>> ", the Python ;; interactive interpreter main prompt, and end with a blank line. ;; Doctest blocks are treated as a special case of literal blocks, ;; without requiring the literal block syntax. If both are present, the ;; literal block syntax takes priority over Doctest block syntax: ;; ;; This is an ordinary paragraph. ;; ;; >>> print 'this is a Doctest block' ;; this is a Doctest block ;; ;; The following is a literal block:: ;; ;; >>> This is not recognized as a doctest block by ;; reStructuredText. It *will* be recognized by the doctest ;; module, though! ;; ;; Indentation is not required for doctest blocks. (,(rst-re 'lin-beg '(:grp (:alt ">>>" ell-tag)) '(:grp ".+")) (1 rst-block-face) (2 rst-literal-face))) "Keywords to highlight in rst mode.") (defvar font-lock-beg) (defvar font-lock-end) (defun rst-font-lock-extend-region () "Extend the font-lock region if it might be in a multi-line construct. Return non-nil if so. Font-lock region is from `font-lock-beg' to `font-lock-end'." (let ((r (rst-font-lock-extend-region-internal font-lock-beg font-lock-end))) (when r (setq font-lock-beg (car r)) (setq font-lock-end (cdr r)) t))) (defun rst-font-lock-extend-region-internal (beg end) "Check the region BEG / END for being in the middle of a multi-line construct. Return nil if not or a cons with new values for BEG / END" (let ((nbeg (rst-font-lock-extend-region-extend beg -1)) (nend (rst-font-lock-extend-region-extend end 1))) (if (or nbeg nend) (cons (or nbeg beg) (or nend end))))) (defun rst-forward-line (&optional n) "Like `forward-line' but always end up in column 0 and return accordingly. Move N lines forward just as `forward-line'." (let ((moved (forward-line n))) (if (bolp) moved (forward-line 0) (- moved (rst-signum n))))) ;; FIXME: If a single line is made a section header by `rst-adjust' the header ;; is not always fontified immediately. (defun rst-font-lock-extend-region-extend (pt dir) "Extend the region starting at point PT and extending in direction DIR. Return extended point or nil if not moved." ;; There are many potential multiline constructs but there are two groups ;; which are really relevant. The first group consists of ;; ;; * comment lines without leading explicit markup tag and ;; ;; * literal blocks following "::" ;; ;; which are both indented. Thus indentation is the first thing recognized ;; here. The second criteria is an explicit markup tag which may be a comment ;; or a double colon at the end of a line. ;; ;; The second group consists of the adornment cases. (if (not (get-text-property pt 'font-lock-multiline)) ;; Move only if we don't start inside a multiline construct already. (save-excursion (let (;; Non-empty non-indented line, explicit markup tag or literal ;; block tag. (stop-re (rst-re '(:alt "[^ \t\n]" (:seq hws-tag exm-tag) (:seq ".*" dcl-tag lin-end))))) ;; The comments below are for dir == -1 / dir == 1. (goto-char pt) (forward-line 0) (setq pt (point)) (while (and (not (looking-at stop-re)) (zerop (rst-forward-line dir)))) ; try previous / next ; line if it exists. (if (looking-at (rst-re 'ado-beg-2-1)) ; may be an underline / ; overline. (if (zerop (rst-forward-line dir)) (if (looking-at (rst-re 'ttl-beg)) ; title found, i.e. ; underline / overline ; found. (if (zerop (rst-forward-line dir)) (if (not (looking-at (rst-re 'ado-beg-2-1))) ; no ; overline / ; underline. (rst-forward-line (- dir)))) ; step back to title ; / adornment. (if (< dir 0) ; keep downward adornment. (rst-forward-line (- dir))))) ; step back to adornment. (if (looking-at (rst-re 'ttl-beg)) ; may be a title. (if (zerop (rst-forward-line dir)) (if (not (looking-at (rst-re 'ado-beg-2-1))) ; no overline / ; underline. (rst-forward-line (- dir)))))) ; step back to line. (if (not (= (point) pt)) (point)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Indented blocks (defun rst-forward-indented-block (&optional column limit) "Move forward across one indented block. Find the next non-empty line which is not indented at least to COLUMN (defaults to the column of the point). Moves point to first character of this line or the first empty line immediately before it and returns that position. If there is no such line before LIMIT (defaults to the end of the buffer) returns nil and point is not moved." (interactive) (let ((clm (or column (current-column))) (start (point)) fnd beg cand) (if (not limit) (setq limit (point-max))) (save-match-data (while (and (not fnd) (< (point) limit)) (forward-line 1) (when (< (point) limit) (setq beg (point)) (if (looking-at (rst-re 'lin-end)) (setq cand (or cand beg)) ; An empty line is a candidate. (move-to-column clm) ;; FIXME: No indentation [(zerop clm)] must be handled in some ;; useful way - though it is not clear what this should mean ;; at all. (if (string-match (rst-re 'linemp-tag) (buffer-substring-no-properties beg (point))) (setq cand nil) ; An indented line resets a candidate. (setq fnd (or cand beg))))))) (goto-char (or fnd start)) fnd)) (defvar rst-font-lock-find-unindented-line-begin nil "Beginning of the match if `rst-font-lock-find-unindented-line-end'.") (defvar rst-font-lock-find-unindented-line-end nil "End of the match as determined by `rst-font-lock-find-unindented-line-limit'. Also used as a trigger for `rst-font-lock-find-unindented-line-match'.") (defun rst-font-lock-find-unindented-line-limit (ind-pnt) "Find the next unindented line relative to indentation at IND-PNT. Return this point, the end of the buffer or nil if nothing found. If IND-PNT is `next' take the indentation from the next line if this is not empty and indented more than the current one. If IND-PNT is non-nil but not a number take the indentation from the next non-empty line if this is indented more than the current one." (setq rst-font-lock-find-unindented-line-begin ind-pnt) (setq rst-font-lock-find-unindented-line-end (save-excursion (when (not (numberp ind-pnt)) ;; Find indentation point in next line if any. (setq ind-pnt ;; FIXME: Should be refactored to two different functions ;; giving their result to this function, may be ;; integrated in caller. (save-match-data (let ((cur-ind (current-indentation))) (if (eq ind-pnt 'next) (when (and (zerop (forward-line 1)) (< (point) (point-max))) ;; Not at EOF. (setq rst-font-lock-find-unindented-line-begin (point)) (when (and (not (looking-at (rst-re 'lin-end))) (> (current-indentation) cur-ind)) ;; Use end of indentation if non-empty line. (looking-at (rst-re 'hws-tag)) (match-end 0))) ;; Skip until non-empty line or EOF. (while (and (zerop (forward-line 1)) (< (point) (point-max)) (looking-at (rst-re 'lin-end)))) (when (< (point) (point-max)) ;; Not at EOF. (setq rst-font-lock-find-unindented-line-begin (point)) (when (> (current-indentation) cur-ind) ;; Indentation bigger than line of departure. (looking-at (rst-re 'hws-tag)) (match-end 0)))))))) (when ind-pnt (goto-char ind-pnt) (or (rst-forward-indented-block nil (point-max)) (point-max)))))) (defun rst-font-lock-find-unindented-line-match (limit) "Set the match found earlier if match were found. Match has been found by `rst-font-lock-find-unindented-line-limit' the first time called or no match is found. Return non-nil if match was found. LIMIT is not used but mandated by the caller." (when rst-font-lock-find-unindented-line-end (set-match-data (list rst-font-lock-find-unindented-line-begin rst-font-lock-find-unindented-line-end)) (put-text-property rst-font-lock-find-unindented-line-begin rst-font-lock-find-unindented-line-end 'font-lock-multiline t) ;; Make sure this is called only once. (setq rst-font-lock-find-unindented-line-end nil) t)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Adornments (defvar rst-font-lock-adornment-level nil "Storage for `rst-font-lock-handle-adornment-matcher'. Either section level of the current adornment or t for a transition.") (defun rst-adornment-level (key) "Return section level for adornment KEY. KEY is the first element of the return list of `rst-classify-adornment'. If KEY is not a cons return it. If KEY is found in the hierarchy return its level. Otherwise return a level one beyond the existing hierarchy." (if (not (consp key)) key (let* ((hier (rst-get-hierarchy)) (char (car key)) (style (cdr key))) (1+ (or (lexical-let ((char char) (style style) (hier hier)) ; Create closure. (rst-position-if (lambda (elt) (and (equal (car elt) char) (equal (cadr elt) style))) hier)) (length hier)))))) (defvar rst-font-lock-adornment-match nil "Storage for match for current adornment. Set by `rst-font-lock-handle-adornment-pre-match-form'. Also used as a trigger for `rst-font-lock-handle-adornment-matcher'.") (defun rst-font-lock-handle-adornment-pre-match-form (ado ado-end) "Determine limit for adornments. Determine all things necessary for font-locking section titles and transitions and put the result to `rst-font-lock-adornment-match' and `rst-font-lock-adornment-level'. ADO is the complete adornment matched. ADO-END is the point where ADO ends. Return the point where the whole adorned construct ends. Called as a PRE-MATCH-FORM in the sense of `font-lock-keywords'." (let ((ado-data (rst-classify-adornment ado ado-end))) (if (not ado-data) (setq rst-font-lock-adornment-level nil rst-font-lock-adornment-match nil) (setq rst-font-lock-adornment-level (rst-adornment-level (car ado-data))) (setq rst-font-lock-adornment-match (cdr ado-data)) (goto-char (nth 1 ado-data)) ; Beginning of construct. (nth 2 ado-data)))) ; End of construct. (defun rst-font-lock-handle-adornment-matcher (limit) "Set the match found earlier if match were found. Match has been found by `rst-font-lock-handle-adornment-pre-match-form' the first time called or no match is found. Return non-nil if match was found. Called as a MATCHER in the sense of `font-lock-keywords'. LIMIT is not used but mandated by the caller." (let ((match rst-font-lock-adornment-match)) ;; May run only once - enforce this. (setq rst-font-lock-adornment-match nil) (when match (set-match-data match) (goto-char (match-end 0)) (put-text-property (match-beginning 0) (match-end 0) 'font-lock-multiline t) t))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Compilation (defgroup rst-compile nil "Settings for support of conversion of reStructuredText document with \\[rst-compile]." :group 'rst :version "21.1") (defcustom rst-compile-toolsets `((html ,(if (executable-find "rst2html.py") "rst2html.py" "rst2html") ".html" nil) (latex ,(if (executable-find "rst2latex.py") "rst2latex.py" "rst2latex") ".tex" nil) (newlatex ,(if (executable-find "rst2newlatex.py") "rst2newlatex.py" "rst2newlatex") ".tex" nil) (pseudoxml ,(if (executable-find "rst2pseudoxml.py") "rst2pseudoxml.py" "rst2pseudoxml") ".xml" nil) (xml ,(if (executable-find "rst2xml.py") "rst2xml.py" "rst2xml") ".xml" nil) (pdf ,(if (executable-find "rst2pdf.py") "rst2pdf.py" "rst2pdf") ".pdf" nil) (s5 ,(if (executable-find "rst2s5.py") "rst2s5.py" "rst2s5") ".html" nil)) "Table describing the command to use for each tool-set. An association list of the tool-set to a list of the (command to use, extension of produced filename, options to the tool (nil or a string)) to be used for converting the document." ;; FIXME: These are not options but symbols which may be referenced by ;; `rst-compile-*-toolset` below. The `:validate' keyword of ;; `defcustom' may help to define this properly in newer Emacs ;; versions (> 23.1). :type '(alist :options (html latex newlatex pseudoxml xml pdf s5) :key-type symbol :value-type (list :tag "Specification" (file :tag "Command") (string :tag "File extension") (choice :tag "Command options" (const :tag "No options" nil) (string :tag "Options")))) :group 'rst :package-version "1.2.0") (rst-testcover-defcustom) ;; FIXME: Must be `defcustom`. (defvar rst-compile-primary-toolset 'html "The default tool-set for `rst-compile'.") ;; FIXME: Must be `defcustom`. (defvar rst-compile-secondary-toolset 'latex "The default tool-set for `rst-compile' with a prefix argument.") (defun rst-compile-find-conf () "Look for the configuration file in the parents of the current path." (interactive) (let ((file-name "docutils.conf") (buffer-file (buffer-file-name))) ;; Move up in the dir hierarchy till we find a change log file. (let* ((dir (file-name-directory buffer-file)) (prevdir nil)) (while (and (or (not (string= dir prevdir)) (setq dir nil) nil) (not (file-exists-p (concat dir file-name)))) ;; Move up to the parent dir and try again. (setq prevdir dir) (setq dir (expand-file-name (file-name-directory (directory-file-name (file-name-directory dir)))))) (or (and dir (concat dir file-name)) nil)))) (require 'compile) (defun rst-compile (&optional use-alt) "Compile command to convert reST document into some output file. Attempts to find configuration file, if it can, overrides the options. There are two commands to choose from, with USE-ALT, select the alternative tool-set." (interactive "P") ;; Note: maybe we want to check if there is a Makefile too and not do anything ;; if that is the case. I dunno. (let* ((toolset (cdr (assq (if use-alt rst-compile-secondary-toolset rst-compile-primary-toolset) rst-compile-toolsets))) (command (car toolset)) (extension (cadr toolset)) (options (caddr toolset)) (conffile (rst-compile-find-conf)) (bufname (file-name-nondirectory buffer-file-name)) (outname (file-name-sans-extension bufname))) ;; Set compile-command before invocation of compile. (set (make-local-variable 'compile-command) (mapconcat 'identity (list command (or options "") (if conffile (concat "--config=" (shell-quote-argument conffile)) "") (shell-quote-argument bufname) (shell-quote-argument (concat outname extension))) " ")) ;; Invoke the compile command. (if (or compilation-read-command use-alt) (call-interactively 'compile) (compile compile-command)))) (defun rst-compile-alt-toolset () "Compile command with the alternative tool-set." (interactive) (rst-compile t)) (defun rst-compile-pseudo-region () "Show pseudo-XML rendering. Rendering is done of the current active region, or of the entire buffer, if the region is not selected." ;; FIXME: The region should be given interactively. (interactive) (with-output-to-temp-buffer "*pseudoxml*" (shell-command-on-region (if mark-active (region-beginning) (point-min)) (if mark-active (region-end) (point-max)) (cadr (assq 'pseudoxml rst-compile-toolsets)) standard-output))) ;; FIXME: Should be `defcustom`. (defvar rst-pdf-program "xpdf" "Program used to preview PDF files.") (defun rst-compile-pdf-preview () "Convert the document to a PDF file and launch a preview program." (interactive) (let* ((tmp-filename (make-temp-file "rst_el" nil ".pdf")) (command (format "%s %s %s && %s %s ; rm %s" (cadr (assq 'pdf rst-compile-toolsets)) buffer-file-name tmp-filename rst-pdf-program tmp-filename tmp-filename))) (start-process-shell-command "rst-pdf-preview" nil command) ;; Note: you could also use (compile command) to view the compilation ;; output. )) ;; FIXME: Should be `defcustom` or use something like `browse-url`. (defvar rst-slides-program "firefox" "Program used to preview S5 slides.") (defun rst-compile-slides-preview () "Convert the document to an S5 slide presentation and launch a preview program." (interactive) (let* ((tmp-filename (make-temp-file "rst_el" nil ".html")) (command (format "%s %s %s && %s %s ; rm %s" (cadr (assq 's5 rst-compile-toolsets)) buffer-file-name tmp-filename rst-slides-program tmp-filename tmp-filename))) (start-process-shell-command "rst-slides-preview" nil command) ;; Note: you could also use (compile command) to view the compilation ;; output. )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Imenu support. ;; FIXME: Integrate this properly. Consider a key binding. ;; Based on code from Masatake YAMATO . (defun rst-imenu-find-adornments-for-position (adornments pos) "Find adornments cell in ADORNMENTS for position POS." (let ((a nil)) (while adornments (if (and (car adornments) (eq (car (car adornments)) pos)) (setq a adornments adornments nil) (setq adornments (cdr adornments)))) a)) (defun rst-imenu-convert-cell (elt adornments) "Convert a cell ELT in a tree returned from `rst-section-tree' to imenu index. ADORNMENTS is used as hint information for conversion." (let* ((kar (car elt)) (kdr (cdr elt)) (title (car kar))) (if kar (let* ((p (marker-position (cadr kar))) (adornments (rst-imenu-find-adornments-for-position adornments p)) (a (car adornments)) (adornments (cdr adornments)) ;; FIXME: Overline adornment characters need to be in front so ;; they become visible even for long title lines. May be ;; an additional level number is also useful. (title (format "%s%s%s" (make-string (1+ (nth 3 a)) (nth 1 a)) title (if (eq (nth 2 a) 'simple) "" (char-to-string (nth 1 a)))))) (cons title (if (null kdr) p (cons ;; A bit ugly but this make which-func happy. (cons title p) (mapcar (lambda (elt0) (rst-imenu-convert-cell elt0 adornments)) kdr))))) nil))) ;; FIXME: Document title and subtitle need to be handled properly. They should ;; get an own "Document" top level entry. (defun rst-imenu-create-index () "Create index for imenu. Return as described for `imenu--index-alist'." (rst-reset-section-caches) (let ((tree (rst-section-tree)) ;; Translate line notation to point notation. (adornments (save-excursion (mapcar (lambda (ln-ado) (cons (progn (goto-char (point-min)) (forward-line (1- (car ln-ado))) ;; FIXME: Need to consider ;; `imenu-use-markers' here? (point)) (cdr ln-ado))) (rst-find-all-adornments))))) (delete nil (mapcar (lambda (elt) (rst-imenu-convert-cell elt adornments)) tree)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Generic text functions that are more convenient than the defaults. ;; FIXME: Unbound command - should be bound or removed. (defun rst-replace-lines (fromchar tochar) "Replace flush-left lines of FROMCHAR with equal-length lines of TOCHAR." (interactive "\ cSearch for flush-left lines of char: cand replace with char: ") (save-excursion (let ((searchre (rst-re "^" fromchar "+\\( *\\)$")) (found 0)) (while (search-forward-regexp searchre nil t) (setq found (1+ found)) (goto-char (match-beginning 1)) (let ((width (current-column))) (rst-delete-entire-line) (insert-char tochar width))) (message (format "%d lines replaced." found))))) ;; FIXME: Unbound command - should be bound or removed. (defun rst-join-paragraph () "Join lines in current paragraph into one line, removing end-of-lines." (interactive) (let ((fill-column 65000)) ; Some big number. (call-interactively 'fill-paragraph))) ;; FIXME: Unbound command - should be bound or removed. (defun rst-force-fill-paragraph () "Fill paragraph at point, first joining the paragraph's lines into one. This is useful for filling list item paragraphs." (interactive) (rst-join-paragraph) (fill-paragraph nil)) ;; FIXME: Unbound command - should be bound or removed. ;; Generic character repeater function. ;; For sections, better to use the specialized function above, but this can ;; be useful for creating separators. (defun rst-repeat-last-character (use-next) "Fill the current line using the last character on the current line. Fill up to the length of the preceding line or up to `fill-column' if preceding line is empty. If USE-NEXT, use the next line rather than the preceding line. If the current line is longer than the desired length, shave the characters off the current line to fit the desired length. As an added convenience, if the command is repeated immediately, the alternative column is used (fill-column vs. end of previous/next line)." (interactive "P") (let* ((curcol (current-column)) (curline (+ (count-lines (point-min) (point)) (if (zerop curcol) 1 0))) (lbp (line-beginning-position 0)) (prevcol (if (and (= curline 1) (not use-next)) fill-column (save-excursion (forward-line (if use-next 1 -1)) (end-of-line) (skip-chars-backward " \t" lbp) (let ((cc (current-column))) (if (zerop cc) fill-column cc))))) (rightmost-column (cond ((equal last-command 'rst-repeat-last-character) (if (= curcol fill-column) prevcol fill-column)) (t (save-excursion (if (zerop prevcol) fill-column prevcol)))))) (end-of-line) (if (> (current-column) rightmost-column) ;; Shave characters off the end. (delete-region (- (point) (- (current-column) rightmost-column)) (point)) ;; Fill with last characters. (insert-char (preceding-char) (- rightmost-column (current-column)))))) ;; LocalWords: docutils http sourceforge rst html wp svn svnroot txt reST regex ;; LocalWords: regexes alist seq alt grp keymap abbrev overline overlines toc ;; LocalWords: XML PNT propertized ;; Local Variables: ;; sentence-end-double-space: t ;; End: (provide 'rst) ;;; rst.el ends here docutils-0.12/tools/editors/emacs/tests/0000775000175000017500000000000012356234260022272 5ustar engelbertengelbert00000000000000docutils-0.12/tools/editors/emacs/tests/imenu.el0000664000175000017500000000343212026705225023731 0ustar engelbertengelbert00000000000000;; Tests for rst-imenu-create-index (add-to-list 'load-path ".") (load "init" nil t) (init-rst-ert t) (ert-deftest imenu-asserts () "Check some assertions." (should (equal ert-Buf-point-char "\^@")) (should (equal ert-Buf-mark-char "\^?")) ) (ert-deftest rst-imenu-create-index () "Tests for `rst-imenu-create-index'." (should (ert-equal-buffer-return (rst-imenu-create-index) " " t nil)) (should (ert-equal-buffer-return (rst-imenu-create-index) " Some normal text. " t nil)) (should (ert-equal-buffer-return (rst-imenu-create-index) " Header ======" t '(("=Header" . 2)))) (should (ert-equal-buffer-return (rst-imenu-create-index) " Header ====== Subheader ---------" t '(("=Header" ("=Header" . 2) ("-Subheader" . 17))))) (should (ert-equal-buffer-return (rst-imenu-create-index) " Header ====== Subheader --------- With space ----------" t '(("=Header" ("=Header" . 2) ("-Subheader" . 17) ("-With space" . 38))))) (should (ert-equal-buffer-return (rst-imenu-create-index) " Header ====== Subheader --------- With space ---------- Top level again ===============" t '(("=Header" ("=Header" . 2) ("-Subheader" . 17) ("-With space" . 38)) ("=Top level again" . 61)))) (should (ert-equal-buffer-return (rst-imenu-create-index) " Header ====== Subheader --------- With space ---------- Sub sub ~~~~~~~ Top level again ===============" t '(("=Header" ("=Header" . 2) ("-Subheader" . 17) ("-With space" ("-With space" . 38) ("~Sub sub" . 61))) ("=Top level again" . 78)))) ) ;; FIXME: Test missing intermediate sections. ;; FIXME: Test document titles. docutils-0.12/tools/editors/emacs/tests/cl.el0000664000175000017500000000412312026705225023210 0ustar engelbertengelbert00000000000000;; Tests for replacement functions for `cl.el' (add-to-list 'load-path ".") (load "init" nil t) (init-rst-ert nil) (ert-deftest rst-signum () "Test `rst-signum'." (should (equal (rst-signum 10) 1)) (should (equal (rst-signum -10) -1)) (should (equal (rst-signum 0) 0)) ) (ert-deftest rst-some () "Test `rst-some'." (should (equal (rst-some nil) nil)) (should (equal (rst-some '(t)) t)) (should (equal (rst-some '(0)) 0)) (should (equal (rst-some '(1)) 1)) (should (equal (rst-some '(nil 1)) 1)) (should (equal (rst-some '(nil nil)) nil)) (should (equal (rst-some nil 'not) nil)) (should (equal (rst-some '(t) 'not) nil)) (should (equal (rst-some '(0) 'not) nil)) (should (equal (rst-some '(1 nil) 'not) t)) (should (equal (rst-some '(nil 1) 'not) t)) (should (equal (rst-some '(nil nil) 'not) t)) ) (ert-deftest rst-position () "Test `rst-position'." (should (equal (rst-position nil nil) nil)) (should (equal (rst-position t '(nil)) nil)) (should (equal (rst-position nil '(t)) nil)) (should (equal (rst-position nil '(nil)) 0)) (should (equal (rst-position t '(t)) 0)) (should (equal (rst-position t '(nil t)) 1)) (should (equal (rst-position t '(nil t t nil sym)) 1)) (should (equal (rst-position t '(nil (t) t nil sym)) 2)) (should (equal (rst-position 'sym '(nil (t) t nil sym)) 4)) (should (equal (rst-position 'sym '(nil (t) t nil t)) nil)) (should (equal (rst-position '(t) '(nil (t) t nil sym)) 1)) (should (equal (rst-position '(1 2 3) '(nil (t) t nil sym)) nil)) (should (equal (rst-position '(1 2 3) '(nil (t) t (1 2 3) t)) 3)) (should (equal (rst-position '(1 2 3) '(nil (t) t (1 2 3) (1 2 3))) 3)) ) (ert-deftest rst-position-if () "Test `rst-position-if'." (should (equal (rst-position-if 'not '(t nil nil)) 1)) (should (equal (rst-position-if 'not nil) nil)) (should (equal (rst-position-if 'identity '(nil)) nil)) (should (equal (rst-position-if 'not '(t)) nil)) (should (equal (rst-position-if 'not '(nil)) 0)) (should (equal (rst-position-if 'not '(nil nil)) 0)) (should (equal (rst-position-if 'not '(t t nil)) 2)) ) docutils-0.12/tools/editors/emacs/tests/fill.el0000664000175000017500000002451012026705225023542 0ustar engelbertengelbert00000000000000;; Tests for functions around filling (add-to-list 'load-path ".") (load "init" nil t) (init-rst-ert t) (ert-deftest fill-asserts () "Check some assertions." (should (equal ert-Buf-point-char "\^@")) (should (equal ert-Buf-mark-char "\^?")) ) (defun auto-fill () "Wrapper to do auto fill." (let ((fc fill-column)) (rst-mode) (setq fill-column fc) (auto-fill-mode 1) (funcall auto-fill-function))) (ert-deftest auto-fill () "Tests for auto fill." (let ((rst-indent-width 2) (rst-indent-field 2) (rst-indent-literal-normal 3) (rst-indent-literal-minimized 2) (rst-indent-comment 3) (fill-column 20)) (should (ert-equal-buffer (auto-fill) " * This is a test with a fill column of 20\^@" " * This is a test with a fill column of 20\^@" )) (should (ert-equal-buffer (auto-fill) " * This is a test with a fill column of 20\^@" " * This is a test with a fill column of 20\^@" )) (should (ert-equal-buffer (auto-fill) " :Field: Does this work for fields?\^@" " :Field: Does this work for fields?\^@" )) (should (ert-equal-buffer (auto-fill) " :Field: Does this work for fields?\^@" " :Field: Does this work for fields?\^@" )) (should (ert-equal-buffer (auto-fill) " .. dir:: Yes, quite fine\^@" " .. dir:: Yes, quite fine\^@" )) (should (ert-equal-buffer (auto-fill) " .. dir:: Yes, quite fine\^@ :f: Field" " .. dir:: Yes, quite fine\^@ :f: Field" )) (should (ert-equal-buffer (auto-fill) " .. |s| r:: Dir ectives had problems\^@" " .. |s| r:: Dir ectives had problems\^@" )) (should (ert-equal-buffer (auto-fill) " .. |s| r:: Dir ectives had problems\^@" " .. |s| r:: Dir ectives had problems\^@" )) (should (ert-equal-buffer (auto-fill) " .. [CIT] X cit is citations are also filled\^@" " .. [CIT] X cit is citations are also filled\^@" )) (should (ert-equal-buffer (auto-fill) " .. [CIT] X cit is citations are also filled\^@" " .. [CIT] X cit is citations are also filled\^@" )) (should (ert-equal-buffer (auto-fill) " .. Comments should also fill nicely\^@" " .. Comments should also fill nicely\^@" )) (should (ert-equal-buffer (auto-fill) " Normal text should also fill as expected\^@" " Normal text should also fill as expected\^@" )) (should (ert-equal-buffer (auto-fill) " Normal text should also fill as expected\^@" " Normal text should also fill as expected\^@" )) (should (ert-equal-buffer (auto-fill) " Normal text should also fill \^@as expected" " Normal text should also fill \^@as expected" )) )) (defun explicit-fill () "Wrapper for `fill-paragraph'." (let ((fc fill-column)) (rst-mode) (setq fill-column fc) (fill-paragraph) (untabify (point-min) (point-max)))) (ert-deftest fill-paragraph () "Tests for `fill-paragraph'." (let ((rst-indent-width 2) (rst-indent-field 2) (rst-indent-literal-normal 3) (rst-indent-literal-minimized 2) (rst-indent-comment 3) (fill-column 20)) (should (ert-equal-buffer (explicit-fill) " * This is a test with a fill column of 20\^@ " " * This is a test with a fill column of 20\^@ " )) (should (ert-equal-buffer (explicit-fill) " * This is a test \^@with a fill column of 20 " " * This is a test \^@with a fill column of 20 " )) (should (ert-equal-buffer (explicit-fill) " :Field: Does this work for fields?\^@ " " :Field: Does this work for fields?\^@ " )) (should (ert-equal-buffer (explicit-fill) " :Field: Does this work\^@ for fields? " " :Field: Does this work\^@ for fields? " )) (should (ert-equal-buffer (explicit-fill) " .. dir:: Yes, quite fine\^@ " " .. dir:: Yes, quite fine\^@ " )) (should (ert-equal-buffer (explicit-fill) " \^@.. dir:: Yes, quite fine " " \^@.. dir:: Yes, quite fine " )) (should (ert-equal-buffer (explicit-fill) " .. dir:: Yes, quite fine\^@ :f: Field " " .. dir:: Yes, quite fine\^@ :f: Field " )) (should (ert-equal-buffer (explicit-fill) " .. [CIT] X cit is citations are also filled\^@ " " .. [CIT] X cit is citations are also filled\^@ " )) (should (ert-equal-buffer (explicit-fill) " .. [CIT] X cit is citations are also filled\^@ " " .. [CIT] X cit is citations are also filled\^@ " )) (should (ert-equal-buffer (explicit-fill) " .. [CIT] X cit is citations are also filled\^@ " " .. [CIT] X cit is citations are also filled\^@ " )) (should (ert-equal-buffer (explicit-fill) " .. |s| r:: Dir ectives had problems\^@ " " .. |s| r:: Dir ectives had problems\^@ " )) (should (ert-equal-buffer (explicit-fill) " \^@.. |s| r:: Dir ectives had problems " " \^@.. |s| r:: Dir ectives had problems " )) (should (ert-equal-buffer (explicit-fill) " .. |s| r:: Dir ectives had problems\^@ " " .. |s| r:: Dir ectives had problems\^@ " )) (should (ert-equal-buffer (explicit-fill) " Normal \^@text should also fill as expected " " Normal \^@text should also fill as expected " )) (should (ert-equal-buffer (explicit-fill) " \^@Normal text should also fill as expected " " \^@Normal text should also fill as expected " )) (should (ert-equal-buffer (explicit-fill) " Normal text should also fill as expected\^@ " " Normal text should also fill as expected\^@ " )) (should (ert-equal-buffer (explicit-fill) " Normal text should also fill as expected Normal text should also fill as expected\^@ " " Normal text should also fill as expected Normal text should also fill as expected\^@ " )) (should (ert-equal-buffer (explicit-fill) " \^@Normal text should also fill as expected " " \^@Normal text should also fill as expected " )) )) (ert-deftest fill-paragraph-fixme () "Tests for `fill-paragraph'." :expected-result :failed (let ((rst-indent-width 2) (rst-indent-field 2) (rst-indent-literal-normal 3) (rst-indent-literal-minimized 2) (rst-indent-comment 3) (fill-column 20)) (should (ert-equal-buffer (explicit-fill) " \^@Normal text should also fill as expected " " \^@Normal text should also fill as expected " )) )) (defun explicit-fill-region () "Wrapper for `fill-region'." (let ((fc fill-column)) (rst-mode) (setq fill-column fc) (call-interactively 'fill-region) (untabify (point-min) (point-max)))) (ert-deftest fill-region () "Tests for `fill-region'." (let ((rst-indent-width 2) (rst-indent-field 2) (rst-indent-literal-normal 3) (rst-indent-literal-minimized 2) (rst-indent-comment 3) (fill-column 20)) (should (ert-equal-buffer (explicit-fill-region) "\^@ * This is a test with a fill column of 20 * This is a test with a fill column of 20 :Field: Does this work for fields? :Field: Does this work for fields? .. dir:: Yes, quite fine .. dir:: Yes, quite fine .. dir:: Yes, quite fine :f: Field for a directive .. [CIT] X cit is citations are also filled .. |s| r:: Dir ectives had problems .. |s| r:: Dir ectives had problems Normal text should also fill as expected Normal text should also fill as expected \^?" " * This is a test with a fill column of 20 * This is a test with a fill column of 20 :Field: Does this work for fields? :Field: Does this work for fields? .. dir:: Yes, quite fine .. dir:: Yes, quite fine .. dir:: Yes, quite fine :f: Field for a directive .. [CIT] X cit is citations are also filled .. |s| r:: Dir ectives had problems .. |s| r:: Dir ectives had problems Normal text should also fill as expected Normal text should also fill as expected \^@\^?" )) (should (ert-equal-buffer (explicit-fill-region) "\^@ * This is a test with a fill column of 20 * This is a test with a fill column of 20 :Field: Does this work for fields? :Field: Does this work for fields? .. dir:: Yes, quite fine .. dir:: Yes, quite fine .. dir:: Yes, quite fine :f: Field for a directive .. [CIT] X cit is citations are also filled .. |s| r:: Dir ectives had problems .. |s| r:: Dir ectives had problems Normal text should also fill as expected Normal text should also fill as expected \^?" " * This is a test with a fill column of 20 * This is a test with a fill column of 20 :Field: Does this work for fields? :Field: Does this work for fields? .. dir:: Yes, quite fine .. dir:: Yes, quite fine .. dir:: Yes, quite fine :f: Field for a directive .. [CIT] X cit is citations are also filled .. |s| r:: Dir ectives had problems .. |s| r:: Dir ectives had problems Normal text should also fill as expected Normal text should also fill as expected \^@\^?" )) )) docutils-0.12/tools/editors/emacs/tests/indent.el0000664000175000017500000001172312026705225024077 0ustar engelbertengelbert00000000000000;; Tests for functions around indentation (add-to-list 'load-path ".") (load "init" nil t) (init-rst-ert t) (ert-deftest indent-asserts () "Check some assertions." (should (equal ert-Buf-point-char "\^@")) (should (equal ert-Buf-mark-char "\^?")) ) (defun indent-for-tab (&optional count) "Wrapper to call `indent-for-tab-command' COUNT times defaulting to 1." (setq count (or count 1)) (rst-mode) (dotimes (i count) (indent-for-tab-command))) (ert-deftest indent-for-tab-command () "Tests for `indent-for-tab-command'." (let ((rst-indent-width 2) (rst-indent-field 2) (rst-indent-literal-normal 3) (rst-indent-literal-minimized 2) (rst-indent-comment 3)) (should (ert-equal-buffer (indent-for-tab) "\^@" t )) (should (ert-equal-buffer (indent-for-tab) " * a \^@" " * a \^@" )) (should (ert-equal-buffer (indent-for-tab) " * a \^@" " * a \^@" )) (should (ert-equal-buffer (indent-for-tab) " * a * b\^@" " * a * b\^@" )) (should (ert-equal-buffer (indent-for-tab) " * a * b\^@" " * a * b\^@" )) (should (ert-equal-buffer (indent-for-tab) " * a \^@* b" " * a \^@* b" )) (should (ert-equal-buffer (indent-for-tab) " * a \^@* b" " * a \^@* b" )) (should (ert-equal-buffer (indent-for-tab) " * a * b XV. c * d * e \^@" " * a * b XV. c * d * e \^@" )) (should (ert-equal-buffer (indent-for-tab) " * a * b XV. c * d * e \^@" " * a * b XV. c * d * e \^@" )) (should (ert-equal-buffer (indent-for-tab) " * a * b XV. c * d * e\^@" " * a * b XV. c * d * e\^@" )) (should (ert-equal-buffer (indent-for-tab) " * a * b XV. c * d * e\^@" " * a * b XV. c * d * e\^@" )) (should (ert-equal-buffer (indent-for-tab) " * a * b XV. c * d * e\^@" " * a * b XV. c * d * e\^@" )) (should (ert-equal-buffer (indent-for-tab) " * a * b XV. c * d * e\^@" " * a * b XV. c * d * e\^@" )) (should (ert-equal-buffer (indent-for-tab) " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" )) (should (ert-equal-buffer (indent-for-tab) " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" )) (should (ert-equal-buffer (indent-for-tab) " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" )) (should (ert-equal-buffer (indent-for-tab) " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" )) (should (ert-equal-buffer (indent-for-tab) " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" )) (should (ert-equal-buffer (indent-for-tab) " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" )) (should (ert-equal-buffer (indent-for-tab) " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" )) (should (ert-equal-buffer (indent-for-tab) " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" )) (should (ert-equal-buffer (indent-for-tab) " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" " .. [CIT] citation .. |sub| dir:: Same * a * b :f: val:: \^@" )) )) docutils-0.12/tools/editors/emacs/tests/re.el0000664000175000017500000007676512026705225023245 0ustar engelbertengelbert00000000000000;; Tests for the regular expression builder (add-to-list 'load-path ".") (load "init" nil t) (init-rst-ert t) (ert-deftest rst-re () "Tests `rst-re'." (should (equal (rst-re "xy") "xy")) (should (equal (rst-re ?A) "A")) (should (equal (rst-re ?$) "\\$")) (should (equal (rst-re 'exm-tag) "\\.\\.")) (should (equal (rst-re "xy" ?A ?$ 'exm-tag) "xyA\\$\\.\\.")) (should (equal (rst-re '(:seq "xy" ?A ?$ exm-tag)) "xyA\\$\\.\\.")) (should (equal (rst-re '(:shy "xy" ?A ?$ exm-tag)) "\\(?:xyA\\$\\.\\.\\)")) (should (equal (rst-re '(:grp "xy" ?A ?$ exm-tag)) "\\(xyA\\$\\.\\.\\)")) (should (equal (rst-re '(:alt "xy" ?A ?$ exm-tag)) "\\(?:xy\\|A\\|\\$\\|\\.\\.\\)")) (should (equal (rst-re '(:seq (:seq "xy" ?A ?$ exm-tag))) "xyA\\$\\.\\.")) (should (equal (rst-re '(:grp (:alt "xy" ?A ?$ exm-tag))) "\\(\\(?:xy\\|A\\|\\$\\|\\.\\.\\)\\)")) (should (equal (rst-re '(:alt (:grp "xy" ?A ?$ exm-tag))) "\\(?:\\(xyA\\$\\.\\.\\)\\)")) (should (equal (rst-re '(:alt "xy" ?A) '(:grp ?$ exm-tag)) "\\(?:xy\\|A\\)\\(\\$\\.\\.\\)")) (should-error (rst-re '(:unknown "xy"))) (should-error (rst-re [1])) ) (defun re-equal-modify-orig (orig loc refactored repls) (let ((case-fold-search nil)) (while (string-match "\\[ \t]" orig) ;; Transpose horizontal whitespace (setq orig (replace-match "[\t ]" t nil orig))) (while (string-match "\\\\s \\*\\$" orig) ;; Replace symbolic whitespace (setq orig (replace-match "[\t ]*$" t nil orig))) (dolist (regex-repl repls) (if (string-match (car regex-repl) orig) (setq orig (replace-match (cdr regex-repl) t t orig)) (error "Replacement regex /%s/ didn't match in '%s' for location '%s'" (car regex-repl) orig loc))) orig)) (defun re-equal (orig loc refactored &rest repls) "Compare regex ORIG at location LOC to REFACTORED. REPLS starts with a list of cons cells telling where regex in car is replaced by cdr in ORIG." (equal (re-equal-modify-orig orig loc refactored repls) refactored)) (defun re-equal-explain (orig loc refactored &rest repls) (setq orig (re-equal-modify-orig orig loc refactored repls)) (ert--explain-not-equal orig refactored)) (put 're-equal 'ert-explainer 're-equal-explain) (defun re-check-matches (orig loc refactored s pairs) "Check matches and return those pairs which didn't work" (let ((case-fold-search nil) failed) (dolist (pair pairs failed) (let ((orig-mtc (if (string-match orig s) (match-string (car pair) s))) (refa-mtc (if (string-match refactored s) (match-string (cdr pair) s)))) (if (not orig-mtc) (error "Original regex '%s' didn't match string '%s' for location '%s'" orig s loc) (if (not refa-mtc) (error "Refactored regex '%s' didn't match string '%s' for location '%s'" refactored s loc) (if (not (equal orig-mtc refa-mtc)) (push pair failed)))))))) (defun re-equal-matches (orig loc refactored matches &rest repls) "Like `re-equal'. However, if MATCHES is non-nil it must be a list with a string and cons cells each consisting of two numbers. For each cons cell the string is matched with ORIG and REFACTORED and the numbered matches are compared." (and (equal (re-equal-modify-orig orig loc refactored repls) refactored) (not (re-check-matches orig loc refactored (car matches) (cdr matches))))) (defun re-equal-matches-explain (orig loc refactored matches &rest repls) (if (not (equal (re-equal-modify-orig orig loc refactored repls) refactored)) (apply 're-equal-explain orig loc refactored repls) (let (result) (dolist (failed (re-check-matches orig loc refactored (car matches) (cdr matches)) result) (push (list 'matchers-didnt-match (car failed) (cdr failed)) result))))) (put 're-equal-matches 'ert-explainer 're-equal-matches-explain) (ert-deftest rst-re-refactoring () "Test the refactorings done based on rst_el_1_68." ;; Any comment or string "=== rst.el.~rst_el_1_68~:..." gives the line number ;; of the refactored code in the original file for the previous expression. (let* ((rst-bullets '(?- ?* ?+)) ;; === rst.el.~rst_el_1_68~:451 (rst-re-bullets (format "\\([%s][ \t]\\)[^ \t]" (regexp-quote (concat rst-bullets)))) ;; === rst.el.~rst_el_1_68~:1604 ;; More parameters (c ?*) (len 10) (char ?+) (adornment "$$$$") (ado-re (regexp-quote adornment)) (fromchar ?.) ) (should (re-equal "^\\.\\. " "=== rst.el.~rst_el_1_68~:398" (rst-re "^" 'exm-sta) (cons " $" "[ ]+") ;; Any whitespace may follow )) (should (re-equal "^[ \t]*\\S *\\w\\S *" "=== rst.el.~rst_el_1_68~:567" (rst-re 'lin-beg "\\S *\\w\\S *") )) (should (re-equal "::[ \t]*$" "=== rst.el.~rst_el_1_68~:591" (rst-re 'dcl-tag 'lin-end) )) (should (re-equal "\\.\\.\\.[ \t]*$" "=== rst.el.~rst_el_1_68~:592" (rst-re 'ell-tag 'lin-end) )) (should (re-equal ".[ \t]*$" "=== rst.el.~rst_el_1_68~:594" (rst-re "." 'lin-end) )) (should (re-equal "^[ \t]+" "=== rst.el.~rst_el_1_68~:605" (rst-re 'hws-sta) (cons "^^" "") ;; No need to anchor for looking-at )) (should (re-equal "^[ \t]*$" "=== rst.el.~rst_el_1_68~:744" (rst-re 'lin-end) (cons "^^" "") ;; No need to anchor for looking-at )) (should (re-equal "^[ \t]*$" "=== rst.el.~rst_el_1_68~:1517" (rst-re 'lin-end) (cons "^^" "") ;; No need to anchor for looking-at )) (should (re-equal "^[ \t]*$" "=== rst.el.~rst_el_1_68~:1545" (rst-re 'lin-end) (cons "^^" "") ;; No need to anchor for looking-at )) (should (re-equal "^[ \t]*$" "=== rst.el.~rst_el_1_68~:1548" (rst-re 'lin-end) (cons "^^" "") ;; No need to anchor for looking-at )) (should (re-equal "[0-9]+" "=== rst.el.~rst_el_1_68~:1657" (rst-re 'num-tag) )) (should (re-equal "[IVXLCDMivxlcdm]+" "=== rst.el.~rst_el_1_68~:1661" (rst-re 'rom-tag) )) (should (re-equal "[IVXLCDMivxlcdm]+" "=== rst.el.~rst_el_1_68~:1677" (rst-re 'rom-tag) )) (should (re-equal "[a-zA-Z]" "=== rst.el.~rst_el_1_68~:1685" (rst-re 'ltr-tag) )) (should (re-equal "[ \t\n]*\\'" "=== rst.el.~rst_el_1_68~:1762" (rst-re "[ \t\n]*\\'") )) (should (re-equal "\\S .*\\S " "=== rst.el.~rst_el_1_68~:1767" (rst-re "\\S .*\\S ") )) (should (re-equal "[ \t]*$" "=== rst.el.~rst_el_1_68~:2066" (rst-re 'lin-end) )) (should (re-equal "[ \t]*$" "=== rst.el.~rst_el_1_68~:2366" (rst-re 'lin-end) )) (should (re-equal "^[ \t]*$" "=== rst.el.~rst_el_1_68~:2414" (rst-re 'lin-end) (cons "^^" "") ;; No need to anchor for looking-at )) (should (re-equal "[ \t]*$" "=== rst.el.~rst_el_1_68~:2610" (rst-re 'lin-end) )) (should (re-equal "[ \t]*$" "=== rst.el.~rst_el_1_68~:2612" (rst-re 'lin-end) )) (should (re-equal "[ \t]*$" "=== rst.el.~rst_el_1_68~:2645" (rst-re 'lin-end) )) (should (re-equal "[^ \t]\\|[ \t]*\\.\\.[^ \t]\\|.*::$" "=== rst.el.~rst_el_1_68~:3177" (rst-re '(:alt "[^ \t]" (:seq hws-tag exm-tag "[^ \t]") (:seq ".*" dcl-tag lin-end))) (cons "^" "\\(?:") (cons "$" "\\)") ;; Add outermost shy group (cons "::\\$" "::[ ]*$") ;; Allow trailing space after double ;; colon )) (should (re-equal "\\s *$" "=== rst.el.~rst_el_1_68~:3209" (rst-re 'lin-end) )) (should (re-equal "^\\s *$" "=== rst.el.~rst_el_1_68~:3215" (rst-re 'linemp-tag) )) (should (re-equal "\\s *$" "=== rst.el.~rst_el_1_68~:3253" (rst-re 'lin-end) )) (should (re-equal "\\s *" "=== rst.el.~rst_el_1_68~:3256" (rst-re 'hws-tag) (cons "\\\\s \\*" "[\t ]*") ;; Replace symbolic by real whitespace )) (should (re-equal "\\s *$" "=== rst.el.~rst_el_1_68~:3261" (rst-re 'lin-end) )) (should (re-equal "\\s *" "=== rst.el.~rst_el_1_68~:3268" (rst-re 'hws-tag) (cons "\\\\s \\*" "[\t ]*") ;; Replace symbolic by real whitespace )) (should (re-equal (regexp-quote adornment) "=== rst.el.~rst_el_1_68~:3346" (rst-re (regexp-quote adornment)) )) (should (re-equal "\\s *$" "=== rst.el.~rst_el_1_68~:3354" (rst-re 'lin-end) )) (should (re-equal "\\s *$" "=== rst.el.~rst_el_1_68~:3358" (rst-re 'lin-end) )) (should (re-equal "\\s *$" "=== rst.el.~rst_el_1_68~:3374" (rst-re 'lin-end) )) (should (re-equal (concat "\\(" ado-re "\\)\\s *$") "=== rst.el.~rst_el_1_68~:3377" (rst-re (list :grp ado-re) 'lin-end) )) (should (re-equal (concat "\\(" ado-re "\\)\\s *$") "=== rst.el.~rst_el_1_68~:3393" (rst-re (list :grp ado-re) 'lin-end) )) (should (re-equal (concat "^" (regexp-quote (string fromchar)) "+\\( *\\)$") "=== rst.el.~rst_el_1_68~:3590" (rst-re "^" fromchar "+\\( *\\)$") )) (should (re-equal "\f\\|>*[ \t]*$\\|>*[ \t]*[-+*] \\|>*[ \t]*[0-9#]+\\. " "=== rst.el.~rst_el_1_68~:391" (rst-re '(:alt "\f" lin-end (:seq hws-tag itmany-sta-1))) (cons "^" "\\(?:") (cons "$" "\\)") ;; Add outermost shy group (cons (regexp-quote "[-+*] \\|>*[ ]*[0-9#]+\\. ") "\\(\\(?:\\(?:\\(?:[a-zA-Z]\\|[0-9]+\\|[IVXLCDMivxlcdm]+\\|#\\)\\.\\|(?\\(?:[a-zA-Z]\\|[0-9]+\\|[IVXLCDMivxlcdm]+\\|#\\))\\)\\|[-*+\u2022\u2023\u2043]\\)\\)[ ]+" ) ;; Now matches all items (cons ">\\*" "") ;; Remove ">" prefix (cons ">\\*" "") ;; Remove another ">" prefix (cons "\\[\t ]\\+" "\\(?:[\t ]+\\|$\\)") ;; Item tag needs no ;; trailing whitespace )) (should (re-equal (format "[%s]+[ \t]*$" (char-to-string c)) "=== rst.el.~rst_el_1_68~:587" (rst-re c "+" 'lin-end) (cons "\\[\\*]" "\\*") ;; Use quoting instead of char class )) (should (re-equal (concat "^" (regexp-quote (make-string len char)) "$") "=== rst.el.~rst_el_1_68~:941" (rst-re "^" char (format "\\{%d\\}" len) "$") (cons "\\(\\\\\\+\\)\\{9\\}\\$" "\\{10\\}$") ;; Use regex repeat instead of explicit repeat )) (should (re-equal (format "#.\\|[%s]" (regexp-quote (concat rst-bullets))) "=== rst.el.~rst_el_1_68~:1653" (rst-re '(:alt enmaut-tag bul-tag)) (cons "^" "\\(?:") (cons "$" "\\)") ;; Add outermost shy group (cons (regexp-quote "[-\\*\\+]") "[-*+\u2022\u2023\u2043]") ;; Wrongly quoted characters in ;; class and more bullets (cons "#\\." "\\(?:#\\.\\|(?#)\\)") ;; Use all auto enumerators )) (should (re-equal "[a-zA-Z]+" "=== rst.el.~rst_el_1_68~:1672" (rst-re 'ltr-tag) (cons "\\+$" "") ;; Wrong in source )) (should (re-equal rst-re-bullets "=== rst.el.~rst_el_1_68~:1735" (rst-re 'bul-sta) (cons (regexp-quote "[-\\*\\+]") "[-*+\u2022\u2023\u2043]") ;; Wrongly quoted characters in ;; class and more bullets (cons "\\[^ \t]" "") ;; Accept bullets without content (cons "^\\\\(" "") (cons "\\\\)" "") ;; Remove superfluous group (cons "$" "+") ;; Allow more whitespace (cons "\\[\t ]\\+" "\\(?:[\t ]+\\|$\\)") ;; Item tag needs no ;; trailing whitespace )) (should (re-equal "^\\.\\. contents[ \t]*::\\(.*\\)\n\\([ \t]+:\\w+:.*\n\\)*\\.\\." "=== rst.el.~rst_el_1_68~:2056" (rst-re "^" 'exm-sta "contents" 'dcl-tag ".*\n" "\\(?:" 'hws-sta 'fld-tag ".*\n\\)*" 'exm-tag) (cons " contents\\[\t ]\\*" "[\t ]+contents") ;; Any whitespace before but no after (cons "\\\\(\\.\\*\\\\)" ".*") ;; Remove superfluous group (cons "\\\\(" "\\(?:") ;; Make group shy (cons ":\\\\w\\+:" ":\\(?:[^:\n]\\|\\\\:\\)+:") ;; Use improved ;; field tag )) (should (re-equal "[ \t]+[^ \t]" "=== rst.el.~rst_el_1_68~:2065" (rst-re 'hws-sta "\\S ") (cons "\\[^ \t]" "\\S ") ;; Require non-whitespace instead ;; of only non-horizontal whitespace )) )) (ert-deftest rst-re-refactoring-complicated () "Try to test complicated refactorings done based on rst_el_1_68." :expected-result :failed ;; These have been reviewed logically and are ok (let* ((rst-bullets '(?- ?* ?+)) ;; === rst.el.~rst_el_1_68~:451 (rst-re-enumerator "\\(?:[a-zA-Z]\\|[0-9IVXLCDMivxlcdm]+\\)") ;; === rst.el.~rst_el_1_68~:1608 (rst-re-enumerations (format "^[ \t]*\\(%s.\\|(?%s)\\)[ \t]" rst-re-enumerator rst-re-enumerator)) ;; === rst.el.~rst_el_1_68~:1610 (rst-re-items (format "^[ \t]*\\([%s]\\|\\(#\\|%s\\)\\.\\|(?%s)\\)[ \t]" (regexp-quote (concat rst-bullets)) rst-re-enumerator rst-re-enumerator)) ;; === rst.el.~rst_el_1_68~:1616 ;; More parameters (char ?+) ) (should (re-equal rst-re-items "=== rst.el.~rst_el_1_68~:2718" (rst-re 'itmany-sta-1) (cons "^^\\[\t ]\\*" "") ;; Wrongly anchored at the beginning of ;; the line (cons (regexp-quote "\\(#\\|\\(?:[a-zA-Z]\\|[0-9IVXLCDMivxlcdm]+\\)\\)") "\\(?:[a-zA-Z]\\|[0-9]+\\|[IVXLCDMivxlcdm]+\\|#\\)" ) ;; Replace counter for "\\." (cons (regexp-quote "\\(?:[a-zA-Z]\\|[0-9IVXLCDMivxlcdm]+\\)") "\\(?:[a-zA-Z]\\|[0-9]+\\|[IVXLCDMivxlcdm]+\\|#\\)" ) ;; Replace counter for "(?)" (cons "$" "+") ;; Allow more whitespace (cons "^\\\\(" "\\(\\(?:") (cons "\\[\t ]\\+$" "\\)[\t ]+" ) ;; Add superfluous shy group (cons (regexp-quote "[-\\*\\+]\\|") "") ;; Remove wrongly quoted ;; characters (cons (regexp-quote "\\)\\)[\t ]+") "\\|[-*+\u2022\u2023\u2043]\\)\\)[\t ]+" ) ;; Re-add bullets )) (should (re-equal rst-re-items "=== rst.el.~rst_el_1_68~:2724" (rst-re 'itmany-beg-1) )) (should (re-equal rst-re-items "=== rst.el.~rst_el_1_68~:1649" (rst-re 'itmany-beg-1) )) (should (re-equal rst-re-enumerations "=== rst.el.~rst_el_1_68~:1671" (rst-re 'enmexp-beg) )) (should (re-equal rst-re-items "=== rst.el.~rst_el_1_68~:1719" (rst-re 'itmany-beg-1) )) (should (re-equal (concat "\\(?:" "\\(\\(?:[0-9a-zA-Z#]\\{1,3\\}[.):-]\\|[*+-]\\)[ \t]+\\)[^ \t\n]" "\\|" (format "\\(%s%s+[ \t]+\\)[^ \t\n]" (regexp-quote (char-to-string char)) (regexp-quote (char-to-string char))) "\\)") "=== rst.el.~rst_el_1_68~:2430" (rst-re `(:grp (:alt itmany-tag (:seq ,(char-after) "\\{2,\\}")) hws-sta) "\\S ") (cons "^\\\\(\\?:" "") (cons "\\\\)$" "") ;; Remove superfluous ;; shy group (cons (regexp-quote "[0-9a-zA-Z#]\\{1,3\\}[.):-]\\|[*+-]") "\\(\\(?:\\(?:\\(?:[a-zA-Z]\\|[0-9]+\\|[IVXLCDMivxlcdm]+\\|#\\)\\.\\|(?\\(?:[a-zA-Z]\\|[0-9]+\\|[IVXLCDMivxlcdm]+\\|#\\))\\)\\|[-*+\u2022\u2023\u2043]\\)\\)" ) ;; Replace wrong item tag by correct one (cons (regexp-quote "\\+\\++") "\\+\\{2,\\}") ;; Use regex repeat instead of explicit repeat (cons "\\[^ \t\n]" "\\S ") ;; Use symbolic non-whitespace (cons "\\[^ \t\n]" "\\S ") ;; Use symbolic non-whitespace again (cons "\\\\S " "") ;; Factor out symbolic non-whitespace )) )) (ert-deftest rst-re-refactoring-font-lock () "Test the refactorings in font-lock done based on rst_el_1_68." ;; Any comment or string "=== rst.el.~rst_el_1_68~:..." gives the line number ;; of the refactored code in the original file for the previous expression. (let* ((rst-use-char-classes t) (rst-use-unicode t) ;; horizontal white space (re-hws "[\t ]") ;; beginning of line with possible indentation (re-bol (concat "^" re-hws "*")) ;; Separates block lead-ins from their content (re-blksep1 (concat "\\(" re-hws "+\\|$\\)")) ;; explicit markup tag (re-emt "\\.\\.") ;; explicit markup start (re-ems (concat re-emt re-hws "+")) ;; inline markup prefix (re-imp1 (concat "\\(^\\|" re-hws "\\|[-'\"([{<" (if rst-use-unicode "\u2018\u201c\u00ab\u2019" "") "/:]\\)")) ;; inline markup suffix (re-ims1 (concat "\\(" re-hws "\\|[]-'\")}>" (if rst-use-unicode "\u2019\u201d\u00bb" "") "/:.,;!?\\]\\|$\\)")) ;; symbol character (re-sym1 "\\(\\sw\\|\\s_\\)") ;; inline markup content begin (re-imbeg2 "\\(\\S \\|\\S \\([^") ;; There seems to be a bug leading to error "Stack overflow in regexp ;; matcher" when "|" or "\\*" are the characters searched for (re-imendbegbeg (if (< emacs-major-version 21) "]" "\\]\\|\\\\.")) ;; inline markup content end (re-imendbeg (concat re-imendbegbeg "\\)\\{0," (format "%d" rst-max-inline-length) "\\}[^\t ")) (re-imendend "\\\\]\\)") ;; inline markup content without asterisk (re-ima2 (concat re-imbeg2 "*" re-imendbeg "*" re-imendend)) ;; inline markup content without backquote (re-imb2 (concat re-imbeg2 "`" re-imendbeg "`" re-imendend)) ;; inline markup content without vertical bar (re-imv2 (concat re-imbeg2 "|" re-imendbeg "|" re-imendend)) ;; Supported URI schemes (re-uris1 "\\(acap\\|cid\\|data\\|dav\\|fax\\|file\\|ftp\\|gopher\\|http\\|https\\|imap\\|ldap\\|mailto\\|mid\\|modem\\|news\\|nfs\\|nntp\\|pop\\|prospero\\|rtsp\\|service\\|sip\\|tel\\|telnet\\|tip\\|urn\\|vemmi\\|wais\\)") ;; Line starting with adornment and optional whitespace; complete ;; adornment is in (match-string 1); there must be at least 3 ;; characters because otherwise explicit markup start would be ;; recognized (re-ado2 (concat "^\\(\\([" (if rst-use-char-classes "^[:word:][:space:][:cntrl:]" "^\\w \t\x00-\x1F") "]\\)\\2\\2+\\)" re-hws "*$")) ) (should (re-equal-matches ;; `Bullet Lists`_ (concat re-bol "\\([-*+]" re-blksep1 "\\)") "=== rst.el.~rst_el_1_68~:3011" (rst-re 'lin-beg '(:grp bul-sta)) (list "*" (cons 1 1)) (cons (regexp-quote "[-*+]") "[-*+\u2022\u2023\u2043]") ;; More bullets (cons "\\\\(\\[\t " "\\(?:[\t ") ;; Make a group shy )) (should (re-equal-matches ;; `Enumerated Lists`_ (concat re-bol "\\((?\\(#\\|[0-9]+\\|[A-Za-z]\\|[IVXLCMivxlcm]+\\)[.)]" re-blksep1 "\\)") "=== rst.el.~rst_el_1_68~:3015" (rst-re 'lin-beg '(:grp enmany-sta)) (list " (#) Item" (cons 1 1)) (cons (regexp-quote "(?\\(#\\|[0-9]+\\|[A-Za-z]\\|[IVXLCMivxlcm]+\\)[.)]") "\\(?:\\(?:[a-zA-Z]\\|[0-9]+\\|[IVXLCDMivxlcdm]+\\|#\\)\\.\\|(?\\(?:[a-zA-Z]\\|[0-9]+\\|[IVXLCDMivxlcdm]+\\|#\\))\\)" ) ;; Enumeration tags are more sophisticated (cons "\\\\(\\[\t " "\\(?:[\t ") ;; Make a group shy )) (should (re-equal-matches ;; `Field Lists`_ (concat re-bol "\\(:[^:\n]+:\\)" re-blksep1) "=== rst.el.~rst_el_1_68~:3021" (rst-re 'lin-beg '(:grp fld-tag) 'bli-sfx) (list " :some field: " (cons 1 1)) (cons "\\[^:\n]" "\\(?:[^:\n]\\|\\\\:\\)") ;; Field name more ;; sophisticated (cons "\\\\(\\[\t " "\\(?:[\t ") ;; Make a group shy )) (should (re-equal-matches ;; `Option Lists`_ (concat re-bol "\\(\\(\\(\\([-+/]\\|--\\)\\sw\\(-\\|\\sw\\)*" "\\([ =]\\S +\\)?\\)\\(,[\t ]\\)?\\)+\\)\\($\\|[\t ]\\{2\\}\\)") "=== rst.el.~rst_el_1_68~:3025" (rst-re 'lin-beg '(:grp opt-tag (:shy optsep-tag opt-tag) "*") '(:alt "$" (:seq hws-prt "\\{2\\}"))) (list " --len=length, -l length Explanation" (cons 1 1)) (cons (regexp-quote "\\(\\(\\(\\([-+/]\\|--\\)\\sw\\(-\\|\\sw\\)*\\([ =]\\S +\\)?\\)\\(,[ ]\\)?\\)+\\)") "\\(\\(?:\\(?:[-+/]\\|--\\)\\sw\\(?:-\\|\\sw\\)*\\(?:[ =]\\S +\\)?\\)\\(?:\\(?:,[ ]\\)\\(?:\\(?:[-+/]\\|--\\)\\sw\\(?:-\\|\\sw\\)*\\(?:[ =]\\S +\\)?\\)\\)*\\)" ) ;; Option recognition more sophisticated (cons "\\\\(\\$" "\\(?:$") ;; Make a group shy )) (should (re-equal-matches ;; `Line Blocks`_ (concat re-bol "\\(|" re-blksep1 "\\)[^|\n]*$") "=== rst.el.~rst_el_1_68~:3030" (rst-re 'lin-beg '(:grp "|" bli-sfx) "[^|\n]*$") (list " | Some text" (cons 1 1)) (cons "\\\\(\\[\t " "\\(?:[\t ") ;; Make a group shy )) (should (re-equal-matches ;; `Footnotes`_ / `Citations`_ (concat re-bol "\\(" re-ems "\\[[^[\n]+\\]\\)" re-blksep1) "=== rst.el.~rst_el_1_68~:3038" (rst-re 'lin-beg '(:grp exm-sta fnc-tag) 'bli-sfx) (list ".. [#]" (cons 1 1)) (cons "\\[^\\[" "[^]") ;; Error correction in old code (cons "\\\\]" "]") ;; Remove superfluous quote (cons "\\\\(\\[\t " "\\(?:[\t ") ;; Make a group shy )) (should (re-equal-matches ;; `Directives`_ / `Substitution Definitions`_ (concat re-bol "\\(" re-ems "\\)\\(\\(|[^|\n]+|[\t ]+\\)?\\)\\(" re-sym1 "+::\\)" re-blksep1) "=== rst.el.~rst_el_1_68~:3042" (rst-re 'lin-beg '(:grp exm-sta) '(:grp (:shy subdef-tag hws-sta) "?") '(:grp sym-tag dcl-tag) 'bli-sfx) (list ".. |attr| replace:: val" (cons 1 1) (cons 2 2) (cons 4 3)) (cons "\\\\(|" "\\(?:|") ;; Make a group shy (cons "\\[^|\n]\\+" "\\(?:\\S \\|\\S \\(?:[^|\\\n]\\|\\\\.\\)\\{0,1000\\}[^ |\\]\\)" ) ;; Symbol name more sophisticated (cons (regexp-quote "\\(\\sw\\|\\s_\\)+") "\\(?:\\sw+\\(?:[-+.:_]\\sw+\\)*\\)") ;; New syntax for ;; symbols (cons "\\\\(\\[\t " "\\(?:[\t ") ;; Make a group shy )) (should (re-equal-matches ;; `Hyperlink Targets`_ (concat re-bol "\\(" re-ems "_\\([^:\\`\n]\\|\\\\.\\|`[^`\n]+`\\)+:\\)" re-blksep1) "=== rst.el.~rst_el_1_68~:3049" (rst-re 'lin-beg '(:grp exm-sta "_" (:alt (:seq "`" ilcbkqdef-tag "`") (:seq (:alt "[^:\\\n]" "\\\\.") "+")) ":") 'bli-sfx) (list ".. _`some\\: target`:" (cons 1 1)) (cons (regexp-quote "\\([^:\\`\n]\\|\\\\.\\|`[^`\n]+`\\)+") "\\(?:`\\(?:\\S \\|\\S \\(?:[^`\\\n]\\|\\\\.\\)\\{0,1000\\}[^ `\\]\\)`\\|\\(?:[^:\\\n]\\|\\\\.\\)+\\)" ) ;; Hyperlink name recognition more sophisticated (cons "\\\\(\\[\t " "\\(?:[\t ") ;; Make a group shy )) (should (re-equal-matches ;; `Hyperlink Targets`_ (concat re-bol "\\(__\\)" re-blksep1) "=== rst.el.~rst_el_1_68~:3053" (rst-re 'lin-beg '(:grp "__") 'bli-sfx) (list " __" (cons 1 1)) (cons "\\\\(\\[\t " "\\(?:[\t ") ;; Make a group shy )) (should (re-equal-matches ;; `Strong Emphasis`_ (concat re-imp1 "\\(\\*\\*" re-ima2 "\\*\\*\\)" re-ims1) "=== rst.el.~rst_el_1_68~:3062" (rst-re 'ilm-pfx '(:grp "\\*\\*" ilcast-tag "\\*\\*") 'ilm-sfx) (list "abc **def** ghi" (cons 2 1)) (cons "^\\\\(" "\\(?:") ;; Make a group shy (cons "\\\\(\\\\S" "\\(?:\\S") ;; Make a group shy (cons "\\\\(\\[^" "\\(?:[^") ;; Make a group shy (cons (regexp-quote "\\\\]") "\\]") ;; Remove superfluous quote (cons (regexp-quote "\\|$") "") (cons (regexp-quote "\\([\t ]") "\\(?:$\\|[\t ]") ;; Move "$" in regex and make a group shy )) (should (re-equal-matches ;; `Emphasis`_ (concat re-imp1 "\\(\\*" re-ima2 "\\*\\)" re-ims1) "=== rst.el.~rst_el_1_68~:3066" (rst-re 'ilm-pfx '(:grp "\\*" ilcast-tag "\\*") 'ilm-sfx) (list "*x*" (cons 2 1)) (cons "^\\\\(" "\\(?:") ;; Make a group shy (cons "\\\\(\\\\S" "\\(?:\\S") ;; Make a group shy (cons "\\\\(\\[^" "\\(?:[^") ;; Make a group shy (cons (regexp-quote "\\\\]") "\\]") ;; Remove superfluous quote (cons (regexp-quote "\\|$") "") (cons (regexp-quote "\\([\t ]") "\\(?:$\\|[\t ]") ;; Move "$" in regex and make a group shy )) (should (re-equal-matches ;; `Inline Literals`_ (concat re-imp1 "\\(``" re-imb2 "``\\)" re-ims1) "=== rst.el.~rst_el_1_68~:3070" (rst-re 'ilm-pfx '(:grp "``" ilcbkq-tag "``") 'ilm-sfx) (list "``co de``" (cons 2 1)) (cons "^\\\\(" "\\(?:") ;; Make a group shy (cons "\\\\(\\\\S" "\\(?:\\S") ;; Make a group shy (cons "\\\\(\\[^" "\\(?:[^") ;; Make a group shy (cons (regexp-quote "\\\\]") "\\]") ;; Remove superfluous quote (cons (regexp-quote "\\|$") "") (cons (regexp-quote "\\([\t ]") "\\(?:$\\|[\t ]") ;; Move "$" in regex and make a group shy )) (should (re-equal-matches ;; `Inline Internal Targets`_ (concat re-imp1 "\\(_`" re-imb2 "`\\)" re-ims1) "=== rst.el.~rst_el_1_68~:3074" (rst-re 'ilm-pfx '(:grp "_`" ilcbkq-tag "`") 'ilm-sfx) (list "_`Inline\ntarget`" (cons 2 1)) (cons "^\\\\(" "\\(?:") ;; Make a group shy (cons "\\\\(\\\\S" "\\(?:\\S") ;; Make a group shy (cons "\\\\(\\[^" "\\(?:[^") ;; Make a group shy (cons (regexp-quote "\\\\]") "\\]") ;; Remove superfluous quote (cons (regexp-quote "\\|$") "") (cons (regexp-quote "\\([\t ]") "\\(?:$\\|[\t ]") ;; Move "$" in regex and make a group shy )) (should (re-equal-matches ;; `Hyperlink References`_ (concat re-imp1 "\\(\\(`" re-imb2 "`\\|\\(\\sw\\(\\sw\\|-\\)+\\sw\\)\\)__?\\)" re-ims1) "=== rst.el.~rst_el_1_68~:3079" (rst-re 'ilm-pfx '(:grp (:alt (:seq "`" ilcbkq-tag "`") (:seq "\\sw" (:alt "\\sw" "-") "+\\sw")) "__?") 'ilm-sfx) (list "<`xxx`__>" (cons 2 1)) (cons "^\\\\(" "\\(?:") ;; Make a group shy (cons "\\\\(\\\\S" "\\(?:\\S") ;; Make a group shy (cons "\\\\(\\[^" "\\(?:[^") ;; Make a group shy (cons (regexp-quote "\\\\]") "\\]") ;; Remove superfluous quote (cons (regexp-quote "\\|$") "") (cons (regexp-quote "\\([\t ]") "\\(?:$\\|[\t ]") ;; Move "$" in regex and make a group shy (cons "\\\\(`" "\\(?:`") ;; Make a group shy (cons "\\\\(\\\\sw" "\\sw") (cons "\\\\sw\\\\)" "\\sw") ;; Remove a group (cons "sw\\\\(\\\\sw" "sw\\(?:\\sw") ;; Make a group shy )) (should (re-equal-matches ;; `Interpreted Text`_ (concat re-imp1 "\\(\\(:" re-sym1 "+:\\)?\\)\\(`" re-imb2 "`\\)\\(\\(:" re-sym1 "+:\\)?\\)" re-ims1) "=== rst.el.~rst_el_1_68~:3083" (rst-re 'ilm-pfx '(:grp (:shy ":" sym-tag ":") "?") '(:grp "`" ilcbkq-tag "`") '(:grp (:shy ":" sym-tag ":") "?") 'ilm-sfx) (list "`Interpreted`" (cons 2 1) (cons 5 2) (cons 8 3)) (cons "^\\\\(" "\\(?:") ;; Make a group shy (cons "\\\\(\\\\S" "\\(?:\\S") ;; Make a group shy (cons "\\\\(\\[^" "\\(?:[^") ;; Make a group shy (cons "\\\\(:" "\\(?::") ;; Make a group shy (cons "\\\\(:" "\\(?::") ;; Make a group shy (cons (regexp-quote "\\(\\sw\\|\\s_\\)+") "\\(?:\\sw+\\(?:[-+.:_]\\sw+\\)*\\)") ;; New syntax for ;; symbols (cons (regexp-quote "\\(\\sw\\|\\s_\\)+") "\\(?:\\sw+\\(?:[-+.:_]\\sw+\\)*\\)") ;; New syntax for ;; symbols (cons (regexp-quote "\\\\]") "\\]") ;; Remove superfluous quote (cons (regexp-quote "\\|$") "") (cons (regexp-quote "\\([\t ]") "\\(?:$\\|[\t ]") ;; Move "$" in regex and make a group shy )) (should (re-equal-matches ;; `Footnote References`_ / `Citation References`_ (concat re-imp1 "\\(\\[[^]]+\\]_\\)" re-ims1) "=== rst.el.~rst_el_1_68~:3090" (rst-re 'ilm-pfx '(:grp fnc-tag "_") 'ilm-sfx) (list "[1]_" (cons 2 1)) (cons "^\\\\(" "\\(?:") ;; Make a group shy (cons "]]" "]\n]") ;; A reference may not contain \n (cons "\\\\]" "]") ;; Remove superfluous quote (cons (regexp-quote "\\|$") "") (cons (regexp-quote "\\([\t ]") "\\(?:$\\|[\t ]") ;; Move "$" in regex and make a group shy )) (should (re-equal-matches ;; `Substitution References`_ (concat re-imp1 "\\(|" re-imv2 "|\\)" re-ims1) "=== rst.el.~rst_el_1_68~:3094" (rst-re 'ilm-pfx '(:grp sub-tag) 'ilm-sfx) (list "|attr|" (cons 2 1)) (cons "^\\\\(" "\\(?:") ;; Make a group shy (cons "\\\\(\\\\S" "\\(?:\\S") ;; Make a group shy (cons (regexp-quote "\\([^|") "\\(?:[^|") ;; Make a group shy (cons "\\\\]" "]") ;; Remove superfluous quote (cons "\\\\]" "]") ;; Remove superfluous quote (cons "\\[^|]" "[^|\\]") ;; Improve recognition (cons (regexp-quote "\\|$") "") (cons (regexp-quote "\\([\t ]") "\\(?:$\\|[\t ]") ;; Move "$" in regex and make a group shy )) (should (re-equal-matches ;; `Standalone Hyperlinks`_ (concat re-imp1 "\\(" re-uris1 ":\\S +\\)" re-ims1) "=== rst.el.~rst_el_1_68~:3099" (rst-re 'ilm-pfx '(:grp uri-tag ":\\S +") 'ilm-sfx) (list "http://example.com/" (cons 2 1)) (cons "^\\\\(" "\\(?:") ;; Make a group shy (cons "\\\\(acap" "\\(?:acap") ;; Make a group shy (cons (regexp-quote "\\|$") "") (cons (regexp-quote "\\([\t ]") "\\(?:$\\|[\t ]") ;; Move "$" in regex and make a group shy )) (should (re-equal-matches ;; `Standalone Hyperlinks`_ (concat re-imp1 "\\(" re-sym1 "+@" re-sym1 "+\\)" re-ims1) "=== rst.el.~rst_el_1_68~:3102" (rst-re 'ilm-pfx '(:grp sym-tag "@" sym-tag ) 'ilm-sfx) (list "someone@example" (cons 2 1)) (cons "^\\\\(" "\\(?:") ;; Make a group shy (cons (regexp-quote "\\(\\sw\\|\\s_\\)+") "\\(?:\\sw+\\(?:[-+.:_]\\sw+\\)*\\)") ;; New syntax for ;; symbols (cons (regexp-quote "\\(\\sw\\|\\s_\\)+") "\\(?:\\sw+\\(?:[-+.:_]\\sw+\\)*\\)") ;; New syntax for ;; symbols (cons (regexp-quote "\\|$") "") (cons (regexp-quote "\\([\t ]") "\\(?:$\\|[\t ]") ;; Move "$" in regex and make a group shy )) (should (re-equal ;; Sections_ / Transitions_ re-ado2 "=== rst.el.~rst_el_1_68~:3109" (rst-re 'ado-beg-2-1) (cons "\\^\\[:word:]\\[:space:]\\[:cntrl:]" "]!\"#$%&'()*+,./:;<=>?@[\\^_`{|}~-") ;; Use real adornment ;; characters (cons "2\\+" "{2,\\}") ;; Use repeat count )) (should (re-equal ;; `Comments`_ (concat re-bol "\\(" re-ems "\\)\[^[|_\n]\\([^:\n]\\|:\\([^:\n]\\|$\\)\\)*$") "=== rst.el.~rst_el_1_68~:3128" (rst-re 'lin-beg '(:grp exm-sta) "[^\[|_\n]" '(:alt "[^:\n]" (:seq ":" (:alt "[^:\n]" "$"))) "*$") (cons "\\\\(\\[^:" "\\(?:[^:") ;; Make a group shy (cons "\\\\(\\[^:" "\\(?:[^:") ;; Make a group shy )) (should (re-equal-matches ;; `Comments`_ (concat re-bol "\\(" re-emt "\\)\\(\\s *\\)$") "=== rst.el.~rst_el_1_68~:3135" (rst-re 'lin-beg '(:grp exm-tag) '(:grp hws-tag) "$") (list ".. " (cons 1 1) (cons 2 2)) (cons "\\\\s " "[\t ]") ;; Only horizontal space )) (should (re-equal-matches ;; `Literal Blocks`_ (concat re-bol "\\(\\([^.\n]\\|\\.[^.\n]\\).*\\)?\\(::\\)$") "=== rst.el.~rst_el_1_68~:3145" (rst-re 'lin-beg '(:shy (:alt "[^.\n]" "\\.[^.\n]") ".*") "?" '(:grp dcl-tag) "$") (list "Some text ::" (cons 3 1)) (cons "\\\\(\\\\(" "\\(?:\\(?:") ;; Make two groups shy )) (should (re-equal-matches ;; `Doctest Blocks`_ (concat re-bol "\\(>>>\\|\\.\\.\\.\\)\\(.+\\)") "=== rst.el.~rst_el_1_68~:3154" (rst-re 'lin-beg '(:grp (:alt ">>>" ell-tag)) '(:grp ".+")) (list ">>> content" (cons 1 1) (cons 2 2)) (cons ">>>" "\\(?:>>>") (cons "\\.\\\\)" ".\\)\\)") ;; Add a shy ;; group )) )) docutils-0.12/tools/editors/emacs/tests/buffer.el0000664000175000017500000001516312026705225024071 0ustar engelbertengelbert00000000000000;;; buffer.el --- Test the test support for buffers (add-to-list 'load-path ".") (load "ert-buffer" nil t) ;; **************************************************************************** ;; `ert-Buf' (defun roundtrip-ert-Buf (in) (with-temp-buffer (ert-Buf--to-buffer (ert-Buf-from-string in)) (ert-Buf-string (ert-Buf-from-buffer)))) (ert-deftest ert-Buf () "Tests for functions working with `ert-Buf's." (should (equal (concat ert-Buf-point-char "abc\n") (roundtrip-ert-Buf (concat ert-Buf-point-char "abc\n")))) (should (equal (concat "a" ert-Buf-point-char "bc\n") (roundtrip-ert-Buf (concat "a" ert-Buf-point-char "bc\n")))) (should (equal (concat "ab" ert-Buf-point-char "c\n") (roundtrip-ert-Buf (concat "ab" ert-Buf-point-char "c\n")))) (should (equal (concat "abc" ert-Buf-point-char "\n") (roundtrip-ert-Buf (concat "abc" ert-Buf-point-char "\n")))) (should (equal (concat "abc\n" ert-Buf-point-char) (roundtrip-ert-Buf (concat "abc\n" ert-Buf-point-char)))) (should (equal (concat ert-Buf-point-char "abc\n" ert-Buf-mark-char "") (roundtrip-ert-Buf (concat ert-Buf-point-char "abc\n" ert-Buf-mark-char "")))) (should (equal (concat ert-Buf-mark-char "abc\n" ert-Buf-point-char) (roundtrip-ert-Buf (concat ert-Buf-mark-char "abc\n" ert-Buf-point-char)))) (should (equal (concat "a" ert-Buf-mark-char ert-Buf-point-char "bc\n") (roundtrip-ert-Buf (concat "a" ert-Buf-point-char "" ert-Buf-mark-char "bc\n")))) (should (equal (concat "ab" ert-Buf-mark-char "" ert-Buf-point-char "c\n") (roundtrip-ert-Buf (concat "ab" ert-Buf-mark-char ert-Buf-point-char "c\n")))) (should-error (ert-Buf-from-string (concat "ab" ert-Buf-point-char ert-Buf-point-char "c\n"))) (should-error (ert-Buf-from-string (concat "ab" ert-Buf-mark-char ert-Buf-mark-char "c\n"))) ) (ert-deftest ert-Buf--from-argument () "Test `ert-Buf--from-argument'." (let ((marked-a (ert-Buf-from-string (concat ert-Buf-point-char "a" ert-Buf-mark-char)))) (should (not (ert-Buf--from-argument nil nil))) (should (equal (ert-Buf--from-argument ?a nil) (ert-Buf-from-string "a"))) (should (equal (ert-Buf--from-argument ert-Buf-point-char nil) (ert-Buf-from-string ert-Buf-point-char))) (should (equal (ert-Buf--from-argument '("a" "b") nil) (ert-Buf-from-string "ab"))) (should (equal (ert-Buf--from-argument `("a" ,ert-Buf-point-char "b") nil) (ert-Buf-from-string (concat "a" ert-Buf-point-char "b")))) (should (equal (ert-Buf--from-argument marked-a nil) marked-a)) (should-error (ert-Buf--from-argument -1 nil)) (should-error (ert-Buf--from-argument [0] nil)) (should-error (ert-Buf--from-argument t nil)) (should-error (ert-Buf--from-argument t t)) (should (eq (ert-Buf--from-argument t marked-a) marked-a)) )) ;; **************************************************************************** ;; Advice `ert-completing-read' (defvar read-fun-args nil "Input for for functions reading the minibuffer. Consists of a list of functions and their argument lists to be run successively. Prompt is omitted.") (defun insert-reads () (interactive) (while read-fun-args (let* ((fun-arg (pop read-fun-args)) (result (apply (car fun-arg) "" (cdr fun-arg)))) (insert (if (integerp result) (int-to-string result) result) "\n")))) (defun test-reads (inputs fun-args result) (setq read-fun-args fun-args) (ert-equal-buffer (insert-reads) "" result inputs)) (ert-deftest reads () "Tests for functions using `completing-read's." (should (test-reads '(5) '((read-number)) "5\n")) (should (test-reads nil nil "")) (should-error (test-reads '("") nil "")) ;; Too much input. (should-error (test-reads '(5) '((read-number) (read-number)) "")) ;; Too less input. (should (test-reads '("") '((completing-read nil)) "\n")) (should (test-reads '("" "") '((completing-read nil) (completing-read nil)) "\n\n")) (should (test-reads '("a" "b") '((completing-read nil) (completing-read nil)) "a\nb\n")) (should (test-reads '("a" "b") '((completing-read ("a" "b")) (completing-read ("a" "b"))) "a\nb\n")) (should (test-reads '("a" "b") '((completing-read ("a" "b")) (completing-read ("a"))) "a\nb\n")) (should-error (test-reads '("a" "b") '((completing-read ("a" "b")) (completing-read ("a") nil t)) "a\nb\n")) ;; Invalid input. (should (test-reads '("a" "") '((completing-read ("a" "b")) (completing-read ("a") nil t)) "a\n\n")) (should-error (test-reads '("a" "") '((completing-read ("a" "b")) (completing-read ("a") nil 'non-empty)) "a\n\n")) (should (test-reads '("x") '((read-string)) "x\n")) (should (test-reads '("") '((read-string nil nil "x")) "x\n")) (should (test-reads '("y") '((read-string nil nil "x")) "y\n")) (should (test-reads '("") '((read-number 5)) "5\n")) (should (test-reads '(0) '((read-number 5)) "0\n")) ) ;; **************************************************************************** ;; Test main functions (ert-deftest ert-equal-buffer () "Tests for `ert-equal-buffer'." (should (ert-equal-buffer (insert "foo") (concat ert-Buf-point-char ert-Buf-mark-char) (concat ert-Buf-mark-char "foo" ert-Buf-point-char))) (should (ert-equal-buffer (delete-region) (concat ert-Buf-mark-char "foo" ert-Buf-point-char) (concat ert-Buf-point-char ert-Buf-mark-char) t)) (should (ert-equal-buffer (delete-region 1 4) "foo" "")) (should-error (ert-equal-buffer (delete-region 0 3) (concat "foo") "") :type 'args-out-of-range) (should (ert-equal-buffer (goto-char 4) "foo" (concat "foo" ert-Buf-point-char))) ) (ert-deftest ert-equal-buffer-return () "Tests for `ert-equal-buffer-return'." (should (ert-equal-buffer-return (buffer-substring-no-properties 4 1) "foo" t "foo")) (should (ert-equal-buffer-return (delete-and-extract-region 1 4) "foo" "" "foo")) (should (ert-equal-buffer-return (point) ert-Buf-point-char t 1)) (should (ert-equal-buffer-return (point) (concat " " ert-Buf-point-char) t 2)) (should (ert-equal-buffer-return (region-beginning) (concat ert-Buf-point-char " " ert-Buf-mark-char) t 1)) (should (ert-equal-buffer-return (region-end) (concat ert-Buf-mark-char " " ert-Buf-point-char) t 2)) (should (ert-equal-buffer-return (following-char) (concat ert-Buf-point-char "A") t ?A)) (should (ert-equal-buffer-return (following-char) (concat "A" ert-Buf-point-char) t 0)) ) docutils-0.12/tools/editors/emacs/tests/ert-buffer.el0000664000175000017500000003577112005560235024665 0ustar engelbertengelbert00000000000000;;; ert-buffer.el --- Support functions for running ert tests on buffers ;; Copyright (C) 2010-2012 Free Software Foundation, Inc. ;; Author: Stefan Merten , ;; This file is part of GNU Emacs. ;; GNU Emacs is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; GNU Emacs is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs. If not, see . ;;; Commentary: ;; ;; Some functions need a buffer to run on. They may use the buffer content as ;; well as point and mark as input and may modify all of them. In addition ;; they may return some result. Here are some support functions to test such ;; functions using `ert'. ;; ;; Use `ert-equal-buffer' and/or `ert-equal-buffer-return' for your `should' ;; forms. ;; ;; You may use the constants `ert-Buf-point-char' and `ert-Buf-mark-char' in ;; constructing comparison strings to represent point or mark, respectively. ;; ;; Examples: ;; ;; (should (ert-equal-buffer (insert "foo") ;; ; Insertion of "foo"... ;; (concat ert-Buf-point-char ert-Buf-mark-char) ;; ; ...into an empty buffer with point and mark... ;; (concat ert-Buf-mark-char "foo" ;; ert-Buf-point-char))) ;; ; ...should result in a buffer containing "foo" ;; ; with point and mark moved appropriately. ;; ;; (should (ert-equal-buffer (delete-region) ;; ; Deleting region... ;; `(,ert-Buf-mark-char "foo" ,ert-Buf-point-char) ;; ; ...in a region spanning the whole buffer... ;; (concat ert-Buf-point-char ert-Buf-mark-char) ;; ; ...should result in an empty buffer... ;; t)) ;; ; ...when called interactively. ;; ;; (should (ert-equal-buffer-return (point) ;; ; Returning the point... ;; ert-Buf-point-char ;; ; ...in an empty buffer... ;; t ;; ; ...without changing the result buffer... ;; 1)) ;; ; ...should return 1. ;;; Code: (eval-when-compile (require 'cl)) (require 'ert) ;; **************************************************************************** ;; `ert-Buf' and related functions (defconst ert-Buf-point-char "\^@" "Special character used to mark the position of point in a `ert-Buf'.") (defconst ert-Buf-mark-char "\^?" "Special character used to mark the position of mark in a `ert-Buf'.") (defstruct (ert-Buf (:constructor nil) ; No default constructor. (:constructor ert-Buf-from-string (string &aux (analysis (ert-Buf--parse-string string)) (content (car analysis)) (point (cadr analysis)) (mark (caddr analysis)))) (:constructor ert-Buf-from-buffer (&aux (content (buffer-substring-no-properties (point-min) (point-max))) (point (point)) (mark (mark t)) (string (ert-Buf--create-string content point mark))))) "Structure to hold comparable information about a buffer. `ert-Buf-from-string' constructs a structure from a given STRING. `ert-Buf-from-buffer' constructs a structure from the current buffer." (content nil :read-only t) ; Pure string content without any special markup. (point nil :read-only t) ; Position of point. (mark nil :read-only t) ; Position of mark. (string nil :read-only t) ; String representation. ) (defun ert-Buf--parse-string (string) "Parse STRING and return clean results. Return a list consisting of the cleaned content, the position of point if `ert-Buf-point-char' was found and the the position of mark if `ert-Buf-mark-char' was found." (with-temp-buffer (let ((case-fold-search nil) fnd point-fnd mark-fnd) (insert string) (goto-char (point-min)) (while (re-search-forward (concat "[" ert-Buf-point-char ert-Buf-mark-char "]") nil t) (setq fnd (match-string 0)) (replace-match "") (cond ((equal fnd ert-Buf-point-char) (if point-fnd (error "Duplicate point")) (setq point-fnd (point))) ((equal fnd ert-Buf-mark-char) (if mark-fnd (error "Duplicate mark")) (setq mark-fnd (point))) (t (error "Unexpected marker found")))) (list (buffer-substring-no-properties (point-min) (point-max)) point-fnd mark-fnd)))) (defun ert-Buf--create-string (content point mark) "Create a string representation from CONTENT, POINT and MARK." (with-temp-buffer (insert content) (let (pnt-chs) (if point (setq pnt-chs (nconc pnt-chs (list (cons point ert-Buf-point-char))))) (if mark (setq pnt-chs (nconc pnt-chs (list (cons mark ert-Buf-mark-char))))) ;; Sort pairs so the highest position is last. (setq pnt-chs (sort pnt-chs (lambda (el1 el2) (> (car el1) (car el2))))) (while pnt-chs (goto-char (caar pnt-chs)) (insert (cdar pnt-chs)) (setq pnt-chs (cdr pnt-chs))) (buffer-substring-no-properties (point-min) (point-max))))) (defun ert-Buf--to-buffer (buf) "Set current buffer according to BUF." (insert (ert-Buf-content buf)) (if (ert-Buf-point buf) (goto-char (ert-Buf-point buf))) (if (ert-Buf-mark buf) (set-mark (ert-Buf-mark buf)))) (defun ert-Buf--from-argument (arg other) "Interpret ARG as input for an `ert-Buf', convert it and return the `ert-Buf'. ARG may be one of the types described in `ert-equal-buffer-return' or nil which is also returned." (cond ((not arg) nil) ((eq arg t) (when (or (not other) (eq other t)) (error "First argument to `ert-Buf--from-argument' t requires a non-nil, non-t second argument")) (ert-Buf--from-argument other nil)) ((characterp arg) (ert-Buf-from-string (char-to-string arg))) ((stringp arg) (ert-Buf-from-string arg)) ((ert-Buf-p arg) arg) ((listp arg) (ert-Buf-from-string (apply 'concat arg))) (t (error "Unknown type for `ert-Buf--from-argument'")))) ;; **************************************************************************** ;; Runners (defvar ert--inputs nil "Variable to hold the strings to give successively to `ert-completing-read'.") (defadvice completing-read (around ert-completing-read first (prompt collection &optional predicate require-match initial-input hist def inherit-input-method)) "Advice `completing-read' to accept input from `ert--inputs'." (if (not ert--inputs) (error "No more input strings in `ert--inputs'")) (let* ((input (pop ert--inputs))) (setq ad-return-value (cond ((eq (try-completion input collection predicate) t) ;; Perfect match. input) ((not require-match) ;; Non-matching input allowed. input) ((and (equal input "") (eq require-match t)) ;; Empty input and this is allowed. input) (t (error "Input '%s' is not allowed for `completing-read' expecting %s" input collection)))))) (defadvice read-string (around ert-read-string first (prompt &optional initial-input history default-value inherit-input-method)) "Advice `read-string' to accept input from `ert--inputs'." (if (not ert--inputs) (error "No more input strings in `ert--inputs'")) (let* ((input (pop ert--inputs))) (setq ad-return-value (if (and (equal input "") default-value) default-value input)))) (defadvice read-number (around ert-read-number first (prompt &optional default)) "Advice `read-number' to accept input from `ert--inputs'." (if (not ert--inputs) (error "No more input strings in `ert--inputs'")) (let* ((input (pop ert--inputs))) (setq ad-return-value (if (and (equal input "") default) default input)))) (defun ert--run-test-with-buffer (buf form interactive) "With a buffer filled with `ert-Buf' BUF evaluate function form FORM. Return a cons consisting of the return value and a `ert-Buf'. If INTERACTIVE is non-nil FORM is evaluated in an interactive environment." (with-temp-buffer (ert-Buf--to-buffer buf) (let ((act-return (cond ((not interactive) (apply (car form) (cdr form))) ((eq interactive t) (let ((current-prefix-arg (cadr form))) (call-interactively (car form)))) ((listp interactive) (setq ert--inputs interactive) (ad-activate 'read-string) (ad-activate 'read-number) (ad-activate 'completing-read) (unwind-protect (let ((current-prefix-arg (cadr form))) (call-interactively (car form))) (progn (ad-deactivate 'completing-read) (ad-deactivate 'read-number) (ad-deactivate 'read-string))) (if ert--inputs (error "%d input strings left over" (length ert--inputs)))))) (act-buf (ert-Buf-from-buffer))) (cons act-return act-buf)))) (defun ert--compare-test-with-buffer (result buf ignore-return exp-return) "Compare RESULT of test with expected buffer BUF. RESULT is a return value from `ert--run-test-with-buffer'. Return a list of booleans where t stands for a successful test of this kind: * Content of output buffer * Point in output buffer * Return value IGNORE-RETURN, EXP-RETURN are described in `ert--equal-buffer'." (let ((act-return (car result)) (act-buf (cdr result))) (list (or (not buf) (equal (ert-Buf-content act-buf) (ert-Buf-content buf))) (or (not buf) (not (ert-Buf-point buf)) (equal (ert-Buf-point act-buf) (ert-Buf-point buf))) (or ignore-return (equal act-return exp-return))))) (defun ert--equal-buffer (form input exp-output ignore-return exp-return interactive) "Run tests for `ert-equal-buffer-return' and `ert-equal-buffer'. FORM, INPUT and EXP-OUTPUT are as described for `ert-equal-buffer-return'. Ignore return value if IGNORE-RETURN or compare the return value to EXP-RETURN. INTERACTIVE is as described for `ert-equal-buffer-return'. Return t if equal." (catch 'return (dolist (elem (ert--compare-test-with-buffer (ert--run-test-with-buffer (ert-Buf--from-argument input exp-output) form interactive) (ert-Buf--from-argument exp-output input) ignore-return exp-return) t) (unless elem (throw 'return nil))))) (defmacro ert-equal-buffer-return (form input exp-output exp-return &optional interactive) "Evaluate function form FORM with a buffer and compare results. Since `ert-equal-buffer-return' is a macro FORM is not evaluated immediately. Thus you must give FORM as a normal function form with no additional quoting. The buffer is filled with INPUT. Compare the buffer content to EXP-OUTPUT if this is non-nil. Compare the return value to EXP-RETURN. Return t if buffer and return value are equal to the expected values. INPUT and EXP-OUTPUT represent the input buffer or the expected output buffer, respectively. They can be one of the following: * nil in which case the respective buffer is not used. Makes sense only for EXP-OUTPUT. * t in which case the other buffer is used unchanged. The other buffer must not be nil or t in this case. * A character which is converted to a one character string. * A string. * A list of strings which are concatenated using `concat'. This can be used to shorten the form describing the buffer when used with quote or backquote. * An `ert-Buf' object. All input variants which end up in a string are parsed by `ert-Buf-from-string'. If INTERACTIVE is nil FORM is evaluated with no special context. If INTERACTIVE is non-nil FORM is evaluated interactively and `current-prefix-arg' is set to the cadr of FORM (i.e\. the first argument in FORM) and thus must comply to the format of `current-prefix-arg'. If INTERACTIVE is t `call-interactively' is used normally. If INTERACTIVE is a list of strings the elements of the list are given to (advised forms of) functions reading from the minibuffer as user input strings. This allows simulating interactive user input. Return t if buffer and return value equal the expected values." `(let ((formq ',form)) (ert--equal-buffer formq ,input ,exp-output nil ,exp-return ,interactive))) (defmacro ert-equal-buffer (form input exp-output &optional interactive) "Like `ert-equal-buffer-return' but the return value of FORM is ignored. INPUT, EXP-OUTPUT and INTERACTIVE are described in `ert-equal-buffer-return'." `(let ((formq ',form)) (ert--equal-buffer formq ,input ,exp-output t nil ,interactive))) ;; **************************************************************************** ;; Explainers (defun ert--equal-buffer-explain (form input exp-output ignore-return exp-return interactive) "Explain why `ert--equal-buffer' failed with these parameters. Return the explanation. FORM, INPUT, EXP-OUTPUT, IGNORE-RETURN, EXP-RETURN, INTERACTIVE are described in `ert--equal-buffer'." (let ((test-result (ert--run-test-with-buffer (ert-Buf--from-argument input exp-output) form interactive)) (exp-buf (ert-Buf--from-argument exp-output input))) (destructuring-bind (ok-string ok-point ok-return) (ert--compare-test-with-buffer test-result (ert-Buf--from-argument exp-output input) ignore-return exp-return) (let (result) (if (not ok-return) (push (list 'different-return-values (ert--explain-not-equal (car test-result) exp-return)) result)) (if (not ok-point) (push (list 'different-points (ert-Buf-string (cdr test-result)) (ert-Buf-string exp-buf)) result)) (if (not ok-string) (push (list 'different-buffer-contents (ert--explain-not-equal (ert-Buf-content (cdr test-result)) (ert-Buf-content exp-buf))) result)) result)))) (defun ert-equal-buffer-return-explain (form input exp-output exp-return &optional interactive) "Explain why `ert-equal-buffer-return' failed with these parameters. Return the explanation. FORM, INPUT, EXP-OUTPUT, EXP-RETURN, INTERACTIVE are described in `ert--equal-buffer'." (ert--equal-buffer-explain form input exp-output nil exp-return interactive)) (put 'ert-equal-buffer-return 'ert-explainer 'ert-equal-buffer-return-explain) (defun ert-equal-buffer-explain (form input exp-output &optional interactive) "Explain why `ert-equal-buffer' failed with these parameters. Return the explanation. FORM, INPUT, EXP-OUTPUT, EXP-RETURN, INTERACTIVE are described in `ert--equal-buffer'." (ert--equal-buffer-explain form input exp-output t nil interactive)) (put 'ert-equal-buffer 'ert-explainer 'ert-equal-buffer-explain) ; LocalWords: foo minibuffer ;; Local Variables: ;; sentence-end-double-space: t ;; End: (provide 'ert-buffer) ;;; ert-buffer.el ends here docutils-0.12/tools/editors/emacs/tests/adjust-section.el0000664000175000017500000002242412026705225025552 0ustar engelbertengelbert00000000000000;; Tests for rst-adjust (add-to-list 'load-path ".") (load "init" nil t) (init-rst-ert t) (ert-deftest adjust-section-asserts () "Check some assertions." (should (equal ert-Buf-point-char "\^@")) (should (equal ert-Buf-mark-char "\^?")) ) (ert-deftest rst-adjust () "Tests for `rst-adjust'." (let ( ;; Set customizable variables to defined values (rst-new-adornment-down t) (rst-default-indent 1) (rst-preferred-adornments '((?= over-and-under 1) (?= simple 0) (?- simple 0) (?~ simple 0) (?+ simple 0) (?` simple 0) (?# simple 0) (?@ simple 0)))) (should (ert-equal-buffer (rst-adjust) " Some Title\^@ " " ============ Some Title ============ " t)) (should (ert-equal-buffer (rst-adjust) " Some Title \^@ " " ============ Some Title ============ " t)) (should (ert-equal-buffer (rst-adjust) " Some Tit\^@le " " ============ Some Title ============ " t)) (should (ert-equal-buffer (rst-adjust) " \^@Some Title " " ============ Some Title ============ " t)) (should (ert-equal-buffer (rst-adjust) " Some Title\^@ Other Title ----------- Other Title2 ~~~~~~~~~~~~ " " ============ Some Title ============ Other Title ----------- Other Title2 ~~~~~~~~~~~~ " t)) (should (ert-equal-buffer (rst-adjust 1) " Some Title\^@ " " Some Title ========== " t)) (should (ert-equal-buffer (rst-adjust) " Some Title\^@ " " ================ Some Title ================ " t)) (should (ert-equal-buffer (rst-adjust 1) " Some Title\^@ " " Some Title ========== " t)) (should (ert-equal-buffer (rst-adjust) " Previous Title -------------- Some Title\^@ " " Previous Title -------------- Some Title ~~~~~~~~~~ " t)) (should (ert-equal-buffer (rst-adjust) " Previous Title -------------- Some Title\^@ Next Title ~~~~~~~~~~ " " Previous Title -------------- Some Title ~~~~~~~~~~ Next Title ~~~~~~~~~~ " t)) (should (ert-equal-buffer (rst-adjust 1) " Previous Title -------------- Some Title\^@ " " Previous Title -------------- ~~~~~~~~~~ Some Title ~~~~~~~~~~ " t)) (should (ert-equal-buffer (rst-adjust 1) " Previous Title -------------- Some Title\^@ " " Previous Title -------------- ~~~~~~~~~~~~~~ Some Title ~~~~~~~~~~~~~~ " t)) (should (ert-equal-buffer (rst-adjust) " Previous Title -------------- Some Title\^@ " " Previous Title -------------- Some Title ~~~~~~~~~~ " t)) (should (ert-equal-buffer (rst-adjust -) " Previous Title -------------- Some Title\^@ Next Title ~~~~~~~~~~ " " Previous Title -------------- Some Title ---------- Next Title ~~~~~~~~~~ " t)) (should (ert-equal-buffer (rst-adjust) " Previous Title\^@ ---------- " " Previous Title -------------- " t)) (should (ert-equal-buffer (rst-adjust) " Previous Title ----------\^@ " " Previous Title -------------- " t)) (should (ert-equal-buffer (rst-adjust) " Previous Title -\^@ " " Previous Title - " t)) (should (ert-equal-buffer (rst-adjust) " Previous Title --\^@ " " Previous Title -- " t)) (should (ert-equal-buffer (rst-adjust) " Previous Title ---\^@ " " Previous Title -------------- " t)) (should (ert-equal-buffer (rst-adjust) " Previous Title ------------------\^@ " " Previous Title -------------- " t)) (should (ert-equal-buffer (rst-adjust) " ---------------- Previous Title ----------\^@ " " ---------------- Previous Title ---------------- " t)) (should (ert-equal-buffer (rst-adjust) " ----------\^@ Previous Title ---------------- " " ---------------- Previous Title ---------------- " t)) (should (ert-equal-buffer (rst-adjust) " ---------- Previous Title\^@ ----- " " ---------------- Previous Title ---------------- " t)) (should (ert-equal-buffer (rst-adjust 1) " Previous Title ----------\^@ " " -------------- Previous Title -------------- " t)) (should (ert-equal-buffer (rst-adjust 1) " ---------------- Previous Title\^@ -------- " " Previous Title -------------- " t)) (should (ert-equal-buffer (rst-adjust 1) " --------\^@ Previous Title ---------------- " " Previous Title -------------- " t)) (should (ert-equal-buffer (rst-adjust) "--------\^@ Previous Title ---------------- " "---------------- Previous Title ---------------- " t)) (should (ert-equal-buffer (rst-adjust) "======= Document Title\^@ ============== " "============== Document Title ============== " t)) (should (ert-equal-buffer (rst-adjust) " ================ Document Title ================ SubTitle -------- My Title\^@ -------- After Title ~~~~~~~~~~~ " " ================ Document Title ================ SubTitle -------- ========== My Title ========== After Title ~~~~~~~~~~~ " t)) (should (ert-equal-buffer (rst-adjust -) " ================ Document Title ================ SubTitle -------- My Title\^@ -------- After Title ~~~~~~~~~~~ " " ================ Document Title ================ SubTitle -------- My Title ~~~~~~~~ After Title ~~~~~~~~~~~ " t)) (should (ert-equal-buffer (rst-adjust -) " ================ Document Title ================ SubTitle ======== My Title\^@ ======== " " ================ Document Title ================ SubTitle ======== My Title -------- " t)) (should (ert-equal-buffer (rst-adjust -) " ================ Document Title ================ SubTitle ======== My Title\^@ -------- " " ================ Document Title ================ SubTitle ======== ========== My Title ========== " t)) (should (ert-equal-buffer (rst-adjust) " ================ Document Title ================ SubTitle ======== ========== My Title\^@ ========== " " ================ Document Title ================ SubTitle ======== My Title -------- " t)) (should (ert-equal-buffer (rst-adjust) " ================ Document Title ================ SubTitle ======== My Title\^@ -------- " " ================ Document Title ================ SubTitle ======== My Title ======== " t)) (should (ert-equal-buffer (rst-adjust 1) " SubTitle\^@ ~~~~~~~~ " " ~~~~~~~~~~ SubTitle ~~~~~~~~~~ " t)) (should (ert-equal-buffer (rst-adjust 1) " ~~~~~~~~~~ SubTitle\^@ ~~~~~~~~~~ " " SubTitle ~~~~~~~~ " t)) (should (ert-equal-buffer (rst-adjust) " Document Title\^@ " " ================ Document Title\^@ ================ " t)) (should (ert-equal-buffer (rst-adjust) " Document Title\^@ " " ================ Document Title\^@ ================ " t)) (should (ert-equal-buffer (rst-adjust) " Document Title\^@" " ================ Document Title\^@ ================ " t)) (should (ert-equal-buffer (rst-adjust) " Document Title ============== Subtitle\^@ " " Document Title ============== Subtitle\^@ -------- " t)) (should (ert-equal-buffer (rst-adjust) "============== Document Title\^@ ============== Subtitle ======== " "Document Title\^@ ============== Subtitle ======== " t)) (should (ert-equal-buffer (rst-adjust) " ============== Document Title\^@ ============== Subtitle ======== " " Document Title\^@ ============== Subtitle ======== " t)) (should (ert-equal-buffer (rst-adjust) " ============== Document Title ============== =============== Document Title2\^@ =============== " " ============== Document Title ============== Document Title2 =============== " t)) ;; docutils-Bugs #2972588 (should (ert-equal-buffer (rst-adjust) " ============== Document Title ============== Subtitle ======== .. contents:: :depth: 2 .. 1 Section 1 2 Section 2 Section 1\^@ --------- Section 2 --------- " " ============== Document Title ============== Subtitle ======== .. contents:: :depth: 2 .. 1 Section 1 2 Section 2 Section 1\^@ ========= Section 2 --------- " t)) ;; FIXME: todo ;; ;;------------------------------------------------------------------------------ ;; (cycle-previous-only ;; " ;; ================== ;; Document Title ;; ================== ;; ;; Document Title2 ;; =============== ;; ;; ======= ;; Bli\^@ ;; ======= ;; ;; Document Title2 ;; =============== ;; ;; Document Title3 ;; --------------- ;; ;; Document Title4 ;; ~~~~~~~~~~~~~~~ ;; ;; " ;; " ;; ================== ;; Document Title ;; ================== ;; ;; Document Title2 ;; =============== ;; ;; Bli\^@ ;; --- ;; ;; Document Title2 ;; =============== ;; ;; Document Title3 ;; --------------- ;; ;; Document Title4 ;; ~~~~~~~~~~~~~~~ ;; ;; " ;; ) )) docutils-0.12/tools/editors/emacs/tests/font-lock.el0000664000175000017500000000632512026705225024514 0ustar engelbertengelbert00000000000000;; Tests for font-locking code (add-to-list 'load-path ".") (load "init" nil t) (init-rst-ert t) (ert-deftest font-lock--asserts () "Check some assertions." (should (equal ert-Buf-point-char "\^@")) (should (equal ert-Buf-mark-char "\^?")) ) (ert-deftest rst-forward-indented-block () "Tests `rst-forward-indented-block'." (should (ert-equal-buffer-return (rst-forward-indented-block) "\^@abc" t nil)) (should (ert-equal-buffer-return (rst-forward-indented-block) (concat " \^@abc def") (concat " abc \^@ def") 7)) ) (defun extend-region (beg end) "Wrapper for `rst-font-lock-extend-region-internal'. Uses and sets region and returns t if region has been changed." (interactive "r") (let ((r (rst-font-lock-extend-region-internal beg end))) (when r (goto-char (car r)) (set-mark (cdr r)) t))) (ert-deftest rst-font-lock-extend-region-internal-indent () "Tests `rst-font-lock-extend-region-internal'." (should (ert-equal-buffer-return (extend-region) "\^@abc\^?" t nil t)) (should (ert-equal-buffer-return (extend-region) "\^@ abc\^?" t nil t)) (should (ert-equal-buffer-return (extend-region) " abc \^@ def\^?" "\^@ abc def\^?" t t)) (should (ert-equal-buffer-return (extend-region) " abc \^@ def \^? ghi uvw" "\^@ abc def ghi \^?uvw" t t)) (should (ert-equal-buffer-return (extend-region) "xyz abc \^@ def \^? ghi" "xyz \^@abc def ghi\^?" t t)) (should (ert-equal-buffer-return (extend-region) "xyz abc:: \^@ def \^? ghi uvw" "xyz \^@ abc:: def ghi \^?uvw" t t)) (should (ert-equal-buffer-return (extend-region) "xyz .. abc \^@ def \^?uvw" "xyz \^@ .. abc def \^?uvw" t t)) (should (ert-equal-buffer-return (extend-region) "xyz .. abc 123 \^@ def \^? uvw" "xyz \^@ .. abc 123 def \^? uvw" t t)) (should (ert-equal-buffer-return (extend-region) "xyz .. abc 123 \^@ def \^? uvw" "xyz \^@ .. abc 123 def \^? uvw" t t)) ) (ert-deftest rst-font-lock-extend-region-internal-adornment () "Tests `rst-font-lock-extend-region-internal'." (should (ert-equal-buffer-return (extend-region) "\^@===\^?" t nil t)) (should (ert-equal-buffer-return (extend-region) "abc \^@===\^?" "\^@abc ===\^?" t t)) (should (ert-equal-buffer-return ; Quite complicated without the trailing newline (extend-region) "\^@abc \^?===" t nil t)) (should (ert-equal-buffer-return (extend-region) "\^@abc \^?=== " "\^@abc === \^?" t t)) (should (ert-equal-buffer-return (extend-region) "=== abc \^@=== \^?" "\^@=== abc === \^?" t t)) (should (ert-equal-buffer-return (extend-region) "\^@=== \^?abc === " "\^@=== abc === \^?" t t)) (should (ert-equal-buffer-return (extend-region) "def === \^@abc === \^?" "def \^@=== abc === \^?" t t)) (should (ert-equal-buffer-return (extend-region) "def \^@=== abc \^?=== xyz" "def \^@=== abc === \^? xyz" t t)) ) docutils-0.12/tools/editors/emacs/tests/tree.el0000664000175000017500000000674012026705225023560 0ustar engelbertengelbert00000000000000;; Tests for `rst-section-tree' (add-to-list 'load-path ".") (load "init" nil t) (init-rst-ert t) (ert-deftest toc-asserts () "Check some assertions." (should (equal ert-Buf-point-char "\^@")) (should (equal ert-Buf-mark-char "\^?")) ) (defun mrk2int (obj) "Replace all markers in OBJ by integers and return result." (cond ((markerp obj) (marker-position obj)) ((stringp obj) obj) ((sequencep obj) (mapcar 'mrk2int obj)) (t obj))) (defun section-tree () "Return result of `rst-section-tree' with markers replaced by integers." (mrk2int (rst-section-tree))) (defun section-tree-point () "Return result of `rst-section-tree-point' with markers replaced by integers." (mrk2int (rst-section-tree-point (rst-section-tree)))) (ert-deftest rst-section-tree () "Tests `rst-section-tree'." (let ((title "===== Title ===== ") (headers "Header A ======== Header B ======== Subheader B.a ------------- SubSubheader B.a.1 ~~~~~~~~~~~~~~~~~~ Subheader B.b ------------- Header C ========")) (should (ert-equal-buffer-return (section-tree) "" t '((nil)) )) (should (ert-equal-buffer-return (section-tree) title t '((nil 7) (("Title" 7))) )) (should (ert-equal-buffer-return (section-tree) (concat title headers) t '((nil 7) (("Title" 7) (("Header A" 20)) (("Header B" 39) (("Subheader B.a" 58) (("SubSubheader B.a.1" 87))) (("Subheader B.b" 126))) (("Header C" 155)))) )) )) (ert-deftest rst-section-tree-point () "Tests `rst-section-tree-point'." (let ((title "===== Title ===== ")) (should (ert-equal-buffer-return (section-tree-point) "\^@" t '(((nil))) )) (should (ert-equal-buffer-return (section-tree-point) (concat "\^@" title) t '(((nil 7))) )) (should (ert-equal-buffer-return (section-tree-point) (concat title "\^@") t '(((nil 7) ("Title" 7)) ("Title" 7)) )) (should (ert-equal-buffer-return (section-tree-point) (concat title "\^@Header A ======== Header B ======== Subheader B.a ------------- SubSubheader B.a.1 ~~~~~~~~~~~~~~~~~~ Subheader B.b ------------- Header C ========") t '(((nil 7) ("Title" 7) ("Header A" 20)) ("Header A" 20)) )) (should (ert-equal-buffer-return (section-tree-point) (concat title "Header A ======== Header B ======== \^@ Subheader B.a ------------- SubSubheader B.a.1 ~~~~~~~~~~~~~~~~~~ Subheader B.b ------------- Header C ========") t '(((nil 7) ("Title" 7) ("Header B" 39)) ("Header B" 39) (("Subheader B.a" 58) (("SubSubheader B.a.1" 87))) (("Subheader B.b" 126))) )) (should (ert-equal-buffer-return (section-tree-point) (concat title "Header A ======== Header B ======== Subheader B.a\^@ ------------- SubSubheader B.a.1 ~~~~~~~~~~~~~~~~~~ Subheader B.b ------------- Header C ========") t '(((nil 7) ("Title" 7) ("Header B" 39) ("Subheader B.a" 58)) ("Subheader B.a" 58) (("SubSubheader B.a.1" 87))) )) (should (ert-equal-buffer-return (section-tree-point) (concat title "Header A ======== Header B ======== Subheader B.a ------------- SubSubheader B.a.1 ~~~~~~~~~~~~~~~~~~ S\^@ubheader B.b ------------- Header C ========") t '(((nil 7) ("Title" 7) ("Header B" 39) ("Subheader B.b" 126)) ("Subheader B.b" 126)) )) )) docutils-0.12/tools/editors/emacs/tests/movement.el0000664000175000017500000000745412026705225024456 0ustar engelbertengelbert00000000000000;; Tests for various movement commands (add-to-list 'load-path ".") (load "init" nil t) (init-rst-ert t) (ert-deftest movement-asserts () "Check some assertions." (should (equal ert-Buf-point-char "\^@")) (should (equal ert-Buf-mark-char "\^?")) ) (defun fwd-para () "Wrapper to call `forward-paragraph'." (rst-mode) (forward-paragraph)) (ert-deftest forward-paragraph () "Tests for `forward-paragraph'." (should (ert-equal-buffer-return (fwd-para) " :Field: Content \^@ More content over several * An item with multi " " :Field: Content More content over several \^@ * An item with multi " 0 )) (should (ert-equal-buffer-return (fwd-para) "\^@ This is a short para" " This is a short para\^@" 0 )) (should (ert-equal-buffer-return (fwd-para) "\^@ This is a short para " " This is a short para \^@" 0 )) (should (ert-equal-buffer-return (fwd-para) "\^@ This is a short para " " This is a short para \^@ " 0 )) (should (ert-equal-buffer-return (fwd-para) "\^@ This is a short para " " This is a short para \^@ " 0 )) (should (ert-equal-buffer-return (fwd-para) " \^@This is a short para " " This is a short para \^@ " 0 )) (should (ert-equal-buffer-return (fwd-para) " This is a short \^@para " " This is a short para \^@ " 0 )) (should (ert-equal-buffer-return (fwd-para) " This is a short \^@para " " This is a short para \^@ " 0 )) (should (ert-equal-buffer-return (fwd-para) " This is \^@a short para " " This is a short para \^@ " 0 )) (should (ert-equal-buffer-return (fwd-para) " This is a short \^@para This is a short para " " This is a short para \^@ This is a short para " 0 )) (should (ert-equal-buffer-return (fwd-para) " \^@* An item * Another item " " * An item \^@ * Another item " 0 )) (should (ert-equal-buffer-return (fwd-para) " \^@* An item * Another item " " * An item \^@* Another item " 0 )) (should (ert-equal-buffer-return (fwd-para) " \^@:Field: Content More content over several * An item with multi " " :Field: Content \^@ More content over several * An item with multi " 0 )) (should (ert-equal-buffer-return (fwd-para) " :Field: Content \^@ More content over several * An item with multi " " :Field: Content More content over several \^@ * An item with multi " 0 )) (should (ert-equal-buffer-return (fwd-para) " :Field: Content More content over several \^@ * An item with multi " " :Field: Content More content over several * An item with multi \^@" 0 )) (should (ert-equal-buffer-return (fwd-para) "\^@ .. |s| d:: :F: Content More content over several * An item with multi " " .. |s| d:: \^@ :F: Content More content over several * An item with multi " 0 )) (should (ert-equal-buffer-return (fwd-para) " .. |s| d:: \^@ :F: Content More content over several * An item with multi " " .. |s| d:: :F: Content \^@ More content over several * An item with multi " 0 )) (should (ert-equal-buffer-return (fwd-para) " .. |s| d:: :F: Content \^@ More content over several * An item with multi " " .. |s| d:: :F: Content More content over several \^@ * An item with multi " 0 )) (should (ert-equal-buffer-return (fwd-para) " .. |s| d:: :F: Content More content over several \^@ * An item with multi " " .. |s| d:: :F: Content More content over several * An item with multi \^@" 0 )) ) docutils-0.12/tools/editors/emacs/tests/shift.el0000664000175000017500000002776112026705225023744 0ustar engelbertengelbert00000000000000;; Tests for various functions around shifting text (add-to-list 'load-path ".") (load "init" nil t) (init-rst-ert t) (ert-deftest shift-asserts () "Check some assertions." (should (equal ert-Buf-point-char "\^@")) (should (equal ert-Buf-mark-char "\^?")) ) (defun string-insert (s col char) "Insert CHAR at position COL in S. Return S." (let ((l (length s)) (c (char-to-string char))) (if (<= l col) (concat s (make-string (- col l) ? ) c) (concat (substring s 0 col) c (substring s (1+ col)))))) (defun line-tabs () "Wrapper to call `rst-line-tabs' creating a readable result." (let ((tabs (rst-line-tabs)) (s "") (cnt 0) c) (delete-region (point-min) (point-max)) (dolist (tab tabs) (setq c (+ ?A cnt)) (if (cdr tab) (setq c (+ c (- ?a ?A)))) (setq s (string-insert s (car tab) c)) (setq cnt (1+ cnt))) (insert "\n" s))) (ert-deftest rst-line-tabs () "Tests for `rst-line-tabs'." (let ((rst-indent-width 2) (rst-indent-field 2) (rst-indent-literal-normal 3) (rst-indent-literal-minimized 2) (rst-indent-comment 3)) (should (ert-equal-buffer (line-tabs) "\^@" " " )) (should (ert-equal-buffer (line-tabs) " * a\^@" " B a" )) (should (ert-equal-buffer (line-tabs) " * b\^@" " B a" )) (should (ert-equal-buffer (line-tabs) " XV. c\^@" " B a" )) (should (ert-equal-buffer (line-tabs) " * \^@" " A" )) (should (ert-equal-buffer (line-tabs) " *\tb\^@" " B a" )) (should (ert-equal-buffer (line-tabs) "Some para\^@" " A" )) (should (ert-equal-buffer (line-tabs) " A quoted block\^@" " A" )) (should (ert-equal-buffer (line-tabs) " :Field: Content on same line\^@" " C b a" )) (should (ert-equal-buffer (line-tabs) " :Field: \^@" " B a" )) (let ((rst-indent-field 0)) (should (ert-equal-buffer (line-tabs) " :Field: Content on same line\^@" " B a" )) (should (ert-equal-buffer (line-tabs) " :Field: \^@" " B a" ))) (should (ert-equal-buffer (line-tabs) " .. dir:: Content on same line\^@" " C b a" )) (should (ert-equal-buffer (line-tabs) " .. dir:: \^@" " B a" )) (should (ert-equal-buffer (line-tabs) " .. |sub| dir:: Content on same line\^@" " D c b a" )) (should (ert-equal-buffer (line-tabs) " .. |sub| dir::\^@" " C b a" )) (should (ert-equal-buffer (line-tabs) " .. [CIT] citation\^@" " C b a" )) (should (ert-equal-buffer (line-tabs) " .. [#FN] Footnote\^@" " C b a" )) (should (ert-equal-buffer (line-tabs) " .. [CIT]\^@" " B a" )) (should (ert-equal-buffer (line-tabs) " Some text::\^@" " B a" )) (should (ert-equal-buffer (line-tabs) " ::\^@" " B a" )) (should (ert-equal-buffer (line-tabs) " ::\^@" " B a" )) (should (ert-equal-buffer (line-tabs) " .. First comment\^@" " B a" )) (should (ert-equal-buffer (line-tabs) " XV. c::\^@" " C b a" )) (should (ert-equal-buffer (line-tabs) " :f: val::\^@" " D c b a" )) )) (defun compute-tabs () "Wrapper to call `rst-compute-tabs' creating a readable result." (let ((tabs (rst-compute-tabs (point))) (s "") (cnt 0)) (delete-region (point-min) (point-max)) (dolist (tab tabs) (setq s (string-insert s tab (+ ?A cnt))) (setq cnt (1+ cnt))) (insert "\n" s))) (ert-deftest rst-compute-tabs () "Tests for `rst-compute-tabs'." (let ((rst-indent-width 2) (rst-indent-field 2) (rst-indent-literal-normal 3) (rst-indent-literal-minimized 2) (rst-indent-comment 3)) (should (ert-equal-buffer (compute-tabs) "\^@" " " )) (should (ert-equal-buffer (compute-tabs) " * a \^@" " B A" )) (should (ert-equal-buffer (compute-tabs) " * a * b \^@" " C B A" )) (should (ert-equal-buffer (compute-tabs) " * a * b XV. c \^@" " D C B A" )) (should (ert-equal-buffer (compute-tabs) " * a XV. c \^@" " D C B A" )) (should (ert-equal-buffer (compute-tabs) " * XV. c \^@" " C B A" )) (should (ert-equal-buffer (compute-tabs) " * a * b XV. c * d \^@" " C B A" )) (should (ert-equal-buffer (compute-tabs) " * a * b XV. c * d * e \^@" " B A" )) (should (ert-equal-buffer (compute-tabs) " * a * b XV. c \^@" " D C B A" )) (should (ert-equal-buffer (compute-tabs) " * a *\tb \^@" " C B A" )) (should (ert-equal-buffer (compute-tabs) "* a \^@" " B A" )) (should (ert-equal-buffer (compute-tabs) " * a * b XV. c \^@" " D C B A" )) (should (ert-equal-buffer (compute-tabs) "Some para A quoted block Quoting again \^@" " C B A" )) (should (ert-equal-buffer (compute-tabs) " :Field: Content on same line \^@" " C B A" )) (should (ert-equal-buffer (compute-tabs) " :Field: Content on same line but continued differently \^@" " D CA B" )) (should (ert-equal-buffer (compute-tabs) " :Field: Content on same line but continued differently \^@" " D C B A" )) (should (ert-equal-buffer (compute-tabs) " :Field: Content on next line \^@" " C BA" )) (should (ert-equal-buffer (compute-tabs) " :Field: Starts on same line Content on next line \^@" " C A B" )) (should (ert-equal-buffer (compute-tabs) " .. dir:: Content on same line \^@" " C B A" )) (should (ert-equal-buffer (compute-tabs) " .. dir:: Content on next line \^@" " B A" )) (should (ert-equal-buffer (compute-tabs) " .. dir:: Content on next line \^@" " C B A" )) (should (ert-equal-buffer (compute-tabs) " .. dir:: Same Content on next line \^@" " D C A B" )) (should (ert-equal-buffer (compute-tabs) " .. |sub| dir:: Content on same line \^@" " D C B A" )) (should (ert-equal-buffer (compute-tabs) " .. |sub| dir:: Content on next line \^@" " C A B" )) (should (ert-equal-buffer (compute-tabs) " .. |sub| dir:: Content on next line \^@" " D C A B" )) (should (ert-equal-buffer (compute-tabs) " .. |sub| dir:: Same Content on next line \^@" " E D A C B" )) (should (ert-equal-buffer (compute-tabs) " .. |sub| dir:: Same :par: val Content on next line \^@" " E DC A B" )) (should (ert-equal-buffer (compute-tabs) " .. |sub| dir:: :par: val Content on next line \^@" " C A B" )) (should (ert-equal-buffer (compute-tabs) " .. |sub| dir:: Same :f: val Content on next line \^@" " E DAC B" )) (should (ert-equal-buffer (compute-tabs) " .. |sub| dir:: Same :f: val Content on next line \^@" " D A C B" )) (should (ert-equal-buffer (compute-tabs) " .. |sub| dir:: Same :f: val * Item \^@" " C B A" )) (should (ert-equal-buffer (compute-tabs) " .. |sub| dir:: Same :f: val * Item 1. Enumerated \^@" " D C B A" )) (should (ert-equal-buffer (compute-tabs) " .. [CIT] citation \^@" " C B A" )) (should (ert-equal-buffer (compute-tabs) " .. [#FN] Footnote \^@" " C B A" )) (should (ert-equal-buffer (compute-tabs) " .. [CIT] citation \^@" " B A" )) (should (ert-equal-buffer (compute-tabs) " .. [CIT] citation \^@" " C B A" )) (should (ert-equal-buffer (compute-tabs) " .. [CIT] citation .. |sub| dir:: Same :f: val * Item 1. Enumerated \^@" " E D C B A" )) (should (ert-equal-buffer (compute-tabs) " Some text:: \^@" " B A" )) (should (ert-equal-buffer (compute-tabs) " No text :: \^@" " B A" )) (should (ert-equal-buffer (compute-tabs) " No text :: \^@" " C B A" )) (should (ert-equal-buffer (compute-tabs) " .. [CIT] citation .. |sub| dir:: Same :f: val No text :: \^@" " E D C B A" )) (should (ert-equal-buffer (compute-tabs) " .. First comment \^@" " B A" )) (should (ert-equal-buffer (compute-tabs) " * a XV. c:: \^@" " E D C B A" )) (should (ert-equal-buffer (compute-tabs) " .. [CIT] citation .. |sub| dir:: Same :f: val:: \^@" " F E D C B A" )) )) (ert-deftest rst-shift-region-right () "Tests for `rst-shift-region' to the right." (let ((rst-indent-width 2)) ; Set relevant variables (should (ert-equal-buffer (rst-shift-region 1) " \^@a \^?" " \^@ a \^?" t)) (should (ert-equal-buffer (rst-shift-region 1) " \^@ a \^?" " \^@ a \^?" t)) (should (ert-equal-buffer (rst-shift-region 1) "\^@ a b \^?" "\^@ a b \^?" t)) (should (ert-equal-buffer (rst-shift-region 1) "* x \^@ a b \^?" "* x \^@ a b \^?" t)) (should (ert-equal-buffer (rst-shift-region 1) "* x \^@ a b \^?" "* x \^@ a b \^?" t)) (should (ert-equal-buffer (rst-shift-region 1) "* x * y \^@ a b \^?" "* x * y \^@ a b \^?" t)) (should (ert-equal-buffer (rst-shift-region 1) "* x \^? a b \^@" "* x \^? a b \^@" t)) (should (ert-equal-buffer (rst-shift-region 2) "* x \^? a b \^@" "* x \^? a b \^@" t)) )) (ert-deftest rst-shift-region-left () "Tests for `rst-shift-region' to the left." (let ((rst-indent-width 2)) ; Set relevant variables (should (ert-equal-buffer (rst-shift-region -1) "* x \^@ a b \^?" "* x \^@ a b \^?" t)) (should (ert-equal-buffer (rst-shift-region -1) " \^@ a \^?" " \^@a \^?" t)) (should (ert-equal-buffer (rst-shift-region -1) " \^@ a \^?" " \^@ a \^?" t)) (should (ert-equal-buffer (rst-shift-region -1) "\^@ a b \^?" "\^@ a b \^?" t)) (should (ert-equal-buffer (rst-shift-region -1) "* x \^@ a b \^?" "* x \^@ a b \^?" t)) (should (ert-equal-buffer (rst-shift-region -1) "* x * y \^@ a b \^?" "* x * y \^@ a b \^?" t)) (should (ert-equal-buffer (rst-shift-region -1) "* x \^? a b \^@" "* x \^? a b \^@" t)) (should (ert-equal-buffer (rst-shift-region 0) "* x * y \^@ a b \^?" "* x * y \^@ a b \^?" t)) (should (ert-equal-buffer (rst-shift-region -1) "\^@* x * y a b \^?" "\^@* x * y a b \^?" t)) (should (ert-equal-buffer (rst-shift-region -2) "* x * y \^@ a b \^?" "* x * y \^@ a b \^?" t)) )) docutils-0.12/tools/editors/emacs/tests/comment.el0000664000175000017500000000664312026705225024265 0ustar engelbertengelbert00000000000000;; Tests for comment handling (add-to-list 'load-path ".") (load "init" nil t) (init-rst-ert t) (ert-deftest comment-asserts () "Check some assertions." (should (equal ert-Buf-point-char "\^@")) (should (equal ert-Buf-mark-char "\^?")) ) (defun cmnt-insert () "Wrapper to insert comment via `comment-dwim'. Must be called on a line conaining at most whitespace." (let ((fc fill-column)) (rst-mode) (setq fill-column fc) (comment-dwim nil))) (ert-deftest comment-insert () "Tests for inserting a comment." (let ((rst-indent-width 2) (rst-indent-comment 3) (fill-column 20)) (should (ert-equal-buffer (cmnt-insert) "\^@" ".. \^@" )) (should (ert-equal-buffer (cmnt-insert) " \^@" " .. \^@" )) (should (ert-equal-buffer (cmnt-insert) " * bla \^@" " * bla .. \^@" )) (should (ert-equal-buffer (cmnt-insert) " :Field: Content \^@" " :Field: Content .. \^@" )) )) (defun cmnt-indent (continue) "Wrapper for `comment-indent'." (let ((fc fill-column)) (rst-mode) (setq fill-column fc) (comment-indent continue))) (ert-deftest comment-indent () "Tests for `comment-indent'." (let ((rst-indent-width 2) (rst-indent-comment 3) (fill-column 20)) (should (ert-equal-buffer (cmnt-indent nil) "\^@" ".. \^@" )) (should (ert-equal-buffer (cmnt-indent nil) " \^@" " .. \^@" )) (should (ert-equal-buffer (cmnt-indent nil) ".. comment\^@" ".. \^@comment" )) (should (ert-equal-buffer (cmnt-indent nil) " * bla .. comment\^@" " * bla .. \^@comment" )) (should (ert-equal-buffer (cmnt-indent nil) " :Field: Content \^@" " :Field: Content .. \^@" )) (should (ert-equal-buffer (cmnt-indent nil) " :Field: Content .. comment\^@" " :Field: Content .. \^@comment" )) )) (defun uncmnt-region () "Wrapper for `uncomment-region'." (let ((fc fill-column)) (rst-mode) (setq fill-column fc) (call-interactively 'uncomment-region))) (ert-deftest uncomment-region () "Tests for `uncomment-region'." (let ((rst-indent-width 2) (rst-indent-comment 3) (fill-column 20)) (should (ert-equal-buffer (uncmnt-region) "\^?.. com\^@ment" "\^?com\^@ment" )) (should (ert-equal-buffer (uncmnt-region) "\^?.. com\^@ment bla " "\^?com\^@ment bla " )) (should (ert-equal-buffer (uncmnt-region) "\^?.. comment bl\^@a " "\^?comment bl\^@a " )) )) (defun cmnt-region () "Wrapper for `comment-region'." (let ((fc fill-column)) (rst-mode) (setq fill-column fc) (call-interactively 'comment-region))) (ert-deftest comment-region () "Tests for `comment-region'." (let ((rst-indent-width 2) (rst-indent-comment 3) (fill-column 20)) (should (ert-equal-buffer (cmnt-region) "\^?com\^@ment" "\^?.. com\^@ment" )) (should (ert-equal-buffer (cmnt-region) "\^?com\^@ment bla " "\^?.. com\^@ment bla " )) (should (ert-equal-buffer (cmnt-region) "\^?comment bl\^@a " "\^?.. comment bl\^@a " )) )) ;; comment-kill could be tested but since there are no suffix comments in ;; reStructuredText this makes little sense docutils-0.12/tools/editors/emacs/tests/init.el0000664000175000017500000000203512026705225023555 0ustar engelbertengelbert00000000000000;; Initialize tests (defun init-rst-ert (&optional with-buffer) "Initialize tests. Prepare for buffer using tests if WITH-BUFFER." (when with-buffer (add-to-list 'load-path ".") (load "ert-buffer" nil t) (if (equal (car load-path) ".") (setq load-path (cdr load-path)))) (add-to-list 'load-path "..") (load "rst.el" nil t) (if (equal (car load-path) "..") (setq load-path (cdr load-path))) ;; Emacs 24 should have a patch in `testcover-after` declaring a ;; `gv-expander'. (if (< emacs-major-version 24) ;; Define a setf-method for `testcover-after' so `ert' tests can be run ;; without problems. (defsetf testcover-after (idx val) (store) (list 'progn (list 'testcover-after idx val) ;; FIXME: Though it solves the problem it is not really correct ;; because `val' is only a temporary variable here. (list 'setf val store))))) ;; Clean up `load-path' if set caller just to load this file. (if (equal (car load-path) ".") (setq load-path (cdr load-path))) docutils-0.12/tools/editors/emacs/tests/Makefile0000664000175000017500000000114312005560235023724 0ustar engelbertengelbert00000000000000#!/usr/bin/env make EMACS = /usr/bin/emacs ERT = ~/lib/emacs/ert RST_EL = ../rst.el EMACS_ERT_PFX = $(EMACS) --batch --quick --directory=$(ERT) --load=ert.el EMACS_ERT_SFX = --funcall=ert-run-tests-batch-and-exit ERT_TESTS := $(filter-out ert-%,$(wildcard *.el)) EMACS_COMPILE_PFX = $(EMACS) --batch --quick --eval '(progn \ (setq byte-compile-error-on-warn t) \ (kill-emacs (if (byte-compile-file EMACS_COMPILE_SFX = ) 0 1)))' all: compile tests tests: $(EMACS_ERT_PFX) $(addprefix -l ,$(ERT_TESTS)) $(EMACS_ERT_SFX) compile: $(EMACS_COMPILE_PFX) "$(RST_EL)" $(EMACS_COMPILE_SFX) clean: docutils-0.12/tools/editors/emacs/tests/README.txt0000664000175000017500000000106611501212462023762 0ustar engelbertengelbert00000000000000==================== Tests for rst.el ==================== :Author: Martin Blais , Stefan Merten The tests are using ERT_. You need to install ERT_ for to run them. If you did you should change the path to the library contained in the variable `ERT` in `Makefile`. To run the tests in Emacs use the facilities provided by ERT_. Namely evaluate the buffer containing the tests and do:: M-x ert [RETURN] [RETURN] To run the tests by `make` use :: make ert-tests .. _ERT: http://www.emacswiki.org/emacs/ErtTestLibrary docutils-0.12/tools/editors/emacs/tests/toc.el0000664000175000017500000000632612026705225023406 0ustar engelbertengelbert00000000000000;; Tests for operations on toc (add-to-list 'load-path ".") (load "init" nil t) (init-rst-ert t) (ert-deftest toc-asserts () "Check some assertions." (should (equal ert-Buf-point-char "\^@")) (should (equal ert-Buf-mark-char "\^?")) ) (ert-deftest rst-toc-insert () "Tests `rst-toc-insert'." (let ((title "===== Title ===== ") (headers "Header A ======== Header B ======== Subheader B.a ------------- SubSubheader B.a.1 ~~~~~~~~~~~~~~~~~~ Subheader B.b ------------- Header C ========")) ;; Set customizable variables to defaults (let ((rst-toc-indent 2) (rst-toc-insert-style 'fixed) (rst-toc-insert-number-separator " ") (rst-toc-insert-max-level nil)) ;; Can't identify a title so do nothing - that's actually a (MIS-)FEATURE (should (ert-equal-buffer (rst-toc-insert) (concat "\^@" headers) t)) ;; Won't work on a section title (should (ert-equal-buffer (rst-toc-insert) (concat title "\^@" headers) t)) ;; No indentation (should (ert-equal-buffer (rst-toc-insert) (concat title "\^@\n\n" headers) (concat title "1 Header A 2 Header B 2.1 Subheader B.a 2.1.1 SubSubheader B.a.1 2.2 Subheader B.b 3 Header C\^@ " headers))) ;; Indentation (should (ert-equal-buffer (rst-toc-insert) (concat title " \^@\n\n" headers) (concat title " 1 Header A 2 Header B 2.1 Subheader B.a 2.1.1 SubSubheader B.a.1 2.2 Subheader B.b 3 Header C\^@ " headers))) ;; Only first level (should (ert-equal-buffer (rst-toc-insert 1) (concat title " \^@\n\n" headers) (concat title " 1 Header A 2 Header B 3 Header C\^@ " headers))) ;; Prefix and indentation (should (ert-equal-buffer (rst-toc-insert) (concat title ".. \^@\n\n" headers) (concat title ".. 1 Header A 2 Header B 2.1 Subheader B.a 2.1.1 SubSubheader B.a.1 2.2 Subheader B.b 3 Header C\^@ " headers))) ) )) (ert-deftest rst-toc-update () "Tests `rst-toc-update'." (let ((title "===== Title ===== ") (headers "Header A ======== Header B ======== Subheader B.a ------------- SubSubheader B.a.1 ~~~~~~~~~~~~~~~~~~ Subheader B.b ------------- Header C ========") (contents ".. contents:: Inhalt\n") (fields " :bla: blub\n :local:\n") (old ".. 1 Header A 2 Header B 3 Header C") (new ".. 1 Header A 2 Header B 2.1 Subheader B.a 2.1.1 SubSubheader B.a.1 2.2 Subheader B.b 3 Header C") ) ;; Set customizable variables to defaults (let ((rst-toc-indent 2) (rst-toc-insert-style 'fixed) (rst-toc-insert-number-separator " ") (rst-toc-insert-max-level nil)) (should (ert-equal-buffer (rst-toc-update) (concat title contents fields old "\n\n" headers "\^@") (concat title contents fields new "\n\n" headers "\^@"))) (should (ert-equal-buffer (rst-toc-update) (concat title contents old "\n\n" headers "\^@") (concat title contents new "\n\n" headers "\^@"))) ) )) ;; FIXME: More functions to test: ;; * rst-toc ;; * rst-toc-mode-goto-section docutils-0.12/tools/editors/emacs/tests/items.el0000664000175000017500000001046712026705225023743 0ustar engelbertengelbert00000000000000;; Tests for operations on list items (add-to-list 'load-path ".") (load "init" nil t) (init-rst-ert t) (ert-deftest items-asserts () "Check some assertions." (should (equal ert-Buf-point-char "\^@")) (should (equal ert-Buf-mark-char "\^?")) ) (ert-deftest rst-convert-bullets-to-enumeration () "Tests `rst-convert-bullets-to-enumeration'." (should (ert-equal-buffer (rst-convert-bullets-to-enumeration) "\^@Normal paragraph. * A bullet * Another bullet Another normal paragraph. \^?" "\^@Normal paragraph. 1. A bullet 2. Another bullet Another normal paragraph. \^?" t)) (should (ert-equal-buffer (rst-convert-bullets-to-enumeration) "Normal paragraph. \^?* A bullet * Another bullet \^@Another normal paragraph. " "Normal paragraph. \^?1. A bullet 2. Another bullet \^@Another normal paragraph. " t)) (should (ert-equal-buffer (rst-convert-bullets-to-enumeration) "Normal paragraph. \^?* A bullet * Another bullet 1. A bullet 2. Another bullet \^@Another normal paragraph. " "Normal paragraph. \^?1. A bullet 2. Another bullet 3. A bullet 4. Another bullet \^@Another normal paragraph. " t)) ) (ert-deftest rst-convert-bullets-to-enumeration-BUGS () "Exposes bugs in `rst-convert-bullets-to-enumeration'." :expected-result :failed ;; These are bugs (should (ert-equal-buffer (rst-convert-bullets-to-enumeration) "\^@Normal paragraph. * A bullet * Another bullet * A bullet * Another bullet Another normal paragraph. \^?" "\^@Normal paragraph. 1. A bullet 2. Another bullet * A bullet * Another bullet Another normal paragraph. \^?" t)) ) (ert-deftest rst-insert-list-continue () "Tests `rst-insert-list' when continuing a list." (should (ert-equal-buffer (rst-insert-list) "* Some text\^@\n" "* Some text * \^@\n")) (should (ert-equal-buffer (rst-insert-list) "* Some \^@text\n" "* Some text * \^@\n")) (should (ert-equal-buffer (rst-insert-list) "* \^@Some text\n" "* Some text * \^@\n")) (should (ert-equal-buffer (rst-insert-list) "* Some text - A deeper hyphen bullet\^@\n" "* Some text - A deeper hyphen bullet - \^@\n")) (should (ert-equal-buffer (rst-insert-list) "* Some text - \^@Some text\n" "* Some text - Some text - \^@\n")) (should (ert-equal-buffer (rst-insert-list) "1. Some text\^@\n" "1. Some text 2. \^@\n")) (should (ert-equal-buffer (rst-insert-list) "2. Some text\^@\n" "2. Some text 3. \^@\n")) (should (ert-equal-buffer (rst-insert-list) "a) Some text\^@\n" "a) Some text b) \^@\n")) (should (ert-equal-buffer (rst-insert-list) "(A) Some text\^@\n" "(A) Some text \(B) \^@\n")) (should (ert-equal-buffer (rst-insert-list) "(I) Some text\^@\n" "(I) Some text \(J) \^@\n")) (should (ert-equal-buffer (rst-insert-list) "(I) Some text\^@\n" "(I) Some text \(J) \^@\n")) (should (ert-equal-buffer (rst-insert-list) "(h) Some text \(i) Some text\^@\n" "(h) Some text \(i) Some text \(j) \^@\n")) (should (ert-equal-buffer (rst-insert-list t) "(i) Some text\^@\n" "(i) Some text \(ii) \^@\n")) (should (ert-equal-buffer (rst-insert-list) "(iv) Some text \(v) Some text\^@\n" "(iv) Some text \(v) Some text \(vi) \^@\n")) ) (ert-deftest rst-insert-list-continue-BUGS () "Exposes bugs in `rst-insert-list-continue'." :expected-result :failed ;; These are bugs (should (ert-equal-buffer (rst-insert-list) "(iv) Some text \(v) Some text\^@\n" "(iv) Some text \(v) Some text \(vi) \^@\n"))) (ert-deftest rst-insert-list-new () "Tests `rst-insert-list' when inserting a new list." (should (ert-equal-buffer (rst-insert-list) "\^@\n" "* \^@\n" '("*"))) (should (ert-equal-buffer (rst-insert-list) "\^@\n" "- \^@\n" '("-"))) (should (ert-equal-buffer (rst-insert-list) "\^@\n" "#. \^@\n" '("#."))) (should (ert-equal-buffer (rst-insert-list) "\^@\n" "5) \^@\n" '("1)" 5))) (should (ert-equal-buffer (rst-insert-list) "\^@\n" "(i) \^@\n" '("(i)" ""))) (should (ert-equal-buffer (rst-insert-list) "\^@\n" "IV. \^@\n" '("I." 4))) (should (ert-equal-buffer (rst-insert-list) "Some line\^@\n" "Some line IV. \^@\n" '("I." 4))) (should (ert-equal-buffer (rst-insert-list) "Some line \^@\n" "Some line IV. \^@\n" '("I." 4))) (should (ert-equal-buffer (rst-insert-list) "Some line \^@\n" "Some line IV. \^@\n" '("I." 4))) ) docutils-0.12/tools/editors/emacs/tests/adornment.el0000664000175000017500000003254712026705225024614 0ustar engelbertengelbert00000000000000;; Tests for various functions handling adornments (add-to-list 'load-path ".") (load "init" nil t) (init-rst-ert t) (ert-deftest adornment-asserts () "Check some assertions." (should (equal ert-Buf-point-char "\^@")) (should (equal ert-Buf-mark-char "\^?")) ) (defun find-title-line () "Wrapper for calling `rst-find-title-line'." (apply-adornment-match (rst-find-title-line))) (ert-deftest rst-find-title-line () "Tests for `rst-find-title-line'." (should (ert-equal-buffer-return (find-title-line) " Du bon vin tous les jours. \^@ " " \^@Du bon vin tous les jours. " '((nil . nil) nil "Du bon vin tous les jours." nil) )) (should (ert-equal-buffer-return (find-title-line) " \^@ Du bon vin tous les jours. " " \^@Du bon vin tous les jours. " '((nil . nil) nil "Du bon vin tous les jours." nil) )) (should (ert-equal-buffer-return (find-title-line) " Du bon vin tous les jours. ------\^@----- " " \^@Du bon vin tous les jours. ----------- " '((?- . simple) nil "Du bon vin tous les jours." "-----------") )) (should (ert-equal-buffer-return (find-title-line) " ------\^@----- Du bon vin tous les jours. " " ----------- \^@Du bon vin tous les jours. " '((?- . nil) "-----------" "Du bon vin tous les jours." nil) )) (should (ert-equal-buffer-return (find-title-line) " \^@----------- Du bon vin tous les jours. ----------- " " ----------- \^@Du bon vin tous les jours. ----------- " '((?- . over-and-under) "-----------" "Du bon vin tous les jours." "-----------") )) (should (ert-equal-buffer-return (find-title-line) " Du bon vin tous les jours. \^@----------- Du bon vin tous les jours. ----------- " " Du bon vin tous les jours. ----------- \^@Du bon vin tous les jours. ----------- " ; This is not how the parser works but looks more logical '((?- . over-and-under) "-----------" "Du bon vin tous les jours." "-----------") )) (should (ert-equal-buffer-return (find-title-line) " \^@----------- " " \^@----------- " nil )) (should (ert-equal-buffer-return (find-title-line) " Line 1 \^@ Line 2 " " \^@Line 1 Line 2 " '((nil . nil) nil "Line 1" nil) )) (should (ert-equal-buffer-return (find-title-line) " ===================================== Project Idea: Panorama Stitcher ==================================== :Author: Martin Blais \^@ Another Title ============= " " ===================================== Project Idea: Panorama Stitcher ==================================== \^@:Author: Martin Blais Another Title ============= " '((nil . nil) nil ":Author: Martin Blais " nil) )) ) (setq text-1 "=============================== Project Idea: My Document =============================== :Author: Martin Blais Introduction ============ This is the introduction. Notes ----- Some notes. Main Points =========== Yep. Super Point ----------- ~~~~~~~~~~~ \^@ Sub Point ~~~~~~~~~~~ Isn't this fabulous? Conclusion ========== That's it, really. ") (setq text-2 " Previous -------- Current\^@ ~~~~~~~ Next ++++ ") (setq text-3 " Previous -------- Current\^@ ~~~~~~~ Next ++++ ") (ert-deftest rst-find-all-adornments () "Tests for `rst-find-all-adornments'." (should (ert-equal-buffer-return (rst-find-all-adornments) text-1 t '((2 ?= over-and-under 3) (7 ?= simple 0) (12 ?- simple 0) (17 ?= simple 0) (22 ?- simple 0) (26 ?~ over-and-under 1) (31 ?= simple 0)) )) (should (ert-equal-buffer-return (rst-find-all-adornments) text-2 t '((3 ?- simple 0) (6 ?~ simple 0) (9 ?+ simple 0)) )) (should (ert-equal-buffer-return (rst-find-all-adornments) text-3 t '((3 ?- simple 0) (6 ?~ simple 0)) )) ) (ert-deftest rst-get-hierarchy () "Tests for `rst-get-hierarchy'." (should (ert-equal-buffer-return (rst-get-hierarchy) text-1 t '((?= over-and-under 3) (?= simple 0) (?- simple 0) (?~ over-and-under 1)) )) ) (ert-deftest rst-get-hierarchy-ignore () "Tests for `rst-get-hierarchy' with ignoring a line." (should (ert-equal-buffer-return (rst-get-hierarchy 26) text-1 t '((?= over-and-under 3) (?= simple 0) (?- simple 0)) )) ) (ert-deftest rst-adornment-level () "Tests for `rst-adornment-level'." (should (ert-equal-buffer-return (rst-adornment-level t) text-1 t t )) (should (ert-equal-buffer-return (rst-adornment-level nil) text-1 t nil )) (should (ert-equal-buffer-return (rst-adornment-level (?= . over-and-under)) text-1 t 1 )) (should (ert-equal-buffer-return (rst-adornment-level (?= . simple)) text-1 t 2 )) (should (ert-equal-buffer-return (rst-adornment-level (?- . simple)) text-1 t 3 )) (should (ert-equal-buffer-return (rst-adornment-level (?~ . over-and-under)) text-1 t 4 )) (should (ert-equal-buffer-return (rst-adornment-level (?# . simple)) text-1 t 5 )) ) (ert-deftest rst-adornment-complete-p () "Tests for `rst-adornment-complete-p'." (should (ert-equal-buffer-return (rst-adornment-complete-p (?= simple 0)) " \^@Vaudou " t nil)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= simple 0)) " \^@Vaudou ====== " t t)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= over-and-under 0)) " ====== \^@Vaudou ====== " t t)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= over-and-under 2)) " ========== \^@ Vaudou ========== " t t)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= simple 0)) " \^@Vaudou ===== " t nil)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= simple 0)) " \^@Vaudou ======= " t nil)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= simple 0)) " \^@Vaudou ===-== " t nil)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= over-and-under 0)) " ====== \^@Vaudou ===== " t nil)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= over-and-under 0)) " ===== \^@Vaudou ====== " t nil)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= over-and-under 0)) " ====== \^@Vaudou ===-== " t nil)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= over-and-under 0)) " ===-== \^@Vaudou ====== " t nil)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= over-and-under 0)) " ====== \^@Vaudou " t nil)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= over-and-under 0)) " ====== \^@Vaudou ------ " t nil)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= over-and-under 0)) " ========== \^@Vaudou ========= " t nil)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= over-and-under 0)) " ========= \^@Vaudou ========== " t nil)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= over-and-under 0)) " ========== \^@Vaudou ===-====== " t nil)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= over-and-under 0)) " ===-====== \^@Vaudou ========== " t nil)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= over-and-under 0)) " ========== \^@Vaudou " t nil)) (should (ert-equal-buffer-return (rst-adornment-complete-p (?= over-and-under 0)) " ========== \^@Vaudou ---------- " t nil)) ) (ert-deftest rst-get-adornments-around () "Tests for `rst-get-adornments-around'." (should (ert-equal-buffer-return (rst-get-adornments-around) " Previous -------- \^@Current Next ++++ " t '((?- simple 0) (?+ simple 0)))) (should (ert-equal-buffer-return (rst-get-adornments-around) " Previous -------- Current\^@ ~~~~~~~ Next ++++ " t '((?- simple 0) (?+ simple 0)))) ) (defun apply-adornment-match (match) "Apply the MATCH to the buffer and return important data. MATCH is as returned by `rst-classify-adornment' or `rst-find-title-line'. Puts point in the beginning of the title line. Return a list consisting of (CHARACTER . STYLE) and the three embedded match groups. Return nil if MATCH is nil. Checks whether embedded match groups match match group 0." (when match (set-match-data (cdr match)) (let ((whole (match-string-no-properties 0)) (over (match-string-no-properties 1)) (text (match-string-no-properties 2)) (under (match-string-no-properties 3)) (gather "")) (if over (setq gather (concat gather over "\n"))) (if text (setq gather (concat gather text "\n"))) (if under (setq gather (concat gather under "\n"))) (if (not (string= (substring gather 0 -1) whole)) (error "Match 0 '%s' doesn't match concatenated parts '%s'" whole gather)) (goto-char (match-beginning 2)) (list (car match) over text under)))) (defun classify-adornment (beg end) "Wrapper for calling `rst-classify-adornment'." (interactive "r") (apply-adornment-match (rst-classify-adornment (buffer-substring-no-properties beg end) end))) (ert-deftest rst-classify-adornment () "Tests for `rst-classify-adornment'." (should (ert-equal-buffer-return (classify-adornment) " Du bon vin tous les jours \^@=========================\^? " nil '((?= . simple) nil "Du bon vin tous les jours" "=========================") t)) (should (ert-equal-buffer-return (classify-adornment) " Du bon vin tous les jours \^@====================\^? " nil '((?= . simple) nil "Du bon vin tous les jours" "====================") t)) (should (ert-equal-buffer-return (classify-adornment) " Du bon vin tous les jours \^@====================\^? " nil '((?= . simple) nil " Du bon vin tous les jours" "====================") t)) (should (ert-equal-buffer-return (classify-adornment) " Du bon vin tous les jours \^@-\^? " nil nil t)) (should (ert-equal-buffer-return (classify-adornment) " Du bon vin tous les jours \^@--\^? " nil nil t)) (should (ert-equal-buffer-return (classify-adornment) " Du bon vin tous les jours \^@---\^? " nil '((?- . simple) nil "Du bon vin tous les jours" "---") t)) (should (ert-equal-buffer-return (classify-adornment) " \^@~~~~~~~~~~~~~~~~~~~~~~~~~\^? Du bon vin tous les jours ~~~~~~~~~~~~~~~~~~~~~~~~~ " nil '((?~ . over-and-under) "~~~~~~~~~~~~~~~~~~~~~~~~~" "Du bon vin tous les jours" "~~~~~~~~~~~~~~~~~~~~~~~~~") t)) (should (ert-equal-buffer-return (classify-adornment) "~~~~~~~~~~~~~~~~~~~~~~~~~ Du bon vin tous les jours \^@~~~~~~~~~~~~~~~~~~~~~~~~~\^? " nil '((?~ . over-and-under) "~~~~~~~~~~~~~~~~~~~~~~~~~" "Du bon vin tous les jours" "~~~~~~~~~~~~~~~~~~~~~~~~~") t)) (should (ert-equal-buffer-return (classify-adornment) " \^@~~~~~~~~~~~~~~~~~~~~~~~~~\^? Du bon vin tous les jours ~~~~~~~~~~~~~~~~~~~~~~~~~ " nil '((?~ . over-and-under) "~~~~~~~~~~~~~~~~~~~~~~~~~" " Du bon vin tous les jours" "~~~~~~~~~~~~~~~~~~~~~~~~~") t)) (should (ert-equal-buffer-return (classify-adornment) " \^@~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\^? Du bon vin tous les jours ~~~~~~~~~~~~~~~~~~~ " nil '((?~ . over-and-under) "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" "Du bon vin tous les jours" "~~~~~~~~~~~~~~~~~~~") t)) (should (ert-equal-buffer-return (classify-adornment) " --------------------------- Du bon vin tous les jours \^@~~~~~~~~~~~~~~~~~~~~~~~~~~~\^? " nil '((?~ . simple) nil "Du bon vin tous les jours" "~~~~~~~~~~~~~~~~~~~~~~~~~~~") t)) (should (ert-equal-buffer-return (classify-adornment) "\^@---------------------------\^?" nil '(t nil "---------------------------" nil) t)) (should (ert-equal-buffer-return (classify-adornment) " \^@---------------------------\^? Du bon vin tous les jours ~~~~~~~~~~~~~~~~~~~~~~~~~~~ " nil nil t)) (should (ert-equal-buffer-return (classify-adornment) " ========================= Du bon vin tous les jours \^@=========================\^? Du bon vin " nil '((?= . over-and-under) "=========================" "Du bon vin tous les jours" "=========================") t)) (should (ert-equal-buffer-return (classify-adornment) " ========================= Du bon vin tous les jours ========================= Du bon vin \^@----------\^? " nil '((?- . simple) nil "Du bon vin" "----------") t)) (should (ert-equal-buffer-return (classify-adornment) " ========================= Du bon vin tous les jours ========================= \^@----------\^? Du bon vin ---------- " nil '((?- . over-and-under) "----------" "Du bon vin" "----------") t)) (should (ert-equal-buffer-return (classify-adornment) " ========================= Du bon vin tous les jours ========================= -------------- Du bon vin \^@--------------\^? " nil '((?- . over-and-under) "--------------" " Du bon vin" "--------------") t)) ) docutils-0.12/tools/editors/emacs/docutils.conf0000664000175000017500000000004210215427641023620 0ustar engelbertengelbert00000000000000[general] input_encoding: latin-1 docutils-0.12/tools/editors/emacs/IDEAS.rst0000664000175000017500000002465012026705225022514 0ustar engelbertengelbert00000000000000The following is a list of ideas of functionality which would be nice to have in `rst.el`. In the examples a ``@`` stands for the cursor. Convert to id ============= * Convert the region to an HTML id * For instance "Eine berschrift" to "eine-berschrift" * According the same rules as reST does this Jump to internal target ======================= * A command to jump to the internal target the point is on * A target may be * A section title * Footnotes / citations * Inline internal targets * Hyperlink target definition * Substitution definition * See hunk #26 in `rst_el-emacs_V23_1_patch1_1_2` vs. `emacs_V23_1` for some ideas Completion for directive options ================================ * Imagine :: .. list-table:: :@ with the cursor at the asterisk * There should be a command which offers all the possible options for this particular directive as completion * May be `skeleton.el` can also be useful Completion for directives ========================= * Imagine :: .. @ * There should be a command which offers all directives as completion * May be this should work for other keywords as well * May be this could work even at the beginning of the line * Completion must be bound to M-TAB * Already existing binding must be chained * May be `expand.el` can help (look in package finder)? * May be `hippie` is good here * Check `(info)autotype` Completion for user-defined elements ==================================== * Imagine :: |@ or :: [@ or :: _@ * There should be a command which offers all defined substitutions / footnotes / links as completion Insertion of link alias ======================= * Imagine :: Aspect of something =================== This is about the `aspect of something`_@ * There should be a command which asks you for an alias for the link, add the alias and change the link :: .. _aspects of something: Aspect of something =================== This is about the `aspects of something`_@ Smart use of `iimage-mode` ========================== * There is `iimage-mode` which shows ``.. image::``\s in Emacs * May be we can add a binding to toggle it TOC in speedbar =============== * If the TOC is displayed in the speedbar this could be used for permanent navigation * Probably `imenu` functionality can be used for this * See `imenu` documentation and `speedbar-use-imenu-flag` * See `speedbar` toc-mode without markup ======================= * The markup which may be contained in a section title is not useful in toc-mode and should be suppressed Sophisticated navigation in sections ==================================== * Navigation in sections similar to navigation in other structured data * Like XML, Lisp * C-M-u fr Up * C-M-d fr Down * C-M-f / C-M-b fr Forward / Backward Display of current location =========================== * Display the "section path" to the current point * Like in XML: In which element is the point? toc-mode only to a certain level ================================ * If a TOC buffer is created a prefix argument should limit the depth of the listing to the given level Imenu support or similar ======================== * Imenu could be supported * See `(elisp)Imenu` * `etags` could be supported * See `(emacs)Tags` and `etags.el` * May be this can be used for generating HTML local tags somehow? * As requested by `Convert to id`_ * Could use `complete-tag` Outline support =============== * Support for `outline-mode` / `allout-mode` would be nice * Should consider section titles * May be item lists can also be included * Using `allout-mode` is difficult * It's not customizable enough for the complex syntax of reStructuredText * However, some commands make sense * Motion commands * Exposure commands * Some alteration commands * Should be reimplemented * Key bindings need to be reused * However, care must be taken if a file uses `allout-mode` for instance by comment strings * In this case key bindings must not be overridden * A command adding / updating `allout-mode` tags could be a solution Sophisticated filling ===================== * These things must be filled special: * Definitions * Filling of :: * VeryLongWordSuchAsAnURLVeryLongWordSuchAsAnURLVeryLongWordSuchAsAnURLVeryLongWordSuchAsAnURLVeryLongWordSuchAsAnURL should work as expected by *not* breaking the line * May be `fill-nobreak-predicate` can help here * These things may not be filled at all * Literal blocks * Tables * Section headers * Link definitions * May be `fill-nobreak-predicate` can help here, too * May be defining an own `auto-fill-function` may be useful * Might prevent auto-filling of literal text * Filling of a re-indented item doesn't work as expected:: * Something just indented once more by the user though continuation line is not indented already * Alternatively indentation could indent the whole item * See `Sophisticated indentation`_ Sophisticated indentation ========================= * It should be generally possible to shift one more to the right * This makes indentation for quotes possible * But not for literal blocks * For item lists the best tab should be on the same level as the last item:: * bla @ * The second best tab should be where text starts:: * bla @ * should be used to indent in the other direction * Or may be C-u but this has a different meaning * could obsolete C-c C-r * For this the indentation needs to be determined at the start instead of per line * over list works:: Text * GGGGGG * SSSSSSSSSSSSSSS * TTTTTTTT * ZZZZZZZZ * over list doesn't work:: Text * GGGGGG * SSSSSSSSSSSSSSS * TTTTTTTT * ZZZZZZZZ * An indenting tab on the head of a list item should indent the whole list item instead of only the first line * Alternatively `fill-paragraph` could do so * See `Sophisticated filling`_ * May be `refill-mode` can be useful List to sections ================ * A command would be nice which * transforms the first level of a nested list in a region into a header * removes one level of indentation from the rest of the list Change section level by more than one step ========================================== * It would be nice if `rst-adjust` could rotate a section adornment more than one level * A modification of the semantic of the prefix arguments could do this * Non-zero numeric prefix arg n rotates n step in the given direction * Prefix arg 0 toggles overline / underline * This would be different from current setup Compiling for syntax check ========================== * Compiling with results going to `/dev/null` would be useful * This would just do a syntax check with no files lying around * Toolset choice for `rst-compile` must be by customizable if at all necessary * Customization group must be used Renumber an exisiting enumeration ================================= * Renumbering an exisiting enumeration is not possible yet Command to move across blocks ============================= * A command moving forward / backward across the content blocks of the current block would be nice * For instance: Move across all blocks contained in an item or field * This would move to the start of the sibling of the current block * Would allow to jump to the next item on the same level in a list * `forward-sexp` could be a nice binding rst-toc-insert features ======================= * The `contents::` options could be parsed to figure out how deep to render the inserted TOC * On load, detect any existing TOCs and set the properties for links * TOC insertion should have an option to add empty lines * TOC insertion should deal with multiple lines * Automatically detect if we have a `section-numbering::` in the corresponding section, to render the toc. Automatic handling of `.txt` files ================================== It would be nice to differentiate between text files using reStructuredText and other general text files. If we had a function to automatically guess whether a `.txt` file is following the reStructuredText conventions, we could trigger `rst-mode` without having to hard-code this in every text file, nor forcing the user to add a local mode variable at the top of the file. We could perform this guessing by searching for a valid adornment at the top of the document or searching for reStructuredText directives further on. Entry level for rst-straighten-adornments ========================================= * `rst-straighten-adornments` should have an entry level to start at a lower than the top level * I for one prefer a verbose style for top level titles which is not appropriate for documents without titles * Should be done by a prefix argument Support for ispell ================== * `ispell` may skip certain things * Using `ispell-skip-region-alist` * ``Code`` should be skipped * Literal text after ``::`` should be skipped * A customization should switch this on so users are not surprised Marriage with `forms-mode` ========================== * Like I married `forms-mode` with `sdf-mode` * Would allow editing a number of records with a fixed layout * The base reStructuredText file should be either * a list consisting of field lists * The separator needs to be defined, however * A section header or transition may be a useful separator * a `list-table` * a CSV file * That would call for a general support for CSV support for forms * May be `orgtbl-to-csv` in `org/org-table.el` could be useful for this Marriage with `org-mode` ======================== * May be Org mode can be utilized instead of `forms-mode` * See `orgtbl-mode` * See `orgstruct-mode` * Though this looks more like `allout-mode` Intelligent quote insertion =========================== * Use or develop something like `insert-pair` * Main use for forgotten quoting * Thus may rather quote preceding word than following one * If `forward-sexp` could be overridden `insert-pair` might me usable directly * Also add something like `delete-pair` Sophisticated alignment ======================= * May be aligning can be used to get results like this :Some: Field :Longer name: Aligned :Even longer name: More aligned * See `align.el` docutils-0.12/tools/editors/emacs/README.txt0000664000175000017500000000211211113310163022605 0ustar engelbertengelbert00000000000000.. -*- coding: utf-8 -*- ===================== Emacs Support Files ===================== :Date: $Date: 2008-11-26 19:07:47 +0100 (Mit, 26. Nov 2008) $ This directory contains the following Emacs lisp package files: * ``_: Emacs support for reStructuredText_. This file contains a major mode that provides: * Section decoration/adornment creation and updating (M. Blais); * Table-of-contents mode and insertion (M. Blais); * Font-lock syntax highlighting (S. Merten); * Some handy editing functions (D. Goodger). * Some functions for converting rest documents from within emacs (M. Blais). * ``_ subdirectory: automated tests for some of the features in rst.el. Please make sure the tests pass if you change the LISP code. Just type "make" to run the tests. To install the package, put a copy of the package file in a directory on your ``load-path`` (use ``C-h v load-path`` to check). For setup and usage details, see `Emacs Support for reStructuredText <../../../docs/user/emacs.html>`_. .. _reStructuredText: http://docutils.sourceforge.net/rst.html docutils-0.12/tools/editors/README.txt0000664000175000017500000000155210470117775021547 0ustar engelbertengelbert00000000000000====================================== Editor Support for reStructuredText_ ====================================== :Date: $Date: 2006-08-14 18:08:29 +0200 (Mon, 14. Aug 2006) $ The files in this directory contain support code for reStructuredText editing for the following editors: * `Emacs `__: see the `README `__ and `Emacs Support for reStructuredText <../../docs/user/emacs.html>`_. External links: * `reStructuredText syntax highlighting mode for vim `__ * `VST (Vim reStructured Text) is a plugin for Vim7 with folding for reST `__ * `rst mode `__ for the `JED`_ programmers editor Additions are welcome. .. _reStructuredText: http://docutils.sf.net/rst.html .. _JED: http://www.jedsoft.org/jed/ docutils-0.12/tools/quicktest.py0000775000175000017500000001531211766220707020767 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: quicktest.py 7442 2012-06-13 23:27:03Z milde $ # Authors: Garth Kidd ; # David Goodger # Copyright: This module has been placed in the public domain. try: import locale locale.setlocale(locale.LC_ALL, '') except: pass import sys import os import getopt import docutils from docutils.frontend import OptionParser from docutils.utils import new_document from docutils.parsers.rst import Parser usage_header = """\ quicktest.py: Quickly test the reStructuredText parser. This is not an interface to the full functionality of Docutils. Use one of the ``rst2*.py`` front-end tools instead. Usage:: quicktest.py [options] [ []] ``source`` is the name of the file to use as input (default is stdin). ``destination`` is the name of the file to create as output (default is stdout). Options: """ options = [('pretty', 'p', 'output pretty pseudo-xml: no "&abc;" entities (default)'), ('test', 't', 'output test-ready data (input & expected output, ' 'ready to be copied to a parser test module)'), ('rawxml', 'r', 'output raw XML'), ('styledxml=', 's', 'output raw XML with XSL style sheet ' 'reference (filename supplied in the option argument)'), ('xml', 'x', 'output pretty XML (indented)'), ('attributes', 'A', 'dump document attributes after processing'), ('debug', 'd', 'debug mode (lots of output)'), ('version', 'V', 'show Docutils version then exit'), ('help', 'h', 'show help text then exit')] """See ``distutils.fancy_getopt.FancyGetopt.__init__`` for a description of the data structure: (long option, short option, description).""" def usage(): print(usage_header) for longopt, shortopt, description in options: if longopt[-1:] == '=': opts = '-%s arg, --%sarg' % (shortopt, longopt) else: opts = '-%s, --%s' % (shortopt, longopt) sys.stdout.write('%-15s' % opts) if len(opts) > 14: sys.stdout.write('%-16s' % '\n') while len(description) > 60: limit = description.rindex(' ', 0, 60) print(description[:limit].strip()) description = description[limit + 1:] sys.stdout.write('%-15s' % ' ') print(description) def _pretty(input, document, optargs): return document.pformat() def _rawxml(input, document, optargs): return document.asdom().toxml() def _styledxml(input, document, optargs): docnode = document.asdom().childNodes[0] return '%s\n%s\n%s' % ( '', '' % optargs['styledxml'], docnode.toxml()) def _prettyxml(input, document, optargs): return document.asdom().toprettyxml(' ', '\n') def _test(input, document, optargs): tq = '"""' output = document.pformat() # same as _pretty() return """\ totest['change_this_test_name'] = [ [%s\\ %s %s, %s\\ %s %s], ] """ % ( tq, escape(input.rstrip()), tq, tq, escape(output.rstrip()), tq ) def escape(text): """ Return `text` in triple-double-quoted Python string form. """ text = text.replace('\\', '\\\\') # escape backslashes text = text.replace('"""', '""\\"') # break up triple-double-quotes text = text.replace(' \n', ' \\n\\\n') # protect trailing whitespace return text _outputFormatters = { 'rawxml': _rawxml, 'styledxml': _styledxml, 'xml': _prettyxml, 'pretty' : _pretty, 'test': _test } def format(outputFormat, input, document, optargs): formatter = _outputFormatters[outputFormat] return formatter(input, document, optargs) def getArgs(): if os.name == 'mac' and len(sys.argv) <= 1: return macGetArgs() else: return posixGetArgs(sys.argv[1:]) def posixGetArgs(argv): outputFormat = 'pretty' # convert fancy_getopt style option list to getopt.getopt() arguments shortopts = ''.join([option[1] + ':' * (option[0][-1:] == '=') for option in options if option[1]]) longopts = [option[0] for option in options if option[0]] try: opts, args = getopt.getopt(argv, shortopts, longopts) except getopt.GetoptError: usage() sys.exit(2) optargs = {'debug': 0, 'attributes': 0} for o, a in opts: if o in ['-h', '--help']: usage() sys.exit() elif o in ['-V', '--version']: sys.stderr.write('quicktest.py (Docutils %s [%s])\n' % (docutils.__version__, docutils.__version_details__)) sys.exit() elif o in ['-r', '--rawxml']: outputFormat = 'rawxml' elif o in ['-s', '--styledxml']: outputFormat = 'styledxml' optargs['styledxml'] = a elif o in ['-x', '--xml']: outputFormat = 'xml' elif o in ['-p', '--pretty']: outputFormat = 'pretty' elif o in ['-t', '--test']: outputFormat = 'test' elif o in ['--attributes', '-A']: optargs['attributes'] = 1 elif o in ['-d', '--debug']: optargs['debug'] = 1 else: raise getopt.GetoptError("getopt should have saved us!") if len(args) > 2: print('Maximum 2 arguments allowed.') usage() sys.exit(1) inputFile = sys.stdin outputFile = sys.stdout if args: inputFile = open(args.pop(0)) if args: outputFile = open(args.pop(0), 'w') return inputFile, outputFile, outputFormat, optargs def macGetArgs(): import EasyDialogs EasyDialogs.Message("""\ Use the next dialog to build a command line: 1. Choose an output format from the [Option] list 2. Click [Add] 3. Choose an input file: [Add existing file...] 4. Save the output: [Add new file...] 5. [OK]""") optionlist = [(longopt, description) for (longopt, shortopt, description) in options] argv = EasyDialogs.GetArgv(optionlist=optionlist, addfolder=0) return posixGetArgs(argv) def main(): # process cmdline arguments: inputFile, outputFile, outputFormat, optargs = getArgs() settings = OptionParser(components=(Parser,)).get_default_values() settings.debug = optargs['debug'] parser = Parser() input = inputFile.read() document = new_document(inputFile.name, settings) parser.parse(input, document) output = format(outputFormat, input, document, optargs) outputFile.write(output) if optargs['attributes']: import pprint pprint.pprint(document.__dict__) if __name__ == '__main__': sys.stderr = sys.stdout main() docutils-0.12/tools/rst2latex.py0000775000175000017500000000143211171617341020673 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: rst2latex.py 5905 2009-04-16 12:04:49Z milde $ # Author: David Goodger # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing LaTeX. """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline description = ('Generates LaTeX documents from standalone reStructuredText ' 'sources. ' 'Reads from (default is stdin) and writes to ' ' (default is stdout). See ' ' for ' 'the full reference.') publish_cmdline(writer_name='latex', description=description) docutils-0.12/tools/rst2pseudoxml.py0000775000175000017500000000113410434150472021573 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: rst2pseudoxml.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing pseudo-XML. """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates pseudo-XML from standalone reStructuredText ' 'sources (for testing purposes). ' + default_description) publish_cmdline(description=description) docutils-0.12/tools/dev/0000775000175000017500000000000012356234260017145 5ustar engelbertengelbert00000000000000docutils-0.12/tools/dev/profile_docutils.py0000775000175000017500000000163611766220707023103 0ustar engelbertengelbert00000000000000#!/usr/bin/python -i # $Id: profile_docutils.py 7442 2012-06-13 23:27:03Z milde $ # Author: Lea Wiemann # Copyright: This script has been placed in the public domain. import os.path import docutils.core import hotshot.stats print('Profiler started.') os.chdir(os.path.join(os.path.dirname(docutils.__file__), '..')) print('Profiling...') prof = hotshot.Profile('docutils.prof') prof.runcall(docutils.core.publish_file, source_path='HISTORY.txt', destination_path='prof.HISTORY.html', writer_name='html') prof.close() print('Loading statistics...') print(""" stats = hotshot.stats.load('docutils.prof') stats.strip_dirs() stats.sort_stats('time') # 'cumulative'; 'calls' stats.print_stats(40) """) stats = hotshot.stats.load('docutils.prof') stats.strip_dirs() stats.sort_stats('time') stats.print_stats(40) try: exec(open(os.environ['PYTHONSTARTUP']).read()) except: pass docutils-0.12/tools/dev/unicode2rstsubs.py0000775000175000017500000001510611766220707022670 0ustar engelbertengelbert00000000000000#! /usr/bin/env python # $Id: unicode2rstsubs.py 7442 2012-06-13 23:27:03Z milde $ # Author: David Goodger # Copyright: This program has been placed in the public domain. """ unicode2subfiles.py -- produce character entity files (reSructuredText substitutions) from the W3C master unicode.xml file. This program extracts character entity and entity set information from a unicode.xml file and produces multiple reStructuredText files (in the current directory) containing substitutions. Entity sets are from ISO 8879 & ISO 9573-13 (combined), MathML, and HTML4. One or two files are produced for each entity set; a second file with a "-wide.txt" suffix is produced if there are wide-Unicode characters in the set. The input file, unicode.xml, is maintained as part of the MathML 2 Recommentation XML source, and is available from . """ import sys import os import optparse import re from xml.parsers.expat import ParserCreate usage_msg = """Usage: %s [unicode.xml]\n""" def usage(prog, status=0, msg=None): sys.stderr.write(usage_msg % prog) if msg: sys.stderr.write(msg + '\n') sys.exit(status) def main(argv=None): if argv is None: argv = sys.argv if len(argv) == 2: inpath = argv[1] elif len(argv) > 2: usage(argv[0], 2, 'Too many arguments (%s): only 1 expected.' % (len(argv) - 1)) else: inpath = 'unicode.xml' if not os.path.isfile(inpath): usage(argv[0], 1, 'No such file: "%s".' % inpath) if sys.version_info >= (3,0): infile = open(inpath, mode='rb') else: infile = open(inpath) process(infile) def process(infile): grouper = CharacterEntitySetExtractor(infile) grouper.group() grouper.write_sets() class CharacterEntitySetExtractor: """ Extracts character entity information from unicode.xml file, groups it by entity set, and writes out reStructuredText substitution files. """ unwanted_entity_sets = ['stix', # unknown, buggy set 'predefined'] header = """\ .. This data file has been placed in the public domain. .. Derived from the Unicode character mappings available from . Processed by unicode2rstsubs.py, part of Docutils: . """ def __init__(self, infile): self.infile = infile """Input unicode.xml file.""" self.parser = self.setup_parser() """XML parser.""" self.elements = [] """Stack of element names. Last is current element.""" self.sets = {} """Mapping of charent set name to set dict.""" self.charid = None """Current character's "id" attribute value.""" self.descriptions = {} """Mapping of character ID to description.""" def setup_parser(self): parser = ParserCreate() parser.StartElementHandler = self.StartElementHandler parser.EndElementHandler = self.EndElementHandler parser.CharacterDataHandler = self.CharacterDataHandler return parser def group(self): self.parser.ParseFile(self.infile) def StartElementHandler(self, name, attributes): self.elements.append(name) handler = name + '_start' if hasattr(self, handler): getattr(self, handler)(name, attributes) def EndElementHandler(self, name): assert self.elements[-1] == name, \ 'unknown end-tag %r (%r)' % (name, self.element) self.elements.pop() handler = name + '_end' if hasattr(self, handler): getattr(self, handler)(name) def CharacterDataHandler(self, data): handler = self.elements[-1] + '_data' if hasattr(self, handler): getattr(self, handler)(data) def character_start(self, name, attributes): self.charid = attributes['id'] def entity_start(self, name, attributes): set = self.entity_set_name(attributes['set']) if not set: return if set not in self.sets: print('bad set: %r' % set) return entity = attributes['id'] assert (entity not in self.sets[set] or self.sets[set][entity] == self.charid), \ ('sets[%r][%r] == %r (!= %r)' % (set, entity, self.sets[set][entity], self.charid)) self.sets[set][entity] = self.charid def description_data(self, data): self.descriptions.setdefault(self.charid, '') self.descriptions[self.charid] += data entity_set_name_pat = re.compile(r'[0-9-]*(.+)$') """Pattern to strip ISO numbers off the beginning of set names.""" def entity_set_name(self, name): """ Return lowcased and standard-number-free entity set name. Return ``None`` for unwanted entity sets. """ match = self.entity_set_name_pat.match(name) name = match.group(1).lower() if name in self.unwanted_entity_sets: return None self.sets.setdefault(name, {}) return name def write_sets(self): sets = list(self.sets.keys()) sets.sort() for set_name in sets: self.write_set(set_name) def write_set(self, set_name, wide=None): if wide: outname = set_name + '-wide.txt' else: outname = set_name + '.txt' outfile = open(outname, 'w') print('writing file "%s"' % outname) outfile.write(self.header + '\n') set = self.sets[set_name] entities = [(e.lower(), e) for e in set.keys()] entities.sort() longest = 0 for _, entity_name in entities: longest = max(longest, len(entity_name)) has_wide = None for _, entity_name in entities: has_wide = self.write_entity( set, set_name, entity_name, outfile, longest, wide) or has_wide if has_wide and not wide: self.write_set(set_name, 1) def write_entity(self, set, set_name, entity_name, outfile, longest, wide=None): charid = set[entity_name] if not wide: for code in charid[1:].split('-'): if int(code, 16) > 0xFFFF: return 1 # wide-Unicode character codes = ' '.join(['U+%s' % code for code in charid[1:].split('-')]) outfile.write('.. %-*s unicode:: %s .. %s\n' % (longest + 2, '|' + entity_name + '|', codes, self.descriptions[charid])) if __name__ == '__main__': sys.exit(main()) docutils-0.12/tools/dev/create_unimap.py0000775000175000017500000000535111766220707022347 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: create_unimap.py 7442 2012-06-13 23:27:03Z milde $ # Author: Lea Wiemann # Copyright: This file has been placed in the public domain. # Call: create_unimap.py < unicode.xml > unicode_latex.py # # Get unicode.xml from # . from xml.dom import minidom import sys import pprint if sys.version_info >= (3,0): unicode = str else: bytes = str chr = unichr def w(s): if sys.version_info >= (3,0) and isinstance(s, unicode): s = s.encode('utf8') sys.stdout.write(s) text_map = {} math_map = {} class Visitor: """Node visitor for contents of unicode.xml.""" def visit_character(self, node): for n in node.childNodes: if n.nodeName == 'latex': code = node.attributes['dec'].value if '-' in code: # I don't know what this means, but we probably # don't need it.... continue if int(code) < 128: # Wrong (maps "-" to "$-$", which is too wide) and # unnecessary (maps "a" to "{a}"). continue latex_code = n.childNodes[0].nodeValue.encode('ascii').strip() if node.attributes['mode'].value == 'math': math_map[chr(int(code))] = '$%s$' % latex_code else: text_map[chr(int(code))] = '{%s}' % latex_code def call_visitor(node, visitor=Visitor()): if isinstance(node, minidom.Text): name = 'Text' else: name = node.nodeName.replace('#', '_') if hasattr(visitor, 'visit_' + name): getattr(visitor, 'visit_' + name)(node) for child in node.childNodes: call_visitor(child) if hasattr(visitor, 'depart_' + name): getattr(visitor, 'depart_' + name)(node) document = minidom.parse(sys.stdin) call_visitor(document) unicode_map = math_map unicode_map.update(text_map) # Now unicode_map contains the text entries plus dollar-enclosed math # entries for those chars for which no text entry exists. print('# $%s$' % 'Id') print('# Author: Lea Wiemann ') print('# Copyright: This file has been placed in the public domain.') print('') print('# This is a mapping of Unicode characters to LaTeX equivalents.') print('# The information has been extracted from') print('# , written by') print('# David Carlisle and Sebastian Rahtz.') print('#') print('# The extraction has been done by the "create_unimap.py" script') print('# located at .') print('') print('unicode_map = %s' % pprint.pformat(unicode_map, indent=0)) docutils-0.12/tools/dev/README.txt0000664000175000017500000000002610254137714020642 0ustar engelbertengelbert00000000000000Tools for developers. docutils-0.12/tools/rst2xetex.py0000775000175000017500000000142511565157342020724 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: rst2xetex.py 7038 2011-05-19 09:12:02Z milde $ # Author: Guenter Milde # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing XeLaTeX source code. """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline description = ('Generates XeLaTeX documents from standalone reStructuredText ' 'sources. ' 'Reads from (default is stdin) and writes to ' ' (default is stdout). See ' ' for ' 'the full reference.') publish_cmdline(writer_name='xetex', description=description) docutils-0.12/tools/test/0000775000175000017500000000000012356234260017346 5ustar engelbertengelbert00000000000000docutils-0.12/tools/test/test_buildhtml.py0000664000175000017500000000733212021072633022741 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: test_buildhtml.py 7505 2012-09-03 09:17:15Z milde $ # Author: engelbert gruber # Copyright: This module has been placed in the public domain. """ test buildhtml options, because ``--local`` is broken. Build-HTML Options ------------------ --recurse Recursively scan subdirectories for files to process. This is the default. --local Do not scan subdirectories for files to process. --prune= Do not process files in . This option may be used more than once to specify multiple directories. --ignore= Recursively ignore files or directories matching any of the given wildcard (shell globbing) patterns (separated by colons). Default: ".svn:CVS" --silent Work silently (no progress messages). Independent of "--quiet". """ import unittest import os import re try: import tempfile except ImportError: pass try: from subprocess import Popen, PIPE, STDOUT except ImportError: pass buildhtml_path = os.path.abspath(os.path.join( os.path.dirname(__file__) or os.curdir, '..', 'buildhtml.py')) def process_and_return_filelist(options): dirs = [] files = [] try: p = Popen(buildhtml_path+" "+options, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) (cin, cout) = (p.stdin, p.stdout) except NameError: cin, cout = os.popen4(buildhtml_path+" "+options) while 1: line = cout.readline() if not line: break # in Py 3x, cout.readline() returns `bytes` and the processing fails line = line.decode('ascii', 'replace') # BUG no colon in filename/path allowed item = line.split(": ")[-1].strip() if line.startswith(" "): files.append(item) else: dirs.append(item) cin.close() cout.close() return (dirs, files) class BuildHtmlTests(unittest.TestCase): tree = ( "_tmp_test_tree", "_tmp_test_tree/one.txt", "_tmp_test_tree/two.txt", "_tmp_test_tree/dir1", "_tmp_test_tree/dir1/one.txt", "_tmp_test_tree/dir1/two.txt", "_tmp_test_tree/dir2", "_tmp_test_tree/dir2/one.txt", "_tmp_test_tree/dir2/two.txt", "_tmp_test_tree/dir2/sub", "_tmp_test_tree/dir2/sub/one.txt", "_tmp_test_tree/dir2/sub/two.txt", ) def setUp(self): try: self.root = tempfile.mkdtemp() except NameError: self.root = os.tempnam() os.mkdir(self.root) for s in self.tree: s = os.path.join(self.root, s) if not "." in s: os.mkdir(s) else: fd_s = open(s, "w") fd_s.write("dummy") fd_s.close() def tearDown(self): for i in range(len(self.tree) - 1, -1, -1): s = os.path.join(self.root, self.tree[i]) if not "." in s: os.rmdir(s) else: os.remove(s) os.rmdir(self.root) def test_1(self): opts = "--dry-run "+ self.root dirs, files = process_and_return_filelist( opts ) self.assertEqual(files.count("one.txt"), 4) def test_local(self): opts = "--dry-run --local "+ self.root dirs, files = process_and_return_filelist( opts ) self.assertEqual( len(dirs), 1) self.assertEqual( files, []) if __name__ == '__main__': unittest.main() docutils-0.12/tools/rst2html.py0000775000175000017500000000112510434150472020517 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: rst2html.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing HTML. """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates (X)HTML documents from standalone reStructuredText ' 'sources. ' + default_description) publish_cmdline(writer_name='html', description=description) docutils-0.12/tools/docutils.conf0000664000175000017500000000050710347137343021070 0ustar engelbertengelbert00000000000000# These entries affect all processing: [general] source-link: yes datestamp: %Y-%m-%d %H:%M UTC generator: on # These entries affect HTML output: [html4css1 writer] # Required for docutils-update, the website build system: stylesheet-path: ../docutils/writers/html4css1/html4css1.css embed-stylesheet: no field-name-limit: 20 docutils-0.12/tools/rst2odt_prepstyles.py0000775000175000017500000000324511131176750022642 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: rst2odt_prepstyles.py 5839 2009-01-07 19:09:28Z dkuhlman $ # Author: Dave Kuhlman # Copyright: This module has been placed in the public domain. """ Fix a word-processor-generated styles.odt for odtwriter use: Drop page size specifications from styles.xml in STYLE_FILE.odt. """ # # Author: Michael Schutte from lxml import etree import sys import zipfile from tempfile import mkstemp import shutil import os NAMESPACES = { "style": "urn:oasis:names:tc:opendocument:xmlns:style:1.0", "fo": "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" } def prepstyle(filename): zin = zipfile.ZipFile(filename) styles = zin.read("styles.xml") root = etree.fromstring(styles) for el in root.xpath("//style:page-layout-properties", namespaces=NAMESPACES): for attr in el.attrib: if attr.startswith("{%s}" % NAMESPACES["fo"]): del el.attrib[attr] tempname = mkstemp() zout = zipfile.ZipFile(os.fdopen(tempname[0], "w"), "w", zipfile.ZIP_DEFLATED) for item in zin.infolist(): if item.filename == "styles.xml": zout.writestr(item, etree.tostring(root)) else: zout.writestr(item, zin.read(item.filename)) zout.close() zin.close() shutil.move(tempname[1], filename) def main(): args = sys.argv[1:] if len(args) != 1: print >> sys.stderr, __doc__ print >> sys.stderr, "Usage: %s STYLE_FILE.odt\n" % sys.argv[0] sys.exit(1) filename = args[0] prepstyle(filename) if __name__ == '__main__': main() # vim:tw=78:sw=4:sts=4:et: docutils-0.12/tools/rst2man.py0000775000175000017500000000113311242572553020333 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # Author: # Contact: grubert@users.sf.net # Copyright: This module has been placed in the public domain. """ man.py ====== This module provides a simple command line interface that uses the man page writer to output from ReStructuredText source. """ import locale try: locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description from docutils.writers import manpage description = ("Generates plain unix manual documents. " + default_description) publish_cmdline(writer=manpage.Writer(), description=description) docutils-0.12/tools/rst2odt.py0000775000175000017500000000137711131176750020354 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: rst2odt.py 5839 2009-01-07 19:09:28Z dkuhlman $ # Author: Dave Kuhlman # Copyright: This module has been placed in the public domain. """ A front end to the Docutils Publisher, producing OpenOffice documents. """ import sys try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline_to_binary, default_description from docutils.writers.odf_odt import Writer, Reader description = ('Generates OpenDocument/OpenOffice/ODF documents from ' 'standalone reStructuredText sources. ' + default_description) writer = Writer() reader = Reader() output = publish_cmdline_to_binary(reader=reader, writer=writer, description=description) docutils-0.12/tools/rst2xml.py0000775000175000017500000000113510434150472020354 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: rst2xml.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing Docutils XML. """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates Docutils-native XML from standalone ' 'reStructuredText sources. ' + default_description) publish_cmdline(writer_name='xml', description=description) docutils-0.12/tools/rst2s5.py0000775000175000017500000000120010434150472020074 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: rst2s5.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Chris Liechti # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing HTML slides using the S5 template system. """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates S5 (X)HTML slideshow documents from standalone ' 'reStructuredText sources. ' + default_description) publish_cmdline(writer_name='s5', description=description) docutils-0.12/tools/rstpep2html.py0000775000175000017500000000124110434150472021223 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: rstpep2html.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing HTML from PEP (Python Enhancement Proposal) documents. """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates (X)HTML from reStructuredText-format PEP files. ' + default_description) publish_cmdline(reader_name='pep', writer_name='pep_html', description=description) docutils-0.12/setup.py0000775000175000017500000002076112173166426016757 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: setup.py 7699 2013-07-22 08:28:06Z grubert $ # Copyright: This file has been placed in the public domain. import sys import os import glob try: from distutils.core import setup, Command from distutils.command.build import build from distutils.command.build_py import build_py if sys.version_info >= (3,): from distutils.command.build_py import build_py_2to3 from distutils.util import copydir_run_2to3 from distutils.command.install_data import install_data from distutils.util import convert_path from distutils import log except ImportError: print ('Error: The "distutils" standard module, which is required for the ') print ('installation of Docutils, could not be found. You may need to ') print ('install a package called "python-devel" (or similar) on your ') print ('system using your package manager.') sys.exit(1) if sys.version_info >= (3,): # copy-convert auxiliary python sources class copy_build_py_2to3(build_py_2to3): """Copy/convert Python source files in given directories recursively. Build py3k versions of the modules and packages. Also copy 'test/' suite and run 2to3 on *.py files. """ manifest_in = """\ exclude *.pyc *~ .DS_Store recursive-exclude * *.pyc *~ .DS_Store recursive-exclude functional/output * include functional/output/README.txt prune .svn prune */.svn prune */*/.svn prune */*/*/.svn prune */*/*/*/.svn prune */*/*/*/*/.svn """ def run(self): build_py_2to3.run(self) print("copy/convert test suite") loglevel = log.set_threshold(log.ERROR) copydir_run_2to3('test', 'test3', template=self.manifest_in) log.set_threshold(loglevel) class smart_install_data(install_data): # From , # by Pete Shinners. def run(self): #need to change self.install_dir to the library dir install_cmd = self.get_finalized_command('install') self.install_dir = getattr(install_cmd, 'install_lib') return install_data.run(self) class build_data(Command): def initialize_options(self): pass def finalize_options(self): pass def run(self): build_py = self.get_finalized_command('build_py') data_files = self.distribution.data_files for f in data_files: dir = convert_path(f[0]) dir = os.path.join(build_py.build_lib, dir) self.mkpath(dir) for data in f[1]: data = convert_path(data) self.copy_file(data, dir) # let our build_data run build.sub_commands.append(('build_data', lambda *a: True)) def do_setup(): kwargs = package_data.copy() kwargs['classifiers'] = classifiers # Install data files properly. kwargs['cmdclass'] = {'build_data': build_data, 'install_data': smart_install_data} # Auto-convert source code for Python 3 if sys.version_info >= (3,): kwargs['cmdclass']['build_py'] = copy_build_py_2to3 else: kwargs['cmdclass']['build_py'] = build_py dist = setup(**kwargs) return dist s5_theme_files = [] for dir in glob.glob('docutils/writers/s5_html/themes/*'): if os.path.isdir(dir): theme_files = glob.glob('%s/*' % dir) s5_theme_files.append((dir, theme_files)) package_data = { 'name': 'docutils', 'description': 'Docutils -- Python Documentation Utilities', 'long_description': """\ Docutils is a modular system for processing documentation into useful formats, such as HTML, XML, and LaTeX. For input Docutils supports reStructuredText, an easy-to-read, what-you-see-is-what-you-get plaintext markup syntax.""", # wrap at col 60 'url': 'http://docutils.sourceforge.net/', 'version': '0.12', 'author': 'David Goodger', 'author_email': 'goodger@python.org', 'maintainer': 'docutils-develop list', 'maintainer_email': 'docutils-develop@lists.sourceforge.net', 'license': 'public domain, Python, 2-Clause BSD, GPL 3 (see COPYING.txt)', 'platforms': 'OS-independent', 'package_dir': {'docutils': 'docutils', 'docutils.tools': 'tools'}, 'packages': ['docutils', 'docutils.languages', 'docutils.parsers', 'docutils.parsers.rst', 'docutils.parsers.rst.directives', 'docutils.parsers.rst.languages', 'docutils.readers', # 'docutils.readers.python', # in the sandbox since 0.8 'docutils.transforms', 'docutils.utils', 'docutils.utils.math', 'docutils.writers', 'docutils.writers.html4css1', # 'docutils.writers.html4strict', # in the sandbox! 'docutils.writers.pep_html', 'docutils.writers.s5_html', 'docutils.writers.latex2e', # 'docutils.writers.newlatex2e', # in the sandbox since 0.8 'docutils.writers.xetex', 'docutils.writers.odf_odt', ], 'data_files': ([('docutils/parsers/rst/include', glob.glob('docutils/parsers/rst/include/*.txt')), ('docutils/writers/html4css1', ['docutils/writers/html4css1/html4css1.css', 'docutils/writers/html4css1/math.css', 'docutils/writers/html4css1/template.txt']), ('docutils/writers/latex2e', ['docutils/writers/latex2e/default.tex', 'docutils/writers/latex2e/titlepage.tex', 'docutils/writers/latex2e/xelatex.tex',]), ('docutils/writers/pep_html', ['docutils/writers/pep_html/pep.css', 'docutils/writers/pep_html/template.txt']), ('docutils/writers/s5_html/themes', ['docutils/writers/s5_html/themes/README.txt']), ('docutils/writers/odf_odt', ['docutils/writers/odf_odt/styles.odt']), ] + s5_theme_files), 'scripts' : ['tools/rst2html.py', 'tools/rst2s5.py', 'tools/rst2latex.py', 'tools/rst2xetex.py', 'tools/rst2man.py', 'tools/rst2xml.py', 'tools/rst2pseudoxml.py', 'tools/rstpep2html.py', 'tools/rst2odt.py', 'tools/rst2odt_prepstyles.py', ],} """Distutils setup parameters.""" classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Other Audience', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: Public Domain', 'License :: OSI Approved :: Python Software Foundation License', 'License :: OSI Approved :: BSD License', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Documentation', 'Topic :: Software Development :: Documentation', 'Topic :: Text Processing', 'Natural Language :: English', # main/default language, keep first 'Natural Language :: Afrikaans', 'Natural Language :: Catalan', 'Natural Language :: Chinese (Simplified)', 'Natural Language :: Chinese (Traditional)', 'Natural Language :: Czech', 'Natural Language :: Dutch', 'Natural Language :: Esperanto', 'Natural Language :: Finnish', 'Natural Language :: French', 'Natural Language :: Galician', 'Natural Language :: German', 'Natural Language :: Italian', 'Natural Language :: Japanese', 'Natural Language :: Polish', 'Natural Language :: Portuguese (Brazilian)', 'Natural Language :: Russian', 'Natural Language :: Slovak', 'Natural Language :: Spanish', 'Natural Language :: Swedish', ] # BUG pypi did not like fllowing languages # 'Natural Language :: Lithuanian', """Trove classifiers for the Distutils "register" command.""" if __name__ == '__main__' : do_setup() docutils-0.12/COPYING.txt0000664000175000017500000001263312037252704017104 0ustar engelbertengelbert00000000000000================== Copying Docutils ================== :Author: David Goodger :Contact: goodger@python.org :Date: $Date: 2012-10-16 14:40:36 +0200 (Die, 16. Okt 2012) $ :Web site: http://docutils.sourceforge.net/ :Copyright: This document has been placed in the public domain. Most of the files included in this project have been placed in the public domain, and therefore have no license requirements and no restrictions on copying or usage; see the `Public Domain Dedication`_ below. There are a few exceptions_, listed below. Files in the Sandbox_ are not distributed with Docutils releases and may have different license terms. Public Domain Dedication ======================== The persons who have associated their work with this project (the "Dedicator": David Goodger and the many contributors to the Docutils project) hereby dedicate the entire copyright, less the exceptions_ listed below, in the work of authorship known as "Docutils" identified below (the "Work") to the public domain. The primary repository for the Work is the Internet World Wide Web site . The Work consists of the files within the "docutils" module of the Docutils project Subversion repository (Internet host docutils.svn.sourceforge.net, filesystem path /svnroot/docutils), whose Internet web interface is located at . Files dedicated to the public domain may be identified by the inclusion, near the beginning of each file, of a declaration of the form:: Copyright: This document/module/DTD/stylesheet/file/etc. has been placed in the public domain. Dedicator makes this dedication for the benefit of the public at large and to the detriment of Dedicator's heirs and successors. Dedicator intends this dedication to be an overt act of relinquishment in perpetuity of all present and future rights under copyright law, whether vested or contingent, in the Work. Dedicator understands that such relinquishment of all rights includes the relinquishment of all rights to enforce (by lawsuit or otherwise) those copyrights in the Work. Dedicator recognizes that, once placed in the public domain, the Work may be freely reproduced, distributed, transmitted, used, modified, built upon, or otherwise exploited by anyone for any purpose, commercial or non-commercial, and in any way, including by methods that have not yet been invented or conceived. (This dedication is derived from the text of the `Creative Commons Public Domain Dedication`. [#]_) .. [#] Creative Commons has `retired this legal tool`__ and does not recommend that it be applied to works: This tool is based on United States law and may not be applicable outside the US. For dedicating new works to the public domain, Creative Commons recommend the replacement Public Domain Dedication CC0_ (CC zero, "No Rights Reserved"). So does the Free Software Foundation in its license-list_. __ http://creativecommons.org/retiredlicenses .. _CC0: http://creativecommons.org/about/cc0 Exceptions ========== The exceptions to the `Public Domain Dedication`_ above are: * docutils/writers/s5_html/themes/default/iepngfix.htc: IE5.5+ PNG Alpha Fix v1.0 by Angus Turnbull . Free usage permitted as long as this notice remains intact. * docutils/utils/math/__init__.py, docutils/utils/math/latex2mathml.py, docutils/writers/xetex/__init__.py, docutils/writers/latex2e/docutils-05-compat.sty, docs/user/docutils-05-compat.sty.txt, docutils/utils/error_reporting.py, docutils/test/transforms/test_smartquotes.py: Copyright © Günter Milde. Released under the terms of the `2-Clause BSD license`_ (`local copy `__). * docutils/utils/smartquotes.py Copyright © 2011 Günter Milde, based on `SmartyPants`_ © 2003 John Gruber (released under a 3-Clause BSD license included in the file) and smartypants.py © 2004, 2007 Chad Miller. Released under the terms of the `2-Clause BSD license`_ (`local copy `__). .. _SmartyPants: http://daringfireball.net/projects/smartypants/ * docutils/utils/math/math2html.py, docutils/writers/html4css1/math.css Copyright © Alex Fernández These files are part of eLyXer_, released under the `GNU General Public License`_ version 3 or later. The author relicensed them for Docutils under the terms of the `2-Clause BSD license`_ (`local copy `__). .. _eLyXer: http://www.nongnu.org/elyxer/ * extras/roman.py, copyright by Mark Pilgrim, released under the `Python 2.1.1 license`_ (`local copy`__). __ licenses/python-2-1-1.txt * tools/editors/emacs/rst.el, copyright by Free Software Foundation, Inc., released under the `GNU General Public License`_ version 3 or later (`local copy`__). __ licenses/gpl-3-0.txt The `2-Clause BSD license`_ and the Python licenses are OSI-approved_ and GPL-compatible_. Plaintext versions of all the linked-to licenses are provided in the licenses_ directory. .. _sandbox: http://docutils.sourceforge.net/sandbox/README.html .. _licenses: licenses/ .. _Python 2.1.1 license: http://www.python.org/2.1.1/license.html .. _GNU General Public License: http://www.gnu.org/copyleft/gpl.html .. _2-Clause BSD license: http://www.spdx.org/licenses/BSD-2-Clause .. _OSI-approved: http://opensource.org/licenses/ .. _license-list: .. _GPL-compatible: http://www.gnu.org/licenses/license-list.html docutils-0.12/install.py0000775000175000017500000000125510075003131017240 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: install.py 2428 2004-07-13 15:57:13Z goodger $ # Copyright: This file has been placed in the public domain. """ This is a quick & dirty installation shortcut. It is equivalent to the command:: python setup.py install However, the shortcut lacks error checking and command-line option processing. If you need any kind of customization or help, please use one of:: python setup.py install --help python setup.py --help """ from distutils import core from setup import do_setup if __name__ == '__main__' : print __doc__ core._setup_stop_after = 'config' dist = do_setup() dist.commands = ['install'] dist.run_commands() docutils-0.12/test/0000775000175000017500000000000012356234260016206 5ustar engelbertengelbert00000000000000docutils-0.12/test/test_pickle.py0000775000175000017500000000140712054671616021100 0ustar engelbertengelbert00000000000000#! /usr/bin/env python # $Id: test_pickle.py 7539 2012-11-26 13:50:06Z milde $ # Author: David Goodger # Copyright: This module has been placed in the public domain. """ Tests of document tree pickling. """ import unittest import DocutilsTestSupport # must be imported before docutils import pickle from docutils import core class PickleTests(unittest.TestCase): def test_pickle(self): doctree = core.publish_doctree( source='Title\n=====\n\nparagraph\n', settings_overrides={'_disable_config': True}) dill = pickle.dumps(doctree) reconstituted = pickle.loads(dill) self.assertEqual(doctree.pformat(), reconstituted.pformat()) if __name__ == '__main__': unittest.main() docutils-0.12/test/test_language.py0000775000175000017500000002002112016441755021402 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: test_language.py 7503 2012-08-26 15:42:37Z grubert $ # Authors: Engelbert Gruber ; # David Goodger # Copyright: This module has been placed in the public domain. """ Tests for language module completeness. Specify a language code (e.g. "de") as a command-line parameter to test only that language. """ import sys import os import re import DocutilsTestSupport # must be imported before docutils import docutils.languages import docutils.parsers.rst.languages from docutils.parsers.rst import states, directives, roles import docutils.utils, docutils.frontend _settings = docutils.frontend.OptionParser().get_default_values() _reporter = docutils.utils.new_reporter('', _settings) reference_language = 'en' class LanguageTestSuite(DocutilsTestSupport.CustomTestSuite): language_module_pattern = re.compile('^([a-z]{2,3}(_[a-z]{2,8})*)\.py$') def __init__(self, languages=None): DocutilsTestSupport.CustomTestSuite.__init__(self) if languages: self.languages = languages else: self.get_languages() def get_languages(self): """ Get installed language translations from docutils.languages and from docutils.parsers.rst.languages. """ languages = {} for mod in (os.listdir(docutils.languages.__path__[0]) + os.listdir(docutils.parsers.rst.languages.__path__[0])): match = self.language_module_pattern.match(mod) if match: languages[match.group(1)] = 1 self.languages = languages.keys() # test language tag normalization: self.languages += ['en_gb', 'en_US', 'en-CA', 'de-DE', 'de-AT-1901', 'pt-BR', 'pt-foo-BR'] # test that locally created language files are also loaded. # requires local_dummy_lang.py in test directory (testroot) # The local_dummy_lang.py contains all the fields from both # the docutils language tags and the parser.rst language tags self.languages += ['local_dummy_lang'] def generateTests(self): for language in self.languages: for method in LanguageTestCase.test_methods: self.addTestCase(LanguageTestCase, method, None, None, id=language+'.py', language=language) class LanguageTestCase(DocutilsTestSupport.CustomTestCase): test_methods = ['test_labels', 'test_bibliographic_fields', 'test_directives', 'test_roles'] """Names of methods used to test each language.""" def __init__(self, *args, **kwargs): self.ref = docutils.languages.get_language(reference_language, _reporter) self.language = kwargs['language'] del kwargs['language'] # only wanted here DocutilsTestSupport.CustomTestCase.__init__(self, *args, **kwargs) def _xor(self, ref_dict, l_dict): """ Returns entries that are only in one dictionary. (missing_in_lang, more_than_in_ref). """ missing = [] # in ref but not in l. too_much = [] # in l but not in ref. for label in ref_dict.keys(): if label not in l_dict: missing.append(label) for label in l_dict.keys(): if label not in ref_dict: too_much.append(label) return (missing, too_much) def _invert(self, adict): """Return an inverted (keys & values swapped) dictionary.""" inverted = {} for key, value in adict.items(): inverted[value] = key return inverted def test_labels(self): try: module = docutils.languages.get_language(self.language, _reporter) if not module: raise ImportError except ImportError: self.fail('No docutils.languages.%s module.' % self.language) missed, unknown = self._xor(self.ref.labels, module.labels) if missed or unknown: self.fail('Module docutils.languages.%s.labels:\n' ' Missed: %s; Unknown: %s' % (self.language, str(missed), str(unknown))) def test_bibliographic_fields(self): try: module = docutils.languages.get_language(self.language, _reporter) if not module: raise ImportError except ImportError: self.fail('No docutils.languages.%s module.' % self.language) missed, unknown = self._xor( self._invert(self.ref.bibliographic_fields), self._invert(module.bibliographic_fields)) if missed or unknown: self.fail('Module docutils.languages.%s.bibliographic_fields:\n' ' Missed: %s; Unknown: %s' % (self.language, str(missed), str(unknown))) def test_directives(self): try: module = docutils.parsers.rst.languages.get_language( self.language) if not module: raise ImportError except ImportError: self.fail('No docutils.parsers.rst.languages.%s module.' % self.language) failures = [] for d in module.directives.keys(): try: func, msg = directives.directive(d, module, None) if not func: failures.append('"%s": unknown directive' % d) except Exception, error: failures.append('"%s": %s' % (d, error)) inverted = self._invert(module.directives) canonical = directives._directive_registry.keys() canonical.sort() canonical.remove('restructuredtext-test-directive') for name in canonical: if name not in inverted: failures.append('"%s": translation missing' % name) if failures: text = ('Module docutils.parsers.rst.languages.%s:\n %s' % (self.language, '\n '.join(failures))) if type(text) is unicode: text = text.encode('raw_unicode_escape') self.fail(text) def test_roles(self): try: module = docutils.parsers.rst.languages.get_language( self.language) if not module: raise ImportError module.roles except ImportError: self.fail('No docutils.parsers.rst.languages.%s module.' % self.language) except AttributeError: self.fail('No "roles" mapping in docutils.parsers.rst.languages.' '%s module.' % self.language) failures = [] for d in module.roles.values(): try: method = roles._role_registry[d] #if not method: # failures.append('"%s": unknown role' % d) except KeyError, error: failures.append('"%s": %s' % (d, error)) inverted = self._invert(module.roles) canonical = roles._role_registry.keys() canonical.sort() canonical.remove('restructuredtext-unimplemented-role') for name in canonical: if name not in inverted: failures.append('"%s": translation missing' % name) if failures: text = ('Module docutils.parsers.rst.languages.%s:\n %s' % (self.language, '\n '.join(failures))) if type(text) is unicode: text = text.encode('raw_unicode_escape') self.fail(text) languages_to_test = [] def suite(): s = LanguageTestSuite(languages_to_test) s.generateTests() return s def get_language_arguments(): while len(sys.argv) > 1: last = sys.argv[-1] if last.startswith('-'): break languages_to_test.append(last) sys.argv.pop() languages_to_test.reverse() if __name__ == '__main__': get_language_arguments() import unittest unittest.main(defaultTest='suite') # vim: set et ts=4 ai : docutils-0.12/test/alltests.py0000775000175000017500000000543211753277213020427 0ustar engelbertengelbert00000000000000#!/bin/sh ''''exec python -u "$0" "$@" #''' # $Id: alltests.py 7433 2012-05-11 21:03:07Z milde $ # Author: David Goodger # Copyright: This module has been placed in the public domain. __doc__ = \ """ All modules named 'test_*.py' in the current directory, and recursively in subdirectories (packages) called 'test_*', are loaded and test suites within are run. """ import time # Start point for actual elapsed time, including imports # and setup outside of unittest. start = time.time() import sys import os import DocutilsTestSupport # must be imported before docutils import docutils class Tee: """Write to a file and a stream (default: stdout) simultaneously.""" def __init__(self, filename, stream=sys.__stdout__): self.file = open(filename, 'w') self.stream = stream self.encoding = getattr(stream, 'encoding', None) def write(self, string): try: self.stream.write(string) self.file.write(string) except UnicodeEncodeError: # Py3k writing to "ascii" stream/file string = string.encode('raw_unicode_escape').decode('ascii') self.stream.write(string) self.file.write(string) def flush(self): self.stream.flush() self.file.flush() def pformat(suite): step = 4 suitestr = repr(suite).replace('=[<', '=[\n<').replace(', ', ',\n') indent = 0 output = [] for line in suitestr.splitlines(): output.append(' ' * indent + line) if line[-1:] == '[': indent += step else: if line [-5:] == ']>]>,': indent -= step * 2 elif line[-3:] == ']>,': indent -= step return '\n'.join(output) def suite(): path, script = os.path.split(sys.argv[0]) suite = package_unittest.loadTestModules(DocutilsTestSupport.testroot, 'test_', packages=1) sys.stdout.flush() return suite # must redirect stderr *before* first import of unittest sys.stdout = sys.stderr = Tee('alltests.out') import package_unittest if __name__ == '__main__': suite = suite() print ('Testing Docutils %s [%s] with Python %s on %s at %s' % (docutils.__version__, docutils.__version_details__, sys.version.split()[0], time.strftime('%Y-%m-%d'), time.strftime('%H:%M:%S'))) print 'Working directory: %s' % os.getcwd() print 'Docutils package: %s' % os.path.dirname(docutils.__file__) sys.stdout.flush() result = package_unittest.main(suite) #if package_unittest.verbosity > 1: # print >>sys.stderr, pformat(suite) # check the test suite finish = time.time() print 'Elapsed time: %.3f seconds' % (finish - start) sys.exit(not result.wasSuccessful()) docutils-0.12/test/test_transforms/0000775000175000017500000000000012356234260021443 5ustar engelbertengelbert00000000000000docutils-0.12/test/test_transforms/test_strip_comments.py0000775000175000017500000000166410434150472026131 0ustar engelbertengelbert00000000000000#! /usr/bin/env python # $Id: test_strip_comments.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger # Copyright: This module has been placed in the public domain. """ Tests for docutils.transforms.universal.StripComments. """ from __init__ import DocutilsTestSupport from docutils.transforms.universal import StripComments from docutils.parsers.rst import Parser def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite( parser, suite_settings={'strip_comments': 1}) s.generateTests(totest) return s totest = {} totest['strip_comments'] = ((StripComments,), [ ["""\ .. this is a comment Title ===== Paragraph. """, """\
Title <paragraph> Paragraph. """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����������������������������������������������������������������������������docutils-0.12/test/test_transforms/test_contents.py�������������������������������������������������0000775�0001750�0001750�00000024643�10434150472�024722� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_contents.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for `docutils.transforms.parts.Contents` (via `docutils.transforms.universal.LastReaderPending`). """ from __init__ import DocutilsTestSupport from docutils.transforms.references import Substitutions from docutils.parsers.rst import Parser def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite(parser) s.generateTests(totest) return s totest = {} totest['tables_of_contents'] = ((Substitutions,), [ ["""\ .. contents:: Title 1 ======= Paragraph 1. Title_ 2 -------- Paragraph 2. _`Title` 3 `````````` Paragraph 3. Title 4 ------- Paragraph 4. """, """\ <document source="test data"> <topic classes="contents" ids="contents" names="contents"> <title> Contents <bullet_list> <list_item> <paragraph> <reference ids="id1" refid="title-1"> Title 1 <bullet_list> <list_item> <paragraph> <reference ids="id2" refid="title-2"> Title 2 <bullet_list> <list_item> <paragraph> <reference ids="id3" refid="title-3"> Title 3 <list_item> <paragraph> <reference ids="id4" refid="title-4"> Title 4 <section ids="title-1" names="title\ 1"> <title refid="id1"> Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title> <reference name="Title" refname="title"> Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title refid="id3"> <target ids="title" names="title"> Title 3 <paragraph> Paragraph 3. <section ids="title-4" names="title\ 4"> <title refid="id4"> Title 4 <paragraph> Paragraph 4. """], ["""\ .. contents:: Table of Contents Title 1 ======= Paragraph 1. Title 2 ------- Paragraph 2. """, """\ <document source="test data"> <topic classes="contents" ids="table-of-contents" names="table\ of\ contents"> <title> Table of Contents <bullet_list> <list_item> <paragraph> <reference ids="id1" refid="title-1"> Title 1 <bullet_list> <list_item> <paragraph> <reference ids="id2" refid="title-2"> Title 2 <section ids="title-1" names="title\ 1"> <title refid="id1"> Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title refid="id2"> Title 2 <paragraph> Paragraph 2. """], ["""\ .. contents:: There's an image in Title 2 Title 1 ======= Paragraph 1. |Title 2| ========= Paragraph 2. .. |Title 2| image:: title2.png """, """\ <document source="test data"> <topic classes="contents" ids="there-s-an-image-in-title-2" names="there's\ an\ image\ in\ title\ 2"> <title> There's an image in Title 2 <bullet_list> <list_item> <paragraph> <reference ids="id1" refid="title-1"> Title 1 <list_item> <paragraph> <reference ids="id2" refid="title-2"> Title 2 <section ids="title-1" names="title\ 1"> <title refid="id1"> Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title refid="id2"> <image alt="Title 2" uri="title2.png"> <paragraph> Paragraph 2. <substitution_definition names="Title\ 2"> <image alt="Title 2" uri="title2.png"> """], # emacs cruft: " ["""\ .. contents:: :depth: 2 Title 1 ======= Paragraph 1. Title 2 ------- Paragraph 2. Title 3 ``````` Paragraph 3. Title 4 ------- Paragraph 4. """, """\ <document source="test data"> <topic classes="contents" ids="contents" names="contents"> <title> Contents <bullet_list> <list_item> <paragraph> <reference ids="id1" refid="title-1"> Title 1 <bullet_list> <list_item> <paragraph> <reference ids="id2" refid="title-2"> Title 2 <list_item> <paragraph> <reference ids="id3" refid="title-4"> Title 4 <section ids="title-1" names="title\ 1"> <title refid="id1"> Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title refid="id2"> Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title> Title 3 <paragraph> Paragraph 3. <section ids="title-4" names="title\ 4"> <title refid="id3"> Title 4 <paragraph> Paragraph 4. """], ["""\ Title 1 ======= .. contents:: :local: Paragraph 1. Title 2 ------- Paragraph 2. Title 3 ``````` Paragraph 3. Title 4 ------- Paragraph 4. """, """\ <document source="test data"> <section ids="title-1" names="title\ 1"> <title> Title 1 <topic classes="contents local" ids="contents" names="contents"> <bullet_list> <list_item> <paragraph> <reference ids="id1" refid="title-2"> Title 2 <bullet_list> <list_item> <paragraph> <reference ids="id2" refid="title-3"> Title 3 <list_item> <paragraph> <reference ids="id3" refid="title-4"> Title 4 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title refid="id1"> Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title refid="id2"> Title 3 <paragraph> Paragraph 3. <section ids="title-4" names="title\ 4"> <title refid="id3"> Title 4 <paragraph> Paragraph 4. """], ["""\ .. contents:: :local: Test duplicate name "Contents". Section -------- Paragraph. """, """\ <document source="test data"> <topic classes="contents local" ids="contents" names="contents"> <bullet_list> <list_item> <paragraph> <reference ids="id1" refid="section"> Section <paragraph> Test duplicate name "Contents". <section ids="section" names="section"> <title refid="id1"> Section <paragraph> Paragraph. """], ["""\ .. contents:: :backlinks: top Section -------- Paragraph. """, """\ <document source="test data"> <topic classes="contents" ids="contents" names="contents"> <title> Contents <bullet_list> <list_item> <paragraph> <reference ids="id1" refid="section"> Section <section ids="section" names="section"> <title refid="contents"> Section <paragraph> Paragraph. """], ["""\ .. contents:: :backlinks: none Section -------- Paragraph. """, """\ <document source="test data"> <topic classes="contents" ids="contents" names="contents"> <title> Contents <bullet_list> <list_item> <paragraph> <reference ids="id1" refid="section"> Section <section ids="section" names="section"> <title> Section <paragraph> Paragraph. """], ["""\ .. contents:: Degenerate case, no table of contents generated. """, """\ <document source="test data"> <paragraph> Degenerate case, no table of contents generated. """], ["""\ Title 1 ======= Paragraph 1. .. sidebar:: Contents .. contents:: :local: Title 2 ------- Paragraph 2. Title 3 ``````` Paragraph 3. """, """\ <document source="test data"> <section ids="title-1" names="title\ 1"> <title> Title 1 <paragraph> Paragraph 1. <sidebar> <title> Contents <topic classes="contents local" ids="contents" names="contents"> <bullet_list> <list_item> <paragraph> <reference ids="id1" refid="title-2"> Title 2 <bullet_list> <list_item> <paragraph> <reference ids="id2" refid="title-3"> Title 3 <section ids="title-2" names="title\ 2"> <title refid="id1"> Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title refid="id2"> Title 3 <paragraph> Paragraph 3. """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ���������������������������������������������������������������������������������������������docutils-0.12/test/test_transforms/test_sectnum.py��������������������������������������������������0000775�0001750�0001750�00000022170�10434150472�024534� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_sectnum.py 4564 2006-05-21 20:44:42Z wiemann $ # Authors: David Goodger <goodger@python.org>; Dmitry Jemerov # Copyright: This module has been placed in the public domain. """ Tests for `docutils.transforms.parts.SectNum` (via `docutils.transforms.universal.LastReaderPending`). """ from __init__ import DocutilsTestSupport from docutils.transforms.references import Substitutions from docutils.parsers.rst import Parser def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite(parser) s.generateTests(totest) return s totest = {} totest['section_numbers'] = ((Substitutions,), [ ["""\ .. sectnum:: Title 1 ======= Paragraph 1. Title 2 ------- Paragraph 2. Title 3 ``````` Paragraph 3. Title 4 ------- Paragraph 4. """, u"""\ <document source="test data"> <section ids="title-1" names="title\ 1"> <title auto="1"> <generated classes="sectnum"> 1\u00a0\u00a0\u00a0 Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title auto="1"> <generated classes="sectnum"> 1.1\u00a0\u00a0\u00a0 Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title auto="1"> <generated classes="sectnum"> 1.1.1\u00a0\u00a0\u00a0 Title 3 <paragraph> Paragraph 3. <section ids="title-4" names="title\ 4"> <title auto="1"> <generated classes="sectnum"> 1.2\u00a0\u00a0\u00a0 Title 4 <paragraph> Paragraph 4. """], ["""\ .. sectnum:: **Bold Title** ============== Paragraph 1. """, u"""\ <document source="test data"> <section ids="bold-title" names="bold\ title"> <title auto="1"> <generated classes="sectnum"> 1\u00a0\u00a0\u00a0 <strong> Bold Title <paragraph> Paragraph 1. """], ["""\ .. sectnum:: :depth: 2 Title 1 ======= Paragraph 1. Title 2 ------- Paragraph 2. Title 3 ``````` Paragraph 3. Title 4 ------- Paragraph 4. """, u"""\ <document source="test data"> <section ids="title-1" names="title\ 1"> <title auto="1"> <generated classes="sectnum"> 1\u00a0\u00a0\u00a0 Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title auto="1"> <generated classes="sectnum"> 1.1\u00a0\u00a0\u00a0 Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title> Title 3 <paragraph> Paragraph 3. <section ids="title-4" names="title\ 4"> <title auto="1"> <generated classes="sectnum"> 1.2\u00a0\u00a0\u00a0 Title 4 <paragraph> Paragraph 4. """], ["""\ .. contents:: .. sectnum:: :depth: 2 Title 1 ======= Paragraph 1. Title 2 ------- Paragraph 2. Title 3 ``````` Paragraph 3. Title 4 ------- Paragraph 4. """, u"""\ <document source="test data"> <topic classes="contents" ids="contents" names="contents"> <title> Contents <bullet_list classes="auto-toc"> <list_item> <paragraph> <reference ids="id1" refid="title-1"> <generated classes="sectnum"> 1\u00a0\u00a0\u00a0 Title 1 <bullet_list classes="auto-toc"> <list_item> <paragraph> <reference ids="id2" refid="title-2"> <generated classes="sectnum"> 1.1\u00a0\u00a0\u00a0 Title 2 <bullet_list> <list_item> <paragraph> <reference ids="id3" refid="title-3"> Title 3 <list_item> <paragraph> <reference ids="id4" refid="title-4"> <generated classes="sectnum"> 1.2\u00a0\u00a0\u00a0 Title 4 <section ids="title-1" names="title\ 1"> <title auto="1" refid="id1"> <generated classes="sectnum"> 1\u00a0\u00a0\u00a0 Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title auto="1" refid="id2"> <generated classes="sectnum"> 1.1\u00a0\u00a0\u00a0 Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title refid="id3"> Title 3 <paragraph> Paragraph 3. <section ids="title-4" names="title\ 4"> <title auto="1" refid="id4"> <generated classes="sectnum"> 1.2\u00a0\u00a0\u00a0 Title 4 <paragraph> Paragraph 4. """], ["""\ .. sectnum:: :prefix: Arbitrary- Title 1 ======= Paragraph 1. Title 2 ------- Paragraph 2. Title 3 ``````` Paragraph 3. Title 4 ------- Paragraph 4. """, u"""\ <document source="test data"> <section ids="title-1" names="title\ 1"> <title auto="1"> <generated classes="sectnum"> Arbitrary-1\u00a0\u00a0\u00a0 Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title auto="1"> <generated classes="sectnum"> Arbitrary-1.1\u00a0\u00a0\u00a0 Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title auto="1"> <generated classes="sectnum"> Arbitrary-1.1.1\u00a0\u00a0\u00a0 Title 3 <paragraph> Paragraph 3. <section ids="title-4" names="title\ 4"> <title auto="1"> <generated classes="sectnum"> Arbitrary-1.2\u00a0\u00a0\u00a0 Title 4 <paragraph> Paragraph 4. """], ["""\ .. sectnum:: :start: 3 Title 1 ======= Paragraph 1. Title 2 ------- Paragraph 2. Title 3 ``````` Paragraph 3. Title 4 ------- Paragraph 4. """, u"""\ <document source="test data"> <section ids="title-1" names="title\ 1"> <title auto="1"> <generated classes="sectnum"> 3\u00a0\u00a0\u00a0 Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title auto="1"> <generated classes="sectnum"> 3.1\u00a0\u00a0\u00a0 Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title auto="1"> <generated classes="sectnum"> 3.1.1\u00a0\u00a0\u00a0 Title 3 <paragraph> Paragraph 3. <section ids="title-4" names="title\ 4"> <title auto="1"> <generated classes="sectnum"> 3.2\u00a0\u00a0\u00a0 Title 4 <paragraph> Paragraph 4. """], ["""\ .. sectnum:: :prefix: (5.9. :suffix: ) :start: 3 Title 1 ======= Paragraph 1. Title 2 ------- Paragraph 2. Title 3 ``````` Paragraph 3. Title 4 ------- Paragraph 4. """, u"""\ <document source="test data"> <section ids="title-1" names="title\ 1"> <title auto="1"> <generated classes="sectnum"> (5.9.3)\u00a0\u00a0\u00a0 Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title auto="1"> <generated classes="sectnum"> (5.9.3.1)\u00a0\u00a0\u00a0 Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title auto="1"> <generated classes="sectnum"> (5.9.3.1.1)\u00a0\u00a0\u00a0 Title 3 <paragraph> Paragraph 3. <section ids="title-4" names="title\ 4"> <title auto="1"> <generated classes="sectnum"> (5.9.3.2)\u00a0\u00a0\u00a0 Title 4 <paragraph> Paragraph 4. """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_transforms/test_target_notes.py���������������������������������������������0000775�0001750�0001750�00000004375�10434150472�025563� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_target_notes.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for `docutils.transforms.references.TargetNotes` (via `docutils.transforms.universal.LastReaderPending`). """ from __init__ import DocutilsTestSupport from docutils.transforms.references import PropagateTargets, \ AnonymousHyperlinks, IndirectHyperlinks, ExternalTargets, \ InternalTargets, DanglingReferences, Footnotes from docutils.parsers.rst import Parser def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite(parser) s.generateTests(totest) return s totest = {} totest['tables_of_contents'] = ((PropagateTargets, AnonymousHyperlinks, IndirectHyperlinks, ExternalTargets, InternalTargets, DanglingReferences, ), [ ["""\ .. _target: http://exammple.org A reference to a target_. .. target-notes:: """, """\ <document source="test data"> <target ids="target" names="target" refuri="http://exammple.org"> <paragraph> A reference to a \n\ <reference name="target" refuri="http://exammple.org"> target \n\ <footnote_reference auto="1" ids="id2" refid="id1"> . <footnote auto="1" ids="id1" names="TARGET_NOTE:\\ id1"> <paragraph> <reference refuri="http://exammple.org"> http://exammple.org """], ["""\ .. _target: http://exammple.org A reference to a target_. .. target-notes:: :class: custom """, """\ <document source="test data"> <target ids="target" names="target" refuri="http://exammple.org"> <paragraph> A reference to a \n\ <reference name="target" refuri="http://exammple.org"> target <inline classes="custom"> \n\ <footnote_reference auto="1" classes="custom" ids="id2" refid="id1"> . <footnote auto="1" ids="id1" names="TARGET_NOTE:\\ id1"> <paragraph> <reference refuri="http://exammple.org"> http://exammple.org """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_transforms/test_writer_aux.py�����������������������������������������������0000775�0001750�0001750�00000003251�10627410160�025243� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_writer_aux.py 5174 2007-05-31 00:01:52Z wiemann $ # Author: Lea Wiemann <LeWiemann@gmail.com> # Copyright: This module has been placed in the public domain. """ Test module for writer_aux transforms. """ from __init__ import DocutilsTestSupport # must be imported before docutils from docutils.transforms import writer_aux from docutils.parsers.rst import Parser def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite(parser) s.generateTests(totest) return s totest = {} totest['compound'] = ((writer_aux.Compound,), [ ["""\ .. class:: compound .. compound:: .. class:: paragraph1 Paragraph 1. .. class:: paragraph2 Paragraph 2. Block quote. """, """\ <document source="test data"> <paragraph classes="paragraph1 compound"> Paragraph 1. <paragraph classes="paragraph2 continued"> Paragraph 2. <block_quote classes="continued"> <paragraph> Block quote. """], ]) totest['admonitions'] = ((writer_aux.Admonitions,), [ ["""\ .. note:: These are the note contents. Another paragraph. """, """\ <document source="test data"> <admonition classes="note"> <title> Note <paragraph> These are the note contents. <paragraph> Another paragraph. """], ["""\ .. admonition:: Generic Admonitions contents... """, """\ <document source="test data"> <admonition classes="admonition-generic admonition"> <title> Generic <paragraph> Admonitions contents... """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_transforms/test_hyperlinks.py�����������������������������������������������0000775�0001750�0001750�00000063106�12117443017�025252� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_hyperlinks.py 7629 2013-03-11 21:01:03Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for docutils.transforms.references.Hyperlinks. """ from __init__ import DocutilsTestSupport from docutils.transforms.references import PropagateTargets, \ AnonymousHyperlinks, IndirectHyperlinks, ExternalTargets, \ InternalTargets, DanglingReferences from docutils.parsers.rst import Parser def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite(parser) s.generateTests(totest) return s totest = {} # Exhaustive listing of hyperlink variations: every combination of # target/reference, direct/indirect, internal/external, and named/anonymous, # plus embedded URIs. totest['exhaustive_hyperlinks'] = ((PropagateTargets, AnonymousHyperlinks, IndirectHyperlinks, ExternalTargets, InternalTargets, DanglingReferences), [ ["""\ direct_ external .. _direct: http://direct """, """\ <document source="test data"> <paragraph> <reference name="direct" refuri="http://direct"> direct external <target ids="direct" names="direct" refuri="http://direct"> """], ["""\ indirect_ external .. _indirect: xtarget_ .. _xtarget: http://indirect """, """\ <document source="test data"> <paragraph> <reference name="indirect" refuri="http://indirect"> indirect external <target ids="indirect" names="indirect" refuri="http://indirect"> <target ids="xtarget" names="xtarget" refuri="http://indirect"> """], ["""\ .. _direct: direct_ internal """, """\ <document source="test data"> <target refid="direct"> <paragraph ids="direct" names="direct"> <reference name="direct" refid="direct"> direct internal """], ["""\ .. _ztarget: indirect_ internal .. _indirect2: ztarget_ .. _indirect: indirect2_ """, """\ <document source="test data"> <target refid="ztarget"> <paragraph ids="ztarget" names="ztarget"> <reference name="indirect" refid="ztarget"> indirect internal <target ids="indirect2" names="indirect2" refid="ztarget"> <target ids="indirect" names="indirect" refid="ztarget"> """], ["""\ Implicit -------- indirect_ internal .. _indirect: implicit_ """, """\ <document source="test data"> <section ids="implicit" names="implicit"> <title> Implicit <paragraph> <reference name="indirect" refid="implicit"> indirect internal <target ids="indirect" names="indirect" refid="implicit"> """], ["""\ Implicit -------- `multiply-indirect`_ internal .. _multiply-indirect: indirect_ .. _indirect: implicit_ """, """\ <document source="test data"> <section ids="implicit" names="implicit"> <title> Implicit <paragraph> <reference name="multiply-indirect" refid="implicit"> multiply-indirect internal <target ids="multiply-indirect" names="multiply-indirect" refid="implicit"> <target ids="indirect" names="indirect" refid="implicit"> """], ["""\ circular_ indirect reference .. _circular: indirect_ .. _indirect: circular_ """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> circular_ indirect reference <target ids="circular" names="circular" refid="circular"> <problematic ids="id3 indirect" names="indirect" refid="id1"> .. _indirect: circular_ <system_message backrefs="id2 id3" ids="id1" level="3" line="3" source="test data" type="ERROR"> <paragraph> Indirect hyperlink target "circular" (id="circular") refers to target "indirect", forming a circular reference. """], ["""\ Implicit -------- Duplicate implicit targets. Implicit -------- indirect_ internal .. _indirect: implicit_ Direct internal reference: Implicit_ """, """\ <document source="test data"> <section dupnames="implicit" ids="implicit"> <title> Implicit <paragraph> Duplicate implicit targets. <section dupnames="implicit" ids="id1"> <title> Implicit <system_message backrefs="id1" level="1" line="7" source="test data" type="INFO"> <paragraph> Duplicate implicit target name: "implicit". <paragraph> <problematic ids="id3" refid="id2"> indirect_ internal <target ids="indirect" names="indirect" refname="implicit"> <paragraph> Direct internal reference: <problematic ids="id5" refid="id4"> Implicit_ <system_message backrefs="id3" ids="id2" level="3" line="11" source="test data" type="ERROR"> <paragraph> Indirect hyperlink target "indirect" (id="indirect") refers to target "implicit", which is a duplicate, and cannot be used as a unique reference. <system_message backrefs="id5" ids="id4" level="3" line="13" source="test data" type="ERROR"> <paragraph> Duplicate target name, cannot be used as a unique reference: "implicit". """], ["""\ `direct external`__ __ http://direct """, """\ <document source="test data"> <paragraph> <reference anonymous="1" name="direct external" refuri="http://direct"> direct external <target anonymous="1" ids="id1" refuri="http://direct"> """], ["""\ `indirect external`__ __ xtarget_ .. _xtarget: http://indirect """, """\ <document source="test data"> <paragraph> <reference anonymous="1" name="indirect external" refuri="http://indirect"> indirect external <target anonymous="1" ids="id1" refuri="http://indirect"> <target ids="xtarget" names="xtarget" refuri="http://indirect"> """], ["""\ __ `direct internal`__ """, """\ <document source="test data"> <target anonymous="1" refid="id1"> <paragraph ids="id1"> <reference anonymous="1" name="direct internal" refid="id1"> direct internal """], ["""\ .. _ztarget: `indirect internal`__ __ ztarget_ """, """\ <document source="test data"> <target refid="ztarget"> <paragraph ids="ztarget" names="ztarget"> <reference anonymous="1" name="indirect internal" refid="ztarget"> indirect internal <target anonymous="1" ids="id1" refid="ztarget"> """], ["""\ .. _ztarget: First .. _ztarget: Second `indirect internal`__ __ ztarget_ """, """\ <document source="test data"> <target dupnames="ztarget" refid="ztarget"> <paragraph ids="ztarget"> First <system_message backrefs="id1" level="2" line="5" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "ztarget". <target dupnames="ztarget" refid="id1"> <paragraph ids="id1"> Second <paragraph> <problematic ids="id4" refid="id3"> `indirect internal`__ <target anonymous="1" ids="id2" refname="ztarget"> <system_message backrefs="id4" ids="id3" level="3" line="11" source="test data" type="ERROR"> <paragraph> Indirect hyperlink target (id="id2") refers to target "ztarget", which is a duplicate, and cannot be used as a unique reference. """], ["""\ The next anonymous hyperlink reference is parsed (and discarded) at some point, but nonetheless anonymous hyperlink references and targets match in this snippet. .. |invalid| replace:: anonymous__ hyperlink__ __ URL """, """\ <document source="test data"> <paragraph> The next anonymous hyperlink reference is parsed (and discarded) at some point, but nonetheless anonymous hyperlink references and targets match in this snippet. <system_message level="3" line="5" source="test data" type="ERROR"> <paragraph> Substitution definition contains illegal element: <literal_block xml:space="preserve"> <reference anonymous="1" name="anonymous"> anonymous <literal_block xml:space="preserve"> .. |invalid| replace:: anonymous__ <paragraph> <reference anonymous="1" name="hyperlink" refuri="URL"> hyperlink <target anonymous="1" ids="id1" refuri="URL"> """], ["""\ An `embedded uri <http://direct>`_. Another reference to the same `embedded URI`_. """, """\ <document source="test data"> <paragraph> An \n\ <reference name="embedded uri" refuri="http://direct"> embedded uri <target ids="embedded-uri" names="embedded\ uri" refuri="http://direct"> . <paragraph> Another reference to the same \n\ <reference name="embedded URI" refuri="http://direct"> embedded URI . """], ["""\ An `anonymous embedded uri <http://direct>`__. """, """\ <document source="test data"> <paragraph> An \n\ <reference name="anonymous embedded uri" refuri="http://direct"> anonymous embedded uri . """], ["""\ An `embedded alias <alias_>`_. Another reference to the same `embedded alias`_. .. _alias: ham.py """, """\ <document source="test data"> <paragraph> An \n\ <reference name="embedded alias" refuri="ham.py"> embedded alias <target names="embedded\ alias" refuri="ham.py"> . <paragraph> Another reference to the same \n\ <reference name="embedded alias" refuri="ham.py"> embedded alias . <target ids="alias" names="alias" refuri="ham.py"> """], ["""\ An `anonymous embedded alias <redirect_>`__. .. _redirect: spam.py """, """\ <document source="test data"> <paragraph> An \n\ <reference name="anonymous embedded alias" refuri="spam.py"> anonymous embedded alias . <target ids="redirect" names="redirect" refuri="spam.py"> """], ["""\ An `embedded alias <alias_>`_ with unknown reference. """, """\ <document source="test data"> <paragraph> An \n\ <problematic ids="id3" refid="id2"> `embedded alias <alias_>`_ <target names="embedded\ alias" refname="alias"> with unknown reference. <system_message ids="id1" level="3" line="1" source="test data" type="ERROR"> <paragraph> Indirect hyperlink target "embedded alias" refers to target "alias", which does not exist. <system_message backrefs="id3" ids="id2" level="3" line="1" source="test data" type="ERROR"> <paragraph> Unknown target name: "alias". <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Hyperlink target "embedded alias" is not referenced.\ """], ["""\ An embedded URI with trailing underline: `__init__ <http:example.py.html#__init__>`__. """, """\ <document source="test data"> <paragraph> An embedded URI with trailing underline: <reference name="__init__" refuri="http:example.py.html#__init__"> __init__ . """], ["""\ Hyperlinks with angle-bracketed text need escaping. See `Element \<a>`_, `Element <b\>`_, and `Element <c>\ `_. .. _`Element <a>`: .. _`Element <b>`: .. _`Element <c>`: elements.txt """, """\ <document source="test data"> <paragraph> Hyperlinks with angle-bracketed text need escaping. <paragraph> See \n\ <reference name="Element <a>" refuri="elements.txt"> Element <a> , \n\ <reference name="Element <b>" refuri="elements.txt"> Element <b> , and \n\ <reference name="Element <c>" refuri="elements.txt"> Element <c> . <target refid="element-a"> <target refid="element-b"> <target ids="element-c element-b element-a" names="element\ <c> element\ <b> element\ <a>" refuri="elements.txt"> """], ["""\ .. _target: .. [1] Footnote; target_ """, """\ <document source="test data"> <target ids="target" names="target"> <footnote ids="id1" names="1"> <label> 1 <paragraph> Footnote; \n\ <reference name="target" refid="target"> target """], ["""\ .. _target: .. [cit] Citation; target_ """, """\ <document source="test data"> <target ids="target" names="target"> <citation ids="cit" names="cit"> <label> cit <paragraph> Citation; \n\ <reference name="target" refid="target"> target """], ]) totest['hyperlinks'] = ((PropagateTargets, AnonymousHyperlinks, IndirectHyperlinks, ExternalTargets, InternalTargets, DanglingReferences), [ ["""\ .. _internal hyperlink: This paragraph referenced. By this `internal hyperlink`_ reference. """, """\ <document source="test data"> <target refid="internal-hyperlink"> <paragraph ids="internal-hyperlink" names="internal\ hyperlink"> This paragraph referenced. <paragraph> By this \n\ <reference name="internal hyperlink" refid="internal-hyperlink"> internal hyperlink reference. """], ["""\ .. _chained: .. _internal hyperlink: This paragraph referenced. By this `internal hyperlink`_ reference as well as by this chained_ reference. The results of the transform are not visible at the XML level. """, """\ <document source="test data"> <target refid="chained"> <target refid="internal-hyperlink"> <paragraph ids="internal-hyperlink chained" names="internal\ hyperlink chained"> This paragraph referenced. <paragraph> By this \n\ <reference name="internal hyperlink" refid="internal-hyperlink"> internal hyperlink reference as well as by this \n\ <reference name="chained" refid="chained"> chained reference. <paragraph> The results of the transform are not visible at the XML level. """], ["""\ .. _chained: __ http://anonymous Anonymous__ and chained_ both refer to the same URI. """, """\ <document source="test data"> <target refid="chained"> <target anonymous="1" ids="id1 chained" names="chained" refuri="http://anonymous"> <paragraph> <reference anonymous="1" name="Anonymous" refuri="http://anonymous"> Anonymous and \n\ <reference name="chained" refuri="http://anonymous"> chained both refer to the same URI. """], ["""\ .. _a: .. _b: x """, """\ <document source="test data"> <target refid="a"> <target refid="b"> <paragraph ids="b a" names="b a"> x <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Hyperlink target "a" is not referenced. <system_message level="1" line="2" source="test data" type="INFO"> <paragraph> Hyperlink target "b" is not referenced. """], ["""\ .. _a: .. _b: a_ """, """\ <document source="test data"> <target refid="a"> <target refid="b"> <paragraph ids="b a" names="b a"> <reference name="a" refid="a"> a <system_message level="1" line="2" source="test data" type="INFO"> <paragraph> Hyperlink target "b" is not referenced. """], ["""\ .. _a: .. _b: b_ """, """\ <document source="test data"> <target refid="a"> <target refid="b"> <paragraph ids="b a" names="b a"> <reference name="b" refid="b"> b <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Hyperlink target "a" is not referenced. """], ["""\ .. _a: .. _b: a_\ b_ """, """\ <document source="test data"> <target refid="a"> <target refid="b"> <paragraph ids="b a" names="b a"> <reference name="a" refid="a"> a <reference name="b" refid="b"> b """], ["""\ .. _external hyperlink: http://uri `External hyperlink`_ reference. """, """\ <document source="test data"> <target ids="external-hyperlink" names="external\ hyperlink" refuri="http://uri"> <paragraph> <reference name="External hyperlink" refuri="http://uri"> External hyperlink reference. """], ["""\ .. _external hyperlink: http://uri .. _indirect target: `external hyperlink`_ """, """\ <document source="test data"> <target ids="external-hyperlink" names="external\ hyperlink" refuri="http://uri"> <target ids="indirect-target" names="indirect\ target" refuri="http://uri"> <system_message level="1" line="2" source="test data" type="INFO"> <paragraph> Hyperlink target "indirect target" is not referenced. """], ["""\ .. _chained: .. _external hyperlink: http://uri `External hyperlink`_ reference and a chained_ reference too. """, """\ <document source="test data"> <target refid="chained"> <target ids="external-hyperlink chained" names="external\ hyperlink chained" refuri="http://uri"> <paragraph> <reference name="External hyperlink" refuri="http://uri"> External hyperlink reference and a \n\ <reference name="chained" refuri="http://uri"> chained reference too. """], ["""\ .. _external hyperlink: http://uri .. _indirect hyperlink: `external hyperlink`_ `Indirect hyperlink`_ reference. """, """\ <document source="test data"> <target ids="external-hyperlink" names="external\ hyperlink" refuri="http://uri"> <target ids="indirect-hyperlink" names="indirect\ hyperlink" refuri="http://uri"> <paragraph> <reference name="Indirect hyperlink" refuri="http://uri"> Indirect hyperlink reference. """], ["""\ .. _external hyperlink: http://uri .. _chained: .. _indirect hyperlink: `external hyperlink`_ Chained_ `indirect hyperlink`_ reference. """, """\ <document source="test data"> <target ids="external-hyperlink" names="external\ hyperlink" refuri="http://uri"> <target refuri="http://uri"> <target ids="indirect-hyperlink chained" names="indirect\ hyperlink chained" refuri="http://uri"> <paragraph> <reference name="Chained" refuri="http://uri"> Chained \n\ <reference name="indirect hyperlink" refuri="http://uri"> indirect hyperlink reference. """], ["""\ .. __: http://full __ __ http://simplified .. _external: http://indirect.external __ external_ __ `Full syntax anonymous external hyperlink reference`__, `chained anonymous external reference`__, `simplified syntax anonymous external hyperlink reference`__, `indirect anonymous hyperlink reference`__, `internal anonymous hyperlink reference`__. """, """\ <document source="test data"> <target anonymous="1" ids="id1" refuri="http://full"> <target anonymous="1" refid="id2"> <target anonymous="1" ids="id3 id2" refuri="http://simplified"> <target ids="external" names="external" refuri="http://indirect.external"> <target anonymous="1" ids="id4" refuri="http://indirect.external"> <target anonymous="1" refid="id5"> <paragraph ids="id5"> <reference anonymous="1" name="Full syntax anonymous external hyperlink reference" refuri="http://full"> Full syntax anonymous external hyperlink reference , <reference anonymous="1" name="chained anonymous external reference" refuri="http://simplified"> chained anonymous external reference , <reference anonymous="1" name="simplified syntax anonymous external hyperlink reference" refuri="http://simplified"> simplified syntax anonymous external hyperlink reference , <reference anonymous="1" name="indirect anonymous hyperlink reference" refuri="http://indirect.external"> indirect anonymous hyperlink reference , <reference anonymous="1" name="internal anonymous hyperlink reference" refid="id5"> internal anonymous hyperlink reference . """], ["""\ Duplicate external target_'s (different URIs): .. _target: first .. _target: second """, """\ <document source="test data"> <paragraph> Duplicate external \n\ <problematic ids="id3" refid="id2"> target_ 's (different URIs): <target dupnames="target" ids="target" refuri="first"> <system_message backrefs="id1" level="2" line="5" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "target". <target dupnames="target" ids="id1" refuri="second"> <system_message backrefs="id3" ids="id2" level="3" line="1" source="test data" type="ERROR"> <paragraph> Duplicate target name, cannot be used as a unique reference: "target". """], ["""\ Duplicate external targets (different URIs) without reference: .. _target: first .. _target: second """, """\ <document source="test data"> <paragraph> Duplicate external targets (different URIs) without reference: <target dupnames="target" ids="target" refuri="first"> <system_message backrefs="id1" level="2" line="5" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "target". <target dupnames="target" ids="id1" refuri="second"> """], ["""\ Several__ anonymous__ hyperlinks__, but not enough targets. __ http://example.org """, """\ <document source="test data"> <paragraph> <problematic ids="id3" refid="id2"> Several__ \n\ <problematic ids="id4" refid="id2"> anonymous__ \n\ <problematic ids="id5" refid="id2"> hyperlinks__ , but not enough targets. <target anonymous="1" ids="id1" refuri="http://example.org"> <system_message backrefs="id3 id4 id5" ids="id2" level="3" source="test data" type="ERROR"> <paragraph> Anonymous hyperlink mismatch: 3 references but 1 targets. See "backrefs" attribute for IDs. """], ["""\ .. _external: http://uri .. _indirect: external_ .. _internal: .. image:: picture.png :target: external_ .. image:: picture.png :target: indirect_ .. image:: picture.png :target: internal_ """, """\ <document source="test data"> <target ids="external" names="external" refuri="http://uri"> <target ids="indirect" names="indirect" refuri="http://uri"> <target refid="internal"> <reference ids="internal" name="external" names="internal" refuri="http://uri"> <image uri="picture.png"> <reference name="indirect" refuri="http://uri"> <image uri="picture.png"> <reference name="internal" refid="internal"> <image uri="picture.png"> """], ["""\ .. contents:: Table of Contents .. _indirect reference to the table of contents: `table of contents`_ Section ======= Testing an `indirect reference to the table of contents`_. """, """\ <document source="test data"> <topic classes="contents" ids="table-of-contents" names="table\ of\ contents"> <title> Table of Contents <bullet_list> <list_item> <paragraph> <reference ids="id1" refid="section"> Section <target ids="indirect-reference-to-the-table-of-contents" names="indirect\ reference\ to\ the\ table\ of\ contents" refid="table-of-contents"> <section ids="section" names="section"> <title refid="id1"> Section <paragraph> Testing an <reference name="indirect reference to the table of contents" refid="table-of-contents"> indirect reference to the table of contents . """], ["""\ .. _explicit target: Title ----- Let's reference it (`explicit target`_) to avoid an irrelevant error. """, """\ <document source="test data"> <target refid="explicit-target"> <section ids="title explicit-target" names="title explicit\ target"> <title> Title <paragraph> Let's reference it ( <reference name="explicit target" refid="explicit-target"> explicit target ) to avoid an irrelevant error. """], ["""\ target1_ should refer to target2_, not the Title. .. _target1: .. _target2: URI Title ===== """, """\ <document source="test data"> <paragraph> <reference name="target1" refuri="URI"> target1 should refer to \n\ <reference name="target2" refuri="URI"> target2 , not the Title. <target refid="target1"> <target ids="target2 target1" names="target2 target1" refuri="URI"> <section ids="title" names="title"> <title> Title """], ["""\ Unknown reference_. """, """\ <document source="test data"> <paragraph> Unknown \n\ <problematic ids="id2" refid="id1"> reference_ . <system_message backrefs="id2" ids="id1" level="3" line="1" source="test data" type="ERROR"> <paragraph> Unknown target name: "reference". """], ["""\ Duplicate manual footnote labels, with reference ([1]_): .. [1] Footnote. .. [1] Footnote. """, """\ <document source="test data"> <paragraph> Duplicate manual footnote labels, with reference ( <problematic ids="id5 id1" refid="id4"> [1]_ ): <footnote dupnames="1" ids="id2"> <label> 1 <paragraph> Footnote. <footnote dupnames="1" ids="id3"> <label> 1 <system_message backrefs="id3" level="2" line="5" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "1". <paragraph> Footnote. <system_message backrefs="id5" ids="id4" level="3" line="1" source="test data" type="ERROR"> <paragraph> Duplicate target name, cannot be used as a unique reference: "1". """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_transforms/test_substitutions.py��������������������������������������������0000775�0001750�0001750�00000023560�11413643335�026024� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_substitutions.py 6351 2010-07-03 14:19:09Z gbrandl $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for docutils.transforms.references.Substitutions. """ from __init__ import DocutilsTestSupport from docutils.transforms.references import Substitutions from docutils.parsers.rst import Parser def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite(parser) s.generateTests(totest) return s totest = {} totest['substitutions'] = ((Substitutions,), [ ["""\ The |biohazard| symbol is deservedly scary-looking. .. |biohazard| image:: biohazard.png """, """\ <document source="test data"> <paragraph> The \n\ <image alt="biohazard" uri="biohazard.png"> symbol is deservedly scary-looking. <substitution_definition names="biohazard"> <image alt="biohazard" uri="biohazard.png"> """], ["""\ Here's an |unknown| substitution. """, """\ <document source="test data"> <paragraph> Here's an \n\ <problematic ids="id2" refid="id1"> |unknown| substitution. <system_message backrefs="id2" ids="id1" level="3" line="1" source="test data" type="ERROR"> <paragraph> Undefined substitution referenced: "unknown". """], [u"""\ Substitutions support case differences: .. |eacute| replace:: \u00E9 .. |Eacute| replace:: \u00C9 |Eacute|\\t\\ |eacute|, and even |EACUTE|. """, u"""\ <document source="test data"> <paragraph> Substitutions support case differences: <substitution_definition names="eacute"> \u00E9 <substitution_definition names="Eacute"> \u00C9 <paragraph> \u00C9 t \u00E9 , and even \n\ \u00C9 . """], [u"""\ Indirect substitution definitions with multiple references: |substitute| my coke for gin |substitute| you for my mum at least I'll get my washing done .. |substitute| replace:: |replace| .. |replace| replace:: swap """, u"""\ <document source="test data"> <paragraph> Indirect substitution definitions with multiple references: <paragraph> swap my coke for gin swap you for my mum at least I'll get my washing done <substitution_definition names="substitute"> swap <substitution_definition names="replace"> swap """], ["""\ .. |l| unicode:: U+00AB .. left chevron .. |r| unicode:: U+00BB .. right chevron .. |.| replace:: |l|\ ``.``\ |r| .. Delete either of the following lines, and there is no error. Regular expression |.| will match any character .. Note:: Note that |.| matches *exactly* one character """, u"""\ <document source="test data"> <substitution_definition names="l"> \xab <substitution_definition names="r"> \xbb <substitution_definition names="."> \xab <literal> . \xbb <comment xml:space="preserve"> Delete either of the following lines, and there is no error. <paragraph> Regular expression \n\ \xab <literal> . \xbb will match any character <note> <paragraph> Note that \n\ \xab <literal> . \xbb matches \n\ <emphasis> exactly one character """], ["""\ .. |sub| replace:: |sub| """, """\ <document source="test data"> <system_message level="3" line="1" names="sub" source="test data" type="ERROR"> <paragraph> Circular substitution definition detected: <literal_block xml:space="preserve"> .. |sub| replace:: |sub| """], ["""\ .. |sub| replace:: |indirect1| .. |indirect1| replace:: |indirect2| .. |indirect2| replace:: |Sub| """, """\ <document source="test data"> <system_message level="3" line="1" names="sub" source="test data" type="ERROR"> <paragraph> Circular substitution definition detected: <literal_block xml:space="preserve"> .. |sub| replace:: |indirect1| <system_message level="3" line="2" names="indirect1" source="test data" type="ERROR"> <paragraph> Circular substitution definition detected: <literal_block xml:space="preserve"> .. |indirect1| replace:: |indirect2| <system_message level="3" line="3" names="indirect2" source="test data" type="ERROR"> <paragraph> Circular substitution definition detected: <literal_block xml:space="preserve"> .. |indirect2| replace:: |Sub| """], ["""\ .. |indirect1| replace:: |indirect2| .. |indirect2| replace:: |Sub| .. |sub| replace:: |indirect1| Use |sub| and |indirect1| and |sub| again (and |sub| one more time). """, """\ <document source="test data"> <system_message level="3" line="1" names="indirect1" source="test data" type="ERROR"> <paragraph> Circular substitution definition detected: <literal_block xml:space="preserve"> .. |indirect1| replace:: |indirect2| <system_message level="3" line="2" names="indirect2" source="test data" type="ERROR"> <paragraph> Circular substitution definition detected: <literal_block xml:space="preserve"> .. |indirect2| replace:: |Sub| <system_message level="3" line="3" names="sub" source="test data" type="ERROR"> <paragraph> Circular substitution definition detected: <literal_block xml:space="preserve"> .. |sub| replace:: |indirect1| <paragraph> Use \n\ <problematic ids="id8" refid="id7"> |Sub| and \n\ <problematic ids="id2" refid="id1"> |indirect1| and \n\ <problematic ids="id4" refid="id3"> |sub| again (and \n\ <problematic ids="id6" refid="id5"> |sub| one more time). <system_message backrefs="id2" ids="id1" level="3" line="5" source="test data" type="ERROR"> <paragraph> Circular substitution definition referenced: "indirect1". <system_message backrefs="id4" ids="id3" level="3" line="5" source="test data" type="ERROR"> <paragraph> Circular substitution definition referenced: "sub". <system_message backrefs="id6" ids="id5" level="3" line="5" source="test data" type="ERROR"> <paragraph> Circular substitution definition referenced: "sub". <system_message backrefs="id8" ids="id7" level="3" source="test data" type="ERROR"> <paragraph> Circular substitution definition referenced: "Sub". """], ]) totest['unicode'] = ((Substitutions,), [ ["""\ Insert an em-dash (|mdash|), a copyright symbol (|copy|), a non-breaking space (|nbsp|), a backwards-not-equals (|bne|), and a captial omega (|Omega|). .. |mdash| unicode:: 0x02014 .. |copy| unicode:: \\u00A9 .. |nbsp| unicode::   .. |bne| unicode:: U0003D U020E5 .. |Omega| unicode:: U+003A9 """, u"""\ <document source="test data"> <paragraph> Insert an em-dash ( \u2014 ), a copyright symbol ( \u00a9 ), a non-breaking space ( \u00a0 ), a backwards-not-equals ( = \u20e5 ), and a captial omega ( \u03a9 ). <substitution_definition names="mdash"> \u2014 <substitution_definition names="copy"> \u00a9 <substitution_definition names="nbsp"> \u00a0 <substitution_definition names="bne"> = \u20e5 <substitution_definition names="Omega"> \u03a9 """], [""" Testing comments and extra text. Copyright |copy| 2003, |BogusMegaCorp (TM)|. .. |copy| unicode:: 0xA9 .. copyright sign .. |BogusMegaCorp (TM)| unicode:: BogusMegaCorp U+2122 .. with trademark sign """, u"""\ <document source="test data"> <paragraph> Testing comments and extra text. <paragraph> Copyright \n\ \u00a9 2003, \n\ BogusMegaCorp \u2122 . <substitution_definition names="copy"> \u00a9 <substitution_definition names="BogusMegaCorp\ (TM)"> BogusMegaCorp \u2122 """], ["""\ Insert an em-dash |---| automatically trimming whitespace. Some substitutions |TM| only need |rarrow| trimming on one side. .. |---| unicode:: U+02014 :trim: .. |TM| unicode:: U+02122 :ltrim: .. |rarrow| unicode:: U+2192 :rtrim: """, u"""\ <document source="test data"> <paragraph> Insert an em-dash \u2014 automatically trimming whitespace. Some substitutions \u2122 only need \n\ \u2192 trimming on one side. <substitution_definition ltrim="1" names="---" rtrim="1"> \u2014 <substitution_definition ltrim="1" names="TM"> \u2122 <substitution_definition names="rarrow" rtrim="1"> \u2192 """], ["""\ Substitution definition with an illegal element: .. |target| replace:: _`target` Make sure this substitution definition is not registered: |target| """, """\ <document source="test data"> <paragraph> Substitution definition with an illegal element: <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> Substitution definition contains illegal element: <literal_block xml:space="preserve"> <target ids="target" names="target"> target <literal_block xml:space="preserve"> .. |target| replace:: _`target` <paragraph> Make sure this substitution definition is not registered: \n\ <problematic ids="id2" refid="id1"> |target| <system_message backrefs="id2" ids="id1" level="3" line="5" source="test data" type="ERROR"> <paragraph> Undefined substitution referenced: "target". """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_transforms/test_messages.py�������������������������������������������������0000775�0001750�0001750�00000003502�10434150472�024663� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_messages.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for docutils.transforms.universal.Messages. """ from __init__ import DocutilsTestSupport from docutils.transforms.universal import Messages from docutils.transforms.references import Substitutions from docutils.parsers.rst import Parser def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite(parser) s.generateTests(totest) return s totest = {} totest['system_message_sections'] = ((Substitutions, Messages), [ ["""\ This |unknown substitution| will generate a system message, thanks to the ``Substitutions`` transform. The ``Messages`` transform will generate a "System Messages" section. (A second copy of the system message is tacked on to the end of the document by the test framework.) """, """\ <document source="test data"> <paragraph> This \n\ <problematic ids="id2" refid="id1"> |unknown substitution| will generate a system message, thanks to the \n\ <literal> Substitutions transform. The \n\ <literal> Messages transform will generate a "System Messages" section. <paragraph> (A second copy of the system message is tacked on to the end of the document by the test framework.) <section classes="system-messages"> <title> Docutils System Messages <system_message backrefs="id2" ids="id1" level="3" line="1" source="test data" type="ERROR"> <paragraph> Undefined substitution referenced: "unknown substitution". """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_transforms/test_expose_internals.py�����������������������������������������0000775�0001750�0001750�00000001734�10627410160�026440� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_expose_internals.py 5174 2007-05-31 00:01:52Z wiemann $ # Author: Lea Wiemann <LeWiemann@gmail.com> # Copyright: This module has been placed in the public domain. """ Test module for universal.ExposeInternals transform. """ from __init__ import DocutilsTestSupport # must be imported before docutils from docutils.transforms.universal import ExposeInternals from docutils.parsers.rst import Parser def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite( parser, suite_settings={'expose_internals': ['rawsource', 'source']}) s.generateTests(totest) return s totest = {} totest['transitions'] = ((ExposeInternals,), [ ["""\ This is a test. """, """\ <document internal:rawsource="" source="test data"> <paragraph internal:rawsource="This is a test." internal:source="test data"> This is a test. """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ������������������������������������docutils-0.12/test/test_transforms/test_docinfo.py��������������������������������������������������0000775�0001750�0001750�00000022141�10434150472�024475� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_docinfo.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for docutils.transforms.frontmatter.DocInfo. """ from __init__ import DocutilsTestSupport from docutils.transforms.frontmatter import DocInfo from docutils.parsers.rst import Parser def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite(parser) s.generateTests(totest) return s totest = {} totest['bibliographic_field_lists'] = ((DocInfo,), [ ["""\ .. Bibliographic element extraction. :Abstract: There can only be one abstract. It is automatically moved to the end of the other bibliographic elements. :Author: Me :Version: 1 :Date: 2001-08-11 :Parameter i: integer """, """\ <document source="test data"> <docinfo> <author> Me <version> 1 <date> 2001-08-11 <field> <field_name> Parameter i <field_body> <paragraph> integer <topic classes="abstract"> <title> Abstract <paragraph> There can only be one abstract. <paragraph> It is automatically moved to the end of the other bibliographic elements. <comment xml:space="preserve"> Bibliographic element extraction. """], ["""\ .. Bibliographic element extraction. :Abstract: Abstract 1. :Author: Me :Address: 123 My Street Example, EX :Contact: me@my.org :Version: 1 :Abstract: Abstract 2 (should generate a warning). :Date: 2001-08-11 :Parameter i: integer """, """\ <document source="test data"> <docinfo> <author> Me <address xml:space="preserve"> 123 My Street Example, EX <contact> <reference refuri="mailto:me@my.org"> me@my.org <version> 1 <field> <field_name> Abstract <field_body> <paragraph> Abstract 2 (should generate a warning). <system_message level="2" line="9" source="test data" type="WARNING"> <paragraph> There can only be one "Abstract" field. <date> 2001-08-11 <field> <field_name> Parameter i <field_body> <paragraph> integer <topic classes="abstract"> <title> Abstract <paragraph> Abstract 1. <comment xml:space="preserve"> Bibliographic element extraction. """], ["""\ :Author: - must be a paragraph :Status: a *simple* paragraph :Date: But only one paragraph. :Version: .. and not empty either """, """\ <document source="test data"> <docinfo> <field> <field_name> Author <field_body> <bullet_list bullet="-"> <list_item> <paragraph> must be a paragraph <system_message level="2" line="1" source="test data" type="WARNING"> <paragraph> Cannot extract bibliographic field "Author" containing anything other than a single paragraph. <status> a \n\ <emphasis> simple paragraph <field> <field_name> Date <field_body> <paragraph> But only one <paragraph> paragraph. <system_message level="2" line="3" source="test data" type="WARNING"> <paragraph> Cannot extract compound bibliographic field "Date". <field> <field_name> Version <field_body> <system_message level="2" line="6" source="test data" type="WARNING"> <paragraph> Cannot extract empty bibliographic field "Version". <comment xml:space="preserve"> and not empty either """], ["""\ :Authors: Me, Myself, **I** :Authors: PacMan; Ms. PacMan; PacMan, Jr. :Authors: Here There *Everywhere* :Authors: - First - Second - Third """, """\ <document source="test data"> <docinfo> <authors> <author> Me <author> Myself <author> I <authors> <author> PacMan <author> Ms. PacMan <author> PacMan, Jr. <authors> <author> Here <author> There <author> <emphasis> Everywhere <authors> <author> First <author> Second <author> Third """], ["""\ :Authors: Only One :Authors: One, Only; """, """\ <document source="test data"> <docinfo> <authors> <author> Only One <authors> <author> One, Only """], ["""\ :Authors: :Authors: 1. One 2. Two :Authors: - - :Authors: - One Two :Authors: - One Two """, """\ <document source="test data"> <docinfo> <field> <field_name> Authors <field_body> <system_message level="2" line="1" source="test data" type="WARNING"> <paragraph> Cannot extract empty bibliographic field "Authors". <field> <field_name> Authors <field_body> <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> One <list_item> <paragraph> Two <system_message level="2" line="3" source="test data" type="WARNING"> <paragraph> Bibliographic field "Authors" incompatible with extraction: it must contain either a single paragraph (with authors separated by one of ";,"), multiple paragraphs (one per author), or a bullet list with one paragraph (one author) per item. <field> <field_name> Authors <field_body> <bullet_list bullet="-"> <list_item> <list_item> <system_message level="2" line="6" source="test data" type="WARNING"> <paragraph> Bibliographic field "Authors" incompatible with extraction: it must contain either a single paragraph (with authors separated by one of ";,"), multiple paragraphs (one per author), or a bullet list with one paragraph (one author) per item. <field> <field_name> Authors <field_body> <bullet_list bullet="-"> <list_item> <paragraph> One <paragraph> Two <system_message level="2" line="10" source="test data" type="WARNING"> <paragraph> Bibliographic field "Authors" incompatible with extraction: it must contain either a single paragraph (with authors separated by one of ";,"), multiple paragraphs (one per author), or a bullet list with one paragraph (one author) per item. <field> <field_name> Authors <field_body> <bullet_list bullet="-"> <list_item> <paragraph> One <paragraph> Two <system_message level="2" line="15" source="test data" type="WARNING"> <paragraph> Bibliographic field "Authors" incompatible with extraction: it must contain either a single paragraph (with authors separated by one of ";,"), multiple paragraphs (one per author), or a bullet list with one paragraph (one author) per item. """], ["""\ .. RCS keyword extraction. :Status: (some text) $""" + """RCSfile: test_docinfo.py,v $ (more text) :Date: (some text) $""" + """Date: 2002/10/08 01:34:23 $ (more text) :Date: (some text) $""" + """Date: 2005-03-26T16:21:28.693201Z $ (more text) :Version: (some text) $""" + """Revision: 1.1 $ (more text) """, """\ <document source="test data"> <docinfo> <status> (some text) test_docinfo.py (more text) <date> (some text) 2002-10-08 (more text) <date> (some text) 2005-03-26 (more text) <version> (some text) 1.1 (more text) <comment xml:space="preserve"> RCS keyword extraction. """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_transforms/test_class.py����������������������������������������������������0000775�0001750�0001750�00000007767�10434150472�024202� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_class.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for `docutils.transforms.misc.ClassAttribute`. """ from __init__ import DocutilsTestSupport from docutils.parsers.rst import Parser def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite(parser) s.generateTests(totest) return s totest = {} totest['class'] = ((), [ ["""\ .. class:: one paragraph """, """\ <document source="test data"> <paragraph classes="one"> paragraph """], ["""\ .. class:: two .. Block quote """, """\ <document source="test data"> <comment xml:space="preserve"> <block_quote classes="two"> <paragraph> Block quote """], ["""\ Block quote .. class:: three Paragraph """, """\ <document source="test data"> <block_quote> <paragraph> Block quote <paragraph classes="three"> Paragraph """], ["""\ .. class:: four Section Title ============= Paragraph """, """\ <document source="test data"> <section classes="four" ids="section-title" names="section\ title"> <title> Section Title <paragraph> Paragraph """], ["""\ .. class:: multiple paragraph 1 paragraph 2 """, """\ <document source="test data"> <paragraph classes="multiple"> paragraph 1 <paragraph classes="multiple"> paragraph 2 """], ["""\ .. class:: multiple .. Just a comment. It's silly, but possible """, """\ <document source="test data"> <comment classes="multiple" xml:space="preserve"> Just a comment. It's silly, but possible """], ["""\ .. class:: .. class:: 99 """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "class" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> .. class:: <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> Invalid class attribute value for "class" directive: "99". <literal_block xml:space="preserve"> .. class:: 99 """], ["""\ .. class:: one .. class:: two multiple class values may be assigned to one element """, """\ <document source="test data"> <paragraph classes="one two"> multiple class values may be assigned to one element """], ["""\ .. class:: one two multiple class values may be assigned to one element """, """\ <document source="test data"> <paragraph classes="one two"> multiple class values may be assigned to one element """], ["""\ .. class:: fancy 2. List starts at 2. 3. Class should apply to list, not to system message. """, """\ <document source="test data"> <enumerated_list classes="fancy" enumtype="arabic" prefix="" start="2" suffix="."> <list_item> <paragraph> List starts at 2. <list_item> <paragraph> Class should apply to list, not to system message. <system_message level="1" line="3" source="test data" type="INFO"> <paragraph> Enumerated list start value not ordinal-1: "2" (ordinal 2) """], ["""\ 2. List starts at 2. 3. Class should apply to next paragraph, not to system message. .. class:: fancy A paragraph. """, """\ <document source="test data"> <enumerated_list enumtype="arabic" prefix="" start="2" suffix="."> <list_item> <paragraph> List starts at 2. <list_item> <paragraph> Class should apply to next paragraph, not to system message. <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Enumerated list start value not ordinal-1: "2" (ordinal 2) <paragraph classes="fancy"> A paragraph. """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ���������docutils-0.12/test/test_transforms/__init__.py������������������������������������������������������0000664�0001750�0001750�00000000462�10254646615�023564� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������import os import os.path import sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) prev = '' while sys.path[0] != prev: try: import DocutilsTestSupport break except ImportError: prev = sys.path[0] sys.path[0] = os.path.dirname(prev) sys.path.pop(0) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_transforms/test_peps.py�����������������������������������������������������0000775�0001750�0001750�00000003242�10434150472�024024� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_peps.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for docutils.transforms.peps. """ from __init__ import DocutilsTestSupport from docutils.transforms.peps import TargetNotes from docutils.parsers.rst import Parser def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite(parser) s.generateTests(totest) return s totest = {} totest['target_notes'] = ((TargetNotes,), [ ["""\ No references or targets exist, therefore no "References" section should be generated. """, """\ <document source="test data"> <paragraph> No references or targets exist, therefore no "References" section should be generated. """], ["""\ A target exists, here's the reference_. A "References" section should be generated. .. _reference: http://www.example.org """, """\ <document source="test data"> <paragraph> A target exists, here's the \n\ <reference name="reference" refname="reference"> reference \n\ <footnote_reference auto="1" ids="id3" refname="TARGET_NOTE: id2"> . A "References" section should be generated. <target ids="reference" names="reference" refuri="http://www.example.org"> <section ids="id1"> <title> References <footnote auto="1" ids="id2" names="TARGET_NOTE:\ id2"> <paragraph> <reference refuri="http://www.example.org"> http://www.example.org """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_transforms/test_footnotes.py������������������������������������������������0000775�0001750�0001750�00000036661�10434150472�025110� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_footnotes.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for docutils.transforms.references.Footnotes. """ from __init__ import DocutilsTestSupport from docutils.transforms.references import Footnotes from docutils.parsers.rst import Parser def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite(parser) s.generateTests(totest) return s totest = {} totest['footnotes'] = ((Footnotes,), [ ["""\ [#autolabel]_ .. [#autolabel] text """, """\ <document source="test data"> <paragraph> <footnote_reference auto="1" ids="id1" refid="autolabel"> 1 <footnote auto="1" backrefs="id1" ids="autolabel" names="autolabel"> <label> 1 <paragraph> text """], ["""\ autonumber: [#]_ .. [#] text """, """\ <document source="test data"> <paragraph> autonumber: \n\ <footnote_reference auto="1" ids="id1" refid="id2"> 1 <footnote auto="1" backrefs="id1" ids="id2" names="1"> <label> 1 <paragraph> text """], ["""\ [#]_ is the first auto-numbered footnote reference. [#]_ is the second auto-numbered footnote reference. .. [#] Auto-numbered footnote 1. .. [#] Auto-numbered footnote 2. .. [#] Auto-numbered footnote 3. [#]_ is the third auto-numbered footnote reference. """, """\ <document source="test data"> <paragraph> <footnote_reference auto="1" ids="id1" refid="id3"> 1 is the first auto-numbered footnote reference. <footnote_reference auto="1" ids="id2" refid="id4"> 2 is the second auto-numbered footnote reference. <footnote auto="1" backrefs="id1" ids="id3" names="1"> <label> 1 <paragraph> Auto-numbered footnote 1. <footnote auto="1" backrefs="id2" ids="id4" names="2"> <label> 2 <paragraph> Auto-numbered footnote 2. <footnote auto="1" backrefs="id6" ids="id5" names="3"> <label> 3 <paragraph> Auto-numbered footnote 3. <paragraph> <footnote_reference auto="1" ids="id6" refid="id5"> 3 is the third auto-numbered footnote reference. """], ["""\ [#third]_ is a reference to the third auto-numbered footnote. .. [#first] First auto-numbered footnote. .. [#second] Second auto-numbered footnote. .. [#third] Third auto-numbered footnote. [#second]_ is a reference to the second auto-numbered footnote. [#first]_ is a reference to the first auto-numbered footnote. [#third]_ is another reference to the third auto-numbered footnote. Here are some internal cross-references to the implicit targets generated by the footnotes: first_, second_, third_. """, """\ <document source="test data"> <paragraph> <footnote_reference auto="1" ids="id1" refid="third"> 3 is a reference to the third auto-numbered footnote. <footnote auto="1" backrefs="id3" ids="first" names="first"> <label> 1 <paragraph> First auto-numbered footnote. <footnote auto="1" backrefs="id2" ids="second" names="second"> <label> 2 <paragraph> Second auto-numbered footnote. <footnote auto="1" backrefs="id1 id4" ids="third" names="third"> <label> 3 <paragraph> Third auto-numbered footnote. <paragraph> <footnote_reference auto="1" ids="id2" refid="second"> 2 is a reference to the second auto-numbered footnote. <footnote_reference auto="1" ids="id3" refid="first"> 1 is a reference to the first auto-numbered footnote. <footnote_reference auto="1" ids="id4" refid="third"> 3 is another reference to the third auto-numbered footnote. <paragraph> Here are some internal cross-references to the implicit targets generated by the footnotes: \n\ <reference name="first" refname="first"> first , \n\ <reference name="second" refname="second"> second , \n\ <reference name="third" refname="third"> third . """], ["""\ Mixed anonymous and labelled auto-numbered footnotes: [#four]_ should be 4, [#]_ should be 1, [#]_ should be 3, [#]_ is one too many, [#two]_ should be 2, and [#six]_ doesn't exist. .. [#] Auto-numbered footnote 1. .. [#two] Auto-numbered footnote 2. .. [#] Auto-numbered footnote 3. .. [#four] Auto-numbered footnote 4. .. [#five] Auto-numbered footnote 5. .. [#five] Auto-numbered footnote 5 again (duplicate). """, """\ <document source="test data"> <paragraph> Mixed anonymous and labelled auto-numbered footnotes: <paragraph> <footnote_reference auto="1" ids="id1" refid="four"> 4 should be 4, \n\ <footnote_reference auto="1" ids="id2" refid="id7"> 1 should be 1, <footnote_reference auto="1" ids="id3" refid="id8"> 3 should be 3, \n\ <problematic ids="id11 id4" refid="id10"> [#]_ is one too many, <footnote_reference auto="1" ids="id5" refid="two"> 2 should be 2, and \n\ <footnote_reference auto="1" ids="id6" refname="six"> doesn't exist. <footnote auto="1" backrefs="id2" ids="id7" names="1"> <label> 1 <paragraph> Auto-numbered footnote 1. <footnote auto="1" backrefs="id5" ids="two" names="two"> <label> 2 <paragraph> Auto-numbered footnote 2. <footnote auto="1" backrefs="id3" ids="id8" names="3"> <label> 3 <paragraph> Auto-numbered footnote 3. <footnote auto="1" backrefs="id1" ids="four" names="four"> <label> 4 <paragraph> Auto-numbered footnote 4. <footnote auto="1" dupnames="five" ids="five"> <label> 5 <paragraph> Auto-numbered footnote 5. <footnote auto="1" dupnames="five" ids="id9"> <label> 6 <system_message backrefs="id9" level="2" line="12" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "five". <paragraph> Auto-numbered footnote 5 again (duplicate). <system_message backrefs="id11" ids="id10" level="3" line="3" source="test data" type="ERROR"> <paragraph> Too many autonumbered footnote references: only 2 corresponding footnotes available. """], ["""\ Mixed auto-numbered and manual footnotes: .. [1] manually numbered .. [#] auto-numbered .. [#label] autonumber-labeled """, """\ <document source="test data"> <paragraph> Mixed auto-numbered and manual footnotes: <footnote ids="id1" names="1"> <label> 1 <paragraph> manually numbered <footnote auto="1" ids="id2" names="2"> <label> 2 <paragraph> auto-numbered <footnote auto="1" ids="label" names="label"> <label> 3 <paragraph> autonumber-labeled """], ["""\ A labeled autonumbered footnote referece: [#footnote]_. An unlabeled autonumbered footnote referece: [#]_. .. [#] Unlabeled autonumbered footnote. .. [#footnote] Labeled autonumbered footnote. Note that the footnotes are not in the same order as the references. """, """\ <document source="test data"> <paragraph> A labeled autonumbered footnote referece: \n\ <footnote_reference auto="1" ids="id1" refid="footnote"> 2 . <paragraph> An unlabeled autonumbered footnote referece: \n\ <footnote_reference auto="1" ids="id2" refid="id3"> 1 . <footnote auto="1" backrefs="id2" ids="id3" names="1"> <label> 1 <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" backrefs="id1" ids="footnote" names="footnote"> <label> 2 <paragraph> Labeled autonumbered footnote. Note that the footnotes are not in the same order as the references. """], ["""\ Mixed manually-numbered, anonymous auto-numbered, and labelled auto-numbered footnotes: [#four]_ should be 4, [#]_ should be 2, [1]_ is 1, [3]_ is 3, [#]_ should be 6, [#]_ is one too many, [#five]_ should be 5, and [#eight]_ doesn't exist. .. [1] Manually-numbered footnote 1. .. [#] Auto-numbered footnote 2. .. [#four] Auto-numbered footnote 4. .. [3] Manually-numbered footnote 3 .. [#five] Auto-numbered footnote 5. .. [#] Auto-numbered footnote 6. .. [#five] Auto-numbered footnote 5 again (duplicate). """, """\ <document source="test data"> <paragraph> Mixed manually-numbered, anonymous auto-numbered, and labelled auto-numbered footnotes: <paragraph> <footnote_reference auto="1" ids="id1" refid="four"> 4 should be 4, \n\ <footnote_reference auto="1" ids="id2" refid="id10"> 2 should be 2, <footnote_reference ids="id3" refid="id9"> 1 is 1, \n\ <footnote_reference ids="id4" refid="id11"> 3 is 3, <footnote_reference auto="1" ids="id5" refid="id12"> 6 should be 6, \n\ <problematic ids="id15 id6" refid="id14"> [#]_ is one too many, <footnote_reference auto="1" ids="id7" refname="five"> should be 5, and \n\ <footnote_reference auto="1" ids="id8" refname="eight"> doesn't exist. <footnote backrefs="id3" ids="id9" names="1"> <label> 1 <paragraph> Manually-numbered footnote 1. <footnote auto="1" backrefs="id2" ids="id10" names="2"> <label> 2 <paragraph> Auto-numbered footnote 2. <footnote auto="1" backrefs="id1" ids="four" names="four"> <label> 4 <paragraph> Auto-numbered footnote 4. <footnote backrefs="id4" ids="id11" names="3"> <label> 3 <paragraph> Manually-numbered footnote 3 <footnote auto="1" dupnames="five" ids="five"> <label> 5 <paragraph> Auto-numbered footnote 5. <footnote auto="1" backrefs="id5" ids="id12" names="6"> <label> 6 <paragraph> Auto-numbered footnote 6. <footnote auto="1" dupnames="five" ids="id13"> <label> 7 <system_message backrefs="id13" level="2" line="15" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "five". <paragraph> Auto-numbered footnote 5 again (duplicate). <system_message backrefs="id15" ids="id14" level="3" line="4" source="test data" type="ERROR"> <paragraph> Too many autonumbered footnote references: only 2 corresponding footnotes available. """], ["""\ Referencing a footnote by symbol [*]_. .. [*] This is an auto-symbol footnote. """, """\ <document source="test data"> <paragraph> Referencing a footnote by symbol \n\ <footnote_reference auto="*" ids="id1" refid="id2"> * . <footnote auto="*" backrefs="id1" ids="id2"> <label> * <paragraph> This is an auto-symbol footnote. """], ["""\ A sequence of symbol footnote references: [*]_ [*]_ [*]_ [*]_ [*]_ [*]_ [*]_ [*]_ [*]_ [*]_ [*]_ [*]_. .. [*] Auto-symbol footnote 1. .. [*] Auto-symbol footnote 2. .. [*] Auto-symbol footnote 3. .. [*] Auto-symbol footnote 4. .. [*] Auto-symbol footnote 5. .. [*] Auto-symbol footnote 6. .. [*] Auto-symbol footnote 7. .. [*] Auto-symbol footnote 8. .. [*] Auto-symbol footnote 9. .. [*] Auto-symbol footnote 10. .. [*] Auto-symbol footnote 11. .. [*] Auto-symbol footnote 12. """, u"""\ <document source="test data"> <paragraph> A sequence of symbol footnote references: <footnote_reference auto="*" ids="id1" refid="id13"> * \n\ <footnote_reference auto="*" ids="id2" refid="id14"> \u2020 \n\ <footnote_reference auto="*" ids="id3" refid="id15"> \u2021 \n\ <footnote_reference auto="*" ids="id4" refid="id16"> \u00A7 \n\ <footnote_reference auto="*" ids="id5" refid="id17"> \u00B6 \n\ <footnote_reference auto="*" ids="id6" refid="id18"> # \n\ <footnote_reference auto="*" ids="id7" refid="id19"> \u2660 \n\ <footnote_reference auto="*" ids="id8" refid="id20"> \u2665 \n\ <footnote_reference auto="*" ids="id9" refid="id21"> \u2666 \n\ <footnote_reference auto="*" ids="id10" refid="id22"> \u2663 \n\ <footnote_reference auto="*" ids="id11" refid="id23"> ** \n\ <footnote_reference auto="*" ids="id12" refid="id24"> \u2020\u2020 . <footnote auto="*" backrefs="id1" ids="id13"> <label> * <paragraph> Auto-symbol footnote 1. <footnote auto="*" backrefs="id2" ids="id14"> <label> \u2020 <paragraph> Auto-symbol footnote 2. <footnote auto="*" backrefs="id3" ids="id15"> <label> \u2021 <paragraph> Auto-symbol footnote 3. <footnote auto="*" backrefs="id4" ids="id16"> <label> \u00A7 <paragraph> Auto-symbol footnote 4. <footnote auto="*" backrefs="id5" ids="id17"> <label> \u00B6 <paragraph> Auto-symbol footnote 5. <footnote auto="*" backrefs="id6" ids="id18"> <label> # <paragraph> Auto-symbol footnote 6. <footnote auto="*" backrefs="id7" ids="id19"> <label> \u2660 <paragraph> Auto-symbol footnote 7. <footnote auto="*" backrefs="id8" ids="id20"> <label> \u2665 <paragraph> Auto-symbol footnote 8. <footnote auto="*" backrefs="id9" ids="id21"> <label> \u2666 <paragraph> Auto-symbol footnote 9. <footnote auto="*" backrefs="id10" ids="id22"> <label> \u2663 <paragraph> Auto-symbol footnote 10. <footnote auto="*" backrefs="id11" ids="id23"> <label> ** <paragraph> Auto-symbol footnote 11. <footnote auto="*" backrefs="id12" ids="id24"> <label> \u2020\u2020 <paragraph> Auto-symbol footnote 12. """], ["""\ Duplicate manual footnote labels: .. [1] Footnote. .. [1] Footnote. """, """\ <document source="test data"> <paragraph> Duplicate manual footnote labels: <footnote dupnames="1" ids="id1"> <label> 1 <paragraph> Footnote. <footnote dupnames="1" ids="id2"> <label> 1 <system_message backrefs="id2" level="2" line="5" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "1". <paragraph> Footnote. """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �������������������������������������������������������������������������������docutils-0.12/test/test_transforms/test_smartquotes.py����������������������������������������������0000664�0001750�0001750�00000013007�12153360646�025447� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # -*- coding: utf-8 -*- # $Id: test_smartquotes.py 7668 2013-06-04 12:46:30Z milde $ # # :Copyright: © 2011 Günter Milde. # :Maintainer: docutils-develop@lists.sourceforge.net # :License: Released under the terms of the `2-Clause BSD license`_, in short: # # Copying and distribution of this file, with or without modification, # are permitted in any medium without royalty provided the copyright # notice and this notice are preserved. # This file is offered as-is, without any warranty. # # .. _2-Clause BSD license: http://www.spdx.org/licenses/BSD-2-Clause """ Test module for universal.SmartQuotes transform. """ from __init__ import DocutilsTestSupport # must be imported before docutils from docutils.transforms.universal import SmartQuotes from docutils.parsers.rst import Parser def suite(): parser = Parser() settings = {'smart_quotes': True} s = DocutilsTestSupport.TransformTestSuite( parser, suite_settings=settings) s.generateTests(totest) settings['language_code'] = 'de' s.generateTests(totest_de) settings['smart_quotes'] = 'alternative' s.generateTests(totest_de_alt) return s totest = {} totest_de = {} totest_de_alt = {} totest['transitions'] = ((SmartQuotes,), [ ["""\ Test "smart quotes", 'single smart quotes', "'nested' smart" quotes -- and ---also long--- dashes. """, u"""\ <document source="test data"> <paragraph> Test “smart quotes”, ‘single smart quotes’, “‘nested’ smart” quotes – and —also long— dashes. """], ["""\ Do not "educate" quotes ``inside "literal" text`` and :: "literal" blocks. Keep quotes straight in code and math: :code:`print "hello"` :math:`1' 12"`. .. code:: print "hello" .. math:: f'(x) = df(x)/dx """, u"""\ <document source="test data"> <paragraph> Do not “educate” quotes <literal> inside "literal" text and <literal_block xml:space="preserve"> "literal" blocks. <paragraph> Keep quotes straight in code and math: <literal classes="code"> print "hello" <math> 1' 12" . <literal_block classes="code" xml:space="preserve"> print "hello" <math_block xml:space="preserve"> f'(x) = df(x)/dx """], ["""\ Quotes and inline-elements: * Around "_`targets`", "*emphasized*" or "``literal``" text and links to "targets_". * Inside *"emphasized"* or other `inline "roles"` Do not drop characters from intra-word inline markup like *re*\ ``Structured``\ *Text*. """, u"""\ <document source="test data"> <paragraph> Quotes and inline-elements: <bullet_list bullet="*"> <list_item> <paragraph> Around “ <target ids="targets" names="targets"> targets ”, “ <emphasis> emphasized ” or “ <literal> literal ” text and links to “ <reference name="targets" refname="targets"> targets ”. <list_item> <paragraph> Inside \n\ <emphasis> “emphasized” or other \n\ <title_reference> inline “roles” <paragraph> Do not drop characters from intra-word inline markup like <emphasis> re <literal> Structured <emphasis> Text .\ """], ["""\ .. class:: language-de German "smart quotes" and 'single smart quotes'. .. class:: language-foo "Quoting style" for unknown languages is 'ASCII'. .. class:: language-de-x-altquot Alternative German "smart quotes" and 'single smart quotes'. """, u"""\ <document source="test data"> <paragraph classes="language-de"> German „smart quotes“ and ‚single smart quotes‘. <paragraph classes="language-foo"> "Quoting style" for unknown languages is 'ASCII'. <paragraph classes="language-de-x-altquot"> Alternative German »smart quotes« and ›single smart quotes‹. <system_message level="2" line="7" source="test data" type="WARNING"> <paragraph> No smart quotes defined for language "foo". """], ]) totest_de['transitions'] = ((SmartQuotes,), [ ["""\ German "smart quotes" and 'single smart quotes'. .. class:: language-en-UK English "smart quotes" and 'single smart quotes'. """, u"""\ <document source="test data"> <paragraph> German „smart quotes“ and ‚single smart quotes‘. <paragraph classes="language-en-uk"> English “smart quotes” and ‘single smart quotes’. """], ]) totest_de_alt['transitions'] = ((SmartQuotes,), [ ["""\ Alternative German "smart quotes" and 'single smart quotes'. .. class:: language-en-UK English "smart quotes" and 'single smart quotes' have no alternative. .. class:: language-ro Alternative Romanian "smart quotes" and 'single' smart quotes. """, u"""\ <document source="test data"> <paragraph> Alternative German »smart quotes« and ›single smart quotes‹. <paragraph classes="language-en-uk"> English “smart quotes” and ‘single smart quotes’ have no alternative. <paragraph classes="language-ro"> Alternative Romanian «smart quotes» and „single” smart quotes. """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_transforms/test_filter.py���������������������������������������������������0000775�0001750�0001750�00000001614�10434150472�024343� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_filter.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for docutils.transforms.components.Filter. """ from __init__ import DocutilsTestSupport from docutils.parsers.rst import Parser def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite(parser) s.generateTests(totest) return s totest = {} totest['meta'] = ((), [ ["""\ .. meta:: :description: The reStructuredText plaintext markup language :keywords: plaintext,markup language """, """\ <document source="test data"> <meta content="The reStructuredText plaintext markup language" name="description"> <meta content="plaintext,markup language" name="keywords"> """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ��������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_transforms/test_doctitle.py�������������������������������������������������0000775�0001750�0001750�00000012774�12077276004�024703� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_doctitle.py 7595 2013-01-21 17:33:56Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for docutils.transforms.frontmatter.DocTitle. """ from __init__ import DocutilsTestSupport from docutils.transforms.frontmatter import DocTitle, SectionSubTitle from docutils.parsers.rst import Parser, Directive from docutils.parsers.rst.directives import register_directive # dummy directive to test attribute merging: class AddNameToDocumentTitle(Directive): required_arguments = 0 optional_arguments = 0 final_argument_whitespace = True option_spec = { } has_content = False def run(self): document = self.state_machine.document document['names'].append('Name') return [] register_directive('add-name-to-title', AddNameToDocumentTitle) def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite(parser) s.generateTests(totest) return s totest = {} totest['section_headers'] = ((DocTitle, SectionSubTitle), [ ["""\ .. test title promotion Title ===== Paragraph. """, """\ <document ids="title" names="title" source="test data" title="Title"> <title> Title <comment xml:space="preserve"> test title promotion <paragraph> Paragraph. """], ["""\ Title ===== Paragraph (no blank line). """, """\ <document ids="title" names="title" source="test data" title="Title"> <title> Title <paragraph> Paragraph (no blank line). """], ["""\ Paragraph. Title ===== Paragraph. """, """\ <document source="test data"> <paragraph> Paragraph. <section ids="title" names="title"> <title> Title <paragraph> Paragraph. """], ["""\ Title ===== Subtitle -------- .. title:: Another Title Test title, subtitle, and title metadata. """, """\ <document ids="title" names="title" source="test data" title="Another Title"> <title> Title <subtitle ids="subtitle" names="subtitle"> Subtitle <paragraph> Test title, subtitle, and title metadata. """], ["""\ Title ==== Test short underline. """, """\ <document ids="title" names="title" source="test data" title="Title"> <title> Title <system_message level="2" line="2" source="test data" type="WARNING"> <paragraph> Title underline too short. <literal_block xml:space="preserve"> Title ==== <paragraph> Test short underline. """], ["""\ ======= Long Title ======= Test long title and space normalization. The system_message should move after the document title (it was before the beginning of the section). """, """\ <document ids="long-title" names="long\ title" source="test data" title="Long Title"> <title> Long Title <system_message level="2" line="1" source="test data" type="WARNING"> <paragraph> Title overline too short. <literal_block xml:space="preserve"> ======= Long Title ======= <paragraph> Test long title and space normalization. The system_message should move after the document title (it was before the beginning of the section). """], ["""\ .. Test multiple second-level titles. Title 1 ======= Paragraph 1. Title 2 ------- Paragraph 2. Title 3 ------- Paragraph 3. """, """\ <document ids="title-1" names="title\ 1" source="test data" title="Title 1"> <title> Title 1 <comment xml:space="preserve"> Test multiple second-level titles. <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title> Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title> Title 3 <paragraph> Paragraph 3. """], ["""\ .. |foo| replace:: bar .. _invisible target: Title ===== This title should be the document title despite the substitution_definition. """, """\ <document ids="title" names="title" source="test data" title="Title"> <title> Title <substitution_definition names="foo"> bar <target ids="invisible-target" names="invisible\ target"> <paragraph> This title should be the document title despite the substitution_definition. """], ["""\ (Because of this paragraph, the following is not a doc title.) =============== Section Title =============== Subtitle ======== ----------------- Another Section ----------------- Another Subtitle ---------------- """, """\ <document source="test data"> <paragraph> (Because of this paragraph, the following is not a doc title.) <section ids="section-title" names="section\ title"> <title> Section Title <subtitle ids="subtitle" names="subtitle"> Subtitle <section ids="another-section" names="another\ section"> <title> Another Section <subtitle ids="another-subtitle" names="another\ subtitle"> Another Subtitle """], ["""\ ----- Title ----- This is a document, it flows nicely, so the attributes of it are at the bottom. .. add-name-to-title:: """, """\ <document ids="title" names="Name title" source="test data" title="Title"> <title> Title <paragraph> This is a document, it flows nicely, so the attributes of it are at the bottom. """] ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����docutils-0.12/test/test_transforms/test_strip_elements_with_class.py��������������������������������0000664�0001750�0001750�00000002224�12013206626�030324� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_strip_elements_with_class.py 7496 2012-08-16 15:11:18Z milde $ # Author: Guenter Milde <milde@users.sf.net> # Copyright: This module has been placed in the public domain. """ Tests for docutils.transforms.universal.StripComments. """ from __init__ import DocutilsTestSupport from docutils.parsers.rst import Parser from docutils.transforms.universal import StripClassesAndElements def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite( parser, suite_settings={'strip_elements_with_classes': ['spam', 'no-ham']}) s.generateTests(totest) return s totest = {} totest['strip_spam'] = ((StripClassesAndElements,), [ ["""\ not classy .. class:: spam this is spam .. class:: ham this is ham .. code:: :class: spam print "spam" .. image:: spam.jpg :class: spam this is not ham """, """\ <document source="test data"> <paragraph> not classy <paragraph classes="ham"> this is ham <paragraph> this is not ham """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_transforms/test_transitions.py����������������������������������������������0000775�0001750�0001750�00000016561�10434150472�025442� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_transitions.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Test module for misc.Transitions transform. """ from __init__ import DocutilsTestSupport # must be imported before docutils from docutils.transforms.misc import Transitions from docutils.parsers.rst import Parser def suite(): parser = Parser() s = DocutilsTestSupport.TransformTestSuite(parser) s.generateTests(totest) return s totest = {} totest['transitions'] = ((Transitions,), [ ["""\ Section 1 ========= Subsection 1 ------------ Some text. ---------- Section 2 ========= Some text. """, """\ <document source="test data"> <section ids="section-1" names="section\ 1"> <title> Section 1 <section ids="subsection-1" names="subsection\ 1"> <title> Subsection 1 <paragraph> Some text. <transition> <section ids="section-2" names="section\ 2"> <title> Section 2 <paragraph> Some text. """], ["""\ A paragraph. ---------- Section 1 ========= Paragraph. """, """\ <document source="test data"> <paragraph> A paragraph. <transition> <section ids="section-1" names="section\ 1"> <title> Section 1 <paragraph> Paragraph. """], ["""\ -------- A section or document may not begin with a transition. The DTD specifies that two transitions may not be adjacent: -------- -------- -------- The DTD also specifies that a section or document may not end with a transition. -------- """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Document or section may not begin with a transition. <transition> <paragraph> A section or document may not begin with a transition. <paragraph> The DTD specifies that two transitions may not be adjacent: <transition> <system_message level="3" line="10" source="test data" type="ERROR"> <paragraph> At least one body element must separate transitions; adjacent transitions are not allowed. <transition> <system_message level="3" line="12" source="test data" type="ERROR"> <paragraph> At least one body element must separate transitions; adjacent transitions are not allowed. <transition> <paragraph> The DTD also specifies that a section or document may not end with a transition. <transition> <system_message level="3" line="17" source="test data" type="ERROR"> <paragraph> Document may not end with a transition. """], ["""\ Sections with transitions at beginning and end. Section 1 ========= ---------- The next transition is legal: ---------- Section 2 ========= ---------- """, """\ <document source="test data"> <paragraph> Sections with transitions at beginning and end. <section ids="section-1" names="section\ 1"> <title> Section 1 <system_message level="3" line="6" source="test data" type="ERROR"> <paragraph> Document or section may not begin with a transition. <transition> <paragraph> The next transition is legal: <transition> <section ids="section-2" names="section\ 2"> <title> Section 2 <system_message level="3" line="15" source="test data" type="ERROR"> <paragraph> Document or section may not begin with a transition. <transition> <system_message level="3" line="15" source="test data" type="ERROR"> <paragraph> Document may not end with a transition. """], ["""\ A paragraph and two transitions. ---------- ---------- """, # the same: """\ <document source="test data"> <paragraph> A paragraph and two transitions. <transition> <system_message level="3" line="5" source="test data" type="ERROR"> <paragraph> At least one body element must separate transitions; adjacent transitions are not allowed. <transition> <system_message level="3" line="5" source="test data" type="ERROR"> <paragraph> Document may not end with a transition. """], ["""\ A paragraph, two transitions, and a blank line. ---------- ---------- """, """\ <document source="test data"> <paragraph> A paragraph, two transitions, and a blank line. <transition> <system_message level="3" line="5" source="test data" type="ERROR"> <paragraph> At least one body element must separate transitions; adjacent transitions are not allowed. <transition> <system_message level="3" line="5" source="test data" type="ERROR"> <paragraph> Document may not end with a transition. """], ["""\ ---------- Document beginning with a transition. """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Document or section may not begin with a transition. <transition> <paragraph> Document beginning with a transition. """], ["""\ Section 1 ========= ---------- ---------- ---------- Section 2 ========= Some text. """, """\ <document source="test data"> <section ids="section-1" names="section\ 1"> <title> Section 1 <system_message level="3" line="4" source="test data" type="ERROR"> <paragraph> Document or section may not begin with a transition. <transition> <system_message level="3" line="6" source="test data" type="ERROR"> <paragraph> At least one body element must separate transitions; adjacent transitions are not allowed. <transition> <system_message level="3" line="8" source="test data" type="ERROR"> <paragraph> At least one body element must separate transitions; adjacent transitions are not allowed. <transition> <section ids="section-2" names="section\ 2"> <title> Section 2 <paragraph> Some text. """], ["""\ ---------- ---------- ---------- """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Document or section may not begin with a transition. <transition> <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> At least one body element must separate transitions; adjacent transitions are not allowed. <transition> <system_message level="3" line="5" source="test data" type="ERROR"> <paragraph> At least one body element must separate transitions; adjacent transitions are not allowed. <transition> <system_message level="3" line="5" source="test data" type="ERROR"> <paragraph> Document may not end with a transition. """], ["""\ A paragraph. ---------- """, """\ <document source="test data"> <paragraph> A paragraph. <transition> <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> Document may not end with a transition. """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �����������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_transforms/test___init__.py�������������������������������������������������0000775�0001750�0001750�00000002160�10627410160�024607� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test___init__.py 5174 2007-05-31 00:01:52Z wiemann $ # Author: Lea Wiemann <LeWiemann@gmail.com> # Copyright: This module has been placed in the public domain. """ Test module for transforms/__init__.py. """ from __init__ import DocutilsTestSupport # must be imported before docutils from docutils import transforms, utils import unittest class TestTransform(transforms.Transform): default_priority = 100 applied = 0 def apply(self, **kwargs): self.applied += 1 assert kwargs == {'foo': 42} class KwargsTestCase(unittest.TestCase): def test_kwargs(self): transformer = transforms.Transformer(utils.new_document('test data')) transformer.add_transform(TestTransform, foo=42) transformer.apply_transforms() self.assertEqual(len(transformer.applied), 1) self.assertEqual(len(transformer.applied[0]), 4) transform_record = transformer.applied[0] self.assertEqual(transform_record[1], TestTransform) self.assertEqual(transform_record[3], {'foo': 42}) if __name__ == '__main__': unittest.main() ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_error_reporting.py����������������������������������������������������������0000664�0001750�0001750�00000027371�12221517223�023045� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # .. coding: utf-8 # $Id: test_error_reporting.py 7723 2013-09-28 09:17:07Z milde $ # Author: Günter Milde <milde@users.sourceforge.net> # Copyright: This module has been placed in the public domain. """ Test `EnvironmentError` reporting. In some locales, the `errstr` argument of IOError and OSError contains non-ASCII chars. In Python 2, converting an exception instance to `str` or `unicode` might fail, with non-ASCII chars in arguments and the default encoding and errors ('ascii', 'strict'). Therefore, Docutils must not use string interpolation with exception instances like, e.g., :: try: something except IOError, error: print 'Found %s' % error unless the minimal required Python version has this problem fixed. """ import unittest import sys, os import codecs try: # from standard library module `io` from io import StringIO, BytesIO except ImportError: # new in Python 2.6 from StringIO import StringIO BytesIO = StringIO import DocutilsTestSupport # must be imported before docutils from docutils import core, parsers, frontend, utils from docutils.utils.error_reporting import SafeString, ErrorString, ErrorOutput from docutils._compat import b, bytes oldlocale = None if sys.version_info < (3,0): # problems solved in py3k try: import locale # module missing in Jython oldlocale = locale.getlocale() # Why does getlocale return the defaultlocale in Python 3.2 ???? # oldlocale = (None, None) # test suite runs without locale except ImportError: print ('cannot test error reporting with problematic locales,\n' '`import locale` failed.') # locales confirmed to use non-ASCII chars in the IOError message # for a missing file (https://bugs.gentoo.org/show_bug.cgi?id=349101) # TODO: add more confirmed problematic locales problematic_locales = ['cs_CZ', 'cs_CZ.UTF8', 'el_GR', 'el_GR.UTF-8', # 'fr_FR.UTF-8', # only OSError 'ja_JP.UTF-8', 'ru_RU', 'ru_RU.KOI8-R', 'ru_RU.UTF-8', '', # default locale: might be non-problematic ] if oldlocale is not None: # find a supported problematic locale: for testlocale in problematic_locales: try: locale.setlocale(locale.LC_ALL, testlocale) except locale.Error: testlocale = None else: break locale.setlocale(locale.LC_ALL, oldlocale) # reset else: testlocale = None class SafeStringTests(unittest.TestCase): # the error message in EnvironmentError instances comes from the OS # and in some locales (e.g. ru_RU), contains high bit chars. # -> see the test in test_error_reporting.py # test data: bs = b('\xfc') # unicode(bs) fails, str(bs) in Python 3 return repr() us = u'\xfc' # bytes(us) fails; str(us) fails in Python 2 be = Exception(bs) # unicode(be) fails ue = Exception(us) # bytes(ue) fails, str(ue) fails in Python 2; # unicode(ue) fails in Python < 2.6 (issue2517_) # .. _issue2517: http://bugs.python.org/issue2517 # wrapped test data: wbs = SafeString(bs) wus = SafeString(us) wbe = SafeString(be) wue = SafeString(ue) def test_7bit(self): # wrapping (not required with 7-bit chars) must not change the # result of conversions: bs7 = b('foo') us7 = u'foo' be7 = Exception(bs7) ue7 = Exception(us7) self.assertEqual(str(42), str(SafeString(42))) self.assertEqual(str(bs7), str(SafeString(bs7))) self.assertEqual(str(us7), str(SafeString(us7))) self.assertEqual(str(be7), str(SafeString(be7))) self.assertEqual(str(ue7), str(SafeString(ue7))) self.assertEqual(unicode(7), unicode(SafeString(7))) self.assertEqual(unicode(bs7), unicode(SafeString(bs7))) self.assertEqual(unicode(us7), unicode(SafeString(us7))) self.assertEqual(unicode(be7), unicode(SafeString(be7))) self.assertEqual(unicode(ue7), unicode(SafeString(ue7))) def test_ustr(self): """Test conversion to a unicode-string.""" # unicode(self.bs) fails self.assertEqual(unicode, type(unicode(self.wbs))) self.assertEqual(unicode(self.us), unicode(self.wus)) # unicode(self.be) fails self.assertEqual(unicode, type(unicode(self.wbe))) # unicode(ue) fails in Python < 2.6 (issue2517_) self.assertEqual(unicode, type(unicode(self.wue))) self.assertEqual(self.us, unicode(self.wue)) def test_str(self): """Test conversion to a string (bytes in Python 2, unicode in Python 3).""" self.assertEqual(str(self.bs), str(self.wbs)) self.assertEqual(str(self.be), str(self.be)) # str(us) fails in Python 2 self.assertEqual(str, type(str(self.wus))) # str(ue) fails in Python 2 self.assertEqual(str, type(str(self.wue))) class ErrorStringTests(unittest.TestCase): bs = b('\xfc') # unicode(bs) fails, str(bs) in Python 3 return repr() us = u'\xfc' # bytes(us) fails; str(us) fails in Python 2 def test_str(self): self.assertEqual('Exception: spam', str(ErrorString(Exception('spam')))) self.assertEqual('IndexError: '+str(self.bs), str(ErrorString(IndexError(self.bs)))) self.assertEqual('ImportError: %s' % SafeString(self.us), str(ErrorString(ImportError(self.us)))) def test_unicode(self): self.assertEqual(u'Exception: spam', unicode(ErrorString(Exception(u'spam')))) self.assertEqual(u'IndexError: '+self.us, unicode(ErrorString(IndexError(self.us)))) self.assertEqual(u'ImportError: %s' % SafeString(self.bs), unicode(ErrorString(ImportError(self.bs)))) # ErrorOutput tests # ----------------- # Stub: Buffer with 'strict' auto-conversion of input to byte string: class BBuf(BytesIO, object): # super class object required by Python <= 2.5 def write(self, data): if isinstance(data, unicode): data.encode('ascii', 'strict') super(BBuf, self).write(data) # Stub: Buffer expecting unicode string: class UBuf(StringIO, object): # super class object required by Python <= 2.5 def write(self, data): # emulate Python 3 handling of stdout, stderr if isinstance(data, bytes): raise TypeError('must be unicode, not bytes') super(UBuf, self).write(data) class ErrorOutputTests(unittest.TestCase): def test_defaults(self): e = ErrorOutput() self.assertEqual(e.stream, sys.stderr) def test_bbuf(self): buf = BBuf() # buffer storing byte string e = ErrorOutput(buf, encoding='ascii') # write byte-string as-is e.write(b('b\xfc')) self.assertEqual(buf.getvalue(), b('b\xfc')) # encode unicode data with backslashescape fallback replacement: e.write(u' u\xfc') self.assertEqual(buf.getvalue(), b('b\xfc u\\xfc')) # handle Exceptions with Unicode string args # unicode(Exception(u'e\xfc')) # fails in Python < 2.6 e.write(AttributeError(u' e\xfc')) self.assertEqual(buf.getvalue(), b('b\xfc u\\xfc e\\xfc')) # encode with `encoding` attribute e.encoding = 'utf8' e.write(u' u\xfc') self.assertEqual(buf.getvalue(), b('b\xfc u\\xfc e\\xfc u\xc3\xbc')) def test_ubuf(self): buf = UBuf() # buffer only accepting unicode string # decode of binary strings e = ErrorOutput(buf, encoding='ascii') e.write(b('b\xfc')) self.assertEqual(buf.getvalue(), u'b\ufffd') # use REPLACEMENT CHARACTER # write Unicode string and Exceptions with Unicode args e.write(u' u\xfc') self.assertEqual(buf.getvalue(), u'b\ufffd u\xfc') e.write(AttributeError(u' e\xfc')) self.assertEqual(buf.getvalue(), u'b\ufffd u\xfc e\xfc') # decode with `encoding` attribute e.encoding = 'latin1' e.write(b(' b\xfc')) self.assertEqual(buf.getvalue(), u'b\ufffd u\xfc e\xfc b\xfc') class SafeStringTests_locale(unittest.TestCase): """ Test docutils.SafeString with 'problematic' locales. The error message in `EnvironmentError` instances comes from the OS and in some locales (e.g. ru_RU), contains high bit chars. """ if testlocale: locale.setlocale(locale.LC_ALL, testlocale) # test data: bs = b('\xfc') us = u'\xfc' try: open(b('\xfc')) except IOError, e: # in Python 3 the name for the exception instance bioe = e # is local to the except clause try: open(u'\xfc') except IOError, e: uioe = e except UnicodeEncodeError: try: open(u'\xfc'.encode(sys.getfilesystemencoding(), 'replace')) except IOError, e: uioe = e try: os.chdir(b('\xfc')) except OSError, e: bose = e try: os.chdir(u'\xfc') except OSError, e: uose = e except UnicodeEncodeError: try: os.chdir(u'\xfc'.encode(sys.getfilesystemencoding(), 'replace')) except OSError, e: uose = e # wrapped test data: wbioe = SafeString(bioe) wuioe = SafeString(uioe) wbose = SafeString(bose) wuose = SafeString(uose) # reset locale if testlocale: locale.setlocale(locale.LC_ALL, oldlocale) def test_ustr(self): """Test conversion to a unicode-string.""" # unicode(bioe) fails with e.g. 'ru_RU.utf8' locale self.assertEqual(unicode, type(unicode(self.wbioe))) self.assertEqual(unicode, type(unicode(self.wuioe))) self.assertEqual(unicode, type(unicode(self.wbose))) self.assertEqual(unicode, type(unicode(self.wuose))) def test_str(self): """Test conversion to a string (bytes in Python 2, unicode in Python 3).""" self.assertEqual(str(self.bioe), str(self.wbioe)) self.assertEqual(str(self.uioe), str(self.wuioe)) self.assertEqual(str(self.bose), str(self.wbose)) self.assertEqual(str(self.uose), str(self.wuose)) class ErrorReportingTests(unittest.TestCase): """ Test cases where error reporting can go wrong. Do not test the exact output (as this varies with the locale), just ensure that the correct exception is thrown. """ # These tests fail with a 'problematic locale', # Docutils revision < 7035, and Python 2: parser = parsers.rst.Parser() """Parser shared by all ParserTestCases.""" option_parser = frontend.OptionParser(components=(parsers.rst.Parser,)) settings = option_parser.get_default_values() settings.report_level = 1 settings.halt_level = 1 settings.warning_stream = '' document = utils.new_document('test data', settings) def setUp(self): if testlocale: locale.setlocale(locale.LC_ALL, testlocale) def tearDown(self): if testlocale: locale.setlocale(locale.LC_ALL, oldlocale) def test_include(self): source = ('.. include:: bogus.txt') self.assertRaises(utils.SystemMessage, self.parser.parse, source, self.document) def test_raw_file(self): source = ('.. raw:: html\n' ' :file: bogus.html\n') self.assertRaises(utils.SystemMessage, self.parser.parse, source, self.document) def test_csv_table(self): source = ('.. csv-table:: external file\n' ' :file: bogus.csv\n') self.assertRaises(utils.SystemMessage, self.parser.parse, source, self.document) if __name__ == '__main__': unittest.main() �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/local-reader.py������������������������������������������������������������������0000664�0001750�0001750�00000000776�12016623750�021123� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# -*- coding: utf-8 -*- # $Id: local-reader.py 7504 2012-08-27 07:55:20Z grubert $ # Authors: Engelbert Gruber <grubert@users.sourceforge.net> # Toshio Kuratomi <toshio@fedoraproject.org> # Copyright: This module is put into the public domain. """ mini-reader to test get_reader_class with local reader """ import docutils from docutils import readers class Reader(readers.Reader): supported = ('dummy',) """Formats this reader supports.""" document = None """A document tree.""" ��docutils-0.12/test/test_settings.py�����������������������������������������������������������������0000775�0001750�0001750�00000021131�12120720070�021444� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # $Id: test_settings.py 7630 2013-03-15 22:27:04Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests of runtime settings. """ import sys import os import difflib import pprint import warnings import unittest import DocutilsTestSupport # must be imported before docutils from docutils import frontend, utils from docutils.writers import html4css1, pep_html from docutils.parsers import rst warnings.filterwarnings(action='ignore', category=frontend.ConfigDeprecationWarning) def fixpath(path): return os.path.abspath(os.path.join(*(path.split('/')))) class ConfigFileTests(unittest.TestCase): config_files = {'old': fixpath('data/config_old.txt'), 'one': fixpath('data/config_1.txt'), 'two': fixpath('data/config_2.txt'), 'list': fixpath('data/config_list.txt'), 'list2': fixpath('data/config_list_2.txt'), 'error': fixpath('data/config_error_handler.txt')} settings = { 'old': {u'datestamp': u'%Y-%m-%d %H:%M UTC', u'generator': True, u'no_random': True, u'python_home': u'http://www.python.org', u'source_link': True, 'stylesheet': None, u'stylesheet_path': [u'stylesheets/pep.css'], 'template': fixpath(u'data/pep-html-template')}, 'one': {u'datestamp': u'%Y-%m-%d %H:%M UTC', u'generator': True, u'no_random': True, u'python_home': u'http://www.python.org', u'raw_enabled': False, 'record_dependencies': utils.DependencyList(), u'source_link': True, 'stylesheet': None, u'stylesheet_path': [u'stylesheets/pep.css'], u'tab_width': 8, u'template': fixpath(u'data/pep-html-template'), u'trim_footnote_reference_space': True, }, 'two': {u'footnote_references': u'superscript', u'generator': False, 'record_dependencies': utils.DependencyList(), u'stylesheet': None, u'stylesheet_path': [u'test.css'], 'trim_footnote_reference_space': None}, 'list': {u'expose_internals': [u'a', u'b', u'c', u'd', u'e'], u'strip_classes': [u'spam', u'pan', u'fun', u'parrot'], u'strip_elements_with_classes': [u'sugar', u'flour', u'milk', u'safran']}, 'list2': {u'expose_internals': [u'a', u'b', u'c', u'd', u'e', u'f'], u'strip_classes': [u'spam', u'pan', u'fun', u'parrot', u'ham', u'eggs'], u'strip_elements_with_classes': [u'sugar', u'flour', u'milk', u'safran', u'eggs', u'salt']}, 'error': {u'error_encoding': u'ascii', u'error_encoding_error_handler': u'strict'}, } compare = difflib.Differ().compare """Comparison method shared by all tests.""" def setUp(self): self.option_parser = frontend.OptionParser( components=(pep_html.Writer, rst.Parser), read_config_files=None) def files_settings(self, *names): settings = frontend.Values() for name in names: settings.update(self.option_parser.get_config_file_settings( self.config_files[name]), self.option_parser) return settings.__dict__ def expected_settings(self, *names): expected = {} for name in names: expected.update(self.settings[name]) return expected def compare_output(self, result, expected): """`result` and `expected` should both be dicts.""" self.assertTrue('record_dependencies' in result) if 'record_dependencies' not in expected: # Delete it if we don't want to test it. del result['record_dependencies'] result = pprint.pformat(result) + '\n' expected = pprint.pformat(expected) + '\n' try: self.assertEqual(result, expected) except AssertionError: print >>sys.stderr, '\n%s\n' % (self,) print >>sys.stderr, '-: expected\n+: result' print >>sys.stderr, ''.join(self.compare(expected.splitlines(1), result.splitlines(1))) raise def test_nofiles(self): self.compare_output(self.files_settings(), self.expected_settings()) def test_old(self): self.compare_output(self.files_settings('old'), self.expected_settings('old')) def test_one(self): self.compare_output(self.files_settings('one'), self.expected_settings('one')) def test_multiple(self): self.compare_output(self.files_settings('one', 'two'), self.expected_settings('one', 'two')) def test_old_and_new(self): self.compare_output(self.files_settings('old', 'two'), self.expected_settings('old', 'two')) def test_list(self): self.compare_output(self.files_settings('list'), self.expected_settings('list')) def test_list2(self): self.compare_output(self.files_settings('list', 'list2'), self.expected_settings('list2')) def test_error_handler(self): self.compare_output(self.files_settings('error'), self.expected_settings('error')) class ConfigEnvVarFileTests(ConfigFileTests): """ Repeats the tests of `ConfigFileTests` using the ``DOCUTILSCONFIG`` environment variable and the standard Docutils config file mechanism. """ def setUp(self): ConfigFileTests.setUp(self) self.orig_environ = os.environ os.environ = os.environ.copy() def files_settings(self, *names): files = [self.config_files[name] for name in names] os.environ['DOCUTILSCONFIG'] = os.pathsep.join(files) settings = self.option_parser.get_standard_config_settings() return settings.__dict__ def tearDown(self): os.environ = self.orig_environ class HelperFunctionsTests(unittest.TestCase): pathdict = {'foo': 'hallo', 'ham': u'h\xE4m', 'spam': u'spam'} keys = ['foo', 'ham'] def test_make_paths_absolute(self): pathdict = self.pathdict.copy() frontend.make_paths_absolute(pathdict, self.keys, base_path='base') self.assertEqual(pathdict['foo'], os.path.abspath('base/hallo')) self.assertEqual(pathdict['ham'], os.path.abspath(u'base/h\xE4m')) # not touched, because key not in keys: self.assertEqual(pathdict['spam'], u'spam') def test_make_paths_absolute_cwd(self): # With base_path None, the cwd is used as base path. # Settings values may-be `unicode` instances, therefore # os.getcwdu() is used and the converted path is a unicode instance: pathdict = self.pathdict.copy() frontend.make_paths_absolute(pathdict, self.keys) self.assertEqual(pathdict['foo'], os.path.abspath(u'hallo')) self.assertEqual(pathdict['ham'], os.path.abspath(u'h\xE4m')) # not touched, because key not in keys: self.assertEqual(pathdict['spam'], u'spam') def test_validate_colon_separated_string_list(self): tests = ( (u'a', ['a',] ), ('a', ['a',] ), (u'a:b', ['a', 'b'] ), ('a:b', ['a', 'b'] ), ([u'a',], ['a',] ), ([u'a', u'b:c'], ['a', 'b', 'c'] ), ) for t in tests: self.assertEqual( frontend.validate_colon_separated_string_list(None, t[0], None), t[1]) def test_validate_comma_separated_list(self): tests = ( (u'a', ['a',] ), ('a', ['a',] ), (u'a,b', ['a', 'b'] ), ('a,b', ['a', 'b'] ), ([u'a',], ['a',] ), ([u'a', u'b,c'], ['a', 'b', 'c'] ), (['a', 'b,c'], ['a', 'b', 'c'] ), ) for t in tests: self.assertEqual( frontend.validate_comma_separated_list(None, t[0], None), t[1]) if __name__ == '__main__': unittest.main() ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test__init__.py������������������������������������������������������������������0000664�0001750�0001750�00000001374�12153360646�021227� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # .. coding: utf-8 # $Id: test__init__.py 7668 2013-06-04 12:46:30Z milde $ # Author: Günter Milde <milde@users.sourceforge.net> # Copyright: This module has been placed in the public domain. """ Test module for the docutils' __init__.py. """ import unittest import sys import DocutilsTestSupport # must be imported before docutils import docutils class ApplicationErrorTests(unittest.TestCase): def test_message(self): err = docutils.ApplicationError('the message') self.assertEqual(unicode(err), u'the message') def test_non_ASCII_message(self): err = docutils.ApplicationError(u'\u0169') self.assertEqual(unicode(err), u'\u0169') if __name__ == '__main__': unittest.main() ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/docutils.conf��������������������������������������������������������������������0000664�0001750�0001750�00000000576�10067121525�020707� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������[general] # This tests the test framework; this config file should *not* be read # when testing. source-link: yes datestamp: %Y-%m-%d %H:%M UTC (If you see this in test output, there's a bug in the test code!) generator: on [buildhtml application] # This part is not for testing, but to prevent tools/buildhtml.py from # processing text files in and below this directory. prune: . ����������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_traversals.py���������������������������������������������������������������0000775�0001750�0001750�00000004035�11771146137�022017� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_traversals.py 7463 2012-06-22 19:49:51Z milde $ # Author: Martin Blais <blais@furius.ca> # Copyright: This module has been placed in the public domain. """ Test module for traversals. """ import unittest import DocutilsTestSupport # must be imported before docutils from docutils import nodes, core, io, utils, writers from docutils.writers.null import Writer as NullWriter import docutils stop_traversal_input = ''' ================== Train Travel ================== Happily, happily going by train. .. attention:: Attention, attention. This is a public annoucement. You must get off the train now. KaZoom! Train crashes. - Told ya!!! Get off the train next time. ''' class AttentiveVisitor(nodes.SparseNodeVisitor): def visit_attention(self, node): raise nodes.StopTraversal def visit_bullet_list(self, node): raise RuntimeError("It's too late for attention, " "more discipline is needed!.") class AttentiveWriter(writers.Writer): def translate(self): self.visitor = visitor = AttentiveVisitor(self.document) # Test both kinds of traversals. self.document.walkabout(visitor) self.document.walk(visitor) class StopTraversalTests(unittest.TestCase, docutils.SettingsSpec): """ Test interrupting the visitor during traversal. In this test we stop it when we reach an attention node. """ def test_stop_traversal(self): # Load some document tree in memory. doctree = docutils.core.publish_doctree( source=stop_traversal_input, reader_name='standalone', parser_name='restructuredtext', settings_spec=self) self.assertTrue(isinstance(doctree, nodes.document)) parts = docutils.core.publish_parts( reader_name='doctree', source_class=docutils.io.DocTreeInput, source=doctree, source_path='test', writer=AttentiveWriter()) if __name__ == '__main__': unittest.main() ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_utils.py��������������������������������������������������������������������0000775�0001750�0001750�00000030040�12114424152�020750� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# -*- coding: utf-8 -*- #! /usr/bin/env python # $Id: test_utils.py 7618 2013-03-02 16:27:22Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Test module for utils/__init__.py. """ import unittest import sys import os from DocutilsTestSupport import utils, nodes try: from io import StringIO except ImportError: # io is new in Python 2.6 from StringIO import StringIO class ReporterTests(unittest.TestCase): stream = StringIO() reporter = utils.Reporter('test data', 2, 4, stream, 1) def setUp(self): self.stream.seek(0) self.stream.truncate() def test_level0(self): sw = self.reporter.system_message(0, 'debug output') self.assertEqual(sw.pformat(), """\ <system_message level="0" source="test data" type="DEBUG"> <paragraph> debug output """) self.assertEqual(self.stream.getvalue(), 'test data:: (DEBUG/0) debug output\n') def test_level1(self): sw = self.reporter.system_message(1, 'a little reminder') self.assertEqual(sw.pformat(), """\ <system_message level="1" source="test data" type="INFO"> <paragraph> a little reminder """) self.assertEqual(self.stream.getvalue(), '') def test_level2(self): sw = self.reporter.system_message(2, 'a warning') self.assertEqual(sw.pformat(), """\ <system_message level="2" source="test data" type="WARNING"> <paragraph> a warning """) self.assertEqual(self.stream.getvalue(), 'test data:: (WARNING/2) a warning\n') def test_level3(self): sw = self.reporter.system_message(3, 'an error') self.assertEqual(sw.pformat(), """\ <system_message level="3" source="test data" type="ERROR"> <paragraph> an error """) self.assertEqual(self.stream.getvalue(), 'test data:: (ERROR/3) an error\n') def test_level4(self): self.assertRaises(utils.SystemMessage, self.reporter.system_message, 4, 'a severe error, raises an exception') self.assertEqual(self.stream.getvalue(), 'test data:: (SEVERE/4) ' 'a severe error, raises an exception\n') def test_unicode_message(self): sw = self.reporter.system_message(0, u'mesidʒ') self.assertEqual(sw.pformat(), u"""\ <system_message level="0" source="test data" type="DEBUG"> <paragraph> mesidʒ """) def test_unicode_message_from_exception(self): """Workaround for Python < 2.6 bug: unicode(<exception instance>) uses __str__ and hence fails with unicode message""" try: raise Exception(u'mesidʒ') except Exception, err: sw = self.reporter.system_message(0, err) self.assertEqual(sw.pformat(), u"""\ <system_message level="0" source="test data" type="DEBUG"> <paragraph> mesidʒ """) class QuietReporterTests(unittest.TestCase): stream = StringIO() reporter = utils.Reporter('test data', 5, 5, stream, 0) def setUp(self): self.stream.seek(0) self.stream.truncate() def test_debug(self): sw = self.reporter.debug('a debug message') # None because debug is disabled. self.assertEqual(sw, None) self.assertEqual(self.stream.getvalue(), '') def test_info(self): sw = self.reporter.info('an informational message') self.assertEqual(sw.pformat(), """\ <system_message level="1" source="test data" type="INFO"> <paragraph> an informational message """) self.assertEqual(self.stream.getvalue(), '') def test_warning(self): sw = self.reporter.warning('a warning') self.assertEqual(sw.pformat(), """\ <system_message level="2" source="test data" type="WARNING"> <paragraph> a warning """) self.assertEqual(self.stream.getvalue(), '') def test_error(self): sw = self.reporter.error('an error') self.assertEqual(sw.pformat(), """\ <system_message level="3" source="test data" type="ERROR"> <paragraph> an error """) self.assertEqual(self.stream.getvalue(), '') def test_severe(self): sw = self.reporter.severe('a severe error') self.assertEqual(sw.pformat(), """\ <system_message level="4" source="test data" type="SEVERE"> <paragraph> a severe error """) self.assertEqual(self.stream.getvalue(), '') class NameValueTests(unittest.TestCase): def test_extract_name_value(self): self.assertRaises(utils.NameValueError, utils.extract_name_value, 'hello') self.assertRaises(utils.NameValueError, utils.extract_name_value, 'hello') self.assertRaises(utils.NameValueError, utils.extract_name_value, '=hello') self.assertRaises(utils.NameValueError, utils.extract_name_value, 'hello=') self.assertRaises(utils.NameValueError, utils.extract_name_value, 'hello="') self.assertRaises(utils.NameValueError, utils.extract_name_value, 'hello="something') self.assertRaises(utils.NameValueError, utils.extract_name_value, 'hello="something"else') output = utils.extract_name_value( """att1=val1 att2=val2 att3="value number '3'" att4=val4""") self.assertEqual(output, [('att1', 'val1'), ('att2', 'val2'), ('att3', "value number '3'"), ('att4', 'val4')]) class ExtensionOptionTests(unittest.TestCase): optionspec = {'a': int, 'bbb': float, 'cdef': (lambda x: x), 'empty': (lambda x: x)} def test_assemble_option_dict(self): input = utils.extract_name_value('a=1 bbb=2.0 cdef=hol%s' % chr(224)) self.assertEqual( utils.assemble_option_dict(input, self.optionspec), {'a': 1, 'bbb': 2.0, 'cdef': ('hol%s' % chr(224))}) input = utils.extract_name_value('a=1 b=2.0 c=hol%s' % chr(224)) self.assertRaises(KeyError, utils.assemble_option_dict, input, self.optionspec) input = utils.extract_name_value('a=1 bbb=two cdef=hol%s' % chr(224)) self.assertRaises(ValueError, utils.assemble_option_dict, input, self.optionspec) def test_extract_extension_options(self): field_list = nodes.field_list() field_list += nodes.field( '', nodes.field_name('', 'a'), nodes.field_body('', nodes.paragraph('', '1'))) field_list += nodes.field( '', nodes.field_name('', 'bbb'), nodes.field_body('', nodes.paragraph('', '2.0'))) field_list += nodes.field( '', nodes.field_name('', 'cdef'), nodes.field_body('', nodes.paragraph('', u'hol\u00e0'))) field_list += nodes.field( '', nodes.field_name('', 'empty'), nodes.field_body()) self.assertEqual( utils.extract_extension_options(field_list, self.optionspec), {'a': 1, 'bbb': 2.0, 'cdef': u'hol\u00e0', 'empty': None}) self.assertRaises(KeyError, utils.extract_extension_options, field_list, {}) field_list += nodes.field( '', nodes.field_name('', 'cdef'), nodes.field_body('', nodes.paragraph('', 'one'), nodes.paragraph('', 'two'))) self.assertRaises(utils.BadOptionDataError, utils.extract_extension_options, field_list, self.optionspec) field_list[-1] = nodes.field( '', nodes.field_name('', 'cdef bad'), nodes.field_body('', nodes.paragraph('', 'no arguments'))) self.assertRaises(utils.BadOptionError, utils.extract_extension_options, field_list, self.optionspec) field_list[-1] = nodes.field( '', nodes.field_name('', 'cdef'), nodes.field_body('', nodes.paragraph('', 'duplicate'))) self.assertRaises(utils.DuplicateOptionError, utils.extract_extension_options, field_list, self.optionspec) field_list[-2] = nodes.field( '', nodes.field_name('', 'unkown'), nodes.field_body('', nodes.paragraph('', 'unknown'))) self.assertRaises(KeyError, utils.extract_extension_options, field_list, self.optionspec) class HelperFunctionsTests(unittest.TestCase): def test_normalize_language_tag(self): self.assertEqual(utils.normalize_language_tag('de'), ['de']) self.assertEqual(utils.normalize_language_tag('de-AT'), ['de-at', 'de']) self.assertEqual(utils.normalize_language_tag('de-AT-1901'), ['de-at-1901', 'de-at', 'de-1901', 'de']) self.assertEqual(utils.normalize_language_tag('de-AT-1901-frak'), ['de-at-1901-frak', 'de-at-1901', 'de-at-frak', 'de-1901-frak', 'de-at', 'de-1901', 'de-frak', 'de']) self.assertEqual(utils.normalize_language_tag('grc-ibycus-x-altquot'), ['grc-ibycus-x-altquot', 'grc-ibycus', 'grc-x-altquot', 'grc']) def test_column_width(self): self.assertEqual(utils.column_width(u'de'), 2) self.assertEqual(utils.column_width(u'dâ'), 2) # pre-composed self.assertEqual(utils.column_width(u'dâ'), 2) # combining def test_relative_path(self): # Build and return a path to `target`, relative to `source`: # Use '/' as path sep in result. self.assertEqual(utils.relative_path('spam', 'spam'), '') source = os.path.join('h\xE4m', 'spam', 'fileA') target = os.path.join('h\xE4m', 'spam', 'fileB') self.assertEqual(utils.relative_path(source, target), 'fileB') source = os.path.join('h\xE4m', 'spam', 'fileA') target = os.path.join('h\xE4m', 'fileB') self.assertEqual(utils.relative_path(source, target), '../fileB') # if source is None, default to the cwd: target = os.path.join('eggs', 'fileB') self.assertEqual(utils.relative_path(None, target), 'eggs/fileB') # If there is no common prefix, return the absolute path to `target`: # source = '/foo/bar/fileA' # POSIX # TODO: how to specify an absolute path independent of the OS? # target = os.path.join('eggs', 'fileB') # self.assertEqual(utils.relative_path(source, target), # os.path.abspath('fileB')) # Correctly process unicode instances: self.assertEqual(utils.relative_path(u'spam', u'spam'), u'') source = os.path.join(u'h\xE4m', u'spam', u'fileA') target = os.path.join(u'h\xE4m', u'spam', u'fileB') self.assertEqual(utils.relative_path(source, target), u'fileB') source = os.path.join(u'h\xE4m', u'spam', u'fileA') target = os.path.join(u'h\xE4m', u'fileB') self.assertEqual(utils.relative_path(source, target), u'../fileB') # if source is None, default to the cwd: target = os.path.join(u'eggs', u'fileB') self.assertEqual(utils.relative_path(None, target), u'eggs/fileB') def test_find_file_in_dirs(self): # Search for file `path` in the sequence of directories `dirs`. # Return the first expansion that matches an existing file. dirs = ('nonex', '.', '..') self.assertEqual(utils.find_file_in_dirs('HISTORY.txt', dirs), '../HISTORY.txt') # Return `path` if the file exists in the cwd or if there is no match self.assertEqual(utils.find_file_in_dirs('alltests.py', dirs), 'alltests.py') self.assertEqual(utils.find_file_in_dirs('gibts/nicht.txt', dirs), 'gibts/nicht.txt') if __name__ == '__main__': unittest.main() ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/����������������������������������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�017117� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/config_old.txt��������������������������������������������������������������0000664�0001750�0001750�00000000412�10215337625�021761� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Test config file (old format) [options] source-link: 1 datestamp: %Y-%m-%d %H:%M UTC generator: 1 stylesheet-path: stylesheets/default.css pep-template: pep-html-template pep-stylesheet-path: stylesheets/pep.css python-home: http://www.python.org no-random: 1 ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/config_1.txt����������������������������������������������������������������0000664�0001750�0001750�00000000615�10525660651�021352� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Test config file (new format) [general] source-link: on datestamp: %Y-%m-%d %H:%M UTC generator: true raw-enabled: off [restructuredtext parser] trim-footnote-reference-space: 1 tab-width = 8 [html4css1 writer] stylesheet-path: stylesheets/default.css [pep_html writer] template: pep-html-template stylesheet-path: stylesheets/pep.css python-home: http://www.python.org no-random: yes �������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/ham.css���������������������������������������������������������������������0000664�0001750�0001750�00000000052�11116564105�020370� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������dl.docutils dd { margin-bottom: 0.5em } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/config_2.txt����������������������������������������������������������������0000664�0001750�0001750�00000000213�10134577006�021342� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Test config file (new format) [general] generator: no [html4css1 writer] footnote-references: superscript stylesheet-path: test.css �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/config_list.txt�������������������������������������������������������������0000664�0001750�0001750�00000000463�11662733056�022171� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������[general] expose_internals: a strip-classes: spam strip-elements-with-classes: sugar, flour [html4css1 writer] expose_internals: b:c:d strip-classes: pan, fun, strip-elements-with-classes: milk [pep_html writer] expose_internals: e strip-classes: parrot strip-elements-with-classes: safran �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/raw.txt���������������������������������������������������������������������0000664�0001750�0001750�00000000000�10126762313�020435� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/include.txt�����������������������������������������������������������������0000664�0001750�0001750�00000000023�10126762313�021274� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Some include text. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/stylesheet.txt��������������������������������������������������������������0000664�0001750�0001750�00000000000�10126762313�022035� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/config_list_2.txt�����������������������������������������������������������0000664�0001750�0001750�00000000137�11662733056�022410� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������[general] expose_internals: f strip-classes: ham, eggs strip-elements-with-classes: eggs,salt ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/config_error_handler.txt����������������������������������������������������0000664�0001750�0001750�00000000047�07724660237�024046� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������[general] error_encoding: ascii:strict �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/csv_dep.txt�����������������������������������������������������������������0000664�0001750�0001750�00000000046�10126762313�021301� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������.. csv-table:: :file: csv_data.txt ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/csv_data.txt����������������������������������������������������������������0000664�0001750�0001750�00000000011�10126762313�021432� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������foo, bar �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/dependencies.txt������������������������������������������������������������0000664�0001750�0001750�00000001303�11672233402�022300� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Test input for test_dependencies. Docutils can write a list of files required to generate the output like included files or embedded stylesheets. This is particularly useful in conjunction with programs like ``make``. Included files are recorded: .. include:: include.txt .. raw:: HTML :file: raw.txt Dependencies are recorded only once: .. include:: include.txt Image files are only recorded, if actually accessed (to extract the size or if embedded in the output document): .. image:: test.jpg .. figure:: ../docs/user/rst/images/title.png :figwidth: image Scaled images without given size are recorded by the html writer: .. image:: ../docs/user/rst/images/biohazard.png :scale: 50 % �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/ham.tex���������������������������������������������������������������������0000664�0001750�0001750�00000000041�11173315160�020374� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������\newcommand{\ham}{wonderful ham} �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/latin1.txt������������������������������������������������������������������0000664�0001750�0001750�00000000006�11656261702�021047� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Gre ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/data/full-template.txt�����������������������������������������������������������0000664�0001750�0001750�00000001676�10413121674�022441� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������head_prefix = """\ %(head_prefix)s""" head = """\ %(head)s""" stylesheet = """\ %(stylesheet)s""" body_prefix = """\ %(body_prefix)s""" body_pre_docinfo = """\ %(body_pre_docinfo)s""" docinfo = """\ %(docinfo)s""" body = """\ %(body)s""" body_suffix = """\ %(body_suffix)s""" head_prefix = """\ %(head_prefix)s""" head = """\ %(head)s""" stylesheet = """\ %(stylesheet)s""" body_prefix = """\ %(body_prefix)s""" body_pre_docinfo = """\ %(body_pre_docinfo)s""" docinfo = """\ %(docinfo)s""" body = """\ %(body)s""" body_suffix = """\ %(body_suffix)s""" title = """\ %(title)s""" subtitle = """\ %(subtitle)s""" header = """\ %(header)s""" footer = """\ %(footer)s""" meta = """\ %(meta)s""" fragment = """\ %(fragment)s""" html_prolog = """\ %(html_prolog)s""" html_head = """\ %(html_head)s""" html_title = """\ %(html_title)s""" html_subtitle = """\ %(html_subtitle)s""" html_body = """\ %(html_body)s""" ������������������������������������������������������������������docutils-0.12/test/local_dummy_lang.py��������������������������������������������������������������0000664�0001750�0001750�00000012346�12016623750�022073� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# $Id: local_dummy_lang.py 7504 2012-08-27 07:55:20Z grubert $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ English-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': 'dummy Author', 'authors': 'dummy Authors', 'organization': 'dummy Organization', 'address': 'dummy Address', 'contact': 'dummy Contact', 'version': 'dummy Version', 'revision': 'dummy Revision', 'status': 'dummy Status', 'date': 'dummy Date', 'copyright': 'dummy Copyright', 'dedication': 'dummy Dedication', 'abstract': 'dummy Abstract', 'attention': 'dummy Attention!', 'caution': 'dummy Caution!', 'danger': 'dummy !DANGER!', 'error': 'dummy Error', 'hint': 'dummy Hint', 'important': 'dummy Important', 'note': 'dummy Note', 'tip': 'dummy Tip', 'warning': 'dummy Warning', 'contents': 'dummy Contents'} """Mapping of node class name to label text.""" bibliographic_fields = { # language-dependent: fixed 'dummy author': 'author', 'dummy authors': 'authors', 'dummy organization': 'organization', 'dummy address': 'address', 'dummy contact': 'contact', 'dummy version': 'version', 'dummy revision': 'revision', 'dummy status': 'status', 'dummy date': 'date', 'dummy copyright': 'copyright', 'dummy dedication': 'dedication', 'dummy abstract': 'abstract'} """English (lowcased) to canonical name mapping for bibliographic fields.""" author_separators = [';', ','] """List of separator strings for the 'Authors' bibliographic field. Tried in order.""" directives = { # language-dependent: fixed 'dummy attention': 'attention', 'dummy caution': 'caution', 'dummy code': 'code', 'dummy code-block': 'code', 'dummy sourcecode': 'code', 'dummy danger': 'danger', 'dummy error': 'error', 'dummy hint': 'hint', 'dummy important': 'important', 'dummy note': 'note', 'dummy tip': 'tip', 'dummy warning': 'warning', 'dummy admonition': 'admonition', 'dummy sidebar': 'sidebar', 'dummy topic': 'topic', 'dummy line-block': 'line-block', 'dummy parsed-literal': 'parsed-literal', 'dummy rubric': 'rubric', 'dummy epigraph': 'epigraph', 'dummy highlights': 'highlights', 'dummy pull-quote': 'pull-quote', 'dummy compound': 'compound', 'dummy container': 'container', #'dummy questions': 'questions', 'dummy table': 'table', 'dummy csv-table': 'csv-table', 'dummy list-table': 'list-table', #'dummy qa': 'questions', #'dummy faq': 'questions', 'dummy meta': 'meta', 'dummy math': 'math', #'dummy imagemap': 'imagemap', 'dummy image': 'image', 'dummy figure': 'figure', 'dummy include': 'include', 'dummy raw': 'raw', 'dummy replace': 'replace', 'dummy unicode': 'unicode', 'dummy date': 'date', 'dummy class': 'class', 'dummy role': 'role', 'dummy default-role': 'default-role', 'dummy title': 'title', 'dummy contents': 'contents', 'dummy sectnum': 'sectnum', 'dummy section-numbering': 'sectnum', 'dummy header': 'header', 'dummy footer': 'footer', #'dummy footnotes': 'footnotes', #'dummy citations': 'citations', 'dummy target-notes': 'target-notes', 'dummy restructuredtext-test-directive': 'restructuredtext-test-directive'} """English name to registered (in directives/__init__.py) directive name mapping.""" roles = { # language-dependent: fixed 'dummy abbreviation': 'abbreviation', 'dummy ab': 'abbreviation', 'dummy acronym': 'acronym', 'dummy ac': 'acronym', 'dummy code': 'code', 'dummy index': 'index', 'dummy i': 'index', 'dummy subscript': 'subscript', 'dummy sub': 'subscript', 'dummy superscript': 'superscript', 'dummy sup': 'superscript', 'dummy title-reference': 'title-reference', 'dummy title': 'title-reference', 'dummy t': 'title-reference', 'dummy pep-reference': 'pep-reference', 'dummy pep': 'pep-reference', 'dummy rfc-reference': 'rfc-reference', 'dummy rfc': 'rfc-reference', 'dummy emphasis': 'emphasis', 'dummy strong': 'strong', 'dummy literal': 'literal', 'dummy math': 'math', 'dummy named-reference': 'named-reference', 'dummy anonymous-reference': 'anonymous-reference', 'dummy footnote-reference': 'footnote-reference', 'dummy citation-reference': 'citation-reference', 'dummy substitution-reference': 'substitution-reference', 'dummy target': 'target', 'dummy uri-reference': 'uri-reference', 'dummy uri': 'uri-reference', 'dummy url': 'uri-reference', 'dummy raw': 'raw',} """Mapping of English role names to canonical role names for interpreted text. """ ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_writers/��������������������������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�020744� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_writers/test_html4css1_template.py������������������������������������������0000775�0001750�0001750�00000011570�11763213420�026075� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # $Id: test_html4css1_template.py 7437 2012-06-04 20:14:08Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for the HTML writer. """ import os from __init__ import DocutilsTestSupport def suite(): settings = {'template': os.path.join(DocutilsTestSupport.testroot, 'data', 'full-template.txt'), 'stylesheet_path': '/test.css', 'embed_stylesheet': 0,} s = DocutilsTestSupport.PublishTestSuite('html', suite_settings=settings) s.generateTests(totest) return s totest = {} totest['template'] = [ ["""\ ================ Document Title ================ ---------- Subtitle ---------- :Author: Me .. footer:: footer text Section ======= Some text. """, r'''head_prefix = """\ <?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head>""" head = """\ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="generator" content="Docutils %(version)s: http://docutils.sourceforge.net/" /> <title>Document Title """ stylesheet = """\ """ body_prefix = """\
""" body_pre_docinfo = """\

Document Title

Subtitle

""" docinfo = """\
Author: Me
""" body = """\

Section

Some text.

""" body_suffix = """\
""" head_prefix = """\ """ head = """\ Document Title """ stylesheet = """\ """ body_prefix = """\
""" body_pre_docinfo = """\

Document Title

Subtitle

""" docinfo = """\
Author: Me
""" body = """\

Section

Some text.

""" body_suffix = """\
""" title = """\ Document Title""" subtitle = """\ Subtitle""" header = """\ """ footer = """\ """ meta = """\ """ fragment = """\

Section

Some text.

""" html_prolog = """\ """ html_head = """\ Document Title """ html_title = """\

Document Title

""" html_subtitle = """\

Subtitle

""" html_body = """\

Document Title

Subtitle

Author: Me

Section

Some text.

""" ''' % {'version': DocutilsTestSupport.docutils.__version__}] ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') docutils-0.12/test/test_writers/test_latex2e.py0000775000175000017500000002737412304115037023732 0ustar engelbertengelbert00000000000000# -*- coding: utf-8 -*- #! /usr/bin/env python # $Id: test_latex2e.py 7745 2014-02-28 14:15:59Z milde $ # Author: engelbert gruber # Copyright: This module has been placed in the public domain. """ Tests for latex2e writer. """ import string from __init__ import DocutilsTestSupport def suite(): settings = {'use_latex_toc': False} s = DocutilsTestSupport.PublishTestSuite('latex', suite_settings=settings) s.generateTests(totest) settings['use_latex_toc'] = True s.generateTests(totest_latex_toc) settings['use_latex_toc'] = False settings['sectnum_xform'] = False s.generateTests(totest_latex_sectnum) settings['sectnum_xform'] = True settings['use_latex_citations'] = True s.generateTests(totest_latex_citations) settings['stylesheet_path'] = 'data/spam,data/ham.tex' s.generateTests(totest_stylesheet) settings['embed_stylesheet'] = True settings['warning_stream'] = '' s.generateTests(totest_stylesheet_embed) return s head_template = string.Template( r"""$head_prefix% generated by Docutils \usepackage{fixltx2e} % LaTeX patches, \textsubscript \usepackage{cmap} % fix search and cut-and-paste in Acrobat $requirements %%% Custom LaTeX preamble $latex_preamble %%% User specified packages and stylesheets $stylesheet %%% Fallback definitions for Docutils-specific commands $fallbacks$pdfsetup $titledata %%% Body \begin{document} """) parts = dict( head_prefix = r"""\documentclass[a4paper]{article} """, requirements = r"""\usepackage{ifthen} \usepackage[T1]{fontenc} \usepackage[utf8]{inputenc} """, latex_preamble = r"""% PDF Standard Fonts \usepackage{mathptmx} % Times \usepackage[scaled=.90]{helvet} \usepackage{courier} """, stylesheet = '', fallbacks = '', fallbacks_highlight = r"""% basic code highlight: \providecommand*\DUrolecomment[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}} \providecommand*\DUroledeleted[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}} \providecommand*\DUrolekeyword[1]{\textbf{#1}} \providecommand*\DUrolestring[1]{\textit{#1}} % inline markup (custom roles) % \DUrole{#1}{#2} tries \DUrole#1{#2} \providecommand*{\DUrole}[2]{% \ifcsname DUrole#1\endcsname% \csname DUrole#1\endcsname{#2}% \else% backwards compatibility: try \docutilsrole#1{#2} \ifcsname docutilsrole#1\endcsname% \csname docutilsrole#1\endcsname{#2}% \else% #2% \fi% \fi% } """, pdfsetup = r""" % hyperlinks: \ifthenelse{\isundefined{\hypersetup}}{ \usepackage[colorlinks=true,linkcolor=blue,urlcolor=blue]{hyperref} \urlstyle{same} % normal text font (alternatives: tt, rm, sf) }{} """, titledata = '') head = head_template.substitute(parts) head_table = head_template.substitute( dict(parts, requirements = parts['requirements'] + r"""\usepackage{longtable,ltcaption,array} \setlength{\extrarowheight}{2pt} \newlength{\DUtablewidth} % internal use in tables """)) head_textcomp = head_template.substitute( dict(parts, requirements = parts['requirements'] + r"""\usepackage{textcomp} % text symbol macros """)) totest = {} totest_latex_toc = {} totest_latex_sectnum = {} totest_latex_citations = {} totest_stylesheet = {} totest_stylesheet_embed = {} totest['url_chars'] = [ ["http://nowhere/url_with%28parens%29", head + r""" \url{http://nowhere/url_with\%28parens\%29} \end{document} """], ] totest['textcomp'] = [ ["2 µm is just 2/1000000 m", head_textcomp + r""" 2 µm is just 2/1000000 m \end{document} """], ] totest['spanish quote'] = [ [".. role:: language-es\n\nUnd damit :language-es:`basta`!", head_template.substitute(dict(parts, requirements = r"""\usepackage{ifthen} \usepackage[T1]{fontenc} \usepackage[utf8]{inputenc} \usepackage[spanish,english]{babel} \AtBeginDocument{\shorthandoff{.<>}} """)) + r""" Und damit \foreignlanguage{spanish}{basta}! \end{document} """], ] totest['code role'] = [ [":code:`x=1`", head_template.substitute(dict(parts, requirements = parts['requirements']+ r"""\usepackage{color} """, fallbacks = parts['fallbacks_highlight'])) + r""" \texttt{\DUrole{code}{x=1}} \end{document} """], ] totest['table_of_contents'] = [ # input ["""\ .. contents:: Table of Contents Title 1 ======= Paragraph 1. Title 2 ------- Paragraph 2. """, ## # expected output head_template.substitute(dict(parts, requirements=parts['requirements'] + '\\setcounter{secnumdepth}{0}\n', fallbacks=r""" % title for topics, admonitions, unsupported section levels, and sidebar \providecommand*{\DUtitle}[2][class-arg]{% % call \DUtitle#1{#2} if it exists: \ifcsname DUtitle#1\endcsname% \csname DUtitle#1\endcsname{#2}% \else \smallskip\noindent\textbf{#2}\smallskip% \fi } """)) + r""" \phantomsection\label{table-of-contents} \pdfbookmark[1]{Table of Contents}{table-of-contents} \DUtitle[contents]{Table of Contents} % \begin{list}{}{} \item \hyperref[title-1]{Title 1} % \begin{list}{}{} \item \hyperref[title-2]{Title 2} \end{list} \end{list} \section{Title 1% \label{title-1}% } Paragraph 1. \subsection{Title 2% \label{title-2}% } Paragraph 2. \end{document} """], ] totest_latex_toc['no_sectnum'] = [ # input ["""\ .. contents:: first section ------------- """, ## # expected output head_template.substitute(dict(parts, requirements=parts['requirements'] + '\\setcounter{secnumdepth}{0}\n' )) + r""" \phantomsection\label{contents} \pdfbookmark[1]{Contents}{contents} \tableofcontents \section{first section% \label{first-section}% } \end{document} """], ] totest_latex_toc['sectnum'] = [ # input ["""\ .. contents:: .. sectnum:: first section ------------- """, ## # expected output head_template.substitute(dict(parts, requirements=parts['requirements'] + '\\setcounter{secnumdepth}{0}\n' )) + r""" \phantomsection\label{contents} \pdfbookmark[1]{Contents}{contents} \tableofcontents \section{1~~~first section% \label{first-section}% } \end{document} """], ] totest_latex_sectnum['no_sectnum'] = [ # input ["""\ some text first section ------------- """, ## # expected output head_template.substitute(dict(parts, requirements = parts['requirements'] + r"""\setcounter{secnumdepth}{0} """)) + r""" some text \section{first section% \label{first-section}% } \end{document} """], ] totest_latex_sectnum['sectnum'] = [ # input ["""\ .. sectnum:: some text first section ------------- """, ## # expected output head_template.substitute(dict(parts, requirements=parts['requirements'] + '\\setcounter{secnumdepth}{0}\n' )) + r""" some text \section{first section% \label{first-section}% } \end{document} """], ] totest_latex_citations['citations_with_underscore'] = [ # input ["""\ Just a test citation [my_cite2006]_. .. [my_cite2006] The underscore is mishandled. """, ## # expected output head + r""" Just a test citation \cite{my_cite2006}. \begin{thebibliography}{my\_cite2006} \bibitem[my\_cite2006]{my_cite2006}{ The underscore is mishandled. } \end{thebibliography} \end{document} """], ] totest_latex_citations['adjacent_citations'] = [ # input ["""\ Two non-citations: [MeYou2007]_[YouMe2007]_. Need to be separated for grouping: [MeYou2007]_ [YouMe2007]_. Two spaces (or anything else) for no grouping: [MeYou2007]_ [YouMe2007]_. But a line break should work: [MeYou2007]_ [YouMe2007]_. .. [MeYou2007] not. .. [YouMe2007] important. """, # expected output head + r""" Two non-citations: {[}MeYou2007{]}\_{[}YouMe2007{]}\_. Need to be separated for grouping: \cite{MeYou2007,YouMe2007}. Two spaces (or anything else) for no grouping: \cite{MeYou2007} \cite{YouMe2007}. But a line break should work: \cite{MeYou2007,YouMe2007}. \begin{thebibliography}{MeYou2007} \bibitem[MeYou2007]{MeYou2007}{ not. } \bibitem[YouMe2007]{YouMe2007}{ important. } \end{thebibliography} \end{document} """], ] totest['enumerated_lists'] = [ # input ["""\ 1. Item 1. 2. Second to the previous item this one will explain a) nothing. b) or some other. 3. Third is (I) having pre and postfixes (II) in roman numerals. """, # expected output head + r"""\newcounter{listcnt0} \begin{list}{\arabic{listcnt0}.} { \usecounter{listcnt0} \setlength{\rightmargin}{\leftmargin} } \item Item 1. \item Second to the previous item this one will explain \end{list} % \begin{quote} \setcounter{listcnt0}{0} \begin{list}{\alph{listcnt0})} { \usecounter{listcnt0} \setlength{\rightmargin}{\leftmargin} } \item nothing. \item or some other. \end{list} \end{quote} \setcounter{listcnt0}{0} \begin{list}{\arabic{listcnt0}.} { \usecounter{listcnt0} \addtocounter{listcnt0}{2} \setlength{\rightmargin}{\leftmargin} } \item Third is \end{list} % \begin{quote} \setcounter{listcnt0}{0} \begin{list}{(\Roman{listcnt0})} { \usecounter{listcnt0} \setlength{\rightmargin}{\leftmargin} } \item having pre and postfixes \item in roman numerals. \end{list} \end{quote} \end{document} """], ] # TODO: need to test for quote replacing if the language uses "ASCII-quotes" # as active character (e.g. de (ngerman)). totest['table_caption'] = [ # input ["""\ .. table:: Foo +-----+-----+ | | | +-----+-----+ | | | +-----+-----+ """, head_table + r""" \setlength{\DUtablewidth}{\linewidth} \begin{longtable}[c]{|p{0.075\DUtablewidth}|p{0.075\DUtablewidth}|} \caption{Foo}\\ \hline & \\ \hline & \\ \hline \end{longtable} \end{document} """], ] totest['table_class'] = [ # input ["""\ .. table:: :class: borderless +-----+-----+ | 1 | 2 | +-----+-----+ | 3 | 4 | +-----+-----+ """, head_table + r""" \setlength{\DUtablewidth}{\linewidth} \begin{longtable*}[c]{p{0.075\DUtablewidth}p{0.075\DUtablewidth}} 1 & 2 \\ 3 & 4 \\ \end{longtable*} \end{document} """], ] # The "[" needs to be protected (otherwise it will be seen as an # option to "\\", "\item", etc. ). totest['bracket_protection'] = [ # input ["""\ :: something before to get a end of line. [ the empty line gets tested too ] """, head + r"""% \begin{quote}{\ttfamily \raggedright \noindent something~before~to~get~a~end~of~line.\\ {[}\\ ~\\ the~empty~line~gets~tested~too\\ {]} } \end{quote} \end{document} """], ] totest['raw'] = [ [r""".. raw:: latex $E=mc^2$ A paragraph. .. |sub| raw:: latex (some raw text) Foo |sub| same paragraph. """, head + r""" $E=mc^2$ A paragraph. Foo (some raw text) same paragraph. \end{document} """], ] totest['title_with_inline_markup'] = [ ["""\ This is the *Title* =================== This is the *Subtitle* ---------------------- This is a *section title* ~~~~~~~~~~~~~~~~~~~~~~~~~ This is the *document*. """, head_template.substitute(dict(parts, requirements=parts['requirements'] + '\\setcounter{secnumdepth}{0}\n', fallbacks=r""" % subtitle (in document title) \providecommand*{\DUdocumentsubtitle}[1]{{\large #1}} """, pdfsetup=parts['pdfsetup'] + r"""\hypersetup{ pdftitle={This is the Title}, } """, titledata=r"""%%% Title Data \title{\phantomsection% This is the \emph{Title}% \label{this-is-the-title}% \\ % subtitle% \DUdocumentsubtitle{This is the \emph{Subtitle}}% \label{this-is-the-subtitle}} \author{} \date{} """)) + r"""\maketitle \section{This is a \emph{section title}% \label{this-is-a-section-title}% } This is the \emph{document}. \end{document} """], ] totest_stylesheet['two-styles'] = [ # input ["""two stylesheet links in the header""", head_template.substitute(dict(parts, stylesheet = r"""\usepackage{data/spam} \input{data/ham.tex} """)) + r""" two stylesheet links in the header \end{document} """], ] totest_stylesheet_embed['two-styles'] = [ # input ["""two stylesheets embedded in the header""", head_template.substitute(dict(parts, stylesheet = r"""% Cannot embed stylesheet 'data/spam.sty': % No such file or directory. % embedded stylesheet: data/ham.tex \newcommand{\ham}{wonderful ham} """)) + r""" two stylesheets embedded in the header \end{document} """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') docutils-0.12/test/test_writers/test_manpage.py0000664000175000017500000001276512116324524023775 0ustar engelbertengelbert00000000000000#! /usr/bin/env python # $Id: test_latex2e.py 6003 2009-06-27 20:44:09Z milde $ # Author: engelbert gruber # Copyright: This module has been placed in the public domain. """ Tests for manpage writer. """ from __init__ import DocutilsTestSupport from docutils._compat import b def suite(): settings = {} s = DocutilsTestSupport.PublishTestSuite('manpage', suite_settings=settings) s.generateTests(totest) return s indend_macros = r""". .nr rst2man-indent-level 0 . .de1 rstReportMargin \\$1 \\n[an-margin] level \\n[rst2man-indent-level] level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] - \\n[rst2man-indent0] \\n[rst2man-indent1] \\n[rst2man-indent2] .. .de1 INDENT .\" .rstReportMargin pre: . RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1 .\" .rstReportMargin post: .. .de UNINDENT . RE .\" indent \\n[an-margin] .\" old: \\n[rst2man-indent\\n[rst2man-indent-level]] .nr rst2man-indent-level -1 .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] .in \\n[rst2man-indent\\n[rst2man-indent-level]]u .. """ totest = {} totest['blank'] = [ ["", r""".\" Man page generated from reStructuredText. . .TH "" "" "" .SH NAME \- """+indend_macros+ r""".\" Generated by docutils manpage writer. . """], [r"""Hello, world. ============= .. WARNING:: This broke docutils-sphinx. """, r""".\" Man page generated from reStructuredText. . .TH HELLO, WORLD. "" "" "" .SH NAME Hello, world. \- """+indend_macros+ r""".sp \fBWARNING:\fP .INDENT 0.0 .INDENT 3.5 This broke docutils\-sphinx. .UNINDENT .UNINDENT .\" Generated by docutils manpage writer. . """], ] totest['simple'] = [ ["""\ ======== simple ======== --------------- The way to go --------------- :Author: someone@somewhere.net :Date: 2009-08-05 :Copyright: public domain :Version: 0.1 :Manual section: 1 :Manual group: text processing :Arbitrary field: some text SYNOPSIS ======== :: K.I.S.S keep it simple. DESCRIPTION =========== General rule of life. OPTIONS ======= --config= Read configuration settings from , if it exists. --version, -V Show this program's version number and exit. --help, -h Show this help message and exit. OtHeR SECTION ============= With mixed case. .. Attention:: Admonition with title * bullet list * bull and list .. admonition:: homegrown something important . period at line start. """, r""".\" Man page generated from reStructuredText. . .TH SIMPLE 1 "2009-08-05" "0.1" "text processing" .SH NAME simple \- The way to go """+indend_macros+ r""".SH SYNOPSIS .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C K.I.S.S keep it simple. .ft P .fi .UNINDENT .UNINDENT .SH DESCRIPTION .sp General rule of life. .SH OPTIONS .INDENT 0.0 .TP .BI \-\-config\fB= Read configuration settings from , if it exists. .TP .B \-\-version\fP,\fB \-V Show this program\(aqs version number and exit. .TP .B \-\-help\fP,\fB \-h Show this help message and exit. .UNINDENT .SH OTHER SECTION .sp With mixed case. .sp \fBATTENTION!:\fP .INDENT 0.0 .INDENT 3.5 Admonition with title .INDENT 0.0 .IP \(bu 2 bullet list .IP \(bu 2 bull and list .UNINDENT .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .IP "homegrown" .sp something important .UNINDENT .UNINDENT .sp \&. period at line start. .SH AUTHOR someone@somewhere.net Arbitrary field: some text .SH COPYRIGHT public domain .\" Generated by docutils manpage writer. . """], ] totest['table'] = [ ["""\ ====== ===== head and ====== ===== 1 2 abc so ====== ===== """, '''\ .\\" Man page generated from reStructuredText. . .TH "" "" "" .SH NAME \\- \n\ '''+indend_macros+ '''.INDENT 0.0 .INDENT 3.5 .TS center; |l|l|. _ T{ head T}\tT{ and T} _ T{ 1 T}\tT{ 2 T} _ T{ abc T}\tT{ so T} _ .TE .UNINDENT .UNINDENT .\\" Generated by docutils manpage writer. . '''] ] totest['optiongroup'] = [ [""" optin group with dot as group item $ bla bla bla # bla bla bla . bla bla bla [ bla bla bla ] bla bla bla """, """\ .\\" Man page generated from reStructuredText. . .TH "" "" "" .SH NAME \\- \n\ """+indend_macros+ """optin group with dot as group item .INDENT 0.0 .TP .B $ bla bla bla .UNINDENT .INDENT 0.0 .TP .B # bla bla bla .UNINDENT .INDENT 0.0 .TP .B \&. bla bla bla .UNINDENT .INDENT 0.0 .TP .B [ bla bla bla .UNINDENT .INDENT 0.0 .TP .B ] bla bla bla .UNINDENT .\\" Generated by docutils manpage writer. ."""], ] totest['definitionlist'] = [ [""" ==================== Definition List Test ==================== :Abstract: Docinfo is required. Section ======= :term1: Description of Term 1 Description of Term 1 Description of Term 1 Description of Term 1 Description of Term 1 Description of Term 1 Description of Term 1 Description of Term 1 Description of Term 1 Description of Term 1 """, '''\ .\\" Man page generated from reStructuredText. . .TH DEFINITION LIST TEST "" "" "" .SH NAME Definition List Test \\- \n\ '''+indend_macros+ '''.SS Abstract .sp Docinfo is required. .SH SECTION .INDENT 0.0 .TP .B term1 Description of Term 1 Description of Term 1 Description of Term 1 Description of Term 1 Description of Term 1 .sp Description of Term 1 Description of Term 1 Description of Term 1 Description of Term 1 Description of Term 1 .UNINDENT .\\" Generated by docutils manpage writer. .'''], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') docutils-0.12/test/test_writers/test_get_writer_class.py0000664000175000017500000000164712142141314025713 0ustar engelbertengelbert00000000000000#! /usr/bin/env python # $Id: test_get_writer_class.py 7660 2013-05-07 09:01:00Z milde $ # Author: grubert # Maintainer: docutils-develop@lists.sourceforge.net # Copyright: This module has been placed in the public domain. """ test get_writer_class """ from __init__ import DocutilsTestSupport from docutils.writers import get_writer_class class GetWriterClassTestCase(DocutilsTestSupport.StandardTestCase): #tests = ( ('manpage', 1), ('nope', 0), ('dummy-writer', 1)) def test_registered_writer(self): wr = get_writer_class('manpage') # raises ImportError on failure def test_bogus_writer(self): self.assertRaises(ImportError, get_writer_class, 'nope') def test_local_writer(self): # requires local-writer.py in test directory (testroot) wr = get_writer_class('local-writer') if __name__ == '__main__': import unittest unittest.main() docutils-0.12/test/test_writers/test_odt.py0000775000175000017500000001444511712713765023165 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: test_odt.py 7337 2012-02-03 08:16:53Z milde $ # Author: Dave Kuhlman # Copyright: This module has been placed in the public domain. """ Tests for docutils odtwriter. Instructions for adding a new test: 1. Add a new method to class DocutilsOdtTestCase (below) named test_odt_xxxx, where xxxx describes your new feature. See test_odt_basic for an example. 2. Add a new input reST (.txt) file in test/functional/input. This file should contain the smallest amount of reST that tests your new feature. Name this file odt_xxxx.txt. 3. Convert your input reST (.txt) file to an ODF (.odt) file using rst2odt.py. Place this ODF (.odt) file in test/functional/expected. Name this file odt_xxxx.odt. You can also pass parameter save_output_name='filename' to method process_test() in order to produce expected output. See and modify variable TEMP_FILE_PATH for destination. 4. Run your test. Your new test should pass. 5. If any other tests fail, that's a possible regression. """ import sys import os import StringIO import zipfile from xml.dom import minidom import tempfile from __init__ import DocutilsTestSupport import docutils import docutils.core from docutils._compat import BytesIO # # Globals TEMP_FILE_PATH = '/tmp' INPUT_PATH = 'functional/input/' EXPECTED_PATH = 'functional/expected/' class DocutilsOdtTestCase(DocutilsTestSupport.StandardTestCase): # # Check to see if we can import the needed XML library. # Report failure if we cannot. def check_import(self): WhichElementTree = '' try: # 1. Try to use lxml. #from lxml import etree #WhichElementTree = 'lxml' raise ImportError('Ignoring lxml') except ImportError, e: try: # 2. Try to use ElementTree from the Python standard library. from xml.etree import ElementTree as etree WhichElementTree = 'elementtree' except ImportError, e: try: # 3. Try to use a version of ElementTree installed as a separate # product. from elementtree import ElementTree as etree WhichElementTree = 'elementtree' except ImportError, e: s1 = '\nSkipped test of odf_odt writer. ' \ 'In order to test odf_odt writer ' \ 'must install either a version of Python containing ' \ 'ElementTree (Python version >=2.5) or ' \ 'install ElementTree.\n\n' #self.fail(s1) sys.stderr.write(s1) return WhichElementTree def process_test(self, input_filename, expected_filename, save_output_name=None, settings_overrides=None): if not self.check_import(): return # Test that xmlcharrefreplace is the default output encoding # error handler. input_file = open(INPUT_PATH + input_filename, 'rb') expected_file = open(EXPECTED_PATH + expected_filename, 'rb') input = input_file.read() expected = expected_file.read() input_file.close() expected_file.close() if settings_overrides is None: settings_overrides={ } result = docutils.core.publish_string( source=input, reader_name='standalone', writer_name='odf_odt', settings_overrides=settings_overrides) ## msg = 'file length not equal: expected length: %d actual length: %d' % ( ## len(expected), len(result), ) ## self.assertEqual(str(len(result)), str(len(expected))) if save_output_name: filename = '%s%s%s' % (TEMP_FILE_PATH, os.sep, save_output_name,) outfile = open(filename, 'w') outfile.write(result) outfile.close() content1 = self.extract_file(result, 'content.xml') content2 = self.extract_file(expected, 'content.xml') msg = 'content.xml not equal: expected len: %d actual len: %d' % ( len(content2), len(content1), ) self.assertEqual(content1, content2, msg) def extract_file(self, payload, filename): payloadfile = BytesIO() payloadfile.write(payload) payloadfile.seek(0) zfile = zipfile.ZipFile(payloadfile, 'r') content1 = zfile.read(filename) doc = minidom.parseString(content1) #content2 = doc.toprettyxml(indent=' ') content2 = doc.toxml() return content2 def assertEqual(self, first, second, msg=None): if msg is None: msg2 = msg else: sep = '+' * 60 msg1 = '\n%s\nresult:\n%s\n%s\nexpected:\n%s\n%s' % ( sep, first, sep, second, sep, ) #msg2 = '%s\n%s' % (msg1, msg, ) msg2 = '%s' % (msg, ) DocutilsTestSupport.StandardTestCase.assertEqual(self, first, second, msg2) # # Unit test methods # # All test methods should be named "test_odt_xxxx", where # xxxx is replaced with a name for the new test. # See instructions above in module doc-string. # def test_odt_basic(self): self.process_test('odt_basic.txt', 'odt_basic.odt', #save_output_name='odt_basic.odt' ) def test_odt_tables1(self): self.process_test('odt_tables1.txt', 'odt_tables1.odt', #save_output_name='odt_tables1.odt' ) def test_odt_custom_headfoot(self): settings_overrides = { 'custom_header': 'Page %p% of %P%', 'custom_footer': 'Title: %t% Date: %d3% Time: %t4%', } self.process_test('odt_custom_headfoot.txt', 'odt_custom_headfoot.odt', settings_overrides=settings_overrides, #save_output_name='odt_custom_headfoot.odt' ) # # Template for new tests. # Also add functional/input/odt_xxxx.txt and # functional/expected/odt_xxxx.odt # Replace all xxxx with name of your test. # ## def test_odt_xxxx(self): ## self.process_test('odt_xxxx.txt', 'odt_xxxx.odt') # ----------------------------------------------------------------- if __name__ == '__main__': import unittest unittest.main() docutils-0.12/test/test_writers/test_pseudoxml.py0000775000175000017500000000160210627410160024371 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: test_pseudoxml.py 5174 2007-05-31 00:01:52Z wiemann $ # Author: Lea Wiemann # Copyright: This module has been placed in the public domain. """ Test for pseudo-XML writer. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.PublishTestSuite('pseudoxml') s.generateTests(totest) return s totest = {} totest['basic'] = [ # input ["""\ This is a paragraph. ---------- This is another paragraph. A Section --------- Foo. """, # output """\ This is a paragraph. This is another paragraph.
A Section <paragraph> Foo. """] ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_writers/test_docutils_xml.py������������������������������������������������0000775�0001750�0001750�00000013357�11705515764�025107� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # $Id: test_docutils_xml.py 7315 2012-01-18 10:16:20Z milde $ # Author: Lea Wiemann <LeWiemann@gmail.com> # Copyright: This module has been placed in the public domain. """ Test for docutils XML writer. .. Attention:: While the tests compare the output on the string-level, no guarantee is given against changes to identical XML representations like ``<empty></empty>`` vs. ``<empty/>``. The sample strings in this test module mirrors the current behaviour of the docutils_xml writer. """ from StringIO import StringIO from __init__ import DocutilsTestSupport # must be imported before docutils import docutils import docutils.core # sample strings # -------------- source = u"""\ Test ---------- Test. \xe4\xf6\xfc\u20ac""" xmldecl = u"""<?xml version="1.0" encoding="iso-8859-1"?> """ doctypedecl = u"""\ <!DOCTYPE document PUBLIC "+//IDN docutils.sourceforge.net\ //DTD Docutils Generic//EN//XML"\ "http://docutils.sourceforge.net/docs/ref/docutils.dtd"> """ generatedby = u'<!-- Generated by Docutils %s -->\n' % docutils.__version__ bodynormal = u"""\ <document source="<string>"><paragraph>Test</paragraph>\ <transition></transition><paragraph>Test. \xe4\xf6\xfc€</paragraph>\ </document>""" bodynewlines = u"""\ <document source="<string>"> <paragraph>Test</paragraph> <transition> </transition> <paragraph>Test. \xe4\xf6\xfc€</paragraph> </document> """ bodyindents = u"""\ <document source="<string>"> <paragraph>Test</paragraph> <transition> </transition> <paragraph>Test. \xe4\xf6\xfc€</paragraph> </document> """ # raw XML # """"""" raw_xml_source = u"""\ .. raw:: xml <root> <child>Test \xe4\xf6\xfc\u20ac</child> > < </root> .. role:: xml(raw) :format: xml :xml:`<test>inline raw XML</test>`. """ raw_xml = u"""\ <document source="<string>"> <raw format="xml" xml:space="preserve"><root> <child>Test \xe4\xf6\xfc€</child> > < </root></raw> <paragraph><raw classes="xml" format="xml" xml:space="preserve">\ <test>inline raw XML</test></raw>.</paragraph> </document> """ invalid_raw_xml_source = u"""\ .. raw:: xml <root> <child>Test \xe4\xf6\xfc\u20ac</child> </mismatch> .. role:: xml(raw) :format: xml :xml:`<test>inline raw XML</test>`. """ invalid_raw_xml = u"""\ <document source="<string>"> <raw format="xml" xml:space="preserve"><root> <child>Test \xe4\xf6\xfc\u20ac</child> </mismatch></raw> <paragraph><raw classes="xml" format="xml" xml:space="preserve">\ <test>inline raw XML</test></raw>.</paragraph> </document> """ def publish_xml(settings, source): return docutils.core.publish_string(source=source.encode('utf8'), reader_name='standalone', writer_name='docutils_xml', settings_overrides=settings) # XML Test Case # ------------- class DocutilsXMLTestCase(DocutilsTestSupport.StandardTestCase): settings = {'input_encoding': 'utf8', 'output_encoding': 'iso-8859-1', '_disable_config': True, 'indents': False, 'newlines': True, 'xml_declaration': False, 'doctype_declaration': False, } def test_publish(self): settings = self.settings.copy() settings['newlines'] = False for settings['xml_declaration'] in True, False: for settings['doctype_declaration'] in True, False: expected = u'' if settings['xml_declaration']: expected += xmldecl if settings['doctype_declaration']: expected += doctypedecl expected += generatedby expected += bodynormal result = publish_xml(settings, source) self.assertEqual(result, expected.encode('latin1')) def test_publish_indents(self): settings = self.settings.copy() settings['indents'] = True result = publish_xml(settings, source) expected = (generatedby + bodyindents).encode('latin1') self.assertEqual(result, expected) def test_publish_newlines(self): settings = self.settings.copy() result = publish_xml(settings, source) expected = (generatedby + bodynewlines).encode('latin1') self.assertEqual(result, expected) def test_raw_xml(self): result = publish_xml(self.settings, raw_xml_source) expected = (generatedby + raw_xml).encode('latin1', 'xmlcharrefreplace') self.assertEqual(result, expected) def test_invalid_raw_xml(self): warnings = StringIO() settings = self.settings.copy() settings['warning_stream'] = warnings result = publish_xml(settings, invalid_raw_xml_source) expected = (generatedby + invalid_raw_xml).encode('latin1', 'xmlcharrefreplace') self.assertEqual(result, expected) warnings.seek(0) self.assertEqual(warnings.readlines(), [u'<string>:5: ' u'(WARNING/2) Invalid raw XML in column 2, line offset 3:\n', u'<root>\n', u' <child>Test \xe4\xf6\xfc\u20ac</child>\n', u'</mismatch>\n', u'<string>:10: ' u'(WARNING/2) Invalid raw XML in column 30, line offset 1:\n', u'<test>inline raw XML</test>\n']) # abort with SystemMessage if halt_level is "info": settings['halt_level'] = 2 settings['warning_stream'] = '' self.assertRaises(docutils.utils.SystemMessage, publish_xml, settings, invalid_raw_xml_source) if __name__ == '__main__': import unittest unittest.main() ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_writers/test_html4css1_parts.py���������������������������������������������0000775�0001750�0001750�00000024321�11501514370�025407� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_html4css1_parts.py 6502 2010-12-13 22:06:48Z smerten $ # Author: reggie dugard <reggie@users.sourceforge.net> # Copyright: This module has been placed in the public domain. """ Test for fragment code in HTML writer. Note: the 'body' and 'whole' entries have been removed from the parts dictionaries (redundant), along with 'meta' and 'stylesheet' entries with standard values, and any entries with empty values. """ from __init__ import DocutilsTestSupport from docutils import core def suite(): s = DocutilsTestSupport.HtmlPublishPartsTestSuite() s.generateTests(totest) return s totest = {} totest['Title promotion'] = ({'stylesheet_path': '', 'embed_stylesheet': 0}, [ ["""\ Simple String """, """\ {'fragment': '''<p>Simple String</p>\\n''', 'html_body': '''<div class="document"> <p>Simple String</p> </div>\\n''', 'html_head': '''...<title>\\n'''} """], ["""\ Simple String with *markup* """, """\ {'fragment': '''

Simple String with markup

\\n''', 'html_body': '''

Simple String with markup

\\n''', 'html_head': '''...\\n'''} """], ["""\ Simple String with an even simpler ``inline literal`` """, """\ {'fragment': '''

Simple String with an even simpler inline literal

\\n''', 'html_body': '''

Simple String with an even simpler inline literal

\\n''', 'html_head': '''...\\n'''} """], ["""\ A simple `anonymous reference`__ __ http://www.test.com/test_url """, """\ {'fragment': '''

A simple anonymous reference

\\n''', 'html_body': '''\\n''', 'html_head': '''...\\n'''} """], ["""\ One paragraph. Two paragraphs. """, """\ {'fragment': '''

One paragraph.

Two paragraphs.

\\n''', 'html_body': '''

One paragraph.

Two paragraphs.

\\n''', 'html_head': '''...\\n'''} """], ["""\ A simple `named reference`_ with stuff in between the reference and the target. .. _`named reference`: http://www.test.com/test_url """, """\ {'fragment': '''

A simple named reference with stuff in between the reference and the target.

\\n''', 'html_body': '''

A simple named reference with stuff in between the reference and the target.

\\n''', 'html_head': '''...\\n'''} """], ["""\ +++++ Title +++++ Subtitle ======== Some stuff Section ------- Some more stuff Another Section ............... And even more stuff """, """\ {'fragment': '''

Some stuff

Section

Some more stuff

Another Section

And even more stuff

\\n''', 'html_body': '''

Title

Subtitle

Some stuff

Section

Some more stuff

Another Section

And even more stuff

\\n''', 'html_head': '''...Title\\n''', 'html_subtitle': '''

Subtitle

\\n''', 'html_title': '''

Title

\\n''', 'subtitle': '''Subtitle''', 'title': '''Title'''} """], ["""\ +++++ Title +++++ :author: me Some stuff """, """\ {'docinfo': '''
Author: me
\\n''', 'fragment': '''

Some stuff

\\n''', 'html_body': '''

Title

Author: me

Some stuff

\\n''', 'html_head': '''...Title \\n''', 'html_title': '''

Title

\\n''', 'meta': '''\\n''', 'title': '''Title'''} """] ]) totest['No title promotion'] = ({'doctitle_xform' : 0, 'stylesheet_path': '', 'embed_stylesheet': 0}, [ ["""\ Simple String """, """\ {'fragment': '''

Simple String

\\n''', 'html_body': '''

Simple String

\\n''', 'html_head': '''...\\n'''} """], ["""\ Simple String with *markup* """, """\ {'fragment': '''

Simple String with markup

\\n''', 'html_body': '''

Simple String with markup

\\n''', 'html_head': '''...\\n'''} """], ["""\ Simple String with an even simpler ``inline literal`` """, """\ {'fragment': '''

Simple String with an even simpler inline literal

\\n''', 'html_body': '''

Simple String with an even simpler inline literal

\\n''', 'html_head': '''...\\n'''} """], ["""\ A simple `anonymous reference`__ __ http://www.test.com/test_url """, """\ {'fragment': '''

A simple anonymous reference

\\n''', 'html_body': '''\\n''', 'html_head': '''...\\n'''} """], ["""\ A simple `named reference`_ with stuff in between the reference and the target. .. _`named reference`: http://www.test.com/test_url """, """\ {'fragment': '''

A simple named reference with stuff in between the reference and the target.

\\n''', 'html_body': '''

A simple named reference with stuff in between the reference and the target.

\\n''', 'html_head': '''...\\n'''} """], ["""\ +++++ Title +++++ Not A Subtitle ============== Some stuff Section ------- Some more stuff Another Section ............... And even more stuff """, """\ {'fragment': '''

Title

Not A Subtitle

Some stuff

Section

Some more stuff

Another Section

And even more stuff

\\n''', 'html_body': '''

Title

Not A Subtitle

Some stuff

Section

Some more stuff

Another Section

And even more stuff

\\n''', 'html_head': '''...\\n'''} """], ["""\ * bullet * list """, """\ {'fragment': '''
  • bullet
  • list
\\n''', 'html_body': '''
  • bullet
  • list
\\n''', 'html_head': '''...\\n'''} """], ["""\ Not a docinfo. :This: .. _target: is :a: :simple: :field: list """, """\ {'fragment': '''

Not a docinfo.

This:

is

a:
simple:
field:list
\\n''', 'html_body': '''

Not a docinfo.

This:

is

a:
simple:
field:list
\\n''', 'html_head': '''...\\n'''} """], ["""\ Not a docinfo. :This is: a :simple field list with loooong field: names """, """\ {'fragment': '''

Not a docinfo.

This is:a
simple field list with loooong field:
 names
\\n''', 'html_body': '''

Not a docinfo.

This is:a
simple field list with loooong field:
 names
\\n''', 'html_head': '''...\\n'''} """], ]) if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') docutils-0.12/test/test_writers/__init__.py0000664000175000017500000000046210254646615023065 0ustar engelbertengelbert00000000000000import os import os.path import sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) prev = '' while sys.path[0] != prev: try: import DocutilsTestSupport break except ImportError: prev = sys.path[0] sys.path[0] = os.path.dirname(prev) sys.path.pop(0) docutils-0.12/test/test_writers/test_html4css1_misc.py0000775000175000017500000001651012120720070025204 0ustar engelbertengelbert00000000000000#! /usr/bin/env python # coding: utf-8 # $Id: test_html4css1_misc.py 7630 2013-03-15 22:27:04Z milde $ # Authors: Lea Wiemann, Dmitry Shachnev, Günter Milde # Maintainer: docutils-develop@lists.sourceforge.net # Copyright: This module has been placed in the public domain. """ Miscellaneous HTML writer tests. """ from __init__ import DocutilsTestSupport from docutils import core from docutils._compat import b class EncodingTestCase(DocutilsTestSupport.StandardTestCase): def test_xmlcharrefreplace(self): # Test that xmlcharrefreplace is the default output encoding # error handler. settings_overrides={ 'output_encoding': 'latin1', 'stylesheet': '', '_disable_config': True,} result = core.publish_string( u'EUR = \u20ac', writer_name='html4css1', settings_overrides=settings_overrides) # Encoding a euro sign with latin1 doesn't work, so the # xmlcharrefreplace handler is used. self.assertIn(b('EUR = €'), result) class SettingsTestCase(DocutilsTestSupport.StandardTestCase): data = 'test' def test_default_stylesheet(self): # default style sheet, embedded mysettings = {'_disable_config': True,} styles = core.publish_parts(self.data, writer_name='html4css1', settings_overrides=mysettings)['stylesheet'] self.assertIn('Default cascading style sheet ' 'for the HTML output of Docutils.', styles) def test_default_stylesheet_linked(self): # default style sheet, linked mysettings = {'_disable_config': True, 'embed_stylesheet': False} styles = core.publish_parts(self.data, writer_name='html4css1', settings_overrides=mysettings)['stylesheet'] self.assertIn('docutils/writers/html4css1/html4css1.css', styles) def test_math_stylesheet_linked(self): # default + math style sheet, linked mysettings = {'_disable_config': True, 'embed_stylesheet': False, 'stylesheet_path': 'html4css1.css, math.css'} styles = core.publish_parts(self.data, writer_name='html4css1', settings_overrides=mysettings)['stylesheet'] self.assertIn('docutils/writers/html4css1/html4css1.css', styles) self.assertIn('docutils/writers/html4css1/math.css', styles) def test_custom_stylesheet_linked(self): # default + custom style sheet, linked mysettings = {'_disable_config': True, 'embed_stylesheet': False, 'stylesheet_path': 'html4css1.css, ' 'data/ham.css'} styles = core.publish_parts(self.data, writer_name='html4css1', settings_overrides=mysettings)['stylesheet'] self.assertIn('docutils/writers/html4css1/html4css1.css', styles) self.assertIn('href="data/ham.css"', styles) def test_custom_stylesheet_dir(self): mysettings = {'_disable_config': True, 'embed_stylesheet': False, 'stylesheet_dirs': ('../docutils/writers/html4css1/', 'data'), 'stylesheet_path': 'html4css1.css, ham.css'} styles = core.publish_parts(self.data, writer_name='html4css1', settings_overrides=mysettings)['stylesheet'] self.assertIn('docutils/writers/html4css1/html4css1.css', styles) self.assertIn('href="data/ham.css"', styles) def test_custom_stylesheet_dir_embedded(self): mysettings = {'_disable_config': True, 'embed_stylesheet': True, 'stylesheet_dirs': ('../docutils/writers/html4css1/', 'data'), 'stylesheet_path': 'ham.css'} styles = core.publish_parts(self.data, writer_name='html4css1', settings_overrides=mysettings)['stylesheet'] self.assertIn('dl.docutils dd {\n margin-bottom: 0.5em }', styles) class MathTestCase(DocutilsTestSupport.StandardTestCase): """Attention: This class tests the current implementation of maths support which is open to change in future Docutils releases. """ mathjax_script = '

Show Title

Title slide

First Slide

Slide text.

""" % interpolations] ] totest_2['settings'] = [ ["""\ ================== Bogus Slide Show ================== We're just checking the settings """, """\ Bogus Slide Show

Bogus Slide Show

We're just checking the settings

""" % interpolations] ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') docutils-0.12/test/test_dependencies.py0000775000175000017500000001154011771146137022256 0ustar engelbertengelbert00000000000000#! /usr/bin/env python # $Id: test_dependencies.py 7463 2012-06-22 19:49:51Z milde $ # Author: Lea Wiemann # Copyright: This module has been placed in the public domain. """ Test module for the --record-dependencies option. """ import os.path import unittest import sys import DocutilsTestSupport # must be imported before docutils import docutils.core import docutils.utils import docutils.io from docutils.parsers.rst.directives.images import PIL # docutils.utils.DependencyList records POSIX paths, # i.e. "/" as a path separator even on Windows (not os.path.join). paths = {'include': u'data/include.txt', # included rst file 'raw': u'data/raw.txt', # included raw "HTML file" 'scaled-image': u'../docs/user/rst/images/biohazard.png', 'figure-image': u'../docs/user/rst/images/title.png', 'stylesheet': u'data/stylesheet.txt', } class RecordDependenciesTests(unittest.TestCase): def get_record(self, **settings): recordfile = 'record.txt' recorder = docutils.utils.DependencyList(recordfile) # (Re) create the record file by running a conversion: settings.setdefault('source_path', os.path.join('data', 'dependencies.txt')) settings.setdefault('settings_overrides', {}) settings['settings_overrides'].update(_disable_config=True, record_dependencies=recorder) docutils.core.publish_file(destination=DocutilsTestSupport.DevNull(), **settings) recorder.close() # Read the record file: record = docutils.io.FileInput(source_path=recordfile, encoding='utf8') return record.read().splitlines() def test_dependencies(self): # Note: currently, raw input files are read (and hence recorded) while # parsing even if not used in the chosen output format. # This should change (see parsers/rst/directives/misc.py). keys = ['include', 'raw'] if PIL: keys += ['figure-image'] expected = [paths[key] for key in keys] record = self.get_record(writer_name='xml') # the order of the files is arbitrary record.sort() expected.sort() self.assertEqual(record, expected) def test_dependencies_html(self): keys = ['include', 'raw'] if PIL: keys += ['figure-image', 'scaled-image'] expected = [paths[key] for key in keys] # stylesheets are tested separately in test_stylesheet_dependencies(): so = {'stylesheet_path': None, 'stylesheet': None} record = self.get_record(writer_name='html', settings_overrides=so) # the order of the files is arbitrary record.sort() expected.sort() self.assertEqual(record, expected) def test_dependencies_latex(self): # since 0.9, the latex writer records only really accessed files, too # Note: currently, raw input files are read (and hence recorded) while # parsing even if not used in the chosen output format. # This should change (see parsers/rst/directives/misc.py). keys = ['include', 'raw'] if PIL: keys += ['figure-image'] expected = [paths[key] for key in keys] record = self.get_record(writer_name='latex') # the order of the files is arbitrary record.sort() expected.sort() self.assertEqual(record, expected) def test_csv_dependencies(self): try: import csv csvsource = os.path.join('data', 'csv_dep.txt') self.assertEqual(self.get_record(source_path=csvsource), ['data/csv_data.txt']) except ImportError: pass def test_stylesheet_dependencies(self): stylesheet = paths['stylesheet'] so = {'stylesheet_path': paths['stylesheet'], 'stylesheet': None} so['embed_stylesheet'] = False record = self.get_record(writer_name='html', settings_overrides=so) self.assertTrue(stylesheet not in record, '%r should not be in %r' % (stylesheet, record)) record = self.get_record(writer_name='latex', settings_overrides=so) self.assertTrue(stylesheet not in record, '%r should not be in %r' % (stylesheet, record)) so['embed_stylesheet'] = True record = self.get_record(writer_name='html', settings_overrides=so) self.assertTrue(stylesheet in record, '%r should be in %r' % (stylesheet, record)) record = self.get_record(writer_name='latex', settings_overrides=so) self.assertTrue(stylesheet in record, '%r should be in %r' % (stylesheet, record)) if __name__ == '__main__': unittest.main() docutils-0.12/test/local-writer.py0000664000175000017500000000170612015232446021164 0ustar engelbertengelbert00000000000000# -*- coding: utf-8 -*- # $Id: local-writer.py 7500 2012-08-22 19:38:14Z grubert $ # Author: Engelbert Gruber # Copyright: This module is put into the public domain. """ mini-writer to test get_writer_class with local writer """ import docutils from docutils import nodes, writers, languages try: import roman except ImportError: import docutils.utils.roman as roman class Writer(writers.Writer): supported = ('dummy',) """Formats this writer supports.""" output = None """Final translated form of `document`.""" def __init__(self): writers.Writer.__init__(self) self.translator_class = Translator def translate(self): visitor = self.translator_class(self.document) self.document.walkabout(visitor) self.output = visitor.astext() class Translator(nodes.NodeVisitor): def __init__(self, document): nodes.NodeVisitor.__init__(self, document) docutils-0.12/test/test_publisher.py0000775000175000017500000001403712054671616021631 0ustar engelbertengelbert00000000000000#!/usr/bin/env python # $Id: test_publisher.py 7539 2012-11-26 13:50:06Z milde $ # Author: Martin Blais # Copyright: This module has been placed in the public domain. """ Test the `Publisher` facade and the ``publish_*`` convenience functions. """ import pickle import DocutilsTestSupport # must be imported before docutils import docutils from docutils import core, nodes, io from docutils._compat import b, bytes, u_prefix test_document = """\ Test Document ============= This is a test document with a broken reference: nonexistent_ """ pseudoxml_output = b("""\ Test Document <paragraph> This is a test document with a broken reference: \n\ <problematic ids="id2" refid="id1"> nonexistent_ <section classes="system-messages"> <title> Docutils System Messages <system_message backrefs="id2" ids="id1" level="3" line="4" source="<string>" type="ERROR"> <paragraph> Unknown target name: "nonexistent". """) exposed_pseudoxml_output = b("""\ <document ids="test-document" internal:refnames="{%s\'nonexistent\': [<reference: <#text: \'nonexistent\'>>]}" names="test\ document" source="<string>" title="Test Document"> <title> Test Document <paragraph> This is a test document with a broken reference: \n\ <problematic ids="id2" refid="id1"> nonexistent_ <section classes="system-messages"> <title> Docutils System Messages <system_message backrefs="id2" ids="id1" level="3" line="4" source="<string>" type="ERROR"> <paragraph> Unknown target name: "nonexistent". """ % u_prefix) class PublisherTests(DocutilsTestSupport.StandardTestCase): def test_input_error_handling(self): # core.publish_cmdline(argv=['nonexisting/path']) # exits with a short message, if `traceback` is False, # pass IOErrors to calling application if `traceback` is True try: core.publish_cmdline(argv=['nonexisting/path'], settings_overrides={'traceback': True}) except IOError, e: self.assertTrue(isinstance(e, io.InputError)) def test_output_error_handling(self): # pass IOErrors to calling application if `traceback` is True try: core.publish_cmdline(argv=['data/include.txt', 'nonexisting/path'], settings_overrides={'traceback': True}) except IOError, e: self.assertTrue(isinstance(e, io.OutputError)) class PublishDoctreeTestCase(DocutilsTestSupport.StandardTestCase, docutils.SettingsSpec): settings_default_overrides = { '_disable_config': True, 'warning_stream': io.NullOutput()} def test_publish_doctree(self): # Test `publish_doctree` and `publish_from_doctree`. # Produce the document tree. doctree = core.publish_doctree( source=test_document, reader_name='standalone', parser_name='restructuredtext', settings_spec=self, settings_overrides={'expose_internals': ['refnames', 'do_not_expose'], 'report_level': 5}) self.assertTrue(isinstance(doctree, nodes.document)) # Confirm that transforms have been applied (in this case, the # DocTitle transform): self.assertTrue(isinstance(doctree[0], nodes.title)) self.assertTrue(isinstance(doctree[1], nodes.paragraph)) # Confirm that the Messages transform has not yet been applied: self.assertEqual(len(doctree), 2) # The `do_not_expose` attribute may not show up in the # pseudoxml output because the expose_internals transform may # not be applied twice. doctree.do_not_expose = 'test' # Write out the document: output = core.publish_from_doctree( doctree, writer_name='pseudoxml', settings_spec=self, settings_overrides={'expose_internals': ['refnames', 'do_not_expose'], 'report_level': 1}) self.assertEqual(output, exposed_pseudoxml_output) # Test publishing parts using document as the source. parts = core.publish_parts( reader_name='doctree', source_class=io.DocTreeInput, source=doctree, source_path='test', writer_name='html', settings_spec=self) self.assertTrue(isinstance(parts, dict)) def test_publish_pickle(self): # Test publishing a document tree with pickling and unpickling. # Produce the document tree. doctree = core.publish_doctree( source=test_document, reader_name='standalone', parser_name='restructuredtext', settings_spec=self) self.assertTrue(isinstance(doctree, nodes.document)) # Pickle the document. Note: if this fails, some unpickleable # reference has been added somewhere within the document tree. # If so, you need to fix that. # # Note: Please do not remove this test, this is an important # requirement, applications will be built on the assumption # that we can pickle the document. # Remove the reporter and the transformer before pickling. doctree.reporter = None doctree.transformer = None doctree_pickled = pickle.dumps(doctree) self.assertTrue(isinstance(doctree_pickled, bytes)) del doctree # Unpickle the document. doctree_zombie = pickle.loads(doctree_pickled) self.assertTrue(isinstance(doctree_zombie, nodes.document)) # Write out the document: output = core.publish_from_doctree( doctree_zombie, writer_name='pseudoxml', settings_spec=self) self.assertEqual(output, pseudoxml_output) if __name__ == '__main__': import unittest unittest.main() �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_statemachine.py�������������������������������������������������������������0000775�0001750�0001750�00000024767�11771146137�022314� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_statemachine.py 7463 2012-06-22 19:49:51Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Test module for statemachine.py. """ import unittest import sys import re from DocutilsTestSupport import statemachine debug = False testtext = statemachine.string2lines("""\ First paragraph. - This is a bullet list. First list item. Second line of first para. Second para. block quote - Second list item. Example:: a literal block Last paragraph.""") expected = ('StateMachine1 text1 blank1 bullet1 known_indent1 ' 'StateMachine2 text2 text2 blank2 text2 blank2 indent2 ' 'StateMachine3 text3 blank3 finished3 finished2 ' 'bullet1 known_indent1 ' 'StateMachine2 text2 blank2 literalblock2(4) finished2 ' 'text1 finished1').split() para1 = testtext[:2] item1 = [line[2:] for line in testtext[2:9]] item2 = [line[2:] for line in testtext[9:-1]] lbindent = 6 literalblock = [line[lbindent:] for line in testtext[11:-1]] para2 = testtext[-1] class MockState(statemachine.StateWS): patterns = {'bullet': re.compile(r'- '), 'text': ''} initial_transitions = ['bullet', ['text']] levelholder = [0] def bof(self, context): self.levelholder[0] += 1 self.level = self.levelholder[0] if self.debug: print >>sys.stderr, 'StateMachine%s' % self.level return [], ['StateMachine%s' % self.level] def blank(self, match, context, next_state): result = ['blank%s' % self.level] if self.debug: print >>sys.stderr, 'blank%s' % self.level if context and context[-1] and context[-1][-2:] == '::': result.extend(self.literalblock()) return [], None, result def indent(self, match, context, next_state): if self.debug: print >>sys.stderr, 'indent%s' % self.level context, next_state, result = statemachine.StateWS.indent( self, match, context, next_state) return context, next_state, ['indent%s' % self.level] + result def known_indent(self, match, context, next_state): if self.debug: print >>sys.stderr, 'known_indent%s' % self.level context, next_state, result = statemachine.StateWS.known_indent( self, match, context, next_state) return context, next_state, ['known_indent%s' % self.level] + result def bullet(self, match, context, next_state): if self.debug: print >>sys.stderr, 'bullet%s' % self.level context, next_state, result \ = self.known_indent(match, context, next_state) return [], next_state, ['bullet%s' % self.level] + result def text(self, match, context, next_state): if self.debug: print >>sys.stderr, 'text%s' % self.level return [match.string], next_state, ['text%s' % self.level] def literalblock(self): indented, indent, offset, good = self.state_machine.get_indented() if self.debug: print >>sys.stderr, 'literalblock%s(%s)' % (self.level, indent) return ['literalblock%s(%s)' % (self.level, indent)] def eof(self, context): self.levelholder[0] -= 1 if self.debug: print >>sys.stderr, 'finished%s' % self.level return ['finished%s' % self.level] class EmptySMTests(unittest.TestCase): def setUp(self): self.sm = statemachine.StateMachine( state_classes=[], initial_state='State') self.sm.debug = debug def test_add_state(self): self.sm.add_state(statemachine.State) self.assertTrue(len(self.sm.states) == 1) self.assertRaises(statemachine.DuplicateStateError, self.sm.add_state, statemachine.State) self.sm.add_state(statemachine.StateWS) self.assertTrue(len(self.sm.states) == 2) def test_add_states(self): self.sm.add_states((statemachine.State, statemachine.StateWS)) self.assertEqual(len(self.sm.states), 2) def test_get_state(self): self.assertRaises(statemachine.UnknownStateError, self.sm.get_state) self.sm.add_states((statemachine.State, statemachine.StateWS)) self.assertRaises(statemachine.UnknownStateError, self.sm.get_state, 'unknownState') self.assertTrue(isinstance(self.sm.get_state('State'), statemachine.State)) self.assertTrue(isinstance(self.sm.get_state('StateWS'), statemachine.State)) self.assertEqual(self.sm.current_state, 'StateWS') class EmptySMWSTests(EmptySMTests): def setUp(self): self.sm = statemachine.StateMachineWS( state_classes=[], initial_state='State') self.sm.debug = debug class SMWSTests(unittest.TestCase): def setUp(self): self.sm = statemachine.StateMachineWS([MockState], 'MockState', debug=debug) self.sm.debug = debug self.sm.states['MockState'].levelholder[0] = 0 def tearDown(self): self.sm.unlink() def test___init__(self): self.assertEqual(self.sm.states.keys(), ['MockState']) self.assertEqual(len(self.sm.states['MockState'].transitions), 4) def test_get_indented(self): self.sm.input_lines = statemachine.StringList(testtext) self.sm.line_offset = -1 self.sm.next_line(3) indented, offset, good = self.sm.get_known_indented(2) self.assertEqual(indented, item1) self.assertEqual(offset, len(para1)) self.assertTrue(good) self.sm.next_line() indented, offset, good = self.sm.get_known_indented(2) self.assertEqual(indented, item2) self.assertEqual(offset, len(para1) + len(item1)) self.assertTrue(good) self.sm.previous_line(3) if self.sm.debug: print '\ntest_get_indented: self.sm.line:\n', self.sm.line indented, indent, offset, good = self.sm.get_indented() if self.sm.debug: print '\ntest_get_indented: indented:\n', indented self.assertEqual(indent, lbindent) self.assertEqual(indented, literalblock) self.assertEqual(offset, (len(para1) + len(item1) + len(item2) - len(literalblock))) self.assertTrue(good) def test_get_text_block(self): self.sm.input_lines = statemachine.StringList(testtext) self.sm.line_offset = -1 self.sm.next_line() textblock = self.sm.get_text_block() self.assertEqual(textblock, testtext[:1]) self.sm.next_line(2) textblock = self.sm.get_text_block() self.assertEqual(textblock, testtext[2:4]) def test_get_text_block_flush_left(self): self.sm.input_lines = statemachine.StringList(testtext) self.sm.line_offset = -1 self.sm.next_line() textblock = self.sm.get_text_block(flush_left=1) self.assertEqual(textblock, testtext[:1]) self.sm.next_line(2) self.assertRaises(statemachine.UnexpectedIndentationError, self.sm.get_text_block, flush_left=1) def test_run(self): self.assertEqual(self.sm.run(testtext), expected) class EmptyClass: pass class EmptyStateTests(unittest.TestCase): def setUp(self): self.state = statemachine.State(EmptyClass(), debug=debug) self.state.patterns = {'nop': 'dummy', 'nop2': 'dummy', 'nop3': 'dummy', 'bogus': 'dummy'} self.state.nop2 = self.state.nop3 = self.state.nop def test_add_transitions(self): self.assertEqual(len(self.state.transitions), 0) self.state.add_transitions(['None'], {'None': None}) self.assertEqual(len(self.state.transitions), 1) self.assertRaises(statemachine.UnknownTransitionError, self.state.add_transitions, ['bogus'], {}) self.assertRaises(statemachine.DuplicateTransitionError, self.state.add_transitions, ['None'], {'None': None}) def test_add_transition(self): self.assertEqual(len(self.state.transitions), 0) self.state.add_transition('None', None) self.assertEqual(len(self.state.transitions), 1) self.assertRaises(statemachine.DuplicateTransitionError, self.state.add_transition, 'None', None) def test_remove_transition(self): self.assertEqual(len(self.state.transitions), 0) self.state.add_transition('None', None) self.assertEqual(len(self.state.transitions), 1) self.state.remove_transition('None') self.assertEqual(len(self.state.transitions), 0) self.assertRaises(statemachine.UnknownTransitionError, self.state.remove_transition, 'None') def test_make_transition(self): dummy = re.compile('dummy') self.assertEqual(self.state.make_transition('nop', 'bogus'), (dummy, self.state.nop, 'bogus')) self.assertEqual(self.state.make_transition('nop'), (dummy, self.state.nop, self.state.__class__.__name__)) self.assertRaises(statemachine.TransitionPatternNotFound, self.state.make_transition, 'None') self.assertRaises(statemachine.TransitionMethodNotFound, self.state.make_transition, 'bogus') def test_make_transitions(self): dummy = re.compile('dummy') self.assertEqual(self.state.make_transitions(('nop', ['nop2'], ('nop3', 'bogus'))), (['nop', 'nop2', 'nop3'], {'nop': (dummy, self.state.nop, self.state.__class__.__name__), 'nop2': (dummy, self.state.nop2, self.state.__class__.__name__), 'nop3': (dummy, self.state.nop3, 'bogus')})) class MiscTests(unittest.TestCase): s2l_string = "hello\tthere\thow are\tyou?\n\tI'm fine\tthanks.\n" s2l_expected = ['hello there how are you?', " I'm fine thanks."] def test_string2lines(self): self.assertEqual(statemachine.string2lines(self.s2l_string), self.s2l_expected) if __name__ == '__main__': unittest.main() ���������docutils-0.12/test/local-parser.py������������������������������������������������������������������0000664�0001750�0001750�00000001122�12016623750�021137� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# -*- coding: utf-8 -*- # $Id: local-parser.py 7504 2012-08-27 07:55:20Z grubert $ # Authors: Engelbert Gruber <grubert@users.sourceforge.net> # Toshio Kuratomi <toshio@fedoraproject.org> # Copyright: This module is put into the public domain. """ mini-reader to test get_reader_class with local reader """ from docutils import parsers class Parser(parsers.Parser): supported = ('dummy',) """Formats this reader supports.""" def parser(self, inputstring, document): self.setup_parse(inputstring, document) document = dict() self.finish_parse() ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/��������������������������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�020724� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/__init__.py���������������������������������������������������������0000664�0001750�0001750�00000000462�10254646615�023045� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������import os import os.path import sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) prev = '' while sys.path[0] != prev: try: import DocutilsTestSupport break except ImportError: prev = sys.path[0] sys.path[0] = os.path.dirname(prev) sys.path.pop(0) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_get_parser_class.py��������������������������������������������0000664�0001750�0001750�00000001561�12016623750�025657� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_get_parser_class.py 7504 2012-08-27 07:55:20Z grubert $ # Author: grubert abadger1999 # Maintainer: docutils-develop@lists.sourceforge.net # Copyright: This module has been placed in the public domain. """ test get_parser_class """ from __init__ import DocutilsTestSupport from docutils.parsers import get_parser_class class GetParserClassTestCase(DocutilsTestSupport.StandardTestCase): def test_registered_parser(self): rdr = get_parser_class('rst') # raises ImportError on failure def test_bogus_parser(self): self.assertRaises(ImportError, get_parser_class, 'nope') def test_local_parser(self): # requires local-parser.py in test directory (testroot) wr = get_parser_class('local-parser') if __name__ == '__main__': import unittest unittest.main() �����������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/�����������������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�022573� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_TableParser.py����������������������������������������0000775�0001750�0001750�00000013724�12153360646�026425� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # coding: utf-8 # $Id: test_TableParser.py 7668 2013-06-04 12:46:30Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.GridTableParserTestSuite() s.generateTests(totest) return s totest = {} totest['grid_tables'] = [ ["""\ +-------------------------------------+ | A table with one cell and one line. | +-------------------------------------+ """, [(0, 0, 2, 38, ['A table with one cell and one line.'])], ([37], [], [[(0, 0, 1, ['A table with one cell and one line.'])]])], ["""\ +--------------+--------------+ | A table with | two columns. | +--------------+--------------+ """, [(0, 0, 2, 15, ['A table with']), (0, 15, 2, 30, ['two columns.'])], ([14, 14], [], [[(0, 0, 1, ['A table with']), (0, 0, 1, ['two columns.'])]])], # Combining chars in grid tables still fail # [u"""\ # +--------------+------------------+ # | A tāble w̅ith | comb̲ining chars. | # +--------------+------------------+ # """, # [(0, 0, 2, 15, [u'A table with']), # (0, 15, 2, 30, [u'combining chars.'])], # ([14, 14], # [], # [[(0, 0, 1, [u'A table with']), # (0, 0, 1, [u'combining chars.'])]])], ["""\ +--------------+-------------+ | A table with | two columns | +--------------+-------------+ | and | two rows. | +--------------+-------------+ """, [(0, 0, 2, 15, ['A table with']), (0, 15, 2, 29, ['two columns']), (2, 0, 4, 15, ['and']), (2, 15, 4, 29, ['two rows.'])], ([14, 13], [], [[(0, 0, 1, ['A table with']), (0, 0, 1, ['two columns'])], [(0, 0, 3, ['and']), (0, 0, 3, ['two rows.'])]])], ["""\ +--------------------------+ | A table with three rows, | +------------+-------------+ | and two | columns. | +------------+-------------+ | First and last rows | | contain column spans. | +--------------------------+ """, [(0, 0, 2, 27, ['A table with three rows,']), (2, 0, 4, 13, ['and two']), (2, 13, 4, 27, ['columns.']), (4, 0, 7, 27, ['First and last rows', 'contain column spans.'])], ([12, 13], [], [[(0, 1, 1, ['A table with three rows,']), None], [(0, 0, 3, ['and two']), (0, 0, 3, ['columns.'])], [(0, 1, 5, ['First and last rows', 'contain column spans.']), None]])], ["""\ +------------+-------------+---------------+ | A table | two rows in | and row spans | | with three +-------------+ to left and | | columns, | the middle, | right. | +------------+-------------+---------------+ """, [(0, 0, 4, 13, ['A table', 'with three', 'columns,']), (0, 13, 2, 27, ['two rows in']), (0, 27, 4, 43, ['and row spans', 'to left and', 'right.']), (2, 13, 4, 27, ['the middle,'])], ([12, 13, 15], [], [[(1, 0, 1, ['A table', 'with three', 'columns,']), (0, 0, 1, ['two rows in']), (1, 0, 1, ['and row spans', 'to left and', 'right.'])], [None, (0, 0, 3, ['the middle,']), None]])], ["""\ +------------+-------------+---------------+ | A table | | two rows in | and funny | | with 3 +--+-------------+-+ stuff. | | columns, | the middle, | | | +------------+-------------+---------------+ """, [(0, 0, 4, 13, ['A table |', 'with 3 +--', 'columns,']), (0, 13, 2, 27, ['two rows in']), (0, 27, 4, 43, [' and funny', '-+ stuff.', ' |']), (2, 13, 4, 27, ['the middle,'])], ([12, 13, 15], [], [[(1, 0, 1, ['A table |', 'with 3 +--', 'columns,']), (0, 0, 1, ['two rows in']), (1, 0, 1, [' and funny', '-+ stuff.', ' |'])], [None, (0, 0, 3, ['the middle,']), None]])], ["""\ +-----------+-------------------------+ | W/NW cell | N/NE cell | | +-------------+-----------+ | | Middle cell | E/SE cell | +-----------+-------------+ | | S/SE cell | | +-------------------------+-----------+ """, [(0, 0, 4, 12, ['W/NW cell', '', '']), (0, 12, 2, 38, ['N/NE cell']), (2, 12, 4, 26, ['Middle cell']), (2, 26, 6, 38, ['E/SE cell', '', '']), (4, 0, 6, 26, ['S/SE cell'])], ([11, 13, 11], [], [[(1, 0, 1, ['W/NW cell', '', '']), (0, 1, 1, ['N/NE cell']), None], [None, (0, 0, 3, ['Middle cell']), (1, 0, 3, ['E/SE cell', '', ''])], [(0, 1, 5, ['S/SE cell']), None, None]])], ["""\ +--------------+-------------+ | A bad table. | | +--------------+ | | Cells must be rectangles. | +----------------------------+ """, 'TableMarkupError: Malformed table; parse incomplete.', 'TableMarkupError: Malformed table; parse incomplete.'], ["""\ +-------------------------------+ | A table with two header rows, | +------------+------------------+ | the first | with a span. | +============+==================+ | Two body | rows, | +------------+------------------+ | the second with a span. | +-------------------------------+ """, [(0, 0, 2, 32, ['A table with two header rows,']), (2, 0, 4, 13, ['the first']), (2, 13, 4, 32, ['with a span.']), (4, 0, 6, 13, ['Two body']), (4, 13, 6, 32, ['rows,']), (6, 0, 8, 32, ['the second with a span.'])], ([12, 18], [[(0, 1, 1, ['A table with two header rows,']), None], [(0, 0, 3, ['the first']), (0, 0, 3, ['with a span.'])]], [[(0, 0, 5, ['Two body']), (0, 0, 5, ['rows,'])], [(0, 1, 7, ['the second with a span.']), None]])], ["""\ +-------------------------------+ | A table with two head/body | +=============+=================+ | row | separators. | +=============+=================+ | That's bad. | | +-------------+-----------------+ """, 'TableMarkupError: Multiple head/body row separators ' '(table lines 3 and 5); only one allowed.', 'TableMarkupError: Multiple head/body row separators ' '(table lines 3 and 5); only one allowed.'], ["""\ +-------------------------------------+ | | +-------------------------------------+ """, [(0, 0, 2, 38, [''])], ([37], [], [[(0, 0, 1, [''])]])], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ��������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_doctest_blocks.py�������������������������������������0000775�0001750�0001750�00000002554�10434150472�027214� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_doctest_blocks.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['doctest_blocks'] = [ ["""\ Paragraph. >>> print "Doctest block." Doctest block. Paragraph. """, """\ <document source="test data"> <paragraph> Paragraph. <doctest_block xml:space="preserve"> >>> print "Doctest block." Doctest block. <paragraph> Paragraph. """], ["""\ Paragraph. >>> print " Indented output." Indented output. """, """\ <document source="test data"> <paragraph> Paragraph. <doctest_block xml:space="preserve"> >>> print " Indented output." Indented output. """], ["""\ Paragraph. >>> print " Indented block & output." Indented block & output. """, """\ <document source="test data"> <paragraph> Paragraph. <block_quote> <doctest_block xml:space="preserve"> >>> print " Indented block & output." Indented block & output. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_tables.py���������������������������������������������0000775�0001750�0001750�00000111160�11703370411�025453� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_tables.py 7313 2012-01-11 20:28:57Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ import os from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s mydir = 'test_parsers/test_rst/' include2 = os.path.join(mydir, 'test_directives/include2.txt') totest = {} totest['grid_tables'] = [ ["""\ +-------------------------------------+ | A table with one cell and one line. | +-------------------------------------+ """, """\ <document source="test data"> <table> <tgroup cols="1"> <colspec colwidth="37"> <tbody> <row> <entry> <paragraph> A table with one cell and one line. """], ["""\ +-----------------------+ | A table with one cell | | and two lines. | +-----------------------+ """, """\ <document source="test data"> <table> <tgroup cols="1"> <colspec colwidth="23"> <tbody> <row> <entry> <paragraph> A table with one cell and two lines. """], ["""\ +-----------------------+ | A malformed table. | +-----------------------+ """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Malformed table. <literal_block xml:space="preserve"> +-----------------------+ | A malformed table. | +-----------------------+ """], ["""\ +------------------------+ | A well-formed | table. | +------------------------+ +------------------------+ | This +----------+ too! | +------------------------+ """, """\ <document source="test data"> <table> <tgroup cols="1"> <colspec colwidth="24"> <tbody> <row> <entry> <paragraph> A well-formed | table. <table> <tgroup cols="1"> <colspec colwidth="24"> <tbody> <row> <entry> <paragraph> This +----------+ too! """], ["""\ +--------------+--------------+ | A table with | two columns. | +--------------+--------------+ """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="14"> <colspec colwidth="14"> <tbody> <row> <entry> <paragraph> A table with <entry> <paragraph> two columns. """], ["""\ +--------------+ | A table with | +--------------+ | two rows. | +--------------+ """, """\ <document source="test data"> <table> <tgroup cols="1"> <colspec colwidth="14"> <tbody> <row> <entry> <paragraph> A table with <row> <entry> <paragraph> two rows. """], ["""\ +--------------+-------------+ | A table with | two columns | +--------------+-------------+ | and | two rows. | +--------------+-------------+ """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="14"> <colspec colwidth="13"> <tbody> <row> <entry> <paragraph> A table with <entry> <paragraph> two columns <row> <entry> <paragraph> and <entry> <paragraph> two rows. """], ["""\ +--------------+---------------+ | A table with | two columns, | +--------------+---------------+ | two rows, and a column span. | +------------------------------+ """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="14"> <colspec colwidth="15"> <tbody> <row> <entry> <paragraph> A table with <entry> <paragraph> two columns, <row> <entry morecols="1"> <paragraph> two rows, and a column span. """], ["""\ +--------------------------+ | A table with three rows, | +------------+-------------+ | and two | columns. | +------------+-------------+ | First and last rows | | contains column spans. | +--------------------------+ """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="12"> <colspec colwidth="13"> <tbody> <row> <entry morecols="1"> <paragraph> A table with three rows, <row> <entry> <paragraph> and two <entry> <paragraph> columns. <row> <entry morecols="1"> <paragraph> First and last rows contains column spans. """], ["""\ +--------------+--------------+ | A table with | two columns, | +--------------+ and a row | | two rows, | span. | +--------------+--------------+ """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="14"> <colspec colwidth="14"> <tbody> <row> <entry> <paragraph> A table with <entry morerows="1"> <paragraph> two columns, and a row span. <row> <entry> <paragraph> two rows, """], ["""\ +------------+-------------+---------------+ | A table | two rows in | and row spans | | with three +-------------+ to left and | | columns, | the middle, | right. | +------------+-------------+---------------+ """, """\ <document source="test data"> <table> <tgroup cols="3"> <colspec colwidth="12"> <colspec colwidth="13"> <colspec colwidth="15"> <tbody> <row> <entry morerows="1"> <paragraph> A table with three columns, <entry> <paragraph> two rows in <entry morerows="1"> <paragraph> and row spans to left and right. <row> <entry> <paragraph> the middle, """], ["""\ Complex spanning pattern (no edge knows all rows/cols): +-----------+-------------------------+ | W/NW cell | N/NE cell | | +-------------+-----------+ | | Middle cell | E/SE cell | +-----------+-------------+ | | S/SE cell | | +-------------------------+-----------+ """, """\ <document source="test data"> <paragraph> Complex spanning pattern (no edge knows all rows/cols): <table> <tgroup cols="3"> <colspec colwidth="11"> <colspec colwidth="13"> <colspec colwidth="11"> <tbody> <row> <entry morerows="1"> <paragraph> W/NW cell <entry morecols="1"> <paragraph> N/NE cell <row> <entry> <paragraph> Middle cell <entry morerows="1"> <paragraph> E/SE cell <row> <entry morecols="1"> <paragraph> S/SE cell """], ["""\ +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | +------------------------+------------+----------+----------+ | body row 2 | Cells may span columns. | +------------------------+------------+---------------------+ | body row 3 | Cells may | - Table cells | +------------------------+ span rows. | - contain | | body row 4 | | - body elements. | +------------------------+------------+---------------------+ """, """\ <document source="test data"> <table> <tgroup cols="4"> <colspec colwidth="24"> <colspec colwidth="12"> <colspec colwidth="10"> <colspec colwidth="10"> <thead> <row> <entry> <paragraph> Header row, column 1 <entry> <paragraph> Header 2 <entry> <paragraph> Header 3 <entry> <paragraph> Header 4 <tbody> <row> <entry> <paragraph> body row 1, column 1 <entry> <paragraph> column 2 <entry> <paragraph> column 3 <entry> <paragraph> column 4 <row> <entry> <paragraph> body row 2 <entry morecols="2"> <paragraph> Cells may span columns. <row> <entry> <paragraph> body row 3 <entry morerows="1"> <paragraph> Cells may span rows. <entry morecols="1" morerows="1"> <bullet_list bullet="-"> <list_item> <paragraph> Table cells <list_item> <paragraph> contain <list_item> <paragraph> body elements. <row> <entry> <paragraph> body row 4 """], ["""\ +-----------------+--------+ | A simple table | cell 2 | +-----------------+--------+ | cell 3 | cell 4 | +-----------------+--------+ No blank line after table. """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="17"> <colspec colwidth="8"> <tbody> <row> <entry> <paragraph> A simple table <entry> <paragraph> cell 2 <row> <entry> <paragraph> cell 3 <entry> <paragraph> cell 4 <system_message level="2" line="6" source="test data" type="WARNING"> <paragraph> Blank line required after table. <paragraph> No blank line after table. """], ["""\ +-----------------+--------+ | A simple table | cell 2 | +-----------------+--------+ | cell 3 | cell 4 | +-----------------+--------+ Unexpected indent and no blank line after table. """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="17"> <colspec colwidth="8"> <tbody> <row> <entry> <paragraph> A simple table <entry> <paragraph> cell 2 <row> <entry> <paragraph> cell 3 <entry> <paragraph> cell 4 <system_message level="3" line="6" source="test data" type="ERROR"> <paragraph> Unexpected indentation. <system_message level="2" line="6" source="test data" type="WARNING"> <paragraph> Blank line required after table. <block_quote> <paragraph> Unexpected indent and no blank line after table. """], ["""\ +--------------+-------------+ | A bad table. | | +--------------+ | | Cells must be rectangles. | +----------------------------+ """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Malformed table. Malformed table; parse incomplete. <literal_block xml:space="preserve"> +--------------+-------------+ | A bad table. | | +--------------+ | | Cells must be rectangles. | +----------------------------+ """], ["""\ +------------------------------+ | This table contains another. | | | | +-------------------------+ | | | A table within a table. | | | +-------------------------+ | +------------------------------+ """, """\ <document source="test data"> <table> <tgroup cols="1"> <colspec colwidth="30"> <tbody> <row> <entry> <paragraph> This table contains another. <table> <tgroup cols="1"> <colspec colwidth="25"> <tbody> <row> <entry> <paragraph> A table within a table. """], ["""\ +------------------+--------+ | A simple table | | +------------------+--------+ | with empty cells | | +------------------+--------+ """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="18"> <colspec colwidth="8"> <tbody> <row> <entry> <paragraph> A simple table <entry> <row> <entry> <paragraph> with empty cells <entry> """], [("""\ +------------------------------------------------------------------------------+ | .. include:: | %s +------------------------------------------------------------------------------+ | (The first cell of this table may expand | | to accommodate long filesystem paths.) | +------------------------------------------------------------------------------+ """) % ('\n'.join(['| %-70s |' % include2[part * 70 : (part + 1) * 70] for part in range(len(include2) // 70 + 1)])), """\ <document source="test data"> <table> <tgroup cols="1"> <colspec colwidth="78"> <tbody> <row> <entry> <paragraph> Here are some paragraphs that can appear at any level. <paragraph> This file (include2.txt) is used by <literal> test_include.py . <row> <entry> <paragraph> (The first cell of this table may expand to accommodate long filesystem paths.) """], [("""\ Something before. +------------------------------------------------------------------------------+ | .. include:: | %s +------------------------------------------------------------------------------+ Something afterwards. And more. """) % ('\n'.join(['| %-70s |' % include2[part * 70 : (part + 1) * 70] for part in range(len(include2) // 70 + 1)])), """\ <document source="test data"> <paragraph> Something before. <table> <tgroup cols="1"> <colspec colwidth="78"> <tbody> <row> <entry> <paragraph> Here are some paragraphs that can appear at any level. <paragraph> This file (include2.txt) is used by <literal> test_include.py . <paragraph> Something afterwards. <paragraph> And more. """], ] totest['simple_tables'] = [ ["""\ ============ ============ A table with two columns. ============ ============ Paragraph. """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="12"> <colspec colwidth="12"> <tbody> <row> <entry> <paragraph> A table with <entry> <paragraph> two columns. <paragraph> Paragraph. """], ["""\ ============ ============ A table with two columns and two rows. ============ ============ """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="12"> <colspec colwidth="12"> <tbody> <row> <entry> <paragraph> A table with <entry> <paragraph> two columns <row> <entry> <paragraph> and <entry> <paragraph> two rows. """], ["""\ ============ ============== A table with two columns, two rows, and a column span. ============================ """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="12"> <colspec colwidth="14"> <tbody> <row> <entry> <paragraph> A table with <entry> <paragraph> two columns, <row> <entry morecols="1"> <paragraph> two rows, and a column span. """], ["""\ == =========== =========== 1 A table with three rows, -- ------------------------ 2 and three columns. 3 First and third rows contain column spans. This row is a multi-line row, and overflows to the right. -- ------------------------ 4 One last row. == =========== =========== """, """\ <document source="test data"> <table> <tgroup cols="3"> <colspec colwidth="2"> <colspec colwidth="11"> <colspec colwidth="44"> <tbody> <row> <entry> <paragraph> 1 <entry morecols="1"> <paragraph> A table with three rows, <row> <entry> <paragraph> 2 <entry> <paragraph> and three <entry> <paragraph> columns. <row> <entry> <paragraph> 3 <entry morecols="1"> <paragraph> First and third rows contain column spans. <paragraph> This row is a multi-line row, and overflows to the right. <row> <entry> <paragraph> 4 <entry> <paragraph> One last <entry> <paragraph> row. """], ["""\ ======= ========= ======== A table with three columns. ================== ======== """, """\ <document source="test data"> <table> <tgroup cols="3"> <colspec colwidth="7"> <colspec colwidth="9"> <colspec colwidth="8"> <tbody> <row> <entry morecols="1"> <paragraph> A table with three <entry> <paragraph> columns. """], ["""\ ============== ====== A simple table with no bottom border """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Malformed table. No bottom table border found. <literal_block xml:space="preserve"> ============== ====== A simple table with no bottom border """], ["""\ ============== ====== A simple table cell 2 cell 3 cell 4 ============== ====== No blank line after table. """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Malformed table. No bottom table border found or no blank line after table bottom. <literal_block xml:space="preserve"> ============== ====== A simple table cell 2 cell 3 cell 4 ============== ====== <system_message level="2" line="5" source="test data" type="WARNING"> <paragraph> Blank line required after table. <paragraph> No blank line after table. """], ["""\ ============== ====== A simple table cell 2 ============== ====== cell 3 cell 4 ============== ====== No blank line after table. """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="14"> <colspec colwidth="6"> <thead> <row> <entry> <paragraph> A simple table <entry> <paragraph> cell 2 <tbody> <row> <entry> <paragraph> cell 3 <entry> <paragraph> cell 4 <system_message level="2" line="6" source="test data" type="WARNING"> <paragraph> Blank line required after table. <paragraph> No blank line after table. """], ["""\ ============== ====== A simple table cell 2 cell 3 cell 4 ============== ====== Unexpected indent and no blank line after table. """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Malformed table. No bottom table border found or no blank line after table bottom. <literal_block xml:space="preserve"> ============== ====== A simple table cell 2 cell 3 cell 4 ============== ====== <system_message level="2" line="5" source="test data" type="WARNING"> <paragraph> Blank line required after table. <block_quote> <paragraph> Unexpected indent and no blank line after table. """], ["""\ ============== ====== A bad table cell 2 cell 3 cell 4 ============ ======== """, """\ <document source="test data"> <system_message level="3" line="4" source="test data" type="ERROR"> <paragraph> Malformed table. Column span alignment problem in table line 4. <literal_block xml:space="preserve"> ============== ====== A bad table cell 2 cell 3 cell 4 ============ ======== """], ["""\ ======== ========= A bad table cell 2 cell 3 cell 4 ======== ========= """, """\ <document source="test data"> <system_message level="3" line="2" source="test data" type="ERROR"> <paragraph> Malformed table. Text in column margin in table line 2. <literal_block xml:space="preserve"> ======== ========= A bad table cell 2 cell 3 cell 4 ======== ========= """], ["""\ == ============================ 1 This table contains another. 2 ======= ====== ======== A table within a table. ======= ====== ======== The outer table does have to have at least two columns though. == ============================ """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="2"> <colspec colwidth="28"> <tbody> <row> <entry> <paragraph> 1 <entry> <paragraph> This table contains another. <row> <entry> <paragraph> 2 <entry> <table> <tgroup cols="3"> <colspec colwidth="7"> <colspec colwidth="6"> <colspec colwidth="8"> <tbody> <row> <entry> <paragraph> A table <entry> <paragraph> within <entry> <paragraph> a table. <paragraph> The outer table does have to have at least two columns though. """], ["""\ ================ ====== A simple table with empty cells ================ ====== """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="16"> <colspec colwidth="6"> <tbody> <row> <entry> <paragraph> A simple table <entry> <row> <entry> <paragraph> with empty cells <entry> """], ["""\ ============== ======== A table with ============== ======== centered cells. ============== ======== """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="14"> <colspec colwidth="8"> <thead> <row> <entry> <paragraph> A table <entry> <paragraph> with <tbody> <row> <entry> <paragraph> centered <entry> <paragraph> cells. """], ["""\ ============== ====== A simple table this text extends to the right cell 3 the bottom border below is too long ============== ======== """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Malformed table. Bottom/header table border does not match top border. <literal_block xml:space="preserve"> ============== ====== A simple table this text extends to the right cell 3 the bottom border below is too long ============== ======== """], ["""\ ============ ================= A table with row separators. ------------ ----------------- Blank line before. ------------ ----------------- Blank lines before and after. ------------ ----------------- Blank line after. ============ ================= """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="12"> <colspec colwidth="17"> <tbody> <row> <entry> <paragraph> A table with <entry> <paragraph> row separators. <row> <entry> <paragraph> Blank line <entry> <paragraph> before. <row> <entry> <paragraph> Blank lines <entry> <paragraph> before and after. <row> <entry> <paragraph> Blank line <entry> <paragraph> after. """], ["""\ ============ ==================== A table with many row separators. ------------ -------------------- ------------ -------------------- ------------ -------------------- ============ ==================== """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="12"> <colspec colwidth="20"> <tbody> <row> <entry> <paragraph> A table with <entry> <paragraph> many row separators. <row> <entry> <entry> <row> <entry> <entry> <row> <entry> <entry> """], ["""\ == =========== =========== 1 Span columns 2 & 3 -- ------------------------ 2 Span columns 2 & 3 ------------------------ 3 == =========== =========== == =========== =========== 1 Span cols 1&2 but not 3 --------------- ----------- 2 Span cols 1&2 but not 3 --------------- 3 no spans here == =========== =========== == =========== =========== 1 Not a span Not a span ----------- ----------- 2 == =========== =========== """, """\ <document source="test data"> <system_message level="3" line="4" source="test data" type="ERROR"> <paragraph> Malformed table. Text in column margin in table line 4. <literal_block xml:space="preserve"> == =========== =========== 1 Span columns 2 & 3 -- ------------------------ 2 Span columns 2 & 3 ------------------------ 3 == =========== =========== <system_message level="3" line="13" source="test data" type="ERROR"> <paragraph> Malformed table. Column span incomplete in table line 5. <literal_block xml:space="preserve"> == =========== =========== 1 Span cols 1&2 but not 3 --------------- ----------- 2 Span cols 1&2 but not 3 --------------- 3 no spans here == =========== =========== <table> <tgroup cols="3"> <colspec colwidth="2"> <colspec colwidth="11"> <colspec colwidth="11"> <tbody> <row> <entry> <paragraph> 1 <entry> <system_message level="4" line="19" source="test data" type="SEVERE"> <paragraph> Unexpected section title. <literal_block xml:space="preserve"> Not a span ----------- <entry> <system_message level="4" line="19" source="test data" type="SEVERE"> <paragraph> Unexpected section title. <literal_block xml:space="preserve"> Not a span ----------- <row> <entry> <paragraph> 2 <entry> <entry> """], ["""\ ========= ===================================================================== Inclusion .. include:: %s Note The first row of this table may expand to accommodate long filesystem paths. ========= ===================================================================== """ % ('\n'.join([' %-65s' % include2[part * 65 : (part + 1) * 65] for part in range(len(include2) // 65 + 1)])), """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="9"> <colspec colwidth="69"> <tbody> <row> <entry> <paragraph> Inclusion <entry> <paragraph> Here are some paragraphs that can appear at any level. <paragraph> This file (include2.txt) is used by <literal> test_include.py . <row> <entry> <paragraph> Note <entry> <paragraph> The first row of this table may expand to accommodate long filesystem paths. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_section_headers.py������������������������������������0000775�0001750�0001750�00000047704�11466520626�027367� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# -*- coding: utf-8 -*- #! /usr/bin/env python # $Id: test_section_headers.py 6476 2010-11-10 13:43:50Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """Tests for states.py.""" from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['section_headers'] = [ ["""\ Title ===== Paragraph. """, """\ <document source="test data"> <section ids="title" names="title"> <title> Title <paragraph> Paragraph. """], ["""\ Title ===== Paragraph (no blank line). """, """\ <document source="test data"> <section ids="title" names="title"> <title> Title <paragraph> Paragraph (no blank line). """], ["""\ Paragraph. Title ===== Paragraph. """, """\ <document source="test data"> <paragraph> Paragraph. <section ids="title" names="title"> <title> Title <paragraph> Paragraph. """], ["""\ Test unexpected section titles. Title ===== Paragraph. ----- Title ----- Paragraph. """, """\ <document source="test data"> <paragraph> Test unexpected section titles. <block_quote> <system_message level="4" line="4" source="test data" type="SEVERE"> <paragraph> Unexpected section title. <literal_block xml:space="preserve"> Title ===== <paragraph> Paragraph. <system_message level="4" line="7" source="test data" type="SEVERE"> <paragraph> Unexpected section title or transition. <literal_block xml:space="preserve"> ----- <system_message level="4" line="9" source="test data" type="SEVERE"> <paragraph> Unexpected section title. <literal_block xml:space="preserve"> Title ----- <paragraph> Paragraph. """], ["""\ Title ==== Test short underline. """, """\ <document source="test data"> <section ids="title" names="title"> <title> Title <system_message level="2" line="2" source="test data" type="WARNING"> <paragraph> Title underline too short. <literal_block xml:space="preserve"> Title ==== <paragraph> Test short underline. """], [u"""\ à with combining varia ====================== Do not count combining chars in title column width. """, u"""\ <document source="test data"> <section ids="a-with-combining-varia" names="a\u0300\ with\ combining\ varia"> <title> à with combining varia <paragraph> Do not count combining chars in title column width. """], ["""\ ===== Title ===== Test overline title. """, """\ <document source="test data"> <section ids="title" names="title"> <title> Title <paragraph> Test overline title. """], ["""\ ======= Title ======= Test overline title with inset. """, """\ <document source="test data"> <section ids="title" names="title"> <title> Title <paragraph> Test overline title with inset. """], ["""\ ======================== Test Missing Underline """, """\ <document source="test data"> <system_message level="4" line="1" source="test data" type="SEVERE"> <paragraph> Incomplete section title. <literal_block xml:space="preserve"> ======================== Test Missing Underline """], ["""\ ======================== Test Missing Underline """, """\ <document source="test data"> <system_message level="4" line="1" source="test data" type="SEVERE"> <paragraph> Missing matching underline for section title overline. <literal_block xml:space="preserve"> ======================== Test Missing Underline """], ["""\ ======= Title Test missing underline, with paragraph. """, """\ <document source="test data"> <system_message level="4" line="1" source="test data" type="SEVERE"> <paragraph> Missing matching underline for section title overline. <literal_block xml:space="preserve"> ======= Title <paragraph> Test missing underline, with paragraph. """], ["""\ ======= Long Title ======= Test long title and space normalization. """, """\ <document source="test data"> <section ids="long-title" names="long\ title"> <title> Long Title <system_message level="2" line="1" source="test data" type="WARNING"> <paragraph> Title overline too short. <literal_block xml:space="preserve"> ======= Long Title ======= <paragraph> Test long title and space normalization. """], ["""\ ======= Title ------- Paragraph. """, """\ <document source="test data"> <system_message level="4" line="1" source="test data" type="SEVERE"> <paragraph> Title overline & underline mismatch. <literal_block xml:space="preserve"> ======= Title ------- <paragraph> Paragraph. """], ["""\ ======================== ======================== Test missing titles; blank line in-between. ======================== ======================== """, """\ <document source="test data"> <transition> <transition> <paragraph> Test missing titles; blank line in-between. <transition> <transition> """], ["""\ ======================== ======================== Test missing titles; nothing in-between. ======================== ======================== """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Invalid section title or transition marker. <literal_block xml:space="preserve"> ======================== ======================== <paragraph> Test missing titles; nothing in-between. <system_message level="3" line="6" source="test data" type="ERROR"> <paragraph> Invalid section title or transition marker. <literal_block xml:space="preserve"> ======================== ======================== """], ["""\ .. Test return to existing, highest-level section (Title 3). Title 1 ======= Paragraph 1. Title 2 ------- Paragraph 2. Title 3 ======= Paragraph 3. Title 4 ------- Paragraph 4. """, """\ <document source="test data"> <comment xml:space="preserve"> Test return to existing, highest-level section (Title 3). <section ids="title-1" names="title\ 1"> <title> Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title> Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title> Title 3 <paragraph> Paragraph 3. <section ids="title-4" names="title\ 4"> <title> Title 4 <paragraph> Paragraph 4. """], ["""\ Test return to existing, highest-level section (Title 3, with overlines). ======= Title 1 ======= Paragraph 1. ------- Title 2 ------- Paragraph 2. ======= Title 3 ======= Paragraph 3. ------- Title 4 ------- Paragraph 4. """, """\ <document source="test data"> <paragraph> Test return to existing, highest-level section (Title 3, with overlines). <section ids="title-1" names="title\ 1"> <title> Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title> Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title> Title 3 <paragraph> Paragraph 3. <section ids="title-4" names="title\ 4"> <title> Title 4 <paragraph> Paragraph 4. """], ["""\ Test return to existing, higher-level section (Title 4). Title 1 ======= Paragraph 1. Title 2 ------- Paragraph 2. Title 3 ``````` Paragraph 3. Title 4 ------- Paragraph 4. """, """\ <document source="test data"> <paragraph> Test return to existing, higher-level section (Title 4). <section ids="title-1" names="title\ 1"> <title> Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title> Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title> Title 3 <paragraph> Paragraph 3. <section ids="title-4" names="title\ 4"> <title> Title 4 <paragraph> Paragraph 4. """], ["""\ Test bad subsection order (Title 4). Title 1 ======= Paragraph 1. Title 2 ------- Paragraph 2. Title 3 ======= Paragraph 3. Title 4 ``````` Paragraph 4. """, """\ <document source="test data"> <paragraph> Test bad subsection order (Title 4). <section ids="title-1" names="title\ 1"> <title> Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title> Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title> Title 3 <paragraph> Paragraph 3. <system_message level="4" line="15" source="test data" type="SEVERE"> <paragraph> Title level inconsistent: <literal_block xml:space="preserve"> Title 4 ``````` <paragraph> Paragraph 4. """], ["""\ Test bad subsection order (Title 4, with overlines). ======= Title 1 ======= Paragraph 1. ------- Title 2 ------- Paragraph 2. ======= Title 3 ======= Paragraph 3. ``````` Title 4 ``````` Paragraph 4. """, """\ <document source="test data"> <paragraph> Test bad subsection order (Title 4, with overlines). <section ids="title-1" names="title\ 1"> <title> Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title\ 2"> <title> Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title\ 3"> <title> Title 3 <paragraph> Paragraph 3. <system_message level="4" line="19" source="test data" type="SEVERE"> <paragraph> Title level inconsistent: <literal_block xml:space="preserve"> ``````` Title 4 ``````` <paragraph> Paragraph 4. """], ["""\ Title containing *inline* ``markup`` ==================================== Paragraph. """, """\ <document source="test data"> <section ids="title-containing-inline-markup" names="title\ containing\ inline\ markup"> <title> Title containing \n\ <emphasis> inline \n\ <literal> markup <paragraph> Paragraph. """], ["""\ 1. Numbered Title ================= Paragraph. """, """\ <document source="test data"> <section ids="numbered-title" names="1.\ numbered\ title"> <title> 1. Numbered Title <paragraph> Paragraph. """], ["""\ 1. Item 1. 2. Item 2. 3. Numbered Title ================= Paragraph. """, """\ <document source="test data"> <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Item 1. <list_item> <paragraph> Item 2. <system_message level="2" line="3" source="test data" type="WARNING"> <paragraph> Enumerated list ends without a blank line; unexpected unindent. <section ids="numbered-title" names="3.\ numbered\ title"> <title> 3. Numbered Title <paragraph> Paragraph. """], ["""\ ABC === Short title. """, """\ <document source="test data"> <section ids="abc" names="abc"> <title> ABC <paragraph> Short title. """], ["""\ ABC == Underline too short. """, """\ <document source="test data"> <system_message level="1" line="2" source="test data" type="INFO"> <paragraph> Possible title underline, too short for the title. Treating it as ordinary text because it's so short. <paragraph> ABC == <paragraph> Underline too short. """], ["""\ == ABC == Over & underline too short. """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Possible incomplete section title. Treating the overline as ordinary text because it's so short. <paragraph> == ABC == <paragraph> Over & underline too short. """], ["""\ == ABC Overline too short, no underline. """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Possible incomplete section title. Treating the overline as ordinary text because it's so short. <paragraph> == ABC <paragraph> Overline too short, no underline. """], ["""\ == ABC """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Possible incomplete section title. Treating the overline as ordinary text because it's so short. <paragraph> == ABC """], ["""\ == Not a title: a definition list item. """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Possible incomplete section title. Treating the overline as ordinary text because it's so short. <definition_list> <definition_list_item> <term> == <definition> <paragraph> Not a title: a definition list item. """], ["""\ == Not a title: a definition list item. -- Another definition list item. It's in a different list, but that's an acceptable limitation given that this will probably never happen in real life. The next line will trigger a warning: == """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Possible incomplete section title. Treating the overline as ordinary text because it's so short. <definition_list> <definition_list_item> <term> == <definition> <paragraph> Not a title: a definition list item. <system_message level="2" line="3" source="test data" type="WARNING"> <paragraph> Definition list ends without a blank line; unexpected unindent. <system_message level="1" line="3" source="test data" type="INFO"> <paragraph> Possible incomplete section title. Treating the overline as ordinary text because it's so short. <definition_list> <definition_list_item> <term> -- <definition> <paragraph> Another definition list item. It's in a different list, but that's an acceptable limitation given that this will probably never happen in real life. <paragraph> The next line will trigger a warning: <system_message level="2" line="9" source="test data" type="WARNING"> <paragraph> Definition list ends without a blank line; unexpected unindent. <paragraph> == """], ["""\ Paragraph == ABC == Over & underline too short. """, """\ <document source="test data"> <paragraph> Paragraph <block_quote> <system_message level="1" line="3" source="test data" type="INFO"> <paragraph> Unexpected possible title overline or transition. Treating it as ordinary text because it's so short. <paragraph> == ABC == <paragraph> Over & underline too short. """], ["""\ Paragraph ABC == Underline too short. """, """\ <document source="test data"> <paragraph> Paragraph <block_quote> <paragraph> ABC == <paragraph> Underline too short. """], ["""\ ... ... ... --- ... ... ... """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Possible incomplete section title. Treating the overline as ordinary text because it's so short. <section dupnames="..." ids="id1"> <title> ... <system_message level="1" line="4" source="test data" type="INFO"> <paragraph> Possible incomplete section title. Treating the overline as ordinary text because it's so short. <section dupnames="..." ids="id2"> <title> ... <system_message backrefs="id2" level="1" line="5" source="test data" type="INFO"> <paragraph> Duplicate implicit target name: "...". <system_message level="1" line="7" source="test data" type="INFO"> <paragraph> Possible incomplete section title. Treating the overline as ordinary text because it's so short. <system_message level="1" line="7" source="test data" type="INFO"> <paragraph> Possible incomplete section title. Treating the overline as ordinary text because it's so short. <section dupnames="..." ids="id3"> <title> ... <system_message backrefs="id3" level="1" line="8" source="test data" type="INFO"> <paragraph> Duplicate implicit target name: "...". <paragraph> ... """], ["""\ .. Hi .. ... Yo ... Ho """, """\ <document source="test data"> <comment xml:space="preserve"> <system_message level="2" line="2" source="test data" type="WARNING"> <paragraph> Explicit markup ends without a blank line; unexpected unindent. <section ids="hi" names="hi"> <title> Hi <section ids="yo" names="yo"> <title> Yo <paragraph> Ho """], ["""\ Empty Section ============= """, """\ <document source="test data"> <section ids="empty-section" names="empty\ section"> <title> Empty Section """], ["""\ === One === The bubble-up parser strategy conflicts with short titles (<= 3 char-long over- & underlines). === Two === The parser currently contains a work-around kludge. Without it, the parser ends up in an infinite loop. """, """\ <document source="test data"> <section ids="one" names="one"> <title> One <paragraph> The bubble-up parser strategy conflicts with short titles (<= 3 char-long over- & underlines). <section ids="two" names="two"> <title> Two <paragraph> The parser currently contains a work-around kludge. Without it, the parser ends up in an infinite loop. """], ["""\ """, """\ <document source="test data"> """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_citations.py������������������������������������������0000775�0001750�0001750�00000010207�10755254773�026220� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_citations.py 5510 2008-02-15 09:23:07Z grubert $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['citations'] = [ ["""\ .. [citation] This is a citation. """, """\ <document source="test data"> <citation ids="citation" names="citation"> <label> citation <paragraph> This is a citation. """], ["""\ .. [citation1234] This is a citation with year. """, """\ <document source="test data"> <citation ids="citation1234" names="citation1234"> <label> citation1234 <paragraph> This is a citation with year. """], ["""\ .. [citation] This is a citation on multiple lines. """, """\ <document source="test data"> <citation ids="citation" names="citation"> <label> citation <paragraph> This is a citation on multiple lines. """], ["""\ .. [citation1] This is a citation on multiple lines with more space. .. [citation2] This is a citation on multiple lines with less space. """, """\ <document source="test data"> <citation ids="citation1" names="citation1"> <label> citation1 <paragraph> This is a citation on multiple lines with more space. <citation ids="citation2" names="citation2"> <label> citation2 <paragraph> This is a citation on multiple lines with less space. """], ["""\ .. [citation] This is a citation on multiple lines whose block starts on line 2. """, """\ <document source="test data"> <citation ids="citation" names="citation"> <label> citation <paragraph> This is a citation on multiple lines whose block starts on line 2. """], ["""\ .. [citation] That was an empty citation. """, """\ <document source="test data"> <citation ids="citation" names="citation"> <label> citation <paragraph> That was an empty citation. """], ["""\ .. [citation] No blank line. """, """\ <document source="test data"> <citation ids="citation" names="citation"> <label> citation <system_message level="2" line="2" source="test data" type="WARNING"> <paragraph> Explicit markup ends without a blank line; unexpected unindent. <paragraph> No blank line. """], ["""\ .. [citation label with spaces] this isn't a citation .. [*citationlabelwithmarkup*] this isn't a citation """, """\ <document source="test data"> <comment xml:space="preserve"> [citation label with spaces] this isn't a citation <comment xml:space="preserve"> [*citationlabelwithmarkup*] this isn't a citation """], [""" isolated internals : ``.-_``. .. [citation.withdot] one dot .. [citation-withdot] one hyphen .. [citation_withunderscore] one underscore .. [citation:with:colons] two colons .. [citation+withplus] one plus """, """<document source="test data"> <paragraph> isolated internals : \n\ <literal> .-_ . <citation ids="citation-withdot" names="citation.withdot"> <label> citation.withdot <paragraph> one dot <citation ids="id1" names="citation-withdot"> <label> citation-withdot <paragraph> one hyphen <citation ids="citation-withunderscore" names="citation_withunderscore"> <label> citation_withunderscore <paragraph> one underscore <citation ids="citation-with-colons" names="citation:with:colons"> <label> citation:with:colons <paragraph> two colons <citation ids="citation-withplus" names="citation+withplus"> <label> citation+withplus <paragraph> one plus """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_interpreted_fr.py�������������������������������������0000664�0001750�0001750�00000002444�11555377264�027240� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_interpreted.py 6424 2010-09-18 10:43:52Z smerten $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for interpreted text in docutils/parsers/rst/states.py. Test not default/fallback language french. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite(suite_settings={'language_code':'fr'}) s.generateTests(totest) return s totest = {} totest['basics'] = [ ["""\ Simple explicit roles and english fallbacks: :acronym:`acronym`, :exp:`superscript`, :ind:`subscript`, :titre:`title reference`. """, """\ <document source="test data"> <paragraph> Simple explicit roles and english fallbacks: <acronym> acronym , <superscript> superscript , <subscript> subscript , <title_reference> title reference . <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> No role entry for "acronym" in module "docutils.parsers.rst.languages.fr". Using English fallback for role "acronym". """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_substitutions.py��������������������������������������0000775�0001750�0001750�00000021263�10434150472�027147� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_substitutions.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['substitution_definitions'] = [ ["""\ Here's an image substitution definition: .. |symbol| image:: symbol.png """, """\ <document source="test data"> <paragraph> Here's an image substitution definition: <substitution_definition names="symbol"> <image alt="symbol" uri="symbol.png"> """], ["""\ Embedded directive starts on the next line: .. |symbol| image:: symbol.png """, """\ <document source="test data"> <paragraph> Embedded directive starts on the next line: <substitution_definition names="symbol"> <image alt="symbol" uri="symbol.png"> """], ["""\ Trailing spaces should not be significant: .. |symbol| image:: \n\ symbol.png """, """\ <document source="test data"> <paragraph> Trailing spaces should not be significant: <substitution_definition names="symbol"> <image alt="symbol" uri="symbol.png"> """], ["""\ Here's a series of substitution definitions: .. |symbol 1| image:: symbol1.png .. |SYMBOL 2| image:: symbol2.png :height: 50 :width: 100 .. |symbol 3| image:: symbol3.png """, """\ <document source="test data"> <paragraph> Here's a series of substitution definitions: <substitution_definition names="symbol\ 1"> <image alt="symbol 1" uri="symbol1.png"> <substitution_definition names="SYMBOL\ 2"> <image alt="SYMBOL 2" height="50" uri="symbol2.png" width="100"> <substitution_definition names="symbol\ 3"> <image alt="symbol 3" uri="symbol3.png"> """], ["""\ .. |very long substitution text, split across lines| image:: symbol.png """, """\ <document source="test data"> <substitution_definition names="very\ long\ substitution\ text,\ split\ across\ lines"> <image alt="very long substitution text, split across lines" uri="symbol.png"> """], ["""\ .. |symbol 1| image:: symbol.png Followed by a block quote. """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: no content permitted. <literal_block xml:space="preserve"> image:: symbol.png \n\ Followed by a block quote. <system_message level="2" line="1" source="test data" type="WARNING"> <paragraph> Substitution definition "symbol 1" empty or invalid. <literal_block xml:space="preserve"> .. |symbol 1| image:: symbol.png \n\ Followed by a block quote. """], ["""\ .. |symbol 1| image:: symbol.png Followed by a paragraph. .. |symbol 2| image:: symbol.png .. Followed by a block quote. """, """\ <document source="test data"> <substitution_definition names="symbol\ 1"> <image alt="symbol 1" uri="symbol.png"> <paragraph> Followed by a paragraph. <substitution_definition names="symbol\ 2"> <image alt="symbol 2" uri="symbol.png"> <comment xml:space="preserve"> <block_quote> <paragraph> Followed by a block quote. """], [u"""\ Substitutions support case differences: .. |eacute| replace:: \u00E9 .. |Eacute| replace:: \u00C9 """, u"""\ <document source="test data"> <paragraph> Substitutions support case differences: <substitution_definition names="eacute"> \u00E9 <substitution_definition names="Eacute"> \u00C9 """], ["""\ Raw substitution, backslashes should be preserved: .. |alpha| raw:: latex $\\\\alpha$ """, """\ <document source="test data"> <paragraph> Raw substitution, backslashes should be preserved: <substitution_definition names="alpha"> <raw format="latex" xml:space="preserve"> $\\\\alpha$ """], ["""\ Here are some duplicate substitution definitions: .. |symbol| image:: symbol.png .. |symbol| image:: symbol.png """, """\ <document source="test data"> <paragraph> Here are some duplicate substitution definitions: <substitution_definition dupnames="symbol"> <image alt="symbol" uri="symbol.png"> <system_message level="3" line="4" source="test data" type="ERROR"> <paragraph> Duplicate substitution definition name: "symbol". <substitution_definition names="symbol"> <image alt="symbol" uri="symbol.png"> """], ["""\ Here are some bad cases: .. |symbol| image:: symbol.png No blank line after. .. |empty| .. |unknown| directive:: symbol.png .. |invalid 1| there's no directive here .. |invalid 2| there's no directive here With some block quote text, line 1. And some more, line 2. .. |invalid 3| there's no directive here .. | bad name | bad data .. | """, """\ <document source="test data"> <paragraph> Here are some bad cases: <substitution_definition names="symbol"> <image alt="symbol" uri="symbol.png"> <system_message level="2" line="4" source="test data" type="WARNING"> <paragraph> Explicit markup ends without a blank line; unexpected unindent. <paragraph> No blank line after. <system_message level="2" line="6" source="test data" type="WARNING"> <paragraph> Substitution definition "empty" missing contents. <literal_block xml:space="preserve"> .. |empty| <system_message level="1" line="8" source="test data" type="INFO"> <paragraph> No directive entry for "directive" in module "docutils.parsers.rst.languages.en". Trying "directive" as canonical directive name. <system_message level="3" line="8" source="test data" type="ERROR"> <paragraph> Unknown directive type "directive". <literal_block xml:space="preserve"> directive:: symbol.png <system_message level="2" line="8" source="test data" type="WARNING"> <paragraph> Substitution definition "unknown" empty or invalid. <literal_block xml:space="preserve"> .. |unknown| directive:: symbol.png <system_message level="2" line="10" source="test data" type="WARNING"> <paragraph> Substitution definition "invalid 1" empty or invalid. <literal_block xml:space="preserve"> .. |invalid 1| there's no directive here <system_message level="2" line="11" source="test data" type="WARNING"> <paragraph> Substitution definition "invalid 2" empty or invalid. <literal_block xml:space="preserve"> .. |invalid 2| there's no directive here With some block quote text, line 1. And some more, line 2. <system_message level="2" line="15" source="test data" type="WARNING"> <paragraph> Substitution definition "invalid 3" empty or invalid. <literal_block xml:space="preserve"> .. |invalid 3| there's no directive here <comment xml:space="preserve"> | bad name | bad data <comment xml:space="preserve"> | """], ["""\ Elements that are prohibited inside of substitution definitions: .. |target| replace:: _`target` .. |reference| replace:: anonymous__ .. |auto-numbered footnote| replace:: [#]_ """, """\ <document source="test data"> <paragraph> Elements that are prohibited inside of substitution definitions: <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> Substitution definition contains illegal element: <literal_block xml:space="preserve"> <target ids="target" names="target"> target <literal_block xml:space="preserve"> .. |target| replace:: _`target` <system_message level="3" line="4" source="test data" type="ERROR"> <paragraph> Substitution definition contains illegal element: <literal_block xml:space="preserve"> <reference anonymous="1" name="anonymous"> anonymous <literal_block xml:space="preserve"> .. |reference| replace:: anonymous__ <system_message level="3" line="5" source="test data" type="ERROR"> <paragraph> Substitution definition contains illegal element: <literal_block xml:space="preserve"> <footnote_reference auto="1" ids="id1"> <literal_block xml:space="preserve"> .. |auto-numbered footnote| replace:: [#]_ """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_east_asian_text.py������������������������������������0000775�0001750�0001750�00000022232�11703370411�027355� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # -*- coding: utf-8 -*- # $Id: test_east_asian_text.py 7313 2012-01-11 20:28:57Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for East Asian text with double-width characters. """ from __init__ import DocutilsTestSupport import unicodedata try: east_asian_width = unicodedata.east_asian_width except AttributeError: east_asian_width = None from docutils._compat import b def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} if not east_asian_width: print ('test_east_asian_text.py tests skipped; ' 'Python 2.4 or higher required.') else: totest['double-width'] = [ [u"""\ タイトル1 ========= タイトル2 ======== """, u"""\ <document source="test data"> <section ids="id1" names="タイトル1"> <title> タイトル1 <section ids="id2" names="タイトル2"> <title> タイトル2 <system_message level="2" line="5" source="test data" type="WARNING"> <paragraph> Title underline too short. <literal_block xml:space="preserve"> タイトル2 ======== """], [ur""" +-----------------------+ | * ヒョウ:ダイ1ギョウ | | * ダイ2ギョウ | +-----------------------+ | \* ダイ1ギョウ | | * ダイ2ギョウ | +-----------------------+ """, u"""\ <document source="test data"> <table> <tgroup cols="1"> <colspec colwidth="23"> <tbody> <row> <entry> <bullet_list bullet="*"> <list_item> <paragraph> ヒョウ:ダイ1ギョウ <list_item> <paragraph> ダイ2ギョウ <row> <entry> <paragraph> * ダイ1ギョウ * ダイ2ギョウ """], [u"""\ Complex spanning pattern (no edge knows all rows/cols): +--------+---------------------+ | 北西・ | 北・北東セル | | 西セル +--------------+------+ | | 真ん中のセル | 東・ | +--------+--------------+ 南東 | | 南西・南セル | セル | +-----------------------+------+ """, u"""\ <document source="test data"> <paragraph> Complex spanning pattern (no edge knows all rows/cols): <table> <tgroup cols="3"> <colspec colwidth="8"> <colspec colwidth="14"> <colspec colwidth="6"> <tbody> <row> <entry morerows="1"> <paragraph> 北西・ 西セル <entry morecols="1"> <paragraph> 北・北東セル <row> <entry> <paragraph> 真ん中のセル <entry morerows="1"> <paragraph> 東・ 南東 セル <row> <entry morecols="1"> <paragraph> 南西・南セル """], [u"""\ ========= ========= ダイ1ラン ダイ2ラン ========= ========= ======== ========= ダイ1ラン ダイ2ラン ======== ========= """, u"""\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="9"> <colspec colwidth="9"> <tbody> <row> <entry> <paragraph> ダイ1ラン <entry> <paragraph> ダイ2ラン <system_message level="3" line="6" source="test data" type="ERROR"> <paragraph> Malformed table. Text in column margin in table line 2. <literal_block xml:space="preserve"> ======== ========= ダイ1ラン ダイ2ラン ======== ========= """], [u"""\ Some ambiguous-width characters: = =================================== © copyright sign ® registered sign « left pointing guillemet » right pointing guillemet – en-dash — em-dash ‘ single turned comma quotation mark ’ single comma quotation mark ‚ low single comma quotation mark “ double turned comma quotation mark ” double comma quotation mark „ low double comma quotation mark † dagger ‡ double dagger … ellipsis ™ trade mark sign ⇔ left-right double arrow = =================================== """, b("""\ <document source="test data"> <paragraph> Some ambiguous-width characters: <table> <tgroup cols="2"> <colspec colwidth="1"> <colspec colwidth="35"> <tbody> <row> <entry> <paragraph> \xa9 <entry> <paragraph> copyright sign <row> <entry> <paragraph> \xae <entry> <paragraph> registered sign <row> <entry> <paragraph> \xab <entry> <paragraph> left pointing guillemet <row> <entry> <paragraph> \xbb <entry> <paragraph> right pointing guillemet <row> <entry> <paragraph> \\u2013 <entry> <paragraph> en-dash <row> <entry> <paragraph> \\u2014 <entry> <paragraph> em-dash <row> <entry> <paragraph> \\u2018 <entry> <paragraph> single turned comma quotation mark <row> <entry> <paragraph> \\u2019 <entry> <paragraph> single comma quotation mark <row> <entry> <paragraph> \\u201a <entry> <paragraph> low single comma quotation mark <row> <entry> <paragraph> \\u201c <entry> <paragraph> double turned comma quotation mark <row> <entry> <paragraph> \\u201d <entry> <paragraph> double comma quotation mark <row> <entry> <paragraph> \\u201e <entry> <paragraph> low double comma quotation mark <row> <entry> <paragraph> \\u2020 <entry> <paragraph> dagger <row> <entry> <paragraph> \\u2021 <entry> <paragraph> double dagger <row> <entry> <paragraph> \\u2026 <entry> <paragraph> ellipsis <row> <entry> <paragraph> \\u2122 <entry> <paragraph> trade mark sign <row> <entry> <paragraph> \\u21d4 <entry> <paragraph> left-right double arrow """).decode('raw_unicode_escape')], ] ''' [u"""\ """, u"""\ """], ''' if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_SimpleTableParser.py����������������������������������0000775�0001750�0001750�00000006436�11703370411�027570� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # .. coding: utf-8 # $Id: test_SimpleTableParser.py 7313 2012-01-11 20:28:57Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.SimpleTableParserTestSuite() s.generateTests(totest) return s totest = {} totest['simple_tables'] = [ ["""\ ============ ============ A table with two columns. ============ ============ """, ([12, 12], [], [[[0, 0, 1, ['A table with']], [0, 0, 1, ['two columns.']]]])], [u"""\ ============ =============== A tāble w̅ith comb̲ining chars ============ =============== """, ([12, 15], [], [[[0, 0, 1, [u'A ta\u0304ble w\u0305ith']], [0, 0, 1, [u'comb\u0332ining chars']]]])], ["""\ ============ ============ A table with two columns and two rows. ============ ============ """, ([12, 12], [], [[[0, 0, 1, ['A table with']], [0, 0, 1, ['two columns']]], [[0, 0, 2, ['and']], [0, 0, 2, ['two rows.']]]])], ["""\ ====================================== The last row might stick into the margin second row. ====================================== """, ([40], [], [[[0, 0, 1, ['The last row might stick into the margin']]], [[0, 0, 2, ['second row.']]]])], ["""\ ========== =========== A table with four rows, ----------------------- and two columns. First and last rows contain column spans. ======================= """, ([10, 11], [], [[[0, 1, 1, ['A table with four rows,']]], [[0, 0, 3, ['and two']], [0, 0, 3, ['columns.']]], [[0, 0, 4, ['First and']], [0, 0, 4, ['last rows']]], [[0, 1, 5, ['contain column spans.']]]])], ["""\ ======= ===== ====== A bad table cell 2 cell 3 cell 4 ============ ====== """, 'TableMarkupError: Text in column margin in table line 2.'], ["""\ ====== ===== ====== row one Another bad table ====== ===== ====== """, 'TableMarkupError: Text in column margin in table line 3.'], ["""\ =========== ================ A table with two header rows, ----------------------------- the first with a span. =========== ================ Two body rows, the second with a span. ============================= """, ([11, 16], [[[0, 1, 1, ['A table with two header rows,']]], [[0, 0, 3, ['the first']], [0, 0, 3, ['with a span.']]]], [[[0, 0, 5, ['Two body']], [0, 0, 5, ['rows,']]], [[0, 1, 6, ['the second with a span.']]]])], ["""\ ============ ============= A table with two head/body ============ ============= row separators. ============ ============= That's bad. ============ ============= """, 'TableMarkupError: Multiple head/body row separators ' '(table lines 3 and 5); only one allowed.'], ["""\ ============ ============ ============ ============ """, ([12, 12], [], [[[0, 0, 1, []], [0, 0, 1, []]]])], # ["""\ # ============== ========== # Table with row separators # ============== ========== # and blank # -------------- ---------- # entries # -------------- ---------- # in first # -------------- ---------- # columns. # ============== ========== # """, # ''] ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_inline_markup.py��������������������������������������0000775�0001750�0001750�00000126250�12153360646�027055� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # -*- coding: utf-8 -*- # $Id: test_inline_markup.py 7668 2013-06-04 12:46:30Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for inline markup in docutils/parsers/rst/states.py. Interpreted text tests are in a separate module, test_interpreted.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['emphasis'] = [ ["""\ *emphasis* """, """\ <document source="test data"> <paragraph> <emphasis> emphasis """], [u"""\ l'*emphasis* with the *emphasis*' apostrophe. l\u2019*emphasis* with the *emphasis*\u2019 apostrophe. """, u"""\ <document source="test data"> <paragraph> l\' <emphasis> emphasis with the \n\ <emphasis> emphasis \' apostrophe. l\u2019 <emphasis> emphasis with the \n\ <emphasis> emphasis \u2019 apostrophe. """], ["""\ *emphasized sentence across lines* """, """\ <document source="test data"> <paragraph> <emphasis> emphasized sentence across lines """], ["""\ *emphasis without closing asterisk """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> * emphasis without closing asterisk <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline emphasis start-string without end-string. """], [r"""some punctuation is allowed around inline markup, e.g. /*emphasis*/, -*emphasis*-, and :*emphasis*: (delimiters), (*emphasis*), [*emphasis*], <*emphasis*>, {*emphasis*} (open/close pairs) *emphasis*., *emphasis*,, *emphasis*!, and *emphasis*\ (closing delimiters), but not )*emphasis*(, ]*emphasis*[, >*emphasis*>, }*emphasis*{ (close/open pairs), (*), [*], '*' or '"*"' ("quoted" start-string), x*2* or 2*x* (alphanumeric char before), \*args or * (escaped, whitespace behind start-string), or *the\* *stars\* *inside* (escaped, whitespace before end-string). However, '*args' will trigger a warning and may be problematic. what about *this**? """, """\ <document source="test data"> <paragraph> some punctuation is allowed around inline markup, e.g. / <emphasis> emphasis /, - <emphasis> emphasis -, and : <emphasis> emphasis : (delimiters), ( <emphasis> emphasis ), [ <emphasis> emphasis ], < <emphasis> emphasis >, { <emphasis> emphasis } (open/close pairs) <emphasis> emphasis ., \n\ <emphasis> emphasis ,, \n\ <emphasis> emphasis !, and \n\ <emphasis> emphasis (closing delimiters), <paragraph> but not )*emphasis*(, ]*emphasis*[, >*emphasis*>, }*emphasis*{ (close/open pairs), (*), [*], '*' or '"*"' ("quoted" start-string), x*2* or 2*x* (alphanumeric char before), *args or * (escaped, whitespace behind start-string), or \n\ <emphasis> the* *stars* *inside (escaped, whitespace before end-string). <paragraph> However, ' <problematic ids="id2" refid="id1"> * args' will trigger a warning and may be problematic. <system_message backrefs="id2" ids="id1" level="2" line="13" source="test data" type="WARNING"> <paragraph> Inline emphasis start-string without end-string. <paragraph> what about \n\ <emphasis> this* ? """], [u"""\ Quotes around inline markup: '*emphasis*' "*emphasis*" Straight, ‘*emphasis*’ “*emphasis*” English, ..., « *emphasis* » ‹ *emphasis* › « *emphasis* » ‹ *emphasis* › « *emphasis* » ‹ *emphasis* › French, „*emphasis*“ ‚*emphasis*‘ »*emphasis*« ›*emphasis*‹ German, Czech, ..., „*emphasis*” «*emphasis*» Romanian, “*emphasis*„ ‘*emphasis*‚ Greek, 「*emphasis*」 『*emphasis*』traditional Chinese, ”*emphasis*” ’*emphasis*’ »*emphasis*» ›*emphasis*› Swedish, Finnish, „*emphasis*” ‚*emphasis*’ Polish, „*emphasis*” »*emphasis*« ’*emphasis*’ Hungarian, """, u"""\ <document source="test data"> <paragraph> Quotes around inline markup: <paragraph> \' <emphasis> emphasis \' " <emphasis> emphasis " Straight, \u2018 <emphasis> emphasis \u2019 \u201c <emphasis> emphasis \u201d English, ..., \xab\u202f <emphasis> emphasis \u202f\xbb \u2039\u202f <emphasis> emphasis \u202f\u203a \xab\xa0 <emphasis> emphasis \xa0\xbb \u2039\xa0 <emphasis> emphasis \xa0\u203a \xab\u2005 <emphasis> emphasis \u2005\xbb \u2039\u2005 <emphasis> emphasis \u2005\u203a French, \u201e <emphasis> emphasis \u201c \u201a <emphasis> emphasis \u2018 \xbb <emphasis> emphasis \xab \u203a <emphasis> emphasis \u2039 German, Czech, ..., \u201e <emphasis> emphasis \u201d \xab <emphasis> emphasis \xbb Romanian, \u201c <emphasis> emphasis \u201e \u2018 <emphasis> emphasis \u201a Greek, \u300c <emphasis> emphasis \u300d \u300e <emphasis> emphasis \u300ftraditional Chinese, \u201d <emphasis> emphasis \u201d \u2019 <emphasis> emphasis \u2019 \xbb <emphasis> emphasis \xbb \u203a <emphasis> emphasis \u203a Swedish, Finnish, \u201e <emphasis> emphasis \u201d \u201a <emphasis> emphasis \u2019 Polish, \u201e <emphasis> emphasis \u201d \xbb <emphasis> emphasis \xab \u2019 <emphasis> emphasis \u2019 Hungarian, """], [r""" Emphasized asterisk: *\** Emphasized double asterisk: *\*** """, """\ <document source="test data"> <paragraph> Emphasized asterisk: \n\ <emphasis> * <paragraph> Emphasized double asterisk: \n\ <emphasis> ** """], ] totest['strong'] = [ ["""\ **strong** """, """\ <document source="test data"> <paragraph> <strong> strong """], [u"""\ l'**strong** and l\u2019**strong** with apostrophe """, u"""\ <document source="test data"> <paragraph> l' <strong> strong and l\u2019 <strong> strong with apostrophe """], [u"""\ quoted '**strong**', quoted "**strong**", quoted \u2018**strong**\u2019, quoted \u201c**strong**\u201d, quoted \xab**strong**\xbb """, u"""\ <document source="test data"> <paragraph> quoted ' <strong> strong ', quoted " <strong> strong ", quoted \u2018 <strong> strong \u2019, quoted \u201c <strong> strong \u201d, quoted \xab <strong> strong \xbb """], [r""" (**strong**) but not (**) or '(** ' or x**2 or \**kwargs or ** (however, '**kwargs' will trigger a warning and may be problematic) """, """\ <document source="test data"> <paragraph> ( <strong> strong ) but not (**) or '(** ' or x**2 or **kwargs or ** <paragraph> (however, ' <problematic ids="id2" refid="id1"> ** kwargs' will trigger a warning and may be problematic) <system_message backrefs="id2" ids="id1" level="2" line="4" source="test data" type="WARNING"> <paragraph> Inline strong start-string without end-string. """], ["""\ Strong asterisk: ***** Strong double asterisk: ****** """, """\ <document source="test data"> <paragraph> Strong asterisk: \n\ <strong> * <paragraph> Strong double asterisk: \n\ <strong> ** """], ["""\ **strong without closing asterisks """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> ** strong without closing asterisks <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline strong start-string without end-string. """], ] totest['literal'] = [ ["""\ ``literal`` """, """\ <document source="test data"> <paragraph> <literal> literal """], [r""" ``\literal`` """, """\ <document source="test data"> <paragraph> <literal> \\literal """], [r""" ``lite\ral`` """, """\ <document source="test data"> <paragraph> <literal> lite\\ral """], [r""" ``literal\`` """, """\ <document source="test data"> <paragraph> <literal> literal\\ """], [u"""\ l'``literal`` and l\u2019``literal`` with apostrophe """, u"""\ <document source="test data"> <paragraph> l' <literal> literal and l\u2019 <literal> literal with apostrophe """], [u"""\ quoted '``literal``', quoted "``literal``", quoted \u2018``literal``\u2019, quoted \u201c``literal``\u201d, quoted \xab``literal``\xbb """, u"""\ <document source="test data"> <paragraph> quoted ' <literal> literal ', quoted " <literal> literal ", quoted \u2018 <literal> literal \u2019, quoted \u201c <literal> literal \u201d, quoted \xab <literal> literal \xbb """], [u"""\ ``'literal'`` with quotes, ``"literal"`` with quotes, ``\u2018literal\u2019`` with quotes, ``\u201cliteral\u201d`` with quotes, ``\xabliteral\xbb`` with quotes """, u"""\ <document source="test data"> <paragraph> <literal> 'literal' with quotes, \n\ <literal> "literal" with quotes, <literal> \u2018literal\u2019 with quotes, \n\ <literal> \u201cliteral\u201d with quotes, <literal> \xabliteral\xbb with quotes """], [r""" ``literal ``TeX quotes'' & \backslash`` but not "``" or `` (however, ``standalone TeX quotes'' will trigger a warning and may be problematic) """, """\ <document source="test data"> <paragraph> <literal> literal ``TeX quotes'' & \\backslash but not "``" or `` <paragraph> (however, \n\ <problematic ids="id2" refid="id1"> `` standalone TeX quotes'' will trigger a warning and may be problematic) <system_message backrefs="id2" ids="id1" level="2" line="4" source="test data" type="WARNING"> <paragraph> Inline literal start-string without end-string. """], ["""\ Find the ```interpreted text``` in this paragraph! """, """\ <document source="test data"> <paragraph> Find the \n\ <literal> `interpreted text` in this paragraph! """], ["""\ ``literal without closing backquotes """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> `` literal without closing backquotes <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline literal start-string without end-string. """], [r""" Python ``list``\s use square bracket syntax. """, """\ <document source="test data"> <paragraph> Python \n\ <literal> list s use square bracket syntax. """], ] totest['references'] = [ ["""\ ref_ """, """\ <document source="test data"> <paragraph> <reference name="ref" refname="ref"> ref """], [u"""\ l'ref_ and l\u2019ref_ with apostrophe """, u"""\ <document source="test data"> <paragraph> l' <reference name="ref" refname="ref"> ref and l\u2019 <reference name="ref" refname="ref"> ref with apostrophe """], [u"""\ quoted 'ref_', quoted "ref_", quoted \u2018ref_\u2019, quoted \u201cref_\u201d, quoted \xabref_\xbb, but not 'ref ref'_, "ref ref"_, \u2018ref ref\u2019_, \u201cref ref\u201d_, or \xabref ref\xbb_ """, u"""\ <document source="test data"> <paragraph> quoted ' <reference name="ref" refname="ref"> ref ', quoted " <reference name="ref" refname="ref"> ref ", quoted \u2018 <reference name="ref" refname="ref"> ref \u2019, quoted \u201c <reference name="ref" refname="ref"> ref \u201d, quoted \xab <reference name="ref" refname="ref"> ref \xbb, but not 'ref ref'_, "ref ref"_, \u2018ref ref\u2019_, \u201cref ref\u201d_, or \xabref ref\xbb_ """], ["""\ ref__ """, """\ <document source="test data"> <paragraph> <reference anonymous="1" name="ref"> ref """], [u"""\ l'ref__ and l\u2019ref__ with apostrophe """, u"""\ <document source="test data"> <paragraph> l' <reference anonymous="1" name="ref"> ref and l\u2019 <reference anonymous="1" name="ref"> ref with apostrophe """], [u"""\ quoted 'ref__', quoted "ref__", quoted \u2018ref__\u2019, quoted \u201cref__\u201d, quoted \xabref__\xbb, but not 'ref ref'__, "ref ref"__, \u2018ref ref\u2019__, \u201cref ref\u201d__, or \xabref ref\xbb__ """, u"""\ <document source="test data"> <paragraph> quoted ' <reference anonymous="1" name="ref"> ref ', quoted " <reference anonymous="1" name="ref"> ref ", quoted \u2018 <reference anonymous="1" name="ref"> ref \u2019, quoted \u201c <reference anonymous="1" name="ref"> ref \u201d, quoted \xab <reference anonymous="1" name="ref"> ref \xbb, but not 'ref ref'__, "ref ref"__, \u2018ref ref\u2019__, \u201cref ref\u201d__, or \xabref ref\xbb__ """], ["""\ ref_, r_, r_e-f_, -ref_, and anonymousref__, but not _ref_ or __attr__ or object.__attr__ """, """\ <document source="test data"> <paragraph> <reference name="ref" refname="ref"> ref , \n\ <reference name="r" refname="r"> r , \n\ <reference name="r_e-f" refname="r_e-f"> r_e-f , - <reference name="ref" refname="ref"> ref , and \n\ <reference anonymous="1" name="anonymousref"> anonymousref , but not _ref_ or __attr__ or object.__attr__ """], ] totest['phrase_references'] = [ ["""\ `phrase reference`_ """, """\ <document source="test data"> <paragraph> <reference name="phrase reference" refname="phrase reference"> phrase reference """], [u"""\ l'`phrase reference`_ and l\u2019`phrase reference`_ with apostrophe """, u"""\ <document source="test data"> <paragraph> l' <reference name="phrase reference" refname="phrase reference"> phrase reference and l\u2019 <reference name="phrase reference" refname="phrase reference"> phrase reference with apostrophe """], [u"""\ quoted '`phrase reference`_', quoted "`phrase reference`_", quoted \u2018`phrase reference`_\u2019, quoted \u201c`phrase reference`_\u201d, quoted \xab`phrase reference`_\xbb """, u"""\ <document source="test data"> <paragraph> quoted ' <reference name="phrase reference" refname="phrase reference"> phrase reference ', quoted " <reference name="phrase reference" refname="phrase reference"> phrase reference ", quoted \u2018 <reference name="phrase reference" refname="phrase reference"> phrase reference \u2019, quoted \u201c <reference name="phrase reference" refname="phrase reference"> phrase reference \u201d, quoted \xab <reference name="phrase reference" refname="phrase reference"> phrase reference \xbb """], [u"""\ `'phrase reference'`_ with quotes, `"phrase reference"`_ with quotes, `\u2018phrase reference\u2019`_ with quotes, `\u201cphrase reference\u201d`_ with quotes, `\xabphrase reference\xbb`_ with quotes """, u"""\ <document source="test data"> <paragraph> <reference name="'phrase reference'" refname="'phrase reference'"> 'phrase reference' with quotes, \n\ <reference name=""phrase reference"" refname=""phrase reference""> "phrase reference" with quotes, <reference name="\u2018phrase reference\u2019" refname="\u2018phrase reference\u2019"> \u2018phrase reference\u2019 with quotes, <reference name="\u201cphrase reference\u201d" refname="\u201cphrase reference\u201d"> \u201cphrase reference\u201d with quotes, <reference name="\xabphrase reference\xbb" refname="\xabphrase reference\xbb"> \xabphrase reference\xbb with quotes """], ["""\ `anonymous reference`__ """, """\ <document source="test data"> <paragraph> <reference anonymous="1" name="anonymous reference"> anonymous reference """], [u"""\ l'`anonymous reference`__ and l\u2019`anonymous reference`__ with apostrophe """, u"""\ <document source="test data"> <paragraph> l' <reference anonymous="1" name="anonymous reference"> anonymous reference and l\u2019 <reference anonymous="1" name="anonymous reference"> anonymous reference with apostrophe """], [u"""\ quoted '`anonymous reference`__', quoted "`anonymous reference`__", quoted \u2018`anonymous reference`__\u2019, quoted \u201c`anonymous reference`__\u201d, quoted \xab`anonymous reference`__\xbb """, u"""\ <document source="test data"> <paragraph> quoted ' <reference anonymous="1" name="anonymous reference"> anonymous reference ', quoted " <reference anonymous="1" name="anonymous reference"> anonymous reference ", quoted \u2018 <reference anonymous="1" name="anonymous reference"> anonymous reference \u2019, quoted \u201c <reference anonymous="1" name="anonymous reference"> anonymous reference \u201d, quoted \xab <reference anonymous="1" name="anonymous reference"> anonymous reference \xbb """], [u"""\ `'anonymous reference'`__ with quotes, `"anonymous reference"`__ with quotes, `\u2018anonymous reference\u2019`__ with quotes, `\u201canonymous reference\u201d`__ with quotes, `\xabanonymous reference\xbb`__ with quotes """, u"""\ <document source="test data"> <paragraph> <reference anonymous="1" name="'anonymous reference'"> 'anonymous reference' with quotes, \n\ <reference anonymous="1" name=""anonymous reference""> "anonymous reference" with quotes, <reference anonymous="1" name="\u2018anonymous reference\u2019"> \u2018anonymous reference\u2019 with quotes, <reference anonymous="1" name="\u201canonymous reference\u201d"> \u201canonymous reference\u201d with quotes, <reference anonymous="1" name="\xabanonymous reference\xbb"> \xabanonymous reference\xbb with quotes """], ["""\ `phrase reference across lines`_ """, """\ <document source="test data"> <paragraph> <reference name="phrase reference across lines" refname="phrase reference across lines"> phrase reference across lines """], ["""\ `phrase\`_ reference`_ """, """\ <document source="test data"> <paragraph> <reference name="phrase`_ reference" refname="phrase`_ reference"> phrase`_ reference """], ["""\ Invalid phrase reference: :role:`phrase reference`_ """, """\ <document source="test data"> <paragraph> Invalid phrase reference: <paragraph> <problematic ids="id2" refid="id1"> :role:`phrase reference`_ <system_message backrefs="id2" ids="id1" level="2" line="3" source="test data" type="WARNING"> <paragraph> Mismatch: both interpreted text role prefix and reference suffix. """], ["""\ Invalid phrase reference: `phrase reference`:role:_ """, """\ <document source="test data"> <paragraph> Invalid phrase reference: <paragraph> <problematic ids="id2" refid="id1"> `phrase reference`:role:_ <system_message backrefs="id2" ids="id1" level="2" line="3" source="test data" type="WARNING"> <paragraph> Mismatch: both interpreted text role suffix and reference suffix. """], ["""\ `phrase reference_ without closing backquote """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> ` phrase \n\ <reference name="reference" refname="reference"> reference without closing backquote <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline interpreted text or phrase reference start-string without end-string. """], ["""\ `anonymous phrase reference__ without closing backquote """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> ` anonymous phrase \n\ <reference anonymous="1" name="reference"> reference without closing backquote <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline interpreted text or phrase reference start-string without end-string. """], ] totest['embedded_URIs'] = [ ["""\ `phrase reference <http://example.com>`_ """, """\ <document source="test data"> <paragraph> <reference name="phrase reference" refuri="http://example.com"> phrase reference <target ids="phrase-reference" names="phrase\ reference" refuri="http://example.com"> """], ["""\ `anonymous reference <http://example.com>`__ """, """\ <document source="test data"> <paragraph> <reference name="anonymous reference" refuri="http://example.com"> anonymous reference """], ["""\ `embedded URI on next line <http://example.com>`__ """, """\ <document source="test data"> <paragraph> <reference name="embedded URI on next line" refuri="http://example.com"> embedded URI on next line """], ["""\ `embedded URI across lines <http://example.com/ long/path>`__ """, """\ <document source="test data"> <paragraph> <reference name="embedded URI across lines" refuri="http://example.com/long/path"> embedded URI across lines """], ["""\ `embedded URI with whitespace <http://example.com/ long/path /and /whitespace>`__ """, """\ <document source="test data"> <paragraph> <reference name="embedded URI with whitespace" refuri="http://example.com/long/path/and/whitespace"> embedded URI with whitespace """], ["""\ `embedded email address <jdoe@example.com>`__ `embedded email address broken across lines <jdoe @example.com>`__ """, """\ <document source="test data"> <paragraph> <reference name="embedded email address" refuri="mailto:jdoe@example.com"> embedded email address <paragraph> <reference name="embedded email address broken across lines" refuri="mailto:jdoe@example.com"> embedded email address broken across lines """], [r""" `embedded URI with too much whitespace < http://example.com/ long/path /and /whitespace >`__ `embedded URI with too much whitespace at end <http://example.com/ long/path /and /whitespace >`__ `embedded URI with no preceding whitespace<http://example.com>`__ `escaped URI \<http://example.com>`__ See `HTML Anchors: \<a>`_. """, """\ <document source="test data"> <paragraph> <reference anonymous="1" name="embedded URI with too much whitespace < http://example.com/ long/path /and /whitespace >"> embedded URI with too much whitespace < http://example.com/ long/path /and /whitespace > <paragraph> <reference anonymous="1" name="embedded URI with too much whitespace at end <http://example.com/ long/path /and /whitespace >"> embedded URI with too much whitespace at end <http://example.com/ long/path /and /whitespace > <paragraph> <reference anonymous="1" name="embedded URI with no preceding whitespace<http://example.com>"> embedded URI with no preceding whitespace<http://example.com> <paragraph> <reference anonymous="1" name="escaped URI <http://example.com>"> escaped URI <http://example.com> <paragraph> See \n\ <reference name="HTML Anchors: <a>" refname="html anchors: <a>"> HTML Anchors: <a> . """], ["""\ Relative URIs' reference text can be omitted: `<reference>`_ `<anonymous>`__ """, """\ <document source="test data"> <paragraph> Relative URIs' reference text can be omitted: <paragraph> <reference name="reference" refuri="reference"> reference <target ids="reference" names="reference" refuri="reference"> <paragraph> <reference name="anonymous" refuri="anonymous"> anonymous """], ["""\ Escape trailing low-line char in URIs: `<reference\_>`_ `<anonymous\_>`__ """, """\ <document source="test data"> <paragraph> Escape trailing low-line char in URIs: <paragraph> <reference name="reference_" refuri="reference_"> reference_ <target ids="reference" names="reference_" refuri="reference_"> <paragraph> <reference name="anonymous_" refuri="anonymous_"> anonymous_ """], ] totest['embedded_aliases'] = [ ["""\ `phrase reference <alias_>`_ """, """\ <document source="test data"> <paragraph> <reference name="phrase reference" refname="alias"> phrase reference <target names="phrase\ reference" refname="alias"> """], ["""\ `anonymous reference <alias_>`__ """, """\ <document source="test data"> <paragraph> <reference name="anonymous reference" refname="alias"> anonymous reference """], ["""\ `embedded alias on next line <alias_>`__ """, """\ <document source="test data"> <paragraph> <reference name="embedded alias on next line" refname="alias"> embedded alias on next line """], ["""\ `embedded alias across lines <alias phrase_>`__ """, """\ <document source="test data"> <paragraph> <reference name="embedded alias across lines" refname="alias phrase"> embedded alias across lines """], ["""\ `embedded alias with whitespace <alias long phrase_>`__ """, """\ <document source="test data"> <paragraph> <reference name="embedded alias with whitespace" refname="alias long phrase"> embedded alias with whitespace """], [r""" `embedded alias with too much whitespace < alias_ >`__ `embedded alias with no preceding whitespace<alias_>`__ """, """\ <document source="test data"> <paragraph> <reference anonymous="1" name="embedded alias with too much whitespace < alias_ >"> embedded alias with too much whitespace < alias_ > <paragraph> <reference anonymous="1" name="embedded alias with no preceding whitespace<alias_>"> embedded alias with no preceding whitespace<alias_> """], ] totest['inline_targets'] = [ ["""\ _`target` Here is _`another target` in some text. And _`yet another target`, spanning lines. _`Here is a TaRgeT` with case and spacial difficulties. """, """\ <document source="test data"> <paragraph> <target ids="target" names="target"> target <paragraph> Here is \n\ <target ids="another-target" names="another\ target"> another target in some text. And \n\ <target ids="yet-another-target" names="yet\ another\ target"> yet another target , spanning lines. <paragraph> <target ids="here-is-a-target" names="here\ is\ a\ target"> Here is a TaRgeT with case and spacial difficulties. """], [u"""\ l'_`target1` and l\u2019_`target2` with apostrophe """, u"""\ <document source="test data"> <paragraph> l' <target ids="target1" names="target1"> target1 and l\u2019 <target ids="target2" names="target2"> target2 with apostrophe """], [u"""\ quoted '_`target1`', quoted "_`target2`", quoted \u2018_`target3`\u2019, quoted \u201c_`target4`\u201d, quoted \xab_`target5`\xbb """, u"""\ <document source="test data"> <paragraph> quoted ' <target ids="target1" names="target1"> target1 ', quoted " <target ids="target2" names="target2"> target2 ", quoted \u2018 <target ids="target3" names="target3"> target3 \u2019, quoted \u201c <target ids="target4" names="target4"> target4 \u201d, quoted \xab <target ids="target5" names="target5"> target5 \xbb """], [u"""\ _`'target1'` with quotes, _`"target2"` with quotes, _`\u2018target3\u2019` with quotes, _`\u201ctarget4\u201d` with quotes, _`\xabtarget5\xbb` with quotes """, u"""\ <document source="test data"> <paragraph> <target ids="target1" names="'target1'"> 'target1' with quotes, \n\ <target ids="target2" names=""target2""> "target2" with quotes, <target ids="target3" names="\u2018target3\u2019"> \u2018target3\u2019 with quotes, \n\ <target ids="target4" names="\u201ctarget4\u201d"> \u201ctarget4\u201d with quotes, <target ids="target5" names="\xabtarget5\xbb"> \xabtarget5\xbb with quotes """], ["""\ But this isn't a _target; targets require backquotes. And _`this`_ is just plain confusing. """, """\ <document source="test data"> <paragraph> But this isn't a _target; targets require backquotes. <paragraph> And \n\ <problematic ids="id2" refid="id1"> _` this`_ is just plain confusing. <system_message backrefs="id2" ids="id1" level="2" line="3" source="test data" type="WARNING"> <paragraph> Inline target start-string without end-string. """], ["""\ _`inline target without closing backquote """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> _` inline target without closing backquote <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline target start-string without end-string. """], ] totest['footnote_reference'] = [ ["""\ [1]_ """, """\ <document source="test data"> <paragraph> <footnote_reference ids="id1" refname="1"> 1 """], ["""\ [#]_ """, """\ <document source="test data"> <paragraph> <footnote_reference auto="1" ids="id1"> """], ["""\ [#label]_ """, """\ <document source="test data"> <paragraph> <footnote_reference auto="1" ids="id1" refname="label"> """], ["""\ [*]_ """, """\ <document source="test data"> <paragraph> <footnote_reference auto="*" ids="id1"> """], ["""\ Adjacent footnote refs are not possible: [*]_[#label]_ [#]_[2]_ [1]_[*]_ """, """\ <document source="test data"> <paragraph> Adjacent footnote refs are not possible: [*]_[#label]_ [#]_[2]_ [1]_[*]_ """], ] totest['citation_reference'] = [ ["""\ [citation]_ """, """\ <document source="test data"> <paragraph> <citation_reference ids="id1" refname="citation"> citation """], ["""\ [citation]_ and [cit-ation]_ and [cit.ation]_ and [CIT1]_ but not [CIT 1]_ """, """\ <document source="test data"> <paragraph> <citation_reference ids="id1" refname="citation"> citation and \n\ <citation_reference ids="id2" refname="cit-ation"> cit-ation and \n\ <citation_reference ids="id3" refname="cit.ation"> cit.ation and \n\ <citation_reference ids="id4" refname="cit1"> CIT1 but not [CIT 1]_ """], ["""\ Adjacent citation refs are not possible: [citation]_[CIT1]_ """, """\ <document source="test data"> <paragraph> Adjacent citation refs are not possible: [citation]_[CIT1]_ """], ] totest['substitution_references'] = [ ["""\ |subref| """, """\ <document source="test data"> <paragraph> <substitution_reference refname="subref"> subref """], ["""\ |subref|_ and |subref|__ """, """\ <document source="test data"> <paragraph> <reference refname="subref"> <substitution_reference refname="subref"> subref and \n\ <reference anonymous="1"> <substitution_reference refname="subref"> subref """], ["""\ |substitution reference| """, """\ <document source="test data"> <paragraph> <substitution_reference refname="substitution reference"> substitution reference """], ["""\ |substitution reference| """, """\ <document source="test data"> <paragraph> <substitution_reference refname="substitution reference"> substitution reference """], ["""\ |substitution reference without closing verbar """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> | substitution reference without closing verbar <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline substitution_reference start-string without end-string. """], ["""\ first | then || and finally ||| """, """\ <document source="test data"> <paragraph> first | then || and finally ||| """], ] totest['standalone_hyperlink'] = [ ["""\ http://www.standalone.hyperlink.com http:/one-slash-only.absolute.path [http://example.com] (http://example.com) <http://example.com> http://[1080:0:0:0:8:800:200C:417A]/IPv6address.html http://[3ffe:2a00:100:7031::1] (the final "]" is ambiguous in text) http://[3ffe:2a00:100:7031::1]/ mailto:someone@somewhere.com news:comp.lang.python An email address in a sentence: someone@somewhere.com. ftp://ends.with.a.period. (a.question.mark@end?) """, """\ <document source="test data"> <paragraph> <reference refuri="http://www.standalone.hyperlink.com"> http://www.standalone.hyperlink.com <paragraph> <reference refuri="http:/one-slash-only.absolute.path"> http:/one-slash-only.absolute.path <paragraph> [ <reference refuri="http://example.com"> http://example.com ] <paragraph> ( <reference refuri="http://example.com"> http://example.com ) <paragraph> < <reference refuri="http://example.com"> http://example.com > <paragraph> <reference refuri="http://[1080:0:0:0:8:800:200C:417A]/IPv6address.html"> http://[1080:0:0:0:8:800:200C:417A]/IPv6address.html <paragraph> <reference refuri="http://[3ffe:2a00:100:7031::1"> http://[3ffe:2a00:100:7031::1 ] (the final "]" is ambiguous in text) <paragraph> <reference refuri="http://[3ffe:2a00:100:7031::1]/"> http://[3ffe:2a00:100:7031::1]/ <paragraph> <reference refuri="mailto:someone@somewhere.com"> mailto:someone@somewhere.com <paragraph> <reference refuri="news:comp.lang.python"> news:comp.lang.python <paragraph> An email address in a sentence: \n\ <reference refuri="mailto:someone@somewhere.com"> someone@somewhere.com . <paragraph> <reference refuri="ftp://ends.with.a.period"> ftp://ends.with.a.period . <paragraph> ( <reference refuri="mailto:a.question.mark@end"> a.question.mark@end ?) """], [r""" Valid URLs with escaped markup characters: http://example.com/\*content\*/whatever http://example.com/\*content*/whatever """, """\ <document source="test data"> <paragraph> Valid URLs with escaped markup characters: <paragraph> <reference refuri="http://example.com/*content*/whatever"> http://example.com/*content*/whatever <paragraph> <reference refuri="http://example.com/*content*/whatever"> http://example.com/*content*/whatever """], ["""\ Valid URLs may end with punctuation inside "<>": <http://example.org/ends-with-dot.> """, """\ <document source="test data"> <paragraph> Valid URLs may end with punctuation inside "<>": <paragraph> < <reference refuri="http://example.org/ends-with-dot."> http://example.org/ends-with-dot. > """], ["""\ Valid URLs with interesting endings: http://example.org/ends-with-pluses++ """, """\ <document source="test data"> <paragraph> Valid URLs with interesting endings: <paragraph> <reference refuri="http://example.org/ends-with-pluses++"> http://example.org/ends-with-pluses++ """], ["""\ None of these are standalone hyperlinks (their "schemes" are not recognized): signal:noise, a:b. """, """\ <document source="test data"> <paragraph> None of these are standalone hyperlinks (their "schemes" are not recognized): signal:noise, a:b. """], ["""\ Escaped email addresses are not recognized: test\@example.org """, """\ <document source="test data"> <paragraph> Escaped email addresses are not recognized: test@example.org """], ] totest['markup recognition rules'] = [ ["""\ __This__ should be left alone. """, """\ <document source="test data"> <paragraph> __This__ should be left alone. """], [r""" Character-level m\ *a*\ **r**\ ``k``\ `u`:title:\p with backslash-escaped whitespace, including new\ lines. """, """\ <document source="test data"> <paragraph> Character-level m <emphasis> a <strong> r <literal> k <title_reference> u p with backslash-escaped whitespace, including newlines. """], [u"""\ text-*separated*\u2010*by*\u2011*various*\u2012*dashes*\u2013*and*\u2014*hyphens*. \u00bf*punctuation*? \u00a1*examples*!\u00a0*\u00a0no-break-space\u00a0*. """, u"""\ <document source="test data"> <paragraph> text- <emphasis> separated \u2010 <emphasis> by \u2011 <emphasis> various \u2012 <emphasis> dashes \u2013 <emphasis> and \u2014 <emphasis> hyphens . \xbf <emphasis> punctuation ? \xa1 <emphasis> examples !\xa0 <emphasis> \u00a0no-break-space\u00a0 . """], # Whitespace characters: # \u180e*MONGOLIAN VOWEL SEPARATOR*\u180e, fails in Python 2.4 [u"""\ text separated by *newline* or *space* or one of \xa0*NO-BREAK SPACE*\xa0, \u1680*OGHAM SPACE MARK*\u1680, \u2000*EN QUAD*\u2000, \u2001*EM QUAD*\u2001, \u2002*EN SPACE*\u2002, \u2003*EM SPACE*\u2003, \u2004*THREE-PER-EM SPACE*\u2004, \u2005*FOUR-PER-EM SPACE*\u2005, \u2006*SIX-PER-EM SPACE*\u2006, \u2007*FIGURE SPACE*\u2007, \u2008*PUNCTUATION SPACE*\u2008, \u2009*THIN SPACE*\u2009, \u200a*HAIR SPACE*\u200a, \u202f*NARROW NO-BREAK SPACE*\u202f, \u205f*MEDIUM MATHEMATICAL SPACE*\u205f, \u3000*IDEOGRAPHIC SPACE*\u3000, \u2028*LINE SEPARATOR*\u2028 """, u"""\ <document source="test data"> <paragraph> text separated by <emphasis> newline \n\ or \n\ <emphasis> space or one of \xa0 <emphasis> NO-BREAK SPACE \xa0, \u1680 <emphasis> OGHAM SPACE MARK \u1680, \u2000 <emphasis> EN QUAD \u2000, \u2001 <emphasis> EM QUAD \u2001, \u2002 <emphasis> EN SPACE \u2002, \u2003 <emphasis> EM SPACE \u2003, \u2004 <emphasis> THREE-PER-EM SPACE \u2004, \u2005 <emphasis> FOUR-PER-EM SPACE \u2005, \u2006 <emphasis> SIX-PER-EM SPACE \u2006, \u2007 <emphasis> FIGURE SPACE \u2007, \u2008 <emphasis> PUNCTUATION SPACE \u2008, \u2009 <emphasis> THIN SPACE \u2009, \u200a <emphasis> HAIR SPACE \u200a, \u202f <emphasis> NARROW NO-BREAK SPACE \u202f, \u205f <emphasis> MEDIUM MATHEMATICAL SPACE \u205f, \u3000 <emphasis> IDEOGRAPHIC SPACE \u3000, <paragraph> <emphasis> LINE SEPARATOR """], # « * » ‹ * › « * » ‹ * › « * » ‹ * › French, [u"""\ "Quoted" markup start-string (matched openers & closers) -> no markup: '*' "*" (*) <*> [*] {*} ⁅*⁆ Some international quoting styles: ‘*’ “*” English, ..., „*“ ‚*‘ »*« ›*‹ German, Czech, ..., „*” «*» Romanian, “*„ ‘*‚ Greek, 「*」 『*』traditional Chinese, ”*” ’*’ »*» ›*› Swedish, Finnish, „*” ‚*’ Polish, „*” »*« ’*’ Hungarian, But this is „*’ emphasized »*‹. """, u"""\ <document source="test data"> <paragraph> "Quoted" markup start-string (matched openers & closers) -> no markup: <paragraph> '*' "*" (*) <*> [*] {*} ⁅*⁆ <paragraph> Some international quoting styles: ‘*’ “*” English, ..., „*“ ‚*‘ »*« ›*‹ German, Czech, ..., „*” «*» Romanian, “*„ ‘*‚ Greek, 「*」 『*』traditional Chinese, ”*” ’*’ »*» ›*› Swedish, Finnish, „*” ‚*’ Polish, „*” »*« ’*’ Hungarian, <paragraph> But this is „ <emphasis> ’ emphasized » ‹. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/�������������������������������������������0000775�0001750�0001750�00000000000�12356234260�025773� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_role.py�������������������������������0000775�0001750�0001750�00000014005�11445113750�030346� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_role.py 6424 2010-09-18 10:43:52Z smerten $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for misc.py "role" directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['role'] = [ ["""\ .. role:: custom .. role:: special :custom:`interpreted` and :special:`interpreted` """, """\ <document source="test data"> <paragraph> <inline classes="custom"> interpreted and \n\ <inline classes="special"> interpreted """], ["""\ .. role:: custom :class: custom-class .. role:: special :class: special-class :custom:`interpreted` and :special:`interpreted` """, """\ <document source="test data"> <paragraph> <inline classes="custom-class"> interpreted and \n\ <inline classes="special-class"> interpreted """], ["""\ Must define :custom:`interpreted` before using it. .. role:: custom Now that it's defined, :custom:`interpreted` works. """, """\ <document source="test data"> <paragraph> Must define <problematic ids="id2" refid="id1"> :custom:`interpreted` before using it. <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> No role entry for "custom" in module "docutils.parsers.rst.languages.en". Trying "custom" as canonical role name. <system_message backrefs="id2" ids="id1" level="3" line="1" source="test data" type="ERROR"> <paragraph> Unknown interpreted text role "custom". <paragraph> Now that it's defined, \n\ <inline classes="custom"> interpreted works. """], ["""\ .. role:: custom(emphasis) :custom:`text` """, """\ <document source="test data"> <paragraph> <emphasis classes="custom"> text """], ["""\ .. role:: custom ( emphasis ) :custom:`text` """, """\ <document source="test data"> <paragraph> <emphasis classes="custom"> text """], ["""\ .. role:: custom(emphasis) :class: special :custom:`text` """, """\ <document source="test data"> <paragraph> <emphasis classes="special"> text """], ["""\ .. role:: custom(unknown-role) """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> No role entry for "unknown-role" in module "docutils.parsers.rst.languages.en". Trying "unknown-role" as canonical role name. <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Unknown interpreted text role "unknown-role". <literal_block xml:space="preserve"> .. role:: custom(unknown-role) """], ["""\ .. role:: custom :class: 1 """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "role" directive: invalid option value: (option: "class"; value: '1') cannot make "1" into a class name. <literal_block xml:space="preserve"> .. role:: custom :class: 1 """], ["""\ .. role:: 1 """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Invalid argument for "role" directive: cannot make "1" into a class name. <literal_block xml:space="preserve"> .. role:: 1 """], ["""\ .. role:: (error) """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> "role" directive arguments not valid role names: "(error)". <literal_block xml:space="preserve"> .. role:: (error) """], ["""\ .. role:: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> "role" directive requires arguments on the first line. <literal_block xml:space="preserve"> .. role:: """], ["""\ Test ---- .. role:: fileref(emphasis) Testing a :fileref:`role` in a nested parse. """, """\ <document source="test data"> <section ids="test" names="test"> <title> Test <paragraph> Testing a \n\ <emphasis classes="fileref"> role in a nested parse. """], ["""\ .. role:: custom .. role:: special Empty :custom:`\ ` and empty `\ `:special: """, """\ <document source="test data"> <paragraph> Empty <inline classes="custom"> and empty <inline classes="special"> """], ] totest['raw_role'] = [ ["""\ .. role:: html(raw) :format: html Here's some :html:`<i>raw HTML data</i>`. """, """\ <document source="test data"> <paragraph> Here's some \n\ <raw classes="html" format="html" xml:space="preserve"> <i>raw HTML data</i> . """], ["""\ .. role:: itex(raw) :format: latex html Here's some itex markup: :itex:`$x^\\infty$`. """, """\ <document source="test data"> <paragraph> Here's some itex markup: \n\ <raw classes="itex" format="latex html" xml:space="preserve"> $x^\\infty$ . """], ["""\ Can't use the :raw:`role` directly. """, """\ <document source="test data"> <paragraph> Can't use the \n\ <problematic ids="id2" refid="id1"> :raw:`role` directly. <system_message backrefs="id2" ids="id1" level="3" line="1" source="test data" type="ERROR"> <paragraph> No format (Writer name) is associated with this role: "raw". The "raw" role cannot be used directly. Instead, use the "role" directive to create a new role with an associated format. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/utf-16.csv���������������������������������0000664�0001750�0001750�00000000602�10121136756�027527� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000�������������������������������������������������������������������������������������������������������������������������������������������������������������������������"�T�r�e�a�t�"�,� �"�Q�u�a�n�t�i�t�y�"�,� �"�D�e�s�c�r�i�p�t�i�o�n�"� �"�A�l�b�a�t�r���"�,� �2�.�9�9�,� �"��O�n� �a� �!�"� �"�C�r�u�n�c�h�y� �F�r�o�g�"�,� �1�.�4�9�,� �"�I�f� �w�e� �t�o�o�k� �t�h�e� �b��n�e�s� �o�u�t�,� �i�t� �w�o�u�l�d�n �t� �b�e� �c�r�u�n�c�h�y�,� �n�o�w� �w�o�u�l�d� �i�t�?�"� �"�G�a�n�n�e�t� �R�i�p�p�l�e�"�,� �1�.�9�9�,� �"��O�n� �a� �?�"� ������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_tables.py�����������������������������0000775�0001750�0001750�00000074054�12145363551�030675� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_tables.py 7664 2013-05-17 08:16:41Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for tables.py directives. """ from __init__ import DocutilsTestSupport import os, sys import csv from docutils.parsers.rst.directives import tables def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s mydir = 'test_parsers/test_rst/test_directives/' utf_16_csv = os.path.join(mydir, 'utf-16.csv') utf_16_csv_rel = DocutilsTestSupport.utils.relative_path(None, utf_16_csv) empty_txt = os.path.join(mydir, 'empty.txt') unichr_exception = DocutilsTestSupport.exception_data( unichr, int("9999999999999", 16))[0] if isinstance(unichr_exception, OverflowError): unichr_exception_string = 'code too large (%s)' % unichr_exception else: unichr_exception_string = str(unichr_exception) # some error messages changed in Python 3.3: csv_eod_error_str = 'unexpected end of data' if sys.version_info < (3,2,4) and not (# backport to 2.7.4 sys.version_info[:2] == (2,7) and sys.version_info[2] > 3): csv_eod_error_str = 'newline inside string' csv_unknown_url = "'bogus.csv'" if sys.version_info < (3,3,2): csv_unknown_url = "bogus.csv" def null_bytes(): import csv csv_data = open(utf_16_csv, 'rb').read() csv_data = unicode(csv_data, 'latin1').splitlines() reader = csv.reader([tables.CSVTable.encode_for_csv(line + '\n') for line in csv_data]) reader.next() null_bytes_exception = DocutilsTestSupport.exception_data(null_bytes)[0] totest = {} totest['table'] = [ ["""\ .. table:: Truth table for "not" :class: custom :name: tab:truth.not ===== ===== A not A ===== ===== False True True False ===== ===== """, """\ <document source="test data"> <table classes="custom" ids="tab-truth-not" names="tab:truth.not"> <title> Truth table for "not" <tgroup cols="2"> <colspec colwidth="5"> <colspec colwidth="5"> <thead> <row> <entry> <paragraph> A <entry> <paragraph> not A <tbody> <row> <entry> <paragraph> False <entry> <paragraph> True <row> <entry> <paragraph> True <entry> <paragraph> False """], ["""\ .. table:: ========== ========== Table without a title ========== ========== """, """\ <document source="test data"> <table> <tgroup cols="2"> <colspec colwidth="10"> <colspec colwidth="10"> <tbody> <row> <entry> <paragraph> Table <entry> <paragraph> without <row> <entry> <paragraph> a <entry> <paragraph> title """], ["""\ .. table:: title with an *error ====== ===== Simple table ====== ===== """, """\ <document source="test data"> <table> <title> title with an \n\ <problematic ids="id2" refid="id1"> * error <tgroup cols="2"> <colspec colwidth="6"> <colspec colwidth="5"> <tbody> <row> <entry> <paragraph> Simple <entry> <paragraph> table <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline emphasis start-string without end-string. """], ["""\ .. table:: Not a table. This is a paragraph. """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error parsing content block for the "table" directive: exactly one table expected. <literal_block xml:space="preserve"> .. table:: Not a table. \n\ This is a paragraph. """], ["""\ .. table:: empty """, """\ <document source="test data"> <system_message level="2" line="1" source="test data" type="WARNING"> <paragraph> Content block expected for the "table" directive; none found. <literal_block xml:space="preserve"> .. table:: empty """], ] totest['csv-table'] = [ ["""\ .. csv-table:: inline with integral header :widths: 10, 20, 30 :header-rows: 1 :stub-columns: 1 "Treat", "Quantity", "Description" "Albatross", 2.99, "On a stick!" "Crunchy Frog", 1.49, "If we took the bones out, it wouldn\'t be crunchy, now would it?" "Gannet Ripple", 1.99, "On a stick!" """, """\ <document source="test data"> <table> <title> inline with integral header <tgroup cols="3"> <colspec colwidth="10" stub="1"> <colspec colwidth="20"> <colspec colwidth="30"> <thead> <row> <entry> <paragraph> Treat <entry> <paragraph> Quantity <entry> <paragraph> Description <tbody> <row> <entry> <paragraph> Albatross <entry> <paragraph> 2.99 <entry> <paragraph> On a stick! <row> <entry> <paragraph> Crunchy Frog <entry> <paragraph> 1.49 <entry> <paragraph> If we took the bones out, it wouldn't be crunchy, now would it? <row> <entry> <paragraph> Gannet Ripple <entry> <paragraph> 1.99 <entry> <paragraph> On a stick! """], ["""\ .. csv-table:: inline with separate header :header: "Treat", Quantity, "Description" :widths: 10,20,30 "Albatross", 2.99, "On a stick!" """, """\ <document source="test data"> <table> <title> inline with separate header <tgroup cols="3"> <colspec colwidth="10"> <colspec colwidth="20"> <colspec colwidth="30"> <thead> <row> <entry> <paragraph> Treat <entry> <paragraph> Quantity <entry> <paragraph> Description <tbody> <row> <entry> <paragraph> Albatross <entry> <paragraph> 2.99 <entry> <paragraph> On a stick! """], ["""\ .. csv-table:: complex internal structure :header: "Treat", Quantity, " * Description, * Definition, or * Narrative" " * Ice cream * Sorbet * Albatross", 2.99, "On a stick!" """, """\ <document source="test data"> <table> <title> complex internal structure <tgroup cols="3"> <colspec colwidth="33"> <colspec colwidth="33"> <colspec colwidth="33"> <thead> <row> <entry> <paragraph> Treat <entry> <paragraph> Quantity <entry> <bullet_list bullet="*"> <list_item> <paragraph> Description, <list_item> <paragraph> Definition, or <list_item> <paragraph> Narrative <tbody> <row> <entry> <bullet_list bullet="*"> <list_item> <paragraph> Ice cream <list_item> <paragraph> Sorbet <list_item> <paragraph> Albatross <entry> <paragraph> 2.99 <entry> <paragraph> On a stick! """], ["""\ .. csv-table:: short rows one, 2, three 4, five """, """\ <document source="test data"> <table> <title> short rows <tgroup cols="3"> <colspec colwidth="33"> <colspec colwidth="33"> <colspec colwidth="33"> <tbody> <row> <entry> <paragraph> one <entry> <paragraph> 2 <entry> <paragraph> three <row> <entry> <paragraph> 4 <entry> <paragraph> five <entry> """], ["""\ .. csv-table:: short rows :header-rows: 1 header col 1, header col 2 one, 2, three 4 """, """\ <document source="test data"> <table> <title> short rows <tgroup cols="3"> <colspec colwidth="33"> <colspec colwidth="33"> <colspec colwidth="33"> <thead> <row> <entry> <paragraph> header col 1 <entry> <paragraph> header col 2 <entry> <tbody> <row> <entry> <paragraph> one <entry> <paragraph> 2 <entry> <paragraph> three <row> <entry> <paragraph> 4 <entry> <entry> """], [u"""\ .. csv-table:: non-ASCII characters Heiz\xf6lr\xfccksto\xdfabd\xe4mpfung """, u"""\ <document source="test data"> <table> <title> non-ASCII characters <tgroup cols="1"> <colspec colwidth="100"> <tbody> <row> <entry> <paragraph> Heiz\xf6lr\xfccksto\xdfabd\xe4mpfung """], ["""\ .. csv-table:: empty """, """\ <document source="test data"> <system_message level="2" line="1" source="test data" type="WARNING"> <paragraph> The "csv-table" directive requires content; none supplied. <literal_block xml:space="preserve"> .. csv-table:: empty """], ["""\ .. csv-table:: insufficient header row data :header-rows: 2 some, csv, data """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> 2 header row(s) specified but only 1 row(s) of data supplied ("csv-table" directive). <literal_block xml:space="preserve"> .. csv-table:: insufficient header row data :header-rows: 2 \n\ some, csv, data """], ["""\ .. csv-table:: insufficient body data :header-rows: 1 some, csv, data """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Insufficient data supplied (1 row(s)); no data remaining for table body, required by "csv-table" directive. <literal_block xml:space="preserve"> .. csv-table:: insufficient body data :header-rows: 1 \n\ some, csv, data """], ["""\ .. csv-table:: content and external :file: bogus.csv some, csv, data """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> "csv-table" directive may not both specify an external file and have content. <literal_block xml:space="preserve"> .. csv-table:: content and external :file: bogus.csv \n\ some, csv, data """], ["""\ .. csv-table:: external file and url :file: bogus.csv :url: http://example.org/bogus.csv """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> The "file" and "url" options may not be simultaneously specified for the "csv-table" directive. <literal_block xml:space="preserve"> .. csv-table:: external file and url :file: bogus.csv :url: http://example.org/bogus.csv """], ["""\ .. csv-table:: error in the *title some, csv, data """, """\ <document source="test data"> <table> <title> error in the \n\ <problematic ids="id2" refid="id1"> * title <tgroup cols="3"> <colspec colwidth="33"> <colspec colwidth="33"> <colspec colwidth="33"> <tbody> <row> <entry> <paragraph> some <entry> <paragraph> csv <entry> <paragraph> data <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline emphasis start-string without end-string. """], ["""\ .. csv-table:: no such file :file: bogus.csv """, """\ <document source="test data"> <system_message level="4" line="1" source="test data" type="SEVERE"> <paragraph> Problems with "csv-table" directive path: [Errno 2] No such file or directory: 'bogus.csv'. <literal_block xml:space="preserve"> .. csv-table:: no such file :file: bogus.csv """], # note that this output is rewritten below for certain python versions ["""\ .. csv-table:: bad URL :url: bogus.csv """, """\ <document source="test data"> <system_message level="4" line="1" source="test data" type="SEVERE"> <paragraph> Problems with "csv-table" directive URL "bogus.csv": unknown url type: %s. <literal_block xml:space="preserve"> .. csv-table:: bad URL :url: bogus.csv """ % csv_unknown_url], ["""\ .. csv-table:: column mismatch :widths: 10,20 some, csv, data """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> "csv-table" widths do not match the number of columns in table (3). <literal_block xml:space="preserve"> .. csv-table:: column mismatch :widths: 10,20 \n\ some, csv, data """], ["""\ .. csv-table:: bad column widths :widths: 10,y,z some, csv, data .. csv-table:: bad column widths :widths: 0 0 0 some, csv, data """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "csv-table" directive: invalid option value: (option: "widths"; value: '10,y,z') %s. <literal_block xml:space="preserve"> .. csv-table:: bad column widths :widths: 10,y,z \n\ some, csv, data <system_message level="3" line="6" source="test data" type="ERROR"> <paragraph> Error in "csv-table" directive: invalid option value: (option: "widths"; value: '0 0 0') negative or zero value; must be positive. <literal_block xml:space="preserve"> .. csv-table:: bad column widths :widths: 0 0 0 \n\ some, csv, data """ % DocutilsTestSupport.exception_data(int, "y")[1][0]], ["""\ .. csv-table:: good delimiter :delim: / some/csv/data .. csv-table:: good delimiter :delim: \\ some\\csv\\data .. csv-table:: good delimiter :delim: 0x5c some\\csv\\data .. csv-table:: good delimiter :delim: space some csv data """, """\ <document source="test data"> <table> <title> good delimiter <tgroup cols="3"> <colspec colwidth="33"> <colspec colwidth="33"> <colspec colwidth="33"> <tbody> <row> <entry> <paragraph> some <entry> <paragraph> csv <entry> <paragraph> data <table> <title> good delimiter <tgroup cols="3"> <colspec colwidth="33"> <colspec colwidth="33"> <colspec colwidth="33"> <tbody> <row> <entry> <paragraph> some <entry> <paragraph> csv <entry> <paragraph> data <table> <title> good delimiter <tgroup cols="3"> <colspec colwidth="33"> <colspec colwidth="33"> <colspec colwidth="33"> <tbody> <row> <entry> <paragraph> some <entry> <paragraph> csv <entry> <paragraph> data <table> <title> good delimiter <tgroup cols="3"> <colspec colwidth="33"> <colspec colwidth="33"> <colspec colwidth="33"> <tbody> <row> <entry> <paragraph> some <entry> <paragraph> csv <entry> <paragraph> data """], ["""\ .. csv-table:: bad delimiter :delim: multiple .. csv-table:: bad delimiter :delim: U+9999999999999 """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "csv-table" directive: invalid option value: (option: "delim"; value: 'multiple') 'multiple' invalid; must be a single character or a Unicode code. <literal_block xml:space="preserve"> .. csv-table:: bad delimiter :delim: multiple <system_message level="3" line="4" source="test data" type="ERROR"> <paragraph> Error in "csv-table" directive: invalid option value: (option: "delim"; value: 'U+9999999999999') %s. <literal_block xml:space="preserve"> .. csv-table:: bad delimiter :delim: U+9999999999999 """ % unichr_exception_string], ["""\ .. csv-table:: bad CSV data "bad", \"csv, data """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error with CSV data in "csv-table" directive: %s <literal_block xml:space="preserve"> .. csv-table:: bad CSV data \n\ "bad", \"csv, data """ % csv_eod_error_str], ["""\ .. csv-table:: bad CSV header data :header: "bad", \"csv, data good, csv, data """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error with CSV data in "csv-table" directive: %s <literal_block xml:space="preserve"> .. csv-table:: bad CSV header data :header: "bad", \"csv, data \n\ good, csv, data """ % csv_eod_error_str], ["""\ .. csv-table:: bad encoding :file: %s :encoding: latin-1 (7- and 8-bit text encoded as UTF-16 has lots of null/zero bytes.) """ % utf_16_csv, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error with CSV data in "csv-table" directive: %s <literal_block xml:space="preserve"> .. csv-table:: bad encoding :file: %s :encoding: latin-1 <paragraph> (7- and 8-bit text encoded as UTF-16 has lots of null/zero bytes.) """ % (null_bytes_exception, utf_16_csv)], ["""\ .. csv-table:: good encoding :file: %s :encoding: utf-16 :header-rows: 1 """ % utf_16_csv, u"""\ <document source="test data"> <table> <title> good encoding <tgroup cols="3"> <colspec colwidth="33"> <colspec colwidth="33"> <colspec colwidth="33"> <thead> <row> <entry> <paragraph> Treat <entry> <paragraph> Quantity <entry> <paragraph> Description <tbody> <row> <entry> <paragraph> Albatr\u00b0\u00df <entry> <paragraph> 2.99 <entry> <paragraph> \u00a1On a \u03c3\u03c4\u03b9\u03ba! <row> <entry> <paragraph> Crunchy Frog <entry> <paragraph> 1.49 <entry> <paragraph> If we took the b\u00f6nes out, it wouldn\u2019t be crunchy, now would it? <row> <entry> <paragraph> Gannet Ripple <entry> <paragraph> 1.99 <entry> <paragraph> \u00bfOn a \u03c3\u03c4\u03b9\u03ba? """], ["""\ .. csv-table:: no CSV data :file: %s """ % empty_txt, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> No table data detected in CSV file. <literal_block xml:space="preserve"> .. csv-table:: no CSV data :file: %s """ % empty_txt], ] totest['list-table'] = [ ["""\ .. list-table:: list table with integral header :widths: 10 20 30 :header-rows: 1 :stub-columns: 1 * - Treat - Quantity - Description * - Albatross - 2.99 - On a stick! * - Crunchy Frog - 1.49 - If we took the bones out, it wouldn\'t be crunchy, now would it? * - Gannet Ripple - 1.99 - On a stick! """, """\ <document source="test data"> <table> <title> list table with integral header <tgroup cols="3"> <colspec colwidth="10" stub="1"> <colspec colwidth="20"> <colspec colwidth="30"> <thead> <row> <entry> <paragraph> Treat <entry> <paragraph> Quantity <entry> <paragraph> Description <tbody> <row> <entry> <paragraph> Albatross <entry> <paragraph> 2.99 <entry> <paragraph> On a stick! <row> <entry> <paragraph> Crunchy Frog <entry> <paragraph> 1.49 <entry> <paragraph> If we took the bones out, it wouldn\'t be crunchy, now would it? <row> <entry> <paragraph> Gannet Ripple <entry> <paragraph> 1.99 <entry> <paragraph> On a stick! """], ["""\ .. list-table:: not a bullet list """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error parsing content block for the "list-table" directive: exactly one bullet list expected. <literal_block xml:space="preserve"> .. list-table:: \n\ not a bullet list """], ["""\ .. list-table:: * not a second-level bullet list """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error parsing content block for the "list-table" directive: two-level bullet list expected, but row 1 does not contain a second-level bullet list. <literal_block xml:space="preserve"> .. list-table:: \n\ * not a second-level bullet list """], ["""\ .. list-table:: * - columns not uniform * - first row has one, - second row has two """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error parsing content block for the "list-table" directive: uniform two-level bullet list expected, but row 2 does not contain the same number of items as row 1 (2 vs 1). <literal_block xml:space="preserve"> .. list-table:: \n\ * - columns not uniform * - first row has one, - second row has two """], ["""\ .. list-table:: :widths: 10 20 * - ":widths:" option doesn't match columns """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> "list-table" widths do not match the number of columns in table (1). <literal_block xml:space="preserve"> .. list-table:: :widths: 10 20 \n\ * - ":widths:" option doesn\'t match columns """], ["""\ .. list-table:: :stub-columns: 3 * - column 1 - column 2 """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> 3 stub column(s) specified but only 2 columns(s) of data supplied ("list-table" directive). <literal_block xml:space="preserve"> .. list-table:: :stub-columns: 3 \n\ * - column 1 - column 2 """], ["""\ .. list-table:: :stub-columns: 2 * - column 1 - column 2 """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Insufficient data supplied (2 columns(s)); no data remaining for table body, required by "list-table" directive. <literal_block xml:space="preserve"> .. list-table:: :stub-columns: 2 \n\ * - column 1 - column 2 """], ["""\ .. list-table:: empty """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> The "list-table" directive is empty; content required. <literal_block xml:space="preserve"> .. list-table:: empty """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/raw1.txt�����������������������������������0000664�0001750�0001750�00000000062�07546461603�027414� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<p>This file is used by <tt>test_raw.py</tt>.</p> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/include1.txt�������������������������������0000664�0001750�0001750�00000000103�07546461603�030242� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Inclusion 1 ----------- This file is used by ``test_include.py``. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_contents.py���������������������������0000775�0001750�0001750�00000014142�11164743725�031255� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_contents.py 5889 2009-04-01 20:00:21Z gbrandl $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for parts.py contents directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['contents'] = [ ["""\ .. contents:: """, """\ <document source="test data"> <topic classes="contents" ids="contents" names="contents"> <title> Contents <pending> .. internal attributes: .transform: docutils.transforms.parts.Contents .details: """], ["""\ .. contents:: Table of Contents """, """\ <document source="test data"> <topic classes="contents" ids="table-of-contents" names="table\ of\ contents"> <title> Table of Contents <pending> .. internal attributes: .transform: docutils.transforms.parts.Contents .details: """], ["""\ .. contents:: Table of Contents """, """\ <document source="test data"> <topic classes="contents" ids="table-of-contents" names="table\ of\ contents"> <title> Table of Contents <pending> .. internal attributes: .transform: docutils.transforms.parts.Contents .details: """], ["""\ .. contents:: Table of Contents """, """\ <document source="test data"> <topic classes="contents" ids="table-of-contents" names="table\ of\ contents"> <title> Table of Contents <pending> .. internal attributes: .transform: docutils.transforms.parts.Contents .details: """], ["""\ .. contents:: *Table* of ``Contents`` """, """\ <document source="test data"> <topic classes="contents" ids="table-of-contents" names="table\ of\ contents"> <title> <emphasis> Table of <literal> Contents <pending> .. internal attributes: .transform: docutils.transforms.parts.Contents .details: """], ["""\ .. contents:: :depth: 2 :local: """, """\ <document source="test data"> <topic classes="contents local" ids="contents" names="contents"> <pending> .. internal attributes: .transform: docutils.transforms.parts.Contents .details: depth: 2 local: None """], ["""\ .. contents:: :local: arg """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "contents" directive: invalid option value: (option: "local"; value: 'arg') no argument is allowed; "arg" supplied. <literal_block xml:space="preserve"> .. contents:: :local: arg """], ["""\ .. contents:: Table of Contents :local: :depth: 2 :backlinks: none """, """\ <document source="test data"> <topic classes="contents local" ids="table-of-contents" names="table\ of\ contents"> <title> Table of Contents <pending> .. internal attributes: .transform: docutils.transforms.parts.Contents .details: backlinks: None depth: 2 local: None """], ["""\ .. contents:: :depth: two """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "contents" directive: invalid option value: (option: "depth"; value: 'two') %s. <literal_block xml:space="preserve"> .. contents:: :depth: two """ % DocutilsTestSupport.exception_data(int, "two")[1][0]], ["""\ .. contents:: :width: 2 """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "contents" directive: unknown option: "width". <literal_block xml:space="preserve"> .. contents:: :width: 2 """], ["""\ .. contents:: :backlinks: no way! """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "contents" directive: invalid option value: (option: "backlinks"; value: 'no way!') "no way!" unknown; choose from "top", "entry", or "none". <literal_block xml:space="preserve"> .. contents:: :backlinks: no way! """], ["""\ .. contents:: :backlinks: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "contents" directive: invalid option value: (option: "backlinks"; value: None) must supply an argument; choose from "top", "entry", or "none". <literal_block xml:space="preserve"> .. contents:: :backlinks: """], ["""\ * .. contents:: """, """\ <document source="test data"> <bullet_list bullet="*"> <list_item> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> The "contents" directive may not be used within topics or body elements. <literal_block xml:space="preserve"> .. contents:: """], ["""\ .. sidebar:: containing contents .. contents:: """, """\ <document source="test data"> <sidebar> <title> containing contents <topic classes="contents" ids="contents" names="contents"> <title> Contents <pending> .. internal attributes: .transform: docutils.transforms.parts.Contents .details: """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_sectnum.py����������������������������0000775�0001750�0001750�00000002065�10627410160�031062� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_sectnum.py 5174 2007-05-31 00:01:52Z wiemann $ # Author: Lea Wiemann <LeWiemann@gmail.com> # Copyright: This module has been placed in the public domain. """ Tests for the 'sectnum' directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['sectnum'] = [ ["""\ .. sectnum:: """, """\ <document source="test data"> <pending> .. internal attributes: .transform: docutils.transforms.parts.SectNum .details: """], ["""\ .. sectnum:: :depth: 23 :start: 42 :prefix: A Prefix :suffix: A Suffix """, """\ <document source="test data"> <pending> .. internal attributes: .transform: docutils.transforms.parts.SectNum .details: depth: 23 prefix: 'A Prefix' start: 42 suffix: 'A Suffix' """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_target_notes.py�����������������������0000775�0001750�0001750�00000003265�11603172505�032110� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_target_notes.py 7062 2011-06-30 22:14:29Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for the target-notes directives. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['target-notes'] = [ ["""\ .. target-notes:: """, """\ <document source="test data"> <pending> .. internal attributes: .transform: docutils.transforms.references.TargetNotes .details: """], ["""\ .. target-notes:: :class: custom """, """\ <document source="test data"> <pending> .. internal attributes: .transform: docutils.transforms.references.TargetNotes .details: class: ['custom'] """], ["""\ .. target-notes:: :class: custom :name: targets """, """\ <document source="test data"> <pending ids="targets" names="targets"> .. internal attributes: .transform: docutils.transforms.references.TargetNotes .details: class: ['custom'] """], ["""\ .. target-notes:: :class: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "target-notes" directive: invalid option value: (option: "class"; value: None) argument required but none supplied. <literal_block xml:space="preserve"> .. target-notes:: :class: """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_decorations.py������������������������0000775�0001750�0001750�00000003467�10455266150�031734� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_decorations.py 4667 2006-07-12 21:40:56Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for the "header" & "footer" directives. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['headers'] = [ ["""\ .. header:: a paragraph for the header """, """\ <document source="test data"> <decoration> <header> <paragraph> a paragraph for the header """], ["""\ .. header:: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Content block expected for the "header" directive; none found. <literal_block xml:space="preserve"> .. header:: """], ["""\ .. header:: first part of the header .. header:: second part of the header """, """\ <document source="test data"> <decoration> <header> <paragraph> first part of the header <paragraph> second part of the header """], ] totest['footers'] = [ ["""\ .. footer:: a paragraph for the footer """, """\ <document source="test data"> <decoration> <footer> <paragraph> a paragraph for the footer """], ["""\ .. footer:: even if a footer is declared first .. header:: the header appears first """, """\ <document source="test data"> <decoration> <header> <paragraph> the header appears first <footer> <paragraph> even if a footer is declared first """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_default_role.py�����������������������0000775�0001750�0001750�00000003416�10434150472�032055� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_default_role.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for misc.py "default-role" directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['default-role'] = [ ["""\ .. default-role:: subscript This is a `subscript`. """, """\ <document source="test data"> <paragraph> This is a \n\ <subscript> subscript . """], ["""\ Must define a custom role before using it. .. default-role:: custom """, """\ <document source="test data"> <paragraph> Must define a custom role before using it. <system_message level="1" line="3" source="test data" type="INFO"> <paragraph> No role entry for "custom" in module "docutils.parsers.rst.languages.en". Trying "custom" as canonical role name. <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> Unknown interpreted text role "custom". <literal_block xml:space="preserve"> .. default-role:: custom """], ["""\ .. role:: custom .. default-role:: custom This text uses the `default role`. .. default-role:: Returned the `default role` to its standard default. """, """\ <document source="test data"> <paragraph> This text uses the \n\ <inline classes="custom"> default role . <paragraph> Returned the \n\ <title_reference> default role to its standard default. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_code.py�������������������������������0000664�0001750�0001750�00000012751�12024637300�030316� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_code.py 7514 2012-09-14 14:27:12Z milde $ # Author: Guenter Milde # Copyright: This module has been placed in the public domain. """ Test the 'code' directive in parsers/rst/directives/body.py. """ from __init__ import DocutilsTestSupport from docutils.utils.code_analyzer import with_pygments def suite(): s = DocutilsTestSupport.ParserTestSuite() if not with_pygments: del(totest['code-parsing']) s.generateTests(totest) return s totest = {} totest['code'] = [ ["""\ .. code:: This is a code block. """, """\ <document source="test data"> <literal_block classes="code" xml:space="preserve"> This is a code block. """], ["""\ .. code:: :class: testclass :name: without argument This is a code block with generic options. """, """\ <document source="test data"> <literal_block classes="code testclass" ids="without-argument" names="without\ argument" xml:space="preserve"> This is a code block with generic options. """], ["""\ .. code:: text :class: testclass This is a code block with text. """, """\ <document source="test data"> <literal_block classes="code text testclass" xml:space="preserve"> This is a code block with text. """], ["""\ .. code:: :number-lines: This is a code block with text. """, """\ <document source="test data"> <literal_block classes="code" xml:space="preserve"> <inline classes="ln"> 1 \n\ This is a code block with text. """], ["""\ .. code:: :number-lines: 30 This is a code block with text. """, """\ <document source="test data"> <literal_block classes="code" xml:space="preserve"> <inline classes="ln"> 30 \n\ This is a code block with text. """], ["""\ .. code:: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Content block expected for the "code" directive; none found. <literal_block xml:space="preserve"> .. code:: """], ] totest['code-parsing'] = [ ["""\ .. code:: python :class: testclass print 'hello world' # to stdout """, """\ <document source="test data"> <literal_block classes="code python testclass" xml:space="preserve"> \n\ <inline classes="keyword"> print \n\ <inline classes="literal string"> 'hello world' \n\ <inline classes="comment"> # to stdout """], ["""\ .. code:: python :class: testclass :name: my_function :number-lines: 7 def my_function(): '''Test the lexer. ''' # and now for something completely different print 8/2 """, """\ <document source="test data"> <literal_block classes="code python testclass" ids="my-function" names="my_function" xml:space="preserve"> <inline classes="ln"> 7 \n\ <inline classes="keyword"> def \n\ <inline classes="name function"> my_function <inline classes="punctuation"> (): \n\ <inline classes="ln"> 8 \n\ \n\ <inline classes="literal string doc"> \'\'\'Test the lexer. <inline classes="ln"> 9 \n\ <inline classes="literal string doc"> \'\'\' \n\ <inline classes="ln"> 10 \n\ \n\ <inline classes="ln"> 11 \n\ \n\ <inline classes="comment"> # and now for something completely different \n\ <inline classes="ln"> 12 \n\ \n\ <inline classes="keyword"> print \n\ <inline classes="literal number integer"> 8 <inline classes="operator"> / <inline classes="literal number integer"> 2 """], ["""\ .. code:: latex :class: testclass hello \emph{world} % emphasize """, """\ <document source="test data"> <literal_block classes="code latex testclass" xml:space="preserve"> hello \n\ <inline classes="keyword"> \\emph <inline classes="name builtin"> { world <inline classes="name builtin"> } \n\ <inline classes="comment"> % emphasize"""], ["""\ .. code:: rst :number-lines: This is a code block with text. """, """\ <document source="test data"> <literal_block classes="code rst" xml:space="preserve"> <inline classes="ln"> 1 \n\ This is a code block with text. """], ["""\ .. code:: s-lang % abc.sl autoload("abc_mode", "abc"); """, """\ <document source="test data"> <system_message level="2" line="1" source="test data" type="WARNING"> <paragraph> Cannot analyze code. No Pygments lexer found for "s-lang". <literal_block xml:space="preserve"> .. code:: s-lang \n\ % abc.sl autoload("abc_mode", "abc"); """], ["""\ Place the language name in a class argument to avoid the no-lexer warning: .. code:: :class: s-lang % abc.sl autoload("abc_mode", "abc"); """, """\ <document source="test data"> <paragraph> Place the language name in a class argument to avoid the no-lexer warning: <literal_block classes="code s-lang" xml:space="preserve"> % abc.sl autoload("abc_mode", "abc"); """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �����������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_figures.py����������������������������0000775�0001750�0001750�00000016204�11603172505�031053� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_figures.py 7062 2011-06-30 22:14:29Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for images.py figure directives. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['figures'] = [ ["""\ .. figure:: picture.png """, """\ <document source="test data"> <figure> <image uri="picture.png"> """], ["""\ .. figure:: picture.png A picture with a caption. """, """\ <document source="test data"> <figure> <image uri="picture.png"> <caption> A picture with a caption. """], ["""\ .. figure:: picture.png - A picture with an invalid caption. """, """\ <document source="test data"> <figure> <image uri="picture.png"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Figure caption must be a paragraph or empty comment. <literal_block xml:space="preserve"> .. figure:: picture.png \n\ - A picture with an invalid caption. """], ["""\ .. figure:: picture.png .. A picture with a legend but no caption. """, """\ <document source="test data"> <figure> <image uri="picture.png"> <legend> <paragraph> A picture with a legend but no caption. """], ["""\ .. Figure:: picture.png :height: 100 :width: 200 :scale: 50 A picture with image options and a caption. """, """\ <document source="test data"> <figure> <image height="100" scale="50" uri="picture.png" width="200"> <caption> A picture with image options and a caption. """], ["""\ .. Figure:: picture.png :height: 100 :alt: alternate text :width: 200 :scale: 50 :figwidth: 300 :figclass: class1 class2 :name: fig:pix A picture with image options on individual lines, and this caption. """, """\ <document source="test data"> <figure classes="class1 class2" width="300px"> <image alt="alternate text" height="100" ids="fig-pix" names="fig:pix" scale="50" uri="picture.png" width="200"> <caption> A picture with image options on individual lines, and this caption. """], ["""\ .. figure:: picture.png :align: center A figure with explicit alignment. """, """\ <document source="test data"> <figure align="center"> <image uri="picture.png"> <caption> A figure with explicit alignment. """], ["""\ .. figure:: picture.png :align: top A figure with wrong alignment. """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "figure" directive: invalid option value: (option: "align"; value: 'top') "top" unknown; choose from "left", "center", or "right". <literal_block xml:space="preserve"> .. figure:: picture.png :align: top A figure with wrong alignment. """], ["""\ This figure lacks a caption. It may still have a "Figure 1."-style caption appended in the output. .. figure:: picture.png """, """\ <document source="test data"> <paragraph> This figure lacks a caption. It may still have a "Figure 1."-style caption appended in the output. <figure> <image uri="picture.png"> """], ["""\ .. figure:: picture.png A picture with a caption and a legend. +-----------------------+-----------------------+ | Symbol | Meaning | +=======================+=======================+ | .. image:: tent.png | Campground | +-----------------------+-----------------------+ | .. image:: waves.png | Lake | +-----------------------+-----------------------+ | .. image:: peak.png | Mountain | +-----------------------+-----------------------+ """, """\ <document source="test data"> <figure> <image uri="picture.png"> <caption> A picture with a caption and a legend. <legend> <table> <tgroup cols="2"> <colspec colwidth="23"> <colspec colwidth="23"> <thead> <row> <entry> <paragraph> Symbol <entry> <paragraph> Meaning <tbody> <row> <entry> <image uri="tent.png"> <entry> <paragraph> Campground <row> <entry> <image uri="waves.png"> <entry> <paragraph> Lake <row> <entry> <image uri="peak.png"> <entry> <paragraph> Mountain """], ["""\ .. figure:: picture.png .. A picture with a legend but no caption. (The empty comment replaces the caption, which must be a single paragraph.) """, """\ <document source="test data"> <figure> <image uri="picture.png"> <legend> <paragraph> A picture with a legend but no caption. (The empty comment replaces the caption, which must be a single paragraph.) """], ["""\ Testing for line-leaks: .. figure:: picture.png A picture with a caption. .. figure:: picture.png A picture with a caption. .. figure:: picture.png A picture with a caption. .. figure:: picture.png .. figure:: picture.png .. figure:: picture.png .. figure:: picture.png A picture with a caption. .. figure:: picture.png .. figure:: picture.png A picture with a caption. .. figure:: picture.png """, """\ <document source="test data"> <paragraph> Testing for line-leaks: <figure> <image uri="picture.png"> <caption> A picture with a caption. <figure> <image uri="picture.png"> <caption> A picture with a caption. <figure> <image uri="picture.png"> <caption> A picture with a caption. <figure> <image uri="picture.png"> <figure> <image uri="picture.png"> <figure> <image uri="picture.png"> <figure> <image uri="picture.png"> <caption> A picture with a caption. <figure> <image uri="picture.png"> <figure> <image uri="picture.png"> <caption> A picture with a caption. <figure> <image uri="picture.png"> """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_unknown.py����������������������������0000775�0001750�0001750�00000004530�10434150472�031105� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_unknown.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for unknown directives. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['unknown'] = [ ["""\ .. reStructuredText-unknown-directive:: .. reStructuredText-unknown-directive:: argument .. reStructuredText-unknown-directive:: block """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> No directive entry for "reStructuredText-unknown-directive" in module "docutils.parsers.rst.languages.en". Trying "reStructuredText-unknown-directive" as canonical directive name. <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Unknown directive type "reStructuredText-unknown-directive". <literal_block xml:space="preserve"> .. reStructuredText-unknown-directive:: <system_message level="1" line="3" source="test data" type="INFO"> <paragraph> No directive entry for "reStructuredText-unknown-directive" in module "docutils.parsers.rst.languages.en". Trying "reStructuredText-unknown-directive" as canonical directive name. <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> Unknown directive type "reStructuredText-unknown-directive". <literal_block xml:space="preserve"> .. reStructuredText-unknown-directive:: argument <system_message level="1" line="5" source="test data" type="INFO"> <paragraph> No directive entry for "reStructuredText-unknown-directive" in module "docutils.parsers.rst.languages.en". Trying "reStructuredText-unknown-directive" as canonical directive name. <system_message level="3" line="5" source="test data" type="ERROR"> <paragraph> Unknown directive type "reStructuredText-unknown-directive". <literal_block xml:space="preserve"> .. reStructuredText-unknown-directive:: block """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_include.py����������������������������0000775�0001750�0001750�00000070241�12024637300�031030� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_include.py 7514 2012-09-14 14:27:12Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for misc.py "include" directive. """ import os.path import sys from __init__ import DocutilsTestSupport from docutils.parsers.rst import states from docutils._compat import b from docutils.utils.code_analyzer import with_pygments def suite(): s = DocutilsTestSupport.ParserTestSuite() if not with_pygments: del(totest['include-code']) s.generateTests(totest) return s # prepend this directory (relative to the test root): def mydir(path): return os.path.join('test_parsers/test_rst/test_directives/', path) # make `path` relative with utils.relative_path(): def reldir(path): return DocutilsTestSupport.utils.relative_path(None, path) include1 = mydir('include1.txt') include2 = mydir('include2.txt') include3 = mydir('include3.txt') include8 = mydir('include8.txt') include10 = mydir('include10.txt') include11 = mydir('include 11.txt') include12 = mydir('include12.txt') include13 = mydir('include13.txt') include_literal = mydir('include_literal.txt') utf_16_file = mydir('utf-16.csv') utf_16_error_str = ("UnicodeDecodeError: 'ascii' codec can't decode byte 0xfe " "in position 0: ordinal not in range(128)") if sys.version_info < (3,0): utf_16_error_str = ("UnicodeError: Unable to decode input data. " "Tried the following encodings: 'ascii'.\n" " (%s)" % utf_16_error_str) nonexistent = os.path.join(os.path.dirname(states.__file__), 'include', 'nonexistent') nonexistent_rel = DocutilsTestSupport.utils.relative_path( os.path.join(DocutilsTestSupport.testroot, 'dummy'), nonexistent) # Different error for path with 8bit chars with locale == C or None: try: open(u'\u043c\u0438\u0440.txt') except UnicodeEncodeError: errstr_8bit_path = u"""\ Cannot encode input file path "\u043c\u0438\u0440.txt" (wrong locale?).\ """ except: errstr_8bit_path = u"""\ InputError: [Errno 2] No such file or directory: '\u043c\u0438\u0440.txt'.\ """ totest = {} totest['include'] = [ ["""\ Include Test ============ .. include:: %s A paragraph. """ % include1, """\ <document source="test data"> <section ids="include-test" names="include\ test"> <title> Include Test <section ids="inclusion-1" names="inclusion\ 1"> <title> Inclusion 1 <paragraph> This file is used by \n\ <literal> test_include.py . <paragraph> A paragraph. """], ["""\ Include Test ============ .. include:: %s :literal: :class: test :name: my name A paragraph. """ % include1, """\ <document source="test data"> <section ids="include-test" names="include\ test"> <title> Include Test <literal_block classes="test" ids="my-name" names="my\ name" source="%s" xml:space="preserve"> Inclusion 1 ----------- \n\ This file is used by ``test_include.py``. <paragraph> A paragraph. """ % reldir(include1)], ["""\ Literal include, add line numbers .. include:: %s :literal: :number-lines: """ % include1, """\ <document source="test data"> <paragraph> Literal include, add line numbers <literal_block source="%s" xml:space="preserve"> <inline classes="ln"> 1 \n\ Inclusion 1 <inline classes="ln"> 2 \n\ ----------- <inline classes="ln"> 3 \n\ \n\ <inline classes="ln"> 4 \n\ This file is used by ``test_include.py``. """ % reldir(include1)], ["""\ Include code .. include:: %s :code: :class: test :name: my name """ % include1, """\ <document source="test data"> <paragraph> Include code <literal_block classes="code test" ids="my-name" names="my\ name" source="%s" xml:space="preserve"> Inclusion 1 ----------- \n\ This file is used by ``test_include.py``. """ % reldir(include1)], ["""\ Include code, add line numbers .. include:: %s :code: :number-lines: """ % include1, """\ <document source="test data"> <paragraph> Include code, add line numbers <literal_block classes="code" source="%s" xml:space="preserve"> <inline classes="ln"> 1 \n\ Inclusion 1 <inline classes="ln"> 2 \n\ ----------- <inline classes="ln"> 3 \n\ \n\ <inline classes="ln"> 4 \n\ This file is used by ``test_include.py``. """ % reldir(include1)], ["""\ Let's test the parse context. This paragraph is in a block quote. .. include:: %s The included paragraphs should also be in the block quote. """ % include2, """\ <document source="test data"> <paragraph> Let's test the parse context. <block_quote> <paragraph> This paragraph is in a block quote. <paragraph> Here are some paragraphs that can appear at any level. <paragraph> This file (include2.txt) is used by <literal> test_include.py . <paragraph> The included paragraphs should also be in the block quote. """], ["""\ Include Test ============ .. include:: nonexistent.txt A paragraph. """, """\ <document source="test data"> <section ids="include-test" names="include\ test"> <title> Include Test <system_message level="4" line="4" source="test data" type="SEVERE"> <paragraph> Problems with "include" directive path: InputError: [Errno 2] No such file or directory: 'nonexistent.txt'. <literal_block xml:space="preserve"> .. include:: nonexistent.txt <paragraph> A paragraph. """], ["""\ Include Test ============ .. include:: %s .. include:: %s A paragraph. """ % (include1, include1), """\ <document source="test data"> <section ids="include-test" names="include\ test"> <title> Include Test <section dupnames="inclusion\ 1" ids="inclusion-1"> <title> Inclusion 1 <paragraph> This file is used by <literal> test_include.py . <section dupnames="inclusion\ 1" ids="id1"> <title> Inclusion 1 <system_message backrefs="id1" level="1" line="2" source="%s" type="INFO"> <paragraph> Duplicate implicit target name: "inclusion 1". <paragraph> This file is used by <literal> test_include.py . <paragraph> A paragraph. """ % reldir(include1)], ["""\ Include Test ============ .. include:: %s ---------- .. include:: %s A paragraph. """ % (include1, include1), """\ <document source="test data"> <section ids="include-test" names="include\ test"> <title> Include Test <section dupnames="inclusion\ 1" ids="inclusion-1"> <title> Inclusion 1 <paragraph> This file is used by \n\ <literal> test_include.py . <transition> <section dupnames="inclusion\ 1" ids="id1"> <title> Inclusion 1 <system_message backrefs="id1" level="1" line="2" source="%s" type="INFO"> <paragraph> Duplicate implicit target name: "inclusion 1". <paragraph> This file is used by \n\ <literal> test_include.py . <paragraph> A paragraph. """ % reldir(include1)], ["""\ In test data .. include:: %s """ % include3, """\ <document source="test data"> <paragraph> In test data <paragraph> In include3.txt <paragraph> In includes/include4.txt <paragraph> In includes/include5.txt <paragraph> In includes/more/include6.txt <paragraph> In includes/sibling/include7.txt """], ["""\ In test data Section ======= (Section contents in nested parse; slice of input_lines ViewList.) .. include:: %s """ % include3, """\ <document source="test data"> <paragraph> In test data <section ids="section" names="section"> <title> Section <paragraph> (Section contents in nested parse; slice of input_lines ViewList.) <paragraph> In include3.txt <paragraph> In includes/include4.txt <paragraph> In includes/include5.txt <paragraph> In includes/more/include6.txt <paragraph> In includes/sibling/include7.txt """], ["""\ Testing relative includes: .. include:: %s """ % include8, """\ <document source="test data"> <paragraph> Testing relative includes: <paragraph> In include8.txt <paragraph> In ../includes/include9.txt. <paragraph> Here are some paragraphs that can appear at any level. <paragraph> This file (include2.txt) is used by <literal> test_include.py . """], ["""\ Encoding: .. include:: %s :encoding: utf-16 """ % reldir(utf_16_file), b("""\ <document source="test data"> <paragraph> Encoding: <paragraph> "Treat", "Quantity", "Description" "Albatr\xb0\xdf", 2.99, "\xa1On a \\u03c3\\u03c4\\u03b9\\u03ba!" "Crunchy Frog", 1.49, "If we took the b\xf6nes out, it wouldn\\u2019t be crunchy, now would it?" "Gannet Ripple", 1.99, "\xbfOn a \\u03c3\\u03c4\\u03b9\\u03ba?" """).decode('raw_unicode_escape')], ["""\ Include file is UTF-16-encoded, and is not valid ASCII. .. include:: %s :encoding: ascii """ % reldir(utf_16_file), """\ <document source="test data"> <paragraph> Include file is UTF-16-encoded, and is not valid ASCII. <system_message level="4" line="3" source="test data" type="SEVERE"> <paragraph> Problem with "include" directive: %s <literal_block xml:space="preserve"> .. include:: %s :encoding: ascii """ % (utf_16_error_str, reldir(utf_16_file))], [u"""\ cyrillic filename: .. include:: \u043c\u0438\u0440.txt """, u"""\ <document source="test data"> <paragraph> cyrillic filename: <system_message level="4" line="3" source="test data" type="SEVERE"> <paragraph> Problems with "include" directive path: %s <literal_block xml:space="preserve"> .. include:: \u043c\u0438\u0440.txt """ % errstr_8bit_path], ["""\ Testing errors in included file: .. include:: %s """ % include10, """\ <document source="test data"> <paragraph> Testing errors in included file: <system_message level="3" line="1" source="%(source)s" type="ERROR"> <paragraph> Invalid character code: 0x11111111 %(unichr_exception)s <literal_block xml:space="preserve"> unicode:: 0x11111111 <system_message level="2" line="1" source="%(source)s" type="WARNING"> <paragraph> Substitution definition "bad" empty or invalid. <literal_block xml:space="preserve"> .. |bad| unicode:: 0x11111111 <section dupnames="hi" ids="hi"> <title> hi <block_quote> <paragraph> indent <system_message level="2" line="7" source="%(source)s" type="WARNING"> <paragraph> Block quote ends without a blank line; unexpected unindent. <paragraph> error <section dupnames="hi" ids="id1"> <title> hi <system_message backrefs="id1" level="1" line="10" source="%(source)s" type="INFO"> <paragraph> Duplicate implicit target name: "hi". <system_message level="4" line="12" source="%(source)s" type="SEVERE"> <paragraph> Problems with "include" directive path: InputError: [Errno 2] No such file or directory: '%(nonexistent)s'. <literal_block xml:space="preserve"> .. include:: <nonexistent> <system_message level="3" line="14" source="%(source)s" type="ERROR"> <paragraph> Content block expected for the "note" directive; none found. <literal_block xml:space="preserve"> .. note:: <system_message level="3" line="16" source="%(source)s" type="ERROR"> <paragraph> Content block expected for the "admonition" directive; none found. <literal_block xml:space="preserve"> .. admonition:: without title <system_message level="3" line="19" source="%(source)s" type="ERROR"> <paragraph> Content block expected for the "epigraph" directive; none found. <literal_block xml:space="preserve"> .. epigraph:: <system_message level="3" line="21" source="%(source)s" type="ERROR"> <paragraph> Content block expected for the "highlights" directive; none found. <literal_block xml:space="preserve"> .. highlights:: <system_message level="3" line="23" source="%(source)s" type="ERROR"> <paragraph> Content block expected for the "pull-quote" directive; none found. <literal_block xml:space="preserve"> .. pull-quote:: <system_message level="3" line="25" source="%(source)s" type="ERROR"> <paragraph> Invalid context: the "date" directive can only be used within a substitution definition. <literal_block xml:space="preserve"> .. date:: <paragraph> not a definition list: <system_message level="3" line="29" source="%(source)s" type="ERROR"> <paragraph> Unexpected indentation. <block_quote> <paragraph> as a term may only be one line long. <system_message level="3" line="31" source="%(source)s" type="ERROR"> <paragraph> Error in "admonition" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> .. admonition:: without title and content following a blank line <section ids="section-underline-too-short" names="section\ underline\ too\ short"> <title> section underline too short <system_message level="2" line="36" source="%(source)s" type="WARNING"> <paragraph> Title underline too short. <literal_block xml:space="preserve"> section underline too short ----- <table> <tgroup cols="2"> <colspec colwidth="14"> <colspec colwidth="6"> <thead> <row> <entry> <paragraph> A simple table <entry> <paragraph> cell 2 <tbody> <row> <entry> <paragraph> cell 3 <entry> <paragraph> cell 4 <system_message level="2" line="43" source="%(source)s" type="WARNING"> <paragraph> Blank line required after table. <paragraph> No blank line after table. <system_message level="3" line="45" source="%(source)s" type="ERROR"> <paragraph> Error in "unicode" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> unicode:: <system_message level="2" line="45" source="%(source)s" type="WARNING"> <paragraph> Substitution definition "empty" empty or invalid. <literal_block xml:space="preserve"> .. |empty| unicode:: <system_message level="3" line="47" source="%(source)s" type="ERROR"> <paragraph> Error in "topic" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> .. topic:: <system_message level="3" line="49" source="%(source)s" type="ERROR"> <paragraph> Error in "rubric" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> .. rubric:: <rubric> A rubric has no content <comment xml:space="preserve"> _`target: No matching backquote. <system_message level="2" line="52" source="%(source)s" type="WARNING"> <paragraph> malformed hyperlink target. <comment xml:space="preserve"> __malformed: no good <system_message level="2" line="53" source="%(source)s" type="WARNING"> <paragraph> malformed hyperlink target. <definition_list> <definition_list_item> <term> A literal block:: <definition> <system_message level="1" line="57" source="%(source)s" type="INFO"> <paragraph> Blank line missing before literal block (after the "::")? Interpreted as a definition list item. <paragraph> with no blank line above. <literal_block xml:space="preserve"> > A literal block. <system_message level="3" line="61" source="%(source)s" type="ERROR"> <paragraph> Inconsistent literal block quoting. <paragraph> $ with inconsistent quoting. <paragraph> <problematic ids="id3" refid="id2"> :unknown-role:`role` and <problematic ids="id5" refid="id4"> * unbalanced <problematic ids="id7" refid="id6"> ` inline <problematic ids="id9" refid="id8"> ** markup <system_message level="1" line="63" source="%(source)s" type="INFO"> <paragraph> No role entry for "unknown-role" in module "docutils.parsers.rst.languages.en". Trying "unknown-role" as canonical role name. <system_message backrefs="id3" ids="id2" level="3" line="63" source="%(source)s" type="ERROR"> <paragraph> Unknown interpreted text role "unknown-role". <system_message backrefs="id5" ids="id4" level="2" line="63" source="%(source)s" type="WARNING"> <paragraph> Inline emphasis start-string without end-string. <system_message backrefs="id7" ids="id6" level="2" line="63" source="%(source)s" type="WARNING"> <paragraph> Inline interpreted text or phrase reference start-string without end-string. <system_message backrefs="id9" ids="id8" level="2" line="63" source="%(source)s" type="WARNING"> <paragraph> Inline strong start-string without end-string. <paragraph> <problematic ids="id11" refid="id10"> :PEP:`-1` <system_message backrefs="id11" ids="id10" level="3" line="68" source="%(source)s" type="ERROR"> <paragraph> PEP number must be a number from 0 to 9999; "-1" is invalid. <system_message level="1" line="66" source="%(source)s" type="INFO"> <paragraph> No directive entry for "unknown" in module "docutils.parsers.rst.languages.en". Trying "unknown" as canonical directive name. <system_message level="3" line="70" source="%(source)s" type="ERROR"> <paragraph> Unknown directive type "unknown". <literal_block xml:space="preserve"> .. unknown:: directive (info still reported with wrong line) <system_message level="3" line="72" source="%(source)s" type="ERROR"> <paragraph> Malformed table. No bottom table border found. <literal_block xml:space="preserve"> ============== ====== A simple table with no bottom border """ % {'source': reldir(include10), 'nonexistent': reldir(nonexistent), 'unichr_exception': DocutilsTestSupport.exception_data(unichr, int("11111111", 16))[2] }], ["""\ Include file with whitespace in the path: .. include:: %s """ % reldir(include11), """\ <document source="test data"> <paragraph> Include file with whitespace in the path: <paragraph> some text """], ["""\ Standard include data file: .. include:: <isogrk4.txt> """, b("""\ <document source="test data"> <paragraph> Standard include data file: <comment xml:space="preserve"> This data file has been placed in the public domain. <comment xml:space="preserve"> Derived from the Unicode character mappings available from <http://www.w3.org/2003/entities/xml/>. Processed by unicode2rstsubs.py, part of Docutils: <http://docutils.sourceforge.net>. <substitution_definition names="b.Gammad"> \\u03dc <substitution_definition names="b.gammad"> \\u03dd """).decode('raw_unicode_escape')], ["""\ Nonexistent standard include data file: .. include:: <nonexistent> """, """\ <document source="test data"> <paragraph> Nonexistent standard include data file: <system_message level="4" line="3" source="test data" type="SEVERE"> <paragraph> Problems with "include" directive path: InputError: [Errno 2] No such file or directory: '%s'. <literal_block xml:space="preserve"> .. include:: <nonexistent> """ % nonexistent_rel], ["""\ Include start-line/end-line Test .. include:: %s :start-line: 3 :end-line: 4 """ % include2, """\ <document source="test data"> <paragraph> Include start-line/end-line Test <paragraph> This file (include2.txt) is used by """], ["""\ Include start-line/end-line + start-after Test .. include:: %s :start-line: 2 :end-line: 5 :start-after: here Text search is limited to the specified lines. """ % include12, """\ <document source="test data"> <paragraph> Include start-line/end-line + start-after Test <paragraph> In include12.txt (after "start here", before "stop here") <paragraph> Text search is limited to the specified lines. """], ["""\ Include start-after/end-before Test .. include:: %s :start-after: .. start here :end-before: .. stop here A paragraph. """ % include12, """\ <document source="test data"> <paragraph> Include start-after/end-before Test <paragraph> In include12.txt (after "start here", before "stop here") <paragraph> A paragraph. """], ["""\ Include start-after/end-before Test, single option variant .. include:: %s :end-before: .. start here .. include:: %s :start-after: .. stop here A paragraph. """ % (include12, include12), """\ <document source="test data"> <paragraph> Include start-after/end-before Test, single option variant <paragraph> In include12.txt (but before "start here") <paragraph> In include12.txt (after "stop here") <paragraph> A paragraph. """], ["""\ Include start-after/end-before multi-line test. .. include:: %s :start-after: From: me To: you :end-before: ------- -- mork of ork .. include:: %s :start-after: From: me To: you :end-before: ------- -- mork of ork A paragraph. """ % (include13, include13), """\ <document source="test data"> <paragraph> Include start-after/end-before multi-line test. <system_message level="4" line="3" source="test data" type="SEVERE"> <paragraph> Problem with "end-before" option of "include" directive: Text not found. <literal_block xml:space="preserve"> .. include:: %s :start-after: From: me To: you :end-before: ------- -- mork of ork <paragraph> In include13.txt (between header and signature) <paragraph> A paragraph. """ % include13], ["""\ Error handling test; "end-before" error handling tested in previous test. .. include:: %s :start-after: bad string :end-before: mork of ork """ % include13, """\ <document source="test data"> <paragraph> Error handling test; "end-before" error handling tested in previous test. <system_message level="4" line="3" source="test data" type="SEVERE"> <paragraph> Problem with "start-after" option of "include" directive: Text not found. <literal_block xml:space="preserve"> .. include:: %s :start-after: bad string :end-before: mork of ork """ % include13], ["""\ TAB expansion with literal include: .. include:: %s :literal: """ % include_literal, """\ <document source="test data"> <paragraph> TAB expansion with literal include: <literal_block source="%s" xml:space="preserve"> Literal included this should **not** be *marked* `up`. <- leading raw tab. Newlines are normalized. """ % include_literal], ["""\ Custom TAB expansion with literal include: .. include:: %s :literal: :tab-width: 2 """ % include_literal, """\ <document source="test data"> <paragraph> Custom TAB expansion with literal include: <literal_block source="%s" xml:space="preserve"> Literal included this should **not** be *marked* `up`. <- leading raw tab. Newlines are normalized. """ % include_literal], ["""\ No TAB expansion with literal include: .. include:: %s :literal: :tab-width: -1 """ % include_literal, """\ <document source="test data"> <paragraph> No TAB expansion with literal include: <literal_block source="%s" xml:space="preserve"> Literal included this should **not** be *marked* `up`. \t<- leading raw tab. Newlines are normalized. """ % include_literal], ] totest['include-code'] = [ ["""\ Included code .. include:: %s :code: rst """ % include1, """\ <document source="test data"> <paragraph> Included code <literal_block classes="code rst" source="%s" xml:space="preserve"> <inline classes="generic heading"> Inclusion 1 \n\ <inline classes="generic heading"> ----------- \n\ \n\ This file is used by \n\ <inline classes="literal string"> ``test_include.py`` . """ % reldir(include1)], ["""\ Included code .. include:: %s :code: rst :number-lines: """ % include1, """\ <document source="test data"> <paragraph> Included code <literal_block classes="code rst" source="%s" xml:space="preserve"> <inline classes="ln"> 1 \n\ <inline classes="generic heading"> Inclusion 1 \n\ <inline classes="ln"> 2 \n\ <inline classes="generic heading"> ----------- \n\ <inline classes="ln"> 3 \n\ \n\ <inline classes="ln"> 4 \n\ This file is used by \n\ <inline classes="literal string"> ``test_include.py`` . """ % reldir(include1)], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_compound.py���������������������������0000775�0001750�0001750�00000005127�11605102276�031235� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_compound.py 7072 2011-07-06 15:52:30Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for the 'compound' directive from body.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['compound'] = [ ["""\ .. compound:: Compound paragraphs are single logical paragraphs which contain embedded * lists * tables * literal blocks * and other body elements and are split into multiple physical paragraphs. """, """\ <document source="test data"> <compound> <paragraph> Compound paragraphs are single logical paragraphs which contain embedded <bullet_list bullet="*"> <list_item> <paragraph> lists <list_item> <paragraph> tables <list_item> <paragraph> literal blocks <list_item> <paragraph> and other body elements <paragraph> and are split into multiple physical paragraphs. """], ["""\ .. compound:: :name: interesting :class: log This is an extremely interesting compound paragraph containing a simple paragraph, a literal block with some useless log messages:: Connecting... OK Transmitting data... OK Disconnecting... OK and another simple paragraph which is actually just a continuation of the first simple paragraph, with the literal block in between. """, """\ <document source="test data"> <compound classes="log" ids="interesting" names="interesting"> <paragraph> This is an extremely interesting compound paragraph containing a simple paragraph, a literal block with some useless log messages: <literal_block xml:space="preserve"> Connecting... OK Transmitting data... OK Disconnecting... OK <paragraph> and another simple paragraph which is actually just a continuation of the first simple paragraph, with the literal block in between. """], ["""\ .. compound:: content may start on same line second paragraph """, """\ <document source="test data"> <compound> <paragraph> content may start on same line <paragraph> second paragraph """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_admonitions.py������������������������0000775�0001750�0001750�00000011676�11714550403�031743� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_admonitions.py 7348 2012-02-08 19:46:11Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for admonitions.py directives. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['admonitions'] = [ ["""\ .. Attention:: Directives at large. .. Note:: :name: mynote :class: testnote Admonitions support the generic "name" and "class" options. .. Tip:: 15% if the service is good. .. Hint:: It's bigger than a bread box. - .. WARNING:: Strong prose may provoke extreme mental exertion. Reader discretion is strongly advised. - .. Error:: Does not compute. .. Caution:: Don't take any wooden nickels. .. DANGER:: Mad scientist at work! .. Important:: - Wash behind your ears. - Clean up your room. - Call your mother. - Back up your data. """, """\ <document source="test data"> <attention> <paragraph> Directives at large. <note classes="testnote" ids="mynote" names="mynote"> <paragraph> Admonitions support the generic "name" and "class" options. <tip> <paragraph> 15% if the service is good. <hint> <paragraph> It's bigger than a bread box. <bullet_list bullet="-"> <list_item> <warning> <paragraph> Strong prose may provoke extreme mental exertion. Reader discretion is strongly advised. <list_item> <error> <paragraph> Does not compute. <caution> <paragraph> Don't take any wooden nickels. <danger> <paragraph> Mad scientist at work! <important> <bullet_list bullet="-"> <list_item> <paragraph> Wash behind your ears. <list_item> <paragraph> Clean up your room. <list_item> <paragraph> Call your mother. <list_item> <paragraph> Back up your data. """], ["""\ .. note:: One-line notes. .. note:: One after the other. .. note:: No blank lines in-between. """, """\ <document source="test data"> <note> <paragraph> One-line notes. <note> <paragraph> One after the other. <note> <paragraph> No blank lines in-between. """], ["""\ .. note:: Content before options is possible too. :class: mynote .. note:: :strong:`a role is not an option`. :name: role not option .. note:: a role is :strong:`not an option`, even if its starts a line. """, """\ <document source="test data"> <note classes="mynote"> <paragraph> Content before options is possible too. <note ids="role-not-option" names="role\ not\ option"> <paragraph> <strong> a role is not an option . <note> <paragraph> a role is <strong> not an option , even if its starts a line. """], ["""\ .. note:: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Content block expected for the "note" directive; none found. <literal_block xml:space="preserve"> .. note:: """], ["""\ .. admonition:: Admonition This is a generic admonition. """, """\ <document source="test data"> <admonition classes="admonition-admonition"> <title> Admonition <paragraph> This is a generic admonition. """], ["""\ .. admonition:: And, by the way... You can make up your own admonition too. """, """\ <document source="test data"> <admonition classes="admonition-and-by-the-way"> <title> And, by the way... <paragraph> You can make up your own admonition too. """], ["""\ .. admonition:: Admonition :class: emergency :name: reference name Test the "class" override. """, """\ <document source="test data"> <admonition classes="emergency" ids="reference-name" names="reference\ name"> <title> Admonition <paragraph> Test the "class" override. """], ["""\ .. admonition:: Generic admonitions require a title. """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "admonition" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> .. admonition:: Generic admonitions require a title. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/include 11.txt�����������������������������0000664�0001750�0001750�00000000012�10215427137�030351� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������some text ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/include12.txt������������������������������0000664�0001750�0001750�00000000251�10575333504�030322� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������In include12.txt (but before "start here") .. start here In include12.txt (after "start here", before "stop here") .. stop here In include12.txt (after "stop here") �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/include_literal.txt������������������������0000664�0001750�0001750�00000000146�11271134532�031670� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Literal included this should **not** be *marked* `up`. <- leading raw tab. Newlines are normalized. ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_parsed_literals.py��������������������0000775�0001750�0001750�00000003254�11605102276�032565� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_parsed_literals.py 7072 2011-07-06 15:52:30Z milde $ # Author: Lea Wiemann <LeWiemann@gmail.com> # Copyright: This module has been placed in the public domain. """ Tests for the body.py 'parsed-literal' directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['parsed_literals'] = [ ["""\ .. parsed-literal:: This is a parsed literal block. It may contain *inline markup spanning lines.* """, """\ <document source="test data"> <literal_block xml:space="preserve"> This is a parsed literal block. It may contain \n\ <emphasis> inline markup spanning lines. """], ["""\ .. parsed-literal:: :class: myliteral :name: example: parsed This is a parsed literal block with options. """, """\ <document source="test data"> <literal_block classes="myliteral" ids="example-parsed" names="example:\ parsed" xml:space="preserve"> This is a parsed literal block with options. """], ["""\ .. parsed-literal:: content may start on same line """, """\ <document source="test data"> <literal_block xml:space="preserve"> content may start on same line """], ["""\ .. parsed-literal:: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Content block expected for the "parsed-literal" directive; none found. <literal_block xml:space="preserve"> .. parsed-literal:: """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_container.py��������������������������0000775�0001750�0001750�00000003514�11603172505�031371� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_container.py 7062 2011-06-30 22:14:29Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for the 'container' directive from body.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['container'] = [ ["""\ .. container:: "container" is a generic element, an extension mechanism for users & applications. Containers may contain arbitrary body elements. """, """\ <document source="test data"> <container> <paragraph> "container" is a generic element, an extension mechanism for users & applications. <paragraph> Containers may contain arbitrary body elements. """], ["""\ .. container:: custom Some text. """, """\ <document source="test data"> <container classes="custom"> <paragraph> Some text. """], ["""\ .. container:: one two three four Multiple classes. Multi-line argument. Multiple paragraphs in the container. """, """\ <document source="test data"> <container classes="one two three four"> <paragraph> Multiple classes. <paragraph> Multi-line argument. <paragraph> Multiple paragraphs in the container. """], ["""\ .. container:: :name: my name The name argument allows hyperlinks to `my name`_. """, """\ <document source="test data"> <container ids="my-name" names="my\ name"> <paragraph> The name argument allows hyperlinks to <reference name="my name" refname="my name"> my name . """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_code_long.py��������������������������0000664�0001750�0001750�00000004556�11674114075�031352� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_code_long.py 7267 2011-12-20 14:14:21Z milde $ # Author: Guenter Milde # Copyright: This module has been placed in the public domain. """ Test the 'code' directive in body.py with syntax_highlight = 'long'. """ from __init__ import DocutilsTestSupport from docutils.utils.code_analyzer import with_pygments def suite(): s = DocutilsTestSupport.ParserTestSuite(suite_settings={'syntax_highlight':'long'}) if with_pygments: s.generateTests(totest) return s totest = {} totest['code-parsing-long'] = [ ["""\ .. code:: python :number-lines: 7 def my_function(): '''Test the lexer. ''' # and now for something completely different print 8/2 """, """\ <document source="test data"> <literal_block classes="code python" xml:space="preserve"> <inline classes="ln"> 7 \n\ <inline classes="keyword"> def \n\ <inline classes="name function"> my_function <inline classes="punctuation"> (): \n\ <inline classes="ln"> 8 \n\ \n\ <inline classes="literal string doc"> \'\'\'Test the lexer. <inline classes="ln"> 9 \n\ <inline classes="literal string doc"> \'\'\' \n\ <inline classes="ln"> 10 \n\ \n\ <inline classes="ln"> 11 \n\ \n\ <inline classes="comment"> # and now for something completely different \n\ <inline classes="ln"> 12 \n\ \n\ <inline classes="keyword"> print \n\ <inline classes="literal number integer"> 8 <inline classes="operator"> / <inline classes="literal number integer"> 2 """], ["""\ .. code:: latex hello \emph{world} % emphasize """, """\ <document source="test data"> <literal_block classes="code latex" xml:space="preserve"> hello \n\ <inline classes="keyword"> \\emph <inline classes="name builtin"> { world <inline classes="name builtin"> } \n\ <inline classes="comment"> % emphasize"""], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ��������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_block_quotes.py�����������������������0000775�0001750�0001750�00000003054�10627410160�032075� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_block_quotes.py 5174 2007-05-31 00:01:52Z wiemann $ # Author: Lea Wiemann <LeWiemann@gmail.com> # Copyright: This module has been placed in the public domain. """ Tests for the block quote directives "epigraph", "highlights", and "pull-quote". """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s generic_tests = [ ["""\ .. %(type)s:: This is a block quote. -- Attribution This is another block quote. -- Another Attribution, Second Line """, """\ <document source="test data"> <block_quote classes="%(type)s"> <paragraph> This is a block quote. <attribution> Attribution <block_quote classes="%(type)s"> <paragraph> This is another block quote. <attribution> Another Attribution, Second Line """], # TODO: Add class option. ["""\ .. %(type)s:: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Content block expected for the "%(type)s" directive; none found. <literal_block xml:space="preserve"> .. %(type)s:: """], ] totest = {} for block_quote_type in ('epigraph', 'highlights', 'pull-quote'): totest[block_quote_type] = [ [text % {'type': block_quote_type} for text in pair] for pair in generic_tests] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/include2.txt�������������������������������0000664�0001750�0001750�00000000161�07701625121�030235� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Here are some paragraphs that can appear at any level. This file (include2.txt) is used by ``test_include.py``. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_sidebars.py���������������������������0000775�0001750�0001750�00000003561�11603172505�031205� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_sidebars.py 7062 2011-06-30 22:14:29Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for the "sidebar" directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['sidebars'] = [ ["""\ .. sidebar:: Outer .. sidebar:: Nested Body. """, """\ <document source="test data"> <sidebar> <title> Outer <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> The "sidebar" directive may not be used within a sidebar element. <literal_block xml:space="preserve"> .. sidebar:: Nested \n\ Body. """], ["""\ .. sidebar:: Margin Notes :subtitle: with options :class: margin :name: note:Options Body. """, """\ <document source="test data"> <sidebar classes="margin" ids="note-options" names="note:options"> <title> Margin Notes <subtitle> with options <paragraph> Body. """], ["""\ .. sidebar:: Outer .. topic:: Topic .. sidebar:: Inner text """, """\ <document source="test data"> <sidebar> <title> Outer <topic> <title> Topic <system_message level="3" line="5" source="test data" type="ERROR"> <paragraph> The "sidebar" directive may not be used within topics or body elements. <literal_block xml:space="preserve"> .. sidebar:: Inner \n\ text """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �����������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_class.py������������������������������0000775�0001750�0001750�00000002072�10627410160�030507� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_class.py 5174 2007-05-31 00:01:52Z wiemann $ # Author: Lea Wiemann <LeWiemann@gmail.com> # Copyright: This module has been placed in the public domain. """ Tests for the 'class' directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['class'] = [ ["""\ .. class:: class1 class2 """, """\ <document source="test data"> <pending> .. internal attributes: .transform: docutils.transforms.misc.ClassAttribute .details: class: ['class1', 'class2'] directive: 'class' """], ["""\ .. class:: class1 class2 The classes are applied to this paragraph. And this one. """, """\ <document source="test data"> <paragraph classes="class1 class2"> The classes are applied to this paragraph. <paragraph classes="class1 class2"> And this one. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/include10.txt������������������������������0000664�0001750�0001750�00000001670�11365262441�030325� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������.. |bad| unicode:: 0x11111111 hi ----- indent error hi ----- .. include:: <nonexistent> .. note:: .. admonition:: without title .. epigraph:: .. highlights:: .. pull-quote:: .. date:: not a definition list: as a term may only be one line long. .. admonition:: without title and content following a blank line section underline too short ----- ============== ====== A simple table cell 2 ============== ====== cell 3 cell 4 ============== ====== No blank line after table. .. |empty| unicode:: .. topic:: .. rubric:: .. rubric:: A rubric has no content .. _`target: No matching backquote. .. __malformed: no good A literal block:: with no blank line above. :: > A literal block. $ with inconsistent quoting. :unknown-role:`role` and *unbalanced `inline **markup :PEP:`-1` .. unknown:: directive (info still reported with wrong line) ============== ====== A simple table with no bottom border ������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/empty.txt����������������������������������0000664�0001750�0001750�00000000000�10206505134�027651� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/__init__.py��������������������������������0000664�0001750�0001750�00000000462�10254646615�030114� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������import os import os.path import sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) prev = '' while sys.path[0] != prev: try: import DocutilsTestSupport break except ImportError: prev = sys.path[0] sys.path[0] = os.path.dirname(prev) sys.path.pop(0) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_code_none.py��������������������������0000664�0001750�0001750�00000003230�11660414555�031337� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_code_none.py 7221 2011-11-15 07:49:01Z milde $ # Author: Guenter Milde # Copyright: This module has been placed in the public domain. """ Test the 'code' directive in body.py with syntax_highlight = 'none'. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite(suite_settings={'syntax_highlight':'none'}) s.generateTests(totest) return s totest = {} totest['code-parsing-none'] = [ ["""\ .. code:: This is a code block. """, """\ <document source="test data"> <literal_block classes="code" xml:space="preserve"> This is a code block. """], ["""\ .. code:: python :number-lines: 7 def my_function(): '''Test the lexer. ''' # and now for something completely different print 8/2 """, """\ <document source="test data"> <literal_block classes="code python" xml:space="preserve"> <inline classes="ln"> 7 \n\ def my_function(): <inline classes="ln"> 8 \n\ \'\'\'Test the lexer. <inline classes="ln"> 9 \n\ \'\'\' <inline classes="ln"> 10 \n\ \n\ <inline classes="ln"> 11 \n\ # and now for something completely different <inline classes="ln"> 12 \n\ print 8/2 """], ["""\ .. code:: latex hello \emph{world} % emphasize """, """\ <document source="test data"> <literal_block classes="code latex" xml:space="preserve"> hello \\emph{world} % emphasize """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_date.py�������������������������������0000775�0001750�0001750�00000003205�12012307054�030313� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_date.py 7491 2012-08-13 23:30:52Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for the misc.py "date" directive. """ from __init__ import DocutilsTestSupport import time from docutils.utils.error_reporting import locale_encoding def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['date'] = [ ["""\ .. |date| date:: Today's date is |date|. """, """\ <document source="test data"> <substitution_definition names="date"> %s <paragraph> Today's date is \n\ <substitution_reference refname="date"> date . """ % time.strftime('%Y-%m-%d')], ["""\ .. |date| date:: %a, %d %b %Y """, """\ <document source="test data"> <substitution_definition names="date"> %s """ % time.strftime('%a, %d %b %Y')], ["""\ .. date:: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Invalid context: the "date" directive can only be used within a substitution definition. <literal_block xml:space="preserve"> .. date:: """], ] # some locales return non-ASCII characters for names of days or months if locale_encoding in ['utf8', 'utf-8', 'latin-1']: totest['decode date'] = [ [u"""\ .. |date| date:: t\xc3glich """, u"""\ <document source="test data"> <substitution_definition names="date"> t\xc3glich """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_unicode.py����������������������������0000775�0001750�0001750�00000012457�11164743725�031055� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_unicode.py 5889 2009-04-01 20:00:21Z gbrandl $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for misc.py "unicode" directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s unichr_exception = DocutilsTestSupport.exception_data( unichr, int("111111111111111111", 16))[0] if isinstance(unichr_exception, OverflowError): unichr_exception_string = 'code too large (%s)' % unichr_exception else: unichr_exception_string = str(unichr_exception) totest = {} totest['unicode'] = [ [""" Insert an em-dash (|mdash|), a copyright symbol (|copy|), a non-breaking space (|nbsp|), a backwards-not-equals (|bne|), and a captial omega (|Omega|). .. |mdash| unicode:: 0x02014 .. |copy| unicode:: \\u00A9 .. |nbsp| unicode::   .. |bne| unicode:: U0003D U020E5 .. |Omega| unicode:: U+003A9 """, u"""\ <document source="test data"> <paragraph> Insert an em-dash ( <substitution_reference refname="mdash"> mdash ), a copyright symbol ( <substitution_reference refname="copy"> copy ), a non-breaking space ( <substitution_reference refname="nbsp"> nbsp ), a backwards-not-equals ( <substitution_reference refname="bne"> bne ), and a captial omega ( <substitution_reference refname="Omega"> Omega ). <substitution_definition names="mdash"> \u2014 <substitution_definition names="copy"> \u00A9 <substitution_definition names="nbsp"> \u00A0 <substitution_definition names="bne"> = \u20e5 <substitution_definition names="Omega"> \u03a9 """], [""" Bad input: .. |empty| unicode:: .. |empty too| unicode:: .. comment doesn't count as content .. |not hex| unicode:: 0xHEX .. |not all hex| unicode:: UABCX .. unicode:: not in a substitution definition """, """\ <document source="test data"> <paragraph> Bad input: <system_message level="3" line="4" source="test data" type="ERROR"> <paragraph> Error in "unicode" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> unicode:: <system_message level="2" line="4" source="test data" type="WARNING"> <paragraph> Substitution definition "empty" empty or invalid. <literal_block xml:space="preserve"> .. |empty| unicode:: <system_message level="2" line="5" source="test data" type="WARNING"> <paragraph> Substitution definition "empty too" empty or invalid. <literal_block xml:space="preserve"> .. |empty too| unicode:: .. comment doesn't count as content <substitution_definition names="not\ hex"> 0xHEX <substitution_definition names="not\ all\ hex"> UABCX <system_message level="3" line="8" source="test data" type="ERROR"> <paragraph> Invalid context: the "unicode" directive can only be used within a substitution definition. <literal_block xml:space="preserve"> .. unicode:: not in a substitution definition """], [""" Testing comments and extra text. Copyright |copy| 2003, |BogusMegaCorp (TM)|. .. |copy| unicode:: 0xA9 .. copyright sign .. |BogusMegaCorp (TM)| unicode:: BogusMegaCorp U+2122 .. with trademark sign """, u"""\ <document source="test data"> <paragraph> Testing comments and extra text. <paragraph> Copyright <substitution_reference refname="copy"> copy 2003, <substitution_reference refname="BogusMegaCorp (TM)"> BogusMegaCorp (TM) . <substitution_definition names="copy"> \u00A9 <substitution_definition names="BogusMegaCorp\ (TM)"> BogusMegaCorp \u2122 """], [""" .. |too big for int| unicode:: 0x111111111111111111 .. |too big for unicode| unicode:: 0x11111111 """, """\ <document source="test data"> <system_message level="3" line="2" source="test data" type="ERROR"> <paragraph> Invalid character code: 0x111111111111111111 ValueError: %s <literal_block xml:space="preserve"> unicode:: 0x111111111111111111 <system_message level="2" line="2" source="test data" type="WARNING"> <paragraph> Substitution definition "too big for int" empty or invalid. <literal_block xml:space="preserve"> .. |too big for int| unicode:: 0x111111111111111111 <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> Invalid character code: 0x11111111 %s <literal_block xml:space="preserve"> unicode:: 0x11111111 <system_message level="2" line="3" source="test data" type="WARNING"> <paragraph> Substitution definition "too big for unicode" empty or invalid. <literal_block xml:space="preserve"> .. |too big for unicode| unicode:: 0x11111111 """ % (unichr_exception_string, DocutilsTestSupport.exception_data(unichr, int("11111111", 16))[2])] ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_meta.py�������������������������������0000775�0001750�0001750�00000013670�10455266150�030345� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_meta.py 4667 2006-07-12 21:40:56Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for html meta directives. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['meta'] = [ ["""\ .. meta:: :description: The reStructuredText plaintext markup language :keywords: plaintext,markup language """, """\ <document source="test data"> <pending> .. internal attributes: .transform: docutils.transforms.components.Filter .details: component: 'writer' format: 'html' nodes: <meta content="The reStructuredText plaintext markup language" name="description"> <pending> .. internal attributes: .transform: docutils.transforms.components.Filter .details: component: 'writer' format: 'html' nodes: <meta content="plaintext,markup language" name="keywords"> """], ["""\ .. meta:: :description lang=en: An amusing story :description lang=fr: Un histoire amusant """, """\ <document source="test data"> <pending> .. internal attributes: .transform: docutils.transforms.components.Filter .details: component: 'writer' format: 'html' nodes: <meta content="An amusing story" lang="en" name="description"> <pending> .. internal attributes: .transform: docutils.transforms.components.Filter .details: component: 'writer' format: 'html' nodes: <meta content="Un histoire amusant" lang="fr" name="description"> """], ["""\ .. meta:: :http-equiv=Content-Type: text/html; charset=ISO-8859-1 """, """\ <document source="test data"> <pending> .. internal attributes: .transform: docutils.transforms.components.Filter .details: component: 'writer' format: 'html' nodes: <meta content="text/html; charset=ISO-8859-1" http-equiv="Content-Type"> """], ["""\ .. meta:: :name: content over multiple lines """, """\ <document source="test data"> <pending> .. internal attributes: .transform: docutils.transforms.components.Filter .details: component: 'writer' format: 'html' nodes: <meta content="content over multiple lines" name="name"> """], ["""\ Paragraph .. meta:: :name: content """, """\ <document source="test data"> <paragraph> Paragraph <pending> .. internal attributes: .transform: docutils.transforms.components.Filter .details: component: 'writer' format: 'html' nodes: <meta content="content" name="name"> """], ["""\ .. meta:: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Content block expected for the "meta" directive; none found. <literal_block xml:space="preserve"> .. meta:: """], ["""\ .. meta:: :empty: """, """\ <document source="test data"> <system_message level="1" line="2" source="test data" type="INFO"> <paragraph> No content for meta tag "empty". <literal_block xml:space="preserve"> :empty: """], ["""\ .. meta:: not a field list """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Invalid meta directive. <literal_block xml:space="preserve"> .. meta:: not a field list """], ["""\ .. meta:: :name: content not a field :name: content """, """\ <document source="test data"> <pending> .. internal attributes: .transform: docutils.transforms.components.Filter .details: component: 'writer' format: 'html' nodes: <meta content="content" name="name"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Invalid meta directive. <literal_block xml:space="preserve"> .. meta:: :name: content not a field :name: content """], ["""\ .. meta:: :name: content :name: content not a field """, """\ <document source="test data"> <pending> .. internal attributes: .transform: docutils.transforms.components.Filter .details: component: 'writer' format: 'html' nodes: <meta content="content" name="name"> <pending> .. internal attributes: .transform: docutils.transforms.components.Filter .details: component: 'writer' format: 'html' nodes: <meta content="content" name="name"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Invalid meta directive. <literal_block xml:space="preserve"> .. meta:: :name: content :name: content not a field """], ["""\ .. meta:: :name notattval: content """, """\ <document source="test data"> <system_message level="3" line="2" source="test data" type="ERROR"> <paragraph> Error parsing meta tag attribute "notattval": missing "=". <literal_block xml:space="preserve"> :name notattval: content """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/include13.txt������������������������������0000664�0001750�0001750�00000000246�10575333504�030327� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������In include13.txt (but before header) From: me To: you In include13.txt (between header and signature) ------- -- mork of ork In include13.txt (after signature) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_images.py�����������������������������0000775�0001750�0001750�00000026115�12115117661�030657� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_images.py 7621 2013-03-04 13:20:49Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for images.py image directives. """ from __init__ import DocutilsTestSupport from docutils.nodes import reprunicode def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['images'] = [ ["""\ .. image:: picture.png """, """\ <document source="test data"> <image uri="picture.png"> """], ["""\ .. image:: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> .. image:: """], ["""\ .. image:: one two three.png """, """\ <document source="test data"> <image uri="onetwothree.png"> """], ["""\ .. image:: picture.png :height: 100 :width: 200 :scale: 50 """, """\ <document source="test data"> <image height="100" scale="50" uri="picture.png" width="200"> """], ["""\ .. image:: picture.png :height: 100 :width: 200 :scale: 50 """, """\ <document source="test data"> <image height="100" scale="50" uri="picture.png" width="200"> """], ["""\ .. image:: :height: 100 :width: 200 :scale: 50 """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> .. image:: :height: 100 :width: 200 :scale: 50 """], # If there are multiple lines in the link block, they are stripped of # leading and trailing whitespace and joined together: ["""\ .. image:: a/very/long/path/to/ picture.png :height: 100 :width: 200 :scale: 50 """, """\ <document source="test data"> <image height="100" scale="50" uri="a/very/long/path/to/picture.png" width="200"> """], # The following two misspellings were detected in Docutils <= 0.8 # (the option block was started by any line starting with a colon # which led to problems with named roles in other directives): ["""\ .. image:: picture.png :scale 50 """, """\ <document source="test data"> <image uri="picture.png:scale50"> """], ["""\ .. image:: picture.png :: 50 """, """\ <document source="test data"> <image uri="picture.png::50"> """], # a missing leading colon went undetected also in Docutils <= 0.8: ["""\ .. image:: picture.png scale: 50 """, """\ <document source="test data"> <image uri="picture.pngscale:50"> """], ["""\ .. image:: picture.png :width: 200px :height: 100 em """, """\ <document source="test data"> <image height="100em" uri="picture.png" width="200px"> """], ["""\ .. image:: picture.png :width: 50% :height: 10mm """, """\ <document source="test data"> <image height="10mm" uri="picture.png" width="50%"> """], ["""\ .. image:: picture.png :width: 50% :height: 40% """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: invalid option value: (option: "height"; value: \'40%\') not a positive measure of one of the following units: "em" "ex" "px" "in" "cm" "mm" "pt" "pc" "". <literal_block xml:space="preserve"> .. image:: picture.png :width: 50% :height: 40% """], ["""\ .. image:: picture.png :width: 20mc """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: invalid option value: (option: "width"; value: \'20mc\') not a positive measure of one of the following units: "em" "ex" "px" "in" "cm" "mm" "pt" "pc" "%". <literal_block xml:space="preserve"> .. image:: picture.png :width: 20mc """], ["""\ .. image:: picture.png :height: 100 :width: 200 :scale: 50 :alt: Alternate text for the picture """, """\ <document source="test data"> <image alt="Alternate text for the picture" height="100" scale="50" uri="picture.png" width="200"> """], ["""\ .. image:: picture.png :scale: -50 """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: invalid option value: (option: "scale"; value: '-50') negative value; must be positive or zero. <literal_block xml:space="preserve"> .. image:: picture.png :scale: -50 """], ["""\ .. image:: picture.png :scale: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: invalid option value: (option: "scale"; value: None) %s. <literal_block xml:space="preserve"> .. image:: picture.png :scale: """ % DocutilsTestSupport.exception_data(int, None)[1][0]], ["""\ .. image:: picture.png :height: 100 :scale 50 """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: invalid option block. <literal_block xml:space="preserve"> .. image:: picture.png :height: 100 :scale 50 """], ["""\ .. image:: picture.png :sale: 50 """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: unknown option: "sale". <literal_block xml:space="preserve"> .. image:: picture.png :sale: 50 """], ["""\ .. image:: picture.png :scale is: 50 """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: invalid option data: extension option field name may not contain multiple words. <literal_block xml:space="preserve"> .. image:: picture.png :scale is: 50 """], ["""\ .. image:: picture.png :scale: fifty """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: invalid option value: (option: "scale"; value: 'fifty') %s. <literal_block xml:space="preserve"> .. image:: picture.png :scale: fifty """ % DocutilsTestSupport.exception_data(int, "fifty")[1][0]], ["""\ .. image:: picture.png :scale: 50 :scale: 50 """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: invalid option data: duplicate option "scale". <literal_block xml:space="preserve"> .. image:: picture.png :scale: 50 :scale: 50 """], ["""\ .. image:: picture.png :alt: (Empty "alt" option.) """, """\ <document source="test data"> <image alt="" uri="picture.png"> <paragraph> (Empty "alt" option.) """], ["""\ .. image:: picture.png :target: bigpicture.png :name: fig:pix """, """\ <document source="test data"> <reference refuri="bigpicture.png"> <image ids="fig-pix" names="fig:pix" uri="picture.png"> """], ["""\ .. image:: picture.png :target: indirect_ """, """\ <document source="test data"> <reference name="indirect" refname="indirect"> <image uri="picture.png"> """], ["""\ .. image:: picture.png :target: a/multi/ line/uri .. image:: picture.png :target: `a multi line internal reference`_ """, """\ <document source="test data"> <reference refuri="a/multi/line/uri"> <image uri="picture.png"> <reference name="a multi line internal reference" refname="a multi line internal reference"> <image uri="picture.png"> """], ["""\ .. image:: picture.png :target: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: invalid option value: (option: "target"; value: None) argument required but none supplied. <literal_block xml:space="preserve"> .. image:: picture.png :target: """], ["""\ .. image:: picture.png :align: left """, """\ <document source="test data"> <image align="left" uri="picture.png"> """], ["""\ .. image:: picture.png :align: top """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: "top" is not a valid value for the "align" option. Valid values for "align" are: "left", "center", "right". <literal_block xml:space="preserve"> .. image:: picture.png :align: top """], ["""\ .. |img| image:: picture.png :align: top """, """\ <document source="test data"> <substitution_definition names="img"> <image align="top" alt="img" uri="picture.png"> """], ["""\ .. |img| image:: picture.png :align: left """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: "left" is not a valid value for the "align" option within a substitution definition. Valid values for "align" are: "top", "middle", "bottom". <literal_block xml:space="preserve"> image:: picture.png :align: left <system_message level="2" line="1" source="test data" type="WARNING"> <paragraph> Substitution definition "img" empty or invalid. <literal_block xml:space="preserve"> .. |img| image:: picture.png :align: left """], [u"""\ .. image:: picture.png :align: \xe4 """, u"""\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "image" directive: invalid option value: (option: "align"; value: %s) "\xe4" unknown; choose from "top", "middle", "bottom", "left", "center", or "right". <literal_block xml:space="preserve"> .. image:: picture.png :align: \xe4 """ % repr(reprunicode(u'\xe4'))], [""" .. image:: test.png :target: Uppercase_ .. _Uppercase: http://docutils.sourceforge.net/ """, """\ <document source="test data"> <reference name="Uppercase" refname="uppercase"> <image uri="test.png"> <target ids="uppercase" names="uppercase" refuri="http://docutils.sourceforge.net/"> """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_raw.py��������������������������������0000775�0001750�0001750�00000011571�11731735075�030213� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_raw.py 7384 2012-03-19 22:59:09Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for misc.py "raw" directive. """ import os.path import sys from __init__ import DocutilsTestSupport from docutils._compat import b def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s mydir = 'test_parsers/test_rst/test_directives/' raw1 = os.path.join(mydir, 'raw1.txt') utf_16_file = os.path.join(mydir, 'utf-16.csv') utf_16_file_rel = DocutilsTestSupport.utils.relative_path(None, utf_16_file) utf_16_error_str = ("UnicodeDecodeError: 'ascii' codec can't decode byte 0xfe " "in position 0: ordinal not in range(128)") if sys.version_info < (3,0): utf_16_error_str = ("UnicodeError: Unable to decode input data. " "Tried the following encodings: 'ascii'.\n" " (%s)" % utf_16_error_str) totest = {} totest['raw'] = [ ["""\ .. raw:: html <span>This is some plain old raw text.</span> """, """\ <document source="test data"> <raw format="html" xml:space="preserve"> <span>This is some plain old raw text.</span> """], ["""\ .. raw:: html :file: %s """ % raw1, """\ <document source="test data"> <raw format="html" source="%s" xml:space="preserve"> <p>This file is used by <tt>test_raw.py</tt>.</p> """ % DocutilsTestSupport.utils.relative_path(None, raw1)], ["""\ .. raw:: html :file: rawfile.html :url: http://example.org/ """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> The "file" and "url" options may not be simultaneously specified for the "raw" directive. <literal_block xml:space="preserve"> .. raw:: html :file: rawfile.html :url: http://example.org/ """], ["""\ .. raw:: html :file: rawfile.html <p>Can't have both content and file attribute.</p> """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> "raw" directive may not both specify an external file and have content. <literal_block xml:space="preserve"> .. raw:: html :file: rawfile.html <p>Can't have both content and file attribute.</p> """], [r""" .. raw:: latex html \[ \sum_{n=1}^\infty \frac{1}{n} \text{ etc.} \] """, """\ <document source="test data"> <raw format="latex html" xml:space="preserve"> \\[ \\sum_{n=1}^\\infty \\frac{1}{n} \\text{ etc.} \\] """], ["""\ .. raw:: html :file: %s :encoding: utf-16 """ % utf_16_file_rel, b("""\ <document source="test data"> <raw format="html" source="%s" xml:space="preserve"> "Treat", "Quantity", "Description" "Albatr\xb0\xdf", 2.99, "\xa1On a \\u03c3\\u03c4\\u03b9\\u03ba!" "Crunchy Frog", 1.49, "If we took the b\xf6nes out, it wouldn\\u2019t be crunchy, now would it?" "Gannet Ripple", 1.99, "\xbfOn a \\u03c3\\u03c4\\u03b9\\u03ba?" """ % utf_16_file_rel).decode('raw_unicode_escape')], ["""\ Raw input file is UTF-16-encoded, and is not valid ASCII. .. raw:: html :file: %s :encoding: ascii """ % utf_16_file_rel, """\ <document source="test data"> <paragraph> Raw input file is UTF-16-encoded, and is not valid ASCII. <system_message level="4" line="3" source="test data" type="SEVERE"> <paragraph> Problem with "raw" directive: %s <literal_block xml:space="preserve"> .. raw:: html :file: %s :encoding: ascii """ % (utf_16_error_str, utf_16_file_rel)], [u"""\ .. raw:: html :encoding: utf-8 Should the parser complain becau\xdfe there is no :file:? BUG? """, """\ <document source="test data"> <raw format="html" xml:space="preserve"> Should the parser complain becau\xdfe there is no :file:? BUG? """], ["""\ .. raw:: html """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Content block expected for the "raw" directive; none found. <literal_block xml:space="preserve"> .. raw:: html """], ["""\ .. raw:: html :file: non-existent.file """, """\ <document source="test data"> <system_message level="4" line="1" source="test data" type="SEVERE"> <paragraph> Problems with "raw" directive path: InputError: [Errno 2] No such file or directory: 'non-existent.file'. <literal_block xml:space="preserve"> .. raw:: html :file: non-existent.file """], # note that this output is rewritten below for certain python versions ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ���������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_title.py������������������������������0000775�0001750�0001750�00000001160�10627410160�030520� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_title.py 5174 2007-05-31 00:01:52Z wiemann $ # Author: Lea Wiemann <LeWiemann@gmail.com> # Copyright: This module has been placed in the public domain. """ Tests for the 'title' directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['title'] = [ ["""\ .. title:: This is the document title. """, """\ <document source="test data" title="This is the document title."> """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_test_directives.py��������������������0000775�0001750�0001750�00000013373�10434150472�032613� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_test_directives.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for misc.py test directives. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['test_directives'] = [ ["""\ .. reStructuredText-test-directive:: Paragraph. """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Directive processed. Type="reStructuredText-test-directive", arguments=[], options={}, content: None <paragraph> Paragraph. """], ["""\ .. reStructuredText-test-directive :: An optional space before the "::". """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Directive processed. Type="reStructuredText-test-directive", arguments=[], options={}, content: None <paragraph> An optional space before the "::". """], ["""\ .. reStructuredText-test-directive:: argument Paragraph. """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Directive processed. Type="reStructuredText-test-directive", arguments=['argument'], options={}, content: None <paragraph> Paragraph. """], ["""\ .. reStructuredText-test-directive:: argument :option: value Paragraph. """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Directive processed. Type="reStructuredText-test-directive", arguments=['argument'], options={'option': 'value'}, content: None <paragraph> Paragraph. """], ["""\ .. reStructuredText-test-directive:: :option: value Paragraph. """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Directive processed. Type="reStructuredText-test-directive", arguments=[], options={'option': 'value'}, content: None <paragraph> Paragraph. """], ["""\ .. reStructuredText-test-directive:: :option: Paragraph. """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "reStructuredText-test-directive" directive: invalid option value: (option: "option"; value: None) argument required but none supplied. <literal_block xml:space="preserve"> .. reStructuredText-test-directive:: :option: <paragraph> Paragraph. """], ["""\ .. reStructuredText-test-directive:: Directive block contains one paragraph, with a blank line before. Paragraph. """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Directive processed. Type="reStructuredText-test-directive", arguments=[], options={}, content: <literal_block xml:space="preserve"> Directive block contains one paragraph, with a blank line before. <paragraph> Paragraph. """], ["""\ .. reStructuredText-test-directive:: Directive block contains one paragraph, with two blank lines before. Paragraph. """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Directive processed. Type="reStructuredText-test-directive", arguments=[], options={}, content: <literal_block xml:space="preserve"> Directive block contains one paragraph, with two blank lines before. <paragraph> Paragraph. """], ["""\ .. reStructuredText-test-directive:: Directive block contains one paragraph, no blank line before. Paragraph. """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Directive processed. Type="reStructuredText-test-directive", arguments=['Directive block contains one paragraph, no blank line before.'], options={}, content: None <paragraph> Paragraph. """], ["""\ .. reStructuredText-test-directive:: block no blank line. Paragraph. """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Directive processed. Type="reStructuredText-test-directive", arguments=['block'], options={}, content: None <system_message level="2" line="3" source="test data" type="WARNING"> <paragraph> Explicit markup ends without a blank line; unexpected unindent. <paragraph> no blank line. <paragraph> Paragraph. """], ["""\ .. reStructuredText-test-directive:: argument :option: * value1 * value2 Paragraph. """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Directive processed. Type="reStructuredText-test-directive", arguments=['argument'], options={'option': '* value1\\n* value2'}, content: None <paragraph> Paragraph. """], ["""\ .. reStructuredText-test-directive:: Directive \\block \\*contains* \\\\backslashes. """, """\ <document source="test data"> <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> Directive processed. Type="reStructuredText-test-directive", arguments=[], options={}, content: <literal_block xml:space="preserve"> Directive \\block \\*contains* \\\\backslashes. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_replace.py����������������������������0000775�0001750�0001750�00000007504�11556643726�031044� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_replace.py 7021 2011-04-29 23:20:54Z grubert $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for misc.py "replace" directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['replace'] = [ ["""\ Test the |name| directive. .. |name| replace:: "**replace**" """, """\ <document source="test data"> <paragraph> Test the \n\ <substitution_reference refname="name"> name directive. <substitution_definition names="name"> " <strong> replace " """], ["""\ .. |name| replace:: paragraph 1 paragraph 2 """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "replace" directive: may contain a single paragraph only. <system_message level="2" line="1" source="test data" type="WARNING"> <paragraph> Substitution definition "name" empty or invalid. <literal_block xml:space="preserve"> .. |name| replace:: paragraph 1 paragraph 2 """], ["""\ .. |name| replace:: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Content block expected for the "replace" directive; none found. <literal_block xml:space="preserve"> replace:: <system_message level="2" line="1" source="test data" type="WARNING"> <paragraph> Substitution definition "name" empty or invalid. <literal_block xml:space="preserve"> .. |name| replace:: """], ["""\ .. |Python| replace:: Python, *the* best language around .. _Python: http://www.python.org/ I recommend you try |Python|_. """, """\ <document source="test data"> <substitution_definition names="Python"> Python, <emphasis> the best language around <target ids="python" names="python" refuri="http://www.python.org/"> <paragraph> I recommend you try <reference refname="python"> <substitution_reference refname="Python"> Python . """], ["""\ .. |name| replace:: *error in **inline ``markup """, """\ <document source="test data"> <system_message ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline emphasis start-string without end-string. <system_message ids="id3" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline strong start-string without end-string. <system_message ids="id5" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline literal start-string without end-string. <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Substitution definition contains illegal element: <literal_block xml:space="preserve"> <problematic ids="id2" refid="id1"> * <literal_block xml:space="preserve"> .. |name| replace:: *error in **inline ``markup """], ["""\ .. replace:: not valid outside of a substitution definition """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Invalid context: the "replace" directive can only be used within a substitution definition. <literal_block xml:space="preserve"> .. replace:: not valid outside of a substitution definition """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_topics.py�����������������������������0000775�0001750�0001750�00000011703�11603172505�030707� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_topics.py 7062 2011-06-30 22:14:29Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for the "topic" directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['topics'] = [ ["""\ .. topic:: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "topic" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> .. topic:: """], ["""\ .. topic:: Title """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Content block expected for the "topic" directive; none found. <literal_block xml:space="preserve"> .. topic:: Title """], ["""\ .. topic:: Title Body. """, """\ <document source="test data"> <topic> <title> Title <paragraph> Body. """], ["""\ .. topic:: With Options :class: custom :name: my point Body. """, """\ <document source="test data"> <topic classes="custom" ids="my-point" names="my\ point"> <title> With Options <paragraph> Body. """], ["""\ .. topic:: Title Body. """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "topic" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> .. topic:: \n\ Title \n\ Body. """], ["""\ .. topic:: Title Body. """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Content block expected for the "topic" directive; none found. <literal_block xml:space="preserve"> .. topic:: Title Body. """], ["""\ .. topic:: Title Body. """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "topic" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> .. topic:: \n\ Title Body. """], ["""\ .. topic:: Title .. topic:: Nested Body. """, """\ <document source="test data"> <topic> <title> Title <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> The "topic" directive may not be used within topics or body elements. <literal_block xml:space="preserve"> .. topic:: Nested \n\ Body. """], ["""\ .. topic:: Title .. topic:: Nested Body. More. """, """\ <document source="test data"> <topic> <title> Title <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> The "topic" directive may not be used within topics or body elements. <literal_block xml:space="preserve"> .. topic:: Nested \n\ Body. <system_message level="2" line="6" source="test data" type="WARNING"> <paragraph> Explicit markup ends without a blank line; unexpected unindent. <paragraph> More. """], ["""\ .. topic:: Title .. topic:: Nested Body. More. More. """, """\ <document source="test data"> <topic> <title> Title <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> The "topic" directive may not be used within topics or body elements. <literal_block xml:space="preserve"> .. topic:: Nested \n\ Body. <paragraph> More. <paragraph> More. """], ["""\ .. topic:: First Body .. topic:: Second Body. """, """\ <document source="test data"> <topic> <title> First <paragraph> Body <topic> <title> Second <paragraph> Body. """], ["""\ .. sidebar:: Title :subtitle: Outer .. topic:: Nested Body. More. More. """, """\ <document source="test data"> <sidebar> <title> Title <subtitle> Outer <topic> <title> Nested <paragraph> Body. <paragraph> More. <paragraph> More. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/include8.txt�������������������������������0000664�0001750�0001750�00000000067�07607426742�030265� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������In include8.txt .. include:: ../includes/include9.txt �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/includes/����������������������������������0000775�0001750�0001750�00000000000�12356234260�027601� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/includes/more/�����������������������������0000775�0001750�0001750�00000000000�12356234260�030543� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/includes/more/include6.txt�����������������0000664�0001750�0001750�00000000104�07607427457�033027� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������In includes/more/include6.txt .. include:: ../sibling/include7.txt ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/includes/include5.txt����������������������0000664�0001750�0001750�00000000071�07566321757�032067� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������In includes/include5.txt .. include:: more/include6.txt �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/includes/include4.txt����������������������0000664�0001750�0001750�00000000064�07566321757�032070� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������In includes/include4.txt .. include:: include5.txt ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/includes/sibling/��������������������������0000775�0001750�0001750�00000000000�12356234260�031230� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/includes/sibling/include7.txt��������������0000664�0001750�0001750�00000000041�07607426742�033511� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������In includes/sibling/include7.txt �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_math.py�������������������������������0000664�0001750�0001750�00000002720�11603172505�030333� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_math.py 7062 2011-06-30 22:14:29Z milde $ # Author: Guenter Milde <milde@users.sf.net> # Copyright: This module has been placed in the public domain. """ Tests for the 'math' directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['argument'] = [ ["""\ .. math:: y = f(x) """, """\ <document source="test data"> <math_block xml:space="preserve"> y = f(x) """], ] totest['content'] = [ ["""\ .. math:: 1+1=2 """, """\ <document source="test data"> <math_block xml:space="preserve"> 1+1=2 """], ] totest['options'] = [ ["""\ .. math:: :class: new :name: eq:Eulers law e^i*2*\pi = 1 """, """\ <document source="test data"> <math_block classes="new" ids="eq-eulers-law" names="eq:eulers\ law" xml:space="preserve"> e^i*2*\pi = 1 """], ] totest['argument_and_content'] = [ ["""\ .. math:: y = f(x) 1+1=2 """, """\ <document source="test data"> <math_block xml:space="preserve"> y = f(x) <math_block xml:space="preserve"> 1+1=2 """], ] totest['content with blank line'] = [ ["""\ .. math:: 1+1=2 E = mc^2 """, """\ <document source="test data"> <math_block xml:space="preserve"> 1+1=2 <math_block xml:space="preserve"> E = mc^2 """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_rubrics.py����������������������������0000775�0001750�0001750�00000003346�11603172505�031063� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_rubrics.py 7062 2011-06-30 22:14:29Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for the "rubric" directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['rubrics'] = [ ["""\ .. rubric:: This is a rubric """, """\ <document source="test data"> <rubric> This is a rubric """], ["""\ .. rubric:: .. rubric:: A rubric has no content Invalid content """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "rubric" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> .. rubric:: <system_message level="3" line="2" source="test data" type="ERROR"> <paragraph> Error in "rubric" directive: no content permitted. <literal_block xml:space="preserve"> .. rubric:: A rubric has no content \n\ Invalid content """], ["""\ .. rubric:: A rubric followed by a block quote .. Block quote """, """\ <document source="test data"> <rubric> A rubric followed by a block quote <comment xml:space="preserve"> <block_quote> <paragraph> Block quote """], ["""\ .. rubric:: A Rubric :class: foo bar :name: Foo Rubric """, """\ <document source="test data"> <rubric classes="foo bar" ids="foo-rubric" names="foo\ rubric"> A Rubric """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/include3.txt�������������������������������0000664�0001750�0001750�00000000064�07566322044�030247� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������In include3.txt .. include:: includes/include4.txt ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_replace_fr.py�������������������������0000664�0001750�0001750�00000003320�11556643726�031520� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_replace.py 4667 2006-07-12 21:40:56Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for misc.py "replace" directive. Test in french (not default/fallback language). """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite(suite_settings={'language_code':'fr'}) s.generateTests(totest) return s totest = {} totest['replace'] = [ ["""\ Test directive containing french role exposant (superscript). .. |Na+| remplace:: Na\ :exp:`+` Le |Na+| est l'ion sodium. """, """\ <document source="test data"> <paragraph> Test directive containing french role exposant (superscript). <substitution_definition names="Na+"> Na <superscript> + <paragraph> Le \n\ <substitution_reference refname="Na+"> Na+ est l\'ion sodium. """], ["""\ Test directive containing english role superscript. .. |Na+| remplace:: Na\ :sup:`+` Le |Na+| est l'ion sodium. """, """\ <document source="test data"> <paragraph> Test directive containing english role superscript. <system_message level="1" line="3" source="test data" type="INFO"> <paragraph> No role entry for "sup" in module "docutils.parsers.rst.languages.fr". Using English fallback for role "sup". <substitution_definition names="Na+"> Na <superscript> + <paragraph> Le \n\ <substitution_reference refname="Na+"> Na+ est l\'ion sodium."""], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_directives/test_line_blocks.py������������������������0000775�0001750�0001750�00000004045�11603172505�031673� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_line_blocks.py 7062 2011-06-30 22:14:29Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for the body.py 'line-block' directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['line_blocks'] = [ ["""\ .. line-block:: This is a line block. Newlines are *preserved*. As is initial whitespace. """, """\ <document source="test data"> <line_block> <line> This is a line block. <line> Newlines are \n\ <emphasis> preserved . <line_block> <line> As is initial whitespace. """], ["""\ .. line-block:: :class: linear :name: cit:short This is a line block with options. """, """\ <document source="test data"> <line_block classes="linear" ids="cit-short" names="cit:short"> <line> This is a line block with options. """], ["""\ .. line-block:: Inline markup *may not span multiple lines* of a line block. """, """\ <document source="test data"> <line_block> <line> Inline markup \n\ <problematic ids="id2" refid="id1"> * may not span <line_block> <line> multiple lines* of a line block. <system_message backrefs="id2" ids="id1" level="2" line="3" source="test data" type="WARNING"> <paragraph> Inline emphasis start-string without end-string. """], ["""\ .. line-block:: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Content block expected for the "line-block" directive; none found. <literal_block xml:space="preserve"> .. line-block:: """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_paragraphs.py�����������������������������������������0000775�0001750�0001750�00000002461�10434150472�026337� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_paragraphs.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['paragraphs'] = [ ["""\ A paragraph. """, """\ <document source="test data"> <paragraph> A paragraph. """], ["""\ Paragraph 1. Paragraph 2. """, """\ <document source="test data"> <paragraph> Paragraph 1. <paragraph> Paragraph 2. """], ["""\ Line 1. Line 2. Line 3. """, """\ <document source="test data"> <paragraph> Line 1. Line 2. Line 3. """], ["""\ Paragraph 1, Line 1. Line 2. Line 3. Paragraph 2, Line 1. Line 2. Line 3. """, """\ <document source="test data"> <paragraph> Paragraph 1, Line 1. Line 2. Line 3. <paragraph> Paragraph 2, Line 1. Line 2. Line 3. """], ["""\ A. Einstein was a really smart dude. """, """\ <document source="test data"> <paragraph> A. Einstein was a really smart dude. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_functions.py������������������������������������������0000775�0001750�0001750�00000002021�11712713765�026221� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_functions.py 7337 2012-02-03 08:16:53Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ import unittest from __init__ import DocutilsTestSupport states = DocutilsTestSupport.states class FuctionTests(unittest.TestCase): escaped = r'escapes: \*one, \\*two, \\\*three' nulled = 'escapes: \x00*one, \x00\\*two, \x00\\\x00*three' unescaped = r'escapes: *one, \*two, \*three' def test_escape2null(self): nulled = states.escape2null(self.escaped) self.assertEqual(nulled, self.nulled) nulled = states.escape2null(self.escaped + '\\') self.assertEqual(nulled, self.nulled + '\x00') def test_unescape(self): unescaped = states.unescape(self.nulled) self.assertEqual(unescaped, self.unescaped) restored = states.unescape(self.nulled, 1) self.assertEqual(restored, self.escaped) if __name__ == '__main__': unittest.main() ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_block_quotes.py���������������������������������������0000775�0001750�0001750�00000015011�10434150472�026674� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_block_quotes.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['block_quotes'] = [ ["""\ Line 1. Line 2. Indented. """, """\ <document source="test data"> <paragraph> Line 1. Line 2. <block_quote> <paragraph> Indented. """], ["""\ Line 1. Line 2. Indented 1. Indented 2. """, """\ <document source="test data"> <paragraph> Line 1. Line 2. <block_quote> <paragraph> Indented 1. <block_quote> <paragraph> Indented 2. """], ["""\ Line 1. Line 2. Unexpectedly indented. """, """\ <document source="test data"> <paragraph> Line 1. Line 2. <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> Unexpected indentation. <block_quote> <paragraph> Unexpectedly indented. """], ["""\ Line 1. Line 2. Indented. no blank line """, """\ <document source="test data"> <paragraph> Line 1. Line 2. <block_quote> <paragraph> Indented. <system_message level="2" line="5" source="test data" type="WARNING"> <paragraph> Block quote ends without a blank line; unexpected unindent. <paragraph> no blank line """], ["""\ Here is a paragraph. Indent 8 spaces. Indent 4 spaces. Is this correct? Should it generate a warning? Yes, it is correct, no warning necessary. """, """\ <document source="test data"> <paragraph> Here is a paragraph. <block_quote> <block_quote> <paragraph> Indent 8 spaces. <paragraph> Indent 4 spaces. <paragraph> Is this correct? Should it generate a warning? Yes, it is correct, no warning necessary. """], ["""\ Paragraph. Block quote. -- Attribution Paragraph. Block quote. --Attribution """, """\ <document source="test data"> <paragraph> Paragraph. <block_quote> <paragraph> Block quote. <attribution> Attribution <paragraph> Paragraph. <block_quote> <paragraph> Block quote. <attribution> Attribution """], [u"""\ Alternative: true em-dash. Block quote. \u2014 Attribution Alternative: three hyphens. Block quote. --- Attribution """, """\ <document source="test data"> <paragraph> Alternative: true em-dash. <block_quote> <paragraph> Block quote. <attribution> Attribution <paragraph> Alternative: three hyphens. <block_quote> <paragraph> Block quote. <attribution> Attribution """], ["""\ Paragraph. Block quote. -- Attribution line one and line two Paragraph. Block quote. -- Attribution line one and line two Paragraph. """, """\ <document source="test data"> <paragraph> Paragraph. <block_quote> <paragraph> Block quote. <attribution> Attribution line one and line two <paragraph> Paragraph. <block_quote> <paragraph> Block quote. <attribution> Attribution line one and line two <paragraph> Paragraph. """], ["""\ Paragraph. Block quote 1. -- Attribution 1 Block quote 2. --Attribution 2 """, """\ <document source="test data"> <paragraph> Paragraph. <block_quote> <paragraph> Block quote 1. <attribution> Attribution 1 <block_quote> <paragraph> Block quote 2. <attribution> Attribution 2 """], ["""\ Paragraph. Block quote 1. -- Attribution 1 Block quote 2. """, """\ <document source="test data"> <paragraph> Paragraph. <block_quote> <paragraph> Block quote 1. <attribution> Attribution 1 <block_quote> <paragraph> Block quote 2. """], ["""\ Unindented paragraph. Block quote 1. -- Attribution 1 Block quote 2. .. Block quote 3. """, """\ <document source="test data"> <paragraph> Unindented paragraph. <block_quote> <paragraph> Block quote 1. <attribution> Attribution 1 <block_quote> <paragraph> Block quote 2. <comment xml:space="preserve"> <block_quote> <paragraph> Block quote 3. """], ["""\ Paragraph. -- Not an attribution Paragraph. Block quote. \-- Not an attribution Paragraph. Block quote. -- Not an attribution line one and line two and line three """, """\ <document source="test data"> <paragraph> Paragraph. <block_quote> <paragraph> -- Not an attribution <paragraph> Paragraph. <block_quote> <paragraph> Block quote. <paragraph> -- Not an attribution <paragraph> Paragraph. <block_quote> <paragraph> Block quote. <definition_list> <definition_list_item> <term> -- Not an attribution line one <definition> <definition_list> <definition_list_item> <term> and line two <definition> <paragraph> and line three """], ["""\ Paragraph. -- Not a valid attribution Block quote 1. --Attribution 1 --Invalid attribution Block quote 2. --Attribution 2 """, """\ <document source="test data"> <paragraph> Paragraph. <block_quote> <paragraph> -- Not a valid attribution <paragraph> Block quote 1. <attribution> Attribution 1 <block_quote> <paragraph> --Invalid attribution <paragraph> Block quote 2. <attribution> Attribution 2 """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_field_lists.py����������������������������������������0000775�0001750�0001750�00000032205�10434150472�026507� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_field_lists.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['field_lists'] = [ ["""\ One-liners: :Author: Me :Version: 1 :Date: 2001-08-11 :Parameter i: integer """, """\ <document source="test data"> <paragraph> One-liners: <field_list> <field> <field_name> Author <field_body> <paragraph> Me <field> <field_name> Version <field_body> <paragraph> 1 <field> <field_name> Date <field_body> <paragraph> 2001-08-11 <field> <field_name> Parameter i <field_body> <paragraph> integer """], ["""\ One-liners, no blank lines: :Author: Me :Version: 1 :Date: 2001-08-11 :Parameter i: integer """, """\ <document source="test data"> <paragraph> One-liners, no blank lines: <field_list> <field> <field_name> Author <field_body> <paragraph> Me <field> <field_name> Version <field_body> <paragraph> 1 <field> <field_name> Date <field_body> <paragraph> 2001-08-11 <field> <field_name> Parameter i <field_body> <paragraph> integer """], ["""\ :field: empty item above, no blank line """, """\ <document source="test data"> <field_list> <field> <field_name> field <field_body> <system_message level="2" line="2" source="test data" type="WARNING"> <paragraph> Field list ends without a blank line; unexpected unindent. <paragraph> empty item above, no blank line """], ["""\ Field bodies starting on the next line: :Author: Me :Version: 1 :Date: 2001-08-11 :Parameter i: integer """, """\ <document source="test data"> <paragraph> Field bodies starting on the next line: <field_list> <field> <field_name> Author <field_body> <paragraph> Me <field> <field_name> Version <field_body> <paragraph> 1 <field> <field_name> Date <field_body> <paragraph> 2001-08-11 <field> <field_name> Parameter i <field_body> <paragraph> integer """], ["""\ One-paragraph, multi-liners: :Authors: Me, Myself, and I :Version: 1 or so :Date: 2001-08-11 (Saturday) :Parameter i: counter (integer) """, """\ <document source="test data"> <paragraph> One-paragraph, multi-liners: <field_list> <field> <field_name> Authors <field_body> <paragraph> Me, Myself, and I <field> <field_name> Version <field_body> <paragraph> 1 or so <field> <field_name> Date <field_body> <paragraph> 2001-08-11 (Saturday) <field> <field_name> Parameter i <field_body> <paragraph> counter (integer) """], ["""\ One-paragraph, multi-liners, not lined up: :Authors: Me, Myself, and I :Version: 1 or so :Date: 2001-08-11 (Saturday) :Parameter i: counter (integer) """, """\ <document source="test data"> <paragraph> One-paragraph, multi-liners, not lined up: <field_list> <field> <field_name> Authors <field_body> <paragraph> Me, Myself, and I <field> <field_name> Version <field_body> <paragraph> 1 or so <field> <field_name> Date <field_body> <paragraph> 2001-08-11 (Saturday) <field> <field_name> Parameter i <field_body> <paragraph> counter (integer) """], ["""\ Multiple body elements: :Authors: - Me - Myself - I :Abstract: This is a field list item's body, containing multiple elements. Here's a literal block:: def f(x): return x**2 + x Even nested field lists are possible: :Date: 2001-08-11 :Day: Saturday :Time: 15:07 """, """\ <document source="test data"> <paragraph> Multiple body elements: <field_list> <field> <field_name> Authors <field_body> <bullet_list bullet="-"> <list_item> <paragraph> Me <list_item> <paragraph> Myself <list_item> <paragraph> I <field> <field_name> Abstract <field_body> <paragraph> This is a field list item's body, containing multiple elements. <paragraph> Here's a literal block: <literal_block xml:space="preserve"> def f(x): return x**2 + x <paragraph> Even nested field lists are possible: <field_list> <field> <field_name> Date <field_body> <paragraph> 2001-08-11 <field> <field_name> Day <field_body> <paragraph> Saturday <field> <field_name> Time <field_body> <paragraph> 15:07 """], ["""\ Nested field lists on one line: :field1: :field2: :field3: body :field4: :field5: :field6: body :field7: body :field8: body :field9: body line 1 body line 2 """, """\ <document source="test data"> <paragraph> Nested field lists on one line: <field_list> <field> <field_name> field1 <field_body> <field_list> <field> <field_name> field2 <field_body> <field_list> <field> <field_name> field3 <field_body> <paragraph> body <field> <field_name> field4 <field_body> <field_list> <field> <field_name> field5 <field_body> <field_list> <field> <field_name> field6 <field_body> <paragraph> body <field> <field_name> field7 <field_body> <paragraph> body <field> <field_name> field8 <field_body> <paragraph> body <field> <field_name> field9 <field_body> <paragraph> body line 1 body line 2 """], ["""\ :Parameter i j k: multiple arguments """, """\ <document source="test data"> <field_list> <field> <field_name> Parameter i j k <field_body> <paragraph> multiple arguments """], ["""\ :Field *name* `with` **inline** ``markup``: inline markup in field name is parsed. """, """\ <document source="test data"> <field_list> <field> <field_name> Field \n\ <emphasis> name \n\ <title_reference> with \n\ <strong> inline \n\ <literal> markup <field_body> <paragraph> inline markup in field name is parsed. """], ["""\ :Field name with *bad inline markup: should generate warning. """, """\ <document source="test data"> <field_list> <field> <field_name> Field name with \n\ <problematic ids="id2" refid="id1"> * bad inline markup <field_body> <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline emphasis start-string without end-string. <paragraph> should generate warning. """], [r"""Some edge cases: :Empty: :Author: Me No blank line before this paragraph. : Field: marker must not begin with whitespace. :Field : marker must not end with whitespace. Field: marker is missing its open-colon. :Field marker is missing its close-colon. :Field\: names\: with\: colons\:: are possible. :\\Field\ names with backslashes\\: are possible, too. :\\: A backslash. :Not a\\\: field list. :Not a \: field list either. :\: Not a field list either. :\: A definition list, not a field list. """, """\ <document source="test data"> <paragraph> Some edge cases: <field_list> <field> <field_name> Empty <field_body> <field> <field_name> Author <field_body> <paragraph> Me <system_message level="2" line="5" source="test data" type="WARNING"> <paragraph> Field list ends without a blank line; unexpected unindent. <paragraph> No blank line before this paragraph. <paragraph> : Field: marker must not begin with whitespace. <paragraph> :Field : marker must not end with whitespace. <paragraph> Field: marker is missing its open-colon. <paragraph> :Field marker is missing its close-colon. <field_list> <field> <field_name> Field: names: with: colons: <field_body> <paragraph> are possible. <field> <field_name> \\Field names with backslashes\\ <field_body> <paragraph> are possible, too. <field> <field_name> \\ <field_body> <paragraph> A backslash. <paragraph> :Not a\\: field list. <paragraph> :Not a : field list either. <paragraph> :: Not a field list either. <definition_list> <definition_list_item> <term> :: <definition> <paragraph> A definition list, not a field list. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_targets.py��������������������������������������������0000775�0001750�0001750�00000032705�11603172505�025664� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_targets.py 7062 2011-06-30 22:14:29Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['targets'] = [ ["""\ .. _target: (Internal hyperlink target.) """, """\ <document source="test data"> <target ids="target" names="target"> <paragraph> (Internal hyperlink target.) """], ["""\ .. _optional space before colon : """, """\ <document source="test data"> <target ids="optional-space-before-colon" names="optional\ space\ before\ colon"> """], ["""\ External hyperlink targets: .. _one-liner: http://structuredtext.sourceforge.net .. _starts-on-this-line: http:// structuredtext. sourceforge.net .. _entirely-below: http://structuredtext. sourceforge.net .. _not-indirect: uri\\_ """, """\ <document source="test data"> <paragraph> External hyperlink targets: <target ids="one-liner" names="one-liner" refuri="http://structuredtext.sourceforge.net"> <target ids="starts-on-this-line" names="starts-on-this-line" refuri="http://structuredtext.sourceforge.net"> <target ids="entirely-below" names="entirely-below" refuri="http://structuredtext.sourceforge.net"> <target ids="not-indirect" names="not-indirect" refuri="uri_"> """], ["""\ Indirect hyperlink targets: .. _target1: reference_ .. _target2: `phrase-link reference`_ """, """\ <document source="test data"> <paragraph> Indirect hyperlink targets: <target ids="target1" names="target1" refname="reference"> <target ids="target2" names="target2" refname="phrase-link reference"> """], ["""\ .. _a long target name: .. _`a target name: including a colon (quoted)`: .. _a target name\: including a colon (escaped): """, """\ <document source="test data"> <target ids="a-long-target-name" names="a\ long\ target\ name"> <target ids="a-target-name-including-a-colon-quoted" names="a\ target\ name:\ including\ a\ colon\ (quoted)"> <target ids="a-target-name-including-a-colon-escaped" names="a\ target\ name:\ including\ a\ colon\ (escaped)"> """], ["""\ .. _`target: No matching backquote. .. _`: No matching backquote either. """, """\ <document source="test data"> <comment xml:space="preserve"> _`target: No matching backquote. <system_message level="2" line="1" source="test data" type="WARNING"> <paragraph> malformed hyperlink target. <comment xml:space="preserve"> _`: No matching backquote either. <system_message level="2" line="2" source="test data" type="WARNING"> <paragraph> malformed hyperlink target. """], ["""\ .. _a very long target name, split across lines: .. _`and another, with backquotes`: """, """\ <document source="test data"> <target ids="a-very-long-target-name-split-across-lines" names="a\ very\ long\ target\ name,\ split\ across\ lines"> <target ids="and-another-with-backquotes" names="and\ another,\ with\ backquotes"> """], ["""\ External hyperlink: .. _target: http://www.python.org/ """, """\ <document source="test data"> <paragraph> External hyperlink: <target ids="target" names="target" refuri="http://www.python.org/"> """], ["""\ .. _email: jdoe@example.com .. _multi-line email: jdoe @example.com """, """\ <document source="test data"> <target ids="email" names="email" refuri="mailto:jdoe@example.com"> <target ids="multi-line-email" names="multi-line\ email" refuri="mailto:jdoe@example.com"> """], ["""\ Malformed target: .. __malformed: no good Target beginning with an underscore: .. _`_target`: OK """, """\ <document source="test data"> <paragraph> Malformed target: <comment xml:space="preserve"> __malformed: no good <system_message level="2" line="3" source="test data" type="WARNING"> <paragraph> malformed hyperlink target. <paragraph> Target beginning with an underscore: <target ids="target" names="_target" refuri="OK"> """], ["""\ Duplicate external targets (different URIs): .. _target: first .. _target: second """, """\ <document source="test data"> <paragraph> Duplicate external targets (different URIs): <target dupnames="target" ids="target" refuri="first"> <system_message backrefs="id1" level="2" line="5" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "target". <target dupnames="target" ids="id1" refuri="second"> """], ["""\ Duplicate external targets (same URIs): .. _target: first .. _target: first """, """\ <document source="test data"> <paragraph> Duplicate external targets (same URIs): <target ids="target" names="target" refuri="first"> <system_message backrefs="id1" level="1" line="5" source="test data" type="INFO"> <paragraph> Duplicate explicit target name: "target". <target dupnames="target" ids="id1" refuri="first"> """], ["""\ Duplicate implicit targets. Title ===== Paragraph. Title ===== Paragraph. """, """\ <document source="test data"> <paragraph> Duplicate implicit targets. <section dupnames="title" ids="title"> <title> Title <paragraph> Paragraph. <section dupnames="title" ids="id1"> <title> Title <system_message backrefs="id1" level="1" line="9" source="test data" type="INFO"> <paragraph> Duplicate implicit target name: "title". <paragraph> Paragraph. """], ["""\ Duplicate implicit/explicit targets. Title ===== .. _title: Paragraph. """, """\ <document source="test data"> <paragraph> Duplicate implicit/explicit targets. <section dupnames="title" ids="title"> <title> Title <system_message backrefs="id1" level="1" line="6" source="test data" type="INFO"> <paragraph> Duplicate implicit target name: "title". <target ids="id1" names="title"> <paragraph> Paragraph. """], ["""\ Duplicate implicit/directive targets. Title ===== .. target-notes:: :name: title """, """\ <document source="test data"> <paragraph> Duplicate implicit/directive targets. <section dupnames="title" ids="title"> <title> Title <pending ids="id1" names="title"> <system_message backrefs="id1" level="1" line="4" source="test data" type="INFO"> <paragraph> Duplicate implicit target name: "title". .. internal attributes: .transform: docutils.transforms.references.TargetNotes .details: """], ["""\ Duplicate explicit targets. .. _title: First. .. _title: Second. .. _title: Third. """, """\ <document source="test data"> <paragraph> Duplicate explicit targets. <target dupnames="title" ids="title"> <paragraph> First. <system_message backrefs="id1" level="2" line="7" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "title". <target dupnames="title" ids="id1"> <paragraph> Second. <system_message backrefs="id2" level="2" line="11" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "title". <target dupnames="title" ids="id2"> <paragraph> Third. """], ["""\ Duplicate explicit/directive targets. .. _title: First. .. rubric:: this is a title too :name: title """, """\ <document source="test data"> <paragraph> Duplicate explicit/directive targets. <target dupnames="title" ids="title"> <paragraph> First. <rubric dupnames="title" ids="id1"> this is a title too <system_message backrefs="id1" level="2" line="9" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "title". """], ["""\ Duplicate targets: Target ====== Implicit section header target. .. [TARGET] Citation target. .. [#target] Autonumber-labeled footnote target. .. _target: Explicit internal target. .. _target: Explicit_external_target .. rubric:: directive with target :name: Target """, """\ <document source="test data"> <paragraph> Duplicate targets: <section dupnames="target" ids="target"> <title> Target <paragraph> Implicit section header target. <citation dupnames="target" ids="id1"> <label> TARGET <system_message backrefs="id1" level="1" line="8" source="test data" type="INFO"> <paragraph> Duplicate implicit target name: "target". <paragraph> Citation target. <footnote auto="1" dupnames="target" ids="id2"> <system_message backrefs="id2" level="2" line="10" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "target". <paragraph> Autonumber-labeled footnote target. <system_message backrefs="id3" level="2" line="12" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "target". <target dupnames="target" ids="id3"> <paragraph> Explicit internal target. <system_message backrefs="id4" level="2" line="16" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "target". <target dupnames="target" ids="id4" refuri="Explicit_external_target"> <rubric dupnames="target" ids="id5"> directive with target <system_message backrefs="id5" level="2" line="4" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "target". """], ["""\ .. _unescaped colon at end:: no good .. _:: no good either .. _escaped colon\:: OK .. _`unescaped colon, quoted:`: OK """, """\ <document source="test data"> <comment xml:space="preserve"> _unescaped colon at end:: no good <system_message level="2" line="1" source="test data" type="WARNING"> <paragraph> malformed hyperlink target. <comment xml:space="preserve"> _:: no good either <system_message level="2" line="3" source="test data" type="WARNING"> <paragraph> malformed hyperlink target. <target ids="escaped-colon" names="escaped\ colon:" refuri="OK"> <target ids="unescaped-colon-quoted" names="unescaped\ colon,\ quoted:" refuri="OK"> """], ] totest['anonymous_targets'] = [ ["""\ Anonymous external hyperlink target: .. __: http://w3c.org/ """, """\ <document source="test data"> <paragraph> Anonymous external hyperlink target: <target anonymous="1" ids="id1" refuri="http://w3c.org/"> """], ["""\ Anonymous external hyperlink target: __ http://w3c.org/ """, """\ <document source="test data"> <paragraph> Anonymous external hyperlink target: <target anonymous="1" ids="id1" refuri="http://w3c.org/"> """], ["""\ Anonymous indirect hyperlink target: .. __: reference_ """, """\ <document source="test data"> <paragraph> Anonymous indirect hyperlink target: <target anonymous="1" ids="id1" refname="reference"> """], ["""\ Anonymous external hyperlink target, not indirect: __ uri\\_ __ this URI ends with an underscore_ """, """\ <document source="test data"> <paragraph> Anonymous external hyperlink target, not indirect: <target anonymous="1" ids="id1" refuri="uri_"> <target anonymous="1" ids="id2" refuri="thisURIendswithanunderscore_"> """], ["""\ Anonymous indirect hyperlink targets: __ reference_ __ `a very long reference`_ """, """\ <document source="test data"> <paragraph> Anonymous indirect hyperlink targets: <target anonymous="1" ids="id1" refname="reference"> <target anonymous="1" ids="id2" refname="a very long reference"> """], ["""\ Mixed anonymous & named indirect hyperlink targets: __ reference_ .. __: reference_ __ reference_ .. _target1: reference_ no blank line .. _target2: reference_ __ reference_ .. __: reference_ __ reference_ no blank line """, """\ <document source="test data"> <paragraph> Mixed anonymous & named indirect hyperlink targets: <target anonymous="1" ids="id1" refname="reference"> <target anonymous="1" ids="id2" refname="reference"> <target anonymous="1" ids="id3" refname="reference"> <target ids="target1" names="target1" refname="reference"> <system_message level="2" line="7" source="test data" type="WARNING"> <paragraph> Explicit markup ends without a blank line; unexpected unindent. <paragraph> no blank line <target ids="target2" names="target2" refname="reference"> <target anonymous="1" ids="id4" refname="reference"> <target anonymous="1" ids="id5" refname="reference"> <target anonymous="1" ids="id6" refname="reference"> <system_message level="2" line="13" source="test data" type="WARNING"> <paragraph> Explicit markup ends without a blank line; unexpected unindent. <paragraph> no blank line """], ["""\ .. _ """, """\ <document source="test data"> <comment xml:space="preserve"> _ """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �����������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_interpreted.py����������������������������������������0000775�0001750�0001750�00000024134�12024637300�026532� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_interpreted.py 7514 2012-09-14 14:27:12Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for interpreted text in docutils/parsers/rst/states.py. """ from __init__ import DocutilsTestSupport from docutils.utils.code_analyzer import with_pygments def suite(): s = DocutilsTestSupport.ParserTestSuite() if not with_pygments: del(totest['code-parsing']) s.generateTests(totest) return s totest = {} totest['basics'] = [ ["""\ `interpreted` """, """\ <document source="test data"> <paragraph> <title_reference> interpreted """], ["""\ :title:`interpreted` """, """\ <document source="test data"> <paragraph> <title_reference> interpreted """], ["""\ `interpreted`:title: """, """\ <document source="test data"> <paragraph> <title_reference> interpreted """], ["""\ `interpreted \`title`` """, """\ <document source="test data"> <paragraph> <title_reference> interpreted `title` """], ["""\ :title:`:not-role: interpreted` """, """\ <document source="test data"> <paragraph> <title_reference> :not-role: interpreted """], ["""\ `interpreted` but not \\`interpreted` [`] or ({[`] or [`]}) or ` """, """\ <document source="test data"> <paragraph> <title_reference> interpreted but not `interpreted` [`] or ({[`] or [`]}) or ` """], ["""\ `interpreted`-text `interpreted`: text `interpreted`:text `text`'s interpreted """, """\ <document source="test data"> <paragraph> <title_reference> interpreted -text \n\ <title_reference> interpreted : text \n\ <title_reference> interpreted :text \n\ <title_reference> text 's interpreted """], ["""\ `interpreted without closing backquote """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> ` interpreted without closing backquote <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline interpreted text or phrase reference start-string without end-string. """], ["""\ `interpreted`:not a role if it contains whitespace: """, """\ <document source="test data"> <paragraph> <title_reference> interpreted :not a role if it contains whitespace: """], ["""\ :title:`` (empty interpteted text not recognized) """, """\ <document source="test data"> <paragraph> :title:`` (empty interpteted text not recognized) """], ["""\ :title:`\ ` (interpteted text containing empty string) """, """\ <document source="test data"> <paragraph> <title_reference> (interpteted text containing empty string) """], ["""\ `\ `:title: (interpteted text containing empty string (postfix)) """, """\ <document source="test data"> <paragraph> <title_reference> (interpteted text containing empty string (postfix)) """], ["""\ :title:`\ non-empty` """, """\ <document source="test data"> <paragraph> <title_reference> non-empty """], ["""\ :title:`\ ` (trailing unquoted space) """, """\ <document source="test data"> <paragraph> :title: <problematic ids="id2" refid="id1"> ` ` (trailing unquoted space) <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline interpreted text or phrase reference start-string without end-string. """], ["""\ Explicit roles for standard inline markup: :emphasis:`emphasis`, :strong:`strong`, :literal:`inline literal text`. """, """\ <document source="test data"> <paragraph> Explicit roles for standard inline markup: <emphasis> emphasis , <strong> strong , <literal> inline literal text . """], ["""\ Simple explicit roles: :ab:`abbreviation`, :ac:`acronym`, :sup:`superscript`, :sub:`subscript`, :title:`title reference`. """, """\ <document source="test data"> <paragraph> Simple explicit roles: <abbreviation> abbreviation , <acronym> acronym , <superscript> superscript , <subscript> subscript , <title_reference> title reference . """], ] totest['code'] = [ ["""\ Code role for inline code snippets: :code:`$\alpha = \int_0^\infty f(x) dx$`. """, """\ <document source="test data"> <paragraph> Code role for inline code snippets: <literal classes="code"> $\x07lpha = \\int_0^\\infty f(x) dx$ . """], ] totest['code-parsing'] = [ ["""\ .. role:: tex(code) :language: latex Custom role based on code role: :tex:`$\alpha = f(x)$`. """, """\ <document source="test data"> <paragraph> Custom role based on code role: <literal classes="code tex latex"> <inline classes="literal string"> $ <inline classes="name builtin"> \x07lpha \n\ <inline classes="operator"> = <inline classes="name builtin"> f <inline classes="operator"> ( <inline classes="name builtin"> x <inline classes="operator"> ) <inline classes="literal string"> $ . """], ["""\ Custom role based on code role: .. role:: python(code) :language: python :class: testclass Python code :python:`print("The end")`. """, """\ <document source="test data"> <paragraph> Custom role based on code role: <paragraph> Python code \n\ <literal classes="code testclass python"> <inline classes="keyword"> print <inline classes="punctuation"> ( <inline classes="literal string"> "The end" <inline classes="punctuation"> ) . """], ] totest['references'] = [ ["""\ :PEP:`0` """, """\ <document source="test data"> <paragraph> <reference refuri="http://www.python.org/dev/peps/pep-0000"> PEP 0 """], ["""\ :PEP:`-1` """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> :PEP:`-1` <system_message backrefs="id2" ids="id1" level="3" line="1" source="test data" type="ERROR"> <paragraph> PEP number must be a number from 0 to 9999; "-1" is invalid. """], ["""\ :RFC:`2822` """, """\ <document source="test data"> <paragraph> <reference refuri="http://www.faqs.org/rfcs/rfc2822.html"> RFC 2822 """], ["""\ :RFC:`0` """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> :RFC:`0` <system_message backrefs="id2" ids="id1" level="3" line="1" source="test data" type="ERROR"> <paragraph> RFC number must be a number greater than or equal to 1; "0" is invalid. """], ] totest['unknown_roles'] = [ ["""\ :role:`interpreted` """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> :role:`interpreted` <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> No role entry for "role" in module "docutils.parsers.rst.languages.en". Trying "role" as canonical role name. <system_message backrefs="id2" ids="id1" level="3" line="1" source="test data" type="ERROR"> <paragraph> Unknown interpreted text role "role". """], ["""\ `interpreted`:role: """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> `interpreted`:role: <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> No role entry for "role" in module "docutils.parsers.rst.languages.en". Trying "role" as canonical role name. <system_message backrefs="id2" ids="id1" level="3" line="1" source="test data" type="ERROR"> <paragraph> Unknown interpreted text role "role". """], ["""\ :role:`interpreted`:role: """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> :role:`interpreted`:role: <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Multiple roles in interpreted text (both prefix and suffix present; only one allowed). """], ["""\ :very.long-role_name:`interpreted` """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> :very.long-role_name:`interpreted` <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> No role entry for "very.long-role_name" in module "docutils.parsers.rst.languages.en". Trying "very.long-role_name" as canonical role name. <system_message backrefs="id2" ids="id1" level="3" line="1" source="test data" type="ERROR"> <paragraph> Unknown interpreted text role "very.long-role_name". """], ["""\ :restructuredtext-unimplemented-role:`interpreted` """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> :restructuredtext-unimplemented-role:`interpreted` <system_message level="1" line="1" source="test data" type="INFO"> <paragraph> No role entry for "restructuredtext-unimplemented-role" in module "docutils.parsers.rst.languages.en". Trying "restructuredtext-unimplemented-role" as canonical role name. <system_message backrefs="id2" ids="id1" level="3" line="1" source="test data" type="ERROR"> <paragraph> Interpreted text role "restructuredtext-unimplemented-role" not implemented. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_literal_blocks.py�������������������������������������0000775�0001750�0001750�00000015421�10434150472�027200� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_literal_blocks.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['indented_literal_blocks'] = [ ["""\ A paragraph:: A literal block. """, """\ <document source="test data"> <paragraph> A paragraph: <literal_block xml:space="preserve"> A literal block. """], ["""\ A paragraph with a space after the colons:: \n\ A literal block. """, """\ <document source="test data"> <paragraph> A paragraph with a space after the colons: <literal_block xml:space="preserve"> A literal block. """], ["""\ A paragraph:: A literal block. Another paragraph:: Another literal block. With two blank lines following. A final paragraph. """, """\ <document source="test data"> <paragraph> A paragraph: <literal_block xml:space="preserve"> A literal block. <paragraph> Another paragraph: <literal_block xml:space="preserve"> Another literal block. With two blank lines following. <paragraph> A final paragraph. """], ["""\ A paragraph on more than one line:: A literal block. """, """\ <document source="test data"> <paragraph> A paragraph on more than one line: <literal_block xml:space="preserve"> A literal block. """], ["""\ A paragraph on more than one line:: A literal block with no blank line above. """, """\ <document source="test data"> <paragraph> A paragraph on more than one line: <system_message level="3" line="4" source="test data" type="ERROR"> <paragraph> Unexpected indentation. <literal_block xml:space="preserve"> A literal block with no blank line above. """], ["""\ A paragraph:: A literal block. no blank line """, """\ <document source="test data"> <paragraph> A paragraph: <literal_block xml:space="preserve"> A literal block. <system_message level="2" line="4" source="test data" type="WARNING"> <paragraph> Literal block ends without a blank line; unexpected unindent. <paragraph> no blank line """], [r""" A paragraph\\:: A literal block. A paragraph\:: Not a literal block. """, r"""<document source="test data"> <paragraph> A paragraph\: <literal_block xml:space="preserve"> A literal block. <paragraph> A paragraph:: <block_quote> <paragraph> Not a literal block. """], [r""" \\:: A literal block. \:: Not a literal block. """, r"""<document source="test data"> <paragraph> \: <literal_block xml:space="preserve"> A literal block. <paragraph> :: <block_quote> <paragraph> Not a literal block. """], ["""\ A paragraph: :: A literal block. """, """\ <document source="test data"> <paragraph> A paragraph: <literal_block xml:space="preserve"> A literal block. """], ["""\ A paragraph: :: A literal block. """, """\ <document source="test data"> <paragraph> A paragraph: <literal_block xml:space="preserve"> A literal block. """], ["""\ A paragraph: :: A literal block. """, """\ <document source="test data"> <system_message level="1" line="2" source="test data" type="INFO"> <paragraph> Possible title underline, too short for the title. Treating it as ordinary text because it's so short. <paragraph> A paragraph: <literal_block xml:space="preserve"> A literal block. """], ["""\ A paragraph: :: A literal block. """, """\ <document source="test data"> <paragraph> A paragraph: <literal_block xml:space="preserve"> A literal block. """], ["""\ A paragraph:: Not a literal block. """, """\ <document source="test data"> <paragraph> A paragraph: <system_message level="2" line="3" source="test data" type="WARNING"> <paragraph> Literal block expected; none found. <paragraph> Not a literal block. """], ["""\ A paragraph:: A wonky literal block. Literal line 2. Literal line 3. """, """\ <document source="test data"> <paragraph> A paragraph: <literal_block xml:space="preserve"> A wonky literal block. Literal line 2. \n\ Literal line 3. """], ["""\ EOF, even though a literal block is indicated:: """, """\ <document source="test data"> <paragraph> EOF, even though a literal block is indicated: <system_message level="2" line="2" source="test data" type="WARNING"> <paragraph> Literal block expected; none found. """], ] totest['quoted_literal_blocks'] = [ ["""\ A paragraph:: > A literal block. """, """\ <document source="test data"> <paragraph> A paragraph: <literal_block xml:space="preserve"> > A literal block. """], ["""\ A paragraph:: > A literal block. """, """\ <document source="test data"> <paragraph> A paragraph: <literal_block xml:space="preserve"> > A literal block. """], ["""\ A paragraph:: > A literal block. > Line 2. """, """\ <document source="test data"> <paragraph> A paragraph: <literal_block xml:space="preserve"> > A literal block. > Line 2. """], ["""\ A paragraph:: > A literal block. Indented line. """, """\ <document source="test data"> <paragraph> A paragraph: <literal_block xml:space="preserve"> > A literal block. <system_message level="3" line="4" source="test data" type="ERROR"> <paragraph> Unexpected indentation. <block_quote> <paragraph> Indented line. """], ["""\ A paragraph:: > A literal block. Text. """, """\ <document source="test data"> <paragraph> A paragraph: <literal_block xml:space="preserve"> > A literal block. <system_message level="3" line="4" source="test data" type="ERROR"> <paragraph> Inconsistent literal block quoting. <paragraph> Text. """], ["""\ A paragraph:: > A literal block. $ Inconsistent line. """, """\ <document source="test data"> <paragraph> A paragraph: <literal_block xml:space="preserve"> > A literal block. <system_message level="3" line="4" source="test data" type="ERROR"> <paragraph> Inconsistent literal block quoting. <paragraph> $ Inconsistent line. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_comments.py�������������������������������������������0000775�0001750�0001750�00000014703�10434150472�026036� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_comments.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['comments'] = [ ["""\ .. A comment Paragraph. """, """\ <document source="test data"> <comment xml:space="preserve"> A comment <paragraph> Paragraph. """], ["""\ .. A comment block. Paragraph. """, """\ <document source="test data"> <comment xml:space="preserve"> A comment block. <paragraph> Paragraph. """], ["""\ .. A comment consisting of multiple lines starting on the line after the explicit markup start. """, """\ <document source="test data"> <comment xml:space="preserve"> A comment consisting of multiple lines starting on the line after the explicit markup start. """], ["""\ .. A comment. .. Another. Paragraph. """, """\ <document source="test data"> <comment xml:space="preserve"> A comment. <comment xml:space="preserve"> Another. <paragraph> Paragraph. """], ["""\ .. A comment no blank line Paragraph. """, """\ <document source="test data"> <comment xml:space="preserve"> A comment <system_message level="2" line="2" source="test data" type="WARNING"> <paragraph> Explicit markup ends without a blank line; unexpected unindent. <paragraph> no blank line <paragraph> Paragraph. """], ["""\ .. A comment. .. Another. no blank line Paragraph. """, """\ <document source="test data"> <comment xml:space="preserve"> A comment. <comment xml:space="preserve"> Another. <system_message level="2" line="3" source="test data" type="WARNING"> <paragraph> Explicit markup ends without a blank line; unexpected unindent. <paragraph> no blank line <paragraph> Paragraph. """], ["""\ .. A comment:: Paragraph. """, """\ <document source="test data"> <comment xml:space="preserve"> A comment:: <paragraph> Paragraph. """], ["""\ .. comment:: The extra newline before the comment text prevents the parser from recognizing a directive. """, """\ <document source="test data"> <comment xml:space="preserve"> comment:: <paragraph> The extra newline before the comment text prevents the parser from recognizing a directive. """], ["""\ .. _comment: http://example.org The extra newline before the comment text prevents the parser from recognizing a hyperlink target. """, """\ <document source="test data"> <comment xml:space="preserve"> _comment: http://example.org <paragraph> The extra newline before the comment text prevents the parser from recognizing a hyperlink target. """], ["""\ .. [comment] Not a citation. The extra newline before the comment text prevents the parser from recognizing a citation. """, """\ <document source="test data"> <comment xml:space="preserve"> [comment] Not a citation. <paragraph> The extra newline before the comment text prevents the parser from recognizing a citation. """], ["""\ .. |comment| image:: bogus.png The extra newline before the comment text prevents the parser from recognizing a substitution definition. """, """\ <document source="test data"> <comment xml:space="preserve"> |comment| image:: bogus.png <paragraph> The extra newline before the comment text prevents the parser from recognizing a substitution definition. """], ["""\ .. Next is an empty comment, which serves to end this comment and prevents the following block quote being swallowed up. .. A block quote. """, """\ <document source="test data"> <comment xml:space="preserve"> Next is an empty comment, which serves to end this comment and prevents the following block quote being swallowed up. <comment xml:space="preserve"> <block_quote> <paragraph> A block quote. """], ["""\ term 1 definition 1 .. a comment term 2 definition 2 """, """\ <document source="test data"> <definition_list> <definition_list_item> <term> term 1 <definition> <paragraph> definition 1 <comment xml:space="preserve"> a comment <definition_list_item> <term> term 2 <definition> <paragraph> definition 2 """], ["""\ term 1 definition 1 .. a comment term 2 definition 2 """, """\ <document source="test data"> <definition_list> <definition_list_item> <term> term 1 <definition> <paragraph> definition 1 <comment xml:space="preserve"> a comment <definition_list> <definition_list_item> <term> term 2 <definition> <paragraph> definition 2 """], ["""\ + bullet paragraph 1 bullet paragraph 2 .. comment between bullet paragraphs 2 and 3 bullet paragraph 3 """, """\ <document source="test data"> <bullet_list bullet="+"> <list_item> <paragraph> bullet paragraph 1 <paragraph> bullet paragraph 2 <comment xml:space="preserve"> comment between bullet paragraphs 2 and 3 <paragraph> bullet paragraph 3 """], ["""\ + bullet paragraph 1 .. comment between bullet paragraphs 1 (leader) and 2 bullet paragraph 2 """, """\ <document source="test data"> <bullet_list bullet="+"> <list_item> <paragraph> bullet paragraph 1 <comment xml:space="preserve"> comment between bullet paragraphs 1 (leader) and 2 <paragraph> bullet paragraph 2 """], ["""\ + bullet .. trailing comment """, """\ <document source="test data"> <bullet_list bullet="+"> <list_item> <paragraph> bullet <comment xml:space="preserve"> trailing comment """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/__init__.py������������������������������������������������0000664�0001750�0001750�00000000462�10254646615�024714� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������import os import os.path import sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) prev = '' while sys.path[0] != prev: try: import DocutilsTestSupport break except ImportError: prev = sys.path[0] sys.path[0] = os.path.dirname(prev) sys.path.pop(0) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_enumerated_lists.py�����������������������������������0000775�0001750�0001750�00000047766�10600306272�027573� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_enumerated_lists.py 5033 2007-03-21 19:51:22Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['enumerated_lists'] = [ ["""\ 1. Item one. 2. Item two. 3. Item three. """, """\ <document source="test data"> <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Item one. <list_item> <paragraph> Item two. <list_item> <paragraph> Item three. """], ["""\ No blank lines betwen items: 1. Item one. 2. Item two. 3. Item three. """, """\ <document source="test data"> <paragraph> No blank lines betwen items: <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Item one. <list_item> <paragraph> Item two. <list_item> <paragraph> Item three. """], ["""\ 1. empty item above, no blank line """, """\ <document source="test data"> <paragraph> 1. empty item above, no blank line """], ["""\ Scrambled: 3. Item three. 2. Item two. 1. Item one. 3. Item three. 2. Item two. 1. Item one. """, """\ <document source="test data"> <paragraph> Scrambled: <enumerated_list enumtype="arabic" prefix="" start="3" suffix="."> <list_item> <paragraph> Item three. <system_message level="1" line="3" source="test data" type="INFO"> <paragraph> Enumerated list start value not ordinal-1: "3" (ordinal 3) <enumerated_list enumtype="arabic" prefix="" start="2" suffix="."> <list_item> <paragraph> Item two. <system_message level="1" line="5" source="test data" type="INFO"> <paragraph> Enumerated list start value not ordinal-1: "2" (ordinal 2) <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Item one. <paragraph> 3. Item three. 2. Item two. 1. Item one. """], ["""\ Skipping item 3: 1. Item 1. 2. Item 2. 4. Item 4. """, """\ <document source="test data"> <paragraph> Skipping item 3: <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Item 1. <system_message level="2" line="4" source="test data" type="WARNING"> <paragraph> Enumerated list ends without a blank line; unexpected unindent. <paragraph> 2. Item 2. 4. Item 4. """], ["""\ Start with non-ordinal-1: 0. Item zero. 1. Item one. 2. Item two. 3. Item three. And again: 2. Item two. 3. Item three. """, """\ <document source="test data"> <paragraph> Start with non-ordinal-1: <enumerated_list enumtype="arabic" prefix="" start="0" suffix="."> <list_item> <paragraph> Item zero. <list_item> <paragraph> Item one. <list_item> <paragraph> Item two. <list_item> <paragraph> Item three. <system_message level="1" line="3" source="test data" type="INFO"> <paragraph> Enumerated list start value not ordinal-1: "0" (ordinal 0) <paragraph> And again: <enumerated_list enumtype="arabic" prefix="" start="2" suffix="."> <list_item> <paragraph> Item two. <list_item> <paragraph> Item three. <system_message level="1" line="10" source="test data" type="INFO"> <paragraph> Enumerated list start value not ordinal-1: "2" (ordinal 2) """], ["""\ 1. Item one: line 1, line 2. 2. Item two: line 1, line 2. 3. Item three: paragraph 1, line 1, line 2. Paragraph 2. """, """\ <document source="test data"> <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Item one: line 1, line 2. <list_item> <paragraph> Item two: line 1, line 2. <list_item> <paragraph> Item three: paragraph 1, line 1, line 2. <paragraph> Paragraph 2. """], ["""\ Different enumeration sequences: 1. Item 1. 2. Item 2. 3. Item 3. A. Item A. B. Item B. C. Item C. a. Item a. b. Item b. c. Item c. I. Item I. II. Item II. III. Item III. i. Item i. ii. Item ii. iii. Item iii. """, """\ <document source="test data"> <paragraph> Different enumeration sequences: <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Item 1. <list_item> <paragraph> Item 2. <list_item> <paragraph> Item 3. <enumerated_list enumtype="upperalpha" prefix="" suffix="."> <list_item> <paragraph> Item A. <list_item> <paragraph> Item B. <list_item> <paragraph> Item C. <enumerated_list enumtype="loweralpha" prefix="" suffix="."> <list_item> <paragraph> Item a. <list_item> <paragraph> Item b. <list_item> <paragraph> Item c. <enumerated_list enumtype="upperroman" prefix="" suffix="."> <list_item> <paragraph> Item I. <list_item> <paragraph> Item II. <list_item> <paragraph> Item III. <enumerated_list enumtype="lowerroman" prefix="" suffix="."> <list_item> <paragraph> Item i. <list_item> <paragraph> Item ii. <list_item> <paragraph> Item iii. """], ["""\ Bad Roman numerals: i. i ii. ii iii. iii iiii. iiii second line (LCD) is an acronym made up of Roman numerals (livid) is a word made up of Roman numerals (CIVIL) is another such word (I) I (IVXLCDM) IVXLCDM """, """\ <document source="test data"> <paragraph> Bad Roman numerals: <enumerated_list enumtype="lowerroman" prefix="" suffix="."> <list_item> <paragraph> i <list_item> <paragraph> ii <list_item> <paragraph> iii <definition_list> <definition_list_item> <term> iiii. iiii <definition> <paragraph> second line <paragraph> (LCD) is an acronym made up of Roman numerals <paragraph> (livid) is a word made up of Roman numerals <paragraph> (CIVIL) is another such word <enumerated_list enumtype="upperroman" prefix="(" suffix=")"> <list_item> <paragraph> I <paragraph> (IVXLCDM) IVXLCDM """], ["""\ Potentially ambiguous cases: A. Item A. B. Item B. C. Item C. I. Item I. II. Item II. III. Item III. a. Item a. b. Item b. c. Item c. i. Item i. ii. Item ii. iii. Item iii. Phew! Safe! """, """\ <document source="test data"> <paragraph> Potentially ambiguous cases: <enumerated_list enumtype="upperalpha" prefix="" suffix="."> <list_item> <paragraph> Item A. <list_item> <paragraph> Item B. <list_item> <paragraph> Item C. <enumerated_list enumtype="upperroman" prefix="" suffix="."> <list_item> <paragraph> Item I. <list_item> <paragraph> Item II. <list_item> <paragraph> Item III. <enumerated_list enumtype="loweralpha" prefix="" suffix="."> <list_item> <paragraph> Item a. <list_item> <paragraph> Item b. <list_item> <paragraph> Item c. <enumerated_list enumtype="lowerroman" prefix="" suffix="."> <list_item> <paragraph> Item i. <list_item> <paragraph> Item ii. <list_item> <paragraph> Item iii. <paragraph> Phew! Safe! """], ["""\ Definitely ambiguous: A. Item A. B. Item B. C. Item C. D. Item D. E. Item E. F. Item F. G. Item G. H. Item H. I. Item I. II. Item II. III. Item III. a. Item a. b. Item b. c. Item c. d. Item d. e. Item e. f. Item f. g. Item g. h. Item h. i. Item i. ii. Item ii. iii. Item iii. """, """\ <document source="test data"> <paragraph> Definitely ambiguous: <enumerated_list enumtype="upperalpha" prefix="" suffix="."> <list_item> <paragraph> Item A. <list_item> <paragraph> Item B. <list_item> <paragraph> Item C. <list_item> <paragraph> Item D. <list_item> <paragraph> Item E. <list_item> <paragraph> Item F. <list_item> <paragraph> Item G. <list_item> <paragraph> Item H. <system_message level="2" line="11" source="test data" type="WARNING"> <paragraph> Enumerated list ends without a blank line; unexpected unindent. <enumerated_list enumtype="upperroman" prefix="" suffix="."> <list_item> <paragraph> Item I. <list_item> <paragraph> Item II. <list_item> <paragraph> Item III. <enumerated_list enumtype="loweralpha" prefix="" suffix="."> <list_item> <paragraph> Item a. <list_item> <paragraph> Item b. <list_item> <paragraph> Item c. <list_item> <paragraph> Item d. <list_item> <paragraph> Item e. <list_item> <paragraph> Item f. <list_item> <paragraph> Item g. <list_item> <paragraph> Item h. <system_message level="2" line="23" source="test data" type="WARNING"> <paragraph> Enumerated list ends without a blank line; unexpected unindent. <enumerated_list enumtype="lowerroman" prefix="" suffix="."> <list_item> <paragraph> Item i. <list_item> <paragraph> Item ii. <list_item> <paragraph> Item iii. """], ["""\ Different enumeration formats: 1. Item 1. 2. Item 2. 3. Item 3. 1) Item 1). 2) Item 2). 3) Item 3). (1) Item (1). (2) Item (2). (3) Item (3). """, """\ <document source="test data"> <paragraph> Different enumeration formats: <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Item 1. <list_item> <paragraph> Item 2. <list_item> <paragraph> Item 3. <enumerated_list enumtype="arabic" prefix="" suffix=")"> <list_item> <paragraph> Item 1). <list_item> <paragraph> Item 2). <list_item> <paragraph> Item 3). <enumerated_list enumtype="arabic" prefix="(" suffix=")"> <list_item> <paragraph> Item (1). <list_item> <paragraph> Item (2). <list_item> <paragraph> Item (3). """], ["""\ Nested enumerated lists: 1. Item 1. A) Item A). B) Item B). C) Item C). 2. Item 2. (a) Item (a). I) Item I). II) Item II). III) Item III). (b) Item (b). (c) Item (c). (i) Item (i). (ii) Item (ii). (iii) Item (iii). 3. Item 3. """, """\ <document source="test data"> <paragraph> Nested enumerated lists: <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Item 1. <enumerated_list enumtype="upperalpha" prefix="" suffix=")"> <list_item> <paragraph> Item A). <list_item> <paragraph> Item B). <list_item> <paragraph> Item C). <list_item> <paragraph> Item 2. <enumerated_list enumtype="loweralpha" prefix="(" suffix=")"> <list_item> <paragraph> Item (a). <enumerated_list enumtype="upperroman" prefix="" suffix=")"> <list_item> <paragraph> Item I). <list_item> <paragraph> Item II). <list_item> <paragraph> Item III). <list_item> <paragraph> Item (b). <list_item> <paragraph> Item (c). <enumerated_list enumtype="lowerroman" prefix="(" suffix=")"> <list_item> <paragraph> Item (i). <list_item> <paragraph> Item (ii). <list_item> <paragraph> Item (iii). <list_item> <paragraph> Item 3. """], [u"""\ A. Einstein was a great influence on B. Physicist, who was a colleague of C. Chemist. They all worked in Princeton, NJ. Using a non-breaking space as a workaround: A.\u00a0Einstein was a great influence on B. Physicist, who was a colleague of C. Chemist. They all worked in Princeton, NJ. """, """\ <document source="test data"> <enumerated_list enumtype="upperalpha" prefix="" suffix="."> <list_item> <paragraph> Einstein was a great influence on <list_item> <paragraph> Physicist, who was a colleague of <system_message level="2" line="3" source="test data" type="WARNING"> <paragraph> Enumerated list ends without a blank line; unexpected unindent. <paragraph> C. Chemist. They all worked in Princeton, NJ. <paragraph> Using a non-breaking space as a workaround: <paragraph> A.\xa0Einstein was a great influence on B. Physicist, who was a colleague of C. Chemist. They all worked in Princeton, NJ. """], ["""\ 1. Item one: line 1, line 2. 2. Item two: line 1, line 2. 3. Item three: paragraph 1, line 1, line 2. Paragraph 2. """, """\ <document source="test data"> <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Item one: line 1, line 2. <list_item> <paragraph> Item two: line 1, <system_message level="2" line="4" source="test data" type="WARNING"> <paragraph> Enumerated list ends without a blank line; unexpected unindent. <block_quote> <paragraph> line 2. <system_message level="2" line="5" source="test data" type="WARNING"> <paragraph> Block quote ends without a blank line; unexpected unindent. <enumerated_list enumtype="arabic" prefix="" start="3" suffix="."> <list_item> <paragraph> Item three: paragraph 1, line 1, <system_message level="1" line="5" source="test data" type="INFO"> <paragraph> Enumerated list start value not ordinal-1: "3" (ordinal 3) <system_message level="2" line="6" source="test data" type="WARNING"> <paragraph> Enumerated list ends without a blank line; unexpected unindent. <block_quote> <paragraph> line 2. <block_quote> <paragraph> Paragraph 2. """], ["""\ 1. Item one. #. Item two. #. Item three. """, """\ <document source="test data"> <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Item one. <list_item> <paragraph> Item two. <list_item> <paragraph> Item three. """], ["""\ a. Item one. #. Item two. #. Item three. """, """\ <document source="test data"> <enumerated_list enumtype="loweralpha" prefix="" suffix="."> <list_item> <paragraph> Item one. <list_item> <paragraph> Item two. <list_item> <paragraph> Item three. """], ["""\ i. Item one. ii. Item two. #. Item three. """, """\ <document source="test data"> <enumerated_list enumtype="lowerroman" prefix="" suffix="."> <list_item> <paragraph> Item one. <list_item> <paragraph> Item two. <list_item> <paragraph> Item three. """], ["""\ #. Item one. #. Item two. #. Item three. """, """\ <document source="test data"> <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Item one. <list_item> <paragraph> Item two. <list_item> <paragraph> Item three. """], ["""\ 1. Item one. #. Item two. 3. Item three. """, """\ <document source="test data"> <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Item one. <system_message level="2" line="2" source="test data" type="WARNING"> <paragraph> Enumerated list ends without a blank line; unexpected unindent. <paragraph> #. Item two. 3. Item three. """], ["""\ z. x """, """\ <document source="test data"> <paragraph> z. x """], ["""\ 3-space indent, with a trailing space: 1. \n\ foo 3-space indent, no trailing space: 1. foo 2-space indent: 1. foo 1-space indent: 1. foo 0-space indent, not a list item: 1. foo No item content: 1. """, """\ <document source="test data"> <paragraph> 3-space indent, with a trailing space: <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> foo <paragraph> 3-space indent, no trailing space: <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> foo <paragraph> 2-space indent: <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> foo <paragraph> 1-space indent: <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> foo <paragraph> 0-space indent, not a list item: <paragraph> 1. foo <paragraph> No item content: <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����������docutils-0.12/test/test_parsers/test_rst/test_footnotes.py������������������������������������������0000775�0001750�0001750�00000022350�10434150472�026226� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_footnotes.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['footnotes'] = [ ["""\ .. [1] This is a footnote. """, """\ <document source="test data"> <footnote ids="id1" names="1"> <label> 1 <paragraph> This is a footnote. """], ["""\ .. [1] This is a footnote on multiple lines. """, """\ <document source="test data"> <footnote ids="id1" names="1"> <label> 1 <paragraph> This is a footnote on multiple lines. """], ["""\ .. [1] This is a footnote on multiple lines with more space. .. [2] This is a footnote on multiple lines with less space. """, """\ <document source="test data"> <footnote ids="id1" names="1"> <label> 1 <paragraph> This is a footnote on multiple lines with more space. <footnote ids="id2" names="2"> <label> 2 <paragraph> This is a footnote on multiple lines with less space. """], ["""\ .. [1] This is a footnote on multiple lines whose block starts on line 2. """, """\ <document source="test data"> <footnote ids="id1" names="1"> <label> 1 <paragraph> This is a footnote on multiple lines whose block starts on line 2. """], ["""\ .. [1] That was an empty footnote. """, """\ <document source="test data"> <footnote ids="id1" names="1"> <label> 1 <paragraph> That was an empty footnote. """], ["""\ .. [1] No blank line. """, """\ <document source="test data"> <footnote ids="id1" names="1"> <label> 1 <system_message level="2" line="2" source="test data" type="WARNING"> <paragraph> Explicit markup ends without a blank line; unexpected unindent. <paragraph> No blank line. """], ] totest['auto_numbered_footnotes'] = [ ["""\ [#]_ is the first auto-numbered footnote reference. [#]_ is the second auto-numbered footnote reference. .. [#] Auto-numbered footnote 1. .. [#] Auto-numbered footnote 2. .. [#] Auto-numbered footnote 3. [#]_ is the third auto-numbered footnote reference. """, """\ <document source="test data"> <paragraph> <footnote_reference auto="1" ids="id1"> is the first auto-numbered footnote reference. <footnote_reference auto="1" ids="id2"> is the second auto-numbered footnote reference. <footnote auto="1" ids="id3"> <paragraph> Auto-numbered footnote 1. <footnote auto="1" ids="id4"> <paragraph> Auto-numbered footnote 2. <footnote auto="1" ids="id5"> <paragraph> Auto-numbered footnote 3. <paragraph> <footnote_reference auto="1" ids="id6"> is the third auto-numbered footnote reference. """], ["""\ [#third]_ is a reference to the third auto-numbered footnote. .. [#first] First auto-numbered footnote. .. [#second] Second auto-numbered footnote. .. [#third] Third auto-numbered footnote. [#second]_ is a reference to the second auto-numbered footnote. [#first]_ is a reference to the first auto-numbered footnote. [#third]_ is another reference to the third auto-numbered footnote. Here are some internal cross-references to the targets generated by the footnotes: first_, second_, third_. """, """\ <document source="test data"> <paragraph> <footnote_reference auto="1" ids="id1" refname="third"> is a reference to the third auto-numbered footnote. <footnote auto="1" ids="first" names="first"> <paragraph> First auto-numbered footnote. <footnote auto="1" ids="second" names="second"> <paragraph> Second auto-numbered footnote. <footnote auto="1" ids="third" names="third"> <paragraph> Third auto-numbered footnote. <paragraph> <footnote_reference auto="1" ids="id2" refname="second"> is a reference to the second auto-numbered footnote. <footnote_reference auto="1" ids="id3" refname="first"> is a reference to the first auto-numbered footnote. <footnote_reference auto="1" ids="id4" refname="third"> is another reference to the third auto-numbered footnote. <paragraph> Here are some internal cross-references to the targets generated by the footnotes: \n\ <reference name="first" refname="first"> first , \n\ <reference name="second" refname="second"> second , \n\ <reference name="third" refname="third"> third . """], ["""\ Mixed anonymous and labelled auto-numbered footnotes: [#four]_ should be 4, [#]_ should be 1, [#]_ should be 3, [#]_ is one too many, [#two]_ should be 2, and [#six]_ doesn't exist. .. [#] Auto-numbered footnote 1. .. [#two] Auto-numbered footnote 2. .. [#] Auto-numbered footnote 3. .. [#four] Auto-numbered footnote 4. .. [#five] Auto-numbered footnote 5. .. [#five] Auto-numbered footnote 5 again (duplicate). """, """\ <document source="test data"> <paragraph> Mixed anonymous and labelled auto-numbered footnotes: <paragraph> <footnote_reference auto="1" ids="id1" refname="four"> should be 4, \n\ <footnote_reference auto="1" ids="id2"> should be 1, <footnote_reference auto="1" ids="id3"> should be 3, \n\ <footnote_reference auto="1" ids="id4"> is one too many, <footnote_reference auto="1" ids="id5" refname="two"> should be 2, and \n\ <footnote_reference auto="1" ids="id6" refname="six"> doesn't exist. <footnote auto="1" ids="id7"> <paragraph> Auto-numbered footnote 1. <footnote auto="1" ids="two" names="two"> <paragraph> Auto-numbered footnote 2. <footnote auto="1" ids="id8"> <paragraph> Auto-numbered footnote 3. <footnote auto="1" ids="four" names="four"> <paragraph> Auto-numbered footnote 4. <footnote auto="1" dupnames="five" ids="five"> <paragraph> Auto-numbered footnote 5. <footnote auto="1" dupnames="five" ids="id9"> <system_message backrefs="id9" level="2" line="12" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "five". <paragraph> Auto-numbered footnote 5 again (duplicate). """], ["""\ Mixed manually-numbered, anonymous auto-numbered, and labelled auto-numbered footnotes: [#four]_ should be 4, [#]_ should be 2, [1]_ is 1, [3]_ is 3, [#]_ should be 6, [#]_ is one too many, [#five]_ should be 5, and [#six]_ doesn't exist. .. [1] Manually-numbered footnote 1. .. [#] Auto-numbered footnote 2. .. [#four] Auto-numbered footnote 4. .. [3] Manually-numbered footnote 3 .. [#five] Auto-numbered footnote 5. .. [#five] Auto-numbered footnote 5 again (duplicate). .. [#] Auto-numbered footnote 6. """, """\ <document source="test data"> <paragraph> Mixed manually-numbered, anonymous auto-numbered, and labelled auto-numbered footnotes: <paragraph> <footnote_reference auto="1" ids="id1" refname="four"> should be 4, \n\ <footnote_reference auto="1" ids="id2"> should be 2, <footnote_reference ids="id3" refname="1"> 1 is 1, \n\ <footnote_reference ids="id4" refname="3"> 3 is 3, <footnote_reference auto="1" ids="id5"> should be 6, \n\ <footnote_reference auto="1" ids="id6"> is one too many, <footnote_reference auto="1" ids="id7" refname="five"> should be 5, and \n\ <footnote_reference auto="1" ids="id8" refname="six"> doesn't exist. <footnote ids="id9" names="1"> <label> 1 <paragraph> Manually-numbered footnote 1. <footnote auto="1" ids="id10"> <paragraph> Auto-numbered footnote 2. <footnote auto="1" ids="four" names="four"> <paragraph> Auto-numbered footnote 4. <footnote ids="id11" names="3"> <label> 3 <paragraph> Manually-numbered footnote 3 <footnote auto="1" dupnames="five" ids="five"> <paragraph> Auto-numbered footnote 5. <footnote auto="1" dupnames="five" ids="id12"> <system_message backrefs="id12" level="2" line="14" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "five". <paragraph> Auto-numbered footnote 5 again (duplicate). <footnote auto="1" ids="id13"> <paragraph> Auto-numbered footnote 6. """], ] totest['auto_symbol_footnotes'] = [ ["""\ .. [*] This is an auto-symbol footnote. """, """\ <document source="test data"> <footnote auto="*" ids="id1"> <paragraph> This is an auto-symbol footnote. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_option_lists.py���������������������������������������0000775�0001750�0001750�00000047623�11635160103�026742� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_option_lists.py 7128 2011-09-17 18:00:35Z grubert $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['option_lists'] = [ ["""\ Short options: -a option -a -b file option -b -c name option -c """, """\ <document source="test data"> <paragraph> Short options: <option_list> <option_list_item> <option_group> <option> <option_string> -a <description> <paragraph> option -a <option_list_item> <option_group> <option> <option_string> -b <option_argument delimiter=" "> file <description> <paragraph> option -b <option_list_item> <option_group> <option> <option_string> -c <option_argument delimiter=" "> name <description> <paragraph> option -c """], ["""\ Long options: --aaaa option --aaaa --bbbb=file option --bbbb --cccc name option --cccc --d-e-f-g option --d-e-f-g --h_i_j_k option --h_i_j_k """, """\ <document source="test data"> <paragraph> Long options: <option_list> <option_list_item> <option_group> <option> <option_string> --aaaa <description> <paragraph> option --aaaa <option_list_item> <option_group> <option> <option_string> --bbbb <option_argument delimiter="="> file <description> <paragraph> option --bbbb <option_list_item> <option_group> <option> <option_string> --cccc <option_argument delimiter=" "> name <description> <paragraph> option --cccc <option_list_item> <option_group> <option> <option_string> --d-e-f-g <description> <paragraph> option --d-e-f-g <option_list_item> <option_group> <option> <option_string> --h_i_j_k <description> <paragraph> option --h_i_j_k """], ["""\ Old GNU-style options: +a option +a +b file option +b +c name option +c """, """\ <document source="test data"> <paragraph> Old GNU-style options: <option_list> <option_list_item> <option_group> <option> <option_string> +a <description> <paragraph> option +a <option_list_item> <option_group> <option> <option_string> +b <option_argument delimiter=" "> file <description> <paragraph> option +b <option_list_item> <option_group> <option> <option_string> +c <option_argument delimiter=" "> name <description> <paragraph> option +c """], ["""\ VMS/DOS-style options: /A option /A /B file option /B /CCC option /CCC /DDD string option /DDD /EEE=int option /EEE """, """\ <document source="test data"> <paragraph> VMS/DOS-style options: <option_list> <option_list_item> <option_group> <option> <option_string> /A <description> <paragraph> option /A <option_list_item> <option_group> <option> <option_string> /B <option_argument delimiter=" "> file <description> <paragraph> option /B <option_list_item> <option_group> <option> <option_string> /CCC <description> <paragraph> option /CCC <option_list_item> <option_group> <option> <option_string> /DDD <option_argument delimiter=" "> string <description> <paragraph> option /DDD <option_list_item> <option_group> <option> <option_string> /EEE <option_argument delimiter="="> int <description> <paragraph> option /EEE """], ["""\ Mixed short, long, and VMS/DOS options: -a option -a --bbbb=file option -bbbb /C option /C --dddd name option --dddd -e string option -e /F file option /F """, """\ <document source="test data"> <paragraph> Mixed short, long, and VMS/DOS options: <option_list> <option_list_item> <option_group> <option> <option_string> -a <description> <paragraph> option -a <option_list_item> <option_group> <option> <option_string> --bbbb <option_argument delimiter="="> file <description> <paragraph> option -bbbb <option_list_item> <option_group> <option> <option_string> /C <description> <paragraph> option /C <option_list_item> <option_group> <option> <option_string> --dddd <option_argument delimiter=" "> name <description> <paragraph> option --dddd <option_list_item> <option_group> <option> <option_string> -e <option_argument delimiter=" "> string <description> <paragraph> option -e <option_list_item> <option_group> <option> <option_string> /F <option_argument delimiter=" "> file <description> <paragraph> option /F """], ["""\ Aliased options: -a, --aaaa, /A option -a, --aaaa, /A -b file, --bbbb=file, /B file option -b, --bbbb, /B """, """\ <document source="test data"> <paragraph> Aliased options: <option_list> <option_list_item> <option_group> <option> <option_string> -a <option> <option_string> --aaaa <option> <option_string> /A <description> <paragraph> option -a, --aaaa, /A <option_list_item> <option_group> <option> <option_string> -b <option_argument delimiter=" "> file <option> <option_string> --bbbb <option_argument delimiter="="> file <option> <option_string> /B <option_argument delimiter=" "> file <description> <paragraph> option -b, --bbbb, /B """], ["""\ Multiple lines in descriptions, aligned: -a option -a, line 1 line 2 -b file option -b, line 1 line 2 """, """\ <document source="test data"> <paragraph> Multiple lines in descriptions, aligned: <option_list> <option_list_item> <option_group> <option> <option_string> -a <description> <paragraph> option -a, line 1 line 2 <option_list_item> <option_group> <option> <option_string> -b <option_argument delimiter=" "> file <description> <paragraph> option -b, line 1 line 2 """], ["""\ Multiple lines in descriptions, not aligned: -a option -a, line 1 line 2 -b file option -b, line 1 line 2 """, """\ <document source="test data"> <paragraph> Multiple lines in descriptions, not aligned: <option_list> <option_list_item> <option_group> <option> <option_string> -a <description> <paragraph> option -a, line 1 line 2 <option_list_item> <option_group> <option> <option_string> -b <option_argument delimiter=" "> file <description> <paragraph> option -b, line 1 line 2 """], ["""\ Descriptions begin on next line: -a option -a, line 1 line 2 -b file option -b, line 1 line 2 """, """\ <document source="test data"> <paragraph> Descriptions begin on next line: <option_list> <option_list_item> <option_group> <option> <option_string> -a <description> <paragraph> option -a, line 1 line 2 <option_list_item> <option_group> <option> <option_string> -b <option_argument delimiter=" "> file <description> <paragraph> option -b, line 1 line 2 """], ["""\ Multiple body elements in descriptions: -a option -a, para 1 para 2 -b file option -b, para 1 para 2 """, """\ <document source="test data"> <paragraph> Multiple body elements in descriptions: <option_list> <option_list_item> <option_group> <option> <option_string> -a <description> <paragraph> option -a, para 1 <paragraph> para 2 <option_list_item> <option_group> <option> <option_string> -b <option_argument delimiter=" "> file <description> <paragraph> option -b, para 1 <paragraph> para 2 """], ["""\ --option empty item above, no blank line """, """\ <document source="test data"> <paragraph> --option empty item above, no blank line """], ["""\ An option list using equals: --long1=arg1 Description 1 --long2=arg2 Description 2 An option list using spaces: --long1 arg1 Description 1 --long2 arg2 Description 2 An option list using mixed delimiters: --long1=arg1 Description 1 --long2 arg2 Description 2 An option list using mixed delimiters in one line: --long1=arg1, --long2 arg2 Description """, """\ <document source="test data"> <paragraph> An option list using equals: <option_list> <option_list_item> <option_group> <option> <option_string> --long1 <option_argument delimiter="="> arg1 <description> <paragraph> Description 1 <option_list_item> <option_group> <option> <option_string> --long2 <option_argument delimiter="="> arg2 <description> <paragraph> Description 2 <paragraph> An option list using spaces: <option_list> <option_list_item> <option_group> <option> <option_string> --long1 <option_argument delimiter=" "> arg1 <description> <paragraph> Description 1 <option_list_item> <option_group> <option> <option_string> --long2 <option_argument delimiter=" "> arg2 <description> <paragraph> Description 2 <paragraph> An option list using mixed delimiters: <option_list> <option_list_item> <option_group> <option> <option_string> --long1 <option_argument delimiter="="> arg1 <description> <paragraph> Description 1 <option_list_item> <option_group> <option> <option_string> --long2 <option_argument delimiter=" "> arg2 <description> <paragraph> Description 2 <paragraph> An option list using mixed delimiters in one line: <option_list> <option_list_item> <option_group> <option> <option_string> --long1 <option_argument delimiter="="> arg1 <option> <option_string> --long2 <option_argument delimiter=" "> arg2 <description> <paragraph> Description """], ["""\ Some edge cases: --option=arg arg too many arguments --option=arg,arg not supported (yet?) --option=arg=arg too many arguments --option arg arg too many arguments -a letter arg2 too many arguments /A letter arg2 too many arguments --option= argument missing --=argument option missing -- everything missing - this should be a bullet list item These next ones should be simple paragraphs: -1 --option --1 -1 and this one too. """, """\ <document source="test data"> <paragraph> Some edge cases: <paragraph> --option=arg arg too many arguments <paragraph> --option=arg,arg not supported (yet?) <paragraph> --option=arg=arg too many arguments <paragraph> --option arg arg too many arguments <paragraph> -a letter arg2 too many arguments <paragraph> /A letter arg2 too many arguments <paragraph> --option= argument missing <paragraph> --=argument option missing <paragraph> -- everything missing <bullet_list bullet="-"> <list_item> <paragraph> this should be a bullet list item <paragraph> These next ones should be simple paragraphs: <paragraph> -1 <paragraph> --option <paragraph> --1 <paragraph> -1 and this one too. """], ["""\ Complex optargs: --source-url=<URL> Use the supplied <URL> verbatim. --output-encoding=<name[:handler]>, -o<name[:handler]> Specify the text encoding for output. --af=<filter1[=parameter1:parameter2:...],filter2,...> Setup a chain of audio filters. Option argument containing delimiter ``=``. -f <[path]filename> Send output to file. -d <src dest> Use diff from <src> to <dest>. --bogus=<x y z> Bogus 3D coordinates. """, """\ <document source="test data"> <paragraph> Complex optargs: <option_list> <option_list_item> <option_group> <option> <option_string> --source-url <option_argument delimiter="="> <URL> <description> <paragraph> Use the supplied <URL> verbatim. <option_list_item> <option_group> <option> <option_string> --output-encoding <option_argument delimiter="="> <name[:handler]> <option> <option_string> -o <option_argument delimiter=""> <name[:handler]> <description> <paragraph> Specify the text encoding for output. <option_list_item> <option_group> <option> <option_string> --af <option_argument delimiter="="> <filter1[=parameter1:parameter2:...],filter2,...> <description> <paragraph> Setup a chain of audio filters. Option argument containing delimiter \n\ <literal> = . <option_list_item> <option_group> <option> <option_string> -f <option_argument delimiter=" "> <[path]filename> <description> <paragraph> Send output to file. <option_list_item> <option_group> <option> <option_string> -d <option_argument delimiter=" "> <src dest> <description> <paragraph> Use diff from <src> to <dest>. <option_list_item> <option_group> <option> <option_string> --bogus <option_argument delimiter="="> <x y z> <description> <paragraph> Bogus 3D coordinates. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_bullet_lists.py���������������������������������������0000775�0001750�0001750�00000007477�10440651315�026727� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_bullet_lists.py 4593 2006-06-04 21:38:21Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['bullet_lists'] = [ ["""\ - item """, """\ <document source="test data"> <bullet_list bullet="-"> <list_item> <paragraph> item """], ["""\ * item 1 * item 2 """, """\ <document source="test data"> <bullet_list bullet="*"> <list_item> <paragraph> item 1 <list_item> <paragraph> item 2 """], ["""\ No blank line between: + item 1 + item 2 """, """\ <document source="test data"> <paragraph> No blank line between: <bullet_list bullet="+"> <list_item> <paragraph> item 1 <list_item> <paragraph> item 2 """], ["""\ - item 1, para 1. item 1, para 2. - item 2 """, """\ <document source="test data"> <bullet_list bullet="-"> <list_item> <paragraph> item 1, para 1. <paragraph> item 1, para 2. <list_item> <paragraph> item 2 """], ["""\ - item 1, line 1 item 1, line 2 - item 2 """, """\ <document source="test data"> <bullet_list bullet="-"> <list_item> <paragraph> item 1, line 1 item 1, line 2 <list_item> <paragraph> item 2 """], ["""\ Different bullets: - item 1 + item 2 * item 3 - item 4 """, """\ <document source="test data"> <paragraph> Different bullets: <bullet_list bullet="-"> <list_item> <paragraph> item 1 <bullet_list bullet="+"> <list_item> <paragraph> item 2 <bullet_list bullet="*"> <list_item> <paragraph> item 3 <system_message level="2" line="8" source="test data" type="WARNING"> <paragraph> Bullet list ends without a blank line; unexpected unindent. <bullet_list bullet="-"> <list_item> <paragraph> item 4 """], ["""\ - item no blank line """, """\ <document source="test data"> <bullet_list bullet="-"> <list_item> <paragraph> item <system_message level="2" line="2" source="test data" type="WARNING"> <paragraph> Bullet list ends without a blank line; unexpected unindent. <paragraph> no blank line """], ["""\ - empty item above """, """\ <document source="test data"> <bullet_list bullet="-"> <list_item> <paragraph> empty item above """], ["""\ - empty item above, no blank line """, """\ <document source="test data"> <bullet_list bullet="-"> <list_item> <system_message level="2" line="2" source="test data" type="WARNING"> <paragraph> Bullet list ends without a blank line; unexpected unindent. <paragraph> empty item above, no blank line """], [u"""\ Unicode bullets: \u2022 BULLET \u2023 TRIANGULAR BULLET \u2043 HYPHEN BULLET """, u"""\ <document source="test data"> <paragraph> Unicode bullets: <bullet_list bullet="\u2022"> <list_item> <paragraph> BULLET <bullet_list bullet="\u2023"> <list_item> <paragraph> TRIANGULAR BULLET <bullet_list bullet="\u2043"> <list_item> <paragraph> HYPHEN BULLET """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_outdenting.py�����������������������������������������0000775�0001750�0001750�00000003721�10434150472�026367� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_outdenting.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['outdenting'] = [ ["""\ Anywhere a paragraph would have an effect on the current indentation level, a comment or list item should also. + bullet This paragraph ends the bullet list item before a block quote. Block quote. """, """\ <document source="test data"> <paragraph> Anywhere a paragraph would have an effect on the current indentation level, a comment or list item should also. <bullet_list bullet="+"> <list_item> <paragraph> bullet <paragraph> This paragraph ends the bullet list item before a block quote. <block_quote> <paragraph> Block quote. """], ["""\ + bullet .. Comments swallow up all indented text following. (Therefore this is not a) block quote. - bullet If we want a block quote after this bullet list item, we need to use an empty comment: .. Block quote. """, """\ <document source="test data"> <bullet_list bullet="+"> <list_item> <paragraph> bullet <comment xml:space="preserve"> Comments swallow up all indented text following. \n\ (Therefore this is not a) block quote. <bullet_list bullet="-"> <list_item> <paragraph> bullet <paragraph> If we want a block quote after this bullet list item, we need to use an empty comment: <comment xml:space="preserve"> <block_quote> <paragraph> Block quote. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �����������������������������������������������docutils-0.12/test/test_parsers/test_rst/includes/��������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�024401� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/includes/include9.txt��������������������������������������0000664�0001750�0001750�00000000113�07607426742�026664� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������In ../includes/include9.txt. .. include:: ../test_directives/include2.txt �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_transitions.py����������������������������������������0000775�0001750�0001750�00000012234�10434150472�026563� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_transitions.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for transition markers. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} # See DocutilsTestSupport.ParserTestSuite.generateTests for a # description of the 'totest' data structure. totest['transitions'] = [ ["""\ Test transition markers. -------- Paragraph """, """\ <document source="test data"> <paragraph> Test transition markers. <transition> <paragraph> Paragraph """], ["""\ Section 1 ========= First text division of section 1. -------- Second text division of section 1. Section 2 --------- Paragraph 2 in section 2. """, """\ <document source="test data"> <section ids="section-1" names="section\ 1"> <title> Section 1 <paragraph> First text division of section 1. <transition> <paragraph> Second text division of section 1. <section ids="section-2" names="section\ 2"> <title> Section 2 <paragraph> Paragraph 2 in section 2. """], ["""\ -------- A section or document may not begin with a transition. The DTD specifies that two transitions may not be adjacent: -------- -------- -------- The DTD also specifies that a section or document may not end with a transition. -------- """, """\ <document source="test data"> <transition> <paragraph> A section or document may not begin with a transition. <paragraph> The DTD specifies that two transitions may not be adjacent: <transition> <transition> <transition> <paragraph> The DTD also specifies that a section or document may not end with a transition. <transition> """], ["""\ Test unexpected transition markers. Block quote. -------- Paragraph. """, """\ <document source="test data"> <paragraph> Test unexpected transition markers. <block_quote> <paragraph> Block quote. <system_message level="4" line="5" source="test data" type="SEVERE"> <paragraph> Unexpected section title or transition. <literal_block xml:space="preserve"> -------- <paragraph> Paragraph. """], ["""\ Short transition marker. --- Paragraph """, """\ <document source="test data"> <paragraph> Short transition marker. <paragraph> --- <paragraph> Paragraph """], ["""\ Sections with transitions at beginning and end. Section 1 ========= ---------- The next transition is legal: ---------- Section 2 ========= ---------- """, """\ <document source="test data"> <paragraph> Sections with transitions at beginning and end. <section ids="section-1" names="section\ 1"> <title> Section 1 <transition> <paragraph> The next transition is legal: <transition> <section ids="section-2" names="section\ 2"> <title> Section 2 <transition> """], ["""\ A paragraph, two transitions, and a blank line. ---------- ---------- """, """\ <document source="test data"> <paragraph> A paragraph, two transitions, and a blank line. <transition> <transition> """], ["""\ A paragraph and two transitions. ---------- ---------- """, # the same: """\ <document source="test data"> <paragraph> A paragraph and two transitions. <transition> <transition> """], ["""\ ---------- Document beginning with a transition. """, """\ <document source="test data"> <transition> <paragraph> Document beginning with a transition. """], ["""\ Section 1 ========= Subsection 1 ------------ Some text. ---------- Section 2 ========= Some text. """, """\ <document source="test data"> <section ids="section-1" names="section\ 1"> <title> Section 1 <section ids="subsection-1" names="subsection\ 1"> <title> Subsection 1 <paragraph> Some text. <transition> <section ids="section-2" names="section\ 2"> <title> Section 2 <paragraph> Some text. """], ["""\ Section 1 ========= ---------- ---------- ---------- Section 2 ========= Some text. """, """\ <document source="test data"> <section ids="section-1" names="section\ 1"> <title> Section 1 <transition> <transition> <transition> <section ids="section-2" names="section\ 2"> <title> Section 2 <paragraph> Some text. """], ["""\ ---------- ---------- ---------- """, """\ <document source="test data"> <transition> <transition> <transition> """], ["""\ A paragraph. ---------- """, """\ <document source="test data"> <paragraph> A paragraph. <transition> """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_definition_lists.py�����������������������������������0000775�0001750�0001750�00000026157�10434150472�027565� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_definition_lists.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['definition_lists'] = [ ["""\ term definition """, """\ <document source="test data"> <definition_list> <definition_list_item> <term> term <definition> <paragraph> definition """], ["""\ term definition paragraph """, """\ <document source="test data"> <definition_list> <definition_list_item> <term> term <definition> <paragraph> definition <paragraph> paragraph """], ["""\ term definition no blank line """, """\ <document source="test data"> <definition_list> <definition_list_item> <term> term <definition> <paragraph> definition <system_message level="2" line="3" source="test data" type="WARNING"> <paragraph> Definition list ends without a blank line; unexpected unindent. <paragraph> no blank line """], ["""\ A paragraph:: A literal block without a blank line first? """, """\ <document source="test data"> <definition_list> <definition_list_item> <term> A paragraph:: <definition> <system_message level="1" line="2" source="test data" type="INFO"> <paragraph> Blank line missing before literal block (after the "::")? Interpreted as a definition list item. <paragraph> A literal block without a blank line first? """], ["""\ this is not a term; a term may only be one line long this is not a definition """, """\ <document source="test data"> <paragraph> this is not a term; a term may only be one line long <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> Unexpected indentation. <block_quote> <paragraph> this is not a definition """], ["""\ term 1 definition 1 term 2 definition 2 """, """\ <document source="test data"> <definition_list> <definition_list_item> <term> term 1 <definition> <paragraph> definition 1 <definition_list_item> <term> term 2 <definition> <paragraph> definition 2 """], ["""\ term 1 definition 1 (no blank line below) term 2 definition 2 """, """\ <document source="test data"> <definition_list> <definition_list_item> <term> term 1 <definition> <paragraph> definition 1 (no blank line below) <definition_list_item> <term> term 2 <definition> <paragraph> definition 2 """], ["""\ term 1 definition 1 (no blank line below) term 2 definition 2 No blank line after the definition list. """, """\ <document source="test data"> <definition_list> <definition_list_item> <term> term 1 <definition> <paragraph> definition 1 (no blank line below) <definition_list_item> <term> term 2 <definition> <paragraph> definition 2 <system_message level="2" line="5" source="test data" type="WARNING"> <paragraph> Definition list ends without a blank line; unexpected unindent. <paragraph> No blank line after the definition list. """], ["""\ term 1 definition 1 term 1a definition 1a term 1b definition 1b term 2 definition 2 paragraph """, """\ <document source="test data"> <definition_list> <definition_list_item> <term> term 1 <definition> <paragraph> definition 1 <definition_list> <definition_list_item> <term> term 1a <definition> <paragraph> definition 1a <definition_list_item> <term> term 1b <definition> <paragraph> definition 1b <definition_list_item> <term> term 2 <definition> <paragraph> definition 2 <paragraph> paragraph """], ["""\ Term : classifier The ' : ' indicates a classifier in definition list item terms only. """, """\ <document source="test data"> <definition_list> <definition_list_item> <term> Term <classifier> classifier <definition> <paragraph> The ' : ' indicates a classifier in definition list item terms only. """], ["""\ Term: not a classifier Because there's no space before the colon. Term :not a classifier Because there's no space after the colon. Term \: not a classifier Because the colon is escaped. """, """\ <document source="test data"> <definition_list> <definition_list_item> <term> Term: not a classifier <definition> <paragraph> Because there's no space before the colon. <definition_list_item> <term> Term :not a classifier <definition> <paragraph> Because there's no space after the colon. <definition_list_item> <term> Term : not a classifier <definition> <paragraph> Because the colon is escaped. """], ["""\ ``Term : not a classifier`` Because the ' : ' is inside an inline literal. """, """\ <document source="test data"> <definition_list> <definition_list_item> <term> <literal> Term : not a classifier <definition> <paragraph> Because the ' : ' is inside an inline literal. """], ["""\ Term `with *inline ``text **errors : classifier `with *errors ``too Definition `with *inline ``text **markup errors. """, """\ <document source="test data"> <definition_list> <definition_list_item> <term> Term \n\ <problematic ids="id2" refid="id1"> ` with \n\ <problematic ids="id4" refid="id3"> * inline \n\ <problematic ids="id6" refid="id5"> `` text \n\ <problematic ids="id8" refid="id7"> ** errors <classifier> classifier \n\ <problematic ids="id10" refid="id9"> ` with \n\ <problematic ids="id12" refid="id11"> * errors \n\ <problematic ids="id14" refid="id13"> `` too <definition> <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline interpreted text or phrase reference start-string without end-string. <system_message backrefs="id4" ids="id3" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline emphasis start-string without end-string. <system_message backrefs="id6" ids="id5" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline literal start-string without end-string. <system_message backrefs="id8" ids="id7" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline strong start-string without end-string. <system_message backrefs="id10" ids="id9" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline interpreted text or phrase reference start-string without end-string. <system_message backrefs="id12" ids="id11" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline emphasis start-string without end-string. <system_message backrefs="id14" ids="id13" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline literal start-string without end-string. <paragraph> Definition \n\ <problematic ids="id16" refid="id15"> ` with \n\ <problematic ids="id18" refid="id17"> * inline \n\ <problematic ids="id20" refid="id19"> `` text \n\ <problematic ids="id22" refid="id21"> ** markup errors. <system_message backrefs="id16" ids="id15" level="2" line="2" source="test data" type="WARNING"> <paragraph> Inline interpreted text or phrase reference start-string without end-string. <system_message backrefs="id18" ids="id17" level="2" line="2" source="test data" type="WARNING"> <paragraph> Inline emphasis start-string without end-string. <system_message backrefs="id20" ids="id19" level="2" line="2" source="test data" type="WARNING"> <paragraph> Inline literal start-string without end-string. <system_message backrefs="id22" ids="id21" level="2" line="2" source="test data" type="WARNING"> <paragraph> Inline strong start-string without end-string. """], ["""\ Term : classifier one : classifier two Definition """, """\ <document source="test data"> <definition_list> <definition_list_item> <term> Term <classifier> classifier one <classifier> classifier two <definition> <paragraph> Definition """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_rst/test_line_blocks.py����������������������������������������0000775�0001750�0001750�00000017073�12123055732�026500� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_line_blocks.py 7638 2013-03-22 13:25:46Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for states.py. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['line_blocks'] = [ ["""\ | This is a line block. | Line breaks are *preserved*. | This is a second line block. | This is a third. """, """\ <document source="test data"> <line_block> <line> This is a line block. <line> Line breaks are \n\ <emphasis> preserved . <line_block> <line> This is a second line block. <line_block> <line> This is a third. """], ["""\ | In line blocks, | Initial indentation is *also* preserved. """, """\ <document source="test data"> <line_block> <line> In line blocks, <line_block> <line> Initial indentation is \n\ <emphasis> also preserved. """], ["""\ | Individual lines in line blocks *may* wrap, as indicated by the lack of a vertical bar prefix. | These are called "continuation lines". """, """\ <document source="test data"> <line_block> <line> Individual lines in line blocks <emphasis> may wrap, as indicated by the lack of a vertical bar prefix. <line> These are called "continuation lines". """], ["""\ | Inline markup in line blocks may also wrap *to continuation lines*. | But not to following lines. """, """\ <document source="test data"> <line_block> <line> Inline markup in line blocks may also wrap \n\ <emphasis> to continuation lines . <line> But not to following lines. """], ["""\ \\| This is not a line block. The vertical bar is simply part of a paragraph. """, """\ <document source="test data"> <paragraph> | This is not a line block. The vertical bar is simply part of a paragraph. """], ["""\ | This line block is incomplete. There should be a blank line before this paragraph. """, """\ <document source="test data"> <line_block> <line> This line block is incomplete. <system_message level="2" line="2" source="test data" type="WARNING"> <paragraph> Line block ends without a blank line. <paragraph> There should be a blank line before this paragraph. """], ["""\ | This line block contains | | blank lines. """, """\ <document source="test data"> <line_block> <line> This line block contains <line> <line> blank lines. """], ["""\ | The blank lines in this block | \n\ | \n\ | have bogus spaces. """, """\ <document source="test data"> <line_block> <line> The blank lines in this block <line> <line> <line> have bogus spaces. """], ["""\ | Initial indentation is also significant and preserved: | | Indented 4 spaces | Not indented | Indented 2 spaces | Indented 4 spaces | Only one space | | Continuation lines may be indented less than their base lines. """, """\ <document source="test data"> <line_block> <line> Initial indentation is also significant and preserved: <line> <line_block> <line> Indented 4 spaces <line> Not indented <line_block> <line_block> <line> Indented 2 spaces <line_block> <line> Indented 4 spaces <line> Only one space <line> <line_block> <line> Continuation lines may be indented less than their base lines. """], ["""\ | | This block begins and ends with blank lines. | """, """\ <document source="test data"> <line_block> <line> <line> This block begins and ends with blank lines. <line> """], ["""\ This is not | a line block. """, """\ <document source="test data"> <paragraph> This is not | a line block. """], ["""\ | The first line is indented. | The second line is more indented. """, """\ <document source="test data"> <line_block> <line> The first line is indented. <line_block> <line> The second line is more indented. """], ["""\ | The first line is indented. | The second line is less indented. """, """\ <document source="test data"> <line_block> <line_block> <line> The first line is indented. <line> The second line is less indented. """], ["""\ |This is not |a line block | This is an |incomplete line block. """, """\ <document source="test data"> <paragraph> <problematic ids="id2" refid="id1"> | This is not <problematic ids="id4" refid="id3"> | a line block <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline substitution_reference start-string without end-string. <system_message backrefs="id4" ids="id3" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline substitution_reference start-string without end-string. <line_block> <line> This is an <system_message level="2" line="5" source="test data" type="WARNING"> <paragraph> Line block ends without a blank line. <paragraph> <problematic ids="id6" refid="id5"> | incomplete line block. <system_message backrefs="id6" ids="id5" level="2" line="5" source="test data" type="WARNING"> <paragraph> Inline substitution_reference start-string without end-string. """], ["""\ | Inline markup *may not | wrap* over several lines. """, """\ <document source="test data"> <line_block> <line> Inline markup \n\ <problematic ids="id2" refid="id1"> * may not <line> wrap* over several lines. <system_message backrefs="id2" ids="id1" level="2" line="1" source="test data" type="WARNING"> <paragraph> Inline emphasis start-string without end-string. """], ["""\ | * Block level markup | * is not recognized. """, """\ <document source="test data"> <line_block> <line> * Block level markup <line> * is not recognized. """], ["""\ System messages can appear in place of lines: | `uff <test1>`_ | `uff <test2>`_ """, """\ <document source="test data"> <paragraph> System messages can appear in place of lines: <line_block> <line> <reference name="uff" refuri="test1"> uff <target dupnames="uff" ids="uff" refuri="test1"> <system_message backrefs="id1" level="2" line="3" source="test data" type="WARNING"> <paragraph> Duplicate explicit target name: "uff". <line> <reference name="uff" refuri="test2"> uff <target dupnames="uff" ids="id1" refuri="test2"> """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_parsers/test_parser.py������������������������������������������������������0000664�0001750�0001750�00000002241�11771146137�023635� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_parser.py 7463 2012-06-22 19:49:51Z milde $ # Author: Stefan Rank <strank(AT)strank(DOT)info> # Copyright: This module has been placed in the public domain. """ Tests for basic functionality of parser classes. """ import sys import unittest import DocutilsTestSupport # must be imported before docutils import docutils from docutils import parsers, utils, frontend from docutils._compat import b class RstParserTests(unittest.TestCase): def test_inputrestrictions(self): parser_class = parsers.get_parser_class('rst') parser = parser_class() document = utils.new_document('test data', frontend.OptionParser( components=(parser, )).get_default_values()) if sys.version_info < (3,): # supplying string input is supported, but only if ascii-decodable self.assertRaises(UnicodeDecodeError, parser.parse, b('hol%s' % chr(224)), document) else: # input must be unicode at all times self.assertRaises(TypeError, parser.parse, b('hol'), document) if __name__ == '__main__': unittest.main() ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/package_unittest.py��������������������������������������������������������������0000664�0001750�0001750�00000012343�11706115036�022112� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: package_unittest.py 7320 2012-01-19 22:33:02Z milde $ # Author: Garth Kidd <garth@deadlybloodyserious.com> # Copyright: This module has been placed in the public domain. """ This module extends unittest.py with `loadTestModules()`, by loading multiple test modules from a directory. Optionally, test packages are also loaded, recursively. """ import sys import os import getopt import types import unittest import re # So that individual test modules can share a bit of state, # `package_unittest` acts as an intermediary for the following # variables: debug = False verbosity = 1 USAGE = """\ Usage: test_whatever [options] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output -d, --debug Debug mode """ def usageExit(msg=None): """Print usage and exit.""" if msg: print msg print USAGE sys.exit(2) def parseArgs(argv=sys.argv): """Parse command line arguments and set TestFramework state. State is to be acquired by test_* modules by a grotty hack: ``from TestFramework import *``. For this stylistic transgression, I expect to be first up against the wall when the revolution comes. --Garth""" global verbosity, debug try: options, args = getopt.getopt(argv[1:], 'hHvqd', ['help', 'verbose', 'quiet', 'debug']) for opt, value in options: if opt in ('-h', '-H', '--help'): usageExit() if opt in ('-q', '--quiet'): verbosity = 0 if opt in ('-v', '--verbose'): verbosity = 2 if opt in ('-d', '--debug'): debug =1 if len(args) != 0: usageExit("No command-line arguments supported yet.") except getopt.error, msg: usageExit(msg) def loadTestModules(path, name='', packages=None): """ Return a test suite composed of all the tests from modules in a directory. Search for modules in directory `path`, beginning with `name`. If `packages` is true, search subdirectories (also beginning with `name`) recursively. Subdirectories must be Python packages; they must contain an '__init__.py' module. """ testLoader = unittest.defaultTestLoader testSuite = unittest.TestSuite() testModules = [] path = os.path.abspath(path) # current working dir if `path` empty paths = [path] while paths: p = paths.pop(0) files = os.listdir(p) for filename in files: if filename.startswith(name): fullpath = os.path.join(p, filename) if filename.endswith('.py'): fullpath = fullpath[len(path)+1:] testModules.append(path2mod(fullpath)) elif packages and os.path.isdir(fullpath) and \ os.path.isfile(os.path.join(fullpath, '__init__.py')): paths.append(fullpath) # Import modules and add their tests to the suite. sys.path.insert(0, path) for mod in testModules: if debug: print >>sys.stderr, "importing %s" % mod try: module = import_module(mod) except ImportError: print >>sys.stderr, "ERROR: Can't import %s, skipping its tests:" % mod sys.excepthook(*sys.exc_info()) else: # if there's a suite defined, incorporate its contents try: suite = getattr(module, 'suite') except AttributeError: # Look for individual tests moduleTests = testLoader.loadTestsFromModule(module) # unittest.TestSuite.addTests() doesn't work as advertised, # as it can't load tests from another TestSuite, so we have # to cheat: testSuite.addTest(moduleTests) continue if type(suite) == types.FunctionType: testSuite.addTest(suite()) elif isinstance(suite, unittest.TestSuite): testSuite.addTest(suite) else: raise AssertionError, "don't understand suite (%s)" % mod sys.path.pop(0) return testSuite def path2mod(path): """Convert a file path to a dotted module name.""" return path[:-3].replace(os.sep, '.') def import_module(name): """Import a dotted-path module name, and return the final component.""" mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod def main(suite=None): """ Shared `main` for any individual test_* file. suite -- TestSuite to run. If not specified, look for any globally defined tests and run them. """ parseArgs() if suite is None: # Load any globally defined tests. suite = unittest.defaultTestLoader.loadTestsFromModule( __import__('__main__')) if debug: print >>sys.stderr, "Debug: Suite=%s" % suite testRunner = unittest.TextTestRunner(verbosity=verbosity) # run suites (if we were called from test_all) or suite... if type(suite) == type([]): for s in suite: testRunner.run(s) else: return testRunner.run(suite) ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_viewlist.py�����������������������������������������������������������������0000775�0001750�0001750�00000015743�11771146137�021507� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_viewlist.py 7463 2012-06-22 19:49:51Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Test module for the ViewList class from statemachine.py. """ import unittest import sys import re from DocutilsTestSupport import statemachine class ViewListTests(unittest.TestCase): a_list = list('abcdefg') b_list = list('AEIOU') c_list = list('XYZ') def setUp(self): self.a = statemachine.ViewList(self.a_list, 'a') self.b = statemachine.ViewList(self.b_list, 'b') self.c = statemachine.ViewList(self.c_list, 'c') def test_xitems(self): self.assertEqual(list(self.b.xitems()), [('b', 0, 'A'), ('b', 1, 'E'), ('b', 2, 'I'), ('b', 3, 'O'), ('b', 4, 'U')]) self.assertEqual(list(self.c.xitems()), [('c', 0, 'X'), ('c', 1, 'Y'), ('c', 2, 'Z')]) def test_lists(self): # be compatible to standard lists whenever sensible: self.assertEqual(self.a, self.a_list) self.assertEqual(str(self.a), str(self.a_list)) self.assertEqual(self.b, self.b_list) self.assertEqual(self.c, self.c_list) self.assertEqual(len(self.a), len(self.a_list)) self.assertTrue('d' in self.a) # __contains__ self.assertEqual([value for value in self.a], self.a_list) # get and set values self.assertEqual(self.a[2], self.a_list[2]) a = self.a[:] self.assertEqual(a, self.a) a[1] = 3 self.assertEqual(a[1], 3) # the `items` list contains the metadata (source/offset tuples) self.assertEqual(self.a.items, [('a', i) for (i, v) in enumerate(self.a_list)]) def test_special_class_methods(self): # `repr` returns instantiation expression self.assertEqual(repr(self.a), "ViewList(%s, items=%s)" % (repr(self.a_list), repr(self.a.items))) # `del` also deletes meta-data: del(self.c[1]) self.assertEqual(list(self.c.xitems()), [('c', 0, 'X'), ('c', 2, 'Z')]) # operators with extended behaviour ab = self.a + self.b self.assertEqual(ab, self.a_list + self.b_list) self.assertEqual(ab.items, self.a.items + self.b.items) aa = self.a * 2 self.assertEqual(aa, self.a_list * 2) self.assertEqual(aa.items, self.a.items * 2) self.a += self.b self.assertEqual(self.a, self.a_list + self.b_list) # self.assertEqual(self.a.items, self.a.items + self.b.items) def test_get_slice(self): a = self.a[1:-1] a_list = self.a_list[1:-1] self.assertEqual(a, a_list) self.assertEqual(a.items, [('a', i+1) for (i, v) in enumerate(a_list)]) self.assertEqual(a.parent, self.a) # a.pprint() def test_set_slice(self): a = statemachine.ViewList(self.a[:]) s = a[2:-2] s[2:2] = self.b s_list = self.a_list[2:-2] s_list[2:2] = self.b_list # s.pprint() # s[1:4].pprint() self.assertEqual(s, s_list) self.assertEqual(s, a[2:-2]) self.assertEqual(s.items, a[2:-2].items) def test_del_slice(self): a = statemachine.ViewList(self.a[:]) s = a[2:] s_list = self.a_list[2:] del s[3:5] del s_list[3:5] self.assertEqual(s, s_list) self.assertEqual(s, a[2:]) self.assertEqual(s.items, a[2:].items) def test_insert(self): a_list = self.a_list[:] a_list.insert(2, 'Q') a_list[4:4] = self.b_list a = self.a[:] self.assertTrue(isinstance(a, statemachine.ViewList)) a.insert(2, 'Q', 'runtime') a.insert(4, self.b) self.assertEqual(a, a_list) self.assertEqual(a.info(2), ('runtime', 0)) self.assertEqual(a.info(5), ('b', 1)) def test_append(self): a_list = self.a_list[:] a_list.append('Q') a_list.extend(self.b_list) a = statemachine.ViewList(self.a) a.append('Q', 'runtime') a.append(self.b) # a.pprint() self.assertEqual(a, a_list) self.assertEqual(a.info(len(self.a)), ('runtime', 0)) self.assertEqual(a.info(-2), ('b', len(self.b) - 2)) def test_extend(self): a_list = self.a_list[:] a_list.extend(self.b_list) a = statemachine.ViewList(self.a) a.extend(self.b) self.assertEqual(a, a_list) self.assertEqual(a.info(len(self.a) + 1), ('b', 1)) # a.pprint() def test_view(self): a = statemachine.ViewList(self.a[:]) a.insert(4, self.b) s = a[2:-2] s.insert(5, self.c) self.assertEqual(s, a[2:-2]) self.assertEqual(s.items, a[2:-2].items) s.pop() self.assertEqual(s, a[2:-2]) self.assertEqual(s.items, a[2:-2].items) s.remove('X') self.assertEqual(s, a[2:-2]) self.assertEqual(s.items, a[2:-2].items) def test_trim(self): a = statemachine.ViewList(self.a[:]) s = a[1:-1] s.trim_start(1) self.assertEqual(a, self.a) self.assertEqual(s, a[2:-1]) s.trim_end(1) self.assertEqual(a, self.a) self.assertEqual(s, a[2:-2]) def test_info(self): ab = self.a + self.b self.assertEqual(ab.info(0), ('a', 0)) self.assertEqual(ab.info(-1), ('b', len(self.b)-1)) # report source if index is off the list by one self.assertEqual(ab.info(len(ab)), ('b', None)) # `source` and `offset` methods are based on info self.assertEqual(ab.source(-1), 'b') self.assertEqual(ab.offset(-1), len(self.b)-1) def test_reverse(self): c = self.c[:] c.reverse() self.assertEqual(list(c.xitems()), [('c', 2, 'Z'), ('c', 1, 'Y'), ('c', 0, 'X')]) def test_sort(self): c = self.c[:] c.reverse() # c.pprint() c.sort() self.assertEqual(self.c, c) # print # print a # print s # print a.items # print s.items class StringList(unittest.TestCase): text = """\ This is some example text. Here is some indented text. Unindented text. """ indented_string = """\ a literal block""" def setUp(self): self.a_list = self.text.splitlines(1) self.a = statemachine.StringList(self.a_list, 'a') def test_trim_left(self): s = self.a[3:5] s.trim_left(4) self.assertEqual(s, [line.lstrip() for line in self.a_list[3:5]]) def test_get_indented(self): self.assertEqual(self.a.get_indented(), ([], 0, 0)) block = statemachine.StringList( statemachine.string2lines(self.indented_string)) self.assertEqual(block.get_indented(), ([s[6:] for s in block], 6, 1)) if __name__ == '__main__': unittest.main() �����������������������������docutils-0.12/test/test_readers/��������������������������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�020672� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_readers/test_get_reader_class.py��������������������������������������������0000664�0001750�0001750�00000001561�12016623750�025573� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_get_reader_class.py 7504 2012-08-27 07:55:20Z grubert $ # Author: grubert abadger1999 # Maintainer: docutils-develop@lists.sourceforge.net # Copyright: This module has been placed in the public domain. """ test get_reader_class """ from __init__ import DocutilsTestSupport from docutils.readers import get_reader_class class GetReaderClassTestCase(DocutilsTestSupport.StandardTestCase): def test_registered_reader(self): rdr = get_reader_class('pep') # raises ImportError on failure def test_bogus_reader(self): self.assertRaises(ImportError, get_reader_class, 'nope') def test_local_reader(self): # requires local-reader.py in test directory (testroot) wr = get_reader_class('local-reader') if __name__ == '__main__': import unittest unittest.main() �����������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_readers/__init__.py���������������������������������������������������������0000664�0001750�0001750�00000000462�10254646615�023013� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������import os import os.path import sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) prev = '' while sys.path[0] != prev: try: import DocutilsTestSupport break except ImportError: prev = sys.path[0] sys.path[0] = os.path.dirname(prev) sys.path.pop(0) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_readers/test_pep/�����������������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�022515� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_readers/test_pep/test_inline_markup.py��������������������������������������0000775�0001750�0001750�00000006264�10434150472�026773� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_inline_markup.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for inline markup in PEPs (readers/pep.py). """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.PEPParserTestSuite() s.generateTests(totest) return s totest = {} totest['standalone_references'] = [ ["""\ See PEP 287 (pep-0287.txt), and RFC 2822 (which obsoletes RFC822 and RFC-733). """, """\ <document source="test data"> <paragraph> See \n\ <reference refuri="http://www.python.org/dev/peps/pep-0287"> PEP 287 ( <reference refuri="http://www.python.org/dev/peps/pep-0287"> pep-0287.txt ), and \n\ <reference refuri="http://www.faqs.org/rfcs/rfc2822.html"> RFC 2822 (which obsoletes \n\ <reference refuri="http://www.faqs.org/rfcs/rfc822.html"> RFC822 and \n\ <reference refuri="http://www.faqs.org/rfcs/rfc733.html"> RFC-733 ). """], ["""\ References split across lines: PEP 287 RFC 2822 """, """\ <document source="test data"> <paragraph> References split across lines: <paragraph> <reference refuri="http://www.python.org/dev/peps/pep-0287"> PEP 287 <paragraph> <reference refuri="http://www.faqs.org/rfcs/rfc2822.html"> RFC 2822 """], ["""\ Test PEP-specific implicit references before a URL: PEP 287 (http://www.python.org/dev/peps/pep-0287), RFC 2822. """, """\ <document source="test data"> <paragraph> Test PEP-specific implicit references before a URL: <paragraph> <reference refuri="http://www.python.org/dev/peps/pep-0287"> PEP 287 ( <reference refuri="http://www.python.org/dev/peps/pep-0287"> http://www.python.org/dev/peps/pep-0287 ), \n\ <reference refuri="http://www.faqs.org/rfcs/rfc2822.html"> RFC 2822 . """], ] totest['miscellaneous'] = [ ["""\ For *completeness*, _`let's` ``test`` **other** forms_ |of| `inline markup` [*]_. .. [*] See http://docutils.sf.net/docs/ref/rst/restructuredtext.html. """, """\ <document source="test data"> <paragraph> For \n\ <emphasis> completeness , \n\ <target ids="let-s" names="let's"> let's \n\ <literal> test \n\ <strong> other \n\ <reference name="forms" refname="forms"> forms \n\ <substitution_reference refname="of"> of \n\ <title_reference> inline markup \n\ <footnote_reference auto="*" ids="id1"> . <footnote auto="*" ids="id2"> <paragraph> See \n\ <reference refuri="http://docutils.sf.net/docs/ref/rst/restructuredtext.html"> http://docutils.sf.net/docs/ref/rst/restructuredtext.html . """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_readers/test_pep/__init__.py������������������������������������������������0000664�0001750�0001750�00000000462�10254646615�024636� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������import os import os.path import sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) prev = '' while sys.path[0] != prev: try: import DocutilsTestSupport break except ImportError: prev = sys.path[0] sys.path[0] = os.path.dirname(prev) sys.path.pop(0) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_readers/test_pep/test_rfc2822.py��������������������������������������������0000775�0001750�0001750�00000013671�10434150472�025226� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_rfc2822.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for RFC-2822 headers in PEPs (readers/pep.py). """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.PEPParserTestSuite() s.generateTests(totest) return s totest = {} totest['rfc2822'] = [ ["""\ Author: Me Version: 1 Date: 2002-04-23 """, """\ <document source="test data"> <field_list classes="rfc2822"> <field> <field_name> Author <field_body> <paragraph> Me <field> <field_name> Version <field_body> <paragraph> 1 <field> <field_name> Date <field_body> <paragraph> 2002-04-23 """], ["""\ Author: Me Version: 1 Date: 2002-04-23 .. Leading blank lines don't affect RFC-2822 header parsing. """, """\ <document source="test data"> <field_list classes="rfc2822"> <field> <field_name> Author <field_body> <paragraph> Me <field> <field_name> Version <field_body> <paragraph> 1 <field> <field_name> Date <field_body> <paragraph> 2002-04-23 <comment xml:space="preserve"> Leading blank lines don't affect RFC-2822 header parsing. """], ["""\ .. A comment should prevent RFC-2822 header parsing. Author: Me Version: 1 Date: 2002-04-23 """, """\ <document source="test data"> <comment xml:space="preserve"> A comment should prevent RFC-2822 header parsing. <paragraph> Author: Me Version: 1 Date: 2002-04-23 """], ["""\ Author: Me Version: 1 Date: 2002-04-23 """, """\ <document source="test data"> <field_list classes="rfc2822"> <field> <field_name> Author <field_body> <paragraph> Me <paragraph> Version: 1 Date: 2002-04-23 """], ["""\ field: empty item above, no blank line """, """\ <document source="test data"> <field_list classes="rfc2822"> <field> <field_name> field <field_body> <system_message level="2" line="2" source="test data" type="WARNING"> <paragraph> RFC2822-style field list ends without a blank line; unexpected unindent. <paragraph> empty item above, no blank line """], ["""\ Author: Me Version: 1 Date: 2002-04-23 """, """\ <document source="test data"> <field_list classes="rfc2822"> <field> <field_name> Author <field_body> <paragraph> Me <field> <field_name> Version <field_body> <paragraph> 1 <field> <field_name> Date <field_body> <paragraph> 2002-04-23 """], ["""\ Authors: Me, Myself, and I Version: 1 or so Date: 2002-04-23 (Tuesday) """, """\ <document source="test data"> <field_list classes="rfc2822"> <field> <field_name> Authors <field_body> <paragraph> Me, Myself, and I <field> <field_name> Version <field_body> <paragraph> 1 or so <field> <field_name> Date <field_body> <paragraph> 2002-04-23 (Tuesday) """], ["""\ Authors: Me, Myself, and I Version: 1 or so Date: 2002-04-23 (Tuesday) """, """\ <document source="test data"> <field_list classes="rfc2822"> <field> <field_name> Authors <field_body> <paragraph> Me, Myself, and I <field> <field_name> Version <field_body> <paragraph> 1 or so <field> <field_name> Date <field_body> <paragraph> 2002-04-23 (Tuesday) """], ["""\ Authors: - Me - Myself - I Version: """, """\ <document source="test data"> <field_list classes="rfc2822"> <field> <field_name> Authors <field_body> <bullet_list bullet="-"> <list_item> <paragraph> Me <list_item> <paragraph> Myself <list_item> <paragraph> I <field> <field_name> Version <field_body> """], ["""\ Authors: Me Myself and I Version: """, """\ <document source="test data"> <field_list classes="rfc2822"> <field> <field_name> Authors <field_body> <paragraph> Me <block_quote> <paragraph> Myself and I <system_message level="2" line="4" source="test data" type="WARNING"> <paragraph> Block quote ends without a blank line; unexpected unindent. <paragraph> Version: """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite') �����������������������������������������������������������������������docutils-0.12/test/test_command_line.py�������������������������������������������������������������0000664�0001750�0001750�00000002730�12153360646�022251� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # .. coding: utf-8 # $Id: test_command_line.py 7668 2013-06-04 12:46:30Z milde $ # Author: Günter Milde <milde@users.sourceforge.net> # Copyright: This module has been placed in the public domain. """ Test module for the command line. """ import unittest import sys, codecs import DocutilsTestSupport # must be imported before docutils import docutils.core # determine/guess the encoding of the standard input: try: import locale # module missing in Jython locale_encoding = locale.getlocale()[1] or locale.getdefaultlocale()[1] except ImportError: locale_encoding = None argv_encoding = locale_encoding or 'ascii' try: codecs.lookup(argv_encoding) except LookupError: argv_encoding = 'ascii' class CommandLineEncodingTests(unittest.TestCase): def test_sys_argv_decoding(self): if argv_encoding == 'ascii': # cannot test return sys.argv.append('--source-url=test.txt') # pure ASCII argument if sys.version_info < (3,0): sys.argv.append(u'--title=Dornröschen'.encode(argv_encoding)) else: sys.argv.append(u'--title=Dornröschen') publisher = docutils.core.Publisher() publisher.process_command_line() self.assertEqual(publisher.settings.source_url, 'test.txt') self.assertEqual(publisher.settings.title, u'Dornröschen') sys.argv.pop() # --title sys.argv.pop() # --source-url if __name__ == '__main__': unittest.main() ����������������������������������������docutils-0.12/test/test_nodes.py��������������������������������������������������������������������0000775�0001750�0001750�00000100064�12304116367�020733� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # -*- coding: utf-8 -*- # $Id: test_nodes.py 7746 2014-02-28 14:28:07Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Test module for nodes.py. """ import sys import unittest import types import DocutilsTestSupport # must be imported before docutils from DocutilsTestSupport import nodes, utils from docutils._compat import b debug = False class TextTests(unittest.TestCase): def setUp(self): self.text = nodes.Text('Line 1.\nLine 2.') self.unicode_text = nodes.Text(u'Möhren') self.longtext = nodes.Text('Mary had a little lamb whose ' 'fleece was white as snow and ' 'everwhere that Mary went the ' 'lamb was sure to go.') def test_repr(self): self.assertEqual(repr(self.text), r"<#text: 'Line 1.\nLine 2.'>") self.assertEqual(self.text.shortrepr(), r"<#text: 'Line 1.\nLine 2.'>") self.assertEqual(nodes.reprunicode('foo'), u'foo') if sys.version_info < (3,): self.assertEqual(repr(self.unicode_text), r"<#text: 'M\xf6hren'>") else: self.assertEqual(repr(self.unicode_text), u"<#text: 'Möhren'>") def test_str(self): self.assertEqual(str(self.text), 'Line 1.\nLine 2.') def test_unicode(self): self.assertEqual(unicode(self.unicode_text), u'Möhren') self.assertEqual(str(self.unicode_text), 'M\xf6hren') def test_astext(self): self.assertTrue(isinstance(self.text.astext(), unicode)) self.assertEqual(self.text.astext(), u'Line 1.\nLine 2.') self.assertEqual(self.unicode_text.astext(), u'Möhren') def test_pformat(self): self.assertTrue(isinstance(self.text.pformat(), unicode)) self.assertEqual(self.text.pformat(), u'Line 1.\nLine 2.\n') def test_asciirestriction(self): if sys.version_info < (3,): self.assertRaises(UnicodeDecodeError, nodes.Text, b('hol%s' % chr(224))) else: # no bytes at all allowed self.assertRaises(TypeError, nodes.Text, b('hol')) def test_longrepr(self): self.assertEqual(repr(self.longtext), r"<#text: 'Mary had a " r"little lamb whose fleece was white as snow " r"and everwh ...'>") self.assertEqual(self.longtext.shortrepr(), r"<#text: 'Mary had a lit ...'>") class ElementTests(unittest.TestCase): def test_empty(self): element = nodes.Element() self.assertEqual(repr(element), '<Element: >') self.assertEqual(str(element), '<Element/>') dom = element.asdom() self.assertEqual(dom.toxml(), '<Element/>') dom.unlink() element['attr'] = '1' self.assertEqual(repr(element), '<Element: >') self.assertEqual(str(element), '<Element attr="1"/>') dom = element.asdom() self.assertEqual(dom.toxml(), '<Element attr="1"/>') dom.unlink() self.assertEqual(element.pformat(), '<Element attr="1">\n') del element['attr'] element['mark'] = u'\u2022' self.assertEqual(repr(element), '<Element: >') if sys.version_info < (3,): self.assertEqual(str(element), '<Element mark="\\u2022"/>') else: self.assertEqual(str(element), u'<Element mark="\u2022"/>') dom = element.asdom() self.assertEqual(dom.toxml(), u'<Element mark="\u2022"/>') dom.unlink() element['names'] = ['nobody', u'имя', u'näs'] if sys.version_info < (3,): self.assertEqual(repr(element), '<Element "nobody; \\u0438\\u043c\\u044f; n\\xe4s": >') else: self.assertEqual(repr(element), u'<Element "nobody; имя; näs": >') self.assertTrue(isinstance(repr(element), str)) def test_withtext(self): element = nodes.Element('text\nmore', nodes.Text('text\nmore')) uelement = nodes.Element(u'grün', nodes.Text(u'grün')) self.assertEqual(repr(element), r"<Element: <#text: 'text\nmore'>>") if sys.version_info < (3,): self.assertEqual(repr(uelement), "<Element: <#text: 'gr\\xfcn'>>") else: self.assertEqual(repr(uelement), u"<Element: <#text: 'grün'>>") self.assertTrue(isinstance(repr(uelement),str)) self.assertEqual(str(element), '<Element>text\nmore</Element>') self.assertEqual(str(uelement), '<Element>gr\xfcn</Element>') dom = element.asdom() self.assertEqual(dom.toxml(), '<Element>text\nmore</Element>') dom.unlink() element['attr'] = '1' self.assertEqual(repr(element), r"<Element: <#text: 'text\nmore'>>") self.assertEqual(str(element), '<Element attr="1">text\nmore</Element>') dom = element.asdom() self.assertEqual(dom.toxml(), '<Element attr="1">text\nmore</Element>') dom.unlink() self.assertEqual(element.pformat(), '<Element attr="1">\n text\n more\n') def test_clear(self): element = nodes.Element() element += nodes.Element() self.assertTrue(len(element)) element.clear() self.assertTrue(not len(element)) def test_normal_attributes(self): element = nodes.Element() self.assertTrue('foo' not in element) self.assertRaises(KeyError, element.__getitem__, 'foo') element['foo'] = 'sometext' self.assertEqual(element['foo'], 'sometext') del element['foo'] self.assertRaises(KeyError, element.__getitem__, 'foo') def test_default_attributes(self): element = nodes.Element() self.assertEqual(element['ids'], []) self.assertEqual(element.non_default_attributes(), {}) self.assertTrue(not element.is_not_default('ids')) self.assertTrue(element['ids'] is not nodes.Element()['ids']) element['ids'].append('someid') self.assertEqual(element['ids'], ['someid']) self.assertEqual(element.non_default_attributes(), {'ids': ['someid']}) self.assertTrue(element.is_not_default('ids')) def test_update_basic_atts(self): element1 = nodes.Element(ids=['foo', 'bar'], test=['test1']) element2 = nodes.Element(ids=['baz', 'qux'], test=['test2']) element1.update_basic_atts(element2) # 'ids' are appended because 'ids' is a basic attribute. self.assertEqual(element1['ids'], ['foo', 'bar', 'baz', 'qux']) # 'test' is not overwritten because it is not a basic attribute. self.assertEqual(element1['test'], ['test1']) def test_update_all_atts(self): # Note: Also tests is_not_list_attribute and is_not_known_attribute # and various helpers ## Test for full attribute replacement element1 = nodes.Element(ids=['foo', 'bar'], parent_only='parent', all_nodes='mom') element2 = nodes.Element(ids=['baz', 'qux'], child_only='child', all_nodes='dad', source='source') # Test for when same fields are replaced as well as source... element1.update_all_atts_consistantly(element2, True, True) # 'ids' are appended because 'ids' is a basic attribute. self.assertEquals(element1['ids'], ['foo', 'bar', 'baz', 'qux']) # 'parent_only' should remain unaffected. self.assertEquals(element1['parent_only'], 'parent') # 'all_nodes' is overwritten due to the second parameter == True. self.assertEquals(element1['all_nodes'], 'dad') # 'child_only' should have been added. self.assertEquals(element1['child_only'], 'child') # 'source' is also overwritten due to the third parameter == True. self.assertEquals(element1['source'], 'source') # Test for when same fields are replaced but not source... element1 = nodes.Element(ids=['foo', 'bar'], parent_only='parent', all_nodes='mom') element1.update_all_atts_consistantly(element2) # 'ids' are appended because 'ids' is a basic attribute. self.assertEquals(element1['ids'], ['foo', 'bar', 'baz', 'qux']) # 'parent_only' should remain unaffected. self.assertEquals(element1['parent_only'], 'parent') # 'all_nodes' is overwritten due to the second parameter default of True. self.assertEquals(element1['all_nodes'], 'dad') # 'child_only' should have been added. self.assertEquals(element1['child_only'], 'child') # 'source' remains unset due to the third parameter default of False. self.assertEquals(element1.get('source'), None) # Test for when fields are NOT replaced but source is... element1 = nodes.Element(ids=['foo', 'bar'], parent_only='parent', all_nodes='mom') element1.update_all_atts_consistantly(element2, False, True) # 'ids' are appended because 'ids' is a basic attribute. self.assertEquals(element1['ids'], ['foo', 'bar', 'baz', 'qux']) # 'parent_only' should remain unaffected. self.assertEquals(element1['parent_only'], 'parent') # 'all_nodes' is preserved due to the second parameter == False. self.assertEquals(element1['all_nodes'], 'mom') # 'child_only' should have been added. self.assertEquals(element1['child_only'], 'child') # 'source' is added due to the third parameter == True. self.assertEquals(element1['source'], 'source') element1 = nodes.Element(source='destination') element1.update_all_atts_consistantly(element2, False, True) # 'source' remains unchanged due to the second parameter == False. self.assertEquals(element1['source'], 'destination') # Test for when same fields are replaced but not source... element1 = nodes.Element(ids=['foo', 'bar'], parent_only='parent', all_nodes='mom') element1.update_all_atts_consistantly(element2, False) # 'ids' are appended because 'ids' is a basic attribute. self.assertEquals(element1['ids'], ['foo', 'bar', 'baz', 'qux']) # 'parent_only' should remain unaffected. self.assertEquals(element1['parent_only'], 'parent') # 'all_nodes' is preserved due to the second parameter == False. self.assertEquals(element1['all_nodes'], 'mom') # 'child_only' should have been added. self.assertEquals(element1['child_only'], 'child') # 'source' remains unset due to the third parameter default of False. self.assertEquals(element1.get('source'), None) ## Test for List attribute merging # Attribute Concatination element1 = nodes.Element(ss='a', sl='1', ls=['I'], ll=['A']) element2 = nodes.Element(ss='b', sl=['2'], ls='II', ll=['B']) element1.update_all_atts_concatenating(element2) # 'ss' is replaced because non-list self.assertEquals(element1['ss'], 'b') # 'sl' is replaced because they are both not lists self.assertEquals(element1['sl'], ['2']) # 'ls' is replaced because they are both not lists self.assertEquals(element1['ls'], 'II') # 'll' is extended because they are both lists self.assertEquals(element1['ll'], ['A', 'B']) # Attribute Coercion element1 = nodes.Element(ss='a', sl='1', ls=['I'], ll=['A']) element2 = nodes.Element(ss='b', sl=['2'], ls='II', ll=['B']) element1.update_all_atts_coercion(element2) # 'ss' is replaced because non-list self.assertEquals(element1['ss'], 'b') # 'sl' is converted to a list and appended because element2 has a list self.assertEquals(element1['sl'], ['1', '2']) # 'ls' has element2's value appended to the list self.assertEquals(element1['ls'], ['I', 'II']) # 'll' is extended because they are both lists self.assertEquals(element1['ll'], ['A', 'B']) # Attribute Conversion element1 = nodes.Element(ss='a', sl='1', ls=['I'], ll=['A']) element2 = nodes.Element(ss='b', sl=['2'], ls='II', ll=['B']) element1.update_all_atts_convert(element2) # 'ss' is converted to a list with the values from each element self.assertEquals(element1['ss'], ['a', 'b']) # 'sl' is converted to a list and appended self.assertEquals(element1['sl'], ['1', '2']) # 'ls' has element2's value appended to the list self.assertEquals(element1['ls'], ['I', 'II']) # 'll' is extended self.assertEquals(element1['ll'], ['A', 'B']) def test_replace_self(self): parent = nodes.Element(ids=['parent']) child1 = nodes.Element(ids=['child1']) grandchild = nodes.Element(ids=['grandchild']) child1 += grandchild child2 = nodes.Element(ids=['child2']) twins = [nodes.Element(ids=['twin%s' % i]) for i in (1, 2)] child2 += twins child3 = nodes.Element(ids=['child3']) child4 = nodes.Element(ids=['child4']) parent += [child1, child2, child3, child4] self.assertEqual(parent.pformat(), """\ <Element ids="parent"> <Element ids="child1"> <Element ids="grandchild"> <Element ids="child2"> <Element ids="twin1"> <Element ids="twin2"> <Element ids="child3"> <Element ids="child4"> """) # Replace child1 with the grandchild. child1.replace_self(child1[0]) self.assertEqual(parent[0], grandchild) # Assert that 'ids' have been updated. self.assertEqual(grandchild['ids'], ['grandchild', 'child1']) # Replace child2 with its children. child2.replace_self(child2[:]) self.assertEqual(parent[1:3], twins) # Assert that 'ids' have been propagated to first child. self.assertEqual(twins[0]['ids'], ['twin1', 'child2']) self.assertEqual(twins[1]['ids'], ['twin2']) # Replace child3 with new child. newchild = nodes.Element(ids=['newchild']) child3.replace_self(newchild) self.assertEqual(parent[3], newchild) self.assertEqual(newchild['ids'], ['newchild', 'child3']) # Crazy but possible case: Substitute child4 for itself. child4.replace_self(child4) # Make sure the 'child4' ID hasn't been duplicated. self.assertEqual(child4['ids'], ['child4']) self.assertEqual(len(parent), 5) def test_unicode(self): node = nodes.Element(u'Möhren', nodes.Text(u'Möhren', u'Möhren')) self.assertEqual(unicode(node), u'<Element>Möhren</Element>') class MiscTests(unittest.TestCase): def test_reprunicode(self): # return `unicode` instance self.assertTrue(isinstance(nodes.reprunicode('foo'), unicode)) self.assertEqual(nodes.reprunicode('foo'), u'foo') self.assertEqual(nodes.reprunicode(u'Möhre'), u'Möhre') if sys.version_info < (3,): # strip leading "u" from representation self.assertEqual(repr(nodes.reprunicode(u'Möhre')), repr(u'Möhre')[1:]) else: # no change to `unicode` under Python 3k self.assertEqual(repr(nodes.reprunicode(u'Möhre')), repr(u'Möhre')) def test_ensure_str(self): self.assertTrue(isinstance(nodes.ensure_str(u'über'), str)) self.assertEqual(nodes.ensure_str('over'), 'over') if sys.version_info < (3,): # strip leading "u" from representation self.assertEqual(nodes.ensure_str(u'über'), r'\xfcber') else: self.assertEqual(nodes.ensure_str(u'über'), r'über') def test_node_class_names(self): node_class_names = [] for x in dir(nodes): c = getattr(nodes, x) if isinstance(c, (type, types.ClassType)) and \ issubclass(c, nodes.Node) and len(c.__bases__) > 1: node_class_names.append(x) node_class_names.sort() nodes.node_class_names.sort() self.assertEqual(node_class_names, nodes.node_class_names) ids = [(u'a', 'a'), ('A', 'a'), ('', ''), ('a b \n c', 'a-b-c'), ('a.b.c', 'a-b-c'), (' - a - b - c - ', 'a-b-c'), (' - ', ''), (u'\u2020\u2066', ''), (u'a \xa7 b \u2020 c', 'a-b-c'), ('1', ''), ('1abc', 'abc'), ] ids_unicode_all = [ (u'\u00f8 o with stroke', 'o-o-with-stroke'), (u'\u0111 d with stroke', 'd-d-with-stroke'), (u'\u0127 h with stroke', 'h-h-with-stroke'), (u'\u0131 dotless i', 'i-dotless-i'), (u'\u0142 l with stroke', 'l-l-with-stroke'), (u'\u0167 t with stroke', 't-t-with-stroke'), # From Latin Extended-B (u'\u0180 b with stroke', 'b-b-with-stroke'), (u'\u0183 b with topbar', 'b-b-with-topbar'), (u'\u0188 c with hook', 'c-c-with-hook'), (u'\u018c d with topbar', 'd-d-with-topbar'), (u'\u0192 f with hook', 'f-f-with-hook'), (u'\u0199 k with hook', 'k-k-with-hook'), (u'\u019a l with bar', 'l-l-with-bar'), (u'\u019e n with long right leg', 'n-n-with-long-right-leg'), (u'\u01a5 p with hook', 'p-p-with-hook'), (u'\u01ab t with palatal hook', 't-t-with-palatal-hook'), (u'\u01ad t with hook', 't-t-with-hook'), (u'\u01b4 y with hook', 'y-y-with-hook'), (u'\u01b6 z with stroke', 'z-z-with-stroke'), (u'\u01e5 g with stroke', 'g-g-with-stroke'), (u'\u0225 z with hook', 'z-z-with-hook'), (u'\u0234 l with curl', 'l-l-with-curl'), (u'\u0235 n with curl', 'n-n-with-curl'), (u'\u0236 t with curl', 't-t-with-curl'), (u'\u0237 dotless j', 'j-dotless-j'), (u'\u023c c with stroke', 'c-c-with-stroke'), (u'\u023f s with swash tail', 's-s-with-swash-tail'), (u'\u0240 z with swash tail', 'z-z-with-swash-tail'), (u'\u0247 e with stroke', 'e-e-with-stroke'), (u'\u0249 j with stroke', 'j-j-with-stroke'), (u'\u024b q with hook tail', 'q-q-with-hook-tail'), (u'\u024d r with stroke', 'r-r-with-stroke'), (u'\u024f y with stroke', 'y-y-with-stroke'), # From Latin-1 Supplements (u'\u00e0: a with grave', 'a-a-with-grave'), (u'\u00e1 a with acute', 'a-a-with-acute'), (u'\u00e2 a with circumflex', 'a-a-with-circumflex'), (u'\u00e3 a with tilde', 'a-a-with-tilde'), (u'\u00e4 a with diaeresis', 'a-a-with-diaeresis'), (u'\u00e5 a with ring above', 'a-a-with-ring-above'), (u'\u00e7 c with cedilla', 'c-c-with-cedilla'), (u'\u00e8 e with grave', 'e-e-with-grave'), (u'\u00e9 e with acute', 'e-e-with-acute'), (u'\u00ea e with circumflex', 'e-e-with-circumflex'), (u'\u00eb e with diaeresis', 'e-e-with-diaeresis'), (u'\u00ec i with grave', 'i-i-with-grave'), (u'\u00ed i with acute', 'i-i-with-acute'), (u'\u00ee i with circumflex', 'i-i-with-circumflex'), (u'\u00ef i with diaeresis', 'i-i-with-diaeresis'), (u'\u00f1 n with tilde', 'n-n-with-tilde'), (u'\u00f2 o with grave', 'o-o-with-grave'), (u'\u00f3 o with acute', 'o-o-with-acute'), (u'\u00f4 o with circumflex', 'o-o-with-circumflex'), (u'\u00f5 o with tilde', 'o-o-with-tilde'), (u'\u00f6 o with diaeresis', 'o-o-with-diaeresis'), (u'\u00f9 u with grave', 'u-u-with-grave'), (u'\u00fa u with acute', 'u-u-with-acute'), (u'\u00fb u with circumflex', 'u-u-with-circumflex'), (u'\u00fc u with diaeresis', 'u-u-with-diaeresis'), (u'\u00fd y with acute', 'y-y-with-acute'), (u'\u00ff y with diaeresis', 'y-y-with-diaeresis'), # From Latin Extended-A (u'\u0101 a with macron', 'a-a-with-macron'), (u'\u0103 a with breve', 'a-a-with-breve'), (u'\u0105 a with ogonek', 'a-a-with-ogonek'), (u'\u0107 c with acute', 'c-c-with-acute'), (u'\u0109 c with circumflex', 'c-c-with-circumflex'), (u'\u010b c with dot above', 'c-c-with-dot-above'), (u'\u010d c with caron', 'c-c-with-caron'), (u'\u010f d with caron', 'd-d-with-caron'), (u'\u0113 e with macron', 'e-e-with-macron'), (u'\u0115 e with breve', 'e-e-with-breve'), (u'\u0117 e with dot above', 'e-e-with-dot-above'), (u'\u0119 e with ogonek', 'e-e-with-ogonek'), (u'\u011b e with caron', 'e-e-with-caron'), (u'\u011d g with circumflex', 'g-g-with-circumflex'), (u'\u011f g with breve', 'g-g-with-breve'), (u'\u0121 g with dot above', 'g-g-with-dot-above'), (u'\u0123 g with cedilla', 'g-g-with-cedilla'), (u'\u0125 h with circumflex', 'h-h-with-circumflex'), (u'\u0129 i with tilde', 'i-i-with-tilde'), (u'\u012b i with macron', 'i-i-with-macron'), (u'\u012d i with breve', 'i-i-with-breve'), (u'\u012f i with ogonek', 'i-i-with-ogonek'), (u'\u0133 ligature ij', 'ij-ligature-ij'), (u'\u0135 j with circumflex', 'j-j-with-circumflex'), (u'\u0137 k with cedilla', 'k-k-with-cedilla'), (u'\u013a l with acute', 'l-l-with-acute'), (u'\u013c l with cedilla', 'l-l-with-cedilla'), (u'\u013e l with caron', 'l-l-with-caron'), (u'\u0140 l with middle dot', 'l-l-with-middle-dot'), (u'\u0144 n with acute', 'n-n-with-acute'), (u'\u0146 n with cedilla', 'n-n-with-cedilla'), (u'\u0148 n with caron', 'n-n-with-caron'), (u'\u014d o with macron', 'o-o-with-macron'), (u'\u014f o with breve', 'o-o-with-breve'), (u'\u0151 o with double acute', 'o-o-with-double-acute'), (u'\u0155 r with acute', 'r-r-with-acute'), (u'\u0157 r with cedilla', 'r-r-with-cedilla'), (u'\u0159 r with caron', 'r-r-with-caron'), (u'\u015b s with acute', 's-s-with-acute'), (u'\u015d s with circumflex', 's-s-with-circumflex'), (u'\u015f s with cedilla', 's-s-with-cedilla'), (u'\u0161 s with caron', 's-s-with-caron'), (u'\u0163 t with cedilla', 't-t-with-cedilla'), (u'\u0165 t with caron', 't-t-with-caron'), (u'\u0169 u with tilde', 'u-u-with-tilde'), (u'\u016b u with macron', 'u-u-with-macron'), (u'\u016d u with breve', 'u-u-with-breve'), (u'\u016f u with ring above', 'u-u-with-ring-above'), (u'\u0171 u with double acute', 'u-u-with-double-acute'), (u'\u0173 u with ogonek', 'u-u-with-ogonek'), (u'\u0175 w with circumflex', 'w-w-with-circumflex'), (u'\u0177 y with circumflex', 'y-y-with-circumflex'), (u'\u017a z with acute', 'z-z-with-acute'), (u'\u017c z with dot above', 'z-z-with-dot-above'), (u'\u017e z with caron', 'z-z-with-caron'), # From Latin Extended-B (u'\u01a1 o with horn', 'o-o-with-horn'), (u'\u01b0 u with horn', 'u-u-with-horn'), (u'\u01c6 dz with caron', 'dz-dz-with-caron'), (u'\u01c9 lj', 'lj-lj'), (u'\u01cc nj', 'nj-nj'), (u'\u01ce a with caron', 'a-a-with-caron'), (u'\u01d0 i with caron', 'i-i-with-caron'), (u'\u01d2 o with caron', 'o-o-with-caron'), (u'\u01d4 u with caron', 'u-u-with-caron'), (u'\u01e7 g with caron', 'g-g-with-caron'), (u'\u01e9 k with caron', 'k-k-with-caron'), (u'\u01eb o with ogonek', 'o-o-with-ogonek'), (u'\u01ed o with ogonek and macron', 'o-o-with-ogonek-and-macron'), (u'\u01f0 j with caron', 'j-j-with-caron'), (u'\u01f3 dz', 'dz-dz'), (u'\u01f5 g with acute', 'g-g-with-acute'), (u'\u01f9 n with grave', 'n-n-with-grave'), (u'\u0201 a with double grave', 'a-a-with-double-grave'), (u'\u0203 a with inverted breve', 'a-a-with-inverted-breve'), (u'\u0205 e with double grave', 'e-e-with-double-grave'), (u'\u0207 e with inverted breve', 'e-e-with-inverted-breve'), (u'\u0209 i with double grave', 'i-i-with-double-grave'), (u'\u020b i with inverted breve', 'i-i-with-inverted-breve'), (u'\u020d o with double grave', 'o-o-with-double-grave'), (u'\u020f o with inverted breve', 'o-o-with-inverted-breve'), (u'\u0211 r with double grave', 'r-r-with-double-grave'), (u'\u0213 r with inverted breve', 'r-r-with-inverted-breve'), (u'\u0215 u with double grave', 'u-u-with-double-grave'), (u'\u0217 u with inverted breve', 'u-u-with-inverted-breve'), (u'\u0219 s with comma below', 's-s-with-comma-below'), (u'\u021b t with comma below', 't-t-with-comma-below'), (u'\u021f h with caron', 'h-h-with-caron'), (u'\u0227 a with dot above', 'a-a-with-dot-above'), (u'\u0229 e with cedilla', 'e-e-with-cedilla'), (u'\u022f o with dot above', 'o-o-with-dot-above'), (u'\u0233 y with macron', 'y-y-with-macron'), # digraphs From Latin-1 Supplements (u'\u00df: ligature sz', 'sz-ligature-sz'), (u'\u00e6 ae', 'ae-ae'), (u'\u0153 ligature oe', 'oe-ligature-oe'), (u'\u0238 db digraph', 'db-db-digraph'), (u'\u0239 qp digraph', 'qp-qp-digraph'), ] def test_make_id(self): failures = [] tests = self.ids + self.ids_unicode_all for input, expect in tests: output = nodes.make_id(input) if expect != output: failures.append("'%s' != '%s'" % (expect, output)) if failures: self.fail("%d failures in %d\n%s" % (len(failures), len(self.ids), "\n".join(failures))) def test_traverse(self): e = nodes.Element() e += nodes.Element() e[0] += nodes.Element() e[0] += nodes.TextElement() e[0][1] += nodes.Text('some text') e += nodes.Element() e += nodes.Element() self.assertEqual(list(e.traverse()), [e, e[0], e[0][0], e[0][1], e[0][1][0], e[1], e[2]]) self.assertEqual(list(e.traverse(include_self=False)), [e[0], e[0][0], e[0][1], e[0][1][0], e[1], e[2]]) self.assertEqual(list(e.traverse(descend=False)), [e]) self.assertEqual(list(e[0].traverse(descend=False, ascend=True)), [e[0], e[1], e[2]]) self.assertEqual(list(e[0][0].traverse(descend=False, ascend=True)), [e[0][0], e[0][1], e[1], e[2]]) self.assertEqual(list(e[0][0].traverse(descend=False, siblings=True)), [e[0][0], e[0][1]]) self.testlist = e[0:2] self.assertEqual(list(e.traverse(condition=self.not_in_testlist)), [e, e[0][0], e[0][1], e[0][1][0], e[2]]) # Return siblings despite siblings=False because ascend is true. self.assertEqual(list(e[1].traverse(ascend=True, siblings=False)), [e[1], e[2]]) self.assertEqual(list(e[0].traverse()), [e[0], e[0][0], e[0][1], e[0][1][0]]) self.testlist = [e[0][0], e[0][1]] self.assertEqual(list(e[0].traverse(condition=self.not_in_testlist)), [e[0], e[0][1][0]]) self.testlist.append(e[0][1][0]) self.assertEqual(list(e[0].traverse(condition=self.not_in_testlist)), [e[0]]) self.assertEqual(list(e.traverse(nodes.TextElement)), [e[0][1]]) def test_next_node(self): e = nodes.Element() e += nodes.Element() e[0] += nodes.Element() e[0] += nodes.TextElement() e[0][1] += nodes.Text('some text') e += nodes.Element() e += nodes.Element() self.testlist = [e[0], e[0][1], e[1]] compare = [(e, e[0][0]), (e[0], e[0][0]), (e[0][0], e[0][1][0]), (e[0][1], e[0][1][0]), (e[0][1][0], e[2]), (e[1], e[2]), (e[2], None)] for node, next_node in compare: self.assertEqual(node.next_node(self.not_in_testlist, ascend=True), next_node) self.assertEqual(e[0][0].next_node(ascend=True), e[0][1]) self.assertEqual(e[2].next_node(), None) def not_in_testlist(self, x): return x not in self.testlist def test_copy(self): grandchild = nodes.Text('rawsource') child = nodes.emphasis('rawsource', grandchild, att='child') e = nodes.Element('rawsource', child, att='e') # Shallow copy: e_copy = e.copy() self.assertTrue(e is not e_copy) # Internal attributes (like `rawsource`) are also copied. self.assertEqual(e.rawsource, 'rawsource') self.assertEqual(e_copy.rawsource, e.rawsource) self.assertEqual(e_copy['att'], 'e') # Children are not copied. self.assertEqual(len(e_copy), 0) # Deep copy: e_deepcopy = e.deepcopy() self.assertEqual(e_deepcopy.rawsource, e.rawsource) self.assertEqual(e_deepcopy['att'], 'e') # Children are copied recursively. self.assertEqual(e_deepcopy[0][0], grandchild) self.assertTrue(e_deepcopy[0][0] is not grandchild) self.assertEqual(e_deepcopy[0]['att'], 'child') class TreeCopyVisitorTests(unittest.TestCase): def setUp(self): document = utils.new_document('test data') document += nodes.paragraph('', 'Paragraph 1.') blist = nodes.bullet_list() for i in range(1, 6): item = nodes.list_item() for j in range(1, 4): item += nodes.paragraph('', 'Item %s, paragraph %s.' % (i, j)) blist += item document += blist self.document = document def compare_trees(self, one, two): self.assertEqual(one.__class__, two.__class__) self.assertNotEqual(id(one), id(two)) self.assertEqual(len(one.children), len(two.children)) for i in range(len(one.children)): self.compare_trees(one.children[i], two.children[i]) def test_copy_whole(self): visitor = nodes.TreeCopyVisitor(self.document) self.document.walkabout(visitor) newtree = visitor.get_tree_copy() self.assertEqual(self.document.pformat(), newtree.pformat()) self.compare_trees(self.document, newtree) class MiscFunctionTests(unittest.TestCase): names = [('a', 'a'), ('A', 'a'), ('A a A', 'a a a'), ('A a A a', 'a a a a'), (' AaA\n\r\naAa\tAaA\t\t', 'aaa aaa aaa')] def test_normalize_name(self): for input, output in self.names: normed = nodes.fully_normalize_name(input) self.assertEqual(normed, output) def test_set_id_default(self): # Default prefixes. document = utils.new_document('test') # From name. element = nodes.Element(names=['test']) document.set_id(element) self.assertEqual(element['ids'], ['test']) # Auto-generated. element = nodes.Element() document.set_id(element) self.assertEqual(element['ids'], ['id1']) def test_set_id_custom(self): # Custom prefixes. document = utils.new_document('test') # Change settings. document.settings.id_prefix = 'prefix' document.settings.auto_id_prefix = 'auto' # From name. element = nodes.Element(names=['test']) document.set_id(element) self.assertEqual(element['ids'], ['prefixtest']) # Auto-generated. element = nodes.Element() document.set_id(element) self.assertEqual(element['ids'], ['prefixauto1']) if __name__ == '__main__': unittest.main() ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_io.py�����������������������������������������������������������������������0000775�0001750�0001750�00000016435�12115207312�020231� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#! /usr/bin/env python # $Id: test_io.py 7622 2013-03-04 21:14:50Z milde $ # Author: Lea Wiemann <LeWiemann@gmail.com> # Copyright: This module has been placed in the public domain. """ Test module for io.py. """ import unittest, sys import DocutilsTestSupport # must be imported before docutils from docutils import io from docutils._compat import b, bytes from docutils.utils.error_reporting import locale_encoding from test_error_reporting import BBuf, UBuf class mock_stdout(UBuf): encoding = 'utf8' def __init__(self): self.buffer = BBuf() UBuf.__init__(self) class HelperTests(unittest.TestCase): def test_check_encoding_true(self): """Return `True` if lookup returns the same codec""" self.assertEqual(io.check_encoding(mock_stdout, 'utf8'), True) self.assertEqual(io.check_encoding(mock_stdout, 'utf-8'), True) self.assertEqual(io.check_encoding(mock_stdout, 'UTF-8'), True) def test_check_encoding_false(self): """Return `False` if lookup returns different codecs""" self.assertEqual(io.check_encoding(mock_stdout, 'ascii'), False) self.assertEqual(io.check_encoding(mock_stdout, 'latin-1'), False) def test_check_encoding_none(self): """Cases where the comparison fails.""" # stream.encoding is None: self.assertEqual(io.check_encoding(io.FileInput(), 'ascii'), None) # stream.encoding does not exist: self.assertEqual(io.check_encoding(BBuf, 'ascii'), None) # encoding is None: self.assertEqual(io.check_encoding(mock_stdout, None), None) # encoding is invalid self.assertEqual(io.check_encoding(mock_stdout, 'UTF-9'), None) class InputTests(unittest.TestCase): def test_bom(self): input = io.StringInput(source=b('\xef\xbb\xbf foo \xef\xbb\xbf bar'), encoding='utf8') # Assert BOMs are gone. self.assertEqual(input.read(), u' foo bar') # With unicode input: input = io.StringInput(source=u'\ufeff foo \ufeff bar') # Assert BOMs are still there. self.assertEqual(input.read(), u'\ufeff foo \ufeff bar') def test_coding_slug(self): input = io.StringInput(source=b("""\ .. -*- coding: ascii -*- data blah """)) data = input.read() self.assertEqual(input.successful_encoding, 'ascii') input = io.StringInput(source=b("""\ #! python # -*- coding: ascii -*- print "hello world" """)) data = input.read() self.assertEqual(input.successful_encoding, 'ascii') input = io.StringInput(source=b("""\ #! python # extraneous comment; prevents coding slug from being read # -*- coding: ascii -*- print "hello world" """)) data = input.read() self.assertNotEqual(input.successful_encoding, 'ascii') def test_bom_detection(self): source = u'\ufeffdata\nblah\n' input = io.StringInput(source=source.encode('utf-16-be')) data = input.read() self.assertEqual(input.successful_encoding, 'utf-16-be') input = io.StringInput(source=source.encode('utf-16-le')) data = input.read() self.assertEqual(input.successful_encoding, 'utf-16-le') input = io.StringInput(source=source.encode('utf-8')) data = input.read() self.assertEqual(input.successful_encoding, 'utf-8') def test_readlines(self): input = io.FileInput(source_path='data/include.txt') data = input.readlines() self.assertEqual(data, [u'Some include text.\n']) def test_heuristics_utf8(self): # if no encoding is given, try decoding with utf8: input = io.FileInput(source_path='functional/input/cyrillic.txt') data = input.read() if sys.version_info < (3,0): # in Py3k, the locale encoding is used without --input-encoding # skipping the heuristic self.assertEqual(input.successful_encoding, 'utf-8') def test_heuristics_no_utf8(self): # if no encoding is given and decoding with utf8 fails, # use either the locale encoding (if specified) or latin1: input = io.FileInput(source_path='data/latin1.txt') data = input.read() self.assertTrue(input.successful_encoding in (locale_encoding, 'latin-1')) if input.successful_encoding == 'latin-1': self.assertEqual(data, u'Gr\xfc\xdfe\n') def test_decode_unicode(self): # With the special value "unicode" or "Unicode": uniinput = io.Input(encoding='unicode') # keep unicode instances as-is self.assertEqual(uniinput.decode(u'ja'), u'ja') # raise AssertionError if data is not an unicode string self.assertRaises(AssertionError, uniinput.decode, b('ja')) class OutputTests(unittest.TestCase): bdata = b('\xfc') udata = u'\xfc' def setUp(self): self.bdrain = BBuf() """Buffer accepting binary strings (bytes)""" self.udrain = UBuf() """Buffer accepting unicode strings""" self.mock_stdout = mock_stdout() """Stub of sys.stdout under Python 3""" def test_write_unicode(self): fo = io.FileOutput(destination=self.udrain, encoding='unicode', autoclose=False) fo.write(self.udata) self.assertEqual(self.udrain.getvalue(), self.udata) def test_write_utf8(self): if sys.version_info >= (3,0): fo = io.FileOutput(destination=self.udrain, encoding='utf8', autoclose=False) fo.write(self.udata) self.assertEqual(self.udrain.getvalue(), self.udata) else: fo = io.FileOutput(destination=self.bdrain, encoding='utf8', autoclose=False) fo.write(self.udata) self.assertEqual(self.bdrain.getvalue(), self.udata.encode('utf8')) # With destination in binary mode, data must be binary string # and is written as-is: def test_write_bytes(self): fo = io.FileOutput(destination=self.bdrain, encoding='utf8', mode='wb', autoclose=False) fo.write(self.bdata) self.assertEqual(self.bdrain.getvalue(), self.bdata) # Test for Python 3 features: if sys.version_info >= (3,0): def test_write_bytes_to_stdout(self): # try writing data to `destination.buffer`, if data is # instance of `bytes` and writing to `destination` fails: fo = io.FileOutput(destination=self.mock_stdout) fo.write(self.bdata) self.assertEqual(self.mock_stdout.buffer.getvalue(), self.bdata) def test_encoding_clash_resolved(self): fo = io.FileOutput(destination=self.mock_stdout, encoding='latin1', autoclose=False) fo.write(self.udata) self.assertEqual(self.mock_stdout.buffer.getvalue(), self.udata.encode('latin1')) def test_encoding_clash_nonresolvable(self): del(self.mock_stdout.buffer) fo = io.FileOutput(destination=self.mock_stdout, encoding='latin1', autoclose=False) self.assertRaises(ValueError, fo.write, self.udata) if __name__ == '__main__': unittest.main() �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/test_functional.py���������������������������������������������������������������0000775�0001750�0001750�00000020132�12054671616�021767� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # $Id: test_functional.py 7539 2012-11-26 13:50:06Z milde $ # Author: Lea Wiemann <LeWiemann@gmail.com> # Copyright: This module has been placed in the public domain. """ Perform tests with the data in the functional/ directory. Read README.txt for details on how this is done. """ import sys import os import os.path import shutil import unittest import difflib import DocutilsTestSupport # must be imported before docutils import docutils import docutils.core datadir = 'functional' """The directory to store the data needed for the functional tests.""" def join_path(*args): return '/'.join(args) or '.' class FunctionalTestSuite(DocutilsTestSupport.CustomTestSuite): """Test suite containing test cases for all config files.""" def __init__(self): """Process all config files in functional/tests/.""" DocutilsTestSupport.CustomTestSuite.__init__(self) os.chdir(DocutilsTestSupport.testroot) self.clear_output_directory() self.added = 0 try: for root, dirs, files in os.walk(join_path(datadir, 'tests')): # Process all config files among `names` in `dirname`. A config # file is a Python file (*.py) which sets several variables. for name in files: if name.endswith('.py') and not name.startswith('_'): config_file_full_path = join_path(root, name) self.addTestCase(FunctionalTestCase, 'test', None, None, id=config_file_full_path, configfile=config_file_full_path) self.added += 1 except (AttributeError): # python2.2 does not have os.walk os.path.walk(join_path(datadir, 'tests'), self.walker, None) assert self.added, 'No functional tests found.' def clear_output_directory(self): files = os.listdir(os.path.join('functional', 'output')) for f in files: if f in ('README.txt', '.svn', 'CVS'): continue # don't touch the infrastructure path = os.path.join('functional', 'output', f) if os.path.isdir(path): shutil.rmtree(path) else: os.remove(path) def walker(self, dummy, dirname, names): """ Process all config files among `names` in `dirname`. This is a helper function for os.path.walk. A config file is a Python file (*.py) which sets several variables. """ for name in names: if name.endswith('.py') and not name.startswith('_'): config_file_full_path = join_path(dirname, name) self.addTestCase(FunctionalTestCase, 'test', None, None, id=config_file_full_path, configfile=config_file_full_path) self.added += 1 class FunctionalTestCase(DocutilsTestSupport.CustomTestCase): """Test case for one config file.""" no_expected_template = """\ Cannot find expected output at %(exp)s If the output in %(out)s is correct, move it to the expected/ dir and check it in: mv %(out)s %(exp)s svn add %(exp)s svn commit -m "<comment>" %(exp)s""" expected_output_differs_template = """\ The expected and actual output differs. Please compare the expected and actual output files: diff %(exp)s %(out)s\n' If the actual output is correct, please replace the expected output and check it in: mv %(out)s %(exp)s svn add %(exp)s svn commit -m "<comment>" %(exp)s""" def __init__(self, *args, **kwargs): """Set self.configfile, pass arguments to parent __init__.""" self.configfile = kwargs['configfile'] del kwargs['configfile'] DocutilsTestSupport.CustomTestCase.__init__(self, *args, **kwargs) def shortDescription(self): return 'test_functional.py: ' + self.configfile def test(self): """Process self.configfile.""" os.chdir(DocutilsTestSupport.testroot) # Keyword parameters for publish_file: namespace = {} # Initialize 'settings_overrides' for test settings scripts, # and disable configuration files: namespace['settings_overrides'] = {'_disable_config': True} # Read the variables set in the default config file and in # the current config file into namespace: defaultpy = open(join_path(datadir, 'tests', '_default.py')).read() exec(defaultpy, namespace) exec(open(self.configfile).read(), namespace) # Check for required settings: assert 'test_source' in namespace,\ "No 'test_source' supplied in " + self.configfile assert 'test_destination' in namespace,\ "No 'test_destination' supplied in " + self.configfile # Set source_path and destination_path if not given: namespace.setdefault('source_path', join_path(datadir, 'input', namespace['test_source'])) # Path for actual output: namespace.setdefault('destination_path', join_path(datadir, 'output', namespace['test_destination'])) # Path for expected output: expected_path = join_path(datadir, 'expected', namespace['test_destination']) # shallow copy of namespace to minimize: params = namespace.copy() # remove unneeded parameters: del params['test_source'] del params['test_destination'] # Delete private stuff like params['__builtins__']: for key in params.keys(): if key.startswith('_'): del params[key] # Get output (automatically written to the output/ directory # by publish_file): output = docutils.core.publish_file(**params) # ensure output is unicode output_encoding = params.get('output_encoding', 'utf-8') if sys.version_info < (3,0): try: output = output.decode(output_encoding) except UnicodeDecodeError: # failsafe output = output.decode('latin1', 'replace') # Normalize line endings: output = '\n'.join(output.splitlines()) # Get the expected output *after* writing the actual output. no_expected = self.no_expected_template % { 'exp': expected_path, 'out': params['destination_path']} self.assertTrue(os.access(expected_path, os.R_OK), no_expected) if sys.version_info < (3,0): f = open(expected_path, 'r') else: # samples are UTF8 encoded. 'rb' leads to errors with Python 3! f = open(expected_path, 'r', encoding='utf-8') # Normalize line endings: expected = '\n'.join(f.read().splitlines()) f.close() if sys.version_info < (3,0): try: expected = expected.decode(output_encoding) except UnicodeDecodeError: expected = expected.decode('latin1', 'replace') diff = self.expected_output_differs_template % { 'exp': expected_path, 'out': params['destination_path']} try: self.assertEqual(output, expected, diff) except AssertionError: diff = ''.join(difflib.unified_diff( expected.splitlines(True), output.splitlines(True), expected_path, params['destination_path'])) if sys.version_info < (3,0): diff = diff.encode(sys.stderr.encoding or 'ascii', 'replace') print >>sys.stderr, '\n%s:' % (self,) print >>sys.stderr, diff raise # Execute optional function containing extra tests: if '_test_more' in namespace: namespace['_test_more'](join_path(datadir, 'expected'), join_path(datadir, 'output'), self, namespace) def suite(): return FunctionalTestSuite() if __name__ == '__main__': unittest.main(defaultTest='suite') ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/DocutilsTestSupport.py�����������������������������������������������������������0000664�0001750�0001750�00000077557�12054671616�022635� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# $Id: DocutilsTestSupport.py 7539 2012-11-26 13:50:06Z milde $ # Authors: David Goodger <goodger@python.org>; # Garth Kidd <garth@deadlybloodyserious.com> # Copyright: This module has been placed in the public domain. """ Exports the following: :Modules: - `statemachine` is 'docutils.statemachine' - `nodes` is 'docutils.nodes' - `urischemes` is 'docutils.utils.urischemes' - `utils` is 'docutils.utils' - `transforms` is 'docutils.transforms' - `states` is 'docutils.parsers.rst.states' - `tableparser` is 'docutils.parsers.rst.tableparser' :Classes: - `StandardTestCase` - `CustomTestCase` - `CustomTestSuite` - `TransformTestCase` - `TransformTestSuite` - `ParserTestCase` - `ParserTestSuite` - `ParserTransformTestCase` - `PEPParserTestCase` - `PEPParserTestSuite` - `GridTableParserTestCase` - `GridTableParserTestSuite` - `SimpleTableParserTestCase` - `SimpleTableParserTestSuite` - `WriterPublishTestCase` - `LatexWriterPublishTestCase` - `PseudoXMLWriterPublishTestCase` - `HtmlWriterPublishTestCase` - `PublishTestSuite` - `HtmlFragmentTestSuite` - `DevNull` (output sink) """ __docformat__ = 'reStructuredText' import sys import os import unittest import re import inspect import traceback from pprint import pformat testroot = os.path.abspath(os.path.dirname(__file__) or os.curdir) os.chdir(testroot) if sys.version_info >= (3,0): sys.path.insert(0, os.path.normpath(os.path.join(testroot, '..', 'build', 'lib'))) sys.path.append(os.path.normpath(os.path.join(testroot, '..', 'build', 'lib', 'extras'))) else: sys.path.insert(0, os.path.normpath(os.path.join(testroot, '..'))) sys.path.append(os.path.normpath(os.path.join(testroot, '..', 'extras'))) sys.path.insert(0, testroot) try: import difflib import package_unittest import docutils import docutils.core from docutils import frontend, nodes, statemachine, utils from docutils.utils import urischemes from docutils.transforms import universal from docutils.parsers import rst from docutils.parsers.rst import states, tableparser, roles, languages from docutils.readers import standalone, pep from docutils.statemachine import StringList, string2lines from docutils._compat import bytes except ImportError: # The importing module (usually __init__.py in one of the # subdirectories) may catch ImportErrors in order to detect the # absence of DocutilsTestSupport in sys.path. Thus, ImportErrors # resulting from problems with importing Docutils modules must # caught here. traceback.print_exc() sys.exit(1) try: import mypdb as pdb except: import pdb # Hack to make repr(StringList) look like repr(list): StringList.__repr__ = StringList.__str__ class DevNull: """Output sink.""" def write(self, string): pass def close(self): pass class StandardTestCase(unittest.TestCase): """ Helper class, providing the same interface as unittest.TestCase, but with useful setUp and comparison methods. """ def setUp(self): os.chdir(testroot) def assertEqual(self, first, second, msg=None): """Fail if the two objects are unequal as determined by the '==' operator. """ if not first == second: raise self.failureException, ( msg or '%s != %s' % _format_str(first, second)) def assertNotEqual(self, first, second, msg=None): """Fail if the two objects are equal as determined by the '==' operator. """ if first == second: raise self.failureException, ( msg or '%s == %s' % _format_str(first, second)) # assertIn and assertNotIn: new in Python 2.7: def assertIn(self, a, b, msg=None): if a not in b: raise self.failureException, ( msg or '%s not in %s' % _format_str(a, b)) def assertNotIn(self, a, b, msg=None): if a in b: raise self.failureException, ( msg or '%s in %s' % _format_str(a, b)) # aliases for assertion methods, deprecated since Python 2.7 failUnlessEqual = assertEquals = assertEqual assertNotEquals = failIfEqual = assertNotEqual class CustomTestCase(StandardTestCase): """ Helper class, providing extended functionality over unittest.TestCase. The methods assertEqual and assertNotEqual have been overwritten to provide better support for multi-line strings. Furthermore, see the compare_output method and the parameter list of __init__. """ compare = difflib.Differ().compare """Comparison method shared by all subclasses.""" def __init__(self, method_name, input, expected, id, run_in_debugger=True, suite_settings=None): """ Initialise the CustomTestCase. Arguments: method_name -- name of test method to run. input -- input to the parser. expected -- expected output from the parser. id -- unique test identifier, used by the test framework. run_in_debugger -- if true, run this test under the pdb debugger. suite_settings -- settings overrides for this test suite. """ self.id = id self.input = input self.expected = expected self.run_in_debugger = run_in_debugger self.suite_settings = suite_settings.copy() or {} # Ring your mother. unittest.TestCase.__init__(self, method_name) def __str__(self): """ Return string conversion. Overridden to give test id, in addition to method name. """ return '%s; %s' % (self.id, unittest.TestCase.__str__(self)) def __repr__(self): return "<%s %s>" % (self.id, unittest.TestCase.__repr__(self)) def clear_roles(self): # Language-specific roles and roles added by the # "default-role" and "role" directives are currently stored # globally in the roles._roles dictionary. This workaround # empties that dictionary. roles._roles = {} def setUp(self): StandardTestCase.setUp(self) self.clear_roles() def compare_output(self, input, output, expected): """`input`, `output`, and `expected` should all be strings.""" if isinstance(input, unicode): input = input.encode('raw_unicode_escape') if sys.version_info > (3,): # API difference: Python 3's node.__str__ doesn't escape #assert expected is None or isinstance(expected, unicode) if isinstance(expected, bytes): expected = expected.decode('utf-8') if isinstance(output, bytes): output = output.decode('utf-8') else: if isinstance(expected, unicode): expected = expected.encode('raw_unicode_escape') if isinstance(output, unicode): output = output.encode('raw_unicode_escape') # Normalize line endings: if expected: expected = '\n'.join(expected.splitlines()) if output: output = '\n'.join(output.splitlines()) try: self.assertEqual(output, expected) except AssertionError, error: print >>sys.stderr, '\n%s\ninput:' % (self,) print >>sys.stderr, input try: comparison = ''.join(self.compare(expected.splitlines(1), output.splitlines(1))) print >>sys.stderr, '-: expected\n+: output' print >>sys.stderr, comparison except AttributeError: # expected or output not a string # alternative output for non-strings: print >>sys.stderr, 'expected: %r' % expected print >>sys.stderr, 'output: %r' % output raise error class CustomTestSuite(unittest.TestSuite): """ A collection of CustomTestCases. Provides test suite ID generation and a method for adding test cases. """ id = '' """Identifier for the TestSuite. Prepended to the TestCase identifiers to make identification easier.""" next_test_case_id = 0 """The next identifier to use for non-identified test cases.""" def __init__(self, tests=(), id=None, suite_settings=None): """ Initialize the CustomTestSuite. Arguments: id -- identifier for the suite, prepended to test cases. suite_settings -- settings overrides for this test suite. """ unittest.TestSuite.__init__(self, tests) self.suite_settings = suite_settings or {} if id is None: mypath = os.path.abspath( sys.modules[CustomTestSuite.__module__].__file__) outerframes = inspect.getouterframes(inspect.currentframe()) for outerframe in outerframes[1:]: if outerframe[3] != '__init__': callerpath = outerframe[1] if callerpath is None: # It happens sometimes. Why is a mystery. callerpath = os.getcwd() callerpath = os.path.abspath(callerpath) break mydir, myname = os.path.split(mypath) if not mydir: mydir = os.curdir if callerpath.startswith(mydir): self.id = callerpath[len(mydir) + 1:] # caller's module else: self.id = callerpath else: self.id = id def addTestCase(self, test_case_class, method_name, input, expected, id=None, run_in_debugger=False, **kwargs): """ Create a CustomTestCase in the CustomTestSuite. Also return it, just in case. Arguments: test_case_class -- the CustomTestCase to add method_name -- a string; CustomTestCase.method_name is the test input -- input to the parser. expected -- expected output from the parser. id -- unique test identifier, used by the test framework. run_in_debugger -- if true, run this test under the pdb debugger. """ if id is None: # generate id if required id = self.next_test_case_id self.next_test_case_id += 1 # test identifier will become suiteid.testid tcid = '%s: %s' % (self.id, id) # suite_settings may be passed as a parameter; # if not, set from attribute: kwargs.setdefault('suite_settings', self.suite_settings) # generate and add test case tc = test_case_class(method_name, input, expected, tcid, run_in_debugger=run_in_debugger, **kwargs) self.addTest(tc) return tc def generate_no_tests(self, *args, **kwargs): pass class TransformTestCase(CustomTestCase): """ Output checker for the transform. Should probably be called TransformOutputChecker, but I can deal with that later when/if someone comes up with a category of transform test cases that have nothing to do with the input and output of the transform. """ option_parser = frontend.OptionParser(components=(rst.Parser,)) settings = option_parser.get_default_values() settings.report_level = 1 settings.halt_level = 5 settings.debug = package_unittest.debug settings.warning_stream = DevNull() unknown_reference_resolvers = () def __init__(self, *args, **kwargs): self.transforms = kwargs['transforms'] """List of transforms to perform for this test case.""" self.parser = kwargs['parser'] """Input parser for this test case.""" del kwargs['transforms'], kwargs['parser'] # only wanted here CustomTestCase.__init__(self, *args, **kwargs) def supports(self, format): return 1 def test_transforms(self): if self.run_in_debugger: pdb.set_trace() settings = self.settings.copy() settings.__dict__.update(self.suite_settings) document = utils.new_document('test data', settings) self.parser.parse(self.input, document) # Don't do a ``populate_from_components()`` because that would # enable the Transformer's default transforms. document.transformer.add_transforms(self.transforms) document.transformer.add_transform(universal.TestMessages) document.transformer.components['writer'] = self document.transformer.apply_transforms() output = document.pformat() self.compare_output(self.input, output, self.expected) def test_transforms_verbosely(self): if self.run_in_debugger: pdb.set_trace() print '\n', self.id print '-' * 70 print self.input settings = self.settings.copy() settings.__dict__.update(self.suite_settings) document = utils.new_document('test data', settings) self.parser.parse(self.input, document) print '-' * 70 print document.pformat() for transformClass in self.transforms: transformClass(document).apply() output = document.pformat() print '-' * 70 print output self.compare_output(self.input, output, self.expected) class TransformTestSuite(CustomTestSuite): """ A collection of TransformTestCases. A TransformTestSuite instance manufactures TransformTestCases, keeps track of them, and provides a shared test fixture (a-la setUp and tearDown). """ def __init__(self, parser, suite_settings=None): self.parser = parser """Parser shared by all test cases.""" CustomTestSuite.__init__(self, suite_settings=suite_settings) def generateTests(self, dict, dictname='totest', testmethod='test_transforms'): """ Stock the suite with test cases generated from a test data dictionary. Each dictionary key (test type's name) maps to a tuple, whose first item is a list of transform classes and whose second item is a list of tests. Each test is a list: input, expected output, optional modifier. The optional third entry, a behavior modifier, can be 0 (temporarily disable this test) or 1 (run this test under the pdb debugger). Tests should be self-documenting and not require external comments. """ for name, (transforms, cases) in dict.items(): for casenum in range(len(cases)): case = cases[casenum] run_in_debugger = False if len(case)==3: # TODO: (maybe) change the 3rd argument to a dict, so it # can handle more cases by keyword ('disable', 'debug', # 'settings'), here and in other generateTests methods. # But there's also the method that # HtmlPublishPartsTestSuite uses <DJG> if case[2]: run_in_debugger = True else: continue self.addTestCase( TransformTestCase, testmethod, transforms=transforms, parser=self.parser, input=case[0], expected=case[1], id='%s[%r][%s]' % (dictname, name, casenum), run_in_debugger=run_in_debugger) class ParserTestCase(CustomTestCase): """ Output checker for the parser. Should probably be called ParserOutputChecker, but I can deal with that later when/if someone comes up with a category of parser test cases that have nothing to do with the input and output of the parser. """ parser = rst.Parser() """Parser shared by all ParserTestCases.""" option_parser = frontend.OptionParser(components=(rst.Parser,)) settings = option_parser.get_default_values() settings.report_level = 5 settings.halt_level = 5 settings.debug = package_unittest.debug def test_parser(self): if self.run_in_debugger: pdb.set_trace() settings = self.settings.copy() settings.__dict__.update(self.suite_settings) document = utils.new_document('test data', settings) self.parser.parse(self.input, document) output = document.pformat() self.compare_output(self.input, output, self.expected) class ParserTestSuite(CustomTestSuite): """ A collection of ParserTestCases. A ParserTestSuite instance manufactures ParserTestCases, keeps track of them, and provides a shared test fixture (a-la setUp and tearDown). """ test_case_class = ParserTestCase def generateTests(self, dict, dictname='totest'): """ Stock the suite with test cases generated from a test data dictionary. Each dictionary key (test type name) maps to a list of tests. Each test is a list: input, expected output, optional modifier. The optional third entry, a behavior modifier, can be 0 (temporarily disable this test) or 1 (run this test under the pdb debugger). Tests should be self-documenting and not require external comments. """ for name, cases in dict.items(): for casenum in range(len(cases)): case = cases[casenum] run_in_debugger = False if len(case)==3: if case[2]: run_in_debugger = True else: continue self.addTestCase( self.test_case_class, 'test_parser', input=case[0], expected=case[1], id='%s[%r][%s]' % (dictname, name, casenum), run_in_debugger=run_in_debugger) class PEPParserTestCase(ParserTestCase): """PEP-specific parser test case.""" parser = rst.Parser(rfc2822=True, inliner=rst.states.Inliner()) """Parser shared by all PEPParserTestCases.""" option_parser = frontend.OptionParser(components=(rst.Parser, pep.Reader)) settings = option_parser.get_default_values() settings.report_level = 5 settings.halt_level = 5 settings.debug = package_unittest.debug class PEPParserTestSuite(ParserTestSuite): """A collection of PEPParserTestCases.""" test_case_class = PEPParserTestCase class GridTableParserTestCase(CustomTestCase): parser = tableparser.GridTableParser() def test_parse_table(self): self.parser.setup(StringList(string2lines(self.input), 'test data')) try: self.parser.find_head_body_sep() self.parser.parse_table() output = self.parser.cells except Exception, details: output = '%s: %s' % (details.__class__.__name__, details) self.compare_output(self.input, pformat(output) + '\n', pformat(self.expected) + '\n') def test_parse(self): try: output = self.parser.parse(StringList(string2lines(self.input), 'test data')) except Exception, details: output = '%s: %s' % (details.__class__.__name__, details) self.compare_output(self.input, pformat(output) + '\n', pformat(self.expected) + '\n') class GridTableParserTestSuite(CustomTestSuite): """ A collection of GridTableParserTestCases. A GridTableParserTestSuite instance manufactures GridTableParserTestCases, keeps track of them, and provides a shared test fixture (a-la setUp and tearDown). """ test_case_class = GridTableParserTestCase def generateTests(self, dict, dictname='totest'): """ Stock the suite with test cases generated from a test data dictionary. Each dictionary key (test type name) maps to a list of tests. Each test is a list: an input table, expected output from parse_table(), expected output from parse(), optional modifier. The optional fourth entry, a behavior modifier, can be 0 (temporarily disable this test) or 1 (run this test under the pdb debugger). Tests should be self-documenting and not require external comments. """ for name, cases in dict.items(): for casenum in range(len(cases)): case = cases[casenum] run_in_debugger = False if len(case) == 4: if case[-1]: run_in_debugger = True else: continue self.addTestCase(self.test_case_class, 'test_parse_table', input=case[0], expected=case[1], id='%s[%r][%s]' % (dictname, name, casenum), run_in_debugger=run_in_debugger) self.addTestCase(self.test_case_class, 'test_parse', input=case[0], expected=case[2], id='%s[%r][%s]' % (dictname, name, casenum), run_in_debugger=run_in_debugger) class SimpleTableParserTestCase(GridTableParserTestCase): parser = tableparser.SimpleTableParser() class SimpleTableParserTestSuite(CustomTestSuite): """ A collection of SimpleTableParserTestCases. """ test_case_class = SimpleTableParserTestCase def generateTests(self, dict, dictname='totest'): """ Stock the suite with test cases generated from a test data dictionary. Each dictionary key (test type name) maps to a list of tests. Each test is a list: an input table, expected output from parse(), optional modifier. The optional third entry, a behavior modifier, can be 0 (temporarily disable this test) or 1 (run this test under the pdb debugger). Tests should be self-documenting and not require external comments. """ for name, cases in dict.items(): for casenum in range(len(cases)): case = cases[casenum] run_in_debugger = False if len(case) == 3: if case[-1]: run_in_debugger = True else: continue self.addTestCase(self.test_case_class, 'test_parse', input=case[0], expected=case[1], id='%s[%r][%s]' % (dictname, name, casenum), run_in_debugger=run_in_debugger) class PythonModuleParserTestCase(CustomTestCase): def test_parser(self): if self.run_in_debugger: pdb.set_trace() try: import compiler except ImportError: # skip on Python 3 return from docutils.readers.python import moduleparser module = moduleparser.parse_module(self.input, 'test data').pformat() output = str(module) self.compare_output(self.input, output, self.expected) def test_token_parser_rhs(self): if self.run_in_debugger: pdb.set_trace() try: import compiler except ImportError: # skip on Python 3 return from docutils.readers.python import moduleparser tr = moduleparser.TokenParser(self.input) output = tr.rhs(1) self.compare_output(self.input, output, self.expected) class PythonModuleParserTestSuite(CustomTestSuite): """ A collection of PythonModuleParserTestCase. """ def generateTests(self, dict, dictname='totest', testmethod='test_parser'): """ Stock the suite with test cases generated from a test data dictionary. Each dictionary key (test type's name) maps to a list of tests. Each test is a list: input, expected output, optional modifier. The optional third entry, a behavior modifier, can be 0 (temporarily disable this test) or 1 (run this test under the pdb debugger). Tests should be self-documenting and not require external comments. """ for name, cases in dict.items(): for casenum in range(len(cases)): case = cases[casenum] run_in_debugger = False if len(case)==3: if case[2]: run_in_debugger = True else: continue self.addTestCase( PythonModuleParserTestCase, testmethod, input=case[0], expected=case[1], id='%s[%r][%s]' % (dictname, name, casenum), run_in_debugger=run_in_debugger) class WriterPublishTestCase(CustomTestCase, docutils.SettingsSpec): """ Test case for publish. """ settings_default_overrides = {'_disable_config': True, 'strict_visitor': True} writer_name = '' # set in subclasses or constructor def __init__(self, *args, **kwargs): if 'writer_name' in kwargs: self.writer_name = kwargs['writer_name'] del kwargs['writer_name'] CustomTestCase.__init__(self, *args, **kwargs) def test_publish(self): if self.run_in_debugger: pdb.set_trace() output = docutils.core.publish_string( source=self.input, reader_name='standalone', parser_name='restructuredtext', writer_name=self.writer_name, settings_spec=self, settings_overrides=self.suite_settings) self.compare_output(self.input, output, self.expected) class PublishTestSuite(CustomTestSuite): def __init__(self, writer_name, suite_settings=None): """ `writer_name` is the name of the writer to use. """ CustomTestSuite.__init__(self, suite_settings=suite_settings) self.test_class = WriterPublishTestCase self.writer_name = writer_name def generateTests(self, dict, dictname='totest'): for name, cases in dict.items(): for casenum in range(len(cases)): case = cases[casenum] run_in_debugger = False if len(case)==3: if case[2]: run_in_debugger = True else: continue self.addTestCase( self.test_class, 'test_publish', input=case[0], expected=case[1], id='%s[%r][%s]' % (dictname, name, casenum), run_in_debugger=run_in_debugger, # Passed to constructor of self.test_class: writer_name=self.writer_name) class HtmlPublishPartsTestSuite(CustomTestSuite): def generateTests(self, dict, dictname='totest'): for name, (settings_overrides, cases) in dict.items(): settings = self.suite_settings.copy() settings.update(settings_overrides) for casenum in range(len(cases)): case = cases[casenum] run_in_debugger = False if len(case)==3: if case[2]: run_in_debugger = True else: continue self.addTestCase( HtmlWriterPublishPartsTestCase, 'test_publish', input=case[0], expected=case[1], id='%s[%r][%s]' % (dictname, name, casenum), run_in_debugger=run_in_debugger, suite_settings=settings) class HtmlWriterPublishPartsTestCase(WriterPublishTestCase): """ Test case for HTML writer via the publish_parts interface. """ writer_name = 'html' settings_default_overrides = \ WriterPublishTestCase.settings_default_overrides.copy() settings_default_overrides['stylesheet'] = '' def test_publish(self): if self.run_in_debugger: pdb.set_trace() parts = docutils.core.publish_parts( source=self.input, reader_name='standalone', parser_name='restructuredtext', writer_name=self.writer_name, settings_spec=self, settings_overrides=self.suite_settings) output = self.format_output(parts) # interpolate standard variables: expected = self.expected % {'version': docutils.__version__} self.compare_output(self.input, output, expected) standard_content_type_template = ('<meta http-equiv="Content-Type"' ' content="text/html; charset=%s" />\n') standard_generator_template = ( '<meta name="generator"' ' content="Docutils %s: http://docutils.sourceforge.net/" />\n') standard_html_meta_value = ( standard_content_type_template + standard_generator_template % docutils.__version__) standard_meta_value = standard_html_meta_value % 'utf-8' standard_html_prolog = """\ <?xml version="1.0" encoding="%s" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> """ def format_output(self, parts): """Minimize & standardize the output.""" # remove redundant parts & uninteresting parts: del parts['whole'] assert parts['body'] == parts['fragment'] del parts['body'] del parts['body_pre_docinfo'] del parts['body_prefix'] del parts['body_suffix'] del parts['head'] del parts['head_prefix'] del parts['encoding'] del parts['version'] # remove standard portions: parts['meta'] = parts['meta'].replace(self.standard_meta_value, '') parts['html_head'] = parts['html_head'].replace( self.standard_html_meta_value, '...') parts['html_prolog'] = parts['html_prolog'].replace( self.standard_html_prolog, '') # remove empty values: for key in parts.keys(): if not parts[key]: del parts[key] # standard output format: keys = parts.keys() keys.sort() output = [] for key in keys: output.append("%r: '''%s'''" % (key, parts[key])) if output[-1].endswith("\n'''"): output[-1] = output[-1][:-4] + "\\n'''" return '{' + ',\n '.join(output) + '}\n' def exception_data(func, *args, **kwds): """ Execute `func(*args, **kwds)` and return the resulting exception, the exception arguments, and the formatted exception string. """ try: func(*args, **kwds) except Exception, detail: return (detail, detail.args, '%s: %s' % (detail.__class__.__name__, detail)) def _format_str(*args): r""" Return a tuple containing representations of all args. Same as map(repr, args) except that it returns multi-line representations for strings containing newlines, e.g.:: '''\ foo \n\ bar baz''' instead of:: 'foo \nbar\n\nbaz' This is a helper function for CustomTestCase. """ return_tuple = [] for i in args: r = repr(i) if ( (isinstance(i, bytes) or isinstance(i, unicode)) and '\n' in i): stripped = '' if isinstance(i, unicode) and r.startswith('u'): stripped = r[0] r = r[1:] elif isinstance(i, bytes) and r.startswith('b'): stripped = r[0] r = r[1:] # quote_char = "'" or '"' quote_char = r[0] assert quote_char in ("'", '"'), quote_char assert r[0] == r[-1] r = r[1:-1] r = (stripped + 3 * quote_char + '\\\n' + re.sub(r'(?<!\\)((\\\\)*)\\n', r'\1\n', r) + 3 * quote_char) r = re.sub(r' \n', r' \\n\\\n', r) return_tuple.append(r) return tuple(return_tuple) �������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/coverage.sh����������������������������������������������������������������������0000775�0001750�0001750�00000002432�10773653743�020355� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/bin/bash # $Id: coverage.sh 5539 2008-03-30 09:05:39Z wiemann $ # Author: Lea Wiemann <LeWiemann@gmail.com> # Copyright: This script has been placed in the public domain. # Usage: ./coverage.sh [project, [module]] set -e # Resolve all symlinks in current path. cd -P . proj="${PWD##*/}" if test "$proj" == test; then cd .. proj="${PWD##*/}" fi if test "$1"; then proj="$1" fi module="${2:-alltests.py}" module="${module#test/}" echo "Performing code coverage test for project \"$proj\", test module \"$module\"..." echo echo "Please be patient; coverage tracking slows test execution down by more" echo "than factor 10." echo cd test rm -rf cover mkdir -p cover python -u -m trace --count --coverdir=cover --missing "$module" cd .. echo echo echo Uncovered lines echo =============== echo ( find "$proj/" -name \*.py | while read i; do i="${i%.py}" test -f test/cover/"${i//\//.}".cover -o "${i##*/}" == Template || echo "${i//\//.}" "`cat "$i.py" | wc -l`" done cd test/cover find . \( -name . -o ! -name "$proj".\* -exec rm {} \; \) for i in *.cover; do sed 's/^>>>>>> \(.*"""\)/ \1/' < "$i" > "${i%.cover}" rm "$i" done for i in *; do echo -n "$i "; grep -c '^>>>>>> ' "$i" || true; done ) | grep -v ' 0$' | sort -nk 2 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/����������������������������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�020350� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/����������������������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�021512� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/_standalone_rst_defaults.py�������������������������������������0000664�0001750�0001750�00000000306�11630242771�027131� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Keyword parameters passed to publish_file. reader_name = "standalone" parser_name = "rst" # Settings. settings_overrides['sectsubtitle_xform'] = 1 settings_overrides['syntax_highlight'] = 'none' ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/standalone_rst_latex.py�����������������������������������������0000664�0001750�0001750�00000000531�12072056102�026270� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������exec(open('functional/tests/_standalone_rst_defaults.py').read()) # Source and destination file names. test_source = "standalone_rst_latex.txt" test_destination = "standalone_rst_latex.tex" # Keyword parameters passed to publish_file. writer_name = "latex" # Settings # use "smartquotes" transition: settings_overrides['smart_quotes'] = True �����������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/latex_docinfo.py������������������������������������������������0000664�0001750�0001750�00000000447�10171754135�024710� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Source and destination file names. test_source = "latex_docinfo.txt" test_destination = "latex_docinfo.tex" # Keyword parameters passed to publish_file. reader_name = "standalone" parser_name = "rst" writer_name = "latex" # Extra setting we need settings_overrides['use_latex_docinfo'] = 1 �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/_default.py�����������������������������������������������������0000664�0001750�0001750�00000000367�11706115036�023652� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Default settings for all tests. settings_overrides['report_level'] = 2 settings_overrides['halt_level'] = 5 settings_overrides['warning_stream'] = '' settings_overrides['input_encoding'] = 'utf-8' settings_overrides['embed_stylesheet'] = False �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/math_output_latex.py��������������������������������������������0000664�0001750�0001750�00000000625�11763213420�025631� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Source and destination file names. test_source = "data/math.txt" test_destination = "math_output_latex.html" # Keyword parameters passed to publish_file. reader_name = "standalone" parser_name = "rst" writer_name = "html" # Settings settings_overrides['math_output'] = 'latex' # local copy of default stylesheet: settings_overrides['stylesheet_path'] = ( 'functional/input/data/html4css1.css') �����������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/math_output_mathml.py�������������������������������������������0000664�0001750�0001750�00000000626�11763213420�025777� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Source and destination file names. test_source = "data/math.txt" test_destination = "math_output_mathml.xhtml" # Keyword parameters passed to publish_file. reader_name = "standalone" parser_name = "rst" writer_name = "html" # Settings settings_overrides['math_output'] = 'MathML' # local copy of default stylesheet: settings_overrides['stylesheet_path'] = ( 'functional/input/data/html4css1.css') ����������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/math_output_html.py���������������������������������������������0000664�0001750�0001750�00000000657�11763213420�025465� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Source and destination file names. test_source = "data/math.txt" test_destination = "math_output_html.html" # Keyword parameters passed to publish_file. reader_name = "standalone" parser_name = "rst" writer_name = "html" # Extra settings settings_overrides['math_output'] = 'HTML' # stylesheets: settings_overrides['stylesheet_path'] = ( 'functional/input/data/html4css1.css,' 'functional/input/data/math.css') ���������������������������������������������������������������������������������docutils-0.12/test/functional/tests/math_output_mathjax.py������������������������������������������0000664�0001750�0001750�00000000634�11763213420�026150� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Source and destination file names. test_source = "data/math.txt" test_destination = "math_output_mathjax.html" # Keyword parameters passed to publish_file. reader_name = "standalone" parser_name = "rst" writer_name = "html" # Settings settings_overrides['math_output'] = 'MathJax' # local copy of default stylesheet: settings_overrides['stylesheet_path'] = ( 'functional/input/data/html4css1.css') ����������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/xetex_cyrillic.py�����������������������������������������������0000664�0001750�0001750�00000001033�12076016516�025111� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Source and destination file names. test_source = "cyrillic.txt" test_destination = "xetex-cyrillic.tex" # Keyword parameters passed to publish_file. writer_name = "xetex" # Settings settings_overrides['language_code'] = 'ru' # Override the automatic addition of "unicode" option for "russian" # language to work around a problem with cyrillic in PDF-bookmarks in # hyperref versions < v6.79g 2009/11/20 settings_overrides['hyperref_options'] = 'unicode=false' # use "smartquotes" transition: settings_overrides['smart_quotes'] = True �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/standalone_rst_s5_html_1.py�������������������������������������0000775�0001750�0001750�00000004743�11763213420�026766� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������exec(open('functional/tests/_standalone_rst_defaults.py').read()) # Source and destination file names: test_source = 'standalone_rst_s5_html.txt' test_destination = 'standalone_rst_s5_html_1.html' # Keyword parameters passed to publish_file: writer_name = 's5_html' # Settings: settings_overrides['theme'] = 'small-black' # local copy of default stylesheet: settings_overrides['stylesheet_path'] = ( 'functional/input/data/html4css1.css') # Extra functional tests. # Prefix all names with '_' to avoid confusing `docutils.core.publish_file`. import filecmp as _filecmp def _test_more(expected_dir, output_dir, test_case, parameters): """Compare ``ui/<theme>`` directories.""" theme = settings_overrides.get('theme', 'default') expected = '%s/%s/%s' % (expected_dir, 'ui', theme) output = '%s/%s/%s' % (output_dir, 'ui', theme) differences, uniques = _compare_directories(expected, output) parts = [] if differences: parts.append('The following files differ from the expected output:') parts.extend(differences) expected = [path.replace('functional/output/', 'functional/expected/') for path in differences] parts.append('Please compare the expected and actual output files:') parts.extend([' diff %s %s' % tup for tup in zip(expected, differences)]) parts.append('If the actual output is correct, please replace the ' 'expected output files:') parts.extend([' mv %s %s' % tup for tup in zip(differences, expected)]) parts.append('and check them in to Subversion:') parts.extend([' svn commit -m "<comment>" %s' % path for path in expected]) if uniques: parts.append('The following paths are unique:') parts.extend(uniques) test_case.assertTrue(not parts, '\n'.join(parts)) def _compare_directories(expected, output): dircmp = _filecmp.dircmp(expected, output, ['.svn', 'CVS']) differences = ['%s/%s' % (output, name) for name in dircmp.diff_files] uniques = (['%s/%s' % (expected, name) for name in dircmp.left_only] + ['%s/%s' % (output, name) for name in dircmp.right_only]) for subdir in dircmp.common_dirs: diffs, uniqs = _compare_directories('%s/%s' % (expected, subdir), '%s/%s' % (output, subdir)) differences.extend(diffs) uniques.extend(uniqs) return differences, uniques �����������������������������docutils-0.12/test/functional/tests/standalone_rst_html4css1.py�������������������������������������0000664�0001750�0001750�00000000710�12115207525�027001� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������exec(open('functional/tests/_standalone_rst_defaults.py').read()) # Source and destination file names. test_source = "standalone_rst_html4css1.txt" test_destination = "standalone_rst_html4css1.html" # Keyword parameters passed to publish_file. writer_name = "html4css1" # Settings: # local copy of stylesheets: # (Test runs in ``docutils/test/``, we need relative path from there.) settings_overrides['stylesheet_dirs'] = ('.', 'functional/input/data') ��������������������������������������������������������docutils-0.12/test/functional/tests/standalone_rst_s5_html_2.py�������������������������������������0000775�0001750�0001750�00000000465�11043302514�026756� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# initialize with the settings & definitions from test 1: exec(open('functional/tests/standalone_rst_s5_html_1.py').read()) # overrides specific to this test: test_destination = 'standalone_rst_s5_html_2.html' del settings_overrides['theme'] # use the default settings_overrides['current_slide'] = 1 �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/compact_lists.py������������������������������������������������0000664�0001750�0001750�00000000547�11763213420�024732� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Source and destination file names. test_source = "compact_lists.txt" test_destination = "compact_lists.html" # Keyword parameters passed to publish_file. reader_name = "standalone" parser_name = "rst" writer_name = "html" # Settings # local copy of default stylesheet: settings_overrides['stylesheet_path'] = ( 'functional/input/data/html4css1.css') ���������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/pep_html.py�����������������������������������������������������0000664�0001750�0001750�00000001050�11763213420�023664� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Source and destination file names. test_source = "pep_html.txt" test_destination = "pep_html.html" # Keyword parameters passed to publish_file. reader_name = "pep" parser_name = "rst" writer_name = "pep_html" # Settings settings_overrides['python_home'] = "http://www.python.org" settings_overrides['pep_home'] = "http://www.python.org/peps" settings_overrides['no_random'] = 1 settings_overrides['cloak_email_addresses'] = 1 # local copy of default stylesheet: settings_overrides['stylesheet_path'] = ( 'functional/input/data/html4css1.css') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/field_name_limit.py���������������������������������������������0000664�0001750�0001750�00000000711�11763213420�025340� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Source and destination file names. test_source = "field_list.txt" test_destination = "field_name_limit.html" # Keyword parameters passed to publish_file. reader_name = "standalone" parser_name = "rst" writer_name = "html" # Settings settings_overrides['field_name_limit'] = 0 # no limit settings_overrides['docinfo_xform'] = False # local copy of default stylesheet: settings_overrides['stylesheet_path'] = ( 'functional/input/data/html4css1.css') �������������������������������������������������������docutils-0.12/test/functional/tests/standalone_rst_xetex.py�����������������������������������������0000664�0001750�0001750�00000000531�12072056102�026310� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������exec(open('functional/tests/_standalone_rst_defaults.py').read()) # Source and destination file names. test_source = "standalone_rst_xetex.txt" test_destination = "standalone_rst_xetex.tex" # Keyword parameters passed to publish_file. writer_name = "xetex" # Settings # use "smartquotes" transition: settings_overrides['smart_quotes'] = True �����������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/standalone_rst_manpage.py���������������������������������������0000664�0001750�0001750�00000000411�11242572553�026573� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������exec(open('functional/tests/_standalone_rst_defaults.py').read()) # Source and destination file names. test_source = "standalone_rst_manpage.txt" test_destination = "standalone_rst_manpage.man" # Keyword parameters passed to publish_file. writer_name = "manpage" �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/latex_babel.py��������������������������������������������������0000664�0001750�0001750�00000000366�12076016516�024334� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Source and destination file names. test_source = "latex_babel.txt" test_destination = "latex_babel.tex" # Keyword parameters passed to publish_file. reader_name = "standalone" parser_name = "rst" writer_name = "latex" # Extra setting we need ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/tests/dangerous.py����������������������������������������������������0000664�0001750�0001750�00000000676�11763213420�024060� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Source and destination file names. test_source = "dangerous.txt" test_destination = "dangerous.html" # Keyword parameters passed to publish_file. reader_name = "standalone" parser_name = "rst" writer_name = "html" # Settings settings_overrides['file_insertion_enabled'] = False settings_overrides['raw_enabled'] = False # local copy of default stylesheet: settings_overrides['stylesheet_path'] = ( 'functional/input/data/html4css1.css') ������������������������������������������������������������������docutils-0.12/test/functional/tests/misc_rst_html4css1.py�������������������������������������������0000664�0001750�0001750�00000000655�11706115036�025614� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Source and destination file names. test_source = "link_in_substitution.txt" test_destination = "misc_rst_html4css1.html" # Keyword parameters passed to publish_file. reader_name = "standalone" parser_name = "rst" writer_name = "html4css1" # Settings # test for encoded attribute value: settings_overrides['stylesheet'] = 'foo&bar.css' settings_overrides['stylesheet_path'] = '' settings_overrides['embed_stylesheet'] = False �����������������������������������������������������������������������������������docutils-0.12/test/functional/tests/latex_cyrillic.py�����������������������������������������������0000664�0001750�0001750�00000000771�12076016516�025101� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Source and destination file names. test_source = "cyrillic.txt" test_destination = "cyrillic.tex" # Keyword parameters passed to publish_file. reader_name = "standalone" parser_name = "rst" writer_name = "latex" # Extra setting we need settings_overrides['hyperref_options'] = 'unicode=true' settings_overrides['font_encoding'] = 'T1,T2A' settings_overrides['stylesheet'] = 'cmlgc' settings_overrides['language_code'] = 'ru' # use "smartquotes" transition: settings_overrides['smart_quotes'] = True �������docutils-0.12/test/functional/tests/standalone_rst_pseudoxml.py�������������������������������������0000664�0001750�0001750�00000000564�11720535704�027212� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������exec(open('functional/tests/_standalone_rst_defaults.py').read()) # Source and destination file names. test_source = "standalone_rst_pseudoxml.txt" test_destination = "standalone_rst_pseudoxml.txt" # Keyword parameters passed to publish_file. writer_name = "pseudoxml" # Settings # enable INFO-level system messages in this test: settings_overrides['report_level'] = 1 ��������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/����������������������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�021507� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/simple.txt������������������������������������������������������0000664�0001750�0001750�00000000015�10210142265�023523� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������simple input �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/standalone_rst_pseudoxml.txt������������������������������������0000664�0001750�0001750�00000000355�10355367513�027400� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������.. include:: data/standard.txt .. include:: data/header_footer.txt .. include:: data/table_colspan.txt .. include:: data/table_rowspan.txt .. include:: data/table_complex.txt .. include:: data/list_table.txt .. include:: data/errors.txt �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/latex_babel.txt�������������������������������������������������0000664�0001750�0001750�00000001737�12076016516�024523� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������The babel_ package introduces the concept of "shorthands": additional characters that introduce a latex macro. Most common is the active double quote ("). Problematic is the tilde character (~) which is regularely used for no-break spaces but redefined by some language definition files: English: 'an' "active"-quote, ^circumflex, and no-break spaces .. class:: language-eu Basque: 'an' "active"-quote, ^circumflex, and no-break spaces .. class:: language-eo Esperanto: 'an' "active"-quote, ^circumflex, and no-break spaces .. class:: language-et Estonian: 'an' "active"-quote, ^circumflex, and no-break spaces .. class:: language-gl Galician: 'an' "active"-quote, ^circumflex, and no-break spaces .. class:: language-de German: 'an' "active"-quote, ^circumflex, and no-break spaces Spanish: option clash with Galician! .. .. class:: language-es Spanish: 'an' "active"-quote, ^circumflex, and no-break spaces .. _babel: http://www.ctan.org/packages/babel ���������������������������������docutils-0.12/test/functional/input/standalone_rst_latex.txt����������������������������������������0000664�0001750�0001750�00000001623�11710250064�026460� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������.. include:: data/standard.txt .. currently not implemented in LaTeX: .. include:: data/header_footer.txt .. include:: data/table_colspan.txt .. include:: data/table_rowspan.txt .. include:: data/custom_roles.txt .. include:: data/math.txt Tests for the LaTeX writer ========================== Test syntax elements which may cause trouble for the LaTeX writer but might not need to be tested with other writers (e.g. the HTML writer). .. include:: data/custom_roles_latex.txt .. include:: data/tables_latex.txt .. include:: data/option_lists.txt .. include:: data/nonalphanumeric.txt .. include:: data/unicode.txt .. include:: data/latex_encoding.txt .. include:: data/hyperlinking.txt .. include:: data/urls.txt .. include:: data/section_titles.txt .. unusual combinations (from newlatex, for interactive testing) .. include:: data/latex.txt .. Preface for System Messages: .. include:: data/errors.txt �������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/compact_lists.txt�����������������������������������������������0000664�0001750�0001750�00000001575�10350277141�025121� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������* This is an ordinary simple bullet list. * It should be made compact (<p> & </p> tags omitted). ********** * This is a bullet list that is not simple. There are multiple paragraphs in some items. * It should not be made compact. * Even though some items may have only one paragraph. ********** .. class:: open * This is a simple bullet list, but class="open" is set. * It should not be made compact. ********** .. class:: compact * This is a bullet list that is not simple. There are multiple paragraphs in some items. * However, the class="compact" setting will cause all first paragraph's <p> & </p> tags to be omitted. * Items with multiple paragraphs will not appear changed. * Items may have one paragraph, or multiple. Items with multiple paragraphs will still be followed by vertical whitespace because of the later paragraphs. * The effect is interesting. �����������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/standalone_rst_xetex.txt����������������������������������������0000664�0001750�0001750�00000002735�11710250064�026505� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������.. include:: data/standard.txt .. currently not implemented in LaTeX: .. include:: data/header_footer.txt .. include:: data/table_colspan.txt .. include:: data/table_rowspan.txt .. include:: data/custom_roles.txt Tests for the LaTeX writer ========================== Test syntax elements which may cause trouble for the LaTeX writer but might not need to be tested with other writers (e.g. the HTML writer). .. include:: data/custom_roles_latex.txt .. include:: data/option_lists.txt .. include:: data/nonalphanumeric.txt .. include:: data/unicode.txt .. include:: data/latex_encoding.txt .. include:: data/hyperlinking.txt .. include:: data/urls.txt .. include:: data/section_titles.txt Tests for the XeTeX writer ========================== With XeTeX, you can typeset text in any language/script supported by Unicode and the selected font, e.g. Azərbaycanca, Bân-lâm-gú, Башҡорт Беларуская, Български, Català, Чӑвашла, Česky, Ελληνικά, Español, Français, Føroyskt, Хальмг, Íslenska, עברית , Қазақша, Kurdî, Latviešu, Lietuvių, Македонски, Монгол, Nāhuatl, Português, Română, Русский, Slovenščina, Српски, Türkçe, Українська, Tiếng Việt, Volapük, Võro, ייִדיש , Žemaitėška. Currently, there is extended support for 28 languages in the polyglossia_ package. .. _polyglossia: http://ctan.org/pkg/polyglossia .. System Messages: .. include:: data/errors.txt �����������������������������������docutils-0.12/test/functional/input/link_in_substitution.txt����������������������������������������0000664�0001750�0001750�00000001073�11263555662�026540� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Test the interaction of transforms.references.Substitutions and transforms.references.ExternalLinks. |rest| is cool! .. |rest| replace:: reStructuredText_ .. _reStructuredText: http://docutils.sourceforge.net/rst.html There is a preferred alternative: |rst|_ is cool! .. |rst| replace:: reStructuredText .. _rst: http://docutils.sourceforge.net/rst.html This only works for the case where the entire substitution is a reference, not when the reference is embedded as part of the substitution: |urst| is uncool! .. |urst| replace:: unstructured reStructuredText_ ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/odt_tables1.txt�������������������������������������������������0000664�0001750�0001750�00000015551�11125256176�024463� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������================================================================================ Grid test ================================================================================ Test 1 ======= +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | | (header rows optional) | | | | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | +------------------------+------------+----------+----------+ | body row 2 | Cells may span columns. | +------------------------+------------+---------------------+ | body row 3 | Cells may | - Table cells | +------------------------+ span rows. + - contain + | body row 4 | aaa | - body elements. | +------------------------+------------+---------------------+ Test 2 ======= +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | | (header rows optional) | | | | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | + +------------+----------+----------+ | body row 2 | column 2 | column 3 | column 4 | +------------------------+ +----------+----------+ | body row 3 | may span | - Table cells | +------------------------+------------+ - contain + | body row 4 | column 2 | - body elements. | +------------------------+------------+---------------------+ Test 3 ======= +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | | (header rows optional) | | | | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | + +------------+----------+ + | body row 2 | column 2 | column 3 | may span | +------------------------+------------+ +----------+ | body row 3 | column 2 | may span | column 4 | +------------------------+ +----------+----------+ | body row 4 | may span | column 3 | column 4 | +------------------------+------------+----------+----------+ Test 4 ======= +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | | (header rows optional) | | | | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | + +------------+----------+ + | body row 2 | column 2 and column 3 | may span | +------------------------+ +----------+ | body row 3 | may span | column 4 | + +------------+----------+----------+ | may span | may span | column 3 | column 4 | +------------------------+------------+----------+----------+ Test 4a ======= +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | | (header rows optional) | | | | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | + +------------+----------+ + | body row 2 | column 2 and column 3 | may span | +------------------------+ +----------+ | body row 3 | may span | column 4 | + +------------+----------+----------+ | may span | may span | column 3 | column 4 | +------------------------+------------+----------+----------+ | body row 4 | column 2 | column 3 | column 4 | +------------------------+------------+----------+----------+ Test 5 ======= +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | | (header rows optional) | | | | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | +------------------------+------------+----------+----------+ | body row 2 | Cells may span columns. | +------------------------+------------+---------------------+ | body row 3 | Cells may | - Table cells | +------------------------+ span rows. | - contain | | body row 4 | | - body elements. | +------------------------+------------+---------------------+ Test 6 ======= Some care must be taken with grid tables to avoid undesired interactions with cell text in rare cases. For example, the following table contains a cell in row 2 spanning from column 2 to column 4: +--------------+----------+-----------+-----------+ | row 1, col 1 | column 2 | column 3 | column 4 | +--------------+----------+-----------+-----------+ | row 2 | | +--------------+----------+-----------+-----------+ | row 3 | | | | +--------------+----------+-----------+-----------+ Test 7 ======= If a vertical bar is used in the text of that cell, it could have unintended effects if accidentally aligned with column boundaries: +--------------+----------+-----------+-----------+ | row 1, col 1 | column 2 | column 3 | column 4 | +--------------+----------+-----------+-----------+ | row 2 | Use the command ``ls \| more``. | +--------------+----------+-----------+-----------+ | row 3 | | | | +--------------+----------+-----------+-----------+ Test 8 ======= Several solutions are possible. All that is needed is to break the continuity of the cell outline rectangle. One possibility is to shift the text by adding an extra space before: +--------------+----------+-----------+-----------+ | row 1, col 1 | column 2 | column 3 | column 4 | +--------------+----------+-----------+-----------+ | row 2 | Use the command ``ls | more``. | +--------------+----------+-----------+-----------+ | row 3 | | | | +--------------+----------+-----------+-----------+ Test 9 ======= Another possibility is to add an extra line to row 2: +--------------+----------+-----------+-----------+ | row 1, col 1 | column 2 | column 3 | column 4 | +--------------+----------+-----------+-----------+ | row 2 | Use the command ``ls | more``. | | | | +--------------+----------+-----------+-----------+ | row 3 | | | | +--------------+----------+-----------+-----------+ �������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/field_list.txt��������������������������������������������������0000664�0001750�0001750�00000000306�10224271741�024362� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������:short: This field's name is short. :medium-length: This field's name is medium-length. :long field name: This field's name is long. :very very long field name: This field's name is quite long. ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/cyrillic.txt����������������������������������������������������0000664�0001750�0001750�00000001337�12076016516�024067� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Заголовок --------- первый пример: "Здравствуй, мир!" Title ----- .. class:: language-en first example: "Hello world". Notes ----- .. class:: language-en This example tests rendering of Latin and Cyrillic characters by the LaTeX and XeTeX writers. Check the compiled PDF for garbage characters in text and bookmarks. .. class:: language-en To work around a problem with Cyrillic in PDF-bookmarks in `hyperref` versions older than v6.79g 2009/11/20, the test caller ``latex_cyrillic.py`` sets ``hyperref_options`` to ``'unicode=true'`` while ``xetex_cyrillic.py`` sets it to ``'unicode=false'``. The recommended option for current (2011-08-24) hyperref versions is ``'pdfencoding=auto'``. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/�����������������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�022420� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/standard.txt�����������������������������������������������0000664�0001750�0001750�00000052064�12024637300�024762� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������.. This is a comment. Note how any initial comments are moved by transforms to after the document title, subtitle, and docinfo. .. _doctitle: ================================ reStructuredText Test Document ================================ .. Above is the document title, and below is the subtitle. They are transformed from section titles after parsing. .. _subtitle: -------------------------------- Examples of Syntax Constructs -------------------------------- .. bibliographic fields (which also require a transform): :Author: David Goodger :Address: 123 Example Street Example, EX Canada A1B 2C3 :Contact: goodger@python.org :Authors: Me; Myself; I :organization: humankind :date: Now, or yesterday. Or maybe even *before* yesterday. :status: This is a "work in progress" :revision: is managed by a version control system. :version: 1 :copyright: This document has been placed in the public domain. You may do with it as you wish. You may copy, modify, redistribute, reattribute, sell, buy, rent, lease, destroy, or improve it, quote it at length, excerpt, incorporate, collate, fold, staple, or mutilate it, or do anything else to it that your or anyone else's heart desires. :field name: This is a "generic bibliographic field". :field name "2": Generic bibliographic fields may contain multiple body elements. Like this. :Dedication: For Docutils users & co-developers. :abstract: This is a test document, containing at least one example of each reStructuredText construct. .. meta:: :keywords: reStructuredText, test, parser :description lang=en: A test document, containing at least one example of each reStructuredText construct. .. raw:: latex \pagebreak[4] % start ToC on new page .. contents:: Table of Contents .. section-numbering:: Structural Elements =================== Section Title ------------- Section Subtitle ```````````````` Lone subsections are converted to a section subtitle by a transform activated with the ``--section-subtitles`` command line option or the ``sectsubtitle-xform`` configuration value. Empty Section ------------- Transitions ----------- Here's a transition: --------- It divides the section. Transitions may also occur between sections: --------- Body Elements ============= Paragraphs ---------- A paragraph. Inline Markup ````````````` Paragraphs contain text and may contain inline markup: *emphasis*, **strong emphasis**, ``inline literals``, standalone hyperlinks (http://www.python.org), external hyperlinks (Python_), internal cross-references (example_), external hyperlinks with embedded URIs (`Python web site <http://www.python.org>`__), `anonymous hyperlink references`__ (`a second reference`__), footnote references (manually numbered [1]_, anonymous auto-numbered [#]_, labeled auto-numbered [#label]_, or symbolic [*]_), citation references ([CIT2002]_), substitution references (|example|), and _`inline hyperlink targets` (see Targets_ below for a reference back to here). Character-level inline markup is also possible (although exceedingly ugly!) in *re*\ ``Structured``\ *Text*. Problems are indicated by |problematic| text (generated by processing errors; this one is intentional). Here is a reference to the doctitle_ and the subtitle_. __ http://www.python.org/ __ http://docutils.sourceforge.net/ The default role for interpreted text is `Title Reference`. Here are some explicit interpreted text roles: a PEP reference (:PEP:`287`); an RFC reference (:RFC:`2822`); an abbreviation (:ab:`abb.`), an acronym (:ac:`reST`), code (:code:`print "hello world"`); a :sub:`subscript`; a :sup:`superscript` and explicit roles for :title:`Docutils`' :emphasis:`standard` :strong:`inline` :literal:`markup`. .. DO NOT RE-WRAP THE FOLLOWING PARAGRAPH! Let's test wrapping and whitespace significance in inline literals: ``This is an example of --inline-literal --text, --including some-- strangely--hyphenated-words. Adjust-the-width-of-your-browser-window to see how the text is wrapped. -- ---- -------- Now note the spacing between the words of this sentence (words should be grouped in pairs).`` If the ``--pep-references`` option was supplied, there should be a live link to PEP 258 here. Bullet Lists ------------ - A bullet list + Nested bullet list. + Nested item 2. - Item 2. Paragraph 2 of item 2. * Nested bullet list. * Nested item 2. - Third level. - Item 2. * Nested item 3. * This nested list should be compacted by the HTML writer. .. _target: .. Even if this item contains a target and a comment. Enumerated Lists ---------------- 1. Arabic numerals. a) lower alpha) (i) (lower roman) A. upper alpha. I) upper roman) 2. Lists that don't start at 1: 3. Three 4. Four C. C D. D iii. iii iv. iv Definition Lists ---------------- Term Definition Term : classifier Definition paragraph 1. Definition paragraph 2. Term Definition Term : classifier one : classifier two Definition Field Lists ----------- :what: Field lists map field names to field bodies, like database records. They are often part of an extension syntax. They are an unambiguous variant of RFC 2822 fields. :how arg1 arg2: The field marker is a colon, the field name, and a colon. The field body may contain one or more body elements, indented relative to the field marker. :credits: .. class:: credits This paragraph has the `credits` class set. (This is actually not about credits but just for ensuring that the class attribute doesn't get stripped away.) Option Lists ------------ For listing command-line options: -a command-line option "a" -b file options can have arguments and long descriptions --long options can be long also --input=file long options can also have arguments --very-long-option The description can also start on the next line. The description may contain multiple body elements, regardless of where it starts. -x, -y, -z Multiple options are an "option group". -v, --verbose Commonly-seen: short & long options. -1 file, --one=file, --two file Multiple options with arguments. /V DOS/VMS-style options too There must be at least two spaces between the option and the description. Literal Blocks -------------- Literal blocks are indicated with a double-colon ("::") at the end of the preceding paragraph (over there ``-->``). They can be indented:: if literal_block: text = 'is left as-is' spaces_and_linebreaks = 'are preserved' markup_processing = None Or they can be quoted without indentation:: >> Great idea! > > Why didn't I think of that? Line Blocks ----------- This section tests line blocks. Line blocks are body elements which consist of lines and other line blocks. Nested line blocks cause indentation. | This is a line block. It ends with a blank line. | New lines begin with a vertical bar ("|"). | Line breaks and initial indent are significant, and preserved. | Continuation lines are also possible. A long line that is intended to wrap should begin with a space in place of the vertical bar. | The left edge of a continuation line need not be aligned with the left edge of the text above it. | This is a second line block. | | Blank lines are permitted internally, but they must begin with a "|". Another line block, surrounded by paragraphs: | And it's no good waiting by the window | It's no good waiting for the sun | Please believe me, the things you dream of | They don't fall in the lap of no-one Take it away, Eric the Orchestra Leader! | A one, two, a one two three four | | Half a bee, philosophically, | must, *ipso facto*, half not be. | But half the bee has got to be, | *vis a vis* its entity. D'you see? | | But can a bee be said to be | or not to be an entire bee, | when half the bee is not a bee, | due to some ancient injury? | | Singing... A line block, like the following poem by Christian Morgenstern, can also be centre-aligned: .. class:: language-de align-center | **Die Trichter** | | Zwei Trichter wandeln durch die Nacht. | Durch ihres Rumpfs verengten Schacht | fließt weißes Mondlicht | still und heiter | auf   ihren | Waldweg | u. s. | w. | Block Quotes ------------ Block quotes consist of indented body elements: My theory by A. Elk. Brackets Miss, brackets. This theory goes as follows and begins now. All brontosauruses are thin at one end, much much thicker in the middle and then thin again at the far end. That is my theory, it is mine, and belongs to me and I own it, and what it is too. -- Anne Elk (Miss) The language of a quote (like any other object) can be specified by a class attribute: .. class:: language-fr .. ReStructuredText est un langage de balisage léger utilisé notamment dans la documentation du langage Python. Doctest Blocks -------------- >>> print 'Python-specific usage examples; begun with ">>>"' Python-specific usage examples; begun with ">>>" >>> print '(cut and pasted from interactive Python sessions)' (cut and pasted from interactive Python sessions) Footnotes --------- .. [1] A footnote contains body elements, consistently indented by at least 3 spaces. This is the footnote's second paragraph. .. [#label] Footnotes may be numbered, either manually (as in [1]_) or automatically using a "#"-prefixed label. This footnote has a label so it can be referred to from multiple places, both as a footnote reference ([#label]_) and as a `hyperlink reference`__. __ label_ .. [#] This footnote is numbered automatically and anonymously using a label of "#" only. This is the second paragraph. And this is the third paragraph. .. [*] Footnotes may also use symbols, specified with a "*" label. Here's a reference to the next footnote: [*]_. .. [*] This footnote shows the next symbol in the sequence. .. [4] Here's an unreferenced footnote, with a reference to a nonexistent footnote: [5]_. Citations --------- .. [CIT2002] Citations are text-labeled footnotes. They may be rendered separately and differently from footnotes. Here's a reference to the above, [CIT2002]_, and a [nonexistent]_ citation. .. _Another Target: Targets ------- .. _example: This paragraph is pointed to by the explicit "example" target. A reference can be found under `Inline Markup`_, above. `Inline hyperlink targets`_ are also possible. Section headers are implicit targets, referred to by name. See Targets_, which is a subsection of `Body Elements`_. Explicit external targets are interpolated into references such as "Python_". .. _Python: http://www.python.org/ Targets may be indirect and anonymous. Thus `this phrase`__ may also refer to the Targets_ section. __ Targets_ Here's a `hyperlink reference without a target`_, which generates an error. Duplicate Target Names `````````````````````` Duplicate names in section headers or other implicit targets will generate "info" (level-1) system messages. Duplicate names in explicit targets will generate "warning" (level-2) system messages. Duplicate Target Names `````````````````````` Since there are two "Duplicate Target Names" section headers, we cannot uniquely refer to either of them by name. If we try to (like this: `Duplicate Target Names`_), an error is generated. Directives ---------- .. contents:: :local: These are just a sample of the many reStructuredText Directives. For others, please see http://docutils.sourceforge.net/docs/ref/rst/directives.html. Document Parts `````````````` An example of the "contents" directive can be seen above this section (a local, untitled table of contents_) and at the beginning of the document (a document-wide `table of contents`_). Images and Figures `````````````````` An image directive (also clickable -- a hyperlink reference): .. image:: ../../../docs/user/rst/images/title.png :class: class1 class2 :target: directives_ Image with multiple IDs: .. _image target 1: .. _image target 2: .. _image target 3: .. image:: ../../../docs/user/rst/images/title.png A centered image: .. image:: ../../../docs/user/rst/images/biohazard.png :align: center A left-aligned image: .. image:: ../../../docs/user/rst/images/biohazard.png :align: left This paragraph might flow around the image. The specific behavior depends upon the style sheet and the browser or rendering software used. A right-aligned image: .. image:: ../../../docs/user/rst/images/biohazard.png :align: right This paragraph might flow around the image. The specific behavior depends upon the style sheet and the browser or rendering software used. For inline images see `Substitution Definitions`_. Image size: An image 2 em wide: .. image:: ../../../docs/user/rst/images/biohazard.png :width: 2 em An image 2 em wide and 15 pixel high: .. image:: ../../../docs/user/rst/images/biohazard.png :width: 2em :height: 15 px An image occupying 50% of the line width: .. image:: ../../../docs/user/rst/images/title.png :width: 50% An image 2 cm high: .. image:: ../../../docs/user/rst/images/biohazard.png :height: 2 cm A *figure* is an image with a caption and/or a legend. With page-based output media, figures might float to a different position if this helps the page layout. .. figure:: ../../../docs/user/rst/images/title.png :figclass: figclass1 figclass2 :class: class1 class2 :alt: reStructuredText, the markup syntax :width: 258 Plaintext markup syntax and parser system. +------------+-----------------------------------------------+ | re | Revised, revisited, based on 're' module. | +------------+-----------------------------------------------+ | Structured | Structure-enhanced text, structuredtext. | +------------+-----------------------------------------------+ | Text | Well it is, isn't it? | +------------+-----------------------------------------------+ This paragraph is also part of the legend. A left-aligned figure: .. figure:: ../../../docs/user/rst/images/biohazard.png :figclass: figclass1 figclass2 :class: class1 class2 :alt: reStructuredText, the markup syntax :align: left :width: 40 px :figwidth: 70 % This is the caption. This is the legend. The legend may consist of several paragraphs. This paragraph might flow around the figure. The specific behavior depends upon the style sheet and the browser or rendering software used. A centered figure: .. figure:: ../../../docs/user/rst/images/biohazard.png :align: center :width: 40 px This is the caption. This is the legend. The legend may consist of several paragraphs. This paragraph might flow around the figure. The specific behavior depends upon the style sheet and the browser or rendering software used. A right-aligned figure: .. figure:: ../../../docs/user/rst/images/biohazard.png :align: right :width: 40 px This is the caption. This is the legend. The legend may consist of several paragraphs. This paragraph might flow around the figure. The specific behavior depends upon the style sheet and the browser or rendering software used. Admonitions ``````````` .. Attention:: Directives at large. .. Caution:: Don't take any wooden nickels. .. DANGER:: Mad scientist at work! .. Error:: Does not compute. .. Hint:: It's bigger than a bread box. .. Important:: - Wash behind your ears. - Clean up your room. - Call your mother. - Back up your data. .. Note:: This is a note. .. Tip:: 15% if the service is good. .. WARNING:: Strong prose may provoke extreme mental exertion. Reader discretion is strongly advised. .. admonition:: And, by the way... You can make up your own admonition too. .. _Docutils: http://docutils.sourceforge.net/ Topics, Sidebars, and Rubrics ````````````````````````````` *Sidebars* are like miniature, parallel documents. .. sidebar:: Sidebar Title :subtitle: Optional Subtitle This is a sidebar. It is for text outside the flow of the main text. .. rubric:: This is a rubric inside a sidebar Sidebars often appear beside the main text with a border and a different background or font color. A *topic* is like a block quote with a title, or a self-contained section with no subsections. .. topic:: Topic Title This is a topic. A *rubric* is like an informal heading that doesn't correspond to the document's structure. It is typically highlighted in red (hence the name). .. rubric:: This is a rubric Topics and rubrics can be used at places where a `section title`_ is not allowed (e.g. inside a directive). Target Footnotes ```````````````` .. target-notes:: Replacement Text ```````````````` I recommend you try |Python|_. .. |Python| replace:: Python, *the* best language around Compound Paragraph `````````````````` .. compound:: :class: some-class Compound 1, paragraph 1. Compound 1, paragraph 2. * Compound 1, list item one. * Compound 1, list item two. Another compound statement: .. compound:: Compound 2, a literal block:: Compound 2, literal. Compound 2, this is a test. .. compound:: Compound 3, only consisting of one paragraph. .. compound:: :: Compound 4. This one starts with a literal block. Compound 4, a paragraph. Now something *really* perverted -- a nested compound block. This is just to test that it works at all; the results don't have to be meaningful. .. compound:: Compound 5, block 1 (a paragraph). .. compound:: Compound 6, block 2 in compound 5. Compound 6, another paragraph. Compound 5, block 3 (a paragraph). .. compound:: Compound 7, with a table inside: +--------------------+--------------------+--------------------+ | Left cell, first | Middle cell, | Right cell. | | paragraph. | consisting of | | | | exactly one | Paragraph 2. | | Left cell, second | paragraph. | | | paragraph. | | Paragraph 3. | +--------------------+--------------------+--------------------+ Compound 7, a paragraph after the table. Compound 7, another paragraph. Parsed Literal Blocks ````````````````````` .. parsed-literal:: This is a parsed literal block. This line is indented. The next line is blank. Inline markup is supported, e.g. *emphasis*, **strong**, ``literal text``, footnotes [1]_, _`hyperlink targets`, and `references <http://www.python.org/>`_. Code ```` Blocks of source code can be set with the `code` directive. If the code language is specified, the content is parsed and tagged by the Pygments_ syntax highlighter and can be formatted with a style sheet. (Code parsing is turned off using the ``syntax-highlight`` config setting in the test conversions in order to get identical results with/without installed Pygments highlighter.) .. code:: python print 'This is Python code.' The ``:number-lines:`` option (with optional start value) generates line numbers: .. code:: python :number-lines: 8 # print integers from 0 to 9: for i in range(10): print i For inline code snippets, there is the `code` role, which can be used directly (the code will not be parsed/tagged, as the language is not known) or as base for special code roles, e.g. the LaTeX code in the next paragraph. .. role:: tex(code) :language: tex Docutils uses LaTeX syntax for math directives and roles: :tex:`\alpha = f(x)` prints :math:`\alpha = f(x)`. The ``:code:`` option of the `include` directive sets the included content as a code block, here the rst file ``header_footer.txt`` with line numbers: .. include:: header_footer.txt :code: rst :number-lines: .. _Pygments: http://pygments.org/ Substitution Definitions ------------------------ An inline image (|example|) example: .. |EXAMPLE| image:: ../../../docs/user/rst/images/biohazard.png (Substitution definitions are not visible in the HTML source.) Comments -------- Here's one: .. Comments begin with two dots and a space. Anything may follow, except for the syntax of footnotes, hyperlink targets, directives, or substitution definitions. Double-dashes -- "--" -- must be escaped somehow in HTML output. Comments may contain non-ASCII characters: ä ö ü æ ø å (View the HTML source to see the comment.) Raw text -------- This does not necessarily look nice, because there may be missing white space. It's just there to freeze the behavior. .. raw:: html latex A test. .. raw:: html latex Second test. .. class:: myclass .. raw:: html latex Another test with myclass set. .. role:: raw-role(raw) :format: html latex :class: myrawroleclass This is the :raw-role:`fourth test` with myrawroleclass set. .. raw:: html Fifth test in HTML.<br />Line two. .. raw:: latex Fifth test in LaTeX.\\Line two. Container --------- .. container:: custom paragraph 1 paragraph 2 ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/math.txt���������������������������������������������������0000664�0001750�0001750�00000006042�11635205440�024111� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Mathematics ----------- Docutils supports inline math with the prefix or postfix ``:math:`` role specificator, :math:`n! + \sin(x_n^2)` and `A_\text{c} = \frac{\pi}{4} d^2`:math:, as well as displayed math via the `math` directive: .. math:: f(\epsilon) = \frac{1}{1 + \exp\left(\frac{\varepsilon}{k_\text{B}T}\right)} Content may start on the first line of the directive, e.g. .. math:: N = \frac{\text{number of apples}}{7} Equations can be labeled with a reference name using the ``:name:`` option. See `eq:M`_ and `eq:schrödinger`_ below. The determinant of the matrix .. math:: :name: eq:M \mathbf{M} = \left(\begin{matrix}a&b\\c&d\end{matrix}\right) is :math:`|\mathbf{M}| = ad - bc`. More than one display math block can be put in one math directive. For example, the following sum and integral with limits: .. math:: \int_0^1 x^n dx = \frac{1}{n + 1} \sum_{n=1}^m n = \frac{m(m+1)}{2} LaTeX-supported Unicode math symbols can be used in math roles and directives: The Schrödinger equation .. math:: :name: eq:schrödinger i\hbar \frac{∂}{∂t}Ψ = \hat{H}Ψ, with the *wave function* :math:`Ψ`, describes how the quantum state of a physical system changes in time. Math-Accents: .. list-table:: :class: borderless * - :math:`\acute{a}` ``\acute{a}`` - :math:`\dot{t}` ``\dot{t}`` - :math:`\hat{\gamma}` ``\hat{\gamma}`` * - :math:`\grave{a}` ``\grave{a}`` - :math:`\ddot{t}` ``\ddot{t}`` - :math:`\tilde{\alpha}` ``\tilde{\alpha}`` * - :math:`\breve{x}` ``\breve{x}`` - :math:`\dddot{t}` ``\dddot{t}`` - :math:`\vec{\imath}` ``\vec{\imath}`` * - :math:`\check{a}` ``\check{a}`` - :math:`\bar{a}` ``\bar{a}`` - :math:`\vec{R}` ``\vec{R}`` .. \widetilde{xxx} \widehat{xxx} Modulation Transfer Function: .. math:: \text{MTF} = \left|\frac{\mathcal{F}\{s(x)\}} {\mathcal{F}\{ s(x)\} |_{ω_{x}=0}}\right| = \mathrm{abs}\left(\frac {∫_{-∞}^{∞}s(x) \mathrm{e}^{\mathrm{i}ω_{x}x}\mathrm{d}{x}} {∫_{-∞}^{∞}s(x)\mathrm{d}{x}} \right). Math split over two lines: If a double backslash is detected outside a ``\begin{...} \end{...}`` pair, the math code is wrapped in an AMSmath_ ``align`` environment: .. math:: s_{\mathrm{out}}(x) & = s_{\mathrm{in}}(x') * s_δ(x-x') \\ & = ∫ s_{\mathrm{in}}(x')s_δ(x-x')\mathrm{d}x' Cases ("manually", with ``matrix`` environment): .. math:: \mathrm{sgn}(x) = \left\{\begin{matrix} -1 & x<0\\ 1 & x>0 \end{matrix}\right. Cases with the AMSmath_ ``cases`` environment (not (yet) supported by HTML writers with ``--math-output=MathML``): .. math:: \mathrm{sgn}(x) = \begin{cases} -1 & x<0\\ 1 & x>0 \end{cases} .. _AMSmath: ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/section_titles.txt�����������������������������������������0000664�0001750�0001750�00000000714�11722521564�026215� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Section titles with `inline markup`_ ------------------------------------ *emphasized*, H\ :sub:`2`\ O and :math:`x^2` ```````````````````````````````````````````` Substitutions |fail| ```````````````````` .. |fail| replace:: work Deeply nested sections ---------------------- In LaTeX and HTML, Level 3 ``````` nested sections level 4 ^^^^^^^ reach at some level level 5 ::::::: (depending on the document class) level 6 +++++++ an unsupported level. ����������������������������������������������������docutils-0.12/test/functional/input/data/option_lists.txt�������������������������������������������0000664�0001750�0001750�00000000734�11140601226�025701� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������.. This file is used by the standalone_rst_latex test. Option lists ------------ The LaTeX-2e description environment is used for definition lists. The definition is continued on the same line as the term, this should not happen if a option-list is at the top of the definition. If the option list is not at the first element in the definition, it is contained in a quote --help show help -v verbose In a definition list: --help show help -v verbose ������������������������������������docutils-0.12/test/functional/input/data/latex.txt��������������������������������������������������0000664�0001750�0001750�00000014671�11200272533�024277� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Some Tests for the LaTeX Writer =============================== These tests have been written to exercise some unusual combinations of syntax elements which may cause trouble for the LaTeX writer but do not need to be tested with other writers (e.g. the HTML writer). This file is not yet used by any automated test. It is currently only used to control the visual appearance of the output. Block Quotes ------------ This block quote comes directly after the section heading and is followed by a paragraph. This is the second paragraph of the block quote and it contains some more text filling up some space which would otherwise be empty. -- Attribution This is a paragraph. This block quote does not have an attribution. This is another paragraph. Another block quote at the end of the section. More Block Quotes ----------------- Block quote followed by a transition. ---------- Another block quote. Sidebars -------- This paragraph precedes the sidebar. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. .. sidebar:: Sidebar Title These are the sidebar contents. These are the sidebar contents. These are the sidebar contents. These are the sidebar contents. These are the sidebar contents. These are the sidebar contents. These are the sidebar contents. These are the sidebar contents. This paragraph follows the sidebar. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. Next Section ------------ This section comes after the sidebar, and this text should float around the sidebar as well. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. Nested Elements --------------- :Field list: | Line | Block :Field 2: * Bullet * list :Another (longer) field: * Bullet * list :Yet another long field: * .. comment Bullet .. comment * .. comment list .. comment :Field: * This is a * bullet list :Field: * | This is | a bullet * | list with | line blocks :Last field: Last field. Too deeply nested lists fail. TODO: generate an error or provide a workaround. .. * * * * * * * * Deeply nested list. .. 1. 2. 3. 4. 5. 6. 7. 8. Deeply nested list. +-----------------+ | | Line block | | | | * Bullet list | | | | :: | | | | Literal | | block | +-----------------+ | :Field 1: | | Text. | | :Field 2: | | More text. | +-----------------+ | +-------+-----+ | | | A |* foo| | | | nested| | | | | table.|* bar| | | +-------+-----+ | +-----------------+ | This is a | | paragraph. | | | | +-------+-----+ | | | A |* foo| | | | nested| | | | | table.|* bar| | | +-------+-----+ | | | | Another longer | | paragraph. | +-----------------+ | * A list. | | * A list. | | | | +-------+-----+ | | | A |* foo| | | | nested| | | | | table.|* bar| | | +-------+-----+ | | | | * Another list. | | * Another list. | +-----------------+ | Foo | | | | Bar | +-----------------+ | * Foo | | | | * Bar | +-----------------+ | * This is a | | paragraph. | | | | This is a | | paragraph. | | | | * This is a | | paragraph. | | | | This is a | | paragraph. | +-----------------+ Images ------ Image with 20% width: .. image:: ../../../../docs/user/rst/images/title.png :width: 20% Image with 100% width: .. image:: ../../../../docs/user/rst/images/title.png :width: 100% Vertical alignment of inline images ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. |top| image:: ../../../../docs/user/rst/images/biohazard.png :align: top .. |middle| image:: ../../../../docs/user/rst/images/biohazard.png :align: middle .. |bottom| image:: ../../../../docs/user/rst/images/biohazard.png :align: bottom A paragraph containing top |top|, middle |middle|, and bottom |bottom| aligned images. Rowspanning tables ------------------ Several rowspanning cells in a table. .. Problem: In the LaTeX `multicol` package, if there are multirow cells, the "overwritten" cells need to be defined as empty cells. Docutils (similarily to HTML) uses is the "Exchange Table Model" (also known as CALS tables, see docs/ref/soextblx.dtd) which defines only the remaining cells in a row "affected" by multirow cells. Therefore, visit_entry() is only called for the remaining cells and the LaTeX writer needs bookkeeping to write out the required number of extra '&'s. .. class:: standard +-----------+------------+------------------+-----------+ | cell 11 | cell 12 | cell 13 | cell 41 | +-----------+------------+------------------+-----------+ | cell 12 | Cell a | | cell 42 | +-----------+ | +-----------+ | cell 13 | | cell b | cell 43 | +-----------+------------+------------------+-----------+ .. class:: standard +------------+------------------+-----------+ | cell 12 | cell 13 | cell 41 | +------------+------------------+-----------+ | Cell a | | cell 42 | + | +-----------+ | | cell b | cell 43 | +------------+------------------+-----------+ .. class:: standard +-----------+------------+-----------+ | cell 11 | cell 12 | cell 41 | +-----------+------------+-----------+ | cell 12 | Cell a | cell 42 | +-----------+ +-----------+ | cell 13 | | cell 43 | +-----------+------------+-----------+ �����������������������������������������������������������������������docutils-0.12/test/functional/input/data/list_table.txt���������������������������������������������0000664�0001750�0001750�00000000706�10224377012�025301� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������List Tables ----------- Here's a list table exercising all features: .. list-table:: list table with integral header :class: test :widths: 10 20 30 :header-rows: 1 :stub-columns: 1 * - Treat - Quantity - Description * - Albatross - 2.99 - On a stick! * - Crunchy Frog - 1.49 - If we took the bones out, it wouldn't be crunchy, now would it? * - Gannet Ripple - 1.99 - On a stick! ����������������������������������������������������������docutils-0.12/test/functional/input/data/table_colspan.txt������������������������������������������0000664�0001750�0001750�00000000437�10066121605�025765� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Colspanning tables ------------------ This table has a cell spanning two columns: ===== ===== ====== Inputs Output ------------ ------ A B A or B ===== ===== ====== False False False True False True False True True True True True ===== ===== ====== ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/custom_roles_latex.txt�������������������������������������0000664�0001750�0001750�00000002741�11454601741�027100� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Custom Roles in LaTeX --------------------- * Role names and class arguments are converted to conform to the regular expression ``[a-z][-a-z0-9]*`` (letters are downcased, accents and similar decoration is stripped, non-conforming characters are replaced by a hyphen). Class arguments may contain numbers and hyphens, which need special treatment in LaTeX command names. .. role:: custom4 :class: large custom4 small_caps custom.role custom\role :custom4:`Interpreted Text` * With LaTeX, roles can be styled within the document using the `raw` directive. .. raw:: latex \newcommand{\DUrolelarge}[1]{{\large #1}} \makeatletter \@namedef{DUrolesmall-caps}{\textsc} \@namedef{DUrolecustom4}{\textbf} \makeatother :custom4:`Interpreted Text` in large, bold, small-caps. * Custom roles can be based on standard roles: .. role:: custom-emphasis(emphasis) This is a :custom-emphasis:`customized emphasis text role` .. role:: custom-literal(literal) This is a :custom-literal:`customized literal text role` .. role:: custom-strong(strong) This is a :custom-strong:`customized strong text role` .. role:: custom-subscript(subscript) This is a :custom-subscript:`customized subscript text role` .. role:: custom-superscript(superscript) This is a :custom-superscript:`customized superscript text role` .. role:: custom-title-reference(title-reference) This is a :custom-title-reference:`customized title-reference text role` �������������������������������docutils-0.12/test/functional/input/data/table_complex.txt������������������������������������������0000664�0001750�0001750�00000002070�10066121605�025770� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Complex tables -------------- Here's a complex table, which should test all features. +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | | (header rows optional) | | | | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | +------------------------+------------+----------+----------+ | body row 2 | Cells may span columns. | +------------------------+------------+---------------------+ | body row 3 | Cells may | - Table cells | +------------------------+ span rows. | - contain | | body row 4 | | - body elements. | | | Paragraph. | | +------------------------+------------+----------+----------+ | body row 5 | Cells may also be | | | | empty: ``-->`` | | +------------------------+-----------------------+----------+ ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/header_footer.txt������������������������������������������0000664�0001750�0001750�00000000070�10225305653�025762� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������.. header:: Document header .. footer:: Document footer ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/nonalphanumeric.txt����������������������������������������0000664�0001750�0001750�00000000615�10126056105�026337� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Monospaced non-alphanumeric characters -------------------------------------- These are all ASCII characters except a-zA-Z0-9 and space: ``!!!"""###$$$%%%&&&'''((()))***+++,,,---...///:::`` ``;;;<<<===>>>???@@@[[[\\\]]]^^^___```{{{|||}}}~~~`` ``xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`` The two lines of non-alphanumeric characters should both have the same width as the third line. �������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/custom_roles.txt�������������������������������������������0000664�0001750�0001750�00000001736�11466350404�025706� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Custom Roles ------------ * A role based on an existing role. .. role:: custom(literal) :custom:`one` :custom:`two` :custom:`three` * A new role. .. role:: customnew :customnew:`one two three` * A role with class attribute. .. role:: customclass :class: special :customclass:`interpreted text` * A language-switching role: .. role:: language-de Let's count in German :language-de:`eins zwei drei`. * A role with multiple class attributes, styled with raw directives: .. role:: customx :class: green sc language-en-GB .. raw:: latex \newcommand{\DUrolegreen}[1]{\textcolor{green}{#1}} \newcommand{\DUrolesc}[1]{\textsc{#1}} The following works in most browsers but does not validate (``<style>`` is only allowed in the document head):: .. raw:: html <style type="text/css"><!-- .green {color: green;} .sc {font-variant: small-caps;} --></style> :customx:`British colourful text in small-caps`. ����������������������������������docutils-0.12/test/functional/input/data/urls.txt���������������������������������������������������0000664�0001750�0001750�00000003344�11710250064�024143� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������External references ------------------- Long URLs should be wrapped in the PDF. This can be achieved with the \url command which is used by the LaTeX writer whenever the content (name) of a reference node equals the link URL. Example: a long URL that should wrap in the output http://docutils.sourceforge.net/docs/user/latex.html#id79 If the argument contains any "%", "#", or "^^", or ends with ``\``, it can't be used in the argument to another command. The argument must not contain unbalanced braces. The characters ^, {, }, and ``\`` are invalid in a "http:" or "ftp:" URL and not recognized as part of it: | http://www.example.org/strange^^name | http://www.example.org\\using\\DOS\\paths\\ | http://www.example.org/XML/strange{n}ame They can, however be used in paths and/or filenames. Handling by the LaTeX writer: * ``#``, ``\`` and ``%`` are escaped: | `URL with # <http://www.w3.org/XML/Schema#dev>`__ http://www.w3.org/XML/Schema#dev | `URL with % <http://www.w3.org/XML/Schema%dev>`__ http://example.org/Schema%dev | `file with DOS path`__ `A:DOS\\path\\`__ .. note:: These URLs are typeset inside a LaTeX command without error. | http://www.w3.org/XML/Schema#dev | http://example.org/Schema%dev | `A:DOS\\path\\`__ __ __ __ A:DOS\\path\\ * ^^ LaTeX's special syntax for characters results in "strange" replacements (both with \href and \url). A warning is given. `file with ^^ <../strange^^name>`__: `<../strange^^name>`__ * Unbalanced braces, { or }, will fail (both with \href and \url):: `file with { <../strange{name>`__ `<../strange{name>`__ while balanced braces are suported: | `<../strange{n}ame>`__ | `<../st{r}ange{n}ame>`__ | `<../{st{r}ange{n}ame}>`__ ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/table_rowspan.txt������������������������������������������0000664�0001750�0001750�00000001247�10245064445�026026� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Rowspanning tables ------------------ Here's a table with cells spanning several rows: +------------------------+------------+------------------+ | Header row, column 1 | Header 2 | Header 3 | | (header rows optional) | | | +========================+============+==================+ | body row 1, column 1 | column 2 | column 3 | +------------------------+------------+------------------+ | body row 2 | Cells may | Another | +------------------------+ span rows. | rowspanning | | body row 3 | | cell. | +------------------------+------------+------------------+ ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/svg_images.txt���������������������������������������������0000664�0001750�0001750�00000003447�11343175705�025320� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������SVG Images ---------- .. image:: ../../../docs/user/rst/images/biohazard.svg :width: 48 px :height: 48 px Scalable vector graphics (SVG) images are not supported by all backends. Rendering depends partially on the backend, especially if the size is not explicitely given. .. image:: ../../../docs/user/rst/images/title-scaling.svg :width: 50% :align: left A scaling image occupying 50% of the line width (scales with the browser window). Whether an SVG image is scaled or clipped/padded cannot be set in the containing HTML. It depends on the viewport declaration inside its root <svg> element. .. |inline-svg| image:: ../../../docs/user/rst/images/biohazard-scaling.svg :height: 0.8 em An inline SVG image |inline-svg| scaled to a height of 0.8 em. .. image:: ../../../docs/user/rst/images/title-scaling.svg :width: 50 % :height: 1.2 em :align: right A scaling image occupying 50% of the line width and 1.2 em high, right aligned (this SVG image keeps the aspect ratio): .. image:: ../../../docs/user/rst/images/biohazard-scaling.svg :height: 1 em :align: left A scaling image 1 em high, left aligned. A scaling image 5 mm x 5 mm, centered, with hyperlink reference: .. image:: ../../../docs/user/rst/images/biohazard-scaling.svg :target: Directives_ :width: 5 mm :height: 5 mm :align: center .. image:: ../../../docs/user/rst/images/biohazard.svg :width: 4 cm :height: 2 em :align: left A fixed-size image in a 4 cm x 2 em box. .. image:: ../../../docs/user/rst/images/title.svg :width: 50% :height: 15 px :align: left A fixed-size image in a box 50% the line width and 15 pixle high. .. figure:: ../../../docs/user/rst/images/title.svg :alt: reStructuredText, the markup syntax :width: 290 px :height: 28 px SVG image in a figure. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/tables_latex.txt�������������������������������������������0000664�0001750�0001750�00000002773�12111503451�025627� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������More Tables ----------- A multicolumn table with multi-paragraph rowspanning cells: +----------+--------------+---------------------------------+-----------+ | test | **bold hd** | multicolumn 1 | *emph hd* | | | | | | | | | With a second paragraph | | +----------+--------------+--------------+--------+---------+-----------+ | multicolumn 2 | cell | cell | cell | cell | | | | | | | | With a second paragraph | | | | | +----------+--------------+--------------+--------+---------+-----------+ | cell | multicolumn 3 (one line, | cell | cell | cell | | | but very very very very | | | | | | very looooong) | | | | +----------+--------------+--------------+--------+---------+-----------+ | cell | cell | cell | Short multicolumn 4 | +----------+--------------+--------------+------------------------------+ A table with multirow header +------------+-------------------+ | XXX | Variable Summary | | +-------------------+ | | Description | +============+===================+ | multirow header breaks latex | +--------------------------------+ �����docutils-0.12/test/functional/input/data/swf_images.txt���������������������������������������������0000664�0001750�0001750�00000001210�11613400512�025265� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������SWF Images ---------- Shockwave Flash is an image/movie format that most modern web browsers support via a plugin. It is sometimes blocked due to privacy/security concerns. Images with extension ``.swf`` are placed inside <object> elements. For complete control over display options use raw HTML. .. image:: ../../../docs/user/rst/images/biohazard.swf :alt: [biohazard.swf] :width: 4 cm :height: 2 em :align: left An SWF image in a 4 cm x 2 em box, left aligned. .. |inline-swf| image:: ../../../docs/user/rst/images/biohazard.swf :width: 0.8 em :height: 0.8 em An inline SWF image |inline-swf| scaled to 0.8 em x 0.8 em. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/errors.txt�������������������������������������������������0000664�0001750�0001750�00000000375�10066121605�024474� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Error Handling ============== Any errors caught during processing will generate system messages. There should be five messages in the following, auto-generated section, "Docutils System Messages": .. section should be added by Docutils automatically �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/math.css���������������������������������������������������0000664�0001750�0001750�00000011257�12114425204�024061� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* * math2html: convert LaTeX equations to HTML output. * * Copyright (C) 2009,2010 Alex Fernández * * Released under the terms of the `2-Clause BSD license'_, in short: * Copying and distribution of this file, with or without modification, * are permitted in any medium without royalty provided the copyright * notice and this notice are preserved. * This file is offered as-is, without any warranty. * * .. _2-Clause BSD license: http://www.spdx.org/licenses/BSD-2-Clause * * Based on eLyXer: convert LyX source files to HTML output. * http://elyxer.nongnu.org/ */ /* --end-- * CSS file for LaTeX formulas. */ /* Formulas */ .formula { text-align: center; font-family: "Droid Serif", "DejaVu Serif", "STIX", serif; margin: 1.2em 0; } span.formula { white-space: nowrap; } div.formula { padding: 0.5ex; margin-left: auto; margin-right: auto; } /* Basic features */ a.eqnumber { display: inline-block; float: right; clear: right; font-weight: bold; } span.unknown { color: #800000; } span.ignored, span.arraydef { display: none; } .formula i { letter-spacing: 0.1ex; } /* Alignment */ .align-left, .align-l { text-align: left; } .align-right, .align-r { text-align: right; } .align-center, .align-c { text-align: center; } /* Structures */ span.overline, span.bar { text-decoration: overline; } .fraction, .fullfraction { display: inline-block; vertical-align: middle; text-align: center; } .fraction .fraction { font-size: 80%; line-height: 100%; } span.numerator { display: block; } span.denominator { display: block; padding: 0ex; border-top: thin solid; } sup.numerator, sup.unit { font-size: 70%; vertical-align: 80%; } sub.denominator, sub.unit { font-size: 70%; vertical-align: -20%; } span.sqrt { display: inline-block; vertical-align: middle; padding: 0.1ex; } sup.root { font-size: 70%; position: relative; left: 1.4ex; } span.radical { display: inline-block; padding: 0ex; font-size: 150%; vertical-align: top; } span.root { display: inline-block; border-top: thin solid; padding: 0ex; vertical-align: middle; } span.symbol { line-height: 125%; font-size: 125%; } span.bigsymbol { line-height: 150%; font-size: 150%; } span.largesymbol { font-size: 175%; } span.hugesymbol { font-size: 200%; } span.scripts { display: inline-table; vertical-align: middle; } .script { display: table-row; text-align: left; line-height: 150%; } span.limits { display: inline-table; vertical-align: middle; } .limit { display: table-row; line-height: 99%; } sup.limit, sub.limit { line-height: 100%; } span.symbolover { display: inline-block; text-align: center; position: relative; float: right; right: 100%; bottom: 0.5em; width: 0px; } span.withsymbol { display: inline-block; } span.symbolunder { display: inline-block; text-align: center; position: relative; float: right; right: 80%; top: 0.3em; width: 0px; } /* Environments */ span.array, span.bracketcases, span.binomial, span.environment { display: inline-table; text-align: center; border-collapse: collapse; margin: 0em; vertical-align: middle; } span.arrayrow, span.binomrow { display: table-row; padding: 0ex; border: 0ex; } span.arraycell, span.bracket, span.case, span.binomcell, span.environmentcell { display: table-cell; padding: 0ex 0.2ex; line-height: 99%; border: 0ex; } /* * CSS file for LaTeX formulas, extra stuff: * binomials, vertical braces, stackrel, fonts and colors. */ /* Inline binomials */ span.binom { display: inline-block; vertical-align: middle; text-align: center; font-size: 80%; } span.binomstack { display: block; padding: 0em; } /* Over- and underbraces */ span.overbrace { border-top: 2pt solid; } span.underbrace { border-bottom: 2pt solid; } /* Stackrel */ span.stackrel { display: inline-block; text-align: center; } span.upstackrel { display: block; padding: 0em; font-size: 80%; line-height: 64%; position: relative; top: 0.15em; } span.downstackrel { display: block; vertical-align: bottom; padding: 0em; } /* Fonts */ span.mathsf, span.textsf { font-style: normal; font-family: sans-serif; } span.mathrm, span.textrm { font-style: normal; font-family: serif; } span.text, span.textnormal { font-style: normal; } span.textipa { color: #008080; } span.fraktur { font-family: "Lucida Blackletter", eufm10, blackletter; } span.blackboard { font-family: Blackboard, msbm10, serif; } span.scriptfont { font-family: "Monotype Corsiva", "Apple Chancery", "URW Chancery L", cursive; font-style: italic; } /* Colors */ span.colorbox { display: inline-block; padding: 5px; } span.fbox { display: inline-block; border: thin solid black; padding: 2px; } span.boxed, span.framebox { display: inline-block; border: thin solid black; padding: 5px; } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/hyperlinking.txt�������������������������������������������0000664�0001750�0001750�00000001411�11333024071�025650� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Hyperlinks and -targets ----------------------- In LaTeX, we must set an explicit anchor (``\phantomsection``) for a _`hypertarget in plain text` or in a figure but not in a longtable or caption: .. _`table label`: .. table:: Table with _`hypertarget in table title`. ===== ===== ===== False True None ===== ===== ===== .. _`figure label`: .. figure:: ../../../docs/user/rst/images/biohazard.png Figure with _`hypertarget in figure caption`. Legend with _`hypertarget in figure legend`. .. _`image label`: .. image:: ../../../docs/user/rst/images/biohazard.png See `hypertarget in plain text`_, `table label`_, `hypertarget in table title`_, `figure label`_, `hypertarget in figure caption`_, `hypertarget in figure legend`_, and `image label`_. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/unicode.txt������������������������������������������������0000664�0001750�0001750�00000004463�11370257652�024623� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Non-ASCII characters -------------------- Punctuation and footnote symbols = =================================== – en-dash — em-dash ‘ single turned comma quotation mark ’ single comma quotation mark ‚ low single comma quotation mark “ double turned comma quotation mark ” double comma quotation mark „ low double comma quotation mark † dagger ‡ double dagger ♦ black diamond suit ♥ black heart suit ♠ black spade suit ♣ black club suit … ellipsis ™ trade mark sign ⇔ left-right double arrow = =================================== The `Latin-1 extended` Unicode block === = = = = = = = = = = .. 0 1 2 3 4 5 6 7 8 9 --- - - - - - - - - - - 160   ¡ ¢ £ ¥ ¦ § ¨ © 170 ª « ¬ ­ ® ¯ ° ± ² ³ 180 ´ µ ¶ · ¸ ¹ º » ¼ ½ 190 ¾ ¿ À Á Â Ã Ä Å Æ Ç 200 È É Ê Ë Ì Í Î Ï Ð Ñ 210 Ò Ó Ô Õ Ö × Ø Ù Ú Û 220 Ü Ý Þ ß à á â ã ä å 230 æ ç è é ê ë ì í î ï 240 ð ñ ò ó ô õ ö ÷ ø ù 250 ú û ü ý þ ÿ === = = = = = = = = = = * The following line should not be wrapped, because it uses no-break spaces (\\u00a0): X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X * Line wrapping with/without breakpoints marked by soft hyphens (\\u00ad): pdn­derd­mdtd­ri­schpdn­derd­mdtd­ri­schpdn­derd­mdtd­ri­schpdn­derd­mdtd­ri­schpdn­derd­mdtd­ri­sch pdnderdmdtdrischpdnderdmdtdrischpdnderdmdtdrischpdnderdmdtdrischpdnderdmdtdrisch * The currency sign (\\u00a4) is not supported by all fonts (some have an Euro sign at its place). You might see an error like:: ! Package textcomp Error: Symbol \textcurrency not provided by (textcomp) font family ptm in TS1 encoding. (textcomp) Default family used instead. (which in case of font family ptm is a false positive). Add either :warn: turn the error in a warning, use the default symbol (bitmap), or :force,almostfull: use the symbol provided by the font at the users risk, to the document options or use a different font package. �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/latex_encoding.txt�����������������������������������������0000664�0001750�0001750�00000002273�12076761575�026165� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Encoding special chars ---------------------- The LaTeX Info pages lists under "2.18 Special Characters" The following characters play a special role in LaTeX and are called "special printing characters", or simply "special characters". # $ % & ~ _ ^ \\ { } The special chars verbatim:: # $ % & ~ _ ^ \ { } However also *square brackets* [] need special care. \item and all the other commands with optional arguments check if the token right after the macro name is an opening bracket. In that case the contents between that bracket and the following closing bracket on the same grouping level are taken as the optional argument. What makes this unintuitive is the fact that the square brackets aren't grouping characters themselves, so in your last example \item[[...]] the optional argument consists of [... (without the closing bracket). Compare the items in the following lists: * simple item * [bracketed] item simple description term [bracketed] description term The OT1 font-encoding has different characters for the less-than, greater-than and bar, < | >, except for typewriter font `cmtt`:: < | > �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/data/html4css1.css����������������������������������������������0000664�0001750�0001750�00000014024�11763213420�024751� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* :Author: David Goodger (goodger@python.org) :Id: $Id: html4css1.css 7437 2012-06-04 20:14:08Z milde $ :Copyright: This stylesheet has been placed in the public domain. Default cascading style sheet for the HTML output of Docutils. See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to customize this style sheet. */ /* used to remove borders from tables and images */ .borderless, table.borderless td, table.borderless th { border: 0 } table.borderless td, table.borderless th { /* Override padding for "table.docutils td" with "! important". The right padding separates the table cells. */ padding: 0 0.5em 0 0 ! important } .first { /* Override more specific margin styles with "! important". */ margin-top: 0 ! important } .last, .with-subtitle { margin-bottom: 0 ! important } .hidden { display: none } a.toc-backref { text-decoration: none ; color: black } blockquote.epigraph { margin: 2em 5em ; } dl.docutils dd { margin-bottom: 0.5em } object[type="image/svg+xml"], object[type="application/x-shockwave-flash"] { overflow: hidden; } /* Uncomment (and remove this text!) to get bold-faced definition list terms dl.docutils dt { font-weight: bold } */ div.abstract { margin: 2em 5em } div.abstract p.topic-title { font-weight: bold ; text-align: center } div.admonition, div.attention, div.caution, div.danger, div.error, div.hint, div.important, div.note, div.tip, div.warning { margin: 2em ; border: medium outset ; padding: 1em } div.admonition p.admonition-title, div.hint p.admonition-title, div.important p.admonition-title, div.note p.admonition-title, div.tip p.admonition-title { font-weight: bold ; font-family: sans-serif } div.attention p.admonition-title, div.caution p.admonition-title, div.danger p.admonition-title, div.error p.admonition-title, div.warning p.admonition-title { color: red ; font-weight: bold ; font-family: sans-serif } /* Uncomment (and remove this text!) to get reduced vertical space in compound paragraphs. div.compound .compound-first, div.compound .compound-middle { margin-bottom: 0.5em } div.compound .compound-last, div.compound .compound-middle { margin-top: 0.5em } */ div.dedication { margin: 2em 5em ; text-align: center ; font-style: italic } div.dedication p.topic-title { font-weight: bold ; font-style: normal } div.figure { margin-left: 2em ; margin-right: 2em } div.footer, div.header { clear: both; font-size: smaller } div.line-block { display: block ; margin-top: 1em ; margin-bottom: 1em } div.line-block div.line-block { margin-top: 0 ; margin-bottom: 0 ; margin-left: 1.5em } div.sidebar { margin: 0 0 0.5em 1em ; border: medium outset ; padding: 1em ; background-color: #ffffee ; width: 40% ; float: right ; clear: right } div.sidebar p.rubric { font-family: sans-serif ; font-size: medium } div.system-messages { margin: 5em } div.system-messages h1 { color: red } div.system-message { border: medium outset ; padding: 1em } div.system-message p.system-message-title { color: red ; font-weight: bold } div.topic { margin: 2em } h1.section-subtitle, h2.section-subtitle, h3.section-subtitle, h4.section-subtitle, h5.section-subtitle, h6.section-subtitle { margin-top: 0.4em } h1.title { text-align: center } h2.subtitle { text-align: center } hr.docutils { width: 75% } img.align-left, .figure.align-left, object.align-left { clear: left ; float: left ; margin-right: 1em } img.align-right, .figure.align-right, object.align-right { clear: right ; float: right ; margin-left: 1em } img.align-center, .figure.align-center, object.align-center { display: block; margin-left: auto; margin-right: auto; } .align-left { text-align: left } .align-center { clear: both ; text-align: center } .align-right { text-align: right } /* reset inner alignment in figures */ div.align-right { text-align: inherit } /* div.align-center * { */ /* text-align: left } */ ol.simple, ul.simple { margin-bottom: 1em } ol.arabic { list-style: decimal } ol.loweralpha { list-style: lower-alpha } ol.upperalpha { list-style: upper-alpha } ol.lowerroman { list-style: lower-roman } ol.upperroman { list-style: upper-roman } p.attribution { text-align: right ; margin-left: 50% } p.caption { font-style: italic } p.credits { font-style: italic ; font-size: smaller } p.label { white-space: nowrap } p.rubric { font-weight: bold ; font-size: larger ; color: maroon ; text-align: center } p.sidebar-title { font-family: sans-serif ; font-weight: bold ; font-size: larger } p.sidebar-subtitle { font-family: sans-serif ; font-weight: bold } p.topic-title { font-weight: bold } pre.address { margin-bottom: 0 ; margin-top: 0 ; font: inherit } pre.literal-block, pre.doctest-block, pre.math, pre.code { margin-left: 2em ; margin-right: 2em } pre.code .ln { /* line numbers */ color: grey; } .code { background-color: #eeeeee } span.classifier { font-family: sans-serif ; font-style: oblique } span.classifier-delimiter { font-family: sans-serif ; font-weight: bold } span.interpreted { font-family: sans-serif } span.option { white-space: nowrap } span.pre { white-space: pre } span.problematic { color: red } span.section-subtitle { /* font-size relative to parent (h1..h6 element) */ font-size: 80% } table.citation { border-left: solid 1px gray; margin-left: 1px } table.docinfo { margin: 2em 4em } table.docutils { margin-top: 0.5em ; margin-bottom: 0.5em } table.footnote { border-left: solid 1px black; margin-left: 1px } table.docutils td, table.docutils th, table.docinfo td, table.docinfo th { padding-left: 0.5em ; padding-right: 0.5em ; vertical-align: top } table.docutils th.field-name, table.docinfo th.docinfo-name { font-weight: bold ; text-align: left ; white-space: nowrap ; padding-left: 0 } h1 tt.docutils, h2 tt.docutils, h3 tt.docutils, h4 tt.docutils, h5 tt.docutils, h6 tt.docutils { font-size: 100% } ul.auto-toc { list-style-type: none } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/standalone_rst_html4css1.txt������������������������������������0000664�0001750�0001750�00000001345�11466350404�027175� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������.. include:: data/standard.txt .. include:: data/header_footer.txt .. include:: data/table_colspan.txt .. include:: data/table_rowspan.txt .. include:: data/table_complex.txt .. include:: data/list_table.txt .. include:: data/custom_roles.txt .. include:: data/svg_images.txt .. include:: data/swf_images.txt .. include:: data/errors.txt .. footer:: |valid-xhtml10| |valid-CSS2| .. |valid-xhtml10| image:: http://www.w3.org/Icons/valid-xhtml10 :height: 31 :width: 88 :alt: Valid XHTML 1.0! :target: http://validator.w3.org/check?uri=referer .. |valid-CSS2| image:: http://jigsaw.w3.org/css-validator/images/vcss :height: 31 :width: 88 :alt: Valid CSS 2.1! :target: http://jigsaw.w3.org/css-validator/check/referer �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/latex_docinfo.txt�����������������������������������������������0000664�0001750�0001750�00000000367�10172311455�025070� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������:Author: Foo Fred :Organization: Food Foomatics & Friends :Contact: foo@food.example.info :Address: Fox St 13 Foowood :Author: Bar Barney :Organization: Bar-BQ Bar :Contact: 1-800-BARBQBAR :Address: Barbara St 16 South Barwell �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/odt_custom_headfoot.txt�����������������������������������������0000664�0001750�0001750�00000000244�11316456115�026301� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������============================ Custom Headers and Footers ============================ Test for custom headers and footers and for page numbers, date, time, etc. ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/dangerous.txt���������������������������������������������������0000664�0001750�0001750�00000000537�10235656213�024244� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Potentially dangerous features (security holes): .. include:: /etc/passwd .. raw:: html :file: /etc/passwd .. raw:: html :url: file:///etc/passwd .. raw:: html <script> that does something really nasty </script> .. csv-table:: :file: /etc/passwd .. csv-table:: :url: file:///etc/passwd .. figure:: picture.png :figwidth: image �����������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/odt_basic.txt���������������������������������������������������0000664�0001750�0001750�00000000072�11125256176�024201� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������===== Test ===== Basic # 1 ========== A *simple* test. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/pep_html.txt����������������������������������������������������0000664�0001750�0001750�00000001056�10232307536�024060� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������PEP: 100 Title: Test PEP Version: 42 Last-Modified: A long time ago. Author: John Doe <john@example.org> Discussions-To: <devnull@example.org> Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 01-Jun-2001 Post-History: 13-Jun-2001 Abstract ======== This is just a test [#]_. See the `PEP repository`_ for the real thing. .. _PEP repository: http://www.python.org/peps/ Copyright ========= This document has been placed in the public domain. References and Footnotes ======================== .. [#] PEP editors: peps@python.org ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/standalone_rst_manpage.txt��������������������������������������0000664�0001750�0001750�00000003546�11465100234�026761� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������========= rst2man ========= --------------------------------------------- generate unix manpages from reStructured text --------------------------------------------- :Author: grubert@users.sourceforge.net :Date: 2006-10-22 :Copyright: public domain :Version: 0.1 :Manual section: 1 :Manual group: text processing .. TODO: authors and author with name <email> SYNOPSIS ======== rst2man.py inputfile outputfile DESCRIPTION =========== rst2man transforms a reStructured text document into a unix man page. In theory any valid reStructured text document should be processable, in reality this is * a goal, that is not met yet * a goal that might never be met, because only few constructs are used in man pages *and* because the common text file does not adhere to man page requirements. For example a unix man page belongs into a numbered section, 1 is user commands, 8 contains administrator commands and the headlines of all manpages are collected into a database, queryable with the programm ``apropos``, therefore the headline should contain a short text describing into which group this command belongs. These informations are collected from title, subtitle and the docinfo, see this document as an example. OPTIONS ======= --config=<file> Read configuration settings from <file>, if it exists. --version, -V Show this program's version number and exit. --help, -h Show this help message and exit. And a lot more standard docutils options. FILES ===== None yet. SEE ALSO ======== `docutils <http://docutils.sourceforge.net>`__ `linux man page howto <http://tldp.org/HOWTO/Man-Page/>`__ and ``man man`` also ``man 7 man`` BUGS ==== 1. Format options are included as they are required. 2. bullet lists 3. number lists 4. math: The LaTeX source is shown, e.g. :math:`n! + \sin(x_n^2)`. Discussion is still open. ����������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/input/standalone_rst_s5_html.txt��������������������������������������0000664�0001750�0001750�00000004737�10345743234�026740� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������.. include:: <s5defs.txt> ============= Slide Shows ============= :Author: David Goodger :Date: 2005-11-28 .. contents:: :class: handout .. class:: handout This is a test. This is only a test. If this were a real slide show, there would be a projector handy. Let's test the S5/HTML writer! .. class:: small * Use the arrow keys to navigate. * Click the "|mode|" button to switch between presentation & handout/outline modes. .. container:: handout In presentation mode, mouse over to the lower right-hand corner to display the controls. .. |bullet| unicode:: U+02022 .. |mode| unicode:: U+00D8 .. capital o with stroke .. footer:: Location |bullet| Date Introduction ============ .. class:: compact * reStructuredText .. class:: handout Uses normal reStructuredText as input. * One section per slide .. class:: handout Each first-level section is converted into a single slide. * (X)HTML output .. class:: handout Presentations can be viewed using any modern graphical web browser. The browser must support CSS, JavaScript, and XHTML. S5 even works with IE! * Themes .. class:: handout A variety of themes are available. * ``rst2s5.py`` .. class:: handout The front-end tool to generate S5 slide shows. Features (1) ============ .. class:: left A flush-left paragraph .. class:: center A centered paragraph .. class:: right A flush-right paragraph Some colours: :black:`black` [black], :gray:`gray`, :silver:`silver`, :white:`white` [white], :maroon:`maroon`, :red:`red`, :magenta:`magenta`, :fuchsia:`fuchsia`, :pink:`pink`, :orange:`orange`, :yellow:`yellow`, :lime:`lime`, :green:`green`, :olive:`olive`, :teal:`teal`, :cyan:`cyan`, :aqua:`aqua`, :blue:`blue`, :navy:`navy`, :purple:`purple` Features (2) ============ `Some` `incremental` `text.` .. class:: incremental open * :tiny:`tiny` (class & role name: "tiny", e.g. "``:tiny:`text```") * :small:`small` ("small") * normal (unstyled) * :big:`big` ("big") * :huge:`huge` ("huge") Checklist ========= * The document title should be duplicated on each slide in the footer (except for the first slide, ``slide0``, where the entire footer is disabled). * The footer also contains a second line, "Location |bullet| Date" * There's no table of contents on the first slide, although it does appear in the handout/outline. * Handout material is not displayed in presentation mode. * The theme directories should be created, and the theme files copied over. ���������������������������������docutils-0.12/test/functional/output/���������������������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�021710� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/output/README.txt�����������������������������������������������������0000664�0001750�0001750�00000000202�10066121605�023372� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������This is the directory where the actual output is stored. This README.txt is just a placeholder to make CVS create the directory. ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/expected/�������������������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�022151� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/expected/odt_custom_headfoot.odt��������������������������������������0000664�0001750�0001750�00000022311�12014257243�026706� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������PK�����tA^2 '���'������mimetypeapplication/vnd.oasis.opendocument.textPK����tA#b5-��o�� ���content.xmlM0'(Ra#UjN�VF ɿ 1ygeYrY!Yߢ0);AS+I\gZԙaP<DY�g.;%1]Fi׫f+UE FAtә ð#%R:LCcQ)0pQRƊoIKiwKK7uPۂY/l6h v-džk/0}oXSCz)lL{@q CxPܠzBm#Ք"6Pf]lyzw-_}j \Co;6Hz 7\YW:ZgTOVc ON8&tRC7-aZ kB Fq,K/x%7SҁJAW'*)Qڌ[%yОO֣'x; :./q,hG[/E#4QoRdz麋gN_ =A[~KwzV {-n}.OEt寚PK����tA6X ����S�����META-INF/manifest.xmlM -= ѱ% MZ4M[L-ޱL,NumxvDYj5'T$IQBB?{@RzUmF:+mٹ:j.60XSAsWp Z,.> ӜoʲN:Hp�2R'muPK����tAպK�������meta.xmlN oey tXq1l^�ohݽ-qx𤥴@m &5:x*69P̺ I@@zD2jۤuZi6`7KI$|ݷv #us7hY+sZnYRiAQK/[yȚK-0/8QAq q*OQL}<NYJ)~JI'~ԾJ)ks8P00.fhTً*32ݍoYٺ>c+-T[lz.7rjmQjJto}PK����tARs��Ri� ���styles.xml]i6_+MP[Ud$Z{DBc^֫H�R"iѩ-t8g;:XłնGr^rv.Ma}zЉjxQp0uS'q\Y}0v|l6@b󻤼&dt/GEwm`smd!ۈtKگQdZ.|ż*#d<'-6=U'ڔЁqАq D>kf&\"[Cŀd%~ȇe{f5F#c:ۦuIgN˺#t 29㤀gb2>ݴ?uѯ9#.U໊a|Ȥ; /}$lFȮ$K+rmCj BbnKIJ6}֐(ᥣ L�+ԃ|HaGSˆ)@$zke:P=-\dld)_Op |dj(<{g_c)?*E:=PuB |2CLiBFj a-2DR0i K+0 �/tF&2|xDNyZ4$o . Qhky8J2-pA'׉r9T:vu-1 hؖ�qa>WEb؎%^8`kr&ɂEGJFU00;T8fV[Fr{0,N޻ t( ė1MKRDfD~~> f (4?1"v]AN^kгiX.DE([<[{V{ꝤG}S{ ;$<T>Џ &~ڜs `(igp&|"飽k\$:e'bGɌR5-w6@D({cצe%$*iؑ˚4ӿŊ9ԧ PT4غS0Ď* 2'CS- Z) ?C`ċC+ aSYGu\S|&cW\/|aQ:,"%-jnx|5`fX Ujl 9=R奂^}hD%bәgH'MTuf\7N6DeVW6"#Q&.h8ܸU~<3ڡѽy=/uܺWe\YʢlJb&IԇOe4fX*cɪKV-d]’u,Y7e<_bUPCJ! E%<:lf?Yԏ&OK'1{J[᱋GO%&[m3/ιSyUﲬuq?X,7kuڬ١:YovY aИ2 )X:#uĿڧTAT<]uDЈ"i"C@&debiZk2=?�N o S#o|A?Y:`^i6^U*>+c,/7|`/I'l[y c6OrakUI0ʷ/ꄞ292,z0W""2@\0t}-TdR~6 |Wlc:#utx몰{Ou ]n@w/U5uM:* jzDi ;vQ W%BʑuuS|Bƒ41{>"7pd8>oU| PMð˂5C%rfp|}}?YE=&be|î (د pPM&TU=Z4_ |MCRj(e`h5Uj$O?/ dRaX.ڝX55 gzb"oZ8 yCSJO,MQb9.L"E%;nHiBrs(oUE#ꝮaoߵLcnEmMFeB[;i3PSb6aCĵJh50 EC.fYC'Uѯ0J:7%#~Pܾ}P/t1̖[urC2; < }s*EW}P =F+<s| ufgnǥwYB,u.p1A wB6s0}jF(aXb%,s 9B Qi<CD]1ӭ9B4 MradVN&bAnϴ=x,L݊!ݛ)b[æ7R G;R At: {@~{@(6:fx8[@-& qa} 5NA"l}a) IrWH:@NM׼D{JVDf wc5Vcj5ԉUjUV]qR x򷪒{W`/uo.!MC"4<hJkc#ˍiYN/U {]K|ɦGX!f<bo!z0|ھ&VzI?_]2<t"mє7\zt,_ƓQG>YSh3/pH C(47}!lfeŧWY|; #gնlvX|wHG2=R|k]:{c5G)i,Z~d򳎟h1OqGdgޓ|!#gjY >\_S|R~e{uU;)>Fm;,>)ټQ|65ŧxTwzY ЖŢⳕg[S|GuYi,& ˖: - .^m/&\~2+6o&]0YnmO$+{>mۚ{H+bkz/2؁A ]ŒNbND%l#v{=.߾W_cpO6qC~/ ëxCvX hQeԆtVӤ"',aؤya S{RQʛDjNjM&QmLqF]T7냗;p ^iΊ[D޶%6bۚgxNk)@|GEn8=щv"/mwܹx="y2"%\grC)8dz@tW|S8<ӡ11$aI$SpWSM >%]~iQ$K3г%ĜI i, DK~3 'HxoG K?-پ}o ѩr=!t$�:<=}XxZIoQ`pd'[X*;KztL'd{w&)48קbG=`$5N[}BODMbn ~{{{NHP۰M,;IYP#W<PDVr9ն/MUҝpA%)>w}0\dE_rį-yrHw *hp)AR"l3/ KX\WM :jJ8o:Tl`-'~-33*BL1<K;垉 [i 艠gy1D%Hiɥ:>ޒ�zxM/Z|sWۙY-9"W-9 t-_ N 3Z|sg~PEo[|k/M+jPo �IܓWg=G<{),ZS3Nji^~|Ua a4Ɓ5 =!uXs6 |ْ. &9S@-=ouT/ZZme[$:WQ"ֈnsNoZZkm[$:YkdסZ(PǮ_x"x�zj*ݬsKa72 Xmz\KcV>uo�A+3s#9v#� ^cB?̱̌1p�Z=_Wk�؍~vfBkkTQj +]? #~\SExt}pOY?UD>>牝gTQDS䉡}SL!L8 =r_>}0ZC{!0|] |0|�|0vN2kI!nn=+S[CHD==1B3`XE齈R.}LQMӞ*C3;EC{yƦg_}=sRt gDWLG^8ǓE_d'-!29D&dg"CdrLv !29D&#0D&"CdrL!2ddz&]<% ZC\rKq.6%|`\2vCTrJQ!*9D%J؛`b &`b &`b &`b &F&*w7lfT/3̨$gfF%=23*陙QIǑJbzffT_\87Wͨ_fF%9=33*铙QIĽJzefT33>̨^Gnfw{4㿾hF%=23*陙QIǑJbzffT/3̨$gfF:UF3~ʢ̨$gfF%=}23*陙QIǑJrzffT'3hg Wt9�lyeb^s}|{y.Qt 8*ñQMb/ %=<z�1nL%ґwPy m,2,x vb^uH47|&6u%NB`օv#h,X"dԑ` FVgcpQ|~v!䗢e :醴<ZZhaTjj(q{b|^(6xUN>*Ed^L$#sFļ"kt�2ٻOh TB@|P99v j:9]C=|6EC増 C8ͷWyEPW!c OL C/mӯګ)mAeJ?,d#ØY>WɌ%ɺrHrJDzA烤?ה19%eB}5j=vOIl9b@$b2IOI**D_mC[e gYylj/MZ�Uu2` -$?DخO)l 0Kьg%[/E/pYO+6M;<jhB/TDf�÷CR-0 ؊gI}/y764Qki%,2�2" Q.c'p#+,r_'tȚ85)OՉ:R>ϓf3uJJ(7'UhnH )gL9[Di lCX),uL#Eˊ}50щn3NwݘZZc1必ziqXP\Z9Ա="GR:2=K7>_u dXTm+bWt>Ljy#I!P}1 VD]阩ԗ bo# VL4QFڕBv]ukC$t "1"<i3USfEݎ4u7_rtC8'i#bz I~hY k~M2MkH-pG>q~(kib>�j~LTWG2B7i%S9ʵxɸr0_92=^-t<wG9<¥J %b(iQ4D! (Ph0 |ѻ %!ahS5C]Wuܷ<1MQPK����tA5&FsR��#�� ���settings.xmlZ[SH~WPyWˬRTakIkO#t\~Ls%|GJs^ԫ 0rr=[W׻y�$i5CktK]^zudd \n\]OѲ's75&Wdv~jR]__Wӷ˥1l @vCvUK~͙wwTYjb�zTQ?@dTz[0{W=mE{|l|c1('Muݎظ:f/~�L7_vy}^Bg}9erze(IΨiˆ™G ā 8b1!!\W\|)"[%͵QYŷ<A/jW_uYpGߝ?_X6tk@h1U߈ѐ\)*SZ?liH" 9FI -1SÖj*㴔z�aKу=f 4Mk(#Ƴb*]/zD'L ܤbP-�LJg̴Q%KX21wX?L$5K`+LXM2ZG)4-T<~(:T?!3 ?Rvj" g:"PCirWoQl#! rD)"{fDɂRrK)5A an^;$X,5(+SbibXe8.G?1#HTJlhSn-hi�NA(]r]o,>-"t$F-L.2l&_5*yM&D8OhRUbHEg�ʻT?WEKV/ `hѝ D>^XcnL&L4WGl%_1Z[w}>t'QWydQűUJL.LiwnK*ݩ=We VY uLeǎVa<)Vv|`: _$%)#[sI}`lmlV.,fk>z@ZOsր�d))tc?t ߶@ԮwkQFDtzw{Fì%W]౯ߙЗ/Xc;g= b 騢 BXw:al >JM)SJ@X7<XdEKF-QjYـ$_sbڰXop9Wl@٫b(HDQ+-;!OGYLhU:%n׮r%_/ )P06CbSO>T~hg-wPK�����tA^2 '���'������������������mimetypePK����tA#b5-��o�� �����������M���content.xmlPK����tA6X ����S���������������META-INF/manifest.xmlPK����tAպK�����������������meta.xmlPK����tARs��Ri� �������������styles.xmlPK����tA5&FsR��#�� �������������settings.xmlPK������Z��Y#���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/expected/xetex-cyrillic.tex�������������������������������������������0000664�0001750�0001750�00000003557�12076016516�025653� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������\documentclass[a4paper,russian]{article} % generated by Docutils <http://docutils.sourceforge.net/> % rubber: set program xelatex \usepackage[no-sscript]{xltxtra} % loads fixltx2e, metalogo, xunicode, fontspec % \defaultfontfeatures{Scale=MatchLowercase} \usepackage{ifthen} \usepackage{polyglossia} \setdefaultlanguage{russian} \setotherlanguages{english} \setcounter{secnumdepth}{0} %%% Custom LaTeX preamble % Linux Libertine (free, wide coverage, not only for Linux) \setmainfont{Linux Libertine O} \setsansfont{Linux Biolinum O} \setmonofont[HyphenChar=None,Scale=MatchLowercase]{DejaVu Sans Mono} %%% User specified packages and stylesheets %%% Fallback definitions for Docutils-specific commands % titlereference role \providecommand*{\DUroletitlereference}[1]{\textsl{#1}} % hyperlinks: \ifthenelse{\isundefined{\hypersetup}}{ \usepackage[colorlinks=true,linkcolor=blue,urlcolor=blue,unicode=false]{hyperref} \urlstyle{same} % normal text font (alternatives: tt, rm, sf) }{} %%% Body \begin{document} \section{Заголовок% \label{id1}% } первый пример: «Здравствуй, мир!» \section{Title% \label{title}% } \foreignlanguage{english}{first example: “Hello world”.} \section{Notes% \label{notes}% } \foreignlanguage{english}{This example tests rendering of Latin and Cyrillic characters by the LaTeX and XeTeX writers. Check the compiled PDF for garbage characters in text and bookmarks.} \foreignlanguage{english}{To work around a problem with Cyrillic in PDF-bookmarks in \DUroletitlereference{hyperref} versions older than v6.79g 2009/11/20, the test caller \texttt{latex\_cyrillic.py} sets \texttt{hyperref\_options} to \texttt{'unicode=true'} while \texttt{xetex\_cyrillic.py} sets it to \texttt{'unicode=false'}. The recommended option for current (2011-08-24) hyperref versions is \texttt{'pdfencoding=auto'}.} \end{document} �������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/expected/standalone_rst_pseudoxml.txt���������������������������������0000664�0001750�0001750�00000271317�12024637300�030037� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<document ids="restructuredtext-test-document doctitle" names="restructuredtext\ test\ document doctitle" source="functional/input/standalone_rst_pseudoxml.txt" title="reStructuredText Test Document"> <title> reStructuredText Test Document <subtitle ids="examples-of-syntax-constructs subtitle" names="examples\ of\ syntax\ constructs subtitle"> Examples of Syntax Constructs <decoration> <header> <paragraph> Document header <footer> <paragraph> Document footer <docinfo> <author> David Goodger <address xml:space="preserve"> 123 Example Street Example, EX Canada A1B 2C3 <contact> <reference refuri="mailto:goodger@python.org"> goodger@python.org <authors> <author> Me <author> Myself <author> I <organization> humankind <date> Now, or yesterday. Or maybe even <emphasis> before yesterday. <status> This is a "work in progress" <revision> is managed by a version control system. <version> 1 <copyright> This document has been placed in the public domain. You may do with it as you wish. You may copy, modify, redistribute, reattribute, sell, buy, rent, lease, destroy, or improve it, quote it at length, excerpt, incorporate, collate, fold, staple, or mutilate it, or do anything else to it that your or anyone else's heart desires. <field> <field_name> field name <field_body> <paragraph> This is a "generic bibliographic field". <field> <field_name> field name "2" <field_body> <paragraph> Generic bibliographic fields may contain multiple body elements. <paragraph> Like this. <topic classes="dedication"> <title> Dedication <paragraph> For Docutils users & co-developers. <topic classes="abstract"> <title> Abstract <paragraph> This is a test document, containing at least one example of each reStructuredText construct. <comment xml:space="preserve"> This is a comment. Note how any initial comments are moved by transforms to after the document title, subtitle, and docinfo. <target refid="doctitle"> <comment xml:space="preserve"> Above is the document title, and below is the subtitle. They are transformed from section titles after parsing. <target refid="subtitle"> <comment xml:space="preserve"> bibliographic fields (which also require a transform): <meta content="reStructuredText, test, parser" name="keywords"> <meta content="A test document, containing at least one example of each reStructuredText construct." lang="en" name="description"> <raw format="latex" xml:space="preserve"> \pagebreak[4] % start ToC on new page <topic classes="contents" ids="table-of-contents" names="table\ of\ contents"> <title> Table of Contents <bullet_list classes="auto-toc"> <list_item> <paragraph> <reference ids="id34" refid="structural-elements"> <generated classes="sectnum"> 1    Structural Elements <bullet_list classes="auto-toc"> <list_item> <paragraph> <reference ids="id35" refid="section-title"> <generated classes="sectnum"> 1.1    Section Title <list_item> <paragraph> <reference ids="id36" refid="empty-section"> <generated classes="sectnum"> 1.2    Empty Section <list_item> <paragraph> <reference ids="id37" refid="transitions"> <generated classes="sectnum"> 1.3    Transitions <list_item> <paragraph> <reference ids="id38" refid="body-elements"> <generated classes="sectnum"> 2    Body Elements <bullet_list classes="auto-toc"> <list_item> <paragraph> <reference ids="id39" refid="paragraphs"> <generated classes="sectnum"> 2.1    Paragraphs <bullet_list classes="auto-toc"> <list_item> <paragraph> <reference ids="id40" refid="inline-markup"> <generated classes="sectnum"> 2.1.1    Inline Markup <list_item> <paragraph> <reference ids="id41" refid="bullet-lists"> <generated classes="sectnum"> 2.2    Bullet Lists <list_item> <paragraph> <reference ids="id42" refid="enumerated-lists"> <generated classes="sectnum"> 2.3    Enumerated Lists <list_item> <paragraph> <reference ids="id43" refid="definition-lists"> <generated classes="sectnum"> 2.4    Definition Lists <list_item> <paragraph> <reference ids="id44" refid="field-lists"> <generated classes="sectnum"> 2.5    Field Lists <list_item> <paragraph> <reference ids="id45" refid="option-lists"> <generated classes="sectnum"> 2.6    Option Lists <list_item> <paragraph> <reference ids="id46" refid="literal-blocks"> <generated classes="sectnum"> 2.7    Literal Blocks <list_item> <paragraph> <reference ids="id47" refid="line-blocks"> <generated classes="sectnum"> 2.8    Line Blocks <list_item> <paragraph> <reference ids="id48" refid="block-quotes"> <generated classes="sectnum"> 2.9    Block Quotes <list_item> <paragraph> <reference ids="id49" refid="doctest-blocks"> <generated classes="sectnum"> 2.10    Doctest Blocks <list_item> <paragraph> <reference ids="id50" refid="footnotes"> <generated classes="sectnum"> 2.11    Footnotes <list_item> <paragraph> <reference ids="id51" refid="citations"> <generated classes="sectnum"> 2.12    Citations <list_item> <paragraph> <reference ids="id52" refid="targets"> <generated classes="sectnum"> 2.13    Targets <bullet_list classes="auto-toc"> <list_item> <paragraph> <reference ids="id53" refid="duplicate-target-names"> <generated classes="sectnum"> 2.13.1    Duplicate Target Names <list_item> <paragraph> <reference ids="id54" refid="id21"> <generated classes="sectnum"> 2.13.2    Duplicate Target Names <list_item> <paragraph> <reference ids="id55" refid="directives"> <generated classes="sectnum"> 2.14    Directives <bullet_list classes="auto-toc"> <list_item> <paragraph> <reference ids="id56" refid="document-parts"> <generated classes="sectnum"> 2.14.1    Document Parts <list_item> <paragraph> <reference ids="id57" refid="images-and-figures"> <generated classes="sectnum"> 2.14.2    Images and Figures <list_item> <paragraph> <reference ids="id58" refid="admonitions"> <generated classes="sectnum"> 2.14.3    Admonitions <list_item> <paragraph> <reference ids="id59" refid="topics-sidebars-and-rubrics"> <generated classes="sectnum"> 2.14.4    Topics, Sidebars, and Rubrics <list_item> <paragraph> <reference ids="id60" refid="target-footnotes"> <generated classes="sectnum"> 2.14.5    Target Footnotes <list_item> <paragraph> <reference ids="id61" refid="replacement-text"> <generated classes="sectnum"> 2.14.6    Replacement Text <list_item> <paragraph> <reference ids="id62" refid="compound-paragraph"> <generated classes="sectnum"> 2.14.7    Compound Paragraph <list_item> <paragraph> <reference ids="id63" refid="parsed-literal-blocks"> <generated classes="sectnum"> 2.14.8    Parsed Literal Blocks <list_item> <paragraph> <reference ids="id64" refid="code"> <generated classes="sectnum"> 2.14.9    Code <list_item> <paragraph> <reference ids="id65" refid="substitution-definitions"> <generated classes="sectnum"> 2.15    Substitution Definitions <list_item> <paragraph> <reference ids="id66" refid="comments"> <generated classes="sectnum"> 2.16    Comments <list_item> <paragraph> <reference ids="id67" refid="raw-text"> <generated classes="sectnum"> 2.17    Raw text <list_item> <paragraph> <reference ids="id68" refid="container"> <generated classes="sectnum"> 2.18    Container <list_item> <paragraph> <reference ids="id69" refid="colspanning-tables"> <generated classes="sectnum"> 2.19    Colspanning tables <list_item> <paragraph> <reference ids="id70" refid="rowspanning-tables"> <generated classes="sectnum"> 2.20    Rowspanning tables <list_item> <paragraph> <reference ids="id71" refid="complex-tables"> <generated classes="sectnum"> 2.21    Complex tables <list_item> <paragraph> <reference ids="id72" refid="list-tables"> <generated classes="sectnum"> 2.22    List Tables <list_item> <paragraph> <reference ids="id73" refid="error-handling"> <generated classes="sectnum"> 3    Error Handling <section ids="structural-elements" names="structural\ elements"> <title auto="1" refid="id34"> <generated classes="sectnum"> 1    Structural Elements <section ids="section-title" names="section\ title"> <title auto="1" refid="id35"> <generated classes="sectnum"> 1.1    Section Title <subtitle ids="section-subtitle" names="section\ subtitle"> Section Subtitle <paragraph> Lone subsections are converted to a section subtitle by a transform activated with the <literal> --section-subtitles command line option or the <literal> sectsubtitle-xform configuration value. <section ids="empty-section" names="empty\ section"> <title auto="1" refid="id36"> <generated classes="sectnum"> 1.2    Empty Section <section ids="transitions" names="transitions"> <title auto="1" refid="id37"> <generated classes="sectnum"> 1.3    Transitions <paragraph> Here's a transition: <transition> <paragraph> It divides the section. Transitions may also occur between sections: <transition> <section ids="body-elements" names="body\ elements"> <title auto="1" refid="id38"> <generated classes="sectnum"> 2    Body Elements <section ids="paragraphs" names="paragraphs"> <title auto="1" refid="id39"> <generated classes="sectnum"> 2.1    Paragraphs <paragraph> A paragraph. <section ids="inline-markup" names="inline\ markup"> <title auto="1" refid="id40"> <generated classes="sectnum"> 2.1.1    Inline Markup <paragraph> Paragraphs contain text and may contain inline markup: <emphasis> emphasis , <strong> strong emphasis , <literal> inline literals , standalone hyperlinks ( <reference refuri="http://www.python.org"> http://www.python.org ), external hyperlinks ( <reference name="Python" refuri="http://www.python.org/"> Python <footnote_reference auto="1" ids="id26" refid="id25"> 5 ), internal cross-references ( <reference name="example" refid="example"> example ), external hyperlinks with embedded URIs ( <reference name="Python web site" refuri="http://www.python.org"> Python web site ), <reference anonymous="1" name="anonymous hyperlink references" refuri="http://www.python.org/"> anonymous hyperlink references <footnote_reference auto="1" ids="id31" refid="id25"> 5 ( <reference anonymous="1" name="a second reference" refuri="http://docutils.sourceforge.net/"> a second reference <footnote_reference auto="1" ids="id33" refid="id32"> 7 ), footnote references (manually numbered <footnote_reference ids="id1" refid="id8"> 1 , anonymous auto-numbered <footnote_reference auto="1" ids="id2" refid="id12"> 3 , labeled auto-numbered <footnote_reference auto="1" ids="id3" refid="label"> 2 , or symbolic <footnote_reference auto="*" ids="id4" refid="id13"> * ), citation references ( <citation_reference ids="id5" refid="cit2002"> CIT2002 ), substitution references ( <image alt="EXAMPLE" uri="../../../docs/user/rst/images/biohazard.png"> ), and <target ids="inline-hyperlink-targets" names="inline\ hyperlink\ targets"> inline hyperlink targets (see <reference name="Targets" refid="targets"> Targets below for a reference back to here). Character-level inline markup is also possible (although exceedingly ugly!) in <emphasis> re <literal> Structured <emphasis> Text . Problems are indicated by <problematic ids="id24" refid="id23"> |problematic| text (generated by processing errors; this one is intentional). Here is a reference to the <reference name="doctitle" refid="doctitle"> doctitle and the <reference name="subtitle" refid="subtitle"> subtitle . <target anonymous="1" ids="id6" refuri="http://www.python.org/"> <target anonymous="1" ids="id7" refuri="http://docutils.sourceforge.net/"> <paragraph> The default role for interpreted text is <title_reference> Title Reference . Here are some explicit interpreted text roles: a PEP reference ( <reference refuri="http://www.python.org/dev/peps/pep-0287"> PEP 287 ); an RFC reference ( <reference refuri="http://www.faqs.org/rfcs/rfc2822.html"> RFC 2822 ); an abbreviation ( <abbreviation> abb. ), an acronym ( <acronym> reST ), code ( <literal classes="code"> print "hello world" ); a <subscript> subscript ; a <superscript> superscript and explicit roles for <title_reference> Docutils ' <emphasis> standard <strong> inline <literal> markup . <comment xml:space="preserve"> DO NOT RE-WRAP THE FOLLOWING PARAGRAPH! <paragraph> Let's test wrapping and whitespace significance in inline literals: <literal> This is an example of --inline-literal --text, --including some-- strangely--hyphenated-words. Adjust-the-width-of-your-browser-window to see how the text is wrapped. -- ---- -------- Now note the spacing between the words of this sentence (words should be grouped in pairs). <paragraph> If the <literal> --pep-references option was supplied, there should be a live link to PEP 258 here. <section ids="bullet-lists" names="bullet\ lists"> <title auto="1" refid="id41"> <generated classes="sectnum"> 2.2    Bullet Lists <bullet_list bullet="-"> <list_item> <paragraph> A bullet list <bullet_list bullet="+"> <list_item> <paragraph> Nested bullet list. <list_item> <paragraph> Nested item 2. <list_item> <paragraph> Item 2. <paragraph> Paragraph 2 of item 2. <bullet_list bullet="*"> <list_item> <paragraph> Nested bullet list. <list_item> <paragraph> Nested item 2. <bullet_list bullet="-"> <list_item> <paragraph> Third level. <list_item> <paragraph> Item 2. <list_item> <paragraph> Nested item 3. <list_item> <paragraph> This nested list should be compacted by the HTML writer. <target ids="target" names="target"> <comment xml:space="preserve"> Even if this item contains a target and a comment. <section ids="enumerated-lists" names="enumerated\ lists"> <title auto="1" refid="id42"> <generated classes="sectnum"> 2.3    Enumerated Lists <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Arabic numerals. <enumerated_list enumtype="loweralpha" prefix="" suffix=")"> <list_item> <paragraph> lower alpha) <enumerated_list enumtype="lowerroman" prefix="(" suffix=")"> <list_item> <paragraph> (lower roman) <enumerated_list enumtype="upperalpha" prefix="" suffix="."> <list_item> <paragraph> upper alpha. <enumerated_list enumtype="upperroman" prefix="" suffix=")"> <list_item> <paragraph> upper roman) <list_item> <paragraph> Lists that don't start at 1: <enumerated_list enumtype="arabic" prefix="" start="3" suffix="."> <list_item> <paragraph> Three <list_item> <paragraph> Four <system_message level="1" line="8" source="functional/input/data/standard.txt" type="INFO"> <paragraph> Enumerated list start value not ordinal-1: "3" (ordinal 3) <enumerated_list enumtype="upperalpha" prefix="" start="3" suffix="."> <list_item> <paragraph> C <list_item> <paragraph> D <system_message level="1" line="8" source="functional/input/data/standard.txt" type="INFO"> <paragraph> Enumerated list start value not ordinal-1: "C" (ordinal 3) <enumerated_list enumtype="lowerroman" prefix="" start="3" suffix="."> <list_item> <paragraph> iii <list_item> <paragraph> iv <system_message level="1" line="8" source="functional/input/data/standard.txt" type="INFO"> <paragraph> Enumerated list start value not ordinal-1: "iii" (ordinal 3) <section ids="definition-lists" names="definition\ lists"> <title auto="1" refid="id43"> <generated classes="sectnum"> 2.4    Definition Lists <definition_list> <definition_list_item> <term> Term <definition> <paragraph> Definition <definition_list_item> <term> Term <classifier> classifier <definition> <paragraph> Definition paragraph 1. <paragraph> Definition paragraph 2. <definition_list_item> <term> Term <definition> <paragraph> Definition <definition_list_item> <term> Term <classifier> classifier one <classifier> classifier two <definition> <paragraph> Definition <section ids="field-lists" names="field\ lists"> <title auto="1" refid="id44"> <generated classes="sectnum"> 2.5    Field Lists <field_list> <field> <field_name> what <field_body> <paragraph> Field lists map field names to field bodies, like database records. They are often part of an extension syntax. They are an unambiguous variant of RFC 2822 fields. <field> <field_name> how arg1 arg2 <field_body> <paragraph> The field marker is a colon, the field name, and a colon. <paragraph> The field body may contain one or more body elements, indented relative to the field marker. <field> <field_name> credits <field_body> <paragraph classes="credits"> This paragraph has the <title_reference> credits class set. (This is actually not about credits but just for ensuring that the class attribute doesn't get stripped away.) <section ids="option-lists" names="option\ lists"> <title auto="1" refid="id45"> <generated classes="sectnum"> 2.6    Option Lists <paragraph> For listing command-line options: <option_list> <option_list_item> <option_group> <option> <option_string> -a <description> <paragraph> command-line option "a" <option_list_item> <option_group> <option> <option_string> -b <option_argument delimiter=" "> file <description> <paragraph> options can have arguments and long descriptions <option_list_item> <option_group> <option> <option_string> --long <description> <paragraph> options can be long also <option_list_item> <option_group> <option> <option_string> --input <option_argument delimiter="="> file <description> <paragraph> long options can also have arguments <option_list_item> <option_group> <option> <option_string> --very-long-option <description> <paragraph> The description can also start on the next line. <paragraph> The description may contain multiple body elements, regardless of where it starts. <option_list_item> <option_group> <option> <option_string> -x <option> <option_string> -y <option> <option_string> -z <description> <paragraph> Multiple options are an "option group". <option_list_item> <option_group> <option> <option_string> -v <option> <option_string> --verbose <description> <paragraph> Commonly-seen: short & long options. <option_list_item> <option_group> <option> <option_string> -1 <option_argument delimiter=" "> file <option> <option_string> --one <option_argument delimiter="="> file <option> <option_string> --two <option_argument delimiter=" "> file <description> <paragraph> Multiple options with arguments. <option_list_item> <option_group> <option> <option_string> /V <description> <paragraph> DOS/VMS-style options too <paragraph> There must be at least two spaces between the option and the description. <section ids="literal-blocks" names="literal\ blocks"> <title auto="1" refid="id46"> <generated classes="sectnum"> 2.7    Literal Blocks <paragraph> Literal blocks are indicated with a double-colon ("::") at the end of the preceding paragraph (over there <literal> --> ). They can be indented: <literal_block xml:space="preserve"> if literal_block: text = 'is left as-is' spaces_and_linebreaks = 'are preserved' markup_processing = None <paragraph> Or they can be quoted without indentation: <literal_block xml:space="preserve"> >> Great idea! > > Why didn't I think of that? <section ids="line-blocks" names="line\ blocks"> <title auto="1" refid="id47"> <generated classes="sectnum"> 2.8    Line Blocks <paragraph> This section tests line blocks. Line blocks are body elements which consist of lines and other line blocks. Nested line blocks cause indentation. <line_block> <line> This is a line block. It ends with a blank line. <line_block> <line> New lines begin with a vertical bar ("|"). <line> Line breaks and initial indent are significant, and preserved. <line_block> <line> Continuation lines are also possible. A long line that is intended to wrap should begin with a space in place of the vertical bar. <line> The left edge of a continuation line need not be aligned with the left edge of the text above it. <line_block> <line> This is a second line block. <line> <line> Blank lines are permitted internally, but they must begin with a "|". <paragraph> Another line block, surrounded by paragraphs: <line_block> <line> And it's no good waiting by the window <line> It's no good waiting for the sun <line> Please believe me, the things you dream of <line> They don't fall in the lap of no-one <paragraph> Take it away, Eric the Orchestra Leader! <block_quote> <line_block> <line> A one, two, a one two three four <line> <line> Half a bee, philosophically, <line_block> <line> must, <emphasis> ipso facto , half not be. <line> But half the bee has got to be, <line_block> <line> <emphasis> vis a vis its entity. D'you see? <line> <line> But can a bee be said to be <line_block> <line> or not to be an entire bee, <line_block> <line> when half the bee is not a bee, <line_block> <line> due to some ancient injury? <line> <line> Singing... <paragraph> A line block, like the following poem by Christian Morgenstern, can also be centre-aligned: <line_block classes="language-de align-center"> <line> <strong> Die Trichter <line> <line> Zwei Trichter wandeln durch die Nacht. <line> Durch ihres Rumpfs verengten Schacht <line> fließt weißes Mondlicht <line> still und heiter <line> auf   ihren <line> Waldweg <line> u. s. <line> w. <line> <section ids="block-quotes" names="block\ quotes"> <title auto="1" refid="id48"> <generated classes="sectnum"> 2.9    Block Quotes <paragraph> Block quotes consist of indented body elements: <block_quote> <paragraph> My theory by A. Elk. Brackets Miss, brackets. This theory goes as follows and begins now. All brontosauruses are thin at one end, much much thicker in the middle and then thin again at the far end. That is my theory, it is mine, and belongs to me and I own it, and what it is too. <attribution> Anne Elk (Miss) <paragraph> The language of a quote (like any other object) can be specified by a class attribute: <comment xml:space="preserve"> <block_quote classes="language-fr"> <paragraph> ReStructuredText est un langage de balisage léger utilisé notamment dans la documentation du langage Python. <section ids="doctest-blocks" names="doctest\ blocks"> <title auto="1" refid="id49"> <generated classes="sectnum"> 2.10    Doctest Blocks <doctest_block xml:space="preserve"> >>> print 'Python-specific usage examples; begun with ">>>"' Python-specific usage examples; begun with ">>>" >>> print '(cut and pasted from interactive Python sessions)' (cut and pasted from interactive Python sessions) <section ids="footnotes" names="footnotes"> <title auto="1" refid="id50"> <generated classes="sectnum"> 2.11    Footnotes <footnote backrefs="id1 id9 id22" ids="id8" names="1"> <label> 1 <paragraph> A footnote contains body elements, consistently indented by at least 3 spaces. <paragraph> This is the footnote's second paragraph. <footnote auto="1" backrefs="id3 id10" ids="label" names="label"> <label> 2 <paragraph> Footnotes may be numbered, either manually (as in <footnote_reference ids="id9" refid="id8"> 1 ) or automatically using a "#"-prefixed label. This footnote has a label so it can be referred to from multiple places, both as a footnote reference ( <footnote_reference auto="1" ids="id10" refid="label"> 2 ) and as a <reference anonymous="1" name="hyperlink reference" refid="label"> hyperlink reference . <target anonymous="1" ids="id11" refid="label"> <footnote auto="1" backrefs="id2" ids="id12" names="3"> <label> 3 <paragraph> This footnote is numbered automatically and anonymously using a label of "#" only. <paragraph> This is the second paragraph. <paragraph> And this is the third paragraph. <footnote auto="*" backrefs="id4" ids="id13"> <label> * <paragraph> Footnotes may also use symbols, specified with a "*" label. Here's a reference to the next footnote: <footnote_reference auto="*" ids="id14" refid="id15"> † . <footnote auto="*" backrefs="id14" ids="id15"> <label> † <paragraph> This footnote shows the next symbol in the sequence. <footnote ids="id16" names="4"> <label> 4 <paragraph> Here's an unreferenced footnote, with a reference to a nonexistent footnote: <problematic ids="id84 id17" refid="id83"> [5]_ . <section ids="citations" names="citations"> <title auto="1" refid="id51"> <generated classes="sectnum"> 2.12    Citations <citation backrefs="id5 id18" ids="cit2002" names="cit2002"> <label> CIT2002 <paragraph> Citations are text-labeled footnotes. They may be rendered separately and differently from footnotes. <paragraph> Here's a reference to the above, <citation_reference ids="id18" refid="cit2002"> CIT2002 , and a <problematic ids="id86 id19" refid="id85"> [nonexistent]_ citation. <target refid="another-target"> <section ids="targets another-target" names="targets another\ target"> <title auto="1" refid="id52"> <generated classes="sectnum"> 2.13    Targets <target refid="example"> <paragraph ids="example" names="example"> This paragraph is pointed to by the explicit "example" target. A reference can be found under <reference name="Inline Markup" refid="inline-markup"> Inline Markup , above. <reference name="Inline hyperlink targets" refid="inline-hyperlink-targets"> Inline hyperlink targets are also possible. <paragraph> Section headers are implicit targets, referred to by name. See <reference name="Targets" refid="targets"> Targets , which is a subsection of <reference name="Body Elements" refid="body-elements"> Body Elements . <paragraph> Explicit external targets are interpolated into references such as " <reference name="Python" refuri="http://www.python.org/"> Python <footnote_reference auto="1" ids="id27" refid="id25"> 5 ". <target ids="python" names="python" refuri="http://www.python.org/"> <paragraph> Targets may be indirect and anonymous. Thus <reference anonymous="1" name="this phrase" refid="targets"> this phrase may also refer to the <reference name="Targets" refid="targets"> Targets section. <target anonymous="1" ids="id20" refid="targets"> <paragraph> Here's a <problematic ids="id88" refid="id87"> `hyperlink reference without a target`_ , which generates an error. <section dupnames="duplicate\ target\ names" ids="duplicate-target-names"> <title auto="1" refid="id53"> <generated classes="sectnum"> 2.13.1    Duplicate Target Names <paragraph> Duplicate names in section headers or other implicit targets will generate "info" (level-1) system messages. Duplicate names in explicit targets will generate "warning" (level-2) system messages. <section dupnames="duplicate\ target\ names" ids="id21"> <title auto="1" refid="id54"> <generated classes="sectnum"> 2.13.2    Duplicate Target Names <system_message backrefs="id21" level="1" line="438" source="functional/input/data/standard.txt" type="INFO"> <paragraph> Duplicate implicit target name: "duplicate target names". <paragraph> Since there are two "Duplicate Target Names" section headers, we cannot uniquely refer to either of them by name. If we try to (like this: <problematic ids="id90" refid="id89"> `Duplicate Target Names`_ ), an error is generated. <section ids="directives" names="directives"> <title auto="1" refid="id55"> <generated classes="sectnum"> 2.14    Directives <topic classes="contents local" ids="contents" names="contents"> <bullet_list classes="auto-toc"> <list_item> <paragraph> <reference ids="id74" refid="document-parts"> <generated classes="sectnum"> 2.14.1    Document Parts <list_item> <paragraph> <reference ids="id75" refid="images-and-figures"> <generated classes="sectnum"> 2.14.2    Images and Figures <list_item> <paragraph> <reference ids="id76" refid="admonitions"> <generated classes="sectnum"> 2.14.3    Admonitions <list_item> <paragraph> <reference ids="id77" refid="topics-sidebars-and-rubrics"> <generated classes="sectnum"> 2.14.4    Topics, Sidebars, and Rubrics <list_item> <paragraph> <reference ids="id78" refid="target-footnotes"> <generated classes="sectnum"> 2.14.5    Target Footnotes <list_item> <paragraph> <reference ids="id79" refid="replacement-text"> <generated classes="sectnum"> 2.14.6    Replacement Text <list_item> <paragraph> <reference ids="id80" refid="compound-paragraph"> <generated classes="sectnum"> 2.14.7    Compound Paragraph <list_item> <paragraph> <reference ids="id81" refid="parsed-literal-blocks"> <generated classes="sectnum"> 2.14.8    Parsed Literal Blocks <list_item> <paragraph> <reference ids="id82" refid="code"> <generated classes="sectnum"> 2.14.9    Code <paragraph> These are just a sample of the many reStructuredText Directives. For others, please see <reference refuri="http://docutils.sourceforge.net/docs/ref/rst/directives.html"> http://docutils.sourceforge.net/docs/ref/rst/directives.html . <section ids="document-parts" names="document\ parts"> <title auto="1" refid="id74"> <generated classes="sectnum"> 2.14.1    Document Parts <paragraph> An example of the "contents" directive can be seen above this section (a local, untitled table of <reference name="contents" refid="contents"> contents ) and at the beginning of the document (a document-wide <reference name="table of contents" refid="table-of-contents"> table of contents ). <section ids="images-and-figures" names="images\ and\ figures"> <title auto="1" refid="id75"> <generated classes="sectnum"> 2.14.2    Images and Figures <paragraph> An image directive (also clickable -- a hyperlink reference): <reference name="directives" refid="directives"> <image classes="class1 class2" uri="../../../docs/user/rst/images/title.png"> <paragraph> Image with multiple IDs: <target refid="image-target-1"> <target refid="image-target-2"> <target refid="image-target-3"> <image ids="image-target-3 image-target-2 image-target-1" names="image\ target\ 3 image\ target\ 2 image\ target\ 1" uri="../../../docs/user/rst/images/title.png"> <paragraph> A centered image: <image align="center" uri="../../../docs/user/rst/images/biohazard.png"> <paragraph> A left-aligned image: <image align="left" uri="../../../docs/user/rst/images/biohazard.png"> <paragraph> This paragraph might flow around the image. The specific behavior depends upon the style sheet and the browser or rendering software used. <paragraph> A right-aligned image: <image align="right" uri="../../../docs/user/rst/images/biohazard.png"> <paragraph> This paragraph might flow around the image. The specific behavior depends upon the style sheet and the browser or rendering software used. <paragraph> For inline images see <reference name="Substitution Definitions" refid="substitution-definitions"> Substitution Definitions . <paragraph> Image size: <paragraph> An image 2 em wide: <image uri="../../../docs/user/rst/images/biohazard.png" width="2em"> <paragraph> An image 2 em wide and 15 pixel high: <image height="15px" uri="../../../docs/user/rst/images/biohazard.png" width="2em"> <paragraph> An image occupying 50% of the line width: <image uri="../../../docs/user/rst/images/title.png" width="50%"> <paragraph> An image 2 cm high: <image height="2cm" uri="../../../docs/user/rst/images/biohazard.png"> <paragraph> A <emphasis> figure is an image with a caption and/or a legend. With page-based output media, figures might float to a different position if this helps the page layout. <figure classes="figclass1 figclass2"> <image alt="reStructuredText, the markup syntax" classes="class1 class2" uri="../../../docs/user/rst/images/title.png" width="258"> <caption> Plaintext markup syntax and parser system. <legend> <table> <tgroup cols="2"> <colspec colwidth="12"> <colspec colwidth="47"> <tbody> <row> <entry> <paragraph> re <entry> <paragraph> Revised, revisited, based on 're' module. <row> <entry> <paragraph> Structured <entry> <paragraph> Structure-enhanced text, structuredtext. <row> <entry> <paragraph> Text <entry> <paragraph> Well it is, isn't it? <paragraph> This paragraph is also part of the legend. <paragraph> A left-aligned figure: <figure align="left" classes="figclass1 figclass2" width="70%"> <image alt="reStructuredText, the markup syntax" classes="class1 class2" uri="../../../docs/user/rst/images/biohazard.png" width="40px"> <caption> This is the caption. <legend> <paragraph> This is the legend. <paragraph> The legend may consist of several paragraphs. <paragraph> This paragraph might flow around the figure. <paragraph> The specific behavior depends upon the style sheet and the browser or rendering software used. <paragraph> A centered figure: <figure align="center"> <image uri="../../../docs/user/rst/images/biohazard.png" width="40px"> <caption> This is the caption. <legend> <paragraph> This is the legend. <paragraph> The legend may consist of several paragraphs. <paragraph> This paragraph might flow around the figure. <paragraph> The specific behavior depends upon the style sheet and the browser or rendering software used. <paragraph> A right-aligned figure: <figure align="right"> <image uri="../../../docs/user/rst/images/biohazard.png" width="40px"> <caption> This is the caption. <legend> <paragraph> This is the legend. <paragraph> The legend may consist of several paragraphs. <paragraph> This paragraph might flow around the figure. The specific behavior depends upon the style sheet and the browser or rendering software used. <section ids="admonitions" names="admonitions"> <title auto="1" refid="id76"> <generated classes="sectnum"> 2.14.3    Admonitions <attention> <paragraph> Directives at large. <caution> <paragraph> Don't take any wooden nickels. <danger> <paragraph> Mad scientist at work! <error> <paragraph> Does not compute. <hint> <paragraph> It's bigger than a bread box. <important> <bullet_list bullet="-"> <list_item> <paragraph> Wash behind your ears. <list_item> <paragraph> Clean up your room. <list_item> <paragraph> Call your mother. <list_item> <paragraph> Back up your data. <note> <paragraph> This is a note. <tip> <paragraph> 15% if the service is good. <warning> <paragraph> Strong prose may provoke extreme mental exertion. Reader discretion is strongly advised. <admonition classes="admonition-and-by-the-way"> <title> And, by the way... <paragraph> You can make up your own admonition too. <target ids="docutils" names="docutils" refuri="http://docutils.sourceforge.net/"> <section ids="topics-sidebars-and-rubrics" names="topics,\ sidebars,\ and\ rubrics"> <title auto="1" refid="id77"> <generated classes="sectnum"> 2.14.4    Topics, Sidebars, and Rubrics <paragraph> <emphasis> Sidebars are like miniature, parallel documents. <sidebar> <title> Sidebar Title <subtitle> Optional Subtitle <paragraph> This is a sidebar. It is for text outside the flow of the main text. <rubric> This is a rubric inside a sidebar <paragraph> Sidebars often appear beside the main text with a border and a different background or font color. <paragraph> A <emphasis> topic is like a block quote with a title, or a self-contained section with no subsections. <topic> <title> Topic Title <paragraph> This is a topic. <paragraph> A <emphasis> rubric is like an informal heading that doesn't correspond to the document's structure. It is typically highlighted in red (hence the name). <rubric> This is a rubric <paragraph> Topics and rubrics can be used at places where a <reference name="section title" refid="section-title"> section title is not allowed (e.g. inside a directive). <section ids="target-footnotes" names="target\ footnotes"> <title auto="1" refid="id78"> <generated classes="sectnum"> 2.14.5    Target Footnotes <footnote auto="1" backrefs="id26 id27 id28 id31" ids="id25" names="TARGET_NOTE:\ id25"> <label> 5 <paragraph> <reference refuri="http://www.python.org/"> http://www.python.org/ <footnote auto="1" backrefs="id30" ids="id29" names="TARGET_NOTE:\ id29"> <label> 6 <paragraph> <reference refuri="http://pygments.org/"> http://pygments.org/ <footnote auto="1" backrefs="id33" ids="id32" names="TARGET_NOTE:\ id32"> <label> 7 <paragraph> <reference refuri="http://docutils.sourceforge.net/"> http://docutils.sourceforge.net/ <section ids="replacement-text" names="replacement\ text"> <title auto="1" refid="id79"> <generated classes="sectnum"> 2.14.6    Replacement Text <paragraph> I recommend you try <reference refuri="http://www.python.org/"> Python, <emphasis> the best language around <footnote_reference auto="1" ids="id28" refid="id25"> 5 . <substitution_definition names="Python"> Python, <emphasis> the best language around <section ids="compound-paragraph" names="compound\ paragraph"> <title auto="1" refid="id80"> <generated classes="sectnum"> 2.14.7    Compound Paragraph <compound classes="some-class"> <paragraph> Compound 1, paragraph 1. <paragraph> Compound 1, paragraph 2. <bullet_list bullet="*"> <list_item> <paragraph> Compound 1, list item one. <list_item> <paragraph> Compound 1, list item two. <paragraph> Another compound statement: <compound> <paragraph> Compound 2, a literal block: <literal_block xml:space="preserve"> Compound 2, literal. <paragraph> Compound 2, this is a test. <compound> <paragraph> Compound 3, only consisting of one paragraph. <compound> <literal_block xml:space="preserve"> Compound 4. This one starts with a literal block. <paragraph> Compound 4, a paragraph. <paragraph> Now something <emphasis> really perverted -- a nested compound block. This is just to test that it works at all; the results don't have to be meaningful. <compound> <paragraph> Compound 5, block 1 (a paragraph). <compound> <paragraph> Compound 6, block 2 in compound 5. <paragraph> Compound 6, another paragraph. <paragraph> Compound 5, block 3 (a paragraph). <compound> <paragraph> Compound 7, with a table inside: <table> <tgroup cols="3"> <colspec colwidth="20"> <colspec colwidth="20"> <colspec colwidth="20"> <tbody> <row> <entry> <paragraph> Left cell, first paragraph. <paragraph> Left cell, second paragraph. <entry> <paragraph> Middle cell, consisting of exactly one paragraph. <entry> <paragraph> Right cell. <paragraph> Paragraph 2. <paragraph> Paragraph 3. <paragraph> Compound 7, a paragraph after the table. <paragraph> Compound 7, another paragraph. <section ids="parsed-literal-blocks" names="parsed\ literal\ blocks"> <title auto="1" refid="id81"> <generated classes="sectnum"> 2.14.8    Parsed Literal Blocks <literal_block xml:space="preserve"> This is a parsed literal block. This line is indented. The next line is blank. Inline markup is supported, e.g. <emphasis> emphasis , <strong> strong , <literal> literal text , footnotes <footnote_reference ids="id22" refid="id8"> 1 , <target ids="hyperlink-targets" names="hyperlink\ targets"> hyperlink targets , and <reference name="references" refuri="http://www.python.org/"> references <target ids="references" names="references" refuri="http://www.python.org/"> . <section ids="code" names="code"> <title auto="1" refid="id82"> <generated classes="sectnum"> 2.14.9    Code <paragraph> Blocks of source code can be set with the <title_reference> code directive. If the code language is specified, the content is parsed and tagged by the <reference name="Pygments" refuri="http://pygments.org/"> Pygments <footnote_reference auto="1" ids="id30" refid="id29"> 6 syntax highlighter and can be formatted with a style sheet. (Code parsing is turned off using the <literal> syntax-highlight config setting in the test conversions in order to get identical results with/without installed Pygments highlighter.) <literal_block classes="code python" xml:space="preserve"> print 'This is Python code.' <paragraph> The <literal> :number-lines: option (with optional start value) generates line numbers: <literal_block classes="code python" xml:space="preserve"> <inline classes="ln"> 8 # print integers from 0 to 9: <inline classes="ln"> 9 for i in range(10): <inline classes="ln"> 10 print i <paragraph> For inline code snippets, there is the <title_reference> code role, which can be used directly (the code will not be parsed/tagged, as the language is not known) or as base for special code roles, e.g. the LaTeX code in the next paragraph. <paragraph> Docutils uses LaTeX syntax for math directives and roles: <literal classes="code tex"> \alpha = f(x) prints <math> \alpha = f(x) . <paragraph> The <literal> :code: option of the <title_reference> include directive sets the included content as a code block, here the rst file <literal> header_footer.txt with line numbers: <literal_block classes="code rst" source="functional/input/data/header_footer.txt" xml:space="preserve"> <inline classes="ln"> 1 .. header:: Document header <inline classes="ln"> 2 .. footer:: Document footer <target ids="pygments" names="pygments" refuri="http://pygments.org/"> <section ids="substitution-definitions" names="substitution\ definitions"> <title auto="1" refid="id65"> <generated classes="sectnum"> 2.15    Substitution Definitions <paragraph> An inline image ( <image alt="EXAMPLE" uri="../../../docs/user/rst/images/biohazard.png"> ) example: <substitution_definition names="EXAMPLE"> <image alt="EXAMPLE" uri="../../../docs/user/rst/images/biohazard.png"> <paragraph> (Substitution definitions are not visible in the HTML source.) <section ids="comments" names="comments"> <title auto="1" refid="id66"> <generated classes="sectnum"> 2.16    Comments <paragraph> Here's one: <comment xml:space="preserve"> Comments begin with two dots and a space. Anything may follow, except for the syntax of footnotes, hyperlink targets, directives, or substitution definitions. Double-dashes -- "--" -- must be escaped somehow in HTML output. Comments may contain non-ASCII characters: ä ö ü æ ø å <paragraph> (View the HTML source to see the comment.) <section ids="raw-text" names="raw\ text"> <title auto="1" refid="id67"> <generated classes="sectnum"> 2.17    Raw text <paragraph> This does not necessarily look nice, because there may be missing white space. <paragraph> It's just there to freeze the behavior. <raw format="html latex" xml:space="preserve"> A test. <raw format="html latex" xml:space="preserve"> Second test. <raw classes="myclass" format="html latex" xml:space="preserve"> Another test with myclass set. <paragraph> This is the <raw classes="myrawroleclass" format="html latex" xml:space="preserve"> fourth test with myrawroleclass set. <raw format="html" xml:space="preserve"> Fifth test in HTML.<br />Line two. <raw format="latex" xml:space="preserve"> Fifth test in LaTeX.\\Line two. <section ids="container" names="container"> <title auto="1" refid="id68"> <generated classes="sectnum"> 2.18    Container <container classes="custom"> <paragraph> paragraph 1 <paragraph> paragraph 2 <section ids="colspanning-tables" names="colspanning\ tables"> <title auto="1" refid="id69"> <generated classes="sectnum"> 2.19    Colspanning tables <paragraph> This table has a cell spanning two columns: <table> <tgroup cols="3"> <colspec colwidth="5"> <colspec colwidth="5"> <colspec colwidth="6"> <thead> <row> <entry morecols="1"> <paragraph> Inputs <entry> <paragraph> Output <row> <entry> <paragraph> A <entry> <paragraph> B <entry> <paragraph> A or B <tbody> <row> <entry> <paragraph> False <entry> <paragraph> False <entry> <paragraph> False <row> <entry> <paragraph> True <entry> <paragraph> False <entry> <paragraph> True <row> <entry> <paragraph> False <entry> <paragraph> True <entry> <paragraph> True <row> <entry> <paragraph> True <entry> <paragraph> True <entry> <paragraph> True <section ids="rowspanning-tables" names="rowspanning\ tables"> <title auto="1" refid="id70"> <generated classes="sectnum"> 2.20    Rowspanning tables <paragraph> Here's a table with cells spanning several rows: <table> <tgroup cols="3"> <colspec colwidth="24"> <colspec colwidth="12"> <colspec colwidth="18"> <thead> <row> <entry> <paragraph> Header row, column 1 (header rows optional) <entry> <paragraph> Header 2 <entry> <paragraph> Header 3 <tbody> <row> <entry> <paragraph> body row 1, column 1 <entry> <paragraph> column 2 <entry> <paragraph> column 3 <row> <entry> <paragraph> body row 2 <entry morerows="1"> <paragraph> Cells may span rows. <entry morerows="1"> <paragraph> Another rowspanning cell. <row> <entry> <paragraph> body row 3 <section ids="complex-tables" names="complex\ tables"> <title auto="1" refid="id71"> <generated classes="sectnum"> 2.21    Complex tables <paragraph> Here's a complex table, which should test all features. <table> <tgroup cols="4"> <colspec colwidth="24"> <colspec colwidth="12"> <colspec colwidth="10"> <colspec colwidth="10"> <thead> <row> <entry> <paragraph> Header row, column 1 (header rows optional) <entry> <paragraph> Header 2 <entry> <paragraph> Header 3 <entry> <paragraph> Header 4 <tbody> <row> <entry> <paragraph> body row 1, column 1 <entry> <paragraph> column 2 <entry> <paragraph> column 3 <entry> <paragraph> column 4 <row> <entry> <paragraph> body row 2 <entry morecols="2"> <paragraph> Cells may span columns. <row> <entry> <paragraph> body row 3 <entry morerows="1"> <paragraph> Cells may span rows. <paragraph> Paragraph. <entry morecols="1" morerows="1"> <bullet_list bullet="-"> <list_item> <paragraph> Table cells <list_item> <paragraph> contain <list_item> <paragraph> body elements. <row> <entry> <paragraph> body row 4 <row> <entry> <paragraph> body row 5 <entry morecols="1"> <paragraph> Cells may also be empty: <literal> --> <entry> <section ids="list-tables" names="list\ tables"> <title auto="1" refid="id72"> <generated classes="sectnum"> 2.22    List Tables <paragraph> Here's a list table exercising all features: <table classes="test"> <title> list table with integral header <tgroup cols="3"> <colspec colwidth="10" stub="1"> <colspec colwidth="20"> <colspec colwidth="30"> <thead> <row> <entry> <paragraph> Treat <entry> <paragraph> Quantity <entry> <paragraph> Description <tbody> <row> <entry> <paragraph> Albatross <entry> <paragraph> 2.99 <entry> <paragraph> On a stick! <row> <entry> <paragraph> Crunchy Frog <entry> <paragraph> 1.49 <entry> <paragraph> If we took the bones out, it wouldn't be crunchy, now would it? <row> <entry> <paragraph> Gannet Ripple <entry> <paragraph> 1.99 <entry> <paragraph> On a stick! <section ids="error-handling" names="error\ handling"> <title auto="1" refid="id73"> <generated classes="sectnum"> 3    Error Handling <paragraph> Any errors caught during processing will generate system messages. <paragraph> There should be five messages in the following, auto-generated section, "Docutils System Messages": <comment xml:space="preserve"> section should be added by Docutils automatically <section classes="system-messages"> <title> Docutils System Messages <system_message backrefs="id24" ids="id23" level="3" line="104" source="functional/input/data/standard.txt" type="ERROR"> <paragraph> Undefined substitution referenced: "problematic". <system_message backrefs="id84" ids="id83" level="3" line="391" source="functional/input/data/standard.txt" type="ERROR"> <paragraph> Unknown target name: "5". <system_message backrefs="id86" ids="id85" level="3" line="400" source="functional/input/data/standard.txt" type="ERROR"> <paragraph> Unknown target name: "nonexistent". <system_message backrefs="id88" ids="id87" level="3" line="427" source="functional/input/data/standard.txt" type="ERROR"> <paragraph> Unknown target name: "hyperlink reference without a target". <system_message backrefs="id90" ids="id89" level="3" line="440" source="functional/input/data/standard.txt" type="ERROR"> <paragraph> Duplicate target name, cannot be used as a unique reference: "duplicate target names". <system_message level="1" line="163" source="functional/input/data/standard.txt" type="INFO"> <paragraph> Hyperlink target "target" is not referenced. <system_message level="1" line="405" source="functional/input/data/standard.txt" type="INFO"> <paragraph> Hyperlink target "another-target" is not referenced. <system_message level="1" line="473" source="functional/input/data/standard.txt" type="INFO"> <paragraph> Hyperlink target "image-target-1" is not referenced. <system_message level="1" line="474" source="functional/input/data/standard.txt" type="INFO"> <paragraph> Hyperlink target "image-target-2" is not referenced. <system_message level="1" line="475" source="functional/input/data/standard.txt" type="INFO"> <paragraph> Hyperlink target "image-target-3" is not referenced. <system_message level="1" line="632" source="functional/input/data/standard.txt" type="INFO"> <paragraph> Hyperlink target "docutils" is not referenced. <system_message level="1" line="753" source="functional/input/data/standard.txt" type="INFO"> <paragraph> Hyperlink target "hyperlink targets" is not referenced. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/expected/odt_tables1.odt����������������������������������������������0000664�0001750�0001750�00000025762�12014257243�025073� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������PK�����tA^2 '���'������mimetypeapplication/vnd.oasis.opendocument.textPK����tA_€Z ���� ���content.xml][o6}ϯ /[`l拌L]؇ Zmb$8Ǘd[8(J5L,}G~<:[Z�-Bba@qE)8إɂ@"1 ,%FBYu|l..F$]`"$Zѱ=XhpDz1{aYX" ˷{Wl Wh /#4.ۑ-!ۼ6X_I/x`kⵒ]Di R4լvd=!lE,P8{] `oSPzߦr|6IR6bbV4Hʢ\9mgjey2IkP:}[l =C8;} pz1gY_~lP O!N( ϻۼ`|<;\� CD3p_8)wTʟ }c=~h~ɗ/2hhe)aDp~I8. cmdP8ȖDzN8䍦L&FxIVl r0@QT2ѧ ϲZ4Di!+˲8X@ICK"2q)^oJfv>l Ðmdʠh'qivDr<-xY-exp9b<*<<y+k6f3k62+̣R<<^1<*91y&f3l<^1<*95yf3l<F=nyfWQ)Ι"#;4 OyZZ3eVFOyT5̯̣Rsgn6fy+o6f3o62mzl=Jo7&hESŐ2^[Fg@ű.bOSͶ,p(>ݒ5yLw]% /ěn[ӷ@W>ݿS0vE-( 'vY!{3qJВ<Γp8ܣ/WS (؀w;̆(U̩wa^畷.L8ɏ::^t"F?ӧ'g!=v-e)JΕ"Olw?KC�nG) [Q0TMKǹ a:~QON OQ>-f9XK<Xk<تo~뮕#ݓ& k61|MՒO \9-Ս+q Jt=\{O"DP3"_y18buz ='Mu/E7r:Л\G>$Myy}(J+ͩk6fa6f1l:2tUv!Ue6w5A7wNV ('yYG%ȧiޤu&45uk RBvwQpܕ`ݺ]]C/ǭN@kLk;[]=2XTcjg Ә"p^뼚kEz{J:'e؅5.gTq^nWm{:ܶm{:ܶgUb.Um3 um+5O+rin?0I2"vlh:nÈP?Y=K|nr҂<|ANN 谓vrNN ~ItXKU= Cod;`ͳʩ\I- xqvR3NV@yTJȾO2m~dM22Ӻ$S$S$S$SCI&QM T]b5jDC7BL!2Xk4p7+̪]W՘.jU+ZB{tż~>]ci4gih$ Sd)7=f .� KBDq0By̙D@�=xm͊DsY s ` N$"n79Eaw4CJ:=g:JU^'ЉaCà à PàVFz|De fge/{Ji޼R))6O `0E*\dI` E!{tKb)h9QyAC.a=(~>SSi- \0ňP:*S;t:\ҙP:vҔNu*e]"tJHS=?(7ıxcX~+nD",v4(ALRtwvg9Vz߼mZ &vVӖPy#IB Z\X`-S'߄fd˶qA Hy0Y~M]H˞nI-tϱ|1)WKkp_W:C:߮p/MUܡpS EMnS$.FMvgˬ9aVzum5/|%)!|/PO'$%?()vQz6k pߵ< `]uxH(]>Tm'6UFkR,o#eB.ߛRZsR+jq~yqJLUHxPPK����tA6X ����S�����META-INF/manifest.xmlM -= ѱ% MZ4M[L-ޱL,NumxvDYj5'T$IQBB?{@RzUmF:+mٹ:j.60XSAsWp Z,.> ӜoʲN:Hp�2R'muPK����tAm=�������meta.xmlj o<Qn,z4`DRA i~YmCyA-PiE[ i o6JO!4u:BR 0db>i{5x ysR;*= ]DHD3}\뺬FE4atʠ(\ǃu J{|ȭ<eͭ KǢ2*(S Ҟǘc)5XI◔Gg?MG<.wZ^~lFERq<#*~de.8baUZBPA{sJnƬD~ PK����tA9^3w��_� ���styles.xml]i6v_q\J"+\xcWَ+ݓS Its >=ͯ. ԣDv{�\\, bAf[#1/�9;& lﰾs=D9v<{8:ܩ8άO{|>O󉋎Sm6OS`!IVk.l,d 181{)ͷ[؊l9\]Kog%za"ub<"D9525۽BBHߌ>Ku�:T [> Z>'|_o.+Vc¼?a>š(mZt䴬 A9B"Sۮ3Nx&O/ M{\ӂR hFX+@&դX_'jJ"95"hTd!U&gk5 ^ li>37׀X8ț}D;:t6 Q<Dz&7#}ML*t2J('$e<0rr Y!t GoU4XM9[EHg:,y�SPѦc@:4щG0.d{Ly8Rvi&B Ӏ. X Dgdb*/c )xțGFPi6OHE!C% #?St[(y8J"-pA'b 9|tu-1 ˨QۖIq`޻WE؎%HRz/ptJ9d"#zjU1LBfc6Yleۛð8]tx0ԡ0_ƎKhl8K٠,$ L!b4}"f (iybFE%: 60Tk4/V((`K 3^fIX=GOvʓJu >~\c�dCIY?{=3 ]"QMm$9IwLk* 8ص2%$C1Ӽ@ؑ˚2ӿŌ9ҧ )5ؼS0Ď* 2'CS% Z) ?C`ēC+ Ĭ#YG:?IUL)SDb$ovXhGnxSG7.+$ռjzʳ^}5"vI)tN$\:2E \y jE+ӊVO+ZZ!vɪ 3dEE8U|:3ZXѽu=/uںVeZYʢlJL\oRe^SӊnZUwSɪL%z*YuJ d݈J,ӗY'Z�-HI:$Qk59riqG<&K6{J[GO%&[m^k1ݦroeU~BYndYiCU u.$ >яQ| G<H5F S~9SYƪ+h$<6>6zIIgӦ28G'͊y=kaLvx[>5LQoG<6;:o8dh@y4{{UIVL<߬Ǐ6MB5$7#mM ȏ`h>˹<tO5Q}Qq=Td,ѯ"28aZX~6 |glc:#ut=hǪzNu Un@/k뤋ǴpF$jn@;v"vr8`R7c$ HCc/G祊+!i#:g0, .Gd\K>|;_c|OhJ?qo5eu_| ؄ 7jP'SK&k}5}p?C`Q`h5UH('uIQơ& TO=9V9 !W)VU}ШivJuGh:^u7W$u FBqs(Ԋ ~ ]4FfOvdFW(+YNfL-ZG0!gJFE\k`(i]h`kdQ<zD,+8薀Wz~0dNv5:ƻRbkzN{Bdg6coR%woBH"ONJֈ[ &6܎wYB,u.sG`<NæwrcF.nڇkhKX|3�e1]cԭ u[4sh[D,.݊$U Tt+|:e8u+torS[æ7)Fbѭ\J1APG w b`c|ZijoњַPiԺ!7kPGʡ|ŏT9_whɊĬ:SzA7b*{3X-:Ѻղ{XժkX=U٠1(*Wq5 R.ZY=$){HdFWUZMYij4xdׄ] &~U5,.yYz%dӴۣY,!f<B6`}Mxͭz0*B%L}v54ҁqnE]pұCOBGQfM/D%!M3=47}!YN6)^,xD>2H̷ڶYjS|Y4}d>rYnw> uǼkG)vi,?2NH';=&Y{yDu=IG;IFfу3S}&}RY>2;pGuj'鳘lٶHgNljҧUw|h>+m0}Rپ>ۚ)n]\wYLZ-u&,[8.,n]^mv_L4VؼLɭ5ݎ۞ IV4}&m5%>>V^;e<"d%UĶٝ@ZKF]}(~ti _cpO6߱#~/ ëxt�`.V-`ni[I6KbyX>,6is^9ox)u(-ՒOt_*Tqܻ@j='WO+V Tbxq:*Z?'PI۶dضY,Z NțTr 'm1:1أ6 Jv*Cϐs)+# u:GڕN}<L4![qN<3LbFa-Ar?WpE?DSS凑=-R"4 =_bkIoDa&@^]E86{8{8℔6,V g 4a<܁{AhK�vty!z?:2=\1Exd-76Rm ‘aϛ7$nal /v$2q>]-3 ı>˴WZՀ]/W8-el\<h4mʺm-^wpt"w߇mbѧL H1@:O,R鯶O~*o"V~W+D>w}0\DE_bį-yp%ֻc$)[+bVw;3]pEy֩pT�QMM&$ݯexFEȟIƋgaײ3!ٞ`?Ncl2/P<ׇ#-R[r1}ZϾcrIEˀ{xvj;3 e=<{@8|Ue=<{$ހ.2૞^Yo)aD{xo|mˀoz x՞iEmm=){6g\=E\k tdzsG_)ІЛ\ WScG^_ְ=!uTs6 |ْ*4 &1S ֚- =oMuR/ZZmOe["ڧWIݢքnOoZZkOm["ڧYkbבZHPǮ_x"x�zj*ݬsKa72 Xmz\KcV>uo�A+sգ+sG�1DŽ~^=2=2?`Z_vhh2XslG �n\'`Wo!T1^w+\ DtEǫׇgT,']Syz&?w}xOy|>>>5ybh/up?gܗ@$O̯!|z>.@>@>^A�>A; W' R77})S_ ӯHˏҝ{E]~1Bjpp}=STtӴgN^)31E7:{zf_Ϝ}=QxsG0Nd 3IxL3<]lL3@Ϥd<grL39x&l3 =}gKv._rKv/9%d�_rK>//WrJ^+9x%J؛`b &`b &`b &`b &F&*w7lfT/3R̨gfF<23*陙Q)ǑJazffTϣ_\87Wͨ_fF8=33*铙Q)ĽJyefT33R>̨Gnfw7?2oF<23*陙Q)ǑJazffT/3R̨gfF<Uz3~ʼ̨gfF<}23*陙Q)ǑJqzffT'3Rhg Wt9�lΕxebs}|{y,Qt 8JöQEbW`t ny�JL&tti;�EES X<1U]zJN>I�s%ئu@ oH,iuD QD |l.Op".2QR#R'ՐRCq[\+l-ϋ`''b7R1" =EgDEkir�`w1Oh ᔊA!D ިzB9LH5]6B ^,=z`Pum^f32Q-v|ЋS2/ JUmm`4f댱XD'Fp6McWUsJ85p*Sa06ōbfZ3$!)fduӟ5)&Zt/#Uj ܊˱ۘ=g?.#1PZ5>�)YYaFo;z gY;;!N�C0vө kЧb?U'4NK&>ϓ%f3uJR(d5BĩܐmMjgL:f~->==6U e iż<v3Dkb [M+x 8""ԡl<u* <EDŔRu`Bsib:SS'9@N1(#ӓ[<u*?Y:{V'Q:뱀rtfVFV_ vbɀry#w?oЁdH2(vj?È #>tH>a @wŞ O_|ԲBĦȵG~(q4w"< ǩ8<' abi pt{7J 'ҒUH(C4Uw^_ITD ?Ak hӌ$%sYd \@{ʻ2+9FȨU"hy9B:钺DRQPK����tA5&FsR��#�� ���settings.xmlZ[SH~WPyWˬRTakIkO#t\~Ls%|GJs^ԫ 0rr=[W׻y�$i5CktK]^zudd \n\]OѲ's75&Wdv~jR]__Wӷ˥1l @vCvUK~͙wwTYjb�zTQ?@dTz[0{W=mE{|l|c1('Muݎظ:f/~�L7_vy}^Bg}9erze(IΨiˆ™G ā 8b1!!\W\|)"[%͵QYŷ<A/jW_uYpGߝ?_X6tk@h1U߈ѐ\)*SZ?liH" 9FI -1SÖj*㴔z�aKу=f 4Mk(#Ƴb*]/zD'L ܤbP-�LJg̴Q%KX21wX?L$5K`+LXM2ZG)4-T<~(:T?!3 ?Rvj" g:"PCirWoQl#! rD)"{fDɂRrK)5A an^;$X,5(+SbibXe8.G?1#HTJlhSn-hi�NA(]r]o,>-"t$F-L.2l&_5*yM&D8OhRUbHEg�ʻT?WEKV/ `hѝ D>^XcnL&L4WGl%_1Z[w}>t'QWydQűUJL.LiwnK*ݩ=We VY uLeǎVa<)Vv|`: _$%)#[sI}`lmlV.,fk>z@ZOsր�d))tc?t ߶@ԮwkQFDtzw{Fì%W]౯ߙЗ/Xc;g= b 騢 BXw:al >JM)SJ@X7<XdEKF-QjYـ$_sbڰXop9Wl@٫b(HDQ+-;!OGYLhU:%n׮r%_/ )P06CbSO>T~hg-wPK�����tA^2 '���'������������������mimetypePK����tA_€Z ���� �����������M���content.xmlPK����tA6X ����S������������� ��META-INF/manifest.xmlPK����tAm=��������������� ��meta.xmlPK����tA9^3w��_� ����������� ��styles.xmlPK����tA5&FsR��#�� �����������%��settings.xmlPK������Z��*������������������docutils-0.12/test/functional/expected/standalone_rst_latex.tex�������������������������������������0000664�0001750�0001750�00000160426�12304115037�027112� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������\documentclass[a4paper]{article} % generated by Docutils <http://docutils.sourceforge.net/> \usepackage{fixltx2e} % LaTeX patches, \textsubscript \usepackage{cmap} % fix search and cut-and-paste in Acrobat \usepackage{ifthen} \usepackage[T1]{fontenc} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage[british,french,ngerman,english]{babel} % Prevent side-effects if French hyphenation patterns are not loaded: \frenchbsetup{StandardLayout} \AtBeginDocument{\selectlanguage{english}\noextrasfrench} \usepackage{color} \usepackage{float} % float configuration \floatplacement{figure}{H} % place figures here definitely \usepackage{graphicx} \usepackage{multirow} \usepackage{pifont} \setcounter{secnumdepth}{0} \usepackage{longtable,ltcaption,array} \setlength{\extrarowheight}{2pt} \newlength{\DUtablewidth} % internal use in tables \usepackage{tabularx} \usepackage{textcomp} % text symbol macros %%% Custom LaTeX preamble % PDF Standard Fonts \usepackage{mathptmx} % Times \usepackage[scaled=.90]{helvet} \usepackage{courier} %%% User specified packages and stylesheets %%% Fallback definitions for Docutils-specific commands % providelength (provide a length variable and set default, if it is new) \providecommand*{\DUprovidelength}[2]{ \ifthenelse{\isundefined{#1}}{\newlength{#1}\setlength{#1}{#2}}{} } % abstract title \providecommand*{\DUtitleabstract}[1]{\centering\textbf{#1}} % admonition (specially marked topic) \providecommand{\DUadmonition}[2][class-arg]{% % try \DUadmonition#1{#2}: \ifcsname DUadmonition#1\endcsname% \csname DUadmonition#1\endcsname{#2}% \else \begin{center} \fbox{\parbox{0.9\textwidth}{#2}} \end{center} \fi } \makeatletter \@namedef{DUrolealign-center}{\centering} \makeatother % dedication topic \providecommand{\DUtopicdedication}[1]{\begin{center}#1\end{center}} % docinfo (width of docinfo table) \DUprovidelength{\DUdocinfowidth}{0.9\textwidth} % subtitle (in document title) \providecommand*{\DUdocumentsubtitle}[1]{{\large #1}} % error admonition title \providecommand*{\DUtitleerror}[1]{\DUtitle{\color{red}#1}} % fieldlist environment \ifthenelse{\isundefined{\DUfieldlist}}{ \newenvironment{DUfieldlist}% {\quote\description} {\enddescription\endquote} }{} % numeric or symbol footnotes with hyperlinks \providecommand*{\DUfootnotemark}[3]{% \raisebox{1em}{\hypertarget{#1}{}}% \hyperlink{#2}{\textsuperscript{#3}}% } \providecommand{\DUfootnotetext}[4]{% \begingroup% \renewcommand{\thefootnote}{% \protect\raisebox{1em}{\protect\hypertarget{#1}{}}% \protect\hyperlink{#2}{#3}}% \footnotetext{#4}% \endgroup% } % inline markup (custom roles) % \DUrole{#1}{#2} tries \DUrole#1{#2} \providecommand*{\DUrole}[2]{% \ifcsname DUrole#1\endcsname% \csname DUrole#1\endcsname{#2}% \else% backwards compatibility: try \docutilsrole#1{#2} \ifcsname docutilsrole#1\endcsname% \csname docutilsrole#1\endcsname{#2}% \else% #2% \fi% \fi% } % legend environment \ifthenelse{\isundefined{\DUlegend}}{ \newenvironment{DUlegend}{\small}{} }{} % lineblock environment \DUprovidelength{\DUlineblockindent}{2.5em} \ifthenelse{\isundefined{\DUlineblock}}{ \newenvironment{DUlineblock}[1]{% \list{}{\setlength{\partopsep}{\parskip} \addtolength{\partopsep}{\baselineskip} \setlength{\topsep}{0pt} \setlength{\itemsep}{0.15\baselineskip} \setlength{\parsep}{0pt} \setlength{\leftmargin}{#1}} \raggedright } {\endlist} }{} % optionlist environment \providecommand*{\DUoptionlistlabel}[1]{\bf #1 \hfill} \DUprovidelength{\DUoptionlistindent}{3cm} \ifthenelse{\isundefined{\DUoptionlist}}{ \newenvironment{DUoptionlist}{% \list{}{\setlength{\labelwidth}{\DUoptionlistindent} \setlength{\rightmargin}{1cm} \setlength{\leftmargin}{\rightmargin} \addtolength{\leftmargin}{\labelwidth} \addtolength{\leftmargin}{\labelsep} \renewcommand{\makelabel}{\DUoptionlistlabel}} } {\endlist} }{} % rubric (informal heading) \providecommand*{\DUrubric}[2][class-arg]{% \subsubsection*{\centering\textit{\textmd{#2}}}} % sidebar (text outside the main text flow) \providecommand{\DUsidebar}[2][class-arg]{% \begin{center} \colorbox[gray]{0.80}{\parbox{0.9\textwidth}{#2}} \end{center} } % subtitle (for topic/sidebar) \providecommand*{\DUsubtitle}[2][class-arg]{\par\emph{#2}\smallskip} % title for topics, admonitions, unsupported section levels, and sidebar \providecommand*{\DUtitle}[2][class-arg]{% % call \DUtitle#1{#2} if it exists: \ifcsname DUtitle#1\endcsname% \csname DUtitle#1\endcsname{#2}% \else \smallskip\noindent\textbf{#2}\smallskip% \fi } % titlereference role \providecommand*{\DUroletitlereference}[1]{\textsl{#1}} % topic (quote with heading) \providecommand{\DUtopic}[2][class-arg]{% \ifcsname DUtopic#1\endcsname% \csname DUtopic#1\endcsname{#2}% \else \begin{quote}#2\end{quote} \fi } % transition (break, fancybreak, anonymous section) \providecommand*{\DUtransition}[1][class-arg]{% \hspace*{\fill}\hrulefill\hspace*{\fill} \vskip 0.5\baselineskip } % hyperlinks: \ifthenelse{\isundefined{\hypersetup}}{ \usepackage[colorlinks=true,linkcolor=blue,urlcolor=blue]{hyperref} \urlstyle{same} % normal text font (alternatives: tt, rm, sf) }{} \hypersetup{ pdftitle={reStructuredText Test Document}, pdfauthor={David Goodger;Me;Myself;I} } %%% Title Data \title{\phantomsection% reStructuredText Test Document% \label{restructuredtext-test-document}% \label{doctitle}% \\ % subtitle% \DUdocumentsubtitle{Examples of Syntax Constructs}% \label{examples-of-syntax-constructs}% \label{subtitle}} \author{} \date{} %%% Body \begin{document} \maketitle % Docinfo \begin{center} \begin{tabularx}{\DUdocinfowidth}{lX} \textbf{Author}: & David Goodger \\ \textbf{Address}: & {\raggedright 123 Example Street\\ Example, EX Canada\\ A1B 2C3 } \\ \textbf{Contact}: & \href{mailto:goodger@python.org}{goodger@python.org} \\ \textbf{Author}: & Me \\ \textbf{Author}: & Myself \\ \textbf{Author}: & I \\ \textbf{Organization}: & humankind \\ \textbf{Date}: & Now, or yesterday. Or maybe even \emph{before} yesterday. \\ \textbf{Status}: & This is a “work in progress” \\ \textbf{Revision}: & is managed by a version control system. \\ \textbf{Version}: & 1 \\ \textbf{Copyright}: & This document has been placed in the public domain. You may do with it as you wish. You may copy, modify, redistribute, reattribute, sell, buy, rent, lease, destroy, or improve it, quote it at length, excerpt, incorporate, collate, fold, staple, or mutilate it, or do anything else to it that your or anyone else’s heart desires. \\ \textbf{field name}: & This is a “generic bibliographic field”. \\ \textbf{field name “2”}: & Generic bibliographic fields may contain multiple body elements. Like this. \\ \end{tabularx} \end{center} \DUtopic[dedication]{ \DUtitle[dedication]{Dedication} For Docutils users \& co-developers. } \DUtopic[abstract]{ \DUtitle[abstract]{Abstract} This is a test document, containing at least one example of each reStructuredText construct. } % This is a comment. Note how any initial comments are moved by % transforms to after the document title, subtitle, and docinfo. % Above is the document title, and below is the subtitle. % They are transformed from section titles after parsing. % bibliographic fields (which also require a transform): \pagebreak[4] % start ToC on new page \phantomsection\label{table-of-contents} \pdfbookmark[1]{Table of Contents}{table-of-contents} \renewcommand{\contentsname}{Table of Contents} \tableofcontents \section{1~~~Structural Elements% \label{structural-elements}% } \subsection{1.1~~~Section Title% \label{section-title}% } \subsubsection*{Section Subtitle} Lone subsections are converted to a section subtitle by a transform activated with the \texttt{-{}-section-subtitles} command line option or the \texttt{sectsubtitle-xform} configuration value. \subsection{1.2~~~Empty Section% \label{empty-section}% } \subsection{1.3~~~Transitions% \label{transitions}% } Here’s a transition: %___________________________________________________________________________ \DUtransition It divides the section. Transitions may also occur between sections: %___________________________________________________________________________ \DUtransition \section{2~~~Body Elements% \label{body-elements}% } \subsection{2.1~~~Paragraphs% \label{paragraphs}% } A paragraph. \subsubsection{2.1.1~~~Inline Markup% \label{inline-markup}% } Paragraphs contain text and may contain inline markup: \emph{emphasis}, \textbf{strong emphasis}, \texttt{inline literals}, standalone hyperlinks (\url{http://www.python.org}), external hyperlinks (\href{http://www.python.org/}{Python}\DUfootnotemark{id30}{id29}{5}), internal cross-references (\hyperref[example]{example}), external hyperlinks with embedded URIs (\href{http://www.python.org}{Python web site}), \href{http://www.python.org/}{anonymous hyperlink references}\DUfootnotemark{id38}{id29}{5} (\href{http://docutils.sourceforge.net/}{a second reference}\DUfootnotemark{id40}{id39}{8}), footnote references (manually numbered\DUfootnotemark{id1}{id8}{1}, anonymous auto-numbered\DUfootnotemark{id2}{id12}{3}, labeled auto-numbered\DUfootnotemark{id3}{label}{2}, or symbolic\DUfootnotemark{id4}{id13}{*}), citation references (\hyperlink{cit2002}{[CIT2002]}), substitution references (\includegraphics{../../../docs/user/rst/images/biohazard.png}), and % \phantomsection\label{inline-hyperlink-targets}inline hyperlink targets (see \hyperref[targets]{Targets} below for a reference back to here). Character-level inline markup is also possible (although exceedingly ugly!) in \emph{re}\texttt{Structured}\emph{Text}. Problems are indicated by % \raisebox{1em}{\hypertarget{id28}{}}\hyperlink{id27}{\textbf{\color{red}|problematic|}} text (generated by processing errors; this one is intentional). Here is a reference to the \hyperref[doctitle]{doctitle} and the \hyperref[subtitle]{subtitle}. The default role for interpreted text is \DUroletitlereference{Title Reference}. Here are some explicit interpreted text roles: a PEP reference (\href{http://www.python.org/dev/peps/pep-0287}{PEP 287}); an RFC reference (\href{http://www.faqs.org/rfcs/rfc2822.html}{RFC 2822}); an abbreviation (\DUrole{abbreviation}{abb.}), an acronym (\DUrole{acronym}{reST}), code (\texttt{\DUrole{code}{print \textquotedbl{}hello world\textquotedbl{}}}); a \textsubscript{subscript}; a \textsuperscript{superscript} and explicit roles for \DUroletitlereference{Docutils}’ \emph{standard} \textbf{inline} \texttt{markup}. % DO NOT RE-WRAP THE FOLLOWING PARAGRAPH! Let’s test wrapping and whitespace significance in inline literals: \texttt{This is an example of -{}-inline-literal -{}-text, -{}-including some-{}- strangely-{}-hyphenated-words. ~Adjust-the-width-of-your-browser-window to see how the text is wrapped. ~-{}- -{}-{}-{}- -{}-{}-{}-{}-{}-{}-{}- ~Now note ~ ~the spacing ~ ~between the ~ ~words of ~ ~this sentence ~ ~(words should ~ ~be grouped ~ ~in pairs).} If the \texttt{-{}-pep-references} option was supplied, there should be a live link to PEP 258 here. \subsection{2.2~~~Bullet Lists% \label{bullet-lists}% } % \begin{itemize} \item A bullet list % \begin{itemize} \item Nested bullet list. \item Nested item 2. \end{itemize} \item Item 2. Paragraph 2 of item 2. % \begin{itemize} \item Nested bullet list. \item Nested item 2. % \begin{itemize} \item Third level. \item Item 2. \end{itemize} \item Nested item 3. \item This nested list should be compacted by the HTML writer. % \phantomsection\label{target} % Even if this item contains a target and a comment. \end{itemize} \end{itemize} \subsection{2.3~~~Enumerated Lists% \label{enumerated-lists}% } \newcounter{listcnt0} \begin{list}{\arabic{listcnt0}.} { \usecounter{listcnt0} \setlength{\rightmargin}{\leftmargin} } \item Arabic numerals. \newcounter{listcnt1} \begin{list}{\alph{listcnt1})} { \usecounter{listcnt1} \setlength{\rightmargin}{\leftmargin} } \item lower alpha) \newcounter{listcnt2} \begin{list}{(\roman{listcnt2})} { \usecounter{listcnt2} \setlength{\rightmargin}{\leftmargin} } \item (lower roman) \newcounter{listcnt3} \begin{list}{\Alph{listcnt3}.} { \usecounter{listcnt3} \setlength{\rightmargin}{\leftmargin} } \item upper alpha. \newcounter{listcnt4} \begin{list}{\Roman{listcnt4})} { \usecounter{listcnt4} \setlength{\rightmargin}{\leftmargin} } \item upper roman) \end{list} \end{list} \end{list} \end{list} \item Lists that don’t start at 1: \setcounter{listcnt1}{0} \begin{list}{\arabic{listcnt1}.} { \usecounter{listcnt1} \addtocounter{listcnt1}{2} \setlength{\rightmargin}{\leftmargin} } \item Three \item Four \end{list} \setcounter{listcnt1}{0} \begin{list}{\Alph{listcnt1}.} { \usecounter{listcnt1} \addtocounter{listcnt1}{2} \setlength{\rightmargin}{\leftmargin} } \item C \item D \end{list} \setcounter{listcnt1}{0} \begin{list}{\roman{listcnt1}.} { \usecounter{listcnt1} \addtocounter{listcnt1}{2} \setlength{\rightmargin}{\leftmargin} } \item iii \item iv \end{list} \end{list} \subsection{2.4~~~Definition Lists% \label{definition-lists}% } % \begin{description} \item[{Term}] \leavevmode Definition \item[{Term}] \leavevmode (\textbf{classifier}) Definition paragraph 1. Definition paragraph 2. \item[{Term}] \leavevmode Definition \item[{Term}] \leavevmode (\textbf{classifier one}) (\textbf{classifier two}) Definition \end{description} \subsection{2.5~~~Field Lists% \label{field-lists}% } % \begin{DUfieldlist} \item[{what:}] Field lists map field names to field bodies, like database records. They are often part of an extension syntax. They are an unambiguous variant of RFC 2822 fields. \item[{how arg1 arg2:}] The field marker is a colon, the field name, and a colon. The field body may contain one or more body elements, indented relative to the field marker. \item[{credits:}] \DUrole{credits}{This paragraph has the \DUroletitlereference{credits} class set. (This is actually not about credits but just for ensuring that the class attribute doesn’t get stripped away.)} \end{DUfieldlist} \subsection{2.6~~~Option Lists% \label{option-lists}% } For listing command-line options: % \begin{DUoptionlist} \item[-a] command-line option “a” \item[-b file] options can have arguments and long descriptions \item[-{}-long] options can be long also \item[-{}-input=file] long options can also have arguments \item[-{}-very-long-option] The description can also start on the next line. The description may contain multiple body elements, regardless of where it starts. \item[-x, -y, -z] Multiple options are an “option group”. \item[-v, -{}-verbose] Commonly-seen: short \& long options. \item[-1 file, -{}-one=file, -{}-two file] Multiple options with arguments. \item[/V] DOS/VMS-style options too \end{DUoptionlist} There must be at least two spaces between the option and the description. \subsection{2.7~~~Literal Blocks% \label{literal-blocks}% } Literal blocks are indicated with a double-colon (“::”) at the end of the preceding paragraph (over there \texttt{-{}->}). They can be indented: % \begin{quote}{\ttfamily \raggedright \noindent if~literal\_block:\\ ~~~~text~=~'is~left~as-is'\\ ~~~~spaces\_and\_linebreaks~=~'are~preserved'\\ ~~~~markup\_processing~=~None } \end{quote} Or they can be quoted without indentation: % \begin{quote}{\ttfamily \raggedright \noindent >{}>~Great~idea!\\ >\\ >~Why~didn't~I~think~of~that? } \end{quote} \subsection{2.8~~~Line Blocks% \label{line-blocks}% } This section tests line blocks. Line blocks are body elements which consist of lines and other line blocks. Nested line blocks cause indentation. \begin{DUlineblock}{0em} \item[] This is a line block. It ends with a blank line. \item[] \begin{DUlineblock}{\DUlineblockindent} \item[] New lines begin with a vertical bar (“|”). \item[] Line breaks and initial indent are significant, and preserved. \item[] \begin{DUlineblock}{\DUlineblockindent} \item[] Continuation lines are also possible. A long line that is intended to wrap should begin with a space in place of the vertical bar. \end{DUlineblock} \item[] The left edge of a continuation line need not be aligned with the left edge of the text above it. \end{DUlineblock} \end{DUlineblock} \begin{DUlineblock}{0em} \item[] This is a second line block. \item[] \item[] Blank lines are permitted internally, but they must begin with a “|”. \end{DUlineblock} Another line block, surrounded by paragraphs: \begin{DUlineblock}{0em} \item[] And it’s no good waiting by the window \item[] It’s no good waiting for the sun \item[] Please believe me, the things you dream of \item[] They don’t fall in the lap of no-one \end{DUlineblock} Take it away, Eric the Orchestra Leader! % \begin{quote} \begin{DUlineblock}{0em} \item[] A one, two, a one two three four \item[] \item[] Half a bee, philosophically, \item[] \begin{DUlineblock}{\DUlineblockindent} \item[] must, \emph{ipso facto}, half not be. \end{DUlineblock} \item[] But half the bee has got to be, \item[] \begin{DUlineblock}{\DUlineblockindent} \item[] \emph{vis a vis} its entity. D’you see? \item[] \end{DUlineblock} \item[] But can a bee be said to be \item[] \begin{DUlineblock}{\DUlineblockindent} \item[] or not to be an entire bee, \item[] \begin{DUlineblock}{\DUlineblockindent} \item[] when half the bee is not a bee, \item[] \begin{DUlineblock}{\DUlineblockindent} \item[] due to some ancient injury? \item[] \end{DUlineblock} \end{DUlineblock} \end{DUlineblock} \item[] Singing… \end{DUlineblock} \end{quote} A line block, like the following poem by Christian Morgenstern, can also be centre-aligned: \begin{DUlineblock}{0em} \foreignlanguage{ngerman}{\DUrole{align-center}{ \item[] \textbf{Die Trichter} \item[] \item[] Zwei Trichter wandeln durch die Nacht. \item[] Durch ihres Rumpfs verengten Schacht \item[] fließt weißes Mondlicht \item[] still und heiter \item[] auf ~ ihren \item[] Waldweg \item[] u. s. \item[] w. \item[] }} \end{DUlineblock} \subsection{2.9~~~Block Quotes% \label{block-quotes}% } Block quotes consist of indented body elements: % \begin{quote} My theory by A. Elk. Brackets Miss, brackets. This theory goes as follows and begins now. All brontosauruses are thin at one end, much much thicker in the middle and then thin again at the far end. That is my theory, it is mine, and belongs to me and I own it, and what it is too. \nopagebreak \raggedleft —Anne Elk (Miss) \end{quote} The language of a quote (like any other object) can be specified by a class attribute: % % \begin{quote} \foreignlanguage{french}{ ReStructuredText est un langage de balisage léger utilisé notamment dans la documentation du langage Python. } \end{quote} \subsection{2.10~~~Doctest Blocks% \label{doctest-blocks}% } % \begin{quote}{\ttfamily \raggedright \noindent >{}>{}>~print~'Python-specific~usage~examples;~begun~with~\textquotedbl{}>{}>{}>\textquotedbl{}'\\ Python-specific~usage~examples;~begun~with~\textquotedbl{}>{}>{}>\textquotedbl{}\\ >{}>{}>~print~'(cut~and~pasted~from~interactive~Python~sessions)'\\ (cut~and~pasted~from~interactive~Python~sessions) } \end{quote} \subsection{2.11~~~Footnotes% \label{footnotes}% } % \DUfootnotetext{id8}{id1}{1}{% A footnote contains body elements, consistently indented by at least 3 spaces. This is the footnote’s second paragraph. } % \DUfootnotetext{label}{id3}{2}{\phantomsection\label{label}% Footnotes may be numbered, either manually (as in\DUfootnotemark{id9}{id8}{1}) or automatically using a “\#”-prefixed label. This footnote has a label so it can be referred to from multiple places, both as a footnote reference (\DUfootnotemark{id10}{label}{2}) and as a \hyperref[label]{hyperlink reference}. } % \DUfootnotetext{id12}{id2}{3}{% This footnote is numbered automatically and anonymously using a label of “\#” only. This is the second paragraph. And this is the third paragraph. } % \DUfootnotetext{id13}{id4}{*}{% Footnotes may also use symbols, specified with a “*” label. Here’s a reference to the next footnote:\DUfootnotemark{id14}{id15}{†}. } % \DUfootnotetext{id15}{id14}{†}{% This footnote shows the next symbol in the sequence. } % \DUfootnotetext{id16}{id16}{4}{% Here’s an unreferenced footnote, with a reference to a nonexistent footnote:% \raisebox{1em}{\hypertarget{id46}{}}% \raisebox{1em}{\hypertarget{id17}{}}\hyperlink{id45}{\textbf{\color{red}{[}5{]}\_}}. } \subsection{2.12~~~Citations% \label{citations}% } \begin{figure}[b]\raisebox{1em}{\hypertarget{cit2002}{}}[CIT2002] Citations are text-labeled footnotes. They may be rendered separately and differently from footnotes. \end{figure} Here’s a reference to the above, \hyperlink{cit2002}{[CIT2002]}, and a % \raisebox{1em}{\hypertarget{id48}{}}% \raisebox{1em}{\hypertarget{id19}{}}\hyperlink{id47}{\textbf{\color{red}{[}nonexistent{]}\_}} citation. \subsection{2.13~~~Targets% \label{targets}% \label{another-target}% } \phantomsection\label{example} This paragraph is pointed to by the explicit “example” target. A reference can be found under \hyperref[inline-markup]{Inline Markup}, above. \hyperref[inline-hyperlink-targets]{Inline hyperlink targets} are also possible. Section headers are implicit targets, referred to by name. See \hyperref[targets]{Targets}, which is a subsection of \hyperref[body-elements]{Body Elements}. Explicit external targets are interpolated into references such as “\href{http://www.python.org/}{Python}\DUfootnotemark{id31}{id29}{5}”. Targets may be indirect and anonymous. Thus \hyperref[targets]{this phrase} may also refer to the \hyperref[targets]{Targets} section. Here’s a % \raisebox{1em}{\hypertarget{id50}{}}\hyperlink{id49}{\textbf{\color{red}`hyperlink reference without a target`\_}}, which generates an error. \subsubsection{2.13.1~~~Duplicate Target Names% \label{duplicate-target-names}% } Duplicate names in section headers or other implicit targets will generate “info” (level-1) system messages. Duplicate names in explicit targets will generate “warning” (level-2) system messages. \subsubsection{2.13.2~~~Duplicate Target Names% \label{id21}% } Since there are two “Duplicate Target Names” section headers, we cannot uniquely refer to either of them by name. If we try to (like this: % \raisebox{1em}{\hypertarget{id52}{}}\hyperlink{id51}{\textbf{\color{red}`Duplicate Target Names`\_}}), an error is generated. \subsection{2.14~~~Directives% \label{directives}% } \phantomsection\label{contents} These are just a sample of the many reStructuredText Directives. For others, please see \url{http://docutils.sourceforge.net/docs/ref/rst/directives.html}. \subsubsection{2.14.1~~~Document Parts% \label{document-parts}% } An example of the “contents” directive can be seen above this section (a local, untitled table of \hyperref[contents]{contents}) and at the beginning of the document (a document-wide \hyperref[table-of-contents]{table of contents}). \subsubsection{2.14.2~~~Images and Figures% \label{images-and-figures}% } An image directive (also clickable – a hyperlink reference): \hyperref[directives]{\includegraphics{../../../docs/user/rst/images/title.png}} Image with multiple IDs: \includegraphics{../../../docs/user/rst/images/title.png} \phantomsection\label{image-target-3}\label{image-target-2}\label{image-target-1} A centered image: \noindent\makebox[\textwidth][c]{\includegraphics{../../../docs/user/rst/images/biohazard.png}} A left-aligned image: \noindent{\includegraphics{../../../docs/user/rst/images/biohazard.png}\hfill} This paragraph might flow around the image. The specific behavior depends upon the style sheet and the browser or rendering software used. A right-aligned image: \noindent{\hfill\includegraphics{../../../docs/user/rst/images/biohazard.png}} This paragraph might flow around the image. The specific behavior depends upon the style sheet and the browser or rendering software used. For inline images see \hyperref[substitution-definitions]{Substitution Definitions}. Image size: An image 2 em wide: \includegraphics[width=2em]{../../../docs/user/rst/images/biohazard.png} An image 2 em wide and 15 pixel high: \includegraphics[height=15px,width=2em]{../../../docs/user/rst/images/biohazard.png} An image occupying 50\% of the line width: \includegraphics[width=0.500\linewidth]{../../../docs/user/rst/images/title.png} An image 2 cm high: \includegraphics[height=2cm]{../../../docs/user/rst/images/biohazard.png} A \emph{figure} is an image with a caption and/or a legend. With page-based output media, figures might float to a different position if this helps the page layout. \begin{figure} \noindent\makebox[\textwidth][c]{\includegraphics[width=258bp]{../../../docs/user/rst/images/title.png}} \caption{Plaintext markup syntax and parser system.} \begin{DUlegend} \setlength{\DUtablewidth}{\linewidth} \begin{longtable*}[c]{|p{0.156\DUtablewidth}|p{0.563\DUtablewidth}|} \hline re & Revised, revisited, based on ‘re’ module. \\ \hline Structured & Structure-enhanced text, structuredtext. \\ \hline Text & Well it is, isn’t it? \\ \hline \end{longtable*} This paragraph is also part of the legend. \end{DUlegend} \end{figure} A left-aligned figure: \begin{figure} % align = "left" \noindent\makebox[\textwidth][c]{\includegraphics[width=40px]{../../../docs/user/rst/images/biohazard.png}} \caption{This is the caption.} \begin{DUlegend} This is the legend. The legend may consist of several paragraphs. \end{DUlegend} \end{figure} This paragraph might flow around the figure. The specific behavior depends upon the style sheet and the browser or rendering software used. A centered figure: \begin{figure} \noindent\makebox[\textwidth][c]{\includegraphics[width=40px]{../../../docs/user/rst/images/biohazard.png}} \caption{This is the caption.} \begin{DUlegend} This is the legend. The legend may consist of several paragraphs. \end{DUlegend} \end{figure} This paragraph might flow around the figure. The specific behavior depends upon the style sheet and the browser or rendering software used. A right-aligned figure: \begin{figure} % align = "right" \noindent\makebox[\textwidth][c]{\includegraphics[width=40px]{../../../docs/user/rst/images/biohazard.png}} \caption{This is the caption.} \begin{DUlegend} This is the legend. The legend may consist of several paragraphs. \end{DUlegend} \end{figure} This paragraph might flow around the figure. The specific behavior depends upon the style sheet and the browser or rendering software used. \subsubsection{2.14.3~~~Admonitions% \label{admonitions}% } \DUadmonition[attention]{ \DUtitle[attention]{Attention!} Directives at large. } \DUadmonition[caution]{ \DUtitle[caution]{Caution!} Don’t take any wooden nickels. } \DUadmonition[danger]{ \DUtitle[danger]{!DANGER!} Mad scientist at work! } \DUadmonition[error]{ \DUtitle[error]{Error} Does not compute. } \DUadmonition[hint]{ \DUtitle[hint]{Hint} It’s bigger than a bread box. } \DUadmonition[important]{ \DUtitle[important]{Important} % \begin{itemize} \item Wash behind your ears. \item Clean up your room. \item Call your mother. \item Back up your data. \end{itemize} } \DUadmonition[note]{ \DUtitle[note]{Note} This is a note. } \DUadmonition[tip]{ \DUtitle[tip]{Tip} 15\% if the service is good. } \DUadmonition[warning]{ \DUtitle[warning]{Warning} Strong prose may provoke extreme mental exertion. Reader discretion is strongly advised. } \DUadmonition[admonition-and-by-the-way]{ \DUtitle[admonition-and-by-the-way]{And, by the way…} You can make up your own admonition too. } \subsubsection{2.14.4~~~Topics, Sidebars, and Rubrics% \label{topics-sidebars-and-rubrics}% } \emph{Sidebars} are like miniature, parallel documents. \DUsidebar{ \DUtitle[title]{Sidebar Title} \DUsubtitle[sidebar]{Optional Subtitle} This is a sidebar. It is for text outside the flow of the main text. \DUrubric{This is a rubric inside a sidebar} Sidebars often appear beside the main text with a border and a different background or font color. } A \emph{topic} is like a block quote with a title, or a self-contained section with no subsections. \DUtopic[]{ \DUtitle[title]{Topic Title} This is a topic. } A \emph{rubric} is like an informal heading that doesn’t correspond to the document’s structure. It is typically highlighted in red (hence the name). \DUrubric{This is a rubric} Topics and rubrics can be used at places where a \hyperref[section-title]{section title} is not allowed (e.g. inside a directive). \subsubsection{2.14.5~~~Target Footnotes% \label{target-footnotes}% } % \DUfootnotetext{id29}{id30}{5}{% \url{http://www.python.org/} } % \DUfootnotetext{id33}{id34}{6}{% \url{http://pygments.org/} } % \DUfootnotetext{id35}{id36}{7}{% \url{ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf} } % \DUfootnotetext{id39}{id40}{8}{% \url{http://docutils.sourceforge.net/} } % \DUfootnotetext{id41}{id42}{9}{% \url{A:DOS\\path\\} } \subsubsection{2.14.6~~~Replacement Text% \label{replacement-text}% } I recommend you try \href{http://www.python.org/}{Python, \emph{the} best language around}\DUfootnotemark{id32}{id29}{5}. \subsubsection{2.14.7~~~Compound Paragraph% \label{compound-paragraph}% } Compound 1, paragraph 1. Compound 1, paragraph 2. % \begin{itemize} \item Compound 1, list item one. \item Compound 1, list item two. \end{itemize} Another compound statement: Compound 2, a literal block: % \begin{quote}{\ttfamily \raggedright \noindent Compound~2,~literal. } \end{quote} Compound 2, this is a test. Compound 3, only consisting of one paragraph. % \begin{quote}{\ttfamily \raggedright \noindent Compound~4.\\ This~one~starts~with~a~literal~block. } \end{quote} Compound 4, a paragraph. Now something \emph{really} perverted – a nested compound block. This is just to test that it works at all; the results don’t have to be meaningful. Compound 5, block 1 (a paragraph). Compound 6, block 2 in compound 5. Compound 6, another paragraph. Compound 5, block 3 (a paragraph). Compound 7, with a table inside: \setlength{\DUtablewidth}{\linewidth} \begin{longtable*}[c]{|p{0.249\DUtablewidth}|p{0.249\DUtablewidth}|p{0.249\DUtablewidth}|} \hline Left cell, first paragraph. Left cell, second paragraph. & Middle cell, consisting of exactly one paragraph. & Right cell. Paragraph 2. Paragraph 3. \\ \hline \end{longtable*} Compound 7, a paragraph after the table. Compound 7, another paragraph. \subsubsection{2.14.8~~~Parsed Literal Blocks% \label{parsed-literal-blocks}% } % \begin{quote}{\ttfamily \raggedright \noindent This~is~a~parsed~literal~block.\\ ~~~~This~line~is~indented.~~The~next~line~is~blank.\\ ~\\ Inline~markup~is~supported,~e.g.~\emph{emphasis},~\textbf{strong},~\texttt{literal\\ text},~footnotes\DUfootnotemark{id22}{id8}{1},~% \phantomsection\label{hyperlink-targets}hyperlink~targets,~and~\href{http://www.python.org/}{references}. } \end{quote} \subsubsection{2.14.9~~~Code% \label{code}% } Blocks of source code can be set with the \DUroletitlereference{code} directive. If the code language is specified, the content is parsed and tagged by the \href{http://pygments.org/}{Pygments}\DUfootnotemark{id34}{id33}{6} syntax highlighter and can be formatted with a style sheet. (Code parsing is turned off using the \texttt{syntax-highlight} config setting in the test conversions in order to get identical results with/without installed Pygments highlighter.) % \begin{quote}{\ttfamily \raggedright \noindent print~'This~is~Python~code.' } \end{quote} The \texttt{:number-lines:} option (with optional start value) generates line numbers: % \begin{quote}{\ttfamily \raggedright \noindent \DUrole{ln}{~8~}\#~print~integers~from~0~to~9:\\ \DUrole{ln}{~9~}for~i~in~range(10):\\ \DUrole{ln}{10~}~~~~print~i } \end{quote} For inline code snippets, there is the \DUroletitlereference{code} role, which can be used directly (the code will not be parsed/tagged, as the language is not known) or as base for special code roles, e.g. the LaTeX code in the next paragraph. Docutils uses LaTeX syntax for math directives and roles: \texttt{\DUrole{code}{\DUrole{tex}{\textbackslash{}alpha = f(x)}}} prints $\alpha = f(x)$. The \texttt{:code:} option of the \DUroletitlereference{include} directive sets the included content as a code block, here the rst file \texttt{header\_footer.txt} with line numbers: % \begin{quote}{\ttfamily \raggedright \noindent \DUrole{ln}{1~}..~header::~Document~header\\ \DUrole{ln}{2~}..~footer::~Document~footer } \end{quote} \subsection{2.15~~~Substitution Definitions% \label{substitution-definitions}% } An inline image (\includegraphics{../../../docs/user/rst/images/biohazard.png}) example: (Substitution definitions are not visible in the HTML source.) \subsection{2.16~~~Comments% \label{comments}% } Here’s one: % Comments begin with two dots and a space. Anything may % follow, except for the syntax of footnotes, hyperlink % targets, directives, or substitution definitions. % % Double-dashes -- "--" -- must be escaped somehow in HTML output. % % Comments may contain non-ASCII characters: ä ö ü æ ø å (View the HTML source to see the comment.) \subsection{2.17~~~Raw text% \label{raw-text}% } This does not necessarily look nice, because there may be missing white space. It’s just there to freeze the behavior. A test. Second test. \DUrole{myclass}{Another test with myclass set.} This is the \DUrole{myrawroleclass}{fourth test} with myrawroleclass set. Fifth test in LaTeX.\\Line two. \subsection{2.18~~~Container% \label{container}% } paragraph 1 paragraph 2 % currently not implemented in LaTeX: % .. include:: data/header_footer.txt \subsection{2.19~~~Colspanning tables% \label{colspanning-tables}% } This table has a cell spanning two columns: \setlength{\DUtablewidth}{\linewidth} \begin{longtable*}[c]{|p{0.075\DUtablewidth}|p{0.075\DUtablewidth}|p{0.086\DUtablewidth}|} \hline \multicolumn{2}{|p{0.15\DUtablewidth}|}{\textbf{% Inputs }} & \textbf{% Output } \\ \hline \textbf{% A } & \textbf{% B } & \textbf{% A or B } \\ \hline \endfirsthead \hline \multicolumn{2}{|p{0.15\DUtablewidth}|}{\textbf{% Inputs }} & \textbf{% Output } \\ \hline \textbf{% A } & \textbf{% B } & \textbf{% A or B } \\ \hline \endhead \multicolumn{3}{c}{\hfill ... continued on next page} \\ \endfoot \endlastfoot False & False & False \\ \hline True & False & True \\ \hline False & True & True \\ \hline True & True & True \\ \hline \end{longtable*} \subsection{2.20~~~Rowspanning tables% \label{rowspanning-tables}% } Here’s a table with cells spanning several rows: \setlength{\DUtablewidth}{\linewidth} \begin{longtable*}[c]{|p{0.296\DUtablewidth}|p{0.156\DUtablewidth}|p{0.226\DUtablewidth}|} \hline \textbf{% Header row, column 1 (header rows optional) } & \textbf{% Header 2 } & \textbf{% Header 3 } \\ \hline \endfirsthead \hline \textbf{% Header row, column 1 (header rows optional) } & \textbf{% Header 2 } & \textbf{% Header 3 } \\ \hline \endhead \multicolumn{3}{c}{\hfill ... continued on next page} \\ \endfoot \endlastfoot body row 1, column 1 & column 2 & column 3 \\ \hline body row 2 & \multirow{2}{0.16\DUtablewidth}{% Cells may span rows. } & \multirow{2}{0.23\DUtablewidth}{% Another rowspanning cell. } \\ \cline{1-1} body row 3 & \\ \hline \end{longtable*} \subsection{2.21~~~Custom Roles% \label{custom-roles}% } % \begin{itemize} \item A role based on an existing role. \texttt{\DUrole{custom}{one}} \texttt{\DUrole{custom}{two}} \texttt{\DUrole{custom}{three}} \item A new role. \DUrole{customnew}{one two three} \item A role with class attribute. \DUrole{special}{interpreted text} \item A language-switching role: Let’s count in German \foreignlanguage{ngerman}{eins zwei drei}. \item A role with multiple class attributes, styled with raw directives: \newcommand{\DUrolegreen}[1]{\textcolor{green}{#1}} \newcommand{\DUrolesc}[1]{\textsc{#1}} The following works in most browsers but does not validate (\texttt{<style>} is only allowed in the document head): % \begin{quote}{\ttfamily \raggedright \noindent ..~raw::~html\\ ~\\ ~~<style~type=\textquotedbl{}text/css\textquotedbl{}><!-{}-\\ ~~~.green~\{color:~green;\}\\ ~~~.sc~\{font-variant:~small-caps;\}\\ ~~~-{}-></style> } \end{quote} \DUrole{green}{\DUrole{sc}{\foreignlanguage{british}{British colourful text in small-caps}}}. \end{itemize} \subsection{2.22~~~Mathematics% \label{mathematics}% } Docutils supports inline math with the prefix or postfix \texttt{:math:} role specificator, $n! + \sin(x_n^2)$ and $A_\text{c} = \frac{\pi}{4} d^2$, as well as displayed math via the \DUroletitlereference{math} directive: % \begin{equation*} f(\epsilon) = \frac{1}{1 + \exp\left(\frac{\varepsilon}{k_\text{B}T}\right)} \end{equation*} Content may start on the first line of the directive, e.g. % \begin{equation*} N = \frac{\text{number of apples}}{7} \end{equation*} Equations can be labeled with a reference name using the \texttt{:name:} option. See \hyperref[eq-m]{eq:M} and \hyperref[eq-schrodinger]{eq:schrödinger} below. The determinant of the matrix % \begin{equation*} \mathbf{M} = \left(\begin{matrix}a&b\\c&d\end{matrix}\right) \phantomsection \label{eq-m} \end{equation*} is $|\mathbf{M}| = ad - bc$. More than one display math block can be put in one math directive. For example, the following sum and integral with limits: % \begin{equation*} \int_0^1 x^n dx = \frac{1}{n + 1} \end{equation*}% \begin{equation*} \sum_{n=1}^m n = \frac{m(m+1)}{2} \end{equation*} LaTeX-supported Unicode math symbols can be used in math roles and directives: The Schrödinger equation % \begin{equation*} i\hbar \frac{\partial }{\partial t}\Psi = \hat{H}\Psi , \phantomsection \label{eq-schrodinger} \end{equation*} with the \emph{wave function} $\Psi $, describes how the quantum state of a physical system changes in time. % \begin{description} \item[{Math-Accents:}] \leavevmode \setlength{\DUtablewidth}{\linewidth} \begin{longtable*}[c]{p{0.315\DUtablewidth}p{0.315\DUtablewidth}p{0.315\DUtablewidth}} $\acute{a}$ \texttt{\textbackslash{}acute\{a\}} & $\dot{t}$ \texttt{\textbackslash{}dot\{t\}} & $\hat{\gamma}$ \texttt{\textbackslash{}hat\{\textbackslash{}gamma\}} \\ $\grave{a}$ \texttt{\textbackslash{}grave\{a\}} & $\ddot{t}$ \texttt{\textbackslash{}ddot\{t\}} & $\tilde{\alpha}$ \texttt{\textbackslash{}tilde\{\textbackslash{}alpha\}} \\ $\breve{x}$ \texttt{\textbackslash{}breve\{x\}} & $\dddot{t}$ \texttt{\textbackslash{}dddot\{t\}} & $\vec{\imath}$ \texttt{\textbackslash{}vec\{\textbackslash{}imath\}} \\ $\check{a}$ \texttt{\textbackslash{}check\{a\}} & $\bar{a}$ \texttt{\textbackslash{}bar\{a\}} & $\vec{R}$ \texttt{\textbackslash{}vec\{R\}} \\ \end{longtable*} \end{description} % \widetilde{xxx} % \widehat{xxx} Modulation Transfer Function: % \begin{equation*} \text{MTF} = \left|\frac{\mathcal{F}\{s(x)\}} {\mathcal{F}\{ s(x)\} |_{\omega _{x}=0}}\right| = \mathrm{abs}\left(\frac {\int _{-\infty }^{\infty }s(x) \mathrm{e}^{\mathrm{i}\omega _{x}x}\mathrm{d}{x}} {\int _{-\infty }^{\infty }s(x)\mathrm{d}{x}} \right). \end{equation*} Math split over two lines: If a double backslash is detected outside a \texttt{\textbackslash{}begin\{...\} \textbackslash{}end\{...\}} pair, the math code is wrapped in an \href{ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf}{AMSmath}\DUfootnotemark{id36}{id35}{7} \texttt{align} environment: % \begin{align*} s_{\mathrm{out}}(x) & = s_{\mathrm{in}}(x') * s_\delta (x-x') \\ & = \int s_{\mathrm{in}}(x')s_\delta (x-x')\mathrm{d}x' \end{align*} Cases (“manually”, with \texttt{matrix} environment): % \begin{equation*} \mathrm{sgn}(x) = \left\{\begin{matrix} -1 & x<0\\ 1 & x>0 \end{matrix}\right. \end{equation*} Cases with the \href{ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf}{AMSmath}\DUfootnotemark{id37}{id35}{7} \texttt{cases} environment (not (yet) supported by HTML writers with \texttt{-{}-math-output=MathML}): % \begin{equation*} \mathrm{sgn}(x) = \begin{cases} -1 & x<0\\ 1 & x>0 \end{cases} \end{equation*} \section{3~~~Tests for the LaTeX writer% \label{tests-for-the-latex-writer}% } Test syntax elements which may cause trouble for the LaTeX writer but might not need to be tested with other writers (e.g. the HTML writer). \subsection{3.1~~~Custom Roles in LaTeX% \label{custom-roles-in-latex}% } % \begin{itemize} \item Role names and class arguments are converted to conform to the regular expression \texttt{{[}a-z{]}{[}-a-z0-9{]}*} (letters are downcased, accents and similar decoration is stripped, non-conforming characters are replaced by a hyphen). Class arguments may contain numbers and hyphens, which need special treatment in LaTeX command names. \DUrole{large}{\DUrole{custom4}{\DUrole{small-caps}{\DUrole{custom-role}{\DUrole{custom-role}{Interpreted Text}}}}} \item With LaTeX, roles can be styled within the document using the \DUroletitlereference{raw} directive. \newcommand{\DUrolelarge}[1]{{\large #1}} \makeatletter \@namedef{DUrolesmall-caps}{\textsc} \@namedef{DUrolecustom4}{\textbf} \makeatother \DUrole{large}{\DUrole{custom4}{\DUrole{small-caps}{\DUrole{custom-role}{\DUrole{custom-role}{Interpreted Text}}}}} in large, bold, small-caps. \item Custom roles can be based on standard roles: This is a \emph{\DUrole{custom-emphasis}{customized emphasis text role}} This is a \texttt{\DUrole{custom-literal}{customized literal text role}} This is a \textbf{\DUrole{custom-strong}{customized strong text role}} This is a \textsubscript{\DUrole{custom-subscript}{customized subscript text role}} This is a \textsuperscript{\DUrole{custom-superscript}{customized superscript text role}} This is a \DUroletitlereference{\DUrole{custom-title-reference}{customized title-reference text role}} \end{itemize} \subsection{3.2~~~More Tables% \label{more-tables}% } A multicolumn table with multi-paragraph rowspanning cells: \setlength{\DUtablewidth}{\linewidth} \begin{longtable*}[c]{|p{0.133\DUtablewidth}|p{0.179\DUtablewidth}|p{0.179\DUtablewidth}|p{0.110\DUtablewidth}|p{0.121\DUtablewidth}|p{0.145\DUtablewidth}|} \hline test & \textbf{bold hd} & \multicolumn{3}{p{0.41\DUtablewidth}|}{ multicolumn 1 With a second paragraph } & \emph{emph hd} \\ \hline \multicolumn{2}{|p{0.31\DUtablewidth}|}{ multicolumn 2 With a second paragraph } & cell & cell & cell & cell \\ \hline cell & \multicolumn{2}{p{0.36\DUtablewidth}|}{ multicolumn 3 (one line, but very very very very very looooong) } & cell & cell & cell \\ \hline cell & cell & cell & \multicolumn{3}{p{0.38\DUtablewidth}|}{ Short multicolumn 4 } \\ \hline \end{longtable*} A table with multirow header % \begin{quote} \setlength{\DUtablewidth}{\linewidth} \begin{longtable*}[c]{|p{0.156\DUtablewidth}|p{0.238\DUtablewidth}|} \hline \multirow{2}{0.16\DUtablewidth}{% \textbf{% XXX }} & \textbf{% Variable Summary } \\ \cline{2-2} & \textbf{% Description } \\ \hline \endfirsthead \hline \multirow{2}{0.16\DUtablewidth}{% \textbf{% XXX }} & \textbf{% Variable Summary } \\ \cline{2-2} & \textbf{% Description } \\ \hline \endhead \multicolumn{2}{c}{\hfill ... continued on next page} \\ \endfoot \endlastfoot \multicolumn{2}{|p{0.39\DUtablewidth}|}{ multirow header breaks latex } \\ \hline \end{longtable*} \end{quote} % This file is used by the standalone_rst_latex test. \subsection{3.3~~~Option lists% \label{id23}% } The LaTeX-2e description environment is used for definition lists. The definition is continued on the same line as the term, this should not happen if a option-list is at the top of the definition. If the option list is not at the first element in the definition, it is contained in a quote % \begin{quote} % \begin{DUoptionlist} \item[-{}-help] show help \item[-v] verbose \end{DUoptionlist} \end{quote} % \begin{description} \item[{In a definition list:}] \leavevmode % \begin{DUoptionlist} \item[-{}-help] show help \item[-v] verbose \end{DUoptionlist} \end{description} \subsection{3.4~~~Monospaced non-alphanumeric characters% \label{monospaced-non-alphanumeric-characters}% } These are all ASCII characters except a-zA-Z0-9 and space: \texttt{!!!\textquotedbl{}\textquotedbl{}\textquotedbl{}\#\#\#\$\$\$\%\%\%\&\&\&'{}'{}'((()))***+++,{},{},-{}-{}-...///:::} \texttt{;;;<{}<{}<===>{}>{}>???@@@{[}{[}{[}\textbackslash{}\textbackslash{}\textbackslash{}{]}{]}{]}\textasciicircum{}\textasciicircum{}\textasciicircum{}\_\_\_`{}`{}`\{\{\{|||\}\}\}\textasciitilde{}\textasciitilde{}\textasciitilde{}} \texttt{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} The two lines of non-alphanumeric characters should both have the same width as the third line. \subsection{3.5~~~Non-ASCII characters% \label{non-ascii-characters}% } Punctuation and footnote symbols \setlength{\DUtablewidth}{\linewidth} \begin{longtable*}[c]{|p{0.028\DUtablewidth}|p{0.424\DUtablewidth}|} \hline – & en-dash \\ \hline — & em-dash \\ \hline ‘ & single turned comma quotation mark \\ \hline ’ & single comma quotation mark \\ \hline ‚ & low single comma quotation mark \\ \hline “ & double turned comma quotation mark \\ \hline ” & double comma quotation mark \\ \hline „ & low double comma quotation mark \\ \hline † & dagger \\ \hline ‡ & double dagger \\ \hline \ding{169} & black diamond suit \\ \hline \ding{170} & black heart suit \\ \hline $\spadesuit$ & black spade suit \\ \hline $\clubsuit$ & black club suit \\ \hline … & ellipsis \\ \hline ™ & trade mark sign \\ \hline $\Leftrightarrow$ & left-right double arrow \\ \hline \end{longtable*} The \DUroletitlereference{Latin-1 extended} Unicode block \setlength{\DUtablewidth}{\linewidth} \begin{longtable*}[c]{|p{0.051\DUtablewidth}|p{0.028\DUtablewidth}|p{0.028\DUtablewidth}|p{0.028\DUtablewidth}|p{0.028\DUtablewidth}|p{0.028\DUtablewidth}|p{0.028\DUtablewidth}|p{0.028\DUtablewidth}|p{0.028\DUtablewidth}|p{0.028\DUtablewidth}|p{0.028\DUtablewidth}|} \hline % & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 \\ \hline 160 & & ¡ & ¢ & £ & & ¥ & ¦ & § & ¨ & © \\ \hline 170 & ª & « & ¬ & \- & ® & ¯ & ° & ± & ² & ³ \\ \hline 180 & ´ & µ & ¶ & · & ¸ & ¹ & º & » & ¼ & ½ \\ \hline 190 & ¾ & ¿ & À & Á &  & à & Ä & Å & Æ & Ç \\ \hline 200 & È & É & Ê & Ë & Ì & Í & Î & Ï & Ð & Ñ \\ \hline 210 & Ò & Ó & Ô & Õ & Ö & × & Ø & Ù & Ú & Û \\ \hline 220 & Ü & Ý & Þ & ß & à & á & â & ã & ä & å \\ \hline 230 & æ & ç & è & é & ê & ë & ì & í & î & ï \\ \hline 240 & ð & ñ & ò & ó & ô & õ & ö & ÷ & ø & ù \\ \hline 250 & ú & û & ü & ý & þ & ÿ & & & & \\ \hline \end{longtable*} % \begin{itemize} \item The following line should not be wrapped, because it uses no-break spaces (\textbackslash{}u00a0): X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X~X \item Line wrapping with/without breakpoints marked by soft hyphens (\textbackslash{}u00ad): pdn\-derd\-mdtd\-ri\-schpdn\-derd\-mdtd\-ri\-schpdn\-derd\-mdtd\-ri\-schpdn\-derd\-mdtd\-ri\-schpdn\-derd\-mdtd\-ri\-sch pdnderdmdtdrischpdnderdmdtdrischpdnderdmdtdrischpdnderdmdtdrischpdnderdmdtdrisch \item The currency sign (\textbackslash{}u00a4) is not supported by all fonts (some have an Euro sign at its place). You might see an error like: % \begin{quote}{\ttfamily \raggedright \noindent !~Package~textcomp~Error:~Symbol~\textbackslash{}textcurrency~not~provided~by\\ (textcomp)~~~~~~~~~~~~~~~~font~family~ptm~in~TS1~encoding.\\ (textcomp)~~~~~~~~~~~~~~~~Default~family~used~instead. } \end{quote} (which in case of font family ptm is a false positive). Add either % \begin{DUfieldlist} \item[{warn:}] turn the error in a warning, use the default symbol (bitmap), or \item[{force,almostfull:}] use the symbol provided by the font at the users risk, \end{DUfieldlist} to the document options or use a different font package. \end{itemize} \subsection{3.6~~~Encoding special chars% \label{encoding-special-chars}% } The LaTeX Info pages lists under “2.18 Special Characters” % \begin{quote} The following characters play a special role in LaTeX and are called “special printing characters”, or simply “special characters”. % \begin{quote} \# \$ \% \& \textasciitilde{} \_ \textasciicircum{} \textbackslash{} \{ \} \end{quote} \end{quote} The special chars verbatim: % \begin{quote}{\ttfamily \raggedright \noindent \#~\$~\%~\&~\textasciitilde{}~\_~\textasciicircum{}~\textbackslash{}~\{~\} } \end{quote} However also \emph{square brackets} {[}{]} need special care. % \begin{quote} item and all the other commands with optional arguments check if the token right after the macro name is an opening bracket. In that case the contents between that bracket and the following closing bracket on the same grouping level are taken as the optional argument. What makes this unintuitive is the fact that the square brackets aren’t grouping characters themselves, so in your last example item{[}{[}…{]}{]} the optional argument consists of {[}… (without the closing bracket). \end{quote} Compare the items in the following lists: % \begin{itemize} \item simple item \item {[}bracketed{]} item \end{itemize} % \begin{description} \item[{simple}] \leavevmode description term \item[{{[}bracketed{]}}] \leavevmode description term \end{description} The OT1 font-encoding has different characters for the less-than, greater-than and bar, < | >, except for typewriter font \DUroletitlereference{cmtt}: % \begin{quote}{\ttfamily \raggedright \noindent <~|~> } \end{quote} \subsection{3.7~~~Hyperlinks and -targets% \label{hyperlinks-and-targets}% } In LaTeX, we must set an explicit anchor (\texttt{\textbackslash{}phantomsection}) for a % \phantomsection\label{hypertarget-in-plain-text}hypertarget in plain text or in a figure but not in a longtable or caption: \setlength{\DUtablewidth}{\linewidth} \begin{longtable}[c]{|p{0.075\DUtablewidth}|p{0.075\DUtablewidth}|p{0.075\DUtablewidth}|} \caption{Table with % \label{hypertarget-in-table-title}hypertarget in table title.}\\ \hline False & True & None \\ \hline \end{longtable} \label{table-label} \begin{figure} \phantomsection\label{figure-label} \noindent\makebox[\textwidth][c]{\includegraphics{../../../docs/user/rst/images/biohazard.png}} \caption{Figure with % \label{hypertarget-in-figure-caption}hypertarget in figure caption.} \begin{DUlegend} Legend with % \phantomsection\label{hypertarget-in-figure-legend}hypertarget in figure legend. \end{DUlegend} \end{figure} \includegraphics{../../../docs/user/rst/images/biohazard.png} \phantomsection\label{image-label} See \hyperref[hypertarget-in-plain-text]{hypertarget in plain text}, \hyperref[table-label]{table label}, \hyperref[hypertarget-in-table-title]{hypertarget in table title}, \hyperref[figure-label]{figure label}, \hyperref[hypertarget-in-figure-caption]{hypertarget in figure caption}, \hyperref[hypertarget-in-figure-legend]{hypertarget in figure legend}, and \hyperref[image-label]{image label}. \subsection{3.8~~~External references% \label{external-references}% } Long URLs should be wrapped in the PDF. This can be achieved with the url command which is used by the LaTeX writer whenever the content (name) of a reference node equals the link URL. % \begin{description} \item[{Example:}] \leavevmode a long URL that should wrap in the output \url{http://docutils.sourceforge.net/docs/user/latex.html\#id79} \end{description} If the argument contains any “\%”, “\#”, or “\textasciicircum{}\textasciicircum{}”, or ends with \texttt{\textbackslash{}}, it can’t be used in the argument to another command. The argument must not contain unbalanced braces. The characters \textasciicircum{}, \{, \}, and \texttt{\textbackslash{}} are invalid in a “http:” or “ftp:” URL and not recognized as part of it: \begin{DUlineblock}{0em} \item[] \url{http://www.example.org}/strange\textasciicircum{}\textasciicircum{}name \item[] \url{http://www.example.org}\textbackslash{}using\textbackslash{}DOS\textbackslash{}paths\textbackslash{} \item[] \url{http://www.example.org/XML}/strange\{n\}ame \end{DUlineblock} They can, however be used in paths and/or filenames. Handling by the LaTeX writer: % \begin{itemize} \item \texttt{\#}, \texttt{\textbackslash{}} and \texttt{\%} are escaped: \begin{DUlineblock}{0em} \item[] \href{http://www.w3.org/XML/Schema\#dev}{URL with \#} \url{http://www.w3.org/XML/Schema\#dev} \item[] \href{http://www.w3.org/XML/Schema\%dev}{URL with \%} \url{http://example.org/Schema\%dev} \item[] \href{A:DOS\\path\\}{file with DOS path}\DUfootnotemark{id42}{id41}{9} \url{A:DOS\\path\\}\DUfootnotemark{id43}{id41}{9} \end{DUlineblock} \DUadmonition[note]{ \DUtitle[note]{Note} These URLs are typeset inside a LaTeX command without error. \begin{DUlineblock}{0em} \item[] \url{http://www.w3.org/XML/Schema\#dev} \item[] \url{http://example.org/Schema\%dev} \item[] \url{A:DOS\\path\\}\DUfootnotemark{id44}{id41}{9} \end{DUlineblock} } \end{itemize} % \begin{itemize} \item \textasciicircum{}\textasciicircum{} LaTeX’s special syntax for characters results in “strange” replacements (both with href and url). A warning is given. \href{../strange^^name}{file with \textasciicircum{}\textasciicircum{}}: \url{../strange^^name} \item Unbalanced braces, \{ or \}, will fail (both with href and url): % \begin{quote}{\ttfamily \raggedright \noindent `file~with~\{~<../strange\{name>`\_\_\\ `<../strange\{name>`\_\_ } \end{quote} while balanced braces are suported: \begin{DUlineblock}{0em} \item[] \url{../strange{n}ame} \item[] \url{../st{r}ange{n}ame} \item[] \url{../{st{r}ange{n}ame}} \end{DUlineblock} \end{itemize} \subsection{3.9~~~Section titles with \hyperref[inline-markup]{inline markup}% \label{section-titles-with-inline-markup}% } \subsubsection{3.9.1~~~\emph{emphasized}, H\textsubscript{2}O and $x^2$% \label{emphasized-h2o-and-x-2}% } \subsubsection{3.9.2~~~Substitutions work% \label{substitutions-fail}% } \subsection{3.10~~~Deeply nested sections% \label{deeply-nested-sections}% } In LaTeX and HTML, \subsubsection{3.10.1~~~Level 3% \label{level-3}% } nested sections \paragraph{3.10.1.1~~~level 4% \label{level-4}% } reach at some level \subparagraph{3.10.1.1.1~~~level 5% \label{level-5}% } (depending on the document class) \DUtitle[sectionVI]{3.10.1.1.1.1~~~level 6% \label{level-6}% } an unsupported level. % unusual combinations (from newlatex, for interactive testing) % .. include:: data/latex.txt % Preface for System Messages: \section{4~~~Error Handling% \label{error-handling}% } Any errors caught during processing will generate system messages. There should be five messages in the following, auto-generated section, “Docutils System Messages”: % section should be added by Docutils automatically \section[Docutils System Messages]{\color{red}Docutils System Messages% } \DUadmonition[system-message]{ \DUtitle[system-message]{system-message} \raisebox{1em}{\hypertarget{id27}{}} {\color{red}ERROR/3} in \texttt{functional/input/data/standard.txt}, line~104 \hyperlink{id28}{ Undefined substitution referenced: \textquotedbl{}problematic\textquotedbl{}. }} \DUadmonition[system-message]{ \DUtitle[system-message]{system-message} \raisebox{1em}{\hypertarget{id45}{}} {\color{red}ERROR/3} in \texttt{functional/input/data/standard.txt}, line~391 \hyperlink{id46}{ Unknown target name: \textquotedbl{}5\textquotedbl{}. }} \DUadmonition[system-message]{ \DUtitle[system-message]{system-message} \raisebox{1em}{\hypertarget{id47}{}} {\color{red}ERROR/3} in \texttt{functional/input/data/standard.txt}, line~400 \hyperlink{id48}{ Unknown target name: \textquotedbl{}nonexistent\textquotedbl{}. }} \DUadmonition[system-message]{ \DUtitle[system-message]{system-message} \raisebox{1em}{\hypertarget{id49}{}} {\color{red}ERROR/3} in \texttt{functional/input/data/standard.txt}, line~427 \hyperlink{id50}{ Unknown target name: \textquotedbl{}hyperlink reference without a target\textquotedbl{}. }} \DUadmonition[system-message]{ \DUtitle[system-message]{system-message} \raisebox{1em}{\hypertarget{id51}{}} {\color{red}ERROR/3} in \texttt{functional/input/data/standard.txt}, line~440 \hyperlink{id52}{ Duplicate target name, cannot be used as a unique reference: \textquotedbl{}duplicate target names\textquotedbl{}. }} \end{document} ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/expected/standalone_rst_manpage.man�����������������������������������0000664�0001750�0001750�00000005016�12116324524�027355� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������.\" Man page generated from reStructuredText. . .TH RST2MAN 1 "2006-10-22" "0.1" "text processing" .SH NAME rst2man \- generate unix manpages from reStructured text . .nr rst2man-indent-level 0 . .de1 rstReportMargin \\$1 \\n[an-margin] level \\n[rst2man-indent-level] level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] - \\n[rst2man-indent0] \\n[rst2man-indent1] \\n[rst2man-indent2] .. .de1 INDENT .\" .rstReportMargin pre: . RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1 .\" .rstReportMargin post: .. .de UNINDENT . RE .\" indent \\n[an-margin] .\" old: \\n[rst2man-indent\\n[rst2man-indent-level]] .nr rst2man-indent-level -1 .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] .in \\n[rst2man-indent\\n[rst2man-indent-level]]u .. .\" TODO: authors and author with name <email> . .SH SYNOPSIS .INDENT 0.0 .INDENT 3.5 rst2man.py inputfile outputfile .UNINDENT .UNINDENT .SH DESCRIPTION .sp rst2man transforms a reStructured text document into a unix man page. .sp In theory any valid reStructured text document should be processable, in reality this is .INDENT 0.0 .IP \(bu 2 a goal, that is not met yet .IP \(bu 2 a goal that might never be met, because only few constructs are used in man pages \fIand\fP because the common text file does not adhere to man page requirements. .sp For example a unix man page belongs into a numbered section, 1 is user commands, 8 contains administrator commands and the headlines of all manpages are collected into a database, queryable with the programm \fBapropos\fP, therefore the headline should contain a short text describing into which group this command belongs. .sp These informations are collected from title, subtitle and the docinfo, see this document as an example. .UNINDENT .SH OPTIONS .INDENT 0.0 .TP .BI \-\-config\fB= <file> Read configuration settings from <file>, if it exists. .TP .B \-\-version\fP,\fB \-V Show this program\(aqs version number and exit. .TP .B \-\-help\fP,\fB \-h Show this help message and exit. .UNINDENT .sp And a lot more standard docutils options. .SH FILES .sp None yet. .SH SEE ALSO .sp \fI\%docutils\fP \fI\%linux man page howto\fP .sp and \fBman man\fP also \fBman 7 man\fP .SH BUGS .INDENT 0.0 .IP 1. 3 Format options are included as they are required. .IP 2. 3 bullet lists .IP 3. 3 number lists .IP 4. 3 math: The LaTeX source is shown, e.g. \fBn! + \esin(x_n^2)\fP\&. .UNINDENT .sp Discussion is still open. .SH AUTHOR grubert@users.sourceforge.net .SH COPYRIGHT public domain .\" Generated by docutils manpage writer. . ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/test/functional/expected/standalone_rst_s5_html_1.html��������������������������������0000664�0001750�0001750�00000014316�12173166426�027744� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="generator" content="Docutils 0.12: http://docutils.sourceforge.net/" /> <meta name="version" content="S5 1.1" /> <title>Slide Shows

Slide Shows

Author: David Goodger
Date: 2005-11-28

This is a test. This is only a test. If this were a real slide show, there would be a projector handy.

Let's test the S5/HTML writer!

  • Use the arrow keys to navigate.
  • Click the "Ø" button to switch between presentation & handout/outline modes.
In presentation mode, mouse over to the lower right-hand corner to display the controls.

Introduction

  • reStructuredText

    Uses normal reStructuredText as input.

  • One section per slide

    Each first-level section is converted into a single slide.

  • (X)HTML output

    Presentations can be viewed using any modern graphical web browser. The browser must support CSS, JavaScript, and XHTML. S5 even works with IE!

  • Themes

    A variety of themes are available.

  • rst2s5.py

    The front-end tool to generate S5 slide shows.

Features (1)

A flush-left paragraph

A centered paragraph

A flush-right paragraph

Some colours: black [black], gray, silver, white [white], maroon, red, magenta, fuchsia, pink, orange, yellow, lime, green, olive, teal, cyan, aqua, blue, navy, purple

Features (2)

Some incremental text.

  • tiny (class & role name: "tiny", e.g. ":tiny:`text`")

  • small ("small")

  • normal (unstyled)

  • big ("big")

  • huge ("huge")

Checklist

  • The document title should be duplicated on each slide in the footer (except for the first slide, slide0, where the entire footer is disabled).
  • The footer also contains a second line, "Location • Date"
  • There's no table of contents on the first slide, although it does appear in the handout/outline.
  • Handout material is not displayed in presentation mode.
  • The theme directories should be created, and the theme files copied over.
docutils-0.12/test/functional/expected/math_output_mathjax.html0000664000175000017500000001347312341404260027125 0ustar engelbertengelbert00000000000000 Mathematics

Mathematics

Docutils supports inline math with the prefix or postfix :math: role specificator, \(n! + \sin(x_n^2)\) and \(A_\text{c} = \frac{\pi}{4} d^2\), as well as displayed math via the math directive:

\begin{equation*} f(\epsilon) = \frac{1}{1 + \exp\left(\frac{\varepsilon}{k_\text{B}T}\right)} \end{equation*}

Content may start on the first line of the directive, e.g.

\begin{equation*} N = \frac{\text{number of apples}}{7} \end{equation*}

Equations can be labeled with a reference name using the :name: option. See eq:M and eq:schrödinger below.

The determinant of the matrix

\begin{equation*} \mathbf{M} = \left(\begin{matrix}a&b\\c&d\end{matrix}\right) \end{equation*}

is \(|\mathbf{M}| = ad - bc\).

More than one display math block can be put in one math directive. For example, the following sum and integral with limits:

\begin{equation*} \int_0^1 x^n dx = \frac{1}{n + 1} \end{equation*}
\begin{equation*} \sum_{n=1}^m n = \frac{m(m+1)}{2} \end{equation*}

LaTeX-supported Unicode math symbols can be used in math roles and directives:

The Schrödinger equation

\begin{equation*} i\hbar \frac{\partial }{\partial t}\Psi = \hat{H}\Psi , \end{equation*}

with the wave function \(\Psi \), describes how the quantum state of a physical system changes in time.

Math-Accents:
\(\acute{a}\) \acute{a} \(\dot{t}\) \dot{t} \(\hat{\gamma}\) \hat{\gamma}
\(\grave{a}\) \grave{a} \(\ddot{t}\) \ddot{t} \(\tilde{\alpha}\) \tilde{\alpha}
\(\breve{x}\) \breve{x} \(\dddot{t}\) \dddot{t} \(\vec{\imath}\) \vec{\imath}
\(\check{a}\) \check{a} \(\bar{a}\) \bar{a} \(\vec{R}\) \vec{R}

Modulation Transfer Function:

\begin{equation*} \text{MTF} = \left|\frac{\mathcal{F}\{s(x)\}} {\mathcal{F}\{ s(x)\} |_{\omega _{x}=0}}\right| = \mathrm{abs}\left(\frac {\int _{-\infty }^{\infty }s(x) \mathrm{e}^{\mathrm{i}\omega _{x}x}\mathrm{d}{x}} {\int _{-\infty }^{\infty }s(x)\mathrm{d}{x}} \right). \end{equation*}

Math split over two lines: If a double backslash is detected outside a \begin{...} \end{...} pair, the math code is wrapped in an AMSmath align environment:

\begin{align*} s_{\mathrm{out}}(x) & = s_{\mathrm{in}}(x') * s_\delta (x-x') \\ & = \int s_{\mathrm{in}}(x')s_\delta (x-x')\mathrm{d}x' \end{align*}

Cases ("manually", with matrix environment):

\begin{equation*} \mathrm{sgn}(x) = \left\{\begin{matrix} -1 & x<0\\ 1 & x>0 \end{matrix}\right. \end{equation*}

Cases with the AMSmath cases environment (not (yet) supported by HTML writers with --math-output=MathML):

\begin{equation*} \mathrm{sgn}(x) = \begin{cases} -1 & x<0\\ 1 & x>0 \end{cases} \end{equation*}
docutils-0.12/test/functional/expected/math_output_html.html0000664000175000017500000002735312341404260026437 0ustar engelbertengelbert00000000000000 Mathematics

Mathematics

Docutils supports inline math with the prefix or postfix :math: role specificator, n! + sin(x2n) and Ac = (π)/(4)d2, as well as displayed math via the math directive:

f(ϵ) = (1)/(1 + exp(ε)/(kBT))

Content may start on the first line of the directive, e.g.

N = (number of apples)/(7)

Equations can be labeled with a reference name using the :name: option. See eq:M and eq:schrödinger below.

The determinant of the matrix

M =  a b c d

is |M| = ad − bc.

More than one display math block can be put in one math directive. For example, the following sum and integral with limits:

10xndx = (1)/(n + 1)
mn = 1n = (m(m + 1))/(2)

LaTeX-supported Unicode math symbols can be used in math roles and directives:

The Schrödinger equation

i()/(t)Ψ = Ψ, 

with the wave function Ψ, describes how the quantum state of a physical system changes in time.

Math-Accents:
\acute{a} \dot{t} γ̂ \hat{\gamma}
\grave{a} \ddot{t} α̃ \tilde{\alpha}
\breve{x} t⃛ \dddot{t} ı⃗ \vec{\imath}
\check{a} a \bar{a} R⃗ \vec{R}

Modulation Transfer Function:

MTF = ||(ℱ{s(x)})/(ℱ{s(x)}|ωx = 0)|| =  abs( − ∞s(x)eiωxxdx)/( − ∞s(x)dx).

Math split over two lines: If a double backslash is detected outside a \begin{...} \end{...} pair, the math code is wrapped in an AMSmath align environment:

sout(x)  = sin(x’)*sδ(x − x’)  = sin(x’)sδ(x − x’)dx

Cases ("manually", with matrix environment):

sgn(x) =   − 1 x < 0 1 x > 0

Cases with the AMSmath cases environment (not (yet) supported by HTML writers with --math-output=MathML):

sgn(x) =   − 1  x < 0        1  x > 0 
docutils-0.12/test/functional/expected/latex_babel.tex0000664000175000017500000000446412076016516025146 0ustar engelbertengelbert00000000000000\documentclass[a4paper]{article} % generated by Docutils \usepackage{fixltx2e} % LaTeX patches, \textsubscript \usepackage{cmap} % fix search and cut-and-paste in Acrobat \usepackage{ifthen} \usepackage[T1]{fontenc} \usepackage[utf8]{inputenc} \usepackage[basque,esperanto,estonian,galician,ngerman,english]{babel} \AtBeginDocument{\shorthandoff{.<>}} \deactivatetilden % restore ~ in Galician \makeatletter \addto\extrasestonian{\bbl@deactivate{~}} \makeatother \makeatletter \addto\extrasbasque{\bbl@deactivate{~}} \makeatother %%% Custom LaTeX preamble % PDF Standard Fonts \usepackage{mathptmx} % Times \usepackage[scaled=.90]{helvet} \usepackage{courier} %%% User specified packages and stylesheets %%% Fallback definitions for Docutils-specific commands % hyperlinks: \ifthenelse{\isundefined{\hypersetup}}{ \usepackage[colorlinks=true,linkcolor=blue,urlcolor=blue]{hyperref} \urlstyle{same} % normal text font (alternatives: tt, rm, sf) }{} %%% Body \begin{document} The \href{http://www.ctan.org/packages/babel}{babel} package introduces the concept of \textquotedbl{}shorthands\textquotedbl{}: additional characters that introduce a latex macro. Most common is the active double quote (\textquotedbl{}). Problematic is the tilde character (\textasciitilde{}) which is regularely used for no-break spaces but redefined by some language definition files: English: 'an' \textquotedbl{}active\textquotedbl{}-quote, \textasciicircum{}circumflex, and~no-break~spaces \foreignlanguage{basque}{Basque: 'an' \textquotedbl{}active\textquotedbl{}-quote, \textasciicircum{}circumflex, and~no-break~spaces} \foreignlanguage{esperanto}{Esperanto: 'an' \textquotedbl{}active\textquotedbl{}-quote, \textasciicircum{}circumflex, and~no-break~spaces} \foreignlanguage{estonian}{Estonian: 'an' \textquotedbl{}active\textquotedbl{}-quote, \textasciicircum{}circumflex, and~no-break~spaces} \foreignlanguage{galician}{Galician: 'an' \textquotedbl{}active\textquotedbl{}-quote, \textasciicircum{}circumflex, and~no-break~spaces} \foreignlanguage{ngerman}{German: 'an' \textquotedbl{}active\textquotedbl{}-quote, \textasciicircum{}circumflex, and~no-break~spaces} Spanish: option clash with Galician! % .. class:: language-es % % Spanish: 'an' "active"-quote, ^circumflex, and no-break spaces \end{document} docutils-0.12/test/functional/expected/ui/0000775000175000017500000000000012356234260022566 5ustar engelbertengelbert00000000000000docutils-0.12/test/functional/expected/ui/small-black/0000775000175000017500000000000012356234260024750 5ustar engelbertengelbert00000000000000docutils-0.12/test/functional/expected/ui/small-black/blank.gif0000664000175000017500000000006110345734741026530 0ustar engelbertengelbert00000000000000GIF89a!,T;docutils-0.12/test/functional/expected/ui/small-black/framing.css0000664000175000017500000000165510345734741027121 0ustar engelbertengelbert00000000000000/* This file has been placed in the public domain. */ /* The following styles size, place, and layer the slide components. Edit these if you want to change the overall slide layout. The commented lines can be uncommented (and modified, if necessary) to help you with the rearrangement process. */ /* target = 1024x768 */ div#header, div#footer, .slide {width: 100%; top: 0; left: 0;} div#footer {top: auto; bottom: 0; height: 2.5em; z-index: 5;} .slide {top: 0; width: 92%; padding: 1em 4% 0 4%; z-index: 2;} div#controls {left: 50%; bottom: 0; width: 50%; z-index: 100;} div#controls form {position: absolute; bottom: 0; right: 0; width: 100%; margin: 0;} #currentSlide {position: absolute; width: 10%; left: 45%; bottom: 1em; z-index: 10;} html>body #currentSlide {position: fixed;} /* div#header {background: #FCC;} div#footer {background: #CCF;} div#controls {background: #BBD;} div#currentSlide {background: #FFC;} */ docutils-0.12/test/functional/expected/ui/small-black/opera.css0000664000175000017500000000040510345734741026574 0ustar engelbertengelbert00000000000000/* This file has been placed in the public domain. */ /* DO NOT CHANGE THESE unless you really want to break Opera Show */ .slide { visibility: visible !important; position: static !important; page-break-before: always; } #slide0 {page-break-before: avoid;} docutils-0.12/test/functional/expected/ui/small-black/slides.css0000664000175000017500000000043310345734741026752 0ustar engelbertengelbert00000000000000/* This file has been placed in the public domain. */ /* required to make the slide show run at all */ @import url(s5-core.css); /* sets basic placement and size of slide components */ @import url(framing.css); /* styles that make the slides look good */ @import url(pretty.css); docutils-0.12/test/functional/expected/ui/small-black/iepngfix.htc0000664000175000017500000000225210345734741027267 0ustar engelbertengelbert00000000000000 docutils-0.12/test/functional/expected/ui/small-black/print.css0000664000175000017500000000146210347555440026625 0ustar engelbertengelbert00000000000000/* This file has been placed in the public domain. */ /* The following rule is necessary to have all slides appear in print! DO NOT REMOVE IT! */ .slide, ul {page-break-inside: avoid; visibility: visible !important;} h1 {page-break-after: avoid;} body {font-size: 12pt; background: white;} * {color: black;} #slide0 h1 {font-size: 200%; border: none; margin: 0.5em 0 0.25em;} #slide0 h3 {margin: 0; padding: 0;} #slide0 h4 {margin: 0 0 0.5em; padding: 0;} #slide0 {margin-bottom: 3em;} #header {display: none;} #footer h1 {margin: 0; border-bottom: 1px solid; color: gray; font-style: italic;} #footer h2, #controls {display: none;} .print {display: inline ! important;} /* The following rule keeps the layout stuff out of print. Remove at your own risk! */ .layout, .layout * {display: none !important;} docutils-0.12/test/functional/expected/ui/small-black/outline.css0000664000175000017500000000121010347555440027137 0ustar engelbertengelbert00000000000000/* This file has been placed in the public domain. */ /* Don't change this unless you want the layout stuff to show up in the outline view! */ .layout div, #footer *, #controlForm * {display: none;} #footer, #controls, #controlForm, #navLinks, #toggle { display: block; visibility: visible; margin: 0; padding: 0;} #toggle {float: right; padding: 0.5em;} html>body #toggle {position: fixed; top: 0; right: 0;} /* making the outline look pretty-ish */ #slide0 h1, #slide0 h2, #slide0 h3, #slide0 h4 {border: none; margin: 0;} #toggle {border: 1px solid; border-width: 0 0 1px 1px; background: #FFF;} .outline {display: inline ! important;} docutils-0.12/test/functional/expected/ui/small-black/slides.js0000664000175000017500000003670410357271726026612 0ustar engelbertengelbert00000000000000// S5 v1.1 slides.js -- released into the Public Domain // Modified for Docutils (http://docutils.sf.net) by David Goodger // // Please see http://www.meyerweb.com/eric/tools/s5/credits.html for // information about all the wonderful and talented contributors to this code! var undef; var slideCSS = ''; var snum = 0; var smax = 1; var slideIDs = new Array(); var incpos = 0; var number = undef; var s5mode = true; var defaultView = 'slideshow'; var controlVis = 'visible'; var isIE = navigator.appName == 'Microsoft Internet Explorer' ? 1 : 0; var isOp = navigator.userAgent.indexOf('Opera') > -1 ? 1 : 0; var isGe = navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('Safari') < 1 ? 1 : 0; function hasClass(object, className) { if (!object.className) return false; return (object.className.search('(^|\\s)' + className + '(\\s|$)') != -1); } function hasValue(object, value) { if (!object) return false; return (object.search('(^|\\s)' + value + '(\\s|$)') != -1); } function removeClass(object,className) { if (!object) return; object.className = object.className.replace(new RegExp('(^|\\s)'+className+'(\\s|$)'), RegExp.$1+RegExp.$2); } function addClass(object,className) { if (!object || hasClass(object, className)) return; if (object.className) { object.className += ' '+className; } else { object.className = className; } } function GetElementsWithClassName(elementName,className) { var allElements = document.getElementsByTagName(elementName); var elemColl = new Array(); for (var i = 0; i< allElements.length; i++) { if (hasClass(allElements[i], className)) { elemColl[elemColl.length] = allElements[i]; } } return elemColl; } function isParentOrSelf(element, id) { if (element == null || element.nodeName=='BODY') return false; else if (element.id == id) return true; else return isParentOrSelf(element.parentNode, id); } function nodeValue(node) { var result = ""; if (node.nodeType == 1) { var children = node.childNodes; for (var i = 0; i < children.length; ++i) { result += nodeValue(children[i]); } } else if (node.nodeType == 3) { result = node.nodeValue; } return(result); } function slideLabel() { var slideColl = GetElementsWithClassName('*','slide'); var list = document.getElementById('jumplist'); smax = slideColl.length; for (var n = 0; n < smax; n++) { var obj = slideColl[n]; var did = 'slide' + n.toString(); if (obj.getAttribute('id')) { slideIDs[n] = obj.getAttribute('id'); } else { obj.setAttribute('id',did); slideIDs[n] = did; } if (isOp) continue; var otext = ''; var menu = obj.firstChild; if (!menu) continue; // to cope with empty slides while (menu && menu.nodeType == 3) { menu = menu.nextSibling; } if (!menu) continue; // to cope with slides with only text nodes var menunodes = menu.childNodes; for (var o = 0; o < menunodes.length; o++) { otext += nodeValue(menunodes[o]); } list.options[list.length] = new Option(n + ' : ' + otext, n); } } function currentSlide() { var cs; var footer_nodes; var vis = 'visible'; if (document.getElementById) { cs = document.getElementById('currentSlide'); footer_nodes = document.getElementById('footer').childNodes; } else { cs = document.currentSlide; footer = document.footer.childNodes; } cs.innerHTML = '' + snum + '<\/span> ' + '\/<\/span> ' + '' + (smax-1) + '<\/span>'; if (snum == 0) { vis = 'hidden'; } cs.style.visibility = vis; for (var i = 0; i < footer_nodes.length; i++) { if (footer_nodes[i].nodeType == 1) { footer_nodes[i].style.visibility = vis; } } } function go(step) { if (document.getElementById('slideProj').disabled || step == 0) return; var jl = document.getElementById('jumplist'); var cid = slideIDs[snum]; var ce = document.getElementById(cid); if (incrementals[snum].length > 0) { for (var i = 0; i < incrementals[snum].length; i++) { removeClass(incrementals[snum][i], 'current'); removeClass(incrementals[snum][i], 'incremental'); } } if (step != 'j') { snum += step; lmax = smax - 1; if (snum > lmax) snum = lmax; if (snum < 0) snum = 0; } else snum = parseInt(jl.value); var nid = slideIDs[snum]; var ne = document.getElementById(nid); if (!ne) { ne = document.getElementById(slideIDs[0]); snum = 0; } if (step < 0) {incpos = incrementals[snum].length} else {incpos = 0;} if (incrementals[snum].length > 0 && incpos == 0) { for (var i = 0; i < incrementals[snum].length; i++) { if (hasClass(incrementals[snum][i], 'current')) incpos = i + 1; else addClass(incrementals[snum][i], 'incremental'); } } if (incrementals[snum].length > 0 && incpos > 0) addClass(incrementals[snum][incpos - 1], 'current'); ce.style.visibility = 'hidden'; ne.style.visibility = 'visible'; jl.selectedIndex = snum; currentSlide(); number = 0; } function goTo(target) { if (target >= smax || target == snum) return; go(target - snum); } function subgo(step) { if (step > 0) { removeClass(incrementals[snum][incpos - 1],'current'); removeClass(incrementals[snum][incpos], 'incremental'); addClass(incrementals[snum][incpos],'current'); incpos++; } else { incpos--; removeClass(incrementals[snum][incpos],'current'); addClass(incrementals[snum][incpos], 'incremental'); addClass(incrementals[snum][incpos - 1],'current'); } } function toggle() { var slideColl = GetElementsWithClassName('*','slide'); var slides = document.getElementById('slideProj'); var outline = document.getElementById('outlineStyle'); if (!slides.disabled) { slides.disabled = true; outline.disabled = false; s5mode = false; fontSize('1em'); for (var n = 0; n < smax; n++) { var slide = slideColl[n]; slide.style.visibility = 'visible'; } } else { slides.disabled = false; outline.disabled = true; s5mode = true; fontScale(); for (var n = 0; n < smax; n++) { var slide = slideColl[n]; slide.style.visibility = 'hidden'; } slideColl[snum].style.visibility = 'visible'; } } function showHide(action) { var obj = GetElementsWithClassName('*','hideme')[0]; switch (action) { case 's': obj.style.visibility = 'visible'; break; case 'h': obj.style.visibility = 'hidden'; break; case 'k': if (obj.style.visibility != 'visible') { obj.style.visibility = 'visible'; } else { obj.style.visibility = 'hidden'; } break; } } // 'keys' code adapted from MozPoint (http://mozpoint.mozdev.org/) function keys(key) { if (!key) { key = event; key.which = key.keyCode; } if (key.which == 84) { toggle(); return; } if (s5mode) { switch (key.which) { case 10: // return case 13: // enter if (window.event && isParentOrSelf(window.event.srcElement, 'controls')) return; if (key.target && isParentOrSelf(key.target, 'controls')) return; if(number != undef) { goTo(number); break; } case 32: // spacebar case 34: // page down case 39: // rightkey case 40: // downkey if(number != undef) { go(number); } else if (!incrementals[snum] || incpos >= incrementals[snum].length) { go(1); } else { subgo(1); } break; case 33: // page up case 37: // leftkey case 38: // upkey if(number != undef) { go(-1 * number); } else if (!incrementals[snum] || incpos <= 0) { go(-1); } else { subgo(-1); } break; case 36: // home goTo(0); break; case 35: // end goTo(smax-1); break; case 67: // c showHide('k'); break; } if (key.which < 48 || key.which > 57) { number = undef; } else { if (window.event && isParentOrSelf(window.event.srcElement, 'controls')) return; if (key.target && isParentOrSelf(key.target, 'controls')) return; number = (((number != undef) ? number : 0) * 10) + (key.which - 48); } } return false; } function clicker(e) { number = undef; var target; if (window.event) { target = window.event.srcElement; e = window.event; } else target = e.target; if (target.href != null || hasValue(target.rel, 'external') || isParentOrSelf(target, 'controls') || isParentOrSelf(target,'embed') || isParentOrSelf(target, 'object')) return true; if (!e.which || e.which == 1) { if (!incrementals[snum] || incpos >= incrementals[snum].length) { go(1); } else { subgo(1); } } } function findSlide(hash) { var target = document.getElementById(hash); if (target) { for (var i = 0; i < slideIDs.length; i++) { if (target.id == slideIDs[i]) return i; } } return null; } function slideJump() { if (window.location.hash == null || window.location.hash == '') { currentSlide(); return; } if (window.location.hash == null) return; var dest = null; dest = findSlide(window.location.hash.slice(1)); if (dest == null) { dest = 0; } go(dest - snum); } function fixLinks() { var thisUri = window.location.href; thisUri = thisUri.slice(0, thisUri.length - window.location.hash.length); var aelements = document.getElementsByTagName('A'); for (var i = 0; i < aelements.length; i++) { var a = aelements[i].href; var slideID = a.match('\#.+'); if ((slideID) && (slideID[0].slice(0,1) == '#')) { var dest = findSlide(slideID[0].slice(1)); if (dest != null) { if (aelements[i].addEventListener) { aelements[i].addEventListener("click", new Function("e", "if (document.getElementById('slideProj').disabled) return;" + "go("+dest+" - snum); " + "if (e.preventDefault) e.preventDefault();"), true); } else if (aelements[i].attachEvent) { aelements[i].attachEvent("onclick", new Function("", "if (document.getElementById('slideProj').disabled) return;" + "go("+dest+" - snum); " + "event.returnValue = false;")); } } } } } function externalLinks() { if (!document.getElementsByTagName) return; var anchors = document.getElementsByTagName('a'); for (var i=0; i' + '
- Pseudo-XML::
A Title <paragraph> A paragraph. -------------------- Many of the element reference sections below are marked "_`to be completed`". Please help complete this document by contributing to its writing. ``abbreviation`` ================ `To be completed`_. ``acronym`` =========== `To be completed`_. ``address`` =========== The ``address`` element holds the surface mailing address information for the author (individual or group) of the document, or a third-party contact address. Its structure is identical to that of the literal_block_ element: whitespace is significant, especially newlines. Details ------- :Category: `Bibliographic Elements`_ :Parents: The following elements may contain ``address``: docinfo_, authors_ :Children: ``address`` elements contain text data plus `inline elements`_. :Analogues: ``address`` is analogous to the DocBook "address" element. :Processing: As with the literal_block_ element, newlines and other whitespace is significant and must be preserved. However, a monospaced typeface need not be used. See also docinfo_. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``address`` element contains the `common attributes`_ (ids_, names_, dupnames_, source_, and classes_), plus `xml:space`_. :Parameter Entities: The `%bibliographic.elements;`_ parameter entity directly includes ``address``. Examples -------- reStructuredText_ source:: Document Title ============== :Address: 123 Example Ave. Example, EX Complete pseudo-XML_ result after parsing and applying transforms:: <document ids="document-title" names="document title"> <title> Document Title <docinfo> <address> 123 Example Ave. Example, EX See docinfo_ for a more complete example, including processing context. ``admonition`` ============== This element is a generic, titled admonition. Also see the specific admonition elements Docutils offers (in alphabetical order): caution_, danger_, error_, hint_, important_, note_, tip_, warning_. Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``admonition``. :Children: ``admonition`` elements begin with a title_ and may contain one or more `body elements`_. :Analogues: ``admonition`` has no direct analogues in common DTDs. It can be emulated with primitives and type effects. :Processing: Rendered distinctly (inset and/or in a box, etc.). Content Model ------------- .. parsed-literal:: (title_, (`%body.elements;`_)+) :Attributes: The ``admonition`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``admonition``. The `%structure.model;`_ parameter entity indirectly includes ``admonition``. Examples -------- reStructuredText source:: .. admonition:: And, by the way... You can make up your own admonition too. Pseudo-XML_ fragment from simple parsing:: <admonition class="admonition-and-by-the-way"> <title> And, by the way... <paragraph> You can make up your own admonition too. ``attention`` ============= The ``attention`` element is an admonition, a distinctive and self-contained notice. Also see the other admonition elements Docutils offers (in alphabetical order): caution_, danger_, error_, hint_, important_, note_, tip_, warning_, and the generic admonition_. Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``attention``. :Children: ``attention`` elements contain one or more `body elements`_. :Analogues: ``attention`` has no direct analogues in common DTDs. It can be emulated with primitives and type effects. :Processing: Rendered distinctly (inset and/or in a box, etc.), with the generated title "Attention!" (or similar). Content Model ------------- .. parsed-literal:: (`%body.elements;`_)+ :Attributes: The ``attention`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``attention``. The `%structure.model;`_ parameter entity indirectly includes ``attention``. Examples -------- reStructuredText source:: .. Attention:: All your base are belong to us. Pseudo-XML_ fragment from simple parsing:: <attention> <paragraph> All your base are belong to us. ``attribution`` =============== `To be completed`_. ``author`` ========== The ``author`` element holds the name of the author of the document. Details ------- :Category: `Bibliographic Elements`_ :Parents: The following elements may contain ``author``: docinfo_, authors_ :Children: ``author`` elements may contain text data plus `inline elements`_. :Analogues: ``author`` is analogous to the DocBook "author" element. :Processing: See docinfo_. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``author`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%bibliographic.elements;`_ parameter entity directly includes ``author``. Examples -------- reStructuredText_ source:: Document Title ============== :Author: J. Random Hacker Complete pseudo-XML_ result after parsing and applying transforms:: <document ids="document-title" names="document title"> <title> Document Title <docinfo> <author> J. Random Hacker See docinfo_ for a more complete example, including processing context. ``authors`` =========== The ``authors`` element is a container for author information for documents with multiple authors. Details ------- :Category: `Bibliographic Elements`_ :Parents: Only the docinfo_ element contains ``authors``. :Children: ``authors`` elements may contain the following elements: author_, organization_, address_, contact_ :Analogues: ``authors`` is analogous to the DocBook "authors" element. :Processing: See docinfo_. Content Model ------------- .. parsed-literal:: ((author_, organization_?, address_?, contact_?)+) :Attributes: The ``authors`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%bibliographic.elements;`_ parameter entity directly includes ``authors``. Examples -------- reStructuredText_ source:: Document Title ============== :Authors: J. Random Hacker; Jane Doe Complete pseudo-XML_ result after parsing and applying transforms:: <document ids="document-title" names="document title"> <title> Document Title <docinfo> <authors> <author> J. Random Hacker <author> Jane Doe In reStructuredText, multiple author's names are separated with semicolons (";") or commas (","); semicolons take precedence. There is currently no way to represent the author's organization, address, or contact in a reStructuredText "Authors" field. See docinfo_ for a more complete example, including processing context. ``block_quote`` =============== The ``block_quote`` element is used for quotations set off from the main text (standalone). Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``block_quote``. :Children: ``block_quote`` elements contain `body elements`_ followed by an optional attribution_ element. :Analogues: ``block_quote`` is analogous to the "blockquote" element in both HTML and DocBook. :Processing: ``block_quote`` elements serve to set their contents off from the main text, typically with indentation and/or other decoration. Content Model ------------- .. parsed-literal:: ((`%body.elements;`_)+, attribution_?) :Attributes: The ``block_quote`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``block_quote``. The `%structure.model;`_ parameter entity indirectly includes ``block_quote``. Examples -------- reStructuredText source:: As a great paleontologist once said, This theory, that is mine, is mine. -- Anne Elk (Miss) Pseudo-XML_ fragment from simple parsing:: <paragraph> As a great paleontologist once said, <block_quote> <paragraph> This theory, that is mine, is mine. <attribution> Anne Elk (Miss) ``bullet_list`` =============== The ``bullet_list`` element contains list_item_ elements which are uniformly marked with bullets. Bullets are typically simple dingbats (symbols) such as circles and squares. Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``bullet_list``. :Children: ``bullet_list`` elements contain one or more list_item_ elements. :Analogues: ``bullet_list`` is analogous to the HTML "ul" element and to the DocBook "itemizedlist" element. HTML's "ul" is short for "unordered list", which we consider to be a misnomer. "Unordered" implies that the list items may be randomly rearranged without affecting the meaning of the list. Bullet lists *are* often ordered; the ordering is simply left implicit. :Processing: Each list item should begin a new vertical block, prefaced by a bullet/dingbat. Content Model ------------- .. parsed-literal:: (list_item_ +) :Attributes: The ``bullet_list`` element contains the `common attributes`_ (ids_, names_, dupnames_, source_, and classes_), plus bullet_. ``bullet`` is used to record the style of bullet from the input data. In documents processed from reStructuredText_, it contains one of "-", "+", or "*". It may be ignored in processing. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``bullet_list``. The `%structure.model;`_ parameter entity indirectly includes ``bullet_list``. Examples -------- reStructuredText_ source:: - Item 1, paragraph 1. Item 1, paragraph 2. - Item 2. Pseudo-XML_ fragment from simple parsing:: <bullet_list bullet="-"> <list_item> <paragraph> Item 1, paragraph 1. <paragraph> Item 1, paragraph 2. <list_item> <paragraph> Item 2. See list_item_ for another example. ``caption`` =========== `To be completed`_. ``caution`` =========== The ``caution`` element is an admonition, a distinctive and self-contained notice. Also see the other admonition elements Docutils offers (in alphabetical order): attention_, danger_, error_, hint_, important_, note_, tip_, warning_, and the generic admonition_. Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``caution``. :Children: ``caution`` elements contain one or more `body elements`_. :Analogues: ``caution`` is analogous to the DocBook "caution" element. :Processing: Rendered distinctly (inset and/or in a box, etc.), with the generated title "Caution" (or similar). Content Model ------------- .. parsed-literal:: (`%body.elements;`_)+ :Attributes: The ``caution`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``caution``. The `%structure.model;`_ parameter entity indirectly includes ``caution``. Examples -------- reStructuredText source:: .. Caution:: Don't take any wooden nickels. Pseudo-XML_ fragment from simple parsing:: <caution> <paragraph> Don't take any wooden nickels. ``citation`` ============ `To be completed`_. ``citation_reference`` ====================== `To be completed`_. ``classifier`` ============== The ``classifier`` element contains the classification or type of the term_ being defined in a definition_list_. For example, it can be used to indicate the type of a variable. Details ------- :Category: `Body Subelements`_ (simple) :Parents: Only the definition_list_item_ element contains ``classifier``. :Children: ``classifier`` elements may contain text data plus `inline elements`_. :Analogues: ``classifier`` has no direct analogues in common DTDs. It can be emulated with primitives or type effects. :Processing: See definition_list_item_. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``classifier`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- Here is a hypothetical data dictionary. reStructuredText_ source:: name : string Customer name. i : int Temporary index variable. Pseudo-XML_ fragment from simple parsing:: <definition_list> <definition_list_item> <term> name <classifier> string <definition> <paragraph> Customer name. <definition_list_item> <term> i <classifier> int <definition> <paragraph> Temporary index variable. ``colspec`` =========== `To be completed`_. ``comment`` =========== `To be completed`_. ``compound`` ============ `To be completed`_. ``contact`` =========== The ``contact`` element holds contact information for the author (individual or group) of the document, or a third-party contact. It is typically used for an email or web address. Details ------- :Category: `Bibliographic Elements`_ :Parents: The following elements may contain ``contact``: docinfo_, authors_ :Children: ``contact`` elements may contain text data plus `inline elements`_. :Analogues: ``contact`` is analogous to the DocBook "email" element. The HTML "address" element serves a similar purpose. :Processing: See docinfo_. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``contact`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%bibliographic.elements;`_ parameter entity directly includes ``contact``. Examples -------- reStructuredText_ source:: Document Title ============== :Contact: jrh@example.com Complete pseudo-XML_ result after parsing and applying transforms:: <document ids="document-title" names="document title"> <title> Document Title <docinfo> <contact> <reference refuri="mailto:jrh@example.com"> jrh@example.com See docinfo_ for a more complete example, including processing context. ``container`` ============= `To be completed`_. ``copyright`` ============= The ``copyright`` element contains the document's copyright statement. Details ------- :Category: `Bibliographic Elements`_ :Parents: Only the docinfo_ element contains ``copyright``. :Children: ``copyright`` elements may contain text data plus `inline elements`_. :Analogues: ``copyright`` is analogous to the DocBook "copyright" element. :Processing: See docinfo_. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``copyright`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%bibliographic.elements;`_ parameter entity directly includes ``copyright``. Examples -------- reStructuredText_ source:: Document Title ============== :Copyright: This document has been placed in the public domain. Complete pseudo-XML_ result after parsing and applying transforms:: <document ids="document-title" names="document title"> <title> Document Title <docinfo> <copyright> This document has been placed in the public domain. See docinfo_ for a more complete example, including processing context. ``danger`` ========== The ``danger`` element is an admonition, a distinctive and self-contained notice. Also see the other admonition elements Docutils offers (in alphabetical order): attention_, caution_, error_, hint_, important_, note_, tip_, warning_, and the generic admonition_. Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``danger``. :Children: ``danger`` elements contain one or more `body elements`_. :Analogues: ``danger`` has no direct analogues in common DTDs. It can be emulated with primitives and type effects. :Processing: Rendered distinctly (inset and/or in a box, etc.), with the generated title "!DANGER!" (or similar). Content Model ------------- .. parsed-literal:: (`%body.elements;`_)+ :Attributes: The ``danger`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``danger``. The `%structure.model;`_ parameter entity indirectly includes ``danger``. Examples -------- reStructuredText source:: .. DANGER:: Mad scientist at work! Pseudo-XML_ fragment from simple parsing:: <danger> <paragraph> Mad scientist at work! ``date`` ======== The ``date`` element contains the date of publication, release, or last modification of the document. Details ------- :Category: `Bibliographic Elements`_ :Parents: Only the docinfo_ element contains ``date``. :Children: ``date`` elements may contain text data plus `inline elements`_. :Analogues: ``date`` is analogous to the DocBook "date" element. :Processing: Often used with the RCS/CVS keyword "Date". See docinfo_. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``date`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%bibliographic.elements;`_ parameter entity directly includes ``date``. Examples -------- reStructuredText_ source:: Document Title ============== :Date: 2002-08-20 Complete pseudo-XML_ result after parsing and applying transforms:: <document ids="document-title" names="document title"> <title> Document Title <docinfo> <date> 2002-08-20 See docinfo_ for a more complete example, including processing context. ``decoration`` ============== The ``decoration`` element is a container for header_ and footer_ elements and potential future extensions. These elements are used for notes, time/datestamp, processing information, etc. Details ------- :Category: `Structural Subelements`_ :Parents: Only the document_ element contains ``decoration``. :Children: ``decoration`` elements may contain `decorative elements`_. :Analogues: There are no direct analogies to ``decoration`` in HTML or in DocBook. Equivalents are typically constructed from primitives and/or generated by the processing system. :Processing: See the individual `decorative elements`_. Content Model ------------- .. parsed-literal:: (header_?, footer_?) Although the content model doesn't specifically require contents, no empty ``decoration`` elements are ever created. :Attributes: The ``decoration`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- reStructuredText_ source:: A paragraph. Complete pseudo-XML_ result after parsing and applying transforms, assuming that the datestamp command-line option or configuration setting has been supplied:: <document> <decoration> <footer> <paragraph> Generated on: 2002-08-20. <paragraph> A paragraph. ``definition`` ============== The ``definition`` element is a container for the body elements used to define a term_ in a definition_list_. Details ------- :Category: `Body Subelements`_ (compound) :Parents: Only definition_list_item_ elements contain ``definition``. :Children: ``definition`` elements may contain `body elements`_. :Analogues: ``definition`` is analogous to the HTML "dd" element and to the DocBook "listitem" element (inside a "variablelistentry" element). :Processing: See definition_list_item_. Content Model ------------- .. parsed-literal:: (`%body.elements;`_)+ :Attributes: The ``definition`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- See the examples for the definition_list_, definition_list_item_, and classifier_ elements. ``definition_list`` =================== The ``definition_list`` element contains a list of terms and their definitions. It can be used for glossaries or dictionaries, to describe or classify things, for dialogues, or to itemize subtopics (such as in this reference). Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``definition_list``. :Children: ``definition_list`` elements contain one or more definition_list_item_ elements. :Analogues: ``definition_list`` is analogous to the HTML "dl" element and to the DocBook "variablelist" element. :Processing: See definition_list_item_. Content Model ------------- .. parsed-literal:: (definition_list_item_ +) :Attributes: The ``definition_list`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``definition_list``. The `%structure.model;`_ parameter entity indirectly includes ``definition_list``. Examples -------- reStructuredText_ source:: Term Definition. Term : classifier The ' : ' indicates a classifier in definition list item terms only. Pseudo-XML_ fragment from simple parsing:: <definition_list> <definition_list_item> <term> Term <definition> <paragraph> Definition. <definition_list_item> <term> Term <classifier> classifier <definition> <paragraph> The ' : ' indicates a classifier in definition list item terms only. See definition_list_item_ and classifier_ for further examples. ``definition_list_item`` ======================== The ``definition_list_item`` element contains a single term_/definition_ pair (with optional classifier_). Details ------- :Category: `Body Subelements`_ (compound) :Parents: Only the definition_list_ element contains ``definition_list_item``. :Children: ``definition_list_item`` elements each contain a single term_, an optional classifier_, and a definition_. :Analogues: ``definition_list_item`` is analogous to the DocBook "variablelistentry" element. :Processing: The optional classifier_ can be rendered differently from the term_. They should be separated visually, typically by spaces plus a colon or dash. Content Model ------------- .. parsed-literal:: (term_, classifier_?, definition_) :Attributes: The ``definition_list_item`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- reStructuredText_ source:: Tyrannosaurus Rex : carnivore Big and scary; the "Tyrant King". Brontosaurus : herbivore All brontosauruses are thin at one end, much much thicker in the middle and then thin again at the far end. -- Anne Elk (Miss) Pseudo-XML_ fragment from simple parsing:: <definition_list> <definition_list_item> <term> Tyrannosaurus Rex <classifier> carnivore <definition> <paragraph> Big and scary; the "Tyrant King". <definition_list_item> <term> Brontosaurus <classifier> herbivore <definition> <paragraph> All brontosauruses are thin at one end, much much thicker in the middle and then thin again at the far end. <paragraph> -- Anne Elk (Miss) See definition_list_ and classifier_ for further examples. ``description`` =============== The ``description`` element contains body elements, describing the purpose or effect of a command-line option or group of options. Details ------- :Category: `Body Subelements`_ :Parents: Only the option_list_item_ element contains ``description``. :Children: ``description`` elements may contain `body elements`_. :Analogues: ``description`` has no direct analogues in common DTDs. :Processing: See option_list_. Content Model ------------- .. parsed-literal:: (`%body.elements;`_)+ :Attributes: The ``description`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- See the examples for the option_list_ element. ``docinfo`` =========== The ``docinfo`` element is a container for document bibliographic data, or meta-data (data about the document). It corresponds to the front matter of a book, such as the title page and copyright page. Details ------- :Category: `Structural Subelements`_ :Parents: Only the document_ element contains ``docinfo``. :Children: ``docinfo`` elements contain `bibliographic elements`_. :Analogues: ``docinfo`` is analogous to DocBook "info" elements ("bookinfo" etc.). There are no directly analogous HTML elements; the "meta" element carries some of the same information, albeit invisibly. :Processing: The ``docinfo`` element may be rendered as a two-column table or in other styles. It may even be invisible or omitted from the processed output. Meta-data may be extracted from ``docinfo`` children; for example, HTML ``<meta>`` tags may be constructed. When Docutils_ transforms a reStructuredText_ field_list_ into a ``docinfo`` element (see the examples below), RCS/CVS keywords are normally stripped from simple (one paragraph) field bodies. For complete details, please see `RCS Keywords`_ in the `reStructuredText Markup Specification`_. .. _RCS Keywords: rst/restructuredtext.html#rcs-keywords Content Model ------------- .. parsed-literal:: (`%bibliographic.elements;`_)+ :Attributes: The ``docinfo`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- Docinfo is represented in reStructuredText_ by a field_list_ in a bibliographic context: the first non-comment element of a document_, after any document title_/subtitle_. The field list is transformed into a ``docinfo`` element and its children by a transform. Source:: Docinfo Example =============== :Author: J. Random Hacker :Contact: jrh@example.com :Date: 2002-08-18 :Status: Work In Progress :Version: 1 :Filename: $RCSfile$ :Copyright: This document has been placed in the public domain. Complete pseudo-XML_ result after parsing and applying transforms:: <document ids="docinfo-example" names="docinfo example"> <title> Docinfo Example <docinfo> <author> J. Random Hacker <contact> <reference refuri="mailto:jrh@example.com"> jrh@example.com <date> 2002-08-18 <status> Work In Progress <version> 1 <field> <field_name> Filename <field_body> <paragraph> doctree.txt <copyright> This document has been placed in the public domain. Note that "Filename" is a non-standard ``docinfo`` field, so becomes a generic ``field`` element. Also note that the "RCSfile" keyword syntax has been stripped from the "Filename" data. See field_list_ for an example in a non-bibliographic context. Also see the individual examples for the various `bibliographic elements`_. ``doctest_block`` ================= The ``doctest_block`` element is a Python-specific variant of literal_block_. It is a block of text where line breaks and whitespace are significant and must be preserved. ``doctest_block`` elements are used for interactive Python interpreter sessions, which are distinguished by their input prompt: ``>>>``. They are meant to illustrate usage by example, and provide an elegant and powerful testing environment via the `doctest module`_ in the Python standard library. .. _doctest module: http://www.python.org/doc/current/lib/module-doctest.html Details ------- :Category: `Simple Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``doctest_block``. :Children: ``doctest_block`` elements may contain text data plus `inline elements`_. :Analogues: ``doctest_block`` is analogous to the HTML "pre" element and to the DocBook "programlisting" and "screen" elements. :Processing: As with literal_block_, ``doctest_block`` elements are typically rendered in a monospaced typeface. It is crucial that all whitespace and line breaks are preserved in the rendered form. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``doctest_block`` element contains the `common attributes`_ (ids_, names_, dupnames_, source_, and classes_), plus `xml:space`_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``doctest_block``. The `%structure.model;`_ parameter entity indirectly includes ``doctest_block``. Examples -------- reStructuredText source:: This is an ordinary paragraph. >>> print 'this is a Doctest block' this is a Doctest block Pseudo-XML_ fragment from simple parsing:: <paragraph> This is an ordinary paragraph. <doctest_block xml:space="preserve"> >>> print 'this is a Doctest block' this is a Doctest block ``document`` ============ The ``document`` element is the root (topmost) element of the Docutils document tree. ``document`` is the direct or indirect ancestor of every other element in the tree. It encloses the entire document tree. It is the starting point for a document. Details ------- :Category: `Structural Elements`_ :Parents: The ``document`` element has no parents. :Children: ``document`` elements may contain `structural subelements`_, `structural elements`_, and `body elements`_. :Analogues: ``document`` is analogous to the HTML "html" element and to several DocBook elements such as "book". Content Model ------------- .. parsed-literal:: ( (title_, subtitle_?)?, decoration_?, (docinfo_, transition_?)?, `%structure.model;`_ ) Depending on the source of the data and the stage of processing, the "document" may not initially contain a "title". A document title is not directly representable in reStructuredText_. Instead, a lone top-level section may have its title promoted to become the document title_, and similarly for a lone second-level (sub)section's title to become the document subtitle_. The contents of "decoration_" may be specified in a document, constructed programmatically, or both. The "docinfo_" may be transformed from an initial field_list_. See the `%structure.model;`_ parameter entity for details of the body of a ``document``. :Attributes: The ``document`` element contains the `common attributes`_ (ids_, names_, dupnames_, source_, and classes_), plus an optional title__ attribute which stores the document title metadata. __ `title (attribute)`_ Examples -------- reStructuredText_ source:: A Title ======= A paragraph. Complete pseudo-XML_ result from simple parsing:: <document> <section ids="a-title" names="a title"> <title> A Title <paragraph> A paragraph. After applying transforms, the section title is promoted to become the document title:: <document ids="a-title" names="a title"> <title> A Title <paragraph> A paragraph. ``emphasis`` ============ `To be completed`_. ``entry`` ========= `To be completed`_. ``enumerated_list`` =================== The ``enumerated_list`` element contains list_item_ elements which are uniformly marked with enumerator labels. Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``enumerated_list``. :Children: ``enumerated_list`` elements contain one or more list_item_ elements. :Analogues: ``enumerated_list`` is analogous to the HTML "ol" element and to the DocBook "orderedlist" element. :Processing: Each list item should begin a new vertical block, prefaced by a enumeration marker (such as "1."). Content Model ------------- .. parsed-literal:: (list_item_ +) :Attributes: The ``enumerated_list`` element contains the `common attributes`_ (ids_, names_, dupnames_, source_, and classes_), plus enumtype_, prefix_, suffix_, and start_. ``enumtype`` is used to record the intended enumeration sequence, one of "arabic" (1, 2, 3, ...), "loweralpha" (a, b, c, ..., z), "upperalpha" (A, B, C, ..., Z), "lowerroman" (i, ii, iii, iv, ..., mmmmcmxcix [4999]), or "upperroman" (I, II, III, IV, ..., MMMMCMXCIX [4999]). ``prefix`` stores the formatting characters used before the enumerator. In documents originating from reStructuredText_ data, it will contain either "" (empty string) or "(" (left parenthesis). It may or may not affect processing. ``suffix`` stores the formatting characters used after the enumerator. In documents originating from reStructuredText_ data, it will contain either "." (period) or ")" (right parenthesis). Depending on the capabilities of the output format, this attribute may or may not affect processing. ``start`` contains the ordinal value of the first item in the list, in decimal. For lists beginning at value 1 ("1", "a", "A", "i", or "I"), this attribute may be omitted. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``enumerated_list``. The `%structure.model;`_ parameter entity indirectly includes ``enumerated_list``. Examples -------- reStructuredText_ source:: 1. Item 1. (A) Item A. (B) Item B. (C) Item C. 2. Item 2. Pseudo-XML_ fragment from simple parsing:: <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Item 1. <enumerated_list enumtype="upperalpha" prefix="(" suffix=")"> <list_item> <paragraph> Item A. <list_item> <paragraph> Item B. <list_item> <paragraph> Item C. <list_item> <paragraph> Item 2. See list_item_ for another example. ``error`` ========= The ``error`` element is an admonition, a distinctive and self-contained notice. Also see the other admonition elements Docutils offers (in alphabetical order): attention_, caution_, danger_, hint_, important_, note_, tip_, warning_, and the generic admonition_. Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``error``. :Children: ``error`` elements contain one or more `body elements`_. :Analogues: ``error`` has no direct analogues in common DTDs. It can be emulated with primitives and type effects. :Processing: Rendered distinctly (inset and/or in a box, etc.), with the generated title "Error" (or similar). Content Model ------------- .. parsed-literal:: (`%body.elements;`_)+ :Attributes: The ``error`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``error``. The `%structure.model;`_ parameter entity indirectly includes ``error``. Examples -------- reStructuredText source:: .. Error:: Does not compute. Pseudo-XML_ fragment from simple parsing:: <error> <paragraph> Does not compute. ``field`` ========= The ``field`` element contains a pair of field_name_ and field_body_ elements. Details ------- :Category: `Body Subelements`_ :Parents: The following elements may contain ``field``: docinfo_, field_list_ :Children: Each ``field`` element contains one field_name_ and one field_body_ element. :Analogues: ``field`` has no direct analogues in common DTDs. :Processing: See field_list_. Content Model ------------- .. parsed-literal:: (field_name_, field_body_) :Attributes: The ``field`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%bibliographic.elements;`_ parameter entity directly includes ``field``. Examples -------- See the examples for the field_list_ and docinfo_ elements. ``field_body`` ============== The ``field_body`` element contains body elements. It is analogous to a database field's data. Details ------- :Category: `Body Subelements`_ :Parents: Only the field_ element contains ``field_body``. :Children: ``field_body`` elements may contain `body elements`_. :Analogues: ``field_body`` has no direct analogues in common DTDs. :Processing: See field_list_. Content Model ------------- .. parsed-literal:: (`%body.elements;`_)* :Attributes: The ``field_body`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- See the examples for the field_list_ and docinfo_ elements. ``field_list`` ============== The ``field_list`` element contains two-column table-like structures resembling database records (label & data pairs). Field lists are often meant for further processing. In reStructuredText_, field lists are used to represent bibliographic fields (contents of the docinfo_ element) and directive options. Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``field_list``. :Children: ``field_list`` elements contain one or more field_ elements. :Analogues: ``field_list`` has no direct analogues in common DTDs. It can be emulated with primitives such as tables. :Processing: A ``field_list`` is typically rendered as a two-column list, where the first column contains "labels" (usually with a colon suffix). However, field lists are often used for extension syntax or special processing. Such structures do not survive as field lists to be rendered. Content Model ------------- .. parsed-literal:: (field_ +) :Attributes: The ``field_list`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``field_list``. The `%structure.model;`_ parameter entity indirectly includes ``field_list``. Examples -------- reStructuredText_ source:: :Author: Me :Version: 1 :Date: 2001-08-11 :Parameter i: integer Pseudo-XML_ fragment from simple parsing:: <field_list> <field> <field_name> Author <field_body> <paragraph> Me <field> <field_name> Version <field_body> <paragraph> 1 <field> <field_name> Date <field_body> <paragraph> 2001-08-11 <field> <field_name> Parameter i <field_body> <paragraph> integer ``field_name`` ============== The ``field_name`` element contains text; it is analogous to a database field's name. Details ------- :Category: `Body Subelements`_ (simple) :Parents: Only the field_ element contains ``field_name``. :Children: ``field_name`` elements may contain text data plus `inline elements`_. :Analogues: ``field_name`` has no direct analogues in common DTDs. :Processing: See field_list_. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``field_name`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- See the examples for the field_list_ and docinfo_ elements. ``figure`` ========== `To be completed`_. ``footer`` ========== The ``footer`` element is a container element whose contents are meant to appear at the bottom of a web page, or repeated at the bottom of every printed page. The ``footer`` element may contain processing information (datestamp, a link to Docutils_, etc.) as well as custom content. Details ------- :Category: `Decorative Elements`_ :Parents: Only the decoration_ element contains ``footer``. :Children: ``footer`` elements may contain `body elements`_. :Analogues: There are no direct analogies to ``footer`` in HTML or DocBook. Equivalents are typically constructed from primitives and/or generated by the processing system. Content Model ------------- .. parsed-literal:: (`%body.elements;`_)+ :Attributes: The ``footer`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- reStructuredText_ source:: A paragraph. Complete pseudo-XML_ result after parsing and applying transforms, assuming that the datestamp command-line option or configuration setting has been supplied:: <document> <decoration> <footer> <paragraph> Generated on: 2002-08-20. <paragraph> A paragraph. ``footnote`` ============ `To be completed`_. ``footnote_reference`` ====================== `To be completed`_. ``generated`` ============= Docutils wraps ``generated`` elements around text that is inserted (generated) by Docutils; i.e., text that was not in the document, like section numbers inserted by the "sectnum" directive. `To be completed`_. ``header`` ========== The ``header`` element is a container element whose contents are meant to appear at the top of a web page, or at the top of every printed page. Details ------- :Category: `Decorative Elements`_ :Parents: Only the decoration_ element contains ``header``. :Children: ``header`` elements may contain `body elements`_. :Analogues: There are no direct analogies to ``header`` in HTML or DocBook. Equivalents are typically constructed from primitives and/or generated by the processing system. Content Model ------------- .. parsed-literal:: (`%body.elements;`_)+ :Attributes: The ``header`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- reStructuredText source fragment:: .. header:: This space for rent. Pseudo-XML_ fragment from simple parsing:: <document> <decoration> <header> <paragraph> This space for rent. ``hint`` ======== The ``hint`` element is an admonition, a distinctive and self-contained notice. Also see the other admonition elements Docutils offers (in alphabetical order): attention_, caution_, danger_, error_, important_, note_, tip_, warning_, and the generic admonition_. Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``hint``. :Children: ``hint`` elements contain one or more `body elements`_. :Analogues: ``hint`` has no direct analogues in common DTDs. It can be emulated with primitives and type effects. :Processing: Rendered distinctly (inset and/or in a box, etc.), with the generated title "Hint" (or similar). Content Model ------------- .. parsed-literal:: (`%body.elements;`_)+ :Attributes: The ``hint`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``hint``. The `%structure.model;`_ parameter entity indirectly includes ``hint``. Examples -------- reStructuredText source:: .. Hint:: It's bigger than a bread box. Pseudo-XML_ fragment from simple parsing:: <hint> <paragraph> It's bigger than a bread box. ``image`` ========= `To be completed`_. ``important`` ============= The ``important`` element is an admonition, a distinctive and self-contained notice. Also see the other admonition elements Docutils offers (in alphabetical order): attention_, caution_, danger_, error_, hint_, note_, tip_, warning_, and the generic admonition_. Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``important``. :Children: ``important`` elements contain one or more `body elements`_. :Analogues: ``important`` is analogous to the DocBook "important" element. :Processing: Rendered distinctly (inset and/or in a box, etc.), with the generated title "Important" (or similar). Content Model ------------- .. parsed-literal:: (`%body.elements;`_)+ :Attributes: The ``important`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``important``. The `%structure.model;`_ parameter entity indirectly includes ``important``. Examples -------- reStructuredText source:: .. Important:: * Wash behind your ears. * Clean up your room. * Back up your data. * Call your mother. Pseudo-XML_ fragment from simple parsing:: <important> <bullet_list> <list_item> <paragraph> Wash behind your ears. <list_item> <paragraph> Clean up your room. <list_item> <paragraph> Back up your data. <list_item> <paragraph> Call your mother. ``inline`` ========== `To be completed`_. ``label`` ========= `To be completed`_. ``legend`` ========== `To be completed`_. ``line`` ======== The ``line`` element contains a single line of text, part of a `line_block`_. Details ------- :Category: `Body Subelements`_ (simple) :Parents: Only the `line_block`_ element contains ``line``. :Children: ``line`` elements may contain text data plus `inline elements`_. :Analogues: ``line`` has no direct analogues in common DTDs. It can be emulated with primitives or type effects. :Processing: See `line_block`_. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``line`` element contains the `common attributes`_ (ids_, names_, dupnames_, source_, and classes_), plus `xml:space`_. Examples -------- See `line_block`_. ``line_block`` ============== The ``line_block`` element contains a sequence of lines and nested line blocks. Line breaks (implied between elements) and leading whitespace (indicated by nesting) is significant and must be preserved. ``line_block`` elements are commonly used for verse and addresses. See `literal_block`_ for an alternative useful for program listings and interactive computer sessions. Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``line_block``. :Children: ``line_block`` elements may contain line_ elements and nested ``line_block`` elements. :Analogues: ``line_block`` is analogous to the DocBook "literallayout" element and to the HTML "pre" element (with modifications to typeface styles). :Processing: Unlike ``literal_block``, ``line_block`` elements are typically rendered in an ordinary text typeface. It is crucial that leading whitespace and line breaks are preserved in the rendered form. Content Model ------------- .. parsed-literal:: (line_ | line_block_)+ :Attributes: The ``line_block`` element contains the `common attributes`_ (ids_, names_, dupnames_, source_, and classes_), plus `xml:space`_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``line_block``. The `%structure.model;`_ parameter entity indirectly includes ``line_block``. Examples -------- reStructuredText uses a directive to indicate a ``line_block``. Example source:: Take it away, Eric the Orchestra Leader! | A one, two, a one two three four | | Half a bee, philosophically, | must, *ipso facto*, half not be. | But half the bee has got to be, | *vis a vis* its entity. D'you see? | | But can a bee be said to be | or not to be an entire bee, | when half the bee is not a bee, | due to some ancient injury? | | Singing... Pseudo-XML_ fragment from simple parsing:: <paragraph> Take it away, Eric the Orchestra Leader! <line_block> <line> A one, two, a one two three four <line> <line> Half a bee, philosophically, <line_block> <line> must, <emphasis> ipso facto , half not be. <line> But half the bee has got to be, <line_block> <line> <emphasis> vis a vis its entity. D'you see? <line> <line> But can a bee be said to be <line_block> <line> or not to be an entire bee, <line_block> <line> when half the bee is not a bee, <line_block> <line> due to some ancient injury? <line> <line> Singing... ``list_item`` ============= The ``list_item`` element is a container for the elements of a list item. Details ------- :Category: `Body Subelements`_ (compound) :Parents: The bullet_list_ and enumerated_list_ elements contain ``list_item``. :Children: ``list_item`` elements may contain `body elements`_. :Analogues: ``list_item`` is analogous to the HTML "li" element and to the DocBook "listitem" element. :Processing: See bullet_list_ or enumerated_list_. Content Model ------------- .. parsed-literal:: (`%body.elements;`_)* :Attributes: The ``list_item`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- reStructuredText_ source:: 1. Outer list, item 1. * Inner list, item 1. * Inner list, item 2. 2. Outer list, item 2. Pseudo-XML_ fragment from simple parsing:: <enumerated_list enumtype="arabic" prefix="" suffix="."> <list_item> <paragraph> Outer list, item 1. <bullet_list bullet="*"> <list_item> <paragraph> Inner list, item 1. <list_item> <paragraph> Inner list, item 2. <list_item> <paragraph> Outer list, item 2. See bullet_list_ or enumerated_list_ for further examples. ``literal`` =========== `To be completed`_. ``literal_block`` ================= The ``literal_block`` element contains a block of text where line breaks and whitespace are significant and must be preserved. ``literal_block`` elements are commonly used for program listings and interactive computer sessions. See `line_block`_ for an alternative useful for verse and addresses. Details ------- :Category: `Simple Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``literal_block``. :Children: ``literal_block`` elements may contain text data plus `inline elements`_. :Analogues: ``literal_block`` is analogous to the HTML "pre" element and to the DocBook "programlisting" and "screen" elements. :Processing: ``literal_block`` elements are typically rendered in a monospaced typeface. It is crucial that all whitespace and line breaks are preserved in the rendered form. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``literal_block`` element contains the `common attributes`_ (ids_, names_, dupnames_, source_, and classes_), plus `xml:space`_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``literal_block``. The `%structure.model;`_ parameter entity indirectly includes ``literal_block``. Examples -------- reStructuredText source:: Here is a literal block:: if literal_block: text = 'is left as-is' spaces_and_linebreaks = 'are preserved' markup_processing = None Pseudo-XML_ fragment from simple parsing:: <paragraph> Here is a literal block: <literal_block xml:space="preserve"> if literal_block: text = 'is left as-is' spaces_and_linebreaks = 'are preserved' markup_processing = None ``math`` ======== The ``math`` element contains text in `LaTeX math format` that is typeset as mathematical notation (inline formula). If the output format does not support math typesetting, the content is inserted verbatim. Details ------- :Category: `Inline Elements`_ :Parents: All elements employing the `%inline.elements;`_ parameter entities in their content models may contain ``math``. :Children: ``math`` elements may contain text data. :Analogues: ``math`` is analogous to a MathML "math" element or the LaTeX (``$ math $``) mode. :Processing: Rendered as mathematical notation. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``math`` element contains the `common attributes`_ (ids_, names_, dupnames_, source_, and classes_). ``math_block`` ============== The ``math_block`` element contains a block of text in `LaTeX math format` that is typeset as mathematical notation (display formula). The ``math_block`` element is generated during the initial parse from a "math" directive. If the output format does not support math typesetting, the content is inserted verbatim. Details ------- :Category: `Simple Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``math_block``. :Children: ``math_block`` elements may contain text data. :Analogues: ``math_block`` is analogous to a LaTeX "equation*" environment or a MathML "math" element displayed as block-level element. :Processing: Rendered in a block as mathematical notation, typically centered or with indentation Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``math`` element contains the `common attributes`_ (ids_, names_, dupnames_, source_, and classes_). ``note`` ======== The ``note`` element is an admonition, a distinctive and self-contained notice. Also see the other admonition elements Docutils offers (in alphabetical order): attention_, caution_, danger_, error_, hint_, important_, tip_, warning_, and the generic admonition_. Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``note``. :Children: ``note`` elements contain one or more `body elements`_. :Analogues: ``note`` is analogous to the DocBook "note" element. :Processing: Rendered distinctly (inset and/or in a box, etc.), with the generated title "Note" (or similar). Content Model ------------- .. parsed-literal:: (`%body.elements;`_)+ :Attributes: The ``note`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``note``. The `%structure.model;`_ parameter entity indirectly includes ``note``. Examples -------- reStructuredText source:: .. Note:: Admonitions can be handy to break up a long boring technical document. Pseudo-XML_ fragment from simple parsing:: <note> <paragraph> Admonitions can be handy to break up a long boring technical document. ``option`` ========== The ``option`` element groups an option string together with zero or more option argument placeholders. Note that reStructuredText_ currently supports only one argument per option. Details ------- :Category: `Body Subelements`_ :Parents: Only the option_group_ element contains ``option``. :Children: Each ``option`` element contains one option_string_ and zero or more option_argument_ elements. :Analogues: ``option`` has no direct analogues in common DTDs. :Processing: See option_list_. Content Model ------------- .. parsed-literal:: (option_string_, option_argument_ \*) :Attributes: The ``option`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- See the examples for the option_list_ element. ``option_argument`` =================== The ``option_argument`` element contains placeholder text for option arguments. Details ------- :Category: `Body Subelements`_ :Parents: Only the option_ element contains ``option_argument``. :Children: ``option_argument`` elements contain text data only. :Analogues: ``option_argument`` has no direct analogues in common DTDs. :Processing: The value of the "delimiter" attribute is prefixed to the ``option_argument``, separating it from its option_string_ or a preceding ``option_argument``. The ``option_argument`` text is typically rendered in a monospaced typeface, possibly italicized or otherwise altered to indicate its placeholder nature. Content Model ------------- .. parsed-literal:: (#PCDATA) :Attributes: The ``option_argument`` element contains the `common attributes`_ (ids_, names_, dupnames_, source_, and classes_), plus delimiter_. ``delimiter`` contains the text preceding the ``option_argument``: either the text separating it from the option_string_ (typically either "=" or " ") or the text between option arguments (typically either "," or " "). Examples -------- See the examples for the option_list_ element. ``option_group`` ================ The ``option_group`` element groups together one or more option_ elements, all synonyms. Details ------- :Category: `Body Subelements`_ :Parents: Only the option_list_item_ element contains ``option_group``. :Children: ``option_group`` elements contain one or more option_ elements. ``option_group`` is an empty element and has no children. Each ``option_group`` element contains one _ and one _ element. :Analogues: ``option_group`` has no direct analogues in common DTDs. :Processing: Typically option_ elements within an ``option_group`` are joined together in a comma-separated list. Content Model ------------- .. parsed-literal:: (option_group_, description_) :Attributes: The ``option_group`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- See the examples for the option_list_ element. ``option_list`` =============== Each ``option_list`` element contains a two-column list of command-line options and descriptions, documenting a program's options. Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``option_list``. :Children: ``option_list`` elements contain one or more option_list_item_ elements. :Analogues: ``option_list`` has no direct analogues in common DTDs. It can be emulated with primitives such as tables. :Processing: An ``option_list`` is typically rendered as a two-column list, where the first column contains option strings and arguments, and the second column contains descriptions. Content Model ------------- .. parsed-literal:: (option_list_item_ +) :Attributes: The ``option_list`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``option_list``. The `%structure.model;`_ parameter entity indirectly includes ``option_list``. Examples -------- reStructuredText_ source:: -a command-line option "a" -1 file, --one=file, --two file Multiple options with arguments. Pseudo-XML_ fragment from simple parsing:: <option_list> <option_list_item> <option_group> <option> <option_string> -a <description> <paragraph> command-line option "a" <option_list_item> <option_group> <option> <option_string> -1 <option_argument delimiter=" "> file <option> <option_string> --one <option_argument delimiter="="> file <option> <option_string> --two <option_argument delimiter=" "> file <description> <paragraph> Multiple options with arguments. ``option_list_item`` ==================== The ``option_list_item`` element is a container for a pair of option_group_ and description_ elements. Details ------- :Category: `Body Subelements`_ :Parents: Only the option_list_ element contains ``option_list_item``. :Children: Each ``option_list_item`` element contains one option_group_ and one description_ element. :Analogues: ``option_list_item`` has no direct analogues in common DTDs. :Processing: See option_list_. Content Model ------------- .. parsed-literal:: (option_group_, description_) :Attributes: The ``option_list_item`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- See the examples for the option_list_ element. ``option_string`` ================= The ``option_string`` element contains the text of a command-line option. Details ------- :Category: `Body Subelements`_ :Parents: Only the option_ element contains ``option_string``. :Children: ``option_string`` elements contain text data only. :Analogues: ``option_string`` has no direct analogues in common DTDs. :Processing: The ``option_string`` text is typically rendered in a monospaced typeface. Content Model ------------- .. parsed-literal:: (#PCDATA) :Attributes: The ``option_string`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- See the examples for the option_list_ element. ``organization`` ================ The ``organization`` element contains the name of document author's organization, or the organization responsible for the document. Details ------- :Category: `Bibliographic Elements`_ :Parents: Only the docinfo_ element contains ``organization``. :Children: ``organization`` elements may contain text data plus `inline elements`_. :Analogues: ``organization`` is analogous to the DocBook "orgname", "corpname", or "publishername" elements. :Processing: See docinfo_. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``organization`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%bibliographic.elements;`_ parameter entity directly includes ``organization``. Examples -------- reStructuredText_ source:: Document Title ============== :Organization: Humankind Complete pseudo-XML_ result after parsing and applying transforms:: <document ids="document-title" names="document title"> <title> Document Title <docinfo> <organization> Humankind See docinfo_ for a more complete example, including processing context. ``paragraph`` ============= The ``paragraph`` element contains the text and inline elements of a single paragraph, a fundamental building block of documents. Details ------- :Category: `Simple Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``paragraph``. :Children: ``paragraph`` elements may contain text data plus `inline elements`_. :Analogues: ``paragraph`` is analogous to the HTML "p" element and to the DocBook "para" elements. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``paragraph`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``paragraph``. The `%structure.model;`_ parameter entity indirectly includes ``paragraph``. Examples -------- reStructuredText_ source:: A paragraph. Pseudo-XML_ fragment from simple parsing:: <paragraph> A paragraph. ``pending`` =========== `To be completed`_. ``problematic`` =============== `To be completed`_. ``raw`` ======= `To be completed`_. ``reference`` ============= `To be completed`_. ``revision`` ============ The ``revision`` element contains the revision number of the document. It can be used alone or in conjunction with version_. Details ------- :Category: `Bibliographic Elements`_ :Parents: Only the docinfo_ element contains ``revision``. :Children: ``revision`` elements may contain text data plus `inline elements`_. :Analogues: ``revision`` is analogous to but simpler than the DocBook "revision" element. It closely matches the DocBook "revnumber" element, but in a simpler context. :Processing: Often used with the RCS/CVS keyword "Revision". See docinfo_. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``revision`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%bibliographic.elements;`_ parameter entity directly includes ``revision``. Examples -------- reStructuredText_ source:: Document Title ============== :Version: 1 :Revision: b Complete pseudo-XML_ result after parsing and applying transforms:: <document ids="document-title" names="document title"> <title> Document Title <docinfo> <version> 1 <revision> b See docinfo_ for a more complete example, including processing context. ``row`` ======= `To be completed`_. ``rubric`` ========== rubric n. 1. a title, heading, or the like, in a manuscript, book, statute, etc., written or printed in red or otherwise distinguished from the rest of the text. ... -- Random House Webster's College Dictionary, 1991 A rubric is like an informal heading that doesn't correspond to the document's structure. `To be completed`_. ``section`` =========== The ``section`` element is the main unit of hierarchy for Docutils documents. Docutils ``section`` elements are a recursive structure; a ``section`` may contain other ``section`` elements, without limit. Paragraphs and other body elements may occur before a ``section``, but not after it. Details ------- :Category: `Structural Elements`_ :Parents: The following elements may contain ``section``: document_, section_ :Children: ``section`` elements begin with a title_, and may contain `body elements`_ as well as transition_, topic_, and sidebar_ elements. :Analogues: ``section`` is analogous to DocBook recursive "section" elements, and to HTML "div" elements combined with "h1" etc. title elements. Content Model ------------- .. parsed-literal:: (title_, `%structure.model;`_) See the `%structure.model;`_ parameter entity for details of the body of a ``section``. :Attributes: The ``section`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%section.elements;`_ parameter entity directly includes ``section``. The `%structure.model;`_ parameter entity indirectly includes ``section``. Examples -------- reStructuredText_ source:: Title 1 ======= Paragraph 1. Title 2 ------- Paragraph 2. Title 3 ======= Paragraph 3. Title 4 ------- Paragraph 4. Complete pseudo-XML_ result after parsing:: <document> <section ids="title-1" names="title 1"> <title> Title 1 <paragraph> Paragraph 1. <section ids="title-2" names="title 2"> <title> Title 2 <paragraph> Paragraph 2. <section ids="title-3" names="title 3"> <title> Title 3 <paragraph> Paragraph 3. <section ids="title-4" names="title 4"> <title> Title 4 <paragraph> Paragraph 4. ``sidebar`` =========== 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. The ``sidebar`` element is a nonrecursive section_-like construct which may occur at the top level of a section_ wherever a body element (list, table, etc.) is allowed. In other words, ``sidebar`` elements cannot nest inside body elements, so you can't have a ``sidebar`` inside a ``table`` or a ``list``, or inside another ``sidebar`` (or topic_). Details ------- :Category: `Structural Elements`_ :Parents: The following elements may contain ``sidebar``: document_, section_ :Children: ``sidebar`` elements begin with a title_ and an optional subtitle_ and contain `body elements`_ and topic_ elements. :Analogues: ``sidebar`` is analogous to the DocBook "sidebar" element. :Processing: A ``sidebar`` element should be set off from the rest of the document somehow, typically with a border. Sidebars typically "float" to the side of the page and the document's main text flows around them. Content Model ------------- .. parsed-literal:: (title_, subtitle_?, (`%body.elements;`_ | topic_)+) :Attributes: The ``sidebar`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%structure.model;`_ parameter entity directly includes ``sidebar``. Examples -------- The `"sidebar" directive`_ is used to create a ``sidebar`` element. reStructuredText_ source:: .. sidebar:: Title :subtitle: If Desired Body. Pseudo-XML_ fragment from simple parsing:: <sidebar> <title> Title <subtitle> If Desired <paragraph> Body. .. _"sidebar" directive: rst/directives.html#sidebar ``status`` ========== The ``status`` element contains a status statement for the document, such as "Draft", "Final", "Work In Progress", etc. Details ------- :Category: `Bibliographic Elements`_ :Parents: Only the docinfo_ element contains ``status``. :Children: ``status`` elements may contain text data plus `inline elements`_. :Analogues: ``status`` is analogous to the DocBook "status" element. :Processing: See docinfo_. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``status`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%bibliographic.elements;`_ parameter entity directly includes ``status``. Examples -------- reStructuredText_ source:: Document Title ============== :Status: Work In Progress Complete pseudo-XML_ result after parsing and applying transforms:: <document ids="document-title" names="document title"> <title> Document Title <docinfo> <status> Work In Progress See docinfo_ for a more complete example, including processing context. ``strong`` ========== `To be completed`_. ``subscript`` ============= `To be completed`_. ``substitution_definition`` =========================== `To be completed`_. ``substitution_reference`` ========================== `To be completed`_. ``subtitle`` ============ The ``subtitle`` element stores the subtitle of a document_. Details ------- :Category: `Structural Subelements`_ :Parents: The document_ and sidebar_ elements may contain ``subtitle``. :Children: ``subtitle`` elements may contain text data plus `inline elements`_. :Analogues: ``subtitle`` is analogous to HTML header elements ("h2" etc.) and to the DocBook "subtitle" element. :Processing: A document's subtitle is usually rendered smaller than its title_. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``subtitle`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- reStructuredText_ source:: ======= Title ======= ---------- Subtitle ---------- A paragraph. Complete pseudo-XML_ result after parsing and applying transforms:: <document ids="title" names="title"> <title> Title <subtitle ids="subtitle" names="subtitle"> Subtitle <paragraph> A paragraph. Note how two section levels have collapsed, promoting their titles to become the document's title and subtitle. Since there is only one structural element (document), the subsection's ``ids`` and ``names`` attributes are stored in the ``subtitle`` element. ``superscript`` =============== `To be completed`_. ``system_message`` ================== `To be completed`_. ``table`` ========= `To be completed`_. ``target`` ========== `To be completed`_. ``tbody`` ========= `To be completed`_. ``term`` ======== The ``term`` element contains a word or phrase being defined in a definition_list_. Details ------- :Category: `Body Subelements`_ (simple) :Parents: Only the definition_list_item_ element contains ``term``. :Children: ``term`` elements may contain text data plus `inline elements`_. :Analogues: ``term`` is analogous to the HTML "dt" element and to the DocBook "term" element. :Processing: See definition_list_item_. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``term`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. Examples -------- See the examples for the definition_list_, definition_list_item_, and classifier_ elements. ``tgroup`` ========== `To be completed`_. ``thead`` ========= `To be completed`_. ``tip`` ======= The ``tip`` element is an admonition, a distinctive and self-contained notice. Also see the other admonition elements Docutils offers (in alphabetical order): attention_, caution_, danger_, error_, hint_, important_, note_, warning_, and the generic admonition_. Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``tip``. :Children: ``tip`` elements contain one or more `body elements`_. :Analogues: ``tip`` is analogous to the DocBook "tip" element. :Processing: Rendered distinctly (inset and/or in a box, etc.), with the generated title "Tip" (or similar). Content Model ------------- .. parsed-literal:: (`%body.elements;`_)+ :Attributes: The ``tip`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``tip``. The `%structure.model;`_ parameter entity indirectly includes ``tip``. Examples -------- reStructuredText source:: .. Tip:: 15% if the service is good. Pseudo-XML_ fragment from simple parsing:: <tip> <paragraph> 15% if the service is good. .. _title: ``title`` ========= The ``title`` element stores the title of a document_, section_, topic_, sidebar_, or generic admonition_. Details ------- :Category: `Structural Subelements`_ :Parents: The following elements may contain ``title``: document_, section_, topic_, sidebar_, admonition_ :Children: ``title`` elements may contain text data plus `inline elements`_. :Analogues: ``title`` is analogous to HTML "title" and header ("h1" etc.) elements, and to the DocBook "title" element. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``title`` element contains the `common attributes`_ (ids_, names_, dupnames_, source_, and classes_), plus refid_ and auto_. ``refid`` is used as a backlink to a table of contents entry. ``auto`` is used to indicate (with value "1") that the ``title`` has been numbered automatically. Examples -------- reStructuredText_ source:: A Title ======= A paragraph. Pseudo-XML_ fragment from simple parsing:: <section ids="a-title" names="a title"> <title> A Title <paragraph> A paragraph. ``title_reference`` =================== `To be completed`_. ``topic`` ========= The ``topic`` element is a nonrecursive section_-like construct which may occur at the top level of a section_ wherever a body element (list, table, etc.) is allowed. In other words, ``topic`` elements cannot nest inside body elements, so you can't have a ``topic`` inside a ``table`` or a ``list``, or inside another ``topic``. Details ------- :Category: `Structural Elements`_ :Parents: The following elements may contain ``topic``: document_, section_, sidebar_ :Children: ``topic`` elements begin with a title_ and may contain `body elements`_. :Analogues: ``topic`` is analogous to the DocBook "simplesect" element. :Processing: A ``topic`` element should be set off from the rest of the document somehow, such as with indentation or a border. Content Model ------------- .. parsed-literal:: (title_?, (`%body.elements;`_)+) :Attributes: The ``topic`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%structure.model;`_ parameter entity directly includes ``topic``. Examples -------- The `"topic" directive`_ is used to create a ``topic`` element. reStructuredText_ source:: .. topic:: Title Body. Pseudo-XML_ fragment from simple parsing:: <topic> <title> Title <paragraph> Body. .. _"topic" directive: rst/directives.html#topic ``transition`` ============== The ``transition`` element is commonly seen in novels and short fiction, as a gap spanning one or more lines, with or without a type ornament such as a row of asterisks. Transitions separate body elements and sections, dividing a section into untitled divisions. A transition may not begin or end a section [#]_ or document, nor may two transitions be immediately adjacent. See `Doctree Representation of Transitions`__ in `A Record of reStructuredText Syntax Alternatives`__. .. [#] In reStructuredText markup, a transition may appear to fall at the end of a section immediately before another section. A transform recognizes this case and moves the transition so it separates the sections. __ ../dev/rst/alternatives.html#doctree-representation-of-transitions __ ../dev/rst/alternatives.html Details ------- :Category: `Structural Subelements`_ :Parents: The following elements may contain ``transition``: document_, section_ :Children: ``transition`` is an empty element and has no children. :Analogues: ``transition`` is analogous to the HTML "hr" element. :Processing: The ``transition`` element is typically rendered as vertical whitespace (more than that separating paragraphs), with or without a horizontal line or row of asterisks. In novels, transitions are often represented as a row of three well-spaced asterisks with vertical space above and below. Content Model ------------- :: EMPTY The ``transition`` element has no content; it is a "point element". :Attributes: The ``transition`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%structure.model;`_ parameter entity directly includes ``transition``. Examples -------- reStructuredText_ source:: Paragraph 1. -------- Paragraph 2. Complete pseudo-XML_ result after parsing:: <document> <paragraph> Paragraph 1. <transition> <paragraph> Paragraph 2. ``version`` =========== The ``version`` element contains the version number of the document. It can be used alone or in conjunction with revision_. Details ------- :Category: `Bibliographic Elements`_ :Parents: Only the docinfo_ element contains ``version``. :Children: ``version`` elements may contain text data plus `inline elements`_. :Analogues: ``version`` may be considered analogous to the DocBook "revision", "revnumber", or "biblioid" elements. :Processing: Sometimes used with the RCS/CVS keyword "Revision". See docinfo_ and revision_. Content Model ------------- .. parsed-literal:: `%text.model;`_ :Attributes: The ``version`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%bibliographic.elements;`_ parameter entity directly includes ``version``. Examples -------- reStructuredText_ source:: Document Title ============== :Version: 1.1 Complete pseudo-XML_ result after parsing and applying transforms:: <document ids="document-title" names="document title"> <title> Document Title <docinfo> <version> 1.1 See docinfo_ for a more complete example, including processing context. ``warning`` =========== The ``warning`` element is an admonition, a distinctive and self-contained notice. Also see the other admonition elements Docutils offers (in alphabetical order): attention_, caution_, danger_, error_, hint_, important_, note_, tip_. Details ------- :Category: `Compound Body Elements`_ :Parents: All elements employing the `%body.elements;`_ or `%structure.model;`_ parameter entities in their content models may contain ``warning``. :Children: ``warning`` elements contain one or more `body elements`_. :Analogues: ``warning`` is analogous to the DocBook "warning" element. :Processing: Rendered distinctly (inset and/or in a box, etc.), with the generated title "Warning" (or similar). Content Model ------------- .. parsed-literal:: (`%body.elements;`_)+ :Attributes: The ``warning`` element contains only the `common attributes`_: ids_, names_, dupnames_, source_, and classes_. :Parameter Entities: The `%body.elements;`_ parameter entity directly includes ``warning``. The `%structure.model;`_ parameter entity indirectly includes ``warning``. Examples -------- reStructuredText source:: .. WARNING:: Reader discretion is strongly advised. Pseudo-XML_ fragment from simple parsing:: <warning> <paragraph> Reader discretion is strongly advised. --------------------- Attribute Reference --------------------- .. contents:: :local: :depth: 1 _`Common Attributes`: Through the `%basic.atts;`_ parameter entity, all elements contain the following attributes: ids_, names_, dupnames_, source_, and classes_. .. _attribute type: Attribute types: ``CDATA`` Character data. ``CDATA`` attributes may contain arbitrary text. ``ID`` Like a ``NMTOKEN``, but it must begin with a letter (a "name production"). Identical ``ID`` values must not appear more than once in a document; i.e., ID values must uniquely identify their elements. ``IDREF`` A reference to an ``ID`` value (a name production) of another element. ``IDREFS`` One or more space-separated ``ID`` references (name productions). ``NMTOKEN`` A "name token". One or more of letters, digits, ".", "-", and "_". ``NMTOKENS`` One or more space-separated ``NMTOKEN`` names. ``%yesorno;`` No if zero ("0"), yes if any other value. This is a parameter entity which resolves to a ``NMTOKEN`` attribute type. ``%number;`` This emphasizes that the attribute value must be a number. This is a parameter entity which resolves to a ``NMTOKEN`` attribute type. enumeration The attribute value may be one of a specified list of values. ``anonymous`` ============= `Attribute type`_: ``%yesorno;``. Default value: none (implies no). The ``anonymous`` attribute is used for unnamed hyperlinks in the target_ and reference_ elements (via the `%anonymous.att;`_ parameter entity). ``auto`` ======== `Attribute type`_: ``CDATA``. Default value: none. The ``auto`` attribute is used to indicate automatically-numbered footnote_, footnote_reference_ and title_ elements (via the `%auto.att;`_ parameter entity). ``backrefs`` ============ `Attribute type`_: ``IDREFS``. Default value: none. The ``backrefs`` attribute contains a space-separated list of ids_ references, used for backlinks from footnote_, citation_, and system_message_ elements (via the `%backrefs.att;`_ parameter entity). ``bullet`` ========== `Attribute type`_: ``CDATA``. Default value: none. The ``bullet`` attribute is used in the bullet_list_ element. ``classes`` =========== `Attribute type`_: ``NMTOKENS``. Default value: none. The ``classes`` attribute is a list containing zero or more names used to classify an element. The names are converted to conform to the regular expression ``[a-z](-?[a-z0-9]+)*`` (see the `"class" directive`_ description for details and rationale_). The purpose of the attribute is to indicate an "is-a" variant relationship, to allow an extensible way of defining sub-classes of existing elements. It can be used to carry context forward between a Docutils Reader and Writer, when a custom structure is reduced to a standardized document tree. One common use is in conjunction with stylesheets, to add selection criteria. It should not be used to carry formatting instructions or arbitrary content. The ``classes`` attribute's contents should be ignorable. Writers that are not familiar with the variant expressed should be able to ignore the attribute. ``classes`` is one of the `common attributes`_, shared by all Docutils elements. .. _"class" directive: rst/directives.html#class .. _rationale: rst/directives.html#rationale ``delimiter`` ============= `Attribute type`_: ``CDATA``. Default value: none. The ``delimiter`` attribute is used in the option_argument_ element. ``dupnames`` ============ `Attribute type`_: ``CDATA``. Default value: none. The ``dupnames`` attribute is a list containing the names of an element when there has been a naming conflict. The contents of the ``dupnames`` attribute would have been transferred from the `names`_ attribute. An element may have at most one of the ``names`` or ``dupnames`` attributes, but not both. ``dupnames`` is one of the `common attributes`_, shared by all Docutils elements. ``enumtype`` ============ `Attribute type`_: enumeration, one of "arabic", "loweralpha", "upperalpha", "lowerroman", or "upperroman". Default value: none. The ``enumtype`` attribute is used in the enumerated_list_ element. ``ids`` ======= `Attribute type`_: ``NMTOKENS``. Default value: none. The ``ids`` attribute is a list containing one or more unique identifier keys. ``ids`` is one of the `common attributes`_, shared by all Docutils elements. ``names`` ========= `Attribute type`_: ``CDATA``. Default value: none. The ``names`` attribute is a list containing the names of an element, typically originating from the element's title or content. Each name in ``names`` must be unique; if there are name conflicts (two or more elements want to the same name), the contents will be transferred to the `dupnames`_ attribute on the duplicate elements. An element may have at most one of the ``names`` or ``dupnames`` attributes, but not both. ``names`` is one of the `common attributes`_, shared by all Docutils elements. ``prefix`` ========== `Attribute type`_: ``CDATA``. Default value: none. The ``prefix`` attribute is used in the enumerated_list_ element. ``refid`` ========= `Attribute type`_: ``IDREF``. Default value: none. The ``refid`` attribute contains references to `ids`_ attributes in other elements. It is used by the target_, reference_, footnote_reference_, citation_reference_, title_ and problematic_ elements (via the `%refid.att;`_ and `%reference.atts;`_ parameter entities). ``refname`` =========== `Attribute type`_: ``NMTOKENS``. Default value: none. The ``refname`` attribute contains an internal reference to the `names`_ attribute of another element. On a `target`_ element, ``refname`` indicates an indirect target which may resolve to either an internal or external reference. ``refname`` is used by the target_, reference_, footnote_reference_, citation_reference_, and substitution_reference_ elements (via the `%refname.att;`_ and `%reference.atts;`_ parameter entities). ``refuri`` ========== `Attribute type`_: ``CDATA``. Default value: none. The ``refuri`` attribute contains an external reference to a URI/URL. It is used by the target_, reference_, footnote_reference_, and citation_reference_ elements (via the `%reference.atts;`_ parameter entity). ``source`` ========== `Attribute type`_: ``CDATA``. Default value: none. The ``source`` attribute is used to store the path or URL to the source text that was used to produce the document tree. It is one of the `common attributes`_, shared by all Docutils elements. ``start`` ========= `Attribute type`_: ``%number;``. Default value: none. The ``start`` attribute is used in the enumerated_list_ element. ``suffix`` ========== `Attribute type`_: ``CDATA``. Default value: none. The ``suffix`` attribute is used in the enumerated_list_ element. ``xml:space`` ============= `Attribute type`_: one of "default" or "preserve". Default value: "preserve" (fixed). The ``xml:space`` attribute is a standard XML attribute for whitespace-preserving elements. It is used by the literal_block_, line_block_, doctest_block_, comment_, and raw_ elements (via the `%fixedspace.att;`_ parameter entity). It is a fixed attribute, meant to communicate to an XML parser that the element contains significant whitespace. The attribute value should not be set in a document instance. .. _title (attribute): ``title`` ========= `Attribute type`_: ``CDATA``. Default value: none. The ``title`` attribute stores the title metadata of a document. This title is typically not part of the rendered document. It may for example be used in HTML's ``title`` element. ---------------------------- Parameter Entity Reference ---------------------------- .. contents:: :local: :depth: 1 Parameter entities are used to simplify the DTD (to share definitions and reduce duplication) and to allow the DTD to be customized by wrapper DTDs (external client DTDs that use or import the Docutils DTD). Parameter entities may be overridden by wrapper DTDs, replacing the definitions below with custom definitions. Parameter entities whose names begin with "additional" are meant to allow easy extension by wrapper DTDs. ``%anonymous.att;`` =================== The ``%anonymous.att;`` parameter entity contains the anonymous_ attribute, used for unnamed hyperlinks. Entity definition: .. parsed-literal:: anonymous_ %yesorno; #IMPLIED The reference_ and target_ elements directly employ the ``%anonymous.att;`` parameter entity in their attribute lists. ``%auto.att;`` ============== The ``%auto.att;`` parameter entity contains the auto_ attribute, used to indicate an automatically-numbered footnote or title. Entity definition: .. parsed-literal:: auto_ CDATA #IMPLIED The footnote_, footnote_reference_, and title_ elements directly employ the ``%auto.att;`` parameter entity in their attribute lists. ``%backrefs.att;`` ================== The ``%backrefs.att;`` parameter entity contains the backrefs_ attribute, a space-separated list of id references, for backlinks. Entity definition: .. parsed-literal:: backrefs_ IDREFS #IMPLIED The citation_, footnote_, and system_message_ elements directly employ the ``%backrefs.att;`` parameter entity in their attribute lists. ``%basic.atts;`` ================ The ``%basic.atts;`` parameter entity lists attributes common to all Docutils elements. See `Common Attributes`_. Entity definition: .. parsed-literal:: ids_ NMTOKENS #IMPLIED names_ CDATA #IMPLIED dupnames_ CDATA #IMPLIED source_ CDATA #IMPLIED classes_ NMTOKENS #IMPLIED %additional.basic.atts; The ``%additional.basic.atts;`` parameter entity can be used by wrapper DTDs to extend ``%basic.atts;``. ``%bibliographic.elements;`` ============================ The ``%bibliographic.elements;`` parameter entity contains an OR-list of all `bibliographic elements`_. Entity definition: .. parsed-literal:: author_ | authors_ | organization_ | contact_ | address_ | version_ | revision_ | status_ | date_ | copyright_ | field_ %additional.bibliographic.elements; The ``%additional.bibliographic.elements;`` parameter entity can be used by wrapper DTDs to extend ``%bibliographic.elements;``. Only the docinfo_ element directly employs the ``%bibliographic.elements;`` parameter entity in its content model. ``%body.elements;`` =================== The ``%body.elements;`` parameter entity contains an OR-list of all `body elements`_. ``%body.elements;`` is itself contained within the `%structure.model;`_ parameter entity. Entity definition: .. parsed-literal:: admonition_ | attention_ | block_quote_ | bullet_list_ | caution_ | citation_ | compound_ | comment_ | container_ | danger_ | definition_list_ | doctest_block_ | enumerated_list_ | error_ | field_list_ | figure_ | footnote_ | hint_ | image_ | important_ | line_block_ | literal_block_ | note_ | option_list_ | paragraph_ | pending_ | raw_ reference_ | rubric_ | substitution_definition_ | system_message_ | table_ | target_ | tip_ | warning_ %additional.body.elements; The ``%additional.body.elements;`` parameter entity can be used by wrapper DTDs to extend ``%body.elements;``. The ``%body.elements;`` parameter entity is directly employed in the content models of the following elements: admonition_, attention_, block_quote_, caution_, citation_, compound_, danger_, definition_, description_, entry_, error_, field_body_, footer_, footnote_, header_, hint_, important_, legend_, list_item_, note_, sidebar_, system_message_, tip_, topic_, warning_ Via `%structure.model;`_, the ``%body.elements;`` parameter entity is indirectly employed in the content models of the document_ and section_ elements. ``%fixedspace.att;`` ==================== The ``%fixedspace.att;`` parameter entity contains the `xml:space`_ attribute, a standard XML attribute for whitespace-preserving elements. Entity definition: .. parsed-literal:: `xml:space`_ (default | preserve) #FIXED 'preserve' The ``%fixedspace.att;`` parameter entity is directly employed in the attribute lists of the following elements: address_, comment_, doctest_block_, line_block_, literal_block_, raw_ ``%inline.elements;`` ===================== The ``%inline.elements;`` parameter entity contains an OR-list of all `inline elements`_. Entity definition: .. parsed-literal:: abbreviation_ | acronym_ | citation_reference_ | emphasis_ | footnote_reference_ | generated_ | image_ | inline_ | literal_ | problematic_ | raw_ | reference_ | strong_ | substitution_reference_ | subscript_ | superscript_ | target_ | title_reference_ %additional.inline.elements; The ``%additional.inline.elements;`` parameter entity can be used by wrapper DTDs to extend ``%inline.elements;``. Via `%text.model;`_, the ``%inline.elements;`` parameter entity is indirectly employed in the content models of the following elements: abbreviation_, acronym_, address_, attribution_, author_, caption_, classifier_, contact_, copyright_, date_, doctest_block_, emphasis_, generated_, inline_, line_block_, literal_block_, math_, math_block_, organization_, paragraph_, problematic_, raw_, reference_, revision_, rubric_, status_, strong_, subscript_, substitution_definition_, substitution_reference_, subtitle_, superscript_, target_, term_, title_, title_reference_, version_ ``%reference.atts;`` ==================== The ``%reference.atts;`` parameter entity groups together the refuri_, refid_, and refname_ attributes. Entity definition: .. parsed-literal:: `%refuri.att;`_ `%refid.att;`_ `%refname.att;`_ %additional.reference.atts; The ``%additional.reference.atts;`` parameter entity can be used by wrapper DTDs to extend ``%additional.reference.atts;``. The citation_reference_, footnote_reference_, reference_, and target_ elements directly employ the ``%reference.att;`` parameter entity in their attribute lists. ``%refid.att;`` ================ The ``%refid.att;`` parameter entity contains the refid_ attribute, an internal reference to the `ids`_ attribute of another element. Entity definition: .. parsed-literal:: refid_ CDATA #IMPLIED The title_ and problematic_ elements directly employ the ``%refid.att;`` parameter entity in their attribute lists. Via `%reference.atts;`_, the ``%refid.att;`` parameter entity is indirectly employed in the attribute lists of the citation_reference_, footnote_reference_, reference_, and target_ elements. ``%refname.att;`` ================= The ``%refname.att;`` parameter entity contains the refname_ attribute, an internal reference to the `names`_ attribute of another element. On a `target`_ element, ``refname`` indicates an indirect target which may resolve to either an internal or external reference. Entity definition: .. parsed-literal:: refname_ NMTOKENS #IMPLIED The substitution_reference_ element directly employs the ``%refname.att;`` parameter entity in its attribute list. Via `%reference.atts;`_, the ``%refname.att;`` parameter entity is indirectly employed in the attribute lists of the citation_reference_, footnote_reference_, reference_, and target_ elements. ``%refuri.att;`` ================ The ``%refuri.att;`` parameter entity contains the refuri_ attribute, an external reference to a URI/URL. Entity definition: .. parsed-literal:: refuri_ CDATA #IMPLIED Via `%reference.atts;`_, the ``%refuri.att;`` parameter entity is indirectly employed in the attribute lists of the citation_reference_, footnote_reference_, reference_, and target_ elements. ``%section.elements;`` ====================== The ``%section.elements;`` parameter entity contains an OR-list of all section_-equivalent elements. ``%section.elements;`` is itself contained within the `%structure.model;`_ parameter entity. Entity definition: .. parsed-literal:: section_ %additional.section.elements; The ``%additional.section.elements;`` parameter entity can be used by wrapper DTDs to extend ``%section.elements;``. Via `%structure.model;`_, the ``%section.elements;`` parameter entity is indirectly employed in the content models of the document_ and section_ elements. ``%structure.model;`` ===================== The ``%structure.model;`` parameter entity encapsulates the hierarchical structure of a document and of its constituent parts. See the discussion of the `element hierarchy`_ above. Entity definition: .. parsed-literal:: ( ( (`%body.elements;`_ | topic_ | sidebar_)+, transition_? )*, ( (`%section.elements;`_), (transition_?, (`%section.elements;`_) )* )? ) Each document_ or section_ contains zero or more body elements, topics, and/or sidebars, optionally interspersed with single transitions, followed by zero or more sections (whose contents are recursively the same as this model) optionally interspersed with transitions. The following restrictions are imposed by this model: * Transitions must be separated by other elements (body elements, sections, etc.). In other words, a transition may not be immediately adjacent to another transition. * A transition may not occur at the beginning of a document or section. An additional restriction, which cannot be expressed in the language of DTDs, is imposed by software: * A transition may not occur at the end of a document or section. The `%structure.model;`_ parameter entity is directly employed in the content models of the document_ and section_ elements. ``%text.model;`` ================ The ``%text.model;`` parameter entity is used by many elements to represent text data mixed with `inline elements`_. Entity definition: .. parsed-literal:: (#PCDATA | `%inline.elements;`_)* The ``%text.model;`` parameter entity is directly employed in the content models of the following elements: abbreviation_, acronym_, address_, author_, caption_, classifier_, contact_, copyright_, date_, doctest_block_, emphasis_, field_name_, generated_, line_block_, literal_block_, organization_, paragraph_, problematic_, raw_, reference_, revision_, status_, strong_, substitution_definition_, substitution_reference_, subtitle_, target_, term_, title_, version_ .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/docs/index.txt������������������������������������������������������������������������0000664�0001750�0001750�00000020114�11700652711�020022� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������========================================== Docutils_ Project Documentation Overview ========================================== :Author: David Goodger :Contact: docutils-develop@lists.sourceforge.net :Date: $Date: 2012-01-03 20:23:53 +0100 (Die, 03. Jän 2012) $ :Revision: $Revision: 7302 $ :Copyright: This document has been placed in the public domain. The latest working documents may be accessed individually below, or from the ``docs`` directory of the `Docutils distribution`_. .. _Docutils: http://docutils.sourceforge.net/ .. _Docutils distribution: http://docutils.sourceforge.net/#download .. contents:: Docutils Stakeholders ===================== Docutils stakeholders can be categorized in several groups: 1. End-users: users of reStructuredText and the Docutils tools. Although some are developers (e.g. Python developers utilizing reStructuredText for docstrings in their source), many are not. 2. Client-developers: developers using Docutils as a library, programmers developing *with* Docutils. 3. Component-developers: those who implement application-specific components, directives, and/or roles, separately from Docutils. 4. Core-developers: developers of the Docutils codebase and participants in the Docutils project community. 5. Re-implementers: developers of alternate implementations of Docutils. There's a lot of overlap between these groups. Most (perhaps all) core-developers, component-developers, client-developers, and re-implementers are also end-users. Core-developers are also client-developers, and may also be component-developers in other projects. Component-developers are also client-developers. Project Fundamentals ==================== These files are for all Docutils stakeholders. They are kept at the top level of the Docutils project directory. :README.txt_: Project overview: quick-start, requirements, installation, and usage. :COPYING.txt_: Conditions for Docutils redistribution, with links to licenses. :FAQ.txt_: Docutils Frequently Asked Questions. If you have a question or issue, there's a good chance it's already answered here. :BUGS.txt_: A list of known bugs, and how to report a bug. :RELEASE-NOTES.txt_: Summary of the major changes in recent releases. :HISTORY.txt_: Detailed change history log. :THANKS.txt_: Acknowledgements. .. _README.txt: ../README.html .. _BUGS.txt: ../BUGS.html .. _COPYING.txt: ../COPYING.html .. _Docutils FAQ: .. _FAQ.txt: ../FAQ.html .. _RELEASE-NOTES.txt: ../RELEASE-NOTES.html .. _HISTORY.txt: ../HISTORY.html .. _THANKS.txt: ../THANKS.html .. _user: ``user/``: Introductory & Tutorial Material for End-Users ========================================================= Docutils-general: * `Docutils Front-End Tools <user/tools.html>`__ * `Docutils Configuration <user/config.html>`__ * `Docutils Mailing Lists <user/mailing-lists.html>`__ * `Docutils Link List <user/links.html>`__ Writer-specific: * `Easy Slide Shows With reStructuredText & S5 <user/slide-shows.html>`__ * `Docutils LaTeX Writer <user/latex.html>`__ * `Docutils ODF/OpenOffice/odt Writer <user/odt.html>`__ `reStructuredText <http://docutils.sourceforge.net/rst.html>`_: * `A ReStructuredText Primer (HTML) <user/rst/quickstart.html>`__ (or `text source <user/rst/quickstart.txt>`__) * `Quick reStructuredText <user/rst/quickref.html>`__ (user reference) * `reStructuredText Cheat Sheet <user/rst/cheatsheet.txt>`__ (text only; 1 page for syntax, 1 page directive & role reference) * `reStructuredText Demonstration <user/rst/demo.html>`_ (a demonstration of most reStructuredText features; you can also have a look at the `text source <user/rst/demo.txt>`__) Editor support: * `Emacs support for reStructuredText <user/emacs.html>`_ .. _ref: ``ref/``: Reference Material for All Groups =========================================== Many of these files began as developer specifications, but now that they're mature and used by end-users and client-developers, they have become reference material. Successful specs evolve into refs. Docutils-general: * `The Docutils Document Tree <ref/doctree.html>`__ (incomplete) * `Docutils Transforms <ref/transforms.html>`__ * `Docutils Generic DTD <ref/docutils.dtd>`__ * `OASIS XML Exchange Table Model Declaration Module <ref/soextblx.dtd>`__ (CALS tables DTD module) Although not in the "ref" directory, `PEP 258`_ is a must-read reference for any Docutils developer. reStructuredText_: * `An Introduction to reStructuredText <ref/rst/introduction.html>`__ (includes the `Goals <ref/rst/introduction.html#goals>`__ and `History <ref/rst/introduction.html#history>`__ of reStructuredText) * `reStructuredText Markup Specification <ref/rst/restructuredtext.html>`__ * `reStructuredText Directives <ref/rst/directives.html>`__ * `reStructuredText Interpreted Text Roles <ref/rst/roles.html>`__ * `reStructuredText Standard Definition Files <ref/rst/definitions.html>`_ Prehistoric: * `Setext Documents Mirror <http://docutils.sourceforge.net/mirror/setext.html>`__ .. _peps: ``peps/``: Python Enhancement Proposals ======================================= * `PEP 256: Docstring Processing System Framework`__ is a high-level generic proposal. [`PEP 256`__ in the `master repository`_] * `PEP 257: Docstring Conventions`__ addresses docstring style and touches on content. [`PEP 257`__ in the `master repository`_] * `PEP 258: Docutils Design Specification`__ is an overview of the architecture of Docutils. It documents design issues and implementation details. [`PEP 258`__ in the `master repository`_] * `PEP 287: reStructuredText Docstring Format`__ proposes a standard markup syntax. [`PEP 287`__ in the `master repository`_] Please note that PEPs in the `master repository`_ may not be current, whereas the local versions are. __ peps/pep-0256.html __ http://www.python.org/peps/pep-0256.html __ peps/pep-0257.html __ http://www.python.org/peps/pep-0257.html .. _PEP 258: __ peps/pep-0258.html __ http://www.python.org/peps/pep-0258.html __ peps/pep-0287.html __ http://www.python.org/peps/pep-0287.html .. _master repository: http://www.python.org/peps/ .. _api: ``api/``: API Reference Material for Client-Developers ====================================================== * `The Docutils Publisher <api/publisher.html>`__ * `Inside A Docutils Command-Line Front-End Tool <api/cmdline-tool.html>`__ * `Docutils Runtime Settings <api/runtime-settings.html>`__ * (`Docutils Transforms <ref/transforms.html>`__ should be moved here) `PEP 258`_ is an overview of the architecture of Docutils. .. _howto: ``howto/``: Instructions for Developers ======================================= * **Security:** `Deploying Docutils Securely <howto/security.html>`__ * `Writing HTML (CSS) Stylesheets for Docutils <howto/html-stylesheets.html>`__ * `Docutils Internationalization <howto/i18n.html>`__ * `Creating reStructuredText Directives <howto/rst-directives.html>`__ * `Creating reStructuredText Interpreted Text Roles <howto/rst-roles.html>`__ .. _dev: ``dev/``: Development Notes and Plans for Core-Developers ========================================================= Docutils-general: * `Docutils Hacker's Guide <dev/hacking.html>`__ * `Docutils Distributor's Guide <dev/distributing.html>`__ * `Docutils To Do List <dev/todo.html>`__ * `Docutils Project Policies <dev/policies.html>`__ * `Docutils Web Site <dev/website.html>`__ * `Docutils Release Procedure <dev/release.html>`__ * `The Docutils Subversion Repository <dev/repository.html>`__ * `Docutils Testing <dev/testing.html>`__ * `Docstring Semantics <dev/semantics.html>`__ (incomplete) * `Python Source Reader <dev/pysource.html>`_ (incomplete) * `Docutils Python DTD <dev/pysource.dtd>`_ (experimental) * `Plan for Enthought API Documentation Tool <dev/enthought-plan.html>`_ * `Enthought API Documentation Tool RFP <dev/enthought-rfp.html>`_ reStructuredText_: * `A Record of reStructuredText Syntax Alternatives <dev/rst/alternatives.html>`__ * `Problems With StructuredText <dev/rst/problems.html>`__ .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/docs/peps/����������������������������������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�017126� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/docs/peps/pep-0287.txt����������������������������������������������������������������0000664�0001750�0001750�00000077526�10434150472�021067� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������PEP: 287 Title: reStructuredText Docstring Format Version: $Revision: 4564 $ Last-Modified: $Date: 2006-05-21 22:44:42 +0200 (Son, 21. Mai 2006) $ Author: David Goodger <goodger@python.org> Discussions-To: <doc-sig@python.org> Status: Draft Type: Informational Content-Type: text/x-rst Created: 25-Mar-2002 Post-History: 02-Apr-2002 Replaces: 216 Abstract ======== When plaintext hasn't been expressive enough for inline documentation, Python programmers have sought out a format for docstrings. This PEP proposes that the `reStructuredText markup`_ be adopted as a standard markup format for structured plaintext documentation in Python docstrings, and for PEPs and ancillary documents as well. reStructuredText is a rich and extensible yet easy-to-read, what-you-see-is-what-you-get plaintext markup syntax. Only the low-level syntax of docstrings is addressed here. This PEP is not concerned with docstring semantics or processing at all (see PEP 256 for a "Road Map to the Docstring PEPs"). Nor is it an attempt to deprecate pure plaintext docstrings, which are always going to be legitimate. The reStructuredText markup is an alternative for those who want more expressive docstrings. Benefits ======== Programmers are by nature a lazy breed. We reuse code with functions, classes, modules, and subsystems. Through its docstring syntax, Python allows us to document our code from within. The "holy grail" of the Python Documentation Special Interest Group (Doc-SIG_) has been a markup syntax and toolset to allow auto-documentation, where the docstrings of Python systems can be extracted in context and processed into useful, high-quality documentation for multiple purposes. Document markup languages have three groups of customers: the authors who write the documents, the software systems that process the data, and the readers, who are the final consumers and the most important group. Most markups are designed for the authors and software systems; readers are only meant to see the processed form, either on paper or via browser software. ReStructuredText is different: it is intended to be easily readable in source form, without prior knowledge of the markup. ReStructuredText is entirely readable in plaintext format, and many of the markup forms match common usage (e.g., ``*emphasis*``), so it reads quite naturally. Yet it is rich enough to produce complex documents, and extensible so that there are few limits. Of course, to write reStructuredText documents some prior knowledge is required. The markup offers functionality and expressivity, while maintaining easy readability in the source text. The processed form (HTML etc.) makes it all accessible to readers: inline live hyperlinks; live links to and from footnotes; automatic tables of contents (with live links!); tables; images for diagrams etc.; pleasant, readable styled text. The reStructuredText parser is available now, part of the Docutils_ project. Standalone reStructuredText documents and PEPs can be converted to HTML; other output format writers are being worked on and will become available over time. Work is progressing on a Python source "Reader" which will implement auto-documentation from docstrings. Authors of existing auto-documentation tools are encouraged to integrate the reStructuredText parser into their projects, or better yet, to join forces to produce a world-class toolset for the Python standard library. Tools will become available in the near future, which will allow programmers to generate HTML for online help, XML for multiple purposes, and eventually PDF, DocBook, and LaTeX for printed documentation, essentially "for free" from the existing docstrings. The adoption of a standard will, at the very least, benefit docstring processing tools by preventing further "reinventing the wheel". Eventually PyDoc, the one existing standard auto-documentation tool, could have reStructuredText support added. In the interim it will have no problem with reStructuredText markup, since it treats all docstrings as preformatted plaintext. Goals ===== These are the generally accepted goals for a docstring format, as discussed in the Doc-SIG: 1. It must be readable in source form by the casual observer. 2. It must be easy to type with any standard text editor. 3. It must not need to contain information which can be deduced from parsing the module. 4. It must contain sufficient information (structure) so it can be converted to any reasonable markup format. 5. It must be possible to write a module's entire documentation in docstrings, without feeling hampered by the markup language. reStructuredText meets and exceeds all of these goals, and sets its own goals as well, even more stringent. See `Docstring-Significant Features`_ below. The goals of this PEP are as follows: 1. To establish reStructuredText as a standard structured plaintext format for docstrings (inline documentation of Python modules and packages), PEPs, README-type files and other standalone documents. "Accepted" status will be sought through Python community consensus and eventual BDFL pronouncement. Please note that reStructuredText is being proposed as *a* standard, not *the only* standard. Its use will be entirely optional. Those who don't want to use it need not. 2. To solicit and address any related concerns raised by the Python community. 3. To encourage community support. As long as multiple competing markups are out there, the development community remains fractured. Once a standard exists, people will start to use it, and momentum will inevitably gather. 4. To consolidate efforts from related auto-documentation projects. It is hoped that interested developers will join forces and work on a joint/merged/common implementation. Once reStructuredText is a Python standard, effort can be focused on tools instead of arguing for a standard. Python needs a standard set of documentation tools. With regard to PEPs, one or both of the following strategies may be applied: a) Keep the existing PEP section structure constructs (one-line section headers, indented body text). Subsections can either be forbidden, or supported with reStructuredText-style underlined headers in the indented body text. b) Replace the PEP section structure constructs with the reStructuredText syntax. Section headers will require underlines, subsections will be supported out of the box, and body text need not be indented (except for block quotes). Strategy (b) is recommended, and its implementation is complete. Support for RFC 2822 headers has been added to the reStructuredText parser for PEPs (unambiguous given a specific context: the first contiguous block of the document). It may be desired to concretely specify what over/underline styles are allowed for PEP section headers, for uniformity. Rationale ========= The lack of a standard syntax for docstrings has hampered the development of standard tools for extracting and converting docstrings into documentation in standard formats (e.g., HTML, DocBook, TeX). There have been a number of proposed markup formats and variations, and many tools tied to these proposals, but without a standard docstring format they have failed to gain a strong following and/or floundered half-finished. Throughout the existence of the Doc-SIG, consensus on a single standard docstring format has never been reached. A lightweight, implicit markup has been sought, for the following reasons (among others): 1. Docstrings written within Python code are available from within the interactive interpreter, and can be "print"ed. Thus the use of plaintext for easy readability. 2. Programmers want to add structure to their docstrings, without sacrificing raw docstring readability. Unadorned plaintext cannot be transformed ("up-translated") into useful structured formats. 3. Explicit markup (like XML or TeX) is widely considered unreadable by the uninitiated. 4. Implicit markup is aesthetically compatible with the clean and minimalist Python syntax. Many alternative markups for docstrings have been proposed on the Doc-SIG over the years; a representative sample is listed below. Each is briefly analyzed in terms of the goals stated above. Please note that this is *not* intended to be an exclusive list of all existing markup systems; there are many other markups (Texinfo, Doxygen, TIM, YODL, AFT, ...) which are not mentioned. - XML_, SGML_, DocBook_, HTML_, XHTML_ XML and SGML are explicit, well-formed meta-languages suitable for all kinds of documentation. XML is a variant of SGML. They are best used behind the scenes, because to untrained eyes they are verbose, difficult to type, and too cluttered to read comfortably as source. DocBook, HTML, and XHTML are all applications of SGML and/or XML, and all share the same basic syntax and the same shortcomings. - TeX_ TeX is similar to XML/SGML in that it's explicit, but not very easy to write, and not easy for the uninitiated to read. - `Perl POD`_ Most Perl modules are documented in a format called POD (Plain Old Documentation). This is an easy-to-type, very low level format with strong integration with the Perl parser. Many tools exist to turn POD documentation into other formats: info, HTML and man pages, among others. However, the POD syntax takes after Perl itself in terms of readability. - JavaDoc_ Special comments before Java classes and functions serve to document the code. A program to extract these, and turn them into HTML documentation is called javadoc, and is part of the standard Java distribution. However, JavaDoc has a very intimate relationship with HTML, using HTML tags for most markup. Thus it shares the readability problems of HTML. - Setext_, StructuredText_ Early on, variants of Setext (Structure Enhanced Text), including Zope Corp's StructuredText, were proposed for Python docstring formatting. Hereafter these variants will collectively be called "STexts". STexts have the advantage of being easy to read without special knowledge, and relatively easy to write. Although used by some (including in most existing Python auto-documentation tools), until now STexts have failed to become standard because: - STexts have been incomplete. Lacking "essential" constructs that people want to use in their docstrings, STexts are rendered less than ideal. Note that these "essential" constructs are not universal; everyone has their own requirements. - STexts have been sometimes surprising. Bits of text are unexpectedly interpreted as being marked up, leading to user frustration. - SText implementations have been buggy. - Most STexts have have had no formal specification except for the implementation itself. A buggy implementation meant a buggy spec, and vice-versa. - There has been no mechanism to get around the SText markup rules when a markup character is used in a non-markup context. In other words, no way to escape markup. Proponents of implicit STexts have vigorously opposed proposals for explicit markup (XML, HTML, TeX, POD, etc.), and the debates have continued off and on since 1996 or earlier. reStructuredText is a complete revision and reinterpretation of the SText idea, addressing all of the problems listed above. Specification ============= The specification and user documentaton for reStructuredText is quite extensive. Rather than repeating or summarizing it all here, links to the originals are provided. Please first take a look at `A ReStructuredText Primer`_, a short and gentle introduction. The `Quick reStructuredText`_ user reference quickly summarizes all of the markup constructs. For complete and extensive details, please refer to the following documents: - `An Introduction to reStructuredText`_ - `reStructuredText Markup Specification`_ - `reStructuredText Directives`_ In addition, `Problems With StructuredText`_ explains many markup decisions made with regards to StructuredText, and `A Record of reStructuredText Syntax Alternatives`_ records markup decisions made independently. Docstring-Significant Features ============================== - A markup escaping mechanism. Backslashes (``\``) are used to escape markup characters when needed for non-markup purposes. However, the inline markup recognition rules have been constructed in order to minimize the need for backslash-escapes. For example, although asterisks are used for *emphasis*, in non-markup contexts such as "*" or "(*)" or "x * y", the asterisks are not interpreted as markup and are left unchanged. For many non-markup uses of backslashes (e.g., describing regular expressions), inline literals or literal blocks are applicable; see the next item. - Markup to include Python source code and Python interactive sessions: inline literals, literal blocks, and doctest blocks. Inline literals use ``double-backquotes`` to indicate program I/O or code snippets. No markup interpretation (including backslash-escape [``\``] interpretation) is done within inline literals. Literal blocks (block-level literal text, such as code excerpts or ASCII graphics) are indented, and indicated with a double-colon ("::") at the end of the preceding paragraph (right here -->):: if literal_block: text = 'is left as-is' spaces_and_linebreaks = 'are preserved' markup_processing = None Doctest blocks begin with ">>> " and end with a blank line. Neither indentation nor literal block double-colons are required. For example:: Here's a doctest block: >>> print 'Python-specific usage examples; begun with ">>>"' Python-specific usage examples; begun with ">>>" >>> print '(cut and pasted from interactive sessions)' (cut and pasted from interactive sessions) - Markup that isolates a Python identifier: interpreted text. Text enclosed in single backquotes is recognized as "interpreted text", whose interpretation is application-dependent. In the context of a Python docstring, the default interpretation of interpreted text is as Python identifiers. The text will be marked up with a hyperlink connected to the documentation for the identifier given. Lookup rules are the same as in Python itself: LGB namespace lookups (local, global, builtin). The "role" of the interpreted text (identifying a class, module, function, etc.) is determined implicitly from the namespace lookup. For example:: class Keeper(Storer): """ Keep data fresher longer. Extend `Storer`. Class attribute `instances` keeps track of the number of `Keeper` objects instantiated. """ instances = 0 """How many `Keeper` objects are there?""" def __init__(self): """ Extend `Storer.__init__()` to keep track of instances. Keep count in `self.instances` and data in `self.data`. """ Storer.__init__(self) self.instances += 1 self.data = [] """Store data in a list, most recent last.""" def storedata(self, data): """ Extend `Storer.storedata()`; append new `data` to a list (in `self.data`). """ self.data = data Each piece of interpreted text is looked up according to the local namespace of the block containing its docstring. - Markup that isolates a Python identifier and specifies its type: interpreted text with roles. Although the Python source context reader is designed not to require explicit roles, they may be used. To classify identifiers explicitly, the role is given along with the identifier in either prefix or suffix form:: Use :method:`Keeper.storedata` to store the object's data in `Keeper.data`:instance_attribute:. The syntax chosen for roles is verbose, but necessarily so (if anyone has a better alternative, please post it to the Doc-SIG_). The intention of the markup is that there should be little need to use explicit roles; their use is to be kept to an absolute minimum. - Markup for "tagged lists" or "label lists": field lists. Field lists represent a mapping from field name to field body. These are mostly used for extension syntax, such as "bibliographic field lists" (representing document metadata such as author, date, and version) and extension attributes for directives (see below). They may be used to implement methodologies (docstring semantics), such as identifying parameters, exceptions raised, etc.; such usage is beyond the scope of this PEP. A modified RFC 2822 syntax is used, with a colon *before* as well as *after* the field name. Field bodies are more versatile as well; they may contain multiple field bodies (even nested field lists). For example:: :Date: 2002-03-22 :Version: 1 :Authors: - Me - Myself - I Standard RFC 2822 header syntax cannot be used for this construct because it is ambiguous. A word followed by a colon at the beginning of a line is common in written text. - Markup extensibility: directives and substitutions. Directives are used as an extension mechanism for reStructuredText, a way of adding support for new block-level constructs without adding new syntax. Directives for images, admonitions (note, caution, etc.), and tables of contents generation (among others) have been implemented. For example, here's how to place an image:: .. image:: mylogo.png Substitution definitions allow the power and flexibility of block-level directives to be shared by inline text. For example:: The |biohazard| symbol must be used on containers used to dispose of medical waste. .. |biohazard| image:: biohazard.png - Section structure markup. Section headers in reStructuredText use adornment via underlines (and possibly overlines) rather than indentation. For example:: This is a Section Title ======================= This is a Subsection Title -------------------------- This paragraph is in the subsection. This is Another Section Title ============================= This paragraph is in the second section. Questions & Answers =================== 1. Is reStructuredText rich enough? Yes, it is for most people. If it lacks some construct that is required for a specific application, it can be added via the directive mechanism. If a useful and common construct has been overlooked and a suitably readable syntax can be found, it can be added to the specification and parser. 2. Is reStructuredText *too* rich? For specific applications or individuals, perhaps. In general, no. Since the very beginning, whenever a docstring markup syntax has been proposed on the Doc-SIG_, someone has complained about the lack of support for some construct or other. The reply was often something like, "These are docstrings we're talking about, and docstrings shouldn't have complex markup." The problem is that a construct that seems superfluous to one person may be absolutely essential to another. reStructuredText takes the opposite approach: it provides a rich set of implicit markup constructs (plus a generic extension mechanism for explicit markup), allowing for all kinds of documents. If the set of constructs is too rich for a particular application, the unused constructs can either be removed from the parser (via application-specific overrides) or simply omitted by convention. 3. Why not use indentation for section structure, like StructuredText does? Isn't it more "Pythonic"? Guido van Rossum wrote the following in a 2001-06-13 Doc-SIG post: I still think that using indentation to indicate sectioning is wrong. If you look at how real books and other print publications are laid out, you'll notice that indentation is used frequently, but mostly at the intra-section level. Indentation can be used to offset lists, tables, quotations, examples, and the like. (The argument that docstrings are different because they are input for a text formatter is wrong: the whole point is that they are also readable without processing.) I reject the argument that using indentation is Pythonic: text is not code, and different traditions and conventions hold. People have been presenting text for readability for over 30 centuries. Let's not innovate needlessly. See `Section Structure via Indentation`__ in `Problems With StructuredText`_ for further elaboration. __ http://docutils.sourceforge.net/docs/dev/rst/problems.html #section-structure-via-indentation 4. Why use reStructuredText for PEPs? What's wrong with the existing standard? The existing standard for PEPs is very limited in terms of general expressibility, and referencing is especially lacking for such a reference-rich document type. PEPs are currently converted into HTML, but the results (mostly monospaced text) are less than attractive, and most of the value-added potential of HTML (especially inline hyperlinks) is untapped. Making reStructuredText a standard markup for PEPs will enable much richer expression, including support for section structure, inline markup, graphics, and tables. In several PEPs there are ASCII graphics diagrams, which are all that plaintext documents can support. Since PEPs are made available in HTML form, the ability to include proper diagrams would be immediately useful. Current PEP practices allow for reference markers in the form "[1]" in the text, and the footnotes/references themselves are listed in a section toward the end of the document. There is currently no hyperlinking between the reference marker and the footnote/reference itself (it would be possible to add this to pep2html.py, but the "markup" as it stands is ambiguous and mistakes would be inevitable). A PEP with many references (such as this one ;-) requires a lot of flipping back and forth. When revising a PEP, often new references are added or unused references deleted. It is painful to renumber the references, since it has to be done in two places and can have a cascading effect (insert a single new reference 1, and every other reference has to be renumbered; always adding new references to the end is suboptimal). It is easy for references to go out of sync. PEPs use references for two purposes: simple URL references and footnotes. reStructuredText differentiates between the two. A PEP might contain references like this:: Abstract This PEP proposes adding frungible doodads [1] to the core. It extends PEP 9876 [2] via the BCA [3] mechanism. ... References and Footnotes [1] http://www.example.org/ [2] PEP 9876, Let's Hope We Never Get Here http://www.python.org/peps/pep-9876.html [3] "Bogus Complexity Addition" Reference 1 is a simple URL reference. Reference 2 is a footnote containing text and a URL. Reference 3 is a footnote containing text only. Rewritten using reStructuredText, this PEP could look like this:: Abstract ======== This PEP proposes adding `frungible doodads`_ to the core. It extends PEP 9876 [#pep9876]_ via the BCA [#]_ mechanism. ... References & Footnotes ====================== .. _frungible doodads: http://www.example.org/ .. [#pep9876] PEP 9876, Let's Hope We Never Get Here .. [#] "Bogus Complexity Addition" URLs and footnotes can be defined close to their references if desired, making them easier to read in the source text, and making the PEPs easier to revise. The "References and Footnotes" section can be auto-generated with a document tree transform. Footnotes from throughout the PEP would be gathered and displayed under a standard header. If URL references should likewise be written out explicitly (in citation form), another tree transform could be used. URL references can be named ("frungible doodads"), and can be referenced from multiple places in the document without additional definitions. When converted to HTML, references will be replaced with inline hyperlinks (HTML <a> tags). The two footnotes are automatically numbered, so they will always stay in sync. The first footnote also contains an internal reference name, "pep9876", so it's easier to see the connection between reference and footnote in the source text. Named footnotes can be referenced multiple times, maintaining consistent numbering. The "#pep9876" footnote could also be written in the form of a citation:: It extends PEP 9876 [PEP9876]_ ... .. [PEP9876] PEP 9876, Let's Hope We Never Get Here Footnotes are numbered, whereas citations use text for their references. 5. Wouldn't it be better to keep the docstring and PEP proposals separate? The PEP markup proposal may be removed if it is deemed that there is no need for PEP markup, or it could be made into a separate PEP. If accepted, PEP 1, PEP Purpose and Guidelines [#PEP-1]_, and PEP 9, Sample PEP Template [#PEP-9]_ will be updated. It seems natural to adopt a single consistent markup standard for all uses of structured plaintext in Python, and to propose it all in one place. 6. The existing pep2html.py script converts the existing PEP format to HTML. How will the new-format PEPs be converted to HTML? A new version of pep2html.py with integrated reStructuredText parsing has been completed. The Docutils project supports PEPs with a "PEP Reader" component, including all functionality currently in pep2html.py (auto-recognition of PEP & RFC references, email masking, etc.). 7. Who's going to convert the existing PEPs to reStructuredText? PEP authors or volunteers may convert existing PEPs if they like, but there is no requirement to do so. The reStructuredText-based PEPs will coexist with the old PEP standard. The pep2html.py mentioned in answer 6 processes both old and new standards. 8. Why use reStructuredText for README and other ancillary files? The reasoning given for PEPs in answer 4 above also applies to README and other ancillary files. By adopting a standard markup, these files can be converted to attractive cross-referenced HTML and put up on python.org. Developers of other projects can also take advantage of this facility for their own documentation. 9. Won't the superficial similarity to existing markup conventions cause problems, and result in people writing invalid markup (and not noticing, because the plaintext looks natural)? How forgiving is reStructuredText of "not quite right" markup? There will be some mis-steps, as there would be when moving from one programming language to another. As with any language, proficiency grows with experience. Luckily, reStructuredText is a very little language indeed. As with any syntax, there is the possibility of syntax errors. It is expected that a user will run the processing system over their input and check the output for correctness. In a strict sense, the reStructuredText parser is very unforgiving (as it should be; "In the face of ambiguity, refuse the temptation to guess" [#Zen]_ applies to parsing markup as well as computer languages). Here's design goal 3 from `An Introduction to reStructuredText`_: Unambiguous. The rules for markup must not be open for interpretation. For any given input, there should be one and only one possible output (including error output). While unforgiving, at the same time the parser does try to be helpful by producing useful diagnostic output ("system messages"). The parser reports problems, indicating their level of severity (from least to most: debug, info, warning, error, severe). The user or the client software can decide on reporting thresholds; they can ignore low-level problems or cause high-level problems to bring processing to an immediate halt. Problems are reported during the parse as well as included in the output, often with two-way links between the source of the problem and the system message explaining it. 10. Will the docstrings in the Python standard library modules be converted to reStructuredText? No. Python's library reference documentation is maintained separately from the source. Docstrings in the Python standard library should not try to duplicate the library reference documentation. The current policy for docstrings in the Python standard library is that they should be no more than concise hints, simple and markup-free (although many *do* contain ad-hoc implicit markup). 11. I want to write all my strings in Unicode. Will anything break? The parser fully supports Unicode. Docutils supports arbitrary input and output encodings. 12. Why does the community need a new structured text design? The existing structured text designs are deficient, for the reasons given in "Rationale" above. reStructuredText aims to be a complete markup syntax, within the limitations of the "readable plaintext" medium. 13. What is wrong with existing documentation methodologies? What existing methodologies? For Python docstrings, there is **no** official standard markup format, let alone a documentation methodology akin to JavaDoc. The question of methodology is at a much higher level than syntax (which this PEP addresses). It is potentially much more controversial and difficult to resolve, and is intentionally left out of this discussion. References & Footnotes ====================== .. [#PEP-1] PEP 1, PEP Guidelines, Warsaw, Hylton (http://www.python.org/peps/pep-0001.html) .. [#PEP-9] PEP 9, Sample PEP Template, Warsaw (http://www.python.org/peps/pep-0009.html) .. [#Zen] From `The Zen of Python (by Tim Peters)`__ (or just "``import this``" in Python) __ http://www.python.org/doc/Humor.html#zen .. [#PEP-216] PEP 216, Docstring Format, Zadka (http://www.python.org/peps/pep-0216.html) .. _reStructuredText markup: http://docutils.sourceforge.net/rst.html .. _Doc-SIG: http://www.python.org/sigs/doc-sig/ .. _XML: http://www.w3.org/XML/ .. _SGML: http://www.oasis-open.org/cover/general.html .. _DocBook: http://docbook.org/tdg/en/html/docbook.html .. _HTML: http://www.w3.org/MarkUp/ .. _XHTML: http://www.w3.org/MarkUp/#xhtml1 .. _TeX: http://www.tug.org/interest.html .. _Perl POD: http://perldoc.perl.org/perlpod.html .. _JavaDoc: http://java.sun.com/j2se/javadoc/ .. _Setext: http://docutils.sourceforge.net/mirror/setext.html .. _StructuredText: http://www.zope.org/DevHome/Members/jim/StructuredTextWiki/FrontPage .. _A ReStructuredText Primer: http://docutils.sourceforge.net/docs/user/rst/quickstart.html .. _Quick reStructuredText: http://docutils.sourceforge.net/docs/user/rst/quickref.html .. _An Introduction to reStructuredText: http://docutils.sourceforge.net/docs/ref/rst/introduction.html .. _reStructuredText Markup Specification: http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html .. _reStructuredText Directives: http://docutils.sourceforge.net/docs/ref/rst/directives.html .. _Problems with StructuredText: http://docutils.sourceforge.net/docs/dev/rst/problems.html .. _A Record of reStructuredText Syntax Alternatives: http://docutils.sourceforge.net/docs/dev/rst/alternatives.html .. _Docutils: http://docutils.sourceforge.net/ Copyright ========= This document has been placed in the public domain. Acknowledgements ================ Some text is borrowed from PEP 216, Docstring Format [#PEP-216]_, by Moshe Zadka. Special thanks to all members past & present of the Python Doc-SIG_. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/docs/peps/pep-0258.txt����������������������������������������������������������������0000664�0001750�0001750�00000106626�11262442032�021053� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������PEP: 258 Title: Docutils Design Specification Version: $Revision: 6154 $ Last-Modified: $Date: 2009-10-05 21:08:10 +0200 (Mon, 05. Okt 2009) $ Author: David Goodger <goodger@python.org> Discussions-To: <doc-sig@python.org> Status: Draft Type: Standards Track Content-Type: text/x-rst Requires: 256, 257 Created: 31-May-2001 Post-History: 13-Jun-2001 ========== Abstract ========== This PEP documents design issues and implementation details for Docutils, a Python Docstring Processing System (DPS). The rationale and high-level concepts of a DPS are documented in PEP 256, "Docstring Processing System Framework" [#PEP-256]_. Also see PEP 256 for a "Road Map to the Docstring PEPs". Docutils is being designed modularly so that any of its components can be replaced easily. In addition, Docutils is not limited to the processing of Python docstrings; it processes standalone documents as well, in several contexts. No changes to the core Python language are required by this PEP. Its deliverables consist of a package for the standard library and its documentation. =============== Specification =============== Docutils Project Model ====================== Project components and data flow:: +---------------------------+ | Docutils: | | docutils.core.Publisher, | | docutils.core.publish_*() | +---------------------------+ / | \ / | \ 1,3,5 / 6 | \ 7 +--------+ +-------------+ +--------+ | READER | ----> | TRANSFORMER | ====> | WRITER | +--------+ +-------------+ +--------+ / \\ | / \\ | 2 / 4 \\ 8 | +-------+ +--------+ +--------+ | INPUT | | PARSER | | OUTPUT | +-------+ +--------+ +--------+ The numbers above each component indicate the path a document's data takes. Double-width lines between Reader & Parser and between Transformer & Writer indicate that data sent along these paths should be standard (pure & unextended) Docutils doc trees. Single-width lines signify that internal tree extensions or completely unrelated representations are possible, but they must be supported at both ends. Publisher --------- The ``docutils.core`` module contains a "Publisher" facade class and several convenience functions: "publish_cmdline()" (for command-line front ends), "publish_file()" (for programmatic use with file-like I/O), and "publish_string()" (for programmatic use with string I/O). The Publisher class encapsulates the high-level logic of a Docutils system. The Publisher class has overall responsibility for processing, controlled by the ``Publisher.publish()`` method: 1. Set up internal settings (may include config files & command-line options) and I/O objects. 2. Call the Reader object to read data from the source Input object and parse the data with the Parser object. A document object is returned. 3. Set up and apply transforms via the Transformer object attached to the document. 4. Call the Writer object which translates the document to the final output format and writes the formatted data to the destination Output object. Depending on the Output object, the output may be returned from the Writer, and then from the ``publish()`` method. Calling the "publish" function (or instantiating a "Publisher" object) with component names will result in default behavior. For custom behavior (customizing component settings), create custom component objects first, and pass *them* to the Publisher or ``publish_*`` convenience functions. Readers ------- Readers understand the input context (where the data is coming from), send the whole input or discrete "chunks" to the parser, and provide the context to bind the chunks together back into a cohesive whole. Each reader is a module or package exporting a "Reader" class with a "read" method. The base "Reader" class can be found in the ``docutils/readers/__init__.py`` module. Most Readers will have to be told what parser to use. So far (see the list of examples below), only the Python Source Reader ("PySource"; still incomplete) will be able to determine the parser on its own. Responsibilities: * Get input text from the source I/O. * Pass the input text to the parser, along with a fresh `document tree`_ root. Examples: * Standalone (Raw/Plain): Just read a text file and process it. The reader needs to be told which parser to use. The "Standalone Reader" has been implemented in module ``docutils.readers.standalone``. * Python Source: See `Python Source Reader`_ below. This Reader is currently in development in the Docutils sandbox. * Email: RFC-822 headers, quoted excerpts, signatures, MIME parts. * PEP: RFC-822 headers, "PEP xxxx" and "RFC xxxx" conversion to URIs. The "PEP Reader" has been implemented in module ``docutils.readers.pep``; see PEP 287 and PEP 12. * Wiki: Global reference lookups of "wiki links" incorporated into transforms. (CamelCase only or unrestricted?) Lazy indentation? * Web Page: As standalone, but recognize meta fields as meta tags. Support for templates of some sort? (After ``<body>``, before ``</body>``?) * FAQ: Structured "question & answer(s)" constructs. * Compound document: Merge chapters into a book. Master manifest file? Parsers ------- Parsers analyze their input and produce a Docutils `document tree`_. They don't know or care anything about the source or destination of the data. Each input parser is a module or package exporting a "Parser" class with a "parse" method. The base "Parser" class can be found in the ``docutils/parsers/__init__.py`` module. Responsibilities: Given raw input text and a doctree root node, populate the doctree by parsing the input text. Example: The only parser implemented so far is for the reStructuredText markup. It is implemented in the ``docutils/parsers/rst/`` package. The development and integration of other parsers is possible and encouraged. .. _transforms: Transformer ----------- The Transformer class, in ``docutils/transforms/__init__.py``, stores transforms and applies them to documents. A transformer object is attached to every new document tree. The Publisher_ calls ``Transformer.apply_transforms()`` to apply all stored transforms to the document tree. Transforms change the document tree from one form to another, add to the tree, or prune it. Transforms resolve references and footnote numbers, process interpreted text, and do other context-sensitive processing. Some transforms are specific to components (Readers, Parser, Writers, Input, Output). Standard component-specific transforms are specified in the ``default_transforms`` attribute of component classes. After the Reader has finished processing, the Publisher_ calls ``Transformer.populate_from_components()`` with a list of components and all default transforms are stored. Each transform is a class in a module in the ``docutils/transforms/`` package, a subclass of ``docutils.tranforms.Transform``. Transform classes each have a ``default_priority`` attribute which is used by the Transformer to apply transforms in order (low to high). The default priority can be overridden when adding transforms to the Transformer object. Transformer responsibilities: * Apply transforms to the document tree, in priority order. * Store a mapping of component type name ('reader', 'writer', etc.) to component objects. These are used by certain transforms (such as "components.Filter") to determine suitability. Transform responsibilities: * Modify a doctree in-place, either purely transforming one structure into another, or adding new structures based on the doctree and/or external data. Examples of transforms (in the ``docutils/transforms/`` package): * frontmatter.DocInfo: Conversion of document metadata (bibliographic information). * references.AnonymousHyperlinks: Resolution of anonymous references to corresponding targets. * parts.Contents: Generates a table of contents for a document. * document.Merger: Combining multiple populated doctrees into one. (Not yet implemented or fully understood.) * document.Splitter: Splits a document into a tree-structure of subdocuments, perhaps by section. It will have to transform references appropriately. (Neither implemented not remotely understood.) * components.Filter: Includes or excludes elements which depend on a specific Docutils component. Writers ------- Writers produce the final output (HTML, XML, TeX, etc.). Writers translate the internal `document tree`_ structure into the final data format, possibly running Writer-specific transforms_ first. By the time the document gets to the Writer, it should be in final form. The Writer's job is simply (and only) to translate from the Docutils doctree structure to the target format. Some small transforms may be required, but they should be local and format-specific. Each writer is a module or package exporting a "Writer" class with a "write" method. The base "Writer" class can be found in the ``docutils/writers/__init__.py`` module. Responsibilities: * Translate doctree(s) into specific output formats. - Transform references into format-native forms. * Write the translated output to the destination I/O. Examples: * XML: Various forms, such as: - Docutils XML (an expression of the internal document tree, implemented as ``docutils.writers.docutils_xml``). - DocBook (being implemented in the Docutils sandbox). * HTML (XHTML implemented as ``docutils.writers.html4css1``). * PDF (a ReportLabs interface is being developed in the Docutils sandbox). * TeX (a LaTeX Writer is being implemented in the sandbox). * Docutils-native pseudo-XML (implemented as ``docutils.writers.pseudoxml``, used for testing). * Plain text * reStructuredText? Input/Output ------------ I/O classes provide a uniform API for low-level input and output. Subclasses will exist for a variety of input/output mechanisms. However, they can be considered an implementation detail. Most applications should be satisfied using one of the convenience functions associated with the Publisher_. I/O classes are currently in the preliminary stages; there's a lot of work yet to be done. Issues: * How to represent multi-file input (files & directories) in the API? * How to represent multi-file output? Perhaps "Writer" variants, one for each output distribution type? Or Output objects with associated transforms? Responsibilities: * Read data from the input source (Input objects) or write data to the output destination (Output objects). Examples of input sources: * A single file on disk or a stream (implemented as ``docutils.io.FileInput``). * Multiple files on disk (``MultiFileInput``?). * Python source files: modules and packages. * Python strings, as received from a client application (implemented as ``docutils.io.StringInput``). Examples of output destinations: * A single file on disk or a stream (implemented as ``docutils.io.FileOutput``). * A tree of directories and files on disk. * A Python string, returned to a client application (implemented as ``docutils.io.StringOutput``). * No output; useful for programmatic applications where only a portion of the normal output is to be used (implemented as ``docutils.io.NullOutput``). * A single tree-shaped data structure in memory. * Some other set of data structures in memory. Docutils Package Structure ========================== * Package "docutils". - Module "__init__.py" contains: class "Component", a base class for Docutils components; class "SettingsSpec", a base class for specifying runtime settings (used by docutils.frontend); and class "TransformSpec", a base class for specifying transforms. - Module "docutils.core" contains facade class "Publisher" and convenience functions. See `Publisher`_ above. - Module "docutils.frontend" provides runtime settings support, for programmatic use and front-end tools (including configuration file support, and command-line argument and option processing). - Module "docutils.io" provides a uniform API for low-level input and output. See `Input/Output`_ above. - Module "docutils.nodes" contains the Docutils document tree element class library plus tree-traversal Visitor pattern base classes. See `Document Tree`_ below. - Module "docutils.statemachine" contains a finite state machine specialized for regular-expression-based text filters and parsers. The reStructuredText parser implementation is based on this module. - Module "docutils.urischemes" contains a mapping of known URI schemes ("http", "ftp", "mail", etc.). - Module "docutils.utils" contains utility functions and classes, including a logger class ("Reporter"; see `Error Handling`_ below). - Package "docutils.parsers": markup parsers_. - Function "get_parser_class(parser_name)" returns a parser module by name. Class "Parser" is the base class of specific parsers. (``docutils/parsers/__init__.py``) - Package "docutils.parsers.rst": the reStructuredText parser. - Alternate markup parsers may be added. See `Parsers`_ above. - Package "docutils.readers": context-aware input readers. - Function "get_reader_class(reader_name)" returns a reader module by name or alias. Class "Reader" is the base class of specific readers. (``docutils/readers/__init__.py``) - Module "docutils.readers.standalone" reads independent document files. - Module "docutils.readers.pep" reads PEPs (Python Enhancement Proposals). - Module "docutils.readers.doctree" is used to re-read a previously stored document tree for reprocessing. - Readers to be added for: Python source code (structure & docstrings), email, FAQ, and perhaps Wiki and others. See `Readers`_ above. - Package "docutils.writers": output format writers. - Function "get_writer_class(writer_name)" returns a writer module by name. Class "Writer" is the base class of specific writers. (``docutils/writers/__init__.py``) - Package "docutils.writers.html4css1" is a simple HyperText Markup Language document tree writer for HTML 4.01 and CSS1. - Package "docutils.writers.pep_html" generates HTML from reStructuredText PEPs. - Package "docutils.writers.s5_html" generates S5/HTML slide shows. - Package "docutils.writers.latex2e" writes LaTeX. - Package "docutils.writers.newlatex2e" also writes LaTeX; it is a new implementation. - Module "docutils.writers.docutils_xml" writes the internal document tree in XML form. - Module "docutils.writers.pseudoxml" is a simple internal document tree writer; it writes indented pseudo-XML. - Module "docutils.writers.null" is a do-nothing writer; it is used for specialized purposes such as storing the internal document tree. - Writers to be added: HTML 3.2 or 4.01-loose, XML (various forms, such as DocBook), PDF, plaintext, reStructuredText, and perhaps others. Subpackages of "docutils.writers" contain modules and data files (such as stylesheets) that support the individual writers. See `Writers`_ above. - Package "docutils.transforms": tree transform classes. - Class "Transformer" stores transforms and applies them to document trees. (``docutils/transforms/__init__.py``) - Class "Transform" is the base class of specific transforms. (``docutils/transforms/__init__.py``) - Each module contains related transform classes. See `Transforms`_ above. - Package "docutils.languages": Language modules contain language-dependent strings and mappings. They are named for their language identifier (as defined in `Choice of Docstring Format`_ below), converting dashes to underscores. - Function "get_language(language_code)", returns matching language module. (``docutils/languages/__init__.py``) - Modules: en.py (English), de.py (German), fr.py (French), it.py (Italian), sk.py (Slovak), sv.py (Swedish). - Other languages to be added. * Third-party modules: "extras" directory. These modules are installed only if they're not already present in the Python installation. - ``extras/roman.py`` contains Roman numeral conversion routines. Front-End Tools =============== The ``tools/`` directory contains several front ends for common Docutils processing. See `Docutils Front-End Tools`_ for details. .. _Docutils Front-End Tools: http://docutils.sourceforge.net/docs/user/tools.html Document Tree ============= A single intermediate data structure is used internally by Docutils, in the interfaces between components; it is defined in the ``docutils.nodes`` module. It is not required that this data structure be used *internally* by any of the components, just *between* components as outlined in the diagram in the `Docutils Project Model`_ above. Custom node types are allowed, provided that either (a) a transform converts them to standard Docutils nodes before they reach the Writer proper, or (b) the custom node is explicitly supported by certain Writers, and is wrapped in a filtered "pending" node. An example of condition (a) is the `Python Source Reader`_ (see below), where a "stylist" transform converts custom nodes. The HTML ``<meta>`` tag is an example of condition (b); it is supported by the HTML Writer but not by others. The reStructuredText "meta" directive creates a "pending" node, which contains knowledge that the embedded "meta" node can only be handled by HTML-compatible writers. The "pending" node is resolved by the ``docutils.transforms.components.Filter`` transform, which checks that the calling writer supports HTML; if it doesn't, the "pending" node (and enclosed "meta" node) is removed from the document. The document tree data structure is similar to a DOM tree, but with specific node names (classes) instead of DOM's generic nodes. The schema is documented in an XML DTD (eXtensible Markup Language Document Type Definition), which comes in two parts: * the Docutils Generic DTD, docutils.dtd_, and * the OASIS Exchange Table Model, soextbl.dtd_. The DTD defines a rich set of elements, suitable for many input and output formats. The DTD retains all information necessary to reconstruct the original input text, or a reasonable facsimile thereof. See `The Docutils Document Tree`_ for details (incomplete). Error Handling ============== When the parser encounters an error in markup, it inserts a system message (DTD element "system_message"). There are five levels of system messages: * Level-0, "DEBUG": an internal reporting issue. There is no effect on the processing. Level-0 system messages are handled separately from the others. * Level-1, "INFO": a minor issue that can be ignored. There is little or no effect on the processing. Typically level-1 system messages are not reported. * Level-2, "WARNING": an issue that should be addressed. If ignored, there may be minor problems with the output. Typically level-2 system messages are reported but do not halt processing. * Level-3, "ERROR": a major issue that should be addressed. If ignored, the output will contain unpredictable errors. Typically level-3 system messages are reported but do not halt processing. * Level-4, "SEVERE": a critical error that must be addressed. Typically level-4 system messages are turned into exceptions which do halt processing. If ignored, the output will contain severe errors. Although the initial message levels were devised independently, they have a strong correspondence to `VMS error condition severity levels`_; the names in quotes for levels 1 through 4 were borrowed from VMS. Error handling has since been influenced by the `log4j project`_. Python Source Reader ==================== The Python Source Reader ("PySource") is the Docutils component that reads Python source files, extracts docstrings in context, then parses, links, and assembles the docstrings into a cohesive whole. It is a major and non-trivial component, currently under experimental development in the Docutils sandbox. High-level design issues are presented here. Processing Model ---------------- This model will evolve over time, incorporating experience and discoveries. 1. The PySource Reader uses an Input class to read in Python packages and modules, into a tree of strings. 2. The Python modules are parsed, converting the tree of strings into a tree of abstract syntax trees with docstring nodes. 3. The abstract syntax trees are converted into an internal representation of the packages/modules. Docstrings are extracted, as well as code structure details. See `AST Mining`_ below. Namespaces are constructed for lookup in step 6. 4. One at a time, the docstrings are parsed, producing standard Docutils doctrees. 5. PySource assembles all the individual docstrings' doctrees into a Python-specific custom Docutils tree paralleling the package/module/class structure; this is a custom Reader-specific internal representation (see the `Docutils Python Source DTD`_). Namespaces must be merged: Python identifiers, hyperlink targets. 6. Cross-references from docstrings (interpreted text) to Python identifiers are resolved according to the Python namespace lookup rules. See `Identifier Cross-References`_ below. 7. A "Stylist" transform is applied to the custom doctree (by the Transformer_), custom nodes are rendered using standard nodes as primitives, and a standard document tree is emitted. See `Stylist Transforms`_ below. 8. Other transforms are applied to the standard doctree by the Transformer_. 9. The standard doctree is sent to a Writer, which translates the document into a concrete format (HTML, PDF, etc.). 10. The Writer uses an Output class to write the resulting data to its destination (disk file, directories and files, etc.). AST Mining ---------- Abstract Syntax Tree mining code will be written (or adapted) that scans a parsed Python module, and returns an ordered tree containing the names, docstrings (including attribute and additional docstrings; see below), and additional info (in parentheses below) of all of the following objects: * packages * modules * module attributes (+ initial values) * classes (+ inheritance) * class attributes (+ initial values) * instance attributes (+ initial values) * methods (+ parameters & defaults) * functions (+ parameters & defaults) (Extract comments too? For example, comments at the start of a module would be a good place for bibliographic field lists.) In order to evaluate interpreted text cross-references, namespaces for each of the above will also be required. See the python-dev/docstring-develop thread "AST mining", started on 2001-08-14. Docstring Extraction Rules -------------------------- 1. What to examine: a) If the "``__all__``" variable is present in the module being documented, only identifiers listed in "``__all__``" are examined for docstrings. b) In the absence of "``__all__``", all identifiers are examined, except those whose names are private (names begin with "_" but don't begin and end with "__"). c) 1a and 1b can be overridden by runtime settings. 2. Where: Docstrings are string literal expressions, and are recognized in the following places within Python modules: a) At the beginning of a module, function definition, class definition, or method definition, after any comments. This is the standard for Python ``__doc__`` attributes. b) Immediately following a simple assignment at the top level of a module, class definition, or ``__init__`` method definition, after any comments. See `Attribute Docstrings`_ below. c) Additional string literals found immediately after the docstrings in (a) and (b) will be recognized, extracted, and concatenated. See `Additional Docstrings`_ below. d) @@@ 2.2-style "properties" with attribute docstrings? Wait for syntax? 3. How: Whenever possible, Python modules should be parsed by Docutils, not imported. There are several reasons: - Importing untrusted code is inherently insecure. - Information from the source is lost when using introspection to examine an imported module, such as comments and the order of definitions. - Docstrings are to be recognized in places where the byte-code compiler ignores string literal expressions (2b and 2c above), meaning importing the module will lose these docstrings. Of course, standard Python parsing tools such as the "parser" library module should be used. When the Python source code for a module is not available (i.e. only the ``.pyc`` file exists) or for C extension modules, to access docstrings the module can only be imported, and any limitations must be lived with. Since attribute docstrings and additional docstrings are ignored by the Python byte-code compiler, no namespace pollution or runtime bloat will result from their use. They are not assigned to ``__doc__`` or to any other attribute. The initial parsing of a module may take a slight performance hit. Attribute Docstrings '''''''''''''''''''' (This is a simplified version of PEP 224 [#PEP-224]_.) A string literal immediately following an assignment statement is interpreted by the docstring extraction machinery as the docstring of the target of the assignment statement, under the following conditions: 1. The assignment must be in one of the following contexts: a) At the top level of a module (i.e., not nested inside a compound statement such as a loop or conditional): a module attribute. b) At the top level of a class definition: a class attribute. c) At the top level of the "``__init__``" method definition of a class: an instance attribute. Instance attributes assigned in other methods are assumed to be implementation details. (@@@ ``__new__`` methods?) d) A function attribute assignment at the top level of a module or class definition. Since each of the above contexts are at the top level (i.e., in the outermost suite of a definition), it may be necessary to place dummy assignments for attributes assigned conditionally or in a loop. 2. The assignment must be to a single target, not to a list or a tuple of targets. 3. The form of the target: a) For contexts 1a and 1b above, the target must be a simple identifier (not a dotted identifier, a subscripted expression, or a sliced expression). b) For context 1c above, the target must be of the form "``self.attrib``", where "``self``" matches the "``__init__``" method's first parameter (the instance parameter) and "attrib" is a simple identifier as in 3a. c) For context 1d above, the target must be of the form "``name.attrib``", where "``name``" matches an already-defined function or method name and "attrib" is a simple identifier as in 3a. Blank lines may be used after attribute docstrings to emphasize the connection between the assignment and the docstring. Examples:: g = 'module attribute (module-global variable)' """This is g's docstring.""" class AClass: c = 'class attribute' """This is AClass.c's docstring.""" def __init__(self): """Method __init__'s docstring.""" self.i = 'instance attribute' """This is self.i's docstring.""" def f(x): """Function f's docstring.""" return x**2 f.a = 1 """Function attribute f.a's docstring.""" Additional Docstrings ''''''''''''''''''''' (This idea was adapted from PEP 216 [#PEP-216]_.) Many programmers would like to make extensive use of docstrings for API documentation. However, docstrings do take up space in the running program, so some programmers are reluctant to "bloat up" their code. Also, not all API documentation is applicable to interactive environments, where ``__doc__`` would be displayed. Docutils' docstring extraction tools will concatenate all string literal expressions which appear at the beginning of a definition or after a simple assignment. Only the first strings in definitions will be available as ``__doc__``, and can be used for brief usage text suitable for interactive sessions; subsequent string literals and all attribute docstrings are ignored by the Python byte-code compiler and may contain more extensive API information. Example:: def function(arg): """This is __doc__, function's docstring.""" """ This is an additional docstring, ignored by the byte-code compiler, but extracted by Docutils. """ pass .. topic:: Issue: ``from __future__ import`` This would break "``from __future__ import``" statements introduced in Python 2.1 for multiple module docstrings (main docstring plus additional docstring(s)). The Python Reference Manual specifies: A future statement must appear near the top of the module. The only lines that can appear before a future statement are: * the module docstring (if any), * comments, * blank lines, and * other future statements. Resolution? 1. Should we search for docstrings after a ``__future__`` statement? Very ugly. 2. Redefine ``__future__`` statements to allow multiple preceding string literals? 3. Or should we not even worry about this? There probably shouldn't be ``__future__`` statements in production code, after all. Perhaps modules with ``__future__`` statements will simply have to put up with the single-docstring limitation. Choice of Docstring Format -------------------------- Rather than force everyone to use a single docstring format, multiple input formats are allowed by the processing system. A special variable, ``__docformat__``, may appear at the top level of a module before any function or class definitions. Over time or through decree, a standard format or set of formats should emerge. A module's ``__docformat__`` variable only applies to the objects defined in the module's file. In particular, the ``__docformat__`` variable in a package's ``__init__.py`` file does not apply to objects defined in subpackages and submodules. The ``__docformat__`` variable is a string containing the name of the format being used, a case-insensitive string matching the input parser's module or package name (i.e., the same name as required to "import" the module or package), or a registered alias. If no ``__docformat__`` is specified, the default format is "plaintext" for now; this may be changed to the standard format if one is ever established. The ``__docformat__`` string may contain an optional second field, separated from the format name (first field) by a single space: a case-insensitive language identifier as defined in RFC 1766. A typical language identifier consists of a 2-letter language code from `ISO 639`_ (3-letter codes used only if no 2-letter code exists; RFC 1766 is currently being revised to allow 3-letter codes). If no language identifier is specified, the default is "en" for English. The language identifier is passed to the parser and can be used for language-dependent markup features. Identifier Cross-References --------------------------- In Python docstrings, interpreted text is used to classify and mark up program identifiers, such as the names of variables, functions, classes, and modules. If the identifier alone is given, its role is inferred implicitly according to the Python namespace lookup rules. For functions and methods (even when dynamically assigned), parentheses ('()') may be included:: This function uses `another()` to do its work. For class, instance and module attributes, dotted identifiers are used when necessary. For example (using reStructuredText markup):: class Keeper(Storer): """ Extend `Storer`. Class attribute `instances` keeps track of the number of `Keeper` objects instantiated. """ instances = 0 """How many `Keeper` objects are there?""" def __init__(self): """ Extend `Storer.__init__()` to keep track of instances. Keep count in `Keeper.instances`, data in `self.data`. """ Storer.__init__(self) Keeper.instances += 1 self.data = [] """Store data in a list, most recent last.""" def store_data(self, data): """ Extend `Storer.store_data()`; append new `data` to a list (in `self.data`). """ self.data = data Each of the identifiers quoted with backquotes ("`") will become references to the definitions of the identifiers themselves. Stylist Transforms ------------------ Stylist transforms are specialized transforms specific to the PySource Reader. The PySource Reader doesn't have to make any decisions as to style; it just produces a logically constructed document tree, parsed and linked, including custom node types. Stylist transforms understand the custom nodes created by the Reader and convert them into standard Docutils nodes. Multiple Stylist transforms may be implemented and one can be chosen at runtime (through a "--style" or "--stylist" command-line option). Each Stylist transform implements a different layout or style; thus the name. They decouple the context-understanding part of the Reader from the layout-generating part of processing, resulting in a more flexible and robust system. This also serves to "separate style from content", the SGML/XML ideal. By keeping the piece of code that does the styling small and modular, it becomes much easier for people to roll their own styles. The "barrier to entry" is too high with existing tools; extracting the stylist code will lower the barrier considerably. ========================== References and Footnotes ========================== .. [#PEP-256] PEP 256, Docstring Processing System Framework, Goodger (http://www.python.org/peps/pep-0256.html) .. [#PEP-224] PEP 224, Attribute Docstrings, Lemburg (http://www.python.org/peps/pep-0224.html) .. [#PEP-216] PEP 216, Docstring Format, Zadka (http://www.python.org/peps/pep-0216.html) .. _docutils.dtd: http://docutils.sourceforge.net/docs/ref/docutils.dtd .. _soextbl.dtd: http://docutils.sourceforge.net/docs/ref/soextblx.dtd .. _The Docutils Document Tree: http://docutils.sourceforge.net/docs/ref/doctree.html .. _VMS error condition severity levels: http://www.openvms.compaq.com:8000/73final/5841/841pro_027.html #error_cond_severity .. _log4j project: http://logging.apache.org/log4j/docs/index.html .. _Docutils Python Source DTD: http://docutils.sourceforge.net/docs/dev/pysource.dtd .. _ISO 639: http://www.loc.gov/standards/iso639-2/englangn.html .. _Python Doc-SIG: http://www.python.org/sigs/doc-sig/ ================== Project Web Site ================== A SourceForge project has been set up for this work at http://docutils.sourceforge.net/. =========== Copyright =========== This document has been placed in the public domain. ================== Acknowledgements ================== This document borrows ideas from the archives of the `Python Doc-SIG`_. Thanks to all members past & present. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: ����������������������������������������������������������������������������������������������������������docutils-0.12/docs/peps/pep-0256.txt����������������������������������������������������������������0000664�0001750�0001750�00000024246�10434150472�021052� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������PEP: 256 Title: Docstring Processing System Framework Version: $Revision: 4564 $ Last-Modified: $Date: 2006-05-21 22:44:42 +0200 (Son, 21. Mai 2006) $ Author: David Goodger <goodger@python.org> Discussions-To: <doc-sig@python.org> Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 01-Jun-2001 Post-History: 13-Jun-2001 Abstract ======== Python lends itself to inline documentation. With its built-in docstring syntax, a limited form of `Literate Programming`_ is easy to do in Python. However, there are no satisfactory standard tools for extracting and processing Python docstrings. The lack of a standard toolset is a significant gap in Python's infrastructure; this PEP aims to fill the gap. The issues surrounding docstring processing have been contentious and difficult to resolve. This PEP proposes a generic Docstring Processing System (DPS) framework, which separates out the components (program and conceptual), enabling the resolution of individual issues either through consensus (one solution) or through divergence (many). It promotes standard interfaces which will allow a variety of plug-in components (input context readers, markup parsers, and output format writers) to be used. The concepts of a DPS framework are presented independently of implementation details. Road Map to the Docstring PEPs ============================== There are many aspects to docstring processing. The "Docstring PEPs" have broken up the issues in order to deal with each of them in isolation, or as close as possible. The individual aspects and associated PEPs are as follows: * Docstring syntax. PEP 287, "reStructuredText Docstring Format" [#PEP-287]_, proposes a syntax for Python docstrings, PEPs, and other uses. * Docstring semantics consist of at least two aspects: - Conventions: the high-level structure of docstrings. Dealt with in PEP 257, "Docstring Conventions" [#PEP-257]_. - Methodology: rules for the informational content of docstrings. Not addressed. * Processing mechanisms. This PEP (PEP 256) outlines the high-level issues and specification of an abstract docstring processing system (DPS). PEP 258, "Docutils Design Specification" [#PEP-258]_, is an overview of the design and implementation of one DPS under development. * Output styles: developers want the documentation generated from their source code to look good, and there are many different ideas about what that means. PEP 258 touches on "Stylist Transforms". This aspect of docstring processing has yet to be fully explored. By separating out the issues, we can form consensus more easily (smaller fights ;-), and accept divergence more readily. Rationale ========= There are standard inline documentation systems for some other languages. For example, Perl has POD_ ("Plain Old Documentation") and Java has Javadoc_, but neither of these mesh with the Pythonic way. POD syntax is very explicit, but takes after Perl in terms of readability. Javadoc is HTML-centric; except for "``@field``" tags, raw HTML is used for markup. There are also general tools such as Autoduck_ and Web_ (Tangle & Weave), useful for multiple languages. There have been many attempts to write auto-documentation systems for Python (not an exhaustive list): - Marc-Andre Lemburg's doc.py_ - Daniel Larsson's pythondoc_ & gendoc_ - Doug Hellmann's HappyDoc_ - Laurence Tratt's Crystal (no longer available on the web) - Ka-Ping Yee's pydoc_ (pydoc.py is now part of the Python standard library; see below) - Tony Ibbs' docutils_ (Tony has donated this name to the `Docutils project`_) - Edward Loper's STminus_ formalization and related efforts These systems, each with different goals, have had varying degrees of success. A problem with many of the above systems was over-ambition combined with inflexibility. They provided a self-contained set of components: a docstring extraction system, a markup parser, an internal processing system and one or more output format writers with a fixed style. Inevitably, one or more aspects of each system had serious shortcomings, and they were not easily extended or modified, preventing them from being adopted as standard tools. It has become clear (to this author, at least) that the "all or nothing" approach cannot succeed, since no monolithic self-contained system could possibly be agreed upon by all interested parties. A modular component approach designed for extension, where components may be multiply implemented, may be the only chance for success. Standard inter-component APIs will make the DPS components comprehensible without requiring detailed knowledge of the whole, lowering the barrier for contributions, and ultimately resulting in a rich and varied system. Each of the components of a docstring processing system should be developed independently. A "best of breed" system should be chosen, either merged from existing systems, and/or developed anew. This system should be included in Python's standard library. PyDoc & Other Existing Systems ------------------------------ PyDoc became part of the Python standard library as of release 2.1. It extracts and displays docstrings from within the Python interactive interpreter, from the shell command line, and from a GUI window into a web browser (HTML). Although a very useful tool, PyDoc has several deficiencies, including: - In the case of the GUI/HTML, except for some heuristic hyperlinking of identifier names, no formatting of the docstrings is done. They are presented within ``<p><small><tt>`` tags to avoid unwanted line wrapping. Unfortunately, the result is not attractive. - PyDoc extracts docstrings and structural information (class identifiers, method signatures, etc.) from imported module objects. There are security issues involved with importing untrusted code. Also, information from the source is lost when importing, such as comments, "additional docstrings" (string literals in non-docstring contexts; see PEP 258 [#PEP-258]_), and the order of definitions. The functionality proposed in this PEP could be added to or used by PyDoc when serving HTML pages. The proposed docstring processing system's functionality is much more than PyDoc needs in its current form. Either an independent tool will be developed (which PyDoc may or may not use), or PyDoc could be expanded to encompass this functionality and *become* the docstring processing system (or one such system). That decision is beyond the scope of this PEP. Similarly for other existing docstring processing systems, their authors may or may not choose compatibility with this framework. However, if this framework is accepted and adopted as the Python standard, compatibility will become an important consideration in these systems' future. Specification ============= The docstring processing system framework is broken up as follows: 1. Docstring conventions. Documents issues such as: - What should be documented where. - First line is a one-line synopsis. PEP 257 [#PEP-257]_ documents some of these issues. 2. Docstring processing system design specification. Documents issues such as: - High-level spec: what a DPS does. - Command-line interface for executable script. - System Python API. - Docstring extraction rules. - Readers, which encapsulate the input context. - Parsers. - Document tree: the intermediate internal data structure. The output of the Parser and Reader, and the input to the Writer all share the same data structure. - Transforms, which modify the document tree. - Writers for output formats. - Distributors, which handle output management (one file, many files, or objects in memory). These issues are applicable to any docstring processing system implementation. PEP 258 [#PEP-258]_ documents these issues. 3. Docstring processing system implementation. 4. Input markup specifications: docstring syntax. PEP 287 [#PEP-287]_ proposes a standard syntax. 5. Input parser implementations. 6. Input context readers ("modes": Python source code, PEP, standalone text file, email, etc.) and implementations. 7. Stylists: certain input context readers may have associated stylists which allow for a variety of output document styles. 8. Output formats (HTML, XML, TeX, DocBook, info, etc.) and writer implementations. Components 1, 2/3/5, and 4 are the subject of individual companion PEPs. If there is another implementation of the framework or syntax/parser, additional PEPs may be required. Multiple implementations of each of components 6 and 7 will be required; the PEP mechanism may be overkill for these components. Project Web Site ================ A SourceForge project has been set up for this work at http://docutils.sourceforge.net/. References and Footnotes ======================== .. [#PEP-287] PEP 287, reStructuredText Docstring Format, Goodger (http://www.python.org/peps/pep-0287.html) .. [#PEP-257] PEP 257, Docstring Conventions, Goodger, Van Rossum (http://www.python.org/peps/pep-0257.html) .. [#PEP-258] PEP 258, Docutils Design Specification, Goodger (http://www.python.org/peps/pep-0258.html) .. _Literate Programming: http://www.literateprogramming.com/ .. _POD: http://perldoc.perl.org/perlpod.html .. _Javadoc: http://java.sun.com/j2se/javadoc/ .. _Autoduck: http://www.helpmaster.com/hlp-developmentaids-autoduck.htm .. _Web: http://www-cs-faculty.stanford.edu/~knuth/cweb.html .. _doc.py: http://www.egenix.com/files/python/SoftwareDescriptions.html#doc.py .. _pythondoc: .. _gendoc: http://starship.python.net/crew/danilo/pythondoc/ .. _HappyDoc: http://happydoc.sourceforge.net/ .. _pydoc: http://www.python.org/doc/current/lib/module-pydoc.html .. _docutils: http://www.tibsnjoan.co.uk/docutils.html .. _Docutils project: http://docutils.sourceforge.net/ .. _STMinus: http://www.cis.upenn.edu/~edloper/pydoc/ .. _Python Doc-SIG: http://www.python.org/sigs/doc-sig/ Copyright ========= This document has been placed in the public domain. Acknowledgements ================ This document borrows ideas from the archives of the `Python Doc-SIG`_. Thanks to all members past & present. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/docs/peps/pep-0257.txt����������������������������������������������������������������0000664�0001750�0001750�00000026733�10434150472�021056� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������PEP: 257 Title: Docstring Conventions Version: $Revision: 4564 $ Last-Modified: $Date: 2006-05-21 22:44:42 +0200 (Son, 21. Mai 2006) $ Authors: David Goodger <goodger@python.org>, Guido van Rossum <guido@python.org> Discussions-To: doc-sig@python.org Status: Active Type: Informational Content-Type: text/x-rst Created: 29-May-2001 Post-History: 13-Jun-2001 Abstract ======== This PEP documents the semantics and conventions associated with Python docstrings. Rationale ========= The aim of this PEP is to standardize the high-level structure of docstrings: what they should contain, and how to say it (without touching on any markup syntax within docstrings). The PEP contains conventions, not laws or syntax. "A universal convention supplies all of maintainability, clarity, consistency, and a foundation for good programming habits too. What it doesn't do is insist that you follow it against your will. That's Python!" -- Tim Peters on comp.lang.python, 2001-06-16 If you violate these conventions, the worst you'll get is some dirty looks. But some software (such as the Docutils_ docstring processing system [1]_ [2]_) will be aware of the conventions, so following them will get you the best results. Specification ============= What is a Docstring? -------------------- A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the ``__doc__`` special attribute of that object. All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the ``__init__`` constructor) should also have docstrings. A package may be documented in the module docstring of the ``__init__.py`` file in the package directory. String literals occurring elsewhere in Python code may also act as documentation. They are not recognized by the Python bytecode compiler and are not accessible as runtime object attributes (i.e. not assigned to ``__doc__``), but two types of extra docstrings may be extracted by software tools: 1. String literals occurring immediately after a simple assignment at the top level of a module, class, or ``__init__`` method are called "attribute docstrings". 2. String literals occurring immediately after another docstring are called "additional docstrings". Please see PEP 258, "Docutils Design Specification" [2]_, for a detailed description of attribute and additional docstrings. XXX Mention docstrings of 2.2 properties. For consistency, always use ``"""triple double quotes"""`` around docstrings. Use ``r"""raw triple double quotes"""`` if you use any backslashes in your docstrings. For Unicode docstrings, use ``u"""Unicode triple-quoted strings"""``. There are two forms of docstrings: one-liners and multi-line docstrings. One-line Docstrings -------------------- One-liners are for really obvious cases. They should really fit on one line. For example:: def kos_root(): """Return the pathname of the KOS root directory.""" global _kos_root if _kos_root: return _kos_root ... Notes: - Triple quotes are used even though the string fits on one line. This makes it easy to later expand it. - The closing quotes are on the same line as the opening quotes. This looks better for one-liners. - There's no blank line either before or after the docstring. - The docstring is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". - The one-line docstring should NOT be a "signature" reiterating the function/method parameters (which can be obtained by introspection). Don't do:: def function(a, b): """function(a, b) -> list""" This type of docstring is only appropriate for C functions (such as built-ins), where introspection is not possible. However, the nature of the *return value* cannot be determined by introspection, so it should be mentioned. The preferred form for such a docstring would be something like:: def function(a, b): """Do X and return a list.""" (Of course "Do X" should be replaced by a useful description!) Multi-line Docstrings ---------------------- Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line, followed by a more elaborate description. The summary line may be used by automatic indexing tools; it is important that it fits on one line and is separated from the rest of the docstring by a blank line. The summary line may be on the same line as the opening quotes or on the next line. The entire docstring is indented the same as the quotes at its first line (see example below). Insert a blank line before and after all docstrings (one-line or multi-line) that document a class -- generally speaking, the class's methods are separated from each other by a single blank line, and the docstring needs to be offset from the first method by a blank line; for symmetry, put a blank line between the class header and the docstring. Docstrings documenting functions or methods generally don't have this requirement, unless the function or method's body is written as a number of blank-line separated sections -- in this case, treat the docstring as another section, and precede it with a blank line. The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user. The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's ``__init__.py`` module) should also list the modules and subpackages exported by the package. The docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface. The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its ``__init__`` method. Individual methods should be documented by their own docstring. If a class subclasses another class and its behavior is mostly inherited from that class, its docstring should mention this and summarize the differences. Use the verb "override" to indicate that a subclass method replaces a superclass method and does not call the superclass method; use the verb "extend" to indicate that a subclass method calls the superclass method (in addition to its own behavior). *Do not* use the Emacs convention of mentioning the arguments of functions or methods in upper case in running text. Python is case sensitive and the argument names can be used for keyword arguments, so the docstring should document the correct argument names. It is best to list each argument on a separate line. For example:: def complex(real=0.0, imag=0.0): """Form a complex number. Keyword arguments: real -- the real part (default 0.0) imag -- the imaginary part (default 0.0) """ if imag == 0.0 and real == 0.0: return complex_zero ... The BDFL [3]_ recommends inserting a blank line between the last paragraph in a multi-line docstring and its closing quotes, placing the closing quotes on a line by themselves. This way, Emacs' ``fill-paragraph`` command can be used on it. Handling Docstring Indentation ------------------------------ Docstring processing tools will strip a uniform amount of indentation from the second and further lines of the docstring, equal to the minimum indentation of all non-blank lines after the first line. Any indentation in the first line of the docstring (i.e., up to the first newline) is insignificant and removed. Relative indentation of later lines in the docstring is retained. Blank lines should be removed from the beginning and end of the docstring. Since code is much more precise than words, here is an implementation of the algorithm:: def trim(docstring): if not docstring: return '' # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expandtabs().splitlines() # Determine minimum indentation (first line doesn't count): indent = sys.maxint for line in lines[1:]: stripped = line.lstrip() if stripped: indent = min(indent, len(line) - len(stripped)) # Remove indentation (first line is special): trimmed = [lines[0].strip()] if indent < sys.maxint: for line in lines[1:]: trimmed.append(line[indent:].rstrip()) # Strip off trailing and leading blank lines: while trimmed and not trimmed[-1]: trimmed.pop() while trimmed and not trimmed[0]: trimmed.pop(0) # Return a single string: return '\n'.join(trimmed) The docstring in this example contains two newline characters and is therefore 3 lines long. The first and last lines are blank:: def foo(): """ This is the second line of the docstring. """ To illustrate:: >>> print repr(foo.__doc__) '\n This is the second line of the docstring.\n ' >>> foo.__doc__.splitlines() ['', ' This is the second line of the docstring.', ' '] >>> trim(foo.__doc__) 'This is the second line of the docstring.' Once trimmed, these docstrings are equivalent:: def foo(): """A multi-line docstring. """ def bar(): """ A multi-line docstring. """ References and Footnotes ======================== .. [1] PEP 256, Docstring Processing System Framework, Goodger (http://www.python.org/peps/pep-0256.html) .. [2] PEP 258, Docutils Design Specification, Goodger (http://www.python.org/peps/pep-0258.html) .. [3] Guido van Rossum, Python's creator and Benevolent Dictator For Life. .. _Docutils: http://docutils.sourceforge.net/ .. _Python Style Guide: http://www.python.org/doc/essays/styleguide.html .. _Doc-SIG: http://www.python.org/sigs/doc-sig/ Copyright ========= This document has been placed in the public domain. Acknowledgements ================ The "Specification" text comes mostly verbatim from the `Python Style Guide`_ essay by Guido van Rossum. This document borrows ideas from the archives of the Python Doc-SIG_. Thanks to all members past and present. .. Local Variables: mode: indented-text indent-tabs-mode: nil fill-column: 70 sentence-end-double-space: t End: �������������������������������������docutils-0.12/docs/dev/�����������������������������������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�016735� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/docs/dev/repository.txt���������������������������������������������������������������0000664�0001750�0001750�00000014305�12334354330�021715� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������===================================== The Docutils_ Subversion Repository ===================================== :Author: Lea Wiemann :Contact: docutils-develop@lists.sourceforge.net :Revision: $Revision: 7748 $ :Date: $Date: 2014-05-13 10:33:28 +0200 (Die, 13. Mai 2014) $ :Copyright: This document has been placed in the public domain. .. _Docutils: http://docutils.sourceforge.net/ .. admonition:: Quick Instructions To get a checkout of the Docutils source tree (with the sandboxes), type :: svn checkout http://svn.code.sf.net/p/docutils/code/trunk docutils-code If you are going to commit changes to the repository, please read the **whole document**, especially the section "`Information for Developers`_"! .. important:: As of 2013-03-13 the subversion urls have changed. The Git clone at http://repo.or.cz/w/docutils.git is currently not updated and should not be used. Docutils uses a Subversion_ repository located at ``docutils.svn.sourceforge.net``. Subversion is exhaustively documented in the `Subversion Book`_ (svnbook). While Unix and Mac OS X users will probably prefer the standard Subversion command line interface, Windows user may want to try TortoiseSVN_, a convenient explorer extension. The instructions apply analogously. .. There is a git_ mirror at http://repo.or.cz/w/docutils.git providing `web access`_ and the base for `creating a local git clone`_. For the project policy on repository use (check-in requirements, branching, etc.), please see the `Docutils Project Policies`__. __ policies.html#subversion-repository .. _Subversion: http://subversion.tigris.org/ .. _Subversion Book: http://svnbook.red-bean.com/ .. _TortoiseSVN: http://tortoisesvn.tigris.org/ .. _SourceForge.net: http://sourceforge.net/ .. _git: http://git-scm.com/ .. contents:: Accessing the Repository ======================== General Information ------------------- Web Access ~~~~~~~~~~ The repository can be browsed and examined via the web at http://sourceforge.net/p/docutils/code .. currently not updated (last update 2012) Alternatively, use the web interface of the git mirror at http://repo.or.cz/w/docutils.git. Repository Access Methods ~~~~~~~~~~~~~~~~~~~~~~~~~ To get a checkout of the Docutils repository, first determine the root of the repository depending on your preferred protocol: anonymous access: (read only) ``http://svn.code.sf.net/p/docutils/code`` `developer access`_: (read and write) ``svn+ssh://<USERNAME>@svn.code.sf.net/p/docutils/code`` .. git clone: (read only) ``git clone git://repo.or.cz/docutils.git`` Checking Out the Repository ~~~~~~~~~~~~~~~~~~~~~~~~~~~ To check out only the current main source tree of Docutils, type :: svn checkout ROOT/trunk/docutils (Substitute your preferred repository root for ROOT.) To check out everything (main tree, sandboxes, web site, and parallel projects), type :: svn checkout ROOT/trunk docutils This will create a working copy of the whole trunk in a new directory called ``docutils``. Note that you probably do *not* want to check out the ROOT itself (without "/trunk"), because then you'd end up fetching the whole Docutils tree for every branch and tag over and over again. To update your working copy later on, ``cd`` into the working copy and type :: svn update .. Creating a local git clone ~~~~~~~~~~~~~~~~~~~~~~~~~~ Users of git_ can clone a mirror of the docutils repository with :: git clone git://repo.or.cz/docutils.git and proceed according to the `git documentation`_. .. _git documentation: http://git-scm.com/documentation Switching the Repository Root ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you changed your mind and want to use a different repository root, ``cd`` into your working copy and type:: svn switch --relocate OLDROOT NEWROOT .. _developer access: Information for Developers -------------------------- If you would like to have write access to the repository, register with SourceForge.net_ and send your SourceForge.net user names to docutils-develop@lists.sourceforge.net. (Note that there may be a delay of several hours until you can commit changes to the repository.) Sourceforge subversion access is documented `here`__ __ http://sourceforge.net/p/forge/documentation/svn/ Setting Up Your Subversion Client For Development ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Before commiting changes to the repository, please ensure that the following lines are contained (and uncommented) in your local ~/.subversion/config file, so that new files are added with the correct properties set:: [miscellany] # For your convenience: global-ignores = ... *.pyc ... # For correct properties: enable-auto-props = yes [auto-props] *.py = svn:eol-style=native;svn:keywords=Author Date Id Revision *.txt = svn:eol-style=native;svn:keywords=Author Date Id Revision *.html = svn:eol-style=native;svn:keywords=Author Date Id Revision *.xml = svn:eol-style=native;svn:keywords=Author Date Id Revision *.tex = svn:eol-style=native;svn:keywords=Author Date Id Revision *.css = svn:eol-style=native;svn:keywords=Author Date Id Revision *.patch = svn:eol-style=native *.sh = svn:eol-style=native;svn:executable;svn:keywords=Author Date Id Revision *.png = svn:mime-type=image/png *.jpg = svn:mime-type=image/jpeg *.gif = svn:mime-type=image/gif Repository Layout ================= The following tree shows the repository layout:: docutils/ |-- branches/ | |-- branch1/ | | |-- docutils/ | | |-- sandbox/ | | `-- web/ | `-- branch2/ | |-- docutils/ | |-- sandbox/ | `-- web/ |-- tags/ | |-- tag1/ | | |-- docutils/ | | |-- sandbox/ | | `-- web/ | `-- tag2/ | |-- docutils/ | |-- sandbox/ | `-- web/ `-- trunk/ |-- docutils/ |-- sandbox/ `-- web/ The main source tree lives at ``docutils/trunk/docutils/``, next to the sandboxes (``docutils/trunk/sandbox/``) and the web site files (``docutils/trunk/web/``). ``docutils/branches/`` and ``docutils/tags/`` contain (shallow) copies of either the whole trunk or only the main source tree (``docutils/trunk/docutils``). ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/docs/dev/distributing.txt�������������������������������������������������������������0000664�0001750�0001750�00000007720�11771146137�022220� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������=============================== Docutils_ Distributor's Guide =============================== :Author: Lea Wiemann :Contact: docutils-develop@lists.sourceforge.net :Revision: $Revision: 7463 $ :Date: $Date: 2012-06-22 21:49:51 +0200 (Fre, 22. Jun 2012) $ :Copyright: This document has been placed in the public domain. .. _Docutils: http://docutils.sourceforge.net/ .. contents:: This document describes how to create packages of Docutils (e.g. for shipping with a Linux distribution). If you have any questions, please direct them to the Docutils-develop_ mailing list. First, please download the most current `release tarball`_ and unpack it. .. _Docutils-develop: ../user/mailing-lists.html#docutils-develop .. _release tarball: http://docutils.sourceforge.net/#download Dependencies ============ Docutils has the following dependencies: * Python 2.4 or later is required. Use ">= Python 2.4" in the dependencies. * Docutils may optionally make use of the PIL (`Python Imaging Library`_). If PIL is present, it is automatically detected by Docutils. * There is one file in the ``extras/`` directory of the Docutils distribution, ``roman.py``. It is automatically installed by the setup script (when calling "python setup.py install"). .. _Python Imaging Library: http://www.pythonware.com/products/pil/ Python Files ============ The Docutils Python files must be installed into the ``site-packages/`` directory of Python. Running ``python setup.py install`` should do the trick, but if you want to place the files yourself, you can just install the ``docutils/`` directory of the Docutils tarball to ``/usr/lib/python/site-packages/docutils/``. In this case you should also compile the Python files to ``.pyc`` and/or ``.pyo`` files so that Docutils doesn't need to be recompiled every time it's executed. Executables =========== The executable front-end tools are located in the ``tools/`` directory of the Docutils tarball. The ``rst2*.py`` tools (except ``rst2newlatex.py``) are intended for end-users. You should install them to ``/usr/bin/``. You do not need to change the names (e.g. to ``docutils-rst2html.py``) because the ``rst2`` prefix is unique. Documentation ============= The documentation should be generated using ``buildhtml.py``. To generate HTML for all documentation files, go to the ``tools/`` directory and run:: # Place html4css1.css in base directory. cp ../docutils/writers/html4css1/html4css1.css .. ./buildhtml.py --stylesheet-path=../html4css1.css .. Then install the following files to ``/usr/share/doc/docutils/`` (or wherever you install documentation): * All ``.html`` and ``.txt`` files in the base directory. * The ``docs/`` directory. Do not install the contents of the ``docs/`` directory directly to ``/usr/share/doc/docutils/``; it's incomplete and would contain invalid references! * The ``licenses/`` directory. * ``html4css1.css`` in the base directory. Removing the ``.txt`` Files --------------------------- If you are tight with disk space, you can remove all ``.txt`` files in the tree except for: * those in the ``licenses/`` directory because they have not been processed to HTML and * ``user/rst/cheatsheet.txt`` and ``user/rst/demo.txt``, which should be readable in source form. Before you remove the ``.txt`` files you should rerun ``buildhtml.py`` with the ``--no-source-link`` switch to avoid broken references to the source files. Other Files =========== You may want to install the Emacs-Lisp files ``tools/editors/emacs/*.el`` into the appropriate directory. Configuration File ================== It is possible to have a system-wide configuration file at ``/etc/docutils.conf``. However, this is usually not necessary. You should *not* install ``tools/docutils.conf`` into ``/etc/``. Tests ===== While you probably do not need to ship the tests with your distribution, you can test your package by installing it and then running ``alltests.py`` from the ``tests/`` directory of the Docutils tarball. ������������������������������������������������docutils-0.12/docs/dev/pysource.txt�����������������������������������������������������������������0000664�0001750�0001750�00000010522�11700652711�021344� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������====================== Python Source Reader ====================== :Author: David Goodger :Contact: docutils-develop@lists.sourceforge.net :Revision: $Revision: 7302 $ :Date: $Date: 2012-01-03 20:23:53 +0100 (Die, 03. Jän 2012) $ :Copyright: This document has been placed in the public domain. This document explores issues around extracting and processing docstrings from Python modules. For definitive element hierarchy details, see the "Python Plaintext Document Interface DTD" XML document type definition, pysource.dtd_ (which modifies the generic docutils.dtd_). Descriptions below list 'DTD elements' (XML 'generic identifiers' or tag names) corresponding to syntax constructs. .. contents:: Model ===== The Python Source Reader ("PySource") model that's evolving in my mind goes something like this: 1. Extract the docstring/namespace [#]_ tree from the module(s) and/or package(s). .. [#] See `Docstring Extractor`_ below. 2. Run the parser on each docstring in turn, producing a forest of doctrees (per nodes.py). 3. Join the docstring trees together into a single tree, running transforms: - merge hyperlinks - merge namespaces - create various sections like "Module Attributes", "Functions", "Classes", "Class Attributes", etc.; see pysource.dtd_ - convert the above special sections to ordinary doctree nodes 4. Run transforms on the combined doctree. Examples: resolving cross-references/hyperlinks (including interpreted text on Python identifiers); footnote auto-numbering; first field list -> bibliographic elements. (Or should step 4's transforms come before step 3?) 5. Pass the resulting unified tree to the writer/builder. I've had trouble reconciling the roles of input parser and output writer with the idea of modes ("readers" or "directors"). Does the mode govern the tranformation of the input, the output, or both? Perhaps the mode should be split into two. For example, say the source of our input is a Python module. Our "input mode" should be the "Python Source Reader". It discovers (from ``__docformat__``) that the input parser is "reStructuredText". If we want HTML, we'll specify the "HTML" output formatter. But there's a piece missing. What *kind* or *style* of HTML output do we want? PyDoc-style, LibRefMan style, etc. (many people will want to specify and control their own style). Is the output style specific to a particular output format (XML, HTML, etc.)? Is the style specific to the input mode? Or can/should they be independent? I envision interaction between the input parser, an "input mode" , and the output formatter. The same intermediate data format would be used between each of these, being transformed as it progresses. Docstring Extractor =================== We need code that scans a parsed Python module, and returns an ordered tree containing the names, docstrings (including attribute and additional docstrings), and additional info (in parentheses below) of all of the following objects: - packages - modules - module attributes (+ values) - classes (+ inheritance) - class attributes (+ values) - instance attributes (+ values) - methods (+ formal parameters & defaults) - functions (+ formal parameters & defaults) (Extract comments too? For example, comments at the start of a module would be a good place for bibliographic field lists.) In order to evaluate interpreted text cross-references, namespaces for each of the above will also be required. See python-dev/docstring-develop thread "AST mining", started on 2001-08-14. Interpreted Text ================ DTD elements: package, module, class, method, function, module_attribute, class_attribute, instance_attribute, variable, parameter, type, exception_class, warning_class. To classify identifiers explicitly, the role is given along with the identifier in either prefix or suffix form:: Use :method:`Keeper.storedata` to store the object's data in `Keeper.data`:instance_attribute:. The role may be one of 'package', 'module', 'class', 'method', 'function', 'module_attribute', 'class_attribute', 'instance_attribute', 'variable', 'parameter', 'type', 'exception_class', 'exception', 'warning_class', or 'warning'. Other roles may be defined. .. _pysource.dtd: pysource.dtd .. _docutils.dtd: ../ref/docutils.dtd .. Local Variables: mode: indented-text indent-tabs-mode: nil fill-column: 70 End: ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/docs/dev/website.txt������������������������������������������������������������������0000664�0001750�0001750�00000006365�11700652711�021147� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������=================== Docutils Web Site =================== :Author: David Goodger; open to all Docutils developers :Contact: docutils-develop@lists.sourceforge.net :Date: $Date: 2012-01-03 20:23:53 +0100 (Die, 03. Jän 2012) $ :Revision: $Revision: 7302 $ :Copyright: This document has been placed in the public domain. The Docutils web site, <http://docutils.sourceforge.net/>, is maintained by the ``docutils-update.local`` script, run by project maintainers on their local machines. The script will process any .txt file which is newer than the corresponding .html file in the local copy of the project's web directory and upload the changes to the web site at SourceForge. .. .. old instructions, for cron job: The Docutils web site, <http://docutils.sourceforge.net/>, is maintained automatically by the ``docutils-update`` script, run as an hourly cron job on shell.berlios.de (by user "wiemann"). The script will process any .txt file which is newer than the corresponding .html file in the project's web directory on shell.berlios.de (``/home/groups/docutils/htdocs/aux/htdocs/``) and upload the changes to the web site at SourceForge. Please **do not** add any generated .html files to the Docutils repository. They will be generated automatically after a one-time setup (`described below`__). __ `Adding .txt Files`_ The docutils-update.local__ script is located at ``sandbox/infrastructure/docutils-update.local``. __ http://docutils.sf.net/sandbox/infrastructure/docutils-update.local If you want to share files via the web, you can upload them using the uploaddocutils.sh__ script (``sandbox/infrastructure/uploaddocutils.sh``). __ http://docutils.sf.net/sandbox/infrastructure/uploaddocutils.sh Setting Up ========== (TBA) .. hint:: Anyone with checkin privileges can be a web-site maintainer. You need to set up the directories for a local website build. The procedure for that was on the docutils-devel list a while ago. Adding .txt Files ================= User/Contributor ---------------- When adding a new .txt file that should be converted to HTML: #. Edit sandbox/infrastructure/htmlfiles.lst, and add the .html file corresponding to the new .txt file (please keep the sorted order). #. Commit the edited version to the SVN repository. Maintainer ---------- #. If there are new directories in the SVN, allow the update script to run once to create the directories in the filesystem before preparing for HTML processing. #. Run the sandbox/infrastructure/update-htmlfiles shell script to generate .html files:: cd <DOCUTILS-ROOT>/docutils/ sandbox/infrastructure/update-htmlfiles \ sandbox/infrastructure/htmlfiles.lst (Maybe this should become part of docutils-update.local.) Removing Files & Directories ============================ #. Remove from SVN #. Remove to-be-generated HTML files from ``sandbox/infrastructure/htmlfiles.lst``. #. Removing files and directories from SVN will not trigger their removal from the web site. Files and directories must be manually removed from sourceforge.net (under ``/home/groups/d/do/docutils/htdocs/``). .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/docs/dev/rst/�������������������������������������������������������������������������0000775�0001750�0001750�00000000000�12356234260�017545� 5����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/docs/dev/rst/problems.txt�������������������������������������������������������������0000664�0001750�0001750�00000105333�11700652711�022133� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������============================== Problems With StructuredText ============================== :Author: David Goodger :Contact: docutils-develop@lists.sourceforge.net :Revision: $Revision: 7302 $ :Date: $Date: 2012-01-03 20:23:53 +0100 (Die, 03. Jän 2012) $ :Copyright: This document has been placed in the public domain. There are several problems, unresolved issues, and areas of controversy within StructuredText_ (Classic and Next Generation). In order to resolve all these issues, this analysis brings all of the issues out into the open, enumerates all the alternatives, and proposes solutions to be incorporated into the reStructuredText_ specification. .. contents:: Formal Specification ==================== The description in the original StructuredText.py has been criticized for being vague. For practical purposes, "the code *is* the spec." Tony Ibbs has been working on deducing a `detailed description`_ from the documentation and code of StructuredTextNG_. Edward Loper's STMinus_ is another attempt to formalize a spec. For this kind of a project, the specification should always precede the code. Otherwise, the markup is a moving target which can never be adopted as a standard. Of course, a specification may be revised during lifetime of the code, but without a spec there is no visible control and thus no confidence. Understanding and Extending the Code ==================================== The original StructuredText_ is a dense mass of sparsely commented code and inscrutable regular expressions. It was not designed to be extended and is very difficult to understand. StructuredTextNG_ has been designed to allow input (syntax) and output extensions, but its documentation (both internal [comments & docstrings], and external) is inadequate for the complexity of the code itself. For reStructuredText to become truly useful, perhaps even part of Python's standard library, it must have clear, understandable documentation and implementation code. For the implementation of reStructuredText to be taken seriously, it must be a sterling example of the potential of docstrings; the implementation must practice what the specification preaches. Section Structure via Indentation ================================= Setext_ required that body text be indented by 2 spaces. The original StructuredText_ and StructuredTextNG_ require that section structure be indicated through indentation, as "inspired by Python". For certain structures with a very limited, local extent (such as lists, block quotes, and literal blocks), indentation naturally indicates structure or hierarchy. For sections (which may have a very large extent), structure via indentation is unnecessary, unnatural and ambiguous. Rather, the syntax of the section title *itself* should indicate that it is a section title. The original StructuredText states that "A single-line paragraph whose immediately succeeding paragraphs are lower level is treated as a header." Requiring indentation in this way is: - Unnecessary. The vast majority of docstrings and standalone documents will have no more than one level of section structure. Requiring indentation for such docstrings is unnecessary and irritating. - Unnatural. Most published works use title style (type size, face, weight, and position) and/or section/subsection numbering rather than indentation to indicate hierarchy. This is a tradition with a very long history. - Ambiguous. A StructuredText header is indistinguishable from a one-line paragraph followed by a block quote (precluding the use of block quotes). Enumerated section titles are ambiguous (is it a header? is it a list item?). Some additional adornment must be required to confirm the line's role as a title, both to a parser and to the human reader of the source text. Python's use of significant whitespace is a wonderful (if not original) innovation, however requiring indentation in ordinary written text is hypergeneralization. reStructuredText_ indicates section structure through title adornment style (as exemplified by this document). This is far more natural. In fact, it is already in widespread use in plain text documents, including in Python's standard distribution (such as the toplevel README_ file). Character Escaping Mechanism ============================ No matter what characters are chosen for markup, some day someone will want to write documentation *about* that markup or using markup characters in a non-markup context. Therefore, any complete markup language must have an escaping or encoding mechanism. For a lightweight markup system, encoding mechanisms like SGML/XML's '*' are out. So an escaping mechanism is in. However, with carefully chosen markup, it should be necessary to use the escaping mechanism only infrequently. reStructuredText_ needs an escaping mechanism: a way to treat markup-significant characters as the characters themselves. Currently there is no such mechanism (although ZWiki uses '!'). What are the candidates? 1. ``!`` (http://www.zope.org/DevHome/Members/jim/StructuredTextWiki/NGEscaping) 2. ``\`` 3. ``~`` 4. doubling of characters The best choice for this is the backslash (``\``). It's "the single most popular escaping character in the world!", therefore familiar and unsurprising. Since characters only need to be escaped under special circumstances, which are typically those explaining technical programming issues, the use of the backslash is natural and understandable. Python docstrings can be raw (prefixed with an 'r', as in 'r""'), which would obviate the need for gratuitous doubling-up of backslashes. (On 2001-03-29 on the Doc-SIG mailing list, GvR endorsed backslash escapes, saying, "'nuff said. Backslash it is." Although neither legally binding nor irrevocable nor any kind of guarantee of anything, it is a good sign.) The rule would be: An unescaped backslash followed by any markup character escapes the character. The escaped character represents the character itself, and is prevented from playing a role in any markup interpretation. The backslash is removed from the output. A literal backslash is represented by an "escaped backslash," two backslashes in a row. A carefully constructed set of recognition rules for inline markup will obviate the need for backslash-escapes in almost all cases; see `Delimitation of Inline Markup`_ below. When an expression (requiring backslashes and other characters used for markup) becomes too complicated and therefore unreadable, a literal block may be used instead. Inside literal blocks, no markup is recognized, therefore backslashes (for the purpose of escaping markup) become unnecessary. We could allow backslashes preceding non-markup characters to remain in the output. This would make describing regular expressions and other uses of backslashes easier. However, this would complicate the markup rules and would be confusing. Blank Lines in Lists ==================== Oft-requested in Doc-SIG (the earliest reference is dated 1996-08-13) is the ability to write lists without requiring blank lines between items. In docstrings, space is at a premium. Authors want to convey their API or usage information in as compact a form as possible. StructuredText_ requires blank lines between all body elements, including list items, even when boundaries are obvious from the markup itself. In reStructuredText, blank lines are optional between list items. However, in order to eliminate ambiguity, a blank line is required before the first list item and after the last. Nested lists also require blank lines before the list start and after the list end. Bullet List Markup ================== StructuredText_ includes 'o' as a bullet character. This is dangerous and counter to the language-independent nature of the markup. There are many languages in which 'o' is a word. For example, in Spanish:: Llamame a la casa o al trabajo. (Call me at home or at work.) And in Japanese (when romanized):: Senshuu no doyoubi ni tegami o kakimashita. ([I] wrote a letter on Saturday last week.) If a paragraph containing an 'o' word wraps such that the 'o' is the first text on a line, or if a paragraph begins with such a word, it could be misinterpreted as a bullet list. In reStructuredText_, 'o' is not used as a bullet character. '-', '*', and '+' are the possible bullet characters. Enumerated List Markup ====================== StructuredText enumerated lists are allowed to begin with numbers and letters followed by a period or right-parenthesis, then whitespace. This has surprising consequences for writing styles. For example, this is recognized as an enumerated list item by StructuredText:: Mr. Creosote. People will write enumerated lists in all different ways. It is folly to try to come up with the "perfect" format for an enumerated list, and limit the docstring parser's recognition to that one format only. Rather, the parser should recognize a variety of enumerator styles. It is also recommended that the enumerator of the first list item be ordinal-1 ('1', 'A', 'a', 'I', or 'i'), as output formats may not be able to begin a list at an arbitrary enumeration. An initial idea was to require two or more consistent enumerated list items in a row. This idea proved impractical and was dropped. In practice, the presence of a proper enumerator is enough to reliably recognize an enumerated list item; any ambiguities are reported by the parser. Here's the original idea for posterity: The parser should recognize a variety of enumerator styles, mark each block as a potential enumerated list item (PELI), and interpret the enumerators of adjacent PELIs to decide whether they make up a consistent enumerated list. If a PELI is labeled with a "1.", and is immediately followed by a PELI labeled with a "2.", we've got an enumerated list. Or "(A)" followed by "(B)". Or "i)" followed by "ii)", etc. The chances of accidentally recognizing two adjacent and consistently labeled PELIs, are acceptably small. For an enumerated list to be recognized, the following must be true: - the list must consist of multiple adjacent list items (2 or more) - the enumerators must all have the same format - the enumerators must be sequential Definition List Markup ====================== StructuredText uses ' -- ' (whitespace, two hyphens, whitespace) on the first line of a paragraph to indicate a definition list item. The ' -- ' serves to separate the term (on the left) from the definition (on the right). Many people use ' -- ' as an em-dash in their text, conflicting with the StructuredText usage. Although the Chicago Manual of Style says that spaces should not be used around an em-dash, Peter Funk pointed out that this is standard usage in German (according to the Duden, the official German reference), and possibly in other languages as well. The widespread use of ' -- ' precludes its use for definition lists; it would violate the "unsurprising" criterion. A simpler, and at least equally visually distinctive construct (proposed by Guido van Rossum, who incidentally is a frequent user of ' -- ') would do just as well:: term 1 Definition. term 2 Definition 2, paragraph 1. Definition 2, paragraph 2. A reStructuredText definition list item consists of a term and a definition. A term is a simple one-line paragraph. A definition is a block indented relative to the term, and may contain multiple paragraphs and other body elements. No blank line precedes a definition (this distinguishes definition lists from block quotes). Literal Blocks ============== The StructuredText_ specification has literal blocks indicated by 'example', 'examples', or '::' ending the preceding paragraph. STNG only recognizes '::'; 'example'/'examples' are not implemented. This is good; it fixes an unnecessary language dependency. The problem is what to do with the sometimes- unwanted '::'. In reStructuredText_ '::' at the end of a paragraph indicates that subsequent *indented* blocks are treated as literal text. No further markup interpretation is done within literal blocks (not even backslash-escapes). If the '::' is preceded by whitespace, '::' is omitted from the output; if '::' was the sole content of a paragraph, the entire paragraph is removed (no 'empty' paragraph remains). If '::' is preceded by a non-whitespace character, '::' is replaced by ':' (i.e., the extra colon is removed). Thus, a section could begin with a literal block as follows:: Section Title ------------- :: print "this is example literal" Tables ====== The table markup scheme in classic StructuredText was horrible. Its omission from StructuredTextNG is welcome, and its markup will not be repeated here. However, tables themselves are useful in documentation. Alternatives: 1. This format is the most natural and obvious. It was independently invented (no great feat of creation!), and later found to be the format supported by the `Emacs table mode`_:: +------------+------------+------------+--------------+ | Header 1 | Header 2 | Header 3 | Header 4 | +============+============+============+==============+ | Column 1 | Column 2 | Column 3 & 4 span (Row 1) | +------------+------------+------------+--------------+ | Column 1 & 2 span | Column 3 | - Column 4 | +------------+------------+------------+ - Row 2 & 3 | | 1 | 2 | 3 | - span | +------------+------------+------------+--------------+ Tables are described with a visual outline made up of the characters '-', '=', '|', and '+': - The hyphen ('-') is used for horizontal lines (row separators). - The equals sign ('=') is optionally used as a header separator (as of version 1.5.24, this is not supported by the Emacs table mode). - The vertical bar ('|') is used for for vertical lines (column separators). - The plus sign ('+') is used for intersections of horizontal and vertical lines. Row and column spans are possible simply by omitting the column or row separators, respectively. The header row separator must be complete; in other words, a header cell may not span into the table body. Each cell contains body elements, and may have multiple paragraphs, lists, etc. Initial spaces for a left margin are allowed; the first line of text in a cell determines its left margin. 2. Below is a simpler table structure. It may be better suited to manual input than alternative #1, but there is no Emacs editing mode available. One disadvantage is that it resembles section titles; a one-column table would look exactly like section & subsection titles. :: ============ ============ ============ ============== Header 1 Header 2 Header 3 Header 4 ============ ============ ============ ============== Column 1 Column 2 Column 3 & 4 span (Row 1) ------------ ------------ --------------------------- Column 1 & 2 span Column 3 - Column 4 ------------------------- ------------ - Row 2 & 3 1 2 3 - span ============ ============ ============ ============== The table begins with a top border of equals signs with a space at each column boundary (regardless of spans). Each row is underlined. Internal row separators are underlines of '-', with spaces at column boundaries. The last of the optional head rows is underlined with '=', again with spaces at column boundaries. Column spans have no spaces in their underline. Row spans simply lack an underline at the row boundary. The bottom boundary of the table consists of '=' underlines. A blank line is required following a table. 3. A minimalist alternative is as follows:: ==== ===== ======== ======== ======= ==== ===== ===== Old State Input Action New State Notes ----------- -------- ----------------- ----------- ids types new type sys.msg. dupname ids types ==== ===== ======== ======== ======= ==== ===== ===== -- -- explicit -- -- new True -- -- implicit -- -- new False None False explicit -- -- new True old False explicit implicit old new True None True explicit explicit new None True old True explicit explicit new,old None True [1] None False implicit implicit new None False old False implicit implicit new,old None False None True implicit implicit new None True old True implicit implicit new old True ==== ===== ======== ======== ======= ==== ===== ===== The table begins with a top border of equals signs with one or more spaces at each column boundary (regardless of spans). There must be at least two columns in the table (to differentiate it from section headers). Each line starts a new row. The rightmost column is unbounded; text may continue past the edge of the table. Each row/line must contain spaces at column boundaries, except for explicit column spans. Underlines of '-' can be used to indicate column spans, but should be used sparingly if at all. Lines containing column span underlines may not contain any other text. The last of the optional head rows is underlined with '=', again with spaces at column boundaries. The bottom boundary of the table consists of '=' underlines. A blank line is required following a table. This table sums up the features. Using all the features in such a small space is not pretty though:: ======== ======== ======== Header 2 & 3 Span ------------------ Header 1 Header 2 Header 3 ======== ======== ======== Each line is a new row. Each row consists of one line only. Row spans are not possible. The last column may spill over to the right. Column spans are possible with an underline joining columns. ---------------------------- The span is limited to the row above the underline. ======== ======== ======== 4. As a variation of alternative 3, bullet list syntax in the first column could be used to indicate row starts. Multi-line rows are possible, but row spans are not. For example:: ===== ===== col 1 col 2 ===== ===== - 1 Second column of row 1. - 2 Second column of row 2. Second line of paragraph. - 3 Second column of row 3. Second paragraph of row 3, column 2 ===== ===== Column spans would be indicated on the line after the last line of the row. To indicate a real bullet list within a first-column cell, simply nest the bullets. 5. In a further variation, we could simply assume that whitespace in the first column implies a multi-line row; the text in other columns is continuation text. For example:: ===== ===== col 1 col 2 ===== ===== 1 Second column of row 1. 2 Second column of row 2. Second line of paragraph. 3 Second column of row 3. Second paragraph of row 3, column 2 ===== ===== Limitations of this approach: - Cells in the first column are limited to one line of text. - Cells in the first column *must* contain some text; blank cells would lead to a misinterpretation. An empty comment ("..") is sufficient. 6. Combining alternative 3 and 4, a bullet list in the first column could mean multi-line rows, and no bullet list means single-line rows only. Alternatives 1 and 5 has been adopted by reStructuredText. Delimitation of Inline Markup ============================= StructuredText specifies that inline markup must begin with whitespace, precluding such constructs as parenthesized or quoted emphatic text:: "**What?**" she cried. (*exit stage left*) The `reStructuredText markup specification`_ allows for such constructs and disambiguates inline markup through a set of recognition rules. These recognition rules define the context of markup start-strings and end-strings, allowing markup characters to be used in most non-markup contexts without a problem (or a backslash). So we can say, "Use asterisks (*) around words or phrases to *emphasisze* them." The '(*)' will not be recognized as markup. This reduces the need for markup escaping to the point where an escape character is *almost* (but not quite!) unnecessary. Underlining =========== StructuredText uses '_text_' to indicate underlining. To quote David Ascher in his 2000-01-21 Doc-SIG mailing list post, "Docstring grammar: a very revised proposal": The tagging of underlined text with _'s is suboptimal. Underlines shouldn't be used from a typographic perspective (underlines were designed to be used in manuscripts to communicate to the typesetter that the text should be italicized -- no well-typeset book ever uses underlines), and conflict with double-underscored Python variable names (__init__ and the like), which would get truncated and underlined when that effect is not desired. Note that while *complete* markup would prevent that truncation ('__init__'), I think of docstring markups much like I think of type annotations -- they should be optional and above all do no harm. In this case the underline markup does harm. Underlining is not part of the reStructuredText specification. Inline Literals =============== StructuredText's markup for inline literals (text left as-is, verbatim, usually in a monospaced font; as in HTML <TT>) is single quotes ('literals'). The problem with single quotes is that they are too often used for other purposes: - Apostrophes: "Don't blame me, 'cause it ain't mine, it's Chris'."; - Quoting text: First Bruce: "Well Bruce, I heard the prime minister use it. 'S'hot enough to boil a monkey's bum in 'ere your Majesty,' he said, and she smiled quietly to herself." In the UK, single quotes are used for dialogue in published works. - String literals: s = '' Alternatives:: 'text' \'text\' ''text'' "text" \"text\" ""text"" #text# @text@ `text` ^text^ ``text'' ``text`` The examples below contain inline literals, quoted text, and apostrophes. Each example should evaluate to the following HTML:: Some <TT>code</TT>, with a 'quote', "double", ain't it grand? Does <TT>a[b] = 'c' + "d" + `2^3`</TT> work? 0. Some code, with a quote, double, ain't it grand? Does a[b] = 'c' + "d" + `2^3` work? 1. Some 'code', with a \'quote\', "double", ain\'t it grand? Does 'a[b] = \'c\' + "d" + `2^3`' work? 2. Some \'code\', with a 'quote', "double", ain't it grand? Does \'a[b] = 'c' + "d" + `2^3`\' work? 3. Some ''code'', with a 'quote', "double", ain't it grand? Does ''a[b] = 'c' + "d" + `2^3`'' work? 4. Some "code", with a 'quote', \"double\", ain't it grand? Does "a[b] = 'c' + "d" + `2^3`" work? 5. Some \"code\", with a 'quote', "double", ain't it grand? Does \"a[b] = 'c' + "d" + `2^3`\" work? 6. Some ""code"", with a 'quote', "double", ain't it grand? Does ""a[b] = 'c' + "d" + `2^3`"" work? 7. Some #code#, with a 'quote', "double", ain't it grand? Does #a[b] = 'c' + "d" + `2^3`# work? 8. Some @code@, with a 'quote', "double", ain't it grand? Does @a[b] = 'c' + "d" + `2^3`@ work? 9. Some `code`, with a 'quote', "double", ain't it grand? Does `a[b] = 'c' + "d" + \`2^3\`` work? 10. Some ^code^, with a 'quote', "double", ain't it grand? Does ^a[b] = 'c' + "d" + `2\^3`^ work? 11. Some ``code'', with a 'quote', "double", ain't it grand? Does ``a[b] = 'c' + "d" + `2^3`'' work? 12. Some ``code``, with a 'quote', "double", ain't it grand? Does ``a[b] = 'c' + "d" + `2^3\``` work? Backquotes (#9 & #12) are the best choice. They are unobtrusive and relatviely rarely used (more rarely than ' or ", anyhow). Backquotes have the connotation of 'quotes', which other options (like carets, #10) don't. Analogously with ``*emph*`` & ``**strong**``, double-backquotes (#12) could be used for inline literals. If single-backquotes are used for 'interpreted text' (context-sensitive domain-specific descriptive markup) such as function name hyperlinks in Python docstrings, then double-backquotes could be used for absolute-literals, wherein no processing whatsoever takes place. An advantage of double-backquotes would be that backslash-escaping would no longer be necessary for embedded single-backquotes; however, embedded double-backquotes (in an end-string context) would be illegal. See `Backquotes in Phrase-Links`__ in `Record of reStructuredText Syntax Alternatives`__. __ alternatives.html#backquotes-in-phrase-links __ alternatives.html Alternative choices are carets (#10) and TeX-style quotes (#11). For examples of TeX-style quoting, see http://www.zope.org/Members/jim/StructuredTextWiki/CustomizingTheDocumentProcessor. Some existing uses of backquotes: 1. As a synonym for repr() in Python. 2. For command-interpolation in shell scripts. 3. Used as open-quotes in TeX code (and carried over into plaintext by TeXies). The inline markup start-string and end-string recognition rules defined by the `reStructuredText markup specification`_ would allow all of these cases inside inline literals, with very few exceptions. As a fallback, literal blocks could handle all cases. Outside of inline literals, the above uses of backquotes would require backslash-escaping. However, these are all prime examples of text that should be marked up with inline literals. If either backquotes or straight single-quotes are used as markup, TeX-quotes are too troublesome to support, so no special-casing of TeX-quotes should be done (at least at first). If TeX-quotes have to be used outside of literals, a single backslash-escaped would suffice: \``TeX quote''. Ugly, true, but very infrequently used. Using literal blocks is a fallback option which removes the need for backslash-escaping:: like this:: Here, we can do ``absolutely'' anything `'`'\|/|\ we like! No mechanism for inline literals is perfect, just as no escaping mechanism is perfect. No matter what we use, complicated inline expressions involving the inline literal quote and/or the backslash will end up looking ugly. We can only choose the least often ugly option. reStructuredText will use double backquotes for inline literals, and single backqoutes for interpreted text. Hyperlinks ========== There are three forms of hyperlink currently in StructuredText_: 1. (Absolute & relative URIs.) Text enclosed by double quotes followed by a colon, a URI, and concluded by punctuation plus white space, or just white space, is treated as a hyperlink:: "Python":http://www.python.org/ 2. (Absolute URIs only.) Text enclosed by double quotes followed by a comma, one or more spaces, an absolute URI and concluded by punctuation plus white space, or just white space, is treated as a hyperlink:: "mail me", mailto:me@mail.com 3. (Endnotes.) Text enclosed by brackets link to an endnote at the end of the document: at the beginning of the line, two dots, a space, and the same text in brackets, followed by the end note itself:: Please refer to the fine manual [GVR2001]. .. [GVR2001] Python Documentation, Release 2.1, van Rossum, Drake, et al., http://www.python.org/doc/ The problem with forms 1 and 2 is that they are neither intuitive nor unobtrusive (they break design goals 5 & 2). They overload double-quotes, which are too often used in ordinary text (potentially breaking design goal 4). The brackets in form 3 are also too common in ordinary text (such as [nested] asides and Python lists like [12]). Alternatives: 1. Have no special markup for hyperlinks. 2. A. Interpret and mark up hyperlinks as any contiguous text containing '://' or ':...@' (absolute URI) or '@' (email address) after an alphanumeric word. To de-emphasize the URI, simply enclose it in parentheses: Python (http://www.python.org/) B. Leave special hyperlink markup as a domain-specific extension. Hyperlinks in ordinary reStructuredText documents would be required to be standalone (i.e. the URI text inline in the document text). Processed hyperlinks (where the URI text is hidden behind the link) are important enough to warrant syntax. 3. The original Setext_ introduced a mechanism of indirect hyperlinks. A source link word ('hot word') in the text was given a trailing underscore:: Here is some text with a hyperlink_ built in. The hyperlink itself appeared at the end of the document on a line by itself, beginning with two dots, a space, the link word with a leading underscore, whitespace, and the URI itself:: .. _hyperlink http://www.123.xyz Setext used ``underscores_instead_of_spaces_`` for phrase links. With some modification, alternative 3 best satisfies the design goals. It has the advantage of being readable and relatively unobtrusive. Since each source link must match up to a target, the odd variable ending in an underscore can be spared being marked up (although it should generate a "no such link target" warning). The only disadvantage is that phrase-links aren't possible without some obtrusive syntax. We could achieve phrase-links if we enclose the link text: 1. in double quotes:: "like this"_ 2. in brackets:: [like this]_ 3. or in backquotes:: `like this`_ Each gives us somewhat obtrusive markup, but that is unavoidable. The bracketed syntax (#2) is reminiscent of links on many web pages (intuitive), although it is somewhat obtrusive. Alternative #3 is much less obtrusive, and is consistent with interpreted text: the trailing underscore indicates the interpretation of the phrase, as a hyperlink. #3 also disambiguates hyperlinks from footnote references. Alternative #3 wins. The same trailing underscore markup can also be used for footnote and citation references, removing the problem with ordinary bracketed text and Python lists:: Please refer to the fine manual [GVR2000]_. .. [GVR2000] Python Documentation, van Rossum, Drake, et al., http://www.python.org/doc/ The two-dots-and-a-space syntax was generalized by Setext for comments, which are removed from the (visible) processed output. reStructuredText uses this syntax for comments, footnotes, and link target, collectively termed "explicit markup". For link targets, in order to eliminate ambiguity with comments and footnotes, reStructuredText specifies that a colon always follow the link target word/phrase. The colon denotes 'maps to'. There is no reason to restrict target links to the end of the document; they could just as easily be interspersed. Internal hyperlinks (links from one point to another within a single document) can be expressed by a source link as before, and a target link with a colon but no URI. In effect, these targets 'map to' the element immediately following. As an added bonus, we now have a perfect candidate for reStructuredText directives, a simple extension mechanism: explicit markup containing a single word followed by two colons and whitespace. The interpretation of subsequent data on the directive line or following is directive-dependent. To summarize:: .. This is a comment. .. The line below is an example of a directive. .. version:: 1 This is a footnote [1]_. This internal hyperlink will take us to the footnotes_ area below. Here is a one-word_ external hyperlink. Here is `a hyperlink phrase`_. .. _footnotes: .. [1] Footnote text goes here. .. external hyperlink target mappings: .. _one-word: http://www.123.xyz .. _a hyperlink phrase: http://www.123.xyz The presence or absence of a colon after the target link differentiates an indirect hyperlink from a footnote, respectively. A footnote requires brackets. Backquotes around a target link word or phrase are required if the phrase contains a colon, optional otherwise. Below are examples using no markup, the two StructuredText hypertext styles, and the reStructuredText hypertext style. Each example contains an indirect link, a direct link, a footnote/endnote, and bracketed text. In HTML, each example should evaluate to:: <P>A <A HREF="http://spam.org">URI</A>, see <A HREF="#eggs2000"> [eggs2000]</A> (in Bacon [Publisher]). Also see <A HREF="http://eggs.org">http://eggs.org</A>.</P> <P><A NAME="eggs2000">[eggs2000]</A> "Spam, Spam, Spam, Eggs, Bacon, and Spam"</P> 1. No markup:: A URI http://spam.org, see eggs2000 (in Bacon [Publisher]). Also see http://eggs.org. eggs2000 "Spam, Spam, Spam, Eggs, Bacon, and Spam" 2. StructuredText absolute/relative URI syntax ("text":http://www.url.org):: A "URI":http://spam.org, see [eggs2000] (in Bacon [Publisher]). Also see "http://eggs.org":http://eggs.org. .. [eggs2000] "Spam, Spam, Spam, Eggs, Bacon, and Spam" Note that StructuredText does not recognize standalone URIs, forcing doubling up as shown in the second line of the example above. 3. StructuredText absolute-only URI syntax ("text", mailto:you@your.com):: A "URI", http://spam.org, see [eggs2000] (in Bacon [Publisher]). Also see "http://eggs.org", http://eggs.org. .. [eggs2000] "Spam, Spam, Spam, Eggs, Bacon, and Spam" 4. reStructuredText syntax:: 4. A URI_, see [eggs2000]_ (in Bacon [Publisher]). Also see http://eggs.org. .. _URI: http:/spam.org .. [eggs2000] "Spam, Spam, Spam, Eggs, Bacon, and Spam" The bracketed text '[Publisher]' may be problematic with StructuredText (syntax 2 & 3). reStructuredText's syntax (#4) is definitely the most readable. The text is separated from the link URI and the footnote, resulting in cleanly readable text. .. _StructuredText: http://www.zope.org/DevHome/Members/jim/StructuredTextWiki/FrontPage .. _Setext: http://docutils.sourceforge.net/mirror/setext.html .. _reStructuredText: http://docutils.sourceforge.net/rst.html .. _detailed description: http://homepage.ntlworld.com/tibsnjoan/docutils/STNG-format.html .. _STMinus: http://www.cis.upenn.edu/~edloper/pydoc/stminus.html .. _StructuredTextNG: http://www.zope.org/DevHome/Members/jim/StructuredTextWiki/StructuredTextNG .. _README: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/~checkout~/ python/python/dist/src/README .. _Emacs table mode: http://table.sourceforge.net/ .. _reStructuredText Markup Specification: ../../ref/rst/restructuredtext.html .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/docs/dev/rst/alternatives.txt���������������������������������������������������������0000664�0001750�0001750�00000335141�11731663461�023023� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������================================================== A Record of reStructuredText Syntax Alternatives ================================================== :Author: David Goodger :Contact: docutils-develop@lists.sourceforge.net :Revision: $Revision: 7383 $ :Date: $Date: 2012-03-19 18:04:49 +0100 (Mon, 19. Mär 2012) $ :Copyright: This document has been placed in the public domain. The following are ideas, alternatives, and justifications that were considered for reStructuredText syntax, which did not originate with Setext_ or StructuredText_. For an analysis of constructs which *did* originate with StructuredText or Setext, please see `Problems With StructuredText`_. See the `reStructuredText Markup Specification`_ for full details of the established syntax. The ideas are divided into sections: * Implemented_: already done. The issues and alternatives are recorded here for posterity. * `Not Implemented`_: these ideas won't be implemented. * Tabled_: these ideas should be revisited in the future. * `To Do`_: these ideas should be implemented. They're just waiting for a champion to resolve issues and get them done. * `... Or Not To Do?`_: possible but questionable. These probably won't be implemented, but you never know. .. _Setext: http://docutils.sourceforge.net/mirror/setext.html .. _StructuredText: http://www.zope.org/DevHome/Members/jim/StructuredTextWiki/FrontPage .. _Problems with StructuredText: problems.html .. _reStructuredText Markup Specification: ../../ref/rst/restructuredtext.html .. contents:: ------------- Implemented ------------- Field Lists =========== Prior to the syntax for field lists being finalized, several alternatives were proposed. 1. Unadorned RFC822_ everywhere:: Author: Me Version: 1 Advantages: clean, precedent (RFC822-compliant). Disadvantage: ambiguous (these paragraphs are a prime example). Conclusion: rejected. 2. Special case: use unadorned RFC822_ for the very first or very last text block of a document:: """ Author: Me Version: 1 The rest of the document... """ Advantages: clean, precedent (RFC822-compliant). Disadvantages: special case, flat (unnested) field lists only, still ambiguous:: """ Usage: cmdname [options] arg1 arg2 ... We obviously *don't* want the like above to be interpreted as a field list item. Or do we? """ Conclusion: rejected for the general case, accepted for specific contexts (PEPs, email). 3. Use a directive:: .. fields:: Author: Me Version: 1 Advantages: explicit and unambiguous, RFC822-compliant. Disadvantage: cumbersome. Conclusion: rejected for the general case (but such a directive could certainly be written). 4. Use Javadoc-style:: @Author: Me @Version: 1 @param a: integer Advantages: unambiguous, precedent, flexible. Disadvantages: non-intuitive, ugly, not RFC822-compliant. Conclusion: rejected. 5. Use leading colons:: :Author: Me :Version: 1 Advantages: unambiguous, obvious (*almost* RFC822-compliant), flexible, perhaps even elegant. Disadvantages: no precedent, not quite RFC822-compliant. Conclusion: accepted! 6. Use double colons:: Author:: Me Version:: 1 Advantages: unambiguous, obvious? (*almost* RFC822-compliant), flexible, similar to syntax already used for literal blocks and directives. Disadvantages: no precedent, not quite RFC822-compliant, similar to syntax already used for literal blocks and directives. Conclusion: rejected because of the syntax similarity & conflicts. Why is RFC822 compliance important? It's a universal Internet standard, and super obvious. Also, I'd like to support the PEP format (ulterior motive: get PEPs to use reStructuredText as their standard). But it *would* be easy to get used to an alternative (easy even to convert PEPs; probably harder to convert python-deviants ;-). Unfortunately, without well-defined context (such as in email headers: RFC822 only applies before any blank lines), the RFC822 format is ambiguous. It is very common in ordinary text. To implement field lists unambiguously, we need explicit syntax. The following question was posed in a footnote: Should "bibliographic field lists" be defined at the parser level, or at the DPS transformation level? In other words, are they reStructuredText-specific, or would they also be applicable to another (many/every other?) syntax? The answer is that bibliographic fields are a reStructuredText-specific markup convention. Other syntaxes may implement the bibliographic elements explicitly. For example, there would be no need for such a transformation for an XML-based markup syntax. .. _RFC822: http://www.rfc-editor.org/rfc/rfc822.txt Interpreted Text "Roles" ======================== The original purpose of interpreted text was as a mechanism for descriptive markup, to describe the nature or role of a word or phrase. For example, in XML we could say "<function>len</function>" to mark up "len" as a function. It is envisaged that within Python docstrings (inline documentation in Python module source files, the primary market for reStructuredText) the role of a piece of interpreted text can be inferred implicitly from the context of the docstring within the program source. For other applications, however, the role may have to be indicated explicitly. Interpreted text is enclosed in single backquotes (`). 1. Initially, it was proposed that an explicit role could be indicated as a word or phrase within the enclosing backquotes: - As a prefix, separated by a colon and whitespace:: `role: interpreted text` - As a suffix, separated by whitespace and a colon:: `interpreted text :role` There are problems with the initial approach: - There could be ambiguity with interpreted text containing colons. For example, an index entry of "Mission: Impossible" would require a backslash-escaped colon. - The explicit role is descriptive markup, not content, and will not be visible in the processed output. Putting it inside the backquotes doesn't feel right; the *role* isn't being quoted. 2. Tony Ibbs suggested that the role be placed outside the backquotes:: role:`prefix` or `suffix`:role This removes the embedded-colons ambiguity, but limits the role identifier to be a single word (whitespace would be illegal). Since roles are not meant to be visible after processing, the lack of whitespace support is not important. The suggested syntax remains ambiguous with respect to ratios and some writing styles. For example, suppose there is a "signal" identifier, and we write:: ...calculate the `signal`:noise ratio. "noise" looks like a role. 3. As an improvement on #2, we can bracket the role with colons:: :role:`prefix` or `suffix`:role: This syntax is similar to that of field lists, which is fine since both are doing similar things: describing. This is the syntax chosen for reStructuredText. 4. Another alternative is two colons instead of one:: role::`prefix` or `suffix`::role But this is used for analogies ("A:B::C:D": "A is to B as C is to D"). Both alternative #2 and #4 lack delimiters on both sides of the role, making it difficult to parse (by the reader). 5. Some kind of bracketing could be used: - Parentheses:: (role)`prefix` or `suffix`(role) - Braces:: {role}`prefix` or `suffix`{role} - Square brackets:: [role]`prefix` or `suffix`[role] - Angle brackets:: <role>`prefix` or `suffix`<role> (The overlap of \*ML tags with angle brackets would be too confusing and precludes their use.) Syntax #3 was chosen for reStructuredText. Comments ======== A problem with comments (actually, with all indented constructs) is that they cannot be followed by an indented block -- a block quote -- without swallowing it up. I thought that perhaps comments should be one-liners only. But would this mean that footnotes, hyperlink targets, and directives must then also be one-liners? Not a good solution. Tony Ibbs suggested a "comment" directive. I added that we could limit a comment to a single text block, and that a "multi-block comment" could use "comment-start" and "comment-end" directives. This would remove the indentation incompatibility. A "comment" directive automatically suggests "footnote" and (hyperlink) "target" directives as well. This could go on forever! Bad choice. Garth Kidd suggested that an "empty comment", a ".." explicit markup start with nothing on the first line (except possibly whitespace) and a blank line immediately following, could serve as an "unindent". An empty comment does **not** swallow up indented blocks following it, so block quotes are safe. "A tiny but practical wart." Accepted. Anonymous Hyperlinks ==================== Alan Jaffray came up with this idea, along with the following syntax:: Search the `Python DOC-SIG mailing list archives`{}_. .. _: http://mail.python.org/pipermail/doc-sig/ The idea is sound and useful. I suggested a "double underscore" syntax:: Search the `Python DOC-SIG mailing list archives`__. .. __: http://mail.python.org/pipermail/doc-sig/ But perhaps single underscores are okay? The syntax looks better, but the hyperlink itself doesn't explicitly say "anonymous":: Search the `Python DOC-SIG mailing list archives`_. .. _: http://mail.python.org/pipermail/doc-sig/ Mixing anonymous and named hyperlinks becomes confusing. The order of targets is not significant for named hyperlinks, but it is for anonymous hyperlinks:: Hyperlinks: anonymous_, named_, and another anonymous_. .. _named: named .. _: anonymous1 .. _: anonymous2 Without the extra syntax of double underscores, determining which hyperlink references are anonymous may be difficult. We'd have to check which references don't have corresponding targets, and match those up with anonymous targets. Keeping to a simple consistent ordering (as with auto-numbered footnotes) seems simplest. reStructuredText will use the explicit double-underscore syntax for anonymous hyperlinks. An alternative (see `Reworking Explicit Markup (Round 1)`_ below) for the somewhat awkward ".. __:" syntax is "__":: An anonymous__ reference. __ http://anonymous Reworking Explicit Markup (Round 1) =================================== Alan Jaffray came up with the idea of `anonymous hyperlinks`_, added to reStructuredText. Subsequently it was asserted that hyperlinks (especially anonymous hyperlinks) would play an increasingly important role in reStructuredText documents, and therefore they require a simpler and more concise syntax. This prompted a review of the current and proposed explicit markup syntaxes with regards to improving usability. 1. Original syntax:: .. _blah: internal hyperlink target .. _blah: http://somewhere external hyperlink target .. _blah: blahblah_ indirect hyperlink target .. __: anonymous internal target .. __: http://somewhere anonymous external target .. __: blahblah_ anonymous indirect target .. [blah] http://somewhere footnote .. blah:: http://somewhere directive .. blah: http://somewhere comment .. Note:: The comment text was intentionally made to look like a hyperlink target. Origins: * Except for the colon (a delimiter necessary to allow for phrase-links), hyperlink target ``.. _blah:`` comes from Setext. * Comment syntax from Setext. * Footnote syntax from StructuredText ("named links"). * Directives and anonymous hyperlinks original to reStructuredText. Advantages: + Consistent explicit markup indicator: "..". + Consistent hyperlink syntax: ".. _" & ":". Disadvantages: - Anonymous target markup is awkward: ".. __:". - The explicit markup indicator ("..") is excessively overloaded? - Comment text is limited (can't look like a footnote, hyperlink, or directive). But this is probably not important. 2. Alan Jaffray's proposed syntax #1:: __ _blah internal hyperlink target __ blah: http://somewhere external hyperlink target __ blah: blahblah_ indirect hyperlink target __ anonymous internal target __ http://somewhere anonymous external target __ blahblah_ anonymous indirect target __ [blah] http://somewhere footnote .. blah:: http://somewhere directive .. blah: http://somewhere comment The hyperlink-connoted underscores have become first-level syntax. Advantages: + Anonymous targets are simpler. + All hyperlink targets are one character shorter. Disadvantages: - Inconsistent internal hyperlink targets. Unlike all other named hyperlink targets, there's no colon. There's an extra leading underscore, but we can't drop it because without it, "blah" looks like a relative URI. Unless we restore the colon:: __ blah: internal hyperlink target - Obtrusive markup? 3. Alan Jaffray's proposed syntax #2:: .. _blah internal hyperlink target .. blah: http://somewhere external hyperlink target .. blah: blahblah_ indirect hyperlink target .. anonymous internal target .. http://somewhere anonymous external target .. blahblah_ anonymous indirect target .. [blah] http://somewhere footnote !! blah: http://somewhere directive ## blah: http://somewhere comment Leading underscores have been (almost) replaced by "..", while comments and directives have gained their own syntax. Advantages: + Anonymous hyperlinks are simpler. + Unique syntax for comments. Connotation of "comment" from some programming languages (including our favorite). + Unique syntax for directives. Connotation of "action!". Disadvantages: - Inconsistent internal hyperlink targets. Again, unlike all other named hyperlink targets, there's no colon. There's a leading underscore, matching the trailing underscores of references, which no other hyperlink targets have. We can't drop that one leading underscore though: without it, "blah" looks like a relative URI. Again, unless we restore the colon:: .. blah: internal hyperlink target - All (except for internal) hyperlink targets lack their leading underscores, losing the "hyperlink" connotation. - Obtrusive syntax for comments. Alternatives:: ;; blah: http://somewhere (also comment syntax in Lisp & others) ,, blah: http://somewhere ("comma comma": sounds like "comment"!) - Iffy syntax for directives. Alternatives? 4. Tony Ibbs' proposed syntax:: .. _blah: internal hyperlink target .. _blah: http://somewhere external hyperlink target .. _blah: blahblah_ indirect hyperlink target .. anonymous internal target .. http://somewhere anonymous external target .. blahblah_ anonymous indirect target .. [blah] http://somewhere footnote .. blah:: http://somewhere directive .. blah: http://somewhere comment This is the same as the current syntax, except for anonymous targets which drop their "__: ". Advantage: + Anonymous targets are simpler. Disadvantages: - Anonymous targets lack their leading underscores, losing the "hyperlink" connotation. - Anonymous targets are almost indistinguishable from comments. (Better to know "up front".) 5. David Goodger's proposed syntax: Perhaps going back to one of Alan's earlier suggestions might be the best solution. How about simply adding "__ " as a synonym for ".. __: " in the original syntax? These would become equivalent:: .. __: anonymous internal target .. __: http://somewhere anonymous external target .. __: blahblah_ anonymous indirect target __ anonymous internal target __ http://somewhere anonymous external target __ blahblah_ anonymous indirect target Alternative 5 has been adopted. Backquotes in Phrase-Links ========================== [From a 2001-06-05 Doc-SIG post in reply to questions from Doug Hellmann.] The first draft of the spec, posted to the Doc-SIG in November 2000, used square brackets for phrase-links. I changed my mind because: 1. In the first draft, I had already decided on single-backquotes for inline literal text. 2. However, I wanted to minimize the necessity for backslash escapes, for example when quoting Python repr-equivalent syntax that uses backquotes. 3. The processing of identifiers (function/method/attribute/module etc. names) into hyperlinks is a useful feature. PyDoc recognizes identifiers heuristically, but it doesn't take much imagination to come up with counter-examples where PyDoc's heuristics would result in embarassing failure. I wanted to do it deterministically, and that called for syntax. I called this construct "interpreted text". 4. Leveraging off the ``*emphasis*/**strong**`` syntax, lead to the idea of using double-backquotes as syntax. 5. I worked out some rules for inline markup recognition. 6. In combination with #5, double backquotes lent themselves to inline literals, neatly satisfying #2, minimizing backslash escapes. In fact, the spec says that no interpretation of any kind is done within double-backquote inline literal text; backslashes do *no* escaping within literal text. 7. Single backquotes are then freed up for interpreted text. 8. I already had square brackets required for footnote references. 9. Since interpreted text will typically turn into hyperlinks, it was a natural fit to use backquotes as the phrase-quoting syntax for trailing-underscore hyperlinks. The original inspiration for the trailing underscore hyperlink syntax was Setext. But for phrases Setext used a very cumbersome ``underscores_between_words_like_this_`` syntax. The underscores can be viewed as if they were right-pointing arrows: ``-->``. So ``hyperlink_`` points away from the reference, and ``.. _hyperlink:`` points toward the target. Substitution Mechanism ====================== Substitutions arose out of a Doc-SIG thread begun on 2001-10-28 by Alan Jaffray, "reStructuredText inline markup". It reminded me of a missing piece of the reStructuredText puzzle, first referred to in my contribution to "Documentation markup & processing / PEPs" (Doc-SIG 2001-06-21). Substitutions allow the power and flexibility of directives to be shared by inline text. They are a way to allow arbitrarily complex inline objects, while keeping the details out of the flow of text. They are the equivalent of SGML/XML's named entities. For example, an inline image (using reference syntax alternative 4d (vertical bars) and definition alternative 3, the alternatives chosen for inclusion in the spec):: The |biohazard| symbol must be used on containers used to dispose of medical waste. .. |biohazard| image:: biohazard.png [height=20 width=20] The ``|biohazard|`` substitution reference will be replaced in-line by whatever the ``.. |biohazard|`` substitution definition generates (in this case, an image). A substitution definition contains the substitution text bracketed with vertical bars, followed by a an embedded inline-compatible directive, such as "image". A transform is required to complete the substitution. Syntax alternatives for the reference: 1. Use the existing interpreted text syntax, with a predefined role such as "sub":: The `biohazard`:sub: symbol... Advantages: existing syntax, explicit. Disadvantages: verbose, obtrusive. 2. Use a variant of the interpreted text syntax, with a new suffix akin to the underscore in phrase-link references:: (a) `name`@ (b) `name`# (c) `name`& (d) `name`/ (e) `name`< (f) `name`:: (g) `name`: Due to incompatibility with other constructs and ordinary text usage, (f) and (g) are not possible. 3. Use interpreted text syntax with a fixed internal format:: (a) `:name:` (b) `name:` (c) `name::` (d) `::name::` (e) `%name%` (f) `#name#` (g) `/name/` (h) `&name&` (i) `|name|` (j) `[name]` (k) `<name>` (l) `&name;` (m) `'name'` To avoid ML confusion (k) and (l) are definitely out. Square brackets (j) won't work in the target (the substitution definition would be indistinguishable from a footnote). The ```/name/``` syntax (g) is reminiscent of "s/find/sub" substitution syntax in ed-like languages. However, it may have a misleading association with regexps, and looks like an absolute POSIX path. (i) is visually equivalent and lacking the connotations. A disadvantage of all of these is that they limit interpreted text, albeit only slightly. 4. Use specialized syntax, something new:: (a) #name# (b) @name@ (c) /name/ (d) |name| (e) <<name>> (f) //name// (g) ||name|| (h) ^name^ (i) [[name]] (j) ~name~ (k) !name! (l) =name= (m) ?name? (n) >name< "#" (a) and "@" (b) are obtrusive. "/" (c) without backquotes looks just like a POSIX path; it is likely for such usage to appear in text. "|" (d) and "^" (h) are feasible. 5. Redefine the trailing underscore syntax. See definition syntax alternative 4, below. Syntax alternatives for the definition: 1. Use the existing directive syntax, with a predefined directive such as "sub". It contains a further embedded directive resolving to an inline-compatible object:: .. sub:: biohazard .. image:: biohazard.png [height=20 width=20] .. sub:: parrot That bird wouldn't *voom* if you put 10,000,000 volts through it! The advantages and disadvantages are the same as in inline alternative 1. 2. Use syntax as in #1, but with an embedded directivecompressed:: .. sub:: biohazard image:: biohazard.png [height=20 width=20] This is a bit better than alternative 1, but still too much. 3. Use a variant of directive syntax, incorporating the substitution text, obviating the need for a special "sub" directive name. If we assume reference alternative 4d (vertical bars), the matching definition would look like this:: .. |biohazard| image:: biohazard.png [height=20 width=20] 4. (Suggested by Alan Jaffray on Doc-SIG from 2001-11-06.) Instead of adding new syntax, redefine the trailing underscore syntax to mean "substitution reference" instead of "hyperlink reference". Alan's example:: I had lunch with Jonathan_ today. We talked about Zope_. .. _Jonathan: lj [user=jhl] .. _Zope: http://www.zope.org/ A problem with the proposed syntax is that URIs which look like simple reference names (alphanum plus ".", "-", "_") would be indistinguishable from substitution directive names. A more consistent syntax would be:: I had lunch with Jonathan_ today. We talked about Zope_. .. _Jonathan: lj:: user=jhl .. _Zope: http://www.zope.org/ (``::`` after ``.. _Jonathan: lj``.) The "Zope" target is a simple external hyperlink, but the "Jonathan" target contains a directive. Alan proposed is that the reference text be replaced by whatever the referenced directive (the "directive target") produces. A directive reference becomes a hyperlink reference if the contents of the directive target resolve to a hyperlink. If the directive target resolves to an icon, the reference is replaced by an inline icon. If the directive target resolves to a hyperlink, the directive reference becomes a hyperlink reference. This seems too indirect and complicated for easy comprehension. The reference in the text will sometimes become a link, sometimes not. Sometimes the reference text will remain, sometimes not. We don't know *at the reference*:: This is a `hyperlink reference`_; its text will remain. This is an `inline icon`_; its text will disappear. That's a problem. The syntax that has been incorporated into the spec and parser is reference alternative 4d with definition alternative 3:: The |biohazard| symbol... .. |biohazard| image:: biohazard.png [height=20 width=20] We can also combine substitution references with hyperlink references, by appending a "_" (named hyperlink reference) or "__" (anonymous hyperlink reference) suffix to the substitution reference. This allows us to click on an image-link:: The |biohazard|_ symbol... .. |biohazard| image:: biohazard.png [height=20 width=20] .. _biohazard: http://www.cdc.gov/ There have been several suggestions for the naming of these constructs, originally called "substitution references" and "substitutions". 1. Candidate names for the reference construct: (a) substitution reference (b) tagging reference (c) inline directive reference (d) directive reference (e) indirect inline directive reference (f) inline directive placeholder (g) inline directive insertion reference (h) directive insertion reference (i) insertion reference (j) directive macro reference (k) macro reference (l) substitution directive reference 2. Candidate names for the definition construct: (a) substitution (b) substitution directive (c) tag (d) tagged directive (e) directive target (f) inline directive (g) inline directive definition (h) referenced directive (i) indirect directive (j) indirect directive definition (k) directive definition (l) indirect inline directive (m) named directive definition (n) inline directive insertion definition (o) directive insertion definition (p) insertion definition (q) insertion directive (r) substitution definition (s) directive macro definition (t) macro definition (u) substitution directive definition (v) substitution definition "Inline directive reference" (1c) seems to be an appropriate term at first, but the term "inline" is redundant in the case of the reference. Its counterpart "inline directive definition" (2g) is awkward, because the directive definition itself is not inline. "Directive reference" (1d) and "directive definition" (2k) are too vague. "Directive definition" could be used to refer to any directive, not just those used for inline substitutions. One meaning of the term "macro" (1k, 2s, 2t) is too programming-language-specific. Also, macros are typically simple text substitution mechanisms: the text is substituted first and evaluated later. reStructuredText substitution definitions are evaluated in place at parse time and substituted afterwards. "Insertion" (1h, 1i, 2n-2q) is almost right, but it implies that something new is getting added rather than one construct being replaced by another. Which brings us back to "substitution". The overall best names are "substitution reference" (1a) and "substitution definition" (2v). A long way to go to add one word! Inline External Targets ======================= Currently reStructuredText has two hyperlink syntax variations: * Named hyperlinks:: This is a named reference_ of one word ("reference"). Here is a `phrase reference`_. Phrase references may even cross `line boundaries`_. .. _reference: http://www.example.org/reference/ .. _phrase reference: http://www.example.org/phrase_reference/ .. _line boundaries: http://www.example.org/line_boundaries/ + Advantages: - The plaintext is readable. - Each target may be reused multiple times (e.g., just write ``"reference_"`` again). - No syncronized ordering of references and targets is necessary. + Disadvantages: - The reference text must be repeated as target names; could lead to mistakes. - The target URLs may be located far from the references, and hard to find in the plaintext. * Anonymous hyperlinks (in current reStructuredText):: This is an anonymous reference__. Here is an anonymous `phrase reference`__. Phrase references may even cross `line boundaries`__. __ http://www.example.org/reference/ __ http://www.example.org/phrase_reference/ __ http://www.example.org/line_boundaries/ + Advantages: - The plaintext is readable. - The reference text does not have to be repeated. + Disadvantages: - References and targets must be kept in sync. - Targets cannot be reused. - The target URLs may be located far from the references. For comparison and historical background, StructuredText also has two syntaxes for hyperlinks: * First, ``"reference text":URL``:: This is a "reference":http://www.example.org/reference/ of one word ("reference"). Here is a "phrase reference":http://www.example.org/phrase_reference/. * Second, ``"reference text", http://example.com/absolute_URL``:: This is a "reference", http://www.example.org/reference/ of one word ("reference"). Here is a "phrase reference", http://www.example.org/phrase_reference/. Both syntaxes share advantages and disadvantages: + Advantages: - The target is specified immediately adjacent to the reference. + Disadvantages: - Poor plaintext readability. - Targets cannot be reused. - Both syntaxes use double quotes, common in ordinary text. - In the first syntax, the URL and the last word are stuck together, exacerbating the line wrap problem. - The second syntax is too magical; text could easily be written that way by accident (although only absolute URLs are recognized here, perhaps because of the potential for ambiguity). A new type of "inline external hyperlink" has been proposed. 1. On 2002-06-28, Simon Budig proposed__ a new syntax for reStructuredText hyperlinks:: This is a reference_(http://www.example.org/reference/) of one word ("reference"). Here is a `phrase reference`_(http://www.example.org/phrase_reference/). Are these examples, (single-underscore), named? If so, `anonymous references`__(http://www.example.org/anonymous/) using two underscores would probably be preferable. __ http://mail.python.org/pipermail/doc-sig/2002-June/002648.html The syntax, advantages, and disadvantages are similar to those of StructuredText. + Advantages: - The target is specified immediately adjacent to the reference. + Disadvantages: - Poor plaintext readability. - Targets cannot be reused (unless named, but the semantics are unclear). + Problems: - The ``"`ref`_(URL)"`` syntax forces the last word of the reference text to be joined to the URL, making a potentially very long word that can't be wrapped (URLs can be very long). The reference and the URL should be separate. This is a symptom of the following point: - The syntax produces a single compound construct made up of two equally important parts, *with syntax in the middle*, *between* the reference and the target. This is unprecedented in reStructuredText. - The "inline hyperlink" text is *not* a named reference (there's no lookup by name), so it shouldn't look like one. - According to the IETF standards RFC 2396 and RFC 2732, parentheses are legal URI characters and curly braces are legal email characters, making their use prohibitively difficult. - The named/anonymous semantics are unclear. 2. After an analysis__ of the syntax of (1) above, we came up with the following compromise syntax:: This is an anonymous reference__ __<http://www.example.org/reference/> of one word ("reference"). Here is a `phrase reference`__ __<http://www.example.org/phrase_reference/>. `Named references`_ _<http://www.example.org/anonymous/> use single underscores. __ http://mail.python.org/pipermail/doc-sig/2002-July/002670.html The syntax builds on that of the existing "inline internal targets": ``an _`inline internal target`.`` + Advantages: - The target is specified immediately adjacent to the reference, improving maintainability: - References and targets are easily kept in sync. - The reference text does not have to be repeated. - The construct is executed in two parts: references identical to existing references, and targets that are new but not too big a stretch from current syntax. - There's overwhelming precedent for quoting URLs with angle brackets [#]_. + Disadvantages: - Poor plaintext readability. - Lots of "line noise". - Targets cannot be reused (unless named; see below). To alleviate the readability issue slightly, we could allow the target to appear later, such as after the end of the sentence:: This is a named reference__ of one word ("reference"). __<http://www.example.org/reference/> Here is a `phrase reference`__. __<http://www.example.org/phrase_reference/> Problem: this could only work for one reference at a time (reference/target pairs must be proximate [refA trgA refB trgB], not interleaved [refA refB trgA trgB] or nested [refA refB trgB trgA]). This variation is too problematic; references and inline external targets will have to be kept imediately adjacent (see (3) below). The ``"reference__ __<target>"`` syntax is actually for "anonymous inline external targets", emphasized by the double underscores. It follows that single trailing and leading underscores would lead to *implicitly named* inline external targets. This would allow the reuse of targets by name. So after ``"reference_ _<target>"``, another ``"reference_"`` would point to the same target. .. [#] From RFC 2396 (URI syntax): The angle-bracket "<" and ">" and double-quote (") characters are excluded [from URIs] because they are often used as the delimiters around URI in text documents and protocol fields. Using <> angle brackets around each URI is especially recommended as a delimiting style for URI that contain whitespace. From RFC 822 (email headers): Angle brackets ("<" and ">") are generally used to indicate the presence of a one machine-usable reference (e.g., delimiting mailboxes), possibly including source-routing to the machine. 3. If it is best for references and inline external targets to be immediately adjacent, then they might as well be integrated. Here's an alternative syntax embedding the target URL in the reference:: This is an anonymous `reference <http://www.example.org /reference/>`__ of one word ("reference"). Here is a `phrase reference <http://www.example.org/phrase_reference/>`__. Advantages and disadvantages are similar to those in (2). Readability is still an issue, but the syntax is a bit less heavyweight (reduced line noise). Backquotes are required, even for one-word references; the target URL is included within the reference text, forcing a phrase context. We'll call this variant "embedded URIs". Problem: how to refer to a title like "HTML Anchors: <a>" (which ends with an HTML/SGML/XML tag)? We could either require more syntax on the target (like ``"`reference text __<http://example.com/>`__"``), or require the odd conflicting title to be escaped (like ``"`HTML Anchors: \<a>`__"``). The latter seems preferable, and not too onerous. Similarly to (2) above, a single trailing underscore would convert the reference & inline external target from anonymous to implicitly named, allowing reuse of targets by name. I think this is the least objectionable of the syntax alternatives. Other syntax variations have been proposed (by Brett Cannon and Benja Fallenstein):: `phrase reference`->http://www.example.com `phrase reference`@http://www.example.com `phrase reference`__ ->http://www.example.com `phrase reference` [-> http://www.example.com] `phrase reference`__ [-> http://www.example.com] `phrase reference` <http://www.example.com>_ None of these variations are clearly superior to #3 above. Some have problems that exclude their use. With any kind of inline external target syntax it comes down to the conflict between maintainability and plaintext readability. I don't see a major problem with reStructuredText's maintainability, and I don't want to sacrifice plaintext readability to "improve" it. The proponents of inline external targets want them for easily maintainable web pages. The arguments go something like this: - Named hyperlinks are difficult to maintain because the reference text is duplicated as the target name. To which I said, "So use anonymous hyperlinks." - Anonymous hyperlinks are difficult to maintain becuase the references and targets have to be kept in sync. "So keep the targets close to the references, grouped after each paragraph. Maintenance is trivial." - But targets grouped after paragraphs break the flow of text. "Surely less than URLs embedded in the text! And if the intent is to produce web pages, not readable plaintext, then who cares about the flow of text?" Many participants have voiced their objections to the proposed syntax: Garth Kidd: "I strongly prefer the current way of doing it. Inline is spectactularly messy, IMHO." Tony Ibbs: "I vehemently agree... that the inline alternatives being suggested look messy - there are/were good reasons they've been taken out... I don't believe I would gain from the new syntaxes." Paul Moore: "I agree as well. The proposed syntax is far too punctuation-heavy, and any of the alternatives discussed are ambiguous or too subtle." Others have voiced their support: fantasai: "I agree with Simon. In many cases, though certainly not in all, I find parenthesizing the url in plain text flows better than relegating it to a footnote." Ken Manheimer: "I'd like to weigh in requesting some kind of easy, direct inline reference link." (Interesting that those *against* the proposal have been using reStructuredText for a while, and those *for* the proposal are either new to the list ["fantasai", background unknown] or longtime StructuredText users [Ken Manheimer].) I was initially ambivalent/against the proposed "inline external targets". I value reStructuredText's readability very highly, and although the proposed syntax offers convenience, I don't know if the convenience is worth the cost in ugliness. Does the proposed syntax compromise readability too much, or should the choice be left up to the author? Perhaps if the syntax is *allowed* but its use strongly *discouraged*, for aesthetic/readability reasons? After a great deal of thought and much input from users, I've decided that there are reasonable use cases for this construct. The documentation should strongly caution against its use in most situations, recommending independent block-level targets instead. Syntax #3 above ("embedded URIs") will be used. Doctree Representation of Transitions ===================================== (Although not reStructuredText-specific, this section fits best in this document.) Having added the "horizontal rule" construct to the `reStructuredText Markup Specification`_, a decision had to be made as to how to reflect the construct in the implementation of the document tree. Given this source:: Document ======== Paragraph 1 -------- Paragraph 2 The horizontal rule indicates a "transition" (in prose terms) or the start of a new "division". Before implementation, the parsed document tree would be:: <document> <section names="document"> <title> Document <paragraph> Paragraph 1 -------- <--- error here <paragraph> Paragraph 2 There are several possibilities for the implementation: 1. Implement horizontal rules as "divisions" or segments. A "division" is a title-less, non-hierarchical section. The first try at an implementation looked like this:: <document> <section names="document"> <title> Document <paragraph> Paragraph 1 <division> <paragraph> Paragraph 2 But the two paragraphs are really at the same level; they shouldn't appear to be at different levels. There's really an invisible "first division". The horizontal rule splits the document body into two segments, which should be treated uniformly. 2. Treating "divisions" uniformly brings us to the second possibility:: <document> <section names="document"> <title> Document <division> <paragraph> Paragraph 1 <division> <paragraph> Paragraph 2 With this change, documents and sections will directly contain divisions and sections, but not body elements. Only divisions will directly contain body elements. Even without a horizontal rule anywhere, the body elements of a document or section would be contained within a division element. This makes the document tree deeper. This is similar to the way HTML_ treats document contents: grouped within a ``<body>`` element. 3. Implement them as "transitions", empty elements:: <document> <section names="document"> <title> Document <paragraph> Paragraph 1 <transition> <paragraph> Paragraph 2 A transition would be a "point element", not containing anything, only identifying a point within the document structure. This keeps the document tree flatter, but the idea of a "point element" like "transition" smells bad. A transition isn't a thing itself, it's the space between two divisions. However, transitions are a practical solution. Solution 3 was chosen for incorporation into the document tree model. .. _HTML: http://www.w3.org/MarkUp/ Syntax for Line Blocks ====================== * An early idea: How about a literal-block-like prefix, perhaps "``;;``"? (It is, after all, a *semi-literal* literal block, no?) Example:: Take it away, Eric the Orchestra Leader! ;; A one, two, a one two three four Half a bee, philosophically, must, *ipso facto*, half not be. But half the bee has got to be, *vis a vis* its entity. D'you see? But can a bee be said to be or not to be an entire bee, when half the bee is not a bee, due to some ancient injury? Singing... Kinda lame. * Another idea: in an ordinary paragraph, if the first line ends with a backslash (escaping the newline), interpret the entire paragraph as a verse block? For example:: Add just one backslash\ And this paragraph becomes An awful haiku (Awful, and arguably invalid, since in Japanese the word "haiku" contains three syllables not two.) This idea was superceded by the rules for escaped whitespace, useful for `character-level inline markup`_. * In a `2004-02-22 docutils-develop message`__, Jarno Elonen proposed a "plain list" syntax (and also provided a patch):: | John Doe | President, SuperDuper Corp. | jdoe@example.org __ http://thread.gmane.org/gmane.text.docutils.devel/1187 This syntax is very natural. However, these "plain lists" seem very similar to line blocks, and I see so little intrinsic "list-ness" that I'm loathe to add a new object. I used the term "blurbs" to remove the "list" connotation from the originally proposed name. Perhaps line blocks could be refined to add the two properties they currently lack: A) long lines wrap nicely B) HTML output doesn't look like program code in non-CSS web browsers (A) is an issue of all 3 aspects of Docutils: syntax (construct behaviour), internal representation, and output. (B) is partly an issue of internal representation but mostly of output. ReStructuredText will redefine line blocks with the "|"-quoting syntax. The following is my current thinking. Syntax ------ Perhaps line block syntax like this would do:: | M6: James Bond | MIB: Mr. J. | IMF: not decided yet, but probably one of the following: | Ethan Hunt | Jim Phelps | Claire Phelps | CIA: Lea Leiter Note that the "nested" list does not have nested syntax (the "|" are not further indented); the leading whitespace would still be significant somehow (more below). As for long lines in the input, this could suffice:: | John Doe | Founder, President, Chief Executive Officer, Cook, Bottle Washer, and All-Round Great Guy | SuperDuper Corp. | jdoe@example.org The lack of "|" on the third line indicates that it's a continuation of the second line, wrapped. I don't see much point in allowing arbitrary nested content. Multiple paragraphs or bullet lists inside a "blurb" doesn't make sense to me. Simple nested line blocks should suffice. Internal Representation ----------------------- Line blocks are currently represented as text blobs as follows:: <!ELEMENT line_block %text.model;> <!ATTLIST line_block %basic.atts; %fixedspace.att;> Instead, we could represent each line by a separate element:: <!ELEMENT line_block (line+)> <!ATTLIST line_block %basic.atts;> <!ELEMENT line %text.model;> <!ATTLIST line %basic.atts;> We'd keep the significance of the leading whitespace of each line either by converting it to non-breaking spaces at output, or with a per-line margin. Non-breaking spaces are simpler (for HTML, anyway) but kludgey, and wouldn't support indented long lines that wrap. But should inter-word whitespace (i.e., not leading whitespace) be preserved? Currently it is preserved in line blocks. Representing a more complex line block may be tricky:: | But can a bee be said to be | or not to be an entire bee, | when half the bee is not a bee, | due to some ancient injury? Perhaps the representation could allow for nested line blocks:: <!ELEMENT line_block (line | line_block)+> With this model, leading whitespace would no longer be significant. Instead, left margins are implied by the nesting. The example above could be represented as follows:: <line_block> <line> But can a bee be said to be <line_block> <line> or not to be an entire bee, <line_block> <line> when half the bee is not a bee, <line_block> <line> due to some ancient injury? I wasn't sure what to do about even more complex line blocks:: | Indented | Not indented | Indented a bit | A bit more | Only one space How should that be parsed and nested? Should the first line have the same nesting level (== indentation in the output) as the fourth line, or the same as the last line? Mark Nodine suggested that such line blocks be parsed similarly to complexly-nested block quotes, which seems reasonable. In the example above, this would result in the nesting of first line matching the last line's nesting. In other words, the nesting would be relative to neighboring lines only. Output ------ In HTML, line blocks are currently output as "<pre>" blocks, which gives us significant whitespace and line breaks, but doesn't allow long lines to wrap and causes monospaced output without stylesheets. Instead, we could output "<div>" elements parallelling the representation above, where each nested <div class="line_block"> would have an increased left margin (specified in the stylesheet). Jarno suggested the following HTML output:: <div class="line_block"> <span class="line">First, top level line</span><br class="hidden"/> <div class="line_block"><span class="hidden"> </span> <span class="line">Second, once nested</span><br class="hidden"/> <span class="line">Third, once nested</span><br class="hidden"/> ... </div> ... </div> The ``<br class="hidden" />`` and ``<span class="hidden"> </span>`` are meant to support non-CSS and non-graphical browsers. I understand the case for "br", but I'm not so sure about hidden " ". I question how much effort should be put toward supporting non-graphical and especially non-CSS browsers, at least for html4css1.py output. Should the lines themselves be ``<span>`` or ``<div>``? I don't like mixing inline and block-level elements. Implementation Plan ------------------- We'll leave the old implementation in place (via the "line-block" directive only) until all Writers have been updated to support the new syntax & implementation. The "line-block" directive can then be updated to use the new internal representation, and its documentation will be updated to recommend the new syntax. List-Driven Tables ================== The original idea came from Dylan Jay: ... to use a two level bulleted list with something to indicate it should be rendered as a table ... It's an interesting idea. It could be implemented in as a directive which transforms a uniform two-level list into a table. Using a directive would allow the author to explicitly set the table's orientation (by column or by row), the presence of row headers, etc. Alternatives: 1. (Implemented in Docutils 0.3.8). Bullet-list-tables might look like this:: .. list-table:: * - Treat - Quantity - Description * - Albatross! - 299 - On a stick! * - Crunchy Frog! - 1499 - If we took the bones out, it wouldn't be crunchy, now would it? * - Gannet Ripple! - 199 - On a stick! This list must be written in two levels. This wouldn't work:: .. list-table:: * Treat * Albatross! * Gannet! * Crunchy Frog! * Quantity * 299 * 199 * 1499 * Description * On a stick! * On a stick! * If we took the bones out... The above is a single list of 12 items. The blank lines are not significant to the markup. We'd have to explicitly specify how many columns or rows to use, which isn't a good idea. 2. Beni Cherniavsky suggested a field list alternative. It could look like this:: .. field-list-table:: :headrows: 1 - :treat: Treat :quantity: Quantity :descr: Description - :treat: Albatross! :quantity: 299 :descr: On a stick! - :treat: Crunchy Frog! :quantity: 1499 :descr: If we took the bones out, it wouldn't be crunchy, now would it? Column order is determined from the order of fields in the first row. Field order in all other rows is ignored. As a side-effect, this allows trivial re-arrangement of columns. By using named fields, it becomes possible to omit fields in some rows without losing track of things, which is important for spans. 3. An alternative to two-level bullet lists would be to use enumerated lists for the table cells:: .. list-table:: * 1. Treat 2. Quantity 3. Description * 1. Albatross! 2. 299 3. On a stick! * 1. Crunchy Frog! 2. 1499 3. If we took the bones out, it wouldn't be crunchy, now would it? That provides better correspondence between cells in the same column than does bullet-list syntax, but not as good as field list syntax. I think that were only field-list-tables available, a lot of users would use the equivalent degenerate case:: .. field-list-table:: - :1: Treat :2: Quantity :3: Description ... 4. Another natural variant is to allow a description list with field lists as descriptions:: .. list-table:: :headrows: 1 Treat :quantity: Quantity :descr: Description Albatross! :quantity: 299 :descr: On a stick! Crunchy Frog! :quantity: 1499 :descr: If we took the bones out, it wouldn't be crunchy, now would it? This would make the whole first column a header column ("stub"). It's limited to a single column and a single paragraph fitting on one source line. Also it wouldn't allow for empty cells or row spans in the first column. But these are limitations that we could live with, like those of simple tables. The List-driven table feature could be done in many ways. Each user will have their preferred usage. Perhaps a single "list-table" directive could handle them all, depending on which options and content are present. Issues: * How to indicate that there's 1 header row? Perhaps two lists? :: .. list-table:: + - Treat - Quantity - Description * - Albatross! - 299 - On a stick! This is probably too subtle though. Better would be a directive option, like ``:headrows: 1``. An early suggestion for the header row(s) was to use a directive option:: .. field-list-table:: :header: - :treat: Treat :quantity: Quantity :descr: Description - :treat: Albatross! :quantity: 299 :descr: On a stick! But the table data is at two levels and looks inconsistent. In general, we cannot extract the header row from field lists' field names because field names cannot contain everything one might put in a table cell. A separate header row also allows shorter field names and doesn't force one to rewrite the whole table when the header text changes. But for simpler cases, we can offer a ":header: fields" option, which does extract header cells from field names:: .. field-list-table:: :header: fields - :Treat: Albatross! :Quantity: 299 :Description: On a stick! * How to indicate the column widths? A directive option? :: .. list-table:: :widths: 15 10 35 Automatic defaults from the text used? * How to handle row and/or column spans? In a field list, column-spans can be indicated by specifying the first and last fields, separated by space-dash-space or ellipsis:: - :foo - baz: quuux - :foo ... baz: quuux Commas were proposed for column spans:: - :foo, bar: quux But non-adjacent columns become problematic. Should we report an error, or duplicate the value into each span of adjacent columns (as was suggested)? The latter suggestion is appealing but may be too clever. Best perhaps to simply specify the two ends. It was suggested that comma syntax should be allowed, too, in order to allow the user to avoid trouble when changing the column order. But changing the column order of a table with spans is not trivial; we shouldn't make it easier to mess up. One possible syntax for row-spans is to simply treat any row where a field is missing as a row-span from the last row where it appeared. Leaving a field empty would still be possible by writing a field with empty content. But this is too implicit. Another way would be to require an explicit continuation marker (``...``/``-"-``/``"``?) in all but the first row of a spanned field. Empty comments could work (".."). If implemented, the same marker could also be supported in simple tables, which lack row-spanning abilities. Explicit markup like ":rowspan:" and ":colspan:" was also suggested. Sometimes in a table, the first header row contains spans. It may be necessary to provide a way to specify the column field names independently of data rows. A directive option would do it. * We could specify "column-wise" or "row-wise" ordering, with the same markup structure. For example, with definition data:: .. list-table:: :column-wise: Treat - Albatross! - Crunchy Frog! Quantity - 299 - 1499 Description - On a stick! - If we took the bones out, it wouldn't be crunchy, now would it? * A syntax for _`stubs in grid tables` is easy to imagine:: +------------------------++------------+----------+ | Header row, column 1 || Header 2 | Header 3 | +========================++============+==========+ | body row 1, column 1 || column 2 | column 3 | +------------------------++------------+----------+ Or this idea from Nick Moffitt:: +-----+---+---+ | XOR # T | F | +=====+===+===+ | T # F | T | +-----+---+---+ | F # T | F | +-----+---+---+ Auto-Enumerated Lists ===================== Implemented 2005-03-24: combination of variation 1 & 2. The advantage of auto-numbered enumerated lists would be similar to that of auto-numbered footnotes: lists could be written and rearranged without having to manually renumber them. The disadvantages are also the same: input and output wouldn't match exactly; the markup may be ugly or confusing (depending on which alternative is chosen). 1. Use the "#" symbol. Example:: #. Item 1. #. Item 2. #. Item 3. Advantages: simple, explicit. Disadvantage: enumeration sequence cannot be specified (limited to arabic numerals); ugly. 2. As a variation on #1, first initialize the enumeration sequence? For example:: a) Item a. #) Item b. #) Item c. Advantages: simple, explicit, any enumeration sequence possible. Disadvantages: ugly; perhaps confusing with mixed concrete/abstract enumerators. 3. Alternative suggested by Fred Bremmer, from experience with MoinMoin:: 1. Item 1. 1. Item 2. 1. Item 3. Advantages: enumeration sequence is explicit (could be multiple "a." or "(I)" tokens). Disadvantages: perhaps confusing; otherwise erroneous input (e.g., a duplicate item "1.") would pass silently, either causing a problem later in the list (if no blank lines between items) or creating two lists (with blanks). Take this input for example:: 1. Item 1. 1. Unintentional duplicate of item 1. 2. Item 2. Currently the parser will produce two list, "1" and "1,2" (no warnings, because of the presence of blank lines). Using Fred's notation, the current behavior is "1,1,2 -> 1 1,2" (without blank lines between items, it would be "1,1,2 -> 1 [WARNING] 1,2"). What should the behavior be with auto-numbering? Fred has produced a patch__, whose initial behavior is as follows:: 1,1,1 -> 1,2,3 1,2,2 -> 1,2,3 3,3,3 -> 3,4,5 1,2,2,3 -> 1,2,3 [WARNING] 3 1,1,2 -> 1,2 [WARNING] 2 (After the "[WARNING]", the "3" would begin a new list.) I have mixed feelings about adding this functionality to the spec & parser. It would certainly be useful to some users (myself included; I often have to renumber lists). Perhaps it's too clever, asking the parser to guess too much. What if you *do* want three one-item lists in a row, each beginning with "1."? You'd have to use empty comments to force breaks. Also, I question whether "1,2,2 -> 1,2,3" is optimal behavior. In response, Fred came up with "a stricter and more explicit rule [which] would be to only auto-number silently if *all* the enumerators of a list were identical". In that case:: 1,1,1 -> 1,2,3 1,2,2 -> 1,2 [WARNING] 2 3,3,3 -> 3,4,5 1,2,2,3 -> 1,2 [WARNING] 2,3 1,1,2 -> 1,2 [WARNING] 2 Should any start-value be allowed ("3,3,3"), or should auto-numbered lists be limited to begin with ordinal-1 ("1", "A", "a", "I", or "i")? __ http://sourceforge.net/tracker/index.php?func=detail&aid=548802 &group_id=38414&atid=422032 4. Alternative proposed by Tony Ibbs:: #1. First item. #3. Aha - I edited this in later. #2. Second item. The initial proposal required unique enumerators within a list, but this limits the convenience of a feature of already limited applicability and convenience. Not a useful requirement; dropped. Instead, simply prepend a "#" to a standard list enumerator to indicate auto-enumeration. The numbers (or letters) of the enumerators themselves are not significant, except: - as a sequence indicator (arabic, roman, alphabetic; upper/lower), - and perhaps as a start value (first list item). Advantages: explicit, any enumeration sequence possible. Disadvantages: a bit ugly. Adjacent citation references ============================ A special case for inline markup was proposed and implemented: multiple citation references could be joined into one:: [cite1]_[cite2]_ instead of requiring [cite1]_ [cite2]_ However, this was rejected as an unwarranted exception to the rules for inline markup. (The main motivation for the proposal, grouping citations in the latex writer, was implemented by recognising the second group in the example above and transforming it into ``\cite{cite1,cite2}``.) Inline markup recognition ========================= Implemented 2011-12-05 (version 0.9): Extended `inline markup recognition rules`_. Non-ASCII whitespace, punctuation characters and "international" quotes are allowed around inline markup (based on `Unicode categories`_). The rules for ASCII characters were not changed. Rejected alternatives: a) Use `Unicode categories`_ for all chars (ASCII or not) +1 comprehensible, standards based, -1 many "false positives" need escaping, -1 not backwards compatible. b) full backwards compatibility :Pi: only before start-string :Pf: only behind end-string :Po: "conservative" sorting of other punctuation: :``.,;!?\\``: Close :``¡¿``: Open +1 backwards compatible, +1 logical extension of the existing rules, -1 exception list for "other" punctuation needed, -1 rules even more complicated, -1 not clear how to sort "other" punctuation that is currently not recognized, -2 international quoting convention like »German ›angular‹ quotes« not recognized. .. _Inline markup recognition rules: ../../ref/rst/restructuredtext.html#inline-markup-recognition-rules .. _Unicode categories: http://www.unicode.org/Public/5.1.0/ucd/UCD.html#General_Category_Values ----------------- Not Implemented ----------------- Reworking Footnotes =================== As a further wrinkle (see `Reworking Explicit Markup (Round 1)`_ above), in the wee hours of 2002-02-28 I posted several ideas for changes to footnote syntax: - Change footnote syntax from ``.. [1]`` to ``_[1]``? ... - Differentiate (with new DTD elements) author-date "citations" (``[GVR2002]``) from numbered footnotes? ... - Render footnote references as superscripts without "[]"? ... These ideas are all related, and suggest changes in the reStructuredText syntax as well as the docutils tree model. The footnote has been used for both true footnotes (asides expanding on points or defining terms) and for citations (references to external works). Rather than dealing with one amalgam construct, we could separate the current footnote concept into strict footnotes and citations. Citations could be interpreted and treated differently from footnotes. Footnotes would be limited to numerical labels: manual ("1") and auto-numbered (anonymous "#", named "#label"). The footnote is the only explicit markup construct (starts with ".. ") that directly translates to a visible body element. I've always been a little bit uncomfortable with the ".. " marker for footnotes because of this; ".. " has a connotation of "special", but footnotes aren't especially "special". Printed texts often put footnotes at the bottom of the page where the reference occurs (thus "foot note"). Some HTML designs would leave footnotes to be rendered the same positions where they're defined. Other online and printed designs will gather footnotes into a section near the end of the document, converting them to "endnotes" (perhaps using a directive in our case); but this "special processing" is not an intrinsic property of the footnote itself, but a decision made by the document author or processing system. Citations are almost invariably collected in a section at the end of a document or section. Citations "disappear" from where they are defined and are magically reinserted at some well-defined point. There's more of a connection to the "special" connotation of the ".. " syntax. The point at which the list of citations is inserted could be defined manually by a directive (e.g., ".. citations::"), and/or have default behavior (e.g., a section automatically inserted at the end of the document) that might be influenced by options to the Writer. Syntax proposals: + Footnotes: - Current syntax:: .. [1] Footnote 1 .. [#] Auto-numbered footnote. .. [#label] Auto-labeled footnote. - The syntax proposed in the original 2002-02-28 Doc-SIG post: remove the ".. ", prefix a "_":: _[1] Footnote 1 _[#] Auto-numbered footnote. _[#label] Auto-labeled footnote. The leading underscore syntax (earlier dropped because ``.. _[1]:`` was too verbose) is a useful reminder that footnotes are hyperlink targets. - Minimal syntax: remove the ".. [" and "]", prefix a "_", and suffix a ".":: _1. Footnote 1. _#. Auto-numbered footnote. _#label. Auto-labeled footnote. ``_1.``, ``_#.``, and ``_#label.`` are markers, like list markers. Footnotes could be rendered something like this in HTML | 1. This is a footnote. The brackets could be dropped | from the label, and a vertical bar could set them | off from the rest of the document in the HTML. Two-way hyperlinks on the footnote marker ("1." above) would also help to differentiate footnotes from enumerated lists. If converted to endnotes (by a directive/transform), a horizontal half-line might be used instead. Page-oriented output formats would typically use the horizontal line for true footnotes. + Footnote references: - Current syntax:: [1]_, [#]_, [#label]_ - Minimal syntax to match the minimal footnote syntax above:: 1_, #_, #label_ As a consequence, pure-numeric hyperlink references would not be possible; they'd be interpreted as footnote references. + Citation references: no change is proposed from the current footnote reference syntax:: [GVR2001]_ + Citations: - Current syntax (footnote syntax):: .. [GVR2001] Python Documentation; van Rossum, Drake, et al.; http://www.python.org/doc/ - Possible new syntax:: _[GVR2001] Python Documentation; van Rossum, Drake, et al.; http://www.python.org/doc/ _[DJG2002] Docutils: Python Documentation Utilities project; Goodger et al.; http://docutils.sourceforge.net/ Without the ".. " marker, subsequent lines would either have to align as in one of the above, or we'd have to allow loose alignment (I'd rather not):: _[GVR2001] Python Documentation; van Rossum, Drake, et al.; http://www.python.org/doc/ I proposed adopting the "minimal" syntax for footnotes and footnote references, and adding citations and citation references to reStructuredText's repertoire. The current footnote syntax for citations is better than the alternatives given. From a reply by Tony Ibbs on 2002-03-01: However, I think easier with examples, so let's create one:: Fans of Terry Pratchett are perhaps more likely to use footnotes [1]_ in their own writings than other people [2]_. Of course, in *general*, one only sees footnotes in academic or technical writing - it's use in fiction and letter writing is not normally considered good style [4]_, particularly in emails (not a medium that lends itself to footnotes). .. [1] That is, little bits of referenced text at the bottom of the page. .. [2] Because Terry himself does, of course [3]_. .. [3] Although he has the distinction of being *funny* when he does it, and his fans don't always achieve that aim. .. [4] Presumably because it detracts from linear reading of the text - this is, of course, the point. and look at it with the second syntax proposal:: Fans of Terry Pratchett are perhaps more likely to use footnotes [1]_ in their own writings than other people [2]_. Of course, in *general*, one only sees footnotes in academic or technical writing - it's use in fiction and letter writing is not normally considered good style [4]_, particularly in emails (not a medium that lends itself to footnotes). _[1] That is, little bits of referenced text at the bottom of the page. _[2] Because Terry himself does, of course [3]_. _[3] Although he has the distinction of being *funny* when he does it, and his fans don't always achieve that aim. _[4] Presumably because it detracts from linear reading of the text - this is, of course, the point. (I note here that if I have gotten the indentation of the footnotes themselves correct, this is clearly not as nice. And if the indentation should be to the left margin instead, I like that even less). and the third (new) proposal:: Fans of Terry Pratchett are perhaps more likely to use footnotes 1_ in their own writings than other people 2_. Of course, in *general*, one only sees footnotes in academic or technical writing - it's use in fiction and letter writing is not normally considered good style 4_, particularly in emails (not a medium that lends itself to footnotes). _1. That is, little bits of referenced text at the bottom of the page. _2. Because Terry himself does, of course 3_. _3. Although he has the distinction of being *funny* when he does it, and his fans don't always achieve that aim. _4. Presumably because it detracts from linear reading of the text - this is, of course, the point. I think I don't, in practice, mind the targets too much (the use of a dot after the number helps a lot here), but I do have a problem with the body text, in that I don't naturally separate out the footnotes as different than the rest of the text - instead I keep wondering why there are numbers interspered in the text. The use of brackets around the numbers ([ and ]) made me somehow parse the footnote references as "odd" - i.e., not part of the body text - and thus both easier to skip, and also (paradoxically) easier to pick out so that I could follow them. Thus, for the moment (and as always susceptable to argument), I'd say -1 on the new form of footnote reference (i.e., I much prefer the existing ``[1]_`` over the proposed ``1_``), and ambivalent over the proposed target change. That leaves David's problem of wanting to distinguish footnotes and citations - and the only thing I can propose there is that footnotes are numeric or # and citations are not (which, as a human being, I can probably cope with!). From a reply by Paul Moore on 2002-03-01: I think the current footnote syntax ``[1]_`` is *exactly* the right balance of distinctness vs unobtrusiveness. I very definitely don't think this should change. On the target change, it doesn't matter much to me. From a further reply by Tony Ibbs on 2002-03-01, referring to the "[1]" form and actual usage in email: Clearly this is a form people are used to, and thus we should consider it strongly (in the same way that the usage of ``*..*`` to mean emphasis was taken partly from email practise). Equally clearly, there is something "magical" for people in the use of a similar form (i.e., ``[1]``) for both footnote reference and footnote target - it seems natural to keep them similar. ... I think that this established plaintext usage leads me to strongly believe we should retain square brackets at both ends of a footnote. The markup of the reference end (a single trailing underscore) seems about as minimal as we can get away with. The markup of the target end depends on how one envisages the thing - if ".." means "I am a target" (as I tend to see it), then that's good, but one can also argue that the "_[1]" syntax has a neat symmetry with the footnote reference itself, if one wishes (in which case ".." presumably means "hidden/special" as David seems to think, which is why one needs a ".." *and* a leading underline for hyperlink targets. Given the persuading arguments voiced, we'll leave footnote & footnote reference syntax alone. Except that these discussions gave rise to the "auto-symbol footnote" concept, which has been added. Citations and citation references have also been added. Syntax for Questions & Answers ============================== Implement as a generic two-column marked list? As a standalone (non-directive) construct? (Is the markup ambiguous?) Add support to parts.contents? New elements would be required. Perhaps:: <!ELEMENT question_list (question_list_item+)> <!ATTLIST question_list numbering (none | local | global) #IMPLIED start NUMBER #IMPLIED> <!ELEMENT question_list_item (question, answer*)> <!ELEMENT question %text.model;> <!ELEMENT answer (%body.elements;)+> Originally I thought of implementing a Q&A list with special syntax:: Q: What am I? A: You are a question-and-answer list. Q: What are you? A: I am the omniscient "we". Where each "Q" and "A" could also be numbered (e.g., "Q1"). However, a simple enumerated or bulleted list will do just fine for syntax. A directive could treat the list specially; e.g. the first paragraph could be treated as a question, the remainder as the answer (multiple answers could be represented by nested lists). Without special syntax, this directive becomes low priority. As described in the FAQ__, no special syntax or directive is needed for this application. __ http://docutils.sf.net/FAQ.html #how-can-i-mark-up-a-faq-or-other-list-of-questions-answers -------- Tabled -------- Reworking Explicit Markup (Round 2) =================================== See `Reworking Explicit Markup (Round 1)`_ for an earlier discussion. In April 2004, a new thread becan on docutils-develop: `Inconsistency in RST markup`__. Several arguments were made; the first argument begat later arguments. Below, the arguments are paraphrased "in quotes", with responses. __ http://thread.gmane.org/gmane.text.docutils.devel/1386 1. References and targets take this form:: targetname_ .. _targetname: stuff But footnotes, "which generate links just like targets do", are written as:: [1]_ .. [1] stuff "Footnotes should be written as":: [1]_ .. _[1]: stuff But they're not the same type of animal. That's not a "footnote target", it's a *footnote*. Being a target is not a footnote's primary purpose (an arguable point). It just happens to grow a target automatically, for convenience. Just as a section title:: Title ===== isn't a "title target", it's a *title*, which happens to grow a target automatically. The consistency is there, it's just deeper than at first glance. Also, ".. [1]" was chosen for footnote syntax because it closely resembles one form of actual footnote rendering. ".. _[1]:" is too verbose; excessive punctuation is required to get the job done. For more of the reasoning behind the syntax, see `Problems With StructuredText (Hyperlinks) <problems.html#hyperlinks>`__ and `Reworking Footnotes`_. 2. "I expect directives to also look like ``.. this:`` [one colon] because that also closely parallels the link and footnote target markup." There are good reasons for the two-colon syntax: Two colons are used after the directive type for these reasons: - Two colons are distinctive, and unlikely to be used in common text. - Two colons avoids clashes with common comment text like:: .. Danger: modify at your own risk! - If an implementation of reStructuredText does not recognize a directive (i.e., the directive-handler is not installed), a level-3 (error) system message is generated, and the entire directive block (including the directive itself) will be included as a literal block. Thus "::" is a natural choice. -- `restructuredtext.html#directives <../../ref/rst/restructuredtext.html#directives>`__ The last reason is not particularly compelling; it's more of a convenient coincidence or mnemonic. 3. "Comments always seemed too easy. I almost never write comments. I'd have no problem writing '.. comment:' in front of my comments. In fact, it would probably be more readable, as comments *should* be set off strongly, because they are very different from normal text." Many people do use comments though, and some applications of reStructuredText require it. For example, all reStructuredText PEPs (and this document!) have an Emacs stanza at the bottom, in a comment. Having to write ".. comment::" would be very obtrusive. Comments *should* be dirt-easy to do. It should be easy to "comment out" a block of text. Comments in programming languages and other markup languages are invariably easy. Any author is welcome to preface their comments with "Comment:" or "Do Not Print" or "Note to Editor" or anything they like. A "comment" directive could easily be implemented. It might be confused with admonition directives, like "note" and "caution" though. In unrelated (and unpublished and unfinished) work, adding a "comment" directive as a true document element was considered:: If structure is necessary, we could use a "comment" directive (to avoid nonsensical DTD changes, the "comment" directive could produce an untitled topic element). 4. "One of the goals of reStructuredText is to be *readable* by people who don't know it. This construction violates that: it is not at all obvious to the uninitiated that text marked by '..' is a comment. On the other hand, '.. comment:' would be totally transparent." Totally transparent, perhaps, but also very obtrusive. Another of `reStructuredText's goals`_ is to be unobtrusive, and ".. comment::" would violate that. The goals of reStructuredText are many, and they conflict. Determining the right set of goals and finding solutions that best fit is done on a case-by-case basis. Even readability is has two aspects. Being readable without any prior knowledge is one. Being as easily read in raw form as in processed form is the other. ".." may not contribute to the former aspect, but ".. comment::" would certainly detract from the latter. .. _author's note: .. _reStructuredText's goals: ../../ref/rst/introduction.html#goals 5. "Recently I sent someone an rst document, and they got confused; I had to explain to them that '..' marks comments, *unless* it's a directive, etc..." The explanation of directives *is* roundabout, defining comments in terms of not being other things. That's definitely a wart. 6. "Under the current system, a mistyped directive (with ':' instead of '::') will be silently ignored. This is an error that could easily go unnoticed." A parser option/setting like "--comments-on-stderr" would help. 7. "I'd prefer to see double-dot-space / command / double-colon as the standard Docutils markup-marker. It's unusual enough to avoid being accidently used. Everything that starts with a double-dot should end with a double-colon." That would increase the punctuation verbosity of some constructs considerably. 8. Edward Loper proposed the following plan for backwards compatibility: 1. ".. foo" will generate a deprecation warning to stderr, and nothing in the output (no system messages). 2. ".. foo: bar" will be treated as a directive foo. If there is no foo directive, then do the normal error output. 3. ".. foo:: bar" will generate a deprecation warning to stderr, and be treated as a directive. Or leave it valid? So some existing documents might start printing deprecation warnings, but the only existing documents that would *break* would be ones that say something like:: .. warning: this should be a comment instead of:: .. warning:: this should be a comment Here, we're trading fairly common a silent error (directive falsely treated as a comment) for a fairly uncommon explicitly flagged error (comment falsely treated as directive). To make things even easier, we could add a sentence to the unknown-directive error. Something like "If you intended to create a comment, please use '.. comment:' instead". On one hand, I understand and sympathize with the points raised. On the other hand, I think the current syntax strikes the right balance (but I acknowledge a possible lack of objectivity). On the gripping hand, the comment and directive syntax has become well established, so even if it's a wart, it may be a wart we have to live with. Making any of these changes would cause a lot of breakage or at least deprecation warnings. I'm not sure the benefit is worth the cost. For now, we'll treat this as an unresolved legacy issue. ------- To Do ------- Nested Inline Markup ==================== These are collected notes on a long-discussed issue. The original mailing list messages should be referred to for details. * In a 2001-10-31 discussion I wrote: Try, for example, `Ed Loper's 2001-03-21 post`_, which details some rules for nested inline markup. I think the complexity is prohibitive for the marginal benefit. (And if you can understand that tree without going mad, you're a better man than I. ;-) Inline markup is already fragile. Allowing nested inline markup would only be asking for trouble IMHO. If it proves absolutely necessary, it can be added later. The rules for what can appear inside what must be well thought out first though. .. _Ed Loper's 2001-03-21 post: http://mail.python.org/pipermail/doc-sig/2001-March/001487.html -- http://mail.python.org/pipermail/doc-sig/2001-October/002354.html * In a 2001-11-09 Doc-SIG post, I wrote: The problem is that in the what-you-see-is-more-or-less-what-you-get markup language that is reStructuredText, the symbols used for inline markup ("*", "**", "`", "``", etc.) may preclude nesting. I've rethought this position. Nested markup is not precluded, just tricky. People and software parse "double and 'single' quotes" all the time. Continuing, I've thought over how we might implement nested inline markup. The first algorithm ("first identify the outer inline markup as we do now, then recursively scan for nested inline markup") won't work; counterexamples were given in my `last post <http://mail.python.org/pipermail/doc-sig/2001-November/002363.html>`__. The second algorithm makes my head hurt:: while 1: scan for start-string if found: push on stack scan for start or end string if new start string found: recurse elif matching end string found: pop stack elif non-matching end string found: if its a markup error: generate warning elif the initial start-string was misinterpreted: # e.g. in this case: ***strong** in emphasis* restart with the other interpretation # but it might be several layers back ... ... This is similar to how the parser does section title recognition, but sections are much more regular and deterministic. Bottom line is, I don't think the benefits are worth the effort, even if it is possible. I'm not going to try to write the code, at least not now. If somebody codes up a consistent, working, general solution, I'll be happy to consider it. -- http://mail.python.org/pipermail/doc-sig/2001-November/002388.html * In a `2003-05-06 Docutils-Users post`__ Paul Tremblay proposed a new syntax to allow for easier nesting. It eventually evolved into this:: :role:[inline text] The duplication with the existing interpreted text syntax is problematic though. __ http://article.gmane.org/gmane.text.docutils.user/317 * Could the parser be extended to parse nested interpreted text? :: :emphasis:`Some emphasized text with :strong:`some more emphasized text` in it and **perhaps** :reference:`a link`` * In a `2003-06-18 Docutils-Develop post`__, Mark Nodine reported on his implementation of a form of nested inline markup in his Perl-based parser (unpublished). He brought up some interesting ideas. The implementation was flawed, however, by the change in semantics required for backslash escapes. __ http://article.gmane.org/gmane.text.docutils.devel/795 * Docutils-develop threads between David Abrahams, David Goodger, and Mark Nodine (beginning 2004-01-16__ and 2004-01-19__) hashed out many of the details of a potentially successful implementation, as described below. David Abrahams checked in code to the "nesting" branch of CVS, awaiting thorough review. __ http://thread.gmane.org/gmane.text.docutils.devel/1102 __ http://thread.gmane.org/gmane.text.docutils.devel/1125 It may be possible to accomplish nested inline markup in general with a more powerful inline markup parser. There may be some issues, but I'm not averse to the idea of nested inline markup in general. I just don't have the time or inclination to write a new parser now. Of course, a good patch would be welcome! I envisage something like this. Explicit-role interpreted text must be nestable. Prefix-based is probably preferred, since suffix-based will look like inline literals:: ``text`:role1:`:role2: But it can be disambiguated, so it ought to be left up to the author:: `\ `text`:role1:`:role2: In addition, other forms of inline markup may be nested if unambiguous:: *emphasized ``literal`` and |substitution ref| and link_* IOW, the parser ought to be as permissive as possible. Index Entries & Indexes ======================= Were I writing a book with an index, I guess I'd need two different kinds of index targets: inline/implicit and out-of-line/explicit. For example:: In this `paragraph`:index:, several words are being `marked`:index: inline as implicit `index`:index: entries. .. index:: markup .. index:: syntax The explicit index directives above would refer to this paragraph. It might also make sense to allow multiple entries in an ``index`` directive: .. index:: markup syntax The words "paragraph", "marked", and "index" would become index entries pointing at the words in the first paragraph. The index entry words appear verbatim in the text. (Don't worry about the ugly ":index:" part; if indexing is the only/main application of interpreted text in your documents, it can be implicit and omitted.) The two directives provide manual indexing, where the index entry words ("markup" and "syntax") do not appear in the main text. We could combine the two directives into one:: .. index:: markup; syntax Semicolons instead of commas because commas could *be* part of the index target, like:: .. index:: van Rossum, Guido Another reason for index directives is because other inline markup wouldn't be possible within inline index targets. Sometimes index entries have multiple levels. Given:: .. index:: statement syntax: expression statements In a hypothetical index, combined with other entries, it might look like this:: statement syntax expression statements ..... 56 assignment ................ 57 simple statements ......... 58 compound statements ....... 60 Inline multi-level index targets could be done too. Perhaps something like:: When dealing with `expression statements <statement syntax:>`, we must remember ... The opposite sense could also be possible:: When dealing with `index entries <:multi-level>`, there are many permutations to consider. Also "see / see also" index entries. Given:: Here's a paragraph. .. index:: paragraph (The "index" directive above actually targets the *preceding* object.) The directive should produce something like this XML:: <paragraph> <index_entry text="paragraph"/> Here's a paragraph. </paragraph> This kind of content model would also allow true inline index-entries:: Here's a `paragraph`:index:. If the "index" role were the default for the application, it could be dropped:: Here's a `paragraph`. Both of these would result in this XML:: <paragraph> Here's a <index_entry>paragraph</index_entry>. </paragraph> from 2002-06-24 docutils-develop posts -------------------------------------- If all of your index entries will appear verbatim in the text, this should be sufficient. If not (e.g., if you want "Van Rossum, Guido" in the index but "Guido van Rossum" in the text), we'll have to figure out a supplemental mechanism, perhaps using substitutions. I've thought a bit more on this, and I came up with two possibilities: 1. Using interpreted text, embed the index entry text within the interpreted text:: ... by `Guido van Rossum [Van Rossum, Guido]` ... The problem with this is obvious: the text becomes cluttered and hard to read. The processed output would drop the text in brackets, which goes against the spirit of interpreted text. 2. Use substitutions:: ... by |Guido van Rossum| ... .. |Guido van Rossum| index:: Van Rossum, Guido A problem with this is that each substitution definition must have a unique name. A subsequent ``.. |Guido van Rossum| index:: BDFL`` would be illegal. Some kind of anonymous substitution definition mechanism would be required, but I think that's going too far. Both of these alternatives are flawed. Any other ideas? ------------------- ... Or Not To Do? ------------------- This is the realm of the possible but questionably probable. These ideas are kept here as a record of what has been proposed, for posterity and in case any of them prove to be useful. Compound Enumerated Lists ========================= Allow for compound enumerators, such as "1.1." or "1.a." or "1(a)", to allow for nested enumerated lists without indentation? Indented Lists ============== Allow for variant styles by interpreting indented lists as if they weren't indented? For example, currently the list below will be parsed as a list within a block quote:: paragraph * list item 1 * list item 2 But a lot of people seem to write that way, and HTML browsers make it look as if that's the way it should be. The parser could check the contents of block quotes, and if they contain only a single list, remove the block quote wrapper. There would be two problems: 1. What if we actually *do* want a list inside a block quote? 2. What if such a list comes immediately after an indented construct, such as a literal block? Both could be solved using empty comments (problem 2 already exists for a block quote after a literal block). But that's a hack. Perhaps a runtime setting, allowing or disabling this convenience, would be appropriate. But that raises issues too: User A, who writes lists indented (and their config file is set up to allow it), sends a file to user B, who doesn't (and their config file disables indented lists). The result of processing by the two users will be different. It may seem minor, but it adds ambiguity to the parser, which is bad. See the `Doc-SIG discussion starting 2001-04-18`__ with Ed Loper's "Structuring: a summary; and an attempt at EBNF", item 4 (and follow-ups, here__ and here__). Also `docutils-users, 2003-02-17`__ and `beginning 2003-08-04`__. __ http://mail.python.org/pipermail/doc-sig/2001-April/001776.html __ http://mail.python.org/pipermail/doc-sig/2001-April/001789.html __ http://mail.python.org/pipermail/doc-sig/2001-April/001793.html __ http://sourceforge.net/mailarchive/message.php?msg_id=3838913 __ http://sf.net/mailarchive/forum.php?thread_id=2957175&forum_id=11444 Sloppy Indentation of List Items ================================ Perhaps the indentation shouldn't be so strict. Currently, this is required:: 1. First line, second line. Anything wrong with this? :: 1. First line, second line. Problem? :: 1. First para. Block quote. (no good: requires some indent relative to first para) Second Para. 2. Have to carefully define where the literal block ends:: Literal block Literal block? Hmm... Non-strict indentation isn't such a good idea. Lazy Indentation of List Items ============================== Another approach: Going back to the first draft of reStructuredText (2000-11-27 post to Doc-SIG):: - This is the fourth item of the main list (no blank line above). The second line of this item is not indented relative to the bullet, which precludes it from having a second paragraph. Change that to *require* a blank line above and below, to reduce ambiguity. This "loosening" may be added later, once the parser's been nailed down. However, a serious drawback of this approach is to limit the content of each list item to a single paragraph. David's Idea for Lazy Indentation --------------------------------- Consider a paragraph in a word processor. It is a single logical line of text which ends with a newline, soft-wrapped arbitrarily at the right edge of the page or screen. We can think of a plaintext paragraph in the same way, as a single logical line of text, ending with two newlines (a blank line) instead of one, and which may contain arbitrary line breaks (newlines) where it was accidentally hard-wrapped by an application. We can compensate for the accidental hard-wrapping by "unwrapping" every unindented second and subsequent line. The indentation of the first line of a paragraph or list item would determine the indentation for the entire element. Blank lines would be required between list items when using lazy indentation. The following example shows the lazy indentation of multiple body elements:: - This is the first paragraph of the first list item. Here is the second paragraph of the first list item. - This is the first paragraph of the second list item. Here is the second paragraph of the second list item. A more complex example shows the limitations of lazy indentation:: - This is the first paragraph of the first list item. Next is a definition list item: Term Definition. The indentation of the term is required, as is the indentation of the definition's first line. When the definition extends to more than one line, lazy indentation may occur. (This is the second paragraph of the definition.) - This is the first paragraph of the second list item. - Here is the first paragraph of the first item of a nested list. So this paragraph would be outside of the nested list, but inside the second list item of the outer list. But this paragraph is not part of the list at all. And the ambiguity remains:: - Look at the hyphen at the beginning of the next line - is it a second list item marker, or a dash in the text? Similarly, we may want to refer to numbers inside enumerated lists: 1. How many socks in a pair? There are 2. How many pants in a pair? Exactly 1. Go figure. Literal blocks and block quotes would still require consistent indentation for all their lines. For block quotes, we might be able to get away with only requiring that the first line of each contained element be indented. For example:: Here's a paragraph. This is a paragraph inside a block quote. Second and subsequent lines need not be indented at all. - A bullet list inside the block quote. Second paragraph of the bullet list inside the block quote. Although feasible, this form of lazy indentation has problems. The document structure and hierarchy is not obvious from the indentation, making the source plaintext difficult to read. This will also make keeping track of the indentation while writing difficult and error-prone. However, these problems may be acceptable for Wikis and email mode, where we may be able to rely on less complex structure (few nested lists, for example). Multiple Roles in Interpreted Text ================================== In reStructuredText, inline markup cannot be nested (yet; `see above`__). This also applies to interpreted text. In order to simultaneously combine multiple roles for a single piece of text, a syntax extension would be necessary. Ideas: 1. Initial idea:: `interpreted text`:role1,role2: 2. Suggested by Jason Diamond:: `interpreted text`:role1:role2: If a document is so complex as to require nested inline markup, perhaps another markup system should be considered. By design, reStructuredText does not have the flexibility of XML. __ `Nested Inline Markup`_ Parameterized Interpreted Text ============================== In some cases it may be expedient to pass parameters to interpreted text, analogous to function calls. Ideas: 1. Parameterize the interpreted text role itself (suggested by Jason Diamond):: `interpreted text`:role1(foo=bar): Positional parameters could also be supported:: `CSS`:acronym(Cascading Style Sheets): is used for HTML, and `CSS`:acronym(Content Scrambling System): is used for DVDs. Technical problem: current interpreted text syntax does not recognize roles containing whitespace. Design problem: this smells like programming language syntax, but reStructuredText is not a programming language. 2. Put the parameters inside the interpreted text:: `CSS (Cascading Style Sheets)`:acronym: is used for HTML, and `CSS (Content Scrambling System)`:acronym: is used for DVDs. Although this could be defined on an individual basis (per role), we ought to have a standard. Hyperlinks with embedded URIs already use angle brackets; perhaps they could be used here too:: `CSS <Cascading Style Sheets>`:acronym: is used for HTML, and `CSS <Content Scrambling System>`:acronym: is used for DVDs. Do angle brackets connote URLs too much for this to be acceptable? How about the "tag" connotation -- does it save them or doom them? 3. `Nested inline markup`_ could prove useful here:: `CSS :def:`Cascading Style Sheets``:acronym: is used for HTML, and `CSS :def:`Content Scrambling System``:acronym: is used for DVDs. Inline markup roles could even define the default roles of nested inline markup, allowing this cleaner syntax:: `CSS `Cascading Style Sheets``:acronym: is used for HTML, and `CSS `Content Scrambling System``:acronym: is used for DVDs. Does this push inline markup too far? Readability becomes a serious issue. Substitutions may provide a better alternative (at the expense of verbosity and duplication) by pulling the details out of the text flow:: |CSS| is used for HTML, and |CSS-DVD| is used for DVDs. .. |CSS| acronym:: Cascading Style Sheets .. |CSS-DVD| acronym:: Content Scrambling System :text: CSS ---------------------------------------------------------------------- This whole idea may be going beyond the scope of reStructuredText. Documents requiring this functionality may be better off using XML or another markup system. This argument comes up regularly when pushing the envelope of reStructuredText syntax. I think it's a useful argument in that it provides a check on creeping featurism. In many cases, the resulting verbosity produces such unreadable plaintext that there's a natural desire *not* to use it unless absolutely necessary. It's a matter of finding the right balance. Syntax for Interpreted Text Role Bindings ========================================= The following syntax (idea from Jeffrey C. Jacobs) could be used to associate directives with roles:: .. :rewrite: class:: rewrite `She wore ribbons in her hair and it lay with streaks of grey`:rewrite: The syntax is similar to that of substitution declarations, and the directive/role association may resolve implementation issues. The semantics, ramifications, and implementation details would need to be worked out. The example above would implement the "rewrite" role as adding a ``class="rewrite"`` attribute to the interpreted text ("inline" element). The stylesheet would then pick up on the "class" attribute to do the actual formatting. The advantage of the new syntax would be flexibility. Uses other than "class" may present themselves. The disadvantage is complexity: having to implement new syntax for a relatively specialized operation, and having new semantics in existing directives ("class::" would do something different). The `"role" directive`__ has been implemented. __ ../../ref/rst/directives.html#role Character Processing ==================== Several people have suggested adding some form of character processing to reStructuredText: * Some sort of automated replacement of ASCII sequences: - ``--`` to em-dash (or ``--`` to en-dash, and ``---`` to em-dash). - Convert quotes to curly quote entities. (Essentially impossible for HTML? Unnecessary for TeX.) - Various forms of ``:-)`` to smiley icons. - ``"\ "`` to  . Problem with line-wrapping though: it could end up escaping the newline. - Escaped newlines to <BR>. - Escaped period or quote or dash as a disappearing catalyst to allow character-level inline markup? * XML-style character entities, such as "©" for the copyright symbol. Docutils has no need of a character entity subsystem. Supporting Unicode and text encodings, character entities should be directly represented in the text: a copyright symbol should be represented by the copyright symbol character. If this is not possible in an authoring environment, a pre-processing stage can be added, or a table of substitution definitions can be devised. A "unicode" directive has been implemented to allow direct specification of esoteric characters. In combination with the substitution construct, "include" files defining common sets of character entities can be defined and used. `A set of character entity set definition files have been defined`__ (`tarball`__). There's also `a description and instructions for use`__. __ http://docutils.sf.net/tmp/charents/ __ http://docutils.sf.net/tmp/charents.tgz __ http://docutils.sf.net/tmp/charents/README.html To allow for `character-level inline markup`_, a limited form of character processing has been added to the spec and parser: escaped whitespace characters are removed from the processed document. Any further character processing will be of this functional type, rather than of the character-encoding type. .. _character-level inline markup: ../../ref/rst/restructuredtext.html#character-level-inline-markup * Directive idea:: .. text-replace:: "pattern" "replacement" - Support Unicode "U+XXXX" codes. - Support regexps, perhaps with alternative "regexp-replace" directive. - Flags for regexps; ":flags:" option, or individuals. - Specifically, should the default be case-sensistive or -insensitive? Page Or Line Breaks =================== * Should ^L (or something else in reST) be defined to mean force/suggest page breaks in whatever output we have? A "break" or "page-break" directive would be easy to add. A new doctree element would be required though (perhaps "break"). The final behavior would be up to the Writer. The directive argument could be one of page/column/recto/verso for added flexibility. Currently ^L (Python's ``\f``) characters are treated as whitespace. They're converted to single spaces, actually, as are vertical tabs (^K, Python's ``\v``). It would be possible to recognize form feeds as markup, but it requires some thought and discussion first. Are there any downsides? Many editing environments do not allow the insertion of control characters. Will it cause any harm? It would be useful as a shorthand for the directive. It's common practice to use ^L before Emacs "Local Variables" lists:: ^L .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: These are already present in many PEPs and Docutils project documents. From the Emacs manual (info): A "local variables list" goes near the end of the file, in the last page. (It is often best to put it on a page by itself.) It would be unfortunate if this construct caused a final blank page to be generated (for those Writers that recognize the page breaks). We'll have to add a transform that looks for a "break" plus zero or more comments at the end of a document, and removes them. Probably a bad idea because there is no such thing as a page in a generic document format. * Could the "break" concept above be extended to inline forms? E.g. "^L" in the middle of a sentence could cause a line break. Only recognize it at the end of a line (i.e., ``\f\n``)? Or is formfeed inappropriate? Perhaps vertical tab (``\v``), but even that's a stretch. Can't use carriage returns, since they're commonly used for line endings. Probably a bad idea as well because we do not want to use control characters for well-readable and well-writable markup, and after all we have the line block syntax for line breaks. Superscript Markup ================== Add ``^superscript^`` inline markup? The only common non-markup uses of "^" I can think of are as short hand for "superscript" itself and for describing control characters ("^C to cancel"). The former supports the proposed syntax, and it could be argued that the latter ought to be literal text anyhow (e.g. "``^C`` to cancel"). However, superscripts are seldom needed, and new syntax would break existing documents. When it's needed, the ``:superscript:`` (``:sup:``) role can we used as well. Code Execution ============== Add the following directives? - "exec": Execute Python code & insert the results. Call it "python" to allow for other languages? - "system": Execute an ``os.system()`` call, and insert the results (possibly as a literal block). Definitely dangerous! How to make it safe? Perhaps such processing should be left outside of the document, in the user's production system (a makefile or a script or whatever). Or, the directive could be disabled by default and only enabled with an explicit command-line option or config file setting. Even then, an interactive prompt may be useful, such as: The file.txt document you are processing contains a "system" directive requesting that the ``sudo rm -rf /`` command be executed. Allow it to execute? (y/N) - "eval": Evaluate an expression & insert the text. At parse time or at substitution time? Dangerous? Perhaps limit to canned macros; see text.date_. .. _text.date: ../todo.html#text-date It's too dangerous (or too complicated in the case of "eval"). We do not want to have such things in the core. ``encoding`` Directive ====================== Add an "encoding" directive to specify the character encoding of the input data? Not a good idea for the following reasons: - When it sees the directive, the parser will already have read the input data, and encoding determination will already have been done. - If a file with an "encoding" directive is edited and saved with a different encoding, the directive may cause data corruption. Support for Annotations ======================= Add an "annotation" role, as the equivalent of the HTML "title" attribute? This is secondary information that may "pop up" when the pointer hovers over the main text. A corresponding directive would be required to associate annotations with the original text (by name, or positionally as in anonymous targets?). There have not been many requests for such feature, though. Also, cluttering WYSIWYG plaintext with annotations may not seem like a good idea, and there is no "tool tip" in formats other than HTML. ``term`` Role ============= Add a "term" role for unfamiliar or specialized terminology? Probably not; there is no real use case, and emphasis is enough for most cases. Object references ================= We need syntax for `object references`_. - Parameterized substitutions? For example:: See |figure (figure name)| on |page (figure name)|. .. |figure (name)| figure-ref:: (name) .. |page (name)| page-ref:: (name) The result would be:: See figure 3.11 on page 157. But this would require substitution directives to be processed at reference-time, not at definition-time as they are now. Or, perhaps the directives could just leave ``pending`` elements behind, and the transforms do the work? How to pass the data through? Too complicated. Use interpreted text roles. .. _object references: ../todo.html#object-numbering-and-object-references .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/docs/dev/enthought-plan.txt�����������������������������������������������������������0000664�0001750�0001750�00000041156�11700652711�022437� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������=========================================== Plan for Enthought API Documentation Tool =========================================== :Author: David Goodger :Contact: docutils-develop@lists.sourceforge.net :Date: $Date: 2012-01-03 20:23:53 +0100 (Die, 03. Jän 2012) $ :Revision: $Revision: 7302 $ :Copyright: 2004 by `Enthought, Inc. <http://www.enthought.com>`_ :License: `Enthought License`_ (BSD-style) .. _Enthought License: http://docutils.sf.net/licenses/enthought.txt This document should be read in conjunction with the `Enthought API Documentation Tool RFP`__ prepared by Janet Swisher. __ enthought-rfp.html .. contents:: .. sectnum:: Introduction ============ In March 2004 at I met Eric Jones, president and CTO of `Enthought, Inc.`_, at `PyCon 2004`_ in Washington DC. He told me that Enthought was using reStructuredText_ for source code documentation, but they had some issues. He asked if I'd be interested in doing some work on a customized API documentation tool. Shortly after PyCon, Janet Swisher, Enthought's senior technical writer, contacted me to work out details. Some email, a trip to Austin in May, and plenty of Texas hospitality later, we had a project. This document will record the details, milestones, and evolution of the project. In a nutshell, Enthought is sponsoring the implementation of an open source API documentation tool that meets their needs. Fortuitously, their needs coincide well with the "Python Source Reader" description in `PEP 258`_. In other words, Enthought is funding some significant improvements to Docutils, improvements that were planned but never implemented due to time and other constraints. The implementation will take place gradually over several months, on a part-time basis. This is an ideal example of cooperation between a corporation and an open-source project. The corporation, the project, I personally, and the community all benefit. Enthought, whose commitment to open source is also evidenced by their sponsorship of SciPy_, benefits by obtaining a useful piece of software, much more quickly than would have been possible without their support. Docutils benefits directly from the implementation of one of its core subsystems. I benefit from the funding, which allows me to justify the long hours to my wife and family. All the corporations, projects, and individuals that make up the community will benefit from the end result, which will be great. All that's left now is to actually do the work! .. _PyCon 2004: http://pycon.org/dc2004/ .. _reStructuredText: http://docutils.sf.net/rst.html .. _SciPy: http://www.scipy.org/ Development Plan ================ 1. Analyze prior art, most notably Epydoc_ and HappyDoc_, to see how they do what they do. I have no desire to reinvent wheels unnecessarily. I want to take the best ideas from each tool, combined with the outline in `PEP 258`_ (which will evolve), and build at least the foundation of the definitive Python auto-documentation tool. .. _Epydoc: http://epydoc.sourceforge.net/ .. _HappyDoc: http://happydoc.sourceforge.net/ .. _PEP 258: http://docutils.sf.net/docs/peps/pep-0258.html#python-source-reader 2. Decide on a base platform. The best way to achieve Enthought's goals in a reasonable time frame may be to extend Epydoc or HappyDoc. Or it may be necessary to start fresh. 3. Extend the reStructuredText parser. See `Proposed Changes to reStructuredText`_ below. 4. Depending on the base platform chosen, build or extend the docstring & doc comment extraction tool. This may be the biggest part of the project, but I won't be able to break it down into details until more is known. Repository ========== If possible, all software and documentation files will be stored in the Subversion repository of Docutils and/or the base project, which are all publicly-available via anonymous pserver access. The Docutils project is very open about granting Subversion write access; so far, everyone who asked has been given access. Any Enthought staff member who would like Subversion write access will get it. If either Epydoc or HappyDoc is chosen as the base platform, I will ask the project's administrator for CVS access for myself and any Enthought staff member who wants it. If sufficient access is not granted -- although I doubt that there would be any problem -- we may have to begin a fork, which could be hosted on SourceForge, on Enthought's Subversion server, or anywhere else deemed appropriate. Copyright & License =================== Most existing Docutils files have been placed in the public domain, as follows:: :Copyright: This document has been placed in the public domain. This is in conjunction with the "Public Domain Dedication" section of COPYING.txt__. __ http://docutils.sourceforge.net/COPYING.html The code and documentation originating from Enthought funding will have Enthought's copyright and license declaration. While I will try to keep Enthought-specific code and documentation separate from the existing files, there will inevitably be cases where it makes the most sense to extend existing files. I propose the following: 1. New files related to this Enthought-funded work will be identified with the following field-list headers:: :Copyright: 2004 by Enthought, Inc. :License: Enthought License (BSD Style) The license field text will be linked to the license file itself. 2. For significant or major changes to an existing file (more than 10% change), the headers shall change as follows (for example):: :Copyright: 2001-2004 by David Goodger :Copyright: 2004 by Enthought, Inc. :License: BSD-style If the Enthought-funded portion becomes greater than the previously existing portion, Enthought's copyright line will be shown first. 3. In cases of insignificant or minor changes to an existing file (less than 10% change), the public domain status shall remain unchanged. A section describing all of this will be added to the Docutils `COPYING`__ instructions file. If another project is chosen as the base project, similar changes would be made to their files, subject to negotiation. __ http://docutils.sf.net/COPYING.html Proposed Changes to reStructuredText ==================================== Doc Comment Syntax ------------------ The "traits" construct is implemented as dictionaries, where standalone strings would be Python syntax errors. Therefore traits require documentation in comments. We also need a way to differentiate between ordinary "internal" comments and documentation comments (doc comments). Javadoc uses the following syntax for doc comments:: /** * The first line of a multi-line doc comment begins with a slash * and *two* asterisks. The doc comment ends normally. */ Python doesn't have multi-line comments; only single-line. A similar convention in Python might look like this:: ## # The first line of a doc comment begins with *two* hash marks. # The doc comment ends with the first non-comment line. 'data' : AnyValue, ## The double-hash-marks could occur on the first line of text, # saving a line in the source. 'data' : AnyValue, How to indicate the end of the doc comment? :: ## # The first line of a doc comment begins with *two* hash marks. # The doc comment ends with the first non-comment line, or another # double-hash-mark. ## # This is an ordinary, internal, non-doc comment. 'data' : AnyValue, ## First line of a doc comment, terse syntax. # Second (and last) line. Ends here: ## # This is an ordinary, internal, non-doc comment. 'data' : AnyValue, Or do we even need to worry about this case? A simple blank line could be used:: ## First line of a doc comment, terse syntax. # Second (and last) line. Ends with a blank line. # This is an ordinary, internal, non-doc comment. 'data' : AnyValue, Other possibilities:: #" Instead of double-hash-marks, we could use a hash mark and a # quotation mark to begin the doc comment. 'data' : AnyValue, ## We could require double-hash-marks on every line. This has the ## added benefit of delimiting the *end* of the doc comment, as ## well as working well with line wrapping in Emacs ## ("fill-paragraph" command). # Ordinary non-doc comment. 'data' : AnyValue, #" A hash mark and a quotation mark on each line looks funny, and #" it doesn't work well with line wrapping in Emacs. 'data' : AnyValue, These styles (repeated on each line) work well with line wrapping in Emacs:: ## #> #| #- #% #! #* These styles do *not* work well with line wrapping in Emacs:: #" #' #: #) #. #/ #@ #$ #^ #= #+ #_ #~ The style of doc comment indicator used could be a runtime, global and/or per-module setting. That may add more complexity than it's worth though. Recommendation `````````````` I recommend adopting "#*" on every line:: # This is an ordinary non-doc comment. #* This is a documentation comment, with an asterisk after the #* hash marks on every line. 'data' : AnyValue, I initially recommended adopting double-hash-marks:: # This is an ordinary non-doc comment. ## This is a documentation comment, with double-hash-marks on ## every line. 'data' : AnyValue, But Janet Swisher rightly pointed out that this could collide with ordinary comments that are then block-commented. This applies to double-hash-marks on the first line only as well. So they're out. On the other hand, the JavaDoc-comment style ("##" on the first line only, "#" after that) is used in Fredrik Lundh's PythonDoc_. It may be worthwhile to conform to this syntax, reinforcing it as a standard. PythonDoc does not support terse doc comments (text after "##" on the first line). .. _PythonDoc: http://effbot.org/zone/pythondoc.htm Update `````` Enthought's Traits system has switched to a metaclass base, and traits are now defined via ordinary attributes. Therefore doc comments are no longer absolutely necessary; attribute docstrings will suffice. Doc comments may still be desirable though, since they allow documentation to precede the thing being documented. Docstring Density & Whitespace Minimization ------------------------------------------- One problem with extensively documented classes & functions, is that there is a lot of screen space wasted on whitespace. Here's some current Enthought code (from lib/cp/fluids/gassmann.py):: def max_gas(temperature, pressure, api, specific_gravity=.56): """ Computes the maximum dissolved gas in oil using Batzle and Wang (1992). Parameters ---------- temperature : sequence Temperature in degrees Celsius pressure : sequence Pressure in MPa api : sequence Stock tank oil API specific_gravity : sequence Specific gravity of gas at STP, default is .56 Returns ------- max_gor : sequence Maximum dissolved gas in liters/liter Description ----------- This estimate is based on equations given by Mavko, Mukerji, and Dvorkin, (1998, pp. 218-219, or 2003, p. 236) obtained originally from Batzle and Wang (1992). """ code... The docstring is 24 lines long. Rather than using subsections, field lists (which exist now) can save 6 lines:: def max_gas(temperature, pressure, api, specific_gravity=.56): """ Computes the maximum dissolved gas in oil using Batzle and Wang (1992). :Parameters: temperature : sequence Temperature in degrees Celsius pressure : sequence Pressure in MPa api : sequence Stock tank oil API specific_gravity : sequence Specific gravity of gas at STP, default is .56 :Returns: max_gor : sequence Maximum dissolved gas in liters/liter :Description: This estimate is based on equations given by Mavko, Mukerji, and Dvorkin, (1998, pp. 218-219, or 2003, p. 236) obtained originally from Batzle and Wang (1992). """ code... As with the "Description" field above, field bodies may begin on the same line as the field name, which also saves space. The output for field lists is typically a table structure. For example: :Parameters: temperature : sequence Temperature in degrees Celsius pressure : sequence Pressure in MPa api : sequence Stock tank oil API specific_gravity : sequence Specific gravity of gas at STP, default is .56 :Returns: max_gor : sequence Maximum dissolved gas in liters/liter :Description: This estimate is based on equations given by Mavko, Mukerji, and Dvorkin, (1998, pp. 218-219, or 2003, p. 236) obtained originally from Batzle and Wang (1992). But the definition lists describing the parameters and return values are still wasteful of space. There are a lot of half-filled lines. Definition lists are currently defined as:: term : classifier definition Where the classifier part is optional. Ideas for improvements: 1. We could allow multiple classifiers:: term : classifier one : two : three ... definition 2. We could allow the definition on the same line as the term, using some embedded/inline markup: * "--" could be used, but only in limited and well-known contexts:: term -- definition This is the syntax used by StructuredText (one of reStructuredText's predecessors). It was not adopted for reStructuredText because it is ambiguous -- people often use "--" in their text, as I just did. But given a constrained context, the ambiguity would be acceptable (or would it?). That context would be: in docstrings, within a field list, perhaps only with certain well-defined field names (parameters, returns). * The "constrained context" above isn't really enough to make the ambiguity acceptable. Instead, a slightly more verbose but far less ambiguous syntax is possible:: term === definition This syntax has advantages. Equals signs lend themselves to the connotation of "definition". And whereas one or two equals signs are commonly used in program code, three equals signs in a row have no conflicting meanings that I know of. (Update: there *are* uses out there.) The problem with this approach is that using inline markup for structure is inherently ambiguous in reStructuredText. For example, writing *about* definition lists would be difficult:: ``term === definition`` is an example of a compact definition list item The parser checks for structural markup before it does inline markup processing. But the "===" should be protected by its inline literal context. 3. We could allow the definition on the same line as the term, using structural markup. A variation on bullet lists would work well:: : term :: definition : another term :: and a definition that wraps across lines Some ambiguity remains:: : term ``containing :: double colons`` :: definition But the likelihood of such cases is negligible, and they can be covered in the documentation. Other possibilities for the definition delimiter include:: : term : classifier -- definition : term : classifier --- definition : term : classifier : : definition : term : classifier === definition The third idea currently has the best chance of being adopted and implemented. Recommendation `````````````` Combining these ideas, the function definition becomes:: def max_gas(temperature, pressure, api, specific_gravity=.56): """ Computes the maximum dissolved gas in oil using Batzle and Wang (1992). :Parameters: : temperature : sequence :: Temperature in degrees Celsius : pressure : sequence :: Pressure in MPa : api : sequence :: Stock tank oil API : specific_gravity : sequence :: Specific gravity of gas at STP, default is .56 :Returns: : max_gor : sequence :: Maximum dissolved gas in liters/liter :Description: This estimate is based on equations given by Mavko, Mukerji, and Dvorkin, (1998, pp. 218-219, or 2003, p. 236) obtained originally from Batzle and Wang (1992). """ code... The docstring is reduced to 14 lines, from the original 24. For longer docstrings with many parameters and return values, the difference would be more significant. ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/docs/dev/pysource.dtd�����������������������������������������������������������������0000664�0001750�0001750�00000016332�11700652711�021305� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!-- ====================================================================== Docutils Python Source DTD ====================================================================== :Author: David Goodger :Contact: docutils-develop@lists.sourceforge.net :Revision: $Revision: 7302 $ :Date: $Date: 2012-01-03 20:23:53 +0100 (Die, 03. Jän 2012) $ :Copyright: This DTD has been placed in the public domain. :Filename: pysource.dtd This DTD (document type definition) extends the Generic DTD (see below). More information about this DTD and the Docutils project can be found at http://docutils.sourceforge.net/. The latest version of this DTD is available from http://docutils.sourceforge.net/docs/dev/pysource.dtd. The formal public identifier for this DTD is:: +//IDN docutils.sourceforge.net//DTD Docutils Python Source//EN//XML --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter Entity Overrides ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!ENTITY % additional.section.elements " | package_section | module_section | class_section | method_section | function_section | module_attribute_section | function_attribute_section | class_attribute_section | instance_attribute_section "> <!ENTITY % additional.inline.elements " | package | module | class | method | function | variable | parameter | type | attribute | module_attribute | class_attribute | instance_attribute | exception_class | warning_class "> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Generic DTD ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This DTD extends the Docutils Generic DTD, available from http://docutils.sourceforge.net/docs/ref/docutils.dtd. --> <!ENTITY % docutils PUBLIC "+//IDN python.org//DTD Docutils Generic//EN//XML" "docutils.dtd"> %docutils; <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Additional Section Elements ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- package's namespace == __init__.py module's namespace --> <!ELEMENT package_section (package, fullname?, import_list?, %structure.model;)> <!ATTLIST package_section %basic.atts;> <!ELEMENT module_section (module, fullname?, import_list?, %structure.model;)> <!ATTLIST module_section %basic.atts;> <!ELEMENT class_section (class, inheritance_list?, fullname?, subclasses?, %structure.model;)> <!ATTLIST class_section %basic.atts;> <!ELEMENT method_section (method, parameter_list?, fullname?, overrides?, %structure.model;)> <!ATTLIST method_section %basic.atts;> <!ELEMENT function_section (function, parameter_list?, fullname?, %structure.model;)> <!ATTLIST function_section %basic.atts;> <!ELEMENT module_attribute_section (attribute, initial_value?, fullname?, %structure.model;)> <!ATTLIST module_attribute_section %basic.atts;> <!ELEMENT function_attribute_section (attribute, initial_value?, fullname?, %structure.model;)> <!ATTLIST function_attribute_section %basic.atts;> <!ELEMENT class_attribute_section (attribute, initial_value?, fullname?, overrides?, %structure.model;)> <!ATTLIST class_attribute_section %basic.atts;> <!ELEMENT instance_attribute_section (attribute, initial_value?, fullname?, overrides?, %structure.model;)> <!ATTLIST instance_attribute_section %basic.atts;> <!-- Section Subelements ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!ELEMENT fullname (package | module | class | method | function | attribute)+> <!ATTLIST fullname %basic.atts;> <!ELEMENT import_list (import_item+)> <!ATTLIST import_list %basic.atts;> <!-- Support ``import module``, ``import module as alias``, ``from module import identifier``, and ``from module import identifier as alias``. --> <!ELEMENT import_item (fullname, identifier?, alias?)> <!ATTLIST import_item %basic.atts;> <!ELEMENT inheritance_list (class+)> <!ATTLIST inheritance_list %basic.atts;> <!ELEMENT subclasses (class+)> <!ATTLIST subclasses %basic.atts;> <!ELEMENT parameter_list ((parameter_item+, optional_parameters*) | optional_parameters+)> <!ATTLIST parameter_list %basic.atts;> <!ELEMENT parameter_item ((parameter | parameter_tuple), parameter_default?)> <!ATTLIST parameter_item %basic.atts;> <!ELEMENT optional_parameters (parameter_item+, optional_parameters*)> <!ATTLIST optional_parameters %basic.atts;> <!ELEMENT parameter_tuple (parameter | parameter_tuple)+> <!ATTLIST parameter_tuple %basic.atts;> <!ELEMENT parameter_default (#PCDATA)> <!ATTLIST parameter_default %basic.atts;> <!ELEMENT overrides (fullname+)> <!ATTLIST overrides %basic.atts;> <!ELEMENT initial_value (#PCDATA)> <!ATTLIST initial_value %basic.atts;> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Additional Inline Elements ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- Also used as the `package_section` identifier/title. --> <!ELEMENT package (#PCDATA)> <!ATTLIST package %basic.atts; %reference.atts;> <!-- Also used as the `module_section` identifier/title. --> <!ELEMENT module (#PCDATA)> <!ATTLIST module %basic.atts; %reference.atts;> <!-- Also used as the `class_section` identifier/title, and in the `inheritance` element. --> <!ELEMENT class (#PCDATA)> <!ATTLIST class %basic.atts; %reference.atts;> <!-- Also used as the `method_section` identifier/title. --> <!ELEMENT method (#PCDATA)> <!ATTLIST method %basic.atts; %reference.atts;> <!-- Also used as the `function_section` identifier/title. --> <!ELEMENT function (#PCDATA)> <!ATTLIST function %basic.atts; %reference.atts;> <!-- ??? Use this instead of the ``*_attribute`` elements below? Add a "type" attribute to differentiate? Also used as the identifier/title for `module_attribute_section`, `class_attribute_section`, and `instance_attribute_section`. --> <!ELEMENT attribute (#PCDATA)> <!ATTLIST attribute %basic.atts; %reference.atts;> <!-- Also used as the `module_attribute_section` identifier/title. A module attribute is an exported module-level global variable. --> <!ELEMENT module_attribute (#PCDATA)> <!ATTLIST module_attribute %basic.atts; %reference.atts;> <!-- Also used as the `class_attribute_section` identifier/title. --> <!ELEMENT class_attribute (#PCDATA)> <!ATTLIST class_attribute %basic.atts; %reference.atts;> <!-- Also used as the `instance_attribute_section` identifier/title. --> <!ELEMENT instance_attribute (#PCDATA)> <!ATTLIST instance_attribute %basic.atts; %reference.atts;> <!ELEMENT variable (#PCDATA)> <!ATTLIST variable %basic.atts; %reference.atts;> <!-- Also used in `parameter_list`. --> <!ELEMENT parameter (#PCDATA)> <!ATTLIST parameter %basic.atts; %reference.atts; excess_positional %yesorno; #IMPLIED excess_keyword %yesorno; #IMPLIED> <!ELEMENT type (#PCDATA)> <!ATTLIST type %basic.atts; %reference.atts;> <!ELEMENT exception_class (#PCDATA)> <!ATTLIST exception_class %basic.atts; %reference.atts;> <!ELEMENT warning_class (#PCDATA)> <!ATTLIST warning_class %basic.atts; %reference.atts;> <!-- Local Variables: mode: sgml indent-tabs-mode: nil fill-column: 70 End: --> ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/docs/dev/hacking.txt������������������������������������������������������������������0000664�0001750�0001750�00000022003�11700652711�021074� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������========================== Docutils_ Hacker's Guide ========================== :Author: Lea Wiemann :Contact: docutils-develop@lists.sourceforge.net :Revision: $Revision: 7302 $ :Date: $Date: 2012-01-03 20:23:53 +0100 (Die, 03. Jän 2012) $ :Copyright: This document has been placed in the public domain. :Abstract: This is the introduction to Docutils for all persons who want to extend Docutils in some way. :Prerequisites: You have used reStructuredText_ and played around with the `Docutils front-end tools`_ before. Some (basic) Python knowledge is certainly helpful (though not necessary, strictly speaking). .. _Docutils: http://docutils.sourceforge.net/ .. _reStructuredText: http://docutils.sourceforge.net/rst.html .. _Docutils front-end tools: ../user/tools.html .. contents:: Overview of the Docutils Architecture ===================================== To give you an understanding of the Docutils architecture, we'll dive right into the internals using a practical example. Consider the following reStructuredText file:: My *favorite* language is Python_. .. _Python: http://www.python.org/ Using the ``rst2html.py`` front-end tool, you would get an HTML output which looks like this:: [uninteresting HTML code removed] <body> <div class="document"> <p>My <em>favorite</em> language is <a class="reference" href="http://www.python.org/">Python</a>.</p> </div> </body> </html> While this looks very simple, it's enough to illustrate all internal processing stages of Docutils. Let's see how this document is processed from the reStructuredText source to the final HTML output: Reading the Document -------------------- The **Reader** reads the document from the source file and passes it to the parser (see below). The default reader is the standalone reader (``docutils/readers/standalone.py``) which just reads the input data from a single text file. Unless you want to do really fancy things, there is no need to change that. Since you probably won't need to touch readers, we will just move on to the next stage: Parsing the Document -------------------- The **Parser** analyzes the the input document and creates a **node tree** representation. In this case we are using the **reStructuredText parser** (``docutils/parsers/rst/__init__.py``). To see what that node tree looks like, we call ``quicktest.py`` (which can be found in the ``tools/`` directory of the Docutils distribution) with our example file (``test.txt``) as first parameter (Windows users might need to type ``python quicktest.py test.txt``):: $ quicktest.py test.txt <document source="test.txt"> <paragraph> My <emphasis> favorite language is <reference name="Python" refname="python"> Python . <target ids="python" names="python" refuri="http://www.python.org/"> Let us now examine the node tree: The top-level node is ``document``. It has a ``source`` attribute whose value is ``text.txt``. There are two children: A ``paragraph`` node and a ``target`` node. The ``paragraph`` in turn has children: A text node ("My "), an ``emphasis`` node, a text node (" language is "), a ``reference`` node, and again a ``Text`` node ("."). These node types (``document``, ``paragraph``, ``emphasis``, etc.) are all defined in ``docutils/nodes.py``. The node types are internally arranged as a class hierarchy (for example, both ``emphasis`` and ``reference`` have the common superclass ``Inline``). To get an overview of the node class hierarchy, use epydoc (type ``epydoc nodes.py``) and look at the class hierarchy tree. Transforming the Document ------------------------- In the node tree above, the ``reference`` node does not contain the target URI (``http://www.python.org/``) yet. Assigning the target URI (from the ``target`` node) to the ``reference`` node is *not* done by the parser (the parser only translates the input document into a node tree). Instead, it's done by a **Transform**. In this case (resolving a reference), it's done by the ``ExternalTargets`` transform in ``docutils/transforms/references.py``. In fact, there are quite a lot of Transforms, which do various useful things like creating the table of contents, applying substitution references or resolving auto-numbered footnotes. The Transforms are applied after parsing. To see how the node tree has changed after applying the Transforms, we use the ``rst2pseudoxml.py`` tool: .. parsed-literal:: $ rst2pseudoxml.py test.txt <document source="test.txt"> <paragraph> My <emphasis> favorite language is <reference name="Python" **refuri="http://www.python.org/"**> Python . <target ids="python" names="python" ``refuri="http://www.python.org/"``> For our small test document, the only change is that the ``refname`` attribute of the reference has been replaced by a ``refuri`` attribute |---| the reference has been resolved. While this does not look very exciting, transforms are a powerful tool to apply any kind of transformation on the node tree. By the way, you can also get a "real" XML representation of the node tree by using ``rst2xml.py`` instead of ``rst2pseudoxml.py``. Writing the Document -------------------- To get an HTML document out of the node tree, we use a **Writer**, the HTML writer in this case (``docutils/writers/html4css1.py``). The writer receives the node tree and returns the output document. For HTML output, we can test this using the ``rst2html.py`` tool:: $ rst2html.py --link-stylesheet test.txt <?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="generator" content="Docutils 0.3.10: http://docutils.sourceforge.net/" /> <title>

My favorite language is Python.

So here we finally have our HTML output. The actual document contents are in the fourth-last line. Note, by the way, that the HTML writer did not render the (invisible) ``target`` node |---| only the ``paragraph`` node and its children appear in the HTML output. Extending Docutils ================== Now you'll ask, "how do I actually extend Docutils?" First of all, once you are clear about *what* you want to achieve, you have to decide *where* to implement it |---| in the Parser (e.g. by adding a directive or role to the reStructuredText parser), as a Transform, or in the Writer. There is often one obvious choice among those three (Parser, Transform, Writer). If you are unsure, ask on the Docutils-develop_ mailing list. In order to find out how to start, it is often helpful to look at similar features which are already implemented. For example, if you want to add a new directive to the reStructuredText parser, look at the implementation of a similar directive in ``docutils/parsers/rst/directives/``. Modifying the Document Tree Before It Is Written ------------------------------------------------ You can modify the document tree right before the writer is called. One possibility is to use the publish_doctree_ and publish_from_doctree_ functions. To retrieve the document tree, call:: document = docutils.core.publish_doctree(...) Please see the docstring of publish_doctree for a list of parameters. .. XXX Need to write a well-readable list of (commonly used) options of the publish_* functions. Probably in api/publisher.txt. ``document`` is the root node of the document tree. You can now change the document by accessing the ``document`` node and its children |---| see `The Node Interface`_ below. When you're done with modifying the document tree, you can write it out by calling:: output = docutils.core.publish_from_doctree(document, ...) .. _publish_doctree: ../api/publisher.html#publish_doctree .. _publish_from_doctree: ../api/publisher.html#publish_from_doctree The Node Interface ------------------ As described in the overview above, Docutils' internal representation of a document is a tree of nodes. We'll now have a look at the interface of these nodes. (To be completed.) What Now? ========= This document is not complete. Many topics could (and should) be covered here. To find out with which topics we should write about first, we are awaiting *your* feedback. So please ask your questions on the Docutils-develop_ mailing list. .. _Docutils-develop: ../user/mailing-lists.html#docutils-develop .. |---| unicode:: 8212 .. em-dash :trim: .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: docutils-0.12/docs/dev/semantics.txt0000664000175000017500000001072511700652711021466 0ustar engelbertengelbert00000000000000===================== Docstring Semantics ===================== :Author: David Goodger :Contact: docutils-develop@lists.sourceforge.net :Revision: $Revision: 7302 $ :Date: $Date: 2012-01-03 20:23:53 +0100 (Die, 03. Jän 2012) $ :Copyright: This document has been placed in the public domain. These are notes for a possible future PEP providing the final piece of the Python docstring puzzle: docstring semantics or documentation methodology. `PEP 257`_, Docstring Conventions, sketches out some guidelines, but does not get into methodology details. I haven't explored documentation methodology more because, in my opinion, it is a completely separate issue from syntax, and it's even more controversial than syntax. Nobody wants to be told how to lay out their documentation, a la JavaDoc_. I think the JavaDoc way is butt-ugly, but it *is* an established standard for the Java world. Any standard documentation methodology has to be formal enough to be useful but remain light enough to be usable. If the methodology is too strict, too heavy, or too ugly, many/most will not want to use it. I think a standard methodology could benefit the Python community, but it would be a hard sell. A PEP would be the place to start. For most human-readable documentation needs, the free-form text approach is adequate. We'd only need a formal methodology if we want to extract the parameters into a data dictionary, index, or summary of some kind. PythonDoc ========= (Not to be confused with Daniel Larsson's pythondoc_ project.) A Python version of the JavaDoc_ semantics (not syntax). A set of conventions which are understood by the Docutils. What JavaDoc has done is to establish a syntax that enables a certain documentation methodology, or standard *semantics*. JavaDoc is not just syntax; it prescribes a methodology. - Use field lists or definition lists for "tagged blocks". By this I mean that field lists can be used similarly to JavaDoc's ``@tag`` syntax. That's actually one of the motivators behind field lists. For example, we could have:: """ :Parameters: - `lines`: a list of one-line strings without newlines. - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip common leading indent if true (1, default). :Return: - a list of indented lines with mininum indent removed; - the amount of the indent; - whether or not the block finished with a blank line or at the end of `lines`. """ This is taken straight out of docutils/statemachine.py, in which I experimented with a simple documentation methodology. Another variation I've thought of exploits the Grouch_-compatible "classifier" element of definition lists. For example:: :Parameters: `lines` : [string] List of one-line strings without newlines. `until_blank` : boolean Stop collecting at the first blank line if true (1). `strip_indent` : boolean Strip common leading indent if true (1, default). - Field lists could even be used in a one-to-one correspondence with JavaDoc ``@tags``, although I doubt if I'd recommend it. Several ports of JavaDoc's ``@tag`` methodology exist in Python, most recently Ed Loper's "epydoc_". Other Ideas =========== - Can we extract comments from parsed modules? Could be handy for documenting function/method parameters:: def method(self, source, # path of input file dest # path of output file ): This would save having to repeat parameter names in the docstring. Idea from Mark Hammond's 1998-06-23 Doc-SIG post, "Re: [Doc-SIG] Documentation tool": it would be quite hard to add a new param to this method without realising you should document it - Frederic Giacometti's `iPhrase Python documentation conventions`_ is an attachment to his Doc-SIG post of 2001-05-30. .. _PEP 257: http://www.python.org/peps/pep-0257.html .. _JavaDoc: http://java.sun.com/j2se/javadoc/ .. _pythondoc: http://starship.python.net/crew/danilo/pythondoc/ .. _Grouch: http://www.mems-exchange.org/software/grouch/ .. _epydoc: http://epydoc.sf.net/ .. _iPhrase Python documentation conventions: http://mail.python.org/pipermail/doc-sig/2001-May/001840.html .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: docutils-0.12/docs/dev/enthought-rfp.txt0000664000175000017500000001065210331153535022270 0ustar engelbertengelbert00000000000000================================== Enthought API Documentation Tool ================================== ----------------------- Request for Proposals ----------------------- :Author: Janet Swisher, Senior Technical Writer :Organization: `Enthought, Inc. `_ :Copyright: 2004 by Enthought, Inc. :License: `Enthought License`_ (BSD Style) .. _Enthought License: http://docutils.sf.net/licenses/enthought.txt The following is excerpted from the full RFP, and is published here with permission from `Enthought, Inc.`_ See the `Plan for Enthought API Documentation Tool`__. __ enthought-plan.html .. contents:: .. sectnum:: Requirements ============ The documentation tool will address the following high-level goals: Documentation Extraction ------------------------ 1. Documentation will be generated directly from Python source code, drawing from the code structure, docstrings, and possibly other comments. 2. The tool will extract logical constructs as appropriate, minimizing the need for comments that are redundant with the code structure. The output should reflect both documented and undocumented elements. Source Format ------------- 1. The docstrings will be formatted in as terse syntax as possible. Required tags, syntax, and white space should be minimized. 2. The tool must support the use of Traits. Special comment syntax for Traits may be necessary. Information about the Traits package is available at http://code.enthought.com/traits/. In the following example, each trait definition is prefaced by a plain comment:: __traits__ = { # The current selection within the frame. 'selection' : Trait([], TraitInstance(list)), # The frame has been activated or deactivated. 'activated' : TraitEvent(), 'closing' : TraitEvent(), # The frame is closed. 'closed' : TraitEvent(), } 3. Support for ReStructuredText (ReST) format is desirable, because much of the existing docstrings uses ReST. However, the complete ReST specification need not be supported, if a subset can achieve the project goals. If the tool does not support ReST, the contractor should also provide a tool or path to convert existing docstrings. Output Format ------------- 1. Documentation will be output as a navigable suite of HTML files. 2. The style of the HTML files will be customizable by a cascading style sheet and/or a customizable template. 3. Page elements such as headers and footer should be customizable, to support differing requirements from one documentation project to the next. Output Structure and Navigation ------------------------------- 1. The navigation scheme for the HTML files should not rely on frames, and should harmonize with conversion to Microsoft HTML Help (.chm) format. 2. The output should be structured to make navigable the architecture of the Python code. Packages, modules, classes, traits, and functions should be presented in clear, logical hierarchies. Diagrams or trees for inheritance, collaboration, sub-packaging, etc. are desirable but not required. 3. The output must include indexes that provide a comprehensive view of all packages, modules, and classes. These indexes will provide readers with a clear and exhaustive view of the code base. These indexes should be presented in a way that is easily accessible and allows easy navigation. 4. Cross-references to other documented elements will be used throughout the documentation, to enable the reader to move quickly relevant information. For example, where type information for an element is available, the type definition should be cross-referenced. 5. The HTML suite should provide consistent navigation back to the home page, which will include the following information: * Bibliographic information - Author - Copyright - Release date - Version number * Abstract * References - Links to related internal docs (i.e., other docs for the same product) - Links to related external docs (e.g., supporting development docs, Python support docs, docs for included packages) It should be possible to specify similar information at the top level of each package, so that packages can be included as appropriate for a given application. License ======= Enthought intends to release the software under an open-source ("BSD-style") license. docutils-0.12/docs/dev/testing.txt0000664000175000017500000001727511771146137021174 0ustar engelbertengelbert00000000000000=================== Docutils_ Testing =================== :Authors: Lea Wiemann ; David Goodger :Revision: $Revision: 7463 $ :Date: $Date: 2012-06-22 21:49:51 +0200 (Fre, 22. Jun 2012) $ :Copyright: This document has been placed in the public domain. .. _Docutils: http://docutils.sourceforge.net/ .. contents:: When adding new functionality (or fixing bugs), be sure to add test cases to the test suite. Practise test-first programming; it's fun, it's addictive, and it works! This document describes how to run the Docutils test suite, how the tests are organized and how to add new tests or modify existing tests. Running the Test Suite ====================== Before checking in any changes, run the entire Docutils test suite to be sure that you haven't broken anything. From a shell:: cd docutils/test ./alltests.py Python Versions =============== The Docutils 0.10 release supports Python 2.4 or later. Therefore, you should actually have Pythons 2.4, as well as the latest Python (3.2 at the time of this writing) installed and always run the tests on all of them. (A good way to do that is to always run the test suite through a short script that runs ``alltests.py`` under each version of Python.) If you can't afford installing 3 or more Python versions, the edge cases (2.4, and 3.2) should cover most of it. Good resources covering the differences between Python versions: * `What's New in Python 2.4`__ * `What's New in Python 2.5`__ * `What's New in Python 2.6`__ * `PEP 290 - Code Migration and Modernization`__ __ http://www.python.org/doc/2.4.4/whatsnew/whatsnew24.html __ http://www.python.org/doc/2.5.2/whatsnew/whatsnew25.html __ http://docs.python.org/whatsnew/2.6.html __ http://www.python.org/peps/pep-0290.html .. _Python Check-in Policies: http://www.python.org/dev/tools.html .. _sandbox directory: http://docutils.svn.sourceforge.net/svnroot/docutils/trunk/sandbox/ .. _nightly repository tarball: http://svn.berlios.de/svndumps/docutils-repos.gz Unit Tests ========== Unit tests test single functions or modules (i.e. whitebox testing). If you are implementing a new feature, be sure to write a test case covering its functionality. It happens very frequently that your implementation (or even only a part of it) doesn't work with an older (or even newer) Python version, and the only reliable way to detect those cases is using tests. Often, it's easier to write the test first and then implement the functionality required to make the test pass. Writing New Tests ----------------- When writing new tests, it very often helps to see how a similar test is implemented. For example, the files in the ``test_parsers/test_rst/`` directory all look very similar. So when adding a test, you don't have to reinvent the wheel. If there is no similar test, you can write a new test from scratch using Python's ``unittest`` module. For an example, please have a look at the following imaginary ``test_square.py``:: #! /usr/bin/env python # $Id: testing.txt 7463 2012-06-22 19:49:51Z milde $ # Author: Your Name # Copyright: This module has been placed in the public domain. """ Test module for docutils.square. """ import unittest import docutils.square class SquareTest(unittest.TestCase): def test_square(self): self.assertEqual(docutils.square.square(0), 0) self.assertEqual(docutils.square.square(5), 25) self.assertEqual(docutils.square.square(7), 49) def test_square_root(self): self.assertEqual(docutils.square.sqrt(49), 7) self.assertEqual(docutils.square.sqrt(0), 0) self.assertRaises(docutils.square.SquareRootError, docutils.square.sqrt, 20) if __name__ == '__main__': unittest.main() For more details on how to write tests, please refer to the documentation of the ``unittest`` module. .. _functional: Functional Tests ================ The directory ``test/functional/`` contains data for functional tests. Performing functional testing means testing the Docutils system as a whole (i.e. blackbox testing). Directory Structure ------------------- + ``functional/`` The main data directory. + ``input/`` The input files. - ``some_test.txt``, for example. + ``output/`` The actual output. - ``some_test.html``, for example. + ``expected/`` The expected output. - ``some_test.html``, for example. + ``tests/`` The config files for processing the input files. - ``some_test.py``, for example. - ``_default.py``, the `default configuration file`_. The Testing Process ------------------- When running ``test_functional.py``, all config files in ``functional/tests/`` are processed. (Config files whose names begin with an underscore are ignored.) The current working directory is always Docutils' main test directory (``test/``). For example, ``functional/tests/some_test.py`` could read like this:: # Source and destination file names. test_source = "some_test.txt" test_destination = "some_test.html" # Keyword parameters passed to publish_file. reader_name = "standalone" parser_name = "rst" writer_name = "html" settings_overrides['output-encoding'] = 'utf-8' # Relative to main ``test/`` directory. settings_overrides['stylesheet_path'] = '../docutils/writers/html4css1/html4css1.css' The two variables ``test_source`` and ``test_destination`` contain the input file name (relative to ``functional/input/``) and the output file name (relative to ``functional/output/`` and ``functional/expected/``). Note that the file names can be chosen arbitrarily. However, the file names in ``functional/output/`` *must* match the file names in ``functional/expected/``. If defined, ``_test_more`` must be a function with the following signature:: def _test_more(expected_dir, output_dir, test_case, parameters): This function is called from the test case to perform tests beyond the simple comparison of expected and actual output files. ``test_source`` and ``test_destination`` are removed from the namespace, as are all variables whose names begin with an underscore ("_"). The remaining names are passed as keyword arguments to ``docutils.core.publish_file``, so you can set reader, parser, writer and anything else you want to configure. Note that ``settings_overrides`` is already initialized as a dictionary *before* the execution of the config file. Creating New Tests ------------------ In order to create a new test, put the input test file into ``functional/input/``. Then create a config file in ``functional/tests/`` which sets at least input and output file names, reader, parser and writer. Now run ``test_functional.py``. The test will fail, of course, because you do not have an expected output yet. However, an output file will have been generated in ``functional/output/``. Check this output file for validity and correctness. Then copy the file to ``functional/expected/``. If you rerun ``test_functional.py`` now, it should pass. If you run ``test_functional.py`` later and the actual output doesn't match the expected output anymore, the test will fail. If this is the case and you made an intentional change, check the actual output for validity and correctness, copy it to ``functional/expected/`` (overwriting the old expected output), and commit the change. .. _default configuration file: The Default Configuration File ------------------------------ The file ``functional/tests/_default.py`` contains default settings. It is executed just before the actual configuration files, which has the same effect as if the contents of ``_default.py`` were prepended to every configuration file. docutils-0.12/docs/dev/policies.txt0000664000175000017500000006077412101437744021323 0ustar engelbertengelbert00000000000000=========================== Docutils Project Policies =========================== :Author: David Goodger; open to all Docutils developers :Contact: docutils-develop@lists.sourceforge.net :Date: $Date: 2013-01-28 10:07:48 +0100 (Mon, 28. Jän 2013) $ :Revision: $Revision: 7597 $ :Copyright: This document has been placed in the public domain. .. contents:: The Docutils project group is a meritocracy based on code contribution and lots of discussion [#bcs]_. A few quotes sum up the policies of the Docutils project. The IETF's classic credo (by MIT professor Dave Clark) is an ideal we can aspire to: We reject: kings, presidents, and voting. We believe in: rough consensus and running code. As architect, chief cook and bottle-washer, David Goodger currently functions as BDFN (Benevolent Dictator For Now). (But he would happily abdicate the throne given a suitable candidate. Any takers?) Eric S. Raymond, anthropologist of the hacker subculture, writes in his essay `The Magic Cauldron`_: The number of contributors [to] projects is strongly and inversely correlated with the number of hoops each project makes a user go through to contribute. We will endeavour to keep the barrier to entry as low as possible. The policies below should not be thought of as barriers, but merely as a codification of experience to date. These are "best practices"; guidelines, not absolutes. Exceptions are expected, tolerated, and used as a source of improvement. Feedback and criticism is welcome. As for control issues, Emmett Plant (CEO of the Xiph.org Foundation, originators of Ogg Vorbis) put it well when he said: Open source dictates that you lose a certain amount of control over your codebase, and that's okay with us. .. [#bcs] Phrase borrowed from `Ben Collins-Sussman of the Subversion project `__. .. _The Magic Cauldron: http://www.catb.org/~esr/writings/magic-cauldron/ How to get a new feature into Docutils ======================================== Question: I would very much like to have this new feature in the Docutils core. What exactly do I have to do to make this possible? * Present your idea at the Docutils-develop_ mailing list, +1 usually triggers a fast response, -1 may be forgotten later, and/or file a feature request at the `docutils tracker`_ +1 there is a permanent record, -1 it may stay forgotten among all the other feature requests. * Convince a Docutils developer that this is a valuable addition worth the effort. * Contribute. The developers will make sure that the contribution fits nicely into Docutils (cf. the `review criteria`_). This might involve discussing (and compromising on) design and implementation details. It might also lead to the conclusion that the addition fits better in the `extensions and related projects`_. * Be patient, and be persistent. None of us are paid to do this, it's all in our spare time -- which is precious and rare. How to make code contributions that are easily accepted: * Have a look at the `Python coding conventions`_ and `documentation conventions`_ below. * **Prepare test cases.** This vastly helps when integrating new code. Test cases are also examples and showcases for new features. See `Docutils Testing`_ for a description of the test suite in ``docutils/test/``. Ensure the addition works with all supported Python versions (2.4 ... 3.2). * Look at the Docutils sources to see how similar features are implemented, learn to do it "the Docutils way". * Prepare the a patch or an addition to the existing documentation. Include links. * If you are familiar with version control, consider creating a `feature branch`_ in a Docutils repository_ checkout. (Working with branches is *much* easier with git_. You can get a git clone of the repository from http://repo.or.cz/w/docutils.git or with git-svn.) .. _docutils-develop: ../user/mailing-lists.html#docutils-develop .. _docutils tracker: http://sourceforge.net/tracker/?group_id=38414 .. _git: http://git-scm.com/ .. _Docutils testing: testing.html Python Coding Conventions ========================= Contributed code will not be refused merely because it does not strictly adhere to these conditions; as long as it's internally consistent, clean, and correct, it probably will be accepted. But don't be surprised if the "offending" code gets fiddled over time to conform to these conventions. The Docutils project shall follow the generic coding conventions as specified in the `Style Guide for Python Code`_ and `Docstring Conventions`_ PEPs, summarized, clarified, and extended as follows: * 4 spaces per indentation level. No hard tabs. * Use only 7-bit ASCII, no 8-bit strings. See `Docutils Internationalization`_. * No one-liner compound statements (i.e., no ``if x: return``: use two lines & indentation), except for degenerate class or method definitions (i.e., ``class X: pass`` is OK.). * Lines should be no more than 78 characters long. * Use "StudlyCaps" for class names (except for element classes in docutils.nodes). * Use "lowercase" or "lowercase_with_underscores" for function, method, and variable names. For short names, maximum two words, joined lowercase may be used (e.g. "tagname"). For long names with three or more words, or where it's hard to parse the split between two words, use lowercase_with_underscores (e.g., "note_explicit_target", "explicit_target"). If in doubt, use underscores. * Avoid lambda expressions, which are inherently difficult to understand. Named functions are preferable and superior: they're faster (no run-time compilation), and well-chosen names serve to document and aid understanding. * Avoid functional constructs (filter, map, etc.). Use list comprehensions instead. * Avoid ``from __future__ import`` constructs. They are inappropriate for production code. * Use 'single quotes' for string literals, and """triple double quotes""" for docstrings. .. _Style Guide for Python Code: http://www.python.org/peps/pep-0008.html .. _Docstring Conventions: http://www.python.org/peps/pep-0257.html .. _Docutils Internationalization: ../howto/i18n.html#python-code Documentation Conventions ========================= * Docutils documentation is written using reStructuredText, of course. * Use 7-bit ASCII if at all possible, and Unicode substitutions when necessary. * Use the following section title adornment styles:: ================ Document Title ================ -------------------------------------------- Document Subtitle, or Major Division Title -------------------------------------------- Section ======= Subsection ---------- Sub-Subsection `````````````` Sub-Sub-Subsection .................. * Use two blank lines before each section/subsection/etc. title. One blank line is sufficient between immediately adjacent titles. * Add a bibliographic field list immediately after the document title/subtitle. See the beginning of this document for an example. * Add an Emacs "local variables" block in a comment at the end of the document. See the end of this document for an example. Copyrights and Licensing ======================== The majority of the Docutils project code and documentation has been placed in the public domain. Unless clearly and explicitly indicated otherwise, any patches (modifications to existing files) submitted to the project for inclusion (via Subversion, SourceForge trackers, mailing lists, or private email) are assumed to be in the public domain as well. Any new files contributed to the project should clearly state their intentions regarding copyright, in one of the following ways: * Public domain (preferred): include the statement "This module/document has been placed in the public domain." * Copyright & open source license: include a copyright notice, along with either an embedded license statement, a reference to an accompanying license file, or a license URL. The license should be well known, simple and compatible with other open source software licenses. To keep the number of different licenses at a minimum, using the `2-Clause BSD license`_ (also known as "Simplified" or `FreeBSD license`_) is recommended. .. _2-Clause BSD license: http://www.opensource.org/licenses/BSD-2-Clause .. _FreeBSD license: http://www.freebsd.org/copyright/freebsd-license.html .. The following licenses are described as simple and permissible on `Various Licenses and Comments about Them`_ by the GNU Project and listed as popular in `OSI Approved Licenses`_: Expat License / MIT License http://www.jclark.com/xml/copying.txt http://www.opensource.org/licenses/MIT http://www.spdx.org/licenses/MIT The term MIT License is ambiguous and may accurately refer to the Expat license or the X11 license [http://en.wikipedia.org/wiki/MIT_License] -1 called `MIT license` by OSI and in the `SPDX Open Source License Registry`_ but `Expat license` by GNU 2-Clause BSD license / FreeBSD license http://www.freebsd.org/copyright/freebsd-license.html http://www.opensource.org/licenses/BSD-2-Clause http://www.spdx.org/licenses/BSD-2-Clause If you want a simple, permissive non-copyleft free software license, the FreeBSD license is a reasonable choice. However, please don't call it a “BSD” or “BSD-style” license, because that is likely to cause confusion which could lead to use of the flawed original BSD license. -- `Various Licenses and Comments about Them`_ +1 license used by the closely related Sphinx project +1 "2-Clause BSD license" is a non-ambiguous name, used by both, OSI and GNU. +1 clear wording, structured text .. _Various Licenses and Comments about Them: http://www.gnu.org/licenses/license-list.html .. _OSI Approved Licenses: http://www.opensource.org/licenses/category .. _SPDX Open Source License Registry: http://www.spdx.org/licenses/ .. _pypi: http://pypi.python.org/pypi?:action=browse&c=54 .. _Subversion Repository: Repository ========== Please see the `repository documentation`_ for details on how to access Docutils' Subversion repository. Anyone can access the repository anonymously. Only project developers can make changes. (If you would like to become a project developer, just ask!) Also see `Setting Up For Docutils Development`_ below for some useful info. Unless you really *really* know what you're doing, please do *not* use ``svn import``. It's quite easy to mess up the repository with an import. .. _repository documentation: repository.html Branches -------- (These branch policies go into effect with Docutils 0.4.) The "docutils" directory of the **trunk** (a.k.a. the **Docutils core**) is used for active -- but stable, fully tested, and reviewed -- development. There will be at least one active **maintenance branch** at a time, based on at least the latest feature release. For example, when Docutils 0.5 is released, its maintenance branch will take over, and the 0.4.x maintenance branch may be retired. Maintenance branches will receive bug fixes only; no new features will be allowed here. Obvious and uncontroversial bug fixes *with tests* can be checked in directly to the core and to the maintenance branches. Don't forget to add test cases! Many (but not all) bug fixes will be applicable both to the core and to the maintenance branches; these should be applied to both. No patches or dedicated branches are required for bug fixes, but they may be used. It is up to the discretion of project developers to decide which mechanism to use for each case. .. _feature branches: .. _feature branch: Feature additions and API changes will be done in **feature branches**. Feature branches will not be managed in any way. Frequent small checkins are encouraged here. Feature branches must be discussed on the `docutils-develop mailing list`_ and reviewed before being merged into the core. .. _docutils-develop mailing list: http://lists.sourceforge.net/lists/listinfo/docutils-develop Review Criteria ``````````````` Before a new feature, an API change, or a complex, disruptive, or controversial bug fix can be checked in to the core or into a maintenance branch, it must undergo review. These are the criteria: * The branch must be complete, and include full documentation and tests. * There should ideally be one branch merge commit per feature or change. In other words, each branch merge should represent a coherent change set. * The code must be stable and uncontroversial. Moving targets and features under debate are not ready to be merged. * The code must work. The test suite must complete with no failures. See `Docutils Testing`_. The review process will ensure that at least one other set of eyeballs & brains sees the code before it enters the core. In addition to the above, the general `Check-ins`_ policy (below) also applies. Check-ins --------- Changes or additions to the Docutils core and maintenance branches carry a commitment to the Docutils user community. Developers must be prepared to fix and maintain any code they have committed. The Docutils core (``trunk/docutils`` directory) and maintenance branches should always be kept in a stable state (usable and as problem-free as possible). All changes to the Docutils core or maintenance branches must be in `good shape`_, usable_, documented_, tested_, and `reasonably complete`_. * _`Good shape` means that the code is clean, readable, and free of junk code (unused legacy code; by analogy to "junk DNA"). * _`Usable` means that the code does what it claims to do. An "XYZ Writer" should produce reasonable XYZ output. * _`Documented`: The more complete the documentation the better. Modules & files must be at least minimally documented internally. `Docutils Front-End Tools`_ should have a new section for any front-end tool that is added. `Docutils Configuration Files`_ should be modified with any settings/options defined. For any non-trivial change, the HISTORY.txt_ file should be updated. * _`Tested` means that unit and/or functional tests, that catch all bugs fixed and/or cover all new functionality, have been added to the test suite. These tests must be checked by running the test suite under all supported Python versions, and the entire test suite must pass. See `Docutils Testing`_. * _`Reasonably complete` means that the code must handle all input. Here "handle" means that no input can cause the code to fail (cause an exception, or silently and incorrectly produce nothing). "Reasonably complete" does not mean "finished" (no work left to be done). For example, a writer must handle every standard element from the Docutils document model; for unimplemented elements, it must *at the very least* warn that "Output for element X is not yet implemented in writer Y". If you really want to check code directly into the Docutils core, you can, but you must ensure that it fulfills the above criteria first. People will start to use it and they will expect it to work! If there are any issues with your code, or if you only have time for gradual development, you should put it on a branch or in the sandbox first. It's easy to move code over to the Docutils core once it's complete. It is the responsibility and obligation of all developers to keep the Docutils core and maintenance branches stable. If a commit is made to the core or maintenance branch which breaks any test, the solution is simply to revert the change. This is not vindictive; it's practical. We revert first, and discuss later. Docutils will pursue an open and trusting policy for as long as possible, and deal with any aberrations if (and hopefully not when) they happen. We'd rather see a torrent of loose contributions than just a trickle of perfect-as-they-stand changes. The occasional mistake is easy to fix. That's what Subversion is for! .. _Docutils Front-End Tools: ../user/tools.html .. _Docutils Configuration Files: ../user/config.html .. _HISTORY.txt: ../../HISTORY.txt Version Numbering ================= Docutils version numbering uses a ``major.minor.micro`` scheme (x.y.z; for example, 0.4.1). **Major releases** (x.0, e.g. 1.0) will be rare, and will represent major changes in API, functionality, or commitment. For example, as long as the major version of Docutils is 0, it is to be considered *experimental code*. When Docutils reaches version 1.0, the major APIs will be considered frozen and backward compatibility will become of paramount importance. Releases that change the minor number (x.y, e.g. 0.5) will be **feature releases**; new features from the `Docutils core`_ will be included. Releases that change the micro number (x.y.z, e.g. 0.4.1) will be **bug-fix releases**. No new features will be introduced in these releases; only bug fixes off of `maintenance branches`_ will be included. This policy was adopted in October 2005, and will take effect with Docutils version 0.4. Prior to version 0.4, Docutils didn't have an official version numbering policy, and micro releases contained both bug fixes and new features. .. _Docutils core: http://docutils.svn.sourceforge.net/viewvc/docutils/trunk/docutils/ .. _maintenance branches: http://docutils.svn.sourceforge.net/viewvc/docutils/branches/ Snapshots ========= Snapshot tarballs will be generated regularly from * the Docutils core, representing the current cutting-edge state of development; * each active maintenance branch, for bug fixes; * each development branch, representing the unstable seat-of-your-pants bleeding edge. The ``sandbox/infrastructure/docutils-update`` shell script, run as an hourly cron job on the BerliOS server, is responsible for automatically generating the snapshots and updating the web site. See the `web site docs `__. Setting Up For Docutils Development =================================== When making changes to the code, testing is a must. The code should be run to verify that it produces the expected results, and the entire test suite should be run too. The modified Docutils code has to be accessible to Python for the tests to have any meaning. There are two ways to keep the Docutils code accessible during development: 1. Update your ``PYTHONPATH`` environment variable so that Python picks up your local working copy of the code. This is the recommended method. We'll assume that the Docutils trunk is checked out under your ~/projects/ directory as follows:: svn co https://@docutils.svn.sourceforge.net/svnroot/docutils/trunk \ docutils For the bash shell, add this to your ``~/.profile``:: PYTHONPATH=$HOME/projects/docutils/docutils PYTHONPATH=$PYTHONPATH:$HOME/projects/docutils/docutils/extras export PYTHONPATH The first line points to the directory containing the ``docutils`` package. The second line adds the directory containing the third-party modules Docutils depends on. The third line exports this environment variable. You may also wish to add the ``tools`` directory to your ``PATH``:: PATH=$PATH:$HOME/projects/docutils/docutils/tools export PATH 2. Before you run anything, every time you make a change, reinstall Docutils:: python setup.py install .. CAUTION:: This method is **not** recommended for day-to-day development; it's too easy to forget. Confusion inevitably ensues. If you install Docutils this way, Python will always pick up the last-installed copy of the code. If you ever forget to reinstall the "docutils" package, Python won't see your latest changes. A useful addition to the ``docutils`` top-level directory in branches and alternate copies of the code is a ``set-PATHS`` file containing the following lines:: # source this file export PYTHONPATH=$PWD:$PWD/extras export PATH=$PWD/tools:$PATH Open a shell for this branch, ``cd`` to the ``docutils`` top-level directory, and "source" this file. For example, using the bash shell:: $ cd some-branch/docutils $ . set-PATHS Mailing Lists ============= Developers are recommended to subscribe to all `Docutils mailing lists`_. .. _Docutils mailing lists: ../user/mailing-lists.html The Wiki ======== There is a development wiki at http://docutils.python-hosting.com/ as a scratchpad for transient notes. Please use the repository for permament document storage. Extensions and Related Projects =============================== The Sandbox ----------- The `sandbox directory`_ is a place to play around, to try out and share ideas. It's a part of the Subversion repository but it isn't distributed as part of Docutils releases. Feel free to check in code to the sandbox; that way people can try it out but you won't have to worry about it working 100% error-free, as is the goal of the Docutils core. A project-specific subdirectory should be created for each new project. Any developer who wants to play in the sandbox may do so, but project directories are recommended over personal directories, which discourage collaboration. It's OK to make a mess in the sandbox! But please, play nice. Please update the `sandbox README`_ file with links and a brief description of your work. In order to minimize the work necessary for others to install and try out new, experimental components, the following sandbox directory structure is recommended:: sandbox/ project_name/ # For a collaborative project. README.txt # Describe the requirements, purpose/goals, usage, # and list the maintainers. docs/ ... component.py # The component is a single module. # *OR* (but *not* both) component/ # The component is a package. __init__.py # Contains the Reader/Writer class. other1.py # Other modules and data files used data.txt # by this component. ... test/ # Test suite. ... tools/ # For front ends etc. ... setup.py # Use Distutils to install the component # code and tools/ files into the right # places in Docutils. userid/ # For *temporary* personal space. Some sandbox projects are destined to move to the Docutils core once completed. Others, such as add-ons to Docutils or applications of Docutils, may graduate to become `parallel projects`_. .. _sandbox README: http://docutils.sf.net/sandbox/README.html .. _sandbox directory: http://docutils.svn.sourceforge.net/viewvc/docutils/trunk/sandbox/ .. _parallel project: Parallel Projects ----------------- Parallel projects contain useful code that is not central to the functioning of Docutils. Examples are specialized add-ons or plug-ins, and applications of Docutils. They use Docutils, but Docutils does not require their presence to function. An official parallel project will have its own directory beside (or parallel to) the main ``docutils`` directory in the Subversion repository. It can have its own web page in the docutils.sourceforge.net domain, its own file releases and downloadable snapshots, and even a mailing list if that proves useful. However, an official parallel project has implications: it is expected to be maintained and continue to work with changes to the core Docutils. A parallel project requires a project leader, who must commit to coordinate and maintain the implementation: * Answer questions from users and developers. * Review suggestions, bug reports, and patches. * Monitor changes and ensure the quality of the code and documentation. * Coordinate with Docutils to ensure interoperability. * Put together official project releases. Of course, related projects may be created independently of Docutils. The advantage of a parallel project is that the SourceForge environment and the developer and user communities are already established. Core Docutils developers are available for consultation and may contribute to the parallel project. It's easier to keep the projects in sync when there are changes made to the core Docutils code. Other related projects ---------------------- Many related but independent projects are listed in the Docutils `link list`_. If you want your project to appear there, drop a note at the Docutils-develop_ mailing list. .. _link list: http://docutils.sourceforge.net/docs/user/links.html .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: docutils-0.12/docs/dev/todo.txt0000664000175000017500000026664012062177750020465 0ustar engelbertengelbert00000000000000====================== Docutils_ To Do List ====================== :Author: David Goodger (with input from many); open to all Docutils developers :Contact: docutils-develop@lists.sourceforge.net :Date: $Date: 2012-12-12 23:06:32 +0100 (Mit, 12. Dez 2012) $ :Revision: $Revision: 7545 $ :Copyright: This document has been placed in the public domain. .. _Docutils: http://docutils.sourceforge.net/ .. contents:: Priority items are marked with "@" symbols. The more @s, the higher the priority. Items in question form (containing "?") are ideas which require more thought and debate; they are potential to-do's. Many of these items are awaiting champions. If you see something you'd like to tackle, please do! If there's something you'd like to see done but are unable to implement it yourself, please consider donating to Docutils: |donate| .. |donate| image:: http://images.sourceforge.net/images/project-support.jpg :target: http://sourceforge.net/donate/index.php?group_id=38414 :align: middle :width: 88 :height: 32 :alt: Support the Docutils project! Please see also the Bugs_ document for a list of bugs in Docutils. .. _bugs: ../../BUGS.html Minimum Requirements for Python Standard Library Candidacy ========================================================== Below are action items that must be added and issues that must be addressed before Docutils can be considered suitable to be proposed for inclusion in the Python standard library. Many of these are now handled by Sphinx_ * Support for `document splitting`_. May require some major code rework. * Support for subdocuments (see `large documents`_). * `Object numbering and object references`_. * `Nested inline markup`_. * `Python Source Reader`_. * The HTML writer needs to be rewritten (or a second HTML writer added) to allow for custom classes, and for arbitrary splitting (stack-based?). * Documentation_ of the architecture. Other docs too. * Plugin support. * Suitability for `Python module documentation `_. .. _Sphinx: http://sphinx.pocoo.org/ General ======= * Encoding of command line arguments can only be guessed: * try UTF-8/strict first, then try the locale's encoding with strict error handling, then ASCII/replace? UTF-8 is almost 100% safe to try first; false positives are rare, The locale's encoding with strict error handling may be a reasonable compromise, but any error would indicate that the locale's encoding is inappropriate. The only safe fallback is ASCII/replace. * Do not decode argv before option parsing but individual string values? +1 Allows for separate command-line vs. filesystem encodings, respectively to keep file names encoded. +1 Allows to configure command-line encoding in a config file, -1 More complicated. Cf. . * Improve handling on Windows: - Get graphical installer. - Make rst2html.py an .exe file using py2exe. * .. _GUI: The user interface is very difficult to use for most Windows users; you can't really expect them to use the command line. We need some kind of GUI that can launch rst2html.py, and save the HTML output to a file, and launch a browser. What's important is that we get settings to work with the GUI. So we need some way to dynamically generate a list of settings for the GUI. The current settings_spec for OptionParser doesn't seem to be usable for this for the following reasons: - It's biased toward the command line -- there are *two* options for one boolean setting. - You cannot have both a one-line description and a longer description for tooltips/help-texts. - It doesn't provide hints for the input type. You cannot easily infer the type of a setting from its validator, because any component can add new validators. In fact, it may be necessary to have both a hint about the input type (e.g. string) and a validator (valid ID), or it may be necessary to have a different set of choices for the CLI (1, INFO, 2, ...) and for the GUI (INFO, WARNING, ...). - It's coupled to the OptionParser. We want to be able to change the underlying system without breaking everything. - It's a bunch of primitive structures. We want an extensible (thus object-oriented) interface. So we probably need to create a class for storing all the settings, and auto-generate the OptionParser data from that. I talked to Stephan Deibel about getting Docutils integrated into Wing IDE. He said it's possible, and he'd be willing to help. There's a scripting interface to Wing, which we'd use. We can dynamically generate a list of preferences and not worry too much about the rendering (from what I understood); Wing's whole GUI is dynamic anyway. The interface could be made usable for other GUIs. For example, we could try to get option support for DocFactory. // FW * Allow different report levels for STDERR and system_messages inside the document? * Change the docutils-update script (in sandbox/infrastructure), to support arbitrary branch snapshots. * Move some general-interest sandboxes out of individuals' directories, into subprojects? * Add option for file (and URL) access restriction to make Docutils usable in Wikis and similar applications. 2005-03-21: added ``file_insertion_enabled`` & ``raw_enabled`` settings. These partially solve the problem, allowing or disabling **all** file accesses, but not limited access. * Configuration file handling needs discussion: - There should be some error checking on the contents of config files. How much checking should be done? How loudly should Docutils complain if it encounters an error/problem? - Docutils doesn't complain when it doesn't find a configuration file supplied with the ``--config`` option. Should it? (If yes, error or warning?) * Internationalization: - I18n needs refactoring, the language dictionaries are difficult to maintain. Maybe have a look at gettext or similar tools. (This would make a nice Google Summer of Code project) - Language modules: in accented languages it may be useful to have both accented and unaccented entries in the ``bibliographic_fields`` mapping for versatility. - Add a "--strict-language" option & setting: no English fallback for language-dependent features. Make this the default for output (as opposed to input)? Throw an error with a helpfull message, e.g. Default "contents" title for language %s missing, please specify an explicit title. or "attention" title for language %s missing, please use a generic admonition with explicit title. - Add internationalization to _`footer boilerplate text` (resulting from "--generator", "--source-link", and "--date" etc.), allowing translations. * Add validation? See http://pytrex.sourceforge.net, RELAX NG, pyRXP. * In ``docutils.readers.get_reader_class`` (& ``parsers`` & ``writers`` too), should we be importing "standalone" or "docutils.readers.standalone"? (This would avoid importing top-level modules if the module name is not in docutils/readers. Potential nastiness.) * Perhaps store a _`name-to-id mapping file`? This could be stored permanently, read by subsequent processing runs, and updated with new entries. ("Persistent ID mapping"?) * Perhaps the ``Component.supports`` method should deal with individual features ("meta" etc.) instead of formats ("html" etc.)? * Think about _`large documents` made up of multiple subdocument files. Issues: continuity (`persistent sequences`_ above), cross-references (`name-to-id mapping file`_ above and `targets in other documents`_ below), splitting (`document splitting`_ below). When writing a book, the author probably wants to split it up into files, perhaps one per chapter (but perhaps even more detailed). However, we'd like to be able to have references from one chapter to another, and have continuous numbering (pages and chapters, as applicable). Of course, none of this is implemented yet. There has been some thought put into some aspects; see `the "include" directive`__ and the `Reference Merging`_ transform below. When I was working with SGML in Japan, we had a system where there was a top-level coordinating file, book.sgml, which contained the top-level structure of a book: the element, containing the book and empty component elements (<preface>, <chapter>, <appendix>, etc.), each with filename attributes pointing to the actual source for the component. Something like this:: <book id="bk01"> <title>Title of the Book (The "inrefid" attribute stood for "insertion reference ID".) The processing system would process each component separately, but it would recognize and use the book file to coordinate chapter and page numbering, and keep a persistent ID to (title, page number) mapping database for cross-references. Docutils could use a similar system for large-scale, multipart documents. __ ../ref/rst/directives.html#including-an-external-document-fragment Aahz's idea: First the ToC:: .. ToC-list:: Introduction.txt Objects.txt Data.txt Control.txt Then a sample use:: .. include:: ToC.txt As I said earlier in chapter :chapter:`Objects.txt`, the reference count gets increased every time a binding is made. Which produces:: As I said earlier in chapter 2, the reference count gets increased every time a binding is made. The ToC in this form doesn't even need to be references to actual reST documents; I'm simply doing it that way for a minimum of future-proofing, in case I do want to add the ability to pick up references within external chapters. Perhaps, instead of ToC (which would overload the "contents" directive concept already in use), we could use "manifest". A "manifest" directive might associate local reference names with files:: .. manifest:: intro: Introduction.txt objects: Objects.txt data: Data.txt control: Control.txt Then the sample becomes:: .. include:: manifest.txt As I said earlier in chapter :chapter:`objects`, the reference count gets increased every time a binding is made. * Add support for _`multiple output files` and _`generic data handling`: It should be possible for a component to **emit or reference** data to be either **included or referenced** in the output document. Examples of such data are stylesheets or images. For this, we need a "data" object which stores the data either inline or by referring to a file. The Docutils framework is responsible for either: * storing the data in the appropriate location (e.g. in the directory of the output file, or in a user-specified directory) and providing the paths of the stored files to the writer, *or* * providing the data itself to the writer so that it can be embedded in the output document. This approach decouples data handling from the data source (which can either be embedded or referenced) and the destination (which can either be embedded or referenced as well). See . * Add testing for Docutils' front end tools? * Publisher: "Ordinary setup" shouldn't requre specific ordering; at the very least, there ought to be error checking higher up in the call chain. [Aahz] ``Publisher.get_settings`` requires that all components be set up before it's called. Perhaps the I/O *objects* shouldn't be set, but I/O *classes*. Then options are set up (``.set_options``), and ``Publisher.set_io`` (or equivalent code) is called with source & destination paths, creating the I/O objects. Perhaps I/O objects shouldn't be instantiated until required. For split output, the Writer may be called multiple times, once for each doctree, and each doctree should have a separate Output object (with a different path). Is the "Builder" pattern applicable here? * Perhaps I/O objects should become full-fledged components (i.e. subclasses of ``docutils.Component``, as are Readers, Parsers, and Writers now), and thus have associated option/setting specs and transforms. * Multiple file I/O suggestion from Michael Hudson: use a file-like object or something you can iterate over to get file-like objects. * Add an "--input-language" option & setting? Specify a different language module for input (bibliographic fields, directives) than for output. The "--language" option would set both input & output languages. * Auto-generate reference tables for language-dependent features? Could be generated from the source modules. A special command-line option could be added to Docutils front ends to do this. (Idea from Engelbert Gruber.) * Enable feedback of some kind from internal decisions, such as reporting the successful input encoding. Modify runtime settings? System message? Simple stderr output? * Rationalize Writer settings (HTML/LaTeX/PEP) -- share settings. * Add an "--include file" command-line option (config setting too?), equivalent to ".. include:: file" as the first line of the doc text? Especially useful for character entity sets, text transform specs, boilerplate, etc. * Parameterize the Reporter object or class? See the `2004-02-18 "rest checking and source path"`_ thread. .. _2004-02-18 "rest checking and source path": http://thread.gmane.org/gmane.text.docutils.user/1112 * Add a "disable_transforms" setting? And a dummy Writer subclass that does nothing when its .write() method is called? Would allow for easy syntax checking. See the `2004-02-18 "rest checking and source path"`_ thread. * Add a generic meta-stylesheet mechanism? An external file could associate style names ("class" attributes) with specific elements. Could be generalized to arbitrary output attributes; useful for HTML & XMLs. Aahz implemented something like this in sandbox/aahz/Effective/EffMap.py. * .. _classes for table cells: William Dode suggested that table cells be assigned "class" attributes by columns, so that stylesheets can affect text alignment. Unfortunately, there doesn't seem to be a way (in HTML at least) to leverage the "colspec" elements (HTML "col" tags) by adding classes to them. The resulting HTML is very verbose:: 111 222 ... At the very least, it should be an option. People who don't use it shouldn't be penalized by increases in their HTML file sizes. Table rows could also be assigned classes (like odd/even). That would be easier to implement. How should it be implemented? * There could be writer options (column classes & row classes) with standard values. * The table directive could grow some options. Something like ":cell-classes: col1 col2 col3" (either must match the number of columns, or repeat to fill?) and ":row-classes: odd even" (repeat to fill; body rows only, or header rows too?). Probably per-table directive options are best. The "class" values could be used by any writer, and applying such classes to all tables in a document with writer options is too broad. * Add file-specific settings support to config files, like:: [file index.txt] compact-lists: no Is this even possible? Should the criterion be the name of the input file or the output file? Alternative (more explicit) syntax:: [source_file index.txt] ... [dest_file index.html] ... Or rather allow settings configuration from the rst source file (see misc.settings_ directive)? * The "validator" support added to OptionParser is very similar to "traits_" in SciPy_. Perhaps something could be done with them? (Had I known about traits when I was implementing docutils.frontend, I may have used them instead of rolling my own.) .. _traits: http://code.enthought.com/traits/ .. _SciPy: http://www.scipy.org/ * tools/buildhtml.py: Extend the --prune option ("prune" config setting) to accept file names (generic path) in addition to directories (e.g. --prune=docs/user/rst/cheatsheet.txt, which should *not* be converted to HTML). * Add support for _`plugins`. * _`Config directories`: Currently, ~/.docutils, ./docutils.conf/, & /etc/docutils.conf are read as configuration files. Proposal: allow ~/.docutils to be a a configuration *directory*, along with /etc/docutils/ and ./docutils.conf/. Within these directories, check for config.txt files. We can also have subdirectories here, for plugins, S5 themes, components (readers/writers/parsers) etc. Docutils will continue to support configuration files for backwards compatibility. * Add support for document decorations other than headers & footers? For example, top/bottom/side navigation bars for web pages. Generic decorations? Seems like a bad idea as long as it isn't independent from the ouput format (for example, navigation bars are only useful for web pages). * docutils_update: Check for a ``Makefile`` in a directory, and run ``make`` if found? This would allow for variant processing on specific source files, such as running rst2s5.py instead of rst2html.py. * Add a "disable table of contents" setting? The S5 writer could set it as a default. Rationale: The ``contents`` (table of contents) directive must not be used [in S5/HTML documents]. It changes the CSS class of headings and they won't show up correctly in the screen presentation. -- `Easy Slide Shows With reStructuredText & S5 <../user/slide-shows.html>`_ Analogue to the ``sectnum_xform`` setting, it could be used by the latex writer to switch to a LaTeX generated ToC (currently, the latex writer calls it "use_latex_toc"). object numbering and object references -------------------------------------- For equations, tables & figures. These would be the equivalent of DocBook's "formal" elements. In LaTeX, automatic counters are implemented for sections, equations and floats (figures, tables) (configurable via stylesheets or in the latex-preamble). Objects can be given `reference names`_ with the ``\label{}`` inserts the corresponding number. No such mechanism exists in HTML. * We need _`persistent sequences`, similar to chapter and footnote numbers. See `OpenOffice.org XML`_ "fields". - Should the sequences be automatic or manual (user-specifyable)? * It is already possible to give `reference names`_ to objects via internal hyperlink targets or the "name" directive option:: .. _figure name: .. figure:: image.png or :: .. figure:: image.png :name: figure name Improve the mapping of "phrase references" to IDs/labels with Literal transcription (i.e. ü -> ue, ß -> ss, å -> aa) instead of just stripping the accents and other non-ASCII chars. Use http://pypi.python.org/pypi/Unidecode? A "table" directive has been implemented, supporting table titles. Perhaps the name could derive from the title/caption? .. _reference names: ../ref/rst/restructuredtext.html#reference-names * We need syntax for object references. Cf. `OpenOffice.org XML`_ "reference fields": - Parameterized substitutions are too complicated (cf. `or not to do`: `object references`_) - An interpreted text approach is simpler and better:: See Figure :ref:`figure name` and Equation :ref:`eq:identity`. - "equation", "figure", and "page" roles could generate appropriate boilerplate text:: See :figure:`figure name` on :page:`figure name`. See `Interpreted Text`_ below. Reference boilerplate could be specified in the document (defaulting to nothing):: .. fignum:: :prefix-ref: "Figure " :prefix-caption: "Fig. " :suffix-caption: : The position of the role (prefix or suffix) could also be utilized .. _OpenOffice.org XML: http://xml.openoffice.org/ .. _object references: rst/alternatives.html#object-references See also the `Modified rst2html `__ by Nicolas Rougier for a sample implementation. Documentation ============= User Docs --------- * Add a FAQ entry about using Docutils (with reStructuredText) on a server and that it's terribly slow. See the first paragraphs in . * Add document about what Docutils has previously been used for (web/use-cases.txt?). * Improve index in docs/user/config.txt. Developer Docs -------------- * Complete `Docutils Runtime Settings <../api/runtime-settings.html>`_. * Improve the internal module documentation (docstrings in the code). Specific deficiencies listed below. - docutils.parsers.rst.states.State.build_table: data structure required (including StringList). - docutils.parsers.rst.states: more complete documentation of parser internals. * docs/ref/doctree.txt: DTD element structural relationships, semantics, and attributes. In progress; element descriptions to be completed. * Document the ``pending`` elements, how they're generated and what they do. * Document the transforms (perhaps in docstrings?): how they're used, what they do, dependencies & order considerations. * Document the HTML classes used by html4css1.py. * Write an overview of the Docutils architecture, as an introduction for developers. What connects to what, why, and how. Either update PEP 258 (see PEPs_ below) or as a separate doc. * Give information about unit tests. Maybe as a howto? * Document the docutils.nodes APIs. * Complete the docs/api/publisher.txt docs. How-Tos ------- * Creating Docutils Writers * Creating Docutils Readers * Creating Docutils Transforms * Creating Docutils Parsers * Using Docutils as a Library PEPs ---- * Complete PEP 258 Docutils Design Specification. - Fill in the blanks in API details. - Specify the nodes.py internal data structure implementation? [Tibs:] Eventually we need to have direct documentation in there on how it all hangs together - the DTD is not enough (indeed, is it still meant to be correct? [Yes, it is. --DG]). * Rework PEP 257, separating style from spec from tools, wrt Docutils? See Doc-SIG from 2001-06-19/20. Python Source Reader ==================== General: * Analyze Tony Ibbs' PySource code. * Analyze Doug Hellmann's HappyDoc project. * Investigate how POD handles literate programming. * Take the best ideas and integrate them into Docutils. Miscellaneous ideas: * Ask Python-dev for opinions (GvR for a pronouncement) on special variables (__author__, __version__, etc.): convenience vs. namespace pollution. Ask opinions on whether or not Docutils should recognize & use them. * If we can detect that a comment block begins with ``##``, a la JavaDoc, it might be useful to indicate interspersed section headers & explanatory text in a module. For example:: """Module docstring.""" ## # Constants # ========= a = 1 b = 2 ## # Exception Classes # ================= class MyException(Exception): pass # etc. * Should standalone strings also become (module/class) docstrings? Under what conditions? We want to prevent arbitrary strings from becomming docstrings of prior attribute assignments etc. Assume that there must be no blank lines between attributes and attribute docstrings? (Use lineno of NEWLINE token.) Triple-quotes are sometimes used for multi-line comments (such as commenting out blocks of code). How to reconcile? * HappyDoc's idea of using comment blocks when there's no docstring may be useful to get around the conflict between `additional docstrings`_ and ``from __future__ import`` for module docstrings. A module could begin like this:: #!/usr/bin/env python # :Author: Me # :Copyright: whatever """This is the public module docstring (``__doc__``).""" # More docs, in comments. # All comments at the beginning of a module could be # accumulated as docstrings. # We can't have another docstring here, because of the # ``__future__`` statement. from __future__ import division Using the JavaDoc convention of a doc-comment block beginning with ``##`` is useful though. It allows doc-comments and implementation comments. .. _additional docstrings: ../peps/pep-0258.html#additional-docstrings * HappyDoc uses an initial comment block to set "parser configuration values". Do the same thing for Docutils, to set runtime settings on a per-module basis? I.e.:: # Docutils:setting=value Could be used to turn on/off function parameter comment recognition & other marginal features. Could be used as a general mechanism to augment config files and command-line options (but which takes precedence?). * Multi-file output should be divisible at arbitrary level. * Support all forms of ``import`` statements: - ``import module``: listed as "module" - ``import module as alias``: "alias (module)" - ``from module import identifier``: "identifier (from module)" - ``from module import identifier as alias``: "alias (identifier from module)" - ``from module import *``: "all identifiers (``*``) from module" * Have links to colorized Python source files from API docs? And vice-versa: backlinks from the colorized source files to the API docs! * In summaries, use the first *sentence* of a docstring if the first line is not followed by a blank line. reStructuredText Parser ======================= Also see the `... Or Not To Do?`__ list. __ rst/alternatives.html#or-not-to-do Misc ---- * Allow embedded references and not only embedded URIs: ```link text `_``; see the second half of . * Another list problem:: * foo * bar * baz This ends up as a definition list. This is more of a usability issue. * This case is probably meant to be a nested list, but it ends up as a list inside a block-quote without an error message:: - foo - bar It should probably just be an error. The problem with this is that you don't notice easily in HTML that it's not a nested list but a block-quote -- there's not much of a visual difference. * Treat enumerated lists that are not arabic and consist of only one item in a single line as ordinary paragraphs. See . * The citation syntax could use some improvements. See (and the sub-thread at , and the follow-ups at , , ), , , , , . * The current list-recognition logic has too many false positives, as in :: * Aorta * V. cava superior * V. cava inferior Here ``V.`` is recognized as an enumerator, which leads to confusion. We need to find a solution that resolves such problems without complicating the spec to much. See . * Add indirect links via citation references & footnote references. Example:: `Goodger (2005)`_ is helpful. .. _Goodger (2005): [goodger2005]_ .. [goodger2005] citation text See . * Complain about bad URI characters (http://article.gmane.org/gmane.text.docutils.user/2046) and disallow internal whitespace (http://article.gmane.org/gmane.text.docutils.user/2214). * Create ``info``-level system messages for unnecessarily backslash-escaped characters (as in ``"\something"``, rendered as "something") to allow checking for errors which silently slipped through. * Add (functional) tests for untested roles. * Add test for ":figwidth: image" option of "figure" directive. (Test code needs to check if PIL is available on the system.) * Add support for CJK double-width whitespace (indentation) & punctuation characters (markup; e.g. double-width "*", "-", "+")? * Add motivation sections for constructs in spec. * Support generic hyperlink references to _`targets in other documents`? Not in an HTML-centric way, though (it's trivial to say ``http://www.example.com/doc#name``, and useless in non-HTML contexts). XLink/XPointer? ``.. baseref::``? See Doc-SIG 2001-08-10. * .. _adaptable file extensions: In target URLs, it would be useful to not explicitly specify the file extension. If we're generating HTML, then ".html" is appropriate; if PDF, then ".pdf"; etc. How about using ".*" to indicate "choose the most appropriate filename extension"? For example:: .. _Another Document: another.* What is to be done for output formats that don't *have* hyperlinks? For example, LaTeX targeted at print. Hyperlinks may be "called out", as footnotes with explicit URLs. (Don't convert the links.) But then there's also LaTeX targeted at PDFs, which *can* have links. Perhaps a runtime setting for "*" could explicitly provide the extension, defaulting to the output file's extension. Should the system check for existing files? No, not practical. Handle documents only, or objects (images, etc.) also? If this handles images also, how to differentiate between document and image links? Element context (within "image")? Which image extension to use for which document format? Again, a runtime setting would suffice. This may not be just a parser issue; it may need framework support. Mailing list threads: `Images in both HTML and LaTeX`__ (especially `this summary of Lea's objections`__), `more-universal links?`__, `Output-format-sensitive link targets?`__ __ http://thread.gmane.org/gmane.text.docutils.user/1239 __ http://article.gmane.org/gmane.text.docutils.user/1278 __ http://thread.gmane.org/gmane.text.docutils.user/1915 __ http://thread.gmane.org/gmane.text.docutils.user/2438 Idea from Jim Fulton: an external lookup table of targets: I would like to specify the extension (e.g. .txt) [in the source, rather than ``filename.*``], but tell the converter to change references to the files anticipating that the files will be converted too. For example:: .. _Another Document: another.txt rst2html.py --convert-links "another.txt bar.txt" foo.txt That is, name the files for which extensions should be converted. Note that I want to refer to original files in the original text (another.txt rather than another.txt) because I want the unconverted text to stand on its own. Note that in most cases, people will be able to use globs:: rst2html.py --convert-link-extensions-for "`echo *.txt`" foo.txt It might be nice to be able to use multiple arguments, as in:: rst2html.py --convert-link-extensions-for *.txt -- foo.txt :: > What is to be done for output formats > that don't have hyperlinks? Don't convert the links. :: > Handle documents only, or objects > (images, etc.) also? No, documents only, but there really is no need for gueswork. Just get the file names as command-line arguments. EIBTI [explicit is better than implicit]. For images, we probably need separate solution (which is being worked on), whereas for documents, the issue is basically interlinking between reStructuredText documents. IMO, this cries for support for multiple input and output files, i.e. support for documents which comprise multiple files. Adding adaptable file extensions seems like a kludge. // FW * Implement the header row separator modification to table.el. (Wrote to Takaaki Ota & the table.el mailing list on 2001-08-12, suggesting support for "=====" header rows. On 2001-08-17 he replied, saying he'd put it on his to-do list, but "don't hold your breath".) * Fix the parser's indentation handling to conform with the stricter definition in the spec. (Explicit markup blocks should be strict or forgiving?) .. XXX What does this mean? Can you elaborate, David? * Make the parser modular. Allow syntax constructs to be added or disabled at run-time. Subclassing is probably not enough because it makes it difficult to apply multiple extensions. * Generalize the "doctest block" construct (which is overly Python-centric) to other interactive sessions? "Doctest block" could be renamed to "I/O block" or "interactive block", and each of these could also be recognized as such by the parser: - Shell sessions:: $ cat example1.txt A block beginning with a "$ " prompt is interpreted as a shell session interactive block. As with Doctest blocks, the interactive block ends with the first blank line, and wouldn't have to be indented. - Root shell sessions:: # cat example2.txt A block beginning with a "# " prompt is interpreted as a root shell session (the user is or has to be logged in as root) interactive block. Again, the block ends with a blank line. Other standard (and unambiguous) interactive session prompts could easily be added (such as "> " for WinDOS). Tony Ibbs spoke out against this idea (2002-06-14 Doc-SIG thread "docutils feedback"). * Add support for pragma (syntax-altering) directives. Some pragma directives could be local-scope unless explicitly specified as global/pragma using ":global:" options. * Support whitespace in angle-bracketed standalone URLs according to Appendix E ("Recommendations for Delimiting URI in Context") of `RFC 2396`_. .. _RFC 2396: http://www.rfc-editor.org/rfc/rfc2396.txt * Use the vertical spacing of the source text to determine the corresponding vertical spacing of the output? * [From Mark Nodine] For cells in simple tables that comprise a single line, the justification can be inferred according to the following rules: 1. If the text begins at the leftmost column of the cell, then left justification, ELSE 2. If the text begins at the rightmost column of the cell, then right justification, ELSE 3. Center justification. The onus is on the author to make the text unambiguous by adding blank columns as necessary. There should be a parser setting to turn off justification-recognition (normally on would be fine). Decimal justification? All this shouldn't be done automatically. Only when it's requested by the user, e.g. with something like this:: .. table:: :auto-indent: (Table goes here.) Otherwise it will break existing documents. * Generate a warning or info message for paragraphs which should have been lists, like this one:: 1. line one 3. line two * Generalize the "target-notes" directive into a command-line option somehow? See docutils-develop 2003-02-13. * Allow a "::"-only paragraph (first line, actually) to introduce a _`literal block without a blank line`? (Idea from Paul Moore.) :: :: This is a literal block Is indentation enough to make the separation between a paragraph which contains just a ``::`` and the literal text unambiguous? (There's one problem with this concession: If one wants a definition list item which defines the term "::", we'd have to escape it.) It would only be reasonable to apply it to "::"-only paragraphs though. I think the blank line is visually necessary if there's text before the "::":: The text in this paragraph needs separation from the literal block following:: This doesn't look right. * Add new syntax for _`nested inline markup`? Or extend the parser to parse nested inline markup somehow? See the `collected notes `__. * Drop the backticks from embedded URIs with omitted reference text? Should the angle brackets be kept in the output or not? :: _ Probably not worth the trouble. * How about a syntax for alternative hyperlink behavior, such as "open in a new window" (as in HTML's ````)? The MoinMoin wiki uses a caret ("^") at the beginning of the URL ("^" is not a legal URI character). That could work for both inline and explicit targets:: The `reference docs <^url>`__ may be handy. .. _name: ^url This may be too specific to HTML. It hasn't been requested very often either. * Add an option to add URI schemes at runtime. * _`Segmented lists`:: : segment : segment : segment : segment : segment : very long segment : segment : segment : segment The initial colon (":") can be thought of as a type of bullet We could even have segment titles:: :: title : title : title : segment : segment : segment : segment : segment : segment This would correspond well to DocBook's SegmentedList. Output could be tabular or "name: value" pairs, as described in DocBook's docs. * Allow backslash-escaped colons in field names:: :Case Study\: Event Handling: This chapter will be dropped. * Enable grid _`tables inside XML comments`, where "--" ends comments. I see three implementation possibilities: 1. Make the table syntax characters into "table" directive options. This is the most flexible but most difficult, and we probably don't need that much flexibility. 2. Substitute "~" for "-" with a specialized directive option (e.g. ":tildes:"). 3. Make the standard table syntax recognize "~" as well as "-", even without a directive option. Individual tables would have to be internally consistent. Directive options are preferable to configuration settings, because tables are document-specific. A pragma directive would be another approach, to set the syntax once for a whole document. In the meantime, the list-table_ directive is a good replacement for grid tables inside XML comments. .. _list-table: ../ref/rst/directives.html#list-table * Generalize docinfo contents (bibliographic fields): remove specific fields, and have only a single generic "field"? * _`Line numbers` and "source" in system messages: - Add "source" and "line" keyword arguments to all Reporter calls? This would require passing source/line arguments along all intermediate functions (where currently only `line` is used). Or rather specify "line" only if actually needed? Currently, `document.reporter` uses a state machine instance to determine the "source" and "line" info from `statemachine.input_lines` if not given explicitely. Except for special cases, the "line" argument is not needed because, `document.statemachine` keeps record of the current line number. - For system messages generated after the parsing is completed (i.e. by transforms or the writer) "line" info must be present in the doctree elements. Elements' .line assignments should be checked. (Assign to .source too? Add a set_info method? To what?) The "source" (and line number in the source) can either be added explicitely to the elements or determined from the “raw” line number by `document.statemachine.get_source_and_line`. - Some line numbers in elements are not being set properly (explicitly), just implicitly/automatically. See rev. 1.74 of docutils/parsers/rst/states.py for an example of how to set. - The line numbers of definition list items are wrong:: $ rst2pseudoxml.py --expose-internal-attribute line 1 2 3 5 6 7 1 2 3 5 6 7 * .. _none source: Quite a few nodes are getting a "None" source attribute as well. In particular, see the bodies of definition lists. Math Markup ----------- Since Docutils 0.8, a "math" role and directive using LaTeX math syntax as input format is part of reStructuredText. Open issues: * Use a "Transform" for math format conversions as extensively discussed in the "math directive issues" thread in May 2008 (http://osdir.com/ml/text.docutils.devel/2008-05/threads.html)? * Generic "math-output" option (currently specific to HTML). (List of math-output preferences?) * Try to be compatible with `Math support in Sphinx`_? * The ``:label:`` option selects a label for the equation, by which it can be cross-referenced, and causes an equation number to be issued. In Docutils, the option ``:name:`` sets the label. Equation numbering is not implemented yet. * Option ``:nowrap:`` prevents wrapping of the given math in a math environment (you have to specify the math environment in the content). .. _Math support in Sphinx: http://sphinx.pocoo.org/ext/math.html * Equation numbering and references. (Should be handled in a unified way with other numbered entities like formal tables and images.) alternative input formats ````````````````````````` Use a directive option to specify an alternative input format, e.g. (but not limited to): MathML_ Not for hand-written code but maybe usefull when pasted in (or included from a file) For an overview of MathML implementations and tests, see, e.g., the `mathweb wiki`_ or the `ConTeXT MathML page`_. .. _MathML: http://www.w3.org/TR/MathML2/ .. _mathweb wiki: http://www.mathweb.org/wiki/MathML .. _ConTeXT MathML page: http://wiki.contextgarden.net/MathML ASCIIMath_ Simple, ASCII based math input language (see also `ASCIIMath tutorial`_). * The Python module ASCIIMathML_ translates a string with ASCIIMath into a MathML tree. Used, e.g., by MultiMarkdown__. A more comprehensive and implementation is ASCIIMathPython_ by Paul Trembley (also used in his sandbox projects). * For conversion to LaTeX, there is a JavaScript script at http://dlippman.imathas.com/asciimathtex/ASCIIMath2TeX.js .. _ASCIIMath: http://www1.chapman.edu/~jipsen/mathml/asciimath.html .. _ASCIIMath tutorial: http://www.wjagray.co.uk/maths/ASCIIMathTutorial.html .. _ASCIIMathML: http://pypi.python.org/pypi/asciimathml/ .. _ASCIIMathPython: http://sourceforge.net/projects/asciimathpython/ __ http://fletcherpenney.net/multimarkdown/ `Unicode Nearly Plain Text Encoding of Mathematics`_ format for lightly marked-up representation of mathematical expressions in Unicode. (Unicode Technical Note. Sole responsibility for its contents rests with the author(s). Publication does not imply any endorsement by the Unicode Consortium.) .. _Unicode Nearly Plain Text Encoding of Mathematics: http://www.unicode.org/notes/tn28/ itex See `the culmination of a relevant discussion in 2003 `__. LaTeX output ```````````` Which equation environments should be supported by the math directive? * one line: + numbered: `equation` + unnumbered: `equation*` * multiline (test for ``\\`` outside of a nested environment (e.g. `array` or `cases`) + numbered: `align` (number every line) (To give one common number to all lines, put them in a `split` environment. Docutils then places it in an `equation` environment.) + unnumbered: `align*` + Sphinx math also supports `gather` (checking for blank lines in the content). Docutils puts content blocks separated by blank lines in separate math-block doctree nodes. (The only difference of `gather` to two consecutive "normal" environments seems to be that page-breaks between the two are prevented.) See http://www.math.uiuc.edu/~hildebr/tex/displays.html. HTML output ``````````` There is no native math support in HTML. MathML_ Converters from LaTeX to MathML include * latex_math_ (Python) by Jens Jørgen Mortensen in the Docutils sandbox * Blahtex_ (C++) * MathToWeb_ (Java) * TeX4ht_ (TeX based) * LaTeXML_ (Perl) * itex_ (also `used in Abiword`__) * TtM_ (C, non free, free binary for Linux) with an `online-trial page`__ * `Steve’s LATEX-to-MathML translator`_ ('mini-language', javascript, Python) latex_math_ is the base for the current latex2mathml_ module used with ``--math-output=MathML``. * Write a new converter based on: * a generic tokenizer (see e.g. a `latex-codec recipe`_, `updated latex-codec`_, ) * the Unicode-Char <-> LaTeX mappings database unimathsymbols_ __ http://msevior.livejournal.com/26377.html __ http://hutchinson.belmont.ma.us/tth/mml/ttmmozform.html .. _MathML: http://www.w3.org/TR/MathML2/ .. _latex_math: ../../../sandbox/jensj/latex_math/ .. _latex2mathml: ../../docutils/math/latex2mathml.py .. _Blahtex: http://gva.noekeon.org/blahtexml/ .. _MathToWeb: http://www.mathtoweb.com/ .. _TeX4ht: http://www.tug.org/applications/tex4ht/mn.html .. _LaTeXML: http://dlmf.nist.gov/LaTeXML/ .. _itex: http://golem.ph.utexas.edu/~distler/blog/itex2MMLcommands.html .. _ttm: http://hutchinson.belmont.ma.us/tth/mml/ .. _Steve’s LATEX-to-MathML translator: http://www.gold-saucer.org/mathml/greasemonkey/dist/display-latex .. _latex-codec recipe: http://code.activestate.com/recipes/252124-latex-codec/ .. _updated latex-codec: http://mirror.ctan.org/biblio/bibtex/utils/mab2bib/latex.py .. _unimathsymbols: http://milde.users.sourceforge.net/LUCR/Math/ .. URL seems down: .. _itex: http://pear.math.pitt.edu/mathzilla/itex2mmlItex.html HTML/CSS format math in standard HTML enhanced by CSS rules (Overview__, `Examples and experiments`__). LaTeX-math to HTML/CSS converters include * TtH_ (C) * Hevea_ (Objective Caml) * eLyXer_ (Python) The ``math-output=html`` option uses the converter from eLyXer. __ http://www.cs.tut.fi/~jkorpela/math/ __ http://www.zipcon.net/~swhite/docs/math/math.html .. _TtH: ttp://hutchinson.belmont.ma.us/tth/index.html .. _Hevea: http://para.inria.fr/~maranget/hevea/ .. _elyxer: http://elyxer.nongnu.org/ images (PNG or SVG) like e.g. Wikipedia. (e.g. with dvisvgm_ or the pure-python MathML->SVG converter SVGMath_) .. _dvisvgm: http://dvisvgm.sourceforge.net/ .. _SVGMath: http://www.grigoriev.ru/svgmath/ OpenOffice output ````````````````` * The `OpenDocument standard`_ version 1.1 says: Mathematical content is represented by MathML 2.0 However, putting MathML into an ODP file seems tricky as these (maybe outdated) links suppose: http://idippedut.dk/post/2008/01/25/Do-your-math-ODF-and-MathML.aspx http://idippedut.dk/post/2008/03/03/Now-I-get-it-ODF-and-MathML.aspx .. _OpenDocument standard: http://www.oasis-open.org/standards#opendocumentv1.1 * OOoLaTeX__: "a set of macros designed to bring the power of LaTeX into OpenOffice." __ http://ooolatex.sourceforge.net/ Directives ---------- Directives below are often referred to as "module.directive", the directive function. The "module." is not part of the directive name when used in a document. * Allow for field lists in list tables. See . * .. _unify tables: Unify table implementations and unify options of table directives (http://article.gmane.org/gmane.text.docutils.user/1857). * Allow directives to be added at run-time? * Use the language module for directive option names? * Add "substitution_only" and "substitution_ok" function attributes, and automate context checking? * Implement options or features on existing directives: - All directives that produce titled elements should grow implicit reference names based on the titles. - Allow the _`:trim:` option for all directives when they occur in a substitution definition, not only the unicode_ directive. .. _unicode: ../ref/rst/directives.html#unicode-character-codes - Add the "class" option to the unicode_ directive. For example, you might want to get characters or strings with borders around them. - _`images.figure`: "title" and "number", to indicate a formal figure? - _`parts.sectnum`: "local"?, "refnum" A "local" option could enable numbering for sections from a certain point down, and sections in the rest of the document are not numbered. For example, a reference section of a manual might be numbered, but not the rest. OTOH, an all-or-nothing approach would probably be enough. The "sectnum" directive should be usable multiple times in a single document. For example, in a long document with "chapter" and "appendix" sections, there could be a second "sectnum" before the first appendix, changing the sequence used (from 1,2,3... to A,B,C...). This is where the "local" concept comes in. This part of the implementation can be left for later. A "refnum" option (better name?) would insert reference names (targets) consisting of the reference number. Then a URL could be of the form ``http://host/document.html#2.5`` (or "2-5"?). Allow internal references by number? Allow name-based *and* number-based ids at the same time, or only one or the other (which would the table of contents use)? Usage issue: altering the section structure of a document could render hyperlinks invalid. - _`parts.contents`: Add a "suppress" or "prune" option? It would suppress contents display for sections in a branch from that point down. Or a new directive, like "prune-contents"? Add an option to include topics in the TOC? Another for sidebars? The "topic" directive could have a "contents" option, or the "contents" directive" could have an "include-topics" option. See docutils-develop 2003-01-29. - _`parts.header` & _`parts.footer`: Support multiple, named headers & footers? For example, separate headers & footers for odd, even, and the first page of a document. This may be too specific to output formats which have a notion of "pages". - _`misc.class`: - Add a ``:parent:`` option for setting the parent's class (http://article.gmane.org/gmane.text.docutils.devel/3165). - _`misc.include`: - Option to label lines? - How about an environment variable, say RSTINCLUDEPATH or RSTPATH, for standard includes (as in ``.. include:: ``)? This could be combined with a setting/option to allow user-defined include directories. - Add support for inclusion by URL? :: .. include:: :url: http://www.example.org/inclusion.txt - Strip blank lines from begin and end of a literal included file or file section. This would correspond to the way a literal block is handled. As nodes.literal_block expects (and we have) the text as a string (rather than a list of lines), using a regexp seems the way. - _`misc.raw`: add a "destination" option to the "raw" directive? :: .. raw:: html :destination: head It needs thought & discussion though, to come up with a consistent set of destination labels and consistent behavior. And placing HTML code inside the element of an HTML document is rather the job of a templating system. - _`body.sidebar`: Allow internal section structure? Adornment styles would be independent of the main document. That is really complicated, however, and the document model greatly benefits from its simplicity. * Implement directives. Each of the list items below begins with an identifier of the form, "module_name.directive_function_name". The directive name itself could be the same as the directive_function_name, or it could differ. - _`html.imagemap` It has the disadvantage that it's only easily implementable for HTML, so it's specific to one output format. (For non-HTML writers, the imagemap would have to be replaced with the image only.) - _`parts.endnotes` (or "footnotes"): See `Footnote & Citation Gathering`_. - _`parts.citations`: See `Footnote & Citation Gathering`_. - _`misc.language`: Specify (= change) the language of a document at parse time? * The misc.settings_ directive suggested below offers a more generic approach. * The language of document parts can be indicated by the "special class value" ``"language-"`` + `BCP 47`_ language code. Class arguments to the title are attached to the document's base node - hence titled documents can be given a different language at parse time. However, "language by class attribute" does not change parsing (localized directives etc.), only supporting writers. .. _BCP 47: http://www.rfc-editor.org/rfc/bcp/bcp47.txt - _`misc.settings`: Set any(?) Docutils runtime setting from within a document? Needs much thought and discussion. Security concerns need to be taken into account (it shouldn't be possible to enable ``file_insertion_enabled`` from within a document), and settings that only would have taken effect before the directive (like ``tab-width``) shouldn't be accessible either. See this sub-thread: - _`misc.gather`: Gather (move, or copy) all instances of a specific element. A generalization of the `Footnote & Citation Gathering`_ ideas. - Add a custom "directive" directive, equivalent to "role"? For example:: .. directive:: incr .. class:: incremental .. incr:: "``.. incr::``" above is equivalent to "``.. class:: incremental``". Another example:: .. directive:: printed-links .. topic:: Links :class: print-block .. target-notes:: :class: print-inline This acts like macros. The directive contents will have to be evaluated when referenced, not when defined. * Needs a better name? "Macro", "substitution"? * What to do with directive arguments & options when the macro/directive is referenced? - Make the meaning of block quotes overridable? Only a 1-shot though; doesn't solve the general problem. - .. _conditional directives: .. note:: See also the implementation in Sphinx_. Docutils already has the ability to say "use this content for Writer X" via the "raw" directive. It also does have the ability to say "use this content for any Writer other than X" via the "strip-elements with class" config value. However, using "raw" input just to select a special writer is inconvenient in many cases. It wouldn't be difficult to get more straightforward support, though. My first idea would be to add a set of conditional directives. Let's call them "writer-is" and "writer-is-not" for discussion purposes (don't worry about implemention details). We might have:: .. writer-is:: text-only :: +----------+ | SNMP | +----------+ | UDP | +----------+ | IP | +----------+ | Ethernet | +----------+ .. writer-is:: pdf .. figure:: protocol_stack.eps .. writer-is-not:: text-only pdf .. figure:: protocol_stack.png This could be an interface to the Filter transform (docutils.transforms.components.Filter). The ideas in `adaptable file extensions`_ above may also be applicable here. SVG's "switch" statement may provide inspiration. Here's an example of a directive that could produce multiple outputs (*both* raw troff pass-through *and* a GIF, for example) and allow the Writer to select. :: .. eqn:: .EQ delim %% .EN %sum from i=o to inf c sup i~=~lim from {m -> inf} sum from i=0 to m sup i% .EQ delim off .EN - _`body.example`: Examples; suggested by Simon Hefti. Semantics as per Docbook's "example"; admonition-style, numbered, reference, with a caption/title. - _`body.index`: Index targets. See `Index Entries & Indexes <./rst/alternatives.html#index-entries-indexes>`__. - _`body.literal`: Literal block, possibly "formal" (see `object numbering and object references`_ above). Possible options: - "highlight" a range of lines - include only a specified range of lines - "number" or "line-numbers"? (since 0.9 available with "code" directive) - "styled" could indicate that the directive should check for style comments at the end of lines to indicate styling or markup. Specific derivatives (i.e., a "python-interactive" directive) could interpret style based on cues, like the ">>> " prompt and "input()"/"raw_input()" calls. See docutils-users 2003-03-03. - _`body.listing`: Code listing with title (to be numbered eventually), equivalent of "figure" and "table" directives. - _`pysource.usage`: Extract a usage message from the program, either by running it at the command line with a ``--help`` option or through an exposed API. [Suggestion for Optik.] Interpreted Text ---------------- Interpreted text is entirely a reStructuredText markup construct, a way to get around built-in limitations of the medium. Some roles are intended to introduce new doctree elements, such as "title-reference". Others are merely convenience features, like "RFC". All supported interpreted text roles must already be known to the Parser when they are encountered in a document. Whether pre-defined in core/client code, or in the document, doesn't matter; the roles just need to have already been declared. Adding a new role may involve adding a new element to the DTD and may require extensive support, therefore such additions should be well thought-out. There should be a limited number of roles. The only place where no limit is placed on variation is at the start, at the Reader/Parser interface. Transforms are inserted by the Reader into the Transformer's queue, where non-standard elements are converted. Once past the Transformer, no variation from the standard Docutils doctree is possible. An example is the Python Source Reader, which will use interpreted text extensively. The default role will be "Python identifier", which will be further interpreted by namespace context into , , , , etc. elements (see pysource.dtd), which will be transformed into standard hyperlink references, which will be processed by the various Writers. No Writer will need to have any knowledge of the Python-Reader origin of these elements. * Add explicit interpreted text roles for the rest of the implicit inline markup constructs: named-reference, anonymous-reference, footnote-reference, citation-reference, substitution-reference, target, uri-reference (& synonyms). * Add directives for each role as well? This would allow indirect nested markup:: This text contains |nested inline markup|. .. |nested inline markup| emphasis:: nested ``inline`` markup * Implement roles: - "_`raw-wrapped`" (or "_`raw-wrap`"): Base role to wrap raw text around role contents. For example, the following reStructuredText source ... :: .. role:: red(raw-formatting) :prefix: :html: :latex: {\color{red} :suffix: :html: :latex: } colored :red:`text` ... will yield the following document fragment:: colored {\color{red} text } Possibly without the intermediate "inline" node. - _`"acronym" and "abbreviation"`: Associate the full text with a short form. Jason Diamond's description: I want to translate ```reST`:acronym:`` into ``reST``. The value of the title attribute has to be defined out-of-band since you can't parameterize interpreted text. Right now I have them in a separate file but I'm experimenting with creating a directive that will use some form of reST syntax to let you define them. Should Docutils complain about undefined acronyms or abbreviations? What to do if there are multiple definitions? How to differentiate between CSS (Content Scrambling System) and CSS (Cascading Style Sheets) in a single document? David Priest responds, The short answer is: you don't. Anyone who did such a thing would be writing very poor documentation indeed. (Though I note that `somewhere else in the docs`__, there's mention of allowing replacement text to be associated with the abbreviation. That takes care of the duplicate acronyms/abbreviations problem, though a writer would be foolish to ever need it.) __ `inline parameter syntax`_ How to define the full text? Possibilities: 1. With a directive and a definition list? :: .. acronyms:: reST reStructuredText DPS Docstring Processing System Would this list remain in the document as a glossary, or would it simply build an internal lookup table? A "glossary" directive could be used to make the intention clear. Acronyms/abbreviations and glossaries could work together. Then again, a glossary could be formed by gathering individual definitions from around the document. 2. Some kind of `inline parameter syntax`_? :: `reST `:acronym: is `WYSIWYG `:acronym: plaintext markup. .. _inline parameter syntax: rst/alternatives.html#parameterized-interpreted-text 3. A combination of 1 & 2? The multiple definitions issue could be handled by establishing rules of priority. For example, directive-based lookup tables have highest priority, followed by the first inline definition. Multiple definitions in directive-based lookup tables would trigger warnings, similar to the rules of `implicit hyperlink targets`__. __ ../ref/rst/restructuredtext.html#implicit-hyperlink-targets 4. Using substitutions? :: .. |reST| acronym:: reST :text: reStructuredText What do we do for other formats than HTML which do not support tool tips? Put the full text in parentheses? - "figure", "table", "listing", "chapter", "page", etc: See `object numbering and object references`_ above. - "glossary-term": This would establish a link to a glossary. It would require an associated "glossary-entry" directive, whose contents could be a definition list:: .. glossary-entry:: term1 definition1 term2 definition2 This would allow entries to be defined anywhere in the document, and collected (via a "glossary" directive perhaps) at one point. Doctree pruning --------------- The number of doctree nodes can be reduced by "normalizing" some related nodes. This makes the document model and the writers somewhat simpler. * The "doctest" element should go away. The construct could simply be a front-end to generic literal blocks. We could immediately (in 0.7) remove the doctest node from the doctree, but leave the syntax in reST. The reST parser could represent doctest blocks as literal blocks with a class attribute. The syntax could be left in reST (for a set period of time?). * "Normalize" special admonitions (note, hint, warning, ...) during parsing (similar to _`transforms.writer_aux.Admonitions`). There is no need to keep them as distinct elements in the doctree specification. Keep the special admonition directives in reStructuredText syntax? Unimplemented Transforms ======================== * _`Footnote & Citation Gathering` Collect and move footnotes & citations to the end of a document or the place of a "footnotes" or "citations" directive (see `<./ref/rst/directives.html>_`) Footnotes: Collect all footnotes that are referenced in the document before the directive (and after an eventually preceding ``.. footnotes::`` directive) and insert at this place. Allows "endnotes" at a configurable place. Citations: Collect citations that are referenced ... Citations can be: a) defined in the document as citation elements b) auto-generated from entries in a bibliographic database. + based on bibstuff_? + also have a look at * CrossTeX_, a backwards-compatible, improved bibtex re-implementation in Python (including HTML export). (development stalled since 2 years) * Pybtex_,a drop-in replacement for BibTeX written in Python. * BibTeX styles & (experimental) pythonic style API. * Database in BibTeX, BibTeXML and YAML formats. * full Unicode support. * Write to TeX, HTML and plain text. * `Zotero plain `__ supports Zotero databases and CSL_ styles with Docutils with an ``xcite`` role. * `sphinxcontrib-bibtex`_ Sphinx extension with "bibliography" directive and "cite" role supporting BibTeX databases. * `Modified rst2html `__ by Nicolas Rougier. * Automatically insert a "References" heading? .. _CrossTeX: http://www.cs.cornell.edu/people/egs/crosstex/ .. _Pybtex: http://pybtex.sourceforge.net/ .. _CSL: http://www.citationstyles.org/ .. _sphinxcontrib-bibtex: http://sphinxcontrib-bibtex.readthedocs.org/ * _`Reference Merging` When merging two or more subdocuments (such as docstrings), conflicting references may need to be resolved. There may be: * duplicate reference and/or substitution names that need to be made unique; and/or * duplicate footnote numbers that need to be renumbered. Should this be done before or after reference-resolving transforms are applied? What about references from within one subdocument to inside another? * _`Document Splitting` If the processed document is written to multiple files (possibly in a directory tree), it will need to be split up. Internal references will have to be adjusted. (HTML only? Initially, yes. Eventually, anything should be splittable.) Ideas: - Insert a "destination" attribute into the root element of each split-out document, containing the path/filename. The Output object or Writer will recognize this attribute and split out the files accordingly. Must allow for common headers & footers, prev/next, breadcrumbs, etc. - Transform a single-root document into a document containing multiple subdocuments, recursively. The content model of the "document" element would have to change to:: (I.e., add the last line -- 0 or more document elements.) Let's look at the case of hierarchical (directories and files) HTML output. Each document element containing further document elements would correspond to a directory (with an index.html file for the content preceding the subdocuments). Each document element containing no subdocuments (i.e., structure model elements only) corresponds to a concrete file with no directory. The natural transform would be to map sections to subdocuments, but possibly only a given number of levels deep. * _`Navigation` If a document is split up, each segment will need navigation links: parent, children (small TOC), previous (preorder), next (preorder). Part of `Document Splitting`_? * _`List of System Messages` The ``system_message`` elements are inserted into the document tree, adjacent to the problems themselves where possible. Some (those generated post-parse) are kept until later, in ``document.messages``, and added as a special final section, "Docutils System Messages". Docutils could be made to generate hyperlinks to all known system_messages and add them to the document, perhaps to the end of the "Docutils System Messages" section. Fred L. Drake, Jr. wrote: I'd like to propose that both parse- and transformation-time messages are included in the "Docutils System Messages" section. If there are no objections, I can make the change. The advantage of the current way of doing things is that parse-time system messages don't require a transform; they're already in the document. This is valuable for testing (unit tests, tools/quicktest.py). So if we do decide to make a change, I think the insertion of parse-time system messages ought to remain as-is and the Messages transform ought to move all parse-time system messages (remove from their originally inserted positions, insert in System Messages section). * _`Index Generation` HTML Writer =========== * Make it easier to find out fragment names (#foo-bar) of ``_`inline targets```. Currently you have to either look at the source or guess the fragment. For example, we could add support for self-referencing targets (i.e. inline targets would [unobtrusively] link to themselves, so that you can just click them and then copy the address). Or we could add support for titles that display the fragment name (as in ; just hover the paragraphs). Either way it should be optional and deactivated by default. This would be useful for documents like Docutils' bug list or to-do list. * Make the _`list compacting` logic more generic: For example, allow for literal blocks or line blocks inside of compact list items. This is not implementable as long as list compacting is done by omitting ``

`` tags. List compacting would need to be done by adjusting CSS margins instead. * Idea for field-list rendering: hanging indent:: Field name (bold): First paragraph of field body begins with the field name inline. If the first item of a field body is not a paragraph, it would begin on the following line. * Add more support for elements, especially for navigation bars. The framework does not have a notion of document relationships, so probably raw.destination_ should be used. We'll have framework support for document relationships when support for `multiple output files`_ is added. The HTML writer could automatically generate elements then. .. _raw.destination: misc.raw_ * Base list compaction on the spacing of source list? Would require parser support. (Idea: fantasai, 16 Dec 2002, doc-sig.) * Add a tool tip ("title" attribute?) to footnote back-links identifying them as such. Text in Docutils language module. PEP/HTML Writer =============== * Remove the generic style information (duplicated from html4css1.css) from pep.css to avoid redundancy. Needs support for multiple stylesheets in the PEP writer (is this inherited from HTML?). S5/HTML Writer ============== * Add a way to begin an untitled slide. * Add a way to begin a new slide, continuation, using the same title as the previous slide? (Unnecessary?) You need that if you have a lot of items in one section which don't fit on one slide. Maybe either this item or the previous one can be realized using transitions. * Have a timeout on incremental items, so the colour goes away after 1 second. * Add an empty, black last slide (optionally). Currently the handling of the last slide is not very nice, it re-cycles through the incremental items on the last slide if you hit space-bar after the last item. * Add a command-line option to disable advance-on-click. * Add a speaker's master document, which would contain a small version of the slide text with speaker's notes interspersed. The master document could use ``target="whatever"`` to direct links to a separate window on a second monitor (e.g., a projector). .. Note:: This item and the following items are partially accomplished by the S5 1.2 code (currently in alpha), which has not yet been integrated into Docutils. * Speaker's notes -- how to intersperse? Could use reST comments (".."), but make them visible in the speaker's master document. If structure is necessary, we could use a "comment" directive (to avoid nonsensical DTD changes, the "comment" directive could produce an untitled topic element). The speaker's notes could (should?) be separate from S5's handout content. * The speaker's master document could use frames for easy navigation: TOC on the left, content on the right. - It would be nice if clicking in the TOC frame simultaneously linked to both the speaker's notes frame and to the slide window, synchronizing both. Needs JavaScript? - TOC would have to be tightly formatted -- minimal indentation. - TOC auto-generated, as in the PEP Reader. (What if there already is a "contents" directive in the document?) - There could be another frame on the left (top-left or bottom-left) containing a single "Next" link, always pointing to the next slide (synchronized, of course). Also "Previous" link? FF/Rew go to the beginning of the next/current parent section? First/Last also? Tape-player-style buttons like ``|<< << < > >> >>|``? Epub/HTML Writer ================ Add epub as an output format. Pack the output of a HTML writer and supporting files (e.g. images) into one single epub document. epub is an open file format for ebooks based on HTML, specified by the `International Digital Publishing Forum`_. Thus, documents in epub format are suited to be read with `electronic reading devices`_. The epub format comprises: * `Open Publication Structure (OPS) `_ * `Open Packaging Format (OPF) `_ * `OEBPS Container Format (OCF) `_ -- rst2epub_ README There is a project for epub support with sphinx providing a (hopefully) reusable framework. .. _rst2epub: http://bitbucket.org/wierob/rst2epub/ .. _International Digital Publishing Forum: http://www.idpf.org/ .. _electronic reading devices: http://en.wikipedia.org/wiki/List_of_e-book_readers Also, the plasTeX_ Python package has an EPUB renderer: It simply calls the XHTML renderer and does the epub packaging in postprocessing. .. _plasTeX: http://plastex.sourceforge.net/ LaTeX writer ============ Also see the Problems__ section in the `latex writer documentation`_. __ ../user/latex.html#problems .. _latex writer documentation: ../user/latex.html .. _latex-variants: ../../../sandbox/latex-variants/README.html Bug fixes --------- * A multirow cell in a table expects empty cells in the spanned rows while the doctree contains only the remaining cells ("Exchange Table Model", see docs/ref/soextblx.dtd). Needs bookkeeping of "open" multirow cells (how many how long) and insertion of additional '&'s. See `<../../test/functional/input/data/latex.txt>`__ * Too deeply nested lists fail: generate a warning and provide a workaround. * Spaces in inline literal text:: Now note the spacing between the words of this sentence (words should be grouped in pairs). Discuss the desired behaviour and implement a consistent one. * An enumerated list in the docinfo fails (\newcounter definition inside tabularx). * File names of included graphics (see also `grffile` package). Generate clean and configurable LaTeX source ---------------------------------------------- * Check the generated source with package `nag`. Configurable placement of figure and table floats ````````````````````````````````````````````````` * Special class argument to individually place figures? Either: placement- -> \figure[]{...} e.g. ``.. class:: placement-htb``, or more verbose: :H: place-here :h: place-here-if-possible :t: place-top :b: place-bottom :p: place-on-extra-page e.g.: ``.. class:: place-here-if-possible place-top place-bottom`` Maybe support both variants? LaTeX constructs and packages instead of re-implementations ``````````````````````````````````````````````````````````` Which packages do we want to use? + base and "recommended" packages (packages that should be in a "reasonably sized and reasonably modern LaTeX installation like the `texlive-latex-recommended` Debian package, say): + No "fancy" or "exotic" requirements. + pointers to advanced packages and their use in the `latex writer documentation`_. * ``alltt`` environment for literal block. * footnotes + True footnotes with LaTeX auto-numbering (as option ``--latex-footnotes``) (also for target-footnotes): - attach footnote text to footnote-symobol node - write \footnote{} - consider cases where LaTeX does not support footnotes (inside tables, headings, ...)? - consider multiple footnote refs to common footnote text. .. Quote: If the symbol you want is not one of the ones listed, you'll need to redefine ``\@fnsymbol`` and add it, e.g. perhaps like:: \def\@fnsymbol#1{\ifcase#1\hbox{}\or *\or \dagger\or \ddagger\or \mathchar "278\or \mathchar "27B\or \|\or **\or \dagger\dagger \or \ddagger\ddagger \or \mathchar"27C \else\@ctrerr\fi\relax} which would allow \symbolfootnote[10]{footnote} to have a club as its mark. + document customization (links to how-to and packages): .. Footnote packages: :footnote: texlive-latex-recommended % savenotes environment :footmisc: texlive-latex-extra % formatting options :manyfoot: texlive-latex-extra :bigfoot: texlive-latex-extra :perpage: texlive-latex-extra :ftnxtra: new on CTAN fixes the issue of footnote inside \caption{}, tabular environment and \section{} like commands. German tutorial: http://www2.informatik.hu-berlin.de/~ahamann/studies/footnotes.pdf .. Footnote FAQs: `Footnotes whose texts are identical `__ * label per hand or use footmisc `More than one sequence of footnotes `__ * manyfoot, bigfoot `Footnotes in tables `__ * `tabularx` and longtable allow footnotes. * `footnote` provides a "savenotes" environment which collects all footnotes and emits them at ``end{savenotes}`` `Footnotes in LaTeX section headings `__ * Take advantage of the fact that the mandatory argument doesn't move if the optional argument is present:: \section[title] {title\footnote{title ftnt}} * Use the footmisc package, with package option stable - this modifies footnotes so that they softly and silently vanish away if used in a moving argument. * Use ftnxtra. `Footnotes numbered per page `__ * perpage provides a general mechanism for resetting counters per page * footmisc provides a package option perpage * enumeration environment, field list * use `mdwlist` from texlive-latex-recommended? * use `eqlist` (texlive-latex-extra) for field-lists? * ``--use-latex-when-possible`` »super option« that would set the following:: --no-section-numbering --use-latex-toc --use-latex-docinfo --use-latex-abstract --use-latex-footnotes --use-latex-citations ? (My preference is to default to use-latex-* whenever possible [GM]) Default layout -------------- * Use italic instead of slanted for titlereference? * Start a new paragraph after lists (as currently) or continue (no blank line in source, no parindent in output)? Overriding: * continue if the `compound paragraph`_ directive is used, or * force a new paragraph with an empty comment. * Sidebar handling (environment with `framed`, `marginnote`, `wrapfig`, ...)? * Use optionlist for docinfo? * Keep literal-blocks together on a page, avoid pagebreaks. Failed experiments up to now: samepage, minipage, pagebreak 1 to 4 before the block. Should be possible with ``--literal-block-env==lstlistings`` and some configuration... * More space between title and subtitle? :: - \\ % subtitle% + \\[0.5em] % subtitle% .. _PSNFSS documentation: http://mirror.ctan.org/macros/latex/required/psnfss/psnfss2e.pdf .. _compound paragraph: ../ref/rst/directives.html#compound-paragraph .. _fixltx2e: http://mirror.ctan.org/help/Catalogue/entries/fixltx2e.html Tables `````` * Improve/simplify logic to set the column width in the output. + Assumed reST line length for table width setting configurable, or + use `ltxtable` (a combination of `tabularx` (auto-width) and `longtable` (page breaks)), or + use tabularx column type ``X`` and let LaTeX decide width, or + use tabulary_? .. _tabulary: http://tug.ctan.org/cgi-bin/ctanPackageInformation.py?id=tabulary * From comp.text.tex (13. 4. 2011): When using fixed width columns, you should ensure that the total width does not exceed \linewidth: if the first column is p{6cm} the second one should be p{\dimexpr\linewidth-6cm-4\tabcolsep} because the glue \tabcolsep is added twice at every column edge. You may also consider to set \tabcolsep to a different value... * csv-tables do not have a colwidth. * Add more classes or options, e.g. for + column width set by latex, + horizontal alignment and rules. + long table vs. tabular (see next item). * Use tabular instead of longtable for tables in legends or generally inside a float? Alternatively, default to tabular and use longtable only if specified by config setting or class argument (analogue to booktable)? * Table heads and footer for longtable (firstpage lastpage ..)? * In tools.txt the option tables right column, there should be some more spacing between the description and the next paragraph "Default:". * Paragraph separation in tables is hairy. see http://www.tex.ac.uk/cgi-bin/texfaq2html?label=struttab - The strut solution did not work. - setting extrarowheight added ad top of row not between paragraphs in a cell. ALTHOUGH i set it to 2pt because, text is too close to the topline. - baselineskip/stretch does not help. * Should there be two hlines after table head and on table end? * Place titled tables in a float ('table' environment)? The 'table', 'csv-table', and 'list-table' directives support an (optional) table title. In analogy to the 'figure' directive this should map to a table float. Image and figure directives ``````````````````````````` * compare the test case in: + `<../../test/functional/input/data/standard.txt>`__ + `<../../test/functional/expected/standalone_rst_html4css1.html>`__ + `<../../test/functional/expected/standalone_rst_latex.tex>`__ * According to the HTML standard http://www.w3.org/TR/html4/struct/objects.html#adef-align-IMG a right- or left-aligned image should be floated alongside the paragraph. + Use this default also for LaTeX? + Wrap text around figures/images with class argument "wrap" (like the odt writer)? Use `wrapfig` (or other recommended) package. * support more graphic formats (especially SVG, the only standard vector format for HTML) There is a `SWF package`_ at CTAN. .. _SWF package: http://mirror.ctan.org/macros/latex/contrib/flashmovie Missing features ---------------- * support "figwidth" argument for figures. As the 'figwidth' argument is still ignored and the "natural width" of a figure in LaTeX is 100 % of the text width, setting the 'align' argument has currently no effect on the LaTeX output. * Let `meta` directive insert PDF-keywords into header? * Multiple author entries in docinfo (same thing as in html). (already solved?) * Consider supporting the "compact" option and class argument (from rst2html) as some lists look better compact and others need the space. * Better citation support (see `Footnote & Citation Gathering`_). * If ``use-latex-citations`` is used, a bibliography is inserted right at the end of the document. Put in place of the to-be-implemented "citations" directive (see `Footnote & Citation Gathering`_). Unicode to LaTeX ```````````````` The `LyX `_ document processor has a comprehensive Unicode to LaTeX conversion feature with a file called ``unicodesymbols`` that lists LaTeX counterparts for a wide range of Unicode characters. * Use this in the LaTeXTranslator? Think of copyright issues! * The "ucs" package has many translations in ...doc/latex/ucs/config/ * The bibstuff_ tool ships a `latex_codec` Python module! .. _bibstuff: http://code.google.com/p/bibstuff/ Allow choice between utf8 (standard) and utf8x (extended) encodings ``````````````````````````````````````````````````````````````````` * Allow the user to select *utf8* or *utf8x* LaTeX encoding. (Docutil's output encoding becomes LaTeX's input encoding.) The `ucs` package provides extended support for UTF-8 encoding in LaTeX via the `inputenc`-option ``utf8x``. It is, however, a non-standard extension and no longer developed. Ideas: a) Python has 4 names for the UTF-8 encoding (``utf_8, U8, UTF, utf8``) give a special meaning to one of the aliases, b) scan "stylesheets" and "latex-preamble" options and use ``utf8x`` if it contains ``ucs`` XeTeX writer ```````````` * Glyphs missing in the font are left out in the PDF without warning (e.g. ⇔ left-right double arrow in the functional test output). * Disable word-wrap (hyphenation) in literal text locally with ``providecommand{\nohyphenation}{\addfontfeatures{HyphenChar=None}}``? problematic URLs ```````````````` * ^^ LaTeX's special syntax for characters results in "strange" replacements (both with \href and \url). `file with ^^ <../strange^^name>`__: `<../strange^^name>`__ * Unbalanced braces, { or }, will fail (both with \href and \url):: `file with { <../strange{name>`__ `<../strange{name>`__ Currently, a warning is written to the error output stream. For correct printing, we can * use the \href command with "normal" escaped name argument, or * define a url-command in the preamble :: \urldef{\fragileURLi}\nolinkurl{myself%node@gateway.net} but need to find a way to insert it as href argument. The following fails:: \href{http://www.w3.org/XML/Schema^^dev}{\fragileURLi} Use %-replacement like http://nowhere/url_with%28parens%29 ? -> does not work for file paths (with pdflatex and xpdf). add-stylesheet option ````````````````````` From http://article.gmane.org/gmane.text.docutils.devel/3429/ The problem is that since we have a default value, we have to differentiate between adding another stylesheet and replacing the default. I suggest that the existing --stylesheet & --stylesheet-path options keep their semantics to replace the existing settings. We could introduce new --add-stylesheet & --add-stylesheet-path options, which accumulate; further --stylesheet/--stylesheet-path options would clear these lists. The stylesheet or stylesheet_path setting (only one may be set), plus the added_stylesheets and added_stylesheet_paths settings, describe the combined styles. For example, this run will have only one custom stylesheet: rstpep2html.py --stylesheet-path custom.css ... This run will use the default stylesheet, and the custom one: rstpep2html.py --add-stylesheet-path custom.css ... This run will use the default stylesheet, a custom local stylesheet, and an external stylesheet: rstpep2html.py --add-stylesheet-path custom.css \ --add-stylesheet http://www.example.org/external.css ... This run will use only the second custom stylesheet: rstpep2html.py --add-stylesheet-path custom.css \ --stylesheet-path second.css ... Front-End Tools =============== * What about if we don't know which Reader and/or Writer we are going to use? If the Reader/Writer is specified on the command-line? (Will this ever happen?) Perhaps have different types of front ends: a) _`Fully qualified`: Reader and Writer are hard-coded into the front end (e.g. ``pep2html [options]``, ``pysource2pdf [options]``). b) _`Partially qualified`: Reader is hard-coded, and the Writer is specified a sub-command (e.g. ``pep2 html [options]``, ``pysource2 pdf [options]``). The Writer is known before option processing happens, allowing the OptionParser to be built dynamically. Alternatively, the Writer could be hard-coded and the Reader specified as a sub-command (e.g. ``htmlfrom pep [options]``). c) _`Unqualified`: Reader and Writer are specified as subcommands (e.g. ``publish pep html [options]``, ``publish pysource pdf [options]``). A single front end would be sufficient, but probably only useful for testing purposes. d) _`Dynamic`: Reader and/or Writer are specified by options, with defaults if unspecified (e.g. ``publish --writer pdf [options]``). Is this possible? The option parser would have to be told about new options it needs to handle, on the fly. Component-specific options would have to be specified *after* the component-specifying option. Allow common options before subcommands, as in CVS? Or group all options together? In the case of the `fully qualified`_ front ends, all the options will have to be grouped together anyway, so there's no advantage (we can't use it to avoid conflicts) to splitting common and component-specific options apart. * Parameterize help text & defaults somehow? Perhaps a callback? Or initialize ``settings_spec`` in ``__init__`` or ``init_options``? * Disable common options that don't apply? (This should now be easier with ``frontend.filter_settings_spec``.) * Add ``--section-numbering`` command line option. The "sectnum" directive should override the ``--no-section-numbering`` command line option then. * Create a single dynamic_ or unqualified_ front end that can be installed? .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: docutils-0.12/docs/dev/release.txt0000664000175000017500000001371712170314423021121 0ustar engelbertengelbert00000000000000============================= Docutils_ Release Procedure ============================= :Authors: David Goodger; Lea Wiemann; open to all Docutils developers :Contact: docutils-develop@lists.sourceforge.net :Date: $Date: 2013-07-13 20:14:43 +0200 (Sam, 13. Jul 2013) $ :Revision: $Revision: 7686 $ :Copyright: This document has been placed in the public domain. .. _Docutils: http://docutils.sourceforge.net/ Assumptions and their failure ----------------------------- On the test machine python2.4, 2.5 2.6 2.7 and 3.2 are installed. Some in /usr/ some under /usr/local. Assumption: If python2.6 is in /usr/bin/ than site-packages is under /usr/local/lib/python2.6. On new ubuntu 12.10 * python2.7 is here /usr/bin/python2.7. * in /usr/lib are python2.7, pymodules and pyshared. in /usr/lib/python2.7 no site-packages directory even after installation of docutils in /usr/local/lib/python2.7 are dist-packages site-packages. site-packages is empty. docutils is installed under dist-packages. pymodules has a python2.7 directory. Releasing --------- REWORK FOR SOURCEFORGE REPO Steps in boldface text are *not* covered by the release script at sandbox/infrastructure/release.sh. "Not covered" means that you aren't even reminded of them. .. Note:: This document does not cover branching and tagging, but the release script does. .. Note:: You may want to use ReleaseForge_ instead of using SourceForge's file release system. .. _ReleaseForge: http://releaseforge.sourceforge.net/ * **On the Docutils-develop mailing list, announce that the release is going to be made, update the release notes and ask for additions.** Consult HISTORY.TXT for changes. * **Announce a check-in freeze on Docutils-develop.** Call ``sandbox/infrastructure/release.sh new_version svn_version``. For details see the script. ``new_version`` is the current version, status will change from ``repository`` to ``release``. ``svn_version`` is the version after release. .. Note:: *BUG* test tarball requires root password, but it is possible to skip this stage interactively, and testing should be done before release. * Change ``__version_details__`` in docutils/docutils/__init__.py to "release" (from "repository"). * Check the _`version number` in the following files, should be already correct: + docutils/setup.py + docutils/docutils/__init__.py + docutils/test/functional/expected/* ("Generator: Docutils X.Y.Z") + docutils/README.txt + web/index.txt * Close the "Changes Since ..." section in docutils/HISTORY.txt. * Clear/unset the PYTHONPATH environment variable. * Create the release tarball: (a) Create a new empty directory and ``cd`` into it. (b) Get a clean snapshot of the main tree:: svn export svn://svn.berlios.de/docutils/trunk/docutils (c) Use Distutils to create the release tarball:: cd docutils python setup.py sdist * Expand and _`install` the release tarball in isolation: (a) Expand the tarball in a new location, not over any existing files. (b) Remove the old installation from site-packages (including roman.py, and optparse.py, textwrap.py). "remove" might fail, see _`Assumptions and their failure` Install from expanded directory:: cd docutils-X.Y.Z python setup.py install The "install" command may require root permissions. (c) Repeat step b) for all supported Python versions. * Run the _`test suite` from the expanded archive directory with all supported Python versions on all available platforms (GNU/Linux, Mac OS X, Windows):: cd test ; python -u alltests.py * Add a directory X.Y.Z (where X.Y.Z is the current version number of Docutils) in the webroot (i.e. the ``htdocs/`` directory). Put all documentation files into it:: cd docutils-X.Y.Z rm -rf build cd tools/ ./buildhtml.py .. cd .. find -name test -type d -prune -o -name \*.css -print0 \ -o -name \*.html -print0 -o -name \*.txt -print0 \ | tar -cjvf docutils-docs.tar.bz2 -T - --null scp docutils-docs.tar.bz2 @shell.sourceforge.net: Now log in to shell.sourceforge.net and:: cd /home/groups/d/do/docutils/htdocs/ mkdir -m g+rwxs X.Y.Z cd X.Y.Z tar -xjvf ~/docutils-docs.tar.bz2 rm ~/docutils-docs.tar.bz2 * Upload the release tarball, release.sh tries with scp. * Access the _`file release system` on SourceForge (Admin interface). ``https://sourceforge.net/projects/docutils/files/docutils/`` * change into the released version's directory * click ``(i)`` button of the tar.gz-file * select as default download for all operating systems. * Submit a notification on project news. * For verifying the integrity of the release, download the release tarball (you may need to wait up to 30 minutes), install_ it, and re-run the `test suite`_. * Register with PyPI (``python setup.py register``). Set the download-url so eggs can access older releases. * Restore ``__version_details__`` in docutils/docutils/__init__.py to "repository" (from "release"). * Bump the `version number`_ again. * Add a new empty section "Changes Since ..." in HISTORY.txt. * Update the web page (web/index.txt). * Run docutils-update on the server. * **Run alltests.py with svn version** * **Send announcement email to:** * docutils-develop@lists.sourceforge.net (also announcing the end of the check-in freeze) * docutils-users@lists.sourceforge.net * doc-sig@python.org * python-announce@python.org * **Add a SourceForge News item, with title "Docutils X.Y.Z released" and containing the release tarball's download URL.** **Mark as default download for all platforms.** * **Register with freecode.** Add a new release for the `Docutils project`__. (freecode is freshmeat.net's new name) __ http://freecode.com/projects/docutils/ .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: docutils-0.12/docs/user/0000775000175000017500000000000012356234260017135 5ustar engelbertengelbert00000000000000docutils-0.12/docs/user/docutils-05-compat.sty.txt0000664000175000017500000005204211700652711024045 0ustar engelbertengelbert00000000000000================================================================== Changes to the Docutils latex2e writer since version 0.5 ================================================================== A backwards compatibility style sheet ************************************* :Author: Guenter Milde :Contact: docutils-develop@lists.sourceforge.net :Revision: $Revision: 7302 $ :Date: $Date: 2012-01-03 20:23:53 +0100 (Die, 03. Jän 2012) $ :Copyright: © 2009 Günter Milde, :License: Released under the terms of the `2-Clause BSD license`_, in short: Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty. :Abstract: This file documents changes and provides a style for best possible compatibility to the behaviour of the `latex2e` writer of Doctutils release 0.5. .. _2-Clause BSD license: http://www.spdx.org/licenses/BSD-2-Clause :: \NeedsTeXFormat{LaTeX2e} \ProvidesPackage{docutils-05-compat} [2009/03/26 v0.1 compatibility with rst2latex from Docutils 0.5] .. contents:: :depth: 3 Usage ===== * To get an (almost) identic look for your old documents, place ``docutils-05-compat.sty`` in the TEXINPUT path (e.g. the current work directory) and pass the ``--stylesheet=docutils-05-compat`` option to ``rst2latex.py``. * To use your custom stylesheets without change, add them to the compatibility style, e.g. ``--stylesheet="docutils-05-compat,mystyle.tex``. .. tip:: As the changes include bug fixes that are partly reverted by this style, it is recommended to adapt the stylesheets to the new version or copy just the relevant parts of this style into them. Changes since 0.5 ================= Bugfixes -------- * Newlines around comments, targets and references prevent run-together paragraphs. + An image directive with hyperlink reference or target did not start a new paragraph (e.g. the first two image examples in standalone_rst_latex.tex). + Paragraphs were not separated if there was a (hyper) target definition inbetween. + Paragraphs did run together, if separated by a comment-paragraph in the rst source. * Fixed missing and spurious internal links/targets. Internal links now take you to the correct place. * Verbose and linked system messages. * `Figure and image alignment`_ now conforms to the rst definition. * Put `header and footer directive`__ content in \DUheader respective \DUfooter macros (ignored by the default style/template). (They were put inside hard-coded markup at the top/bottom of the document without an option to get them on every page.) __ ../ref/rst/directives.html#document-header-footer * Render doctest blocks as literal blocks (fixes bug [1586058] doctest block nested in admonition). I.e. + indent doctest blocks by nesting in a quote environment. This is also the rendering by the HTML writer (html4css2.css). + apply the ``--literal-block-env`` setting also to doctest blocks. .. warning:: (``--literal-block-env=verbatim`` and ``--literal-block-env=lstlistings`` fail with literal or doctest blocks nested in an admonition. * Two-way hyperlinked footnotes and support for symbol footnotes and ``--footnote-references=brackets`` with ``--use-latex-footnotes``. * The packages `fixltx2e` (providing LaTeX patches and the \textsubscript command) and `cmap` (including character maps in the generated PDF for better search and copy-and-paste operations) are now always loaded (configurable with custom templates_). Backwards compatibility: "Bug for bug compatibility" is not provided. New configuration setting defaults ---------------------------------- - font-encoding: "T1" (formerly implicitely set by 'ae'). - use-latex-toc: true (ToC with page numbers). - use-latex-footnotes: true (no mixup with figures). Backwards compatibility: Reset to the former defaults with: | font-encoding: '' | use-latex-toc: False | use-latex-footnotes: False (in the config file) or the command line options: ``--figure-footnotes --use-docutils-toc --font-encoding=''`` Cleaner LaTeX source -------------------- New features: * Remove redundant "double protection" from the encoding of the "special printing characters" and square brackets, e.g. ``\%`` instead of ``{\%}``. * Remove some spurious whitespace, e.g. ``\item [what:] -> \item[what:]``. * Use conventional style for "named" macros, e.g. ``\dots{}`` instead of ``{\dots}`` Backwards compatibility: Changes do not affect the output. LaTeX style sheets ------------------ New Feature: LaTeX packages can be used as ``--stylesheet`` argument without restriction. Implementation: Use ``\usepackage`` if style sheet ends with ``.sty`` or has no extension and ``\input`` else. Rationale: while ``\input`` works with extension as well as without extension, ``\usepackage`` expects the package name without extension. (The latex2e writer will strip a ``.sty`` extension.) Backwards compatibility: Up to Docutils 0.5, if no filename extension is given in the ``stylesheet`` argument, ``.tex`` is assumed (by latex). Since Docutils 0.6, a stylesheet without filename extension is assumed to be a LaTeX package (``*.sty``) and referenced with the ``\usepackage`` command. .. important:: Always specify the extension if you want the style sheet to be ``\input`` by LaTeX. Templates --------- New Feature: Advanced configuration via custom templates. Implementation: A ``--template`` option and config setting allows specification of a template file. See the `LaTeX writer documentation`__ for details. __ latex.html#templates Custom roles ------------ New Feature: failsave implementation As with classes to HTML objects, class arguments are silently ignored if there is no styling rule for this class in a custom style sheet. New Feature: custom roles based on standard roles As class support needs to be handled by the LaTeX writer, this feature was not present "automatically" (as in HTML). Modified visit/depart_*() methods for the standard roles now call visit/depart_inline() if there are class arguments to the node. Backwards compatibility: The implementation is fully backwards compatible. (SVN versions 5742 to 5861 contained an implementation that did not work with commands expecting an argument.) Length units ------------ New Features: 1. Add default unit if none given. A poll on docutils-users favoured ``bp`` (Big Point: 1 bp = 1/72 in). 2. Do not change ``px`` to ``pt``. 3. Lengths specified in the document with unit "pt" will be written with unit "bp" to the LaTeX source. Rationale: 1. prevent LaTeX error "missing unit". 2. ``px`` is a valid unit in pdftex since version 1.3.0 released on 2005-02-04: 1px defaults to 1bp (or 72dpi), but can be changed with the ``\pdfpxdimen`` primitive.:: \pdfpxdimen=1in % 1 dpi \divide\pdfpxdimen by 96 % 96 dpi -- http://www.tug.org/applications/pdftex/NEWS Modern TeX distributions use pdftex also for dvi generation (i.e. ``latex`` actually calls ``pdftex`` with some options). 3. In Docutils (as well as CSS) the unit symbol "pt" denotes the `Postscript point` or `DTP point` while LaTeX uses "pt" for the `LaTeX point`, which is unknown to Docutils and 0.3 % smaller. The `DTP point` is available in LaTeX as "bp" (big point): 1 pt = 1/72.25 in < 1 bp = 1/72 in Backwards compatibility: Images with width specification in ``px`` come out slightly (0.3 %) larger: 1 px = 1 bp = 1/72 in > 1 pt = 1/72.25 in This can be reset with :: \pdfpxdimen=1pt .. caution:: It is impossible to revert the change of lengths specified with "pt" or without unit in a style sheet, however the 0.3 % change will be imperceptible in most cases. .. admonition:: Error ``illegal unit px`` The unit ``px`` is not defined in "pure" LaTeX, but introduced by the `pdfTeX` converter on 2005-02-04. `pdfTeX` is used in all modern LaTeX distributions (since ca. 2006) also for conversion into DVI. If you convert the LaTeX source with a legacy program, you might get the error ``illegal unit px``. If updating LaTeX is not an option, just remove the ``px`` from the length specification. HTML/CSS will default to ``px`` while the `latexe2` writer will add the fallback unit ``bp``. Font encoding ------------- New feature: Do not mix font-encoding and font settings: do not load the obsolete `ae` and `aeguill` packages unless explicitely required via the ``--stylesheet`` option. :font-encoding = "": do not load `ae` and `aeguill`, i.e. * do not change font settings, * do not use the fontenc package (implicitely loaded via `ae`), * use LaTeX default font encoding (OT1) :font-encoding = "OT1": load `fontenc` with ``\usepackage[OT1]{fontenc}`` Example: ``--font-encoding=LGR,T1`` becomes ``\usepackage[LGR,T1]{fontenc}`` (Latin, Latin-1 Supplement, and Greek) Backwards compatibility: Load the ae and aeguill packages if fontenc is not used. .. tip:: Using `ae` is not recommended. A similar look (but better implementation) can be achieved with the packages `lmodern`, `cmsuper`, or `cmlgr` all providing Computer Modern look-alikes in vector format and T1 encoding, e.g. ``--font-encoding=T1 --stylesheet=lmodern``. Sub- and superscript as text ---------------------------- New feature: Set sub- and superscript role argument in text mode not as math. Pass the role content to ``\textsubscript`` or ``\textsuperscript``. Backwards compatibility: The old implementation set the role content in Math mode, where * whitespace is ignored, * a different command set and font setting scheme is active, * Latin letters are typeset italic but numbers upright. Although it is possible to redefine ``\textsubscript`` and ``\textsuperscript`` to typeset the content in math-mode, this can lead to errors with certain input and is therefore not done in this style sheet. .. tip:: To get italic subscripts, define and use in your document `custom roles`_ like ``.. role:: sub(subscript)`` and ``.. role:: super(superscript)`` and define the "role commands":: \newcommand{\DUrolesub}{\itshape} \newcommand{\DUrolesuper}{\itshape} Alternatively, if you want all sub- and superscripts in italic, redefine the macros:: %% \let\DUsup\textsubscript %% \let\DUsuper\textsuperscript %% \renewcommand*{\textsubscript}{\DUsub\itshape} %% \renewcommand*{\textsuperscript}{\DUsuper\itshape} This is not fully backwards compatible, as it will also set numbers in italic shape and not ignore whitespace. Page layout ----------- New features: * Margins are configurable via the ``DIV=...`` document option. * The ``\raggedbottom`` setting is no longer inserted into the document. It is the default for article and report classes. If requested in combination with a book class, it can be given in a custom style sheet. Backwards compatibility: Up to version 0.5, use of `typearea` and a DIV setting of 12 were hard-coded into the latex2e writer :: \usepackage{typearea} \typearea{12} and the vertical alignment of lower boundary of the text area in book classes disabled via :: \raggedbottom ToC and section numbers ----------------------- Better conformance to Docutils specifications. New feature: * The "depth" argument of the "contents" and "sectnum" directives is respected. * section numbering independent of 'use-latex-toc': + sections are only numbered if there is a "sectnum" directive in the document + section numbering by LaTeX if the "sectnum_xforms" config setting is False. Backwards compatibility: The previous behaviour was to always number sections if 'use-latex-toc' is true, using the document class defaults. It cannot be restored universally, the following code sets the default values of the "article" document class:: \setcounter{secnumdepth}{3} \setcounter{tocdepth}{3} .. TODO or not to do? (Back-compatibility problems) * The default "depth" of the LaTeX-created ToC and the LaTeX section numbering is increased to the number of supported section levels. New feature: If 'use-latex-toc' is set, local tables of content are typeset using the 'minitoc' package (instead of being ignored). Backwards compatibility: Disable the creation of local ToCs (ignoring all special commands) by replacing ``\usepackage{minitoc} with ``\usepackage{mtcoff}``. Default font in admonitions and sidebar --------------------------------------- New feature: Use default font in admonitions and sidebar. Backward compatibility: See the fallback definitions for admonitions_, `topic title`_ and `sidebar`_. Figure placement ---------------- New feature: Use ``\floatplacement`` from the `float` package instead of "hard-coded" optional argument for the global setting. Default to ``\floatplacement{figure}{H}`` (here definitely). This corresponds most closely to the source and HTML placement (principle of least surprise). Backwards compatibility: Set the global default back to the previous used value:: \usepackage{float} \floatplacement{figure}{htbp} % here, top, bottom, extra-page Figure and image alignment -------------------------- New features: a) Fix behaviour of 'align' argument to a figure (do not align figure contents). As the 'figwidth' argument is still ignored and the "natural width" of a figure in LaTeX is 100% \textwidth, setting the 'align' argument of a figure has currently no effect on the LaTeX output. b) Set default align of image in a figure to 'center'. c) Also center images that are wider than textwidth. d) Align images with class "align-[right|center|left]" (allows setting the alignment of an image in a figure). Backwards compatibility: There is no "automatic" way to reverse these changes via a style sheet. a) The alignment of the image can be set with the "align-left", "align-center" and "align-right" class arguments. As previously, the caption of a figure is aligned according to the document class -- configurable with a style sheet using the "caption" package. b) See a) c) Set the alignment of "oversized" images to "left" to get back the old placement. Shorter preamble ---------------- New feature: The document preamble is pruned to contain only relevant commands and settings. Packages that are no longer required ```````````````````````````````````` The following packages where required in pre-0.5 versions and still loaded with version 0.5:: \usepackage{shortvrb} \usepackage{amsmath} Packages that are conditionally loaded `````````````````````````````````````` Additional to the `typearea` for `page layout`_, the following packages are only loaded if actually required by doctree elements: Tables ^^^^^^ Standard package for tables across several pages:: \usepackage{longtable} Extra space between text in tables and the line above them ('array' is implicitely loaded by 'tabularx', see below):: \usepackage{array} \setlength{\extrarowheight}{2pt} Table cells spanning multiple rows:: \usepackage{multirow} Docinfo ^^^^^^^ One-page tables with auto-width columns:: \usepackage{tabularx} Images ^^^^^^ Include graphic files:: \usepackage{graphicx} Problematic, Sidebar ^^^^^^^^^^^^^^^^^^^^ Set text and/or background colour, coloured boxes with ``\colorbox``:: \usepackage{color} Floats for footnotes settings ````````````````````````````` Settings for the use of floats for footnotes are only included if * the option "use-latex-footnotes" is False, and * there is at least one footnote in the document. :: % begin: floats for footnotes tweaking. \setlength{\floatsep}{0.5em} \setlength{\textfloatsep}{\fill} \addtolength{\textfloatsep}{3em} \renewcommand{\textfraction}{0.5} \renewcommand{\topfraction}{0.5} \renewcommand{\bottomfraction}{0.5} \setcounter{totalnumber}{50} \setcounter{topnumber}{50} \setcounter{bottomnumber}{50} % end floats for footnotes Special lengths, commands, and environments ------------------------------------------- Removed definitions ``````````````````` admonition width ^^^^^^^^^^^^^^^^ The ``admonitionwith`` lenght is replaced by the more powerful ``\DUadmonition`` command (see admonitions_). Backwards compatibility: The default value (90 % of the textwidth) is unchanged. To configure the admonition width, you must redefine the ``DUadmonition`` command instead of changing the ``admonitionwith`` length value. Renamed definitions (now conditional) ````````````````````````````````````` The names for special doctree elements are now prefixed with ``DU``. Up to version 0.5, all definitions were included in the preamble (before the style sheet) of every document -- even if not used in the body. Since version 0.6, fallback definitions are included after the style sheet and only if required. Customization is done by an alternative definition in a style sheet with ``\newcommand`` instead of the former ``\renewcommand``. The following code provides the old definitions and maps them (or their custom variants) to the new interface. docinfo width ^^^^^^^^^^^^^ :: \newlength{\docinfowidth} \setlength{\docinfowidth}{0.9\textwidth} \newlength{\DUdocinfowidth} \AtBeginDocument{\setlength{\DUdocinfowidth}{\docinfowidth}} line block ^^^^^^^^^^ :: \newlength{\lineblockindentation} \setlength{\lineblockindentation}{2.5em} \newenvironment{lineblock}[1] {\begin{list}{} {\setlength{\partopsep}{\parskip} \addtolength{\partopsep}{\baselineskip} \topsep0pt\itemsep0.15\baselineskip\parsep0pt \leftmargin#1} \raggedright} {\end{list}} \newlength{\DUlineblockindent} \AtBeginDocument{\setlength{\DUlineblockindent}{\lineblockindentation}} \newenvironment{DUlineblock}[1] {\begin{lineblock}{#1}} {\end{lineblock}} local line width ^^^^^^^^^^^^^^^^ The ``\locallinewidth`` length for internal use in tables is replaced by ``\DUtablewidth``. It was never intended for customization:: \newlength{\locallinewidth} option lists ^^^^^^^^^^^^ :: \newcommand{\optionlistlabel}[1]{\bf #1 \hfill} \newenvironment{optionlist}[1] {\begin{list}{} {\setlength{\labelwidth}{#1} \setlength{\rightmargin}{1cm} \setlength{\leftmargin}{\rightmargin} \addtolength{\leftmargin}{\labelwidth} \addtolength{\leftmargin}{\labelsep} \renewcommand{\makelabel}{\optionlistlabel}} }{\end{list}} \newcommand{\DUoptionlistlabel}{\optionlistlabel} \newenvironment{DUoptionlist} {\begin{optionlist}{3cm}} {\end{optionlist}} rubric ^^^^^^ Now less prominent (not bold, normal size) restore with:: \newcommand{\rubric}[1]{\subsection*{~\hfill {\it #1} \hfill ~}} \newcommand{\DUrubric}[2][class-arg]{\rubric{#2}} title reference role ^^^^^^^^^^^^^^^^^^^^ :: \newcommand{\titlereference}[1]{\textsl{#1}} \newcommand{\DUroletitlereference}[1]{\titlereference{#1}} New definitions ``````````````` New Feature: Enable customization of some more Docutils elements with special commands :admonition: ``DUadmonition`` command (replacing ``\admonitionwidth``), :field list: ``DUfieldlist`` environment, :legend: ``DUlegend`` environment, :sidebar: ``\DUsidebar``, ``\DUtitle``, and ``DUsubtitle`` commands, :topic: ``\DUtopic`` and ``\DUtitle`` commands, :transition: ``\DUtransition`` command. :footnotes: ``\DUfootnotemark`` and ``\DUfootnotetext`` commands with hyperlink support using the Docutils-provided footnote label. Backwards compatibility: In most cases, the default definition corresponds to the previously used construct. The following definitions restore the old behaviour in case of changes. admonitions ^^^^^^^^^^^ Use sans-serif fonts:: \newcommand{\DUadmonition}[2][class-arg]{% \begin{center} \fbox{\parbox{0.9\textwidth}{\sffamily #2}} \end{center} } dedication ^^^^^^^^^^ Do not center:: \newcommand{\DUtopicdedication}[1]{#1} But center the title:: \newcommand*{\DUtitlededication}[1]{\centerline{\textbf{#1}}} sidebar ^^^^^^^ Use sans-serif fonts, a frame, and a darker shade of grey:: \providecommand{\DUsidebar}[2][class-arg]{% \begin{center} \sffamily \fbox{\colorbox[gray]{0.80}{\parbox{0.9\textwidth}{#2}}} \end{center} } sidebar sub-title ^^^^^^^^^^^^^^^^^ Bold instead of emphasized:: \providecommand*{\DUsubtitlesidebar}[1]{\hspace*{\fill}\\ \textbf{#1}\smallskip} topic ^^^^^ No quote but normal text:: \newcommand{\DUtopic}[2][class-arg]{% \ifcsname DUtopic#1\endcsname% \csname DUtopic#1\endcsname{#2}% \else #2 \fi } topic title ^^^^^^^^^^^ Title for "topics" (admonitions, sidebar). Larger font size:: \providecommand*{\DUtitletopic}[1]{\textbf{\large #1}\smallskip} transition ^^^^^^^^^^ Do not add vertical space after the transition. :: \providecommand*{\DUtransition}[1][class-arg]{% \hspace*{\fill}\hrulefill\hspace*{\fill}} docutils-0.12/docs/user/links.txt0000664000175000017500000003227112355472567021040 0ustar engelbertengelbert00000000000000===================== Docutils_ Link List ===================== :Author: Lea Wiemann :Contact: docutils-develop@lists.sourceforge.net :Revision: $Revision: 7755 $ :Date: $Date: 2014-07-04 11:35:51 +0200 (Fre, 04. Jul 2014) $ :Copyright: This document has been placed in the public domain. .. title:: Docutils Links .. contents:: This document contains links users of Docutils and reStructuredText may find useful. Many of the project listed here are hosted in the `Docutils Sandbox`_. If you have something to publish, you can get write access, too! The most current version of this link list can always be found at http://docutils.sourceforge.net/docs/user/links.html. Editors ------- Advanced text editors with reStructuredText support, IDEs, and docutils GUIs: * Emacs `rst mode `__. * `Vim `__: - `reStructuredText syntax highlighting mode `__, - `VST `__ (Vim reStructuredText) plugin for Vim7 with folding. - `VOoM `__ plugin for Vim that emulates two-pane outliner with support for reStructuredText (since version 4.0b2). * `JED `__ programmers editor with `rst mode `__ * `reStructuredText editor plug-in for Eclipse`__ __ http://resteditor.sf.net/ * Gnome's gedit offers syntax highlighting and a reST preview pane. Latest version of the plugin is available from `bittner @ github`_ (See also: `Gedit third party plugins`__). __ https://wiki.gnome.org/Apps/Gedit/ThirdPartyPlugins-v3.8 .. _bittner @ github: https://github.com/bittner/gedit-reST-plugin * Gunnar Schwant's DocFactory_ is a wxPython GUI application for Docutils. .. _DocFactory: http://docutils.sf.net/sandbox/gschwant/docfactory/doc/ * ReSTedit_ by Bill Bumgarner is a Docutils GUI for Mac OS X. * Leo_ is an outliner_, written in Python using PyQt. It can be used as IDE for literal programming, as a filing cabinet holding any kind of data and as `document editor`__ with outlines containing reStructuredText markup. .. _Leo: http://leoeditor.com/ .. _outliner: http://en.wikipedia.org/wiki/Outliner __ http://webpages.charter.net/edreamleo/rstplugin3.html * `NoTex `_ is a browser based reStructuredText editor with syntax highlighting and PDF/HTML export functionality using Sphinx. * `rsted `_ is a "simple online editor for reStructuredText on Flask". You can try it on http://rst.ninjs.org/ Export ------ Convert reStructuredText to other formats: PDF ``` * `rst2pdf (reportlab) `_ is a tool to go directly from reStructuredText to PDF, via `reportlab `_. No LaTeX installation is required. * `rst2pdf (pdflatex) `_ by Martin Blais is a minimal front end producing LaTeX, compiling the LaTeX file, getting the produced output to the destination location and finally deleting all the messy temporary files that this process generates. * `rst2pdf (rubber) `_ is a front end for the generation of PDF documents from a reStructuredText source via LaTeX in one step cleaning up intermediate files. It uses the `rubber `_ Python wrapper for LaTeX and friends. * **py.rest** from the Codespeak `py Lib scripts`_ converts reStructuredText files to HTML and PDF (cleaning up the intermediate latex files). Similar to ``buildhtml.py``, it looks recursively for .txt files in the given PATHS. OpenOffice `````````` * odtwriter_ the Open Document Format writer developed by Dave Kuhlman produces files that can be processed with OpenOffice and Abiword. Since version 0.5, the odtwriter_ it is part of the Docutils_ core. HTML variants ````````````` * The Sphinx_ Python Documentation Generator by Georg Brandl was originally created to translate the Python_ documentation, and is now `used by `__ a wide choice of projects. It can generate complete web sites (interlinked and indexed HTML pages) and/or PDF from a set of rst source files. * Nikola__ static site generator, use restructured text by default. __ http://getnikola.com * rst2ht_ by Oliver Rutherfurd, converts reStructuredText to an .ht template, for use with ht2html_. * htmlnav_ by Gunnar Schwant, is an HTML writer which supports navigation bars. * rest2web_, by Michael Foord, is a tool for creating web sites with reStructuredText. * rst2chm_ by Oliver Rutherfurd, generates Microsoft HTML Help files from reStructuredText files. * `html4strict `__ produces XHTML that strictly conforms to the XHTML 1.0 specification. * `html4trans `__ produces XHTML conforming to the version 1.0 Transitional DTD that contains enough formatting information to be viewed by a lightweight HTML browser without CSS support. * A `simple HTML writer`_ by Bill Bumgarner that doesn't rely on CSS (stylesheets). Others `````` * Pandoc_ is a document converter that can write Markdown, reStructuredText, HTML, LaTeX, RTF, DocBook XML, and S5. * restxsl_ by Michael Alyn Miller, lets you transform reStructuredText documents into XML/XHTML files using XSLT stylesheets. * An `XSLT script`__ by Ladislav Lhotka enables reStructuredText annotations to be included in RELAG NG XML schemas. __ http://www.cesnet.cz/doc/techzpravy/2006/rngrest/ * `DocBook Writer`_ by Oliver Rutherfurd. * Nabu_, written by Martin Blais, is a publishing system which extracts information from reStructuredText documents and stores it in a database. Python knowledge is required to write extractor functions (see `Writing an Extractor`_) and to retrieve the data from the database again. * The `pickle writer`_ by Martin Blais pickles the document tree to a binary string. Later unpickling will allow you to publish with other Writers. * The `Texinfo Writer`_, by Jon Waltman converts reStructuredText to Texinfo, the documentation format used by the GNU project and the Emacs text editor. Texinfo can be used to produce multiple output formats, including HTML, PDF, and Info. * For `confluence CMS`_ see https://github.com/netresearch/rst2confluence. * Deploying into wikis might be aided by deploy-rst__. __ https://github.com/netresearch/deploy-rst Import ------ Convert other formats to reStructuredText: * sxw2rest_, by Trent W. Buck, converts StarOffice XML Writer (SXW) files to reStructuredText. * xml2rst_, an XSLT stylesheet written by Stefan Merten, converts XML dumps of the document tree (e.g. created with rst2xml.py) back to reStructuredText. * xhtml2rest_, written by Antonios Christofides, is a simple utility to convert XHTML to reStructuredText. * Sphinx_ includes a `LaTeX to Rst converter `__ in its source code (trimmed to importing the old Python docs). * Pandoc_ can read Markdown and (subsets of) HTML, and LaTeX and export to (amongst others) reStructuredText. * PySource_, by Tony Ibbs, is an experimental Python source Reader. There is some related code in David Goodger's sandbox (pysource_reader_) and a `Python Source Reader`_ document. Extensions ---------- Extend the reStructuredText syntax or the features of Docutils. More extensions are in the `Docutils Sandbox`_. * Jens J. Mortensen developed `LaTeX math for reST`_, which writes to LaTeX or to MathML. It's included with Docutils since 0.8 (2010-11-05). * Beni Cherniavsky has written a generic `preprocessing module`_ for roles and/or directives and built preprocessors for TeX math for both LaTeX and HTML output on top of it. * Beni Cherniavsky maintains a Makefile_ for driving Docutils, hoping to handle everything one might do with Docutils. * The `ASCII art to SVG converter`_ (aafigure) developed by Chris Liechti can parse ASCII art images, embedded in reST documents and output an image. This would mean that simple illustrations could be embedded as ASCII art in the reST source and still look nice when converted to e.g. HTML * zot4rst_ by Erik Hetzner is an extension that allows users to write reST documents using citations from a Zotero_ library. * Quick and easy publishing reStructuredText source files as blog posts on blogger.com is possible with `rst2blogger`_ . Related Applications -------------------- Applications using docutils/reStructuredText and helper applications. * For Wikis, please see the `FAQ entry about Wikis`_. * For Blogs (Weblogs), please see the `FAQ entry about Blogs`_. * `Project Gutenberg`_ uses docutils, but with it's own xetex- and nroff-writer and epub. Development ``````````` * Sphinx_ extends the ReStructuredText syntax to better support the documentation of Software (and other) *projects* (but other documents can be written with it too). Since version 2.6, the `Python documentation`_ is based on reStructuredText and Sphinx. * Trac_, a project management and bug/issue tracking system, supports `using reStructuredText `__ as an alternative to wiki markup. * PyLit_ provides a bidirectional text <--> code converter for *literate programming with reStructuredText*. * If you are developing a Qt app, rst2qhc_ lets you generate the whole help automatically from reStructuredText. That includes keywords, TOC, multiple manuals per project, filters, project file, collection project file, and more. CMS Systems ``````````` * Plone_ and Zope_ both support reStructuredText markup. * ZReST_, by Richard Jones, is a "ReStructuredText Document for Zope_" application that is complete and ready to install. Presentations ````````````` * `native support for S5 `_; * The `PythonPoint interface`_ by Richard Jones produces PDF presentations using ReportLabs' PythonPoint_. * InkSlide_ quick and easy presentations using Inkscape_. InkSlide uses reStructuredText for markup, although it renders only a subset of rst. .. _Docutils: http://docutils.sourceforge.net/ .. _FAQ entry about Wikis: http://docutils.sf.net/FAQ.html#are-there-any-wikis-that-use-restructuredtext-syntax .. _FAQ entry about Blogs: http://docutils.sf.net/FAQ.html#are-there-any-weblog-blog-projects-that-use-restructuredtext-syntax .. _py Lib scripts: http://codespeak.net/py/dist/bin.html .. _PyLit: http://pylit.berlios.de .. _Pandoc: http://sophos.berkeley.edu/macfarlane/pandoc/ .. _restxsl: http://www.strangeGizmo.com/products/restxsl/ .. _ReSTedit: http://www.friday.com/bbum/index.php?s=restedit .. _ASCII art to SVG converter: http://docutils.sf.net/sandbox/cliechti/aafigure/ .. _LaTeX math for reST: http://docutils.sourceforge.net/sandbox/jensj/latex_math/ .. _sxw2rest: http://twb.ath.cx/~twb/darcs/sxw2rest/ .. _xml2rst: http://www.merten-home.de/FreeSoftware/xml2rst/index.html .. _rst2ht: http://www.rutherfurd.net/articles/rst-ht2html.html .. _ht2html: http://ht2html.sourceforge.net/ .. _htmlnav: http://docutils.sf.net/sandbox/gschwant/htmlnav/ .. _Inkscape: http://inkscape.org/ .. _InkSlide: http://wiki.inkscape.org/wiki/index.php/InkSlide .. _xhtml2rest: http://docutils.sf.net/sandbox/wiemann/xhtml2rest/ .. _rst2chm: http://www.rutherfurd.net/software/rst2chm/ .. _rest2web: http://www.voidspace.org.uk/python/rest2web/ .. _Docutils Sandbox: http://docutils.sf.net/sandbox/README.html .. _ZReST: http://docutils.sf.net/sandbox/richard/ZReST/ .. _PySource: http://docutils.sf.net/sandbox/tibs/pysource/ .. _pysource_reader: http://docutils.sf.net/sandbox/davidg/pysource_reader/ .. _Python Source Reader: http://docutils.sf.net/docs/dev/pysource.html .. _Manpage Writer: http://docutils.sf.net/sandbox/manpage-writer/ .. _ReportLabs/PDF Writer: http://docutils.sf.net/sandbox/dreamcatcher/rlpdf/ .. _DocBook Writer: http://docutils.sf.net/sandbox/oliverr/docbook/ .. _odtwriter: http://docutils.sf.net/docs/user/odt.html .. _simple HTML writer: http://docutils.sf.net/sandbox/bbum/DocArticle/ .. _preprocessing module: http://docutils.sf.net/sandbox/cben/rolehack/ .. _Makefile: http://docutils.sf.net/sandbox/cben/make/ .. _Nabu: http://furius.ca/nabu/ .. _Writing an Extractor: http://furius.ca/nabu/doc/nabu-extractor.html .. _pickle writer: http://docutils.sf.net/sandbox/blais/pickle_writer/ .. _Sphinx: http://sphinx.pocoo.org/ .. _Python: http://www.python.org/ .. _Python documentation: http://docs.python.org/ .. _PythonPoint: http://www.reportlab.org/python_point.html .. _PythonPoint interface: http://docutils.sf.net/sandbox/richard/pythonpoint/ .. _rst2qhc: http://rst2qhc.googlecode.com .. _Plone: http://plone.org/ .. _Zope: http://www.zope.org/ .. _Zotero: http://www.zotero.org/ .. _zot4rst: http://e6h.org/~egh/hg/zotero-plain .. _Trac: http://trac.edgewall.org/ .. _Texinfo Writer: http://docutils.sf.net/sandbox/texinfo-writer/README.html .. _confluence CMS: http://www.atlassian.com/software/confluence .. _rst2blogger: https://github.com/dhellmann/rst2blogger#readme .. _Project Gutenberg: http://www.gutenberg.org docutils-0.12/docs/user/latex.txt0000664000175000017500000016257212153065730021027 0ustar engelbertengelbert00000000000000================================ Generating LaTeX with Docutils ================================ :Author: Engelbert Gruber, Guenter Milde :Contact: docutils-develop@lists.sourceforge.net :Revision: $Revision: 7667 $ :Date: $Date: 2013-06-03 12:11:36 +0200 (Mon, 03. Jun 2013) $ :Copyright: This document has been placed in the public domain. .. contents:: .. sectnum:: Introduction ============ This document covers topics specific to Docutils' LaTeX__ export. For an introduction to LaTeX see, e.g., `LaTeX2e for authors`_. There exists a wide selecton of `LaTeX Documentation on the net`_ and `books on LaTeX and related topics`_. __ http://www.latex-project.org/ .. _LaTeX2e for authors: http://www.latex-project.org/guides/usrguide.pdf .. _LaTeX Documentation on the net: http://www.latex-project.org/guides/ .. _books on LaTeX and related topics: http://www.latex-project.org/guides/books.html There are two approaches to typeset documents from reStructuredText sources via LaTeX: 1. treat LaTeX as a document format (like HTML): Transform the internal markup into corresponding LaTeX markup. For example, a section title would be written with the LaTeX section command: ``\section{this section title}``. This keeps the document structure and semantic markup produing a readable LaTeX file, but may require hacking around Docutils — LaTeX incompatibilities. As with HTML, styling is mostly done via style sheets or `LaTeX packages`_. If you prefer this approach, try the `latex2e` or the `xetex` writer. 2. treat LaTeX as a page description format (like Postscript): Use LaTeX as a typesetting system to produce the desired output without representing document structure in the LaTeX source. This will work around Docutils-incompatible features in LaTeX but produces a hard to read LaTeX file. Styling is done via options to the latex writer. The (orphaned) `newlatex` writer (``rst2newlatex.py``) uses LaTeX as a typesetter without caring about producing readable/stylable LaTeX files. This documents describes the first approach used by the `latex2e` and `xetex` writers. LaTeX ===== Unlike HTML/CSS, LaTeX provides one common language for markup and style definitions. Separation of content and style is realized by collecting style definitions in the documentclass_, `LaTeX packages`_, or the document preamble. LaTeX packages -------------- LaTeX packages (similar to Python modules or C libraries) provide means to extend or modify the LaTeX language by redefining macros or providing new ones. There is a *huge* selection of packages (standard as well as user contributed) coming with your TeX distribution or available at CTAN_ (see the `TeX Catalogue`_). .. _CTAN: http://www.ctan.org .. _TeX Catalogue: http://texcatalogue.sarovar.org/ .. _stylesheet: config.html#stylesheet-latex2e-writer .. _TeX input path: http://www.tex.ac.uk/cgi-bin/texfaq2html?label=what-TDS Docutils special LaTeX macros ----------------------------- Some Docutils objects have no LaTeX counterpart, they will be typeset using a Docutils specific LaTeX *macro* (command, environment, or length) to allow customization. By convention, special macros use the prefix ``\DU``\ [#]_. The generated LaTeX documents should be kept processable by a standard LaTeX installation. Therefore fallback definitions are included after the `custom style sheets`_, if a macro is required in the document. * Custom `style sheets`_ can define alternative implementations with ``\newcommand``, ``\newenvironment``, and ``\newlength`` followed by ``\setlength``. * Definitions with `raw LaTeX`_ are part of the document body. Use ``\def``, ``\renewcommand`` or ``\renewenvironment``, and ``\setlength``. See the test output standalone_rst_latex.tex_ for an example of the fallback definitions and their use in the document. .. _standalone_rst_latex.tex: ../../test/functional/expected/standalone_rst_latex.tex .. [#] DU for Documentation Utilities = Docutils Length units ------------ LaTeX supports all `length units`_ defined for Docutils plus the following less common units: :pt: typewriter's (or LaTeX) point (1 pt = 1/72.27 in) :dd: didôt (1 dd = 1238/1157 pt) :cc: cîcero (1 cc = 12 dd) :sp: scaled point (1sp = 1/65536pt) .. attention:: Different definitions of the unit "pt"! * In Docutils (as well as CSS) the unit symbol "pt" denotes the `Postscript point` or `DTP point`. * LaTeX uses "pt" for the `LaTeX point`, which is unknown to Docutils and 0.3 % smaller. * The `DTP point` is available in LaTeX as "bp" (big point): 1 pt = 1/72.25 in < 1 bp = 1/72 in Lengths specified in the document with unit "pt" will be given the unit "bp" in the LaTeX source. In `raw LaTeX`_ and `custom style sheets`_, the `DTP point` must be specified as "bp", while "pt" is interpreted as `LaTeX point`. The default length unit (added by Docutils to length specifications without unit) is the "DTP point". For more on lengths in LaTeX, see e.g. `Hypertext Help with LaTeX: Lengths`__ .. _length units: ../ref/rst/restructuredtext.html#length-units __ http://www.giss.nasa.gov/tools/latex/ltx-86.html. PDF generation ============== In most cases, LaTeX code is not the desired end-format of the document. LaTeX offers many ways to generate PDF documents from the LaTeX source, including: _`pdflatex` Generates a PDF document directly from the LaTeX file. _`latex + dvipdfmx` Use ``latex`` to generate a DVI file and ``dvipdfmx`` to produce a PDF file. If you take this approach, add ``dvipdfmx`` to the _documentoptions. _`latex` + dvips + ps2pdf Produce a DVI file with ``latex``, postscript with ``dvips`` and PDF with ``ps2pdf``. _`xelatex` The `XeTeX`__ engine works with input files in UTF-8 encoding and system fonts. Export your document with the `xetex` writer (``rst2xetex``), if you want to go this route. You need to call latex (or pdflatex/xelatex) twice (or even three times) to get internal references correct. .. _documentoptions: config.html#documentoptions __ http://tug.org/xetex/ _`rubber` The Rubber__ wrapper for LaTeX and friends can be used to automatically run all programs the required number of times and delete "spurious" files. This includes processing bibliographic references or indices, as well as compilation or conversion of figures. __ http://iml.univ-mrs.fr/~beffara/soft/rubber/ Configuration ============= The LaTeX code generation can be configured via * configuration options_ to the Docutils writer, * `LaTeX packages`_, * custom `LaTeX code`_ in + `style sheets`_, + the `LaTeX preamble`_, + the document body (`raw LaTeX`_), or + custom templates_. .. _option: Options ------- Options can be specified as * command-line options (run ``rst2latex.py --help`` to get a list of available options), or * configuration settings (see `Docutils Configuration`_ for details). .. _Docutils Configuration: config.html LaTeX code ---------- Custom LaTeX code can be placed in `style sheets`_, the `LaTeX preamble`_, the document body (`raw LaTeX`_), or custom templates_. .. _style sheet: .. _custom style sheets: Style sheets ```````````` A common way of LaTeX customization is the preparation of custom style sheets, either as simple files with LaTeX code snippets or as home-made `LaTeX packages`_ (see the clsguide_ for an introduction on LaTeX package writing). Options: stylesheet_ It is possible to specify multiple style sheets and mix `LaTeX packages`_ with `custom style sheets`_. You cannot specify package options with the stylesheet_ setting. If you need to pass options to the package, use the ``\usepackage`` command in the `LaTeX preamble`_ or a custom style sheet. Example 1: Select Latin Modern fonts with the `lmodern` package:: --stylesheet=lmodern Example 2: Use the `preamble.tex` home-made custom style sheet together with the package `kerkis` (Bookman fonts):: --stylesheet=kerkis,preamble.tex Example 3: Select Palatino fonts with old-style numbers and true small-caps with the LaTeX command :: \usepackage[osf,sc]{mathpazo} in the `LaTeX preamble`_ or `custom style sheets`_. Stylesheet Repository There is a `repository of user-contributed style sheets`_ in the Docutils Sandbox_. .. _clsguide: http://mirror.ctan.org/macros/latex/doc/clsguide.pdf .. _embed-stylesheet: config.html#embed-stylesheet-latex2e-writer .. _repository of user-contributed style sheets: ../../../sandbox/stylesheets/ .. _sandbox: ../../../sandbox/ LaTeX preamble `````````````` Configuration by LaTeX code in the document preamble is also possible without a separate stylesheet. This way, packages can be loaded with options or commands re-defined without the need to create a separate file (new in Docutils 0.7). Option: latex-preamble_ Default: used for `font setup`_ Example: To use the better looking ``txtt`` font for monospaced text define the latex-preamble_ setting in a configuration file:: latex-preamble: \renewcommand{\ttdefault}{txtt} \usepackage{mathptmx} % Times \usepackage[scaled=.92]{helvet} % Helvetica .. _latex-preamble: config.html#latex-preamble .. _PDF standard fonts: http://en.wikipedia.org/wiki/PDF#Standard_Type_1_Fonts .. _Linux Libertine: http://www.linuxlibertine.org/index.php?id=1&L=1 Templates ````````` Some customizations require commands at places other than the insertion point of stylesheets or depend on the deletion/replacement of parts of the document. This can be done via a custom template. See the `publisher documentation`_ for a description of the document parts available in a template file. Option: template_ In addition to the 'default.tex' template, the latex writer directory contains the alternative 'titlepage.tex'. Example: Print a title page including docinfo, dedication, and abstract:: --template=titlepage.tex .. _publisher documentation: ../api/publisher.html .. _template: config.html#template-latex2e-writer Raw LaTeX ````````` By means of the `raw directive`_ or a derived `custom role`_, one can give commands directly to LaTeX. These can be both, styling as well as printing commands. Example: Math formula:: .. raw:: latex \[x^3 + 3x^2a + 3xa^2 + a^3,\] (Drawback: the formula will be invisible in other output formats.) Most LaTeX code examples also work as raw LaTeX inside the document. An exception are commands that need to be given in the document preamble (e.g. package loading with ``\usepackage``, which can be achieved with the ``--style-sheet`` or ``--latex-preamble`` command line options instead). Remember to use *re-defining* commands for customizing `Docutils special LaTeX macros`_ with raw LaTeX. Example: Define the transition command as page break:: .. raw:: latex \renewcommand*{\DUtransition}{\pagebreak[4]} See also: * Defining a macro for a `custom role`_. * Forcing `page breaks`_. .. _raw directive: ../ref/rst/directives.html#raw How to configure the ... ======================== admonitions ----------- Admonitions__ are specially marked "topics" that can appear anywhere an ordinary body element can. __ ../ref/rst/directives.html#admonitions Command: ``\DUadmonition`` Default: Typeset in a frame (90 % of text width). The admonition title is typeset with the ``\DUtitle`` command which also takes a class argument. See `topic title`_ Example 1: A lighter layout without the frame:: \newcommand{\DUadmonition}[2][class-arg]{% % try \DUadmonition#1{#2}: \ifcsname DUadmonition#1\endcsname% \csname DUadmonition#1\endcsname{#2}% \else \begin{quote} #2 \end{quote} \fi } The first part of this definition acts as a "dispatcher". This way it is possible to define a special handling of `specific admonitions`_ based on the "class" argument. .. _specific admonitions: ../ref/rst/directives.html#specific-admonitions Example 2: Use ``.. note::`` for a margin note:: \newcommand{\DUadmonitionnote}[1]{\marginpar{#1}} Make sure there is enough space to fit the note. See also the marginnote_ and pdfcomment_ packages. .. _marginnote: http://mirror.ctan.org/help/Catalogue/entries/marginnote.html .. _pdfcomment: http://mirror.ctan.org/help/Catalogue/entries/pdfcomment.html .. _custom role: custom interpreted text roles ----------------------------- The rst `role directive`_ allows defining custom `text roles`_ that mark parts of inline text (spans) with a class argument. * Role names and class arguments are converted to conform to the regular expression ``[a-z][-a-z0-9]*`` (see `class directive`_). * Class arguments may contain numbers and hyphens, which need special treatment in LaTeX command names. (The special command ``\@namedef`` can help with the definition of corresponding commands.) * Custom roles can have multiple class arguments. In contrast to HTML/CSS, the order of the class arguments might matter. Commands: ``\DUrole``: dispatcher command ``\DUroleCLASSARGUMENT``: optional styling command Default: The definition of ``\DUrole{CLASSARGUMENT}{}`` calls the macro named ``\DUroleCLASSARGUMENT{}``\ [#]_ if it is defined (but silently ignores this class argument if a corresponding macro is not defined). .. [#] For backwards compatibility, the prefix ``\docutilsrole...`` in the styling commands also recognized. Example 1: Typeset text in small caps:: .. role:: smallcaps :smallcaps:`Fourier` transformation This is transformed to the LaTeX code:: \DUrole{smallcaps}{Fourier} transformation The definition :: \newcommand{\DUrolesmallcaps}{\textsc} as `raw LaTeX`_ or in the custom `style sheet`_ will give the expected result (if the text font_ supports small caps). Example 2: Subscript text in normal size and *italic* shape:: .. role:: sub(subscript) As "sub" inherits from the standard "subscript" role, the LaTeX macro only needs to set the size and shape:: \newcommand{\DUrolesub}{\normalsize\itshape} Example 3: A role with several classes and a converted class name:: .. role:: custom4 :class: argI argII arg_3 is translated to the nested commands:: \DUrole{argi}{\DUrole{argii}{\DUrole{arg-3}{}}} With the definitions:: \newcommand{\DUroleargi}[1]{\textsc} \newcommand{\DUroleargii}[1]{{\large #1}} \makeatletter \@namedef{DUrolearg-3}{\textbf} \makeatother in a `style sheet`_\ [#]_ or as `raw LaTeX`_ in the document source, text styled with ``:custom4:`large bold small-caps``` will be typeset accordingly. .. [#] Leave out the ``\makeatletter`` - ``\makeatother`` pair if the style sheet is a LaTeX package (``*.sty``). .. _role directive: ../ref/rst/directives.html#role .. _text roles: ../ref/rst/roles.html .. _class directive: ../ref/rst/directives.html#class definition lists ---------------- ReStructuredText `definition lists`__ correspond to HTML ``

`` list objects. Environment: ``description``: LaTeX standard environment Command: ``\descriptionlabel``: styling macro for the description term Default: bold label text, hanging indent Example: A non-bold label can be achieved with:: \renewcommand\descriptionlabel[1]{\hspace\labelsep \normalfont #1} __ ../ref/rst/restructuredtext.html#definition-lists document class -------------- There are hundreds of LaTeX document classes installed by modern LaTeX distributions, provided by publishers, or available at CTAN_. The `TeX Catalogue`_ lists most of them. Popular document classes: * article, report, book: standard document classes * scrartcl, scrrprt, scrbook: KOMA-script_ classes * memoir_: highly configurable class for larger documents Option: documentclass_ .. _KOMA-script: http://mirror.ctan.org/help/Catalogue/entries/koma-script.html .. _memoir: http://mirror.ctan.org/help/Catalogue/entries/memoir.html .. _documentclass: config.html#documentclass document info ------------- Content of the `bibliographic fields`__ at the top of a document. By default, docinfo items are typeset as a table. Options: use-latex-docinfo_, use-latex-abstract_ Length: ``\DUdocinfowidth``: the width for the `docinfo` table. Default: 90 % of text width: ``0.9\textwidth`` Example: set to 70 % of text width:: \newlength{\DUdocinfowidth} \setlength{\DUdocinfowidth}{0.7\textwidth} __ ../ref/rst/restructuredtext.html#bibliographic-fields .. _use-latex-docinfo: config.html#use-latex-docinfo .. _use-latex-abstract: config.html#use-latex-abstract document title -------------- A lone top-level section title is (usually) transformed to the document title (see `section structure`_). The format of the document title is defined by the `document class`_. The "article" document class uses an in-page title and the "report" and "book" classes write a separate title page. See the `TeX FAQ`_ on how to customize the `style of document titles`_. The default title page shows only title and subtitle, date and author are shown in the `document info`_ table. Options: use-latex-docinfo_ ``--template=titlepage.tex`` Put docinfo and abstract into the title page. A separate title page is used also with the "abstract" document class. .. _section structure: rst/quickref.html#section-structure .. _TeX FAQ: http://www.tex.ac.uk/faq .. _style of document titles: http://www.tex.ac.uk/cgi-bin/texfaq2html?label=titlsty field lists ----------- `Field lists`__ may be used as generic two-column table constructs in documents. Environment: ``DUfieldlist`` Default: Indented description list. Example: Use a description list customized with enumitem_:: \usepackage{enumitem} \newenvironment{DUfieldlist}% {\description[font=,style=sameline,leftmargin=8em]} {\enddescription} } The `KOMA-script`_ classes provide a similar environment under the name `labeling`. .. _enumitem: http://mirror.ctan.org/help/Catalogue/entries/enumitem.html __ ../ref/rst/restructuredtext.html#field-lists figure and table captions ------------------------- The caption_ package provides many ways to customise the captions in floating environments like figure and table. The chngcntr_ package helps to configure the numbering of figure and table caption numberings. Some document classes (e.g. KOMA-script_) provide additional configuration. Also see the related `LaTeX FAQ entry`__ Example :: \usepackage{caption} \captionsetup{justification=raggedleft,singlelinecheck=false} .. _caption: http://mirror.ctan.org/help/Catalogue/entries/caption.html .. _chngcntr: http://mirror.ctan.org/help/Catalogue/entries/chngcntr.html __ http://www.tex.ac.uk/cgi-bin/texfaq2html?label=running-nos figure placement ---------------- Figures_ might be typeset at the place of definition (default) or "float" to a suitable place at the top or bottom of a page. This is implemented using the float_ package. Command: ``\floatplacement`` The placement setting is valid from the point of definition until the next ``\floatplacement`` command or the end of the document. See float.pdf_ for details. Default: ``\floatplacement{figure}{H}`` (here definitely). This corresponds most closely to the source and HTML placement (principle of least surprise). Example 1: In a custom `style sheet`_, set the default to let LaTeX find a suitable place for figure floats:: \usepackage{float} \floatplacement{figure}{htbp} % here, top, bottom, extra-page Example 2: To move all following figures to the top or bottom of the page write in the document source:: .. raw:: latex \floatplacement{figure}{tb} .. _figures: ../ref/rst/directives.html#figure .. _float: http://mirror.ctan.org/help/Catalogue/entries/float.html .. _float.pdf: http://mirror.ctan.org/macros/latex/contrib/float/float.pdf .. _font setup: font ---- The selected text font influences the *look*, the *feel*, and the *readability* of the document (cf. http://www.csarven.ca/web-typography). Selecting a suitable font also solves the problem with `bad looking PDF output`_. Font selection is one of the main differences between LaTeX and XeTeX: LaTeX cannot use the fonts of the operating system directly but needs specially installed fonts with additional supporting files. XeTeX can use system fonts and provides access to the full feature set of modern OpenType_ fonts. .. _OpenType: http://en.wikipedia.org/wiki/OpenType The default font setup is done in the latex-preamble_: LaTeX `PDF standard fonts`_ (Times, Helvetica, Courier) XeTeX `Linux Libertine`_, a free, high quality alternative to Times with a wide coverage of glyphs, styles, and OpenType features. Despite its name, Linux Libertine can be used on any operating system that can handle OpenType fonts. Alternative fonts can be selected by LaTeX a) specifying the corresponding LaTeX package(s) as argument to the stylesheet_ option_ or with the ``\usepackage`` LaTeX command. * packages can be combined, * passing options to a package is only possible in a `style sheet`_ or the `LaTeX preamble`_. b) changing the font-default macros ``\rmdefault``, ``\sfdefault`` and/or ``\ttdefault`` in a custom `style sheet`_, the `LaTeX preamble`_ or `raw LaTeX`_. Example 1: Use `Latin Modern`_. `LaTeX code`_:: \usepackage{lmodern} Command line argument:: --stylesheet=lmodern Example 2: The _`Times/Helvetica/Courier` `PDF standard fonts`_ are selected by the LaTeX code [#]_:: \usepackage{mathptmx} % Times for serif and math \usepackage[scaled=.90]{helvet} % downscaled Helvetica for sans serif \usepackage{courier} % Courier for teletype (mono-space) Since Docutils 0.7, this is the default value of the `latex-preamble`_ option. .. [#] When generating PDF-files from LaTeX, the `PDF standard fonts`_ do not need to be embedded in the document. While this results in smaller files, the actually used fonts on screen and in print might differ! (For details see, e.g., the testflow_ package documentation.) Example 3: Use the teletype font from the txfonts_ package. As there is no package for this, we re-define the font macro with the `LaTeX code`_:: \renewcommand{\ttdefault}{txtt} XeTeX using the macros of the fontspec_ package. Use some font-viewer or -manager (e.g. fontmatrix_) to find out the correct names of the fonts on your system. Example: DejaVu_, very wide coverage, screen optimized. As this font runs wide, add ``DIV=10`` to the `documentoptions`_:: \setmainfont{DejaVu Serif} \setsansfont{DejaVu Sans} \setmonofont[HyphenChar=None]{DejaVu Sans Mono} .. _fontspec: http://mirror.ctan.org/help/Catalogue/entries/fontspec.html .. _fontmatrix: http://fontmatrix.net/ .. _DejaVu: http://dejavu-fonts.org/ .. _documentoptions: config.html#documentoptions choice of suitable fonts ```````````````````````` High quality free fonts suitable for use with XeTeX are, e.g., listed at `Good Libre Fonts`_, `25 Best Free Quality Fonts`_ and the update `19 More Free Quality Fonts`_. The `LaTeX Font Catalogue`_ provides information and examples for a wide range of fonts available for use with LaTeX. Here is just a selection: a) The `Latin Modern`_ (LM) fonts are extended outline versions of the standard TeX font Computer Modern (CM). +1 simple invocation: ``--stylesheet=lmodern`` +1 keeps the traditional TeX "look and feel": +1 generally accepted as high quality CM replacement, +1 comprehensive math support, +1 including optical sizes, +1 compatible with extensions made to match CM, -1 modern types are hard to read at low (screen) resolutions. -2 not part of a minimal standard TeX installation -1 might not work out-of-the-box -1 large additional download (ca. 12 ... 17 MB) b) CM-Super_ is another outline CM replacement. +1 simple invocation: modern LaTeX distributions use CM-Super automatically instead of CM if it is installed. -1 said to be of inferior quality compared to LM. -2 not part of a minimal standard TeX installation, even bigger download size than Latin Modern. c) `Bera`_ (Bitstream Vera) +1 simple invocation: ``--stylesheet=bera`` +1 optimized for on-screen viewing with goot hinting -2 not part of a minimal standard TeX installation d) PSNFSS_ Postscript fonts +1 part of every standard TeX installation +1 smaller PDF/Postscript document size if standard fonts are not embedded -1 restricted set of glyphs in the free versions [#]_ -1 different fonts for roman, sans-serif and typewriter fonts. -1 invocation somewhat more complex, as several packages are required for a complete font set, sometimes including package options. Roman (serif) PSNFSS fonts: Bookman good legibility but very wide. Charter bread-and-butter type optimized for printing on low-resolution printers New Century Schoolbook good legibility but very wide. Palatino +1 recommended by font experts +1 good LaTeX support including matching math fonts, small caps, old-style figures -1 bad rendering in xpdf viewer (auto-hinting leads to different x-hight for different characters at some magnifications) (this is fixed in recent versions). Times +1 the serif `PDF Standard Font`_, -1 overused and quite narrow (devised for multi-column layouts). Utopia recommended by font experts .. table:: Font packages for standard Postscript fonts (cf. `Using common Postscript fonts with LaTeX`_) ========= ============ ============= ============= ========= Package Roman Sans Serif Typewriter Math ========= ============ ============= ============= ========= (none) CM Roman CM Sans Serif CM Typewriter CM Math mathpazo Palatino Palatino mathptmx Times Times helvet Helvetica avant Avant Garde courier Courier chancery Zapf Chancery bookman Bookman Avant Garde Courier newcent New Century Avant Garde Courier Schoolbook charter Charter utopia Utopia ========= ============ ============= ============= ========= .. [#] Extended versions of the standard Postscript fonts including accented chars, Greek and Cyrillic as well as real small-caps and old-style numbers are available with the `TeX Gyre`_ bundle which is part of, e.g., `TeX Live`_. .. _LaTeX Font Catalogue: http://www.tug.dk/FontCatalogue/ .. _Latin Modern: http://mirror.ctan.org/help/Catalogue/entries/lm.html .. _CM-Super: http://mirror.ctan.org/help/Catalogue/entries/cm-super.html .. _bera: http://mirror.ctan.org/help/Catalogue/entries/bera.html .. _TeX Gyre: http://www.gust.org.pl/projects/e-foundry/tex-gyre .. _PSNFSS: http://mirror.ctan.org/help/Catalogue/entries/psnfss.html .. _Using common PostScript fonts with LaTeX: http://mirror.ctan.org/macros/latex/required/psnfss/psnfss2e.pdf .. _TeX Live: http://tug.org/texlive/ .. _txfonts: http://mirror.ctan.org/help/Catalogue/entries/txfonts.html .. _PDF Standard Font: http://en.wikipedia.org/wiki/PDF#Standard_Type_1_Fonts .. _testflow: http://www.tex.ac.uk/tex-archive/help/Catalogue/entries/testflow.html .. _Good Libre Fonts: http://typophile.com/node/18207 .. _25 Best Free Quality Fonts: http://www.alvit.de/blog/article/20-best-license-free-official-fonts .. _19 More Free Quality Fonts: http://www.smashingmagazine.com/2006/10/11/17-more-free-quality-fonts/ font encoding ------------- LaTeX font encodings are described in detail in the encguide_ which is part of the LaTeX base documentation. Option: font-encoding_ Default: "T1" Example 1: Use the (obsolete) LaTeX default encoding "OT1":: --font-encoding=OT1 or (without loading the fontenc_ package):: --font-encoding="" This will improve the look on screen with the default Computer Modern fonts at the expense of problems with `search and text extraction`_ The recommended way is to select a T1-encoded "Type 1" (vector) font, for example `Latin Modern`_ Example 2: Support for characters in the Unicode blocks Latin, Latin-1 Supplement, and Greek together with a T1-encoded "Type 1" (vector) font, for example `Latin Modern`_:: --font-encoding=LGR,T1 --stylesheet=lmodern .. _encguide: http://mirror.ctan.org/macros/latex/doc/encguide.pdf .. _font-encoding: config.html#font-encoding .. _fontenc: http://mirror.ctan.org/help/Catalogue/entries/fontenc.html font size --------- Add font size in points to the document options, e.g. ``--documentoptions=12``, use e.g. the document classes provided by extsizes_ for values other than [10,11,12]. .. _extsizes: http://mirror.ctan.org/help/Catalogue/entries/extsizes.html footnotes --------- By default, footnotes are set with Docutils-specific wrappers around the standard ``\footnotemark`` and ``\footnotetext`` commands. You can configure the footnote layout similar to standard LaTeX footnotes in a custom `style sheet`_. Further configuration is possible by alternative definitions of ``\DUfootnotemark`` and ``\DUfootnotetext`` Example 1: Set footnote text with a hanging indent. * This is the default with KOMA-script_ classes, e.g:: --documentclass=scrartcl (for further configuration, see the `KOMA-script Guide`_), * with package footmisc_:: \usepackage[hang]{footmisc} \setlength{\footnotemargin}{0em} (play with the ``\footnotemargin`` setting), * redefine ``\DUfootnotetext`` inserting `\hangindent`:: \newcommand{\DUfootnotetext}[4]{% \begingroup% \renewcommand{\thefootnote}{% \protect\raisebox{1em}{\protect\hypertarget{#1}{}}% \protect\hyperlink{#2}{#3}}% \footnotetext{\hangindent=2em #4}% \endgroup% } (adapt the ``\hangindent`` value). Example 2: place the footnote text where it appears in the source document (instead of at the page bottom). This can be used to get the effect of endnotes (needs the hanging_ package):: \usepackage{hanging} \newcommand{\DUfootnotetext}[4]{% \par\noindent\raisebox{1em}{\hypertarget{#1}{}}% \hyperlink{#2}{#3}% \hangpara{\parindent}{1}#4% } .. _footmisc: http://mirror.ctan.org/help/Catalogue/entries/footmisc.html .. _hanging: http://mirror.ctan.org/help/Catalogue/entries/hanging.html hyphenation ----------- The amount of hyphenation is influenced by ``\hyphenpenalty``, setting it to 10000 almost prevents hyphenation. As this produces lines with more space between words one should increase Latex's ``\tolerance`` for this. Example: :: \hyphenpenalty=5000 \tolerance=1000 hyperlinks ---------- Options: hyperlink-color_, hyperref-options_ Hyperlinks are realized using the hyperref_ package. As it re-defines many standard LaTeX macros, this package is loaded last, *after* the style sheets. However, you can load hyperref before a package that requires its presence in a `style sheet`_ or the `LaTeX preamble`_ (see example below). This will ignore options set with hyperlink-color_ and hyperref-options_. URLs are typeset with the "url" package (loaded implicitely by "hyperref"). The font of URLs can be defined with the ``\urlstyle`` command. Valid arguments are :same: normal text font, Docutils default, :tt: teletype (monospaced), LaTeX default, :rm: roman, :sf: sans serif Example: Custom loading of the hyperref package also switches to the LaTeX default (monospaced fonts for URLs). Reset to use the text font:: \usepackage[unicode,colorlinks=true,linkcolor=green]{hyperref} \urlstyle{same} See also `non-breaking hyperlinks`_. .. _hyperlink-color: config.html#hyperlink-color .. _hyperref-options: config.html#hyperref-options disable hyperlinks `````````````````` To suppress the hyper-linking completely (e.g. for printing or to avoid clashes with other packages), set hyperref-options_ to "draft" or load the "nohyperref" package that comes with the "hyperref" bundle. Option: ``--hyperref-options=draft`` `LaTeX code`_:: \usepackage{nohyperref,url} \urlstyle{same} .. _hyperref: http://mirror.ctan.org/help/Catalogue/entries/hyperref.html line blocks ----------- In `line blocks`__, newlines and leading whitespace are respected. Environment: ``DUlineblock``: special list environment for line blocks Length: ``\DUlineblockindent``: indentation of indented lineblock parts. Default: 2.5 times the font hight: ``2.5em`` Example: set to the paragraph indentation:: \newlength{\DUlineblockindent} \setlength{\DUlineblockindent}{\parindent} __ ../ref/rst/restructuredtext.html#line-blocks line spacing ------------ Commands: ``\linespread``: for small adjustments ``\singlespacing``, ``\onehalfspacing``, and ``\doublespacing``: from package `setspace` Example 1: Get document wide double spacing:: \usepackage{setspace} \doublespacing Example 2: Increase line spacing by five percent for better readability:: \linespread{1.05} literal blocks -------------- No markup processing is done within a `literal block`__. It is left as-is, and is typically rendered in a monospaced typeface Option: literal-block-env_ Example: ``--literal-block-env=lstlisting`` The ``lstlisting`` environment is highly configurable (as documented in listings.pdf_), for instance :: \renewcommand{\ttdefault}{txtt} \lstset{language=Python, morekeywords=[1]{yield}} \lstloadlanguages{Python} \lstset{ basicstyle=\ttfamily, keywordstyle=\bfseries, commentstyle=\rmfamily\itshape, stringstyle=\slshape, } \lstset{showstringspaces=false} \lstset{columns=fullflexible, basewidth={0.5em,0.4em}} The indentation of literal blocks can be reset with :: \lstset{resetmargins=true} and/or configured with e. g.:: \lstset{xleftmargin=-2em} __ ../ref/rst/restructuredtext.html#literal-blocks .. _literal-block-env: config.html#literal-block-env .. _listings.pdf: http://mirror.ctan.org/macros/latex/contrib/listings/listings.pdf list of figures/tables ---------------------- Docutils does not support lists of figures or tables. However, with LaTeX, they can be generated using `raw LaTeX`_ in the document source. Commands: ``\listoffigures``: a list of figures ``\listoftables``: a list of tables Example: :: .. raw:: latex \listoffigures option list ----------- `Option lists`__ are two-column lists of command-line options and descriptions, documenting a program's options. Environment: ``DUoptionlist``: environment for option lists, Command: ``\DUoptionlistlabel``: set appearance of the options Example: set command options with a bold monospace font:: \newcommand{\DUoptionlistlabel}{\texttt{\textbf{#1}} \hfill} __ ../ref/rst/restructuredtext.html#option-lists page breaks ----------- * Page breaks before top-level sections are the default with a documentclass that provides "chapters", e.g. "book", "memoir" or "scrbook". * Redefining the \section or \section* command in a style sheet is possible too. * `Raw LaTeX`_ or a `custom role`_ can be used. * The transition element can be re-defined to produce a page break, Commands ``\newpage``: hard pagebreak at exactly this position ``\pagebreak[2]``: recommended page break after line end (precedence 1...4) Example: Define the transition command as page break with the `LaTeX code`_:: \newcommand*{\DUtransition}{\pagebreak[4]} (use ``\renewcommand`` with `raw LaTeX`_). page layout ----------- By default, paper size and margin settings are determined by the document class. The following packages help to configure the page layout: a) The `typearea`_ package (part of the `KOMA-script`_ bundle) calculates a *good* page layout (based on rules and recommendations of typography experts). See the `KOMA-Script Guide`_ for details on what is a *good* layout and how this is achieved. b) The `geometry`_ package is recommended if you have to follow guidelines with fixed values for the margins. For details see the `geometry manual`_. Example 1: Let `typearea` determine the type area with ``DIV=calc`` in the documentoptions:: --documentoptions='a4paper,DIV=calc' The ``DIV`` option can also be specified, like ``DIV=10``. It defines how "crowded" a page will be: larger values mean larger text area (at the expense of readability). Example 2: `LaTeX code`_ to set margins with the geometry_ package:: \usepackage{geometry} \geometry{hmargin={3cm,0.8in},height=8in} \geometry{height=10in}. .. _typearea: http://mirror.ctan.org/help/Catalogue/entries/typearea.html .. _KOMA-Script Guide: http://mirror.ctan.org/macros/latex/contrib/koma-script/scrguien.pdf .. _geometry: http://mirror.ctan.org/help/Catalogue/entries/geometry.html .. _geometry manual: http://mirror.ctan.org/macros/latex/contrib/geometry/geometry.pdf page headers and footers ------------------------ With the fancyhdr_ package or the `KOMA-script`_ classes, you can define custom page head- and foot-lines. The `"header" and "footer" directives`_ save their content in the macros ``\DUheader`` rsp. ``\DUfooter``. The macros can be used in LaTeX code and will be replaced by LaTeX with the content of the directives. Example: `LaTeX code`_ to place left-aligned "header" and "footer" on every page with fancyhdr_:: \usepackage{fancyhdr} \fancyhead[L]{\DUheader} \fancyfoot{} % reset \fancyfoot[L]{\DUfooter} \pagestyle{fancy} .. _fancyhdr: http://www.ctan.org/pkg/fancyhdr .. _"header" and "footer" directives: ../ref/rst/directives.html#header page numbering -------------- Example: Number pages by chapter (using the chappg_ package):: \usepackage{chappg} See the `chappg documentation`_ for details. .. _chappg: http://mirror.ctan.org/help/Catalogue/entries/chappg.html .. _chappg documentation: http://mirror.ctan.org/macros/latex/contrib/chappg/chappg.pdf paper size ---------- Paper geometry can be changed using ``--documentoptions`` or with the `geometry`_ package. `LaTeX code`_:: \usepackage{geometry} \geometry{OPTIONLIST} Default: a4paper Some possibilities: * a4paper, b3paper, letterpaper, executivepaper, legalpaper * landscape, portrait, twoside. Example: Choose A5 pager in landscape orientation with command line argument:: --documentoptions=a5paper,landscape The same with LaTeX commands in the `style sheet`_:: \usepackage{geometry} \geometry{a5paper,landscape} For details see the `geometry manual`_. paragraph indent ---------------- Default (in most document classes): Indent the first line in a paragraph unless it is the first line of a chapter, section, subsection, or subsubsection. Example: To set paragraph indentation to zero but add a vertical space between load the `parskip` package with the command line argument:: --stylesheet=parskip or in a custom `style sheet`_ with:: \usepackage{parskip} rubric ------ A rubric__ is like an informal heading that doesn't correspond to the document's structure. Command: ``\DUrubric`` Default: subsubsection style, italic, centred Example: set flushleft and red:: \newcommand*{\DUrubric}[2][class-arg]{% \subsubsection*{{\color{red}#1}\hfill}} __ ../ref/rst/directives.html#rubric section numbering ----------------- Sections are numbered if there is a `sectnum directive`_ in the document. Option: sectnum_xform_ ``--section-numbering``, ``--no-section-numbering`` If sectnum_xform_ is False, section numbers are generated by LaTeX. In this case the "prefix" and "suffix" arguments of the `sectnum directive`_ are ignored. The section number style is determined by the `document class`_ and can be configured in a LaTeX `style sheet`_, e.g.:: \setcounter{secnumdepth}{5} .. note:: The LaTeX name is 'secnumdepth' (whithout 't'). .. _sectnum directive: ../ref/rst/directives.html#sectnum .. _sectnum_xform: config.html#sectnum-xform sidebar ------- Sidebars__ are like miniature, parallel documents that occur inside other documents, providing related or reference material. They can be likened to super-footnotes; their content is outside of the flow of the document's main text. Command: ``DUsidebar`` Default: Box with grey background. Example 1: Less space before the title:: \providecommand{\DUsidebar}[2]{% \begin{center} \colorbox[gray]{0.90}{\parbox{0.9\textwidth}{% \smallskip\textbf{#1}\smallskip #2}} \end{center} } Example 2: Use margin notes:: \newcommand{\DUsidebar}[2]{\marginpar{\flushleft \textbf{#1} #2}} * Make sure the margin is wide enough to hold the note. * This fails with some constructs inside the `side bar` and where \marginpar cannot be used, e.g., inside floats, footnotes, or in frames made with the framed package (see marginnote_). __ http://docutils.sf.net/docutils/docs/ref/rst/directives.html#sidebar size of a pixel --------------- The length unit ``px`` is a "relative length" whose value depends on the *resolution* of the output device (usually specified in *dots per inch* (DPI). However, when producing a PDF, the resolution of the output device (printer, screen (for PDF-viewer)) is generally not known. With pdftex, the "resolution" is a configuration setting. Default: 72 DPI, i.e. 1 px = 1/72 in. Example: Set a resolution of 96 DPI with the `LaTeX code`_:: \pdfpxdimen=1in % 1 DPI \divide\pdfpxdimen by 96 % 96 DPI topic element ------------- A topic_ is like a block quote with a title, or a self-contained section with no subsections. Topics and rubrics can be used at places where a `section title`_ is not allowed (e.g. inside a directive). Command: ``DUtopic`` Default: "quote" environment Example 1: If you generally prefer a "normal" section over a block quote, define:: \newcommand{\DUtopic}[2][class-arg]{% \ifcsname DUtopic#1\endcsname% \csname DUtopic#1\endcsname{#2}% \else #2 \fi } Example 2: If you want a "normal" section for topics with class argument "noquote", define:: \newcommand{\DUtopicnoquote}[1]{#1} .. _topic: ../ref/rst/directives.html#topic .. _section title: ../ref/rst/restructuredtext.html#sections topic title ----------- The titles of admonitions_, sidebar_, and `topic element`_ are defined with the ``\DUtitle`` command that also takes a "class" argument. Example 1: a centered and somewhat larger title for topcis:: \newcommand*{\DUtitletopic}[1]{\subsection*{\centering #1} Example 2: a right-pointing hand as title for the "attention" directive:: \usepackage{pifont} \newcommand{\DUtitleattention}[1]{\ding{43}} The title argument is "swallowed" by the command. To have both, hand and title use:: \usepackage{pifont} \newcommand{\DUtitleattention}[1]{\ding{43} #1} table of contents ----------------- A `contents directive`_ is replaced by a table of contents (ToC). Option: use-latex-toc_ ``--use-latex-toc``, ``--use-docutils-toc`` With use-latex-toc (default since release 0.6): * The ToC is generated by LaTeX (via the ``\tableofcontents`` command). The layout depends on the choosen document class and can be configured in a custom `style sheet`_ (see e.g. the `KOMA-Script Guide`_ for the `KOMA-script`_ classes). * The depth of the ToC and PDF-bookmarks can be configured + with the "depth" argument of the `contents directive`_, or + in a style sheet with e.g. ``\setcounter{tocdepth}{5}``. * Local ToCs are done with the minitoc_ package. See the `minitoc documentation`_ for the numerous configuration options. .. note:: Minitoc supports local ToCs only at "part" and top section level ("chapter" or "section"). Local `contents` directives at lower levels are ignored (a warning is issued). This is an intended feature of the minitoc_ package. If you really require local ToCs at lower level, turn off the use-latex-toc_ option. .. _use-latex-toc: config.html#use-latex-toc .. _contents directive: ../ref/rst/directives.html#contents .. _minitoc: http://mirror.ctan.org/help/Catalogue/entries/minitoc.html .. _minitoc documentation: http://mirror.ctan.org/macros/latex/contrib/minitoc/minitoc.pdf title reference role -------------------- `Title reference`_ is the default `default role`_ for `interpreted text`_. Command: ``\DUroletitlereference`` Default: use slanted font (``\textsl``) Example: set title references with a bold monospace font:: \newcommand{\DUroletitlereference}[1]{\texttt{\textbf{#1}}} .. _title reference: ../ref/rst/roles.html#title-reference .. _default role: ../ref/rst/directives.html#setting-the-default-interpreted-text-role .. _interpreted text: ../ref/rst/restructuredtext.html#interpreted-text text encoding ------------- The encoding of the LaTeX source file is Docutils' *output* encoding but LaTeX' *input* encoding. Option: output-encoding_ ``--output-encoding=OUTPUT-ENCODING`` Default: "utf8" Example: Encode the LaTeX source file with the ISO `latin-1` (west european) 8-bit encoding (the default in Docutils versions up to 0.6.):: --output-encoding=latin-1 Note: LaTeX comes with two options for UTF-8 support, :utf8: by the standard `inputenc`_ package with only limited coverage (mainly accented characters). :utf8x: supported by the `ucs`_ package covers a wider range of Unicode characters than does "utf8". It is, however, a non-standard extension and no longer developed. Currently (in version 0.6), "utf8" is used if the output-encoding is any of "utf_8", "U8", "UTF", or "utf8". .. with utf8x: If LaTeX issues a Warning about unloaded/unknown characters adding :: \PreloadUnicodePage{n} (where *n* is the Unicode page-number) to the style sheet might help. .. _LaTeX Unicode: http://www.unruh.de/DniQ/latex/unicode/ .. _output-encoding: config.html#output-encoding .. _inputenc: http://mirror.ctan.org/help/Catalogue/entries/inputenc.html .. _ucs: http://mirror.ctan.org/help/Catalogue/entries/unicode.html transition element ------------------ Transitions__ are commonly seen in novels and short fiction, as a gap spanning one or more lines, marking text divisions or signaling changes in subject, time, point of view, or emphasis. Command: ``\DUtransition`` Default: A horizontal line, 1/3 of text width Example 1: Use three stars:: \newcommand*{\DUtransition}[1][class-arg]{\centering{}*\quad*\quad*} Alternatively use the more elaborated version in `transition-stars.sty`_. Example 2: If paragraphs are separated by indentation, you can simply use a vertical space:: \newcommand*{\DUtransition}[1][class-arg]{\vspace{2ex}} __ http://docutils.sf.net/docutils/docs/ref/rst/restructuredtext.html#transitions .. _transition-stars.sty: ../../../sandbox/stylesheets/transition-stars.sty Changes ======= * The Docutils HISTORY_ lists all changes during the history of docutils. * Changes since release (0.5) are summarized in the RELEASE-NOTES_ and explained in detail in docutils-05-compat_. * docutils-05-compat.sty_ is a `style sheet`_ that provides best possible backwards compatibility. .. _HISTORY: ../../HISTORY.html .. _RELEASE-NOTES: ../../RELEASE-NOTES.html .. _docutils-05-compat: docutils-05-compat.sty.html .. _docutils-05-compat.sty: ../../docutils/writers/latex2e/docutils-05-compat.sty Problems ======== Troubleshooting --------------- Bad looking PDF output `````````````````````` What I am looking for when I try Docutils is if the PDF files I can get are of high quality. Unfortunaltely that never is the case. So am I just stupid or is there a way to get really high quality pdf from Docutils? Make sure the default font is not a bitmap font. There is `Latin Modern`_ if you like the look of the standard font on paper, but want nice pdf. Or select something else like Times, Palatino, ... via configuration options_ to the Docutils tool. See font_ and font-encoding_. footnote mark and text at different pages ````````````````````````````````````````` Docutils stores the footnote text in a separate node, at the position where it is specified in the input document. With the default settings, the footnote is put at the bottom of the page where the footnote text is located, maybe far away from the footnote mark (see e.g. ``_). To get footnote mark and text at the same page, keep footnote mark and footnote text close together! non-breaking hyperlinks ``````````````````````` If you convert with ``latex`` (as opposed to ``pdflatex``), hyperlinks will not wrap and sometimes stick into the margin. Wrong: :: \usepackage[breaklinks=true]{hyperref} "breaklinks" is an internal option that indicates whether the chosen driver can handle split links. (It might work to *disable* link breaking.) Right: Use one of the following: a) compile with pdflatex_, b) compile with `latex + dvipdfmx`_, c) use the package breakurl_, d) (for printout) `disable hyperlinks`_ using the package "nohyperref". See also the `Link text doesn’t break at end line`_ FAQ entry. .. _breakurl: http://mirror.ctan.org/help/Catalogue/entries/breakurl.html .. _Link text doesn’t break at end line: http://www.tex.ac.uk/cgi-bin/texfaq2html?label=breaklinks Glyph not defined in PD1 encoding ````````````````````````````````` If a section title or other link contains non-Latin (e.g. Cyrillic) characters, the LaTeX log contains lots of warnings like:: Package hyperref Warning: Glyph not defined in PD1 encoding, (hyperref) removing `\CYRZ' on input line 6. ... This can be solved with the "unicode" hyperref_option_ setting:: --hyperref-option=unicode (works also with non-unicode input/output encoding (e.g. "koi8r" or "latin1"). Newer versions of hyperref default to "unicode=true" if the document language is "russian". However, this setting leads to "strange" characters in the bookmarks if used with xelatex_ in hyperref versions before v6.79g (2009/11/20). (cf `bugreport 3100778`__). If updating the hyperref package is not an option, the workaround is to set :: --hyperref-option="unicode=false" or (in the config file):: [xetex writer] hyperref-option: unicode=false __ http://sourceforge.net/tracker/?func=detail&aid=3100778&group_id=38414&atid=422030 .. _hyperref_option: config.html#stylesheet-latex2e-writer image inclusion ``````````````` Images__ are included in LaTeX with the help of the `graphicx` package. The supported file formats depend on the used driver: * Standard latex_ can include **only EPS** graphics, no other format. * `latex + dvipdfmx`_ works with EPS and JPG (add 'dvipdfmx' to the documentoptions_ and 'bmpsize' to the stylesheet_ setting). * pdflatex_ and xelatex_ work with PNG, JPG, or PDF, but **not EPS**. If PDF-image inclusion in PDF files fails, specifying ``--graphicx-option=pdftex`` or ``--graphicx-option=auto`` might help. For details see grfguide.pdf_. The Rubber_ wrapper can be used for automatic image conversion. Docutils expects an URI as pointer to the image file. The latex writer transforms this URI to a local path. By default, LaTeX does not accept spaces and more than one dot in the filename. If using "traditional" filenames is not an option, the adding grffile_ to the `style sheets`_ can help. __ ../ref/rst/directives.html#images .. _grfguide.pdf: http://mirror.ctan.org/macros/latex/required/graphics/grfguide.pdf .. _grffile: http://mirror.ctan.org/help/Catalogue/entries/grffile.html Why are my images too big? `````````````````````````` HTML-browsers use the actual screen resolution (usually around 100 DPI). The CSS specification suggests: It is recommended that the reference pixel be the visual angle of one pixel on a device with a pixel density of 96 DPI and a distance from the reader of an arm's length. -- http://www.w3.org/TR/CSS2/syndata.html#length-units This is why pixmap images without size specification or objects with a size specified in ``px`` tend to come too large in the PDF. Solution: Specify the image size in fixed units (``pt``, ``cm``, ``in``) or configure the `size of a pixel`_ (length unit px). Error ``illegal unit px`` ````````````````````````` If you convert the LaTeX source with a legacy program, you might get this error. The unit "px" was introduced by the `pdfTeX` converter on 2005-02-04. `pdfTeX` is used also for conversion into DVI format in all modern LaTeX distributions (since ca. 2006). If updating LaTeX is not an option, just remove the "px" from the length specification. HTML/CSS will default to "px" while the `latexe2` writer will add the fallback unit "bp". Error ``Symbol \textcurrency not provided`` ... ``````````````````````````````````````````````` The currency sign (\\u00a4) is not supported by all fonts (some have an Euro sign at its place). You might see an error like:: ! Package textcomp Error: Symbol \textcurrency not provided by (textcomp) font family ptm in TS1 encoding. (textcomp) Default family used instead. (which in case of font family "ptm" is a false positive). Add either :warn: turn the error in a warning, use the default symbol (bitmap), or :force,almostfull: use the symbol provided by the font at the users risk, to the document options or use a different font package. Search and text extraction `````````````````````````` Search for text that contains characters outside the ASCII range (e.g. umlauts) might fail. See font_ and `font encoding`_ (as well as `Searching PDF files`_ for background information). .. _Searching PDF files: http://www.tex.ac.uk/cgi-bin/texfaq2html?label=srchpdf Unicode box drawing and block characters ```````````````````````````````````````` The easiest solution is to use xelatex_ for `PDF generation`_. With "traditional" TeX engines (e.g. pdflatex_): - Generate LaTeX code with `output-encoding`_ "utf-8". - Add the pmboxdraw_ package to the `style sheets`_. (For shaded boxes also add the `color` package.) Unfortunately, this defines only a subset of the characters (see pmboxdraw.pdf_ for a list). .. _pmboxdraw: http://mirror.ctan.org/help/Catalogue/entries/pmboxdraw.html .. _pmboxdraw.pdf: http://mirror.ctan.org/macros/latex/contrib/oberdiek/pmboxdraw.pdf Bugs and open issues -------------------- Open to be fixed or open to discussion. See also the entries in the `Docutils TODO list`_, the BUGS_ documentation and the `SourceForge Bug Tracker`_. .. _Docutils TODO list: ../dev/todo.html#latex-writer .. _bugs: ../../BUGS.html .. _SourceForge Bug Tracker: http://sourceforge.net/tracker/?group_id=38414&atid=422030 Footnotes and citations ``````````````````````` Initially both were implemented using figure floats, because hyperlinking back and forth seemed to be impossible. Later the `figure` directive was added that puts images into figure floats. This results in footnotes, citations, and figures possibly being mixed at page foot. Workaround: Select footnote and citation handling with the docutils-footnotes_ and use-latex-citations_ options. If ``use-latex-citations`` is used, a bibliography is inserted right at the end of the document. *This should be customizable*. If ``use-latex-citations`` is used adjacent citation references (separated only by a single space or a newline) are combined to a single citation group, i.e. ``[cite1]_ [cite2]_`` results in ``\cite{cite1,cite2}``. The appearance in the output can be configured in a `style sheet`_. .. _docutils-footnotes: config.html#docutils-footnotes .. _use-latex-citations: config.html#use-latex-citations Tables `````` :Tablewidth: reST-documents line length is assumed to be 80 characters. The tablewidth is set relative to this value. If someone produces documents with line length of 132 this will fail. Table width is tried to fit in page even if it is wider than the assumed linewidth, still assumed linewidth is a hook. * Table: multicol cells are always left aligned. * The contents of a rowspan cell do not influence table height. (multirow "feature", use a phantom or strut?) * Multirow cells might mix up the following table rows. * Table cells with both multirow and multicolumn are currently not possible. * literal-blocks in table cells: - If verbatim or flushleft is used one gets vertical space above and below. - This is bad for the topmost paragraph in a cell, therefore the writer uses raggedright. - Ragged right fails on followup paragraphs as the vertical space would be missing. * ``--table-style=booktabs``, ``..class:: booktab``: `booktabs` version 1.00 does not work with `longtable`. This is solved in newer versions (current is 2005/04/14 v1.61803). Figures ``````` * Figures are always as wide as the containing text. The "figwidth" argument is currently not supported. As a consequence, the "align" argument has no effect. * Wrapping text around figures is currently not supported. (Requires the `wrapfig`_ package.) .. _wrapfig: http://mirror.ctan.org/help/Catalogue/entries/wrapfig.html Miscellaneous ````````````` * Pdfbookmark level 4 (and greater) does not work (might be settable but complicated). * Hyperlinks are not hyphenated; this leads to bad spacing. See docs/user/rst/demo.txt 2.14 directives. * Pagestyle headings does not work, when sections are starred. Use LaTeX for the section numbering with the options_ ``--no-section-numbers`` (command line) or ``sectnum_xform: False`` (config file). docutils-0.12/docs/user/tools.txt0000664000175000017500000003107612164770550021051 0ustar engelbertengelbert00000000000000========================== Docutils Front-End Tools ========================== :Author: David Goodger :Contact: docutils-develop@lists.sourceforge.net :Revision: $Revision: 7677 $ :Date: $Date: 2013-07-03 11:39:52 +0200 (Mit, 03. Jul 2013) $ :Copyright: This document has been placed in the public domain. .. contents:: -------------- Introduction -------------- Once the Docutils package is unpacked, you will discover a "``tools``" directory containing several front ends for common Docutils processing. Rather than a single all-purpose program, Docutils has many small front ends, each specialized for a specific "Reader" (which knows how to interpret a file in context), a "Parser" (which understands the syntax of the text), and a "Writer" (which knows how to generate a specific data format). Most front ends have common options and the same command-line usage pattern:: toolname [options] [ [ given, and their subdirectories too. (Use the ``--local`` option to skip subdirectories.) Usage:: buildhtml.py [options] [ ...] After unpacking the Docutils package, the following shell commands will generate HTML for all included documentation:: cd docutils/tools buildhtml.py .. For official releases, the directory may be called "docutils-X.Y", where "X.Y" is the release version. Alternatively:: cd docutils tools/buildhtml.py --config=tools/docutils.conf The current directory (and all subdirectories) is chosen by default if no directory is named. Some files may generate system messages (docs/user/rst/demo.txt contains intentional errors); use the ``--quiet`` option to suppress all warnings. The ``--config`` option ensures that the correct settings are in place (a ``docutils.conf`` `configuration file`_ in the current directory is picked up automatically). Command-line options may be used to override config file settings or replace them altogether. rst2html.py ----------- :Reader: Standalone :Parser: reStructuredText :Writer: HTML The ``rst2html.py`` front end reads standalone reStructuredText source files and produces HTML 4 (XHTML 1) output compatible with modern browsers that support cascading stylesheets (CSS). A stylesheet is required for proper rendering; a simple but complete stylesheet is installed and used by default (see Stylesheets_ below). For example, to process a reStructuredText file "``test.txt``" into HTML:: rst2html.py test.txt test.html Now open the "``test.html``" file in your favorite browser to see the results. To get a footer with a link to the source file, date & time of processing, and links to the Docutils project, add some options:: rst2html.py -stg test.txt test.html Stylesheets ``````````` ``rst2html.py`` inserts into the generated HTML a cascading stylesheet (or a link to a stylesheet, when passing the "``--link-stylesheet``" option). A stylesheet is required for proper rendering. The default stylesheet (``docutils/writers/html4css1/html4css1.css``, located in the installation directory) is provided for basic use. To use a different stylesheet, you must specify the stylesheet's location with a "``--stylesheet``" (for a URL) or "``--stylesheet-path``" (for a local file) command-line option, or with `configuration file`_ settings (e.g. ``./docutils.conf`` or ``~/.docutils``). To experiment with styles, please see the `guide to writing HTML (CSS) stylesheets for Docutils`__. __ ../howto/html-stylesheets.html rstpep2html.py -------------- :Reader: PEP :Parser: reStructuredText :Writer: PEP/HTML ``rstpep2html.py`` reads a new-style PEP (marked up with reStructuredText) and produces HTML. It requires a template file and a stylesheet. By default, it makes use of a "``pep-html-template``" file and the "``pep.css``" stylesheet (both in the ``docutils/writers/pep_html/`` directory), but these can be overridden by command-line options or configuration files. For example, to process a PEP into HTML:: cd /docs/peps rstpep2html.py pep-0287.txt pep-0287.html rst2s5.py --------- :Reader: Standalone :Parser: reStructuredText :Writer: S5/HTML The ``rst2s5.py`` front end reads standalone reStructuredText source files and produces (X)HTML output compatible with S5_, the "Simple Standards-based Slide Show System" by Eric Meyer. A theme is required for proper rendering; several are distributed with Docutils and others are available; see Themes_ below. For example, to process a reStructuredText file "``slides.txt``" into S5/HTML:: rst2s5.py slides.txt slides.html Now open the "``slides.html``" file in your favorite browser, switch to full-screen mode, and enjoy the results. .. _S5: http://meyerweb.com/eric/tools/s5/ Themes `````` Each S5 theme consists of a directory containing several files: stylesheets, JavaScript, and graphics. These are copied into a ``ui/`` directory beside the generated HTML. A theme is chosen using the "``--theme``" option (for themes that come with Docutils) or the "``--theme-url``" option (for themes anywhere). For example, the "medium-black" theme can be specified as follows:: rst2s5.py --theme medium-black slides.txt slides.html The theme will be copied to the ``ui/medium-black`` directory. Several themes are included with Docutils: ``default`` This is a simplified version of S5's default theme. :Main content: black serif text on a white background :Text capacity: about 13 lines :Headers: light blue, bold sans-serif text on a dark blue background; titles are limited to one line :Footers: small, gray, bold sans-serif text on a dark blue background ``small-white`` (Small text on a white background.) :Main content: black serif text on a white background :Text capacity: about 15 lines :Headers: black, bold sans-serif text on a white background; titles wrap :Footers: small, dark gray, bold sans-serif text on a white background ``small-black`` :Main content: white serif text on a black background :Text capacity: about 15 lines :Headers: white, bold sans-serif text on a black background; titles wrap :Footers: small, light gray, bold sans-serif text on a black background ``medium-white`` :Main content: black serif text on a white background :Text capacity: about 9 lines :Headers: black, bold sans-serif text on a white background; titles wrap :Footers: small, dark gray, bold sans-serif text on a white background ``medium-black`` :Main content: white serif text on a black background :Text capacity: about 9 lines :Headers: white, bold sans-serif text on a black background; titles wrap :Footers: small, light gray, bold sans-serif text on a black background ``big-white`` :Main content: black, bold sans-serif text on a white background :Text capacity: about 5 lines :Headers: black, bold sans-serif text on a white background; titles wrap :Footers: not displayed ``big-black`` :Main content: white, bold sans-serif text on a black background :Text capacity: about 5 lines :Headers: white, bold sans-serif text on a black background; titles wrap :Footers: not displayed If a theme directory contains a file named ``__base__``, the name of the theme's base theme will be read from it. Files are accumulated from the named theme, any base themes, and the "default" theme (which is the implicit base of all themes). For details, please see `Easy Slide Shows With reStructuredText & S5 `_. LaTeX-Generating Tools ====================== rst2latex.py ------------ :Reader: Standalone :Parser: reStructuredText :Writer: LaTeX2e The ``rst2latex.py`` front end reads standalone reStructuredText source files and produces LaTeX2e output. For example, to process a reStructuredText file "``test.txt``" into LaTeX:: rst2latex.py test.txt test.tex The output file "``test.tex``" should then be processed with ``latex`` or ``pdflatex`` to get a document in DVI, PostScript or PDF format for printing or on-screen viewing. For details see `Generating LaTeX with Docutils`_. XML-Generating Tools ==================== rst2xml.py ---------- :Reader: Standalone :Parser: reStructuredText :Writer: XML (Docutils native) The ``rst2xml.py`` front end produces Docutils-native XML output. This can be transformed with standard XML tools such as XSLT processors into arbitrary final forms. An example is the xml2rst_ processor in the Docutils sandbox. .. _xml2rst: ../../../sandbox/xml2rst ODF/OpenOffice-Generating Tools =============================== rst2odt.py ---------- :Reader: Standalone :Parser: reStructuredText :Writer: ODF/.odt The ``rst2odt.py`` front end reads standalone reStructuredText source files and produces ODF/.odt files that can be read, edited, printed, etc with OpenOffice ``oowriter`` (http://www.openoffice.org/). A stylesheet file is required. A stylesheet file is an OpenOffice .odt file containing definitions of the styles required for ``rst2odt.py``. You can learn more about how to use ``rst2odt.py``, the styles used ``rst2odt.py``, etc from `Odt Writer for Docutils `_. reStructuredText-Generating Tools ================================= Currently, there is no reStructuredText writer in Docutils and therefore an ``rst2rst.py`` tool is still missing. To generate reStructuredText documents with Docutils, you can use the XML (Docutils native) writer and the xml2rst_ processor. Testing/Debugging Tools ======================= rst2pseudoxml.py ---------------- :Reader: Standalone :Parser: reStructuredText :Writer: Pseudo-XML ``rst2pseudoxml.py`` is used for debugging the Docutils "Reader to Transform to Writer" pipeline. It produces a compact pretty-printed "pseudo-XML", where nesting is indicated by indentation (no end-tags). External attributes for all elements are output, and internal attributes for any leftover "pending" elements are also given. quicktest.py ------------ :Reader: N/A :Parser: reStructuredText :Writer: N/A The ``quicktest.py`` tool is used for testing the reStructuredText parser. It does not use a Docutils Reader or Writer or the standard Docutils command-line options. Rather, it does its own I/O and calls the parser directly. No transforms are applied to the parsed document. Various forms output are possible: - Pretty-printed pseudo-XML (default) - Test data (Python list of input and pseudo-XML output strings; useful for creating new test cases) - Pretty-printed native XML - Raw native XML (with or without a stylesheet reference) --------------- Customization --------------- Command-Line Options ==================== Each front-end tool supports command-line options for one-off customization. For persistent customization, use `configuration files`_. Command-line options take priority over configuration file settings. Use the "--help" option on each of the front ends to list the command-line options it supports. Command-line options and their corresponding configuration file entry names are listed in the `Docutils Configuration Files`_ document. .. _configuration file: Configuration Files =================== Configuration files are used for persistent customization; they can be set once and take effect every time you use a front-end tool. For details, see `Docutils Configuration Files`_. .. _Docutils Configuration Files: config.html .. _Generating LaTeX with Docutils: latex.html .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: docutils-0.12/docs/user/rst/0000775000175000017500000000000012356234260017745 5ustar engelbertengelbert00000000000000docutils-0.12/docs/user/rst/quickstart.txt0000664000175000017500000002601311116755202022677 0ustar engelbertengelbert00000000000000A ReStructuredText Primer ========================= :Author: Richard Jones :Version: $Revision: 5801 $ :Copyright: This document has been placed in the public domain. .. contents:: 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. __ .. _Quick reStructuredText: quickref.html .. _master quick reference: http://docutils.sourceforge.net/docs/user/rst/quickref.html .. Note:: This document is an informal introduction to reStructuredText. The `What Next?`_ section below has links to further resources, including a formal reference. 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. __ quickref.html#paragraphs Text styles ----------- (quickref__) __ quickref.html#inline-markup Inside paragraphs and other bodies of text, you may additionally mark text for *italics* with "``*italics*``" or **bold** with "``**bold**``". This is called "inline markup". 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 lone asterisk * is handled just fine, as is the asterisk in this equation: 5*6=30. 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:: ``*`` __ quickref.html#escaping .. Tip:: Think of inline markup as a form of (parentheses) and use it the same way: immediately before and after the text being marked up. Inline markup by itself (surrounded by whitespace) or in the middle of a word won't be recognized. See the `markup spec`__ for full details. __ ../../ref/rst/restructuredtext.html#inline-markup 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. **enumerated** lists (numbers, letters or roman numerals; quickref__) __ quickref.html#enumerated-lists Start a line off with a number or letter followed by a period ".", right bracket ")" or surrounded by brackets "( )" -- whatever you're comfortable with. All of the following forms are recognised:: 1. numbers A. upper-case letters and it goes over many lines with two paragraphs and all! a. lower-case letters 3. with a sub-list starting at a different number 4. make sure the numbers are in the correct sequence though! I. upper-case roman numerals i. lower-case roman numerals (1) numbers again 1) and again Results in (note: the different enumerated list styles are not always supported by every web browser, so you may not get the full effect here): 1. numbers A. upper-case letters and it goes over many lines with two paragraphs and all! a. lower-case letters 3. with a sub-list starting at a different number 4. make sure the numbers are in the correct sequence though! I. upper-case roman numerals i. lower-case roman numerals (1) numbers again 1) and again **bulleted** lists (quickref__) __ quickref.html#bullet-lists 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__) __ quickref.html#definition-lists 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__) __ quickref.html#literal-blocks 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__) __ quickref.html#section-structure 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::
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__) __ quickref.html#directives To include an image in your document, you use the the ``image`` directive__. For example:: .. image:: images/biohazard.png results in: .. image:: images/biohazard.png 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/biohazard.png :height: 100 :width: 200 :scale: 50 :alt: alternate text See the full `image directive documentation`__ for more info. __ ../../ref/rst/directives.html __ ../../ref/rst/directives.html#images 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 [#]_. Users who have questions or need assistance with Docutils or reStructuredText should post a message to the Docutils-users_ mailing list. .. [#] If that relative link doesn't work, try the master document: http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html. .. _reStructuredText Markup Specification: ../../ref/rst/restructuredtext.html .. _Docutils-users: ../mailing-lists.html#docutils-users .. _Docutils project web site: http://docutils.sourceforge.net/ ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������docutils-0.12/docs/user/rst/quickref.html�����������������������������������������������������������0000664�0001750�0001750�00000146663�11227110256�022456� 0����������������������������������������������������������������������������������������������������ustar �engelbert�����������������������engelbert�����������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Quick reStructuredText

Quick reStructuredText

http://docutils.sourceforge.net/docs/user/rst/quickref.html
Being a cheat-sheet for reStructuredText
Updated $Date: 2009-07-14 16:05:34 +0200 (Die, 14. Jul 2009) $

Copyright: This document has been placed in the public domain.

The full details of the markup may be found on the reStructuredText page. This document is just intended as a reminder.

Links that look like "(details)" point into the HTML version of the full reStructuredText specification document. These are relative links; if they don't work, please use the master "Quick reStructuredText" document.

Contents

Inline Markup

(details)

Inline markup allows words and phrases within text to have character styles (like italics and boldface) and functionality (like hyperlinks).

Plain text Typical result Notes
*emphasis* emphasis Normally rendered as italics.
**strong emphasis** strong emphasis Normally rendered as boldface.
`interpreted text` (see note at right) The rendering and meaning of interpreted text is domain- or application-dependent. It can be used for things like index entries or explicit descriptive markup (like program identifiers).
``inline literal`` inline literal Normally rendered as monospaced text. Spaces should be preserved, but line breaks will not be.
reference_ reference A simple, one-word hyperlink reference. See Hyperlink Targets.
`phrase reference`_ phrase reference A hyperlink reference with spaces or punctuation needs to be quoted with backquotes. See Hyperlink Targets.
anonymous__ anonymous With two underscores instead of one, both simple and phrase references may be anonymous (the reference text is not repeated at the target). See Hyperlink Targets.
_`inline internal target` inline internal target A crossreference target within text. See Hyperlink Targets.
|substitution reference| (see note at right) The result is substituted in from the substitution definition. It could be text, an image, a hyperlink, or a combination of these and others.
footnote reference [1]_ footnote reference 1 See Footnotes.
citation reference [CIT2002]_ citation reference [CIT2002] See Citations.
http://docutils.sf.net/ http://docutils.sf.net/ A standalone hyperlink.

Asterisk, backquote, vertical bar, and underscore are inline delimiter characters. Asterisk, backquote, and vertical bar act like quote marks; matching characters surround the marked-up word or phrase, whitespace or other quoting is required outside them, and there can't be whitespace just inside them. If you want to use inline delimiter characters literally, escape (with backslash) or quote them (with double backquotes; i.e. use inline literals).

In detail, the reStructuredText specification says that in inline markup, the following rules apply to start-strings and end-strings (inline markup delimiters):

  1. The start-string must start a text block or be immediately preceded by whitespace or any of  ' " ( [ { or <.
  2. The start-string must be immediately followed by non-whitespace.
  3. The end-string must be immediately preceded by non-whitespace.
  4. The end-string must end a text block (end of document or followed by a blank line) or be immediately followed by whitespace or any of ' " . , : ; ! ? - ) ] } / \ or >.
  5. If a start-string is immediately preceded by one of  ' " ( [ { or <, it must not be immediately followed by the corresponding character from  ' " ) ] } or >.
  6. An end-string must be separated by at least one character from the start-string.
  7. An unescaped backslash preceding a start-string or end-string will disable markup recognition, except for the end-string of inline literals.

Also remember that inline markup may not be nested (well, except that inline literals can contain any of the other inline markup delimiter characters, but that doesn't count because nothing is processed).

Escaping with Backslashes

(details)

reStructuredText uses backslashes ("\") to override the special meaning given to markup characters and get the literal characters themselves. To get a literal backslash, use an escaped backslash ("\\"). For example:

Raw reStructuredText Typical result
*escape* ``with`` "\" escape with ""
\*escape* \``with`` "\\" *escape* ``with`` "\"

In Python strings it will, of course, be necessary to escape any backslash characters so that they actually reach reStructuredText. The simplest way to do this is to use raw strings:

Python string Typical result
r"""\*escape* \`with` "\\"""" *escape* `with` "\"
 """\\*escape* \\`with` "\\\\"""" *escape* `with` "\"
 """\*escape* \`with` "\\"""" escape with ""

Section Structure

(details)

Plain text Typical result
=====
Title
=====
Subtitle
--------
Titles are underlined (or over-
and underlined) with a printing
nonalphanumeric 7-bit ASCII
character. Recommended choices
are "``= - ` : ' " ~ ^ _ * + # < >``".
The underline/overline must be at
least as long as the title text.

A lone top-level (sub)section
is lifted up to be the document's
(sub)title.
Title

Subtitle

Titles are underlined (or over- and underlined) with a printing nonalphanumeric 7-bit ASCII character. Recommended choices are "= - ` : ' " ~ ^ _ * + # < >". The underline/overline must be at least as long as the title text.

A lone top-level (sub)section is lifted up to be the document's (sub)title.

Paragraphs

(details)

Plain text Typical result

This is a paragraph.

Paragraphs line up at their left
edges, and are normally separated
by blank lines.

This is a paragraph.

Paragraphs line up at their left edges, and are normally separated by blank lines.

Bullet Lists

(details)

Plain text Typical result
Bullet lists:

- This is item 1
- This is item 2

- Bullets are "-", "*" or "+".
  Continuing text must be aligned
  after the bullet and whitespace.

Note that a blank line is required
before the first item and after the
last, but is optional between items.

Bullet lists:
  • This is item 1
  • This is item 2
  • Bullets are "-", "*" or "+". Continuing text must be aligned after the bullet and whitespace.

Note that a blank line is required before the first item and after the last, but is optional between items.

Enumerated Lists

(details)

Plain text Typical result
Enumerated lists:

3. This is the first item
4. This is the second item
5. Enumerators are arabic numbers,
   single letters, or roman numerals
6. List items should be sequentially
   numbered, but need not start at 1
   (although not all formatters will
   honour the first index).
#. This item is auto-enumerated

Enumerated lists:
  1. This is the first item
  2. This is the second item
  3. Enumerators are arabic numbers, single letters, or roman numerals
  4. List items should be sequentially numbered, but need not start at 1 (although not all formatters will honour the first index).
  5. This item is auto-enumerated

Definition Lists

(details)

Plain text Typical result
Definition lists:

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.
Definition lists:
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.

Field Lists

(details)

Plain text Typical result
:Authors:
    Tony J. (Tibs) Ibbs,
    David Goodger

    (and sundry other good-natured folks)

:Version: 1.0 of 2001/08/08
:Dedication: To my father.

Authors: Tony J. (Tibs) Ibbs, David Goodger
(and sundry other good-natured folks)
Version:1.0 of 2001/08/08
Dedication:To my father.

Field lists are used as part of an extension syntax, such as options for directives, or database-like records meant for further processing. Field lists may also be used as generic two-column table constructs in documents.

Option Lists

(details)

Plain text Typical result

-a            command-line option "a"
-b file       options can have arguments
              and long descriptions
--long        options can be long also
--input=file  long options can also have
              arguments
/V            DOS/VMS-style options too

-a command-line option "a"
-b file options can have arguments and long descriptions
--long options can be long also
--input=file long options can also have arguments
/V DOS/VMS-style options too

There must be at least two spaces between the option and the description.

Literal Blocks

(details)

Plain text Typical result
A paragraph containing only two colons
indicates that the following indented
or quoted text is a literal block.

::

  Whitespace, newlines, blank lines, and
  all kinds of markup (like *this* or
  \this) is preserved by literal blocks.

  The paragraph containing only '::'
  will be omitted from the result.

The ``::`` may be tacked onto the very
end of any paragraph. The ``::`` will be
omitted if it is preceded by whitespace.
The ``::`` will be converted to a single
colon if preceded by text, like this::

  It's very convenient to use this form.

Literal blocks end when text returns to
the preceding paragraph's indentation.
This means that something like this
is possible::

      We start here
    and continue here
  and end here.

Per-line quoting can also be used on
unindented literal blocks::

> Useful for quotes from email and
> for Haskell literate programming.

A paragraph containing only two colons indicates that the following indented or quoted text is a literal block.

  Whitespace, newlines, blank lines, and
  all kinds of markup (like *this* or
  \this) is preserved by literal blocks.

  The paragraph containing only '::'
  will be omitted from the result.

The :: may be tacked onto the very end of any paragraph. The :: will be omitted if it is preceded by whitespace. The :: will be converted to a single colon if preceded by text, like this:

  It's very convenient to use this form.

Literal blocks end when text returns to the preceding paragraph's indentation. This means that something like this is possible:

      We start here
    and continue here
  and end here.

Per-line quoting can also be used on unindented literal blocks:

  > Useful for quotes from email and
  > for Haskell literate programming.

Line Blocks

(details)

Plain text Typical result
| Line blocks are useful for addresses,
| verse, and adornment-free lists.
|
| Each new line begins with a
| vertical bar ("|").
|     Line breaks and initial indents
|     are preserved.
| Continuation lines are wrapped
  portions of long lines; they begin
  with spaces in place of vertical bars.
Line blocks are useful for addresses,
verse, and adornment-free lists.

Each new line begins with a
vertical bar ("|").
Line breaks and initial indents
are preserved.
Continuation lines are wrapped portions of long lines; they begin with spaces in place of vertical bars.

Block Quotes

(details)

Plain text Typical result
Block quotes are just:

    Indented paragraphs,

        and they may nest.

Block quotes are just:

Indented paragraphs,

and they may nest.

Use empty comments to separate indentation contexts, such as block quotes and directive contents.

Doctest Blocks

(details)

Plain text Typical result

Doctest blocks are interactive
Python sessions. They begin with
"``>>>``" and end with a blank line.

>>> print "This is a doctest block."
This is a doctest block.

Doctest blocks are interactive Python sessions. They begin with ">>>" and end with a blank line.

>>> print "This is a doctest block."
This is a doctest block.

"The doctest module searches a module's docstrings for text that looks like an interactive Python session, then executes all such sessions to verify they still work exactly as shown." (From the doctest docs.)

Tables

(details)

There are two syntaxes for tables in reStructuredText. Grid tables are complete but cumbersome to create. Simple tables are easy to create but limited (no row spans, etc.).

Plain text Typical result

Grid table:

+------------+------------+-----------+
| Header 1   | Header 2   | Header 3  |
+============+============+===========+
| body row 1 | column 2   | column 3  |
+------------+------------+-----------+
| body row 2 | Cells may span columns.|
+------------+------------+-----------+
| body row 3 | Cells may  | - Cells   |
+------------+ span rows. | - contain |
| body row 4 |            | - blocks. |
+------------+------------+-----------+

Grid table:

Header 1 Header 2 Header 3
body row 1 column 2 column 3
body row 2 Cells may span columns.
body row 3 Cells may
span rows.
  • Cells
  • contain
  • blocks.
body row 4

Simple table:

=====  =====  ======
   Inputs     Output
------------  ------
  A      B    A or B
=====  =====  ======
False  False  False
True   False  True
False  True   True
True   True   True
=====  =====  ======

Simple table:

Inputs Output
A B A or B
False False False
True False True
False True True
True True True

Transitions

(details)

Plain text Typical result

A transition marker is a horizontal line
of 4 or more repeated punctuation
characters.

------------

A transition should not begin or end a
section or document, nor should two
transitions be immediately adjacent.

A transition marker is a horizontal line of 4 or more repeated punctuation characters.


A transition should not begin or end a section or document, nor should two transitions be immediately adjacent.

Transitions are commonly seen in novels and short fiction, as a gap spanning one or more lines, marking text divisions or signaling changes in subject, time, point of view, or emphasis.

Explicit Markup

Explicit markup blocks are used for constructs which float (footnotes), have no direct paper-document representation (hyperlink targets, comments), or require specialized processing (directives). They all begin with two periods and whitespace, the "explicit markup start".

Footnotes

(details)

Plain text Typical result
Footnote references, like [5]_.
Note that footnotes may get
rearranged, e.g., to the bottom of
the "page".

.. [5] A numerical footnote. Note
   there's no colon after the ``]``.

Footnote references, like 5. Note that footnotes may get rearranged, e.g., to the bottom of the "page".


[5] A numerical footnote. Note there's no colon after the ].

Autonumbered footnotes are
possible, like using [#]_ and [#]_.

.. [#] This is the first one.
.. [#] This is the second one.

They may be assigned 'autonumber
labels' - for instance,
[#fourth]_ and [#third]_.

.. [#third] a.k.a. third_

.. [#fourth] a.k.a. fourth_

Autonumbered footnotes are possible, like using 1 and 2.

They may be assigned 'autonumber labels' - for instance, 4 and 3.


[1] This is the first one.
[2] This is the second one.
[3] a.k.a. third
[4] a.k.a. fourth

Auto-symbol footnotes are also
possible, like this: [*]_ and [*]_.

.. [*] This is the first one.
.. [*] This is the second one.

Auto-symbol footnotes are also possible, like this: * and .


[*] This is the first symbol footnote
[†] This is the second one.

The numbering of auto-numbered footnotes is determined by the order of the footnotes, not of the references. For auto-numbered footnote references without autonumber labels ("[#]_"), the references and footnotes must be in the same relative order. Similarly for auto-symbol footnotes ("[*]_").

Citations

(details)

Plain text Typical result
Citation references, like [CIT2002]_.
Note that citations may get
rearranged, e.g., to the bottom of
the "page".

.. [CIT2002] A citation
   (as often used in journals).

Citation labels contain alphanumerics,
underlines, hyphens and fullstops.
Case is not significant.

Given a citation like [this]_, one
can also refer to it like this_.

.. [this] here.

Citation references, like [CIT2002]. Note that citations may get rearranged, e.g., to the bottom of the "page".

Citation labels contain alphanumerics, underlines, hyphens and fullstops. Case is not significant.

Given a citation like [this], one can also refer to it like this.


[CIT2002] A citation (as often used in journals).
[this] here.

Hyperlink Targets

(details)

External Hyperlink Targets

Plain text Typical result
External hyperlinks, like Python_.

.. _Python: http://www.python.org/

Fold-in form
External hyperlinks, like Python.
Call-out form
External hyperlinks, like Python.


Python: http://www.python.org/

"Fold-in" is the representation typically used in HTML documents (think of the indirect hyperlink being "folded in" like ingredients into a cake), and "call-out" is more suitable for printed documents, where the link needs to be presented explicitly, for example as a footnote. You can force usage of the call-out form by using the "target-notes" directive.

reStructuredText also provides for embedded URIs (details), a convenience at the expense of readability. A hyperlink reference may directly embed a target URI inline, within angle brackets. The following is exactly equivalent to the example above:

Plain text Typical result
External hyperlinks, like `Python
<http://www.python.org/>`_.
External hyperlinks, like Python.

Internal Hyperlink Targets

Plain text Typical result
Internal crossreferences, like example_.

.. _example:

This is an example crossreference target.

Fold-in form
Internal crossreferences, like example

This is an example crossreference target.

Call-out form
Internal crossreferences, like example

example:
This is an example crossreference target.

Indirect Hyperlink Targets

(details)

Plain text Typical result
Python_ is `my favourite
programming language`__.

.. _Python: http://www.python.org/

__ Python_

Python is my favourite programming language.

The second hyperlink target (the line beginning with "__") is both an indirect hyperlink target (indirectly pointing at the Python website via the "Python_" reference) and an anonymous hyperlink target. In the text, a double-underscore suffix is used to indicate an anonymous hyperlink reference. In an anonymous hyperlink target, the reference text is not repeated. This is useful for references with long text or throw-away references, but the target should be kept close to the reference to prevent them going out of sync.

Implicit Hyperlink Targets

(details)

Section titles, footnotes, and citations automatically generate hyperlink targets (the title text or footnote/citation label is used as the hyperlink name).

Plain text Typical result
Titles are targets, too
=======================
Implict references, like `Titles are
targets, too`_.
Titles are targets, too

Implict references, like Titles are targets, too.

Directives

(details)

Directives are a general-purpose extension mechanism, a way of adding support for new constructs without adding new syntax. For a description of all standard directives, see reStructuredText Directives.

Plain text Typical result
For instance:

.. image:: images/ball1.gif

For instance:

ball1

Substitution References and Definitions

(details)

Substitutions are like inline directives, allowing graphics and arbitrary constructs within text.

Plain text Typical result
The |biohazard| symbol must be used on containers used to dispose of medical waste.

.. |biohazard| image:: biohazard.png

The biohazard symbol must be used on containers used to dispose of medical waste.

Comments

(details)

Any text which begins with an explicit markup start but doesn't use the syntax of any of the constructs above, is a comment.

Plain text Typical result
.. This text will not be shown
   (but, for instance, in HTML might be
   rendered as an HTML comment)
 
An "empty comment" does not
consume following blocks.
(An empty comment is ".." with
blank lines before and after.)

..

        So this block is not "lost",
        despite its indentation.

An "empty comment" does not consume following blocks. (An empty comment is ".." with blank lines before and after.)
So this block is not "lost", despite its indentation.

Getting Help

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.


Authors: Tibs (tibs@tibsnjoan.co.uk) and David Goodger (goodger@python.org)

docutils-0.12/docs/user/rst/cheatsheet.txt0000664000175000017500000001571012111021235022610 0ustar engelbertengelbert00000000000000===================================================== The reStructuredText_ Cheat Sheet: Syntax Reminders ===================================================== :Info: See for introductory docs. :Author: David Goodger :Date: $Date: 2013-02-20 02:10:53 +0100 (Mit, 20. Feb 2013) $ :Revision: $Revision: 7612 $ :Description: This is a "docinfo block", or bibliographic field list .. NOTE:: If you are reading this as HTML, please read ``_ instead to see the input syntax examples! Section Structure ================= Section titles are underlined or overlined & underlined. Body Elements ============= Grid table: +--------------------------------+-----------------------------------+ | Paragraphs are flush-left, | Literal block, preceded by "::":: | | separated by blank lines. | | | | Indented | | Block quotes are indented. | | +--------------------------------+ or:: | | >>> print 'Doctest block' | | | Doctest block | > Quoted | +--------------------------------+-----------------------------------+ | | Line blocks preserve line breaks & indents. [new in 0.3.6] | | | Useful for addresses, verse, and adornment-free lists; long | | lines can be wrapped with continuation lines. | +--------------------------------------------------------------------+ Simple tables: ================ ============================================================ List Type Examples (syntax in the `text source `_) ================ ============================================================ Bullet list * items begin with "-", "+", or "*" Enumerated list 1. items use any variation of "1.", "A)", and "(i)" #. also auto-enumerated Definition list Term is flush-left : optional classifier Definition is indented, no blank line between Field list :field name: field body Option list -o at least 2 spaces between option & description ================ ============================================================ ================ ============================================================ Explicit Markup Examples (visible in the `text source`_) ================ ============================================================ Footnote .. [1] Manually numbered or [#] auto-numbered (even [#labelled]) or [*] auto-symbol Citation .. [CIT2002] A citation. Hyperlink Target .. _reStructuredText: http://docutils.sf.net/rst.html .. _indirect target: reStructuredText_ .. _internal target: Anonymous Target __ http://docutils.sf.net/docs/ref/rst/restructuredtext.html Directive ("::") .. image:: images/biohazard.png Substitution Def .. |substitution| replace:: like an inline directive Comment .. is anything else Empty Comment (".." on a line by itself, with blank lines before & after, used to separate indentation contexts) ================ ============================================================ Inline Markup ============= *emphasis*; **strong emphasis**; `interpreted text`; `interpreted text with role`:emphasis:; ``inline literal text``; standalone hyperlink, http://docutils.sourceforge.net; named reference, reStructuredText_; `anonymous reference`__; footnote reference, [1]_; citation reference, [CIT2002]_; |substitution|; _`inline internal target`. Directive Quick Reference ========================= See for full info. ================ ============================================================ Directive Name Description (Docutils version added to, in [brackets]) ================ ============================================================ attention Specific admonition; also "caution", "danger", "error", "hint", "important", "note", "tip", "warning" admonition Generic titled admonition: ``.. admonition:: By The Way`` image ``.. image:: picture.png``; many options possible figure Like "image", but with optional caption and legend topic ``.. topic:: Title``; like a mini section sidebar ``.. sidebar:: Title``; like a mini parallel document parsed-literal A literal block with parsed inline markup rubric ``.. rubric:: Informal Heading`` epigraph Block quote with class="epigraph" highlights Block quote with class="highlights" pull-quote Block quote with class="pull-quote" compound Compound paragraphs [0.3.6] container Generic block-level container element [0.3.10] table Create a titled table [0.3.1] list-table Create a table from a uniform two-level bullet list [0.3.8] csv-table Create a table from CSV data [0.3.4] contents Generate a table of contents sectnum Automatically number sections, subsections, etc. header, footer Create document decorations [0.3.8] target-notes Create an explicit footnote for each external target math Mathematical notation (input in LaTeX format) meta HTML-specific metadata include Read an external reST file as if it were inline raw Non-reST data passed untouched to the Writer replace Replacement text for substitution definitions unicode Unicode character code conversion for substitution defs date Generates today's date; for substitution defs class Set a "class" attribute on the next element role Create a custom interpreted text role [0.3.2] default-role Set the default interpreted text role [0.3.10] title Set the metadata document title [0.3.10] ================ ============================================================ Interpreted Text Role Quick Reference ===================================== See for full info. ================ ============================================================ Role Name Description ================ ============================================================ emphasis Equivalent to *emphasis* literal Equivalent to ``literal`` but processes backslash escapes math Mathematical notation (input in LaTeX format) PEP Reference to a numbered Python Enhancement Proposal RFC Reference to a numbered Internet Request For Comments raw For non-reST data; cannot be used directly (see docs) [0.3.6] strong Equivalent to **strong** sub Subscript sup Superscript title Title reference (book, etc.); standard default role ================ ============================================================ docutils-0.12/docs/user/rst/demo.txt0000664000175000017500000003453111700652711021435 0ustar engelbertengelbert00000000000000.. This is a comment. Note how any initial comments are moved by transforms to after the document title, subtitle, and docinfo. ================================ reStructuredText Demonstration ================================ .. Above is the document title, and below is the subtitle. They are transformed from section titles after parsing. -------------------------------- Examples of Syntax Constructs -------------------------------- .. bibliographic fields (which also require a transform): :Author: David Goodger :Address: 123 Example Street Example, EX Canada A1B 2C3 :Contact: docutils-develop@lists.sourceforge.net :Authors: Me; Myself; I :organization: humankind :date: $Date: 2012-01-03 20:23:53 +0100 (Die, 03. Jän 2012) $ :status: This is a "work in progress" :revision: $Revision: 7302 $ :version: 1 :copyright: This document has been placed in the public domain. You may do with it as you wish. You may copy, modify, redistribute, reattribute, sell, buy, rent, lease, destroy, or improve it, quote it at length, excerpt, incorporate, collate, fold, staple, or mutilate it, or do anything else to it that your or anyone else's heart desires. :field name: This is a generic bibliographic field. :field name 2: Generic bibliographic fields may contain multiple body elements. Like this. :Dedication: For Docutils users & co-developers. :abstract: This document is a demonstration of the reStructuredText markup language, containing examples of all basic reStructuredText constructs and many advanced constructs. .. meta:: :keywords: reStructuredText, demonstration, demo, parser :description lang=en: A demonstration of the reStructuredText markup language, containing examples of all basic constructs and many advanced constructs. .. contents:: Table of Contents .. section-numbering:: Structural Elements =================== Section Title ------------- That's it, the text just above this line. Transitions ----------- Here's a transition: --------- It divides the section. Body Elements ============= Paragraphs ---------- A paragraph. Inline Markup ````````````` Paragraphs contain text and may contain inline markup: *emphasis*, **strong emphasis**, ``inline literals``, standalone hyperlinks (http://www.python.org), external hyperlinks (Python_), internal cross-references (example_), external hyperlinks with embedded URIs (`Python web site `__), footnote references (manually numbered [1]_, anonymous auto-numbered [#]_, labeled auto-numbered [#label]_, or symbolic [*]_), citation references ([CIT2002]_), substitution references (|example|), and _`inline hyperlink targets` (see Targets_ below for a reference back to here). Character-level inline markup is also possible (although exceedingly ugly!) in *re*\ ``Structured``\ *Text*. Problems are indicated by |problematic| text (generated by processing errors; this one is intentional). The default role for interpreted text is `Title Reference`. Here are some explicit interpreted text roles: a PEP reference (:PEP:`287`); an RFC reference (:RFC:`2822`); a :sub:`subscript`; a :sup:`superscript`; and explicit roles for :emphasis:`standard` :strong:`inline` :literal:`markup`. .. DO NOT RE-WRAP THE FOLLOWING PARAGRAPH! Let's test wrapping and whitespace significance in inline literals: ``This is an example of --inline-literal --text, --including some-- strangely--hyphenated-words. Adjust-the-width-of-your-browser-window to see how the text is wrapped. -- ---- -------- Now note the spacing between the words of this sentence (words should be grouped in pairs).`` If the ``--pep-references`` option was supplied, there should be a live link to PEP 258 here. Bullet Lists ------------ - A bullet list + Nested bullet list. + Nested item 2. - Item 2. Paragraph 2 of item 2. * Nested bullet list. * Nested item 2. - Third level. - Item 2. * Nested item 3. Enumerated Lists ---------------- 1. Arabic numerals. a) lower alpha) (i) (lower roman) A. upper alpha. I) upper roman) 2. Lists that don't start at 1: 3. Three 4. Four C. C D. D iii. iii iv. iv #. List items may also be auto-enumerated. Definition Lists ---------------- Term Definition Term : classifier Definition paragraph 1. Definition paragraph 2. Term Definition Field Lists ----------- :what: Field lists map field names to field bodies, like database records. They are often part of an extension syntax. They are an unambiguous variant of RFC 2822 fields. :how arg1 arg2: The field marker is a colon, the field name, and a colon. The field body may contain one or more body elements, indented relative to the field marker. Option Lists ------------ For listing command-line options: -a command-line option "a" -b file options can have arguments and long descriptions --long options can be long also --input=file long options can also have arguments --very-long-option The description can also start on the next line. The description may contain multiple body elements, regardless of where it starts. -x, -y, -z Multiple options are an "option group". -v, --verbose Commonly-seen: short & long options. -1 file, --one=file, --two file Multiple options with arguments. /V DOS/VMS-style options too There must be at least two spaces between the option and the description. Literal Blocks -------------- Literal blocks are indicated with a double-colon ("::") at the end of the preceding paragraph (over there ``-->``). They can be indented:: if literal_block: text = 'is left as-is' spaces_and_linebreaks = 'are preserved' markup_processing = None Or they can be quoted without indentation:: >> Great idea! > > Why didn't I think of that? Line Blocks ----------- | This is a line block. It ends with a blank line. | Each new line begins with a vertical bar ("|"). | Line breaks and initial indents are preserved. | Continuation lines are wrapped portions of long lines; they begin with a space in place of the vertical bar. | The left edge of a continuation line need not be aligned with the left edge of the text above it. | This is a second line block. | | Blank lines are permitted internally, but they must begin with a "|". Take it away, Eric the Orchestra Leader! | A one, two, a one two three four | | Half a bee, philosophically, | must, *ipso facto*, half not be. | But half the bee has got to be, | *vis a vis* its entity. D'you see? | | But can a bee be said to be | or not to be an entire bee, | when half the bee is not a bee, | due to some ancient injury? | | Singing... Block Quotes ------------ Block quotes consist of indented body elements: My theory by A. Elk. Brackets Miss, brackets. This theory goes as follows and begins now. All brontosauruses are thin at one end, much much thicker in the middle and then thin again at the far end. That is my theory, it is mine, and belongs to me and I own it, and what it is too. -- Anne Elk (Miss) Doctest Blocks -------------- >>> print 'Python-specific usage examples; begun with ">>>"' Python-specific usage examples; begun with ">>>" >>> print '(cut and pasted from interactive Python sessions)' (cut and pasted from interactive Python sessions) Tables ------ Here's a grid table followed by a simple table: +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | | (header rows optional) | | | | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | +------------------------+------------+----------+----------+ | body row 2 | Cells may span columns. | +------------------------+------------+---------------------+ | body row 3 | Cells may | - Table cells | +------------------------+ span rows. | - contain | | body row 4 | | - body elements. | +------------------------+------------+----------+----------+ | body row 5 | Cells may also be | | | | empty: ``-->`` | | +------------------------+-----------------------+----------+ ===== ===== ====== Inputs Output ------------ ------ A B A or B ===== ===== ====== False False False True False True False True True True True True ===== ===== ====== Footnotes --------- .. [1] A footnote contains body elements, consistently indented by at least 3 spaces. This is the footnote's second paragraph. .. [#label] Footnotes may be numbered, either manually (as in [1]_) or automatically using a "#"-prefixed label. This footnote has a label so it can be referred to from multiple places, both as a footnote reference ([#label]_) and as a hyperlink reference (label_). .. [#] This footnote is numbered automatically and anonymously using a label of "#" only. .. [*] Footnotes may also use symbols, specified with a "*" label. Here's a reference to the next footnote: [*]_. .. [*] This footnote shows the next symbol in the sequence. .. [4] Here's an unreferenced footnote, with a reference to a nonexistent footnote: [5]_. Citations --------- .. [CIT2002] Citations are text-labeled footnotes. They may be rendered separately and differently from footnotes. Here's a reference to the above, [CIT2002]_, and a [nonexistent]_ citation. Targets ------- .. _example: This paragraph is pointed to by the explicit "example" target. A reference can be found under `Inline Markup`_, above. `Inline hyperlink targets`_ are also possible. Section headers are implicit targets, referred to by name. See Targets_, which is a subsection of `Body Elements`_. Explicit external targets are interpolated into references such as "Python_". .. _Python: http://www.python.org/ Targets may be indirect and anonymous. Thus `this phrase`__ may also refer to the Targets_ section. __ Targets_ Here's a `hyperlink reference without a target`_, which generates an error. Duplicate Target Names `````````````````````` Duplicate names in section headers or other implicit targets will generate "info" (level-1) system messages. Duplicate names in explicit targets will generate "warning" (level-2) system messages. Duplicate Target Names `````````````````````` Since there are two "Duplicate Target Names" section headers, we cannot uniquely refer to either of them by name. If we try to (like this: `Duplicate Target Names`_), an error is generated. Directives ---------- .. contents:: :local: These are just a sample of the many reStructuredText Directives. For others, please see http://docutils.sourceforge.net/docs/ref/rst/directives.html. Document Parts `````````````` An example of the "contents" directive can be seen above this section (a local, untitled table of contents_) and at the beginning of the document (a document-wide `table of contents`_). Images `````` An image directive (also clickable -- a hyperlink reference): .. image:: images/title.png :target: directives_ A figure directive: .. figure:: images/title.png :alt: reStructuredText, the markup syntax A figure is an image with a caption and/or a legend: +------------+-----------------------------------------------+ | re | Revised, revisited, based on 're' module. | +------------+-----------------------------------------------+ | Structured | Structure-enhanced text, structuredtext. | +------------+-----------------------------------------------+ | Text | Well it is, isn't it? | +------------+-----------------------------------------------+ This paragraph is also part of the legend. Admonitions ``````````` .. Attention:: Directives at large. .. Caution:: Don't take any wooden nickels. .. DANGER:: Mad scientist at work! .. Error:: Does not compute. .. Hint:: It's bigger than a bread box. .. Important:: - Wash behind your ears. - Clean up your room. - Call your mother. - Back up your data. .. Note:: This is a note. .. Tip:: 15% if the service is good. .. WARNING:: Strong prose may provoke extreme mental exertion. Reader discretion is strongly advised. .. admonition:: And, by the way... You can make up your own admonition too. Topics, Sidebars, and Rubrics ````````````````````````````` .. sidebar:: Sidebar Title :subtitle: Optional Subtitle This is a sidebar. It is for text outside the flow of the main text. .. rubric:: This is a rubric inside a sidebar Sidebars often appears beside the main text with a border and background color. .. topic:: Topic Title This is a topic. .. rubric:: This is a rubric Target Footnotes ```````````````` .. target-notes:: Replacement Text ```````````````` I recommend you try |Python|_. .. |Python| replace:: Python, *the* best language around Compound Paragraph `````````````````` .. compound:: This paragraph contains a literal block:: Connecting... OK Transmitting data... OK Disconnecting... OK and thus consists of a simple paragraph, a literal block, and another simple paragraph. Nonetheless it is semantically *one* paragraph. This construct is called a *compound paragraph* and can be produced with the "compound" directive. Substitution Definitions ------------------------ An inline image (|example|) example: .. |EXAMPLE| image:: images/biohazard.png (Substitution definitions are not visible in the HTML source.) Comments -------- Here's one: .. Comments begin with two dots and a space. Anything may follow, except for the syntax of footnotes, hyperlink targets, directives, or substitution definitions. Double-dashes -- "--" -- must be escaped somehow in HTML output. (View the HTML source to see the comment.) Error Handling ============== Any errors caught during processing will generate system messages. |*** Expect 6 errors (including this one). ***| There should be six messages in the following, auto-generated section, "Docutils System Messages": .. section should be added by Docutils automatically docutils-0.12/docs/user/rst/images/0000775000175000017500000000000012356234260021212 5ustar engelbertengelbert00000000000000docutils-0.12/docs/user/rst/images/title.svg0000664000175000017500000000502411343055325023053 0ustar engelbertengelbert00000000000000 image/svg+xml reStructuredText docutils-0.12/docs/user/rst/images/title-scaling.svg0000664000175000017500000000506111343055325024472 0ustar engelbertengelbert00000000000000 image/svg+xml reStructuredText docutils-0.12/docs/user/rst/images/title.png0000664000175000017500000000220311202034447023030 0ustar engelbertengelbert00000000000000PNG  IHDR1#sRGBPLTEpAxEtRNS@fbKGDH pHYs.#.#x?vtIME 612IDATHǥOn7ǰ7͢0}/U0R^zzd[ GQB.{0HQt9A6,:fFR"ð0?.VS$]tl1{9^rd q`Vۧw/b[Г+7,foAC<.)}M Y߸"ON|:$o6a>B$Q@dZ wxKb;q+-s2teZŊjH%"lШڀZ7_Ӫ bD5ҹϾh?Qmp*U/O]v;f` o%?UU֢_\FY(9Q%חczT3?ZLP{1իqg>gS u5}+1q5Eh1Gޖ4ܒd4 9뎐"zrLASl(|tTeG#?p(piU YaMAWȊ` K#'BVa.PgQb׸y*Qz $PRM=pzx^/R,祖0$`VÞTaEM Jxд>AiG(0f)uTz!YfL煤Bnwz,j~JPP.GOUܶ`6‡m: aYۂN/FXQ7nn(Pe~#MF0!Ej* 2Ya,Ix0 `M9V4*pabx]Ϥ\* %i9\9iL!-~X`$5#w94%Y!ݑ(EN~} Y/K)_Ux,NYz5Qȩ Cb/${c~^ cVIk[t5,\ӟUkp7r eI IcB!%"0XIENDB`docutils-0.12/docs/user/rst/images/biohazard.svg0000664000175000017500000001667111343175705023714 0ustar engelbertengelbert00000000000000 Biohazard image/svg+xml Biohazard Standalone biohazard symbol, with no border, background or descriptive text. Silsor http://de.wikipedia.org/wiki/Datei:Biohazard_symbol.svg Wikipedia Bastique, Andux, MarianSigler, GM docutils-0.12/docs/user/rst/images/biohazard.png0000664000175000017500000000026310263337377023674 0ustar engelbertengelbert00000000000000PNG  IHDR%=m"gAMAܲ pHYs+PLTEU~tRNS@f6IDATxb`Q``` cB.y3L! @P A5IENDB`docutils-0.12/docs/user/rst/images/biohazard-scaling.svg0000664000175000017500000001673611343055325025327 0ustar engelbertengelbert00000000000000 Biohazard image/svg+xml Biohazard Standalone biohazard symbol, with no border, background or descriptive text. Silsor http://de.wikipedia.org/wiki/Datei:Biohazard_symbol.svg Wikipedia Bastique, Andux, MarianSigler, GM docutils-0.12/docs/user/rst/images/ball1.gif0000664000175000017500000001041110263337377022701 0ustar engelbertengelbert00000000000000GIF89a ! NETSCAPE2.0c! , ^I8 zWJ>pڂp0z@l?շs(L]p0V{\K&gUX~! , ]I8ͻ`(dihf@ۊ#˯sݝ;' jD$cEpM>n[=~M5+Ax'w! , ^I8ͻ`(dih,>4{@?;] ҆(2(dѮW[huM+Bpx<~! , ZI8ͻ`(dihl >4{@?;] ҆(2(dѮW[huM~;.D! , UI8ͻ`(dihl@,`w@?EBLGZS*zKvLcs6B#! , TI8ͻ`(dihl ϳ'?x KIyB):jܯX4{@?;] ҆(2(dѮW[huM~;.D! , ^I8ͻ`(dih,>4{@?;] ҆(2(dѮW[huM+Bpx<~! , ]I8ͻ`(dihf@ۊ#˯sݝ;' jD$cEpM>n[=~M5+Ax'w! , \I8ͻ`(di>0z@l?շs(L]p0V{\K&gUX~! , ]I8ͻ`(di^@㺫s\7ﮞ 1D* 4F⒉ֶWv<Oڧ|Bx'w! , ^I8ͻ`($`+l@1k ċe/iJja_ ƊwduZ|Nw <~x! , ]I8ͻ`x$)Ot.\m;G@qA 4GTUڴzw!}YZn|Bx'w! , _I8ͻ@~Sh@Ǻ-ikx^iXp6uUn\W3in|NS}y! , _I8/_W}OY"`t*\,fm3 _C<eIIVn"g A]zn|N;}y! , ^I8 zWJ>pڂp * Tables are possible, via the external processor tbl, although one should avoid them. Open issues ''''''''''' * How to typeset command/manpage names in text. * How to write long syntax lines. * Line ends around email or web addresses in texts. How to distinguish something is inline or not ? * Images and equations are discouraged. * Lists in admonitions are not intended. * Encoding declaration ``'\" t -*- coding: ISO-8859-1 -*-`` in first line. BUT if UTF-8 is declared tables are no longer processed. * Input and output encoding are problematic at least. .. _Docutils: http://docutils.sourceforge.net/ docutils-0.12/docs/user/emacs.txt0000664000175000017500000007156312177163210020777 0ustar engelbertengelbert00000000000000.. -*- coding: utf-8 -*- ======================================== Emacs Support for reStructuredText ======================================== :Authors: Stefan Merten , Martin Blais :Version: ``rst.el`` V1.4.0 :Abstract: High-level description of the existing Emacs_ support for editing reStructuredText_ text documents. Suggested setup code and usage instructions are provided. .. contents:: Introduction ============ reStructuredText_ is a syntax for simple text files that allows a tool set - docutils_ - to extract generic document structure. For people who use Emacs_, there is a package that adds a major mode that supports editing the syntax of reStructuredText_: ``rst.el``. This document describes the features it provides, and how to setup your Emacs_ to use them and how to invoke them. Installation ============ Emacs_ support for reStructuredText_ is implemented as an Emacs_ major mode (``rst-mode``) provided by the ``rst.el`` Emacs_ package. Emacs_ distributions contain ``rst.el`` since version V23.1. However, a significantly updated version of ``rst.el`` is contained in Emacs_ V24.3. This document describes the version of ``rst.el`` contained in Emacs_ V24.3. This version of ``rst.el`` has the internal version V1.4.0. If you have Emacs_ V24.3 or later you do not need to install anything to get reST support. If you have an Emacs_ between V23.1 and V24.2 you may use the included version of ``rst.el`` or install a more recent one locally_ (recommended). In other cases you need to install ``rst.el`` locally_ to get reST support. Checking situation ------------------ Here are some steps to check your situation: #. In Emacs_ switch to an empty buffer and try :: M-x rst-mode If this works you have ``rst.el`` installed somewhere. You can see that it works if you find a string ``ReST`` in Emacs' modeline of the current buffer. If this doesn't work you need to install ``rst.el`` yourself locally_. #. In the buffer you just switched to ``rst-mode`` try :: C-h v rst-version If this fails you have a version of ``rst.el`` older than V1.1.0. Either you have an old ``rst.el`` locally or you are using an Emacs_ between V23.1 and V24.2. In this case it is recommended that you install a more recent version of ``rst.el`` locally_. You may also try :: C-h v emacs-version to find out your Emacs_ version. #. Check the version of ``rst.el`` The content of ``rst-version`` gives you the internal version of ``rst.el``. The version contained in Emacs_ V24.3 and described here is V1.4.0. If you have an older version you may or may not install a more recent version of ``rst.el`` locally. .. _locally: Local installation ------------------ If you decided to install locally please follow these steps. #. Download ``rst.el`` Download the most recent published version of ``rst.el`` from http://docutils.sourceforge.net/tools/editors/emacs/rst.el #. Put ``rst.el`` to a directory in ``load-path`` Use :: C-h v load-path If in the resulting list you find a directory in your home directory put ``rst.el`` in this directory. Make sure the directory is one of the first entries in ``load-path``. Otherwise a version of ``rst.el`` which came with Emacs_ may be found before your local version. In Emacs_ see the info node ``Init File Examples`` for more information on how to set up your Emacs_ initialization machinery. Try :: C-h i mEmacs sInit File Examples #. Enable ``rst-mode`` Add the following to your Emacs_ initialization setup :: (require 'rst) After you restarted Emacs_ ``rst.el`` is loaded and ready to be used. Switching ``rst-mode`` on ------------------------- By default ``rst-mode`` is switched on for files ending in ``.rst`` or ``.rest``. If in a buffer you want to switch ``rst-mode`` on manually use :: M-x rst-mode If you want to use ``rst-mode`` in files with other extensions modify ``auto-mode-alist`` to automatically turn it on whenever you visit reStructuredText_ documents:: (setq auto-mode-alist (append '(("\\.txt\\'" . rst-mode) ("\\.rst\\'" . rst-mode) ("\\.rest\\'" . rst-mode)) auto-mode-alist)) Put the extensions you want in the correct place in the example above. Add more lines if needed. If have local variables enabled (try ``C-h v enable-local-variables`` to find out), you can also add the following at the top of your documents to trigger rst-mode:: .. -*- mode: rst -*- Or this at the end of your documents:: .. Local Variables: mode: rst End: Key bindings ============ ``rst-mode`` automatically binds several keys for invoking special functions for editing reStructuredText_. Since ``rst-mode`` contains a lot of functionality most key bindings consist of three keystrokes. Following the Emacs_ conventions for major modes the key bindings of ``rst-mode`` start with ``C-c C-``. The second key stroke selects a group of key bindings: C-c C-a Commands to adjust the section headers and work with the hierarchy they build. C-c C-c Commands to compile the current reStructuredText_ document to various output formats. C-c C-l Commands to work with lists of various kinds. C-c C-r Commands to manipulate the current region. C-c C-t Commands to create and manipulate a table of contents. At any stage of typing you may use ``C-h`` to get help on the available key bindings. I.e. ``C-c C-h`` gives you help on all key bindings while ``C-c C-r C-h`` gives you help on the commands for regions. This is handy if you forgot a certain key binding. Additional key bindings which have a certain meaning in other Emacs_ modes are reused in ``rst-mode`` so you don't have to learn a different set of key bindings for editing reStructuredText_. In ``rst-mode`` try :: C-h m to list all mode specific key bindings. Most of the key bindings are described in this tutorial. .. note:: The key bindings have been completely revamped in ``rst.el`` V1.0.0. This was necessary to make room for new functionality. Some of the old bindings still work but give a warning to use the new binding. In the output of ``C-h m`` these bindings show up as ``??``. The old bindings may be removed completely in a later version. Section Adornments ================== ``rst-mode`` recognizes the section adornments building the section hierarchy of the document. Section adornments are the underlines or under- and overlines used to mark a section title. There are a couple of commands to work with section adornments. These commands are bound to key bindings starting with ``C-c C-a``. Adjusting a Section Title ------------------------- There is a function that helps a great deal to maintain these adornments: ``rst-adjust`` (bound to ``C-c C-a C-a``, ``C-c C-=``, and ``C-=``). This function is a Swiss army knife that can be invoked repeatedly and whose behavior depends on context: #. If there is an incomplete adornment, e.g. :: My Section Title == invocation will complete the adornment. It can also be used to adjust the length of the existing adornment when you need to edit the title. #. If there is no section adornment at all, an adornment of the same level as the last encountered section level is added. You can simply enter a few characters of the title and invoke the function to create the section adornment. #. If there is already a section adornment, it is promoted one level up. You can invoke it like this repeatedly to cycle the title through the hierarchy of existing adornments. Invoking the function with a negative prefix argument, e.g. ``C-- C-=``, will effectively reverse the direction of adornment cycling. To alternate between underline-only and over-and-under styles, you can use a regular prefix argument, e.g. ``C-u C-=``. See the documentation of ``rst-adjust`` for more description of the prefix arguments to alter the behavior of the function. Promoting and Demoting Many Sections ------------------------------------ When you are re-organizing the structure of a document, it can be useful to change the level of a number of section titles. The same key binding can be used to do that: if the region is active when the binding is invoked, all the section titles that are within the region are promoted accordingly (or demoted, with negative prefix argument). Redoing All the Adornments to Your Taste ---------------------------------------- If you open someone else's file and the adornments it contains are unfamiliar, you may want to readjust them to fit your own preferred hierarchy of adornments. This can be difficult to perform by hand. However, you can do this easily by invoking ``rst-straighten-adornments`` (``C-c C-a C-s``), which operates on the entire buffer. Customizations for Adornments ----------------------------- You can customize the variable ``rst-preferred-adornments`` to a list of the adornments that you like to use for documents. ``rst-default-indent`` can be set to the number of indent spaces preferred for the over-and-under adornment style. Viewing the Hierarchy of Section Adornments ------------------------------------------- You can visualize the hierarchy of the section adornments in the current buffer by invoking ``rst-display-adornments-hierarchy``, bound on ``C-c C-a C-d``. A temporary buffer will appear with fake section titles rendered in the style of the current document. This can be useful when editing other people's documents to find out which section adornments correspond to which levels. Movement and Selection ====================== Movement and Selection for Sections ----------------------------------- You can move the cursor between the different section titles by using the ``rst-backward-section`` (``C-M-a``) and ``rst-forward-section`` (``C-M-e``). To mark the section that cursor lies in, use ``rst-mark-section`` (``C-M-h``). The key bindings are modeled after other modes with similar functionality. Movements and Selection for Text Blocks --------------------------------------- The understanding of reStructuredText_ of ``rst-mode`` is used to set all the variables influencing Emacs' understanding of paragraphs. Thus all operations on paragraphs work as usual. For instance ``forward-paragraph`` (``M-}``) works as usual. Indenting and Filling ===================== Indentation of text plays a major role in the syntax of reStructuredText_. It is tedious to maintain the indentation manually. ``rst-mode`` understands most of the structure of reStructuredText_ allowing for sophisticated indentation and filling support described in this section. Indenting Text Blocks --------------------- ``rst-mode`` supports indentation of text blocks by the command ``rst-shift-region`` (``C-c C-r TAB``). Mark a region and use ``C-c C-r TAB`` to indent all blocks one tab to the right. Use ``M-- C-c C-r TAB`` to indent the region one tab to the left. You may use arbitrary prefix arguments such as ``M-2`` or ``M-- 2`` to determine the number of tabs you want to indent. A prefix of ``M-0`` removes all indentation in the active region. A tab is an indentation making sense for the block at hand in reStructuredText_ syntax. In some cases the exact indentation depends on personal taste. You may customize a couple of variables ``M-x customize-group rst-indent`` to match your taste. Indenting Lines While Typing ---------------------------- In Emacs_ the ``TAB`` key is often used for indenting the current line. ``rst-mode`` implements this for the sophisticated indentation rules of reStructuredText_. Pressing ``TAB`` cycles through the possible tabs for the current line. In the same manner ``newline-and-indent`` (``C-j``) indents the new line properly. This is very handy while writing lists. Consider this reStructuredText_ bullet list with the cursor at ``@``:: * Level 1 * Level 2@ Type ``C-j`` twice to get this:: * Level 1 * Level 2 @ Now you an enter text at this level, or start a new list item by typing another ``*``. Or you may type ``TAB`` to reduce the indentation once:: * Level 1 * Level 2 @ Typing another ``TAB`` gets you to the first level:: * Level 1 * Level 2 @ Filling ------- ``rst-mode`` understanding the indentation rules of reStructuredText_ also supports filling paragraphs. Just use ``fill-paragraph`` (``M-q``) as you do in other modes. Operating on Lists ================== Lists are supported in various flavors in reStructuredText_. ``rst-mode`` understands reStructuredText_ lists and offers some support for operating on lists. Key bindings for commands for operating on lists start with ``C-c C-l``. Bulleted and Enumerated Lists ----------------------------- If you have a couple of plain lines you want to turn into an enumerated list you can invoke ``rst-enumerate-region`` (``C-c C-l C-e``). For example, the following region :: Apples Oranges Bananas becomes :: 1. Apples 2. Oranges 3. Bananas ``rst-bullet-list-region`` (``C-c C-l C-b``) does the same, but results in a bullet list :: * Apples * Oranges * Bananas By default, each paragraph starting on the leftmost line in the highlighted region will be taken to be a single list or enumeration item, for example, enumerating the following:: An apple a day keeps the doctor away. But oranges are tastier than apples. If you preferred bananas you may be a monkey. Will result in:: 1. An apple a day keeps the doctor away. 2. But oranges are tastier than apples. 3. If you preferred bananas you may be a monkey. If you would like to enumerate each of the lines, use a prefix argument on the preceding commands, e.g.:: Apples Oranges Bananas becomes:: * Apples * Oranges * Bananas Straightening Existing Bullet List Hierarchies ---------------------------------------------- If you invoke ``rst-straighten-bullets-region`` (``C-c C-l C-s``), the existing bullets in the active region will be replaced to reflect their respective level. This does not make a difference in the document structure that reStructuredText_ defines, but looks better in, for example, if all of the top-level bullet items use the character ``-``, and all of the 2nd level items use ``*``, etc. Inserting a List Item --------------------- To start a new list you may invoke ``rst-insert-list`` (``C-c C-l C-i``). You may choose from an item style supported by reStructuredText_. You may also invoke ``rst-insert-list`` at the end of a list item. In this case it inserts a new line containing the markup for the a list item on the same level. Operating on Other Text Blocks ============================== Creating and Removing Line Blocks --------------------------------- To create line blocks, first select the region to convert and invoke ``rst-line-block-region`` ``C-c C-r C-l``. For example, the following :: Apples Oranges Bananas becomes :: | Apples | Oranges | Bananas This works even if the region is indented. To remove line blocks, select a region and invoke with a prefix argument. Commenting a Region of Text --------------------------- ``rst-mode`` understands reStructuredText_ comments. Use ``comment-dwim`` (``M-;``) to work on comments as usual:: Apples Oranges Bananas becomes:: .. Apples Oranges Bananas To remove a comment you have to tell this to ``comment-dwim`` explicitly by using a prefix argument (``C-u M-;``). Please note that only indented comments are supported properly by the parts of ``comment-dwim`` working on regions. Converting Documents from Emacs =============================== ``rst-mode`` provides a number of functions for running documents being edited through the docutils tools. The key bindings for these commands start with ``C-c C-c``. The main generic function is ``rst-compile`` (``C-c C-c C-c``). It invokes a compilation command with the correct output name for the current buffer and then invokes Emacs' compile function. It also looks for the presence of a ``docutils.conf`` configuration file in the parent directories and adds it to the command line options. There is also ``rst-compile-alt-toolset`` (``C-c C-c C-a``) in case you often need run your document in a second toolset. You can customize the commands being used by setting ``rst-compile-primary-toolset`` and ``rst-compile-secondary-toolset``. Other commands are available for other formats: * ``rst-compile-pseudo-region`` (``C-c C-c C-x``) When crafting documents, it is often convenient to view which data structures docutils will parse them into. You can use to run the active region through ``rst2pseudoxml.py`` and have the output automatically be displayed in a new buffer. * ``rst-compile-pdf-preview`` (``C-c C-c C-p``) Convert the current document to PDF and launch a viewer on the results. * ``rst-compile-slides-preview`` (``C-c C-c C-s``): Convert the current document to S5 slides and view in a web browser. Imenu Support ============= Using Imenu ----------- Emacs_ has a package called ``imenu``. ``rst-mode`` supports Imenu by adding a function to convert the structure of a reStructuredText_ buffer to an Imenu index. Thus you can use invoke ``imenu`` (``M-x imenu``) to navigate through the section index or invoke ``imenu-add-to-menubar`` (``M-x imenu-add-to-menubar``) to add an Imenu menu entry to Emacs' menu bar. Using which function -------------------- As a side effect of Imenu support the ``which-func`` package is also supported. Invoke ``which-function-mode`` (``M-x which-function-mode``) to add the name of the current section to the mode line. This is especially useful if you navigate through documents with long sections which do not fit on a single screen. Using the Table of Contents =========================== The sections in a reStructuredText_ document can be used to form a table of contents. ``rst-mode`` can work with such a table of contents in various forms. Key bindings for these commands start with ``C-c C-t``. Navigating Using the Table of Contents -------------------------------------- When you are editing long documents, it can be a bit difficult to orient yourself in the structure of your text. To that effect, a function is provided that presents a hierarchically indented table of contents of the document in a temporary buffer, in which you can navigate and press ``Return`` to go to a specific section. Invoke ``rst-toc`` (``C-c C-t C-t``). It presents a temporary buffer that looks something like this:: Table of Contents: Debugging Meta-Techniques Introduction Debugging Solution Patterns Recognize That a Bug Exists Subdivide and Isolate Identify and Verify Assumptions Use a Tool for Introspection Change one thing at a time Learn about the System Understanding a bug The Basic Steps in Debugging Attitude Bad Feelings Good Feelings References When you move the cursor to a section title and press ``RET`` or ``f``, the temporary buffer disappears and you are left with the cursor positioned at the chosen section. Use ``q`` in this buffer to just quit it without moving the cursor in the original document. Use ``z`` to zap the buffer altogether. Inserting a Table of Contents ----------------------------- Oftentimes in long text documents that are meant to be read directly, a table of contents is inserted at the beginning of the text. In reStructuredText_ documents, since the table of contents is automatically generated by the parser with the ``.. contents::`` directive, people generally have not been adding an explicit table of contents to their source documents, and partly because it is too much trouble to edit and maintain. The Emacs_ support for reStructuredText_ provides a function to insert such a table of contents in your document. Since it is not meant to be part of the document text, you should place such a table of contents within a comment, so that it is ignored by the parser. This is the favored usage:: .. contents:: .. 1 Introduction 2 Debugging Solution Patterns 2.1 Recognize That a Bug Exists 2.2 Subdivide and Isolate 2.3 Identify and Verify Assumptions 2.4 Use a Tool for Introspection 2.5 Change one thing at a time 2.6 Learn about the System 3 Understanding a bug 4 The Basic Steps in Debugging 5 Attitude 5.1 Bad Feelings 5.2 Good Feelings 6 References Just place the cursor at the top-left corner where you want to insert the TOC and invoke the function ``rst-toc-insert`` with ``C-c C-t C-i``. The table of contents will display all the section titles that are under the location where the insertion occurs. This way you can insert local table of contents by placing them in the appropriate location. You can use a numeric prefix argument to limit the depth of rendering of the TOC. You can customize the look of the TOC by setting the values of the following variables: ``rst-toc-indent``, ``rst-toc-insert-style``, ``rst-toc-insert-max-level``. Maintaining the Table of Contents Up-to-date -------------------------------------------- One issue is that you will probably want to maintain the inserted table of contents up-to-date. ``rst-toc-update`` (``C-c C-t C-u``) will automatically locate an inserted table of contents following a ``.. contents::`` directive. Syntax Highlighting via Font-Lock ================================= ``rst-mode`` provides syntax highlighting for nearly all to reStructuredText_ constructs. Use ``customize-group rst-faces`` to customize the faces used for font-locking. Customization ============= Some aspects of ``rst-mode`` can be configured through the customization feature of Emacs_. Try :: M-x customize-grouprst for all customizations or use the respective menu entry. Those customizations which are useful for many people are described in this section. Customizing Section Title Formatting ------------------------------------ For a couple of things the reStructuredText_ syntax offers a choice of options on how to do things exactly. Some of these choices influence the operation of ``rst.el`` and thus can be configured. The customizations are contained in the ``rst-adjust`` group. Among these things is the exact layout of section adornments. In fact reStructuredText_ prescribes only the characters and how these characters must be used but the exact use of concrete adornments may be different in every source file. Using the customization option ``rst-preferred-adornments`` you can tell ``rst-mode`` on the exact sequence of adornments you prefer to markup the different levels of sections headers. The title text of over-and-under adornments may be indented. ``rst-default-indent`` tells ``rst-mode`` how many positions a over-and-under adornment should be indented. Finally if you create a completely new section adornment by ``rst-adjust`` the question is on what level the new section adornment should be. ``rst-new-adornment-down`` can be used to create one level lower adornments than the previous section title. By default the new section title is on the same level as the previous one. Please note, that normally the given adornments of a buffer are preferred over your preferences, however. See `Redoing All the Adornments to Your Taste`_ for a method to change this for the whole buffer. Customizing Indentation ----------------------- reStructuredText_ uses indentation a lot to signify a certain meaning. In some cases the exact amount of indentation is prescribed by the syntax while in some cases the exact indentation is not fixed. The customization group ``rst-indent`` allows to customize the amount of indentation in these cases. In field lists the content of a field needs to be indented relative to the field label. ``rst-indent-field`` tells ``rst-mode`` the amount of indentation to use for field content. A value of zero always indents according to the content after the field label. The indentation of literal blocks is controlled by ``rst-indent-literal-normal`` and ``rst-indent-literal-minimized``. The first is used when the leading literal tag (``::``) appears alone on a line. The second is used when the minimized style is used where the literal tag follows some text. The indentation of comments is controlled by ``rst-indent-comment``. Of course this makes only sense for the indented comments of reStructuredText_. Customization option ``rst-indent-width`` gives the default indentation when there are no other hints on what amount of indentation to use. Customizing Faces ----------------- The faces used for font-locking can be defined in the ``rst-faces`` customization group. The customization options ending in ``-face`` are only there for backward compatibility so please leave them as they are. reStructuredText_ sets no limit on the nesting of sections. By default there are six levels of fontification defined. Section titles deeper than six level have no special fontification - only the adornments are fontified. The exact mapping from a level to a face is done by by ``rst-adornment-faces-alist``, however. So if you need fontification deeper than six levels you may want to customize this option. You may also want to customize it if you like the general idea of section title fontification in ``rst-mode`` but for instance prefer a reversed order. Related aspects =============== This section covers some general aspects using Emacs_ for editing reStructuredText_ source. They are not directly related to ``rst-mode`` but may enhance your experience. ``text-mode`` Settings ---------------------- Consult the Emacs_ manual for more ``text-mode`` customizations. In particular, you may be interested in setting the following variables, functions and modes that pertain somewhat to ``text-mode``: * ``indent-tabs-mode`` * ``colon-double-space`` * ``sentence-end-double-space`` * ``auto-fill-mode`` * ``auto-mode-alist`` Editing Tables: Emacs table mode -------------------------------- You may want to check out `Emacs table mode`_ to create an edit tables, it allows creating ASCII tables compatible with reStructuredText_. .. _Emacs table mode: http://table.sourceforge.net/ Character Processing -------------------- Since reStructuredText punts on the issue of character processing, here are some useful resources for Emacs_ users in the Unicode world: * `xmlunicode.el and unichars.el from Norman Walsh `__ * `An essay by Tim Bray, with example code `__ * For Emacs_ users on Mac OS X, here are some useful useful additions to your .emacs file. - To get direct keyboard input of non-ASCII characters (like "option-e e" resulting in "é" [eacute]), first enable the option key by setting the command key as your meta key:: (setq mac-command-key-is-meta t) ;; nil for option key Next, use one of these lines:: (set-keyboard-coding-system 'mac-roman) (setq mac-keyboard-text-encoding kTextEncodingISOLatin1) I prefer the first line, because it enables non-Latin-1 characters as well (em-dash, curly quotes, etc.). - To enable the display of all characters in the Mac-Roman charset, first create a fontset listing the fonts to use for each range of characters using charsets that Emacs_ understands:: (create-fontset-from-fontset-spec "-apple-monaco-medium-r-normal--10-*-*-*-*-*-fontset-monaco, ascii:-apple-monaco-medium-r-normal--10-100-75-75-m-100-mac-roman, latin-iso8859-1:-apple-monaco-medium-r-normal--10-100-75-75-m-100-mac-roman, mule-unicode-0100-24ff:-apple-monaco-medium-r-normal--10-100-75-75-m-100-mac-roman") Latin-1 doesn't cover characters like em-dash and curly quotes, so "mule-unicode-0100-24ff" is needed. Next, use that fontset:: (set-frame-font "fontset-monaco") - To enable cooperation between the system clipboard and the Emacs_ kill ring, add this line:: (set-clipboard-coding-system 'mac-roman) Other useful resources are in `Andrew Choi's Emacs 21 for Mac OS X FAQ `__. Credits ======= Part of the original code of ``rst.el`` has been written by Martin Blais and David Goodger and Wei-Wei Guo. The font-locking came from Stefan Merten. Most of the code has been modified, enhanced and extended by Stefan Merten who also is the current maintainer of ``rst.el``. .. _Emacs: http://www.gnu.org/software/emacs/emacs.html .. _reStructuredText: http://docutils.sf.net/rst.html .. _Docutils: http://docutils.sf.net/ .. LocalWords: reST utf Merten Blais rst el docutils modeline emacs .. Local Variables: mode: rst indent-tabs-mode: nil fill-column: 70 End: .. LocalWords: Init mEmacs sInit alist setq txt overlines RET nd py .. LocalWords: dwim conf toolset pseudoxml pdf Imenu imenu menubar .. LocalWords: func toc xmlunicode unichars eacute charset fontset .. LocalWords: kTextEncodingISOLatin charsets monaco ascii latin .. LocalWords: iso unicode Choi's Goodger Guo docutils-0.12/docs/user/mailing-lists.txt0000664000175000017500000001255712130102646022454 0ustar engelbertengelbert00000000000000========================= Docutils_ Mailing Lists ========================= :Author: Lea Wiemann :Contact: docutils-develop@lists.sourceforge.net :Revision: $Revision: 7644 $ :Date: $Date: 2013-04-06 22:29:26 +0200 (Sam, 06. Apr 2013) $ :Copyright: This document has been placed in the public domain. .. raw:: html All discussion about Docutils takes place on mailing lists. There are four different lists with traffic related to Docutils. If unsure, use the **Docutils-users** mailing list: Docutils-users -------------- The Docutils-users mailing list is a place to discuss any issues related to the usage of Docutils and reStructuredText. (Please be sure to check the FAQ_ first.) There are three possibilities to **read and post** messages on the mailing lists; use the one you feel most comfortable with. * Using an `email subscription`__. This is the traditional way; you will receive all messages sent to the mailing list via email. __ http://lists.sourceforge.net/lists/listinfo/docutils-users * Using Gmane's `web interface`__. To post a message, click "post" or "followup" in the drop-down menu on the right. (Gmane also has a complete **archive** of the mailing list; use the search form at the top of this page to search it.) __ http://news.gmane.org/gmane.text.docutils.user * If you prefer to use a newsreader, you can also use Gmane's `NNTP interface`__ (gmane.text.docutils.user on news.gmane.org). __ nntp://news.gmane.org/gmane.text.docutils.user **If you do not wish to subscribe,** you can also just send an email message with your question or comment to Docutils-users@lists.sourceforge.net. Please note in your message that you are not subscribed (to make sure that you receive copies [CCs] of any replies). The first time you post a message without being subscribed (also when posting via Gmane), you will receive an automatic response with the subject "Your message to Docutils-users awaits moderator approval"; this is done to prevent spam to the mailing lists. Your message will usually be approved within a few hours. To avoid duplicates, please do not resend your message using a different email address. After your first message has been approved, your email address will be added to the whitelist and future messages will be posted to the mailing list without moderation. Docutils-develop ---------------- Discussions about developing and extending Docutils take place on the Docutils-develop mailing list. You can access this list via `email subscription`__, web__ or news__ (gmane.text.docutils.devel); the posting address is Docutils-develop@lists.sourceforge.net. __ http://lists.sourceforge.net/lists/listinfo/docutils-develop __ http://news.gmane.org/gmane.text.docutils.devel __ nntp://news.gmane.org/gmane.text.docutils.devel Docutils-checkins ----------------- All check-ins to the `Subversion repository`_ cause a "check-in email" to the Docutils-checkins list. In order to stay informed about current development, developers are advised to monitor this mailing list. This mailing list is for reading only; please direct any discussion about the check-ins to Docutils-develop. (For your convenience, the Reply-To header of all check-in emails points to Docutils-develop.) This mailing list is accessible via `email subscription`__, web__ or news__ (gmane.text.docutils.cvs) as well. If you are using an email subscription and you would prefer to only receive check-in messages for changes that affect the main Docutils distribution (i.e. ``trunk/docutils/*``), go to the `list options`_ page and select the "Docutils core" topic. __ http://lists.sourceforge.net/lists/listinfo/docutils-checkins __ http://news.gmane.org/gmane.text.docutils.cvs __ nntp://news.gmane.org/gmane.text.docutils.cvs .. _list options: http://lists.sf.net/lists/options/docutils-checkins Doc-SIG ------- The "Python Documentation Special Interest Group" (Doc-SIG) mailing list is occasionally used to discuss the usage of Docutils for Python documentation. This mailing list can be accessed via `email subscription`__, web__ or news__ (gmane.comp.python.documentation) as well. You must be subscribed in order to post messages to this mailing list. __ http://mail.python.org/mailman/listinfo/doc-sig __ http://news.gmane.org/gmane.comp.python.documentation __ nntp://news.gmane.org/gmane.comp.python.documentation .. _Subversion repository: ../dev/repository.html .. _Docutils: http://docutils.sourceforge.net/ .. _FAQ: ../../FAQ.html docutils-0.12/docs/user/slide-shows.txt0000664000175000017500000006136110412765547022156 0ustar engelbertengelbert00000000000000.. include:: ================================= Easy Slide Shows With reST & S5 ================================= :Authors: David Goodger & Chris Liechti :Date: $Date: 2006-03-30 16:29:59 +0200 (Don, 30. Mär 2006) $ .. This document has been placed in the public domain. .. container:: handout How to create quick, good-looking presentation slide shows with Docutils_/reStructuredText_ and S5_. This document serves both as a user manual and as a usage example of the s5_html.py writer and the rst2s5.py front end. To view this document as a slide show see http://docutils.sf.net/docs/user/slide-shows.s5.html (or `your local copy `__). .. contents:: :class: handout .. class:: tiny * S5 themes are designed for full-screen display areas with a 4:3 aspect ratio. If the slide text doesn't fit in your browser window, try decreasing the text size. * Use the space bar to advance, Page Up/Down & arrow keys to navigate. * Best viewed in Firefox_, Safari, and Konqueror. Click the "|mode|" button to switch between presentation & handout/outline modes. Hit the "C" key to display the navigation controls, or mouse over the lower right-hand corner. * Functionality is limited in Opera. Switch to full-screen mode (F11 key) to activate Opera Show. * S5 works in Internet Explorer, but it may look ugly. .. container:: handout The first slide of a presentation consists of all visible text up to the first section title. The document title is also added to the footer of all slides. The "footer" directive is used to specify part of the slide footer text. It is currently limited to one short line (one paragraph). There is no support for the "header" directive in the themes included with Docutils. .. _Docutils: http://docutils.sourceforge.net/ .. _reStructuredText: http://docutils.sourceforge.net/rst.html .. _S5: http://meyerweb.com/eric/tools/s5/ .. _Firefox: http://www.mozilla.com/firefox/ .. |bullet| unicode:: U+02022 .. |mode| unicode:: U+00D8 .. capital o with stroke .. footer:: Location |bullet| Date Introduction ============ .. class:: handout ``rst2s5.py`` is a Docutils_ front end that outputs HTML for use with S5_, a "Simple Standards-based Slide Show System" by Eric Meyer. .. topic:: Installation :class: handout Prerequisites: Python and the Docutils_ package have to be installed. See the `Docutils README`__ file for installation instructions. __ http://docutils.sourceforge.net/README.html * reStructuredText .. class:: handout Uses normal reStructuredText as input. * One section per slide .. class:: handout Each first-level section is converted into a single slide. * XHTML output .. container:: handout Presentations can be viewed using most modern graphical web browsers. The browser must support CSS, JavaScript, and XHTML. S5 even works with IE! S5 was designed to add the functionality of the `Opera Show`_ standard (without Opera Show's limitations) to non-Opera browsers. Unfortunately, most of S5's CSS and JavaScript extensions don't function in the Opera browser. .. _Opera Show: http://www.opera.com/support/tutorials/operashow/ * Themes .. class:: handout A variety of themes are available. See `Example Themes`_, below. * ``rst2s5.py`` .. class:: handout The front-end tool to generate S5 slide shows. .. topic:: Keyboard Controls :class: handout The following apply in any supporting browser besides Opera, which uses the default Opera Show controls instead. .. list-table:: :header-rows: 1 * - Action - Key(s) * - Go to the next slide - * [Space bar] * [Return] * [Enter] * [Right arrow] * [Down arrow] * [Page down] * Click the left mouse button outside of the control area, Flash object, or movie * - Go to the previous slide - * [Left arrow] * [Up arrow] * [Page up] * - Go to the title (first) slide - [Home] * - Go to the last slide - [End] * - Jump directly to a slide - Type the slide number, then hit [Return] or [Enter] * - Skip forward *n* slides - Type the number of slides to skip, then hit any "go to next" key (except [Return] or [Enter]) * - Skip backward *n* slides - Type the number of slides to skip, then hit any "go to previous" key * - Switch between slideshow and outline view - * [T] * Click the |mode| button * - Show/hide slide controls - * [C] * Move the mouse pointer over the control area Further details of the S5 user interface can be found at `Eric Meyer's S5 page`__. __ S5_ Features (1) ============ .. container:: handout The S5/HTML Writer supports all the standard Docutils HTML features. S5 has been released to the Public Domain. S5-specific features: .. class:: incremental * The document title is duplicated on each slide in the S5 footer. * The ``footer`` directive may be used to define additional text in the S5 footer. .. container:: handout But it is limited to one line of text. This is useful for information such as the date of the presentation and/or the location. The field in the footer is left blank if no ``footer`` directive is used. Example:: .. footer:: Location - Date There is also a progress indicator (slide counter) in the footer that can be enabled. It's disabled by default. * Incremental display. .. class:: handout An "incremental" class can be assigned to lists and other elements to get one-item-at-a-time behavior (like this list). Incremental display does not work in the Opera browser. * Text auto-scaling. .. class:: handout The text size adjusts relative to the size of your browser window automatically. You may need to reload the document after resizing the window. The browser and platform affect the font used; be sure to test the slide show on the presentation system. Features (2): Handouts ====================== .. container:: handout The contents of any element with a "class" attribute value of "handout" are hidden in the slide presentation, and are only visible when the presentation is printed, or viewed in outline mode. "Handout"-class elements can appear anywhere in the text, as often as needed. This means that the slides and extra handout material can be combined in one document. The handout can be printed directly from the browser, and it will contain more than just silly framed slides. This can be used to provide more detailed information, or for speaker's notes. .. class:: incremental * Use the "class" directive:: .. class:: handout .. container:: handout The ``.. class:: handout`` directive can be used to tag individual paragraphs and other elements. The "class" directive applies to the first element immediately following:: .. class:: handout This paragraph will get a ``class="handout"`` attribute. This paragraph will not be affected. It also applies to multiple elements in the directive content:: .. class:: handout These paragraphs are the content of the "class" directive. And as such... Both paragraphs will *individually* receive ``class="handout"`` attributes. * Use the "container" directive:: .. container:: handout .. container:: handout Arbitrary handout blocks can be created using the ``container`` directive. The content is treated as one. * Use the "class" option of directives that support it:: .. topic:: Extra Material For Handouts :class: handout .. container:: handout The following directives support "class" options: * all admonition directives ("admonition", "note", "hint", etc.) * "image" & "figure" * "topic" * "sidebar" * "line-block" * "parsed-literal" * "rubric" * "compound" * "table", "csv-table", & "list-table" * "target-notes" (more about that below) * "role" (pre-defined; more below) Handout contents are also visible on the screen if the S5 view mode is toggled from "slide show" to "outline" mode. Caveats ======= .. class:: incremental 1. Some Docutils features are not supported by some themes. .. container:: handout For example, header rendering is not supported by the themes supplied with Docutils. The "header" directive is used to set header text. S5 automatically inserts section/slide titles into the "header" area of a slide. If both Docutils headers and S5 headers (slide titles) exist simultaneously, they interfere with each other. 2. Care must be taken with the "contents" directive. .. container:: handout The ``--no-toc-backlinks`` option is the default for the S5/HTML writer (``toc_backlinks=0`` setting). Other values for this setting will change the CSS class of headings such that they won't show up correctly in the slide show. Use the ``:class: handout`` option on the "contents" directive to limit the table of contents to the handout/outline mode only:: .. contents:: :class: handout .. class:: incremental 3. Subsections ... ------------------ ... may be used, sparingly. .. container:: handout Only first-level sections become slides. Not many levels of subsections can fit on a slide. Subsections (of any level) work normally in handouts though. Add "``.. class:: handout``" before a subsection (or sub-subsection, or ...), and the entire subsection will only appear in the handout. Generating a Slide Show (1) =========================== .. class:: incremental 1. Open a console (terminal, command shell) and go to the folder containing your file, ``slides.txt``. 2. Run the command:: rst2s5.py slides.txt slides.html 3. Specify an S5 theme with the ``--theme`` option. .. class:: handout Docutils will copy the S5 theme files into a ``ui/`` folder beside the output HTML file. A slide show can also link to an existing theme using the ``--theme-url`` option. Generating a Slide Show (2) =========================== .. class:: incremental 4. Include a copy of any linked stylesheet. .. class:: handout The default Docutils stylesheet, ``html4css1.css``, will normally be embedded in the output HTML. If you choose to link to a stylesheet instead of embedding, you must include a copy (suggested location: in the ``ui/`` directory). 5. Open ``slides.html`` in a web browser. 6. Expand the browser window to full-screen mode, and speak. .. class:: handout The `Web Developer`__ extension for Firefox is very useful. With it, you can resize your browser window to the exact dimensions of the projector you'll be using, so you can test beforehand. There are many other useful features as well. __ http://chrispederick.com/work/webdeveloper/ 7. Profit! Examples (1) ============ .. sidebar:: Hint Admonitions, tables, sidebars, and other elements can be used in on-screen presentations in handouts. Images too! .. image:: images/happy_monkey.png :alt: sample image ===== ===== ====== A B A or B ===== ===== ====== False False False True False True False True True True True True ===== ===== ====== Examples (2): Incremental Text ============================== .. class:: incremental Paragraphs can be displayed one at a time... .. container:: ... or a bunch at a time. This second paragraph is displayed together with the previous one by grouping them with the "container" directive. `We can also display` `one` `word` `at` `a` `time,` `or a phrase` `at a time,` `or even` `o`\ `n`\ `e` `l`\ `e`\ `t`\ `t`\ `e`\ `r` `at a time!` `(But the markup ain't pretty.)` Examples (3): Incr. Graphics ============================ Let's play... Rock, Scissors, Paper .. container:: animation .. image:: images/rsp-empty.png :class: hidden slide-display .. class:: incremental hidden slide-display .. image:: images/rsp-objects.png .. image:: images/rsp-cuts.png .. image:: images/rsp-covers.png .. image:: images/rsp-breaks.png .. image:: images/rsp-all.png :class: incremental Themes ====== .. class:: incremental * Several themes are available, and they're easy to adapt. .. container:: handout Themes from the `S5 tutorial`__ can be used. These themes are in the public domain and may be redistributed freely. __ http://meyerweb.com/eric/tools/s5/s5blank.zip Sites with other S5 themes: * http://meyerweb.com/eric/tools/s5/themes/ * http://mozilla.wikicities.com/wiki/Firefox_S5:Designs * http://lachy.id.au/dev/mozilla/firefox/s5/ * http://www.openlight.com/Python-S5-Theme.tar.gz S5 is becoming more popular every day. Do a web search for "S5 theme" and you're bound to find plenty of choices. * "``--theme``" option. .. container:: handout The theme can be specified with the "``--theme``" command-line option. Example:: rst2s5 --theme big-black slides.txt slides.html The default theme is "default". * "``theme``" setting. .. class:: handout You can set the theme with the "``theme``" configuration file setting. * Copied to ``./ui//``. .. class:: handout Themes are copied into a ``ui/`` folder inside the folder containing the presentation. * Link with "``--theme-url``" option. .. class:: handout Link to a theme on the same or another web site, using the "``--theme-url``" option or "``theme_url``" configuration file setting. Example Themes ============== .. class:: handout The default theme, "default", is a simplified version of S5's default theme. It accommodates up to 13 lines of text. .. class:: center "default" .. image:: images/default.png :align: center Example Themes: Small Text ========================== .. class:: handout The "small-white" and "small-black" themes are simplifications of the default theme (**small** black text on a **white** background, and **small** black text on a **white** background, respectively). They each accommodate up to 15 lines of text. .. list-table:: :class: borderless * - "small-white" .. image:: images/small-white.png - "small-black" .. image:: images/small-black.png Example Themes: Large Text ========================== .. class:: handout The "big-white" and "big-black" themes feature very large, bold text, with no footers. Only five short lines fit in a slide. .. list-table:: :class: borderless * - "big-white" .. image:: images/big-white.png - "big-black" .. image:: images/big-black.png Example Themes: Medium Text =========================== .. class:: handout The "medium-white" and "medium-black" themes feature medium-sized text. Up to 8 lines of text are accommodated. .. list-table:: :class: borderless * - "medium-white" .. image:: images/medium-white.png - "medium-black" .. image:: images/medium-black.png S5 Theme Files ============== An S5 theme consists of a directory containing several files -- stylesheets, JavaScript, and graphics: .. image:: images/s5-files.png :align: center .. container:: handout The generated HTML contains the entire slide show text. It also contains links to the following files: * slides.css simply contains import links to: - s5-core.css: Default styles critical to the proper functioning of the slide show; don't touch this! - framing.css: Sets the basic layout of slide components (header, footer, controls, etc. This file is the often edited. - pretty.css: Presentation styles that give the slide show a unique look and feel. This is the file that you're most likely to edit for a custom theme. You can make a whole new theme just by editing this file, and not touching the others. * outline.css: Styles for outline mode. * print.css: Styles for printing; hides most layout elements, and may display others. * opera.css: Styles necessary for the proper functioning of S5 in Opera Show. * slides.js: the JavaScript that drives the dynamic side of the slide show (actions and navigation controls). It automatically IDs the slides when the document loads, builds the navigation menu, handles the hiding and showing of slides, and so on. The code also manages the fallback to Opera Show if you're using the Opera web browser. Two files are included to support PNG transparency (alpha channels) in Internet Explorer: - iepngfix.htc - blank.gif Making a Custom Theme ===================== .. class:: incremental 1. Run "``rst2s5.py --theme .txt .html``". .. class:: handout This initializes the ``ui`` directory with the base theme files. 2. Copy ``ui/`` to ``ui/``. 3. Edit the styles. .. class:: handout Start with ``pretty.css``; edit ``framing.css`` if you need to make layout changes. 4. Run "``rst2s5.py --theme-url ui/ .txt .html``". .. class:: handout We use the ``--theme-url`` option to refer to the new theme. Open your ``.html`` in a browser to test the new theme. 5. Rinse & repeat. .. class:: handout Repeat from step 3 until you're satisfied. .. TODO: What to do next: * add a ``__base__`` file * create a personal reusable theme (plugin) * submit the new theme to Docutils ``docutils/writers/s5_html/themes/`` .. container:: handout Resources: * W3C's `Learning CSS `__ * `Creating An S5 Theme `__ * A short tutorial on how to create themes (in German): `Eigenes Theme erstellen `__ Classes: Incremental (1) ======================== .. class:: handout Several "class" attribute values have built-in support in the themes supplied with Docutils. .. class:: incremental As described earlier, * ``.. class:: incremental`` * ``.. container:: incremental`` * :: .. sidebar:: title :class: incremental Classes: Incremental (2) ======================== The "incremental" interpreted text role is also supported: .. class:: incremental :: :incremental:`This will appear first,` `and this will appear second.`:incremental: Requires "``.. include:: ``". .. container:: handout As you can see, this markup is not very convenient. .. class:: incremental | But ``s5defs.txt`` includes this useful definition: | "``.. default-role:: incremental``". So: :: `This` `is` `all` `we` `need` `This` `is` `all` `we` `need` `to mark up incremental text.` Classes: Incremental (3) ======================== .. class:: small :: .. container:: animation .. image:: images/empty.png :class: hidden slide-display .. class:: incremental hidden slide-display .. image:: images/1.png .. image:: images/2.png .. image:: images/3.png :class: incremental .. container:: handout This is how the example works. The animation effects are caused by placing successive images at the same location, laying each image over the last. For best results, all images should be the same size, and the positions of image elements should be consistent. Use image transparency (alpha channels) to get overlay effects. Absolute positioning is used, which means that the images take up no space in the flow. If you want text to follow the images, you have to specify the total size of the container via a style. Otherwise, the images and any following text will overlap. These class values do the work: animation This wraps the container with styles that position the images absolutely, overlaying them over each other. Only useful on a container. hidden Unless overridden (by "slide-display", for example), these elements will not be displayed. Only the last image will be displayed in handout mode, when print, or when processed to ordinary HTML, because it does *not* carry a "hidden" class. slide-display In conjunction with "hidden", these elements will only appear on the slide, preventing clutter in the handout. incremental The second and subsequent images will appear one at a time. The first image will already be present when the slide is displayed, because it does *not* carry an "incremental" class. Classes: Text Size ================== .. class:: incremental * :tiny:`tiny` (class & role name: "tiny", e.g. "``:tiny:`text```") * :small:`small` ("small") * normal (unstyled) * :big:`big` ("big") * :huge:`huge` ("huge") Requires "``.. include:: ``". Classes: Alignment ================== .. class:: incremental .. class:: left Left (class name: "left") .. class:: center Center ("center" & "centre") .. class:: right Right ("right") .. class:: handout These classes apply to block-level elements only. They cannot be used for inline text (i.e., they're not interpreted text roles). .. class:: incremental Example:: .. class:: center Text to be centered. Classes: Text Colours ===================== :black:`black` [black], :gray:`gray`, :silver:`silver`, :white:`white` [white], :maroon:`maroon`, :red:`red`, :magenta:`magenta`, :fuchsia:`fuchsia`, :pink:`pink`, :orange:`orange`, :yellow:`yellow`, :lime:`lime`, :green:`green`, :olive:`olive`, :teal:`teal`, :cyan:`cyan`, :aqua:`aqua`, :blue:`blue`, :navy:`navy`, :purple:`purple` The class names and role names are the same as the colour names. For example, "``:orange:`text```" produces ":orange:`text`". .. class:: incremental Requires "``.. include:: ``". Classes: Borderless Tables ========================== .. class:: handout Here's an ordinary, unstyled table: .. class:: incremental ========= ======= Sometimes borders --------- ------- are useful. ========= ======= And after applying "``.. class:: borderless``": .. class:: borderless ======= ========== ======= But sometimes, borders ------- ---------- ------- are **not** wanted. ======= ========== ======= Classes: Print-Only =================== .. class:: handout Elements with ``class="print"`` attributes display their contents when printed, overriding ``class="hidden"``. .. class:: incremental Example: the "target-notes" directive:: .. topic:: Links :class: hidden print .. target-notes:: :class: hidden print .. container:: handout One good example, used in this document, is the "target-notes" directive. For each external target (hyperlink) in the text, this directive generates a footnote containing the visible URL as content. Footnote references are placed after each hyperlink reference. The "topic" directive is given a "class" attribute with values "hidden" and "print", so the entire topic will only be displayed when printed. The "target-notes" directive also assigns a "class" attributes with values "hidden" and "print" to each of the footnote references it inserts throughout the text; they will only show up when printed. .. class:: incremental Other uses may require "``.. include:: ``". Useful Extensions For Firefox ============================= * `Autohide`__ .. class:: handout Automatically hides toolbars in full-screen mode. __ http://www.krickelkrackel.de/autohide/autohide.htm * `Web Developer`__ .. class:: handout Adds a context submenu and a toolbar with a lot of useful functionality, including the viewing and live editing of stylesheets, and sizing the browser window. __ http://chrispederick.com/work/webdeveloper/ To Do ===== .. class:: incremental * Multi-display support: - speaker's notes on the laptop screen - slides on the projector - two views stay in sync - presentation controlled from either display * Add timeout to incremental style. .. class:: handout I.e., incremental-specific style should go away (revert to normal) after a certain interval. These will require some serious JavaScript-fu! That's All, Folks! ================== .. class:: huge Further information: http://docutils.sf.net Docutils users' mailing list: docutils-users@lists.sf.net `Any questions?` .. topic:: Links :class: hidden print .. target-notes:: :class: hidden print docutils-0.12/docs/user/odt.txt0000664000175000017500000011276012036352177020476 0ustar engelbertengelbert00000000000000======================= Odt Writer for Docutils ======================= :Author: Dave Kuhlman :Contact: docutils-develop@lists.sourceforge.net :Revision: $Revision: 7528 $ :Date: $Date: 2012-10-13 22:52:15 +0200 (Sam, 13. Okt 2012) $ :Copyright: This document has been placed in the public domain. :abstract: This document describes the Docutils odtwriter (rst2odt.py). .. sectnum:: .. contents:: Introduction ============ What it does -- ``rst2odt.py`` translates reST (reStructuredText) into a Open Document Format ``.odt`` file. You can learn more about the ODF format here: - `OASIS Open Document Format for Office Applications (OpenDocument) TC`_ - `Open Document at Wikipedia`_ You should be able to open documents (.odt files) generated with ``rst2odt.py`` in ``OpenOffice/oowriter``. You can learn more about Docutils and reST here: `Docutils`_ Requirements ============ In addition to the Docutils standard requirements, ``odtwriter`` requires: - ElementTree -- Python (version 2.5 or later) now includes ElementTree (``xml.etree.ElementTree``). - Optional -- `Pygments`_ is required if you want syntax highlighting of code in literal blocks. See section `Syntax highlighting`_. - Optional -- `Python Imaging Library`_ (PIL) is required if on an image or figure directive, you specify ``scale`` but not ``width`` and ``height``. See section `Images and figures`_. How to Use It ============= Run it from the command line as follows:: $ rst2odt.py myinput.txt myoutput.odt To see usage information and to learn about command line options that you can use, run the following:: $ rst2odt.py --help Examples:: $ rst2odt.py -s -g python_comments.txt python_comments.odt $ rst2odt.py --source-url=odtwriter.txt --generator --stylesheet=/myconfigs/styles.odt odtwriter.txt odtwriter.odt Configuration file ------------------ The options described below can also be set in a configuration file. Use section ``[odf_odt writer]`` to set options specific to the ``odtwriter``. For example:: [odf_odt writer] stylesheet: styles1.odt See the "Docutils Configuration" document for more information on Docutils configuration files, including locations which are searched. Command line options -------------------- The following command line options are specific to ``odtwriter``: --stylesheet= Specify a stylesheet URL, used verbatim. Default: writers/odf_odt/styles.odt in the installation directory. --odf-config-file= Specify a configuration/mapping file relative to the current working directory for additional ODF options. In particular, this file may contain a section named "Formats" that maps default style names to names to be used in the resulting output file allowing for adhering to external standards. For more info and the format of the configuration/mapping file, see the odtwriter doc. --cloak-email-addresses Obfuscate email addresses to confuse harvesters while still keeping email links usable with standards- compliant browsers. --no-cloak-email-addresses Do not obfuscate email addresses. --table-border-thickness=TABLE_BORDER_THICKNESS Specify the thickness of table borders in thousands of a cm. Default is 35. --add-syntax-highlighting Add syntax highlighting in literal code blocks. --no-syntax-highlighting Do not add syntax highlighting in literal code blocks. (default) --create-sections Create sections for headers. (default) --no-sections Do not create sections for headers. --create-links Create links. --no-links Do not create links. (default) --endnotes-end-doc Generate endnotes at end of document, not footnotes at bottom of page. --no-endnotes-end-doc Generate footnotes at bottom of page, not endnotes at end of document. (default) --generate-list-toc Generate a bullet list table of contents, not an ODF/``oowriter`` table of contents. --generate-oowriter-toc Generate an ODF/``oowriter`` table of contents, not a bullet list. (default) **Note:** ``odtwriter`` is not able to determine page numbers, so you will need to open the generated document in ``oowriter``, then right-click on the table of contents and select "Update" to insert page numbers. --custom-odt-header=CUSTOM_HEADER Specify the contents of an custom header line. See odf_odt writer documentation for details about special field character sequences. See section `Custom header/footers: inserting page numbers, date, time, etc`_ for details --custom-odt-footer=CUSTOM_FOOTER Specify the contents of an custom footer line. See odf_odt writer documentation for details about special field character sequences. See section `Custom header/footers: inserting page numbers, date, time, etc`_ for details Styles and Classes ================== ``odtwriter`` uses a number of styles that are defined in ``styles.xml`` in the default ``styles.odt``. This section describes those styles. Note that with the ``--stylesheet`` command line option, you can use either ``styles.odt`` or ``styles.xml``, as described below. Use of ``styles.odt`` is recommended over ``styles.xml``. You can modify the look of documents generated by ``odtwriter`` in several ways: - Open (a copy of) ``styles.odt`` in ``OpenOffice/oowriter`` and modify the style you wish to change. Now, save this document, then generate your documents using this modified copy of ``styles.odt``. In my version of ``oowriter``, to modify styles, either (1) press F11 or (2) use menu item "Format/Styles and Formatting", then right-click on the relevant style and select "Modify". Modify the style, then save your document. - Open a document generated by ``odtwriter`` in `oowriter``. Now, edit the style you are interested in modifying. Now, you can extract the styles.xml file from your document and either (1) use this as your default styles file or (2) copy and paste the relevant style definition into your styles.xml. - Extract ``styles.xml`` from ``styles.odt`` using your favorite ``zip/unzip`` tool. Then modify ``styles.xml`` with a text editor. Now re-zip it back into your own ``styles.odt``, or use it directly by specifying it with the ``--stylesheet`` command line option. **Hint:** If you intend to extract ``styles.xml`` from an ``.odt`` file (and then "re-zip" it), you should turn off XML optimization/compression in ``oowriter``. In order to this in ``oowriter``, use Tools --> Options... --> Load-Save --> General and turn off "Size optimization for XML format". - Open an empty (or new) document in ``oowriter``. Define all of the styles described in this section. Then, use that document (a .odt file) as your stylesheet. ``odtwriter`` will extract the ``styles.xml`` file from that document and insert it into the output document. - Some combination of the above. Styles used by odtwriter ------------------------ This section describes the styles used by ``odtwriter``. Note that we do not describe the "look" of these styles. That can be easily changed by using ``oowriter`` to edit the document ``styles.odt`` (or a copy of it), and modifying any of the styles described here. To change the definition and appearance of these styles, open ``styles.odt`` in ``oowriter`` and open the Styles and Formatting window by using the following menu item:: Format --> Styles and Formatting Then, click on the Paragraph Styles button or the Character Styles button at the top of the Styles and Formatting window. You may also need to select "All Styles" from the drop-down selection list at the bottom of the Styles and Formatting window in order to see the styles used by ``odtwriter``. Notice that you can make a copy of file ``styles.odt``, modify it using ``oowriter``, and then use your copy with the ``--stylesheet=`` command line option. Example:: $ rst2odt.py --stylesheet=mystyles.odt test2.txt test2.odt Paragraph styles ~~~~~~~~~~~~~~~~ rststyle-attribution The style for attributions, for example, the attribution in a ``.. epigraph::`` directive. Derived from ``rststyle-blockquote``. rststyle-blockindent An indented block. rststyle-blockquote A block quote. rststyle-blockquote-bulletitem The style for bullet list items inside block quote. rststyle-blockquote-enumitem The style for enumerated list items inside block quote. rststyle-bodyindent An indented block. rststyle-bulletitem An item in an bullet list. rststyle-caption The caption in a figure or image. Also see ``rststyle-legend``. rststyle-codeblock Literal code blocks -- A block of example code. Created with double colon ("::") followed by an indented block or with the ``.. parsed-literal::`` directive. Derived from the ``Preformatted Text`` style in ``oowriter``. rststyle-enumitem An item in an enumerated list. rststyle-epigraph The style for epigraphs, for example, the body of an ``.. epigraph::`` directive. Derived from ``rststyle-blockquote``. rststyle-epigraph-bulletitem The style for bullet list items inside epigraphs. rststyle-epigraph-enumitem The style for enumerated list items inside epigraphs. rststyle-footer The style for footers. The footer content originates from the ``..footer::`` directive and in response to the command line flags for generator (``--generator``), date/time generated (``--date`` and ``--time``), and view source link (``--source-link`` and ``--source-url=URL``). rststyle-header The style for headers. The header content originates from the ``..header::`` directive. rststyle-highlights The style for highlightss, for example, the body of an ``.. highlights::`` directive. Derived from ``rststyle-blockquote``. rststyle-highlights-bulletitem The style for bullet list items inside highlights. rststyle-highlights-enumitem The style for enumerated list items inside highlights. rststyle-horizontalline A horizontal line, e.g. used for transitions. rststyle-legend The legend in a figure. See the Docutils figure directive. Also see ``rststyle-caption``. rststyle-table-title The style for titles of tables. See section `The table directive`_. rststyle-textbody Normal text. The style for paragraphs. Derived from the ``Text body`` style in ``oowriter``. Character styles ~~~~~~~~~~~~~~~~ rststyle-emphasis Emphasis. Normally rendered as italics. rststyle-inlineliteral An inline literal. rststyle-strong Strong emphasis. Normally rendered as boldface. rststyle-quotation In-line quoted material. rststyle-codeblock-classname Syntax highlighting in literal code blocks -- class names. rststyle-codeblock-comment Syntax highlighting in literal code blocks -- comments. rststyle-codeblock-functionname Syntax highlighting in literal code blocks -- function names. rststyle-codeblock-keyword Syntax highlighting in literal code blocks -- Python language keywords. rststyle-codeblock-name Syntax highlighting in literal code blocks -- other names, for example, variables. rststyle-codeblock-number Syntax highlighting in literal code blocks -- literal numbers, including integers, floats, hex numbers, and octal numbers. rststyle-codeblock-operator Syntax highlighting in literal code blocks -- Python operators. rststyle-codeblock-string Syntax highlighting in literal code blocks -- literal strings. List styles ~~~~~~~~~~~ rststyle-bulletlist Bullet lists (but not in the table of contents) rststyle-blockquote-bulletlist Bullet lists in block quotes. rststyle-blockquote-enumlist Enumerated lists in block quotes. rststyle-enumlist-arabic Enumerated lists, arabic (but not in the table of contents) rststyle-enumlist-loweralpha Enumerated lists, lower alpha (but not in the table of contents) rststyle-enumlist-lowerroman Enumerated lists, lower roman (but not in the table of contents) rststyle-enumlist-upperalpha Enumerated lists, upper alpha (but not in the table of contents) rststyle-enumlist-upperroman Enumerated lists, upper roman (but not in the table of contents) rststyle-epigraph-bulletlist Bullet lists in epigraphs. See the ``.. epigraph::`` directive. rststyle-epigraph-enumlist Enumerated lists in epigraphs. See the ``.. epigraph::`` directive. rststyle-highlights-bulletlist Bullet lists in highlights blocks. See the ``.. highlights::`` directive. rststyle-highlights-enumlist Enumerated lists in highlights blocks. See the ``.. highlights::`` directive. rststyle-tocbulletlist Lists in the table of contents when section numbering is off. rststyle-tocenumlist Lists in the table of contents when section numbering is on. Admonition styles ~~~~~~~~~~~~~~~~~ rststyle-admon-attention-hdr The style for the attention admonition header/title. rststyle-admon-attention-body The style for the attention admonition body/paragraph. rststyle-admon-caution-hdr The style for the caution admonition header/title. rststyle-admon-caution-body The style for the caution admonition body/paragraph. rststyle-admon-danger-hdr The style for the admonition header/title. rststyle-admon-danger-body The style for the danger admonition body/paragraph. rststyle-admon-error-hdr The style for the error admonition header/title. rststyle-admon-error-body The style for the error admonition body/paragraph. rststyle-admon-hint-hdr The style for the hint admonition header/title. rststyle-admon-hint-body The style for the hint admonition body/paragraph. rststyle-admon-hint-hdr The style for the hint admonition header/title. rststyle-admon-hint-body The style for the hint admonition body/paragraph. rststyle-admon-important-hdr The style for the important admonition header/title. rststyle-admon-important-body The style for the important admonition body/paragraph. rststyle-admon-note-hdr The style for the note admonition header/title. rststyle-admon-note-hdr The style for the note admonition header/title. rststyle-admon-tip-body The style for the tip admonition body/paragraph. rststyle-admon-tip-hdr The style for the tip admonition header/title. rststyle-admon-warning-body The style for the warning admonition body/paragraph. rststyle-admon-warning-hdr The style for the warning admonition header/title. rststyle-admon-generic-body The style for the generic admonition body/paragraph. rststyle-admon-generic-hdr The style for the generic admonition header/title. Rubric style ~~~~~~~~~~~~ rststyle-rubric The style for the text in a rubric directive. The rubric directive recognizes a "class" option. If entered, odtwriter uses the value of that option instead of the ``rststyle-rubric`` style. Here is an example which which attaches the ``rststyle-heading1`` style to the generated rubric:: .. rubric:: This is my first rubric :class: rststyle-heading1 Table styles ~~~~~~~~~~~~ A table style is generated by ``oowriter`` for each table that you create. Therefore, ``odtwriter`` attempts to do something similar. These styles are created in the ``content.xml`` document in the generated ``.odt`` file. These styles have names prefixed with "rststyle-table-". There are two ways in which you can control the styles of your tables: one simple, the other a bit more complex, but more powerful. First, you can change the thickness of the borders of all tables generated in a document using the "--table-border-thickness" command line option. Second, you can control additional table properties and you can apply different styles to different tables within the same document by customizing and using tables in your stylesheet: ``styles.odt`` or whatever you name your copy of it using the --stylesheet command line option. Then, follow these rules to apply a table style to the tables in your document: - The default table style -- Optionally, alter and customize the style applied by default to tables in your document by modifying table "rststyle-table-0" in your stylesheet (``styles.odt`` or a copy). Caution: Do not change the name of this table. - User-created table styles -- Add one or more new table styles to be applied selectively to tables in your document by doing the following: 1. Using ``oowriter``, add a table to your stylesheet and give it a name that starts with the prefix "rststyle-table-", for example "rststyle-table-vegetabledata". Customize the table's border thickness, border color, and table background color. 2. In your reStructuredText document, apply your new table style to a specific table by placing the ".. class::" directive immediately before the table, for example:: .. class:: rststyle-table-vegetabledata The default table style will be applied to all tables for which you do not specify a style with the ".. class::" directive. Customize the table properties in ``oowriter`` using the table properties dialog for the table (style) that you wish to customize. Note that "--table-border-thickness" command line option overrides the border thickness specified in the stylesheet. The specific properties that you can control with this second method are the following: - Border thickness and border color. - Background color -- When you change the background color of a table to be used as a style (in ``styles.odt`` or whatever you name it), make sure you change the background color for the *table* and *not* for a cell in the table. ``odtwriter`` picks the background color from the table, not from a cell within the table. Line block styles ~~~~~~~~~~~~~~~~~~ The line block styles wrap the various nested levels of line blocks. There is one line block style for each indent level. rststyle-lineblock1 Line block style for line block with no indent. rststyle-lineblock2 Line block style for line block indented 1 level. rststyle-lineblock3 Line block style for line block indented 2 levels. rststyle-lineblock4 Line block style for line block indented 3 levels. rststyle-lineblock5 Line block style for line block indented 4 levels. rststyle-lineblock6 Line block style for line block indented 5 levels. Notes: - ``odtwriter`` does not check for a maximum level of indents within line blocks. Therefore, you can define additional line block styles for additional levels if you need them. Define these styles with the names ``rststyle-lineblock7``, ``rststyle-lineblock8``, ... - Since the line block style is used to create indentation, a line block that is inside a block quote will use ``rststyle-lineblock2`` as its first level of indentation. Footnote and citation styles ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ rststyle-footnote The style for footnotes. This style affects the footnote content, *not* the footnote reference in the body of the document. rststyle-citation The style for citations. This style affects the citation content, *not* the citation reference in the body of the document. You might need to adjust the indentation in this style depending on the length of the label used in your citations. Heading and title styles ~~~~~~~~~~~~~~~~~~~~~~~~~ rststyle-heading{1|2|3|4|5} The styles for headings (section titles and sub-titles). Five levels of sub-headings are provided: rststyle-heading1 through rststyle-heading5. rststyle-title The style for the document title. rststyle-subtitle The style for the document sub-title. Image and figure styles ~~~~~~~~~~~~~~~~~~~~~~~~~ rststyle-image The style applied to an image, either an image by itself or an image in a figure. rststyle-figureframe The style applied to a figure (actually to the frame that surrounds a figure). Defining and using a custom stylesheet --------------------------------------- You can create your own custom stylesheet. Here is how: 1. Make a copy of ``styles.odt``, which is in the distribution. 2. Open your copy of ``styles.odt`` in ``oowriter``. Modify styles in that document. Then, save it. 3. When you run ``rst2odt.py``, use the ``--stylesheet`` command line option to use your custom stylesheet. Run ``rst2odt.py --help`` to learn more about these options. Why custom stylesheets ~~~~~~~~~~~~~~~~~~~~~~~ Here are a few reasons and ideas: - The page size is stored in the style sheet. The default page size is ``Letter``. You can change the page size (for example, to ``A4``) in your custom stylesheet by opening it in ``oowriter``, then clicking on menu: ``Format/Page...``, then clicking on the ``Page`` tab. Defining and using custom style names ------------------------------------- [Credits: Stefan Merten designed and implemented the custom style names capability. Thank you, Stefan.] You can also instruct ``odtwriter`` to use style names of your own choice. Why custom style names ~~~~~~~~~~~~~~~~~~~~~~ Here are a few reasons and ideas: - Suppose that your organization has a standard set of styles in OOo ``oowriter`` and suppose that the use of these styles is required. You would like to generate ODF documents from reST text files, and you want the generated documents to contain these styles. - Suppose that your company or organization has a policy of using a certain MS Word template for some set of documents. You would like to generate ODF documents that use these custom style names, so that you can export these documents from ODF ``oowriter`` to MS Word documents that use these style names. - Suppose that your documents are written in a language other than English. You would like the style names visible in the "Styles and Formatting" window in OOo ``oowriter`` (menu item ``Format/Styles and Formatting``) to be understandable in the language of your users. - ``odtwriter`` maps single asterisks/stars (for example, \*stuff\*) to emphasis and double stars to strong. You'd like to reverse these. Or, you would like to generate headings level 3 and 4 where headings level 1 and 2 would normally be produced. How to use custom style names ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In order to define custom style names and to generate documents that contain them, do the following: 1. Create a configuration file containing a "Formats" section. The configuration file obeys the file format supported by the Python ConfigParser module: `ConfigParser -- Configuration file parser -- http://docs.python.org/lib/module-ConfigParser.html `_. 2. In the "Formats" section of the configuration file, create one option (a name-value pair) for each custom style name that you wish to define. The option name is the standard ``odtwriter`` style name (without "rststyle-"), and the value is your custom style name. Here is an example:: [Formats] textbody: mytextbody bulletitem: mybulletitem heading1: myheading1 o o o 3. Create a styles document that defines the styles generated by ``odtwriter``. You can create and edit the styles in OOo ``oowriter``. It may be helpful to begin by making a copy of the styles document that is part of the ``odtwriter`` distribution (``styles.odt``). 4. When you run ``odtwriter``, specify the ``--odf-config-file`` option. You might also want to specify your styles document using the ``--stylesheet`` option in order to include your custom style definitions. For example:: rst2odt.py --odf-config-file=mymappingfile.ini --stylesheet=mystyles.odt mydoc.txt mydoc.odt Classes ------- ``odtwriter`` uses the following Docutils class to provide additional control of the generation of ODF content: - Class ``wrap`` -- Use this to cause the wrapping of text around an image. The default is *not* to wrap text around images. Here is an example:: .. class:: wrap .. image:: images/flower01.png :alt: A bright yellow flower :height: 55 :width: 60 Roles ------- You can use a Docutils custom interpreted text role to attach a character style to an inline area of text. This capability also enables you to attach a new character style (with a new name) that you define yourself. Do this by defining your role in a stylesheet as a character style with "rststyle-" prefixed to your role name, then use the ``role`` directive and inline markup to apply your role. In order to use this capability, do the following: - Define the character style for your custom role in a stylesheet (a copy of ``styles.odt``) with the prefix "rststyle-". Remember: (1) If the name of your custom role is "pretty", then define a character style named "rststyle-pretty". (2) Define the style as a *character* style, and *not*, for example as a paragraph style. - Declare your role in the source reStructuredText document in a ``role`` directive. Example:: .. role:: pretty - Use inline markup to apply your role to text. Example:: We have :pretty:`very nice` apples. Here is another example:: .. role:: fancy Here is some :fancy:`pretty text` that looks fancy. For more on roles see: `Custom Interpreted Text Roles -- http://docutils.sourceforge.net/docs/ref/rst/directives.html#custom-interpreted-text-roles `_. **Note:** The ability to base a role on another existing role is *not* supported by ``odtwriter``. Hints and Suggestions and Features ================================== Table of contents ----------------- The ``..contents::`` directive causes ``odtwriter`` to generate either: 1. A static, outline style table of contents, if the ``--generate-list-toc`` command line option is specified, or 2. An ODF/``oowriter`` style table of contents containing dynamically updated page numbers and with the formatting control that ``oowriter`` gives you. This is the default, or use the command line option ``--generate-list-toc``. **Note:** ``odtwriter`` is not able to determine page numbers, so you will need to open the generated document in ``oowriter``, then right-click on the table of contents and select "Update" to insert correct page numbers. Syntax highlighting ------------------- ``odtwriter`` can add syntax highlighting to code in code blocks. In order to activate this, do all of the following: 1. Install `Pygments`_ and ... 2. Use the command line option ``--add-syntax-highlighting``. Example:: $ rst2odt.py --add-syntax-highlight test.txt test.odt The following styles are defined in styles.odt and are used for literal code blocks and syntax highlighting: - Paragraph styles: - rststyle-codeblock -- The style for the code block as a whole. - Character styles: - rststyle-codeblock-classname -- class names. - rststyle-codeblock-comment -- comments. - rststyle-codeblock-functionname -- function names. - rststyle-codeblock-keyword -- Python language keywords. - rststyle-codeblock-name -- other names, for example, variables. - rststyle-codeblock-number -- literal numbers, including integers, floats, hex numbers, and octal numbers. - rststyle-codeblock-operator -- Python operators. - rststyle-codeblock-string -- literal strings. Each of the above styles has a default appearance that is defined in ``styles.odt``. To change that definition and appearance, open ``styles.odt`` in ``oowriter`` and use menu item:: Format --> Styles and Formatting Then, click on the Paragraph Styles button or the Character Styles button at the top of the Styles and Formatting window. You may also need to select "All Styles" from the drop-down selection list at the bottom of the Styles and Formatting window. The container directive ----------------------- There is limited support for the ``container`` directive. The limitations and rules for the container directive are the following: - Only the first class in the list of classes (arguments) is used. - That class/style must be a paragraph style and not (for example) a character style. - The style/class given to the container directive will have a "rststyle-" prefix in the odt file. So, for example:: .. container:: style-1 style-2 style-3 a block of text - Only ``style-1`` is used; ``style-2`` and ``style-3`` are ignored. - ``rststyle-style-1`` must be defined. It should be an existing, predefined style, or you should define it in your stylesheet (``styles.odt`` or the argument to the ``--stylesheet`` command line option). - ``rststyle-style-1`` must be a paragraph style. To define a paragraph style, use the following menu item in ``oowriter``:: Format --> Styles and Formatting Then, click on the Paragraph Styles button. The following example attaches the ``rststyle-heading2`` style (a predefined style) to each paragraph/line in the container:: .. container:: heading2 Line 1 of container. Line 2 of container. More information on how to define a new style (for example, in your ``styles.odt``) can be found in section `Defining and using custom style names`_. The table directive ------------------- The ``table`` directive can be used to add a title to a table. Example:: .. table:: A little test table =========== ============= Name Value =========== ============= Dave Cute Mona Smart =========== ============= The above will insert the title "A little test table" at the top of the table. You can modify the appearance of the title by modifying the paragraph style ``rststyle-table-title``. Footnotes and citations ----------------------- Footnotes and citations are supported. There are additional styles ``rststyle-footnote`` and ``rststyle-citation`` for footnotes and citations. See `Footnote and citation styles`_. You may need to modify the citation style to fit the length of your citation references. Endnotes -- There are command line options that control whether ``odtwriter`` creates endnotes instead of footnotes. Endnotes appear at the end of the document instead of at the bottom of the page. See flags ``--endnotes-end-doc`` and ``--no-endnotes-end-doc`` in section `Command line options`_. Images and figures ------------------ If on the image or the figure directive you provide the scale option but do not provide the width and height options, then ``odtwriter`` will attempt to determine the size of the image using the `Python Imaging Library`_ (PIL). If ``odtwriter`` cannot find and import Python Imaging Library, it will raise an exception. If this ocurrs, you can fix it by doing one of the following: - Install the Python Imaging Library or - Remove the ``scale`` option or - Add both the ``width`` and the ``height`` options. So, the rule is: if on any image or figure, you specify scale but not both width and height, you must install the `Python Imaging Library`_ library. For more information about PIL, see: `Python Imaging Library`_. The raw directive ----------------- The ``raw`` directive is supported. Use output format type "odt". You will need to be careful about the formatting of the raw content. In particular, introduced whitespace might be a problem. In order to produce content for the raw directive for use by ``odtwriter``, you might want to extract the file ``content.xml`` from a ``.odt`` file (using some Zip tool), and then clip, paste, and modify a selected bit of it. Here is an example:: .. raw:: odt Determining which namespace a name is in is static. It can be determined by a lexical scan of the code. If a variable is assigned a value anywhere in a scope (specifically within a function or method body), then that variable is local to that scope. If Python does not find a variable in the local scope, then it looks next in the global scope (also sometimes called the module scope) and then in the built-ins scope. But, the global statement can be used to force Python to find and use a global variable (a variable defined at top level in a module) rather than create a local one. The meta directive ------------------ ``odtwriter`` supports the ``meta`` directive. Two fields are recognized: "keywords" and "description". Here is an example:: .. meta:: :keywords: reStructuredText, docutils, formatting :description lang=en: A reST document, contains formatted text in a formatted style. To see the results of the ``meta`` directive in ``oowriter``, select menu item "File/Properties...", then click on the "Description" tab. Footnote references inside footnotes ------------------------------------ Not supported. Get a grip. Be serious. Try a dose of reality. ``odtwriter`` ignores them. They cause ``oowriter`` to croak. Page size --------- The default page size, in documents generated by ``odtwriter`` is ``Letter``. You can change this (for example to ``A4``) by using a custom stylesheet. See `Defining and using a custom stylesheet`_ for instructions on how to do this. On machines which support ``paperconf``, ``odtwriter`` can insert the default page size for your locale. In order for this to work, the following conditions must be met: 1. The program ``paperconf`` must be available on your system. ``odtwriter`` uses ``paperconf -s`` to obtain the paper size. See ``man paperconf`` for more information. 2. The default page height and width must be removed from the ``styles.odt`` used to generate the document. A Python script ``rst2odt_prepstyles.py`` is distributed with ``odtwriter`` and is installed in the ``bin`` directory. You can remove the page height and width with something like the following:: $ rst2odt_prepstyles.py styles.odt .. warning:: If you edit your stylesheet in ``oowriter`` and then save it, ``oowriter`` automatically inserts a page height and width in the styles for that (stylesheet) document. If that is not the page size that you want and you want ``odtwriter`` to insert a default page size using ``paperconf``, then you will need to strip the page size from your stylesheet each time you edit that stylesheet with ``oowriter``. Custom header/footers: inserting page numbers, date, time, etc ---------------------------------------------------------------- You can specify custom headers and footers for your document from the command line. These headers and footers can be used to insert fields such as the page number, page count, date, time, etc. See below for a complete list. To insert a custom header or footer, use the "--custom-odt-header" or "--custom-odt-footer" command line options. For example, the following inserts a footer containing the page number and page count:: $ rst2odt.py --custom-odt-footer="Page %p% of %P%" f1.txt f1.odt Field specifiers ~~~~~~~~~~~~~~~~~~ You can use the following field specifiers to insert ``oowriter`` fields in your custom headers and footers: %p% The current page number. %P% The number of pages in the document. %d1% The current date in format 12/31/99. %d2% The current date in format 12/31/1999. %d3% The current date in format Dec 31, 1999. %d4% The current date in format December 31, 1999. %d5% The current date in format 1999-12-31. %t1% The current time in format 14:22. %t2% The current time in format 14:22:33. %t3% The current time in format 02:22 PM. %t4% The current time in format 02:22:33 PM. %a% The author of the document (actually the initial creator). %t% The document title. %s% The document subject. **Note:** The use of the above field specifiers in the body of your reStructuredText document is **not** supported, because these specifiers are not standard across Docutils writers. Credits ======= Stefan Merten designed and implemented the custom style names capability. Thank you, Stefan. Michael Schutte supports the Debian GNU/Linux distribution of ``odtwriter``. Thank you, Michael, for providing and supporting the Debian package. Michael Schutte implemented the fix that enables ``odtwriter`` to pick up the default paper size on platforms where the program ``paperconf`` is available. Thank you. .. _`Pygments`: http://pygments.pocoo.org/ .. _`Docutils`: http://docutils.sourceforge.net/ .. _`Python Imaging Library`: http://www.pythonware.com/products/pil/ .. _`Open Document at Wikipedia`: http://en.wikipedia.org/wiki/OpenDocument .. _`OASIS Open Document Format for Office Applications (OpenDocument) TC`: http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=office docutils-0.12/docs/user/config.txt0000664000175000017500000014474112115207525021153 0ustar engelbertengelbert00000000000000======================== Docutils Configuration ======================== :Author: David Goodger :Contact: docutils-develop@lists.sourceforge.net :Revision: $Revision: 7623 $ :Date: $Date: 2013-03-04 22:17:09 +0100 (Mon, 04. Mär 2013) $ :Copyright: This document has been placed in the public domain. .. sidebar:: Docutils Security for Web Applications For details about securing web applications, please see `Deploying Docutils Securely <../howto/security.html>`_. .. contents:: ------------------- Configuration Files ------------------- Configuration files are used for persistent customization; they can be set once and take effect every time you use a front-end tool. Configuration file settings override the built-in defaults, and command-line options override all. By default, Docutils checks the following places for configuration files, in the following order: 1. ``/etc/docutils.conf``: This is a system-wide configuration file, applicable to all Docutils processing on the system. 2. ``./docutils.conf``: This is a project-specific configuration file, located in the current directory. The Docutils front end has to be executed from the directory containing this configuration file for it to take effect (note that this may have nothing to do with the location of the source files). Settings in the project-specific configuration file will override corresponding settings in the system-wide file. 3. ``~/.docutils``: This is a user-specific configuration file, located in the user's home directory. Settings in this file will override corresponding settings in both the system-wide and project-specific configuration files. If more than one configuration file is found, all will be read but later entries will override earlier ones. For example, a "stylesheet" entry in a user-specific configuration file will override a "stylesheet" entry in the system-wide file. The default implicit config file paths can be overridden by the ``DOCUTILSCONFIG`` environment variable. ``DOCUTILSCONFIG`` should contain a colon-separated (semicolon-separated on Windows) sequence of config file paths to search for; leave it empty to disable implicit config files altogether. Tilde-expansion is performed on paths. Paths are interpreted relative to the current working directory. Empty path items are ignored. In addition, a configuration file may be explicitly specified with the "--config" command-line option. This configuration file is read after the three implicit ones listed above (or the ones defined by the ``DOCUTILSCONFIG`` environment variable), and its entries will have priority. ------------------------- Configuration File Syntax ------------------------- Configuration files are UTF-8-encoded text files. The ConfigParser.py_ module from Python_'s standard library is used to read them. From its documentation: The configuration file consists of sections, lead by a "[section]" header and followed by "name: value" entries, with continuations in the style of `RFC 822`_; "name=value" is also accepted. Note that leading whitespace is removed from values. ... Lines beginning with "#" or ";" are ignored and may be used to provide comments. .. Note:: No format string interpolation is done. Configuration file entry names correspond to internal runtime settings. Underscores ("_") and hyphens ("-") can be used interchangably in entry names; hyphens are automatically converted to underscores. For on/off switch settings (_`booleans`), the following values are recognized: :On: "true", "yes", "on", "1" :Off: "false", "no", "off", "0", "" (no value) .. _list: List values can be comma- or colon-delimited. strip_classes_, strip_elements_with_classes_, stylesheet, and stylesheet_path use the comma as delimiter, whitespace around list values is stripped. :: strip-classes: ham,eggs, strip-elements-with-classes: sugar, salt, flour stylesheet: html4css1.css, math.css, style with spaces.css stylesheet-path: ../styles/my.css, ../styles/funny.css expose_internals_, ignore_ and prune_ use the colon as delimiter and do not strip whitespace:: expose_internals: b:c:d Example ======= This is the contents of the ``tools/docutils.conf`` configuration file supplied with Docutils:: # These entries affect all processing: [general] source-link: yes datestamp: %Y-%m-%d %H:%M UTC generator: on # These entries affect HTML output: [html4css1 writer] # Required for docutils-update, the website build system: stylesheet-path: ../docutils/writers/html4css1/html4css1.css embed-stylesheet: no field-name-limit: 20 Individual configuration sections and settings are described in the following section. ------------------------------------- Configuration File Sections & Entries ------------------------------------- Below are the Docutils runtime settings, listed by config file section. Any setting may be specified in any section, but only settings from active sections will be used. Sections correspond to Docutils components (module name or alias; section names are always in lowercase letters). Each `Docutils application`_ uses a specific set of components; corresponding configuration file sections are applied when the application is used. Configuration sections are applied in general-to-specific order, as follows: 1. `[general]`_ 2. `[parsers]`_, parser dependencies, and the section specific to the Parser used ("[... parser]"). Currently, only `[restructuredtext parser]`_ is applicable. 3. `[readers]`_, reader dependencies, and the section specific to the Reader used ("[... reader]"). For example, `[pep reader]`_ depends on `[standalone reader]`_. 4. `[writers]`_, writer dependencies, and the section specific to the Writer used ("[... writer]"). For example, `[pep_html writer]`_ depends on `[html4css1 writer]`_. 5. `[applications]`_, application dependencies, and the section specific to the Application (front-end tool) in use ("[... application]"). Since any setting may be specified in any section, this ordering allows component- or application-specific overrides of earlier settings. For example, there may be Reader-specific overrides of general settings; Writer-specific overrides of Parser settings; Application-specific overrides of Writer settings; and so on. If multiple configuration files are applicable, the process is completed (all sections are applied in the order given) for each one before going on to the next. For example, a "[pep_html writer] stylesheet" setting in an earlier configuration file would be overridden by an "[html4css1 writer] stylesheet" setting in a later file. Some knowledge of Python_ is assumed for some attributes. .. _ConfigParser.py: http://www.python.org/doc/current/lib/module-ConfigParser.html .. _Python: http://www.python.org/ .. _RFC 822: http://www.rfc-editor.org/rfc/rfc822.txt .. _Docutils application: tools.html [general] ========= Settings in the "[general]" section are always applied. auto_id_prefix -------------- Prefix prepended to all auto-generated IDs generated within the document, after id_prefix_. Default: "id". Options: ``--auto-id-prefix`` (hidden, intended mainly for programmatic use). datestamp --------- Include a time/datestamp in the document footer. Contains a format string for Python's ``time.strftime``. See the `time module documentation`__. Default: None. Options: ``--date, -d, --time, -t, --no-datestamp``. Configuration file entry examples:: # Equivalent to --date command-line option, results in # ISO 8601 extended format datestamp, e.g. "2001-12-21": datestamp: %Y-%m-%d # Equivalent to --time command-line option, results in # date/timestamp like "2001-12-21 18:43 UTC": datestamp: %Y-%m-%d %H:%M UTC # Disables datestamp; equivalent to --no-datestamp: datestamp: __ http://www.python.org/doc/current/lib/module-time.html debug ----- Report debug-level system messages. Default: don't (None). Options: ``--debug, --no-debug``. dump_internals -------------- At the end of processing, write all internal attributes of the document (``document.__dict__``) to stderr. Default: don't (None). Options: ``--dump-internals`` (hidden, for development use only). dump_pseudo_xml --------------- At the end of processing, write the pseudo-XML representation of the document to stderr. Default: don't (None). Options: ``--dump-pseudo-xml`` (hidden, for development use only). dump_settings ------------- At the end of processing, write all Docutils settings to stderr. Default: don't (None). Options: ``--dump-settings`` (hidden, for development use only). dump_transforms --------------- At the end of processing, write a list of all transforms applied to the document to stderr. Default: don't (None). Options: ``--dump-transforms`` (hidden, for development use only). error_encoding -------------- The text encoding for error output. Default: "ascii". Options: ``--error-encoding, -e``. error_encoding_error_handler ---------------------------- The error handler for unencodable characters in error output. See output_encoding_error_handler_ for acceptable values. Default: "backslashreplace" Options: ``--error-encoding-error-handler, --error-encoding, -e``. exit_status_level ----------------- A system message level threshold; non-halting system messages at or above this level will produce a non-zero exit status at normal exit. Exit status is the maximum system message level plus 10 (11 for INFO, etc.). Default: disabled (5). Options: ``--exit-status``. expose_internals ---------------- List_ of internal attribues to expose as external attributes (with "internal:" namespace prefix). To specify multiple attributes in configuration files, use colons to separate names; on the command line, the option may be used more than once. Default: don't (None). Options: ``--expose-internal-attribute`` (hidden, for development use only). footnote_backlinks ------------------ Enable or disable backlinks from footnotes and citations to their references. Default: enabled (1). Options: ``--footnote-backlinks, --no-footnote-backlinks``. generator --------- Include a "Generated by Docutils" credit and link in the document footer. Default: off (None). Options: ``--generator, -g, --no-generator``. halt_level ---------- The threshold at or above which system messages are converted to exceptions, halting execution immediately. If `traceback`_ is set, the exception will propagate; otherwise, Docutils will exit. Default: severe (4). Options: ``--halt, --strict``. id_prefix --------- Prefix prepended to all IDs generated within the document. See also auto_id_prefix_. Default: "" (empty). Options: ``--id-prefix`` (hidden, intended mainly for programmatic use). input_encoding -------------- The text encoding for input. Default: auto-detect (None). Options: ``--input-encoding, -i``. input_encoding_error_handler ---------------------------- The error handler for undecodable characters in the input. Acceptable values include: strict Raise an exception in case of an encoding error. replace Replace malformed data with the official Unicode replacement character, U+FFFD. ignore Ignore malformed data and continue without further notice. Acceptable values are the same as for the "error" parameter of Python's ``unicode`` function; other values may be defined in applications or in future versions of Python. Default: "strict". Options: ``--input-encoding-error-handler, --input-encoding, -i``. language_code ------------- Case-insensitive `language tag`_ as defined in `BCP 47`_. Sets the document language, also used for localized directive and role names as well as Docutils-generated text. A typical language identifier consists of a 2-letter language code from `ISO 639`_ (3-letter codes can be used if no 2-letter code exists). The language identifier can have an optional subtag, typically for variations based on country (from `ISO 3166`_ 2-letter country codes). Avoid subtags except where they add useful distinguishing information. Examples of language tags include "fr", "en-GB", "pt-br" (the same as "pt-BR"), and "de-1901" (German with pre-1996 spelling). The language of document parts can be specified with a "language-" `class attribute`_, e.g. ``.. class:: language-el-polyton`` for a quote in polytonic Greek. Default: English ("en"). Options: ``--language, -l``. .. _class attribute: ../ref/doctree.html#classes output_encoding --------------- The text encoding for output. Default: "UTF-8". Options: ``--output-encoding, -o``. output_encoding_error_handler ----------------------------- The error handler for unencodable characters in the output. Acceptable values include: strict Raise an exception in case of an encoding error. replace Replace malformed data with a suitable replacement marker, such as "?". ignore Ignore malformed data and continue without further notice. xmlcharrefreplace Replace with the appropriate XML character reference, such as "``†``". backslashreplace Replace with backslashed escape sequences, such as "``\u2020``". Acceptable values are the same as for the "error" parameter of Python's ``encode`` string method; other values may be defined in applications or in future versions of Python. Default: "strict". Options: ``--output-encoding-error-handler, --output-encoding, -o``. record_dependencies ------------------- Path to a file where Docutils will write a list of files that were required to generate the output, e.g. included files or embedded stylesheets [#dependencies]_. [#pwd]_ The format is one path per line with forward slashes as separator, the encoding is ``utf8``. Set to ``-`` in order to write dependencies to stdout. This option is particularly useful in conjunction with programs like ``make`` using ``Makefile`` rules like:: ham.html: ham.txt $(shell cat hamdeps.txt) rst2html.py --record-dependencies=hamdeps.txt ham.txt ham.html If the filesystem encoding differs from utf8, replace the ``cat`` command with a call to a converter, e.g.:: $(shell iconv -f utf8 -t latin1 hamdeps.txt) Default: None. Option: ``--record-dependencies``. report_level ------------ Report system messages at or higher than : 1 info 2 warning 3 error 4 severe 5 none Default: warning (2). Options: ``--report, -r, --verbose, -v, --quiet, -q``. sectnum_xform ------------- Enable or disable automatic section numbering by Docutils (docutils.transforms.parts.SectNum) associated with the `sectnum directive`_. If disabled, section numbers might be added to the output by the renderer (e.g. LaTeX or via a CSS style definition). Default: enabled (1). Options: ``--section-numbering``, ``--no-section-numbering``. .. _sectnum directive: ../ref/rst/directives.html#sectnum source_link ----------- Include a "View document source" link in the document footer. URL will be relative to the destination. Default: don't (None). Options: ``--source-link, -s, --no-source-link``. source_url ---------- An explicit URL for a "View document source" link, used verbatim. Default: compute if source_link (None). Options: ``--source-url, --no-source-link``. strict_visitor -------------- When processing a document tree with the Visitor pattern, raise an error if a writer does not support a node type listed as optional. For transitional development use. Default: disabled (None). Option: ``--strict-visitor`` (hidden, for development use only). strip_classes ------------- Comma-separated list_ of "classes" attribute values to remove from all elements in the document tree. The command line option may be used more than once. .. WARNING:: Potentially dangerous; use with caution. Default: disabled (None). Option: ``--strip-class``. strip_comments -------------- Enable the removal of comment elements from the document tree. Default: disabled (None). Options: ``--strip-comments``, ``--leave-comments``. strip_elements_with_classes --------------------------- Comma-separated list_ of "classes" attribute values; matching elements are removed from the document tree. The command line option may be used more than once. .. WARNING:: Potentially dangerous; use with caution. Default: disabled (None). Option: ``--strip-element-with-class``. title ----- The document title as metadata, which does not become part of the document body. It overrides a document-supplied title. For example, in HTML output the metadata document title appears in the title bar of the browser window. Default: none. Option: ``--title``. toc_backlinks ------------- Enable backlinks from section titles to table of contents entries ("entry"), to the top of the TOC ("top"), or disable ("none"). Default: "entry". Options: ``--toc-entry-backlinks, --toc-top-backlinks, --no-toc-backlinks``. traceback --------- Enable Python tracebacks when halt-level system messages and other exceptions occur. Useful for debugging, and essential for issue reports. Exceptions are allowed to propagate, instead of being caught and reported (in a user-friendly way) by Docutils. Default: disabled (None) unless Docutils is run programmatically using the `Publisher Interface`_. Options: ``--traceback, --no-traceback``. .. _Publisher Interface: ../api/publisher.html warning_stream -------------- Path to a file for the output of system messages (warnings) [#pwd]_. Default: stderr (None). Options: ``--warnings``. [parsers] ========= Docutils currently supports only one parser, for reStructuredText. [restructuredtext parser] ------------------------- file_insertion_enabled ~~~~~~~~~~~~~~~~~~~~~~ Enable or disable directives that insert the contents of external files, such as the "include_" & "raw_". A "warning" system message (including the directive text) is inserted instead. (See also raw_enabled_ for another security-relevant setting.) Default: enabled (1). Options: ``--file-insertion-enabled, --no-file-insertion``. .. _include: ../ref/rst/directives.html#include .. _raw: ../ref/rst/directives.html#raw pep_references ~~~~~~~~~~~~~~ Recognize and link to standalone PEP references (like "PEP 258"). Default: disabled (None); enabled (1) in PEP Reader. Options: ``--pep-references``. pep_base_url ~~~~~~~~~~~~ Base URL for PEP references. Default: "http://www.python.org/peps/". Option: ``--pep-base-url``. pep_file_url_template ~~~~~~~~~~~~~~~~~~~~~ Template for PEP file part of URL, interpolated with the PEP number and appended to pep_base_url_. Default: "pep-%04d". Option: ``--pep-file-url``. raw_enabled ~~~~~~~~~~~ Enable or disable the "raw_" directive. A "warning" system message (including the directive text) is inserted instead. (See also file_insertion_enabled_ for another security-relevant setting.) Default: enabled (1). Options: ``--raw-enabled, --no-raw``. rfc_references ~~~~~~~~~~~~~~ Recognize and link to standalone RFC references (like "RFC 822"). Default: disabled (None); enabled (1) in PEP Reader. Options: ``--rfc-references``. rfc_base_url ~~~~~~~~~~~~ Base URL for RFC references. Default: "http://www.faqs.org/rfcs/". Option: ``--rfc-base-url``. smart_quotes ~~~~~~~~~~~~ Change straight quotation marks to typographic form. `Quote characters`_ are selected according to the language of the current block element (see language_code_). Also changes consequtive runs of hyphen-minus and full stops (``---``, ``--``, ``...``) to em-dash, en-dash and ellipsis Unicode characters respectively. Supported values: booleans_ (yes/no) Use smart quotes? alt (or "alternative") Use alternative quote set (if defined for the language). Default: "no". Option: ``--smart-quotes``. New in Docutils 0.10. .. _quote characters: http://en.wikipedia.org/wiki/Non-English_usage_of_quotation_marks syntax_highlight ~~~~~~~~~~~~~~~~ Token type names used by Pygments_ when parsing contents of the code_ directive and role. Supported values: long Use hierarchy of long token type names. short Use short token type names. (For use with `Pygments-generated stylesheets`_.) none No code parsing. Use this to avoid the "Pygments not found" warning when Pygments is not installed. Default: "long". Option: ``--syntax-highlight``. New in Docutils 0.9. .. _Pygments: http://pygments.org/ .. _code: ../ref/rst/directives.html#code .. _Pygments-generated stylesheets: http://pygments.org/docs/cmdline/#generating-styles tab_width ~~~~~~~~~ Number of spaces for hard tab expansion. Default: 8. Options: ``--tab-width``. trim_footnote_reference_space ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Remove spaces before footnote references. Default: don't (None); may be overriden by a writer-specific footnote_references__ default though. Options: ``--trim-footnote-reference-space, --leave-footnote-reference-space``. __ `footnote_references [latex2e writer]`_ [readers] ========= [standalone reader] ------------------- docinfo_xform ~~~~~~~~~~~~~ Enable or disable the bibliographic field list transform (docutils.transforms.frontmatter.DocInfo). Default: enabled (1). Options: ``--no-doc-info``. doctitle_xform ~~~~~~~~~~~~~~ Enable or disable the promotion of a lone top-level section title to document title (and subsequent section title to document subtitle promotion; docutils.transforms.frontmatter.DocTitle). Default: enabled (1). Options: ``--no-doc-title``. sectsubtitle_xform ~~~~~~~~~~~~~~~~~~ Enable or disable the promotion of the title of a lone subsection to a subtitle (docutils.transforms.frontmatter.SectSubTitle). Default: disabled (0). Options: ``--section-subtitles, --no-section-subtitles``. [pep reader] ------------ The `pep_references`_ and `rfc_references`_ settings (`[restructuredtext parser]`_) are set on by default. [python reader] --------------- Not implemented. [writers] ========= [docutils_xml writer] --------------------- .. Caution:: * In Python versions older than 2.7.3 and 3.2.3, the newlines_ and indents_ options may adversely affect whitespace; use them only for reading convenience (see http://bugs.python.org/issue4147). * The XML declaration carries text encoding information, without which standard tools may be unable to read the generated XML. doctype_declaration ~~~~~~~~~~~~~~~~~~~ Generate XML with a DOCTYPE declaration. Default: do (1). Options: ``--no-doctype``. indents ~~~~~~~ Generate XML with indents and newlines. Default: don't (None). Options: ``--indents``. newlines ~~~~~~~~ Generate XML with newlines before and after tags. Default: don't (None). Options: ``--newlines``. .. _xml_declaration [docutils_xml writer]: xml_declaration ~~~~~~~~~~~~~~~ Generate XML with an XML declaration. Also defined for the `HTML Writer`__. Default: do (1). Options: ``--no-xml-declaration``. __ `xml_declaration [html4css1 writer]`_ [html4css1 writer] ------------------ .. _attribution [html4css1 writer]: attribution ~~~~~~~~~~~ Format for block quote attributions: one of "dash" (em-dash prefix), "parentheses"/"parens", or "none". Also defined for the `LaTeX Writer `__. Default: "dash". Options: ``--attribution``. cloak_email_addresses ~~~~~~~~~~~~~~~~~~~~~ Scramble email addresses to confuse harvesters. In the reference URI, the "@" will be replaced by %-escapes (as of RFC 1738). In the visible text (link text) of an email reference, the "@" and all periods (".") will be surrounded by ```` tags. Furthermore, HTML entities are used to encode these characters in order to further complicate decoding the email address. For example, "abc@example.org" will be output as:: abc@example.org .. Note:: While cloaking email addresses will have little to no impact on the rendering and usability of email links in most browsers, some browsers (e.g. the ``links`` browser) may decode cloaked email addresses incorrectly. Default: don't cloak (None). Option: ``--cloak-email-addresses``. compact_lists ~~~~~~~~~~~~~ Remove extra vertical whitespace between items of bullet lists and enumerated lists, when list items are all "simple" (i.e., items each contain one paragraph and/or one "simple" sublist only). The behaviour can be specified directly via "class" attributes (values "compact" and "open") in the document. Default: enabled (1). Options: ``--compact-lists, --no-compact-lists``. compact_field_lists ~~~~~~~~~~~~~~~~~~~ Remove extra vertical whitespace between items of field lists that are "simple" (i.e., all field bodies each contain at most one paragraph). The behaviour can be specified directly via "class" attributes (values "compact" and "open") in the document. Default: enabled (1). Options: ``--compact-field-lists, --no-compact-field-lists``. .. _embed_stylesheet [html4css1 writer]: embed_stylesheet ~~~~~~~~~~~~~~~~ Embed the stylesheet in the output HTML file. The stylesheet file must specified by the stylesheet_path__ setting and must be accessible during processing. Also defined for the `LaTeX Writer `__. Default: enabled. Options: ``--embed-stylesheet, --link-stylesheet``. __ `stylesheet_path [html4css1 writer]`_ field_name_limit ~~~~~~~~~~~~~~~~ The maximum width (in characters) for one-column field names. Longer field names will span an entire row of the table used to render the field list. 0 indicates "no limit". See also option_limit_. Default: 14 (i.e. 14 characters). Option: ``--field-name-limit``. .. _footnote_references [html4css1 writer]: footnote_references ~~~~~~~~~~~~~~~~~~~ Format for footnote references, one of "superscript" or "brackets". Also defined for the `LaTeX Writer `__. Overrides [#override]_ trim_footnote_reference_space_, if applicable. [#footnote_space]_ Default: "brackets". Option: ``--footnote-references``. initial_header_level ~~~~~~~~~~~~~~~~~~~~ The initial level for header elements. This does not affect the document title & subtitle; see doctitle_xform_. Default: 1 (for "

"). Option: ``--initial-header-level``. math_output ~~~~~~~~~~~ The format of mathematical content (`math directive`_ and role) in the output document. Supported values are (case insensitive): :HTML: Format math in standard HTML enhanced by CSS rules. Requires the ``math.css`` stylesheet (in the system `stylesheet directory `_ A `stylesheet_path `_ can be appended after whitespace, the specified stylesheet(s) will only be referenced or embedded, if required (i.e. if there is mathematical content in the document). :MathJax: Format math for display with MathJax_, a JavaScript-based math rendering engine that uses HTML/CSS, JavaScript, and unicode fonts for high-quality typesetting that is scalable and prints at full resolution. Pro: Works 'out of the box' across multiple browsers and platforms. Supports a large subset of LaTeX math commands and constructs (see http://www.mathjax.org/docs/1.1/tex.html). Con: Requires an Internet connection (or a local MathJax installation and configuration). Downloads JavaScript code from a third-party site. A custom URI can be appended after whitespace, for example a local installation :: math-output: MathJax file:/usr/share/javascript/mathjax/MathJax.js or a URI to `access the MathJax CDN using a https secure connection`__. __ http://www.mathjax.org/resources/faqs/#problem-https :MathML: Embed math content as presentational MathML_. Pro: The W3C recommendation for math on the web. Self-contained documents (no JavaScript, no external downloads). Con: Docutil's latex2mathml converter supports only a small subset of LaTeX syntax. With the "html4css1" writer, the resulting HTML document does not validate, as there is no DTD for MathML + XHTML Transitional. However, MathML-enabled browsers will render it fine. :LaTeX: Include literal LaTeX code. The failsave fallback. Default: "HTML math.css". Option: ``--math-output``. New in Docutils 0.8. .. _math directive: ../ref/rst/directives.html#math .. _MathJax: http://www.mathjax.org/ .. _MathPlayer: http://www.dessci.com/en/products/mathplayer/ .. _MathML: http://www.w3.org/TR/MathML/ option_limit ~~~~~~~~~~~~ The maximum width (in characters) for options in option lists. Longer options will span an entire row of the table used to render the option list. 0 indicates "no limit". See also field_name_limit_. Default: 14 (i.e. 14 characters). Option: ``--option-limit``. .. _stylesheet [html4css1 writer]: stylesheet ~~~~~~~~~~ A comma-separated list of CSS stylesheet URLs, used verbatim. Also defined for the `LaTeX Writer `__. Overrides also stylesheet-path__. [#override]_ Default: None. Options: ``--stylesheet``. __ `stylesheet_path [html4css1 writer]`_ .. _stylesheet_dirs [html4css1 writer]: stylesheet_dirs ~~~~~~~~~~~~~~~ A comma-separated list of directories where stylesheets can be found. Used by the stylesheet_path__ setting when expanding relative path arguments. Note: This setting defines a "search path" (similar to the PATH variable for executables). However, the term "path" is already used in the stylesheet_path__ setting with the meaning of a file location. __ __ `stylesheet_path [html4css1 writer]`_ Default: the working directory of the process at launch and the directory with default stylesheet files (writer and installation specific). Use the ``--help`` option to get the exact value. Option: ``--stylesheet-directories``. .. _stylesheet_path [html4css1 writer]: stylesheet_path ~~~~~~~~~~~~~~~ A comma-separated list of paths to CSS stylesheets. Relative paths are expanded if a matching file is found in the stylesheet_dirs__. If embed_stylesheet__ is False, paths are rewritten relative to the output HTML file. Also defined for the `LaTeX Writer`__. Also overrides "stylesheet". [#override]_ Pass an empty string (to either "stylesheet" or "stylesheet_path") to deactivate stylesheet inclusion. Default: "html4css1.css". Options: ``--stylesheet-path``. __ `embed_stylesheet [html4css1 writer]`_ __ `stylesheet_path [latex2e writer]`_ __ `stylesheet_dirs [html4css1 writer]`_ .. _table_style [html4css1 writer]: table_style ~~~~~~~~~~~ Class value(s) added to tables to allow styling with CSS. The default sylesheet defines: borderless No borders around the table. booktabs Lines above and below the table and a thin line after the head. Default: "". Option: ``--table-style``. .. _template [html4css1 writer]: template ~~~~~~~~ Path to template file, which must be encoded in UTF-8 [#pwd]_. Also defined for the `LaTeX Writer`__. Default: "template.txt" in the docutils/writers/html4css1/ directory (installed automatically; for the exact machine-specific path, use the ``--help`` option). Options: ``--template``. __ `template [latex2e writer]`_ .. _xml_declaration [html4css1 writer]: xml_declaration ~~~~~~~~~~~~~~~ Generate XML with an XML declaration. Also defined for the `Docutils XML Writer`__. .. Caution:: The XML declaration carries text encoding information, without which standard tools may be unable to read the generated XML. Default: do (1). Options: ``--no-xml-declaration``. __ `xml_declaration [docutils_xml writer]`_ [pep_html writer] ~~~~~~~~~~~~~~~~~ The PEP/HTML Writer derives from the standard HTML Writer, and shares all settings defined in the `[html4css1 writer]`_ section. The "[html4css1 writer]" section of configuration files is processed before the "[pep_html writer]" section. The PEP/HTML Writer's default for the following settings differ from those of the standard HTML Writer: `stylesheet_path `_: Default: "pep.css" `template