]> code.delx.au - gnu-emacs/blob - doc/lispref/strings.texi
Avoid integer overflows in string-numeric-lessp
[gnu-emacs] / doc / lispref / strings.texi
1 @c -*- mode: texinfo; coding: utf-8 -*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1995, 1998-1999, 2001-2016 Free Software
4 @c Foundation, Inc.
5 @c See the file elisp.texi for copying conditions.
6 @node Strings and Characters
7 @chapter Strings and Characters
8 @cindex strings
9 @cindex character arrays
10 @cindex characters
11 @cindex bytes
12
13 A string in Emacs Lisp is an array that contains an ordered sequence
14 of characters. Strings are used as names of symbols, buffers, and
15 files; to send messages to users; to hold text being copied between
16 buffers; and for many other purposes. Because strings are so important,
17 Emacs Lisp has many functions expressly for manipulating them. Emacs
18 Lisp programs use strings more often than individual characters.
19
20 @xref{Strings of Events}, for special considerations for strings of
21 keyboard character events.
22
23 @menu
24 * Basics: String Basics. Basic properties of strings and characters.
25 * Predicates for Strings:: Testing whether an object is a string or char.
26 * Creating Strings:: Functions to allocate new strings.
27 * Modifying Strings:: Altering the contents of an existing string.
28 * Text Comparison:: Comparing characters or strings.
29 * String Conversion:: Converting to and from characters and strings.
30 * Formatting Strings:: @code{format}: Emacs's analogue of @code{printf}.
31 * Case Conversion:: Case conversion functions.
32 * Case Tables:: Customizing case conversion.
33 @end menu
34
35 @node String Basics
36 @section String and Character Basics
37
38 A character is a Lisp object which represents a single character of
39 text. In Emacs Lisp, characters are simply integers; whether an
40 integer is a character or not is determined only by how it is used.
41 @xref{Character Codes}, for details about character representation in
42 Emacs.
43
44 A string is a fixed sequence of characters. It is a type of
45 sequence called a @dfn{array}, meaning that its length is fixed and
46 cannot be altered once it is created (@pxref{Sequences Arrays
47 Vectors}). Unlike in C, Emacs Lisp strings are @emph{not} terminated
48 by a distinguished character code.
49
50 Since strings are arrays, and therefore sequences as well, you can
51 operate on them with the general array and sequence functions documented
52 in @ref{Sequences Arrays Vectors}. For example, you can access or
53 change individual characters in a string using the functions @code{aref}
54 and @code{aset} (@pxref{Array Functions}). However, note that
55 @code{length} should @emph{not} be used for computing the width of a
56 string on display; use @code{string-width} (@pxref{Size of Displayed
57 Text}) instead.
58
59 There are two text representations for non-@acronym{ASCII}
60 characters in Emacs strings (and in buffers): unibyte and multibyte.
61 For most Lisp programming, you don't need to be concerned with these
62 two representations. @xref{Text Representations}, for details.
63
64 Sometimes key sequences are represented as unibyte strings. When a
65 unibyte string is a key sequence, string elements in the range 128 to
66 255 represent meta characters (which are large integers) rather than
67 character codes in the range 128 to 255. Strings cannot hold
68 characters that have the hyper, super or alt modifiers; they can hold
69 @acronym{ASCII} control characters, but no other control characters.
70 They do not distinguish case in @acronym{ASCII} control characters.
71 If you want to store such characters in a sequence, such as a key
72 sequence, you must use a vector instead of a string. @xref{Character
73 Type}, for more information about keyboard input characters.
74
75 Strings are useful for holding regular expressions. You can also
76 match regular expressions against strings with @code{string-match}
77 (@pxref{Regexp Search}). The functions @code{match-string}
78 (@pxref{Simple Match Data}) and @code{replace-match} (@pxref{Replacing
79 Match}) are useful for decomposing and modifying strings after
80 matching regular expressions against them.
81
82 Like a buffer, a string can contain text properties for the characters
83 in it, as well as the characters themselves. @xref{Text Properties}.
84 All the Lisp primitives that copy text from strings to buffers or other
85 strings also copy the properties of the characters being copied.
86
87 @xref{Text}, for information about functions that display strings or
88 copy them into buffers. @xref{Character Type}, and @ref{String Type},
89 for information about the syntax of characters and strings.
90 @xref{Non-ASCII Characters}, for functions to convert between text
91 representations and to encode and decode character codes.
92
93 @node Predicates for Strings
94 @section Predicates for Strings
95 @cindex predicates for strings
96 @cindex string predicates
97
98 For more information about general sequence and array predicates,
99 see @ref{Sequences Arrays Vectors}, and @ref{Arrays}.
100
101 @defun stringp object
102 This function returns @code{t} if @var{object} is a string, @code{nil}
103 otherwise.
104 @end defun
105
106 @defun string-or-null-p object
107 This function returns @code{t} if @var{object} is a string or
108 @code{nil}. It returns @code{nil} otherwise.
109 @end defun
110
111 @defun char-or-string-p object
112 This function returns @code{t} if @var{object} is a string or a
113 character (i.e., an integer), @code{nil} otherwise.
114 @end defun
115
116 @node Creating Strings
117 @section Creating Strings
118 @cindex creating strings
119 @cindex string creation
120
121 The following functions create strings, either from scratch, or by
122 putting strings together, or by taking them apart.
123
124 @defun make-string count character
125 This function returns a string made up of @var{count} repetitions of
126 @var{character}. If @var{count} is negative, an error is signaled.
127
128 @example
129 (make-string 5 ?x)
130 @result{} "xxxxx"
131 (make-string 0 ?x)
132 @result{} ""
133 @end example
134
135 Other functions to compare with this one include @code{make-vector}
136 (@pxref{Vectors}) and @code{make-list} (@pxref{Building Lists}).
137 @end defun
138
139 @defun string &rest characters
140 This returns a string containing the characters @var{characters}.
141
142 @example
143 (string ?a ?b ?c)
144 @result{} "abc"
145 @end example
146 @end defun
147
148 @defun substring string &optional start end
149 This function returns a new string which consists of those characters
150 from @var{string} in the range from (and including) the character at the
151 index @var{start} up to (but excluding) the character at the index
152 @var{end}. The first character is at index zero. With one argument,
153 this function just copies @var{string}.
154
155 @example
156 @group
157 (substring "abcdefg" 0 3)
158 @result{} "abc"
159 @end group
160 @end example
161
162 @noindent
163 In the above example, the index for @samp{a} is 0, the index for
164 @samp{b} is 1, and the index for @samp{c} is 2. The index 3---which
165 is the fourth character in the string---marks the character position
166 up to which the substring is copied. Thus, @samp{abc} is copied from
167 the string @code{"abcdefg"}.
168
169 A negative number counts from the end of the string, so that @minus{}1
170 signifies the index of the last character of the string. For example:
171
172 @example
173 @group
174 (substring "abcdefg" -3 -1)
175 @result{} "ef"
176 @end group
177 @end example
178
179 @noindent
180 In this example, the index for @samp{e} is @minus{}3, the index for
181 @samp{f} is @minus{}2, and the index for @samp{g} is @minus{}1.
182 Therefore, @samp{e} and @samp{f} are included, and @samp{g} is excluded.
183
184 When @code{nil} is used for @var{end}, it stands for the length of the
185 string. Thus,
186
187 @example
188 @group
189 (substring "abcdefg" -3 nil)
190 @result{} "efg"
191 @end group
192 @end example
193
194 Omitting the argument @var{end} is equivalent to specifying @code{nil}.
195 It follows that @code{(substring @var{string} 0)} returns a copy of all
196 of @var{string}.
197
198 @example
199 @group
200 (substring "abcdefg" 0)
201 @result{} "abcdefg"
202 @end group
203 @end example
204
205 @noindent
206 But we recommend @code{copy-sequence} for this purpose (@pxref{Sequence
207 Functions}).
208
209 If the characters copied from @var{string} have text properties, the
210 properties are copied into the new string also. @xref{Text Properties}.
211
212 @code{substring} also accepts a vector for the first argument.
213 For example:
214
215 @example
216 (substring [a b (c) "d"] 1 3)
217 @result{} [b (c)]
218 @end example
219
220 A @code{wrong-type-argument} error is signaled if @var{start} is not
221 an integer or if @var{end} is neither an integer nor @code{nil}. An
222 @code{args-out-of-range} error is signaled if @var{start} indicates a
223 character following @var{end}, or if either integer is out of range
224 for @var{string}.
225
226 Contrast this function with @code{buffer-substring} (@pxref{Buffer
227 Contents}), which returns a string containing a portion of the text in
228 the current buffer. The beginning of a string is at index 0, but the
229 beginning of a buffer is at index 1.
230 @end defun
231
232 @defun substring-no-properties string &optional start end
233 This works like @code{substring} but discards all text properties from
234 the value. Also, @var{start} may be omitted or @code{nil}, which is
235 equivalent to 0. Thus, @w{@code{(substring-no-properties
236 @var{string})}} returns a copy of @var{string}, with all text
237 properties removed.
238 @end defun
239
240 @defun concat &rest sequences
241 @cindex copying strings
242 @cindex concatenating strings
243 This function returns a new string consisting of the characters in the
244 arguments passed to it (along with their text properties, if any). The
245 arguments may be strings, lists of numbers, or vectors of numbers; they
246 are not themselves changed. If @code{concat} receives no arguments, it
247 returns an empty string.
248
249 @example
250 (concat "abc" "-def")
251 @result{} "abc-def"
252 (concat "abc" (list 120 121) [122])
253 @result{} "abcxyz"
254 ;; @r{@code{nil} is an empty sequence.}
255 (concat "abc" nil "-def")
256 @result{} "abc-def"
257 (concat "The " "quick brown " "fox.")
258 @result{} "The quick brown fox."
259 (concat)
260 @result{} ""
261 @end example
262
263 @noindent
264 This function always constructs a new string that is not @code{eq} to
265 any existing string, except when the result is the empty string (to
266 save space, Emacs makes only one empty multibyte string).
267
268 For information about other concatenation functions, see the
269 description of @code{mapconcat} in @ref{Mapping Functions},
270 @code{vconcat} in @ref{Vector Functions}, and @code{append} in @ref{Building
271 Lists}. For concatenating individual command-line arguments into a
272 string to be used as a shell command, see @ref{Shell Arguments,
273 combine-and-quote-strings}.
274 @end defun
275
276 @defun split-string string &optional separators omit-nulls trim
277 This function splits @var{string} into substrings based on the regular
278 expression @var{separators} (@pxref{Regular Expressions}). Each match
279 for @var{separators} defines a splitting point; the substrings between
280 splitting points are made into a list, which is returned.
281
282 If @var{omit-nulls} is @code{nil} (or omitted), the result contains
283 null strings whenever there are two consecutive matches for
284 @var{separators}, or a match is adjacent to the beginning or end of
285 @var{string}. If @var{omit-nulls} is @code{t}, these null strings are
286 omitted from the result.
287
288 If @var{separators} is @code{nil} (or omitted), the default is the
289 value of @code{split-string-default-separators}.
290
291 As a special case, when @var{separators} is @code{nil} (or omitted),
292 null strings are always omitted from the result. Thus:
293
294 @example
295 (split-string " two words ")
296 @result{} ("two" "words")
297 @end example
298
299 The result is not @code{("" "two" "words" "")}, which would rarely be
300 useful. If you need such a result, use an explicit value for
301 @var{separators}:
302
303 @example
304 (split-string " two words "
305 split-string-default-separators)
306 @result{} ("" "two" "words" "")
307 @end example
308
309 More examples:
310
311 @example
312 (split-string "Soup is good food" "o")
313 @result{} ("S" "up is g" "" "d f" "" "d")
314 (split-string "Soup is good food" "o" t)
315 @result{} ("S" "up is g" "d f" "d")
316 (split-string "Soup is good food" "o+")
317 @result{} ("S" "up is g" "d f" "d")
318 @end example
319
320 Empty matches do count, except that @code{split-string} will not look
321 for a final empty match when it already reached the end of the string
322 using a non-empty match or when @var{string} is empty:
323
324 @example
325 (split-string "aooob" "o*")
326 @result{} ("" "a" "" "b" "")
327 (split-string "ooaboo" "o*")
328 @result{} ("" "" "a" "b" "")
329 (split-string "" "")
330 @result{} ("")
331 @end example
332
333 However, when @var{separators} can match the empty string,
334 @var{omit-nulls} is usually @code{t}, so that the subtleties in the
335 three previous examples are rarely relevant:
336
337 @example
338 (split-string "Soup is good food" "o*" t)
339 @result{} ("S" "u" "p" " " "i" "s" " " "g" "d" " " "f" "d")
340 (split-string "Nice doggy!" "" t)
341 @result{} ("N" "i" "c" "e" " " "d" "o" "g" "g" "y" "!")
342 (split-string "" "" t)
343 @result{} nil
344 @end example
345
346 Somewhat odd, but predictable, behavior can occur for certain
347 ``non-greedy'' values of @var{separators} that can prefer empty
348 matches over non-empty matches. Again, such values rarely occur in
349 practice:
350
351 @example
352 (split-string "ooo" "o*" t)
353 @result{} nil
354 (split-string "ooo" "\\|o+" t)
355 @result{} ("o" "o" "o")
356 @end example
357
358 If the optional argument @var{trim} is non-@code{nil}, it should be a
359 regular expression to match text to trim from the beginning and end of
360 each substring. If trimming makes the substring empty, it is treated
361 as null.
362
363 If you need to split a string into a list of individual command-line
364 arguments suitable for @code{call-process} or @code{start-process},
365 see @ref{Shell Arguments, split-string-and-unquote}.
366 @end defun
367
368 @defvar split-string-default-separators
369 The default value of @var{separators} for @code{split-string}. Its
370 usual value is @w{@code{"[ \f\t\n\r\v]+"}}.
371 @end defvar
372
373 @node Modifying Strings
374 @section Modifying Strings
375 @cindex modifying strings
376 @cindex string modification
377
378 The most basic way to alter the contents of an existing string is with
379 @code{aset} (@pxref{Array Functions}). @code{(aset @var{string}
380 @var{idx} @var{char})} stores @var{char} into @var{string} at index
381 @var{idx}. Each character occupies one or more bytes, and if @var{char}
382 needs a different number of bytes from the character already present at
383 that index, @code{aset} signals an error.
384
385 A more powerful function is @code{store-substring}:
386
387 @defun store-substring string idx obj
388 This function alters part of the contents of the string @var{string}, by
389 storing @var{obj} starting at index @var{idx}. The argument @var{obj}
390 may be either a character or a (smaller) string.
391
392 Since it is impossible to change the length of an existing string, it is
393 an error if @var{obj} doesn't fit within @var{string}'s actual length,
394 or if any new character requires a different number of bytes from the
395 character currently present at that point in @var{string}.
396 @end defun
397
398 To clear out a string that contained a password, use
399 @code{clear-string}:
400
401 @defun clear-string string
402 This makes @var{string} a unibyte string and clears its contents to
403 zeros. It may also change @var{string}'s length.
404 @end defun
405
406 @need 2000
407 @node Text Comparison
408 @section Comparison of Characters and Strings
409 @cindex string equality
410 @cindex text comparison
411
412 @defun char-equal character1 character2
413 This function returns @code{t} if the arguments represent the same
414 character, @code{nil} otherwise. This function ignores differences
415 in case if @code{case-fold-search} is non-@code{nil}.
416
417 @example
418 (char-equal ?x ?x)
419 @result{} t
420 (let ((case-fold-search nil))
421 (char-equal ?x ?X))
422 @result{} nil
423 @end example
424 @end defun
425
426 @defun string= string1 string2
427 This function returns @code{t} if the characters of the two strings
428 match exactly. Symbols are also allowed as arguments, in which case
429 the symbol names are used. Case is always significant, regardless of
430 @code{case-fold-search}.
431
432 This function is equivalent to @code{equal} for comparing two strings
433 (@pxref{Equality Predicates}). In particular, the text properties of
434 the two strings are ignored; use @code{equal-including-properties} if
435 you need to distinguish between strings that differ only in their text
436 properties. However, unlike @code{equal}, if either argument is not a
437 string or symbol, @code{string=} signals an error.
438
439 @example
440 (string= "abc" "abc")
441 @result{} t
442 (string= "abc" "ABC")
443 @result{} nil
444 (string= "ab" "ABC")
445 @result{} nil
446 @end example
447
448 For technical reasons, a unibyte and a multibyte string are
449 @code{equal} if and only if they contain the same sequence of
450 character codes and all these codes are either in the range 0 through
451 127 (@acronym{ASCII}) or 160 through 255 (@code{eight-bit-graphic}).
452 However, when a unibyte string is converted to a multibyte string, all
453 characters with codes in the range 160 through 255 are converted to
454 characters with higher codes, whereas @acronym{ASCII} characters
455 remain unchanged. Thus, a unibyte string and its conversion to
456 multibyte are only @code{equal} if the string is all @acronym{ASCII}.
457 Character codes 160 through 255 are not entirely proper in multibyte
458 text, even though they can occur. As a consequence, the situation
459 where a unibyte and a multibyte string are @code{equal} without both
460 being all @acronym{ASCII} is a technical oddity that very few Emacs
461 Lisp programmers ever get confronted with. @xref{Text
462 Representations}.
463 @end defun
464
465 @defun string-equal string1 string2
466 @code{string-equal} is another name for @code{string=}.
467 @end defun
468
469 @cindex locale-dependent string equivalence
470 @defun string-collate-equalp string1 string2 &optional locale ignore-case
471 This function returns @code{t} if @var{string1} and @var{string2} are
472 equal with respect to collation rules. A collation rule is not only
473 determined by the lexicographic order of the characters contained in
474 @var{string1} and @var{string2}, but also further rules about
475 relations between these characters. Usually, it is defined by the
476 @var{locale} environment Emacs is running with.
477
478 For example, characters with different coding points but
479 the same meaning might be considered as equal, like different grave
480 accent Unicode characters:
481
482 @example
483 @group
484 (string-collate-equalp (string ?\uFF40) (string ?\u1FEF))
485 @result{} t
486 @end group
487 @end example
488
489 The optional argument @var{locale}, a string, overrides the setting of
490 your current locale identifier for collation. The value is system
491 dependent; a @var{locale} @code{"en_US.UTF-8"} is applicable on POSIX
492 systems, while it would be, e.g., @code{"enu_USA.1252"} on MS-Windows
493 systems.
494
495 If @var{ignore-case} is non-@code{nil}, characters are converted to lower-case
496 before comparing them.
497
498 @vindex w32-collate-ignore-punctuation
499 To emulate Unicode-compliant collation on MS-Windows systems,
500 bind @code{w32-collate-ignore-punctuation} to a non-@code{nil} value, since
501 the codeset part of the locale cannot be @code{"UTF-8"} on MS-Windows.
502
503 If your system does not support a locale environment, this function
504 behaves like @code{string-equal}.
505
506 Do @emph{not} use this function to compare file names for equality, only
507 for sorting them.
508 @end defun
509
510 @defun string-prefix-p string1 string2 &optional ignore-case
511 This function returns non-@code{nil} if @var{string1} is a prefix of
512 @var{string2}; i.e., if @var{string2} starts with @var{string1}. If
513 the optional argument @var{ignore-case} is non-@code{nil}, the
514 comparison ignores case differences.
515 @end defun
516
517 @defun string-suffix-p suffix string &optional ignore-case
518 This function returns non-@code{nil} if @var{suffix} is a suffix of
519 @var{string}; i.e., if @var{string} ends with @var{suffix}. If the
520 optional argument @var{ignore-case} is non-@code{nil}, the comparison
521 ignores case differences.
522 @end defun
523
524 @cindex lexical comparison of strings
525 @defun string< string1 string2
526 @c (findex string< causes problems for permuted index!!)
527 This function compares two strings a character at a time. It
528 scans both the strings at the same time to find the first pair of corresponding
529 characters that do not match. If the lesser character of these two is
530 the character from @var{string1}, then @var{string1} is less, and this
531 function returns @code{t}. If the lesser character is the one from
532 @var{string2}, then @var{string1} is greater, and this function returns
533 @code{nil}. If the two strings match entirely, the value is @code{nil}.
534
535 Pairs of characters are compared according to their character codes.
536 Keep in mind that lower case letters have higher numeric values in the
537 @acronym{ASCII} character set than their upper case counterparts; digits and
538 many punctuation characters have a lower numeric value than upper case
539 letters. An @acronym{ASCII} character is less than any non-@acronym{ASCII}
540 character; a unibyte non-@acronym{ASCII} character is always less than any
541 multibyte non-@acronym{ASCII} character (@pxref{Text Representations}).
542
543 @example
544 @group
545 (string< "abc" "abd")
546 @result{} t
547 (string< "abd" "abc")
548 @result{} nil
549 (string< "123" "abc")
550 @result{} t
551 @end group
552 @end example
553
554 When the strings have different lengths, and they match up to the
555 length of @var{string1}, then the result is @code{t}. If they match up
556 to the length of @var{string2}, the result is @code{nil}. A string of
557 no characters is less than any other string.
558
559 @example
560 @group
561 (string< "" "abc")
562 @result{} t
563 (string< "ab" "abc")
564 @result{} t
565 (string< "abc" "")
566 @result{} nil
567 (string< "abc" "ab")
568 @result{} nil
569 (string< "" "")
570 @result{} nil
571 @end group
572 @end example
573
574 Symbols are also allowed as arguments, in which case their print names
575 are compared.
576 @end defun
577
578 @defun string-lessp string1 string2
579 @code{string-lessp} is another name for @code{string<}.
580 @end defun
581
582 @defun string-greaterp string1 string2
583 This function returns the result of comparing @var{string1} and
584 @var{string2} in the opposite order, i.e., it is equivalent to calling
585 @code{(string-lessp @var{string2} @var{string1})}.
586 @end defun
587
588 @cindex locale-dependent string comparison
589 @defun string-collate-lessp string1 string2 &optional locale ignore-case
590 This function returns @code{t} if @var{string1} is less than
591 @var{string2} in collation order. A collation order is not only
592 determined by the lexicographic order of the characters contained in
593 @var{string1} and @var{string2}, but also further rules about
594 relations between these characters. Usually, it is defined by the
595 @var{locale} environment Emacs is running with.
596
597 For example, punctuation and whitespace characters might be ignored
598 for sorting (@pxref{Sequence Functions}):
599
600 @example
601 @group
602 (sort '("11" "12" "1 1" "1 2" "1.1" "1.2") 'string-collate-lessp)
603 @result{} ("11" "1 1" "1.1" "12" "1 2" "1.2")
604 @end group
605 @end example
606
607 This behavior is system-dependent; e.g., punctuation and whitespace
608 are never ignored on Cygwin, regardless of locale.
609
610 The optional argument @var{locale}, a string, overrides the setting of
611 your current locale identifier for collation. The value is system
612 dependent; a @var{locale} @code{"en_US.UTF-8"} is applicable on POSIX
613 systems, while it would be, e.g., @code{"enu_USA.1252"} on MS-Windows
614 systems. The @var{locale} value of @code{"POSIX"} or @code{"C"} lets
615 @code{string-collate-lessp} behave like @code{string-lessp}:
616
617 @example
618 @group
619 (sort '("11" "12" "1 1" "1 2" "1.1" "1.2")
620 (lambda (s1 s2) (string-collate-lessp s1 s2 "POSIX")))
621 @result{} ("1 1" "1 2" "1.1" "1.2" "11" "12")
622 @end group
623 @end example
624
625 If @var{ignore-case} is non-@code{nil}, characters are converted to lower-case
626 before comparing them.
627
628 To emulate Unicode-compliant collation on MS-Windows systems,
629 bind @code{w32-collate-ignore-punctuation} to a non-@code{nil} value, since
630 the codeset part of the locale cannot be @code{"UTF-8"} on MS-Windows.
631
632 If your system does not support a locale environment, this function
633 behaves like @code{string-lessp}.
634 @end defun
635
636 @defun string-numerical-lessp strin1 string2
637 This function behaves like @code{string-lessp} for stretches of
638 consecutive non-numerical characters, but compares sequences of
639 numerical characters as if they comprised a base-ten number, and then
640 compares the numbers. So @samp{foo2.png} is ``smaller'' than
641 @samp{foo12.png} according to this predicate, even if @samp{12} is
642 lexicographically ``smaller'' than @samp{2}.
643
644 If one string has a number in a position in the string, and the other
645 doesn't, then lexicograpic comparison is done at that point, so
646 @samp{foo.png} is ``smaller'' than @samp{foo2.png}. If any of the
647 numbers in the strings are larger than can be represented as an
648 integer number, the entire string is compared using
649 @code{string-less}.
650 @end defun
651
652 @defun string-prefix-p string1 string2 &optional ignore-case
653 This function returns non-@code{nil} if @var{string1} is a prefix of
654 @var{string2}; i.e., if @var{string2} starts with @var{string1}. If
655 the optional argument @var{ignore-case} is non-@code{nil}, the
656 comparison ignores case differences.
657 @end defun
658
659 @defun string-suffix-p suffix string &optional ignore-case
660 This function returns non-@code{nil} if @var{suffix} is a suffix of
661 @var{string}; i.e., if @var{string} ends with @var{suffix}. If the
662 optional argument @var{ignore-case} is non-@code{nil}, the comparison
663 ignores case differences.
664 @end defun
665
666 @defun compare-strings string1 start1 end1 string2 start2 end2 &optional ignore-case
667 This function compares a specified part of @var{string1} with a
668 specified part of @var{string2}. The specified part of @var{string1}
669 runs from index @var{start1} (inclusive) up to index @var{end1}
670 (exclusive); @code{nil} for @var{start1} means the start of the
671 string, while @code{nil} for @var{end1} means the length of the
672 string. Likewise, the specified part of @var{string2} runs from index
673 @var{start2} up to index @var{end2}.
674
675 The strings are compared by the numeric values of their characters.
676 For instance, @var{str1} is considered less than @var{str2} if
677 its first differing character has a smaller numeric value. If
678 @var{ignore-case} is non-@code{nil}, characters are converted to
679 lower-case before comparing them. Unibyte strings are converted to
680 multibyte for comparison (@pxref{Text Representations}), so that a
681 unibyte string and its conversion to multibyte are always regarded as
682 equal.
683
684 If the specified portions of the two strings match, the value is
685 @code{t}. Otherwise, the value is an integer which indicates how many
686 leading characters agree, and which string is less. Its absolute
687 value is one plus the number of characters that agree at the beginning
688 of the two strings. The sign is negative if @var{string1} (or its
689 specified portion) is less.
690 @end defun
691
692 @defun assoc-string key alist &optional case-fold
693 This function works like @code{assoc}, except that @var{key} must be a
694 string or symbol, and comparison is done using @code{compare-strings}.
695 Symbols are converted to strings before testing.
696 If @var{case-fold} is non-@code{nil}, it ignores case differences.
697 Unlike @code{assoc}, this function can also match elements of the alist
698 that are strings or symbols rather than conses. In particular, @var{alist} can
699 be a list of strings or symbols rather than an actual alist.
700 @xref{Association Lists}.
701 @end defun
702
703 See also the function @code{compare-buffer-substrings} in
704 @ref{Comparing Text}, for a way to compare text in buffers. The
705 function @code{string-match}, which matches a regular expression
706 against a string, can be used for a kind of string comparison; see
707 @ref{Regexp Search}.
708
709 @node String Conversion
710 @section Conversion of Characters and Strings
711 @cindex conversion of strings
712
713 This section describes functions for converting between characters,
714 strings and integers. @code{format} (@pxref{Formatting Strings}) and
715 @code{prin1-to-string} (@pxref{Output Functions}) can also convert
716 Lisp objects into strings. @code{read-from-string} (@pxref{Input
717 Functions}) can convert a string representation of a Lisp object
718 into an object. The functions @code{string-to-multibyte} and
719 @code{string-to-unibyte} convert the text representation of a string
720 (@pxref{Converting Representations}).
721
722 @xref{Documentation}, for functions that produce textual descriptions
723 of text characters and general input events
724 (@code{single-key-description} and @code{text-char-description}). These
725 are used primarily for making help messages.
726
727 @defun number-to-string number
728 @cindex integer to string
729 @cindex integer to decimal
730 This function returns a string consisting of the printed base-ten
731 representation of @var{number}. The returned value starts with a
732 minus sign if the argument is negative.
733
734 @example
735 (number-to-string 256)
736 @result{} "256"
737 @group
738 (number-to-string -23)
739 @result{} "-23"
740 @end group
741 (number-to-string -23.5)
742 @result{} "-23.5"
743 @end example
744
745 @cindex int-to-string
746 @code{int-to-string} is a semi-obsolete alias for this function.
747
748 See also the function @code{format} in @ref{Formatting Strings}.
749 @end defun
750
751 @defun string-to-number string &optional base
752 @cindex string to number
753 This function returns the numeric value of the characters in
754 @var{string}. If @var{base} is non-@code{nil}, it must be an integer
755 between 2 and 16 (inclusive), and integers are converted in that base.
756 If @var{base} is @code{nil}, then base ten is used. Floating-point
757 conversion only works in base ten; we have not implemented other
758 radices for floating-point numbers, because that would be much more
759 work and does not seem useful. If @var{string} looks like an integer
760 but its value is too large to fit into a Lisp integer,
761 @code{string-to-number} returns a floating-point result.
762
763 The parsing skips spaces and tabs at the beginning of @var{string},
764 then reads as much of @var{string} as it can interpret as a number in
765 the given base. (On some systems it ignores other whitespace at the
766 beginning, not just spaces and tabs.) If @var{string} cannot be
767 interpreted as a number, this function returns 0.
768
769 @example
770 (string-to-number "256")
771 @result{} 256
772 (string-to-number "25 is a perfect square.")
773 @result{} 25
774 (string-to-number "X256")
775 @result{} 0
776 (string-to-number "-4.5")
777 @result{} -4.5
778 (string-to-number "1e5")
779 @result{} 100000.0
780 @end example
781
782 @findex string-to-int
783 @code{string-to-int} is an obsolete alias for this function.
784 @end defun
785
786 @defun char-to-string character
787 @cindex character to string
788 This function returns a new string containing one character,
789 @var{character}. This function is semi-obsolete because the function
790 @code{string} is more general. @xref{Creating Strings}.
791 @end defun
792
793 @defun string-to-char string
794 This function returns the first character in @var{string}. This
795 mostly identical to @code{(aref string 0)}, except that it returns 0
796 if the string is empty. (The value is also 0 when the first character
797 of @var{string} is the null character, @acronym{ASCII} code 0.) This
798 function may be eliminated in the future if it does not seem useful
799 enough to retain.
800 @end defun
801
802 Here are some other functions that can convert to or from a string:
803
804 @table @code
805 @item concat
806 This function converts a vector or a list into a string.
807 @xref{Creating Strings}.
808
809 @item vconcat
810 This function converts a string into a vector. @xref{Vector
811 Functions}.
812
813 @item append
814 This function converts a string into a list. @xref{Building Lists}.
815
816 @item byte-to-string
817 This function converts a byte of character data into a unibyte string.
818 @xref{Converting Representations}.
819 @end table
820
821 @node Formatting Strings
822 @section Formatting Strings
823 @cindex formatting strings
824 @cindex strings, formatting them
825
826 @dfn{Formatting} means constructing a string by substituting
827 computed values at various places in a constant string. This constant
828 string controls how the other values are printed, as well as where
829 they appear; it is called a @dfn{format string}.
830
831 Formatting is often useful for computing messages to be displayed. In
832 fact, the functions @code{message} and @code{error} provide the same
833 formatting feature described here; they differ from @code{format-message} only
834 in how they use the result of formatting.
835
836 @defun format string &rest objects
837 This function returns a new string that is made by copying
838 @var{string} and then replacing any format specification
839 in the copy with encodings of the corresponding @var{objects}. The
840 arguments @var{objects} are the computed values to be formatted.
841
842 The characters in @var{string}, other than the format specifications,
843 are copied directly into the output, including their text properties,
844 if any.
845 @end defun
846
847 @defun format-message string &rest objects
848 @cindex curved quotes
849 @cindex curly quotes
850 This function acts like @code{format}, except it also converts any
851 curved single quotes in @var{string} as per the value of
852 @code{text-quoting-style}, and treats grave accent (@t{`}) and
853 apostrophe (@t{'}) as if they were curved single quotes. @xref{Keys
854 in Documentation}.
855 @end defun
856
857 @cindex @samp{%} in format
858 @cindex format specification
859 A format specification is a sequence of characters beginning with a
860 @samp{%}. Thus, if there is a @samp{%d} in @var{string}, the
861 @code{format} function replaces it with the printed representation of
862 one of the values to be formatted (one of the arguments @var{objects}).
863 For example:
864
865 @example
866 @group
867 (format "The value of fill-column is %d." fill-column)
868 @result{} "The value of fill-column is 72."
869 @end group
870 @end example
871
872 Since @code{format} interprets @samp{%} characters as format
873 specifications, you should @emph{never} pass an arbitrary string as
874 the first argument. This is particularly true when the string is
875 generated by some Lisp code. Unless the string is @emph{known} to
876 never include any @samp{%} characters, pass @code{"%s"}, described
877 below, as the first argument, and the string as the second, like this:
878
879 @example
880 (format "%s" @var{arbitrary-string})
881 @end example
882
883 If @var{string} contains more than one format specification, the
884 format specifications correspond to successive values from
885 @var{objects}. Thus, the first format specification in @var{string}
886 uses the first such value, the second format specification uses the
887 second such value, and so on. Any extra format specifications (those
888 for which there are no corresponding values) cause an error. Any
889 extra values to be formatted are ignored.
890
891 Certain format specifications require values of particular types. If
892 you supply a value that doesn't fit the requirements, an error is
893 signaled.
894
895 Here is a table of valid format specifications:
896
897 @table @samp
898 @item %s
899 Replace the specification with the printed representation of the object,
900 made without quoting (that is, using @code{princ}, not
901 @code{prin1}---@pxref{Output Functions}). Thus, strings are represented
902 by their contents alone, with no @samp{"} characters, and symbols appear
903 without @samp{\} characters.
904
905 If the object is a string, its text properties are
906 copied into the output. The text properties of the @samp{%s} itself
907 are also copied, but those of the object take priority.
908
909 @item %S
910 Replace the specification with the printed representation of the object,
911 made with quoting (that is, using @code{prin1}---@pxref{Output
912 Functions}). Thus, strings are enclosed in @samp{"} characters, and
913 @samp{\} characters appear where necessary before special characters.
914
915 @item %o
916 @cindex integer to octal
917 Replace the specification with the base-eight representation of an
918 integer.
919
920 @item %d
921 Replace the specification with the base-ten representation of an
922 integer.
923
924 @item %x
925 @itemx %X
926 @cindex integer to hexadecimal
927 Replace the specification with the base-sixteen representation of an
928 integer. @samp{%x} uses lower case and @samp{%X} uses upper case.
929
930 @item %c
931 Replace the specification with the character which is the value given.
932
933 @item %e
934 Replace the specification with the exponential notation for a
935 floating-point number.
936
937 @item %f
938 Replace the specification with the decimal-point notation for a
939 floating-point number.
940
941 @item %g
942 Replace the specification with notation for a floating-point number,
943 using either exponential notation or decimal-point notation, whichever
944 is shorter.
945
946 @item %%
947 Replace the specification with a single @samp{%}. This format
948 specification is unusual in that it does not use a value. For example,
949 @code{(format "%% %d" 30)} returns @code{"% 30"}.
950 @end table
951
952 Any other format character results in an @samp{Invalid format
953 operation} error.
954
955 Here are several examples, which assume the typical
956 @code{text-quoting-style} settings:
957
958 @example
959 @group
960 (format "The octal value of %d is %o,
961 and the hex value is %x." 18 18 18)
962 @result{} "The octal value of 18 is 22,
963 and the hex value is 12."
964
965 (format-message
966 "The name of this buffer is ‘%s’." (buffer-name))
967 @result{} "The name of this buffer is ‘strings.texi’."
968
969 (format-message
970 "The buffer object prints as `%s'." (current-buffer))
971 @result{} "The buffer object prints as ‘strings.texi’."
972 @end group
973 @end example
974
975 @cindex field width
976 @cindex padding
977 A specification can have a @dfn{width}, which is a decimal number
978 between the @samp{%} and the specification character. If the printed
979 representation of the object contains fewer characters than this
980 width, @code{format} extends it with padding. The width specifier is
981 ignored for the @samp{%%} specification. Any padding introduced by
982 the width specifier normally consists of spaces inserted on the left:
983
984 @example
985 (format "%5d is padded on the left with spaces" 123)
986 @result{} " 123 is padded on the left with spaces"
987 @end example
988
989 @noindent
990 If the width is too small, @code{format} does not truncate the
991 object's printed representation. Thus, you can use a width to specify
992 a minimum spacing between columns with no risk of losing information.
993 In the following two examples, @samp{%7s} specifies a minimum width
994 of 7. In the first case, the string inserted in place of @samp{%7s}
995 has only 3 letters, and needs 4 blank spaces as padding. In the
996 second case, the string @code{"specification"} is 13 letters wide but
997 is not truncated.
998
999 @example
1000 @group
1001 (format "The word '%7s' has %d letters in it."
1002 "foo" (length "foo"))
1003 @result{} "The word ' foo' has 3 letters in it."
1004 (format "The word '%7s' has %d letters in it."
1005 "specification" (length "specification"))
1006 @result{} "The word 'specification' has 13 letters in it."
1007 @end group
1008 @end example
1009
1010 @cindex flags in format specifications
1011 Immediately after the @samp{%} and before the optional width
1012 specifier, you can also put certain @dfn{flag characters}.
1013
1014 The flag @samp{+} inserts a plus sign before a positive number, so
1015 that it always has a sign. A space character as flag inserts a space
1016 before a positive number. (Otherwise, positive numbers start with the
1017 first digit.) These flags are useful for ensuring that positive
1018 numbers and negative numbers use the same number of columns. They are
1019 ignored except for @samp{%d}, @samp{%e}, @samp{%f}, @samp{%g}, and if
1020 both flags are used, @samp{+} takes precedence.
1021
1022 The flag @samp{#} specifies an alternate form which depends on
1023 the format in use. For @samp{%o}, it ensures that the result begins
1024 with a @samp{0}. For @samp{%x} and @samp{%X}, it prefixes the result
1025 with @samp{0x} or @samp{0X}. For @samp{%e}, @samp{%f}, and @samp{%g},
1026 the @samp{#} flag means include a decimal point even if the precision
1027 is zero.
1028
1029 The flag @samp{0} ensures that the padding consists of @samp{0}
1030 characters instead of spaces. This flag is ignored for non-numerical
1031 specification characters like @samp{%s}, @samp{%S} and @samp{%c}.
1032 These specification characters accept the @samp{0} flag, but still pad
1033 with @emph{spaces}.
1034
1035 The flag @samp{-} causes the padding inserted by the width
1036 specifier, if any, to be inserted on the right rather than the left.
1037 If both @samp{-} and @samp{0} are present, the @samp{0} flag is
1038 ignored.
1039
1040 @example
1041 @group
1042 (format "%06d is padded on the left with zeros" 123)
1043 @result{} "000123 is padded on the left with zeros"
1044
1045 (format "'%-6d' is padded on the right" 123)
1046 @result{} "'123 ' is padded on the right"
1047
1048 (format "The word '%-7s' actually has %d letters in it."
1049 "foo" (length "foo"))
1050 @result{} "The word 'foo ' actually has 3 letters in it."
1051 @end group
1052 @end example
1053
1054 @cindex precision in format specifications
1055 All the specification characters allow an optional @dfn{precision}
1056 before the character (after the width, if present). The precision is
1057 a decimal-point @samp{.} followed by a digit-string. For the
1058 floating-point specifications (@samp{%e}, @samp{%f}, @samp{%g}), the
1059 precision specifies how many decimal places to show; if zero, the
1060 decimal-point itself is also omitted. For @samp{%s} and @samp{%S},
1061 the precision truncates the string to the given width, so @samp{%.3s}
1062 shows only the first three characters of the representation for
1063 @var{object}. Precision has no effect for other specification
1064 characters.
1065
1066 @node Case Conversion
1067 @section Case Conversion in Lisp
1068 @cindex upper case
1069 @cindex lower case
1070 @cindex character case
1071 @cindex case conversion in Lisp
1072
1073 The character case functions change the case of single characters or
1074 of the contents of strings. The functions normally convert only
1075 alphabetic characters (the letters @samp{A} through @samp{Z} and
1076 @samp{a} through @samp{z}, as well as non-@acronym{ASCII} letters); other
1077 characters are not altered. You can specify a different case
1078 conversion mapping by specifying a case table (@pxref{Case Tables}).
1079
1080 These functions do not modify the strings that are passed to them as
1081 arguments.
1082
1083 The examples below use the characters @samp{X} and @samp{x} which have
1084 @acronym{ASCII} codes 88 and 120 respectively.
1085
1086 @defun downcase string-or-char
1087 This function converts @var{string-or-char}, which should be either a
1088 character or a string, to lower case.
1089
1090 When @var{string-or-char} is a string, this function returns a new
1091 string in which each letter in the argument that is upper case is
1092 converted to lower case. When @var{string-or-char} is a character,
1093 this function returns the corresponding lower case character (an
1094 integer); if the original character is lower case, or is not a letter,
1095 the return value is equal to the original character.
1096
1097 @example
1098 (downcase "The cat in the hat")
1099 @result{} "the cat in the hat"
1100
1101 (downcase ?X)
1102 @result{} 120
1103 @end example
1104 @end defun
1105
1106 @defun upcase string-or-char
1107 This function converts @var{string-or-char}, which should be either a
1108 character or a string, to upper case.
1109
1110 When @var{string-or-char} is a string, this function returns a new
1111 string in which each letter in the argument that is lower case is
1112 converted to upper case. When @var{string-or-char} is a character,
1113 this function returns the corresponding upper case character (an
1114 integer); if the original character is upper case, or is not a letter,
1115 the return value is equal to the original character.
1116
1117 @example
1118 (upcase "The cat in the hat")
1119 @result{} "THE CAT IN THE HAT"
1120
1121 (upcase ?x)
1122 @result{} 88
1123 @end example
1124 @end defun
1125
1126 @defun capitalize string-or-char
1127 @cindex capitalization
1128 This function capitalizes strings or characters. If
1129 @var{string-or-char} is a string, the function returns a new string
1130 whose contents are a copy of @var{string-or-char} in which each word
1131 has been capitalized. This means that the first character of each
1132 word is converted to upper case, and the rest are converted to lower
1133 case.
1134
1135 The definition of a word is any sequence of consecutive characters that
1136 are assigned to the word constituent syntax class in the current syntax
1137 table (@pxref{Syntax Class Table}).
1138
1139 When @var{string-or-char} is a character, this function does the same
1140 thing as @code{upcase}.
1141
1142 @example
1143 @group
1144 (capitalize "The cat in the hat")
1145 @result{} "The Cat In The Hat"
1146 @end group
1147
1148 @group
1149 (capitalize "THE 77TH-HATTED CAT")
1150 @result{} "The 77th-Hatted Cat"
1151 @end group
1152
1153 @group
1154 (capitalize ?x)
1155 @result{} 88
1156 @end group
1157 @end example
1158 @end defun
1159
1160 @defun upcase-initials string-or-char
1161 If @var{string-or-char} is a string, this function capitalizes the
1162 initials of the words in @var{string-or-char}, without altering any
1163 letters other than the initials. It returns a new string whose
1164 contents are a copy of @var{string-or-char}, in which each word has
1165 had its initial letter converted to upper case.
1166
1167 The definition of a word is any sequence of consecutive characters that
1168 are assigned to the word constituent syntax class in the current syntax
1169 table (@pxref{Syntax Class Table}).
1170
1171 When the argument to @code{upcase-initials} is a character,
1172 @code{upcase-initials} has the same result as @code{upcase}.
1173
1174 @example
1175 @group
1176 (upcase-initials "The CAT in the hAt")
1177 @result{} "The CAT In The HAt"
1178 @end group
1179 @end example
1180 @end defun
1181
1182 @xref{Text Comparison}, for functions that compare strings; some of
1183 them ignore case differences, or can optionally ignore case differences.
1184
1185 @node Case Tables
1186 @section The Case Table
1187
1188 You can customize case conversion by installing a special @dfn{case
1189 table}. A case table specifies the mapping between upper case and lower
1190 case letters. It affects both the case conversion functions for Lisp
1191 objects (see the previous section) and those that apply to text in the
1192 buffer (@pxref{Case Changes}). Each buffer has a case table; there is
1193 also a standard case table which is used to initialize the case table
1194 of new buffers.
1195
1196 A case table is a char-table (@pxref{Char-Tables}) whose subtype is
1197 @code{case-table}. This char-table maps each character into the
1198 corresponding lower case character. It has three extra slots, which
1199 hold related tables:
1200
1201 @table @var
1202 @item upcase
1203 The upcase table maps each character into the corresponding upper
1204 case character.
1205 @item canonicalize
1206 The canonicalize table maps all of a set of case-related characters
1207 into a particular member of that set.
1208 @item equivalences
1209 The equivalences table maps each one of a set of case-related characters
1210 into the next character in that set.
1211 @end table
1212
1213 In simple cases, all you need to specify is the mapping to lower-case;
1214 the three related tables will be calculated automatically from that one.
1215
1216 For some languages, upper and lower case letters are not in one-to-one
1217 correspondence. There may be two different lower case letters with the
1218 same upper case equivalent. In these cases, you need to specify the
1219 maps for both lower case and upper case.
1220
1221 The extra table @var{canonicalize} maps each character to a canonical
1222 equivalent; any two characters that are related by case-conversion have
1223 the same canonical equivalent character. For example, since @samp{a}
1224 and @samp{A} are related by case-conversion, they should have the same
1225 canonical equivalent character (which should be either @samp{a} for both
1226 of them, or @samp{A} for both of them).
1227
1228 The extra table @var{equivalences} is a map that cyclically permutes
1229 each equivalence class (of characters with the same canonical
1230 equivalent). (For ordinary @acronym{ASCII}, this would map @samp{a} into
1231 @samp{A} and @samp{A} into @samp{a}, and likewise for each set of
1232 equivalent characters.)
1233
1234 When constructing a case table, you can provide @code{nil} for
1235 @var{canonicalize}; then Emacs fills in this slot from the lower case
1236 and upper case mappings. You can also provide @code{nil} for
1237 @var{equivalences}; then Emacs fills in this slot from
1238 @var{canonicalize}. In a case table that is actually in use, those
1239 components are non-@code{nil}. Do not try to specify
1240 @var{equivalences} without also specifying @var{canonicalize}.
1241
1242 Here are the functions for working with case tables:
1243
1244 @defun case-table-p object
1245 This predicate returns non-@code{nil} if @var{object} is a valid case
1246 table.
1247 @end defun
1248
1249 @defun set-standard-case-table table
1250 This function makes @var{table} the standard case table, so that it will
1251 be used in any buffers created subsequently.
1252 @end defun
1253
1254 @defun standard-case-table
1255 This returns the standard case table.
1256 @end defun
1257
1258 @defun current-case-table
1259 This function returns the current buffer's case table.
1260 @end defun
1261
1262 @defun set-case-table table
1263 This sets the current buffer's case table to @var{table}.
1264 @end defun
1265
1266 @defmac with-case-table table body@dots{}
1267 The @code{with-case-table} macro saves the current case table, makes
1268 @var{table} the current case table, evaluates the @var{body} forms,
1269 and finally restores the case table. The return value is the value of
1270 the last form in @var{body}. The case table is restored even in case
1271 of an abnormal exit via @code{throw} or error (@pxref{Nonlocal
1272 Exits}).
1273 @end defmac
1274
1275 Some language environments modify the case conversions of
1276 @acronym{ASCII} characters; for example, in the Turkish language
1277 environment, the @acronym{ASCII} capital I is downcased into
1278 a Turkish dotless i (@samp{ı}). This can interfere with code that requires
1279 ordinary @acronym{ASCII} case conversion, such as implementations of
1280 @acronym{ASCII}-based network protocols. In that case, use the
1281 @code{with-case-table} macro with the variable @var{ascii-case-table},
1282 which stores the unmodified case table for the @acronym{ASCII}
1283 character set.
1284
1285 @defvar ascii-case-table
1286 The case table for the @acronym{ASCII} character set. This should not be
1287 modified by any language environment settings.
1288 @end defvar
1289
1290 The following three functions are convenient subroutines for packages
1291 that define non-@acronym{ASCII} character sets. They modify the specified
1292 case table @var{case-table}; they also modify the standard syntax table.
1293 @xref{Syntax Tables}. Normally you would use these functions to change
1294 the standard case table.
1295
1296 @defun set-case-syntax-pair uc lc case-table
1297 This function specifies a pair of corresponding letters, one upper case
1298 and one lower case.
1299 @end defun
1300
1301 @defun set-case-syntax-delims l r case-table
1302 This function makes characters @var{l} and @var{r} a matching pair of
1303 case-invariant delimiters.
1304 @end defun
1305
1306 @defun set-case-syntax char syntax case-table
1307 This function makes @var{char} case-invariant, with syntax
1308 @var{syntax}.
1309 @end defun
1310
1311 @deffn Command describe-buffer-case-table
1312 This command displays a description of the contents of the current
1313 buffer's case table.
1314 @end deffn