Skip to content

Commit ed95db2

Browse files
committed
Move dfhack-keybind role to tool_docs.py and call from dfhack-command
1 parent 5ef36d2 commit ed95db2

2 files changed

Lines changed: 67 additions & 66 deletions

File tree

conf.py

Lines changed: 2 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
import sphinx
2222
import sys
2323

24+
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'docs', 'sphinx_extensions'))
25+
from dfhack.util import write_file_if_changed
2426

2527
if os.environ.get('DFHACK_DOCS_BUILD_OFFLINE'):
2628
# block attempted image downloads, particularly for the PDF builder
@@ -38,71 +40,6 @@ def request_disabled(*args, **kwargs):
3840
requests.get = request_disabled
3941

4042

41-
# -- Support :dfhack-keybind:`command` ------------------------------------
42-
# this is a custom directive that pulls info from default keybindings
43-
44-
from docutils import nodes
45-
from docutils.parsers.rst import roles
46-
47-
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'docs', 'sphinx_extensions'))
48-
from dfhack.util import write_file_if_changed
49-
50-
51-
def get_keybinds(root, files, keybindings):
52-
"""Add keybindings in the specified files to the
53-
given keybindings dict.
54-
"""
55-
for file in files:
56-
with open(os.path.join(root, file)) as f:
57-
lines = [l.replace('keybinding add', '').strip() for l in f.readlines()
58-
if l.startswith('keybinding add')]
59-
for k in lines:
60-
first, command = k.split(' ', 1)
61-
bind, context = (first.split('@') + [''])[:2]
62-
if ' ' not in command:
63-
command = command.replace('"', '')
64-
tool = command.split(' ')[0].replace('"', '')
65-
keybindings[tool] = keybindings.get(tool, []) + [
66-
(command, bind.split('-'), context)]
67-
68-
def get_all_keybinds(root_dir):
69-
"""Get the implemented keybinds, and return a dict of
70-
{tool: [(full_command, keybinding, context), ...]}.
71-
"""
72-
keybindings = dict()
73-
for root, _, files in os.walk(root_dir):
74-
get_keybinds(root, files, keybindings)
75-
return keybindings
76-
77-
KEYBINDS = get_all_keybinds('data/init')
78-
79-
80-
# pylint:disable=unused-argument,dangerous-default-value,too-many-arguments
81-
def dfhack_keybind_role_func(role, rawtext, text, lineno, inliner,
82-
options={}, content=[]):
83-
"""Custom role parser for DFHack default keybinds."""
84-
roles.set_classes(options)
85-
if text not in KEYBINDS:
86-
return [], []
87-
newnode = nodes.paragraph()
88-
for cmd, key, ctx in KEYBINDS[text]:
89-
n = nodes.paragraph()
90-
newnode += n
91-
n += nodes.strong('Keybinding:', 'Keybinding:')
92-
n += nodes.inline(' ', ' ')
93-
for k in key:
94-
n += nodes.inline(k, k, classes=['kbd'])
95-
if cmd != text:
96-
n += nodes.inline(' -> ', ' -> ')
97-
n += nodes.literal(cmd, cmd, classes=['guilabel'])
98-
if ctx:
99-
n += nodes.inline(' in ', ' in ')
100-
n += nodes.literal(ctx, ctx)
101-
return [newnode], []
102-
103-
104-
roles.register_canonical_role('dfhack-keybind', dfhack_keybind_role_func)
105-
10643
# -- Autodoc for DFhack plugins and scripts -------------------------------
10744

10845
def doc_dir(dirname, files, prefix):

docs/sphinx_extensions/dfhack/tool_docs.py

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# https://www.sphinx-doc.org/en/master/development/tutorials/recipe.html
44
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#rst-directives
55

6+
import os
67
from typing import List
78

89
import docutils.nodes as nodes
@@ -13,6 +14,63 @@
1314

1415
import dfhack.util
1516

17+
18+
_KEYBINDS = {}
19+
20+
def scan_keybinds(root, files, keybindings):
21+
"""Add keybindings in the specified files to the
22+
given keybindings dict.
23+
"""
24+
for file in files:
25+
with open(os.path.join(root, file)) as f:
26+
lines = [l.replace('keybinding add', '').strip() for l in f.readlines()
27+
if l.startswith('keybinding add')]
28+
for k in lines:
29+
first, command = k.split(' ', 1)
30+
bind, context = (first.split('@') + [''])[:2]
31+
if ' ' not in command:
32+
command = command.replace('"', '')
33+
tool = command.split(' ')[0].replace('"', '')
34+
keybindings[tool] = keybindings.get(tool, []) + [
35+
(command, bind.split('-'), context)]
36+
37+
def scan_all_keybinds(root_dir):
38+
"""Get the implemented keybinds, and return a dict of
39+
{tool: [(full_command, keybinding, context), ...]}.
40+
"""
41+
keybindings = dict()
42+
for root, _, files in os.walk(root_dir):
43+
scan_keybinds(root, files, keybindings)
44+
return keybindings
45+
46+
47+
def render_dfhack_keybind(command) -> List[nodes.paragraph]:
48+
if command not in _KEYBINDS:
49+
return []
50+
newnode = nodes.paragraph()
51+
for keycmd, key, ctx in _KEYBINDS[command]:
52+
n = nodes.paragraph()
53+
newnode += n
54+
n += nodes.strong('Keybinding:', 'Keybinding:')
55+
n += nodes.inline(' ', ' ')
56+
for k in key:
57+
n += nodes.inline(k, k, classes=['kbd'])
58+
if keycmd != command:
59+
n += nodes.inline(' -> ', ' -> ')
60+
n += nodes.literal(keycmd, keycmd, classes=['guilabel'])
61+
if ctx:
62+
n += nodes.inline(' in ', ' in ')
63+
n += nodes.literal(ctx, ctx)
64+
return [newnode]
65+
66+
67+
# pylint:disable=unused-argument,dangerous-default-value,too-many-arguments
68+
def dfhack_keybind_role(role, rawtext, text, lineno, inliner,
69+
options={}, content=[]):
70+
"""Custom role parser for DFHack default keybinds."""
71+
return render_dfhack_keybind(text), []
72+
73+
1674
class DFHackToolDirectiveBase(sphinx.directives.ObjectDescription):
1775
has_content = False
1876
required_arguments = 0
@@ -77,14 +135,20 @@ def run(self):
77135

78136
class DFHackCommandDirective(DFHackToolDirectiveBase):
79137
def render_content(self) -> List[nodes.Node]:
138+
command = self.get_name_or_docname()
80139
return [
81-
self.make_labeled_paragraph('Command', self.get_name_or_docname(), content_class=nodes.literal),
140+
self.make_labeled_paragraph('Command', command, content_class=nodes.literal),
141+
*render_dfhack_keybind(command),
82142
]
83143

84144

85145
def register(app):
86146
app.add_directive('dfhack-tool', DFHackToolDirective)
87147
app.add_directive('dfhack-command', DFHackCommandDirective)
148+
app.add_role('dfhack-keybind', dfhack_keybind_role)
149+
150+
_KEYBINDS.update(scan_all_keybinds(os.path.join(dfhack.util.DFHACK_ROOT, 'data', 'init')))
151+
88152

89153
def setup(app):
90154
app.connect('builder-inited', register)

0 commit comments

Comments
 (0)