[Tex/LaTex] New Command For Inline Code

listingsmacros

I am using the listings package to enter large blocks of code into my document, however I am trying to write a custom command that uses my current settings to do inline code. For example I want to be able to say something like:

To create a new function in Python that took two arguments you would use

\inlinecode{def myFunction(x, y):}

EDIT: Here are is my MWE:

\documentclass{article}
\usepackage{listings,lstautogobble}
\usepackage[usenames,dvipsnames]{color}
\newcommand{\inlinecode}[1]{\begin{lstlisting}#1\end{lstlisting}}

% Custom Python Syntax
\lstset
{
    basicstyle=\small\ttfamily,
    commentstyle=\color{Green},
    keywordstyle=\color{Cerulean},
    frame=L,
    language=python,
    morekeywords={True, False},
    numbers=left,
    numbersep=10pt,
    numberstyle=\footnotesize\color{Gray},
    showstringspaces=false,
    stringstyle=\color{Mulberry},
    tabsize=3,
}

% Color Numbers
\lstset
{
    literate=%
    {0}{{{\color{Orange}0}}}1
    {1}{{{\color{Orange}1}}}1
    {2}{{{\color{Orange}2}}}1
    {3}{{{\color{Orange}3}}}1
    {4}{{{\color{Orange}4}}}1
    {5}{{{\color{Orange}5}}}1
    {6}{{{\color{Orange}6}}}1
    {7}{{{\color{Orange}7}}}1
    {8}{{{\color{Orange}8}}}1
    {9}{{{\color{Orange}9}}}1
}

\begin{document}
    To create a new function in Python that took two arguments you would use \inlinecode{def myFunction(x, y):}
\end{document}

and my new command is:

\newcommand{\inlinecode}[1]{\begin{lstlisting}#1\end{lstlisting}}

however I keep getting this error:

Console Output

I have hardly any experience writing custom commands so I assume that's where my problem is.

Best Answer

The macro for inputting inline code is \lstinline[option]{<code} Hence use \newcommand{\inlinecode}[1]{\lstinline{#1}}.

\documentclass{article}
\usepackage{listings,lstautogobble}
\usepackage[usenames,dvipsnames]{color}
\newcommand{\inlinecode}[1]{\lstinline{#1}}

% Custom Python Syntax
\lstset
{
    basicstyle=\small\ttfamily,
    commentstyle=\color{Green},
    keywordstyle=\color{Cerulean},
    frame=L,
    language=python,
    morekeywords={True, False},
    numbers=left,
    numbersep=10pt,
    numberstyle=\footnotesize\color{Gray},
    showstringspaces=false,
    stringstyle=\color{Mulberry},
    tabsize=3,
}

% Color Numbers
\lstset
{
    literate=%
    {0}{{{\color{Orange}0}}}1
    {1}{{{\color{Orange}1}}}1
    {2}{{{\color{Orange}2}}}1
    {3}{{{\color{Orange}3}}}1
    {4}{{{\color{Orange}4}}}1
    {5}{{{\color{Orange}5}}}1
    {6}{{{\color{Orange}6}}}1
    {7}{{{\color{Orange}7}}}1
    {8}{{{\color{Orange}8}}}1
    {9}{{{\color{Orange}9}}}1
}

\begin{document}
    To create a new function in Python that took two arguments you would use \inlinecode{def myFunction(x, y):}
\end{document}

enter image description here

But why not use \lstinline directly? Or you can simply do \newcommand{\inlinecode}{\lstinline} as suggested by Werner.

Related Question