(台灣使用者請點我開啟中文版 Video for Taiwanese users in Mandarin)
Attention
For GGeditor installed after Jan 15, 2017:
Because the GGeditor starts to support mutliple accounts in that release. But this tutorial is not yet updated. There is a note for your:
Before your first committing to the Github. Please go “Settings” panel to set an accout for it to work.
Tutorial¶
The GGeditor assumes a scenario that
- You already have a project repository in the Github, and
- You already have a project in the readthedocs.org which corresponds to that repository.
Because the Github and the readthedocs.org accept reStructuredText or markup formats only. You have to build documentation in markup or reStructuredText formats. But you are suffering on creating document with markup or reStructuredText formats.
This is the flow chart of working with the GGeditor to build your documentation:
This tutorial would only go through the longest route in the flow chart. Here are the sequences of what are been demonstrated in this tutorial :
- The tutorial will start from creating a new document in the Google Docs.
- The new file will be named “Tutorial”. It has a heading, an image and an admonition created from the sidebar of the GGeditor.
- The new file will be commit to the Github repository, in this demo, it is the repository of the GGeditor.
- Because this is a new file, a process will be initiated for binding. It includes to log-in, navigate, create new file and commit.
It’s done for the “Tutorial” document.
Warning
For CKJ users: (繁體中文、简体中文、한국어、日本語)
English document name is strongly suggested for naming your documents. Especially when the document contains images because images got pathname from their hosting document. Naming document in English would reduce risk of parsing failure in the readthedocs.org.
We also want the document “Tutorial” to be listed on the menu in the readthedocs.org project site. We have to add an item within the “toctree” in the index.rst. So there are extra steps when a new file was created:
- Open the index.rst and add the new filename (“Tutorial”) in the table of toctree.
- Commit the index.rst to the Github. Because the index.rst already has a binding file, we just need to click the “Commit” button.
It’s done for updating the index.rst.
If a document already has a binding file, the process is simple, just to open, edit and commit. This tutorial ends up by checking the project site in reatthedocs.org. You will see the content of this new document “Tutorial” is on the project site of the readthedocs.org. We don’t need to do anything on the Github or the readthedocs.org. The readthedocs.org will automatically rebuild your project site when the corresponding repository move forward.
Here is the video of this tutorial:
Note
- When you name the Google Docs document, the name need not with suffix “.rst”.
- But the binding file in the Github repository do need with suffix “.rst”. It will be automatically appended when the GGeditor created it. If you manually created the binding file, please name it with suffix “.rst”.
- in this tutorial video, the committing of index.rst does not also commit images. That is because the changes include text part only. By un-checking the “Commit images” option, the committing only updates the generated reStructuredText content of the index.rst. That makes the time of committing being shorter.
How to Use¶
The Google Docs Native Features¶
You can use the following list native features of the Google Docs to build your content for generating reStructuredText format.
- Paragraph heading and indentation
- Bold, Italic, subscript and superscript
- List and numbered list
- Table
- Image and chart
- Footnote, hyperlink and bookmark
- Table of contents (links to bookmarks and headings)
- Special characters and CKJ full-width characters
- Horizontal line
Note
A hyperlink will be opened in a new window(tab) if its URL is of format “scheme://…”, like http://, https://, etc.
Inline Markups¶
Some inline reStructuredText markups can be used directly in the document. The table below shows the usage example of these inline markups.
In Google Docs document | Rendered in HTML page |
---|---|
A `single back-quote` | A single back-quote |
A ``double back-quote`` | A double back-quote |
A |replacement| markup | A replaced markup |
That is converted from the source content in document:
Please noted that if you manually put a substitution markup, you got to provide correct replacement markup manually too. Otherwise, the sphinx parser will raise exception.
Table¶
The Google Docs native table can be converted to reStructuredText table. One thing must mention is that, if you want to generate header rows in the generated reStructuredText table, you have to make all text in the header rows to be bold.
This is the rendered table of the above content.
Header Row | Header Row | Header Row |
---|---|---|
Normal Row | Normal Row | Normal Row |
Normal Row | Normal Row | Normal Row |
Hint
You can set background-color for header rows by assign CSS in the /docs/static/theme_overrides.css. For example:
- .wy-table-responsive table th {
- background-color: #f0f0f0;
}
Image¶
Images and charts in the Google Docs document are able to be converted to the generated reStructuredText file bundles. Here is the naming rules:
- A folder named “static” will be created if necessary in the same folder of the document.
- All the images in the document will be stored in the “static” folder in PNG format.
- The image name is the document name + underscore + sequence number + ‘.png’
Images will be re-generated if “Commit images” was checked. That is, the mapping between image content and image name might not be constant.
Warning
For CKJ users: (繁體中文、简体中文、한국어、日本語)
English document name is strongly suggested for naming your documents. Especially those documents with images because an image got pathname from its hosting document. By naming document in English, it would reduce the risk of parsing failure in the readthedocs.org.
Note
Currently, it seems the sphinx parser has problem on parsing :align: of an image markup, so image horizontal alignment is not supported yet.
Markup Panel¶
The “Show Markup Panel” helps you to insert special markups, to see the converted content in reStructuredText, or to download the generated files.
Admonitions¶
Admonition is something like this:
Attention
Here is the content of this attention
The GGeditor try to set the look-and-feel of admonitions to be as close as possible to what they are in the readthedocs.org (RTD). There are 4 kinds of layout for 10 types of admonitions. Please click on the admonition name to insert them into your document.
Custom Admonition¶
The “custom” at lower-right of the admonitions panel is a special feature. It inserts a template of admonition. In the diagram below, the left side is the template and you should change its title to whatever you want. The GGeditor will convert it to native markup of reStructuredText.
It renders like this:
Release Note
(content of Change-me)
Directives¶
Directive is the generic form of admonition and many other reST Markups.
Generic Directive¶
Generic directive
can be used for all kinds of reST directive. It will give you a table as shown below, you should replace all the placeholder to fit your needs.
The following table is an example of the directive toctree
.
Please be noted “name” and “content” are required for a directive, arguments and options are optional. If there are no options, the content can be in the 2nd row. If there is more than one options, these options should be put line by line in 2nd row, or row by row. See the diagram below for illustration.
This is the reST generated from the above table.
You have to replace the name and content for your own purpose. One of the usage is to create customized admonition. The following directive table will create a And, by the way…
dialog for you.
Below is how it is rendered in the web page.
And, by the way…
Here is your content
Code¶
code
is for holding sample codes.
The content in a code directive cannot be in bold or italic. Neither hyperlinks and images.
You can highlight your code by giving a language name after the ..code::, like this: (there is a space in front of “python”)
It is rendered like this:
#!/usr/bin/env python
"""
Twisted moved the C{twisted} hierarchy to the C{src} hierarchy, but C{git}
doesn't know how to track moves of directories, only files. Therefore any
files added in branches after this move will be added into ./twisted/ and need
to be moved over into
"""
import os
from twisted.python.filepath import FilePath
here = FilePath(__file__).parent().parent()
fromPath = here.child("twisted")
toPath = here.child("src")
for fn in fromPath.walk():
if fn.isfile():
os.system("git mv {it} src/{it}"
.format(it="/".join(fn.segmentsFrom(here))))
os.system('git clean -fd')
Code with line number¶
This will insert a “code-block” directive. This feature render the given content with line numbers. The “:linenos” option should not be removed. Because the “code-block” should have an argument for programming language of the given content, a placeholder “python” has been appended as default. This argument can be replaced but shall not been removed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #!/usr/bin/env python
"""
Twisted moved the C{twisted} hierarchy to the C{src} hierarchy, but C{git}
doesn't know how to track moves of directories, only files. Therefore any
files added in branches after this move will be added into ./twisted/ and need
to be moved over into
"""
import os
from twisted.python.filepath import FilePath
here = FilePath(__file__).parent().parent()
fromPath = here.child("twisted")
toPath = here.child("src")
for fn in fromPath.walk():
if fn.isfile():
os.system("git mv {it} src/{it}"
.format(it="/".join(fn.segmentsFrom(here))))
os.system('git clean -fd')
|
Table of Contents¶
The Table of Contents will insert a sphinx toctree, aka cross-document table of contents to the cursor position. Usually, it was inserted into the index.rst
document. The rules of what filename been included in the auto generated toctree table are:
- All the documents with suffix .rst in the same folder of this document. Even the document is not binding to a file in the Github.
- If a document is binding to a file in the Github, the filename will be used. Even the source document is not with suffix “.rst”.
- The current document is excluded. This is for preventing from falling into an infinite loop while the RTD parsing this table. You should add it back manually if that makes sense for you.
Here is an example of what it looks like:
Please be noted the file suffix (.html or .rst) has been omitted. Also, you have to change their order manually. You have to manually edit the list content in the 3rd row when you add or remove your documents. Maybe you can just ask the GGeditor to generate a new doctree table and remove the existing one. You can refer to the source document of the index.rst of the GGeditor for an example.
Raw HTML
This is a handy feature for you to embed html tags into the generated reStructuredText file. This button will insert a table into the document. Then you can put HTML tages in the table. The GGeditor will convert the table content to a “.. raw:: html” directive.
Headings¶
The headings construct the structure of the document. If you put the cursor in a paragraph you can set the heading for that paragraph with this panel. You can click on the upper parts (like Part, Chapter) or use the native heading tools of the Google Docs. The lower parts of this panel shows the relative headings in the Google Docs.
Text Style¶
By putting the cursor in a paragraph you can change the text style of that paragraph. The Paragraph Content is for normal text, Directive Content is for code style (monospace). These two are usually used when you paste stuffs from other browser pages into your document.
Upgrade all headings¶
All the paragraphs with headings will increase one level of heading. That is, Heading 2 becomes Heading 1, and Heading 1 becomes Title. Heading 6 becomes Heading 5. Title keeps Title.
This is useful when you dealing with depth level about what will be listed on the sidebar of your project site in the RTD.
Downgrade all headings¶
All the paragraphs with headings will decrease one level of heading. That is, Heading 1 becomes Heading 2, and Title becomes Heading 1. Heading 5 becomes Heading 6. Heading 6 keeps Heading 6.
Add link to another document¶
Add a link of markup to other Google Docs document for selected text. Once clicked, a list of name of Google Docs will be prompted for your choice. Like this:
Please be noted:
- only files in the same folder of the current document will be listed.
- The Google Docs does not allow relative URL, so the added URL will be a pseudo-URL which starts with “http://cross.document/”, please keep the pseudo header when you are manually editing it. The pseudo-URL will be converted to relative-URL when generating the reST.
Commit to Github¶
Binding the document to a file in repository¶
You can provide your account credentials for binding the document to a file in the Github repository. Here is the process diagram:
If you want to commit to a new file. Please
- Navigate to the folder where the new file would be
- Click on the “New File” item
- Give the file name to create. The name will be suffix with “.rst” automatically.
Hint
While doing any clicking, ONE click is enough. No need to do “Double-Clicking”.
Committing¶
Once you have build the binding, next time you can use the “Commit” button directly to commit. You can reset the binding in this dialog too.
The “Rest Binding” is for rebinding the file in Github repository with this document.
If only the text content has been modified, you can un-check the “Commit images” to exclude images from committing. This would speed up the committing process.
Note
The GGeditor will maintain image files it uploaded to the Github repository while committing. If you modified any image, no matter adding, replacement or deletion, you should check “Commit images”.
Attention
If you have a fat document like this one “How to User”, which has lots of images to upload, you might experience broken images in its corresponding html page in your RTD web site. It is because the RTD re-generating the html when uploading is still ongoing. In that case, you have to wait longer for the RTD to release its lock of building or enforce the RTD to build again from your administration page.
By the way, if you see an obsoleted image the reason might be that the RTD set cache time longer. In that case, you can clear the browser cache or check the Github repository for figuring what happened.
About the Credentials¶
Given credentials is encrypted and kept in the Google App Script platform. None cloud server is built by the GGeditor.
Credentials is optional. You can un-check the “Remember Github Credentials” check box or the “Reset Credentials” button to clean up the stored credentials.
Caution
The GGeditor will never sent you email to request reset credentials or anything else.
Conversion¶
When you open the conversion dialog, the conversion process will be starting. When the conversion has completed, you can copy the generated reStructuredText content to clipboard by “Copy to Clipboard” button, or download the generated reStructuredText content as well as images by the “Download” button.
Conversion Rules¶
What been converted depends on selection and the cursor position, rules are:
- If there are selections, the top elements of every selected one are converted. Which means if a paragraph is partially selected, whole the paragraph is converted.
- If there is no selection and the cursor is in a table, that table is converted
- Otherwise, the whole document is converted
The conversion message on the right side are indications. There are three kinds of message:
Means the whole document is converted to the reStructuredText format.
Means only the table where cursor positioned was converted to the reStructuredText format. (partial conversion)
Means only the selection was converted to the reStructuredText format. (partial conversion)
Why Partial Conversion¶
The idea for partial conversion is mainly for creating comments in a source code. In your source code scripts, you can have comments for functions, classes, modules, packages in reStructuredText format. The RTD can automatically generate API documents from source codes. This “How to Create API Docs” has more.
Copy to Clipboard¶
(This feature is specially for API writers, so it is only visible for partial conversion)
This button will copy the generated reStructuredText to system clipboard (pasteboard). For convenience to paste as a block of comment in source code, you can assign a prefix for every copied line. The options are:
Options | Note |
---|---|
No prefix | |
# | Python |
* | Javascript, C++, Java, … etc |
// | Javascript, C++, Java, … etc |
Ask | whatever you say |
Dowload¶
What been converted depends on selection and the cursor position, rules are:
- When partially converted, a <document-name>_selection.zip or <document-name>_table.zip will be created with the partially generated reStructuredText content and images (if any).
- If whole document is converted, a <document-name>.zip will be created with whole generated reStructuredText content and images (if any).
Generate Document¶
When partial content is converted only, like table or selection, The “Generate Document” button appears. Users can click this button to enforce the whole document is converted.
Settings¶
Accounts¶
The GGeditor supports multipe Github accounts. You can select the account to use when committing converted reStructuredText to the Github for every single document. This panel is where you manage these Githubs accounts.
Document Preferences¶
When converting tables in this document¶
You have two options.
“with pure reStructuredText markups” would convert table in pure reStructuredText syntax. This is the default behavior.
“with HTML tags” would generate table with HTML <TABLE>. This option is useful for those who utilizes the readthedocs.org as a blog system. Please refer to this document for details.
Examples¶
This is the native Table of Contents of the Google Docs. This is a kind of in-document table of contents.
Supported Features List of the GGeditor¶
Paragraphs¶
The next paragraph contains links, bold, italic, subscript and superscript text, clickable inline image . As well as a paragraph of the same content with indentation.
In mathematics, a polynomial[1] is an expression consisting of variables (or indeterminates) and coefficients, that involves only the operations of addition, subtraction, multiplication, and non-negative integer exponents. An example of a polynomial of a single indeterminate x is x2 − 4x + 7. An example in three variables is x3 + 2xyz2 − yz + Tab.
In mathematics,a polynomial is an expression consisting of variables (or indeterminates) and coefficients, that involves only the operations of addition, subtraction, multiplication, and non-negative[2] integer exponents. An example of a polynomial of a single indeterminate x is x2 − 4x + 7. An example in three variables is x3 + 2xyz2 − yz + Tab.
List Item¶
- In mathematics,
a polynomial[3] is an expression consisting of variables (or indeterminates) and coefficients, that involves only the operations of addition, subtraction, multiplication, and non-negative integer exponents. An example of a polynomial of a single indeterminate x is x2 − 4x + 7. An example in three variables is x3 + 2xyz2 − yz + Tab.
- In mathematics,
a polynomial[4] is an expression consisting of variables (or indeterminates) and coefficients, that involves only the operations of addition, subtraction, multiplication, and non-negative integer exponents. An example of a polynomial of a single indeterminate x is x2 − 4x + 7. An example in three variables is x3 + 2xyz2 − yz + Tab.
Table¶
Simple Table¶
header* | 標題 x2+y2 | |
---|---|---|
In mathematics, | In mathematics, | In mathe*matics, |
In mathematics, | In mathematics, |
Complex Table¶
In mathematics, |
|
In mathematics, |
In mathematics, |
Image¶
Image with link¶
Chart¶
Admonitions¶
Attention
인기 펑크록밴드 그린데이는 20일 열린 아메리칸 뮤직 어워즈 무대에서 트럼프를 맹비난했다. 그린 데이는 전 세계로 중계된 이날 시상식 무대에서 최근 발매된 신곡 ‘뱅 뱅’을 부르며 “노 트럼프, 노 KKK, 노 파시스트 미국(No Trump, No KKK, No Fascist USA)”라는 구호를 반복해 외쳤다. 그린 데이의 보컬이자 기타리스트인 빌리 조 암스트롱은 이달 초 열린 MTV 유러피안 뮤직 어워즈 현장에서도 트럼프를 히틀러에 비유하며 쓴 소리를 퍼부은 바 있다.
Caution
NHKが各地の消防に取材したところ、午後1時半現在、この地震で、千葉県で82歳の女性が足の骨を折る大けがをするなど、4つの都県で合わせて12人がけがをしたということです。けがをした人の内訳は、福島県で5人、千葉県で4人、東京で2人、宮城県で1人となっています。
Danger
今年9月,一張具有重要歷史意義的越戰照片「燒夷彈女孩」(Napalm Girl),但Facebook宣稱不該發布裸露的女孩照片,並將上傳者帳號停權。 這引發了另一位挪威編輯不滿,他寫了一封公開信表示「Zuckerberg(臉書CEO)分不清楚歷史的重要照片及色情裸露圖片的不同,恣意的進行內容審查」 臉書已經成為10幾億人的資訊來源,如果它開始恣意下架訊息,這會不會是新白色恐怖?
Error
(content of error)
Hint
(content of hint)
Important
(content of important)
Note
(content of note)
Tip
(content of tip)
Warning
(content of warning)
Code block with line number¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #!/usr/bin/env python
"""
Twisted moved the C{twisted} hierarchy to the C{src} hierarchy, but C{git}
doesn't know how to track moves of directories, only files. Therefore any
files added in branches after this move will be added into ./twisted/ and need
to be moved over into
"""
import os
from twisted.python.filepath import FilePath
here = FilePath(__file__).parent().parent()
fromPath = here.child("twisted")
toPath = here.child("src")
for fn in fromPath.walk():
if fn.isfile():
os.system("git mv {it} src/{it}"
.format(it="/".join(fn.segmentsFrom(here))))
os.system('git clean -fd')
def outer(x):
def indent_start(x):
go start start
go start end
def end(y):
go end start
go end end
|
Custom Admonition¶
Nested List Item¶
item 1
item 1.1
item 1.2
- Item a
- Item b
- Item c
item 1.3
List Item with Text Styles¶
item 1
- item 1.1 with superscript
- item 1.12 with superscript
- item 1.34 with subscript
item 2
- Item with link
- item with a image
item 3
♞ Here is the source document of this page
Footnotes
[1] | Polynomial is poly+nomial |
[2] | Non-negative is positive and zero |
[3] | Polynomial is poly+nomial |
[4] | Polynomial is poly+nomial |
[5] | This is a footnote of a list item |
[6] | This is another footnote of a list item |
How to the Readthedocs¶
The readthedocs.org (RTD) is an awesom place to host your documentation of projects in the Github as well as other repositories.
This is a simple guideline to help the GGeditor users to set up a basic project of the RTD. I have no idea if this is the best practice, it just works for me.
- Create a Google Docs document and bind it to the “docs/index.rst” in the Github repository.
- Insert markups of “toctree” table into index.rst.
- Create “docs/conf.py” on Github
- Create “docs/static/theme_overrides.css” on Github
That’s all. With the above 4 steps, you can go the RTD and create a project for your repository.
Below, I will show you how to do these steps with the GGeditor.
Step 1: Binding to the docs/index.rst¶
You can bind the Google Docs document with the GGeditor by menu item “Add-ons/GGeditor/Commit to Github”. Then select your repository, docs folder and the index.rst file in the dialog.
If the “index.rst” file does not exist in your Github repository, you can navigate to the “docs” folder, then click “New File” and input “index.rst”. The GGeditor will create it.
Or select “New File” to create.
If even the “docs” folder does not exist yet in your Github repository, you can input “docs/index.rst” as the name in the dialog of the “New File”. Like this:
Step 2: insert toctree markup to the index.rst¶
The index.rst is the homepage of your project in the RTD. You can put anything you want. But you should not miss the awesome feature - the sidebar of “table of contents” for your documentation. Just simply do this in the GGeditor markup panel:
- Insert a “Table of Contents” from the “GGeditor Markup Panel / Markup / Directives”
Then, the document would have a “toctree” table like this:
You can reference the index.rst of the GGeditor for example.
Step 3: conf.py¶
The Github allows user to create a new file in the repository page:
Then input the path and file name for your new file (docs/conf.py).
Below is the content for you to copy and paste.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys, os
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
sys.path.append(os.path.abspath(os.pardir))
__version__ = '1.0'
# -- General configuration -----------------------------------------------------
source_suffix = '.rst'
master_doc = 'index'
project = 'CHANGE-THIS'
copyright = '2016, CHANGE-THIS'
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
extlinks = {}
# -- Options for HTML output ---------------------------------------------------
html_theme = 'default'
html_static_path = ['static']
def setup(app):
# overrides for wide tables in RTD theme
app.add_stylesheet('theme_overrides.css') # path relative to static
"""
You might want to uncomment the “latex_documents = []” if you use CKJ characters in your document.
Because the pdflatex raises exception when generate Latex documents with CKJ characters.
"""
#latex_documents = []
|
Tip
To utilize the full power of the Sphinx, you can consult this document.
Step 4: theme_overrides.css¶
You can use the same way to create a new “theme_overrides.css” in the “docs/static” folder. Like this:
Below is the content of the theme_overrides.css for you to copy and paste.
.wy-table-responsive table td, .wy-table-responsive table th {
white-space: inherit;
}
.wy-table-responsive table th {
background-color: #f0f0f0;
}
.line-block, .docutils.footnote {
line-height: 24px;
}
.admonition {
margin-bottom: 20px;
line-height:24px;
}
.admonition > *:not(:first-child){
/* draw a boder around a admonition */
border-left: solid 1px #b59e9e;
border-right: solid 1px #b59e9e;
padding: 12px;
margin: -12px -12px -12px -12px;
margin-bottom: -12px !important;
}
.admonition > .last, .admonition- > .last{
/* draw a boder around a admonition */
border-bottom: solid 1px #b59e9e !important;
}
Because the standard theme set the white-space to be “no-wrap” for table cell undesirable for the converted table of the GGeditor.
Next Step:¶
Go readthedocs.org to create a project for your reStructuredText files in the Github repository.
How to Create API Docs¶
I. Create API document for a Python module¶
Scenario¶
We have a python module “backend”. And suppose that scripts in the backend follows the Google Python Style Guide.
1. Modify the conf.py¶
in the “docs/conf.py”[1],
- Append a line to insert the path of module to sys.path, in this demo, it is “backend” (Line #4)
- Ensure the autodoc and napoleon are in the extensions (Line #7)
- Add a subroutine named run_apidoc (Line #9-17)
- Add a callback to builder-inited by app.connect (Line #23)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import sys, os
# append the next line to conf.py, should change "backend" to your module name
sys.path.insert(0, os.path.join(os.path.dirname(__file__),'..','backend'))
# ensure the autodoc and napoleon are in the extensions
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon']
def run_apidoc(_):
from sphinx.apidoc import main
parentFolder = os.path.join(os.path.dirname(__file__), '..')
cur_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.append(parentFolder)
# change "backend" to your module name
module = os.path.join(parentFolder,'backend')
output_path = os.path.join(cur_dir, 'api')
main(['-e','-f','-o', output_path, module])
def setup(app):
# overrides for wide tables in RTD theme
app.add_stylesheet('theme_overrides.css')
# trigger the run_apidoc
app.connect('builder-inited', run_apidoc)
|
2. Modify the index.rst¶
This step is optional. Suppose we hope the generated api document can be accessed from the menu on the left side, we have to modify the toctree table in the index.rst. Like this:
II. Create API document for a Python script¶
Scenario¶
We have a python script “backend/apidocsample.py”. And suppose that this script follows the Google Python Style Guide.
Process¶
1. Modify the conf.py¶
(You can edit the conf.py by the default web-based text editor of the Github)
In the “docs/conf.py”,
- Append a line to insert the backend to sys.path (Line #4)
- Ensure the autodoc and napoleon are in the extensions (Line #7)
1 2 3 4 5 6 7 | import sys, os
# append the next line to conf.py
sys.path.insert(0, os.path.join(os.path.dirname(__file__),'..','backend'))
# ensure the autodoc and napoleon are in the extensions
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon']
|
2. Create the apidocsample.rst¶
Create the apidocsample.rst in the “docs”. This is simple content, you can create this file by the default web-based text editor of the Github.
apidocsample module
====================
.. automodule:: apidocsample
:members:
:undoc-members:
:show-inheritance:
3. Done¶
Commit the conf.py and the apidocsample.rst (suppose the backend/apidocsample.py has committed already), then that’s done. You can see the api document at the RTD by this URL:
http://<project-name>.readthedocs.io/en/latest/<rst-filename>.html, in this demo case, it is http://ggeditor.readthedocs.io/en/latest/apidocsample.html
Hint
The key ideas are:
- The python script (apidocsample.py) should be able to import by the sphinx builder, so sys.path should be updated in the conf.py.
- apidocsample.rst in the docs folder is a placeholder-like file which triggers the sphinx builder to lookup apidocsample.py and collects markups from it.
Footnotes
[1] | More on http://www.sphinx-doc.org/en/1.4.8/config.html#build-config |
Limitations¶
Unsupported Google Docs Features:¶
The Google Docs is a powerful editor, but not all features are supported to convert to reST markups. Below is the list (included but not limited to)
- Comments. This is not supported by the reST.
- Drawing objects. Because there is no API to get it as an image.
- List styles. The list style is defined by the CSS settings in the html page.
- Math equations. Because this is no API to get it as an image.
- Multi-columns. This is not supported by the reST.
- Page break. This is not able to apply to a html page.
- Page header and page footer. This is not supported by the reST.
- Page numbering. This is not able to apply to a html page.
- Internal link to heading does not work. Currently there is no API to identifiy the target heading element. Please use “Bookmark“ instead.
- Bold and italic styles in footnote content does not exposed by Doc’s API. Which means bold and italic text is rendered as normal text in footnote content.
Known Issues:¶
backend package¶
Submodules¶
backend.apidocsample module¶
Example Google style docstrings.
This module demonstrates documentation as specified by the Google Python Style Guide. Docstrings may extend over multiple lines. Sections are created with a section header and a colon followed by a block of indented text.
Example
Examples can be given using either the Example
or Examples
sections. Sections support any reStructuredText formatting, including
literal blocks:
$ python example_google.py
Section breaks are created by resuming unindented text. Section breaks are also implicitly created anytime a new section starts.
-
backend.apidocsample.
module_level_variable1
¶ Module level variables may be documented in either the
Attributes
section of the module docstring, or in an inline docstring immediately following the variable.Either form is acceptable, but the two should not be mixed. Choose one convention to document module level variables and be consistent with it.
Type: int
-
class
backend.apidocsample.
ExampleClass
(param1, param2, param3)¶ Bases:
object
The summary line for a class docstring should fit on one line.
If the class has public attributes, they may be documented here in an
Attributes
section and follow the same formatting as a function’sArgs
section. Alternatively, attributes may be documented inline with the attribute’s declaration (see __init__ method below).Properties created with the
@property
decorator should be documented in the property’s getter method.Attribute and property types – if given – should be specified according to PEP 484, though PEP 484 conformance isn’t required or enforced.
-
attr1
¶ Description of attr1.
Type: str
-
attr2
¶ Description of attr2.
Type: Optional[int]
-
attr3
= None¶ Doc comment inline with attribute
-
attr4
= None¶ Doc comment before attribute, with type specified
Type: List[str]
-
attr5
= None¶ Docstring after attribute, with type specified.
Type: Optional[str]
-
example_method
(param1, param2)¶ Class methods are similar to regular functions.
Note
Do not include the self parameter in the
Args
section.Parameters: - param1 – The first parameter.
- param2 – The second parameter.
Returns: True if successful, False otherwise.
-
readonly_property
¶ Properties should be documented in their getter method.
Type: str
-
readwrite_property
¶ Properties with both a getter and setter should only be documented in their getter method.
If the setter method contains notable behavior, it should be mentioned here.
Type: List[str]
-
-
exception
backend.apidocsample.
ExampleError
(msg, code)¶ Bases:
exceptions.Exception
Exceptions are documented in the same way as classes.
The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself.
Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it.
Note
Do not include the self parameter in the
Args
section.Parameters: - msg (str) – Human readable string describing the exception.
- code (Optional[int]) – Error code.
-
msg
¶ Human readable string describing the exception.
Type: str
-
code
¶ Exception error code.
Type: int
-
backend.apidocsample.
example_generator
(n)¶ Generators have a
Yields
section instead of aReturns
section.Parameters: n (int) – The upper limit of the range to generate, from 0 to n - 1. Yields: int – The next number in the range of 0 to n - 1. Examples
Examples should be written in doctest format, and should illustrate how to use the function.
>>> print([i for i in example_generator(4)]) [0, 1, 2, 3]
-
backend.apidocsample.
module_level_function
(param1, param2=None, *args, **kwargs)¶ This is an example of a module level function.
Function parameters should be documented in the
Args
section. The name of each parameter is required. The type and description of each parameter is optional, but should be included if not obvious.Parameter types – if given – should be specified according to PEP 484, though PEP 484 conformance isn’t required or enforced.
If *args or **kwargs are accepted, they should be listed as
*args
and**kwargs
.The format for a parameter is:
name (type): description The description may span multiple lines. Following lines should be indented. The "(type)" is optional. Multiple paragraphs are supported in parameter descriptions.
Parameters: - param1 (int) – The first parameter.
- param2 (Optional[str]) – The second parameter. Defaults to None. Second line of description should be indented.
- *args – Variable length argument list.
- **kwargs – Arbitrary keyword arguments.
Returns: True if successful, False otherwise.
The return type is optional and may be specified at the beginning of the
Returns
section followed by a colon.The
Returns
section may span multiple lines and paragraphs. Following lines should be indented to match the first line.The
Returns
section supports any reStructuredText formatting, including literal blocks:{ 'param1': param1, 'param2': param2 }
Return type: bool
Raises: AttributeError
– TheRaises
section is a list of all exceptions that are relevant to the interface.ValueError
– If param2 is equal to param1.
-
backend.apidocsample.
module_level_variable2
= 98765¶ Module level variable documented inline.
The docstring may span multiple lines. The type may optionally be specified on the first line, separated by a colon.
Type: int
backend.apidocsample2 module¶
Example Google style docstrings #2.
This module demonstrates documentation as specified by the Google Python Style Guide. Docstrings may extend over multiple lines. Sections are created with a section header and a colon followed by a block of indented text #2.
- Example #2:
Examples can be given using either the
Example
orExamples
sections. Sections support any reStructuredText formatting, including literal blocks:$ python example_google.py
Section breaks are created by resuming unindented text. Section breaks are also implicitly created anytime a new section starts #2.
-
backend.apidocsample2.
module_level_variable1
¶ Module level variables may be documented in either the
Attributes
section of the module docstring, or in an inline docstring immediately following the variable #2.Either form is acceptable, but the two should not be mixed. Choose one convention to document module level variables and be consistent with it #2.
Type: int
-
class
backend.apidocsample2.
ExampleClass
(param1, param2, param3)¶ Bases:
object
The summary line for a class docstring should fit on one line.
If the class has public attributes, they may be documented here in an
Attributes
section and follow the same formatting as a function’sArgs
section. Alternatively, attributes may be documented inline with the attribute’s declaration (see __init__ method below).Properties created with the
@property
decorator should be documented in the property’s getter method.Attribute and property types – if given – should be specified according to PEP 484, though PEP 484 conformance isn’t required or enforced.
-
attr1
¶ Description of attr1.
Type: str
-
attr2
¶ Description of attr2.
Type: Optional[int]
-
attr3
= None¶ Doc comment inline with attribute
-
attr4
= None¶ Doc comment before attribute, with type specified
Type: List[str]
-
attr5
= None¶ Docstring after attribute, with type specified.
Type: Optional[str]
-
example_method
(param1, param2)¶ Class methods are similar to regular functions.
Note
Do not include the self parameter in the
Args
section.Parameters: - param1 – The first parameter.
- param2 – The second parameter.
Returns: True if successful, False otherwise.
-
readonly_property
¶ Properties should be documented in their getter method.
Type: str
-
readwrite_property
¶ Properties with both a getter and setter should only be documented in their getter method.
If the setter method contains notable behavior, it should be mentioned here.
Type: List[str]
-
-
exception
backend.apidocsample2.
ExampleError
(msg, code)¶ Bases:
exceptions.Exception
Exceptions are documented in the same way as classes.
The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself.
Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it.
Note
Do not include the self parameter in the
Args
section.Parameters: - msg (str) – Human readable string describing the exception.
- code (Optional[int]) – Error code.
-
msg
¶ Human readable string describing the exception.
Type: str
-
code
¶ Exception error code.
Type: int
-
backend.apidocsample2.
example_generator
(n)¶ Generators have a
Yields
section instead of aReturns
section.Parameters: n (int) – The upper limit of the range to generate, from 0 to n - 1. Yields: int – The next number in the range of 0 to n - 1. Examples
Examples should be written in doctest format, and should illustrate how to use the function.
>>> print([i for i in example_generator(4)]) [0, 1, 2, 3]
-
backend.apidocsample2.
module_level_function
(param1, param2=None, *args, **kwargs)¶ This is an example of a module level function.
Function parameters should be documented in the
Args
section. The name of each parameter is required. The type and description of each parameter is optional, but should be included if not obvious.Parameter types – if given – should be specified according to PEP 484, though PEP 484 conformance isn’t required or enforced.
If *args or **kwargs are accepted, they should be listed as
*args
and**kwargs
.The format for a parameter is:
name (type): description The description may span multiple lines. Following lines should be indented. The "(type)" is optional. Multiple paragraphs are supported in parameter descriptions.
Parameters: - param1 (int) – The first parameter.
- param2 (Optional[str]) – The second parameter. Defaults to None. Second line of description should be indented.
- *args – Variable length argument list.
- **kwargs – Arbitrary keyword arguments.
Returns: True if successful, False otherwise.
The return type is optional and may be specified at the beginning of the
Returns
section followed by a colon.The
Returns
section may span multiple lines and paragraphs. Following lines should be indented to match the first line.The
Returns
section supports any reStructuredText formatting, including literal blocks:{ 'param1': param1, 'param2': param2 }
Return type: bool
Raises: AttributeError
– TheRaises
section is a list of all exceptions that are relevant to the interface.ValueError
– If param2 is equal to param1.
-
backend.apidocsample2.
module_level_variable2
= 98765¶ Module level variable documented inline.
The docstring may span multiple lines. The type may optionally be specified on the first line, separated by a colon.
Type: int
Module contents¶
This package is an example Google style docstrings.
Privacy Policy¶
Privacy Policy (for Google OAuth Verification)
version 2021/10/15
This document would thoroughly disclose the manner in which the GGeditor accesses, uses, stores, or shares Google user data. Here, the “Google user data” means the opening Google document which every add-ons of the Google Docs are working with.
How the GGeditor accesses Google user data:The GGeditor is an Add-on for the Google Docs App. When users installed The GGeditor add-on. It is listed on the menu bar by the Google Docs Aoo. The GGeditor works in an environment which is provided and limited by the Add-on feature of the Google Docs. The GGeditor accesses the opening Google document via the Google Docs App.
How the GGeditor uses Google user data:The GGeditor convert content of the opening Google document to reStructuredText format.
How the GGeditor stores Google user data:The GGeditor does not store any content of the opening Google document. The GGeditor only stores users settings via the Google Docs App. Which is provided by the Add-on development API.
How the GGeditor shares Google user data:The GGeditor does not share content of the opening Google document.
The converted reStructuredText content would be pushed to a repository of the Github. That repository is owned by the user, not the GGeditor. Because the repository name, path and credentials for accessing that repository are all given by the user.
Announcements - 2020
Announcements - 2017
- [Jan 29] Tutorial - Create a project site in the RTD
- [Jan 22] 從零開始建立一個RTD文件網站(Mandarin).
- [Jan 15] New Release for multiple accounts and conversion with HTML-table.
GGeditor¶
Italian version by Ciro Spataro
GGeditor hopes to help you to focus on writing your idea instead of marking them up.
GGeditor is a Google Docs Add-on for generating reStructuredText file from the Google Docs. The generated reST file can be committed to the Github repository with the GGeditor. Then, that repository’s documentations hosted by the Readthedocs.org (RTD) got automatically updated.
Note
You don’t need to trigger conversion before committing and downloading, the committing and downloading would do conversion internally at first.
Features¶
- Easy starting for reST beginners, even no idea about reST markups.
- Powered by the Google Docs. Almost what you see is what you get. As well as the coordination of team works.
- One-click to commit to the Github repository.
- Preview the generated reST file and download to local machine.
- Support headings, bold, italic, hyperlink, subscript and superscript.
- Support footnotes, image, list item and table.
- Support full-width characters (CKJ) in headings and table.
- Support internal links to bookmarks, headings and Google Docs native table of contents (in document table of contents).
- Support relative links to other generated reST files of the Google Docs under the same folder and subfolders.
- Support cross-document table of content (.. toctree::) for the RTD.
- Support all style of admonitions of the RTD.
- Support multiple accounts for committing to repositories in different accounts.
- Support converting table with HTML tags to let look-and-feel as the same as possible for blogers.
How to install¶
Click this link to the Google Docs Add-on page, or in a Google Docs Document:
- On the menu item “Add-ons”, click the “Get Add-ons”
- In the search box, input “GGeditor”, then click on the GGeditor icon to install.
How to Use¶
Please refer to this article How to Use
For reStructuredText Beginners¶
If you are a beginner of the reStructuredText and you feel a little bit of confusing about how to put your documents onto the RTD website. I wrote two quick guides to help your task to be quickly completed with the GGeditor.
How to create a generic website of documentation on the RTD
This guide for you to make the 1st copy of your product documents get online.
How to create API document for python modules
This guide for you to make the 1st copy of your module documents get online.
I was struggling on writing reStructuredText for a long time . Now, with the GGeditor and these two tutorials, I hope them can help you to get jobs done quicker and easier.
Acknowledgments¶
- Andrey Rublev as well as all the contributors of the Online reStructuredText editor, it is a great tool for beginner to learn the reST markups.
- Bitwiseshiftleft as well as all the contributors of the sjcl projects. The sjcl.js is used for credentials encryption.
- Neusauber.com. Hard to be briefly described. In short, its excellent AR series let me have time to work on this project.
- Philip Schatz as well as all the contributors of the octokat.js project. The Github-related implementation is on this wonderful tool.
- Pelican project as well as all the contributes. Pelican lead me to the world of markup. The conf.py is borrowed from the pelican’s repository.
- Readthedocs.org (RTD), it provides a great service, which encourage me to create the GGeditor.
Release Notes¶
Jan 15, 2017
New:
- Convert table in HTML tags for preserving background color, column-span, row-span and column width.
- Multiple github accounts
Improved:
- New “Settings” panel for accounts and document options.
- In partial conversion, markups of table will keep the same as it is in whole document conversion.
Dec 27, 2016
Improved:
- Create new file in github failed if the new path has new folder great than 1 level, ex, create docs/blog/technical/how2pythondocs.py in docs/ where blog/technical is not existed yet.
- For In-document TOC, there is no extra empty line between items.
- For partial convsion of selection or table, the conversion dialog would break a line for every 60 characters. It makes content easier to read.
- For simplicity, the “Download” button is hidden in partial conversion except images are included.
- Hyperlink in footnote content is allowed.
- “Add link to another document” only displays items binding to the same repository with current document. And generated path is relative to current document.
Fixed:
- Insert link to another document failed for documents with binding file if the binding path is different document path.
Featured:
- Add directive of “custom admonition”.
- Add directive of “raw HTML”
Limited:
- Internal link to heading does not work. Currently there is no API to identifiy the target heading element. Please use “Bookmark“ instead.
Dec 6, 2016
New
- Support partial conversion for selectd elements and table.
- Same image used multiple times is now only one copy been uploaded.
Improved
- Conversion features has an individual dialog. (improvment)
Fixed
- Downloaded zip file now got file name from binding file. (bug fix)
Appreciation for You¶
It would really help us if you had a second to
that helps us keep momentun on GGeditor.