Debian Codegraph @

texmf-dist/doc/lualatex/pyluatex/example/typesetting-minted.tex

raw
1 %% Copyright 2021-2026 Tobias Enderle
2 %%
3 %% This work may be distributed and/or modified under the
4 %% conditions of the LaTeX Project Public License, either version 1.3c
5 %% of this license or (at your option) any later version.
6 %% The latest version of this license is in
7 %% http://www.latex-project.org/lppl.txt
8 %% and version 1.3c or later is part of all distributions of LaTeX
9 %% version 2005/12/01 or later.
10
11 % DESCRIPTION
12 % A detailed example for typesetting code and output with the *minted* package
13
14 \documentclass{article}
15
16 \usepackage{pyluatex}
17 \usepackage{minted}
18
19 \usepackage{luacode}
20 \begin{luacode}
21 function pytypeset()
22 tex.print("\\begin{minted}[bgcolor=gray!10!white]{python}")
23 tex.print(pyluatex.get_last_code())
24 tex.print("\\end{minted}")
25 tex.print("") -- ensure newline
26 end
27
28 function pytypeset_inline()
29 -- assume there is only one line of code in get_last_code()
30 tex.print("\\mintinline{python}@" .. pyluatex.get_last_code()[1] .. "@")
31 end
32 \end{luacode}
33
34 \newcommand*{\pytypeset}{%
35 \noindent\textbf{Input:}
36 \directlua{pytypeset()}
37 \textbf{Output:}
38 \begin{center}
39 \directlua{tex.print(pyluatex.get_last_output())}
40 \end{center}
41 }
42 \newcommand*{\coderaw}{\directlua{tex.print(pyluatex.get_last_code())}}
43 \newcommand*{\codeinline}{\directlua{pytypeset_inline()}}
44 \newcommand*{\outputraw}{\directlua{tex.print(pyluatex.get_last_output())}}
45
46 \begin{document}
47
48 \section*{Typesetting of Code Blocks and Output}
49 \begin{python}[q]
50 msg = 'Hello'
51
52 print(msg)
53 \end{python}
54 \pytypeset
55
56 \section*{Typesetting of Inline Code and Output}
57 Calling \pyc[q]{print('test', end='')}\codeinline\ in Python outputs ``\outputraw''.
58
59 \begin{python}
60 x = 4
61 \end{python}
62 The value of \py[q]{x}\codeinline\ is \outputraw.
63
64 The result of \py[q]{17 + 300}$\coderaw$ is \outputraw.
65
66 \section*{Custom Environments}
67 You can create a custom environment for typesetting:
68
69 \NewDocumentEnvironment{typesetpython}{}
70 {\PyLTVerbatimEnv\begin{python}[q]}
71 {\end{python}\pytypeset}
72
73 \begin{typesetpython}
74 msg = 'Custom environment'
75
76 print(msg)
77 \end{typesetpython}
78
79 \end{document}