For the underscore it's quite easy:
\documentclass{article}
\usepackage[T1]{fontenc}
\catcode`_=12
\begingroup\lccode`~=`_\lowercase{\endgroup\let~\sb}
\mathcode`_="8000
\begin{document}
Under_score but $a_{x}$
\end{document}
Actually the line \mathcode`_="8000
is redundant, but repeating it makes our intentions clear.
We make the character _
is "math active", i.e., it behaves like a macro, but only in math mode. The \begingroup\lccode...
trick defines this macro to be equivalent to \sb
which in turn is equivalent to the usual _
for introducing a subscript. In order that it's really seen as a math active character, we need to give it category code 12, which also makes it printable (outside math mode). However, we need a font that has an underscore in the right position, so we load the T1 output encoding.
Other special characters have to be treated in different ways. For example, the $
symbol can be "neutralized" by saying
\usepackage{fixltx2e}
\catcode`$=12
in the preamble; the package is necessary because it "robustifies" the \(
and \)
commands. In-line formulas must now be input with these commands, of course.
For the &
, one can say
\def\AM{&}
\catcode`&=12
and use \AM
for marking alignment points in tabular environments.
Also the #
character can be neutralized, as long as after saying
\catcode`#=12
one doesn't try defining new commands.
However, I don't recommend to change catcodes (other than the underscore, perhaps). A "search and replace", in case of a conversion to other formats, is safer.
Best Answer
One option is to use the
verbatim
environment:Sample taken from here: https://en.wikibooks.org/wiki/LaTeX/Paragraph_Formatting#Verbatim_text
Similar environment with line breaking and a tiny font size using listings package:
And like Johannes_B wrote, there are dedicated packages for displaying source code listings:
https://en.wikibooks.org/wiki/LaTeX/Source_Code_Listings https://www.sharelatex.com/learn/Code_Highlighting_with_minted
They allow line nubering, syntax coloring etc. Example using minted package: