From 3ed9c215c286b0aa0066bbd72b914cf9efffe388 Mon Sep 17 00:00:00 2001 From: Christian O'Leary Date: Mon, 25 Aug 2025 12:29:41 +0100 Subject: [PATCH] add support for texttt (monospace) font --- docs/source/changelog.rst | 4 ++++ examples/full.py | 3 ++- pylatex/utils.py | 26 ++++++++++++++++++++++++++ tests/test_args.py | 3 +++ 4 files changed, 35 insertions(+), 1 deletion(-) diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst index 306933d9..af4bb139 100644 --- a/docs/source/changelog.rst +++ b/docs/source/changelog.rst @@ -17,6 +17,10 @@ This version might not be stable, but to install it use:: 1.4.2_ - `docs <../v1.4.2/>`__ - 2023-10-19 ------------------------------------------- +Added +~~~~~ +- Add support for the ``\texttt`` command + Added ~~~~~ - Add `.Chapter` in ``__init__.py`` diff --git a/examples/full.py b/examples/full.py index 06f97264..19054324 100755 --- a/examples/full.py +++ b/examples/full.py @@ -27,7 +27,7 @@ Tabular, TikZ, ) -from pylatex.utils import italic +from pylatex.utils import italic, monospace if __name__ == "__main__": image_filename = os.path.join(os.path.dirname(__file__), "kitten.jpg") @@ -38,6 +38,7 @@ with doc.create(Section("The simple stuff")): doc.append("Some regular text and some") doc.append(italic("italic text. ")) + doc.append(monospace("Even some monospaced (typewriter) text. ")) doc.append("\nAlso some crazy characters: $&#{}") with doc.create(Subsection("Math that is incorrect")): doc.append(Math(data=["2*3", "=", 9])) diff --git a/pylatex/utils.py b/pylatex/utils.py index ee453c85..f1476232 100644 --- a/pylatex/utils.py +++ b/pylatex/utils.py @@ -298,6 +298,32 @@ def italic(s, *, escape=True): return NoEscape(r"\textit{" + s + "}") +def monospace(s, *, escape=True): + r"""Make a string appear monospaced (typewriter) in LaTeX formatting. + monospace() wraps a given string in the LaTeX command \texttt{}. + Args + ---- + s : str + The string to be formatted. + escape: bool + If true the monospace text will be escaped. + Returns + ------- + NoEscape + The formatted string. + Examples + -------- + >>> monospace("hello") + NoEscape(\texttt{hello}) + >>> print(monospace("hello")) + \texttt{hello} + """ + if escape: + s = escape_latex(s) + + return NoEscape(r"\texttt{" + s + "}") + + def verbatim(s, *, delimiter="|"): r"""Make the string verbatim. diff --git a/tests/test_args.py b/tests/test_args.py index 348eb074..79d58c12 100755 --- a/tests/test_args.py +++ b/tests/test_args.py @@ -79,6 +79,7 @@ escape_latex, fix_filename, italic, + monospace, verbatim, ) @@ -493,6 +494,8 @@ def test_utils(): italic(s="") + monospace(s="") + verbatim(s="", delimiter="|")