Skip to content

Commit 55bdfec

Browse files
committed
Improve directive arguments and behavior (#16)
1 parent 80151db commit 55bdfec

File tree

6 files changed

+28
-43
lines changed

6 files changed

+28
-43
lines changed

docs/src/examples.rst

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,6 @@ This was achieved with::
102102
Now all Python code blocks within the same section will be concatenated.
103103
See :ref:`reference` for more information on the exact behavior and options.
104104

105-
.. concat-blocks:: reset
106-
107105
Skipping blocks
108106
---------------
109107
If needed, Python blocks can be skipped, resulting in no links for that block

docs/src/reference.rst

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,6 @@ Configuration
1212
-------------
1313
Available configuration values in ``conf.py``:
1414

15-
- :code:`codeautolink_concat_blocks: str`: Default behavior for code example
16-
concatenation. Concatenated code blocks are treated as a continuous source,
17-
so that imports and statements in previous blocks affect later blocks.
18-
Value must be one of:
19-
20-
- "none" - no concatenation (default)
21-
- "section" - blocks between titles
22-
- "file" - all blocks in the current file
23-
2415
- :code:`codeautolink_autodoc_inject: bool`: Inject a :code:`code-refs` table
2516
to the end of all autodoc definitions. Defaults to :code:`True`.
2617

@@ -34,15 +25,17 @@ rST directives available in Sphinx documentation:
3425
``type`` is "class" by default, which seems to work for other types as well.
3526
The table is removed if it would have no entries or a non-HTML builder is
3627
used.
37-
- :code:`.. concat-blocks:: level`: Toggle literal block concatenation.
28+
- :code:`.. concat-blocks:: [mode]`: Toggle literal block concatenation.
29+
Concatenated code blocks are treated as a continuous source,
30+
so that imports and statements in previous blocks affect later blocks.
3831
Concatenation is begun at the directive, not applied retroactively.
3932
The directive also resets concatenation state.
40-
``level`` must be one of:
33+
``mode``, if specified, must be one of:
4134

42-
- "none" - no concatenation
43-
- "section" - blocks between titles
44-
- "file" - all blocks in the current file
45-
- "reset" - behavior reset to the value set in configuration
35+
- "on" - concatenate all blocks in the current file (default value)
36+
- "off" - no concatenation (default behavior until a :code:`concat-blocks`
37+
directive is encountered)
38+
- "section" - concatenate blocks until the next title
4639

4740
- :code:`.. implicit-import:: code`: Include an implicit import in the next
4841
code block. The next block consumes this directive even if it is not
@@ -55,7 +48,7 @@ rST directives available in Sphinx documentation:
5548
- "next" - next block (default)
5649
- "section" - blocks until the next title
5750
- "file" - all blocks in the current file
58-
- "none" - turn skipping off
51+
- "off" - turn skipping off
5952

6053
If "next" was specified, the following block consumes this directive even if
6154
it is not processed (e.g. non-Python blocks) to avoid placement confusion.

docs/src/release_notes.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ sphinx-codeautolink adheres to
1010

1111
Unreleased
1212
----------
13+
- Improve directive arguments and behavior (:issue:`16`)
1314
- Correctly consume :code:`autolink-skip:: next` (:issue:`17`)
1415

1516
0.1.1 (2021-09-22)

src/sphinx_codeautolink/extension/__init__.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,7 @@ def parse_blocks(self, app, doctree):
6666
if self.do_nothing:
6767
return
6868

69-
visitor = CodeBlockAnalyser(
70-
doctree,
71-
concat_default=app.config.codeautolink_concat_blocks,
72-
source_dir=app.srcdir,
73-
)
69+
visitor = CodeBlockAnalyser(doctree, source_dir=app.srcdir)
7470
doctree.walkabout(visitor)
7571
self.code_refs[visitor.current_document] = visitor.code_refs
7672
self.block_visitors.append(visitor)

src/sphinx_codeautolink/extension/block.py

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ class UserError(Exception):
3333
class CodeBlockAnalyser(nodes.SparseNodeVisitor):
3434
"""Transform literal blocks of Python with links to reference documentation."""
3535

36-
def __init__(self, *args, concat_default: str, source_dir: str, **kwargs):
36+
def __init__(self, *args, source_dir: str, **kwargs):
3737
super().__init__(*args, **kwargs)
3838
self.code_refs = {}
3939
relative_path = Path(self.document['source']).relative_to(source_dir)
@@ -42,26 +42,25 @@ def __init__(self, *args, concat_default: str, source_dir: str, **kwargs):
4242
self.current_refid = None
4343
self.source_transforms: List[SourceTransforms] = []
4444
self.implicit_imports = []
45-
if concat_default not in ('none', 'section', 'file'):
46-
raise UserError(
47-
f'Invalid concatenation default value in "conf.py": `{concat_default}`'
48-
)
49-
self.concat_default = concat_default
50-
self.concat_current = None
45+
self.concat_global = 'off'
46+
self.concat_section = False
5147
self.concat_sources = []
5248
self.autolink_skip = None
5349

5450
def unknown_visit(self, node):
5551
"""Handle and delete custom directives, ignore others."""
5652
if isinstance(node, ConcatBlocksMarker):
57-
if node.level not in ('none', 'section', 'file', 'reset'):
53+
if node.mode not in ('off', 'section', 'on'):
5854
raise UserError(
59-
f'Invalid concatenation argument: `{node.level}` '
55+
f'Invalid concatenation argument: `{node.mode}` '
6056
f'in document "{self.current_document}"'
6157
)
6258

6359
self.concat_sources = []
64-
self.concat_current = node.level if node.level != 'reset' else None
60+
if node.mode == 'section':
61+
self.concat_section = True
62+
else:
63+
self.concat_global = node.mode
6564
node.parent.remove(node)
6665
elif isinstance(node, ImplicitImportMarker):
6766
if '\n' in node.content:
@@ -72,24 +71,22 @@ def unknown_visit(self, node):
7271
self.implicit_imports.append(node.content)
7372
node.parent.remove(node)
7473
elif isinstance(node, AutoLinkSkipMarker):
75-
if node.level not in ('next', 'section', 'file', 'none'):
74+
if node.level not in ('next', 'section', 'file', 'off'):
7675
raise UserError(
7776
f'Invalid skipping argument: `{node.level}` '
7877
f'in document "{self.current_document}"'
7978
)
80-
self.autolink_skip = node.level if node.level != 'none' else None
79+
self.autolink_skip = node.level if node.level != 'off' else None
8180
node.parent.remove(node)
8281

83-
def _concat_mode(self) -> str:
84-
return self.concat_current or self.concat_default
85-
8682
def unknown_departure(self, node):
8783
"""Ignore unknown nodes."""
8884

8985
def visit_title(self, node):
9086
"""Track section names and break concatenation and skipping."""
9187
self.title_stack.append(node.astext())
92-
if self._concat_mode() == 'section':
88+
if self.concat_section:
89+
self.concat_section = False
9390
self.concat_sources = []
9491
if self.autolink_skip == 'section':
9592
self.autolink_skip = None
@@ -142,7 +139,7 @@ def visit_literal_block(self, node: nodes.literal_block):
142139
name.lineno -= hidden_len
143140
name.end_lineno -= hidden_len
144141

145-
if self._concat_mode() != 'none':
142+
if self.concat_section or self.concat_global == 'on':
146143
self.concat_sources.extend(implicit_imports + [source])
147144

148145
transforms = SourceTransforms(source, [])

src/sphinx_codeautolink/extension/directive.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,13 @@ def run(self):
4545
class ConcatBlocksMarker(nodes.Element):
4646
"""Marker for :class:`ConcatBlocks` with attribute :attr:`level`."""
4747

48-
def __init__(self, level: str = None):
48+
def __init__(self, mode: str = None):
4949
super().__init__()
50-
self.level = level
50+
self.mode = mode
5151

5252
def copy(self):
5353
"""Copy element."""
54-
return self.__class__(self.level)
54+
return self.__class__(self.mode)
5555

5656

5757
class ConcatBlocks(Directive):

0 commit comments

Comments
 (0)