xnano.reader
xnano.reader
¶
xnano.reader
Read a file and show it: Markdown, text, JSON, tables, PDFs, images and sounds.
view shows a file. On a terminal it opens a viewer that a person
scrolls, searches and clicks. Without a terminal (a pipe, a file, a test) it prints the
document. xnano FILE on the command line calls it.
from_markdown lays Markdown out as styled text that any
canvas can write.
Functions:
-
from_markdown–Lay Markdown out as styled text, ready to write on a canvas.
-
view–Show a file: in a viewer on a terminal, or printed when there is no terminal.
from_markdown
¶
from_markdown(text: str, *, width: int = DEFAULT_WIDTH, theme: ThemeName | None = None) -> StyledText
Lay Markdown out as styled text, ready to write on a canvas.
Headings, emphasis, code, links, lists, quotes, fenced code and tables keep their look.
The text is wrapped at width cells. An image is named in brackets: to show it, use
view.
Parameters:
-
text(str) –The Markdown source.
-
width(int, default:DEFAULT_WIDTH) –The width to wrap the text at, in cells.
-
theme(ThemeName | None, default:None) –The colors of the text. By default the colors of the terminal. See
ThemeNamefor the themes and their authors.
Returns:
-
StyledText–The styled text, with a newline between two lines.
Raises:
-
ValueError–No theme has the name in
theme.
Examples:
import xnano
text = xnano.from_markdown('# Notes\n\nA **bold** word and `code`.', width=30)
assert str(text).splitlines()[0] == 'Notes'
with xnano.new(width=30, height=4) as canvas:
canvas.write(text)
assert 'A bold word and code.' in canvas.render()
Source code in xnano/reader/__init__.py
def from_markdown(
text: str, *, width: int = DEFAULT_WIDTH, theme: ThemeName | None = None
) -> StyledText:
r"""
Lay Markdown out as styled text, ready to write on a canvas.
Headings, emphasis, code, links, lists, quotes, fenced code and tables keep their look.
The text is wrapped at ``width`` cells. An image is named in brackets: to show it, use
[`view`][xnano.reader.view].
Args:
text: The Markdown source.
width: The width to wrap the text at, in cells.
theme: The colors of the text. By default the colors of the terminal. See
[`ThemeName`][xnano.themes.ThemeName] for the themes and their authors.
Returns:
The styled text, with a newline between two lines.
Raises:
ValueError: No theme has the name in ``theme``.
Examples:
```python
import xnano
text = xnano.from_markdown('# Notes\n\nA **bold** word and `code`.', width=30)
assert str(text).splitlines()[0] == 'Notes'
with xnano.new(width=30, height=4) as canvas:
canvas.write(text)
assert 'A bold word and code.' in canvas.render()
```
"""
chosen = theme_of(theme)
lines = layout_markdown(text, width=width, theme=chosen, directory=None)
spans: list[TextSpan] = []
tables: dict[int, list[str]] = {} # the rows of each table, drawn one time
for index, line in enumerate(lines):
if index:
spans.append(TextSpan('\n'))
spans.extend(TextSpan(run.text, style=chosen.style_of(run)) for run in line.spans)
if line.content is not None:
spans.extend(_content_spans(lines, index, chosen, tables))
return StyledText(spans or [TextSpan('')])
view
¶
view(file: str | PathLike[str], *, interactive: bool | None = None, width: int | None = None, theme: ThemeName | None = None, output: TextIO | None = None) -> None
Show a file: in a viewer on a terminal, or printed when there is no terminal.
The kind of file decides how it is shown. Markdown is laid out with its images, JSON is
indented and colored, comma and tab separated values become a table, a PDF gives its
text, an image is drawn, a sound is played, and any other text is shown with line
numbers. Images need xnano[image], sounds need xnano[audio] and PDFs need
xnano[pdf]. An image or a sound that cannot be shown or played is named in text.
In the viewer, the arrow keys, the wheel and a drag scroll, / finds text, o
lists the headings, r shows the source, a click follows a link, and q leaves.
Every key on the last line of the window is also a button for the mouse.
Parameters:
-
file(str | PathLike[str]) –The path of the file.
-
interactive(bool | None, default:None) –Whether to open the viewer. By default the viewer opens when the program runs on a terminal, and the document is printed otherwise.
-
width(int | None, default:None) –The width of the printed document in cells. By default the width of the terminal, and 80 cells when there is none.
-
theme(ThemeName | None, default:None) –The colors of the document. By default the colors of the terminal. See
ThemeNamefor the themes and their authors. -
output(TextIO | None, default:None) –Where the document is printed. Standard output by default.
Raises:
-
FileNotFoundError–No file exists at the path.
-
IsADirectoryError–The path is a directory.
-
ImportError–The file is a PDF and
pypdfis not installed. -
ValueError–No theme has the name in
theme.
Examples:
import io
import pathlib
import tempfile
import xnano
with tempfile.TemporaryDirectory() as directory:
notes = pathlib.Path(directory) / 'notes.md'
notes.write_text('# Notes\n\n- one\n- two\n')
printed = io.StringIO()
xnano.view(notes, interactive=False, width=20, output=printed)
assert printed.getvalue().splitlines()[0] == 'Notes'
assert '• one' in printed.getvalue()
Source code in xnano/reader/__init__.py
def view(
file: str | os.PathLike[str],
*,
interactive: bool | None = None,
width: int | None = None,
theme: ThemeName | None = None,
output: TextIO | None = None,
) -> None:
r"""
Show a file: in a viewer on a terminal, or printed when there is no terminal.
The kind of file decides how it is shown. Markdown is laid out with its images, JSON is
indented and colored, comma and tab separated values become a table, a PDF gives its
text, an image is drawn, a sound is played, and any other text is shown with line
numbers. Images need ``xnano[image]``, sounds need ``xnano[audio]`` and PDFs need
``xnano[pdf]``. An image or a sound that cannot be shown or played is named in text.
In the viewer, the arrow keys, the wheel and a drag scroll, ``/`` finds text, ``o``
lists the headings, ``r`` shows the source, a click follows a link, and ``q`` leaves.
Every key on the last line of the window is also a button for the mouse.
Args:
file: The path of the file.
interactive: Whether to open the viewer. By default the viewer opens when the
program runs on a terminal, and the document is printed otherwise.
width: The width of the printed document in cells. By default the width of the
terminal, and 80 cells when there is none.
theme: The colors of the document. By default the colors of the terminal. See
[`ThemeName`][xnano.themes.ThemeName] for the themes and their authors.
output: Where the document is printed. Standard output by default.
Raises:
FileNotFoundError: No file exists at the path.
IsADirectoryError: The path is a directory.
ImportError: The file is a PDF and ``pypdf`` is not installed.
ValueError: No theme has the name in ``theme``.
Examples:
```python
import io
import pathlib
import tempfile
import xnano
with tempfile.TemporaryDirectory() as directory:
notes = pathlib.Path(directory) / 'notes.md'
notes.write_text('# Notes\n\n- one\n- two\n')
printed = io.StringIO()
xnano.view(notes, interactive=False, width=20, output=printed)
assert printed.getvalue().splitlines()[0] == 'Notes'
assert '• one' in printed.getvalue()
```
"""
chosen = theme_of(theme)
document = read_document(pathlib.Path(file))
stream = sys.stdout if output is None else output
if interactive is None:
interactive = (
output is None and _is_terminal(sys.stdout) and _is_terminal(sys.stdin)
)
if interactive:
from xnano.reader._viewer import run_viewer
run_viewer(document, chosen)
return
_print(document, stream, width, chosen)