How to make a single word look as some code?

Normally a monospaced font is used for this. This is accomplished with \texttt{...}. If you want to use code, you can use \def\code#1{\texttt{#1}}. From that point on you can write \code{...} to get monospaced output.


If you want a single word to look like a coded word and also to have a light-gray background as in StackExchange you can predefine a color \definecolor{light-gray}{gray}{0.95} and then define a new command: \newcommand{\code}[1]{\colorbox{light-gray}{\texttt{#1}}}.

From this point on you can use \code{word} to get mono-spaced words with gray background.

Of course for this to work you will need to load the xcolor package before \definecolor.

A full example would look like this:

% Better inline directory listings
\usepackage{xcolor}
\definecolor{light-gray}{gray}{0.95}
\newcommand{\code}[1]{\colorbox{light-gray}{\texttt{#1}}}

I can't believe nobody mentioned the listings package. It provides a command called \lstinline{your_code} which can even highlight keywords for you.

See also this question: Should I use \lstinline for the language keywords embedded in text?

Tags:

Fonts

Code