My Avatar

LanternD's Castle

PhD Student in ECE @ MSU

Embed Texts in Other Files in reStructuredText

2021-01-11

Include the texts in other files to generate a new files.

Basic

reStructuredText, shortened as reST, is a markup language, with complexity between Markdown and LaTeX, somewhat similar to org-mode.

Recently I learn reST and use it in documenting my side project.

reST is an extension of docutils, and reST nowadays usually works together with sphinx-doc. All of them are powered by Python.

Goal

My goal is to manage a list of items in separate files, but I need a file to generate a completed list of items from those subfiles.

Suppose I have:

Vegetables
==========

- Carrot
- Cabbage
- Lettuce
- Tomato
Fruits
==========

- Apple
- Peach
- Pear
- Strawberry
Dairy
==========

- Milk
- Cream
- Butter
- Cheese

I would like to generate a file items_in_fridge.txt (automatically), listing all the items above.

Items in Refrigerator
==========

Vegetables
------

- Carrot
- Cabbage
- Lettuce
- Tomato

Fruits
------

- Apple
- Peach
- Pear
- Strawberry

Dairy
----------

- Milk
- Cream
- Butter
- Cheese

How

We can use the “include” directive. “Directive” can be consider as “command”.

In this example, the files should be modified as following:

Vegetables
==========

.. start_mark

- Carrot
- Cabbage
- Lettuce
- Tomato

.. end_mark
Fruits
==========

.. start_mark

- Apple
- Peach
- Pear
- Strawberry

.. end_mark
Dairy
==========

.. start_mark

- Milk
- Cream
- Butter
- Cheese

.. end_mark
Items in Refrigerator
==========

Vegetables
------

.. include:: vege.txt
    :start-after: .. start_mark
    :end-before: .. end_mark

Fruits
------

.. include:: fruits.txt
    :start-after: .. start_mark
    :end-before: .. end_mark

Dairy
----------

.. include:: dairy.txt
    :start-after: .. start_mark
    :end-before: .. end_mark

In this case, we just need to modify the items in the subfiles (vege.txt, fruits.txt, and dairy.txt in this case). Then the items_in_fridge.txt will include them automatically.

I use the mark .. start_mark (comment syntax in reST) to avoid displaying any text in the original documents. You can replace them with something else.

Read More



Disqus Comment 0