246

How can I produce the text Word_one_two in LaTeX?

I tried:

Samp\_Dist\_Corr

But, it doesn't quite look right. Also, I want it in the typewriter font, so actually, I'm doing:

\texttt{Samp\_Dist\_Corr}

I find it looks a bit like the underscore is merging in to the bottom of the "D", but maybe it's just because of the typewriter D?

Joseph Wright
  • 259,911
  • 34
  • 706
  • 1,036
  • 26
    This reminds me of one of my pet peeves : all these unneeded special characters in the text mode.

    If you use the underscore package, then you don't need to escape the _ in text mode.

    FWIW, in ConTeXt, _ has a letter catcode in text mode, so simply typing Samp_Distt_Corr works.

    – Aditya Mar 20 '12 at 03:17
  • 5
    underscore works, but Vim still highlights it as an error. To avoid, edit vimXX/syntax/tex.vim: texOnlyMath "[_^]" becomes "[\^]". – Evgeni Sergeev Jul 16 '13 at 04:40
  • 2
    Hmm, an annoyance with the underscore package is that it's not bold in \textbf{a_b}. – Evgeni Sergeev Jul 30 '13 at 07:34
  • 18
    A greater annoyance is that one cannot \includegraphics{filename_with_underscore} when the underscore package is used. – Evgeni Sergeev Aug 01 '13 at 02:27
  • 1
    The solution I've settled on was to \usepackage[Q=yes,pverb-linebreak=no]{examplep} and then \Q{identifier_typeset_in_monospace}. This suits me, because all my underscores occur in code: variables, function names, filenames, etc., all of which could be typeset in a verbatim-like environment. – Evgeni Sergeev Aug 23 '13 at 04:00
  • 8
    Why is it special? I can understand why \ is special, for example. But what does _ do, except annoy all of us? – Aaron McDaid Nov 04 '14 at 12:51
  • 2
    @AaronMcDaid The “why” is explained in The TeXbook page 134: “The special characters ^ and _ that designate superscripts and subscripts should not be used except in formulas. […] TeX uses these facts to detect missing dollar signs in your input, before such mistakes cause too much trouble. For example, suppose you were to type The smallest $n such that $2^n>1000$ is~10. […] TeX will automatically insert a $ before the ^, and you will get an error message. In this way the computer has gotten back into synch, and the rest of the document can be typeset as if nothing had happened.” – ShreevatsaR Jun 29 '17 at 01:39
  • @EvgeniSergeev @Aditya Yes, I couldn't compile my document when doing \usepackage{underscore}. I do not recommend the usage of this package and the upvoting of the comment suggesting the use of it. – tommy.carstensen Nov 28 '17 at 11:29
  • 1
    no package needed, just use the TeX "" to continue meaning it creates an subscript from the following character or block, and follow it by a dash that will be subscripted. So `-works, as well as_{--}` for a longer dash – verdy_p May 19 '19 at 03:42
  • Note that \_ does not work at all (invalid syntax encountered) in many simple TeX implementations, even within the block of \text{...} or \mbox{...}, and \texttt is also not working (requires also an additional package whose transclusion by \usepackage is restricted/forbidden) – verdy_p May 19 '19 at 03:50
  • Note that you have the choice of dashes to use in the subscript: if your TeX implementation supports Unicode encoding you can use em-dash and en-dash directly after the "_" meta that will subscript it. Or you can use "\emdash" or "\endash" or other term defined for them. – verdy_p May 19 '19 at 15:37
  • As well, if you want to have multiple underscores to be joining together, you can use the (joining) horizontal line U+2015 (―) after the "" metacharacter to subscript it. Note that to represent the underscore alone or at start of line, you need an empty block {} before the `metacharacter for subscripts. So a full substitute of the underscore is{}-, or{}{select your dash here}`. – verdy_p May 19 '19 at 15:41
  • Finally note that this subscripting technic may not work as you want in monospaced (typewriter) styles, because usually the subscript is rendered with a smaller font, just shifted down (so its width is reduced). For that you need special definition of the sequence \_ or _- in the font package definition you use for the monospaced style, but _— (using the em-dash U+2014) should be OK. – verdy_p May 19 '19 at 15:53
  • It's good to understand that the legacy "" ASCII symbol has in fact several typographic representations with no well defined behavior (width, vertical positioning, joining) and several semantic interpretations as well. It is then highly dependant of the style you use in TeX, or the semantics you want to represent in this style. That's probably why it has no predefined arbitrary definition in "core" TeX and why `` was chosen in TeX to have only the meta-connector to create subscripts, and not mapped to any character glyph in any predefined style. – verdy_p May 19 '19 at 16:00
  • Even Unicode shows this variability in character properties of U+005F, which is treated specially to work in limited way like other legacy ASCII characters, (just like also many other compatibility characters imported from various older encoding standards). Linguistically it has no meaning, it is not part of any "script", semantically it may be interpreted like a separating dash or as a whitespace. So it was chosen to assign it as a "symbol" and not a punctuation (but not also that the ASCII "-" is also ambiguous, just like the ASCII single and double quotation marks or apostrophe) – verdy_p May 19 '19 at 16:11
  • If you want _ (and other characters) to work in text mode by default and don't need to use the math mode: see Handling of special LaTeX characters in text - TeX - LaTeX Stack Exchange – user202729 Jan 05 '22 at 12:34

14 Answers14

204

You may prefer the character from the tt font:

\documentclass{article}

\begin{document}

\texttt{Samp\_Dist\_Corr}

\verb|Samp_Dist_Corr|

\texttt{Samp\char`_Dist\char`_Corr}

\end{document}

enter image description here

Or probably better add \usepackage[T1]{fontenc} then all the above forms will use the character from the font.

Fran
  • 80,769
David Carlisle
  • 757,742
  • 10
    I wonder why when _ is used in text mode LaTeX is not smart enough to send it to output directly? – Real Dreams Oct 11 '13 at 18:23
  • 1
    @PHPst This is not LaTeX it is very low level TeX behaviour and in general TeX doesn't do such switches, compare the behaviour of say \alpha also in the original TeX OT1 encoded TeX fonts, they typically didn't have a _ character so it isn't clear what "output directly" means, choice of switching to tt which did have, or using a rule or... – David Carlisle Oct 11 '13 at 18:27
  • 1
    ' it isn't clear what "output directly" means,...' It could simply consider it similar to all other characters by default in non-math mode. – Real Dreams Oct 12 '13 at 05:11
  • @PHPst in the standard OT1 encoding, that wouldn't be useful try setting \catcode\_=12(to make it a standard punctuation character) and you'll seee that unless in tt font you get a dot accent, same as<and>are not useful out of text mode and give spanish punctuation inverted!and?` – David Carlisle Jan 05 '14 at 02:17
  • 2
    \usepackage[T1]{fontenc} was the key. You should probably mention it more prominently in your answer. – varepsilon Aug 03 '16 at 13:02
  • @DavidCarlisle \verb|My_Text| command doesn't work in \begin{table}\begin{tabular} My_Table\end{tabular}\end{table}. How can I resolve the issue? – Admia Jan 17 '17 at 02:34
  • @Admia not sure why you are leaving that question as a comment on an old question, verb does not work in the argument of a command but it works in the body of table and tabular environments so there should be no issue there. or you can use \_ as it says here. – David Carlisle Jan 17 '17 at 07:47
  • \verb|| worked on my particular case, I should mention the reason I can't use \ is because when I copy paste from latex into another file, the underscores dissapear, \verb|_| solves the problem. – Felipe Valdes Apr 17 '19 at 19:17
  • @user202729 yes although OT1 encoding should be avoided in almost all cases anyway for other reasons, and with T1 encoding this isn't an issue. – David Carlisle Jan 05 '22 at 14:24
95

You can use \textunderscore also.

\documentclass{article}
%
\begin{document}
Samp\textunderscore Distt\textunderscore Corr

\texttt{Samp\textunderscore Distt\textunderscore Corr}
\end{document}

enter image description here

Underscore is not merging at the bottom of D actually. It is very close to it.

  • 1
    That \textunderscore thing didn't actually work for me: The underscore symbol \texttt{\char`_} is a special variable that contains the result of the last printed value.
    The underscore symbol \texttt{\textunderscore} is a special variable that contains the result of the last printed value.
    
    

    produces http://minireference.com/static/textunderscore_not_shown_well.png

    – ivan Jul 22 '14 at 16:37
  • 1
    I think this is one of the bad advices on this page. See my answer for analysis what the answers does/explanation. – user202729 May 06 '22 at 17:49
  • Wow, 15 characters for just one. – Phil Nov 13 '22 at 06:28
80

A fairly elementary way of stripping special meaning from things is to \detokenize them:

enter image description here

\documentclass{article}
\begin{document}
\texttt{\detokenize{Samp_Dist_Corr}}

\texttt{\detokenize{a@b\c_d&e~f g}}
\end{document}

Note how a space is inserted after a "control sequence". See What are the exact semantics of \detokenize?

Werner
  • 603,163
  • 10
    I'm glad I was scrolling through these underscore-related questions: \detokenize is a godsend for basic, machine-generated documents. – Sean Allred Nov 12 '15 at 13:27
  • Also for URLs, which may have (oh, the horror) tildes (alias \textasciitilde{}) as well as underscores. – Flash Sheridan Jun 29 '16 at 20:56
  • 1
    Warning, this breaks UTF-8 support, I used it on text which contained umlauts beside the underscores and got a nasty surprise. – rumtscho Jan 03 '17 at 14:47
  • 1
    @FlashSheridan there's \usepackage{url} (and then \url{http://blabla.de/~tilde}) for URLs – cgnieder Apr 24 '17 at 19:09
  • 1
    @rumtscho it doesn't with a true unicode engine (luatex or xetex). With pdflatex for example ä is not one unicode token but two tokens and with \usepackage[utf8]{inputenc} the package does clever stuff to “fool” everybody. \detokenize then just reveals the truth :) – cgnieder Apr 24 '17 at 19:12
68

I was looking to get the underscore character inside a word in any font, and Google brought me here, so here's the solution I found:

{\_}

word{\_}one{\_}two

produces

_

word_one_two
dantiston
  • 1,079
  • 2
    This is already covered in the other answers. – Werner Sep 23 '14 at 02:11
  • 18
    Which answer covers this? All the other answers refer to tt, detokenize, textunderscore, and using underline. – dantiston Sep 23 '14 at 04:12
  • 3
    The original post asks for a typewriter font solution, which is provided in David's answer. Since it also works in other fonts, it makes this answer no different than his. – Werner Sep 23 '14 at 04:40
  • 1
    Alright -- I'll edit my answer to show that I found this page by looking for "underscore character in word latex" to note the relevance of this answer to other fonts. – dantiston Sep 23 '14 at 16:34
  • 1
    @dantiston I'm not sure in what sense do you think this is different from what the question says. I'm with Werner, I think this answer doesn't add anything. – Manuel Sep 23 '14 at 18:29
  • 22
    +1. I didnt even read the question fully. But Google brought me here on searching for "underscore in latex" and I feel this is the easiest solution – Pavan Manjunath Sep 16 '15 at 03:21
  • 1
    Easiest solution maybe, but not the best. With one extra line in the preamble, you can use arekolek's solution and have nice looking output. – SpinUp __ A Davis Jul 09 '17 at 16:28
  • 3
    This should have been the best answer. – The Roy Nov 25 '18 at 15:25
  • 1
    As far as I can tell this is identical to the OP's \_ however. – user202729 Apr 18 '22 at 06:13
33

The solution I like best is to put \chardef\_=`_ in the preamble and use \_ to typeset an underscore. That is because:

  • \verb doesn't work in macros,
  • \char`_ is tedious to write and looks confusing,
  • \usepackage[T1]{fontenc} messes up all my fonts,
  • \textunderscore doesn't work in \texttt,
  • \detokenize looks promising, but I already use a lot of \_,
  • {\_} doesn't work in \texttt,
  • \underline{{ }{ }} looks really bad and \underline{{ }} still doesn't look quite right,
  • \rule is a hack that doesn't look right.

Example:

\documentclass{article}

\begin{document}

\texttt{Samp\_Dist\_Corr} -- original

\texttt{Samp{\_}Dist{\_}Corr} -- brackets

\texttt{Samp\textunderscore Dist\textunderscore Corr} -- textunderscore

\texttt{Samp\underline{{ }{ }}Dist\underline{{ }{ }}Corr} -- double underline

\texttt{Samp\underline{{ }}Dist\underline{{ }}Corr} -- underline

\newcommand{\TextUnderscore}{\rule{.4em}{.4pt}}
\texttt{Samp\TextUnderscore{}Dist\TextUnderscore{}Corr} -- rule

\verb|Samp_Dist_Corr| -- verb

\texttt{Samp\char`_Dist\char`_Corr} -- char

\texttt{\detokenize{Samp_Dist_Corr}} -- detokenize

\chardef\_=`_

\texttt{Samp\_Dist\_Corr} -- chardef

\end{document}

latex output

arekolek
  • 575
  • 1
    »\usepackage[T1]{fontenc} messes up all my fonts,« Really? How's that? Even if I only load one package this usually is it… – cgnieder Apr 24 '17 at 19:05
  • @clemens I'm not sure how to answer your question as it would be difficult to pinpoint the exact cause of the problem I had with fontenc because the document where it occurred was my master's thesis with a lot of different packages. But I guess I can post an example rendering without and with fontenc if you're interested. – arekolek Apr 24 '17 at 19:19
  • I was just curious (mostly because of https://tex.stackexchange.com/questions/664/why-should-i-use-usepackaget1fontenc) but if you don't remember that's fine :) – cgnieder Apr 24 '17 at 19:25
18

There's a package for this!

\documentclass{article}


\usepackage{underscore}


\begin{document}
    This_is_probably_not a_good_idea.
\end{document}
JPi
  • 13,595
  • 3
    For me, this is right now the simplest solution. Having to use workarounds for every single underscore is really painfull. Sometimes I'm really shocked how difficult it can be to do such simple things as writing an underscore in LaTex... Hopefully the package doesn't have any side-effects, but for now it works for me. – mozzbozz Feb 12 '17 at 19:29
  • 1
    I can't as it wasn't me who asked the question ;) (and I've upvoted this answer already and I can't do it twice...) – mozzbozz Feb 13 '17 at 01:14
  • 4
    \usepackage{underscore} does have problems, because it will cause problems where LaTeX does interpret underscores correctly, such as file names :-( – con Mar 05 '19 at 15:53
  • 1
    That's why it says "This is probably not a good idea." – JPi Mar 06 '19 at 03:33
  • 2
    This is by far the best solution. Specially if you are writing a book about programming languages. It should be the default, and if you want a special case then you would need to type \_, not the other way around. – DrBeco Jul 02 '19 at 04:23
7

An explanation of what the answers do.

Figure

(*): \verb always use the tt font instead of current font.

\rule and \underline are "obvious" (typeset a rectangular black box and some "blank space" with underline respectively), read e.g. LaTeX2e unofficial reference manual for more details.

Remark:

  • In T1 encoding, there's absolutely no reason to use one of the 6 items in the "char 95 of current font" category. \_ is shorter.

  • Usually, there's no reason to use {\_} or \textunderscore.

    • \_ is defined to be equivalent to \textunderscore and also work in math mode.

      (in other words, \textunderscore is identical to \_ in text mode, and error out in math mode. Besides it's longer to type.)

    • As far as I know (and also confirmed by some other users) the extra grouping in {\_} does nothing.

  • \char is primitive TeX command. The LaTeX command is \symbol.

  • You can see that LaTeX default underscore does not use char 95 when encoding is OT1, because it occasionally fails depends on the font (i.e., the encoding does not guarantee that the character at position 5F (hex) is an underscore, that character in the specific font cmtt10 "happens" to be an underscore)

    To make it "smart" (works in limited cases) it's possible to do \def\_{\ifttdefault{\char95}{\textunderscore}} using the macro in other question.

  • Not that \string and \detokenize is never useful, but in the context of typesetting a single underscore \char 95 or \char `_ is shorter and does the same thing.

  • \underline is a bit "semantically misleading", but otherwise it can be used, no problem. Although you may find it easier to just use the optional raise parameter to move the rule lower and/or \hspace to add additional space: \hspace{.1em}\rule[-0.2em]{.4em}{.3pt} gives rule for underscore

user202729
  • 7,143
  • Check the package forest – JeT May 06 '22 at 23:05
  • @user202729 For cross-linking -- example question where detokenize _ gives wrong result https://tex.stackexchange.com/questions/346883/detokenize-does-not-produce-the-expected-underscores/ ■ question that asks what rule LaTeX uses for underscore https://tex.stackexchange.com/questions/153634/how-does-work-if-ot1-is-default-encoding-for-latex – user202729 Jun 26 '22 at 08:04
5

In a pinch, a horizontal \rule may also suffice:

enter image description here

\documentclass{article}
\newcommand{\TextUnderscore}{\rule{.4em}{.4pt}}
\begin{document}
\texttt{Samp\textunderscore{}Dist\textunderscore{}Corr}\par
\texttt{Samp\_Dist\_Corr}\par
\texttt{Samp\TextUnderscore{}Dist\TextUnderscore{}Corr}
\end{document}

The width - .4em - can be adjusted to suit. The height - .4pt - is the "typical" rule-thickness used elsewhere in the document.

Werner
  • 603,163
5

Change Category Code

For those not interested the functionality of the underscore in LaTeX and just want it to function like any other character, the category code of the underscore can be changed to make it work as might be expected. Here, we assign the underscore the same category code that most punctuation has. Choose one of the following syntaxes according to your preference:

\catcode`\_=12   % alphabetic constant syntax
\catcode`_=12    % alphabetic constant syntax
\catcode"5F=12   % unicode decimal syntax
\catcode'137=12  % octal syntax
\catcode95=12    % decimal syntax

This way, you can go on about your happy life using the underscore as you normally would. If you need to subset text in math mode, the macro \sb can still be used in math mode for subscript.

Revert Category Code Change

This explanation would not be complete without stating how to restore the underscore to its original category code. Pick one of the following syntaxes according to your preference:

\catcode`\_=8   % alphabetic constant syntax
\catcode`_=8    % alphabetic constant syntax
\catcode"5F=8   % unicode decimal syntax
\catcode'137=8  % octal syntax
\catcode95=8    % decimal syntax

See egreg's answer: Is it safe to set underscore to a non-active character?

4

The easiest way to have an occasional underscore in text mode (without need to reprogram the whole Matrix...) IMHO is as following:

e.g.:

James\underline{{ }{ }}Bond

which produces a nice James_bond, with a correct spacing between letters

I hope it'll help you.

  • 1
    Can you explain to a newb what the two inner curly brace pairs do? I assume the outer curly brace pair delimits the "text" to be underlined, which here is just whitespace, and the two inner pairs define the amount of white space, making the underline longer than a simple sequence of spaces which seem to be collapsed into one, as usual. Does this simply define exactly two spaces, preventing them from collapsing, and accidentally underlining two looks good? (Because underlining just one looks as bad as a simple \_.) – Peter - Reinstate Monica Nov 24 '15 at 17:01
  • @Peter-ReinstateMonica I think you're right. I've tested this solution to others sizes of spaces like \enspace and got an intermediate result. So, if \underline{{ }{ }} is too big, and \underline{{ }} is too small, you can try out \underline{\enspace} as well as combinations of these commands – Leone Jul 18 '21 at 15:26
3

\underline{\hspace{1cm}} is the best solution, I think. Adjust the length of hspace as you see fit.

Schweinebacke
  • 26,336
1

Putting the following at the top of the file seems to work for me. You can then use \_ for underscore.

\def\_{{\tt\char95}}
  • This by itself cannot work. You are defining \_ but _ on its own won't expand to this definition of \_ (unless you have that too somewhere). – ShreevatsaR Jun 29 '17 at 04:16
  • Yes, you have to use \_. I included this because some fonts don't show the underslash character. \tt makes sure that it shows. – Daniel Patru Jun 29 '17 at 15:43
  • The "LaTeX replacement" for def and tt are \newcommand and \texttt respectively however. – user202729 Apr 18 '22 at 06:12
1

I write mostly documents without ever needing subscripts, so my favourite solution is to redefine the catcode of the underscore character. Then it behaves as any normal letter:

I put this into the preamble:

\catcode`\_=12

Should I ever need a subscript in math mode I can use \sb:

$Energy\sb{kinetic}$

Or if I need subscript in text mode I just use \textsubscript:

Normal word\textsubscript{yay!}
0

I wanted to include multiple lines of code with underscores. \verb|...| introduced spacing between the lines and \texttt{} mean that I had to escape each underscore. The best way I found was to use \begin{Verbatim}

\begin{Verbatim}
regs.regs_PC = regs.regs_NPC;
regs.regs_NPC += sizeof(md_inst_t);
\end{Verbatim}

Which compiled as

enter image description here

To indent the block, use\usepackage{fancyvrb} and write \begin{Verbatim}[xleftmargin=.5in]