版權聲明

所有的部落格文章都可以在右邊[blog文章原始檔案]下載最原始的文字檔案,並依你高興使用 docutil 工具轉換成任何對應的格式方便離線閱覽,除了集結成書販賣歡迎任意取用,引用
顯示具有 restructuredtext 標籤的文章。 顯示所有文章
顯示具有 restructuredtext 標籤的文章。 顯示所有文章

Blogger auto poster

Blogger auto poster

長久以來都是笨笨的在 Blogger 提共的難用編輯視窗

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiVEcvMTVprz0vPwM1WKjlD35zdywRuojiKFcLE8serJYxs5KaHfAplzxKgSdVbZ0LDFhFrpXifvlDFOVUmXGSna9MPsA9kl5ZRXIc0DpiPNxem0BpF98gCA2mm8zju3S_RxTlM7DJMu1h/圖片%201.png

每次分享有關程式的文章,想要有漂亮的語法高亮度(syntax highligh)簡直要我的命,要先找個可以幫我把程式碼上色的東西 然後想辦法貼近我的文章中,非常討厭。

後來在 python 的世界裡面發現了 reStructruedText 這個神奇的玩意,他可以依據內定的簡單直覺規則將文字檔轉成 html 檔案, 這對我來說可是不得了得大躍進,再也不用忍受 Blogger 那一點都不好用的編輯視窗了,超爽!

玩了幾天後還是很懷念程式碼語法上色,當然 python 無所不包,一定有相關的module [1] 可以使用,果然讓我找到一個可以說 一勞永逸的解法 pygments ,幾乎檯面上超過一萬人使用過的程式語言或是 script 都有支援到~還不斷更新中,十分了不起, 因此我的 Blog 生活更開心了,可以產生有上色的程式碼就是炫!感覺就是專業!!現在我只要很簡單的打 rest 格式的內容,然後 用 rst2htmlc.py 轉成 html 在用瀏覽器打開,在複製貼上到 blogger 提共 的難用編輯視窗中即可...

說真的,這樣的確可以有美美的code syntax highlight,但好像很笨耶。

[1]module 把他想像成 C++ 世界的 Library 就好了,雖然差有點多...

環境建立

當然,我不是一個抱怨就可以貼一篇文章的人,當然有好方法提共才敢大聲,在 進入重點之前先把待會教學中必要的條件在這邊說明一下。

1. python os上最起碼要有 python 2.4 以上的版本,我自己是使用 python 2.5 至於更高級的版本等他 Third party library 都ok才考慮使用,所以沒有 測試過,不過應該可以使用 2to3 工具來簡單轉換,畢竟我也寫不出什麼超級 複雜的程式。

2. 不一定要裝,不過建議安裝一下 easy_install (python 方便的安裝 工具)。

3. BeautifulSoup 這套 Third party library ,很簡單拉就像裝一般 python library 一樣執行 setup.py install就好了(linux/osx 前面加 sudo)。

4. pygments 這是用來將 source code 作語法高亮度的library,可以到我 替 rst2htmlc.py 作的頁面看效果。

5. docutils 如果有安裝 easy_install 那就輸入 easy_install doctuils ,就會自行安裝了,不然請到連結處下載。

6. rst2htmlc.py 將這個檔案拷貝到執行目錄下面,並記得將權限設定可以 執行。

linux/osx 使用者無腦指令:

$sudo mv ./rst2htmlc.py /usr/local/bin
$chmod +x /usr/local/bin/rst2htmlc.py

Windows 的使用者可以參考 this 讓 windows command line 可以直接執行 python script。

7. post2blogger 小弟寫的懶人 post 程式,請自行修改下面程式碼,由於 牽扯到帳號密碼,所以自己改吧,也千萬拜託不要較我幫你改。

acc = 'xxx@gmail.com'  #你的 blogger 帳號
password = 'xxxxxx'     # 你的 blogger 密碼
name = 'your name'       # 你的作者名稱

都用好了就可以測試看看,打一篇符合reStructruedText 格式的文件,然後將 post2blogger.py 放到同一個目錄下面輸入下面的命令(xxxxx 是你的檔案名稱)

$ post2blogger.py xxxxx

rst2htmlc.py

#!/usr/bin/python

# Author: Chris Liechti
# Contact: cliechti@gmx.net
# Revision: $Revision$
# Date: $Date$
# 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

import pygments
from pygments.lexers import get_lexer_by_name
from pygments.formatters import get_formatter_by_name
from docutils.parsers import rst
from docutils import nodes
from docutils.writers.html4css1 import Writer, HTMLTranslator

class DocorateHeadHTMLTranslator(HTMLTranslator):
    _classText = "docutils"

    def __init__(self, document):
        HTMLTranslator.__init__(self,document)
        self.head_suffix = ['','','','']
        self.body_prefix = []
        self.body_suffix = []
        self.stylesheet = []

    def visit_document(self, node):
        self.head.append('<h1 class="%s" >%s</h1>\n'
                         % (self._classText, self.encode(node.get('title', ''))))

    def visit_title(self, node):
        """Only 6 section levels are supported by HTML."""
        check_id = 0
        close_tag = '</p>\n'
        if isinstance(node.parent, nodes.topic):
            self.body.append(
                  self.starttag(node, 'p', '', CLASS='topic-title first'))
        elif isinstance(node.parent, nodes.sidebar):
            self.body.append(
                  self.starttag(node, 'p', '', CLASS='sidebar-title'))
        elif isinstance(node.parent, nodes.Admonition):
            self.body.append(
                  self.starttag(node, 'p', '', CLASS='admonition-title'))
        elif isinstance(node.parent, nodes.table):
            self.body.append(
                  self.starttag(node, 'caption', ''))
            close_tag = '</caption>\n'
        elif isinstance(node.parent, nodes.document):
            self.body.append(self.starttag(node, 'h1', '', CLASS=self._classText))
            close_tag = '</h1>\n'
            self.in_document_title = len(self.body)
        else:
            assert isinstance(node.parent, nodes.section)
            h_level = self.section_level + self.initial_header_level - 1
            atts = {}
            if (len(node.parent) >= 2 and
                isinstance(node.parent[1], nodes.subtitle)):
                atts['CLASS'] = 'with-subtitle'
            atts['CLASS'] = self._classText
            self.body.append(
                  self.starttag(node, 'h%s' % h_level, '', **atts))
            atts = {}
            if node.hasattr('refid'):
                atts['class'] = 'toc-backref'
                atts['href'] = '#' + node['refid']
            if atts:
                self.body.append(self.starttag({}, 'a', '', **atts))
                close_tag = '</a></h%s>\n' % (h_level)
            else:
                close_tag = '</h%s>\n' % (h_level)
        self.context.append(close_tag)

    def visit_subtitle(self, node):
        if isinstance(node.parent, nodes.sidebar):
            self.body.append(self.starttag(node, 'p', '',
                                           CLASS='sidebar-subtitle'))
            self.context.append('</p>\n')
        elif isinstance(node.parent, nodes.document):
            self.body.append(self.starttag(node, 'h2', '', CLASS=self._classText))
            self.context.append('</h2>\n')
            self.in_document_title = len(self.body)
        elif isinstance(node.parent, nodes.section):
            tag = 'h%s' % (self.section_level + self.initial_header_level - 1)
            self.body.append(
                self.starttag(node, tag, '', CLASS=self._classText) +
                self.starttag({}, 'span', '', CLASS=self._classText))
            self.context.append('</span></%s>\n' % tag)


_w = Writer()
_w.translator_class = DocorateHeadHTMLTranslator

def code_formatter(language, content):
    lexer = get_lexer_by_name(language)
    formatter = get_formatter_by_name('html', noclasses=True)
    html = pygments.highlight(content, lexer, formatter)
    return nodes.raw('', html, format='html')

def code_role(name, rawtext, text, lineno, inliner, options={},
              content=[]):
    language = options.get('language')
    if not language:
        args  = text.split(':', 1)
        language = args[0]
        if len(args) == 2:
            text = args[1]
        else:
            text = ''
    reference = code_formatter(language, text)
    return [reference], []

def code_block(name, arguments, options, content, lineno,
               content_offset, block_text, state, state_machine):
    """
    Create a code-block directive for docutils.

    Usage: .. code-block:: language

    If the language can be syntax highlighted it will be.
    """
    language = arguments[0]
    text = '\n'.join(content)
    reference = code_formatter(language, text)
    return [reference]

# These are documented
# at http://docutils.sourceforge.net/spec/howto/rst-directives.html.
code_block.arguments = (
    1, # Number of required arguments.
    0, # Number of optional arguments.
    0) # True if final argument may contain whitespace.

# A mapping from option name to conversion function.
code_role.options = code_block.options = {
    'language' :
    rst.directives.unchanged # Return the text argument, unchanged
}
code_block.content = 1 # True if content is allowed.
# Register the directive with docutils.
rst.directives.register_directive('code-block', code_block)
rst.roles.register_local_role('code-block', code_role)


from docutils.core import publish_cmdline, default_description

description = ('Generates HTML documents from standalone '
               'reStructuredText sources.  ' + default_description)

#publish_cmdline(writer_name='html', description=description)
publish_cmdline(writer=_w , description=description)

Docutils configure

docutils 設定資料

Configuration Files

doctuils [1] 可以把設定寫成一個設定檔案,然後讓所有的 Front-End Tools 自動遵循設定檔 的規範,設定檔涵蓋所有內建的預設值,和命列列的選項,有三個預設的設定檔:

  1. /etc/docutils.conf: 全系統共用的設定檔。
  2. ./docutils.conf: 目前目錄的設定檔,可以想像成專案使用的設定檔。
  3. ~/.docutils: 使用者等級的設定檔。

使用順序依序為: 使用者等級 -> 目前目錄等級 -> 全系統。

設定檔語法

首先,預設開啟檔案的編碼為utf-8,為了不要要的困擾建議設定檔使用utf-8編碼。

設定檔由數個 section 組成,每個 section 開始那列都是 [section] ,然後接一連串 "name:value" 的設定值(也可以寫成 name=value)。

每一列開頭為"#"或";"(井號或分號)代表註解,程式會忽略他。

Example:

# 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

General Setting

footnote_backlinks

允許 footnote 可以連回引用處 (citation),預設為 Enable.

generator

在文件的註腳加入 "Generated by Docutils" ,預設為 off. Options [2]:--generator, -g, --no-generator .
record_dependencies
輸出 dependen file list 到指定的檔案。 Default: None. Option: --record-dependencies=<file>.
report_level
Verbosity threshold at or above which system messages are reported. Default: warning (2). Options: --report, -r, --verbose, -v, --quiet, -q.
sectnum_xform
Enable or disable the section numbering transform (docutils.transforms.parts.SectNum). Default: enabled (1). Options: --section-numbering, --no-section-numbering.
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.
[1]reStructuredText front-end tools.
[2]command line options

Emacs rst-mode

安裝

  • rst.el 另存新檔rst.el到emacs的收尋路徑
  • 在.emacs中加入
(require 'rst)
(setq auto-mode-alist
(append '(("\\.txt$" . rst-mode)
      ("\\.rst$" . rst-mode)
      ("\\.rest$" . rst-mode)) auto-mode-alist))

Local variables

假如 (set enable-local-variables t) 將下面敘述放在第一行可以觸發rst mode

.. _*_ mode: rst -*-

或是下面放檔案最後

..
Local Variables:
mode: rst
End:

Section 快捷

在title下面輸入C-- or C-=:

Title1
^^

查看目前Section hierarchy:

M-x rst-display-decorations-hierarchy [C-c C-h]

Move to pre section:

M-x rst-backward-section [C-c C-p]

Move to next section:

M-x rst-forward-indented-block [C-c C-n]

Mark section:

M-x rst-mark-section [C-c C-m]

Config

Indent設定:

(setq rst-default-indent 4)

Block

先mark要作用的區域

智慧右移:

M-x rst-shift-region-right [C-c C-r]

智慧左移:

M-x rst-shift-region-left [C-c C-l]

自動bullet list:

M-x rst-enumerate-region [C-c C-e]

Line Block:

Apples
Oranges
Bananas

M-x rst-toggle-line-block [C-c C-d]::

| Apples
| Oranges
| Bananas

Compile

M-x rst-compile [C-c 1]

Related Posts with Thumbnails