You may be misinterpreting what's going on. The insert
function inserts its argument verbatim. The problem is that the string you've included in your program is not \documentclass
but ␡ocumentclass
where ␡ is ASCII character number 127 (which is unprintable).
The string literal "\documentclass"
represents the string ␡ocumentclass
. Notice how two things happen: the literal has additional quotes at the beginning and at the end, and backslash+character in the literal¹ is transformed into a single character in the string. Why? The quotes delimit the string literal, so that the computer knows that you meant to write a string and not whatever code the text could represent. At the very least, there needs to be a way to include a quote character in a string. Emacs Lisp, like most programming languages, uses the backslash to escape the next character: the string literal "foo\"bar"
represents the string foo"bar
— the second quote doesn't end the literal because it's preceded by a backslash. Backslash followed by a non-alphanumeric character always quotes the next character: the backslash character is removed and the next character is included in the string. Backslash followed by some alphanumeric characters allows you to specify characters that it might not be easy to include in source code, such as control characters.
Once again, this is happening when your code is parsed. If you write "\documentclass"
, there is no way to get back to what you typed, because it's stored in exactly the same way as if you'd typed ␡ocumentclass
. If you write "\math"
, it's stored exactly in the same way as if you'd typed "math"
.
Some languages have alternate syntaxes for string literals with a multi-character delimiter and no interpretation of anything but the end delimiter inside the string literal. Emacs Lisp doesn't, it keeps things simple. So just type "\\documentclass"
to get the string \documentclass
.
¹ Sometimes backslash plus a sequence of characters.