[Tex/LaTex] How to typeset a backslash and get line breaks in URLs


I have a lot of Windows file/folder paths and register paths in my document. And I'm having 2 problems:

  1. The \ is seen as and escape character which obviously doesn't compile. \\ Starts a new line rather than escaping the \. I tried $$ too, but that didn't work either.
  2. There is no line breaking, so the paths go out of the page margin.

At the first question, is there a quick way to solve this rather then changing all \ to / ?

At the second question, I tried \path{} from the url package but that didn't help.

Best Answer

  1. You're correct. The backslash is TeX's (default) escape character; it signals to TeX that what follows is different from "normal text". Therefore, simply typing \ will not produce a backslash in the output. (Incidentally, if you type \ followed by any amount of blank space, you will only produce a so-called control space, not a backslash.)

    To typeset a backslash in text mode, use \textbackslash; in math mode, use \backslash.

    Now, if you find (as I do) that typing \textbackslash every single time is a pain in the neck, you can always define a macro with a shorter name that does exactly the same thing, like so:


    and then use that macro throughout your file instead of \textbackslash.

    One more thing: what should you do to produce the following output?

    C:\My documents

    You can try

    C:\textbackslashMy documents

    but that's not going to work, because TeX is going to interpret \textbackslashMy as a macro, won't find it defined anywhere, and will hurl abuse at you. To obtain the desired output, either insert either a blank space or an empty group ({}) right after \textbackslash, like so

    C:\textbackslash{}My documents
  2. The url package makes your life easier in that respect. Load it in our preamble and then use the \url command to typeset a URL; the package will take care of the line breaking for you. Note that you don't need to use \textbackslash inside \url{...}, because \url already "detokenizes" its argument. Happy days!

Here is some code illustrating those two points:


\newcommand\bs\textbackslash % shorthand for \textbackslash


A backslash in text mode: \bs \\
A backslash in math mode: $\backslash$\\[2em]
A long URL: \url{C:\Program Files\Steam\Jubobsgame\procrastinators__paradise\level_one\five_years_into_the_PhD}

and here is the corresponding output:

enter image description here