UP | HOME

LaTeX code snippets

This page contains various use code snippets. The preamble part shows what is needed at the beginning of a LaTeX document and the syntax shows how it is used in the text. Some of the example only require either a preamble or the syntax.

Support for German

preamble

%Support for German
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{ngerman}

Support for Images

Let's you insert a picture, centers it and scales it to 0.88 times the width of the page.

preamble

\usepackage{graphicx}

syntax

\noindent\makebox[\textwidth]{\includegraphics[width=0.88\paperwidth]{picture.png}}

Code with Syntax Highlighting

To change the Code language you'll have to edit the ​language=bash, line to the corresponding language e.g. language=python,.

preamble

\usepackage{listings}
\usepackage{color}
\usepackage{inconsolata}
\definecolor{mygreen}{rgb}{0,0.6,0}
\definecolor{mygray}{rgb}{0.5,0.5,0.5}
\definecolor{mymauve}{rgb}{0.58,0,0.82}
\lstset{
  basicstyle=\ttfamily,
  language=bash,
  breaklines,
  literate={ö}{{\"o}}1
           {ä}{{\"a}}1
           {ü}{{\"u}}1,
  captionpos=b,                    % sets the caption-position to bottom
  commentstyle=\color{mygreen},    % comment style
  escapeinside={\%*}{*)},          % if you want to add LaTeX within your code
  keywordstyle=\color{blue},       % keyword style
  stringstyle=\color{mymauve},     % string literal style
  showstringspaces=false,          % Removes the strange symboles where spaces are
}

Syntax

\begin{lstlisting}
Code with Syntax Highlighting
\end{lstlisting}

Code Box

To make this easier to use with org-mode I've written a little BASH script which replaces the normal listings of the org-mode exports with the sexylisting environment I'm usually using for code blocks. replace-listings.sh

preamble

% Listing with a box around it
\usepackage[most]{tcolorbox}
\newtcblisting{sexylisting}[2][]{
  sharp corners,
  fonttitle=\bfseries,
  colframe=gray,
  listing only,
  listing options={basicstyle=\ttfamily,language=bash},
  title=\thetcbcounter #2, #1
}

syntax

\begin{sexylisting}{Box Title}
Code in a Box
\end{sexylisting}{Some Code}

Sans Serif Helvetica

preamble

%Font settings
\renewcommand{\familydefault}{\sfdefault}  % Enable Sans Serif
\usepackage{helvet}  % Sets the font

Source Serif Pro

preamble

\usepackage{xltxtra}
\setmainfont{Source Serif Pro}

Make sure that you don't have any other font settings set and that the compiler is set to XeTeX.

Table Layout with more Space

Left alligned table with more space for the text inside it.

preamble

\renewcommand\arraystretch{1.5}%

syntax

\begin{tabular}{ |l|l| }
\hline
Text in Cell A1 & Text in Cell B1\\
\hline
Text in Cell A2 & Text in Cell B2\\
\hline
\end{tabular}

Colored URLs

\usepackage{hyperref}
\hypersetup{
    colorlinks=true,
    linkcolor=black,
    urlcolor=blue,
}
\urlstyle{same}
\url{http://example.com}

Increase Linespacing

\linespread{1.5}

Where 1.5 is a factor.