July 13, 2010
XMLの論考: reStructuredText

ツリー指向の処理

reStructuredText文書は、DOMのような仕方で操作できるノードのツリーに変換できます。以下は、リスト2 で示したreST PEPの例を使用する例です。


リスト5. reSTノード・ツリーの作成
>>> txt = open('pep.txt').read() >>> def rst2tree(txt): ...     import docutils.parsers.rst ...     parser = docutils.parsers.rst.Parser() ...     document = docutils.utils.new_document("test") ...     document.settings.tab_width = 4 ...     document.settings.pep_references = 1 ...     document.settings.rfc_references = 1 ...     parser.parse(txt, document) ...     return document ... >>> doc = rst2tree(txt) >>> doc.children [<section "abstract": <title...><paragraph...><paragraph...>, <section "references & footnotes": <title...> <target "frungible doodads"...><footnote "pep9 ...>] >>> print doc.autofootnotes [<footnote "pep9876": <paragraph...>, <footnote: <paragraph...>] >>> print doc.autofootnotes[0].rawsource PEP 9876, Let's Hope We Never Get Here

DOMと対比して注目できる点は、reStructuredTextはすでに固定された文書方言であるということです。したがって、汎用のメソッドを使用して一致するノードを検索する代わりに、意味に応じた名前を持つ属性を使用してノードを検索できます。.children 属性は一般に階層型ですが、ほとんどの属性は特定のタイプのノードを収集します。

via ibm.com

Posted via email from 原宿工業大学 | Comment »

May 31, 2010
はやわかり reStructuredText

(詳細)

reStructuredText には、表(テーブル)を記述する2通りの記法があります。 グリッドテーブルは良く出来ていますが作成が若干大変です。 シンプルテーブルは作成しやすいですが、(列の結合ができないなど) 機能が制限されます。

プレーンテキスト 変換結果の例

グリッドテーブル

+——————+——————+—————-+
| Header 1   | Header 2   | Header 3  |
+============+============+===========+
| body row 1 | column 2   | column 3  |
+——————+——————+—————-+
| body row 2 | Cells may span columns.|
+——————+——————+—————-+
| body row 3 | Cells may  | - Cells   |
+——————+ span rows. | - contain |
| body row 4 |            | - blocks. |
+——————+——————+—————-+

グリッドテーブル

Header 1 Header 2 Header 3
body row 1 column 2 column 3
body row 2 Cells may span columns.
body row 3 Cells may
span rows.
  • Cells
  • contain
  • blocks.
body row 4

シンプルテーブル

=====  =====  ======
   Inputs     Output
——————  ———
  A      B    A or B
=====  =====  ======
False  False  False
True   False  True
False  True   True
True   True   True
=====  =====  ======

シンプルテーブル

Inputs Output
A B A or B
False False False
True False True
False True True
True True True

Posted via web from 原宿工業大学 | Comment »

March 11, 2010
rst2a - reStructuredText to Anything

February 23, 2010
rst2pdf: 簡単なドキュメントだったらJPGの添付はできた

Sphinxプロジェクト準備

(social)hdknr@deblen2010:~/.ve/social/src/testdoc$ sphinx-quickstart

source/conf.py 編集

(social)hdknr@deblen2010:~/.ve/social/src/testdoc$ vi source/conf.py
extensions = extensions + [‘sphinx.ext.graphviz’,’rst2pdf.pdfbuilder’]
pdf_documents = [
    (‘index’, u’social_media_tech’, u’Social Media Technology’, u’hdknr.com’),
]
pdf_stylesheets = [‘sphinx’,’kerning’,’a4’,’ja’]
pdf_extensions = [‘vectorpdf’]
default_dpi=94
font_path=”/usr/share/fonts/truetype/”とりあえず、default_dpi=94 を入れてみる。

スタイルシート

(social)hdknr@deblen2010:~/.ve/social/src/testdoc$ more ja.json
{
  “styles” : [
    [“base” , {
      “wordWrap”: “CJK”
    }]
  ]
}

MakefileにPDF追加

(social)hdknr@deblen2010:~/.ve/social/src/testdoc$ tail Makefile
doctest:
        $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
        @echo "Testing of doctests in the sources finished, look at the " \
              "results in $(BUILDDIR)/doctest/output.txt."
pdf:
        $(SPHINXBUILD) -b pdf $(ALLSPHINXOPTS) $(BUILDDIR)/pdf
        @echo
        @echo "Build finished. The PDF files are in $(BUILDDIR)/pdf."

source/index.rst だけ編集

(social)hdknr@deblen2010:~/.ve/social/src/testdoc$ vi source/index.rst
Welcome to test's documentation!
================================
Contents:
.. toctree::
   :maxdepth: 2

.. image:: facebook_try.JPG

ビルド

(social)hdknr@deblen2010:~/.ve/social/src/testdoc$ make pdf
sphinx-build -b pdf -d build/doctrees   source build/pdf
Running Sphinx v0.6.4
loading pickled environment... done
building [pdf]: targets for 1 source files that are out of date
updating environment: 0 added, 0 changed, 0 removed
looking for now-outdated files... none found
processing social_media_tech... index
resolving references...
done
writing social_media_tech... [WARNING] image.py:338 Using image /home/hdknr/.ve/social/src/testdoc/source/facebook_try.JPG without specifying size.Calculating based on image size at 96dpi [near line UNKNOWN in file UNKNOWN]
[WARNING] image.py:399 image /home/hdknr/.ve/social/src/testdoc/source/facebook_try.JPG is too wide for the frame, rescaling
done
build succeeded.
Build finished. The PDF files are in build/pdf.

表示

 

Posted via email from 原宿工業大学 | Comment »

February 19, 2010
Django: templateにreStructuredTextを流し込む

django.contrib.markup で使えるmarkup


hdknr@deblen:~/.ve/djtweet/src/djcube/www/website$ grep def ../../../../lib/python2.5/site-packages/django/contrib/markup/templatetags/marku
def textile(value):
def markdown(value, arg=”):
def restructuredtext(value):

使えるマークアップ確認

»> import markdown
Traceback (most recent call last):
  File “<input>”, line 1, in <module>
ImportError: No module named markdown
»> import textile
Traceback (most recent call last):
  File “<input>”, line 1, in <module>
ImportError: No module named textile
»> from docutils.core import publish_parts
»>
»>

このvirtualenvではReSTのみ。

settings.pyに設定

INSTALLED_APPS = (
    ‘django.contrib.auth’,
    ‘django.contrib.contenttypes’,
    ‘django.contrib.sessions’,
    ‘django.contrib.sites’,
    ‘django.contrib.admin’,  #HDKNR
    ‘django.contrib.markup’,  #HDKNR

試しにファイルを用意する

Sequence
========

1. (Guest) Submit form on a landing page.
————————————————————- Browser post(get) form to following URL ::

 http://{{cname}}/{{app}}/promocode/{{promotion_name}}/?code={{promotion_code}} 2. (Promo) Process the request
———————————————-

 2.1.  Search djcube.models.Promotion with {{promotion_name}} => `pr`.
 2.2.  Search djcube.models.PromotionCode with `pr` and {{promotion_code}}.
 2.3.  Insert a djcube.models.PromotionEntry.      2.3.1. md5 for UserAgent should be set to `ua`
   2.3.2. Insert djcube.models.UserAgent with `ua` if not exists.

 2.4.  Update jcube.models.PromotionCode with incremented `current`.
 2.4.  Set-Cookie       ‘p’  : djcube.models.Promotion.digest
    ‘e’  : djcube.models.PromotionEntry.digest

 2.5.  Execute  {{ djcube.models.Promotion.ptype }}.py main()    2.5.1. finally return 302 and proper URL 

testビューを用意

views.pyと同じディレクトリにreadme.rst を用意 from django.conf.urls.defaults import *
from django import template
from django.http import HttpResponse
import os

def test(request):
    page = “”” {% load markup %}
    <html>
    <body>
        {{ readme|restructuredtext}}
    </body>
    </html>
“”“
    ctx = {
        ‘readme’:  open(os.path.join( os.path.dirname(os.path.abspath(__file__)),’readme.rst’)).read(),
    }
    return HttpResponse( template.Template( page ).render( template.Context(ctx)))

表示

Posted via email from hdknr’s posterous | Comment »

December 17, 2009
Off : Draft/reStructuredText

Include Directive

外部ファイルをインクルードする。 自分で定義したファイルと docutils のソースについてくるファイルでは書き方が少し違う。

自分のファイルをインクルードしたい場合。

$ head /home/hoge/www/pyblosxom/include/icon/icon_mini.inc    .. |AKU| image:: http://log-rotation.jp/pyblosxom/images/mini/AKU.png  :alt: AKU.png  .. |ATARASII| image:: http://log-rotation.jp/pyblosxom/images/mini/ATARASII.png  :alt: ATARASII.png  .. |AWARE| image:: http://log-rotation.jp/pyblosxom/images/mini/AWARE.png  :alt: AWARE.png  .. |AYAMARI| image:: http://log-rotation.jp/pyblosxom/images/mini/AYAMARI.png  :alt: AYAMARI.png  .. |BIKKURI| image:: http://log-rotation.jp/pyblosxom/images/mini/BIKKURI.png  :alt: BIKKURI.png  .  .  

こんなファイルを用意しておき、reStructuredText ファイルでインクルードして使う。

.. include:: /home/hoge/www/pyblosxom/include/icon/icon_mini.inc    |AKU| |ATARASII| |AWARE| |AYAMARI| |BIKKURI|  

こういう風に表示される。

AKU.pngATARASII.pngAWARE.pngAYAMARI.pngBIKKURI.png

Docutils についてくるファイルをインクルードする場合。

$ head local/lib/python/docutils/parsers/rst/include/isobox.txt    .. This data file has been placed in the public domain.  .. Derived from the Unicode character mappings available from  <http://www.w3.org/2003/entities/xml/>.  Processed by unicode2rstsubs.py, part of Docutils:  <http://docutils.sourceforge.net>.    .. |boxDL| unicode:: U+02557 .. BOX DRAWINGS DOUBLE DOWN AND LEFT  .. |boxDl| unicode:: U+02556 .. BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE  .. |boxdL| unicode:: U+02555 .. BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE  .. |boxdl| unicode:: U+02510 .. BOX DRAWINGS LIGHT DOWN AND LEFT    .  .    .. include:: <isobox.txt>    |boxDL| |boxDl| |boxdL| |boxdl|  
. Processed by unicode2rstsubs.py, part of Docutils: . —>

こういう風に表示される。

╗ ╖ ╕ ┐

インクルードディレクトリは知ってるんだな。

Posted via web from hdknr’s posterous | Comment »

December 14, 2009
Pygments — Python syntax highlighter

From Pygments 0.9, the directive is shipped in the distribution as external/rst-directive.py. You can copy and adapt this code to your liking.

Posted via web from hdknr’s posterous | Comment »