58

What is the command to insert inline code words into the text like this? enter image description here

I know there are packages for inserting snippets into the code, but I need to insert keywords within the main text. I was wondering if there is a more convenient way to do that.

1

2 Answers 2

59

The package listings provides \lstinline for such short snippets. The advantage of such a package is its awareness of keywords etc.

In principle any formatting can be used for the 'code' -- as long as the syntax does not interfere with TeX/LaTeX syntax all is well.

The package xparse allows for verbatim arguments, it can be used as well.

\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}

\usepackage{xparse}

\NewDocumentCommand{\codeword}{v}{%
\texttt{\textcolor{blue}{#1}}%
}

\lstset{language=C,keywordstyle={\bfseries \color{blue}}}

\begin{document}

\lstinline{for} or \lstinline{while} or \lstinline{main}

\codeword{Here} you \codeword{see} an \codeword{example} of \codeword{an} inline \codeword{code}

\end{document}

enter image description here

4
  • And of course you can specify your preferred font for code snippets in the \lstset, not just the colour/weight.
    – Chris H
    Commented Jan 5, 2016 at 13:58
  • 2
    How do we make this look like Stackexchange syntax highlighting?
    – Miladiouss
    Commented Nov 22, 2019 at 21:46
  • The answer works but it changes the style of the all remaing source text in the document: tex.stackexchange.com/q/536192/60344. Commented Mar 31, 2020 at 19:01
  • 1
    lstinline can also be used with vertical bars. Example: \lstinline|os.isfile()| Commented Jul 14, 2021 at 8:07
36

This is also possible using the minted package and the highlighting tool pygmentize

The command for minted inline code is called \mintinline{language}{code}

The inline highlighting will only colorize keywords, that are defined for the language and colored properly according to the highlighting style you choose.

\documentclass{scrartcl}

\usepackage{minted}
\usemintedstyle{vs}

\begin{document}
    To create a table you could use the command \mintinline{MySQL}{ALTER TABLE}. 
    While  \mintinline{MySQL}{DROP TABLE} deletes a table,
    \mintinline{MySQL}{INSERT} enables you to insert something into a table.
\end{document}

Which gives you:

enter image description here

Note that the default highlighting style gives you green keywords and you need to use --shell-escape to get pygmentize to work.

4

You must log in to answer this question.

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