To further extend my recent question about new listings environments, found here: Multiple listings styles.

How do I define a new lstlistings environment, via the command \lstnewenvironment, and, be able to use the command \lstinputlisting to draw the desired contents from file?

I am referring to newly created lstlistingenvironments via the command \lstnewenvironment{MYENV}. These are then accessed by


Anything where BODY is, gets formatted, including the command \input{mycode.whatever}, instead of pulling the contents of the file mycode.whatever and formatting the contents.

  • No just code that I want to be formatted, ie a source file from an application. – Nicholas Hamilton May 11 '13 at 17:28
  • Yeah but whats the way to read contents from file, and put it in the body of an environment. – Nicholas Hamilton May 11 '13 at 17:34

If the file contains the appropriate listing environment (like cplusplus or rcode), then you can just use \input{<filename>}. If it doesn't (or just contains the raw code that should be formatted), you can create a new command that does all of the setup for you, just like it would for your \lstnewenvironment creations. The following can be used in conjunction with the solution in Multiple listings styles:

enter image description here

\usepackage{listings}% http://ctan.org/pkg/listings
\usepackage{filecontents}% http://ctan.org/pkg/filecontents

// 'Hello World!' program 

#include <iostream>

int main()
  std::cout << "Hello World!" << std::endl;
  return 0;
cat('Hello, world!\n')
print "Hello world"

% --------------------------------------- C++
\newcommand{\lstlistcplusplusname}{List of C++}
    \let\lst@temp\@starttoc \def\@starttoc##1{\lst@temp{loc}}%
    \tableofcontents \egroup}
  \renewcommand{\lstlistingname}{C++ Code}%
% --------------------------------------- R
\newcommand{\lstlistrcodename}{List of R}
    \let\lst@temp\@starttoc \def\@starttoc##1{\lst@temp{lor}}%
    \tableofcontents \egroup}
  \renewcommand{\lstlistingname}{R Code}%
% --------------------------------------- Pseudocode
\newcommand{\lstlistpseudocodename}{List of Pseudocode}
    \let\lst@temp\@starttoc \def\@starttoc##1{\lst@temp{lop}}%
    \tableofcontents \egroup}


\lstinputcplusplus[caption={Hello world}]{cplusplus.c}

\lstinputrcode[caption={Hello world}]{rcode.r}

\lstinputpseudocode[caption={Hello world}]{pseudocode.p}


The macros provided for inputting a listing of a specific type are \lstinputcplusplus[<options>]{<filename>}, \lstinputrcode[<options>]{<filename>} and \lstinputpseudocode[<options>]{<filename>}.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.