Debian Codegraph @

texmf-dist/source/luatex/chickenize/chickenize.dtx

raw
1 % \iffalse
2 %<*driver>
3 %% File: chickenize.dtx by Arno Trautmann, mail: arno dot trautmann at gmx dot de
4 \iffalse
5 %</driver>
6 %<*readme>
7 The package chickenize provides several commands and Lua functions to manipulate the input or output tokens of any Lua(La)TeX document. It serves mostly educational and playful usage, but some functions may be used in serious documents.
8
9 To produce the package files, run lualatex on chickinize.dtx, wich should result in the creation of the following files:
10 chickenize.pdf (documentation)
11 chickenize.tex (plainTeX user interface)
12 chickenize.sty (LaTeX user interface)
13 chickenize.lua (Lua package code) [does the actual work]
14
15 You need an up-to-date TeX Live (2020, if possible) to use this package. Maybe a full MiKTeX will also work. (Not tested!) Lua\TeX > 1.0.4 is required for some features since the corresponding syntax has changed; tested with Lua\TeX 1.12.0 (TeX Live 2020)
16
17 For any comments or suggestions, contact me:
18 arno dot trautmann at gmx dot de
19
20 Hope you have fun with this package!
21
22 This package is copyright © 2021 Arno L. Trautmann. It may be distributed and/or
23 modified under the conditions of the LaTeX Project Public License, either version 1.3c
24 of this license or (at your option) any later version. This work has the LPPL mainten-
25 ance status ‘maintained’.
26 %</readme>
27 %<*driver>
28 \fi
29 \def\nameofplainTeX{plain}
30 \ifx\fmtname\nameofplainTeX\else
31 \expandafter\begingroup
32 \fi
33 \input docstrip.tex
34 \keepsilent
35 \let\MetaPrefix\relax
36 \preamble
37
38 EXPERIMENTAL CODE
39
40 This package is copyright © 2021 Arno L. Trautmann. It may be distributed and/or
41 modified under the conditions of the LaTeX Project Public License, either version 1.3c
42 of this license or (at your option) any later version. This work has the LPPL mainten-
43 ance status ‘maintained’.
44 \endpreamble
45 \let\MetaPrefix\DoubleperCent
46 \postamble
47 \endpostamble
48 \askforoverwritefalse
49
50 \generate{\file{chickenize.sty}{\from{chickenize.dtx}{package}}}
51 \generate{\file{chickenize.tex}{\from{chickenize.dtx}{tex}}}
52 \def\MetaPrefix{-- }
53 \def\luapostamble{%
54 \MetaPrefix^^J%
55 \MetaPrefix\space End of File `\outFileName'.%
56 }
57 \def\currentpostamble{\luapostamble}%
58
59 \generate{\file{chickenize.lua}{\from{chickenize.dtx}{lua}}}
60 \nopreamble\nopostamble
61 \catcode`\@12
62
63 \generate{\file{README.md}{\from{chickenize.dtx}{readme}}}
64
65
66 \ifx\fmtname\nameofplainTeX
67 \expandafter\endbatchfile
68 \else
69 \expandafter\endgroup
70 \fi
71 \documentclass[11pt,english]{ltxdoc}
72 \usepackage{
73 array,
74 babel,
75 booktabs,
76 fontspec,
77 geometry,
78 graphicx,
79 hyperref,
80 longtable,
81 microtype,
82 scrlayer-scrpage,
83 tabu,
84 xcolor
85 }
86 \hypersetup{
87 colorlinks=true,
88 linkcolor=blue,
89 filecolor=blue,
90 urlcolor=blue
91 }
92
93 \cfoot{chicken \pagemark}
94 \ohead{}
95 \pagestyle{scrheadings}
96 \setmainfont{Linux Libertine O}
97 \setsansfont{Linux Biolinum O}
98 \newfontfamily\XITS{XITS}
99 \newfontfamily\TGChorus{TeX Gyre Chorus}
100
101 \usepackage{chickenize}
102 \chickenizesetup{
103 rainbow_step=0.3
104 }
105
106 \begin{document}
107 {\hspace*{-2cm}{\scalebox{.2}{\drawchicken\hspace*{20cm}\reflectbox{\chickenizesetup{drawwidth=5}\drawunicorn}}
108 \hfill\hfill \parbox{6.3cm}{{\TGChorus{\Large »\,}\large The Monty Pythons, were they \TeX~users,\\\hspace*{.2em} could have written the chickenize macro.{\Large \textit «}}\\[1ex]
109 \hspace*{4cm}\small Paul Isambert}\kern-2.5cm
110 }
111
112 \begin{center}
113 \rainbowcolor
114 \fontsize{55}{0}\selectfont \fontspec[Letters=Random]{Punk Nova}
115 chickenize
116 \end{center}
117
118 \unrainbowcolor
119
120 \centerline{v0.3}
121 \centerline{\hspace*{2cm} Arno L. Trautmann {\Large \ALT}}
122 \centerline{\href{mailto:[email protected]}{[email protected]}}
123
124 \kern.5cm
125 \textcolor{blue}{\Large How to read this document.}
126
127 This is the documentation of the package |chickenize|. It allows manipulations of any Lua\TeX\ document\footnote{The code is based on pure Lua\TeX\ features, so don't even try to use it with any other \TeX\ flavour. The package is (partially) tested under plain Lua\TeX\ and (fully) under Lua\LaTeX. If you tried using it with Con\TeX t, please share your experience, I will gladly try to make it compatible!} exploiting the possibilities offered by the callbacks that influence line breaking (and~some other stuff). Most of this package's content is just for fun and educational use, but there are also some functions that can be useful in a normal production document.
128
129 The table on the next page shortly informs you about some of your possibilities and provides links to the (documented) Lua functions. The \TeX\ interface is presented \hyperlink{texinterface}{below}.
130
131 The documentation of this package is far from being well-readable, consistent or even complete. This is caused either by lack of time or priority. If you miss anything that should be documented or if you have suggestions on how to increase the readability of the descriptions, please let me know.
132
133 For a better understanding of what's going on in the code of this package, there is a small \hyperlink{tutorial}{tutorial} below that explains shortly the most important features used here.
134
135 \emph{Attention}: This package is under development and everything presented here might be subject to incompatible changes. If, by any reason, you decide to use this package for an important document, please make a local copy of the source code and use that. This package will only be considered stable and long-term compatible should it reach version 1.0.
136
137 If you have any suggestions or comments, just drop me a mail, I’ll be happy to get any response! The latet source code is hosted on github: \url{https://github.com/alt/chickenize}. Feel free to comment or report bugs there, to fork, pull, etc.
138
139 \vfill
140
141 \small\noindent
142 \fbox{\parbox{.97\textwidth}{
143 This package is copyright © 2021 Arno L. Trautmann. It may be distributed and/or
144 modified under the conditions of the LaTeX Project Public License, either version 1.3c
145 of this license or (at your option) any later version. This work has the LPPL maintenance status ‘maintained’.}}
146 \vspace*{1cm}
147
148 \newpage
149
150 \section*{\rainbowcolor For the Impatient:}
151
152 \unrainbowcolor
153 A small and incomplete overview of the functionalities offered by this package.\footnote{If you notice that something is missing, please help me improving the documentation!} Of course, the label “complete nonsense” depends on what you are doing … The links will take you to the source code, while a more complete list with explanations is given \hyperlink{texinterface}{further below}.
154
155 \noindent
156 \tabulinesep=.5ex
157 \begin{longtabu} to .95\textwidth [c]{lX[j]}
158 \hbox to 0cm{\bfseries \hspace*{2cm} maybe useful functions}\\
159 \cmidrule(lr){1-2}
160 \hyperref[sec:colorstretch]{colorstretch} & shows grey boxes that visualise the badness and font expansion line-wise\\
161 \hyperref[sec:letterspaceadjust]{letterspaceadjust} & improves the greyness by using a small amount of letterspacing\\
162 \hyperref[sec:substitutewords]{substitutewords} & replaces words by other words (chosen by the user)\\
163 \hyperref[sec:variantjustification]{variantjustification} & Justification by using glyph variants\\
164 \hyperref[sec:suppressonecharbreak]{suppressonecharbreak} & suppresses linebreaks after single-letter words\\
165 \addlinespace\addlinespace
166 \hbox to 0cm{\bfseries \hspace*{2cm} less useful functions} \\
167 \cmidrule(lr){1-2}
168 \hyperref[sec:boustrophedon]{boustrophedon} & invert every second line in the style of archaic greek texts\\
169 \hyperref[sec:countglyphs]{countglyphs} & counts the number of glyphs in the whole document\\
170 \hyperref[sec:countwords]{countwords} & counts the number of words in the whole document\\
171 \hyperref[sec:leetspeak]{leetspeak} & translates the (latin-based) input into 1337 5p34k\\
172 \hyperref[sec:medievalumlaut]{medievalumlaut} & \medievalumlaut changes each umlaut to normal glyph plus “e” above it: äöü\\
173 \hyperref[sec:randomuclc]{randomuclc} & \unmedievalumlaut alternates randomly between uppercase and lowercase\\
174 \hyperref[sec:randomrainbowcolor]{rainbowcolor} & changes the color of letters slowly according to a rainbow\\
175 \hyperref[sec:randomrainbowcolor]{randomcolor} & prints every letter in a random color\\
176 \hyperref[sec:tabularasa]{tabularasa} & removes every glyph from the output and leaves an empty document\\
177 \hyperref[sec:uppercasecolor]{uppercasecolor} & makes every uppercase letter colored\\
178 \addlinespace\addlinespace
179 \hbox to 0cm{\bfseries \hspace*{2cm} complete nonsense} \\
180 \cmidrule(lr){1-2}
181 \hyperref[sec:chickenize]{chickenize} & replaces every word with “chicken” (or user-adjustable words)\\
182 \hyperref[sec:drawchicken]{drawchicken} & draws a nice chicken with random, “hand-sketch”-type lines\\
183 \hyperref[sec:drawcov]{drawcov} & draws a corona virus\\
184 \hyperref[sec:drawchicken]{drawhorse} & draws a horse\\
185 \hyperref[sec:guttenbergenize]{guttenbergenize} & deletes every quote and footnotes\\
186 \hyperref[sec:hammertime]{hammertime} & U can't touch this!\\
187 \hyperref[sec:italianize]{italianize} & Mamma mia!! \\
188 \hyperref[sec:italianizerandwords]{italianizerandwords} & Will put the word order in a sentence at random. (tbi)\\
189 \hyperref[sec:kernmanipulate]{kernmanipulate} & manipulates the kerning (tbi)\\
190 \hyperref[sec:matrixize]{matrixize} & replaces every glyph by its ASCII value in binary code\\
191 \hyperref[sec:randomerror]{randomerror} & just throws random (La)\TeX\ errors at random times (tbi)\\
192 \hyperref[sec:randomfonts]{randomfonts} & changes the font randomly between every letter\\
193 \hyperref[sec:randomchars]{randomchars} & randomizes the (letters of the) whole input\\
194 \bottomrule
195 \end{longtabu}
196
197 \newpage
198 \tableofcontents
199 \newpage
200 \part{User Documentation}
201 \section{How It Works}
202 We make use of Lua\TeX s callbacks, especially the |pre_line|\-|break_filter| and the |post_line|\-|break_filter|. Hooking a function into these, we can nearly arbitrarily change the content of the document. If the changes should be on the input-side (e.\,g.~replacing words with |chicken|), one can use the |pre_linebreak_filter|. However, changes like inserting color are best made after the linebreak is finalized, so |post_linebreak_filter| is to be preferred for such things.
203
204 All functions traverse the node list of a paragraph and manipulate the nodes' properties (like |.font| or |.char|) or insert nodes (like color push/pop nodes) and return this changed node list.
205
206 \hypertarget{texinterface}{}
207 \section{Commands – How You Can Use It}
208 There are several ways to make use of the \emph{chickenize} package – you can either stay on the \TeX\ side or use the Lua functions directly. In fact, the \TeX\ macros are in most cases simple wrappers around the functions.
209
210 \subsection{\TeX\ Commands – Document Wide}
211 You have a number of commands at your hand, each of which does some manipulation of the input or output. In fact, the code is simple and straightforward, but be careful, especially when combining things. Apply features step by step so your brain won't be damaged …
212
213 The effect of the commands can be influenced, not with arguments, but only via the |\chickenizesetup| described \hyperlink{adjustment}{below}. The links provide here will bring you to the more relevant part of the implementation, i.\,e.~either the \TeX\ code or the Lua code, depending on what is doing the main job. Mostly it's the Lua part.
214
215 \begin{description}
216 \def\command#1{\item[{\hyperref[sec:#1]{\textbackslash #1}}]}
217
218 \command{allownumberincommands} Normally, you cannot use numbers as part of a control sequence (or, command) name. This makes perfect sense and is good as it is. However, just to raise awareness to this, we provide a command here that changes the chategory codes of numbers 0–9 to 11, i.\,e.~normal character. So they \emph{can} be used in command names. However, this will break many packages, so do \emph{not} expect anything to work! At least use it \emph{after} all packages are loaded.
219 \command{boustrophedon} Reverts every second line. This immitates archaic greek writings where one line was right-to-left, the next one left-to-right etc.\footnote{\url{en.wikipedia.org/wiki/Boustrophedon}} Interestingly, also every glyph was adaptet to the writing direction, so all glyphs are inverted in the right-to-left lines. Actually, there are two versions of this command that differ in their implementation: |\boustrophedon| rotates the whole line, while |\boustrophedonglyphs| changes the writing direction and reverses glyph-wise. The second one takes much more compilation time, but may be more reliable. A Rongorongo\footnote{\url{en.wikipedia.org/wiki/Rongorongo}} similar style boustrophedon is available with |\boustrophedoninverse| or |\rongorongonize|, where subsequent lines are rotated by 180° instead of mirrored.
220 \command{countglyphs} \textcolor{blue}{\texttt{\textbackslash countwords}} Counts every printed character (or word, respectively) that appears in anything that is a paragraph. Which is quite everything, in fact, \emph{exept} math mode! The total number of glyphs/words will be printed at the end of the log file/console output. For glyphs, also the number of use for every letter is printed separately.
221 \command{chickenize} Replaces every word of the input with the word “chicken”. Maybe sometime the replacement will be made configurable, but up to now, it's only chicken. To be a bit less static, about every 10\textsuperscript{th} chicken is uppercase. However, the beginning of a sentence is not recognized automatically.\footnote{If you have a nice implementation idea, I'd love to include this!}
222 \command{drawchicken} Draws a chicken based on some low-level lua drawing code. Each stroke is parameterized with random numbers so the chicken will always look different.
223 \command{colorstretch} Inspired by Paul Isambert's code, this command prints boxes instead of lines. The greyness of the first (left-hand) box corresponds to the badness of the line, i.\,e. it is a measure for how much the space between words has been extended to get proper paragraph justification. The second box on the right-hand side shows the amount of stretching/shrinking when font expansion is used. Together, the greyness of both boxes indicate how well the greyness is distributed over the typeset page.
224 \command{dubstepize} wub wub wub wub wub BROOOOOAR WOBBBWOBBWOBB BZZZRRRRRRROOOOOOAAAAA … (inspired by \url{http://www.youtube.com/watch?v=ZFQ5EpO7iHk} and \url{http://www.youtube.com/watch?v=nGxpSsbodnw})
225 \command{dubstepenize} synomym for |\dubstepize| as I am not sure what is the better name. Both macros are just a special case of |chickenize| with a very special “zoo” … there is no |\undubstepize| – once you go dubstep, you cannot go back …
226 \command{explainbackslashes} A small list that gives hints on how many |\| characters you actually need for a backslash. I's supposed to be funny. At least my head thinks it's funny. Inspired (and mostly copied from, actually) xkcd.
227 \command{gameofchicken} This is a temptative implementation of Conway's classic Game of Life. This is actually a rather powerful code with some choices for you. The game itself is played on a matrix in Lua and can be output either on the console (for quick checks) or in a pdf. The latter case needs a LaTeX document, and the packages |geometry|, |placeat|, and |graphicx|. You can choose which \LaTeX\ code represents the cells or you take the pre-defined – a \kern-1.5em\raisebox{.75ex}{\scalebox{0.075}{\drawchicken}}\kern2.5em , of course! Additionally, there are |anticells| which is basically just a second set of cells. However, they can interact, and you have full control over the rules, i.\,e.~how many neighbors a cell or anticell may need to be born, die, or stay alive, and what happens if cell and anticell collide. See below for parameters; all of them start with GOC for clarity.
228 \command{gameoflife} Try it.
229 \command{hammertime} STOP! —— Hammertime!
230 \command{leetspeak} Translates the input into 1337 speak. If you don't understand that, lern it, n00b.
231 \command{matrixize} Replaces every glyph by a binary representation of its ASCII value.
232 \command{medievalumlaut} Changes every lowercase umlaut into the corresponding vocale glyph with a small “e” glyph above it to show the origins of the german umlauts coming from ae, oe, ue. Text-variant may follow.
233 \command{nyanize} A synonym for |rainbowcolor|.
234 \command{randomerror} Just throws a random \TeX\ or \LaTeX\ error at a random time during the compilation. I have quite no idea what this could be used for.
235 \command{randomuclc} Changes every character of the input into its uppercase or lowercase variant. Well, guess what the “random” means …
236 \command{randomfonts} Changes the font randomly for every character. If no parameters are given, all fonts that have been loaded are used, especially including math fonts.
237 \command{randomcolor} Does what its name says.
238 \command{rainbowcolor} Instead of random colors, this command causes the text color to change gradually according to the colors of a rainbow. Do not mix this with |randomcolor|, as that doesn't make any sense.
239 \command{relationship} Draws the relationship. A ship made of relations.
240 \command{pancakenize} This is a dummy command that does nothing. However, every time you use it, you owe a pancake to the package author. You can either send it via mail or bring it to some (local) \TeX\ user's group meeting.
241 \command{substitutewords} You have to specify pairs of words by using |\addtosubstitutions{word1}{word2}|. Then call |\substitutewords| (or the other way round, doesn't matter) and each occurance of |word1| will be replaced by |word2|. You can add replacement pairs by repeated calls to |\addtosubstitutions|. Take care! This function works with the input stream directly, therefore it does \emph{not} work on text that is inserted by macros, but it \emph{will} work on macro names itself! This way, you may use it to change macros (or environments) at will. Bug or feature? I'm not sure right now …
242 \command{suppressonecharbreak} \TeX~normally does not suppress a linebreak after words with only one character (“I“, “a” etc.) This command suppresses line breaks. It is very similar to the code provided by the |impnattypo| package and based on the same ideas. However, the code in |chickenize| has been written before the author knew |impnattypo|, and the code differs a bit, might even be a bit faster. Well, test it!
243 \command{tabularasa} Takes every glyph out of the document and replaces it by empty space of the same width. That could be useful if you want to hide some part of a text or similar. The |\text|-version is most likely more useful.
244 \command{uppercasecolor} Makes every uppercase character in the input colored. At the moment, the color is randomized over the full rgb scale, but that will be adjustable once options are well implemented.
245 \command{variantjustification} For special document types, it might be mandatory to have a fixed interword space. If you still want to have a justified type area, there must be another kind of stretchable material – one version realized by this command is using wide variants of glyphs to fill the remaining space. As the glyph substitution takes place randomly, this does \emph{not} provide the optimum justification, as this would take up much computation power.
246 \end{description}
247
248 \subsection{How to Deactivate It}
249 Every command has a |\un|-version that deactivates it's functionality. So once you used |\chickenize|, it will chickenize the whole document up to |\unchickenize|. However, the paragraph in which |\unchickenize| appears, will \emph{not} be chickenized. The same is true for all other manipulations. Take care that you don't |\un|-anything bevor activating it, as this will result in an error.\footnote{Which is so far not catchable due to missing functionality in luatexbase.}
250
251 If you want to manipulate only a part of a paragraph, you will have to use the corresponding |\text|-version of the function, see below. However, feel free to set and unset every function at will at any place in your document.
252
253 \subsection{\texttt{\textbackslash text}-Versions}
254 The functions provided by this package might be much more useful if applied only to a short sequence of words or single words instead of the whole document or paragraph. Therefore, most of the above-mentioned commands have\footnote{If they don't have, I did miss that, sorry. Please inform me about such cases.} a |\text|-version that takes an argument. |\textrandomcolor{foo}| results in a colored |foo| while the rest of the document remains unaffected. However, to achieve this effect, still the whole node list has to be traversed. Thus, it may slow down the compilation of your document, even if you use |\textrandomcolor| only once. Fortunately, the effect is very small and mostly negligible.\footnote{On a 500 pages text-only \LaTeX\ document the dilation is on the order of 10\% with |textrandomcolor|, but other manipulations can take much more time. However, you are not supposed to make such long documents with |chickenize|!}
255
256 Please don't fool around by mixing a |\text|-version with the non-|\text|-version. If you feel like it and are not pleased with the result, it is up to \emph{you} to provide a stable and working solution.
257
258 \subsection{Lua functions}
259 As all features are implemented on the Lua side, you can use these functions independently. If you do so, please consult the corresponding subsections in the \hyperlink{sec:luamodule}{implementation} part, because there are some variables that can be adapted to your need.
260
261 You can use the following code inside a |\directlua| statement or in a |luacode| environment (or the corresponding thing in your format):
262 \begin{verbatim}
263 luatexbase.add_to_callback("pre_linebreak_filter",chickenize,"chickenize")
264 \end{verbatim}
265 Replace |pre| by |post| to register into the post linebreak filter. The second argument (here: |chickenize|) specifies the function name; the available functions are listed below. You can supply a label as you like in the third argument. The fourth and last argument, which is omitted in the example, determines the order in which the functions in the callback are used. If you have no fancy stuff going on, you can safely use |1|.
266
267 \hypertarget{adjustment}{}
268 \section{Options – How to Adjust It}
269 There are several ways to change the behaviour of |chickenize| and its macros. Most of the options are Lua variables and can be set using |\chickenizesetup|. But be \emph{careful!} The argument of |\chickenizesetup| is passed directly to Lua, therefore you are \emph{not} using a comma-separated key-value list, but uncorrelated Lua commands. The argument must have the syntax |{randomfontslower = 1| |randomfontsupper = 0}| instead of |{randomfontslower = 1,| |randomfontsupper = 0}|. Alright?
270
271 However, |\chickenizesetup| is a macro on the \TeX\ side meaning that you can use \emph{only} |%| as comment string. If you use |--|, all of the argument will be ignored as \TeX\ does not pass an eol to |\directlua|. If you don't understand that, just ignore it and go on as usual.
272
273 The following list tries to kind of keep track of the options and variables. There is no guarantee for completeness, and if you find something that is missing or doesn't work as described here, please inform me!
274
275 \def\arg#1{\textcolor{red}{\ttfamily <#1>}}
276 \def\opt#1{\textcolor{blue}{\ttfamily #1}}
277 \def\default#1{\textcolor{black}{\ttfamily #1}}
278 \begin{description}
279 \item[\opt{randomfontslower}, \opt{randomfontsupper} = \arg{int}] These two integer variables determine the span of fonts used for the font randomization. Just play around with them a bit to find out what they are doing.
280 \subsection{options for chickenization}
281 \item[\opt{chickenstring} = \arg{table}] The string that is printed when using |\chickenize|. In fact, |chickenstring| is a table which allows for some more random action. To specify the default string, say |chickenstring[1] = 'chicken'|. For more than one animal, just step the index:\\
282 |chickenstring[2] = 'rabbit'|. All existing table entries will be used randomly. Remember that we are dealing with Lua strings here, so use |' '| to mark them. (|" "| can cause problems with |babel|.)
283 \item[\opt{chickenizefraction} = \arg{float} \default{1}] Gives the fraction of words that get replaced by the |chickenstring|. The default means that every word is substituted. However, with a value of, say, |0.0001|, only one word in ten thousand will be |chickenstring|. |chickenizefraction| must be specified \emph{after} |\begin{document}|. No idea, why …
284 \item[\opt{chickencount} = \arg{bool} \default{true}] Activates the counting of substituted words and prints the number at the end of the terminal output.
285 \item[\opt{colorstretchnumbers} = \arg{bool} \default{false}] If true, the amount of stretching or shrinking of each line is printed into the margin as a green, red or black number.
286 \item[\opt{chickenkernamount} = \arg{int}] The amount the kerning is set to when using |\kernmanipulate|.
287 \item[\opt{chickenkerninvert} = \arg{bool}] If set to true, the kerning is inverted (to be used with |\kernmanipulate|.
288 \item[\opt{drawwidth} = \arg{float} \default{1}] Defines the widths of the sloppy drawings of chickens, horses, etc.
289 \item[\opt{leettable} = \arg{table}] From this table, the substitution for 1337 is taken. If you want to add or change an entry, you have to provide the unicode numbers of the characters, e.\,g. |leettable[101] = 50| replaces every |e| (|101|) with the number |3| (|50|).
290 \item[\opt{uclcratio} = \arg{float} \default{0.5}] Gives the fraction of uppercases to lowercases in the |\randomuclc| mode. A higher number (up to 1) gives more uppercase letters. Guess what a lower number does.
291 \item[\opt{randomcolor\_grey} = \arg{bool} \default{false}] For a printer-friendly version, this offers a grey scale instead of an rgb value for |\randomcolor|.
292 \item[\opt{rainbow\_step} = \arg{float} \default{0.005}] This indicates the relative change of color using the rainbow functionality. A value of |1| changes the color in one step from red to yellow, while a value of |0.005| takes 200 letters for the transition to be completed. Useful values are below |0.05|, but it depends on the amount of text. The longer the text and the lower the |step|, the nicer your rainbow will be.
293 \item[\opt{Rgb\_lower}, \opt{rGb\_upper} = \arg{int}] To specify the color space that is used for |\randomcolor|, you can specify six values, the upper and lower value for each color. The uppercase letter in the variable denotes the color, so |rGb_upper| gives the upper value for green etc. Possible values are between |1| and |254|. If you enter anything outside this range, your PDF will become invalid and break. For grey scale, use |grey_lower| and |grey_upper|, with values between |0| (black) and |1000| (white), included. Default is |0| to |900| to prevent white letters.
294 \item[\opt{keeptext} = \arg{bool} \default{false}] This is for the |\colorstretch| command. If set to |true|, the text of your document will be kept. This way, it is easier to identify bad lines and the reason for the badness.
295 \item[\opt{colorexpansion} = \arg{bool} \default{true}] If |true|, two bars are shown of which the second one denotes the font expansion. Only useful if font expansion is used. (You \emph{do} use font expansion, don’t you?)
296 \end{description}
297
298 \subsection{Options for Game of Chicken}
299 This deserves a separate section since there are some more options and they need some explanation. So here goes the parameters for the GOC:
300 \begin{description}
301 \item[\opt{GOCrule\_live} = \arg{\{int,int,...\}} \default{\{2,3\}}] This gives the number of neighbors for an existing cell to keep it alive. This is a list, so you can say |\chickenizesetup{GOCrule_live = {2,3,7}| or similar.
302 \item[\opt{GOCrule\_spawn} = \arg{\{int,int,...\}} \default{\{3\}}] The number of neighbors to spawn a new cell.
303 \item[\opt{GOCrule\_antilive} = \arg{int} \default{2,3}] The number of neighbors to keep an anticell alive.
304 \item[\opt{GOCrule\_antispawn} = \arg{int} \default{3}] The number of neighbors to spawn a new anticell.
305 \item[\opt{GOCcellcode} = \arg{string} \default {"\\scalebox\{0.03\}\{\\drawchicken\}"}] The \LaTeX\ code for graphical representation of a living cell. You can use basically any valid \LaTeX\ code in here. A chicken is the default, of course.
306 \item[\opt{GOCanticellcode} = \arg{string} \default {"O"}] The \LaTeX\ code for graphical representation of a living anticell.
307 \item[\opt{GOCx} = \arg{int} \default{100}] Grid size in |x| direction (vertical).
308 \item[\opt{GOCy} = \arg{int} \default{100}] Grid size in |y| direction (horizontal).
309 \item[\opt{GOCiter} = \arg{int} \default{150}] Number of iterations to run the game.
310 \item[\opt{GOC\_console} = \arg{bool} \default{false}] Activate output on the console.
311 \item[\opt{GOC\_pdf} = \arg{bool} \default{true}] Activate output in the pdf.
312 \item[\opt{GOCsleep} = \arg{int} \default{0}] Wait after one cycle of the game. This helps especially on the console, or for debugging. By dafault no wait time is added.
313 \item[\opt{GOCmakegif} = \arg{bool} \default{false}] Produce a gif. This requires the command line tool |convert| since I use it for the creation. If you have troubles with this feel free to contact me.
314 \item[\opt{GOCdensity} = \arg{int} \default{100}] Defines the density of the gif export. 100 is quite dense and it might take quite some time to get your gif done.
315 \end{description}
316 I recommend to use the |\gameofchicken| with a code roughly like this:
317 \begin{verbatim}
318 \documentclass{scrartcl}
319 \usepackage{chickenize}
320 \usepackage[paperwidth=10cm,paperheight=10cm,margin=5mm]{geometry}
321 \usepackage{graphicx}
322 \usepackage{placeat}
323 \placeatsetup{final}
324 \begin{document}
325 \gameofchicken{GOCiter=50}
326 %\gameofchicken{GOCiter=50 GOCmakegif = true}
327 % \directlua{ os.execute("gwenview test.gif")} % substitute your filename
328 \end{document}
329 \end{verbatim}
330 Keep in mind that for convenience |\gameofchicken{}| has one argument which is equivalent to using |\chickenizesetup{}| and actually just executes the argument as Lua code …
331
332 \clearpage
333 \part[Tutorial]{Tutorial\hypertarget{tutorial}}
334 I thought it might be helpful to add a small tutorial to this package as it is mainly written with instructional purposes in mind. However, the following is \emph{not} intended as a comprehensive guide to Lua\TeX\. It's just to get an idea how things work here. For a deeper understanding of Lua\TeX\ you should consult both the Lua\TeX\ manual and some introduction into Lua proper like “Programming in Lua“. (See the section \hyperref[sec:literature]{Literature} at the end of the manual.)
335
336 \section{Lua code}
337 The crucial novelty in Lua\TeX\ is the first part of its name: The programming language Lua. One can use nearly any Lua code inside the commands |\directlua{}| or |\latelua{}|. This alleviates simple tasks like calculating a number and printing it, just as if it was entered by hand:
338 \begin{verbatim}
339 \directlua{
340 a = 5*2
341 tex.print(a)
342 }
343 \end{verbatim}
344 A number of additions to the Lua language renders it particularly suitable for \TeX ing, especially the |tex.| library that offers access to \TeX\ internals. In the simple example above, the function |tex.print()| inserts its argument into the \TeX\ input stream, so the result of the calcuation (10) is printed in the document.
345
346 Larger parts of Lua code should not be embedded in your \TeX\ code, but rather in a separate file. It can then be loaded using
347 \begin{verbatim}
348 \directlua{dofile("filename")}
349 \end{verbatim}
350
351 If you use Lua\LaTeX, you can also use the |luacode| environment from the eponymous package.
352
353 \section{callbacks}
354 While Lua code can be inserted using |\directlua| at any point in the input, a very powerful concept allows to change the way \TeX\ behaves: The \emph{callbacks}. A callback is a point where you can hook into \TeX's working and do anything to it that may make sense – or not. (Thus maybe breaking your document completely …)
355
356 Callbacks are employed at several stages of \TeX's work – e.\,g. for font loading, paragraph breaking, shipping out etc. In this package, we make heavy use of mostly two callbacks: The |pre_linebreak_filter| and the |post_linebreak| filter. These callbacks are called just before (or after, resp.) \TeX\ breaks a paragraph into lines. Normally, these callbacks are empty, so they are a great playground. In between these callbacks, the |linebreak_filter| takes care of \TeX's line breaking mechanism. We won't touch this as I have no idea of what's going on there ;)
357
358 \section{How to use a callback}
359 The normal way to use a callback is to “register” a function in it. This way, the function is called each time the callback is executed. Typically, the function takes a node list (see below) as an argument, does something with it, and returns it. So a basic use of the |post_linebreak_filter| would look like:
360
361 \begin{verbatim}
362 function my_filter(head)
363 return head
364 end
365
366 callback.register("post_linebreak_filter",my_filter)
367 \end{verbatim}
368 The function |callback.register| takes the name of the callback and your new function. However, there are some reasons why we avoid this syntax here. Instead, we rely on the function |luatexbase.add_to_callback|. This is provided by the \LaTeX\ kernel table |luatexbase| which was initially a package by Manuel Pégourié-Gonnard and Élie Roux.\footnote{Since the late 2015 release of \LaTeX, the package has not to be loaded anymore since the functionality is absorbed by the kernel. Plain\TeX~users can load the |ltluatex| file which provides the needed functionality.} This function has a more extended syntax:
369 \begin{verbatim}
370 luatexbase.add_to_callback("post_linebreak_filter",my_filter,"a fancy new filter")
371 \end{verbatim}
372 The third argument is a name you can (have to) give to your function in the callback. That is necessary because the package also allows for removing functions from callbacks, and then you need a unique identifier for the function:
373 \begin{verbatim}
374 luatexbase.remove_from_callback("post_linebreak_filter","a fancy new filter")
375 \end{verbatim}
376
377 You have to consult the Lua\TeX\ manual to see what functionality a callback has when executed, what arguments it expects and what return values have to be given.
378
379 Everything I have written here is not the complete truth – please consult the Lua\TeX\ manual and the |luatexbase| section in the \LaTeX\ kernel documentation for details!
380
381 \section{Nodes}
382 Essentially everything that Lua\TeX\ deals with are nodes – letters, spaces, colors, rules etc. In this package, we make heavy use of different types of nodes, so an understanding of the concept is crucial for the functionality.
383
384 A node is an object that has different properties, depending on its type which is stored in its |.id| field. For example, a node of type |glyph| has |id| 27 (up to Lua\TeX~0.80, it was 37) has a number |.char| that represents its unicode codepoint, a |.font| entry that determines the font used for this glyph, a |.height|, |.depth| and |.width| etc.
385
386 Also, a node typically has a non-empty field |.next| and |.prev|. In a list, these point to the – guess it – next or previous node. Using this, one can walk over a list of nodes step by step and manipulate the list.
387
388 A more convenient way to adress each node of a list is the function |node.traverse(head)| which takes as first argument the first node of the list. However, often one wants to adress only a certain type of nodes in a list – e.\,g. all glyphs in a vertical list that also contains glue, rules etc. This is achieved by calling the function |node.traverse_id(GLYPH,head)|, with the first argument giving the respective id of the nodes.\footnote{GLYPH here stands for the id that the glyph node type has. This number can be achieved by calling |GLYPH = nodeid("glyph")| which will result in the correct number independent of the Lua\TeX~version. We will use this substitute throughout this docmuent.}
389
390 The following example removes all characters “e” from the input just before paragraph breaking. This might not make any sense, but it is a good example anyways:
391 \begin{verbatim}
392 function remove_e(head)
393 for n in node.traverse_id(GLYPH,head) do
394 if n.char == 101 then
395 node.remove(head,n)
396 end
397 end
398 return head
399 end
400
401 luatexbase.add_to_callback("pre_linebreak_filter",remove_e,"remove all letters e")
402 \end{verbatim}
403
404 Now, don't read on, but try out this code by yourself! Change the number of the character to be removed, try to play around a bit. Also, try to remove the spaces between words. Those are glue nodes – look up their id in the Lua\TeX\ manual! Then, you have to remove the |if n.char| condition on the third line of the listing, because glue nodes lack a |.char| field. If everything works, you should have an input consisting of only one long word. Congratulations!
405
406 The |pre_linebreak_filter| is especially easy because its argument (here called |head|) is just one horizontal list. For the |post_linebreak_filter|, one has to traverse a whole vertical stack of horizontal lists, vertical glue and other material. See some of the functions below to understand what is necessary in this more complicated case.
407
408 \section{Other things}
409 Lua is a very intuitive and simple language, but nonetheless powerful. Just two tips: use local variables if possible – your code will be much faster. For this reason we prefer synonyms like |nodetraverseid = node.traverse_id| instead of the original names.
410
411 Also, Lua is kind of built around tables. Everything is best done with tables!
412
413 The namespace of the chickenize package is \emph{not} consistent. Please don't take anything here as an example for good Lua coding, for good \TeX ing or even for good Lua\TeX ing. It's not. For high quality code check out the code written by Hans Hagen or other professionals. Once you understand the package at hand, you should be ready to go on and improve your knowledge. After that, you might come back and help me improve this package – I'm always happy for any help ☺
414
415 \DocInput{chickenize.dtx}
416 \end{document}
417 %</driver>
418 %<*tex>
419 % \fi
420 % \clearpage
421 %\part{Implementation}
422 %\label{sec:implementation}
423 %\section{\TeX\ file}
424 % This file is more-or-less a dummy file to offer a nice interface for the functions. Basically, every macro registers a function of the same name in the corresponding callback. The |un|-macros later remove these functions. Where it makes sense, there are |text|-variants that activate the function only in a certain area of the text, by means of Lua\TeX's attributes.
425 %
426 % For (un)registering, we use the |luatexbase| \LaTeX\ kernel functionality. Then, the |.lua| file is loaded which does the actual work. Finally, the \TeX\ macros are defined as simple |\directlua| calls.
427 %
428 % The Lua file is not found by using a simple |dofile("chickenize.lua")| call, but we have to use kpse's |find_file|.
429 % \begin{macrocode}
430 \directlua{dofile(kpse.find_file("chickenize.lua"))}
431
432 \def\ALT{%
433 \bgroup%
434 \fontspec{Latin Modern Sans}%
435 A%
436 \kern-.375em \raisebox{.65ex}{\scalebox{0.3}{L}}%
437 \kern.03em \raisebox{-.99ex}{T}%
438 \egroup%
439 }
440 % \end{macrocode}
441 % \subsection{allownumberincommands}\label{sec:allownumberincommands}
442 % \begin{macrocode}
443 \def\allownumberincommands{
444 \catcode`\0=11
445 \catcode`\1=11
446 \catcode`\2=11
447 \catcode`\3=11
448 \catcode`\4=11
449 \catcode`\5=11
450 \catcode`\6=11
451 \catcode`\7=11
452 \catcode`\8=11
453 \catcode`\9=11
454 }
455
456 \def\BEClerize{
457 \chickenize
458 \directlua{
459 chickenstring[1] = "noise noise"
460 chickenstring[2] = "atom noise"
461 chickenstring[3] = "shot noise"
462 chickenstring[4] = "photon noise"
463 chickenstring[5] = "camera noise"
464 chickenstring[6] = "noising noise"
465 chickenstring[7] = "thermal noise"
466 chickenstring[8] = "electronic noise"
467 chickenstring[9] = "spin noise"
468 chickenstring[10] = "electron noise"
469 chickenstring[11] = "Bogoliubov noise"
470 chickenstring[12] = "white noise"
471 chickenstring[13] = "brown noise"
472 chickenstring[14] = "pink noise"
473 chickenstring[15] = "bloch sphere"
474 chickenstring[16] = "atom shot noise"
475 chickenstring[17] = "nature physics"
476 }
477 }
478
479 \def\boustrophedon{
480 \directlua{luatexbase.add_to_callback("post_linebreak_filter",boustrophedon,"boustrophedon")}}
481 \def\unboustrophedon{
482 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","boustrophedon")}}
483
484 \def\boustrophedonglyphs{
485 \directlua{luatexbase.add_to_callback("post_linebreak_filter",boustrophedon_glyphs,"boustrophedon_glyphs")}}
486 \def\unboustrophedonglyphs{
487 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","boustrophedon_glyphs")}}
488
489 \def\boustrophedoninverse{
490 \directlua{luatexbase.add_to_callback("post_linebreak_filter",boustrophedon_inverse,"boustrophedon_inverse")}}
491 \def\unboustrophedoninverse{
492 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","boustrophedon_inverse")}}
493
494 \def\bubblesort{
495 \directlua{luatexbase.add_to_callback("post_linebreak_filter",bubblesort,"bubblesort")}}
496 \def\unbubblesort{
497 \directlua{luatexbase.remove_from_callback("bubblesort","bubblesort")}}
498
499 \def\chickenize{
500 \directlua{luatexbase.add_to_callback("pre_linebreak_filter",chickenize,"chickenize")
501 luatexbase.add_to_callback("start_page_number",
502 function() texio.write("["..status.total_pages) end ,"cstartpage")
503 luatexbase.add_to_callback("stop_page_number",
504 function() texio.write(" chickens]") end,"cstoppage")
505 luatexbase.add_to_callback("stop_run",nicetext,"a nice text")
506 }
507 }
508 \def\unchickenize{
509 \directlua{luatexbase.remove_from_callback("pre_linebreak_filter","chickenize")
510 luatexbase.remove_from_callback("start_page_number","cstartpage")
511 luatexbase.remove_from_callback("stop_page_number","cstoppage")}}
512
513 \def\coffeestainize{ %% to be implemented.
514 \directlua{}}
515 \def\uncoffeestainize{
516 \directlua{}}
517
518 \def\colorstretch{
519 \directlua{luatexbase.add_to_callback("post_linebreak_filter",colorstretch,"stretch_expansion")}}
520 \def\uncolorstretch{
521 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","stretch_expansion")}}
522
523 \def\countglyphs{
524 \directlua{
525 counted_glyphs_by_code = {}
526 for i = 1,10000 do
527 counted_glyphs_by_code[i] = 0
528 end
529 glyphnumber = 0 spacenumber = 0
530 luatexbase.add_to_callback("post_linebreak_filter",countglyphs,"countglyphs")
531 luatexbase.add_to_callback("stop_run",printglyphnumber,"printglyphnumber")
532 }
533 }
534
535 \def\countwords{
536 \directlua{wordnumber = 0
537 luatexbase.add_to_callback("pre_linebreak_filter",countwords,"countwords")
538 luatexbase.add_to_callback("stop_run",printwordnumber,"printwordnumber")
539 }
540 }
541
542 \def\detectdoublewords{
543 \directlua{
544 luatexbase.add_to_callback("post_linebreak_filter",detectdoublewords,"detectdoublewords")
545 luatexbase.add_to_callback("stop_run",printdoublewords,"printdoublewords")
546 }
547 }
548
549 \def\dosomethingfunny{
550 %% should execute one of the “funny” commands, but randomly. So every compilation is completely different. Maybe a list of commands could be specified to exclude total nonesense-functions. Maybe also on a per-paragraph-basis?
551 }
552
553 \def\dubstepenize{
554 \chickenize
555 \directlua{
556 chickenstring[1] = "WOB"
557 chickenstring[2] = "WOB"
558 chickenstring[3] = "WOB"
559 chickenstring[4] = "BROOOAR"
560 chickenstring[5] = "WHEE"
561 chickenstring[6] = "WOB WOB WOB"
562 chickenstring[7] = "WAAAAAAAAH"
563 chickenstring[8] = "duhduh duhduh duh"
564 chickenstring[9] = "BEEEEEEEEEW"
565 chickenstring[10] = "DDEEEEEEEW"
566 chickenstring[11] = "EEEEEW"
567 chickenstring[12] = "boop"
568 chickenstring[13] = "buhdee"
569 chickenstring[14] = "bee bee"
570 chickenstring[15] = "BZZZRRRRRRROOOOOOAAAAA"
571
572 chickenizefraction = 1
573 }
574 }
575 \let\dubstepize\dubstepenize
576
577 \def\explainbackslashes{ %% inspired by xkcd #1638
578 {\tt\noindent
579 \textbackslash escape character\\
580 \textbackslash\textbackslash line end or escaped escape character in tex.print("")\\
581 \textbackslash\textbackslash\textbackslash real, real backslash\\
582 \textbackslash\textbackslash\textbackslash\textbackslash line end in tex.print("")\\
583 \textbackslash\textbackslash\textbackslash\textbackslash\textbackslash elder backslash \\
584 \textbackslash\textbackslash\textbackslash\textbackslash\textbackslash\textbackslash backslash which escapes the screen and enters your brain\\
585 \textbackslash\textbackslash\textbackslash\textbackslash\textbackslash\textbackslash\textbackslash backslash so real it transcends time and space \\
586 \textbackslash\textbackslash\textbackslash\textbackslash\textbackslash\textbackslash\textbackslash\textbackslash backslash to end all other text\\
587 \textbackslash\textbackslash\textbackslash\textbackslash\textbackslash\textbackslash\textbackslash\textbackslash\textbackslash\textbackslash... the true name of Ba'al, the soul-eater}
588 }
589
590 \def\francize{
591 \directlua{luatexbase.add_to_callback("pre_linebreak_filter",francize,"francize")}}
592
593 \def\unfrancize{
594 \directlua{luatexbase.remove_from_callback("pre_linebreak_filter",francize)}}
595
596 \def\gameoflife{
597 Your Life Is Tetris. Stop Playing It Like Chess.
598 }
599 % \end{macrocode}
600 % This is just the activation of the command, the typesetting is done in the Lua code/loop as explained below. Use this macro \emph{after} |\begin{document}|. Remember that |graphicx| and |placeat| are required!
601 % \begin{macrocode}
602 \def\gameofchicken#1{\directlua{
603 GOCrule_live = {2,3}
604 GOCrule_spawn = {3}
605 GOCrule_antilive = {2,3}
606 GOCrule_antispawn = {3}
607 GOCcellcode = "\\scalebox{0.03}{\\drawchicken}"
608 GOCcellcode = "\\scalebox{0.03}{\\drawcov}"
609 GOCx = 100
610 GOCy = 100
611 GOCiter = 150
612 GOC_console = false
613 GOC_pdf = true
614 GOCsleep = 0
615 GOCdensity = 100
616 #1
617 gameofchicken()
618
619 if (GOCmakegif == true) then
620 luatexbase.add_to_callback("wrapup_run",make_a_gif,"makeagif")
621 end
622 }}
623 \let\gameofchimken\gameofchicken % yeah, that had to be.
624
625 \def\guttenbergenize{ %% makes only sense when using LaTeX
626 \AtBeginDocument{
627 \let\grqq\relax\let\glqq\relax
628 \let\frqq\relax\let\flqq\relax
629 \let\grq\relax\let\glq\relax
630 \let\frq\relax\let\flq\relax
631 %
632 \gdef\footnote##1{}
633 \gdef\cite##1{}\gdef\parencite##1{}
634 \gdef\Cite##1{}\gdef\Parencite##1{}
635 \gdef\cites##1{}\gdef\parencites##1{}
636 \gdef\Cites##1{}\gdef\Parencites##1{}
637 \gdef\footcite##1{}\gdef\footcitetext##1{}
638 \gdef\footcites##1{}\gdef\footcitetexts##1{}
639 \gdef\textcite##1{}\gdef\Textcite##1{}
640 \gdef\textcites##1{}\gdef\Textcites##1{}
641 \gdef\smartcites##1{}\gdef\Smartcites##1{}
642 \gdef\supercite##1{}\gdef\supercites##1{}
643 \gdef\autocite##1{}\gdef\Autocite##1{}
644 \gdef\autocites##1{}\gdef\Autocites##1{}
645 %% many, many missing … maybe we need to tackle the underlying mechanism?
646 }
647 \directlua{luatexbase.add_to_callback("pre_linebreak_filter",guttenbergenize_rq,"guttenbergenize_rq")}
648 }
649
650 \def\hammertime{
651 \global\let\n\relax
652 \directlua{hammerfirst = true
653 luatexbase.add_to_callback("pre_linebreak_filter",hammertime,"hammertime")}}
654 \def\unhammertime{
655 \directlua{luatexbase.remove_from_callback("pre_linebreak_filter","hammertime")}}
656
657 \let\hendlnize\chickenize % homage to Hendl/Chicken
658 \let\unhendlnize\unchickenize % may the soldering strength always be with him
659
660 \def\italianizerandwords{
661 \directlua{luatexbase.add_to_callback("pre_linebreak_filter",italianizerandwords,"italianizerandwords")}}
662 \def\unitalianizerandwords{
663 \directlua{luatexbase.remove_from_callback("pre_linebreak_filter","italianizerandwords")}}
664
665 \def\italianize{
666 \directlua{luatexbase.add_to_callback("pre_linebreak_filter",italianize,"italianize")}}
667 \def\unitalianize{
668 \directlua{luatexbase.remove_from_callback("pre_linebreak_filter","italianize")}}
669
670 % \def\itsame{
671 % \directlua{drawmario}} %%% does not exist
672
673 \def\kernmanipulate{
674 \directlua{luatexbase.add_to_callback("pre_linebreak_filter",kernmanipulate,"kernmanipulate")}}
675 \def\unkernmanipulate{
676 \directlua{lutaexbase.remove_from_callback("pre_linebreak_filter",kernmanipulate)}}
677
678 \def\leetspeak{
679 \directlua{luatexbase.add_to_callback("post_linebreak_filter",leet,"1337")}}
680 \def\unleetspeak{
681 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","1337")}}
682
683 \def\leftsideright#1{
684 \directlua{luatexbase.add_to_callback("pre_linebreak_filter",leftsideright,"leftsideright")}
685 \directlua{
686 leftsiderightindex = {#1}
687 leftsiderightarray = {}
688 for _,i in pairs(leftsiderightindex) do
689 leftsiderightarray[i] = true
690 end
691 }
692 }
693 \def\unleftsideright{
694 \directlua{luatexbase.remove_from_callback("pre_linebreak_filter","leftsideright")}}
695
696 \def\letterspaceadjust{
697 \directlua{luatexbase.add_to_callback("pre_linebreak_filter",letterspaceadjust,"letterspaceadjust")}}
698 \def\unletterspaceadjust{
699 \directlua{luatexbase.remove_from_callback("pre_linebreak_filter","letterspaceadjust")}}
700
701 \def\listallcommands{
702 \directlua{
703 for name in pairs(tex.hashtokens()) do
704 print(name)
705 end}
706 }
707
708 \let\stealsheep\letterspaceadjust %% synonym in honor of Paul
709 \let\unstealsheep\unletterspaceadjust
710 \let\returnsheep\unletterspaceadjust
711
712 \def\matrixize{
713 \directlua{luatexbase.add_to_callback("pre_linebreak_filter",matrixize,"matrixize")}}
714 \def\unmatrixize{
715 \directlua{luatexbase.remove_from_callback("pre_linebreak_filter","matrixize")}}
716
717 \def\milkcow{ %% FIXME %% to be implemented
718 \directlua{}}
719 \def\unmilkcow{
720 \directlua{}}
721
722 \def\medievalumlaut{
723 \directlua{luatexbase.add_to_callback("post_linebreak_filter",medievalumlaut,"medievalumlaut")}}
724 \def\unmedievalumlaut{
725 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","medievalumlaut")}}
726
727 \def\pancakenize{
728 \directlua{luatexbase.add_to_callback("stop_run",pancaketext,"pancaketext")}}
729
730 \def\rainbowcolor{
731 \directlua{luatexbase.add_to_callback("post_linebreak_filter",randomcolor,"rainbowcolor")
732 rainbowcolor = true}}
733 \def\unrainbowcolor{
734 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","rainbowcolor")
735 rainbowcolor = false}}
736 \let\nyanize\rainbowcolor
737 \let\unnyanize\unrainbowcolor
738
739 \def\randomchars{
740 \directlua{luatexbase.add_to_callback("post_linebreak_filter",randomchars,"randomchars")}}
741 \def\unrandomchars{
742 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","randomchars")}}
743
744 \def\randomcolor{
745 \directlua{luatexbase.add_to_callback("post_linebreak_filter",randomcolor,"randomcolor")}}
746 \def\unrandomcolor{
747 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","randomcolor")}}
748
749 \def\randomerror{ %% FIXME
750 \directlua{luatexbase.add_to_callback("post_linebreak_filter",randomerror,"randomerror")}}
751 \def\unrandomerror{ %% FIXME
752 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","randomerror")}}
753
754 \def\randomfonts{
755 \directlua{luatexbase.add_to_callback("post_linebreak_filter",randomfonts,"randomfonts")}}
756 \def\unrandomfonts{
757 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","randomfonts")}}
758
759 \def\randomuclc{
760 \directlua{luatexbase.add_to_callback("pre_linebreak_filter",randomuclc,"randomuclc")}}
761 \def\unrandomuclc{
762 \directlua{luatexbase.remove_from_callback("pre_linebreak_filter","randomuclc")}}
763
764 \def\relationship{%
765 \directlua{luatexbase.add_to_callback("post_linebreak_filter",cutparagraph,"cut paragraph")
766 luatexbase.add_to_callback("stop_run",missingcharstext,"charsmissing")
767 relationship()
768 }
769 }
770
771 \let\rongorongonize\boustrophedoninverse
772 \let\unrongorongonize\unboustrophedoninverse
773
774 \def\scorpionize{
775 \directlua{luatexbase.add_to_callback("pre_linebreak_filter",scorpionize_color,"scorpionize_color")}}
776 \def\unscorpionize{
777 \directlua{luatexbase.remove_from_callback("pre_linebreak_filter","scorpionize_color")}}
778
779 \def\spankmonkey{ %% to be implemented
780 \directlua{}}
781 \def\unspankmonkey{
782 \directlua{}}
783
784 \def\substitutewords{
785 \directlua{luatexbase.add_to_callback("process_input_buffer",substitutewords,"substitutewords")}}
786 \def\unsubstitutewords{
787 \directlua{luatexbase.remove_from_callback("process_input_buffer","substitutewords")}}
788
789 \def\addtosubstitutions#1#2{
790 \directlua{addtosubstitutions("#1","#2")}
791 }
792
793 \def\suppressonecharbreak{
794 \directlua{luatexbase.add_to_callback("pre_linebreak_filter",suppressonecharbreak,"suppressonecharbreak")}}
795 \def\unsuppressonecharbreak{
796 \directlua{luatexbase.remove_from_callback("pre_linebreak_filter","suppressonecharbreak")}}
797
798 \def\tabularasa{
799 \directlua{luatexbase.add_to_callback("post_linebreak_filter",tabularasa,"tabularasa")}}
800 \def\untabularasa{
801 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","tabularasa")}}
802
803 \def\tanjanize{
804 \directlua{luatexbase.add_to_callback("post_linebreak_filter",tanjanize,"tanjanize")}}
805 \def\untanjanize{
806 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","tanjanize")}}
807
808 \def\uppercasecolor{
809 \directlua{luatexbase.add_to_callback("post_linebreak_filter",uppercasecolor,"uppercasecolor")}}
810 \def\unuppercasecolor{
811 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","uppercasecolor")}}
812
813 \def\upsidedown#1{
814 \directlua{luatexbase.add_to_callback("post_linebreak_filter",upsidedown,"upsidedown")}
815 \directlua{
816 upsidedownindex = {#1}
817 upsidedownarray = {}
818 for _,i in pairs(upsidedownindex) do
819 upsidedownarray[i] = true
820 end
821 }
822 }
823 \def\unupsidedown{
824 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","upsidedown")}}
825
826 \def\variantjustification{
827 \directlua{luatexbase.add_to_callback("post_linebreak_filter",variantjustification,"variantjustification")}}
828 \def\unvariantjustification{
829 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","variantjustification")}}
830
831 \def\zebranize{
832 \directlua{luatexbase.add_to_callback("post_linebreak_filter",zebranize,"zebranize")}}
833 \def\unzebranize{
834 \directlua{luatexbase.remove_from_callback("post_linebreak_filter","zebranize")}}
835 % \end{macrocode}
836 % Now the setup for the |\text|-versions. We utilize Lua\TeX s attributes to mark all nodes that should be manipulated. The macros should be |\long| to allow arbitrary input.
837 % \begin{macrocode}
838 \newattribute\leetattr
839 \newattribute\letterspaceadjustattr
840 \newattribute\randcolorattr
841 \newattribute\randfontsattr
842 \newattribute\randuclcattr
843 \newattribute\tabularasaattr
844 \newattribute\uppercasecolorattr
845
846 \long\def\textleetspeak#1%
847 {\setluatexattribute\leetattr{42}#1\unsetluatexattribute\leetattr}
848
849 \long\def\textletterspaceadjust#1{
850 \setluatexattribute\letterspaceadjustattr{42}#1\unsetluatexattribute\letterspaceadjustattr
851 \directlua{
852 if (textletterspaceadjustactive) then else % -- if already active, do nothing
853 luatexbase.add_to_callback("pre_linebreak_filter",textletterspaceadjust,"textletterspaceadjust")
854 end
855 textletterspaceadjustactive = true % -- set to active
856 }
857 }
858 \let\textlsa\textletterspaceadjust
859
860 \long\def\textrandomcolor#1%
861 {\setluatexattribute\randcolorattr{42}#1\unsetluatexattribute\randcolorattr}
862 \long\def\textrandomfonts#1%
863 {\setluatexattribute\randfontsattr{42}#1\unsetluatexattribute\randfontsattr}
864 \long\def\textrandomfonts#1%
865 {\setluatexattribute\randfontsattr{42}#1\unsetluatexattribute\randfontsattr}
866 \long\def\textrandomuclc#1%
867 {\setluatexattribute\randuclcattr{42}#1\unsetluatexattribute\randuclcattr}
868 \long\def\texttabularasa#1%
869 {\setluatexattribute\tabularasaattr{42}#1\unsetluatexattribute\tabularasaattr}
870 \long\def\textuppercasecolor#1%
871 {\setluatexattribute\uppercasecolorattr{42}#1\unsetluatexattribute\uppercasecolorattr}
872 % \end{macrocode}
873 % Finally, a macro to control the setup. So far, it's only a wrapper that allows \TeX-style comments to make the user feel more at home.
874 % \begin{macrocode}
875 \def\chickenizesetup#1{\directlua{#1}}
876 % \end{macrocode}
877 % \subsection{drawchicken}\label{sec:drawchicken}
878 % The following is the very first try of implementing a small drawing language in Lua. It draws a beautiful (?) chicken. TODO: Make it scalable by giving relative sizes. Also: Allow it to look to the other side if wanted.
879 % \begin{macrocode}
880 \long\def\luadraw#1#2{%
881 \vbox to #1bp{%
882 \vfil
883 \latelua{pdf_print("q") #2 pdf_print("Q")}%
884 }%
885 }
886 \long\def\drawchicken{
887 \luadraw{90}{
888 chickenhead = {200,50} % chicken head center
889 chickenhead_rad = 20
890
891 neckstart = {215,35} % neck
892 neckstop = {230,10} %
893
894 chickenbody = {260,-10}
895 chickenbody_rad = 40
896 chickenleg = {
897 {{260,-50},{250,-70},{235,-70}},
898 {{270,-50},{260,-75},{245,-75}}
899 }
900
901 beak_top = {185,55}
902 beak_front = {165,45}
903 beak_bottom = {185,35}
904
905 wing_front = {260,-10}
906 wing_bottom = {280,-40}
907 wing_back = {275,-15}
908
909 sloppycircle(chickenhead,chickenhead_rad) sloppyline(neckstart,neckstop)
910 sloppycircle(chickenbody,chickenbody_rad)
911 sloppyline(chickenleg[1][1],chickenleg[1][2]) sloppyline(chickenleg[1][2],chickenleg[1][3])
912 sloppyline(chickenleg[2][1],chickenleg[2][2]) sloppyline(chickenleg[2][2],chickenleg[2][3])
913 sloppyline(beak_front,beak_top) sloppyline(beak_front,beak_bottom)
914 sloppyline(wing_front,wing_bottom) sloppyline(wing_back,wing_bottom)
915 }
916 }
917 % \end{macrocode}
918 % \subsection{drawcov}\label{sec:drawcov}
919 % This draws a corona virus since I had some time to work on this package due to the shutdown caused by COVID-19.
920 % \begin{macrocode}
921 \long\def\drawcov{
922 \luadraw{90}{
923 covbody = {200,50}
924 covbody_rad = 50
925
926 covcrown_rad = 5
927 crownno = 13
928 for i=1,crownno do
929 crownpos = {covbody[1]+1.4*covbody_rad*math.sin(2*math.pi/crownno*i),covbody[2]+1.4*covbody_rad*math.cos(2*math.pi/crownno*i)}
930 crownconnect = {covbody[1]+covbody_rad*math.sin(2*math.pi/crownno*i),covbody[2]+covbody_rad*math.cos(2*math.pi/crownno*i)}
931 sloppycircle(crownpos,covcrown_rad)
932 sloppyline(crownpos,crownconnect)
933 end
934
935 covcrown_rad = 6
936 crownno = 8
937 for i=1,crownno do
938 crownpos = {covbody[1]+0.8*covbody_rad*math.sin(2*math.pi/crownno*i),covbody[2]+0.8*covbody_rad*math.cos(2*math.pi/crownno*i)}
939 crownconnect = {covbody[1]+0.5*covbody_rad*math.sin(2*math.pi/crownno*i),covbody[2]+0.5*covbody_rad*math.cos(2*math.pi/crownno*i)}
940 sloppycircle(crownpos,covcrown_rad)
941 sloppyline(crownpos,crownconnect)
942 end
943
944 covcrown_rad = 8
945 sloppycircle(covbody,covcrown_rad)
946 sloppycircle(covbody,covbody_rad)
947 sloppyline(covbody,covbody)
948 }
949 }
950 % \end{macrocode}
951 % \subsection{drawhorse}\label{sec:drawhorse}
952 % Well … guess what this does.
953 % \begin{macrocode}
954 \long\def\drawhorse{
955 \luadraw{90}{
956 horsebod = {100,-40}
957 sloppyellipsis(horsebod,50,20)
958 horsehead = {20,0}
959 sloppyellipsis(horsehead,25,15)
960 sloppyline({35,-10},{50,-40})
961 sloppyline({45,5},{80,-25})
962 sloppyline({60,-50},{60,-90})
963 sloppyline({70,-50},{70,-90})
964 sloppyline({130,-50},{130,-90})
965 sloppyline({140,-50},{140,-90})
966 sloppyline({150,-40},{160,-60})
967 sloppyline({150,-38},{160,-58})
968 sloppyline({150,-42},{160,-62})
969 sloppyline({-5,-10},{10,-5})
970 sloppyellipsis({30,5},5,2) %% it's an eye, aye?
971 sloppyline({27,15},{34,25})
972 sloppyline({34,25},{37,13})
973 }
974 }
975 % \end{macrocode}
976 % There's also a version with a bit more … meat to the bones:
977 % \begin{macrocode}
978 \long\def\drawfathorse{
979 \luadraw{90}{
980 horsebod = {100,-40}
981 sloppyellipsis(horsebod,50,40)
982 horsehead = {20,0}
983 sloppyellipsis(horsehead,25,15)
984 sloppyline({35,-10},{50,-40})
985 sloppyline({45,5},{70,-15})
986 sloppyline({60,-70},{60,-90})
987 sloppyline({70,-70},{70,-90})
988 sloppyline({130,-70},{130,-90})
989 sloppyline({140,-70},{140,-90})
990 sloppyline({150,-40},{160,-60})
991 sloppyline({150,-38},{160,-58})
992 sloppyline({150,-42},{160,-62})
993 sloppyline({-5,-10},{10,-5})
994 sloppyellipsis({30,5},5,2) %% it's an eye, aye?
995 sloppyline({27,15},{34,25})
996 sloppyline({34,25},{37,13})
997 }
998 }
999 % intentioally not documented:
1000 \long\def\drawunicorn{
1001 \color{pink!90!black}
1002 \drawhorse
1003 \luadraw{0}{
1004 sloppyline({15,20},{15,50})
1005 sloppyline({15,50},{25,20})
1006 }
1007 }
1008 \long\def\drawfatunicorn{
1009 \color{pink!90!black}
1010 \drawfathorse
1011 \luadraw{0}{
1012 sloppyline({15,20},{15,50})
1013 sloppyline({15,50},{25,20})
1014 }
1015 }
1016 % \end{macrocode}
1017 % \iffalse
1018 %</tex>
1019 %<*package>
1020 % \fi
1021 % \section{\LaTeX\ package}
1022 % I have decided to keep the \LaTeX-part of this package as small as possible. So far, it does … nothing useful, but it provides a |chickenize.sty| that loads |chickenize.tex| so the user can still say |\usepackage{chickenize}|. This file will never support package options!
1023 %
1024 % Some code might be implemented to manipulate figures for full chickenization. However, I will \emph{not} load any packages at this place, as loading of expl3 or TikZ or whatever takes too much time for such a tiny package like this one. If you require any of the features presented here, you have to load the packages on your own. Maybe this will change.
1025 % \begin{macrocode}
1026 \ProvidesPackage{chickenize}%
1027 [2021/01/03 v0.3 chickenize package]
1028 \input{chickenize}
1029 % \end{macrocode}
1030 % \subsection{Free Compliments}
1031 % \begin{macrocode}
1032 %
1033 % \end{macrocode}
1034 % \subsection{Definition of User-Level Macros}
1035 % Nothing done so far, just some minor ideas. If you want to implement some cool things, contact me! :)
1036 % \begin{macrocode}
1037 \iffalse
1038 \DeclareDocumentCommand\includegraphics{O{}m}{
1039 \fbox{Chicken} %% actually, I'd love to draw an MP graph showing a chicken …
1040 }
1041 %%%% specials: the balmerpeak. A tribute to http://xkcd.com/323/.
1042 %% So far, you have to load pgfplots yourself.
1043 %% As it is a mighty package, I don't want the user to force loading it.
1044 \NewDocumentCommand\balmerpeak{G{}O{-4cm}}{
1045 %% to be done using Lua drawing.
1046 }
1047 \fi
1048 % \end{macrocode}
1049 %\iffalse
1050 %</package>
1051 %<*lua>
1052 %\fi
1053 % \section{Lua Module}
1054 % \label{sec:luamodule}
1055 % This file contains all the necessary functions and is the actual work horse of this package. The functions are sorted alphabetically (or, they \emph{should} be …) and not by sense, functionality or anything.
1056 %
1057 % First, we set up some constants that are used by many of the following functions. These are made global so the code can be manipulated at the document level, too.
1058 % \begin{macrocode}
1059
1060 local nodeid = node.id
1061 local nodecopy = node.copy
1062 local nodenew = node.new
1063 local nodetail = node.tail
1064 local nodeslide = node.slide
1065 local noderemove = node.remove
1066 local nodetraverseid = node.traverse_id
1067 local nodeinsertafter = node.insert_after
1068 local nodeinsertbefore = node.insert_before
1069
1070 Hhead = nodeid("hhead")
1071 RULE = nodeid("rule")
1072 GLUE = nodeid("glue")
1073 WHAT = nodeid("whatsit")
1074 COL = node.subtype("pdf_colorstack")
1075 DISC = nodeid("disc")
1076 GLYPH = nodeid("glyph")
1077 GLUE = nodeid("glue")
1078 HLIST = nodeid("hlist")
1079 KERN = nodeid("kern")
1080 PUNCT = nodeid("punct")
1081 PENALTY = nodeid("penalty")
1082 PDF_LITERAL = node.subtype("pdf_literal")
1083 % \end{macrocode}
1084 % Now we set up the nodes used for all color things. The nodes are whatsits of subtype |pdf_colorstack|.
1085 % \begin{macrocode}
1086 color_push = nodenew(WHAT,COL)
1087 color_pop = nodenew(WHAT,COL)
1088 color_push.stack = 0
1089 color_pop.stack = 0
1090 color_push.command = 1
1091 color_pop.command = 2
1092 % \end{macrocode}
1093 % \subsection{chickenize}\label{sec:chickenize}
1094 % The infamous |\chickenize| macro. Substitutes every word of the input with the given string. This can be elaborated arbitrarily, and whenever I feel like, I might add functionality. So far, only the string replaces the word, and even hyphenation is not possible.
1095 % \begin{macrocode}
1096 chicken_pagenumbers = true
1097
1098 chickenstring = {}
1099 chickenstring[1] = "chicken" -- chickenstring is a table, please remeber this!
1100
1101 chickenizefraction = 0.5 -- set this to a small value to fool somebody,
1102 -- or to see if your text has been read carefully. This is also a great way to lay easter eggs for your own class / package …
1103 chicken_substitutions = 0 -- value to count the substituted chickens. Makes sense for testing your proofreaders.
1104
1105 local match = unicode.utf8.match
1106 chickenize_ignore_word = false
1107 % \end{macrocode}
1108 % The function |chickenize_real_stuff| is started once the beginning of a to-be-substituted word is found.
1109 % \begin{macrocode}
1110 chickenize_real_stuff = function(i,head)
1111 while ((i.next.id == GLYPH) or (i.next.id == KERN) or (i.next.id == DISC) or (i.next.id == HLIST)) do --find end of a word
1112 i.next = i.next.next
1113 end
1114
1115 chicken = {} -- constructing the node list.
1116
1117 -- Should this be done only once? No, otherwise we lose the freedom to change the string in-document.
1118 -- But it could be done only once each paragraph as in-paragraph changes are not possible!
1119
1120 chickenstring_tmp = chickenstring[math.random(1,#chickenstring)]
1121 chicken[0] = nodenew(GLYPH,1) -- only a dummy for the loop
1122 for i = 1,string.len(chickenstring_tmp) do
1123 chicken[i] = nodenew(GLYPH,1)
1124 chicken[i].font = font.current()
1125 chicken[i-1].next = chicken[i]
1126 end
1127
1128 j = 1
1129 for s in string.utfvalues(chickenstring_tmp) do
1130 local char = unicode.utf8.char(s)
1131 chicken[j].char = s
1132 if match(char,"%s") then
1133 chicken[j] = nodenew(GLUE)
1134 chicken[j].width = space
1135 chicken[j].shrink = shrink
1136 chicken[j].stretch = stretch
1137 end
1138 j = j+1
1139 end
1140
1141 nodeslide(chicken[1])
1142 lang.hyphenate(chicken[1])
1143 chicken[1] = node.kerning(chicken[1]) -- FIXME: does not work
1144 chicken[1] = node.ligaturing(chicken[1]) -- dito
1145
1146 nodeinsertbefore(head,i,chicken[1])
1147 chicken[1].next = chicken[2] -- seems to be necessary … to be fixed
1148 chicken[string.len(chickenstring_tmp)].next = i.next
1149
1150 -- shift lowercase latin letter to uppercase if the original input was an uppercase
1151 if (chickenize_capital and (chicken[1].char > 96 and chicken[1].char < 123)) then
1152 chicken[1].char = chicken[1].char - 32
1153 end
1154
1155 return head
1156 end
1157
1158 chickenize = function(head)
1159 for i in nodetraverseid(GLYPH,head) do --find start of a word
1160 -- Random determination of the chickenization of the next word:
1161 if math.random() > chickenizefraction then
1162 chickenize_ignore_word = true
1163 elseif chickencount then
1164 chicken_substitutions = chicken_substitutions + 1
1165 end
1166
1167 if (chickenize_ignore_word == false) then -- normal case: at the beginning of a word, we jump into chickenization
1168 if (i.char > 64 and i.char < 91) then chickenize_capital = true else chickenize_capital = false end
1169 head = chickenize_real_stuff(i,head)
1170 end
1171
1172 -- At the end of the word, the ignoring is reset. New chance for everyone.
1173 if not((i.next.id == GLYPH) or (i.next.id == DISC) or (i.next.id == PUNCT) or (i.next.id == KERN)) then
1174 chickenize_ignore_word = false
1175 end
1176 end
1177 return head
1178 end
1179
1180 % \end{macrocode}
1181 % A small additional feature: Some nice text to cheer up the user. Mainly to show that and how we can access the |stop_run| callback. (see above)
1182 % \begin{macrocode}
1183 local separator = string.rep("=", 28)
1184 local texiowrite_nl = texio.write_nl
1185 nicetext = function()
1186 texiowrite_nl("Output written on "..tex.jobname..".pdf ("..status.total_pages.." chicken,".." eggs).")
1187 texiowrite_nl(" ")
1188 texiowrite_nl(separator)
1189 texiowrite_nl("Hello my dear user,")
1190 texiowrite_nl("good job, now go outside and enjoy the world!")
1191 texiowrite_nl(" ")
1192 texiowrite_nl("And don't forget to feed your chicken!")
1193 texiowrite_nl(separator .. "\n")
1194 if chickencount then
1195 texiowrite_nl("There were "..chicken_substitutions.." substitutions made.")
1196 texiowrite_nl(separator)
1197 end
1198 end
1199 % \end{macrocode}
1200 % \subsection{boustrophedon}\label{sec:boustrophedon}
1201 % There are two implementations of the boustrophedon: One reverses every line as a whole, the other one changes the writing direction and reverses glyphs one by one. The latter one might be more reliable, but takes considerably more time.
1202 %
1203 % Linewise rotation:
1204 % \begin{macrocode}
1205 boustrophedon = function(head)
1206 rot = node.new(WHAT,PDF_LITERAL)
1207 rot2 = node.new(WHAT,PDF_LITERAL)
1208 odd = true
1209 for line in node.traverse_id(0,head) do
1210 if odd == false then
1211 w = line.width/65536*0.99625 -- empirical correction factor (?)
1212 rot.data = "-1 0 0 1 "..w.." 0 cm"
1213 rot2.data = "-1 0 0 1 "..-w.." 0 cm"
1214 line.head = node.insert_before(line.head,line.head,nodecopy(rot))
1215 nodeinsertafter(line.head,nodetail(line.head),nodecopy(rot2))
1216 odd = true
1217 else
1218 odd = false
1219 end
1220 end
1221 return head
1222 end
1223 % \end{macrocode}
1224 % Glyphwise rotation:
1225 % \begin{macrocode}
1226 boustrophedon_glyphs = function(head)
1227 odd = false
1228 rot = nodenew(WHAT,PDF_LITERAL)
1229 rot2 = nodenew(WHAT,PDF_LITERAL)
1230 for line in nodetraverseid(0,head) do
1231 if odd==true then
1232 line.dir = "TRT"
1233 for g in nodetraverseid(GLYPH,line.head) do
1234 w = -g.width/65536*0.99625
1235 rot.data = "-1 0 0 1 " .. w .." 0 cm"
1236 rot2.data = "-1 0 0 1 " .. -w .." 0 cm"
1237 line.head = node.insert_before(line.head,g,nodecopy(rot))
1238 nodeinsertafter(line.head,g,nodecopy(rot2))
1239 end
1240 odd = false
1241 else
1242 line.dir = "TLT"
1243 odd = true
1244 end
1245 end
1246 return head
1247 end
1248 % \end{macrocode}
1249 % Inverse boustrophedon. At least I think, this is the way Rongorongo is written. However, the top-to-bottom direction has to be inverted, too.
1250 % \begin{macrocode}
1251 boustrophedon_inverse = function(head)
1252 rot = node.new(WHAT,PDF_LITERAL)
1253 rot2 = node.new(WHAT,PDF_LITERAL)
1254 odd = true
1255 for line in node.traverse_id(0,head) do
1256 if odd == false then
1257 texio.write_nl(line.height)
1258 w = line.width/65536*0.99625 -- empirical correction factor (?)
1259 h = line.height/65536*0.99625
1260 rot.data = "-1 0 0 -1 "..w.." "..h.." cm"
1261 rot2.data = "-1 0 0 -1 "..-w.." "..0.5*h.." cm"
1262 line.head = node.insert_before(line.head,line.head,node.copy(rot))
1263 node.insert_after(line.head,node.tail(line.head),node.copy(rot2))
1264 odd = true
1265 else
1266 odd = false
1267 end
1268 end
1269 return head
1270 end
1271 % \end{macrocode}
1272 %
1273 % \subsection{bubblesort}\label{sec:bubblesort}
1274 % Bubllesort is to be implemented. Why? Because it's funny.
1275 % \begin{macrocode}
1276 function bubblesort(head)
1277 for line in nodetraverseid(0,head) do
1278 for glyph in nodetraverseid(GLYPH,line.head) do
1279
1280 end
1281 end
1282 return head
1283 end
1284 % \end{macrocode}
1285 % \subsection{countglyphs}\label{sec:countglyphs}
1286 % Counts the glyphs in your document. Where “glyph” means every printed character in everything that is a paragraph – formulas do \emph{not} work! Captions of floats etc.~also will \emph{not} work. However, hyphenations \emph{do} work and the hyphen sign \emph{is counted}! And that is the sole reason for this function – every simple script could read the letters in a doucment, but only after the hyphenation it is possible to count the real number of printed characters – where the hyphen does count.
1287 %
1288 % Not only the total number of glyphs is recorded, but also the number of glyphs by character code. By this, you know exactly how many “a” or “ß” you used. A feature of category “completely useless”.
1289 %
1290 % Spaces are also counted, but only spaces between glyphs in the output (i.\,e.~nothing at the end/beginning of the lines), excluding indentation.
1291 %
1292 % This function will (maybe, upon request) be extended to allow counting of whatever you want.
1293 %
1294 %% Take care: This will slow down the compilation extremely, by about a factor of 2! Only use for playing around or counting a final version of your document!
1295 % \begin{macrocode}
1296 countglyphs = function(head)
1297 for line in nodetraverseid(0,head) do
1298 for glyph in nodetraverseid(GLYPH,line.head) do
1299 glyphnumber = glyphnumber + 1
1300 if (glyph.next.next) then
1301 if (glyph.next.id == 10) and (glyph.next.next.id == GLYPH) then
1302 spacenumber = spacenumber + 1
1303 end
1304 counted_glyphs_by_code[glyph.char] = counted_glyphs_by_code[glyph.char] + 1
1305 end
1306 end
1307 end
1308 return head
1309 end
1310 % \end{macrocode}
1311 % To print out the number at the end of the document, the following function is registered in the |stop_run| callback. This will prevent the normal message from being printed, informing the user about page and memory stats etc. But I guess when counting characters, everything else does not matter at all? …
1312 % \begin{macrocode}
1313 printglyphnumber = function()
1314 texiowrite_nl("\nNumber of glyphs by character code (only up to 127):")
1315 for i = 1,127 do --%% FIXME: should allow for more characters, but cannot be printed to console output – print into document?
1316 texiowrite_nl(string.char(i)..": "..counted_glyphs_by_code[i])
1317 end
1318
1319 texiowrite_nl("\nTotal number of glyphs in this document: "..glyphnumber)
1320 texiowrite_nl("Number of spaces in this document: "..spacenumber)
1321 texiowrite_nl("Glyphs plus spaces: "..glyphnumber+spacenumber.."\n")
1322 end
1323 % \end{macrocode}
1324 % \subsection{countwords}\label{sec:countwords}
1325 % Counts the number of words in the document. The function works directly before the line breaking, so all macros are expanded. A “word” then is everything that is between two spaces before paragraph formatting. The beginning of a paragraph is a word, and the last word of a paragraph is accounted for by explicit increasing the counter, as no space token follows.
1326 % \begin{macrocode}
1327 countwords = function(head)
1328 for glyph in nodetraverseid(GLYPH,head) do
1329 if (glyph.next.id == GLUE) then
1330 wordnumber = wordnumber + 1
1331 end
1332 end
1333 wordnumber = wordnumber + 1 -- add 1 for the last word in a paragraph which is not found otherwise
1334 return head
1335 end
1336 % \end{macrocode}
1337 % Printing is done at the end of the compilation in the |stop_run| callback:
1338 % \begin{macrocode}
1339 printwordnumber = function()
1340 texiowrite_nl("\nNumber of words in this document: "..wordnumber)
1341 end
1342 % \end{macrocode}
1343
1344 % \subsection{detectdoublewords}\label{sec:detectdoublewords}
1345 % \begin{macrocode} %% FIXME: Does this work? …
1346 detectdoublewords = function(head)
1347 prevlastword = {} -- array of numbers representing the glyphs
1348 prevfirstword = {}
1349 newlastword = {}
1350 newfirstword = {}
1351 for line in nodetraverseid(0,head) do
1352 for g in nodetraverseid(GLYPH,line.head) do
1353 texio.write_nl("next glyph",#newfirstword+1)
1354 newfirstword[#newfirstword+1] = g.char
1355 if (g.next.id == 10) then break end
1356 end
1357 texio.write_nl("nfw:"..#newfirstword)
1358 end
1359 end
1360
1361 printdoublewords = function()
1362 texio.write_nl("finished")
1363 end
1364 % \end{macrocode}
1365 % \subsection{francize}\label{sec:francize}
1366 % This function is intentionally undocumented. It randomizes all numbers digit by digit. Why? Because.
1367 % \begin{macrocode}
1368 francize = function(head)
1369 for n in nodetraverseid(GLYPH,head) do
1370 if ((n.char > 47) and (n.char < 58)) then
1371 n.char = math.random(48,57)
1372 end
1373 end
1374 return head
1375 end
1376 % \end{macrocode}
1377 % \subsection{gamofchicken}\label{sec:gamofchicken}
1378 % The |gameofchicken| is an implementation of the Game of Life by Conway. The standard cell here is a chicken, while there are also anticells. For both you can adapt the \LaTeX\ code to represent the cells.
1379 %
1380 % I also kick in some code to convert the pdf into a gif after the pdf has been finalized and Lua\TeX\ is about to end. This uses a system call to |convert|; especially the latter one will change. For now this is a convenient implementation for me and maybe most Linux environments to get the gif by one-click-compiling the |tex| document.
1381 % \begin{macrocode}
1382 function gameofchicken()
1383 GOC_lifetab = {}
1384 GOC_spawntab = {}
1385 GOC_antilifetab = {}
1386 GOC_antispawntab = {}
1387 -- translate the rules into an easily-manageable table
1388 for i=1,#GOCrule_live do; GOC_lifetab[GOCrule_live[i]] = true end
1389 for i=1,#GOCrule_spawn do; GOC_spawntab[GOCrule_spawn[i]] = true end
1390 for i=1,#GOCrule_antilive do; GOC_antilifetab[GOCrule_antilive[i]] = true end
1391 for i=1,#GOCrule_antispawn do; GOC_antispawntab[GOCrule_antispawn[i]] = true end
1392 % \end{macrocode}
1393 % Initialize the arrays for cells and anticells with zeros.
1394 % \begin{macrocode}
1395 -- initialize the arrays
1396 local life = {}
1397 local antilife = {}
1398 local newlife = {}
1399 local newantilife = {}
1400 for i = 0, GOCx do life[i] = {}; newlife[i] = {} for j = 0, GOCy do life[i][j] = 0 end end
1401 for i = 0, GOCx do antilife[i] = {}; newantilife[i] = {} for j = 0, GOCy do antilife[i][j] = 0 end end
1402 % \end{macrocode}
1403 % These are the functions doing the actual work, checking the neighbors and applying the rules defined above.
1404 % \begin{macrocode}
1405 function applyruleslife(neighbors, lifeij, antineighbors, antilifeij)
1406 if GOC_spawntab[neighbors] then myret = 1 else -- new cell
1407 if GOC_lifetab[neighbors] and (lifeij == 1) then myret = 1 else myret = 0 end end
1408 if antineighbors > 1 then myret = 0 end
1409 return myret
1410 end
1411 function applyrulesantilife(neighbors, lifeij, antineighbors, antilifeij)
1412 if (antineighbors == 3) then myret = 1 else -- new cell or keep cell
1413 if (((antineighbors > 1) and (antineighbors < 4)) and (lifeij == 1)) then myret = 1 else myret = 0 end end
1414 if neighbors > 1 then myret = 0 end
1415 return myret
1416 end
1417 % \end{macrocode}
1418 % Preparing the initial state with a default pattern:
1419 % \begin{macrocode}
1420 -- prepare some special patterns as starter
1421 life[53][26] = 1 life[53][25] = 1 life[54][25] = 1 life[55][25] = 1 life[54][24] = 1
1422 % \end{macrocode}
1423 % And the main loop running from here:
1424 % \begin{macrocode}
1425 print("start");
1426 for i = 1,GOCx do
1427 for j = 1,GOCy do
1428 if (life[i][j]==1) then texio.write("X") else if (antilife[i][j]==1) then texio.write("O") else texio.write("_") end end
1429 end
1430 texio.write_nl(" ");
1431 end
1432 os.sleep(GOCsleep)
1433
1434 for i = 0, GOCx do
1435 for j = 0, GOCy do
1436 newlife[i][j] = 0 -- Fill the values from the start settings here
1437 newantilife[i][j] = 0 -- Fill the values from the start settings here
1438 end
1439 end
1440
1441 for k = 1,GOCiter do -- iterate over the cycles
1442 texio.write_nl(k);
1443 for i = 1, GOCx-1 do -- iterate over lines
1444 for j = 1, GOCy-1 do -- iterate over columns -- prevent edge effects
1445 local neighbors = (life[i-1][j-1] + life[i-1][j] + life[i-1][j+1] + life[i][j-1] + life[i][j+1] + life[i+1][j-1] + life[i+1][j] + life[i+1][j+1])
1446 local antineighbors = (antilife[i-1][j-1] + antilife[i-1][j] + antilife[i-1][j+1] + antilife[i][j-1] + antilife[i][j+1] + antilife[i+1][j-1] + antilife[i+1][j] + antilife[i+1][j+1])
1447
1448 newlife[i][j] = applyruleslife(neighbors, life[i][j],antineighbors, antilife[i][j])
1449 newantilife[i][j] = applyrulesantilife(neighbors,life[i][j], antineighbors,antilife[i][j])
1450 end
1451 end
1452
1453 for i = 1, GOCx do
1454 for j = 1, GOCy do
1455 life[i][j] = newlife[i][j] -- copy the values
1456 antilife[i][j] = newantilife[i][j] -- copy the values
1457 end
1458 end
1459
1460 for i = 1,GOCx do
1461 for j = 1,GOCy do
1462 if GOC_console then
1463 if (life[i][j]==1) then texio.write("X") else if (antilife[i][j]==1) then texio.write("O") else texio.write("_") end end
1464 end
1465 if GOC_pdf then
1466 if (life[i][j]==1) then tex.print("\\placeat("..(i/10)..","..(j/10).."){"..GOCcellcode.."}") end
1467 if (antilife[i][j]==1) then tex.print("\\placeat("..(i/10)..","..(j/10).."){"..GOCanticellcode.."}") end
1468 end
1469 end
1470 end
1471 tex.print(".\\newpage")
1472 os.sleep(GOCsleep)
1473 end
1474 end --end function gameofchicken
1475 % \end{macrocode}
1476 % The following is a function calling some tool from your operating system. This requires of course that you have them present – that should be the case on a typical Linux distribution. Take care that |convert| normally does not allow for conversion from pdf, please check that this is allowed by the rules. So this is more an example code that can help you to add it to your game so you can enjoy your chickens developing as a gif.
1477 % \begin{macrocode}
1478 function make_a_gif()
1479 os.execute("convert -verbose -dispose previous -background white -alpha remove -alpha off -density "..GOCdensity.." "..tex.jobname ..".pdf " ..tex.jobname..".gif")
1480 os.execute("gwenview "..tex.jobname..".gif")
1481 end
1482 % \end{macrocode}
1483 % \subsection{guttenbergenize}\label{sec:guttenbergenize}
1484 % A function in honor of the German politician Guttenberg.\footnote{Thanks to Jasper for bringing me to this idea!} Please do \emph{not} confuse him with the grand master Gutenberg!
1485 %
1486 % Calling |\guttenbergenize| will not only execute or manipulate Lua code, but also redefine some \TeX\ or \LaTeX\ commands. The aim is to remove all quotations, footnotes and anything that will give information about the real sources of your work.
1487 %
1488 % The following Lua function will remove all quotation marks from the input. Again, the |pre_linebreak_filter| is used for this, although it should be rather removed in the input filter or so.
1489 % \subsubsection{guttenbergenize – preliminaries}
1490 % This is a nice solution Lua offers for our needs. Learn it, this might be helpful for you sometime, too.
1491 % \begin{macrocode}
1492 local quotestrings = {
1493 [171] = true, [172] = true,
1494 [8216] = true, [8217] = true, [8218] = true,
1495 [8219] = true, [8220] = true, [8221] = true,
1496 [8222] = true, [8223] = true,
1497 [8248] = true, [8249] = true, [8250] = true,
1498 }
1499 % \end{macrocode}
1500 % \subsubsection{guttenbergenize – the function}
1501 % \begin{macrocode}
1502 guttenbergenize_rq = function(head)
1503 for n in nodetraverseid(GLYPH,head) do
1504 local i = n.char
1505 if quotestrings[i] then
1506 noderemove(head,n)
1507 end
1508 end
1509 return head
1510 end
1511 % \end{macrocode}
1512 % \subsection{hammertime}\label{sec:hammertime}
1513 % This is a completely useless function. It just prints STOP! – HAMMERTIME at the beginnig of the first paragraph after |\hammertime|, and “U can't touch this” for every following one. As the function writes to the terminal, you have to be sure that your terminal is line-buffered and not block-buffered. Compare the explanation by Taco on the Lua\TeX\ mailing list.\footnote{\url{http://tug.org/pipermail/luatex/2011-November/003355.html}}
1514 % \begin{macrocode}
1515 hammertimedelay = 1.2
1516 local htime_separator = string.rep("=", 30) .. "\n" -- slightly inconsistent with the “nicetext”
1517 hammertime = function(head)
1518 if hammerfirst then
1519 texiowrite_nl(htime_separator)
1520 texiowrite_nl("============STOP!=============\n")
1521 texiowrite_nl(htime_separator .. "\n\n\n")
1522 os.sleep (hammertimedelay*1.5)
1523 texiowrite_nl(htime_separator .. "\n")
1524 texiowrite_nl("==========HAMMERTIME==========\n")
1525 texiowrite_nl(htime_separator .. "\n\n")
1526 os.sleep (hammertimedelay)
1527 hammerfirst = false
1528 else
1529 os.sleep (hammertimedelay)
1530 texiowrite_nl(htime_separator)
1531 texiowrite_nl("======U can't touch this!=====\n")
1532 texiowrite_nl(htime_separator .. "\n\n")
1533 os.sleep (hammertimedelay*0.5)
1534 end
1535 return head
1536 end
1537 % \end{macrocode}
1538 % \subsection{italianize}\label{sec:italianize}
1539 % This is inspired by some of the more melodic pronounciations of the english language. The command will add randomly an |h| in front of every word starting with a vowel or remove |h| from words starting with one. Also, it will ad randomly an |e| to words ending in consonants. This is tricky and might fail – I'm happy to receive and try to solve ayn bug reports.
1540 % \begin{macrocode}
1541 italianizefraction = 0.5 --%% gives the amount of italianization
1542 mynode = nodenew(GLYPH) -- prepare a dummy glyph
1543
1544 italianize = function(head)
1545 -- skip "h/H" randomly
1546 for n in node.traverse_id(GLYPH,head) do -- go through all glyphs
1547 if n.prev.id ~= GLYPH then -- check if it's a word start
1548 if ((n.char == 72) or (n.char == 104)) and (tex.normal_rand() < italianizefraction) then -- if it's h/H, remove randomly
1549 n.prev.next = n.next
1550 end
1551 end
1552 end
1553
1554 -- add h or H in front of vowels
1555 for n in nodetraverseid(GLYPH,head) do
1556 if math.random() < italianizefraction then
1557 x = n.char
1558 if x == 97 or x == 101 or x == 105 or x == 111 or x == 117 or
1559 x == 65 or x == 69 or x == 73 or x == 79 or x == 85 then
1560 if (n.prev.id == GLUE) then
1561 mynode.font = n.font
1562 if x > 90 then -- lower case
1563 mynode.char = 104
1564 else
1565 mynode.char = 72 -- upper case – convert into lower case
1566 n.char = x + 32
1567 end
1568 node.insert_before(head,n,node.copy(mynode))
1569 end
1570 end
1571 end
1572 end
1573
1574 -- add e after words, but only after consonants
1575 for n in node.traverse_id(GLUE,head) do
1576 if n.prev.id == GLYPH then
1577 x = n.prev.char
1578 -- skip vowels and randomize
1579 if not(x == 97 or x == 101 or x == 105 or x == 111 or x == 117 or x == 44 or x == 46) and math.random() > 0.2 then
1580 mynode.char = 101 -- it's always a lower case e, no?
1581 mynode.font = n.prev.font -- adapt the current font
1582 node.insert_before(head,n,node.copy(mynode)) -- insert the e in the node list
1583 end
1584 end
1585 end
1586
1587 return head
1588 end
1589 % \end{macrocode}
1590 % \subsection{italianizerandwords}\label{sec:italianizerandwords}
1591 % This is inspired by my dearest colleagues and their artistic interpretation of the english grammar. The command will cause LuaTeX to read a sentence (i.\,e.~text until the next full stop), then randomizes the words (i.\,e.~units separated by a space) in it and throws the result back to the typesetting. Useless? Very.
1592 % \begin{macrocode}
1593 italianizerandwords = function(head)
1594 words = {}
1595 wordnumber = 0
1596 -- head.next.next is the very first word. However, let's try to get the first word after the first space correct.
1597 for n in nodetraverseid(GLUE,head) do -- let's try to count words by their separators
1598 wordnumber = wordnumber + 1
1599 if n.next then
1600 words[wordnumber] = {}
1601 words[wordnumber][1] = node.copy(n.next)
1602
1603 glyphnumber = 1
1604 myglyph = n.next
1605 while myglyph.next do
1606 node.tail(words[wordnumber][1]).next = node.copy(myglyph.next)
1607 myglyph = myglyph.next
1608 end
1609 end
1610 print(#words)
1611 if #words > 0 then
1612 print("lengs is: ")
1613 print(#words[#words])
1614 end
1615 end
1616 --myinsertnode = head.next.next -- first letter
1617 --node.tail(words[1][1]).next = myinsertnode.next
1618 --myinsertnode.next = words[1][1]
1619
1620 return head
1621 end
1622
1623 italianize_old = function(head)
1624 local wordlist = {} -- here we will store the number of words of the sentence.
1625 local words = {} -- here we will store the words of the sentence.
1626 local wordnumber = 0
1627 -- let's first count all words in one sentence, howboutdat?
1628 wordlist[wordnumber] = 1 -- let's save the word *length* in here …
1629
1630
1631 for n in nodetraverseid(GLYPH,head) do
1632 if (n.next.id == GLUE) then -- this is a space
1633 wordnumber = wordnumber + 1
1634 wordlist[wordnumber] = 1
1635 words[wordnumber] = n.next.next
1636 end
1637 if (n.next.id == GLYPH) then -- it's a glyph
1638 if (n.next.char == 46) then -- this is a full stop.
1639 wordnumber = wordnumber + 1
1640 texio.write_nl("this sentence had "..wordnumber.."words.")
1641 for i=0,wordnumber-1 do
1642 texio.write_nl("word "..i.." had " .. wordlist[i] .. "glyphs")
1643 end
1644 texio.write_nl(" ")
1645 wordnumber = -1 -- to compensate the fact that the next node will be a space, this would count one word too much.
1646 else
1647
1648 wordlist[wordnumber] = wordlist[wordnumber] + 1 -- the current word got 1 glyph longer
1649 end
1650 end
1651 end
1652 return head
1653 end
1654 % \end{macrocode}
1655
1656 % \subsection{itsame}\label{sec:itsame}
1657 % The (very first, very basic, very stupid) code to draw a small mario. You need to input luadraw.tex or do luadraw.lua for the rectangle function.
1658 % \begin{macrocode}
1659 itsame = function()
1660 local mr = function(a,b) rectangle({a*10,b*-10},10,10) end
1661 color = "1 .6 0"
1662 for i = 6,9 do mr(i,3) end
1663 for i = 3,11 do mr(i,4) end
1664 for i = 3,12 do mr(i,5) end
1665 for i = 4,8 do mr(i,6) end
1666 for i = 4,10 do mr(i,7) end
1667 for i = 1,12 do mr(i,11) end
1668 for i = 1,12 do mr(i,12) end
1669 for i = 1,12 do mr(i,13) end
1670
1671 color = ".3 .5 .2"
1672 for i = 3,5 do mr(i,3) end mr(8,3)
1673 mr(2,4) mr(4,4) mr(8,4)
1674 mr(2,5) mr(4,5) mr(5,5) mr(9,5)
1675 mr(2,6) mr(3,6) for i = 8,11 do mr(i,6) end
1676 for i = 3,8 do mr(i,8) end
1677 for i = 2,11 do mr(i,9) end
1678 for i = 1,12 do mr(i,10) end
1679 mr(3,11) mr(10,11)
1680 for i = 2,4 do mr(i,15) end for i = 9,11 do mr(i,15) end
1681 for i = 1,4 do mr(i,16) end for i = 9,12 do mr(i,16) end
1682
1683 color = "1 0 0"
1684 for i = 4,9 do mr(i,1) end
1685 for i = 3,12 do mr(i,2) end
1686 for i = 8,10 do mr(5,i) end
1687 for i = 5,8 do mr(i,10) end
1688 mr(8,9) mr(4,11) mr(6,11) mr(7,11) mr(9,11)
1689 for i = 4,9 do mr(i,12) end
1690 for i = 3,10 do mr(i,13) end
1691 for i = 3,5 do mr(i,14) end
1692 for i = 7,10 do mr(i,14) end
1693 end
1694 % \end{macrocode}
1695 % \subsection{kernmanipulate}\label{sec:kernmanipulate}
1696 % This function either eliminates all the kerning, inverts the sign of the kerning or changes it to a user-given value.
1697 %
1698 % If the boolean |chickeninvertkerning| is true, the kerning amount is negative, if it is false, the kerning will be set to th e value of |chickenkernvalue|. A large value (> 100\,000) can be used to show explicitely where kerns are inserted. Good for educational use.
1699 % \begin{macrocode}
1700 chickenkernamount = 0
1701 chickeninvertkerning = false
1702
1703 function kernmanipulate (head)
1704 if chickeninvertkerning then -- invert the kerning
1705 for n in nodetraverseid(11,head) do
1706 n.kern = -n.kern
1707 end
1708 else -- if not, set it to the given value
1709 for n in nodetraverseid(11,head) do
1710 n.kern = chickenkernamount
1711 end
1712 end
1713 return head
1714 end
1715 % \end{macrocode}
1716
1717 % \subsection{leetspeak}\label{sec:leetspeak}
1718 % The |leettable| is the substitution scheme. Just add items if you feel to. Maybe we will differ between a light-weight version and a hardcore 1337.
1719 % \begin{macrocode}
1720 leetspeak_onlytext = false
1721 leettable = {
1722 [101] = 51, -- E
1723 [105] = 49, -- I
1724 [108] = 49, -- L
1725 [111] = 48, -- O
1726 [115] = 53, -- S
1727 [116] = 55, -- T
1728
1729 [101-32] = 51, -- e
1730 [105-32] = 49, -- i
1731 [108-32] = 49, -- l
1732 [111-32] = 48, -- o
1733 [115-32] = 53, -- s
1734 [116-32] = 55, -- t
1735 }
1736 % \end{macrocode}
1737 % And here the function itself. So simple that I will not write any
1738 % \begin{macrocode}
1739 leet = function(head)
1740 for line in nodetraverseid(Hhead,head) do
1741 for i in nodetraverseid(GLYPH,line.head) do
1742 if not leetspeak_onlytext or
1743 node.has_attribute(i,luatexbase.attributes.leetattr)
1744 then
1745 if leettable[i.char] then
1746 i.char = leettable[i.char]
1747 end
1748 end
1749 end
1750 end
1751 return head
1752 end
1753 % \end{macrocode}
1754 % \subsection{leftsideright}\label{sec:leftsideright}
1755 % This function mirrors each glyph given in the array of \verb|leftsiderightarray| horizontally.
1756 % \begin{macrocode}
1757 leftsideright = function(head)
1758 local factor = 65536/0.99626
1759 for n in nodetraverseid(GLYPH,head) do
1760 if (leftsiderightarray[n.char]) then
1761 shift = nodenew(WHAT,PDF_LITERAL)
1762 shift2 = nodenew(WHAT,PDF_LITERAL)
1763 shift.data = "q -1 0 0 1 " .. n.width/factor .." 0 cm"
1764 shift2.data = "Q 1 0 0 1 " .. n.width/factor .." 0 cm"
1765 nodeinsertbefore(head,n,shift)
1766 nodeinsertafter(head,n,shift2)
1767 end
1768 end
1769 return head
1770 end
1771 % \end{macrocode}
1772 % \subsection{letterspaceadjust}\label{sec:letterspaceadjust}
1773 % Yet another piece of code by Paul. This is primarily intended for very narrow columns, but may also increase the overall quality of typesetting. Basically, it does nothing else than adding expandable space \emph{between} letters. This way, the amount of stretching between words can be reduced which will, hopefully, result in the greyness to be more equally distributed over the page.
1774 %
1775 % Why the synonym |stealsheep|? Because of a comment of Paul on the |texhax| mailing list: \url{http://tug.org/pipermail/texhax/2011-October/018374.html}
1776 % \subsubsection{setup of variables}
1777 % \begin{macrocode}
1778 local letterspace_glue = nodenew(GLUE)
1779 local letterspace_pen = nodenew(PENALTY)
1780
1781 letterspace_glue.width = tex.sp"0pt"
1782 letterspace_glue.stretch = tex.sp"0.5pt"
1783 letterspace_pen.penalty = 10000
1784 % \end{macrocode}
1785 % \subsubsection{function implementation}
1786 % \begin{macrocode}
1787 letterspaceadjust = function(head)
1788 for glyph in nodetraverseid(GLYPH, head) do
1789 if glyph.prev and (glyph.prev.id == GLYPH or glyph.prev.id == DISC or glyph.prev.id == KERN) then
1790 local g = nodecopy(letterspace_glue)
1791 nodeinsertbefore(head, glyph, g)
1792 nodeinsertbefore(head, g, nodecopy(letterspace_pen))
1793 end
1794 end
1795 return head
1796 end
1797 % \end{macrocode}
1798 % \subsubsection{textletterspaceadjust}
1799 % The |\text...|-version of |letterspaceadjust|. Just works, without the need to call |\letterspaceadjust| globally or anything else. Just put the |\textletterspaceadjust| around the part of text you want the function to work on. Might have problems with surrounding spacing, take care!
1800 % \begin{macrocode}
1801 textletterspaceadjust = function(head)
1802 for glyph in nodetraverseid(GLYPH, head) do
1803 if node.has_attribute(glyph,luatexbase.attributes.letterspaceadjustattr) then
1804 if glyph.prev and (glyph.prev.id == node.id"glyph" or glyph.prev.id == node.id"disc" or glyph.prev.id == KERN) then
1805 local g = node.copy(letterspace_glue)
1806 nodeinsertbefore(head, glyph, g)
1807 nodeinsertbefore(head, g, nodecopy(letterspace_pen))
1808 end
1809 end
1810 end
1811 luatexbase.remove_from_callback("pre_linebreak_filter","textletterspaceadjust")
1812 return head
1813 end
1814 % \end{macrocode}
1815 % \subsection{matrixize}\label{sec:matrixize}
1816 % Substitutes every glyph by a representation of its ASCII value. Migth be extended to cover the entire unicode range, but so far only 8bit is supported. The code is quite straight-forward and works OK. The line ends are not necessarily adjusted correctly. However, with microtype, i.\,e. font expansion, everything looks fine.
1817 % \begin{macrocode}
1818 matrixize = function(head)
1819 x = {}
1820 s = nodenew(DISC)
1821 for n in nodetraverseid(GLYPH,head) do
1822 j = n.char
1823 for m = 0,7 do -- stay ASCII for now
1824 x[7-m] = nodecopy(n) -- to get the same font etc.
1825
1826 if (j / (2^(7-m)) < 1) then
1827 x[7-m].char = 48
1828 else
1829 x[7-m].char = 49
1830 j = j-(2^(7-m))
1831 end
1832 nodeinsertbefore(head,n,x[7-m])
1833 nodeinsertafter(head,x[7-m],nodecopy(s))
1834 end
1835 noderemove(head,n)
1836 end
1837 return head
1838 end
1839 % \end{macrocode}
1840 % \subsection{medievalumlaut}\label{sec:medievalumlaut}
1841 % Changes the umlauts ä, ö, ü into a, o, u with an e as an accent. The exact position of the e is adapted for each glyph, but that is only tested with one font. Other fonts might f*ck up everything.
1842 %
1843 % For this, we define node representing the e (which then is copied every time) and two nodes that shift the e to where it belongs by using pdf matrix-nodes. An additional kern node shifts the space that the e took back so that everything ends up in the right place. All this happens in the \verb|post_linebreak_filter| to enable normal hyphenation and line breaking. Well, \verb|pre_linebreak_filter| would also have done …
1844 % \begin{macrocode}
1845 medievalumlaut = function(head)
1846 local factor = 65536/0.99626
1847 local org_e_node = nodenew(GLYPH)
1848 org_e_node.char = 101
1849 for line in nodetraverseid(0,head) do
1850 for n in nodetraverseid(GLYPH,line.head) do
1851 if (n.char == 228 or n.char == 246 or n.char == 252) then
1852 e_node = nodecopy(org_e_node)
1853 e_node.font = n.font
1854 shift = nodenew(WHAT,PDF_LITERAL)
1855 shift2 = nodenew(WHAT,PDF_LITERAL)
1856 shift2.data = "Q 1 0 0 1 " .. e_node.width/factor .." 0 cm"
1857 nodeinsertafter(head,n,e_node)
1858
1859 nodeinsertbefore(head,e_node,shift)
1860 nodeinsertafter(head,e_node,shift2)
1861
1862 x_node = nodenew(KERN)
1863 x_node.kern = -e_node.width
1864 nodeinsertafter(head,shift2,x_node)
1865 end
1866
1867 if (n.char == 228) then -- ä
1868 shift.data = "q 0.5 0 0 0.5 " ..
1869 -n.width/factor*0.85 .." ".. n.height/factor*0.75 .. " cm"
1870 n.char = 97
1871 end
1872 if (n.char == 246) then -- ö
1873 shift.data = "q 0.5 0 0 0.5 " ..
1874 -n.width/factor*0.75 .." ".. n.height/factor*0.75 .. " cm"
1875 n.char = 111
1876 end
1877 if (n.char == 252) then -- ü
1878 shift.data = "q 0.5 0 0 0.5 " ..
1879 -n.width/factor*0.75 .." ".. n.height/factor*0.75 .. " cm"
1880 n.char = 117
1881 end
1882 end
1883 end
1884 return head
1885 end
1886 % \end{macrocode}
1887 %
1888 % \subsection{pancakenize}\label{sec:pancakenize}
1889 % \begin{macrocode}
1890 local separator = string.rep("=", 28)
1891 local texiowrite_nl = texio.write_nl
1892 pancaketext = function()
1893 texiowrite_nl("Output written on "..tex.jobname..".pdf ("..status.total_pages.." chicken,".." eggs).")
1894 texiowrite_nl(" ")
1895 texiowrite_nl(separator)
1896 texiowrite_nl("Soo ... you decided to use \\pancakenize.")
1897 texiowrite_nl("That means you owe me a pancake!")
1898 texiowrite_nl(" ")
1899 texiowrite_nl("(This goes by document, not compilation.)")
1900 texiowrite_nl(separator.."\n\n")
1901 texiowrite_nl("Looking forward for my pancake! :)")
1902 texiowrite_nl("\n\n")
1903 end
1904 % \end{macrocode}
1905 % \subsection{randomerror}\label{sec:randomerror}
1906 % Not yet implemented, sorry.
1907
1908 % \subsection{randomfonts}\label{sec:randomfonts}
1909 % Traverses the output and substitutes fonts randomly. A check is done so that the font number is existing.
1910 % One day, the fonts should be easily given explicitly in terms of |\bf| etc.
1911 % \begin{macrocode}
1912 randomfontslower = 1
1913 randomfontsupper = 0
1914 %
1915 randomfonts = function(head)
1916 local rfub
1917 if randomfontsupper > 0 then -- fixme: this should be done only once, no? Or at every paragraph?
1918 rfub = randomfontsupper -- user-specified value
1919 else
1920 rfub = font.max() -- or just take all fonts
1921 end
1922 for line in nodetraverseid(Hhead,head) do
1923 for i in nodetraverseid(GLYPH,line.head) do
1924 if not(randomfonts_onlytext) or node.has_attribute(i,luatexbase.attributes.randfontsattr) then
1925 i.font = math.random(randomfontslower,rfub)
1926 end
1927 end
1928 end
1929 return head
1930 end
1931 % \end{macrocode}
1932 % \subsection{randomuclc}\label{sec:randomuclc}
1933 % Traverses the input list and changes lowercase/uppercase codes.
1934 % \begin{macrocode}
1935 uclcratio = 0.5 -- ratio between uppercase and lower case
1936 randomuclc = function(head)
1937 for i in nodetraverseid(GLYPH,head) do
1938 if not(randomuclc_onlytext) or node.has_attribute(i,luatexbase.attributes.randuclcattr) then
1939 if math.random() < uclcratio then
1940 i.char = tex.uccode[i.char]
1941 else
1942 i.char = tex.lccode[i.char]
1943 end
1944 end
1945 end
1946 return head
1947 end
1948 % \end{macrocode}
1949 % \subsection{randomchars}\label{sec:randomchars}
1950 % \begin{macrocode}
1951 randomchars = function(head)
1952 for line in nodetraverseid(Hhead,head) do
1953 for i in nodetraverseid(GLYPH,line.head) do
1954 i.char = math.floor(math.random()*512)
1955 end
1956 end
1957 return head
1958 end
1959 % \end{macrocode}
1960 % \subsection{randomcolor and rainbowcolor}\label{sec:randomrainbowcolor}
1961 % \subsubsection{randomcolor – preliminaries}
1962 % Setup of the boolean for grey/color or rainbowcolor, and boundaries for the colors. RGB space is fully used, but greyscale is only used in a visible range, i.\,e. to 90\% instead of 100\% white.
1963 % \begin{macrocode}
1964 randomcolor_grey = false
1965 randomcolor_onlytext = false --switch between local and global colorization
1966 rainbowcolor = false
1967
1968 grey_lower = 0
1969 grey_upper = 900
1970
1971 Rgb_lower = 1
1972 rGb_lower = 1
1973 rgB_lower = 1
1974 Rgb_upper = 254
1975 rGb_upper = 254
1976 rgB_upper = 254
1977 % \end{macrocode}
1978 % Variables for the rainbow. 1/rainbow\_step*5 is the number of letters used for one cycle, the color changes from red to yellow to green to blue to purple.
1979 % \begin{macrocode}
1980 rainbow_step = 0.005
1981 rainbow_Rgb = 1-rainbow_step -- we start in the red phase
1982 rainbow_rGb = rainbow_step -- values x must always be 0 < x < 1
1983 rainbow_rgB = rainbow_step
1984 rainind = 1 -- 1:red,2:yellow,3:green,4:blue,5:purple
1985 % \end{macrocode}
1986 % This function produces the string needed for the pdf color stack. We need values 0]..[1 for the colors.
1987 % \begin{macrocode}
1988 randomcolorstring = function()
1989 if randomcolor_grey then
1990 return (0.001*math.random(grey_lower,grey_upper)).." g"
1991 elseif rainbowcolor then
1992 if rainind == 1 then -- red
1993 rainbow_rGb = rainbow_rGb + rainbow_step
1994 if rainbow_rGb >= 1-rainbow_step then rainind = 2 end
1995 elseif rainind == 2 then -- yellow
1996 rainbow_Rgb = rainbow_Rgb - rainbow_step
1997 if rainbow_Rgb <= rainbow_step then rainind = 3 end
1998 elseif rainind == 3 then -- green
1999 rainbow_rgB = rainbow_rgB + rainbow_step
2000 rainbow_rGb = rainbow_rGb - rainbow_step
2001 if rainbow_rGb <= rainbow_step then rainind = 4 end
2002 elseif rainind == 4 then -- blue
2003 rainbow_Rgb = rainbow_Rgb + rainbow_step
2004 if rainbow_Rgb >= 1-rainbow_step then rainind = 5 end
2005 else -- purple
2006 rainbow_rgB = rainbow_rgB - rainbow_step
2007 if rainbow_rgB <= rainbow_step then rainind = 1 end
2008 end
2009 return rainbow_Rgb.." "..rainbow_rGb.." "..rainbow_rgB.." rg"
2010 else
2011 Rgb = math.random(Rgb_lower,Rgb_upper)/255
2012 rGb = math.random(rGb_lower,rGb_upper)/255
2013 rgB = math.random(rgB_lower,rgB_upper)/255
2014 return Rgb.." "..rGb.." "..rgB.." ".." rg"
2015 end
2016 end
2017 % \end{macrocode}
2018 % \subsubsection{randomcolor – the function}
2019 % The function that does all the colorizing action. It goes through the whole paragraph and looks at every glyph. If the boolean |randomcolor_onlytext| is set, only glyphs with the set attribute will be colored. Elsewise, all glyphs are taken.
2020 % \begin{macrocode}
2021 randomcolor = function(head)
2022 for line in nodetraverseid(0,head) do
2023 for i in nodetraverseid(GLYPH,line.head) do
2024 if not(randomcolor_onlytext) or
2025 (node.has_attribute(i,luatexbase.attributes.randcolorattr))
2026 then
2027 color_push.data = randomcolorstring() -- color or grey string
2028 line.head = nodeinsertbefore(line.head,i,nodecopy(color_push))
2029 nodeinsertafter(line.head,i,nodecopy(color_pop))
2030 end
2031 end
2032 end
2033 return head
2034 end
2035 % \end{macrocode}
2036 % \subsection{relationship}\label{sec:relationship}
2037 % It literally is what is says: A ship made of relations. Or a boat, rather. There are four parameters, |sailheight|, |mastheight|, |hullheight|, and |relnumber| which you can adjust.
2038 % \begin{macrocode}
2039 sailheight = 12
2040 mastheight = 4
2041 hullheight = 5
2042 relnumber = 402
2043 function relationship()
2044 --%% check if there's a problem with any character in the current font
2045 f = font.getfont(font.current())
2046 fullfont = 1
2047 for i = 8756,8842 do
2048 if not(f.characters[i]) then texio.write_nl((i).." not available") fullfont = 0 end
2049 end
2050 --%% store the result of the check for later, then go on to construct the ship:
2051 shipheight = sailheight + mastheight + hullheight
2052 tex.print("\\parshape "..(shipheight)) --%% prepare the paragraph shape ...
2053 for i =1,sailheight do
2054 tex.print(" "..(4.5-i/3.8).."cm "..((i-0.5)/2.5).."cm ")
2055 end
2056 for i =1,mastheight do
2057 tex.print(" "..(3.2).."cm "..(1).."cm ")
2058 end
2059 for i =1,hullheight do
2060 tex.print(" "..((i-1)/2).."cm "..(10-i).."cm ")
2061 end
2062 tex.print("\\noindent") --%% ... up to here, then insert relations
2063 for i=1,relnumber do
2064 tex.print("\\ \\char"..math.random(8756,8842))
2065 end
2066 tex.print("\\break")
2067 end
2068 % \end{macrocode}
2069 % And this is a helper function to prevent too many relations to be typeset. Problem: The relations are chosen randomly, and each might take different horizontial space. So we cannot make sure the same number of lines for each version. To catch this, we typeset more lines and just remove excess lines with a simple function in our beloved |post_linebreak_filter|.
2070 % \begin{macrocode}
2071 function cutparagraph(head)
2072 local parsum = 0
2073 for n in nodetraverseid(HLIST,head) do
2074 parsum = parsum + 1
2075 if parsum > shipheight then
2076 node.remove(head,n)
2077 end
2078 end
2079 return head
2080 end
2081 % \end{macrocode}
2082 % And finally a helper function to inform our dear users that they have to use a font that actually can display all the necessary symbols.
2083 % \begin{macrocode}
2084 function missingcharstext()
2085 if (fullfont == 0) then
2086 local separator = string.rep("=", 28)
2087 local texiowrite_nl = texio.write_nl
2088 texiowrite_nl("Output written on "..tex.jobname..".pdf ("..status.total_pages.." chicken,".." eggs).")
2089 texiowrite_nl(" ")
2090 texiowrite_nl(separator)
2091 texiowrite_nl("CAREFUL!!")
2092 texiowrite_nl("\\relationship needs special characters (unicode points 8756 to 8842)")
2093 texiowrite_nl("Your font does not support all of them!")
2094 texiowrite_nl("consider using another one, e.g. the XITS font supplied with TeXlive.")
2095 texiowrite_nl(separator .. "\n")
2096 end
2097 end
2098 % \end{macrocode}
2099 % \subsection{rickroll}\label{sec:rickroll}
2100 % Another tribute to pop culture. Either: substitute word-by-word as in pancake. OR: substitute each link to a youtube-rickroll …
2101 % \begin{macrocode}
2102 %
2103 % \end{macrocode}
2104 % \subsection{substitutewords}\label{sec:substitutewords}
2105 % This function is one of the rather usefull ones of this package. It replaces each occurance of one word by another word, which both are specified by the user. So nothing random or funny, but a real serious function! There are three levels for this function: At user-level, the user just specifies two strings that are passed to the function |addtosubstitutions|. This is needed as the |#| has a special meaning both in \TeX s definitions and in Lua. In this second step, the list of substitutions is just extended, and the real work is done by the function |substiuteword| which is registered in the |process_input_buffer| callback. Once the substitution list is built, the rest is very simple: We just use |gsub| to substitute, do this for every item in the list, and that's it.
2106 % \begin{macrocode}
2107 substitutewords_strings = {}
2108
2109 addtosubstitutions = function(input,output)
2110 substitutewords_strings[#substitutewords_strings + 1] = {}
2111 substitutewords_strings[#substitutewords_strings][1] = input
2112 substitutewords_strings[#substitutewords_strings][2] = output
2113 end
2114
2115 substitutewords = function(head)
2116 for i = 1,#substitutewords_strings do
2117 head = string.gsub(head,substitutewords_strings[i][1],substitutewords_strings[i][2])
2118 end
2119 return head
2120 end
2121 % \end{macrocode}
2122 % \subsection{suppressonecharbreak}\label{sec:suppressonecharbreak}
2123 % We rush through the node list before line breaking takes place and insert large penalties for breaks after single glyphs. To keep the code as small, simple and fast as possible, we |traverse_id| over spaces and see wether the |next.next| node is also a space. This might not be the best and most universal way of doing it, but the simplest. The penalty is not created newly each time, but copied – no significant speed gain, however.
2124 % \begin{macrocode}
2125 suppressonecharbreakpenaltynode = node.new(PENALTY)
2126 suppressonecharbreakpenaltynode.penalty = 10000
2127 % \end{macrocode}
2128 % \begin{macrocode}
2129 function suppressonecharbreak(head)
2130 for i in node.traverse_id(GLUE,head) do
2131 if ((i.next) and (i.next.next.id == GLUE)) then
2132 pen = node.copy(suppressonecharbreakpenaltynode)
2133 node.insert_after(head,i.next,pen)
2134 end
2135 end
2136
2137 return head
2138 end
2139 % \end{macrocode}
2140 % \subsection{tabularasa}\label{sec:tabularasa}
2141 % Removes every glyph from the output and replaces it by empty space. In the end, next to nothing will be visible. Should be extended to also remove rules or just anything visible.
2142 % \begin{macrocode}
2143 tabularasa_onlytext = false
2144
2145 tabularasa = function(head)
2146 local s = nodenew(KERN)
2147 for line in nodetraverseid(HLIST,head) do
2148 for n in nodetraverseid(GLYPH,line.head) do
2149 if not(tabularasa_onlytext) or node.has_attribute(n,luatexbase.attributes.tabularasaattr) then
2150 s.kern = n.width
2151 nodeinsertafter(line.list,n,nodecopy(s))
2152 line.head = noderemove(line.list,n)
2153 end
2154 end
2155 end
2156 return head
2157 end
2158 % \end{macrocode}
2159 % \subsection{tanjanize}\label{sec:tanjanize}
2160 % \begin{macrocode}
2161 tanjanize = function(head)
2162 local s = nodenew(KERN)
2163 local m = nodenew(GLYPH,1)
2164 local use_letter_i = true
2165 scale = nodenew(WHAT,PDF_LITERAL)
2166 scale2 = nodenew(WHAT,PDF_LITERAL)
2167 scale.data = "0.5 0 0 0.5 0 0 cm"
2168 scale2.data = "2 0 0 2 0 0 cm"
2169
2170 for line in nodetraverseid(HLIST,head) do
2171 for n in nodetraverseid(GLYPH,line.head) do
2172 mimicount = 0
2173 tmpwidth = 0
2174 while ((n.next.id == GLYPH) or (n.next.id == 11) or (n.next.id == 7) or (n.next.id == 0)) do --find end of a word
2175 n.next = n.next.next
2176 mimicount = mimicount + 1
2177 tmpwidth = tmpwidth + n.width
2178 end
2179
2180 mimi = {} -- constructing the node list.
2181 mimi[0] = nodenew(GLYPH,1) -- only a dummy for the loop
2182 for i = 1,string.len(mimicount) do
2183 mimi[i] = nodenew(GLYPH,1)
2184 mimi[i].font = font.current()
2185 if(use_letter_i) then mimi[i].char = 109 else mimi[i].char = 105 end
2186 use_letter_i = not(use_letter_i)
2187 mimi[i-1].next = mimi[i]
2188 end
2189 --]]
2190
2191 line.head = nodeinsertbefore(line.head,n,nodecopy(scale))
2192 nodeinsertafter(line.head,n,nodecopy(scale2))
2193 s.kern = (tmpwidth*2-n.width)
2194 nodeinsertafter(line.head,n,nodecopy(s))
2195 end
2196 end
2197 return head
2198 end
2199 % \end{macrocode}
2200 % \subsection{uppercasecolor}\label{sec:uppercasecolor}
2201 % Loop through all the nodes and checking whether it is uppercase. If so (and also for small caps), color it.
2202 % \begin{macrocode}
2203 uppercasecolor_onlytext = false
2204
2205 uppercasecolor = function (head)
2206 for line in nodetraverseid(Hhead,head) do
2207 for upper in nodetraverseid(GLYPH,line.head) do
2208 if not(uppercasecolor_onlytext) or node.has_attribute(upper,luatexbase.attributes.uppercasecolorattr) then
2209 if (((upper.char > 64) and (upper.char < 91)) or
2210 ((upper.char > 57424) and (upper.char < 57451))) then -- for small caps! nice ☺
2211 color_push.data = randomcolorstring() -- color or grey string
2212 line.head = nodeinsertbefore(line.head,upper,nodecopy(color_push))
2213 nodeinsertafter(line.head,upper,nodecopy(color_pop))
2214 end
2215 end
2216 end
2217 end
2218 return head
2219 end
2220 % \end{macrocode}
2221 % \subsection{upsidedown}\label{sec:upsidedown}
2222 % This function mirrors all glyphs given in the array \verb|upsidedownarray| vertically.
2223 % \begin{macrocode}
2224 upsidedown = function(head)
2225 local factor = 65536/0.99626
2226 for line in nodetraverseid(Hhead,head) do
2227 for n in nodetraverseid(GLYPH,line.head) do
2228 if (upsidedownarray[n.char]) then
2229 shift = nodenew(WHAT,PDF_LITERAL)
2230 shift2 = nodenew(WHAT,PDF_LITERAL)
2231 shift.data = "q 1 0 0 -1 0 " .. n.height/factor .." cm"
2232 shift2.data = "Q 1 0 0 1 " .. n.width/factor .." 0 cm"
2233 nodeinsertbefore(head,n,shift)
2234 nodeinsertafter(head,n,shift2)
2235 end
2236 end
2237 end
2238 return head
2239 end
2240 % \end{macrocode}
2241 % \subsection{colorstretch}\label{sec:colorstretch}
2242 % This function displays the amount of stretching that has been done for each line of an arbitrary document. A well-typeset document should be equally grey over all lines, which is not always possible.
2243 %
2244 % In fact, two boxes are drawn: The first (left) box shows the badness, i.\,e. the amount of stretching the spaces between words. Too much space results in ligth grey, whereas a too dense line is indicated by a dark grey box.
2245 %
2246 %The second box is only useful if microtypographic extensions are used, e.\,g. with the |microtype| package under \LaTeX. The box color then corresponds to the amount of font expansion in the line. This works great for demonstrating the positive effect of font expansion on the badness of a line!
2247 %
2248 % The base structure of the following code was provided by Paul Isambert. Thanks for the code and support, Paul!
2249 % \subsubsection{colorstretch – preliminaries}
2250 % Two booleans, |keeptext|, and |colorexpansion|, are used to control the behaviour of the function.
2251 % \begin{macrocode}
2252 keeptext = true
2253 colorexpansion = true
2254
2255 colorstretch_coloroffset = 0.5
2256 colorstretch_colorrange = 0.5
2257 chickenize_rule_bad_height = 4/5 -- height and depth of the rules
2258 chickenize_rule_bad_depth = 1/5
2259
2260
2261 colorstretchnumbers = true
2262 drawstretchthreshold = 0.1
2263 drawexpansionthreshold = 0.9
2264 % \end{macrocode}
2265 % After these constants have been set, the function starts. It receives the vertical list of the typeset paragraph as |head|, and loops through all horizontal lists.
2266 %
2267 % If font expansion should be shown (|colorexpansion == true|), then the first glyph node is determined and its width compared with the width of the unexpanded glyph. This gives a measure for the expansion factor and is translated into a grey scale.
2268 % \begin{macrocode}
2269 colorstretch = function (head)
2270 local f = font.getfont(font.current()).characters
2271 for line in nodetraverseid(Hhead,head) do
2272 local rule_bad = nodenew(RULE)
2273
2274 if colorexpansion then -- if also the font expansion should be shown
2275 --%% here use first_glyph function!!
2276 local g = line.head
2277 n = node.first_glyph(line.head.next)
2278 texio.write_nl(line.head.id)
2279 texio.write_nl(line.head.next.id)
2280 texio.write_nl(line.head.next.next.id)
2281 texio.write_nl(n.id)
2282 while not(g.id == GLYPH) and (g.next) do g = g.next end -- find first glyph on line. If line is empty, no glyph:
2283 if (g.id == GLYPH) then -- read width only if g is a glyph!
2284 exp_factor = g.expansion_factor/10000 --%% neato, luatex now directly gives me this!!
2285 exp_color = colorstretch_coloroffset + (exp_factor*0.1) .. " g"
2286 texio.write_nl(exp_factor)
2287 rule_bad.width = 0.5*line.width -- we need two rules on each line!
2288 end
2289 else
2290 rule_bad.width = line.width -- only the space expansion should be shown, only one rule
2291 end
2292 % \end{macrocode}
2293 % Height and depth of the rules are adapted to print a closed grey pattern, so no white interspace is left.
2294 %
2295 % The glue order and sign can be obtained directly and are translated into a grey scale.
2296 % \begin{macrocode}
2297 rule_bad.height = tex.baselineskip.width*chickenize_rule_bad_height -- this should give a better output
2298 rule_bad.depth = tex.baselineskip.width*chickenize_rule_bad_depth
2299
2300 local glue_ratio = 0
2301 if line.glue_order == 0 then
2302 if line.glue_sign == 1 then
2303 glue_ratio = colorstretch_colorrange * math.min(line.glue_set,1)
2304 else
2305 glue_ratio = -colorstretch_colorrange * math.min(line.glue_set,1)
2306 end
2307 end
2308 color_push.data = colorstretch_coloroffset + glue_ratio .. " g"
2309
2310 % \end{macrocode}
2311 % Now, we throw everything together in a way that works. Somehow …
2312 % \begin{macrocode}
2313 -- set up output
2314 local p = line.head
2315
2316 -- a rule to immitate kerning all the way back
2317 local kern_back = nodenew(RULE)
2318 kern_back.width = -line.width
2319
2320 -- if the text should still be displayed, the color and box nodes are inserted additionally
2321 -- and the head is set to the color node
2322 if keeptext then
2323 line.head = nodeinsertbefore(line.head,line.head,nodecopy(color_push))
2324 else
2325 node.flush_list(p)
2326 line.head = nodecopy(color_push)
2327 end
2328 nodeinsertafter(line.head,line.head,rule_bad) -- then the rule
2329 nodeinsertafter(line.head,line.head.next,nodecopy(color_pop)) -- and then pop!
2330 tmpnode = nodeinsertafter(line.head,line.head.next.next,kern_back)
2331
2332 -- then a rule with the expansion color
2333 if colorexpansion then -- if also the stretch/shrink of letters should be shown
2334 color_push.data = exp_color
2335 nodeinsertafter(line.head,tmpnode,nodecopy(color_push))
2336 nodeinsertafter(line.head,tmpnode.next,nodecopy(rule_bad))
2337 nodeinsertafter(line.head,tmpnode.next.next,nodecopy(color_pop))
2338 end
2339 % \end{macrocode}
2340 % Now we are ready with the boxes and stuff and everything. However, a very useful information might be the amount of stretching, not encoded as color, but the real value. In concreto, I mean: narrow boxes get one color, loose boxes get another one, but only if the badness is above a certain amount. This information is printed into the right-hand margin. The threshold is user-adjustable.
2341 % \begin{macrocode}
2342 if colorstretchnumbers then
2343 j = 1
2344 glue_ratio_output = {}
2345 for s in string.utfvalues(math.abs(glue_ratio)) do -- using math.abs here gets us rid of the minus sign
2346 local char = unicode.utf8.char(s)
2347 glue_ratio_output[j] = nodenew(GLYPH,1)
2348 glue_ratio_output[j].font = font.current()
2349 glue_ratio_output[j].char = s
2350 j = j+1
2351 end
2352 if math.abs(glue_ratio) > drawstretchthreshold then
2353 if glue_ratio < 0 then color_push.data = "0.99 0 0 rg"
2354 else color_push.data = "0 0.99 0 rg" end
2355 else color_push.data = "0 0 0 rg"
2356 end
2357
2358 nodeinsertafter(line.head,node.tail(line.head),nodecopy(color_push))
2359 for i = 1,math.min(j-1,7) do
2360 nodeinsertafter(line.head,node.tail(line.head),glue_ratio_output[i])
2361 end
2362 nodeinsertafter(line.head,node.tail(line.head),nodecopy(color_pop))
2363 end -- end of stretch number insertion
2364 end
2365 return head
2366 end
2367 % \end{macrocode}
2368 % \subsection*{dubstepize} %% FIXME – Isn't that already implemented above?
2369 % BROOOAR WOBWOBWOB BROOOOAR WOBWOBWOB BROOOOAR WOB WOB WOB …
2370 % \begin{macrocode}
2371
2372 % \end{macrocode}
2373 % \subsection*{scorpionize}
2374 % This function's intentionally not documented. In memoriam scorpionem. %% FIXME
2375 % \begin{macrocode}
2376 function scorpionize_color(head)
2377 color_push.data = ".35 .55 .75 rg"
2378 nodeinsertafter(head,head,nodecopy(color_push))
2379 nodeinsertafter(head,node.tail(head),nodecopy(color_pop))
2380 return head
2381 end
2382 % \end{macrocode}
2383 % \subsection{variantjustification}\label{sec:variantjustification}
2384 % The list |substlist| defines which glyphs can be replaced by others. Use the unicode code points for this. So far, only wider variants are possible! Extend the list at will. If you find useful definitions, send me any glyph combination!
2385 %
2386 % Some predefined values for hebrew typesetting; the list is not local so the user can change it in a very transparent way (using |\chickenizesetup{}|. This costs runtime, however … I guess … (?)
2387 % \begin{macrocode}
2388 substlist = {}
2389 substlist[1488] = 64289
2390 substlist[1491] = 64290
2391 substlist[1492] = 64291
2392 substlist[1499] = 64292
2393 substlist[1500] = 64293
2394 substlist[1501] = 64294
2395 substlist[1512] = 64295
2396 substlist[1514] = 64296
2397 % \end{macrocode}
2398 % In the function, we need reproduceable randomization so every compilation of the same document looks the same. Else this would make contracts invalid.
2399 %
2400 % The last line is excluded from the procedure as it makes no sense to extend it this way. If you really want to typeset a rectangle, use the appropriate way to disable the space at the end of the paragraph (german “Ausgang“).
2401 % \begin{macrocode}
2402 function variantjustification(head)
2403 math.randomseed(1)
2404 for line in nodetraverseid(Hhead,head) do
2405 if (line.glue_sign == 1 and line.glue_order == 0) then -- exclude the last line!
2406 substitutions_wide = {} -- we store all “expandable” letters of each line
2407 for n in nodetraverseid(GLYPH,line.head) do
2408 if (substlist[n.char]) then
2409 substitutions_wide[#substitutions_wide+1] = n
2410 end
2411 end
2412 line.glue_set = 0 -- deactivate normal glue expansion
2413 local width = node.dimensions(line.head) -- check the new width of the line
2414 local goal = line.width
2415 while (width < goal and #substitutions_wide > 0) do
2416 x = math.random(#substitutions_wide) -- choose randomly a glyph to be substituted
2417 oldchar = substitutions_wide[x].char
2418 substitutions_wide[x].char = substlist[substitutions_wide[x].char] -- substitute by wide letter
2419 width = node.dimensions(line.head) -- check if the line is too wide
2420 if width > goal then substitutions_wide[x].char = oldchar break end -- substitute back if the line would be too wide and break out of the loop
2421 table.remove(substitutions_wide,x) -- if further substitutions have to be done, remove the just substituted node from the list
2422 end
2423 end
2424 end
2425 return head
2426 end
2427 % \end{macrocode}
2428 % That's it. Actually, the function is quite simple and should work out of the box. However, small columns will most probably not work as there typically is not much expandable stuff in a normal line of text.
2429 %
2430 % \subsection{zebranize}\label{sec:zebranize}
2431 % This function is inspired by a discussion with the Heidelberg regular's table and will change the color of each paragraph linewise. Both the textcolor and background color are changed to create a true zebra like look. If you want to change or add colors, just change the values of |zebracolorarray[]| for the text colors and |zebracolorarray_bg[]| for the background. Do not mix with other color changing functions of this package, as that will turn out ugly or erroneous.
2432 %
2433 % The code works just the same as every other thing here: insert color nodes, insert rules, and register the whole thing in |post_linebreak_filter|.
2434 % \subsubsection{zebranize – preliminaries}
2435 % \begin{macrocode}
2436 zebracolorarray = {}
2437 zebracolorarray_bg = {}
2438 zebracolorarray[1] = "0.1 g"
2439 zebracolorarray[2] = "0.9 g"
2440 zebracolorarray_bg[1] = "0.9 g"
2441 zebracolorarray_bg[2] = "0.1 g"
2442 % \end{macrocode}
2443 % \subsubsection{zebranize – the function}
2444 % This code has to be revisited, it is ugly.
2445 % \begin{macrocode}
2446 function zebranize(head)
2447 zebracolor = 1
2448 for line in nodetraverseid(Hhead,head) do
2449 if zebracolor == #zebracolorarray then zebracolor = 0 end
2450 zebracolor = zebracolor + 1
2451 color_push.data = zebracolorarray[zebracolor]
2452 line.head = nodeinsertbefore(line.head,line.head,nodecopy(color_push))
2453 for n in nodetraverseid(GLYPH,line.head) do
2454 if n.next then else
2455 nodeinsertafter(line.head,n,nodecopy(color_pull))
2456 end
2457 end
2458
2459 local rule_zebra = nodenew(RULE)
2460 rule_zebra.width = line.width
2461 rule_zebra.height = tex.baselineskip.width*4/5
2462 rule_zebra.depth = tex.baselineskip.width*1/5
2463
2464 local kern_back = nodenew(RULE)
2465 kern_back.width = -line.width
2466
2467 color_push.data = zebracolorarray_bg[zebracolor]
2468 line.head = nodeinsertbefore(line.head,line.head,nodecopy(color_pop))
2469 line.head = nodeinsertbefore(line.head,line.head,nodecopy(color_push))
2470 nodeinsertafter(line.head,line.head,kern_back)
2471 nodeinsertafter(line.head,line.head,rule_zebra)
2472 end
2473 return (head)
2474 end
2475 % \end{macrocode}
2476 % And that's it!\qquad {\fontsize{40}{0}\raisebox{-2ex}{\XITS ☺}}
2477 % \newpage
2478 % Well, it's not the whole story so far. I plan to test some drawing using only Lua code, writing directly to the pdf file. This section will grow and get better in parallel to my understandings of what's going on. I.e. it will be very slowly … Nothing here is to be taken as good and/or correct LuaTeXing, and most code is plain ugly. However, it kind of works already {\XITS ☺}
2479 % \section{Drawing}
2480 % A \emph{very} first, experimental implementation of a drawing of a chicken. The parameters should be consistent, easy to change and that monster should look more like a cute chicken. However, it is chicken, it is Lua, so it belongs into this package. So far, all numbers and positions are hard coded, this will of course change!
2481 % The parameters |sloppinessh| and |sloppinessv| give the amount of sloppiness, i.\,e.~how strongly the points are “wiggled” randomly to make the drawings more dynamically. You can set them at any time in the document
2482 % \begin{macrocode}
2483 --
2484 function pdf_print (...)
2485 for _, str in ipairs({...}) do
2486 pdf.print(str .. " ")
2487 end
2488 pdf.print("\n")
2489 end
2490
2491 function move (p1,p2)
2492 if (p2) then
2493 pdf_print(p1,p2,"m")
2494 else
2495 pdf_print(p1[1],p1[2],"m")
2496 end
2497 end
2498
2499 function line(p1,p2)
2500 if (p2) then
2501 pdf_print(p1,p2,"l")
2502 else
2503 pdf_print(p1[1],p1[2],"l")
2504 end
2505 end
2506
2507 function curve(p11,p12,p21,p22,p31,p32)
2508 if (p22) then
2509 p1,p2,p3 = {p11,p12},{p21,p22},{p31,p32}
2510 else
2511 p1,p2,p3 = p11,p12,p21
2512 end
2513 pdf_print(p1[1], p1[2],
2514 p2[1], p2[2],
2515 p3[1], p3[2], "c")
2516 end
2517
2518 function close ()
2519 pdf_print("h")
2520 end
2521
2522 % \end{macrocode}
2523 % By setting |drawwidth| to something different than 1 you can adjust the thickness of the strokes. Any stroke done with the |sloppy| functions will by varied between |0.5 drawwidth| and |1.5 drawwidth|.
2524 % \begin{macrocode}
2525 drawwidth = 1
2526
2527 function linewidth (w)
2528 pdf_print(w,"w")
2529 end
2530
2531 function stroke ()
2532 pdf_print("S")
2533 end
2534 --
2535
2536 function strictcircle(center,radius)
2537 local left = {center[1] - radius, center[2]}
2538 local lefttop = {left[1], left[2] + 1.45*radius}
2539 local leftbot = {left[1], left[2] - 1.45*radius}
2540 local right = {center[1] + radius, center[2]}
2541 local righttop = {right[1], right[2] + 1.45*radius}
2542 local rightbot = {right[1], right[2] - 1.45*radius}
2543
2544 move (left)
2545 curve (lefttop, righttop, right)
2546 curve (rightbot, leftbot, left)
2547 stroke()
2548 end
2549
2550 sloppynessh = 5
2551 sloppynessv = 5
2552
2553 function disturb_point(point)
2554 return {point[1] + (math.random() - 1/2)*sloppynessh,
2555 point[2] + (math.random() - 1/2)*sloppynessv}
2556 end
2557
2558 function sloppycircle(center,radius)
2559 local left = disturb_point({center[1] - radius, center[2]})
2560 local lefttop = disturb_point({left[1], left[2] + 1.45*radius})
2561 local leftbot = {lefttop[1], lefttop[2] - 2.9*radius}
2562 local right = disturb_point({center[1] + radius, center[2]})
2563 local righttop = disturb_point({right[1], right[2] + 1.45*radius})
2564 local rightbot = disturb_point({right[1], right[2] - 1.45*radius})
2565
2566 local right_end = disturb_point(right)
2567
2568 move (right)
2569 curve (rightbot, leftbot, left)
2570 curve (lefttop, righttop, right_end)
2571 linewidth(drawwidth*(math.random()+0.5))
2572 stroke()
2573 end
2574
2575 function sloppyellipsis(center,radiusx,radiusy)
2576 local left = disturb_point({center[1] - radiusx, center[2]})
2577 local lefttop = disturb_point({left[1], left[2] + 1.45*radiusy})
2578 local leftbot = {lefttop[1], lefttop[2] - 2.9*radiusy}
2579 local right = disturb_point({center[1] + radiusx, center[2]})
2580 local righttop = disturb_point({right[1], right[2] + 1.45*radiusy})
2581 local rightbot = disturb_point({right[1], right[2] - 1.45*radiusy})
2582
2583 local right_end = disturb_point(right)
2584
2585 move (right)
2586 curve (rightbot, leftbot, left)
2587 curve (lefttop, righttop, right_end)
2588 linewidth(drawwidth*(math.random()+0.5))
2589 stroke()
2590 end
2591
2592 function sloppyline(start,stop)
2593 local start_line = disturb_point(start)
2594 local stop_line = disturb_point(stop)
2595 start = disturb_point(start)
2596 stop = disturb_point(stop)
2597 move(start) curve(start_line,stop_line,stop)
2598 linewidth(drawwidth*(math.random()+0.5))
2599 stroke()
2600 end
2601 % \end{macrocode}
2602 %\iffalse
2603 % </lua>
2604 %\fi
2605 % \newpage
2606 % \section{Known Bugs and Fun Facts}\label{bugs}
2607 % The behaviour of the |\chickenize| macro is under construction and everything it does so far is considered a feature.
2608 % \begin{description}
2609 % \item[babel] Using |chickenize| with |babel| leads to a problem with the " (double quote) character, as it is made active: When using |\chickenizesetup| \emph{after} |\begin{document}|, you can \emph{not} use " for strings, but you have to use ' (single quote) instead. No problem really, but take care of this.
2610 % \item[medievalumlaut] You should use a decent OpenType font to get the best result. The standard font will not nicely support the positioning of the e character.
2611 % \item[boustrophedon and chickenize] do not work together nicely. There is an additional shift I cannot explain so far. However, if you really, really need a boustrophedon of chickenize, you do have some serious problems.
2612 % \item[letterspaceadjust and chickenize] When using both letterspaceadjust and chickenize, make sure to activate |\chickenize| before |\letterspaceadjust|. Elsewise the chickenization will not work due to the implementation of letterspaceadjust.
2613 % \end{description}
2614 % \section{To Do's}
2615 % Some things that should be implemented but aren’t so far or are very poor at the moment:
2616 % \begin{description}
2617 % \item[traversing] Every function that is based on node traversing fails when boxes are involved – so far I have not implemented recursive calling of the functions. I list it here, as it is not really a bug – this package is meant to be as simple as possible!
2618 % \item[countglyphs] should be extended to count anything the user wants to count
2619 % \item[rainbowcolor] should be more flexible – the angle of the rainbow should be easily adjustable.
2620 % \item[pancakenize] should do something funny.
2621 % \item[chickenize] should differentiate between character and punctuation.
2622 % \item[swing] swing dancing apes – that will be very hard, actually …
2623 % \item[chickenmath] chickenization of math mode
2624 % \end{description}
2625 % \section{Literature}\label{sec:literature}
2626 % The following list directs you to helpful literature that will help you to better understand the concepts used in this package and for in-depth explanation. Also, most of the code here is taken from or based on this literature, so it is also a list of references somehow:
2627 % \begin{itemize}
2628 % \item Lua\TeX\ documentation – the manual and links to presentations and talks: \url{http://www.luatex.org/documentation.html}
2629 % \item The Lua manual, for Lua 5.1: \url{http://www.lua.org/manual/5.1/}
2630 % \item Programming in Lua, 1\textsuperscript{st} edition, aiming at Lua 5.0, but still (largely) valid for 5.1: \url{http://www.lua.org/pil/}
2631 %
2632 %
2633 % \end{itemize}
2634 % \section{Thanks}
2635 % This package would not have been possible without the help of many people who patiently answered my annoying questions on mailing lists and in personal mails. And of course not without the work of the Lua\TeX\ team!
2636 %
2637 % Special thanks go to Paul “we could have chickenized the world” Isambert who contributed a lot of ideas, code and bug fixes and made much of the code executable at all. I also thank Philipp Gesang who gave me many advices on the Lua code – which I still didn't have time to correct …
2638 % \Finale
2639 % \endinput