The listings package enables LaTeX users to include source code snippets into LaTeX documents. The source code can be formatted using predefined languages templates. To select a predefined language, use the following code (as an example, Python is used):
\usepackage{listings} \lstset{language=Python} \lstinputlisting{path/to/myFile.py} |
However, it is also possible to define own formatting templates for custom languages, which can be useful for developers of Domain-specific Languages (DSLs), for example. This is accomplished by using the command \lstdefinelanguage. The following example defines a language named myLang with various keywords, single line comments prefixed with //, multiline comments delimited by /* and */ and Strings delimited with double quotes:
% Define Language \lstdefinelanguage{myLang} { % list of keywords morekeywords={ import, if, while, for }, sensitive=false, % keywords are not case-sensitive morecomment=[l]{//}, % l is for line comment morecomment=[s]{/*}{*/}, % s is for start and end delimiter morestring=[b]" % defines that strings are enclosed in double quotes } |
Subsequently you can use the \lstset command to activate your language template for all following listings. All parameters are documented inline. This results in nice listings with line numbers, borders with rounded corners and syntax highlighting for comments, keywords and strings. The colors are based on the Java highlighting style in Eclipse:
% Define Colors \usepackage{color} \definecolor{eclipseBlue}{RGB}{42,0.0,255} \definecolor{eclipseGreen}{RGB}{63,127,95} \definecolor{eclipsePurple}{RGB}{127,0,85} % Set Language \lstset{ language={myLang}, basicstyle=\small\ttfamily, % Global Code Style captionpos=b, % Position of the Caption (t for top, b for bottom) extendedchars=true, % Allows 256 instead of 128 ASCII characters tabsize=2, % number of spaces indented when discovering a tab columns=fixed, % make all characters equal width keepspaces=true, % does not ignore spaces to fit width, convert tabs to spaces showstringspaces=false, % lets spaces in strings appear as real spaces breaklines=true, % wrap lines if they don't fit frame=trbl, % draw a frame at the top, right, left and bottom of the listing frameround=tttt, % make the frame round at all four corners framesep=4pt, % quarter circle size of the round corners numbers=left, % show line numbers at the left numberstyle=\tiny\ttfamily, % style of the line numbers commentstyle=\color{eclipseGreen}, % style of comments keywordstyle=\color{eclipsePurple}, % style of keywords stringstyle=\color{eclipseBlue}, % style of strings } |
That’s it. Now you can include your listings in your custom language using
\lstinputlisting{path/to/myFile.ext} |
Now have fun with your language and LaTeX 🙂