Sometimes we need to include codes in our Latex documents. In this post we will see how to add codes with color formatting and line numbers.
We need to packages to work with code environments. listing is used to create styles and environments for adding codes in the document. color or xcolor is used to define custom colors only if you feel to use a custom one.
\usepackagelistings> \usepackagexcolor>
If you need to use custom defined colors, you can use \definecolor command followed by the custom color name and the rgb settings.
\definecolorcustomgreen>rgb>0,0.6,0> \definecolorcustomgray>rgb>0.5,0.5,0.5> \definecolorcustommauve>rgb>0.6,0,0.8>
Based on LaTeX/Source Code Listings, the package supports the following languages.
ABAP2,4, ACSL, Ada4, Algol4, Ant, Assembler2,4, Awk4, bash, Basic2,4, C#5, C++4, C4, Caml4, Clean, Cobol4, Comal, csh, Delphi, Eiffel, Elan, erlang, Euphoria, Fortran4, GCL, Go (golang), Gnuplot, Haskell, HTML, IDL4, inform, Java4, JVMIS, ksh, Lisp4, Logo, Lua2, make4, Mathematica1,4, Matlab, Mercury, MetaPost, Miranda, Mizar, ML, Modelica3, Modula-2, MuPAD, NASTRAN, Oberon-2, Objective C5, OCL4, Octave, Oz, Pascal4, Perl, PHP, PL/I, Plasm, POV, Prolog, Promela, Python, R, Reduce, Rexx, RSL, Ruby, S4, SAS, Scilab, sh, SHELXL, Simula4, SQL, tcl4, TeX4, VBScript, Verilog, VHDL4, VRML4, XML, XSLT
Here, we will see two different ways to use styles and environments: one is common and can be used for any language, another is defining custom style and environment for different languages.
We can define common formatting for any language we want to include in our document.
\lstset basicstyle=\small, % the size of the fonts that are used for the code breaklines=true, % sets automatic line breaking commentstyle=\colorcustomgreen>, % comment style firstnumber=1, % start line enumeration with line 1000 frame=single, % adds a frame around the code keepspaces=true, % keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible) keywordstyle=\colorblue>, % keyword style numbers=left, % where to put the line-numbers; possible values are (none, left, right) numbersep=10pt, % how far the line-numbers are from the code numberstyle=\tiny\colorcustomgray>, % the style that is used for the line-numbers rulecolor=\colorblack>, % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. comments (green here)) showspaces=false, % show spaces everywhere adding particular underscores; it overrides 'showstringspaces' showstringspaces=false, % underline spaces within strings only showtabs=false, % show tabs within strings adding particular underscores stepnumber=1, % the step between two line-numbers. If it's 1, each line will be numbered stringstyle=\colorcustommauve>, % string literal style tabsize=2, % sets default tabsize to 2 spaces title=\lstname % show the filename of files included with \lstinputlisting; also try caption instead of title >
Now, include your code within the \begin. \end with defining the language you want to format with. For python, it will look like as follows:
\begin [language=python] class MyClass(Yourclass): def __init__(self, test): self.test = test \end
Or for a C program
\begin [language=C] #include int main() // printf() displays the string printf("Hello, World!"); return 0; > \end
For adding an external file, we can use \lstinputlisting and define the language as well. For including an external python file, the code will look like as follows:
\lstinputlisting[language=python]mypythonfile.py>
We can define custom styles and environments as well for different languages. In that case, first we will have to define a new style, for example, for python it might look like as follows
\DeclareFixedFont\ttb>T1>txtt>bx>n>9> % for bold \DeclareFixedFont\ttm>T1>txtt>m>n>9> % for normal \newcommand\pystyle\lstset language=Python, basicstyle=\ttm, morekeywords=self>, % Add more keywords here commentstyle=\colorgray>, keywordstyle=\ttb\colorblue>, emphstyle=\ttb\colorred>, % Custom highlighting style stringstyle=\colorgreen>, showstringspaces=false >>
Then we have to define a new environment for python using a custom name (here we used python )
\lstnewenvironmentpython>[1][] \pystyle \lstset#1> > <>
This allows you to put your code inside
\begin # your code goes here \end
This is how we can add custom environment for each and every language. However, this requires time to do that for every language.
That’s it for today! Cheers.
You can find a comprehensive list of Latex resources in the following post:
If you are a new Latex user, check out this post: 20 Most Common Mistakes Made by New Latex Users
You can find all Latex oriented posts of mine in: https://shantoroy.com/categories/#latex
Categories: Latex
Updated: June 7, 2020