
자동 포맷터를 적용하고 싶은 일부 데이터를 다루고 있습니다. 내 모델에 맞는 "언어"를 정의하기 위해 목록 패키지를 사용하려고 하는데 성공하지 못했습니다.
예를 들어 다음과 같은 형식을 지정하고 싶습니다.
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}