Skip to content

Commit

Permalink
Merge pull request #1162 from akrabat/highlighting-improvements
Browse files Browse the repository at this point in the history
Make the hl_lines directive work with plain text
  • Loading branch information
lornajane committed Aug 20, 2023
2 parents 347f8d0 + 3e11ec2 commit 334d88b
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 18 deletions.
2 changes: 1 addition & 1 deletion rst2pdf/basenodehandler.py
Expand Up @@ -236,7 +236,7 @@ def getstyle(self, client, node, style):
else:
log.info(
"Unknown class %s, ignoring. [%s]",
n,
node['classes'][n],
nodeid(node),
)
except TypeError: # Happens when a docutils.node.Text reaches here
Expand Down
19 changes: 12 additions & 7 deletions rst2pdf/directives/code_block.py
Expand Up @@ -272,23 +272,28 @@ def code_block_directive(
if hl_lines and lineno not in hl_lines:
cls = "diml"
if withln and "\n" in value:
linenumber_cls = 'linenumber'
if (
hl_lines and (lineno + 1) not in hl_lines
): # use lineno+1 as we're on the previous line when we render the next line number
linenumber_cls = 'pygments-diml'
# Split on the "\n"s
values = value.split("\n")
# The first piece, pass as-is
code_block += nodes.Text(values[0], values[0])
c = ''
if cls != '':
c = 'pygments-diml'
code_block += nodes.inline(values[0], values[0], classes=[c])

# On the second and later pieces, insert \n and linenos
linenos = range(lineno, lineno + len(values))
for chunk, ln in list(zip(values, linenos))[1:]:
if ln <= total_lines:
linenumber_cls = 'linenumber'
c = ''
if hl_lines and (ln) not in hl_lines:
linenumber_cls = 'pygments-diml'
c = 'pygments-diml'

code_block += nodes.inline(
fstr % ln, fstr % ln, classes=[linenumber_cls]
)
code_block += nodes.Text(chunk, chunk)
code_block += nodes.inline(chunk, chunk, classes=[c])
lineno += len(values) - 1

elif cls in unstyled_tokens:
Expand Down
33 changes: 23 additions & 10 deletions tests/input/test_hl_lines.rst
@@ -1,20 +1,33 @@
Highlight lines
---------------

The following code snippet should dim all lines that are not marked with
The following code-blocks should dim all lines that are not marked with
``hl_lines``, and so the effect is to highlight the selected lines

With this block of plain text, lines 1 and 3 are dimmed:

.. code-block:: text
:linenos:
:hl_lines: 2
To be
or not to be
that is the question
For this block of Python, lines 1, 2, 4, 6, 8, 9 and 10 are dimmed:

.. code-block:: python
:linenos:
:hl_lines: 3 5 6
:hl_lines: 3 5 7
number = 0
def f():
a = 1
b = 2
c = 3
d = 4
e = 5
f = 6
g = 7
if number > 0:
print("Positive number")
elif number == 0:
print('Zero')
else:
print('Negative number')
print('This statement is always executed')
Binary file modified tests/reference/test_hl_lines.pdf
Binary file not shown.

0 comments on commit 334d88b

Please sign in to comment.