About Sphinx

Sphinx is a tool for making documentation. It was originally created for the Python documentation, but is now used for many other software projects.

Sphinx uses reStructuredText as its markup language. It can produce HTML, LaTeX, ePub and PDF documents.

Source: https://www.sphinx-doc.org

Getting started

After installation, you can get started quickly with the tool sphinx-quickstart. Just enter:

sphinx-quickstart

Answer each customization question with yes or no. Be sure to say yes to the autodoc extension. The sphinx-quickstart creates a directory with several documents:

  • conf.py file, the default configuration file
  • index.rst file, the master document

The conf.py file let’s you configure all aspects of Sphinx. The index.rst is the entry page for your documentation. It contains the toctree directive which determines the files to include. For this project it looks like this:

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   1_intro/intro
   2_draw/draw
   3_image/image
   ...

To build the HTML pages just run:

make html

To make the PDF document run:

make pdf

reStructuredText

reStructuredText (.rst) is the default markup language used with Sphinx. It is important to know that:

  • paragraphs are separated by one or more blank lines
  • indentation is significant

Inline styles

Inside text you can use:

  • one asterisk for italics
  • two asterisks for bold
  • backquotes for code

Lists

This code:

1
2
3
4
5
6
* This is a bulleted list.
* It has two items, the second
  item uses two lines.

#. This is a numbered list.
#. It has two items too.

produces this result:

  • This is a bulleted list.
  • It has two items, the second item uses two lines.
  1. This is a numbered list.
  2. It has two items too.

Admonitions

Danger

Be careful with this code!

Tip

Be careful with this code!

Warning

Be careful with this code!

Footnotes

This is a footnote [1] inside a text, this is another one [2].

Footnotes

[1]Text of the first footnote
[2]Text of the second footnote

Horizontal list

To add a horizontal list add this code:

.. hlist::
   :columns: 3

   * happy
   ...
  • happy
  • short
  • intelligent
  • thankful
  • displayed
  • horizontal

Download

To add a download link add this code:

:download:`requirements.txt<requirements.txt>`.

requirements.txt.

Include from a file

It is possible to include a Python object (class, method) from a file. For example you can include a class definition with:

.. literalinclude:: 5_app/app.py
   :pyobject: Rectangle
   :linenos:
   :emphasize-lines: 5-7

resulting in

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Rectangle(Node):
    """Draw a rectangle on the screen."""
    options = { 'fg': Color('green'),
                'bg': Color('black'),
                'thickness': 2}

    def __init__(self, **options):
        super().__init__(**options)
        self.set_options(Rectangle, options)
        self.render()

    def render(self):
        self.img0 = pygame.Surface(self.rect.size, flags=SRCALPHA)
        if self.fg != None:
            pygame.draw.rect(self.img0, self.fg, Rect(0, 0, *self.rect.size), 0)
        pygame.draw.rect(self.img0, self.bg, Rect(0, 0, *self.rect.size), self.thickness)
        self.img = self.img0.copy()

Or you can include just a method definition with:

.. literalinclude:: 5_app/app.py
   :pyobject: Rectangle.render

resulting in

    def render(self):
        self.img0 = pygame.Surface(self.rect.size, flags=SRCALPHA)
        if self.fg != None:
            pygame.draw.rect(self.img0, self.fg, Rect(0, 0, *self.rect.size), 0)
        pygame.draw.rect(self.img0, self.bg, Rect(0, 0, *self.rect.size), self.thickness)
        self.img = self.img0.copy()

Directives

A directive consists of

  • name
  • arguments
  • options
  • content

The structure is this:

.. name:: arguments
   :option: value

   content

Function

This directive defines a function:

.. function:: spam(eggs)
               ham(eggs)

   Spam ham ham the are made with a certain number of eggs.
spam(eggs)
ham(eggs)

Spam and ham the are made with a certain number of eggs.

To cross-reference you can use:

  • method_name() with :meth:`method_name`
  • class_name with :class:`class_name`
  • function_name() with :func:`function_name`

For example with :func:`spam` one can refernce the above functions spam() or ham() inside a sentence..

Data

To describe global data and constants in a module use this code:

.. data:: number=1000

   Describe data.

produces

number=1000

Describe data.

Class

class App

Describe class without parameters.

run()

Describe the method.

class App(parameters)

Describe class with parameters.

objects

Global class attribute.

Functions with arguments

send_message(sender, recipient, message_body[, priority=1])

Send a message to a recipient

Parameters:
  • sender (str) – The person sending the message
  • recipient (str) – The recipient of the message
  • message_body (str) – The body of the message
  • priority (integer or None) – The priority of the message, can be a number 1-5
Returns:

the message id

Return type:

int

Raises:
  • ValueError – if the message_body exceeds 160 characters
  • TypeError – if the message_body is not a basestring

Math formulas

Since Pythagoras, we know that \(a^2 + b^2 = c^2\).

(1)\[e^{i\pi} + 1 = 0\]

Euler’s identity, equation (1), was elected one of the most beautiful mathematical formulas.

The app module

This code:

.. automodule:: app
   :members:
   :member-order: bysource

Prints the whole app documentation and lists members by source order.

App - there is only one App object - an app has multiple scenes (App.scenes) - an app has one current scene (App.scene) - an app has one window to draw in (App.screen)

Scene

  • a scene has multiple nodes (App.scene.nodes)
  • nodes are ordered: the last in the list is displayed last
  • the node which is clicked becomes active
  • the active node becomes the top node
  • the active node has focus (App.scene.focus)
  • TAB and shift-TAB select the next node

Node (object)

  • nodes have default position and size (pos, size)
  • nodes are automatically placed at creation (dir, gap)
  • nodes inherit options (color, size, …) from the previous object

A Node object has the following properties

  • clickable: mouse-click has effect
  • movable: can be moved (mouse, arrow-keys)
  • visible: is drawn
  • has focus

Debug

  • print events to console (cmd+E)
  • display node label (cmd+L)
  • display outline (cmd+O)
class app.App(size=(640, 240), shortcuts={})[source]

Create a single-window app with multiple scenes having multiple objects.

run()[source]

Run the main event loop.

next_scene(d=1)[source]

Switch to the next scene.

do_shortcut(event)[source]

Find the key/mod combination in the dictionary and execute the cmd.

capture()[source]

Save a screen capture to the directory of the calling class, under the class name in PNG format.

toggle_fullscreen()[source]

Toggle between full screen and windowed screen.

toggle_resizable()[source]

Toggle between resizable and fixed-size window.

toggle_frame()[source]

Toggle between frame and noframe window.

class app.Scene(caption='Pygame', remember=True, **options)[source]

Create a new scene and initialize the node options.

load_img(file)[source]

Load the background image.

enter()[source]

Enter a scene.

update()[source]

Update the nodes in a scene.

set_status(txt)[source]

Set status text and render it.

render_status()[source]

Render the status text.

draw()[source]

Draw all objects in the scene.

do_event(event)[source]

Handle the events of the scene.

next_focus(d=1)[source]

Advance focus to next node.

cut()[source]

Cuts the selected objects and places them in App.selection.

copy()[source]

Copies the selected objects and places them in App.selection.

paste()[source]

Pastes the objects from App.selection.

debug()[source]

Print all scene/node options.

class app.Node(**options)[source]

Create a node object with automatic position and inherited size.

set_options(cls, options)[source]

Set instance options from class options.

create_img()[source]

Create the image surface, and the original img0.

color_img()[source]

Add background color to the image.

set_background(img)[source]

Set background color or transparency.

load_img()[source]

Load the image file.

calculate_pos(options)[source]

Calculate the next node position.

render_label()[source]

Create and render the node label.

do_event(event)[source]

React to events happening for focus node.

draw()[source]

Draw the node and optionally the outline, label and focus.

class app.TextObj(text='Text', **options)[source]

Create a text surface image.

set_font()[source]

Set the font and its properties.

render_text()[source]

Render the text into an image.

class app.Text(text='Text', **options)[source]

Create a text object horizontal and vertical alignement.

class app.TextLines(text, **options)[source]
class app.EditableTextObj(text='Text', cmd='', **options)[source]

Create keyboard and mouse-editable text with cursor and selection.

set_char_positions()[source]

Make a list of all character positions.

get_char_index(position)[source]

Return the character index for a given position.

move_cursor(d)[source]

Move the cursor by d characters, and limit to text length.

get_selection()[source]

Get ordered tuple of selection indices.

copy_text()[source]

Copy text to Scene.text buffer.

cut_text()[source]

Cut text and place copy in Scene.text buffer.

insert_text(text)[source]

Insert text at the cursor position or replace selection.

select_word()[source]

Select word at current position.

select_all()[source]

Select the whole text.

do_event(event)[source]

Move cursor, handle selection, add/backspace text, copy/paste.

render()[source]

Render cursor, selection and text to an image.

class app.EditableText(text='Text', **options)[source]

Create an editable text node.

do_event(event)[source]

React to events happening for focus node.

draw()[source]

Draw the node and optionally the outline, label and focus.

double_click()[source]

Select the current word.

class app.Button(text='Button', cmd='', **options)[source]

Create a button object with command.

do_event(event)[source]

React to events happening for focus node.

class app.Toggle[source]

Add toggle button behavior.

class app.Checkbox(**options)[source]
class app.Radiobutton(**options)[source]
class app.ListBox(items, i=0, **options)[source]

Show a list of text items.

set_list(items)[source]

Set items and selection list.

scroll(d)[source]

Scroll listbox up and down.

move_cursor(d)[source]

Move the active cell up or down.

do_event(event)[source]

React to events happening for focus node.

class app.ListMenu(items, **options)[source]

Display a drop-down menu.

class app.SliderObj(**options)[source]

Define a slider object.

class app.Slider(**options)[source]
do_event(event)[source]

React to events happening for focus node.

class app.NumInput(**options)[source]
do_event(event)[source]

React to events happening for focus node.

class app.Spinbox(**options)[source]

Input a number.

do_event(event)[source]

React to events happening for focus node.

class app.Rectangle(**options)[source]

Draw a rectangle on the screen.

class app.Ellipse(**options)[source]

Draw an ellipse on the screen.

class app.Board(**options)[source]

Draw a mxn board grid with m lines and n columns. m, n number of cells (row, col) i, j index of cell (row, col) dx, dy size of cell Num numeric matrix Num0 initial numeric matrix Col color matrix

set_Num(s)[source]

Load Num table from a string.

render_colors()[source]

Render the background colors.

render_grid()[source]

Render the grid lines.

render_num()[source]

Draw number.

render_tile()[source]

Draw number.

render()[source]

Render the whole board.

get_index(x, y)[source]

Get index (i, j) from mouse position (x, y).

do_event(event)[source]

React to events.

class app.Sudoku(**options)[source]

Create a sudoko game board.

render_grid()[source]

Override the grid lines.

class app.Chess(**options)[source]

Create a sudoko game board.

class app.Go(**options)[source]
render()[source]

Render the Go board and add extra dots on certain intersections.

class app.Puzzle(div=(3, 3), **options)[source]

Take an image and create a puzzle.

Glossary

reStructuredText
reStructedText is ligh-weight markup langage.