Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
1.9.0 (UNRELEASED)
==================

- New ``TerminalWriter.write_source`` method that writes highlighted code to the terminal if
``Pygments`` is installed.

1.8.1 (2019-12-27)
==================

Expand Down
13 changes: 13 additions & 0 deletions py/_io/terminalwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,19 @@ def write(self, msg, **kw):
markupmsg = msg
write_out(self._file, markupmsg)

def write_source(self, source):
"""Writes the given source code highlighted"""
if self.hasmarkup:
try:
from pygments.formatters.terminal import TerminalFormatter
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's also 256-color and true color support.. https://github.com/pygments/pygments/blob/master/pygments/formatters/terminal256.py

Something like this could be used for auto-detect, but it should be made configurable probably.

        pygments_formatter_class = "pygments.formatters.TerminalTrueColorFormatter"
        pygments_formatter_kwargs = {"bg": "light", "style": "solarized-light"}

(from my pdbpp config)

from pygments.lexers.python import PythonLexer
from pygments import highlight
except ImportError:
pass
else:
source = highlight(source, PythonLexer(), TerminalFormatter())
self.write(source)

def _update_chars_on_current_line(self, text_or_bytes):
newline = b'\n' if isinstance(text_or_bytes, bytes) else '\n'
current_line = text_or_bytes.rsplit(newline, 1)[-1]
Expand Down
13 changes: 13 additions & 0 deletions testing/io_/test_terminalwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,3 +303,16 @@ def test_should_do_markup_PY_COLORS_eq_0(monkeypatch):
tw.line("hello", bold=True)
s = f.getvalue()
assert s == "hello\n"


@pytest.mark.parametrize('atty', [True, False])
def test_write_source(atty):
f = py.io.TextIO()
f.isatty = lambda: atty
tw = py.io.TerminalWriter(file=f)
tw.write_source("x = 1")
s = f.getvalue()
if atty:
assert s == 'x = \x1b[34m1\x1b[39;49;00m\n'
else:
assert s == "x = 1"
1 change: 1 addition & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ commands=
py.test --confcutdir=. --junitxml={envlogdir}/junit-{envname}.xml []
deps=
attrs
pygments
pytest29: pytest~=2.9.0
pytest30: pytest~=3.0.0
pytest31: pytest~=3.1.0
Expand Down