Skip to content

Instantly share code, notes, and snippets.

@shimizukawa
Last active October 23, 2018 12:51
Show Gist options
  • Save shimizukawa/e486b01d22fcafd4d57d29e3d429a550 to your computer and use it in GitHub Desktop.
Save shimizukawa/e486b01d22fcafd4d57d29e3d429a550 to your computer and use it in GitHub Desktop.
Sphinx拡張 文字数表示パネル pageinfo.py

pageinfo.py と pageinfo.html を以下のように配置:

sphinx-project/
+- index.rst
+- conf.py
+- ext/pageinfo.py
+- _templates/pageinfo.html

conf.py に設定を追加

import os
import sys
sys.path.insert(0, os.path.abspath('ext'))
extensions = ['pageinfo']
html_sidebars = {
# add 'pageinfo.html' to display the panel.
'**': ['localtoc.html', 'relations.html', 'sourcelink.html', 'pageinfo.html', 'searchbox.html']
}
<div>
<h4>Page Info</h4>
<p>
<ul>
<li>英数記号: {{ ascii_count }}</li>
<li>非アスキー: {{ nonascii_count }}</li>
<li>合計文字数: {{ char_count }}</li>
<li>半角換算: {{ half_char_count }}</li>
<li>全角換算: {{ full_char_count }}</li>
</ul>
</p>
</div>
# -*- coding: utf-8 -*-
from docutils.utils import column_width
from docutils import nodes
DOMAIN_NAME = 'pageinfo'
DEFAULT_PAGEINFO = {
'char_count': 0,
'half_char_count': 0,
'full_char_count': 0,
'ascii_count': 0,
'nonascii_count': 0,
}
def doctree_resolved(app, doctree, docname):
domain_data = app.env.domaindata.setdefault(DOMAIN_NAME, {})
pageinfo = domain_data.setdefault(docname, DEFAULT_PAGEINFO.copy())
for node in doctree.traverse(nodes.Text):
if isinstance(node.parent, nodes.literal_block):
continue # ignore code block
text = node.astext()
for c in text:
if column_width(c) == 1:
pageinfo['ascii_count'] += 1
pageinfo['half_char_count'] += 1
pageinfo['full_char_count'] += 0.5
else:
pageinfo['nonascii_count'] += 1
pageinfo['half_char_count'] += 2
pageinfo['full_char_count'] += 1
pageinfo['char_count'] += len(text)
def html_page_context(app, pagename, templatename, context, doctree):
if pagename:
extras = app.env.domaindata.get(DOMAIN_NAME, {}).get(pagename, {})
context.update(extras)
def setup(app):
app.connect('doctree-resolved', doctree_resolved)
app.connect('html-page-context', html_page_context)
@shimizukawa
Copy link
Author

image

@c-bata
Copy link

c-bata commented Oct 22, 2018

これすごい便利です。ソースコードをカウントするとちょっと長くなりすぎてしまうので docutils.nodes.literal_node を親にもつnodeはskipするようにしてみたら使いやすかったので、コメントしておきます。

def doctree_resolved(app, doctree, docname):
    ...

    for node in doctree.traverse(nodes.Text):
        if isinstance(node.parent, nodes.literal_block):
            continue
        ...

@shimizukawa
Copy link
Author

@c-bata あざっす!取り込みました。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment