[lug] XEmacs quoting madness!

Aaron Crane aaron.crane at pobox.com
Mon Aug 20 12:29:28 MDT 2001


Hi, Chris.

Chris Riddoch <socket at peakpeak.com> writes:
> In XEmacs, I'm trying to make a string with a backslash before single
> quote.

When you say "make a string", do you mean "write a string literal", or
"write a function that takes a string as input and returns another (as
output) in which any single-quote has been preceded by a backslash"?

Executive summary: for option 1, use

  "can\\'t"

and for option 2, use

  (defun backslashify-single-quotes (string)
    (replace-in-string string "'" "\\'" t))

You might also investigate whether `shell-quote-argument' meets your needs.

Details below.

> I want the output string to be this: "Can\'t" because the output will be
> passed as a string value to another program (thus needing quoting).
> 
> "Can\'t" gives me "Can't", as I'd expect.
> 
> "Can\\'t" gives me "Can\\'t", as I really *didn't* expect.

If you're getting the output by executing a string-valued expression
interactively (either with M-: or in the *scratch* buffer), then remember
that what gets printed out is a re-readable representation of the string
itself.  This re-readable representation uses the same syntax as an ordinary
string literal.

Within a string literal, a backslash will either disable the usual special
interpretation of the following character, or enable an unusual special
interpretation of it (depending on what the character is).  In particular,
note that the string whose literal syntax is "\\" contains a single
backslash character.[1]

How does this apply to what you want to do?  If you have a string literal
like "can't", there's nothing tricky, because no backslashes are involved.
A literal like "can\\'t" behaves a little differently.  When this gets read,
the reader interprets the double-backslash as a request to put a single
backslash in the string it's building -- the first backslash has escaped the
special meaning of the backslash character.  So your string actually
contains _six_ characters:

  c  a  n  \  '  t

Similarly, in your first example, "can\'t", the backslash escapes any
special meaning of the single quote character.  In this case, there is no
such special meaning, so the effect is the same as omitting the backslash
from the literal entirely.

Does that make sense?

____
1. The full details can be found in the node `String Type' of the XEmacs
   info file named lispref (`C-h i m lispref RET g String SPC Type RET', or,
   if you're using Debian, `C-h i m xemacs21 RET m lispref RET g String SPC
   Type RET'.

-- 
Aaron Crane



More information about the LUG mailing list