
我正在處理一些我想應用自動格式化程式的資料。我正在嘗試使用列表包來定義適合我的模型的“語言”,但我沒有成功。
例如,我想格式化:
3 HHHHHHHHHHHHHHLLLHH 21
||| | |
3 LLHHHHHHHHHHHHLLLLL 21
對於這樣的事情:
即,字母H具有特定顏色,字母L具有另一種顏色,依此類推。如果字母之間有空格,那就很簡單了,因為
\lstdefinelanguage{MyKindOfLanguage}
{morekeywords={H,L,E},
sensitive=true,
}
會將 H、L 和 E 識別為關鍵字,但在我的情況下,這些字元之間沒有空格。也許我使用了錯誤的套件來做到這一點,所以我問是否有辦法做到這一點。如果我使用正規表示式來指定模式會更好。我可以編寫一個程式來使用 \textcolor 將此程式碼轉換為格式化程式碼,但我想讓編譯器為我完成此操作。
答案1
\documentclass{article}
\usepackage{color}
{
\catcode`H\active
\catcode`L\active
\catcode`\ \active
\gdef\foo{%
\catcode`H\active
\catcode`L\active
\catcode`\ \active
\ttfamily\obeylines\obeyspaces
\def {\ }%
\defH{\textcolor{magenta}{\stringH}}%
\defL{\textcolor{yellow}{\stringL}}%
}%
}%
\def\endfoo{\par}
\begin{document}
\begin{foo}
3 HHHHHHHHHHHHHHLLLHH 21
||| | |
3 LLHHHHHHHHHHHHLLLLL 21
\end{foo}
\end{document}
答案2
使用listings
的literate
選項來為每個要著色的字母指定搜尋和替換:
\documentclass{article}
\usepackage{listings,xcolor}
\lstnewenvironment{foo}[1][]
{\lstset{
basicstyle=\ttfamily,
literate={H}{{{\color{red!20!blue}H}}}1
{L}{{{\color{yellow!20!green}L}}}1,
#1
}}
{}
\begin{document}
\begin{foo}
3 HHHHHHHHHHHHHHLLLHH 21
||| | |
3 LLHHHHHHHHHHHHLLLLL 21
\end{foo}
\end{document}
答案3
有點複雜,但有一個更友好的介面來定義顏色:
\documentclass{article}
\usepackage{xparse,l3regex,xcolor}
\usepackage{lipsum}
\ExplSyntaxOn
\NewDocumentCommand{\foo}{}
{
\begin{flushleft}\ttfamily
% we need to make spaces active, so we let them to a skip
% the change is local to the flushleft environment
\char_set_active_eq:nN { `\ } \buzatto_foo_space:
\char_set_catcode_active:n { `\ }
\buzatto_foo_process:n
}
\NewDocumentCommand{\definefoocolor}{mm}
{
% store in a property list: <letter> -> <color>
\prop_gput:Nnn \g_buzatto_foo_prop { #1 } { #2 }
}
\tl_new:N \l_buzatto_foo_arg_tl
\prop_new:N \g_buzatto_foo_prop
\cs_new_protected:Nn \buzatto_foo_space:
{
\hspace*{.5em}
}
\cs_new_protected:Nn \buzatto_foo_process:n
{
\tl_set:Nn \l_buzatto_foo_arg_tl { #1 }
% process all the keys in the property list
\prop_map_inline:Nn \g_buzatto_foo_prop
{
% any run of the current letter is changed into
% \textcolor{<color>}{<run of letters>}
\regex_replace_all:nnN
{ (##1+) }
{ \c{textcolor}\cB\{##2\cE\}\cB\{\1\cE\} }
\l_buzatto_foo_arg_tl
}
% use the returned token list
\tl_use:N \l_buzatto_foo_arg_tl
\end{flushleft}
}
\ExplSyntaxOff
\definefoocolor{H}{red!20!blue}
\definefoocolor{L}{yellow!20!green}
\begin{document}
\lipsum[2]
\foo{
3 HHHHHHHHHHHHHHLLLHH 21 \\
||| | | \\
3 LLHHHHHHHHHHHHLLLLL 21
}
\lipsum[3]
\end{document}