Slide 1

Slide 1 text

Eric Holscher Django Under The Hood November 6, 2015 Understanding Documentation Systems

Slide 2

Slide 2 text

Who am I • Co-Founder of Read the Docs • Co-Founder of Write the Docs

Slide 3

Slide 3 text

Today • Learn about Docutils/RST internals • Learn how Sphinx builds on top & extends RST • Understand how Django uses these tools, and how you can too

Slide 4

Slide 4 text

Documentation Systems

Slide 5

Slide 5 text

Sphinx • Extends RST with additions for documenting so ware • Has powerful semantic constructs

Slide 6

Slide 6 text

Semantic Meaning • The power of HTML, and RST • What something is, not what it looks like • Once you know what it is, you can display it properly • Separation of Concerns

Slide 7

Slide 7 text

# HTML (Bad) issue 72 # HTML (Good) issue 72 # CSS .issue { text-format: bold; } Classic HTML Example

Slide 8

Slide 8 text

# Bad Warning: Don’t do this! # Good Don’t do this! # Best .. warning:: Don’t do this Classic RST Example

Slide 9

Slide 9 text

# Markdown Check out [PEP 8](https:// www.python.org/dev/peps/pep-0008/) # RST Check out :pep:`8` Markdown vs. RST

Slide 10

Slide 10 text

Semantic Markup shows the intent of your words

Slide 11

Slide 11 text

+----------------------------------------------------------+ | | | Read the Docs | | +----------------------------------------------+ | | | | | | | Sphinx | | | | +-----------------------------------+ | | | | | | | | | | | Docutils | | | | | | +--------------------+ | | | | | | | | | | | | | | | reStructuredText | | | | | | | | | | | | | | | +--------------------+ | | | | | | | | | | | | | | | | | | | | | | | +-----------------------------------+ | | | | | | | | | | | | | | | +----------------------------------------------+ | | | | | +----------------------------------------------------------+ Tech Overview

Slide 12

Slide 12 text

Docutils

Slide 13

Slide 13 text

Parts • Reader • Parser • Transformer • Writer

Slide 14

Slide 14 text

How it fits together

Slide 15

Slide 15 text

Reader • Get input and read it into memory • Quite simple, generally don’t need to do much

Slide 16

Slide 16 text

Title ===== Paragraph. Words that have **bold in them**. Reader Example

Slide 17

Slide 17 text

[u'Title', u'=====', u'', u'Paragraph.', u'', u'Words that have **bold in them**.'] Reader Example

Slide 18

Slide 18 text

Reader’s are useful for adding non-filesystem types of input (StringIO, Network)

Slide 19

Slide 19 text

Parser • Takes the input and actually turns it into a Doctree • RST is the only parser implemented in Docutils • Handles directives, inline markup, etc. • Implemented with a lined-based recursive state machine

Slide 20

Slide 20 text

Doctree • AST for Docutils • Source of Truth • Tree structure with a document at the root node • Made up of a series of Nodes

Slide 21

Slide 21 text

[u'Title', u'=====', u'', u'Paragraph.', u'', u'Words that have **bold in them**.'] Parser Example

Slide 22

Slide 22 text

Title Paragraph. Words that have bold in them Parser Example

Slide 23

Slide 23 text

Nodes • Structural Elements •document, section, sidebar • Body Elements • paragraph, image, note • Inline Elements •emphasis, strong, subscript

Slide 24

Slide 24 text

Nodes • Most common types of nodes are Text Nodes •nodes.paragraph(rawsource, nodes_or_text)

Slide 25

Slide 25 text

RST Directives • Allow block level extension of RST •.. note:: Foo = [ Node]

Slide 26

Slide 26 text

RST Interpreted Text Roles • Allows paragraph level extension of RST •:pep:`8` = [ Node]

Slide 27

Slide 27 text

RST Parser • Really neat language • Some directives are tied to RST because of internal, recursive parsing

Slide 28

Slide 28 text

.. note:: Wootles *blog* Wootles blog RST Parser

Slide 29

Slide 29 text

RST Parser • Recursively parses RST inside nodes • Python objects not portable • Need to think about how to port this to other parsers in the future

Slide 30

Slide 30 text

RST lets you create arbitrary markup that matches the semantics of your problem space

Slide 31

Slide 31 text

Parsers are used for implementing new RST features or adding new markup languages

Slide 32

Slide 32 text

Transformer • Take the doctree and modify it in place • Allows for “full knowledge” of the content • Table of Contents • Generally implemented by traversing nodes of a certain type

Slide 33

Slide 33 text

Title Paragraph. Words that have bold in them Transform Example

Slide 34

Slide 34 text

Title Words that have bold in them Paragraph. Transform Example

Slide 35

Slide 35 text

Transformers are used for changing the document in a way that requires full knowledge

Slide 36

Slide 36 text

Writer • Takes the Doctree and writes it to actual files • HTML, XML, PDF, etc. • Translator does most of the work • Implemented with the Visitor pattern

Slide 37

Slide 37 text

Visitor • Allows you to have arbitrary types of node’s and build `visit_` methods a er the fact • Generally a Directive creates an arbitrary Node type, which is converted by the Translator

Slide 38

Slide 38 text

class MyHTMLVisitor(nodes.GenericNodeVisitor): def visit_foo(self, node): self.body.append(‘
’) def depart_foo(self, node): self.body.append('
\n') Translator

Slide 39

Slide 39 text

Title Words that have bold in them Paragraph. Writer Example

Slide 40

Slide 40 text

Title

Words that have bold in them.

Paragraph.

Writer Example

Slide 41

Slide 41 text

Writers are used to change or add new output formats from the Doctree

Slide 42

Slide 42 text

How it fits together

Slide 43

Slide 43 text

Implementation

Slide 44

Slide 44 text

# docutils/core.py self.document = self.reader.read(self.source, self.parser, self.settings) self.apply_transforms() self.writer.write(self.document, self.destination) Publisher

Slide 45

Slide 45 text

# docutils/core.py self.document = self.reader.read(self.source, self.parser, self.settings) self.apply_transforms() self.writer.write(self.document, self.destination) Publisher

Slide 46

Slide 46 text

# docutils/readers/__init__.py def read(self, source, parser, settings): self.source = source if not self.parser: self.parser = parser self.settings = settings self.input = self.source.read() document = self.new_document() self.parse(self.input, document) return document Reader

Slide 47

Slide 47 text

# docutils/readers/__init__.py def read(self, source, parser, settings): self.source = source if not self.parser: self.parser = parser self.settings = settings self.input = self.source.read() document = self.new_document() self.parse(self.input, document) return document Reader

Slide 48

Slide 48 text

# docutils/readers/__init__.py def parse(self, inputstring, document): """Parse `inputstring` and populate `document`, a document tree.""" self.statemachine = states.RSTStateMachine( state_classes=self.state_classes, initial_state=self.initial_state) inputlines = docutils.statemachine.string2lines( inputstring) self.statemachine.run(inputlines, document) RST Parser

Slide 49

Slide 49 text

# docutils/core.py self.document = self.reader.read(self.source, self.parser, self.settings) self.apply_transforms() self.writer.write(self.document, self.destination) Publisher

Slide 50

Slide 50 text

# docutils/core.py def apply_transforms(self): self.document.transformer.populate_from_components( (self.source, self.reader, self.reader.parser, self.writer, self.destination)) self.document.transformer.apply_transforms() Transforms

Slide 51

Slide 51 text

# docutils/core.py def apply_transforms(self): self.document.transformer.populate_from_components( (self.source, self.reader, self.reader.parser, self.writer, self.destination)) self.document.transformer.apply_transforms() Transforms

Slide 52

Slide 52 text

# docutils/transforms/__init__.py def apply_transforms(self): """Apply all of the stored transforms, in priority order.""" while self.transforms: priority, transform_class, pending, kwargs = self.transforms.pop() transform = transform_class(self.document, startnode=pending) transform.apply(**kwargs) Transforms

Slide 53

Slide 53 text

# docutils/core.py self.document = self.reader.read(self.source, self.parser, self.settings) self.apply_transforms() self.writer.write(self.document, self.destination) Publisher

Slide 54

Slide 54 text

Writer # docutils/writers/__init__.py def write(self, document, destination): self.translate() output = self.destination.write(self.output) return output

Slide 55

Slide 55 text

Writer # docutils/writers/__init__.py def write(self, document, destination): self.translate() output = self.destination.write(self.output) return output

Slide 56

Slide 56 text

# docutils/writers/html4css1/__init__.py def translate(self): visitor = self.translator_class(self.document) self.document.walkabout(visitor) self.output = self.apply_template() Translator

Slide 57

Slide 57 text

# docutils/core.py self.document = self.reader.read(self.source, self.parser, self.settings) self.apply_transforms() self.writer.write(self.document, self.destination) Publisher

Slide 58

Slide 58 text

We now have an HTML (or whatever Writer) document on the disk

Slide 59

Slide 59 text

Sphinx Implementation

Slide 60

Slide 60 text

Sphinx • Builds on top of the standard docutils concepts • Add it’s own abstractions, but uses the same docutils machinery underneath

Slide 61

Slide 61 text

Sphinx Architecture

Slide 62

Slide 62 text

Major Sphinx Components • Application • Environment • Builder

Slide 63

Slide 63 text

Sphinx Application • Main level of orchestration for Sphinx • Handles configuration & building • Sphinx()

Slide 64

Slide 64 text

Sphinx Environment • Keeps state for all the files for a project • Serialized to disk in between runs • Works as a cache

Slide 65

Slide 65 text

Sphinx Builder • Wrapper around Docutils Writer’s • Generates all types of outputs • Generates most HTML output through Jinja templates instead of Translators

Slide 66

Slide 66 text

Sphinx Architecture

Slide 67

Slide 67 text

Typical Sphinx Run

Slide 68

Slide 68 text

make html

Slide 69

Slide 69 text

sphinx-build -b html -d _build/environment . _build/html

Slide 70

Slide 70 text

# sphinx/application.py app = Sphinx(srcdir, confdir, outdir, doctreedir, opts.builder, confoverrides, status, warning, opts.freshenv, opts.warningiserror, opts.tags, opts.verbosity, opts.jobs) app.build(opts.force_all, filenames) Sphinx

Slide 71

Slide 71 text

# sphinx/application.py app = Sphinx(srcdir, confdir, outdir, doctreedir, opts.builder, confoverrides, status, warning, opts.freshenv, opts.warningiserror, opts.tags, opts.verbosity, opts.jobs) app.build(opts.force_all, filenames) Sphinx

Slide 72

Slide 72 text

# sphinx/application.py def build(self, force_all=False, filenames=None): self.builder.compile_all_catalogs() self.builder.build_all() Sphinx Application

Slide 73

Slide 73 text

# sphinx/application.py def build(self, force_all=False, filenames=None): self.builder.compile_all_catalogs() self.builder.build_all() Sphinx Application

Slide 74

Slide 74 text

# sphinx/builders/__init__.py def build_all(self, docnames, summary=None, method='update'): # Read files from disk and put them in the env updated_docnames = set(self.env.update(self.config, self.srcdir, self.doctreedir, self.app)) # Write the actual output to disk self.write(docnames, list(updated_docnames), method) Sphinx Builder

Slide 75

Slide 75 text

# sphinx/builders/__init__.py def build_all(self, docnames, summary=None, method='update'): # Read files from disk and put them in the env updated_docnames = set(self.env.update(self.config, self.srcdir, self.doctreedir, self.app)) # Write the actual output to disk self.write(docnames, list(updated_docnames), method) Sphinx Builder

Slide 76

Slide 76 text

# sphinx/environment.py def update(self, config, srcdir, doctreedir, app): reader = SphinxStandaloneReader(parsers=self.config.source_parsers) pub = Publisher(reader=reader, writer=SphinxDummyWriter(), destination_class=NullOutput) source = SphinxFileInput(app, self, source=None, source_path=src_path, encoding=self.config.source_encoding) pub.publish() doctree = pub.document doctree_filename = self.doc2path(docname, self.doctreedir, '.doctree') dirname = path.dirname(doctree_filename) if not path.isdir(dirname): os.makedirs(dirname) f = open(doctree_filename, 'wb') pickle.dump(doctree, f, pickle.HIGHEST_PROTOCOL) Sphinx Environment

Slide 77

Slide 77 text

# sphinx/builders/__init__.py def build_all(self, docnames, summary=None, method='update'): # Read files from disk and put them in the env updated_docnames = set(self.env.update(self.config, self.srcdir, self.doctreedir, self.app)) # Write the actual output to disk self.write(docnames, list(updated_docnames), method) Sphinx Builder

Slide 78

Slide 78 text

# sphinx/builders/html.py def write(self, build_docnames, updated_docnames, method=‘update'): for docname in list(build_docnames + updated_docnames): self.docwriter.write(doctree, destination) self.docwriter.assemble_parts() body = self.docwriter.parts['fragment'] metatags = self.docwriter.clean_meta ctx = self.get_doc_context(docname, body, metatags) self.handle_page(docname, ctx, event_arg=doctree) Sphinx Builder

Slide 79

Slide 79 text

# sphinx/builders/html.py def write(self, build_docnames, updated_docnames, method=‘update'): for docname in list(build_docnames + updated_docnames): self.docwriter.write(doctree, destination) self.docwriter.assemble_parts() body = self.docwriter.parts['fragment'] metatags = self.docwriter.clean_meta ctx = self.get_doc_context(docname, body, metatags) self.handle_page(docname, ctx, event_arg=doctree) Sphinx Builder

Slide 80

Slide 80 text

# docutils/writers/__init__.py def write(self, document, destination): self.translate() output = self.destination.write(self.output) Docutils Writer

Slide 81

Slide 81 text

# docutils/writers/__init__.py def write(self, document, destination): self.translate() output = self.destination.write(self.output) Docutils Writer

Slide 82

Slide 82 text

# sphinx/writers/html.py def translate(self): visitor = self.builder.translator_class( self.builder, self.document) self.document.walkabout(visitor) self.output = visitor.astext() Sphinx Writer

Slide 83

Slide 83 text

# sphinx/builders/html.py def write(self, build_docnames, updated_docnames, method=‘update'): for docname in list(build_docnames + updated_docnames): self.docwriter.write(doctree, destination) self.docwriter.assemble_parts() body = self.docwriter.parts['fragment'] metatags = self.docwriter.clean_meta ctx = self.get_doc_context(docname, body, metatags) self.handle_page(docname, ctx, event_arg=doctree) Sphinx Builder

Slide 84

Slide 84 text

# sphinx/builders/html.py def write(self, build_docnames, updated_docnames, method=‘update'): for docname in list(build_docnames + updated_docnames): self.docwriter.write(doctree, destination) self.docwriter.assemble_parts() body = self.docwriter.parts['fragment'] metatags = self.docwriter.clean_meta ctx = self.get_doc_context(docname, body, metatags) self.handle_page(docname, ctx, event_arg=doctree) Sphinx Builder

Slide 85

Slide 85 text

# sphinx/builders/html.py def handle_page(self, pagename, addctx, templatename='page.html'): ctx = self.globalcontext.copy() output = self.templates.render(templatename, ctx) f = codecs.open(outfilename, 'w', encoding, 'xmlcharrefreplace') f.write(output) Sphinx Builder

Slide 86

Slide 86 text

We now have a fully templated HTML file on disk

Slide 87

Slide 87 text

Sphinx Core Events allow you to hook into most parts of the build process

Slide 88

Slide 88 text

Sphinx Core Events • builder-inited • source-read • doctree-read • doctree-resolved • env-updated • html-page-context • build-finished

Slide 89

Slide 89 text

Sphinx Architecture

Slide 90

Slide 90 text

Examples

Slide 91

Slide 91 text

Markdown Parser • Uses recommonmark as a bridge • Translates Commonmark Node’s into Docutils Node’s

Slide 92

Slide 92 text

## Markdown Header Hey There Markdown Parser

Slide 93

Slide 93 text

Markdown Header Hey There Markdown Parser

Slide 94

Slide 94 text

# recommonmark/parser.py def reference(block): # Commonmark Block ref_node = nodes.reference() # Docutils Node label = make_refname(block.label) ref_node['name'] = label ref_node['refuri'] = block.destination ref_node['title'] = block.title return ref_node Markdown Parser

Slide 95

Slide 95 text

from recommonmark.parser import CommonMarkParser source_parsers = { '.md': CommonMarkParser, } source_suffix = ['.rst', '.md'] Enable Markdown

Slide 96

Slide 96 text

:name[content]{key=val} :smallcaps[content] :ref[scatter plot]{target=myFigure} Proposed Markdown Inline Markup

Slide 97

Slide 97 text

::: name [inline-content] {key=val} contents, can contain further block elements ::: :::eval [label] {.python} x = 1+1 print x ::: Proposed Markdown Block level Markup

Slide 98

Slide 98 text

Table of Contents • Enabled with `.. contents::` Directive • Adds a pending node during parsing • Transform turns pending into a list of references

Slide 99

Slide 99 text

.. contents:: TOC Getting Started ——————————————— Table of Contents

Slide 100

Slide 100 text

TOC .. internal attributes: .transform: docutils.transforms.parts.Contents .details: Table of Contents

Slide 101

Slide 101 text

TOC Getting Started Table of Contents

Slide 102

Slide 102 text

References • Allow you to define and point at arbitrary points in documents • Sphinx makes them work across an entire project

Slide 103

Slide 103 text

.. page 1 .. _my-title: Title ----- Paragraph .. page 2 Look at the :ref:`my-title`. References

Slide 104

Slide 104 text

References

Slide 105

Slide 105 text

References

Slide 106

Slide 106 text

Intersphinx • Allows you to link across Sphinx projects, semantically •:ref:`django:template-loaders`

Slide 107

Slide 107 text

intersphinx_mapping = { 'python': ('http://python.readthedocs.org/en/latest/', None), 'django17': ('http://django.readthedocs.org/en/1.7/', None), 'django18': (‘http://sphinx.readthedocs.org/en/1.8/', None), } Intersphinx

Slide 108

Slide 108 text

Reference Resolution Order • References • Domains • Intersphinx References • Intersphinx Domains

Slide 109

Slide 109 text

How Django uses Sphinx

Slide 110

Slide 110 text

Django Deployment • All documentation is written in RST • HTML generated at JSON blobs • Rendered through Django templates on the website

Slide 111

Slide 111 text

:ticket:`1325` :setting:`MEDIA_URL` Django specific additions

Slide 112

Slide 112 text

.. snippet:: :filename: part1.py print “hello world” Django specific additions

Slide 113

Slide 113 text

def ticket_role(name, rawtext, text, lineno, inliner): num = int(text.replace('#', '')) url_pattern = inliner.document.settings.env.app.config.ticket_url url = url_pattern % num node = nodes.reference(rawtext, '#' + utils.unescape(text), refuri=url) return [node], [] Ticket Role

Slide 114

Slide 114 text

class snippet_with_filename(nodes.literal_block): pass Snippet Node

Slide 115

Slide 115 text

class SnippetWithFilename(Directive): has_content = True optional_arguments = 1 option_spec = {'filename': directives.unchanged_required} def run(self): code = '\n'.join(self.content) literal = snippet_with_filename(code, code) if self.arguments: literal['language'] = self.arguments[0] literal['filename'] = self.options['filename'] set_source_info(self, literal) return [literal] Snippet Directive

Slide 116

Slide 116 text

def visit_snippet(self, node): lang = self.highlightlang fname = node['filename'] highlighted = highlighter.highlight_block(node.rawsource) starttag = self.starttag(node, 'div', suffix='', CLASS='highlight-%s' % lang) self.body.append(starttag) self.body.append('
%s
\n' % (fname,)) self.body.append(highlighted) self.body.append('\n') raise nodes.SkipNode Snippet visitor

Slide 117

Slide 117 text

These are generally useful for Django users, and should probably be released as a third party app

Slide 118

Slide 118 text

Take Aways

Slide 119

Slide 119 text

Make sure to use semantic markup when writing docs

Slide 120

Slide 120 text

Generally your job is to get the nodes to exist in the way that you want

Slide 121

Slide 121 text

Feel empowered to extend RST & Sphinx, and make them your own

Slide 122

Slide 122 text

Understand where you need to plug into the pipeline, and do as little as possible to make it happen

Slide 123

Slide 123 text

Thanks • @ericholscher • eric@ericholscher.com • Come talk to me around the sprints