Using \verbatim as part of an argument for a macro? - latex

Most things I've wanted to do in LaTeX have either been straight-forward, or easily found on the web, but this one has been stumping me.
I have a macro 'solution': to apply some common formatting to each solution:
\newcommand\solution[1]{{\\ \\* \bf Solution.}#1\qed \newpage}
Which has worked nicely so far, but now I wanted to include a drawing which I've done quickly using 'ASCII Art' so I'd like to use \verbatim. But it doesn't work, it produces the following errors:
Runaway argument?
...
! File ended while scanning use of \#xverbatim.
From what I read in the "Not So Short introduction to LaTeX", \verbatim can't be used this way. I assume there is a better way to do what I'm trying to do?

This is a FAQ.

You could try changing \newcommand to \newenvironment and then use something like
\begin{solution}
\begin{verbatim}
[ascii art here]
\end{verbatim}
\end{solution}

Use the package cprotect
e.g. ( with tcolorbox but it is working with most of the newcommand created)
\usepackage{tcolorbox}
\usepackage{cprotect}
\newcommand{\tcb}[1] {
\begin{tcolorbox} [arc=0mm,colback=bginf,coltitle=black!70!black,colframe=black!30!white,width=\linewidth,fontupper=\bfseries\small,halign title=flush center,halign upper=center]
#1
\end{tcolorbox}
}
\cprotect\tcb{\scriptsize
\begin{verbatim}
...
\end{verbatim}
}

Related

How to automatic break lines in latex?

I have searched but nothing useless, only "use \newline" or "use \".
I'm creating a simple latex document to store any texts instead of using .txt, and the problem is that the pdf document contains the lines going towards right until they go out of the paper.
I'm using this simple code
\documentclass[a4paper]{article}
\usepackage{geometry}
\geometry{
a4paper,
total={170mm,257mm},
left=5mm,
top=20mm,
}
\begin{document}
\section{Text 1}
Loremipsumdolorsitamet,consecteturadipiscingelit,seddoeiusmodtemporincididuntutlabore etdoloremagnaaliqua.Utenimadminimveniam,quisnostrudexercitationullamcolaborisnisiutaliquipexeacommodoconsequat.Duisauteiruredolorinreprehenderitinvoluptatevelitessecillum doloreeufugiatnullapariatur.Excepteursintoccaecatcupidatatnonproident,suntinculpaquiofficiadeseruntmollitanimidestlaborum.
\end{document}
Since latex sees it as a one word, it refuses to break it since it doenst know its hyphenation. But I would like to allow latex to break it regardless. Any thoughts ?
Remarks: I already have used:
\hspace{0pt}
\leavevmode\nobreak\hspace{0pt}
\mbox{Loremip...larorum.}
Nothing worked.
I think I got why nothing worked. See my code below, that I managed to compile successfully after editing your MWE.
You basically have two ways to force hyphenation here.
As in the comment by SamCarter, you manually split words within text, just using \- where necessary. I did it below in line 18 (6 from bottom).
You add to your preamble the command \hyphenation{word-to-split}: I did this below to hyphenate the word in line 20 (4 from bottom). Notice that, in this case, you use - instead of \- within the braces {} enclosing the argument.
\documentclass[a4paper]{article}
\usepackage{geometry}
\geometry{
a4paper,
total={170mm,257mm},
left=5mm,
top=20mm,
}
\hyphenation{Duisauteiruredolorinre-prehenderitinvoluptatevelitesse-cillum doloreeufugiatnullapariatur}
\begin{document}
\section{Text 1}
Loremipsumdolorsitamet, consecteturadipiscingelit,
seddoeiusmodtemporincididuntutlaboreetdoloremagna.
Uten\-imadminimveniam,
quisnostrudexercitationullamcolaborisnisiutaliquipexeacommodoconsequat.
Duisauteiruredolorinreprehenderitinvoluptatevelitessecillumdoloreeufugiatnullapariatur.
Excepteursintoccaecatcupidatatnonproident,
suntinculpaquiofficiadeseruntmollitanimidestlaborum.
\end{document}
Finally, if the full stop character . is not followed by a space, two separate words may be interpreted as one and the command \hyphenation may not work as expected. Not sure that this was the detail making you write that nothing worked, but be careful to this too.

Howto - Latex syntax with \section[]{}: Putting Brackets [ Inside of Brackets

I am writing a beamer presentation. My problem is a syntax issue with \section[Outline]{title}. \section is working fine with all of my section titles except in the following example:
\section[$\mathbb{Z}[G]$-module constructions]{$\mathbb{Z}[G]$-modules and Geometric Constructions}
I need a [ or \[ symbol around the G (i.e., [G]) in the Outline part of \section,however, Tex throws tons of errors whenever anything resembling a bracket is in there.
All ideas are welcome and thanks in advance.
Michael Anderson points out a much cleaner way of doing the same in the comments. Define the command in your preamble as
\newcommand[1]{\bracket}{[#1]}
and use the syntax $\bracket{G}$ to place brackets around G.
The problem is because LaTeX interprets the ] in [G] as a closing bracket for the [Outline] part of the command. Here's a work around for that. In your preamble, add the following:
\newcommand{\rbracket}{]}
Now define your section as
\section[$\mathbb{Z}[G\rbracket $-module constructions]{$\mathbb{Z}[G]$-modules and Geometric Constructions}
This is how the outline should look like
By wrapping the short title in an additional layer of {...} you can "hide" the problematic content from latex:
\documentclass{beamer}
\begin{document}
\begin{frame}
\tableofcontents
\end{frame}
\section[{$\mathbb{Z}[G]$-module constructions}]{$\mathbb{Z}[G]$-modules and Geometric Constructions}
\begin{frame}
content...
\end{frame}
\end{document}
Michael Anderson gave a nice solution, but when I tried it, I got errors. Then I wrote this:
\newcommand{\bracket}[1]{[#1]}
and that worked to get brackets in brackets with:
\bracket{content}
to get [content].

Alternative input to LaTex newcommand

Is there an alternative way to enter multiple arguments to LaTex newcommand constructions? I have defined
\newcommand{\nuc}[2]{\ensuremath{^{\text{#1}}\text{#2}}}
and I would like to call the command through
\nuc{12,C}
and not
\nuc{12}{C}.
I have created other commands with even more arguments and my poor pinky can't handle all the brackets.
Thanks!
Maybe you will like it.
\def\nuc #1,#2.{\ensuremath{^{\text{#1}}\text{#2}}}
Sample of using:
\nuc 12,C.
Note. Use the dot at the end.
I like to praise perltex for defining complicated functions. This isn't complicated, but you can extend it quite impressively.
%myfile.tex
\documentclass{article}
\usepackage{perltex}
\perlnewcommand{\commafrac}[1]{
$input = shift;
#inputs = split(/,/, $input);
return "\\ensuremath{\\frac{$inputs[0]}{$inputs[1]}}";
}
\begin{document}
One half is $\commafrac{1,2}$.
\end{document}
Compile with perltex --latex=pdflatex myfile.tex. I know that \frac wasn't your example, but I find it a visually appealing one.
Use plain TeX \def:
\makeatletter
\newcommand*{\nuc}[1]{\nuc##1\#nil}
\newcommand*{\nuc#}{}
\protected\def\nuc##1,#2\#nil{\ensuremath{^{\text{#1}}\text{#2}}}
\makeatother
As fas as I know \nuc{12}{c} is the only way. If you don't want to put all the "}{"s, let the editor do it. Write \nuc{12,c} first, then replace all commas with "}{"s.

Inserting code in this LaTeX document with indentation

How do I insert code into a LaTeX document? Is there something like:
\begin{code}## Heading ##
...
\end{code}
The only thing that I really need is indentation and a fixed width font. Syntax highlighting could be nice although it is definitely not required.
Use listings package.
Simple configuration for LaTeX header (before \begin{document}):
\usepackage{listings}
\usepackage{color}
\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
\lstset{frame=tb,
language=Java,
aboveskip=3mm,
belowskip=3mm,
showstringspaces=false,
columns=flexible,
basicstyle={\small\ttfamily},
numbers=none,
numberstyle=\tiny\color{gray},
keywordstyle=\color{blue},
commentstyle=\color{dkgreen},
stringstyle=\color{mauve},
breaklines=true,
breakatwhitespace=true,
tabsize=3
}
You can change default language in the middle of document with \lstset{language=Java}.
Example of usage in the document:
\begin{lstlisting}
// Hello.java
import javax.swing.JApplet;
import java.awt.Graphics;
public class Hello extends JApplet {
public void paintComponent(Graphics g) {
g.drawString("Hello, world!", 65, 95);
}
}
\end{lstlisting}
Here's the result:
You could also use the verbatim environment
\begin{verbatim}
your
code
example
\end{verbatim}
Here is how to add inline code:
You can add inline code with {\tt code } or \texttt{ code }. If you want to format the inline code, then it would be best to make your own command
\newcommand{\code}[1]{\texttt{#1}}
Also, note that code blocks can be loaded from other files with
\lstinputlisting[breaklines]{source.c}
breaklines isn't required, but I find it useful. Be aware that you'll have to specify \usepackage{ listings } for this one.
Update: The listings package also includes the \lstinline command, which has the same syntax highlighting features as the \lstlisting and \lstinputlisting commands (see Cloudanger's answer for configuration details). As mentioned in a few other answers, there's also the minted package, which provides the \mintinline command. Like \lstinline, \mintinline provides the same syntax highlighting as a regular minted code block:
\documentclass{article}
\usepackage{minted}
\begin{document}
This is a sentence with \mintinline{python}{def inlineCode(a="ipsum)}
\end{document}
Specialized packages such as minted, which relies on Pygments to do the formatting, offer various advantages over the listings package. To quote from the minted manual,
Pygments provides far superior syntax highlighting compared to conventional packages. For example, listings basically only highlights strings, comments and keywords. Pygments, on the other hand, can be completely customized to highlight any token kind the source language might support. This might include special formatting sequences inside strings, numbers, different kinds of identifiers and exotic constructs such as HTML tags.
Minted, whether from GitHub or CTAN, the Comprehensive TeX Archive Network, works in Overleaf, TeX Live and MiKTeX.
It requires the installation of the Python package Pygments; this is explained in the documentation in either source above. Although Pygments brands itself as a Python syntax highlighter, Minted guarantees the coverage of hundreds of other languages.
Example:
\documentclass{article}
\usepackage{minted}
\begin{document}
\begin{minted}[mathescape, linenos]{python}
# Note: $\pi=\lim_{n\to\infty}\frac{P_n}{d}$
title = "Hello World"
sum = 0
for i in range(10):
sum += i
\end{minted}
\end{document}
Output:
Use Minted.
It's a package that facilitates expressive syntax highlighting in LaTeX using the powerful Pygments library. The package also provides options to customize the highlighted source code output using fancyvrb.
It's much more evolved and customizable than any other package!
A very simple way if your code is in Python, where I didn't have to install a Python package, is the following:
\documentclass[11pt]{article}
\usepackage{pythonhighlight}
\begin{document}
The following is some Python code
\begin{python}
# A comment
x = [5, 7, 10]
y = 0
for num in x:
y += num
print(y)
\end{python}
\end{document}
which looks like:
Unfortunately, this only works for Python.
Since it wasn't yet mentioned here, it may be worth to add one more option, package spverbatim (no syntax highlighting):
\documentclass{article}
\usepackage{spverbatim}
\begin{document}
\begin{spverbatim}
Your code here
\end{spverbatim}
\end{document}
Also, if syntax highlighting is not required, package alltt:
\documentclass{article}
\usepackage{alltt}
\begin{document}
\begin{alltt}
Your code here
\end{alltt}
\end{document}
Use Pygments !

how write this in verbatim latex

i have a little question about the verbatim environment in latex.....
my problem is how can i write "\end{verbatim}" inside of a verbatim environment, it supposed that everything inside a verbatim is written just like it looks but this is the string to end the environment, so how can i do this?
\\end{verbatim}
Should do it by making the initial \ into a literal backslash.
I think it might be impossible in a verbatim environment -- at least, that's what Lamport says in the LaTeX book (first paragraph on pg. 64). However, you can do it with the \verb command: \verb+\end{verbatim}+ works just fine (and in fact, you can use any character instead of + as long as you make them match).
That said, the listings package is smart enough to have an escape character. For example,
\begin{lstlisting}[escapechar=+]
+\verb!\end{lstlisting}!+
\end{lstlisting}
does exactly what you're looking for. (Again, pick a different character than + if you're already using that for something else.)
Use the fancyvrb package instead of the default verbatim package.
Craig's answer is good. Alternatively, \expandafter\string\csname end{verbatim}\endcsname.
These solutions won't linebreak nicely: fixing this is fiddly.
I have a simpler solution. Write a non-breaking space, in Emacs it's C-x 8 SPC (Windows, though I haven't tried it is Alt+0160 (on numeric keypad)). So, you can do this:
\begin{verbatim}
\_end{verbatim}
\end{verbatim}
where the first \end{verbatim} has this "_", the non-breaking character.
Here is my method, thanks #S.Lott for his advice.
If you want to write \end{verbatim} in the verbatim environment, you have to using another 'verbatim' layer to nest your code (this is where fancyvr package comes to play). Here it is:
\documentclass{article}
\usepackage{fancyvrb}
\begin{document}
Some text here
\begin{Verbatim} % note 'uppercase V' in verbatim
\begin{verbatim}
Code example
\end{verbatim}
\end{Verbatim}
\end{document}

Resources