0

I'm looking for a lightweight alternative to inline code listings that is able to make keywords bold. I'm imagining something like the following:

\declarekeywords{if,then,else}
\declarestylecommand\textbf
The expression \texttt{\stylekeywords{if a then b else c}} evaluates to ...

should expand to:

The expression \texttt{\textbf{if} a \textbf{then} b \textbf{else} c} evaluates to ...

The idea is that this command can be adapted to work in many different contexts, for example math mode:

\stylekeywords{let $x = a + b$ in $f(x)$}

1 Answer 1

3

A regex expression in expl3 can add formatting:

regex highlighting

MWE

\documentclass{article}
\usepackage{xcolor}
\usepackage{xparse}

\ExplSyntaxOn

\tl_new:N \l_mykeywords_tl

\NewDocumentCommand { \stylekeywords } { m } {%
\tl_set:Nn 
     \l_mykeywords_tl 
     { #1 }
\dostylekeywords
}

\newcommand{\simplehl}[1]{
\regex_replace_all:nnN 
       { (#1) } 
       { 
            \c{textcolor} \cB\{ blue \cE\} \cB\} 
                   \c{textbf} \cB\{ \0 \cE\} 
            \cE\} 
            } 
       \l_mykeywords_tl

}

\newcommand{\dostylekeywords}{
    \simplehl{[tT]hen}
    \simplehl{[eE]lse}
    \simplehl{let}
    \simplehl{[iI]f}
    \simplehl{in}

    \tl_use:N 
       \l_mykeywords_tl
}

\ExplSyntaxOff

\begin{document}

The expression \texttt{\stylekeywords{if a then b else c}} evaluates to ...

\stylekeywords{let $x = a + b$ in $f(x)$}

\end{document}
1
  • Do texdoc interface3 to open the expl3 documentation.
    – Cicada
    Commented Jan 16, 2022 at 15:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .