Latex: \newcommand interpret # symbol problem - latex

I defined a new command
\newcommand{\test}[1]{\href{https://github.com/microsoft/vscode/blob/main/package.json#1}{#1}}
When I use it as follows:
\test{#L4}
the url will be interpreted as:
https://github.com/microsoft/vscode/blob/main/package.json##L4
There is an extra # in the url, which is unexpected. What I really want is:
https://github.com/microsoft/vscode/blob/main/package.json#L4
which means line 4 of the package.json code
The easiest but no so elegant way to solve the problem is as follows.
\test{\#L4}
but what if other special characters like _ appear in the part of url I copy? It's boring to correct these meaningless grammar mistakes.
Is there any more elegant way to solve the problem? What I want is to copy plain text, which is part of url to the latex code and no extra efforts like adding \ escape character before # and other special characters are needed.

What I want is to copy plain text, which is part of url to the latex code and no extra efforts like adding \ escape character before # and other special characters are needed.
I am afraid it will require extra effort because # is used as a parameter for macros in LaTeX. You can play with redefining categories and when # is consumed, restore its original meaning.
I have another solution based on expl3 where I save the main address and create links with additional parts. See a small demo below
\documentclass{article}
\usepackage[colorlinks]{hyperref}
\usepackage[margin=1in]{geometry} % To fit long links without breaks
\ExplSyntaxOn
\str_new:N \l__xaddr_main_str
\str_new:N \l__xaddr_show_str
\cs_new:Npn \combine_addr:n #1 {
\str_set:Nn \l_tmpa_str {#1}
\str_concat:NNN \l__xaddr_show_str \l__xaddr_main_str \l_tmpa_str
}
\NewDocumentCommand\xsetmainaddr{v}{
\str_set:Nn \l__xaddr_main_str {#1}}
\NewDocumentCommand\xdisplay{v}{%
\str_if_empty:NF \l__xaddr_main_str {
\combine_addr:n {#1}
\str_use:N \l__xaddr_show_str
}}
\NewDocumentCommand\xhref{vv}{%
\str_if_empty:NF \l__xaddr_main_str {
\combine_addr:n {#1}
\href{\l__xaddr_show_str}{#2}
}}
\ExplSyntaxOff
\setlength\parindent{0pt} % To fit long links without breaks
\begin{document}
\xhref{#L4}{GitHub} % Nothing to display. The main address is not defined.
\xsetmainaddr{https://github.com/microsoft/vscode/blob/main/package.json}
\par\xdisplay{#L4} % Display the full address including #L4
\par\xdisplay{#something_else%20here} % all characters accepted
\par\xhref{#L4}{GitHub} % Generates link: <address>#L4
\bigskip
\xsetmainaddr{http://www.google.com} % New address
\par\xhref{}{Google} % Generates link
\end{document}

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.

Pandoc generation of pdf from markdown 4th header is rendered differently

I am using pandoc to generate a pdf from some markdown. I am using h1 through h4 via hash symbols. Example h1=#, h4=####. When I generate my document like this:
pandoc input.md -o output.pdf
I get a document where h1, h2 and h3 have a newline after them but h4 does not have a new line. The text starts on the same line as the header (it isn't formatted the same way, but there isn't a newline character between).
I've tried adding spaces after the #### and adding manual line returns using my editor but nothing seems to work.
Any ideas?
While the mentioned solutions work fine, pandoc offers a build-in variable to enable block-headings for \paragraph.
pandoc -s -o out.pdf some.md -V block-headings
Pandoc Manual
pandoc generates PDFs via LaTeX. In LaTeX, "headers" are generated using the following commands:
\section
\subsection
\subsubsection
\paragraph
\subparagraph
As you can see, a "level four heading" corresponds to the \paragraph command, which is rendered as you describe. There simply isn't a \subsubsubsection command to use.
The only way to get what you want is to redefine the \paragraph command, which is quite tricky. I haven't been able to make it work with Pandoc.
While #tarleb’s answer is surely the best (except that it specifies a
wrong amount of vertical space), here is a “simpler” (by some measure)
but more hacky (in LaTeX terms at least) solution which optionally uses a Pandoc Lua filter or a LaTeX hack but avoids loading another LaTeX package.
We want the LaTeX source to look something like this:
\hypertarget{level-4-heading}{%
\paragraph{Level 4 heading}\label{level-4-heading}}
\hfill
Lorem ipsum dolor sit amet.
This LaTeX looks awful, but if you don’t need to keep or share the LaTeX
source it does what you probably want: a space between the level 4
heading and the paragraph after it equal to the space between a level 3
heading and the paragraph after it.
Here is how it works: since a \hfill on a line on its own is about as
close as you can get to an empty paragraph in LaTeX you get a first
paragraph — the one running in with the heading — containing only
horizontal white space until the end of the line, and then immediately
after a new paragraph — the actual first paragraph after the heading —
with just a normal paragraph space between it and the heading. This
probably also upsets LaTeX’s idea about what a \paragraph should be
like as little as possible.
The “manual” way to do this is as follows:
#### Level 4 heading
````{=latex}
\hfill
````
Lorem ipsum dolor sit amet.
This uses Pandoc’s relatively new raw markup syntax — the “code block”
is actually a raw LaTeX block — but it looks even more awful than the
resulting LaTeX source! It is also a tedious chore to have to insert
this after every level 4 heading. In other words you want to insert that
raw LaTeX automatically, and that can be done with a Lua filter:
--[======================================================================[
latex-h4-break.lua - Pandoc filter to get break after a level 4 heading.
Usage:
$ pandoc --lua-filter latex-h4-break.lua input.md -o output.pdf
--]======================================================================]
-- create it once, use it many times!
local hfill_block = pandoc.RawBlock('latex', '\\hfill')
function Header (elem)
if 4 == elem.level then
return { elem, hfill_block }
else -- ignore headings at other levels!
return nil
end
end
However you can also do a simple LaTeX hack in a header-includes
metadata block to get the same effect:
---
header-includes:
- |
``` {=latex}
\let\originAlParaGraph\paragraph
\renewcommand{\paragraph}[1]{\originAlParaGraph{#1} \hfill}
```
---
#### Level 4 heading
Lorem ipsum dolor sit amet.
This works by first creating an “alias” of the \paragraph command and
then redefining the \paragraph command itself, using the alias in the
new definition so that now wherever the LaTeX source created by Pandoc
contains \paragraph{Foo} it is if it instead had contained
\paragraph{Foo} \hfill which does what we want with zero extra
dependencies! (In case you wonder the wacky spelling of the “aliased”
command is to minimize the risk that it collides with anything which
already exists, since the TeX \let command doesn’t check for that. We
certainly don’t want to overwrite any existing command!)
NOTE: If you really should want more or less space than a normal
paragraph break after the heading just add an appropriate \vspace
command after the \hfill: \hfill \vspace{-0.5\parskip}.
Shifting Headers
Arguably the best way to solve this would be to avoid the problem altogether by shifting what a level 4 header corresponds to. The default for pandoc is to use \section commands for 1st level and \paragraph for 4th level headers. This can be altered via the --top-level-division parameter:
--top-level-division=[default|section|chapter|part]
Treat top-level headers as the given division type in LaTeX [...] output. The hierarchy order is part, chapter, then section; all headers are shifted such that the top-level header becomes the specified type. The default behavior is to determine the best division type via heuristics [...]
So with --top-level-division=chapter, a 4th-level header would be generated via the \subsubsection command.
Styling via LaTeX
If this is not an option, the next best way is to configure the layout of the corresponding LaTeX command: for level-four headers, this is \paragraph by default. The following methods are taken from TeX StackExchange answers.
Please also check the answer by bpj, which is much simpler than what's proposed below.
Default document-classes
The default way would be to configure \paragraph via the titlesec package. We can use the header-includes metadata field for this, which pandoc will include in the intermediate LaTeX document.
---
header-includes: |
``` {=latex}
\usepackage{titlesec}
\titlespacing*{\paragraph}{0pt}{1ex}{-\parskip}
\titleformat{\paragraph}[hang]
{\normalfont\bfseries}
{}
{0pt}
{}
```
---
KOMA document-classes
Using titlesec won't work properly for documents using KOMA classes (like scrartcl), as KOMA has it's own ways of doing things. For these, use this alternative snippet:
---
documentclass: scrartcl
header-includes: |
``` {=latex}
\makeatletter
\renewcommand\paragraph{\#startsection{paragraph}{4}{\z#}%
{-3.25ex \#plus -1ex \#minus -0.2ex}%
{0.01pt}%
{\raggedsection\normalfont\sectfont\nobreak\size#paragraph}%
}
\makeatother
```
---
I am not sure, why, but this works for me:
Put $\ \\ $ in the first line after your #### headline

Multiset notation in LaTeX

Does anyone know how to make (nice looking) double bracket multiset notation in LaTeX, i.e something like (\binom{n}{k}) where there are two outer brackets instead of 1 as in binomial? You can see an example of what I mean in http://en.wikipedia.org/wiki/Multiset under the heading "Multiset coefficients" with the double brackets.
In Wikipedia they typeset it as:
\left(\!\!{n\choose k}\!\!\right)
but although this works well for LaTeX in maths mode, with inline equations the outer bracket becomes much larger than the inner bracket.
I have also tried using
\genfrac{((}{))}{0pt}{}{n}{k}
but it has an error with the double brackets.
I am using \binom as well in my document, so I would like the bracket sizes to be similar for \binom and \multiset.
You can explicitly specify the size of the brackets via
\big( \Big( \bigg( or \Bigg(
Then use \! for negative space to get the brackets closer to each other.
One can use the e-TeX \middle command as follows:
\newcommand{\multibinom}[2]{
\left(\!\middle(\genfrac{}{}{0pt}{}{#1}{#2}\middle)\!\right)
}
This assumes that you are using the AMSmath package. If not, replace \genfrac with the appropriate construct using \atop.
(Of course this is a hack: the proper solution would be scalable glyphs for the doubled parenthesis, but I can't find any fonts that provide it.)
I'm surprised it wasn't googlable either, so I'll provide a solution here for posterity's sake.
It is also possible to define two different new commands, using \tbinom and \dbinom (section 4.11.2 of the User's Guide for the amsmath Package):
\documentclass{article}
\usepackage{amsmath}
\newcommand{\inlinebnm}[2]{\ensuremath{\big(\!\tbinom{#1}{#2}\!\big)}}
\newcommand{\displybnm}[2]{\bigg(\!\!\dbinom{#1}{#2}\!\!\bigg)}
\begin{document}
Text $\inlinebnm{a}{b}$ text. %% inline
Text \inlinebnm{a}{b} text. %% inline (also ok thanks to ensuremath)
\[
\displybnm{a}{b} %% display-style
\]
\end{document}

C Source Code in Latex document

Can anyone recommend me a good template to include C source code with line numbering
in Latex? For example, taking the classical Hello world program, I would like to make it look as follows:
(1) /* Hello World program */
(2)
(3) #include<stdio.h>
(4)
(5) main()
(6) {
(7) printf("Hello World");
(8) }
Typicall, I always used the verbatim environment, but I am wondering if there is a better and nicer way to do that.
Thanks so much
Richard
As others have said, the listings package will probably do what you want using something like the following:
\lstset{
language=C, % choose the language of the code
numbers=left, % where to put the line-numbers
stepnumber=1, % the step between two line-numbers.
numbersep=5pt, % how far the line-numbers are from the code
backgroundcolor=\color{white}, % choose the background color. You must add \usepackage{color}
showspaces=false, % show spaces adding particular underscores
showstringspaces=false, % underline spaces within strings
showtabs=false, % show tabs within strings adding particular underscores
tabsize=2, % sets default tabsize to 2 spaces
captionpos=b, % sets the caption-position to bottom
breaklines=true, % sets automatic line breaking
breakatwhitespace=true, % sets if automatic breaks should only happen at whitespace
title=\lstname, % show the filename of files included with \lstinputlisting;
}
\lstinputlisting{HelloWorld.c}
A more powerful alternative would be to use the minted package, although this will do much more than what you're currently asking, as it uses/requires pygments to be installed on your system so that it can fully tokenize the code you give it.
You might want to have a look at the listings package. It is very flexible and easy to use.
Take a look at Code listings in LaTeX. You'll find a couple of alternatives there. Some options are:
listings
minted
lgrind
Use lgrind package for latex. It converts your code into a .tex file
CWEB had a nice C formatter.

Latex listings-package format option for uppercase keywords

I use the listings package to insert source code. I would like to print all keywords uppercase in the output, regardless of the case in the input.
The manual states that
keywordstyle=[number][*]style
produces just what I want. However the following (almost) minimal example does not work.
if I set keywordstyle to "[1][]{\bfseries}" I end up with "[]" in front of every keyword
and "[*]{\bfseries}" gives me an asterisk in the start of the document.
I also tried "\MakeUppercase" and "{\MakeUppercase}" for keywordstyle which resulted in several errors, the first being:
! Incomplete \iffalse; all text was ignored after line 11
Minimal example:
\documentclass{article}
\usepackage{listings}
\lstdefinelanguage{KA_assembler}
{morekeywords={add,and,or,xor},
keywordstyle=[1][*]{\bfseries},
sensitive=false,
}
\lstset{language=KA_assembler}
\begin{document}
\begin{lstlisting}
and %r1, %r2
xor %r2, %r3
and %r4, %r5
\end{lstlisting}
\end{document}
I use Miktex for compilation of the tex files. So how do I force uppercase for Keywords?
In the manual, the brackets around the * look a bit different then the brackets around number. The reason is that the brackets around * are not meant to be used in the latex code, they just indicate that the presence of the * is optional. So try
keywordstyle=[1]*\bfseries
or
keywordstyle=*\bfseries
- it worked for me.

Resources