]> code.delx.au - gnu-emacs/blob - src/fns.c
Compute C decls for DEFSYMs automatically
[gnu-emacs] / src / fns.c
1 /* Random utility Lisp functions.
2
3 Copyright (C) 1985-1987, 1993-1995, 1997-2015 Free Software Foundation,
4 Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21 #include <config.h>
22
23 #include <unistd.h>
24 #include <time.h>
25
26 #include <intprops.h>
27 #include <vla.h>
28
29 #include "lisp.h"
30 #include "commands.h"
31 #include "character.h"
32 #include "coding.h"
33 #include "buffer.h"
34 #include "keyboard.h"
35 #include "keymap.h"
36 #include "intervals.h"
37 #include "frame.h"
38 #include "window.h"
39 #include "blockinput.h"
40 #if defined (HAVE_X_WINDOWS)
41 #include "xterm.h"
42 #endif
43
44 static void sort_vector_copy (Lisp_Object, ptrdiff_t,
45 Lisp_Object [restrict], Lisp_Object [restrict]);
46 static bool internal_equal (Lisp_Object, Lisp_Object, int, bool, Lisp_Object);
47
48 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
49 doc: /* Return the argument unchanged. */)
50 (Lisp_Object arg)
51 {
52 return arg;
53 }
54
55 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
56 doc: /* Return a pseudo-random number.
57 All integers representable in Lisp, i.e. between `most-negative-fixnum'
58 and `most-positive-fixnum', inclusive, are equally likely.
59
60 With positive integer LIMIT, return random number in interval [0,LIMIT).
61 With argument t, set the random number seed from the current time and pid.
62 With a string argument, set the seed based on the string's contents.
63 Other values of LIMIT are ignored.
64
65 See Info node `(elisp)Random Numbers' for more details. */)
66 (Lisp_Object limit)
67 {
68 EMACS_INT val;
69
70 if (EQ (limit, Qt))
71 init_random ();
72 else if (STRINGP (limit))
73 seed_random (SSDATA (limit), SBYTES (limit));
74
75 val = get_random ();
76 if (INTEGERP (limit) && 0 < XINT (limit))
77 while (true)
78 {
79 /* Return the remainder, except reject the rare case where
80 get_random returns a number so close to INTMASK that the
81 remainder isn't random. */
82 EMACS_INT remainder = val % XINT (limit);
83 if (val - remainder <= INTMASK - XINT (limit) + 1)
84 return make_number (remainder);
85 val = get_random ();
86 }
87 return make_number (val);
88 }
89 \f
90 /* Heuristic on how many iterations of a tight loop can be safely done
91 before it's time to do a QUIT. This must be a power of 2. */
92 enum { QUIT_COUNT_HEURISTIC = 1 << 16 };
93
94 /* Random data-structure functions. */
95
96 static void
97 CHECK_LIST_END (Lisp_Object x, Lisp_Object y)
98 {
99 CHECK_TYPE (NILP (x), Qlistp, y);
100 }
101
102 DEFUN ("length", Flength, Slength, 1, 1, 0,
103 doc: /* Return the length of vector, list or string SEQUENCE.
104 A byte-code function object is also allowed.
105 If the string contains multibyte characters, this is not necessarily
106 the number of bytes in the string; it is the number of characters.
107 To get the number of bytes, use `string-bytes'. */)
108 (register Lisp_Object sequence)
109 {
110 register Lisp_Object val;
111
112 if (STRINGP (sequence))
113 XSETFASTINT (val, SCHARS (sequence));
114 else if (VECTORP (sequence))
115 XSETFASTINT (val, ASIZE (sequence));
116 else if (CHAR_TABLE_P (sequence))
117 XSETFASTINT (val, MAX_CHAR);
118 else if (BOOL_VECTOR_P (sequence))
119 XSETFASTINT (val, bool_vector_size (sequence));
120 else if (COMPILEDP (sequence))
121 XSETFASTINT (val, ASIZE (sequence) & PSEUDOVECTOR_SIZE_MASK);
122 else if (CONSP (sequence))
123 {
124 EMACS_INT i = 0;
125
126 do
127 {
128 ++i;
129 if ((i & (QUIT_COUNT_HEURISTIC - 1)) == 0)
130 {
131 if (MOST_POSITIVE_FIXNUM < i)
132 error ("List too long");
133 QUIT;
134 }
135 sequence = XCDR (sequence);
136 }
137 while (CONSP (sequence));
138
139 CHECK_LIST_END (sequence, sequence);
140
141 val = make_number (i);
142 }
143 else if (NILP (sequence))
144 XSETFASTINT (val, 0);
145 else
146 wrong_type_argument (Qsequencep, sequence);
147
148 return val;
149 }
150
151 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
152 doc: /* Return the length of a list, but avoid error or infinite loop.
153 This function never gets an error. If LIST is not really a list,
154 it returns 0. If LIST is circular, it returns a finite value
155 which is at least the number of distinct elements. */)
156 (Lisp_Object list)
157 {
158 Lisp_Object tail, halftail;
159 double hilen = 0;
160 uintmax_t lolen = 1;
161
162 if (! CONSP (list))
163 return make_number (0);
164
165 /* halftail is used to detect circular lists. */
166 for (tail = halftail = list; ; )
167 {
168 tail = XCDR (tail);
169 if (! CONSP (tail))
170 break;
171 if (EQ (tail, halftail))
172 break;
173 lolen++;
174 if ((lolen & 1) == 0)
175 {
176 halftail = XCDR (halftail);
177 if ((lolen & (QUIT_COUNT_HEURISTIC - 1)) == 0)
178 {
179 QUIT;
180 if (lolen == 0)
181 hilen += UINTMAX_MAX + 1.0;
182 }
183 }
184 }
185
186 /* If the length does not fit into a fixnum, return a float.
187 On all known practical machines this returns an upper bound on
188 the true length. */
189 return hilen ? make_float (hilen + lolen) : make_fixnum_or_float (lolen);
190 }
191
192 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
193 doc: /* Return the number of bytes in STRING.
194 If STRING is multibyte, this may be greater than the length of STRING. */)
195 (Lisp_Object string)
196 {
197 CHECK_STRING (string);
198 return make_number (SBYTES (string));
199 }
200
201 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
202 doc: /* Return t if two strings have identical contents.
203 Case is significant, but text properties are ignored.
204 Symbols are also allowed; their print names are used instead. */)
205 (register Lisp_Object s1, Lisp_Object s2)
206 {
207 if (SYMBOLP (s1))
208 s1 = SYMBOL_NAME (s1);
209 if (SYMBOLP (s2))
210 s2 = SYMBOL_NAME (s2);
211 CHECK_STRING (s1);
212 CHECK_STRING (s2);
213
214 if (SCHARS (s1) != SCHARS (s2)
215 || SBYTES (s1) != SBYTES (s2)
216 || memcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
217 return Qnil;
218 return Qt;
219 }
220
221 DEFUN ("compare-strings", Fcompare_strings, Scompare_strings, 6, 7, 0,
222 doc: /* Compare the contents of two strings, converting to multibyte if needed.
223 The arguments START1, END1, START2, and END2, if non-nil, are
224 positions specifying which parts of STR1 or STR2 to compare. In
225 string STR1, compare the part between START1 (inclusive) and END1
226 \(exclusive). If START1 is nil, it defaults to 0, the beginning of
227 the string; if END1 is nil, it defaults to the length of the string.
228 Likewise, in string STR2, compare the part between START2 and END2.
229 Like in `substring', negative values are counted from the end.
230
231 The strings are compared by the numeric values of their characters.
232 For instance, STR1 is "less than" STR2 if its first differing
233 character has a smaller numeric value. If IGNORE-CASE is non-nil,
234 characters are converted to lower-case before comparing them. Unibyte
235 strings are converted to multibyte for comparison.
236
237 The value is t if the strings (or specified portions) match.
238 If string STR1 is less, the value is a negative number N;
239 - 1 - N is the number of characters that match at the beginning.
240 If string STR1 is greater, the value is a positive number N;
241 N - 1 is the number of characters that match at the beginning. */)
242 (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2,
243 Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
244 {
245 ptrdiff_t from1, to1, from2, to2, i1, i1_byte, i2, i2_byte;
246
247 CHECK_STRING (str1);
248 CHECK_STRING (str2);
249
250 /* For backward compatibility, silently bring too-large positive end
251 values into range. */
252 if (INTEGERP (end1) && SCHARS (str1) < XINT (end1))
253 end1 = make_number (SCHARS (str1));
254 if (INTEGERP (end2) && SCHARS (str2) < XINT (end2))
255 end2 = make_number (SCHARS (str2));
256
257 validate_subarray (str1, start1, end1, SCHARS (str1), &from1, &to1);
258 validate_subarray (str2, start2, end2, SCHARS (str2), &from2, &to2);
259
260 i1 = from1;
261 i2 = from2;
262
263 i1_byte = string_char_to_byte (str1, i1);
264 i2_byte = string_char_to_byte (str2, i2);
265
266 while (i1 < to1 && i2 < to2)
267 {
268 /* When we find a mismatch, we must compare the
269 characters, not just the bytes. */
270 int c1, c2;
271
272 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c1, str1, i1, i1_byte);
273 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c2, str2, i2, i2_byte);
274
275 if (c1 == c2)
276 continue;
277
278 if (! NILP (ignore_case))
279 {
280 c1 = XINT (Fupcase (make_number (c1)));
281 c2 = XINT (Fupcase (make_number (c2)));
282 }
283
284 if (c1 == c2)
285 continue;
286
287 /* Note that I1 has already been incremented
288 past the character that we are comparing;
289 hence we don't add or subtract 1 here. */
290 if (c1 < c2)
291 return make_number (- i1 + from1);
292 else
293 return make_number (i1 - from1);
294 }
295
296 if (i1 < to1)
297 return make_number (i1 - from1 + 1);
298 if (i2 < to2)
299 return make_number (- i1 + from1 - 1);
300
301 return Qt;
302 }
303
304 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
305 doc: /* Return t if first arg string is less than second in lexicographic order.
306 Case is significant.
307 Symbols are also allowed; their print names are used instead. */)
308 (register Lisp_Object s1, Lisp_Object s2)
309 {
310 register ptrdiff_t end;
311 register ptrdiff_t i1, i1_byte, i2, i2_byte;
312
313 if (SYMBOLP (s1))
314 s1 = SYMBOL_NAME (s1);
315 if (SYMBOLP (s2))
316 s2 = SYMBOL_NAME (s2);
317 CHECK_STRING (s1);
318 CHECK_STRING (s2);
319
320 i1 = i1_byte = i2 = i2_byte = 0;
321
322 end = SCHARS (s1);
323 if (end > SCHARS (s2))
324 end = SCHARS (s2);
325
326 while (i1 < end)
327 {
328 /* When we find a mismatch, we must compare the
329 characters, not just the bytes. */
330 int c1, c2;
331
332 FETCH_STRING_CHAR_ADVANCE (c1, s1, i1, i1_byte);
333 FETCH_STRING_CHAR_ADVANCE (c2, s2, i2, i2_byte);
334
335 if (c1 != c2)
336 return c1 < c2 ? Qt : Qnil;
337 }
338 return i1 < SCHARS (s2) ? Qt : Qnil;
339 }
340
341 DEFUN ("string-collate-lessp", Fstring_collate_lessp, Sstring_collate_lessp, 2, 4, 0,
342 doc: /* Return t if first arg string is less than second in collation order.
343 Symbols are also allowed; their print names are used instead.
344
345 This function obeys the conventions for collation order in your
346 locale settings. For example, punctuation and whitespace characters
347 might be considered less significant for sorting:
348
349 \(sort '\("11" "12" "1 1" "1 2" "1.1" "1.2") 'string-collate-lessp)
350 => \("11" "1 1" "1.1" "12" "1 2" "1.2")
351
352 The optional argument LOCALE, a string, overrides the setting of your
353 current locale identifier for collation. The value is system
354 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
355 while it would be, e.g., \"enu_USA.1252\" on MS-Windows systems.
356
357 If IGNORE-CASE is non-nil, characters are converted to lower-case
358 before comparing them.
359
360 To emulate Unicode-compliant collation on MS-Windows systems,
361 bind `w32-collate-ignore-punctuation' to a non-nil value, since
362 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
363
364 If your system does not support a locale environment, this function
365 behaves like `string-lessp'. */)
366 (Lisp_Object s1, Lisp_Object s2, Lisp_Object locale, Lisp_Object ignore_case)
367 {
368 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
369 /* Check parameters. */
370 if (SYMBOLP (s1))
371 s1 = SYMBOL_NAME (s1);
372 if (SYMBOLP (s2))
373 s2 = SYMBOL_NAME (s2);
374 CHECK_STRING (s1);
375 CHECK_STRING (s2);
376 if (!NILP (locale))
377 CHECK_STRING (locale);
378
379 return (str_collate (s1, s2, locale, ignore_case) < 0) ? Qt : Qnil;
380
381 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
382 return Fstring_lessp (s1, s2);
383 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
384 }
385
386 DEFUN ("string-collate-equalp", Fstring_collate_equalp, Sstring_collate_equalp, 2, 4, 0,
387 doc: /* Return t if two strings have identical contents.
388 Symbols are also allowed; their print names are used instead.
389
390 This function obeys the conventions for collation order in your locale
391 settings. For example, characters with different coding points but
392 the same meaning might be considered as equal, like different grave
393 accent Unicode characters:
394
395 \(string-collate-equalp \(string ?\\uFF40) \(string ?\\u1FEF))
396 => t
397
398 The optional argument LOCALE, a string, overrides the setting of your
399 current locale identifier for collation. The value is system
400 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
401 while it would be \"enu_USA.1252\" on MS Windows systems.
402
403 If IGNORE-CASE is non-nil, characters are converted to lower-case
404 before comparing them.
405
406 To emulate Unicode-compliant collation on MS-Windows systems,
407 bind `w32-collate-ignore-punctuation' to a non-nil value, since
408 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
409
410 If your system does not support a locale environment, this function
411 behaves like `string-equal'.
412
413 Do NOT use this function to compare file names for equality, only
414 for sorting them. */)
415 (Lisp_Object s1, Lisp_Object s2, Lisp_Object locale, Lisp_Object ignore_case)
416 {
417 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
418 /* Check parameters. */
419 if (SYMBOLP (s1))
420 s1 = SYMBOL_NAME (s1);
421 if (SYMBOLP (s2))
422 s2 = SYMBOL_NAME (s2);
423 CHECK_STRING (s1);
424 CHECK_STRING (s2);
425 if (!NILP (locale))
426 CHECK_STRING (locale);
427
428 return (str_collate (s1, s2, locale, ignore_case) == 0) ? Qt : Qnil;
429
430 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
431 return Fstring_equal (s1, s2);
432 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
433 }
434 \f
435 static Lisp_Object concat (ptrdiff_t nargs, Lisp_Object *args,
436 enum Lisp_Type target_type, bool last_special);
437
438 /* ARGSUSED */
439 Lisp_Object
440 concat2 (Lisp_Object s1, Lisp_Object s2)
441 {
442 Lisp_Object args[2];
443 args[0] = s1;
444 args[1] = s2;
445 return concat (2, args, Lisp_String, 0);
446 }
447
448 /* ARGSUSED */
449 Lisp_Object
450 concat3 (Lisp_Object s1, Lisp_Object s2, Lisp_Object s3)
451 {
452 Lisp_Object args[3];
453 args[0] = s1;
454 args[1] = s2;
455 args[2] = s3;
456 return concat (3, args, Lisp_String, 0);
457 }
458
459 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
460 doc: /* Concatenate all the arguments and make the result a list.
461 The result is a list whose elements are the elements of all the arguments.
462 Each argument may be a list, vector or string.
463 The last argument is not copied, just used as the tail of the new list.
464 usage: (append &rest SEQUENCES) */)
465 (ptrdiff_t nargs, Lisp_Object *args)
466 {
467 return concat (nargs, args, Lisp_Cons, 1);
468 }
469
470 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
471 doc: /* Concatenate all the arguments and make the result a string.
472 The result is a string whose elements are the elements of all the arguments.
473 Each argument may be a string or a list or vector of characters (integers).
474 usage: (concat &rest SEQUENCES) */)
475 (ptrdiff_t nargs, Lisp_Object *args)
476 {
477 return concat (nargs, args, Lisp_String, 0);
478 }
479
480 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
481 doc: /* Concatenate all the arguments and make the result a vector.
482 The result is a vector whose elements are the elements of all the arguments.
483 Each argument may be a list, vector or string.
484 usage: (vconcat &rest SEQUENCES) */)
485 (ptrdiff_t nargs, Lisp_Object *args)
486 {
487 return concat (nargs, args, Lisp_Vectorlike, 0);
488 }
489
490
491 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
492 doc: /* Return a copy of a list, vector, string or char-table.
493 The elements of a list or vector are not copied; they are shared
494 with the original. */)
495 (Lisp_Object arg)
496 {
497 if (NILP (arg)) return arg;
498
499 if (CHAR_TABLE_P (arg))
500 {
501 return copy_char_table (arg);
502 }
503
504 if (BOOL_VECTOR_P (arg))
505 {
506 EMACS_INT nbits = bool_vector_size (arg);
507 ptrdiff_t nbytes = bool_vector_bytes (nbits);
508 Lisp_Object val = make_uninit_bool_vector (nbits);
509 memcpy (bool_vector_data (val), bool_vector_data (arg), nbytes);
510 return val;
511 }
512
513 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
514 wrong_type_argument (Qsequencep, arg);
515
516 return concat (1, &arg, XTYPE (arg), 0);
517 }
518
519 /* This structure holds information of an argument of `concat' that is
520 a string and has text properties to be copied. */
521 struct textprop_rec
522 {
523 ptrdiff_t argnum; /* refer to ARGS (arguments of `concat') */
524 ptrdiff_t from; /* refer to ARGS[argnum] (argument string) */
525 ptrdiff_t to; /* refer to VAL (the target string) */
526 };
527
528 static Lisp_Object
529 concat (ptrdiff_t nargs, Lisp_Object *args,
530 enum Lisp_Type target_type, bool last_special)
531 {
532 Lisp_Object val;
533 Lisp_Object tail;
534 Lisp_Object this;
535 ptrdiff_t toindex;
536 ptrdiff_t toindex_byte = 0;
537 EMACS_INT result_len;
538 EMACS_INT result_len_byte;
539 ptrdiff_t argnum;
540 Lisp_Object last_tail;
541 Lisp_Object prev;
542 bool some_multibyte;
543 /* When we make a multibyte string, we can't copy text properties
544 while concatenating each string because the length of resulting
545 string can't be decided until we finish the whole concatenation.
546 So, we record strings that have text properties to be copied
547 here, and copy the text properties after the concatenation. */
548 struct textprop_rec *textprops = NULL;
549 /* Number of elements in textprops. */
550 ptrdiff_t num_textprops = 0;
551 USE_SAFE_ALLOCA;
552
553 tail = Qnil;
554
555 /* In append, the last arg isn't treated like the others */
556 if (last_special && nargs > 0)
557 {
558 nargs--;
559 last_tail = args[nargs];
560 }
561 else
562 last_tail = Qnil;
563
564 /* Check each argument. */
565 for (argnum = 0; argnum < nargs; argnum++)
566 {
567 this = args[argnum];
568 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
569 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
570 wrong_type_argument (Qsequencep, this);
571 }
572
573 /* Compute total length in chars of arguments in RESULT_LEN.
574 If desired output is a string, also compute length in bytes
575 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
576 whether the result should be a multibyte string. */
577 result_len_byte = 0;
578 result_len = 0;
579 some_multibyte = 0;
580 for (argnum = 0; argnum < nargs; argnum++)
581 {
582 EMACS_INT len;
583 this = args[argnum];
584 len = XFASTINT (Flength (this));
585 if (target_type == Lisp_String)
586 {
587 /* We must count the number of bytes needed in the string
588 as well as the number of characters. */
589 ptrdiff_t i;
590 Lisp_Object ch;
591 int c;
592 ptrdiff_t this_len_byte;
593
594 if (VECTORP (this) || COMPILEDP (this))
595 for (i = 0; i < len; i++)
596 {
597 ch = AREF (this, i);
598 CHECK_CHARACTER (ch);
599 c = XFASTINT (ch);
600 this_len_byte = CHAR_BYTES (c);
601 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
602 string_overflow ();
603 result_len_byte += this_len_byte;
604 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
605 some_multibyte = 1;
606 }
607 else if (BOOL_VECTOR_P (this) && bool_vector_size (this) > 0)
608 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
609 else if (CONSP (this))
610 for (; CONSP (this); this = XCDR (this))
611 {
612 ch = XCAR (this);
613 CHECK_CHARACTER (ch);
614 c = XFASTINT (ch);
615 this_len_byte = CHAR_BYTES (c);
616 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
617 string_overflow ();
618 result_len_byte += this_len_byte;
619 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
620 some_multibyte = 1;
621 }
622 else if (STRINGP (this))
623 {
624 if (STRING_MULTIBYTE (this))
625 {
626 some_multibyte = 1;
627 this_len_byte = SBYTES (this);
628 }
629 else
630 this_len_byte = count_size_as_multibyte (SDATA (this),
631 SCHARS (this));
632 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
633 string_overflow ();
634 result_len_byte += this_len_byte;
635 }
636 }
637
638 result_len += len;
639 if (MOST_POSITIVE_FIXNUM < result_len)
640 memory_full (SIZE_MAX);
641 }
642
643 if (! some_multibyte)
644 result_len_byte = result_len;
645
646 /* Create the output object. */
647 if (target_type == Lisp_Cons)
648 val = Fmake_list (make_number (result_len), Qnil);
649 else if (target_type == Lisp_Vectorlike)
650 val = Fmake_vector (make_number (result_len), Qnil);
651 else if (some_multibyte)
652 val = make_uninit_multibyte_string (result_len, result_len_byte);
653 else
654 val = make_uninit_string (result_len);
655
656 /* In `append', if all but last arg are nil, return last arg. */
657 if (target_type == Lisp_Cons && EQ (val, Qnil))
658 return last_tail;
659
660 /* Copy the contents of the args into the result. */
661 if (CONSP (val))
662 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
663 else
664 toindex = 0, toindex_byte = 0;
665
666 prev = Qnil;
667 if (STRINGP (val))
668 SAFE_NALLOCA (textprops, 1, nargs);
669
670 for (argnum = 0; argnum < nargs; argnum++)
671 {
672 Lisp_Object thislen;
673 ptrdiff_t thisleni = 0;
674 register ptrdiff_t thisindex = 0;
675 register ptrdiff_t thisindex_byte = 0;
676
677 this = args[argnum];
678 if (!CONSP (this))
679 thislen = Flength (this), thisleni = XINT (thislen);
680
681 /* Between strings of the same kind, copy fast. */
682 if (STRINGP (this) && STRINGP (val)
683 && STRING_MULTIBYTE (this) == some_multibyte)
684 {
685 ptrdiff_t thislen_byte = SBYTES (this);
686
687 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
688 if (string_intervals (this))
689 {
690 textprops[num_textprops].argnum = argnum;
691 textprops[num_textprops].from = 0;
692 textprops[num_textprops++].to = toindex;
693 }
694 toindex_byte += thislen_byte;
695 toindex += thisleni;
696 }
697 /* Copy a single-byte string to a multibyte string. */
698 else if (STRINGP (this) && STRINGP (val))
699 {
700 if (string_intervals (this))
701 {
702 textprops[num_textprops].argnum = argnum;
703 textprops[num_textprops].from = 0;
704 textprops[num_textprops++].to = toindex;
705 }
706 toindex_byte += copy_text (SDATA (this),
707 SDATA (val) + toindex_byte,
708 SCHARS (this), 0, 1);
709 toindex += thisleni;
710 }
711 else
712 /* Copy element by element. */
713 while (1)
714 {
715 register Lisp_Object elt;
716
717 /* Fetch next element of `this' arg into `elt', or break if
718 `this' is exhausted. */
719 if (NILP (this)) break;
720 if (CONSP (this))
721 elt = XCAR (this), this = XCDR (this);
722 else if (thisindex >= thisleni)
723 break;
724 else if (STRINGP (this))
725 {
726 int c;
727 if (STRING_MULTIBYTE (this))
728 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
729 thisindex,
730 thisindex_byte);
731 else
732 {
733 c = SREF (this, thisindex); thisindex++;
734 if (some_multibyte && !ASCII_CHAR_P (c))
735 c = BYTE8_TO_CHAR (c);
736 }
737 XSETFASTINT (elt, c);
738 }
739 else if (BOOL_VECTOR_P (this))
740 {
741 elt = bool_vector_ref (this, thisindex);
742 thisindex++;
743 }
744 else
745 {
746 elt = AREF (this, thisindex);
747 thisindex++;
748 }
749
750 /* Store this element into the result. */
751 if (toindex < 0)
752 {
753 XSETCAR (tail, elt);
754 prev = tail;
755 tail = XCDR (tail);
756 }
757 else if (VECTORP (val))
758 {
759 ASET (val, toindex, elt);
760 toindex++;
761 }
762 else
763 {
764 int c;
765 CHECK_CHARACTER (elt);
766 c = XFASTINT (elt);
767 if (some_multibyte)
768 toindex_byte += CHAR_STRING (c, SDATA (val) + toindex_byte);
769 else
770 SSET (val, toindex_byte++, c);
771 toindex++;
772 }
773 }
774 }
775 if (!NILP (prev))
776 XSETCDR (prev, last_tail);
777
778 if (num_textprops > 0)
779 {
780 Lisp_Object props;
781 ptrdiff_t last_to_end = -1;
782
783 for (argnum = 0; argnum < num_textprops; argnum++)
784 {
785 this = args[textprops[argnum].argnum];
786 props = text_property_list (this,
787 make_number (0),
788 make_number (SCHARS (this)),
789 Qnil);
790 /* If successive arguments have properties, be sure that the
791 value of `composition' property be the copy. */
792 if (last_to_end == textprops[argnum].to)
793 make_composition_value_copy (props);
794 add_text_properties_from_list (val, props,
795 make_number (textprops[argnum].to));
796 last_to_end = textprops[argnum].to + SCHARS (this);
797 }
798 }
799
800 SAFE_FREE ();
801 return val;
802 }
803 \f
804 static Lisp_Object string_char_byte_cache_string;
805 static ptrdiff_t string_char_byte_cache_charpos;
806 static ptrdiff_t string_char_byte_cache_bytepos;
807
808 void
809 clear_string_char_byte_cache (void)
810 {
811 string_char_byte_cache_string = Qnil;
812 }
813
814 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
815
816 ptrdiff_t
817 string_char_to_byte (Lisp_Object string, ptrdiff_t char_index)
818 {
819 ptrdiff_t i_byte;
820 ptrdiff_t best_below, best_below_byte;
821 ptrdiff_t best_above, best_above_byte;
822
823 best_below = best_below_byte = 0;
824 best_above = SCHARS (string);
825 best_above_byte = SBYTES (string);
826 if (best_above == best_above_byte)
827 return char_index;
828
829 if (EQ (string, string_char_byte_cache_string))
830 {
831 if (string_char_byte_cache_charpos < char_index)
832 {
833 best_below = string_char_byte_cache_charpos;
834 best_below_byte = string_char_byte_cache_bytepos;
835 }
836 else
837 {
838 best_above = string_char_byte_cache_charpos;
839 best_above_byte = string_char_byte_cache_bytepos;
840 }
841 }
842
843 if (char_index - best_below < best_above - char_index)
844 {
845 unsigned char *p = SDATA (string) + best_below_byte;
846
847 while (best_below < char_index)
848 {
849 p += BYTES_BY_CHAR_HEAD (*p);
850 best_below++;
851 }
852 i_byte = p - SDATA (string);
853 }
854 else
855 {
856 unsigned char *p = SDATA (string) + best_above_byte;
857
858 while (best_above > char_index)
859 {
860 p--;
861 while (!CHAR_HEAD_P (*p)) p--;
862 best_above--;
863 }
864 i_byte = p - SDATA (string);
865 }
866
867 string_char_byte_cache_bytepos = i_byte;
868 string_char_byte_cache_charpos = char_index;
869 string_char_byte_cache_string = string;
870
871 return i_byte;
872 }
873 \f
874 /* Return the character index corresponding to BYTE_INDEX in STRING. */
875
876 ptrdiff_t
877 string_byte_to_char (Lisp_Object string, ptrdiff_t byte_index)
878 {
879 ptrdiff_t i, i_byte;
880 ptrdiff_t best_below, best_below_byte;
881 ptrdiff_t best_above, best_above_byte;
882
883 best_below = best_below_byte = 0;
884 best_above = SCHARS (string);
885 best_above_byte = SBYTES (string);
886 if (best_above == best_above_byte)
887 return byte_index;
888
889 if (EQ (string, string_char_byte_cache_string))
890 {
891 if (string_char_byte_cache_bytepos < byte_index)
892 {
893 best_below = string_char_byte_cache_charpos;
894 best_below_byte = string_char_byte_cache_bytepos;
895 }
896 else
897 {
898 best_above = string_char_byte_cache_charpos;
899 best_above_byte = string_char_byte_cache_bytepos;
900 }
901 }
902
903 if (byte_index - best_below_byte < best_above_byte - byte_index)
904 {
905 unsigned char *p = SDATA (string) + best_below_byte;
906 unsigned char *pend = SDATA (string) + byte_index;
907
908 while (p < pend)
909 {
910 p += BYTES_BY_CHAR_HEAD (*p);
911 best_below++;
912 }
913 i = best_below;
914 i_byte = p - SDATA (string);
915 }
916 else
917 {
918 unsigned char *p = SDATA (string) + best_above_byte;
919 unsigned char *pbeg = SDATA (string) + byte_index;
920
921 while (p > pbeg)
922 {
923 p--;
924 while (!CHAR_HEAD_P (*p)) p--;
925 best_above--;
926 }
927 i = best_above;
928 i_byte = p - SDATA (string);
929 }
930
931 string_char_byte_cache_bytepos = i_byte;
932 string_char_byte_cache_charpos = i;
933 string_char_byte_cache_string = string;
934
935 return i;
936 }
937 \f
938 /* Convert STRING to a multibyte string. */
939
940 static Lisp_Object
941 string_make_multibyte (Lisp_Object string)
942 {
943 unsigned char *buf;
944 ptrdiff_t nbytes;
945 Lisp_Object ret;
946 USE_SAFE_ALLOCA;
947
948 if (STRING_MULTIBYTE (string))
949 return string;
950
951 nbytes = count_size_as_multibyte (SDATA (string),
952 SCHARS (string));
953 /* If all the chars are ASCII, they won't need any more bytes
954 once converted. In that case, we can return STRING itself. */
955 if (nbytes == SBYTES (string))
956 return string;
957
958 buf = SAFE_ALLOCA (nbytes);
959 copy_text (SDATA (string), buf, SBYTES (string),
960 0, 1);
961
962 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
963 SAFE_FREE ();
964
965 return ret;
966 }
967
968
969 /* Convert STRING (if unibyte) to a multibyte string without changing
970 the number of characters. Characters 0200 trough 0237 are
971 converted to eight-bit characters. */
972
973 Lisp_Object
974 string_to_multibyte (Lisp_Object string)
975 {
976 unsigned char *buf;
977 ptrdiff_t nbytes;
978 Lisp_Object ret;
979 USE_SAFE_ALLOCA;
980
981 if (STRING_MULTIBYTE (string))
982 return string;
983
984 nbytes = count_size_as_multibyte (SDATA (string), SBYTES (string));
985 /* If all the chars are ASCII, they won't need any more bytes once
986 converted. */
987 if (nbytes == SBYTES (string))
988 return make_multibyte_string (SSDATA (string), nbytes, nbytes);
989
990 buf = SAFE_ALLOCA (nbytes);
991 memcpy (buf, SDATA (string), SBYTES (string));
992 str_to_multibyte (buf, nbytes, SBYTES (string));
993
994 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
995 SAFE_FREE ();
996
997 return ret;
998 }
999
1000
1001 /* Convert STRING to a single-byte string. */
1002
1003 Lisp_Object
1004 string_make_unibyte (Lisp_Object string)
1005 {
1006 ptrdiff_t nchars;
1007 unsigned char *buf;
1008 Lisp_Object ret;
1009 USE_SAFE_ALLOCA;
1010
1011 if (! STRING_MULTIBYTE (string))
1012 return string;
1013
1014 nchars = SCHARS (string);
1015
1016 buf = SAFE_ALLOCA (nchars);
1017 copy_text (SDATA (string), buf, SBYTES (string),
1018 1, 0);
1019
1020 ret = make_unibyte_string ((char *) buf, nchars);
1021 SAFE_FREE ();
1022
1023 return ret;
1024 }
1025
1026 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
1027 1, 1, 0,
1028 doc: /* Return the multibyte equivalent of STRING.
1029 If STRING is unibyte and contains non-ASCII characters, the function
1030 `unibyte-char-to-multibyte' is used to convert each unibyte character
1031 to a multibyte character. In this case, the returned string is a
1032 newly created string with no text properties. If STRING is multibyte
1033 or entirely ASCII, it is returned unchanged. In particular, when
1034 STRING is unibyte and entirely ASCII, the returned string is unibyte.
1035 \(When the characters are all ASCII, Emacs primitives will treat the
1036 string the same way whether it is unibyte or multibyte.) */)
1037 (Lisp_Object string)
1038 {
1039 CHECK_STRING (string);
1040
1041 return string_make_multibyte (string);
1042 }
1043
1044 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
1045 1, 1, 0,
1046 doc: /* Return the unibyte equivalent of STRING.
1047 Multibyte character codes are converted to unibyte according to
1048 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
1049 If the lookup in the translation table fails, this function takes just
1050 the low 8 bits of each character. */)
1051 (Lisp_Object string)
1052 {
1053 CHECK_STRING (string);
1054
1055 return string_make_unibyte (string);
1056 }
1057
1058 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
1059 1, 1, 0,
1060 doc: /* Return a unibyte string with the same individual bytes as STRING.
1061 If STRING is unibyte, the result is STRING itself.
1062 Otherwise it is a newly created string, with no text properties.
1063 If STRING is multibyte and contains a character of charset
1064 `eight-bit', it is converted to the corresponding single byte. */)
1065 (Lisp_Object string)
1066 {
1067 CHECK_STRING (string);
1068
1069 if (STRING_MULTIBYTE (string))
1070 {
1071 unsigned char *str = (unsigned char *) xlispstrdup (string);
1072 ptrdiff_t bytes = str_as_unibyte (str, SBYTES (string));
1073
1074 string = make_unibyte_string ((char *) str, bytes);
1075 xfree (str);
1076 }
1077 return string;
1078 }
1079
1080 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1081 1, 1, 0,
1082 doc: /* Return a multibyte string with the same individual bytes as STRING.
1083 If STRING is multibyte, the result is STRING itself.
1084 Otherwise it is a newly created string, with no text properties.
1085
1086 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1087 part of a correct utf-8 sequence), it is converted to the corresponding
1088 multibyte character of charset `eight-bit'.
1089 See also `string-to-multibyte'.
1090
1091 Beware, this often doesn't really do what you think it does.
1092 It is similar to (decode-coding-string STRING 'utf-8-emacs).
1093 If you're not sure, whether to use `string-as-multibyte' or
1094 `string-to-multibyte', use `string-to-multibyte'. */)
1095 (Lisp_Object string)
1096 {
1097 CHECK_STRING (string);
1098
1099 if (! STRING_MULTIBYTE (string))
1100 {
1101 Lisp_Object new_string;
1102 ptrdiff_t nchars, nbytes;
1103
1104 parse_str_as_multibyte (SDATA (string),
1105 SBYTES (string),
1106 &nchars, &nbytes);
1107 new_string = make_uninit_multibyte_string (nchars, nbytes);
1108 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1109 if (nbytes != SBYTES (string))
1110 str_as_multibyte (SDATA (new_string), nbytes,
1111 SBYTES (string), NULL);
1112 string = new_string;
1113 set_string_intervals (string, NULL);
1114 }
1115 return string;
1116 }
1117
1118 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1119 1, 1, 0,
1120 doc: /* Return a multibyte string with the same individual chars as STRING.
1121 If STRING is multibyte, the result is STRING itself.
1122 Otherwise it is a newly created string, with no text properties.
1123
1124 If STRING is unibyte and contains an 8-bit byte, it is converted to
1125 the corresponding multibyte character of charset `eight-bit'.
1126
1127 This differs from `string-as-multibyte' by converting each byte of a correct
1128 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1129 correct sequence. */)
1130 (Lisp_Object string)
1131 {
1132 CHECK_STRING (string);
1133
1134 return string_to_multibyte (string);
1135 }
1136
1137 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1138 1, 1, 0,
1139 doc: /* Return a unibyte string with the same individual chars as STRING.
1140 If STRING is unibyte, the result is STRING itself.
1141 Otherwise it is a newly created string, with no text properties,
1142 where each `eight-bit' character is converted to the corresponding byte.
1143 If STRING contains a non-ASCII, non-`eight-bit' character,
1144 an error is signaled. */)
1145 (Lisp_Object string)
1146 {
1147 CHECK_STRING (string);
1148
1149 if (STRING_MULTIBYTE (string))
1150 {
1151 ptrdiff_t chars = SCHARS (string);
1152 unsigned char *str = xmalloc (chars);
1153 ptrdiff_t converted = str_to_unibyte (SDATA (string), str, chars);
1154
1155 if (converted < chars)
1156 error ("Can't convert the %"pD"dth character to unibyte", converted);
1157 string = make_unibyte_string ((char *) str, chars);
1158 xfree (str);
1159 }
1160 return string;
1161 }
1162
1163 \f
1164 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1165 doc: /* Return a copy of ALIST.
1166 This is an alist which represents the same mapping from objects to objects,
1167 but does not share the alist structure with ALIST.
1168 The objects mapped (cars and cdrs of elements of the alist)
1169 are shared, however.
1170 Elements of ALIST that are not conses are also shared. */)
1171 (Lisp_Object alist)
1172 {
1173 register Lisp_Object tem;
1174
1175 CHECK_LIST (alist);
1176 if (NILP (alist))
1177 return alist;
1178 alist = concat (1, &alist, Lisp_Cons, 0);
1179 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1180 {
1181 register Lisp_Object car;
1182 car = XCAR (tem);
1183
1184 if (CONSP (car))
1185 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1186 }
1187 return alist;
1188 }
1189
1190 /* Check that ARRAY can have a valid subarray [FROM..TO),
1191 given that its size is SIZE.
1192 If FROM is nil, use 0; if TO is nil, use SIZE.
1193 Count negative values backwards from the end.
1194 Set *IFROM and *ITO to the two indexes used. */
1195
1196 void
1197 validate_subarray (Lisp_Object array, Lisp_Object from, Lisp_Object to,
1198 ptrdiff_t size, ptrdiff_t *ifrom, ptrdiff_t *ito)
1199 {
1200 EMACS_INT f, t;
1201
1202 if (INTEGERP (from))
1203 {
1204 f = XINT (from);
1205 if (f < 0)
1206 f += size;
1207 }
1208 else if (NILP (from))
1209 f = 0;
1210 else
1211 wrong_type_argument (Qintegerp, from);
1212
1213 if (INTEGERP (to))
1214 {
1215 t = XINT (to);
1216 if (t < 0)
1217 t += size;
1218 }
1219 else if (NILP (to))
1220 t = size;
1221 else
1222 wrong_type_argument (Qintegerp, to);
1223
1224 if (! (0 <= f && f <= t && t <= size))
1225 args_out_of_range_3 (array, from, to);
1226
1227 *ifrom = f;
1228 *ito = t;
1229 }
1230
1231 DEFUN ("substring", Fsubstring, Ssubstring, 1, 3, 0,
1232 doc: /* Return a new string whose contents are a substring of STRING.
1233 The returned string consists of the characters between index FROM
1234 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1235 zero-indexed: 0 means the first character of STRING. Negative values
1236 are counted from the end of STRING. If TO is nil, the substring runs
1237 to the end of STRING.
1238
1239 The STRING argument may also be a vector. In that case, the return
1240 value is a new vector that contains the elements between index FROM
1241 \(inclusive) and index TO (exclusive) of that vector argument.
1242
1243 With one argument, just copy STRING (with properties, if any). */)
1244 (Lisp_Object string, Lisp_Object from, Lisp_Object to)
1245 {
1246 Lisp_Object res;
1247 ptrdiff_t size, ifrom, ito;
1248
1249 size = CHECK_VECTOR_OR_STRING (string);
1250 validate_subarray (string, from, to, size, &ifrom, &ito);
1251
1252 if (STRINGP (string))
1253 {
1254 ptrdiff_t from_byte
1255 = !ifrom ? 0 : string_char_to_byte (string, ifrom);
1256 ptrdiff_t to_byte
1257 = ito == size ? SBYTES (string) : string_char_to_byte (string, ito);
1258 res = make_specified_string (SSDATA (string) + from_byte,
1259 ito - ifrom, to_byte - from_byte,
1260 STRING_MULTIBYTE (string));
1261 copy_text_properties (make_number (ifrom), make_number (ito),
1262 string, make_number (0), res, Qnil);
1263 }
1264 else
1265 res = Fvector (ito - ifrom, aref_addr (string, ifrom));
1266
1267 return res;
1268 }
1269
1270
1271 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1272 doc: /* Return a substring of STRING, without text properties.
1273 It starts at index FROM and ends before TO.
1274 TO may be nil or omitted; then the substring runs to the end of STRING.
1275 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1276 If FROM or TO is negative, it counts from the end.
1277
1278 With one argument, just copy STRING without its properties. */)
1279 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1280 {
1281 ptrdiff_t from_char, to_char, from_byte, to_byte, size;
1282
1283 CHECK_STRING (string);
1284
1285 size = SCHARS (string);
1286 validate_subarray (string, from, to, size, &from_char, &to_char);
1287
1288 from_byte = !from_char ? 0 : string_char_to_byte (string, from_char);
1289 to_byte =
1290 to_char == size ? SBYTES (string) : string_char_to_byte (string, to_char);
1291 return make_specified_string (SSDATA (string) + from_byte,
1292 to_char - from_char, to_byte - from_byte,
1293 STRING_MULTIBYTE (string));
1294 }
1295
1296 /* Extract a substring of STRING, giving start and end positions
1297 both in characters and in bytes. */
1298
1299 Lisp_Object
1300 substring_both (Lisp_Object string, ptrdiff_t from, ptrdiff_t from_byte,
1301 ptrdiff_t to, ptrdiff_t to_byte)
1302 {
1303 Lisp_Object res;
1304 ptrdiff_t size = CHECK_VECTOR_OR_STRING (string);
1305
1306 if (!(0 <= from && from <= to && to <= size))
1307 args_out_of_range_3 (string, make_number (from), make_number (to));
1308
1309 if (STRINGP (string))
1310 {
1311 res = make_specified_string (SSDATA (string) + from_byte,
1312 to - from, to_byte - from_byte,
1313 STRING_MULTIBYTE (string));
1314 copy_text_properties (make_number (from), make_number (to),
1315 string, make_number (0), res, Qnil);
1316 }
1317 else
1318 res = Fvector (to - from, aref_addr (string, from));
1319
1320 return res;
1321 }
1322 \f
1323 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1324 doc: /* Take cdr N times on LIST, return the result. */)
1325 (Lisp_Object n, Lisp_Object list)
1326 {
1327 EMACS_INT i, num;
1328 CHECK_NUMBER (n);
1329 num = XINT (n);
1330 for (i = 0; i < num && !NILP (list); i++)
1331 {
1332 QUIT;
1333 CHECK_LIST_CONS (list, list);
1334 list = XCDR (list);
1335 }
1336 return list;
1337 }
1338
1339 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1340 doc: /* Return the Nth element of LIST.
1341 N counts from zero. If LIST is not that long, nil is returned. */)
1342 (Lisp_Object n, Lisp_Object list)
1343 {
1344 return Fcar (Fnthcdr (n, list));
1345 }
1346
1347 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1348 doc: /* Return element of SEQUENCE at index N. */)
1349 (register Lisp_Object sequence, Lisp_Object n)
1350 {
1351 CHECK_NUMBER (n);
1352 if (CONSP (sequence) || NILP (sequence))
1353 return Fcar (Fnthcdr (n, sequence));
1354
1355 /* Faref signals a "not array" error, so check here. */
1356 CHECK_ARRAY (sequence, Qsequencep);
1357 return Faref (sequence, n);
1358 }
1359
1360 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1361 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1362 The value is actually the tail of LIST whose car is ELT. */)
1363 (register Lisp_Object elt, Lisp_Object list)
1364 {
1365 register Lisp_Object tail;
1366 for (tail = list; CONSP (tail); tail = XCDR (tail))
1367 {
1368 register Lisp_Object tem;
1369 CHECK_LIST_CONS (tail, list);
1370 tem = XCAR (tail);
1371 if (! NILP (Fequal (elt, tem)))
1372 return tail;
1373 QUIT;
1374 }
1375 return Qnil;
1376 }
1377
1378 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1379 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1380 The value is actually the tail of LIST whose car is ELT. */)
1381 (register Lisp_Object elt, Lisp_Object list)
1382 {
1383 while (1)
1384 {
1385 if (!CONSP (list) || EQ (XCAR (list), elt))
1386 break;
1387
1388 list = XCDR (list);
1389 if (!CONSP (list) || EQ (XCAR (list), elt))
1390 break;
1391
1392 list = XCDR (list);
1393 if (!CONSP (list) || EQ (XCAR (list), elt))
1394 break;
1395
1396 list = XCDR (list);
1397 QUIT;
1398 }
1399
1400 CHECK_LIST (list);
1401 return list;
1402 }
1403
1404 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1405 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1406 The value is actually the tail of LIST whose car is ELT. */)
1407 (register Lisp_Object elt, Lisp_Object list)
1408 {
1409 register Lisp_Object tail;
1410
1411 if (!FLOATP (elt))
1412 return Fmemq (elt, list);
1413
1414 for (tail = list; CONSP (tail); tail = XCDR (tail))
1415 {
1416 register Lisp_Object tem;
1417 CHECK_LIST_CONS (tail, list);
1418 tem = XCAR (tail);
1419 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0, Qnil))
1420 return tail;
1421 QUIT;
1422 }
1423 return Qnil;
1424 }
1425
1426 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1427 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1428 The value is actually the first element of LIST whose car is KEY.
1429 Elements of LIST that are not conses are ignored. */)
1430 (Lisp_Object key, Lisp_Object list)
1431 {
1432 while (1)
1433 {
1434 if (!CONSP (list)
1435 || (CONSP (XCAR (list))
1436 && EQ (XCAR (XCAR (list)), key)))
1437 break;
1438
1439 list = XCDR (list);
1440 if (!CONSP (list)
1441 || (CONSP (XCAR (list))
1442 && EQ (XCAR (XCAR (list)), key)))
1443 break;
1444
1445 list = XCDR (list);
1446 if (!CONSP (list)
1447 || (CONSP (XCAR (list))
1448 && EQ (XCAR (XCAR (list)), key)))
1449 break;
1450
1451 list = XCDR (list);
1452 QUIT;
1453 }
1454
1455 return CAR (list);
1456 }
1457
1458 /* Like Fassq but never report an error and do not allow quits.
1459 Use only on lists known never to be circular. */
1460
1461 Lisp_Object
1462 assq_no_quit (Lisp_Object key, Lisp_Object list)
1463 {
1464 while (CONSP (list)
1465 && (!CONSP (XCAR (list))
1466 || !EQ (XCAR (XCAR (list)), key)))
1467 list = XCDR (list);
1468
1469 return CAR_SAFE (list);
1470 }
1471
1472 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1473 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1474 The value is actually the first element of LIST whose car equals KEY. */)
1475 (Lisp_Object key, Lisp_Object list)
1476 {
1477 Lisp_Object car;
1478
1479 while (1)
1480 {
1481 if (!CONSP (list)
1482 || (CONSP (XCAR (list))
1483 && (car = XCAR (XCAR (list)),
1484 EQ (car, key) || !NILP (Fequal (car, key)))))
1485 break;
1486
1487 list = XCDR (list);
1488 if (!CONSP (list)
1489 || (CONSP (XCAR (list))
1490 && (car = XCAR (XCAR (list)),
1491 EQ (car, key) || !NILP (Fequal (car, key)))))
1492 break;
1493
1494 list = XCDR (list);
1495 if (!CONSP (list)
1496 || (CONSP (XCAR (list))
1497 && (car = XCAR (XCAR (list)),
1498 EQ (car, key) || !NILP (Fequal (car, key)))))
1499 break;
1500
1501 list = XCDR (list);
1502 QUIT;
1503 }
1504
1505 return CAR (list);
1506 }
1507
1508 /* Like Fassoc but never report an error and do not allow quits.
1509 Use only on lists known never to be circular. */
1510
1511 Lisp_Object
1512 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1513 {
1514 while (CONSP (list)
1515 && (!CONSP (XCAR (list))
1516 || (!EQ (XCAR (XCAR (list)), key)
1517 && NILP (Fequal (XCAR (XCAR (list)), key)))))
1518 list = XCDR (list);
1519
1520 return CONSP (list) ? XCAR (list) : Qnil;
1521 }
1522
1523 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1524 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1525 The value is actually the first element of LIST whose cdr is KEY. */)
1526 (register Lisp_Object key, Lisp_Object list)
1527 {
1528 while (1)
1529 {
1530 if (!CONSP (list)
1531 || (CONSP (XCAR (list))
1532 && EQ (XCDR (XCAR (list)), key)))
1533 break;
1534
1535 list = XCDR (list);
1536 if (!CONSP (list)
1537 || (CONSP (XCAR (list))
1538 && EQ (XCDR (XCAR (list)), key)))
1539 break;
1540
1541 list = XCDR (list);
1542 if (!CONSP (list)
1543 || (CONSP (XCAR (list))
1544 && EQ (XCDR (XCAR (list)), key)))
1545 break;
1546
1547 list = XCDR (list);
1548 QUIT;
1549 }
1550
1551 return CAR (list);
1552 }
1553
1554 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1555 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1556 The value is actually the first element of LIST whose cdr equals KEY. */)
1557 (Lisp_Object key, Lisp_Object list)
1558 {
1559 Lisp_Object cdr;
1560
1561 while (1)
1562 {
1563 if (!CONSP (list)
1564 || (CONSP (XCAR (list))
1565 && (cdr = XCDR (XCAR (list)),
1566 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1567 break;
1568
1569 list = XCDR (list);
1570 if (!CONSP (list)
1571 || (CONSP (XCAR (list))
1572 && (cdr = XCDR (XCAR (list)),
1573 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1574 break;
1575
1576 list = XCDR (list);
1577 if (!CONSP (list)
1578 || (CONSP (XCAR (list))
1579 && (cdr = XCDR (XCAR (list)),
1580 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1581 break;
1582
1583 list = XCDR (list);
1584 QUIT;
1585 }
1586
1587 return CAR (list);
1588 }
1589 \f
1590 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1591 doc: /* Delete members of LIST which are `eq' to ELT, and return the result.
1592 More precisely, this function skips any members `eq' to ELT at the
1593 front of LIST, then removes members `eq' to ELT from the remaining
1594 sublist by modifying its list structure, then returns the resulting
1595 list.
1596
1597 Write `(setq foo (delq element foo))' to be sure of correctly changing
1598 the value of a list `foo'. */)
1599 (register Lisp_Object elt, Lisp_Object list)
1600 {
1601 Lisp_Object tail, tortoise, prev = Qnil;
1602 bool skip;
1603
1604 FOR_EACH_TAIL (tail, list, tortoise, skip)
1605 {
1606 Lisp_Object tem = XCAR (tail);
1607 if (EQ (elt, tem))
1608 {
1609 if (NILP (prev))
1610 list = XCDR (tail);
1611 else
1612 Fsetcdr (prev, XCDR (tail));
1613 }
1614 else
1615 prev = tail;
1616 }
1617 return list;
1618 }
1619
1620 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1621 doc: /* Delete members of SEQ which are `equal' to ELT, and return the result.
1622 SEQ must be a sequence (i.e. a list, a vector, or a string).
1623 The return value is a sequence of the same type.
1624
1625 If SEQ is a list, this behaves like `delq', except that it compares
1626 with `equal' instead of `eq'. In particular, it may remove elements
1627 by altering the list structure.
1628
1629 If SEQ is not a list, deletion is never performed destructively;
1630 instead this function creates and returns a new vector or string.
1631
1632 Write `(setq foo (delete element foo))' to be sure of correctly
1633 changing the value of a sequence `foo'. */)
1634 (Lisp_Object elt, Lisp_Object seq)
1635 {
1636 if (VECTORP (seq))
1637 {
1638 ptrdiff_t i, n;
1639
1640 for (i = n = 0; i < ASIZE (seq); ++i)
1641 if (NILP (Fequal (AREF (seq, i), elt)))
1642 ++n;
1643
1644 if (n != ASIZE (seq))
1645 {
1646 struct Lisp_Vector *p = allocate_vector (n);
1647
1648 for (i = n = 0; i < ASIZE (seq); ++i)
1649 if (NILP (Fequal (AREF (seq, i), elt)))
1650 p->contents[n++] = AREF (seq, i);
1651
1652 XSETVECTOR (seq, p);
1653 }
1654 }
1655 else if (STRINGP (seq))
1656 {
1657 ptrdiff_t i, ibyte, nchars, nbytes, cbytes;
1658 int c;
1659
1660 for (i = nchars = nbytes = ibyte = 0;
1661 i < SCHARS (seq);
1662 ++i, ibyte += cbytes)
1663 {
1664 if (STRING_MULTIBYTE (seq))
1665 {
1666 c = STRING_CHAR (SDATA (seq) + ibyte);
1667 cbytes = CHAR_BYTES (c);
1668 }
1669 else
1670 {
1671 c = SREF (seq, i);
1672 cbytes = 1;
1673 }
1674
1675 if (!INTEGERP (elt) || c != XINT (elt))
1676 {
1677 ++nchars;
1678 nbytes += cbytes;
1679 }
1680 }
1681
1682 if (nchars != SCHARS (seq))
1683 {
1684 Lisp_Object tem;
1685
1686 tem = make_uninit_multibyte_string (nchars, nbytes);
1687 if (!STRING_MULTIBYTE (seq))
1688 STRING_SET_UNIBYTE (tem);
1689
1690 for (i = nchars = nbytes = ibyte = 0;
1691 i < SCHARS (seq);
1692 ++i, ibyte += cbytes)
1693 {
1694 if (STRING_MULTIBYTE (seq))
1695 {
1696 c = STRING_CHAR (SDATA (seq) + ibyte);
1697 cbytes = CHAR_BYTES (c);
1698 }
1699 else
1700 {
1701 c = SREF (seq, i);
1702 cbytes = 1;
1703 }
1704
1705 if (!INTEGERP (elt) || c != XINT (elt))
1706 {
1707 unsigned char *from = SDATA (seq) + ibyte;
1708 unsigned char *to = SDATA (tem) + nbytes;
1709 ptrdiff_t n;
1710
1711 ++nchars;
1712 nbytes += cbytes;
1713
1714 for (n = cbytes; n--; )
1715 *to++ = *from++;
1716 }
1717 }
1718
1719 seq = tem;
1720 }
1721 }
1722 else
1723 {
1724 Lisp_Object tail, prev;
1725
1726 for (tail = seq, prev = Qnil; CONSP (tail); tail = XCDR (tail))
1727 {
1728 CHECK_LIST_CONS (tail, seq);
1729
1730 if (!NILP (Fequal (elt, XCAR (tail))))
1731 {
1732 if (NILP (prev))
1733 seq = XCDR (tail);
1734 else
1735 Fsetcdr (prev, XCDR (tail));
1736 }
1737 else
1738 prev = tail;
1739 QUIT;
1740 }
1741 }
1742
1743 return seq;
1744 }
1745
1746 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1747 doc: /* Reverse order of items in a list, vector or string SEQ.
1748 If SEQ is a list, it should be nil-terminated.
1749 This function may destructively modify SEQ to produce the value. */)
1750 (Lisp_Object seq)
1751 {
1752 if (NILP (seq))
1753 return seq;
1754 else if (STRINGP (seq))
1755 return Freverse (seq);
1756 else if (CONSP (seq))
1757 {
1758 Lisp_Object prev, tail, next;
1759
1760 for (prev = Qnil, tail = seq; !NILP (tail); tail = next)
1761 {
1762 QUIT;
1763 CHECK_LIST_CONS (tail, tail);
1764 next = XCDR (tail);
1765 Fsetcdr (tail, prev);
1766 prev = tail;
1767 }
1768 seq = prev;
1769 }
1770 else if (VECTORP (seq))
1771 {
1772 ptrdiff_t i, size = ASIZE (seq);
1773
1774 for (i = 0; i < size / 2; i++)
1775 {
1776 Lisp_Object tem = AREF (seq, i);
1777 ASET (seq, i, AREF (seq, size - i - 1));
1778 ASET (seq, size - i - 1, tem);
1779 }
1780 }
1781 else if (BOOL_VECTOR_P (seq))
1782 {
1783 ptrdiff_t i, size = bool_vector_size (seq);
1784
1785 for (i = 0; i < size / 2; i++)
1786 {
1787 bool tem = bool_vector_bitref (seq, i);
1788 bool_vector_set (seq, i, bool_vector_bitref (seq, size - i - 1));
1789 bool_vector_set (seq, size - i - 1, tem);
1790 }
1791 }
1792 else
1793 wrong_type_argument (Qarrayp, seq);
1794 return seq;
1795 }
1796
1797 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1798 doc: /* Return the reversed copy of list, vector, or string SEQ.
1799 See also the function `nreverse', which is used more often. */)
1800 (Lisp_Object seq)
1801 {
1802 Lisp_Object new;
1803
1804 if (NILP (seq))
1805 return Qnil;
1806 else if (CONSP (seq))
1807 {
1808 for (new = Qnil; CONSP (seq); seq = XCDR (seq))
1809 {
1810 QUIT;
1811 new = Fcons (XCAR (seq), new);
1812 }
1813 CHECK_LIST_END (seq, seq);
1814 }
1815 else if (VECTORP (seq))
1816 {
1817 ptrdiff_t i, size = ASIZE (seq);
1818
1819 new = make_uninit_vector (size);
1820 for (i = 0; i < size; i++)
1821 ASET (new, i, AREF (seq, size - i - 1));
1822 }
1823 else if (BOOL_VECTOR_P (seq))
1824 {
1825 ptrdiff_t i;
1826 EMACS_INT nbits = bool_vector_size (seq);
1827
1828 new = make_uninit_bool_vector (nbits);
1829 for (i = 0; i < nbits; i++)
1830 bool_vector_set (new, i, bool_vector_bitref (seq, nbits - i - 1));
1831 }
1832 else if (STRINGP (seq))
1833 {
1834 ptrdiff_t size = SCHARS (seq), bytes = SBYTES (seq);
1835
1836 if (size == bytes)
1837 {
1838 ptrdiff_t i;
1839
1840 new = make_uninit_string (size);
1841 for (i = 0; i < size; i++)
1842 SSET (new, i, SREF (seq, size - i - 1));
1843 }
1844 else
1845 {
1846 unsigned char *p, *q;
1847
1848 new = make_uninit_multibyte_string (size, bytes);
1849 p = SDATA (seq), q = SDATA (new) + bytes;
1850 while (q > SDATA (new))
1851 {
1852 int ch, len;
1853
1854 ch = STRING_CHAR_AND_LENGTH (p, len);
1855 p += len, q -= len;
1856 CHAR_STRING (ch, q);
1857 }
1858 }
1859 }
1860 else
1861 wrong_type_argument (Qsequencep, seq);
1862 return new;
1863 }
1864
1865 /* Sort LIST using PREDICATE, preserving original order of elements
1866 considered as equal. */
1867
1868 static Lisp_Object
1869 sort_list (Lisp_Object list, Lisp_Object predicate)
1870 {
1871 Lisp_Object front, back;
1872 register Lisp_Object len, tem;
1873 struct gcpro gcpro1, gcpro2;
1874 EMACS_INT length;
1875
1876 front = list;
1877 len = Flength (list);
1878 length = XINT (len);
1879 if (length < 2)
1880 return list;
1881
1882 XSETINT (len, (length / 2) - 1);
1883 tem = Fnthcdr (len, list);
1884 back = Fcdr (tem);
1885 Fsetcdr (tem, Qnil);
1886
1887 GCPRO2 (front, back);
1888 front = Fsort (front, predicate);
1889 back = Fsort (back, predicate);
1890 UNGCPRO;
1891 return merge (front, back, predicate);
1892 }
1893
1894 /* Using PRED to compare, return whether A and B are in order.
1895 Compare stably when A appeared before B in the input. */
1896 static bool
1897 inorder (Lisp_Object pred, Lisp_Object a, Lisp_Object b)
1898 {
1899 return NILP (call2 (pred, b, a));
1900 }
1901
1902 /* Using PRED to compare, merge from ALEN-length A and BLEN-length B
1903 into DEST. Argument arrays must be nonempty and must not overlap,
1904 except that B might be the last part of DEST. */
1905 static void
1906 merge_vectors (Lisp_Object pred,
1907 ptrdiff_t alen, Lisp_Object const a[restrict VLA_ELEMS (alen)],
1908 ptrdiff_t blen, Lisp_Object const b[VLA_ELEMS (blen)],
1909 Lisp_Object dest[VLA_ELEMS (alen + blen)])
1910 {
1911 eassume (0 < alen && 0 < blen);
1912 Lisp_Object const *alim = a + alen;
1913 Lisp_Object const *blim = b + blen;
1914
1915 while (true)
1916 {
1917 if (inorder (pred, a[0], b[0]))
1918 {
1919 *dest++ = *a++;
1920 if (a == alim)
1921 {
1922 if (dest != b)
1923 memcpy (dest, b, (blim - b) * sizeof *dest);
1924 return;
1925 }
1926 }
1927 else
1928 {
1929 *dest++ = *b++;
1930 if (b == blim)
1931 {
1932 memcpy (dest, a, (alim - a) * sizeof *dest);
1933 return;
1934 }
1935 }
1936 }
1937 }
1938
1939 /* Using PRED to compare, sort LEN-length VEC in place, using TMP for
1940 temporary storage. LEN must be at least 2. */
1941 static void
1942 sort_vector_inplace (Lisp_Object pred, ptrdiff_t len,
1943 Lisp_Object vec[restrict VLA_ELEMS (len)],
1944 Lisp_Object tmp[restrict VLA_ELEMS (len >> 1)])
1945 {
1946 eassume (2 <= len);
1947 ptrdiff_t halflen = len >> 1;
1948 sort_vector_copy (pred, halflen, vec, tmp);
1949 if (1 < len - halflen)
1950 sort_vector_inplace (pred, len - halflen, vec + halflen, vec);
1951 merge_vectors (pred, halflen, tmp, len - halflen, vec + halflen, vec);
1952 }
1953
1954 /* Using PRED to compare, sort from LEN-length SRC into DST.
1955 Len must be positive. */
1956 static void
1957 sort_vector_copy (Lisp_Object pred, ptrdiff_t len,
1958 Lisp_Object src[restrict VLA_ELEMS (len)],
1959 Lisp_Object dest[restrict VLA_ELEMS (len)])
1960 {
1961 eassume (0 < len);
1962 ptrdiff_t halflen = len >> 1;
1963 if (halflen < 1)
1964 dest[0] = src[0];
1965 else
1966 {
1967 if (1 < halflen)
1968 sort_vector_inplace (pred, halflen, src, dest);
1969 if (1 < len - halflen)
1970 sort_vector_inplace (pred, len - halflen, src + halflen, dest);
1971 merge_vectors (pred, halflen, src, len - halflen, src + halflen, dest);
1972 }
1973 }
1974
1975 /* Sort VECTOR in place using PREDICATE, preserving original order of
1976 elements considered as equal. */
1977
1978 static void
1979 sort_vector (Lisp_Object vector, Lisp_Object predicate)
1980 {
1981 ptrdiff_t len = ASIZE (vector);
1982 if (len < 2)
1983 return;
1984 ptrdiff_t halflen = len >> 1;
1985 Lisp_Object *tmp;
1986 struct gcpro gcpro1, gcpro2;
1987 GCPRO2 (vector, predicate);
1988 USE_SAFE_ALLOCA;
1989 SAFE_ALLOCA_LISP (tmp, halflen);
1990 for (ptrdiff_t i = 0; i < halflen; i++)
1991 tmp[i] = make_number (0);
1992 sort_vector_inplace (predicate, len, XVECTOR (vector)->contents, tmp);
1993 SAFE_FREE ();
1994 UNGCPRO;
1995 }
1996
1997 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
1998 doc: /* Sort SEQ, stably, comparing elements using PREDICATE.
1999 Returns the sorted sequence. SEQ should be a list or vector. SEQ is
2000 modified by side effects. PREDICATE is called with two elements of
2001 SEQ, and should return non-nil if the first element should sort before
2002 the second. */)
2003 (Lisp_Object seq, Lisp_Object predicate)
2004 {
2005 if (CONSP (seq))
2006 seq = sort_list (seq, predicate);
2007 else if (VECTORP (seq))
2008 sort_vector (seq, predicate);
2009 else if (!NILP (seq))
2010 wrong_type_argument (Qsequencep, seq);
2011 return seq;
2012 }
2013
2014 Lisp_Object
2015 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
2016 {
2017 Lisp_Object value;
2018 register Lisp_Object tail;
2019 Lisp_Object tem;
2020 register Lisp_Object l1, l2;
2021 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2022
2023 l1 = org_l1;
2024 l2 = org_l2;
2025 tail = Qnil;
2026 value = Qnil;
2027
2028 /* It is sufficient to protect org_l1 and org_l2.
2029 When l1 and l2 are updated, we copy the new values
2030 back into the org_ vars. */
2031 GCPRO4 (org_l1, org_l2, pred, value);
2032
2033 while (1)
2034 {
2035 if (NILP (l1))
2036 {
2037 UNGCPRO;
2038 if (NILP (tail))
2039 return l2;
2040 Fsetcdr (tail, l2);
2041 return value;
2042 }
2043 if (NILP (l2))
2044 {
2045 UNGCPRO;
2046 if (NILP (tail))
2047 return l1;
2048 Fsetcdr (tail, l1);
2049 return value;
2050 }
2051 if (inorder (pred, Fcar (l1), Fcar (l2)))
2052 {
2053 tem = l1;
2054 l1 = Fcdr (l1);
2055 org_l1 = l1;
2056 }
2057 else
2058 {
2059 tem = l2;
2060 l2 = Fcdr (l2);
2061 org_l2 = l2;
2062 }
2063 if (NILP (tail))
2064 value = tem;
2065 else
2066 Fsetcdr (tail, tem);
2067 tail = tem;
2068 }
2069 }
2070
2071 \f
2072 /* This does not check for quits. That is safe since it must terminate. */
2073
2074 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
2075 doc: /* Extract a value from a property list.
2076 PLIST is a property list, which is a list of the form
2077 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2078 corresponding to the given PROP, or nil if PROP is not one of the
2079 properties on the list. This function never signals an error. */)
2080 (Lisp_Object plist, Lisp_Object prop)
2081 {
2082 Lisp_Object tail, halftail;
2083
2084 /* halftail is used to detect circular lists. */
2085 tail = halftail = plist;
2086 while (CONSP (tail) && CONSP (XCDR (tail)))
2087 {
2088 if (EQ (prop, XCAR (tail)))
2089 return XCAR (XCDR (tail));
2090
2091 tail = XCDR (XCDR (tail));
2092 halftail = XCDR (halftail);
2093 if (EQ (tail, halftail))
2094 break;
2095 }
2096
2097 return Qnil;
2098 }
2099
2100 DEFUN ("get", Fget, Sget, 2, 2, 0,
2101 doc: /* Return the value of SYMBOL's PROPNAME property.
2102 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
2103 (Lisp_Object symbol, Lisp_Object propname)
2104 {
2105 CHECK_SYMBOL (symbol);
2106 return Fplist_get (XSYMBOL (symbol)->plist, propname);
2107 }
2108
2109 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
2110 doc: /* Change value in PLIST of PROP to VAL.
2111 PLIST is a property list, which is a list of the form
2112 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
2113 If PROP is already a property on the list, its value is set to VAL,
2114 otherwise the new PROP VAL pair is added. The new plist is returned;
2115 use `(setq x (plist-put x prop val))' to be sure to use the new value.
2116 The PLIST is modified by side effects. */)
2117 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
2118 {
2119 register Lisp_Object tail, prev;
2120 Lisp_Object newcell;
2121 prev = Qnil;
2122 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2123 tail = XCDR (XCDR (tail)))
2124 {
2125 if (EQ (prop, XCAR (tail)))
2126 {
2127 Fsetcar (XCDR (tail), val);
2128 return plist;
2129 }
2130
2131 prev = tail;
2132 QUIT;
2133 }
2134 newcell = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
2135 if (NILP (prev))
2136 return newcell;
2137 else
2138 Fsetcdr (XCDR (prev), newcell);
2139 return plist;
2140 }
2141
2142 DEFUN ("put", Fput, Sput, 3, 3, 0,
2143 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
2144 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
2145 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
2146 {
2147 CHECK_SYMBOL (symbol);
2148 set_symbol_plist
2149 (symbol, Fplist_put (XSYMBOL (symbol)->plist, propname, value));
2150 return value;
2151 }
2152 \f
2153 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
2154 doc: /* Extract a value from a property list, comparing with `equal'.
2155 PLIST is a property list, which is a list of the form
2156 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2157 corresponding to the given PROP, or nil if PROP is not
2158 one of the properties on the list. */)
2159 (Lisp_Object plist, Lisp_Object prop)
2160 {
2161 Lisp_Object tail;
2162
2163 for (tail = plist;
2164 CONSP (tail) && CONSP (XCDR (tail));
2165 tail = XCDR (XCDR (tail)))
2166 {
2167 if (! NILP (Fequal (prop, XCAR (tail))))
2168 return XCAR (XCDR (tail));
2169
2170 QUIT;
2171 }
2172
2173 CHECK_LIST_END (tail, prop);
2174
2175 return Qnil;
2176 }
2177
2178 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
2179 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
2180 PLIST is a property list, which is a list of the form
2181 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
2182 If PROP is already a property on the list, its value is set to VAL,
2183 otherwise the new PROP VAL pair is added. The new plist is returned;
2184 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
2185 The PLIST is modified by side effects. */)
2186 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
2187 {
2188 register Lisp_Object tail, prev;
2189 Lisp_Object newcell;
2190 prev = Qnil;
2191 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2192 tail = XCDR (XCDR (tail)))
2193 {
2194 if (! NILP (Fequal (prop, XCAR (tail))))
2195 {
2196 Fsetcar (XCDR (tail), val);
2197 return plist;
2198 }
2199
2200 prev = tail;
2201 QUIT;
2202 }
2203 newcell = list2 (prop, val);
2204 if (NILP (prev))
2205 return newcell;
2206 else
2207 Fsetcdr (XCDR (prev), newcell);
2208 return plist;
2209 }
2210 \f
2211 DEFUN ("eql", Feql, Seql, 2, 2, 0,
2212 doc: /* Return t if the two args are the same Lisp object.
2213 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
2214 (Lisp_Object obj1, Lisp_Object obj2)
2215 {
2216 if (FLOATP (obj1))
2217 return internal_equal (obj1, obj2, 0, 0, Qnil) ? Qt : Qnil;
2218 else
2219 return EQ (obj1, obj2) ? Qt : Qnil;
2220 }
2221
2222 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
2223 doc: /* Return t if two Lisp objects have similar structure and contents.
2224 They must have the same data type.
2225 Conses are compared by comparing the cars and the cdrs.
2226 Vectors and strings are compared element by element.
2227 Numbers are compared by value, but integers cannot equal floats.
2228 (Use `=' if you want integers and floats to be able to be equal.)
2229 Symbols must match exactly. */)
2230 (register Lisp_Object o1, Lisp_Object o2)
2231 {
2232 return internal_equal (o1, o2, 0, 0, Qnil) ? Qt : Qnil;
2233 }
2234
2235 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
2236 doc: /* Return t if two Lisp objects have similar structure and contents.
2237 This is like `equal' except that it compares the text properties
2238 of strings. (`equal' ignores text properties.) */)
2239 (register Lisp_Object o1, Lisp_Object o2)
2240 {
2241 return internal_equal (o1, o2, 0, 1, Qnil) ? Qt : Qnil;
2242 }
2243
2244 /* DEPTH is current depth of recursion. Signal an error if it
2245 gets too deep.
2246 PROPS means compare string text properties too. */
2247
2248 static bool
2249 internal_equal (Lisp_Object o1, Lisp_Object o2, int depth, bool props,
2250 Lisp_Object ht)
2251 {
2252 if (depth > 10)
2253 {
2254 if (depth > 200)
2255 error ("Stack overflow in equal");
2256 if (NILP (ht))
2257 {
2258 Lisp_Object args[2];
2259 args[0] = QCtest;
2260 args[1] = Qeq;
2261 ht = Fmake_hash_table (2, args);
2262 }
2263 switch (XTYPE (o1))
2264 {
2265 case Lisp_Cons: case Lisp_Misc: case Lisp_Vectorlike:
2266 {
2267 struct Lisp_Hash_Table *h = XHASH_TABLE (ht);
2268 EMACS_UINT hash;
2269 ptrdiff_t i = hash_lookup (h, o1, &hash);
2270 if (i >= 0)
2271 { /* `o1' was seen already. */
2272 Lisp_Object o2s = HASH_VALUE (h, i);
2273 if (!NILP (Fmemq (o2, o2s)))
2274 return 1;
2275 else
2276 set_hash_value_slot (h, i, Fcons (o2, o2s));
2277 }
2278 else
2279 hash_put (h, o1, Fcons (o2, Qnil), hash);
2280 }
2281 default: ;
2282 }
2283 }
2284
2285 tail_recurse:
2286 QUIT;
2287 if (EQ (o1, o2))
2288 return 1;
2289 if (XTYPE (o1) != XTYPE (o2))
2290 return 0;
2291
2292 switch (XTYPE (o1))
2293 {
2294 case Lisp_Float:
2295 {
2296 double d1, d2;
2297
2298 d1 = extract_float (o1);
2299 d2 = extract_float (o2);
2300 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2301 though they are not =. */
2302 return d1 == d2 || (d1 != d1 && d2 != d2);
2303 }
2304
2305 case Lisp_Cons:
2306 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1, props, ht))
2307 return 0;
2308 o1 = XCDR (o1);
2309 o2 = XCDR (o2);
2310 /* FIXME: This inf-loops in a circular list! */
2311 goto tail_recurse;
2312
2313 case Lisp_Misc:
2314 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2315 return 0;
2316 if (OVERLAYP (o1))
2317 {
2318 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2319 depth + 1, props, ht)
2320 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2321 depth + 1, props, ht))
2322 return 0;
2323 o1 = XOVERLAY (o1)->plist;
2324 o2 = XOVERLAY (o2)->plist;
2325 goto tail_recurse;
2326 }
2327 if (MARKERP (o1))
2328 {
2329 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2330 && (XMARKER (o1)->buffer == 0
2331 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2332 }
2333 break;
2334
2335 case Lisp_Vectorlike:
2336 {
2337 register int i;
2338 ptrdiff_t size = ASIZE (o1);
2339 /* Pseudovectors have the type encoded in the size field, so this test
2340 actually checks that the objects have the same type as well as the
2341 same size. */
2342 if (ASIZE (o2) != size)
2343 return 0;
2344 /* Boolvectors are compared much like strings. */
2345 if (BOOL_VECTOR_P (o1))
2346 {
2347 EMACS_INT size = bool_vector_size (o1);
2348 if (size != bool_vector_size (o2))
2349 return 0;
2350 if (memcmp (bool_vector_data (o1), bool_vector_data (o2),
2351 bool_vector_bytes (size)))
2352 return 0;
2353 return 1;
2354 }
2355 if (WINDOW_CONFIGURATIONP (o1))
2356 return compare_window_configurations (o1, o2, 0);
2357
2358 /* Aside from them, only true vectors, char-tables, compiled
2359 functions, and fonts (font-spec, font-entity, font-object)
2360 are sensible to compare, so eliminate the others now. */
2361 if (size & PSEUDOVECTOR_FLAG)
2362 {
2363 if (((size & PVEC_TYPE_MASK) >> PSEUDOVECTOR_AREA_BITS)
2364 < PVEC_COMPILED)
2365 return 0;
2366 size &= PSEUDOVECTOR_SIZE_MASK;
2367 }
2368 for (i = 0; i < size; i++)
2369 {
2370 Lisp_Object v1, v2;
2371 v1 = AREF (o1, i);
2372 v2 = AREF (o2, i);
2373 if (!internal_equal (v1, v2, depth + 1, props, ht))
2374 return 0;
2375 }
2376 return 1;
2377 }
2378 break;
2379
2380 case Lisp_String:
2381 if (SCHARS (o1) != SCHARS (o2))
2382 return 0;
2383 if (SBYTES (o1) != SBYTES (o2))
2384 return 0;
2385 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2386 return 0;
2387 if (props && !compare_string_intervals (o1, o2))
2388 return 0;
2389 return 1;
2390
2391 default:
2392 break;
2393 }
2394
2395 return 0;
2396 }
2397 \f
2398
2399 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2400 doc: /* Store each element of ARRAY with ITEM.
2401 ARRAY is a vector, string, char-table, or bool-vector. */)
2402 (Lisp_Object array, Lisp_Object item)
2403 {
2404 register ptrdiff_t size, idx;
2405
2406 if (VECTORP (array))
2407 for (idx = 0, size = ASIZE (array); idx < size; idx++)
2408 ASET (array, idx, item);
2409 else if (CHAR_TABLE_P (array))
2410 {
2411 int i;
2412
2413 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2414 set_char_table_contents (array, i, item);
2415 set_char_table_defalt (array, item);
2416 }
2417 else if (STRINGP (array))
2418 {
2419 register unsigned char *p = SDATA (array);
2420 int charval;
2421 CHECK_CHARACTER (item);
2422 charval = XFASTINT (item);
2423 size = SCHARS (array);
2424 if (STRING_MULTIBYTE (array))
2425 {
2426 unsigned char str[MAX_MULTIBYTE_LENGTH];
2427 int len = CHAR_STRING (charval, str);
2428 ptrdiff_t size_byte = SBYTES (array);
2429
2430 if (INT_MULTIPLY_OVERFLOW (SCHARS (array), len)
2431 || SCHARS (array) * len != size_byte)
2432 error ("Attempt to change byte length of a string");
2433 for (idx = 0; idx < size_byte; idx++)
2434 *p++ = str[idx % len];
2435 }
2436 else
2437 for (idx = 0; idx < size; idx++)
2438 p[idx] = charval;
2439 }
2440 else if (BOOL_VECTOR_P (array))
2441 return bool_vector_fill (array, item);
2442 else
2443 wrong_type_argument (Qarrayp, array);
2444 return array;
2445 }
2446
2447 DEFUN ("clear-string", Fclear_string, Sclear_string,
2448 1, 1, 0,
2449 doc: /* Clear the contents of STRING.
2450 This makes STRING unibyte and may change its length. */)
2451 (Lisp_Object string)
2452 {
2453 ptrdiff_t len;
2454 CHECK_STRING (string);
2455 len = SBYTES (string);
2456 memset (SDATA (string), 0, len);
2457 STRING_SET_CHARS (string, len);
2458 STRING_SET_UNIBYTE (string);
2459 return Qnil;
2460 }
2461 \f
2462 /* ARGSUSED */
2463 Lisp_Object
2464 nconc2 (Lisp_Object s1, Lisp_Object s2)
2465 {
2466 Lisp_Object args[2];
2467 args[0] = s1;
2468 args[1] = s2;
2469 return Fnconc (2, args);
2470 }
2471
2472 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2473 doc: /* Concatenate any number of lists by altering them.
2474 Only the last argument is not altered, and need not be a list.
2475 usage: (nconc &rest LISTS) */)
2476 (ptrdiff_t nargs, Lisp_Object *args)
2477 {
2478 ptrdiff_t argnum;
2479 register Lisp_Object tail, tem, val;
2480
2481 val = tail = Qnil;
2482
2483 for (argnum = 0; argnum < nargs; argnum++)
2484 {
2485 tem = args[argnum];
2486 if (NILP (tem)) continue;
2487
2488 if (NILP (val))
2489 val = tem;
2490
2491 if (argnum + 1 == nargs) break;
2492
2493 CHECK_LIST_CONS (tem, tem);
2494
2495 while (CONSP (tem))
2496 {
2497 tail = tem;
2498 tem = XCDR (tail);
2499 QUIT;
2500 }
2501
2502 tem = args[argnum + 1];
2503 Fsetcdr (tail, tem);
2504 if (NILP (tem))
2505 args[argnum + 1] = tail;
2506 }
2507
2508 return val;
2509 }
2510 \f
2511 /* This is the guts of all mapping functions.
2512 Apply FN to each element of SEQ, one by one,
2513 storing the results into elements of VALS, a C vector of Lisp_Objects.
2514 LENI is the length of VALS, which should also be the length of SEQ. */
2515
2516 static void
2517 mapcar1 (EMACS_INT leni, Lisp_Object *vals, Lisp_Object fn, Lisp_Object seq)
2518 {
2519 register Lisp_Object tail;
2520 Lisp_Object dummy;
2521 register EMACS_INT i;
2522 struct gcpro gcpro1, gcpro2, gcpro3;
2523
2524 if (vals)
2525 {
2526 /* Don't let vals contain any garbage when GC happens. */
2527 for (i = 0; i < leni; i++)
2528 vals[i] = Qnil;
2529
2530 GCPRO3 (dummy, fn, seq);
2531 gcpro1.var = vals;
2532 gcpro1.nvars = leni;
2533 }
2534 else
2535 GCPRO2 (fn, seq);
2536 /* We need not explicitly protect `tail' because it is used only on lists, and
2537 1) lists are not relocated and 2) the list is marked via `seq' so will not
2538 be freed */
2539
2540 if (VECTORP (seq) || COMPILEDP (seq))
2541 {
2542 for (i = 0; i < leni; i++)
2543 {
2544 dummy = call1 (fn, AREF (seq, i));
2545 if (vals)
2546 vals[i] = dummy;
2547 }
2548 }
2549 else if (BOOL_VECTOR_P (seq))
2550 {
2551 for (i = 0; i < leni; i++)
2552 {
2553 dummy = call1 (fn, bool_vector_ref (seq, i));
2554 if (vals)
2555 vals[i] = dummy;
2556 }
2557 }
2558 else if (STRINGP (seq))
2559 {
2560 ptrdiff_t i_byte;
2561
2562 for (i = 0, i_byte = 0; i < leni;)
2563 {
2564 int c;
2565 ptrdiff_t i_before = i;
2566
2567 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2568 XSETFASTINT (dummy, c);
2569 dummy = call1 (fn, dummy);
2570 if (vals)
2571 vals[i_before] = dummy;
2572 }
2573 }
2574 else /* Must be a list, since Flength did not get an error */
2575 {
2576 tail = seq;
2577 for (i = 0; i < leni && CONSP (tail); i++)
2578 {
2579 dummy = call1 (fn, XCAR (tail));
2580 if (vals)
2581 vals[i] = dummy;
2582 tail = XCDR (tail);
2583 }
2584 }
2585
2586 UNGCPRO;
2587 }
2588
2589 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2590 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2591 In between each pair of results, stick in SEPARATOR. Thus, " " as
2592 SEPARATOR results in spaces between the values returned by FUNCTION.
2593 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2594 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2595 {
2596 Lisp_Object len;
2597 register EMACS_INT leni;
2598 EMACS_INT nargs;
2599 ptrdiff_t i;
2600 register Lisp_Object *args;
2601 struct gcpro gcpro1;
2602 Lisp_Object ret;
2603 USE_SAFE_ALLOCA;
2604
2605 len = Flength (sequence);
2606 if (CHAR_TABLE_P (sequence))
2607 wrong_type_argument (Qlistp, sequence);
2608 leni = XINT (len);
2609 nargs = leni + leni - 1;
2610 if (nargs < 0) return empty_unibyte_string;
2611
2612 SAFE_ALLOCA_LISP (args, nargs);
2613
2614 GCPRO1 (separator);
2615 mapcar1 (leni, args, function, sequence);
2616 UNGCPRO;
2617
2618 for (i = leni - 1; i > 0; i--)
2619 args[i + i] = args[i];
2620
2621 for (i = 1; i < nargs; i += 2)
2622 args[i] = separator;
2623
2624 ret = Fconcat (nargs, args);
2625 SAFE_FREE ();
2626
2627 return ret;
2628 }
2629
2630 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2631 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2632 The result is a list just as long as SEQUENCE.
2633 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2634 (Lisp_Object function, Lisp_Object sequence)
2635 {
2636 register Lisp_Object len;
2637 register EMACS_INT leni;
2638 register Lisp_Object *args;
2639 Lisp_Object ret;
2640 USE_SAFE_ALLOCA;
2641
2642 len = Flength (sequence);
2643 if (CHAR_TABLE_P (sequence))
2644 wrong_type_argument (Qlistp, sequence);
2645 leni = XFASTINT (len);
2646
2647 SAFE_ALLOCA_LISP (args, leni);
2648
2649 mapcar1 (leni, args, function, sequence);
2650
2651 ret = Flist (leni, args);
2652 SAFE_FREE ();
2653
2654 return ret;
2655 }
2656
2657 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2658 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2659 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2660 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2661 (Lisp_Object function, Lisp_Object sequence)
2662 {
2663 register EMACS_INT leni;
2664
2665 leni = XFASTINT (Flength (sequence));
2666 if (CHAR_TABLE_P (sequence))
2667 wrong_type_argument (Qlistp, sequence);
2668 mapcar1 (leni, 0, function, sequence);
2669
2670 return sequence;
2671 }
2672 \f
2673 /* This is how C code calls `yes-or-no-p' and allows the user
2674 to redefined it.
2675
2676 Anything that calls this function must protect from GC! */
2677
2678 Lisp_Object
2679 do_yes_or_no_p (Lisp_Object prompt)
2680 {
2681 return call1 (intern ("yes-or-no-p"), prompt);
2682 }
2683
2684 /* Anything that calls this function must protect from GC! */
2685
2686 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2687 doc: /* Ask user a yes-or-no question.
2688 Return t if answer is yes, and nil if the answer is no.
2689 PROMPT is the string to display to ask the question. It should end in
2690 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2691
2692 The user must confirm the answer with RET, and can edit it until it
2693 has been confirmed.
2694
2695 If dialog boxes are supported, a dialog box will be used
2696 if `last-nonmenu-event' is nil, and `use-dialog-box' is non-nil. */)
2697 (Lisp_Object prompt)
2698 {
2699 Lisp_Object ans;
2700 struct gcpro gcpro1;
2701
2702 CHECK_STRING (prompt);
2703
2704 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2705 && use_dialog_box)
2706 {
2707 Lisp_Object pane, menu, obj;
2708 redisplay_preserve_echo_area (4);
2709 pane = list2 (Fcons (build_string ("Yes"), Qt),
2710 Fcons (build_string ("No"), Qnil));
2711 GCPRO1 (pane);
2712 menu = Fcons (prompt, pane);
2713 obj = Fx_popup_dialog (Qt, menu, Qnil);
2714 UNGCPRO;
2715 return obj;
2716 }
2717
2718 AUTO_STRING (yes_or_no, "(yes or no) ");
2719 prompt = Fconcat (2, (Lisp_Object []) {prompt, yes_or_no});
2720 GCPRO1 (prompt);
2721
2722 while (1)
2723 {
2724 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2725 Qyes_or_no_p_history, Qnil,
2726 Qnil));
2727 if (SCHARS (ans) == 3 && !strcmp (SSDATA (ans), "yes"))
2728 {
2729 UNGCPRO;
2730 return Qt;
2731 }
2732 if (SCHARS (ans) == 2 && !strcmp (SSDATA (ans), "no"))
2733 {
2734 UNGCPRO;
2735 return Qnil;
2736 }
2737
2738 Fding (Qnil);
2739 Fdiscard_input ();
2740 message1 ("Please answer yes or no.");
2741 Fsleep_for (make_number (2), Qnil);
2742 }
2743 }
2744 \f
2745 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2746 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2747
2748 Each of the three load averages is multiplied by 100, then converted
2749 to integer.
2750
2751 When USE-FLOATS is non-nil, floats will be used instead of integers.
2752 These floats are not multiplied by 100.
2753
2754 If the 5-minute or 15-minute load averages are not available, return a
2755 shortened list, containing only those averages which are available.
2756
2757 An error is thrown if the load average can't be obtained. In some
2758 cases making it work would require Emacs being installed setuid or
2759 setgid so that it can read kernel information, and that usually isn't
2760 advisable. */)
2761 (Lisp_Object use_floats)
2762 {
2763 double load_ave[3];
2764 int loads = getloadavg (load_ave, 3);
2765 Lisp_Object ret = Qnil;
2766
2767 if (loads < 0)
2768 error ("load-average not implemented for this operating system");
2769
2770 while (loads-- > 0)
2771 {
2772 Lisp_Object load = (NILP (use_floats)
2773 ? make_number (100.0 * load_ave[loads])
2774 : make_float (load_ave[loads]));
2775 ret = Fcons (load, ret);
2776 }
2777
2778 return ret;
2779 }
2780 \f
2781 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2782 doc: /* Return t if FEATURE is present in this Emacs.
2783
2784 Use this to conditionalize execution of lisp code based on the
2785 presence or absence of Emacs or environment extensions.
2786 Use `provide' to declare that a feature is available. This function
2787 looks at the value of the variable `features'. The optional argument
2788 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2789 (Lisp_Object feature, Lisp_Object subfeature)
2790 {
2791 register Lisp_Object tem;
2792 CHECK_SYMBOL (feature);
2793 tem = Fmemq (feature, Vfeatures);
2794 if (!NILP (tem) && !NILP (subfeature))
2795 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2796 return (NILP (tem)) ? Qnil : Qt;
2797 }
2798
2799 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2800 doc: /* Announce that FEATURE is a feature of the current Emacs.
2801 The optional argument SUBFEATURES should be a list of symbols listing
2802 particular subfeatures supported in this version of FEATURE. */)
2803 (Lisp_Object feature, Lisp_Object subfeatures)
2804 {
2805 register Lisp_Object tem;
2806 CHECK_SYMBOL (feature);
2807 CHECK_LIST (subfeatures);
2808 if (!NILP (Vautoload_queue))
2809 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2810 Vautoload_queue);
2811 tem = Fmemq (feature, Vfeatures);
2812 if (NILP (tem))
2813 Vfeatures = Fcons (feature, Vfeatures);
2814 if (!NILP (subfeatures))
2815 Fput (feature, Qsubfeatures, subfeatures);
2816 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2817
2818 /* Run any load-hooks for this file. */
2819 tem = Fassq (feature, Vafter_load_alist);
2820 if (CONSP (tem))
2821 Fmapc (Qfuncall, XCDR (tem));
2822
2823 return feature;
2824 }
2825 \f
2826 /* `require' and its subroutines. */
2827
2828 /* List of features currently being require'd, innermost first. */
2829
2830 static Lisp_Object require_nesting_list;
2831
2832 static void
2833 require_unwind (Lisp_Object old_value)
2834 {
2835 require_nesting_list = old_value;
2836 }
2837
2838 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2839 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2840 If FEATURE is not a member of the list `features', then the feature
2841 is not loaded; so load the file FILENAME.
2842 If FILENAME is omitted, the printname of FEATURE is used as the file name,
2843 and `load' will try to load this name appended with the suffix `.elc' or
2844 `.el', in that order. The name without appended suffix will not be used.
2845 See `get-load-suffixes' for the complete list of suffixes.
2846 If the optional third argument NOERROR is non-nil,
2847 then return nil if the file is not found instead of signaling an error.
2848 Normally the return value is FEATURE.
2849 The normal messages at start and end of loading FILENAME are suppressed. */)
2850 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2851 {
2852 Lisp_Object tem;
2853 struct gcpro gcpro1, gcpro2;
2854 bool from_file = load_in_progress;
2855
2856 CHECK_SYMBOL (feature);
2857
2858 /* Record the presence of `require' in this file
2859 even if the feature specified is already loaded.
2860 But not more than once in any file,
2861 and not when we aren't loading or reading from a file. */
2862 if (!from_file)
2863 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2864 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2865 from_file = 1;
2866
2867 if (from_file)
2868 {
2869 tem = Fcons (Qrequire, feature);
2870 if (NILP (Fmember (tem, Vcurrent_load_list)))
2871 LOADHIST_ATTACH (tem);
2872 }
2873 tem = Fmemq (feature, Vfeatures);
2874
2875 if (NILP (tem))
2876 {
2877 ptrdiff_t count = SPECPDL_INDEX ();
2878 int nesting = 0;
2879
2880 /* This is to make sure that loadup.el gives a clear picture
2881 of what files are preloaded and when. */
2882 if (! NILP (Vpurify_flag))
2883 error ("(require %s) while preparing to dump",
2884 SDATA (SYMBOL_NAME (feature)));
2885
2886 /* A certain amount of recursive `require' is legitimate,
2887 but if we require the same feature recursively 3 times,
2888 signal an error. */
2889 tem = require_nesting_list;
2890 while (! NILP (tem))
2891 {
2892 if (! NILP (Fequal (feature, XCAR (tem))))
2893 nesting++;
2894 tem = XCDR (tem);
2895 }
2896 if (nesting > 3)
2897 error ("Recursive `require' for feature `%s'",
2898 SDATA (SYMBOL_NAME (feature)));
2899
2900 /* Update the list for any nested `require's that occur. */
2901 record_unwind_protect (require_unwind, require_nesting_list);
2902 require_nesting_list = Fcons (feature, require_nesting_list);
2903
2904 /* Value saved here is to be restored into Vautoload_queue */
2905 record_unwind_protect (un_autoload, Vautoload_queue);
2906 Vautoload_queue = Qt;
2907
2908 /* Load the file. */
2909 GCPRO2 (feature, filename);
2910 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2911 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2912 UNGCPRO;
2913
2914 /* If load failed entirely, return nil. */
2915 if (NILP (tem))
2916 return unbind_to (count, Qnil);
2917
2918 tem = Fmemq (feature, Vfeatures);
2919 if (NILP (tem))
2920 error ("Required feature `%s' was not provided",
2921 SDATA (SYMBOL_NAME (feature)));
2922
2923 /* Once loading finishes, don't undo it. */
2924 Vautoload_queue = Qt;
2925 feature = unbind_to (count, feature);
2926 }
2927
2928 return feature;
2929 }
2930 \f
2931 /* Primitives for work of the "widget" library.
2932 In an ideal world, this section would not have been necessary.
2933 However, lisp function calls being as slow as they are, it turns
2934 out that some functions in the widget library (wid-edit.el) are the
2935 bottleneck of Widget operation. Here is their translation to C,
2936 for the sole reason of efficiency. */
2937
2938 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2939 doc: /* Return non-nil if PLIST has the property PROP.
2940 PLIST is a property list, which is a list of the form
2941 \(PROP1 VALUE1 PROP2 VALUE2 ...\). PROP is a symbol.
2942 Unlike `plist-get', this allows you to distinguish between a missing
2943 property and a property with the value nil.
2944 The value is actually the tail of PLIST whose car is PROP. */)
2945 (Lisp_Object plist, Lisp_Object prop)
2946 {
2947 while (CONSP (plist) && !EQ (XCAR (plist), prop))
2948 {
2949 QUIT;
2950 plist = XCDR (plist);
2951 plist = CDR (plist);
2952 }
2953 return plist;
2954 }
2955
2956 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2957 doc: /* In WIDGET, set PROPERTY to VALUE.
2958 The value can later be retrieved with `widget-get'. */)
2959 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2960 {
2961 CHECK_CONS (widget);
2962 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
2963 return value;
2964 }
2965
2966 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
2967 doc: /* In WIDGET, get the value of PROPERTY.
2968 The value could either be specified when the widget was created, or
2969 later with `widget-put'. */)
2970 (Lisp_Object widget, Lisp_Object property)
2971 {
2972 Lisp_Object tmp;
2973
2974 while (1)
2975 {
2976 if (NILP (widget))
2977 return Qnil;
2978 CHECK_CONS (widget);
2979 tmp = Fplist_member (XCDR (widget), property);
2980 if (CONSP (tmp))
2981 {
2982 tmp = XCDR (tmp);
2983 return CAR (tmp);
2984 }
2985 tmp = XCAR (widget);
2986 if (NILP (tmp))
2987 return Qnil;
2988 widget = Fget (tmp, Qwidget_type);
2989 }
2990 }
2991
2992 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
2993 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2994 ARGS are passed as extra arguments to the function.
2995 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2996 (ptrdiff_t nargs, Lisp_Object *args)
2997 {
2998 /* This function can GC. */
2999 Lisp_Object newargs[3];
3000 struct gcpro gcpro1, gcpro2;
3001 Lisp_Object result;
3002
3003 newargs[0] = Fwidget_get (args[0], args[1]);
3004 newargs[1] = args[0];
3005 newargs[2] = Flist (nargs - 2, args + 2);
3006 GCPRO2 (newargs[0], newargs[2]);
3007 result = Fapply (3, newargs);
3008 UNGCPRO;
3009 return result;
3010 }
3011
3012 #ifdef HAVE_LANGINFO_CODESET
3013 #include <langinfo.h>
3014 #endif
3015
3016 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
3017 doc: /* Access locale data ITEM for the current C locale, if available.
3018 ITEM should be one of the following:
3019
3020 `codeset', returning the character set as a string (locale item CODESET);
3021
3022 `days', returning a 7-element vector of day names (locale items DAY_n);
3023
3024 `months', returning a 12-element vector of month names (locale items MON_n);
3025
3026 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
3027 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
3028
3029 If the system can't provide such information through a call to
3030 `nl_langinfo', or if ITEM isn't from the list above, return nil.
3031
3032 See also Info node `(libc)Locales'.
3033
3034 The data read from the system are decoded using `locale-coding-system'. */)
3035 (Lisp_Object item)
3036 {
3037 char *str = NULL;
3038 #ifdef HAVE_LANGINFO_CODESET
3039 Lisp_Object val;
3040 if (EQ (item, Qcodeset))
3041 {
3042 str = nl_langinfo (CODESET);
3043 return build_string (str);
3044 }
3045 #ifdef DAY_1
3046 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
3047 {
3048 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
3049 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
3050 int i;
3051 struct gcpro gcpro1;
3052 GCPRO1 (v);
3053 synchronize_system_time_locale ();
3054 for (i = 0; i < 7; i++)
3055 {
3056 str = nl_langinfo (days[i]);
3057 val = build_unibyte_string (str);
3058 /* Fixme: Is this coding system necessarily right, even if
3059 it is consistent with CODESET? If not, what to do? */
3060 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
3061 0));
3062 }
3063 UNGCPRO;
3064 return v;
3065 }
3066 #endif /* DAY_1 */
3067 #ifdef MON_1
3068 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
3069 {
3070 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
3071 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
3072 MON_8, MON_9, MON_10, MON_11, MON_12};
3073 int i;
3074 struct gcpro gcpro1;
3075 GCPRO1 (v);
3076 synchronize_system_time_locale ();
3077 for (i = 0; i < 12; i++)
3078 {
3079 str = nl_langinfo (months[i]);
3080 val = build_unibyte_string (str);
3081 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
3082 0));
3083 }
3084 UNGCPRO;
3085 return v;
3086 }
3087 #endif /* MON_1 */
3088 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
3089 but is in the locale files. This could be used by ps-print. */
3090 #ifdef PAPER_WIDTH
3091 else if (EQ (item, Qpaper))
3092 return list2i (nl_langinfo (PAPER_WIDTH), nl_langinfo (PAPER_HEIGHT));
3093 #endif /* PAPER_WIDTH */
3094 #endif /* HAVE_LANGINFO_CODESET*/
3095 return Qnil;
3096 }
3097 \f
3098 /* base64 encode/decode functions (RFC 2045).
3099 Based on code from GNU recode. */
3100
3101 #define MIME_LINE_LENGTH 76
3102
3103 #define IS_ASCII(Character) \
3104 ((Character) < 128)
3105 #define IS_BASE64(Character) \
3106 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
3107 #define IS_BASE64_IGNORABLE(Character) \
3108 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
3109 || (Character) == '\f' || (Character) == '\r')
3110
3111 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
3112 character or return retval if there are no characters left to
3113 process. */
3114 #define READ_QUADRUPLET_BYTE(retval) \
3115 do \
3116 { \
3117 if (i == length) \
3118 { \
3119 if (nchars_return) \
3120 *nchars_return = nchars; \
3121 return (retval); \
3122 } \
3123 c = from[i++]; \
3124 } \
3125 while (IS_BASE64_IGNORABLE (c))
3126
3127 /* Table of characters coding the 64 values. */
3128 static const char base64_value_to_char[64] =
3129 {
3130 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
3131 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
3132 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
3133 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
3134 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
3135 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
3136 '8', '9', '+', '/' /* 60-63 */
3137 };
3138
3139 /* Table of base64 values for first 128 characters. */
3140 static const short base64_char_to_value[128] =
3141 {
3142 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
3143 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
3144 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
3145 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
3146 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
3147 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
3148 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
3149 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
3150 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
3151 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
3152 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
3153 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
3154 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
3155 };
3156
3157 /* The following diagram shows the logical steps by which three octets
3158 get transformed into four base64 characters.
3159
3160 .--------. .--------. .--------.
3161 |aaaaaabb| |bbbbcccc| |ccdddddd|
3162 `--------' `--------' `--------'
3163 6 2 4 4 2 6
3164 .--------+--------+--------+--------.
3165 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
3166 `--------+--------+--------+--------'
3167
3168 .--------+--------+--------+--------.
3169 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
3170 `--------+--------+--------+--------'
3171
3172 The octets are divided into 6 bit chunks, which are then encoded into
3173 base64 characters. */
3174
3175
3176 static ptrdiff_t base64_encode_1 (const char *, char *, ptrdiff_t, bool, bool);
3177 static ptrdiff_t base64_decode_1 (const char *, char *, ptrdiff_t, bool,
3178 ptrdiff_t *);
3179
3180 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
3181 2, 3, "r",
3182 doc: /* Base64-encode the region between BEG and END.
3183 Return the length of the encoded text.
3184 Optional third argument NO-LINE-BREAK means do not break long lines
3185 into shorter lines. */)
3186 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
3187 {
3188 char *encoded;
3189 ptrdiff_t allength, length;
3190 ptrdiff_t ibeg, iend, encoded_length;
3191 ptrdiff_t old_pos = PT;
3192 USE_SAFE_ALLOCA;
3193
3194 validate_region (&beg, &end);
3195
3196 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3197 iend = CHAR_TO_BYTE (XFASTINT (end));
3198 move_gap_both (XFASTINT (beg), ibeg);
3199
3200 /* We need to allocate enough room for encoding the text.
3201 We need 33 1/3% more space, plus a newline every 76
3202 characters, and then we round up. */
3203 length = iend - ibeg;
3204 allength = length + length/3 + 1;
3205 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3206
3207 encoded = SAFE_ALLOCA (allength);
3208 encoded_length = base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg),
3209 encoded, length, NILP (no_line_break),
3210 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
3211 if (encoded_length > allength)
3212 emacs_abort ();
3213
3214 if (encoded_length < 0)
3215 {
3216 /* The encoding wasn't possible. */
3217 SAFE_FREE ();
3218 error ("Multibyte character in data for base64 encoding");
3219 }
3220
3221 /* Now we have encoded the region, so we insert the new contents
3222 and delete the old. (Insert first in order to preserve markers.) */
3223 SET_PT_BOTH (XFASTINT (beg), ibeg);
3224 insert (encoded, encoded_length);
3225 SAFE_FREE ();
3226 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
3227
3228 /* If point was outside of the region, restore it exactly; else just
3229 move to the beginning of the region. */
3230 if (old_pos >= XFASTINT (end))
3231 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
3232 else if (old_pos > XFASTINT (beg))
3233 old_pos = XFASTINT (beg);
3234 SET_PT (old_pos);
3235
3236 /* We return the length of the encoded text. */
3237 return make_number (encoded_length);
3238 }
3239
3240 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
3241 1, 2, 0,
3242 doc: /* Base64-encode STRING and return the result.
3243 Optional second argument NO-LINE-BREAK means do not break long lines
3244 into shorter lines. */)
3245 (Lisp_Object string, Lisp_Object no_line_break)
3246 {
3247 ptrdiff_t allength, length, encoded_length;
3248 char *encoded;
3249 Lisp_Object encoded_string;
3250 USE_SAFE_ALLOCA;
3251
3252 CHECK_STRING (string);
3253
3254 /* We need to allocate enough room for encoding the text.
3255 We need 33 1/3% more space, plus a newline every 76
3256 characters, and then we round up. */
3257 length = SBYTES (string);
3258 allength = length + length/3 + 1;
3259 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3260
3261 /* We need to allocate enough room for decoding the text. */
3262 encoded = SAFE_ALLOCA (allength);
3263
3264 encoded_length = base64_encode_1 (SSDATA (string),
3265 encoded, length, NILP (no_line_break),
3266 STRING_MULTIBYTE (string));
3267 if (encoded_length > allength)
3268 emacs_abort ();
3269
3270 if (encoded_length < 0)
3271 {
3272 /* The encoding wasn't possible. */
3273 error ("Multibyte character in data for base64 encoding");
3274 }
3275
3276 encoded_string = make_unibyte_string (encoded, encoded_length);
3277 SAFE_FREE ();
3278
3279 return encoded_string;
3280 }
3281
3282 static ptrdiff_t
3283 base64_encode_1 (const char *from, char *to, ptrdiff_t length,
3284 bool line_break, bool multibyte)
3285 {
3286 int counter = 0;
3287 ptrdiff_t i = 0;
3288 char *e = to;
3289 int c;
3290 unsigned int value;
3291 int bytes;
3292
3293 while (i < length)
3294 {
3295 if (multibyte)
3296 {
3297 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3298 if (CHAR_BYTE8_P (c))
3299 c = CHAR_TO_BYTE8 (c);
3300 else if (c >= 256)
3301 return -1;
3302 i += bytes;
3303 }
3304 else
3305 c = from[i++];
3306
3307 /* Wrap line every 76 characters. */
3308
3309 if (line_break)
3310 {
3311 if (counter < MIME_LINE_LENGTH / 4)
3312 counter++;
3313 else
3314 {
3315 *e++ = '\n';
3316 counter = 1;
3317 }
3318 }
3319
3320 /* Process first byte of a triplet. */
3321
3322 *e++ = base64_value_to_char[0x3f & c >> 2];
3323 value = (0x03 & c) << 4;
3324
3325 /* Process second byte of a triplet. */
3326
3327 if (i == length)
3328 {
3329 *e++ = base64_value_to_char[value];
3330 *e++ = '=';
3331 *e++ = '=';
3332 break;
3333 }
3334
3335 if (multibyte)
3336 {
3337 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3338 if (CHAR_BYTE8_P (c))
3339 c = CHAR_TO_BYTE8 (c);
3340 else if (c >= 256)
3341 return -1;
3342 i += bytes;
3343 }
3344 else
3345 c = from[i++];
3346
3347 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3348 value = (0x0f & c) << 2;
3349
3350 /* Process third byte of a triplet. */
3351
3352 if (i == length)
3353 {
3354 *e++ = base64_value_to_char[value];
3355 *e++ = '=';
3356 break;
3357 }
3358
3359 if (multibyte)
3360 {
3361 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3362 if (CHAR_BYTE8_P (c))
3363 c = CHAR_TO_BYTE8 (c);
3364 else if (c >= 256)
3365 return -1;
3366 i += bytes;
3367 }
3368 else
3369 c = from[i++];
3370
3371 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3372 *e++ = base64_value_to_char[0x3f & c];
3373 }
3374
3375 return e - to;
3376 }
3377
3378
3379 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3380 2, 2, "r",
3381 doc: /* Base64-decode the region between BEG and END.
3382 Return the length of the decoded text.
3383 If the region can't be decoded, signal an error and don't modify the buffer. */)
3384 (Lisp_Object beg, Lisp_Object end)
3385 {
3386 ptrdiff_t ibeg, iend, length, allength;
3387 char *decoded;
3388 ptrdiff_t old_pos = PT;
3389 ptrdiff_t decoded_length;
3390 ptrdiff_t inserted_chars;
3391 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3392 USE_SAFE_ALLOCA;
3393
3394 validate_region (&beg, &end);
3395
3396 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3397 iend = CHAR_TO_BYTE (XFASTINT (end));
3398
3399 length = iend - ibeg;
3400
3401 /* We need to allocate enough room for decoding the text. If we are
3402 working on a multibyte buffer, each decoded code may occupy at
3403 most two bytes. */
3404 allength = multibyte ? length * 2 : length;
3405 decoded = SAFE_ALLOCA (allength);
3406
3407 move_gap_both (XFASTINT (beg), ibeg);
3408 decoded_length = base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg),
3409 decoded, length,
3410 multibyte, &inserted_chars);
3411 if (decoded_length > allength)
3412 emacs_abort ();
3413
3414 if (decoded_length < 0)
3415 {
3416 /* The decoding wasn't possible. */
3417 error ("Invalid base64 data");
3418 }
3419
3420 /* Now we have decoded the region, so we insert the new contents
3421 and delete the old. (Insert first in order to preserve markers.) */
3422 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3423 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3424 SAFE_FREE ();
3425
3426 /* Delete the original text. */
3427 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3428 iend + decoded_length, 1);
3429
3430 /* If point was outside of the region, restore it exactly; else just
3431 move to the beginning of the region. */
3432 if (old_pos >= XFASTINT (end))
3433 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3434 else if (old_pos > XFASTINT (beg))
3435 old_pos = XFASTINT (beg);
3436 SET_PT (old_pos > ZV ? ZV : old_pos);
3437
3438 return make_number (inserted_chars);
3439 }
3440
3441 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3442 1, 1, 0,
3443 doc: /* Base64-decode STRING and return the result. */)
3444 (Lisp_Object string)
3445 {
3446 char *decoded;
3447 ptrdiff_t length, decoded_length;
3448 Lisp_Object decoded_string;
3449 USE_SAFE_ALLOCA;
3450
3451 CHECK_STRING (string);
3452
3453 length = SBYTES (string);
3454 /* We need to allocate enough room for decoding the text. */
3455 decoded = SAFE_ALLOCA (length);
3456
3457 /* The decoded result should be unibyte. */
3458 decoded_length = base64_decode_1 (SSDATA (string), decoded, length,
3459 0, NULL);
3460 if (decoded_length > length)
3461 emacs_abort ();
3462 else if (decoded_length >= 0)
3463 decoded_string = make_unibyte_string (decoded, decoded_length);
3464 else
3465 decoded_string = Qnil;
3466
3467 SAFE_FREE ();
3468 if (!STRINGP (decoded_string))
3469 error ("Invalid base64 data");
3470
3471 return decoded_string;
3472 }
3473
3474 /* Base64-decode the data at FROM of LENGTH bytes into TO. If
3475 MULTIBYTE, the decoded result should be in multibyte
3476 form. If NCHARS_RETURN is not NULL, store the number of produced
3477 characters in *NCHARS_RETURN. */
3478
3479 static ptrdiff_t
3480 base64_decode_1 (const char *from, char *to, ptrdiff_t length,
3481 bool multibyte, ptrdiff_t *nchars_return)
3482 {
3483 ptrdiff_t i = 0; /* Used inside READ_QUADRUPLET_BYTE */
3484 char *e = to;
3485 unsigned char c;
3486 unsigned long value;
3487 ptrdiff_t nchars = 0;
3488
3489 while (1)
3490 {
3491 /* Process first byte of a quadruplet. */
3492
3493 READ_QUADRUPLET_BYTE (e-to);
3494
3495 if (!IS_BASE64 (c))
3496 return -1;
3497 value = base64_char_to_value[c] << 18;
3498
3499 /* Process second byte of a quadruplet. */
3500
3501 READ_QUADRUPLET_BYTE (-1);
3502
3503 if (!IS_BASE64 (c))
3504 return -1;
3505 value |= base64_char_to_value[c] << 12;
3506
3507 c = (unsigned char) (value >> 16);
3508 if (multibyte && c >= 128)
3509 e += BYTE8_STRING (c, e);
3510 else
3511 *e++ = c;
3512 nchars++;
3513
3514 /* Process third byte of a quadruplet. */
3515
3516 READ_QUADRUPLET_BYTE (-1);
3517
3518 if (c == '=')
3519 {
3520 READ_QUADRUPLET_BYTE (-1);
3521
3522 if (c != '=')
3523 return -1;
3524 continue;
3525 }
3526
3527 if (!IS_BASE64 (c))
3528 return -1;
3529 value |= base64_char_to_value[c] << 6;
3530
3531 c = (unsigned char) (0xff & value >> 8);
3532 if (multibyte && c >= 128)
3533 e += BYTE8_STRING (c, e);
3534 else
3535 *e++ = c;
3536 nchars++;
3537
3538 /* Process fourth byte of a quadruplet. */
3539
3540 READ_QUADRUPLET_BYTE (-1);
3541
3542 if (c == '=')
3543 continue;
3544
3545 if (!IS_BASE64 (c))
3546 return -1;
3547 value |= base64_char_to_value[c];
3548
3549 c = (unsigned char) (0xff & value);
3550 if (multibyte && c >= 128)
3551 e += BYTE8_STRING (c, e);
3552 else
3553 *e++ = c;
3554 nchars++;
3555 }
3556 }
3557
3558
3559 \f
3560 /***********************************************************************
3561 ***** *****
3562 ***** Hash Tables *****
3563 ***** *****
3564 ***********************************************************************/
3565
3566 /* Implemented by gerd@gnu.org. This hash table implementation was
3567 inspired by CMUCL hash tables. */
3568
3569 /* Ideas:
3570
3571 1. For small tables, association lists are probably faster than
3572 hash tables because they have lower overhead.
3573
3574 For uses of hash tables where the O(1) behavior of table
3575 operations is not a requirement, it might therefore be a good idea
3576 not to hash. Instead, we could just do a linear search in the
3577 key_and_value vector of the hash table. This could be done
3578 if a `:linear-search t' argument is given to make-hash-table. */
3579
3580
3581 /* The list of all weak hash tables. Don't staticpro this one. */
3582
3583 static struct Lisp_Hash_Table *weak_hash_tables;
3584
3585 \f
3586 /***********************************************************************
3587 Utilities
3588 ***********************************************************************/
3589
3590 static void
3591 CHECK_HASH_TABLE (Lisp_Object x)
3592 {
3593 CHECK_TYPE (HASH_TABLE_P (x), Qhash_table_p, x);
3594 }
3595
3596 static void
3597 set_hash_key_and_value (struct Lisp_Hash_Table *h, Lisp_Object key_and_value)
3598 {
3599 h->key_and_value = key_and_value;
3600 }
3601 static void
3602 set_hash_next (struct Lisp_Hash_Table *h, Lisp_Object next)
3603 {
3604 h->next = next;
3605 }
3606 static void
3607 set_hash_next_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3608 {
3609 gc_aset (h->next, idx, val);
3610 }
3611 static void
3612 set_hash_hash (struct Lisp_Hash_Table *h, Lisp_Object hash)
3613 {
3614 h->hash = hash;
3615 }
3616 static void
3617 set_hash_hash_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3618 {
3619 gc_aset (h->hash, idx, val);
3620 }
3621 static void
3622 set_hash_index (struct Lisp_Hash_Table *h, Lisp_Object index)
3623 {
3624 h->index = index;
3625 }
3626 static void
3627 set_hash_index_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3628 {
3629 gc_aset (h->index, idx, val);
3630 }
3631
3632 /* If OBJ is a Lisp hash table, return a pointer to its struct
3633 Lisp_Hash_Table. Otherwise, signal an error. */
3634
3635 static struct Lisp_Hash_Table *
3636 check_hash_table (Lisp_Object obj)
3637 {
3638 CHECK_HASH_TABLE (obj);
3639 return XHASH_TABLE (obj);
3640 }
3641
3642
3643 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3644 number. A number is "almost" a prime number if it is not divisible
3645 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3646
3647 EMACS_INT
3648 next_almost_prime (EMACS_INT n)
3649 {
3650 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
3651 for (n |= 1; ; n += 2)
3652 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0)
3653 return n;
3654 }
3655
3656
3657 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3658 which USED[I] is non-zero. If found at index I in ARGS, set
3659 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3660 0. This function is used to extract a keyword/argument pair from
3661 a DEFUN parameter list. */
3662
3663 static ptrdiff_t
3664 get_key_arg (Lisp_Object key, ptrdiff_t nargs, Lisp_Object *args, char *used)
3665 {
3666 ptrdiff_t i;
3667
3668 for (i = 1; i < nargs; i++)
3669 if (!used[i - 1] && EQ (args[i - 1], key))
3670 {
3671 used[i - 1] = 1;
3672 used[i] = 1;
3673 return i;
3674 }
3675
3676 return 0;
3677 }
3678
3679
3680 /* Return a Lisp vector which has the same contents as VEC but has
3681 at least INCR_MIN more entries, where INCR_MIN is positive.
3682 If NITEMS_MAX is not -1, do not grow the vector to be any larger
3683 than NITEMS_MAX. Entries in the resulting
3684 vector that are not copied from VEC are set to nil. */
3685
3686 Lisp_Object
3687 larger_vector (Lisp_Object vec, ptrdiff_t incr_min, ptrdiff_t nitems_max)
3688 {
3689 struct Lisp_Vector *v;
3690 ptrdiff_t i, incr, incr_max, old_size, new_size;
3691 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / sizeof *v->contents;
3692 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
3693 ? nitems_max : C_language_max);
3694 eassert (VECTORP (vec));
3695 eassert (0 < incr_min && -1 <= nitems_max);
3696 old_size = ASIZE (vec);
3697 incr_max = n_max - old_size;
3698 incr = max (incr_min, min (old_size >> 1, incr_max));
3699 if (incr_max < incr)
3700 memory_full (SIZE_MAX);
3701 new_size = old_size + incr;
3702 v = allocate_vector (new_size);
3703 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3704 for (i = old_size; i < new_size; ++i)
3705 v->contents[i] = Qnil;
3706 XSETVECTOR (vec, v);
3707 return vec;
3708 }
3709
3710
3711 /***********************************************************************
3712 Low-level Functions
3713 ***********************************************************************/
3714
3715 static struct hash_table_test hashtest_eq;
3716 struct hash_table_test hashtest_eql, hashtest_equal;
3717
3718 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3719 HASH2 in hash table H using `eql'. Value is true if KEY1 and
3720 KEY2 are the same. */
3721
3722 static bool
3723 cmpfn_eql (struct hash_table_test *ht,
3724 Lisp_Object key1,
3725 Lisp_Object key2)
3726 {
3727 return (FLOATP (key1)
3728 && FLOATP (key2)
3729 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3730 }
3731
3732
3733 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3734 HASH2 in hash table H using `equal'. Value is true if KEY1 and
3735 KEY2 are the same. */
3736
3737 static bool
3738 cmpfn_equal (struct hash_table_test *ht,
3739 Lisp_Object key1,
3740 Lisp_Object key2)
3741 {
3742 return !NILP (Fequal (key1, key2));
3743 }
3744
3745
3746 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3747 HASH2 in hash table H using H->user_cmp_function. Value is true
3748 if KEY1 and KEY2 are the same. */
3749
3750 static bool
3751 cmpfn_user_defined (struct hash_table_test *ht,
3752 Lisp_Object key1,
3753 Lisp_Object key2)
3754 {
3755 Lisp_Object args[3];
3756
3757 args[0] = ht->user_cmp_function;
3758 args[1] = key1;
3759 args[2] = key2;
3760 return !NILP (Ffuncall (3, args));
3761 }
3762
3763
3764 /* Value is a hash code for KEY for use in hash table H which uses
3765 `eq' to compare keys. The hash code returned is guaranteed to fit
3766 in a Lisp integer. */
3767
3768 static EMACS_UINT
3769 hashfn_eq (struct hash_table_test *ht, Lisp_Object key)
3770 {
3771 EMACS_UINT hash = XHASH (key) ^ XTYPE (key);
3772 return hash;
3773 }
3774
3775 /* Value is a hash code for KEY for use in hash table H which uses
3776 `eql' to compare keys. The hash code returned is guaranteed to fit
3777 in a Lisp integer. */
3778
3779 static EMACS_UINT
3780 hashfn_eql (struct hash_table_test *ht, Lisp_Object key)
3781 {
3782 EMACS_UINT hash;
3783 if (FLOATP (key))
3784 hash = sxhash (key, 0);
3785 else
3786 hash = XHASH (key) ^ XTYPE (key);
3787 return hash;
3788 }
3789
3790 /* Value is a hash code for KEY for use in hash table H which uses
3791 `equal' to compare keys. The hash code returned is guaranteed to fit
3792 in a Lisp integer. */
3793
3794 static EMACS_UINT
3795 hashfn_equal (struct hash_table_test *ht, Lisp_Object key)
3796 {
3797 EMACS_UINT hash = sxhash (key, 0);
3798 return hash;
3799 }
3800
3801 /* Value is a hash code for KEY for use in hash table H which uses as
3802 user-defined function to compare keys. The hash code returned is
3803 guaranteed to fit in a Lisp integer. */
3804
3805 static EMACS_UINT
3806 hashfn_user_defined (struct hash_table_test *ht, Lisp_Object key)
3807 {
3808 Lisp_Object args[2], hash;
3809
3810 args[0] = ht->user_hash_function;
3811 args[1] = key;
3812 hash = Ffuncall (2, args);
3813 return hashfn_eq (ht, hash);
3814 }
3815
3816 /* An upper bound on the size of a hash table index. It must fit in
3817 ptrdiff_t and be a valid Emacs fixnum. */
3818 #define INDEX_SIZE_BOUND \
3819 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, PTRDIFF_MAX / word_size))
3820
3821 /* Create and initialize a new hash table.
3822
3823 TEST specifies the test the hash table will use to compare keys.
3824 It must be either one of the predefined tests `eq', `eql' or
3825 `equal' or a symbol denoting a user-defined test named TEST with
3826 test and hash functions USER_TEST and USER_HASH.
3827
3828 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3829
3830 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3831 new size when it becomes full is computed by adding REHASH_SIZE to
3832 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3833 table's new size is computed by multiplying its old size with
3834 REHASH_SIZE.
3835
3836 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3837 be resized when the ratio of (number of entries in the table) /
3838 (table size) is >= REHASH_THRESHOLD.
3839
3840 WEAK specifies the weakness of the table. If non-nil, it must be
3841 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
3842
3843 Lisp_Object
3844 make_hash_table (struct hash_table_test test,
3845 Lisp_Object size, Lisp_Object rehash_size,
3846 Lisp_Object rehash_threshold, Lisp_Object weak)
3847 {
3848 struct Lisp_Hash_Table *h;
3849 Lisp_Object table;
3850 EMACS_INT index_size, sz;
3851 ptrdiff_t i;
3852 double index_float;
3853
3854 /* Preconditions. */
3855 eassert (SYMBOLP (test.name));
3856 eassert (INTEGERP (size) && XINT (size) >= 0);
3857 eassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3858 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size)));
3859 eassert (FLOATP (rehash_threshold)
3860 && 0 < XFLOAT_DATA (rehash_threshold)
3861 && XFLOAT_DATA (rehash_threshold) <= 1.0);
3862
3863 if (XFASTINT (size) == 0)
3864 size = make_number (1);
3865
3866 sz = XFASTINT (size);
3867 index_float = sz / XFLOAT_DATA (rehash_threshold);
3868 index_size = (index_float < INDEX_SIZE_BOUND + 1
3869 ? next_almost_prime (index_float)
3870 : INDEX_SIZE_BOUND + 1);
3871 if (INDEX_SIZE_BOUND < max (index_size, 2 * sz))
3872 error ("Hash table too large");
3873
3874 /* Allocate a table and initialize it. */
3875 h = allocate_hash_table ();
3876
3877 /* Initialize hash table slots. */
3878 h->test = test;
3879 h->weak = weak;
3880 h->rehash_threshold = rehash_threshold;
3881 h->rehash_size = rehash_size;
3882 h->count = 0;
3883 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
3884 h->hash = Fmake_vector (size, Qnil);
3885 h->next = Fmake_vector (size, Qnil);
3886 h->index = Fmake_vector (make_number (index_size), Qnil);
3887
3888 /* Set up the free list. */
3889 for (i = 0; i < sz - 1; ++i)
3890 set_hash_next_slot (h, i, make_number (i + 1));
3891 h->next_free = make_number (0);
3892
3893 XSET_HASH_TABLE (table, h);
3894 eassert (HASH_TABLE_P (table));
3895 eassert (XHASH_TABLE (table) == h);
3896
3897 /* Maybe add this hash table to the list of all weak hash tables. */
3898 if (NILP (h->weak))
3899 h->next_weak = NULL;
3900 else
3901 {
3902 h->next_weak = weak_hash_tables;
3903 weak_hash_tables = h;
3904 }
3905
3906 return table;
3907 }
3908
3909
3910 /* Return a copy of hash table H1. Keys and values are not copied,
3911 only the table itself is. */
3912
3913 static Lisp_Object
3914 copy_hash_table (struct Lisp_Hash_Table *h1)
3915 {
3916 Lisp_Object table;
3917 struct Lisp_Hash_Table *h2;
3918
3919 h2 = allocate_hash_table ();
3920 *h2 = *h1;
3921 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3922 h2->hash = Fcopy_sequence (h1->hash);
3923 h2->next = Fcopy_sequence (h1->next);
3924 h2->index = Fcopy_sequence (h1->index);
3925 XSET_HASH_TABLE (table, h2);
3926
3927 /* Maybe add this hash table to the list of all weak hash tables. */
3928 if (!NILP (h2->weak))
3929 {
3930 h2->next_weak = weak_hash_tables;
3931 weak_hash_tables = h2;
3932 }
3933
3934 return table;
3935 }
3936
3937
3938 /* Resize hash table H if it's too full. If H cannot be resized
3939 because it's already too large, throw an error. */
3940
3941 static void
3942 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3943 {
3944 if (NILP (h->next_free))
3945 {
3946 ptrdiff_t old_size = HASH_TABLE_SIZE (h);
3947 EMACS_INT new_size, index_size, nsize;
3948 ptrdiff_t i;
3949 double index_float;
3950
3951 if (INTEGERP (h->rehash_size))
3952 new_size = old_size + XFASTINT (h->rehash_size);
3953 else
3954 {
3955 double float_new_size = old_size * XFLOAT_DATA (h->rehash_size);
3956 if (float_new_size < INDEX_SIZE_BOUND + 1)
3957 {
3958 new_size = float_new_size;
3959 if (new_size <= old_size)
3960 new_size = old_size + 1;
3961 }
3962 else
3963 new_size = INDEX_SIZE_BOUND + 1;
3964 }
3965 index_float = new_size / XFLOAT_DATA (h->rehash_threshold);
3966 index_size = (index_float < INDEX_SIZE_BOUND + 1
3967 ? next_almost_prime (index_float)
3968 : INDEX_SIZE_BOUND + 1);
3969 nsize = max (index_size, 2 * new_size);
3970 if (INDEX_SIZE_BOUND < nsize)
3971 error ("Hash table too large to resize");
3972
3973 #ifdef ENABLE_CHECKING
3974 if (HASH_TABLE_P (Vpurify_flag)
3975 && XHASH_TABLE (Vpurify_flag) == h)
3976 Fmessage (2, ((Lisp_Object [])
3977 { build_string ("Growing hash table to: %d"),
3978 make_number (new_size) }));
3979 #endif
3980
3981 set_hash_key_and_value (h, larger_vector (h->key_and_value,
3982 2 * (new_size - old_size), -1));
3983 set_hash_next (h, larger_vector (h->next, new_size - old_size, -1));
3984 set_hash_hash (h, larger_vector (h->hash, new_size - old_size, -1));
3985 set_hash_index (h, Fmake_vector (make_number (index_size), Qnil));
3986
3987 /* Update the free list. Do it so that new entries are added at
3988 the end of the free list. This makes some operations like
3989 maphash faster. */
3990 for (i = old_size; i < new_size - 1; ++i)
3991 set_hash_next_slot (h, i, make_number (i + 1));
3992
3993 if (!NILP (h->next_free))
3994 {
3995 Lisp_Object last, next;
3996
3997 last = h->next_free;
3998 while (next = HASH_NEXT (h, XFASTINT (last)),
3999 !NILP (next))
4000 last = next;
4001
4002 set_hash_next_slot (h, XFASTINT (last), make_number (old_size));
4003 }
4004 else
4005 XSETFASTINT (h->next_free, old_size);
4006
4007 /* Rehash. */
4008 for (i = 0; i < old_size; ++i)
4009 if (!NILP (HASH_HASH (h, i)))
4010 {
4011 EMACS_UINT hash_code = XUINT (HASH_HASH (h, i));
4012 ptrdiff_t start_of_bucket = hash_code % ASIZE (h->index);
4013 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
4014 set_hash_index_slot (h, start_of_bucket, make_number (i));
4015 }
4016 }
4017 }
4018
4019
4020 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
4021 the hash code of KEY. Value is the index of the entry in H
4022 matching KEY, or -1 if not found. */
4023
4024 ptrdiff_t
4025 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
4026 {
4027 EMACS_UINT hash_code;
4028 ptrdiff_t start_of_bucket;
4029 Lisp_Object idx;
4030
4031 hash_code = h->test.hashfn (&h->test, key);
4032 eassert ((hash_code & ~INTMASK) == 0);
4033 if (hash)
4034 *hash = hash_code;
4035
4036 start_of_bucket = hash_code % ASIZE (h->index);
4037 idx = HASH_INDEX (h, start_of_bucket);
4038
4039 /* We need not gcpro idx since it's either an integer or nil. */
4040 while (!NILP (idx))
4041 {
4042 ptrdiff_t i = XFASTINT (idx);
4043 if (EQ (key, HASH_KEY (h, i))
4044 || (h->test.cmpfn
4045 && hash_code == XUINT (HASH_HASH (h, i))
4046 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
4047 break;
4048 idx = HASH_NEXT (h, i);
4049 }
4050
4051 return NILP (idx) ? -1 : XFASTINT (idx);
4052 }
4053
4054
4055 /* Put an entry into hash table H that associates KEY with VALUE.
4056 HASH is a previously computed hash code of KEY.
4057 Value is the index of the entry in H matching KEY. */
4058
4059 ptrdiff_t
4060 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value,
4061 EMACS_UINT hash)
4062 {
4063 ptrdiff_t start_of_bucket, i;
4064
4065 eassert ((hash & ~INTMASK) == 0);
4066
4067 /* Increment count after resizing because resizing may fail. */
4068 maybe_resize_hash_table (h);
4069 h->count++;
4070
4071 /* Store key/value in the key_and_value vector. */
4072 i = XFASTINT (h->next_free);
4073 h->next_free = HASH_NEXT (h, i);
4074 set_hash_key_slot (h, i, key);
4075 set_hash_value_slot (h, i, value);
4076
4077 /* Remember its hash code. */
4078 set_hash_hash_slot (h, i, make_number (hash));
4079
4080 /* Add new entry to its collision chain. */
4081 start_of_bucket = hash % ASIZE (h->index);
4082 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
4083 set_hash_index_slot (h, start_of_bucket, make_number (i));
4084 return i;
4085 }
4086
4087
4088 /* Remove the entry matching KEY from hash table H, if there is one. */
4089
4090 static void
4091 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
4092 {
4093 EMACS_UINT hash_code;
4094 ptrdiff_t start_of_bucket;
4095 Lisp_Object idx, prev;
4096
4097 hash_code = h->test.hashfn (&h->test, key);
4098 eassert ((hash_code & ~INTMASK) == 0);
4099 start_of_bucket = hash_code % ASIZE (h->index);
4100 idx = HASH_INDEX (h, start_of_bucket);
4101 prev = Qnil;
4102
4103 /* We need not gcpro idx, prev since they're either integers or nil. */
4104 while (!NILP (idx))
4105 {
4106 ptrdiff_t i = XFASTINT (idx);
4107
4108 if (EQ (key, HASH_KEY (h, i))
4109 || (h->test.cmpfn
4110 && hash_code == XUINT (HASH_HASH (h, i))
4111 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
4112 {
4113 /* Take entry out of collision chain. */
4114 if (NILP (prev))
4115 set_hash_index_slot (h, start_of_bucket, HASH_NEXT (h, i));
4116 else
4117 set_hash_next_slot (h, XFASTINT (prev), HASH_NEXT (h, i));
4118
4119 /* Clear slots in key_and_value and add the slots to
4120 the free list. */
4121 set_hash_key_slot (h, i, Qnil);
4122 set_hash_value_slot (h, i, Qnil);
4123 set_hash_hash_slot (h, i, Qnil);
4124 set_hash_next_slot (h, i, h->next_free);
4125 h->next_free = make_number (i);
4126 h->count--;
4127 eassert (h->count >= 0);
4128 break;
4129 }
4130 else
4131 {
4132 prev = idx;
4133 idx = HASH_NEXT (h, i);
4134 }
4135 }
4136 }
4137
4138
4139 /* Clear hash table H. */
4140
4141 static void
4142 hash_clear (struct Lisp_Hash_Table *h)
4143 {
4144 if (h->count > 0)
4145 {
4146 ptrdiff_t i, size = HASH_TABLE_SIZE (h);
4147
4148 for (i = 0; i < size; ++i)
4149 {
4150 set_hash_next_slot (h, i, i < size - 1 ? make_number (i + 1) : Qnil);
4151 set_hash_key_slot (h, i, Qnil);
4152 set_hash_value_slot (h, i, Qnil);
4153 set_hash_hash_slot (h, i, Qnil);
4154 }
4155
4156 for (i = 0; i < ASIZE (h->index); ++i)
4157 ASET (h->index, i, Qnil);
4158
4159 h->next_free = make_number (0);
4160 h->count = 0;
4161 }
4162 }
4163
4164
4165 \f
4166 /************************************************************************
4167 Weak Hash Tables
4168 ************************************************************************/
4169
4170 /* Sweep weak hash table H. REMOVE_ENTRIES_P means remove
4171 entries from the table that don't survive the current GC.
4172 !REMOVE_ENTRIES_P means mark entries that are in use. Value is
4173 true if anything was marked. */
4174
4175 static bool
4176 sweep_weak_table (struct Lisp_Hash_Table *h, bool remove_entries_p)
4177 {
4178 ptrdiff_t bucket, n;
4179 bool marked;
4180
4181 n = ASIZE (h->index) & ~ARRAY_MARK_FLAG;
4182 marked = 0;
4183
4184 for (bucket = 0; bucket < n; ++bucket)
4185 {
4186 Lisp_Object idx, next, prev;
4187
4188 /* Follow collision chain, removing entries that
4189 don't survive this garbage collection. */
4190 prev = Qnil;
4191 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
4192 {
4193 ptrdiff_t i = XFASTINT (idx);
4194 bool key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
4195 bool value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
4196 bool remove_p;
4197
4198 if (EQ (h->weak, Qkey))
4199 remove_p = !key_known_to_survive_p;
4200 else if (EQ (h->weak, Qvalue))
4201 remove_p = !value_known_to_survive_p;
4202 else if (EQ (h->weak, Qkey_or_value))
4203 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
4204 else if (EQ (h->weak, Qkey_and_value))
4205 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
4206 else
4207 emacs_abort ();
4208
4209 next = HASH_NEXT (h, i);
4210
4211 if (remove_entries_p)
4212 {
4213 if (remove_p)
4214 {
4215 /* Take out of collision chain. */
4216 if (NILP (prev))
4217 set_hash_index_slot (h, bucket, next);
4218 else
4219 set_hash_next_slot (h, XFASTINT (prev), next);
4220
4221 /* Add to free list. */
4222 set_hash_next_slot (h, i, h->next_free);
4223 h->next_free = idx;
4224
4225 /* Clear key, value, and hash. */
4226 set_hash_key_slot (h, i, Qnil);
4227 set_hash_value_slot (h, i, Qnil);
4228 set_hash_hash_slot (h, i, Qnil);
4229
4230 h->count--;
4231 }
4232 else
4233 {
4234 prev = idx;
4235 }
4236 }
4237 else
4238 {
4239 if (!remove_p)
4240 {
4241 /* Make sure key and value survive. */
4242 if (!key_known_to_survive_p)
4243 {
4244 mark_object (HASH_KEY (h, i));
4245 marked = 1;
4246 }
4247
4248 if (!value_known_to_survive_p)
4249 {
4250 mark_object (HASH_VALUE (h, i));
4251 marked = 1;
4252 }
4253 }
4254 }
4255 }
4256 }
4257
4258 return marked;
4259 }
4260
4261 /* Remove elements from weak hash tables that don't survive the
4262 current garbage collection. Remove weak tables that don't survive
4263 from Vweak_hash_tables. Called from gc_sweep. */
4264
4265 NO_INLINE /* For better stack traces */
4266 void
4267 sweep_weak_hash_tables (void)
4268 {
4269 struct Lisp_Hash_Table *h, *used, *next;
4270 bool marked;
4271
4272 /* Mark all keys and values that are in use. Keep on marking until
4273 there is no more change. This is necessary for cases like
4274 value-weak table A containing an entry X -> Y, where Y is used in a
4275 key-weak table B, Z -> Y. If B comes after A in the list of weak
4276 tables, X -> Y might be removed from A, although when looking at B
4277 one finds that it shouldn't. */
4278 do
4279 {
4280 marked = 0;
4281 for (h = weak_hash_tables; h; h = h->next_weak)
4282 {
4283 if (h->header.size & ARRAY_MARK_FLAG)
4284 marked |= sweep_weak_table (h, 0);
4285 }
4286 }
4287 while (marked);
4288
4289 /* Remove tables and entries that aren't used. */
4290 for (h = weak_hash_tables, used = NULL; h; h = next)
4291 {
4292 next = h->next_weak;
4293
4294 if (h->header.size & ARRAY_MARK_FLAG)
4295 {
4296 /* TABLE is marked as used. Sweep its contents. */
4297 if (h->count > 0)
4298 sweep_weak_table (h, 1);
4299
4300 /* Add table to the list of used weak hash tables. */
4301 h->next_weak = used;
4302 used = h;
4303 }
4304 }
4305
4306 weak_hash_tables = used;
4307 }
4308
4309
4310 \f
4311 /***********************************************************************
4312 Hash Code Computation
4313 ***********************************************************************/
4314
4315 /* Maximum depth up to which to dive into Lisp structures. */
4316
4317 #define SXHASH_MAX_DEPTH 3
4318
4319 /* Maximum length up to which to take list and vector elements into
4320 account. */
4321
4322 #define SXHASH_MAX_LEN 7
4323
4324 /* Return a hash for string PTR which has length LEN. The hash value
4325 can be any EMACS_UINT value. */
4326
4327 EMACS_UINT
4328 hash_string (char const *ptr, ptrdiff_t len)
4329 {
4330 char const *p = ptr;
4331 char const *end = p + len;
4332 unsigned char c;
4333 EMACS_UINT hash = 0;
4334
4335 while (p != end)
4336 {
4337 c = *p++;
4338 hash = sxhash_combine (hash, c);
4339 }
4340
4341 return hash;
4342 }
4343
4344 /* Return a hash for string PTR which has length LEN. The hash
4345 code returned is guaranteed to fit in a Lisp integer. */
4346
4347 static EMACS_UINT
4348 sxhash_string (char const *ptr, ptrdiff_t len)
4349 {
4350 EMACS_UINT hash = hash_string (ptr, len);
4351 return SXHASH_REDUCE (hash);
4352 }
4353
4354 /* Return a hash for the floating point value VAL. */
4355
4356 static EMACS_UINT
4357 sxhash_float (double val)
4358 {
4359 EMACS_UINT hash = 0;
4360 enum {
4361 WORDS_PER_DOUBLE = (sizeof val / sizeof hash
4362 + (sizeof val % sizeof hash != 0))
4363 };
4364 union {
4365 double val;
4366 EMACS_UINT word[WORDS_PER_DOUBLE];
4367 } u;
4368 int i;
4369 u.val = val;
4370 memset (&u.val + 1, 0, sizeof u - sizeof u.val);
4371 for (i = 0; i < WORDS_PER_DOUBLE; i++)
4372 hash = sxhash_combine (hash, u.word[i]);
4373 return SXHASH_REDUCE (hash);
4374 }
4375
4376 /* Return a hash for list LIST. DEPTH is the current depth in the
4377 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4378
4379 static EMACS_UINT
4380 sxhash_list (Lisp_Object list, int depth)
4381 {
4382 EMACS_UINT hash = 0;
4383 int i;
4384
4385 if (depth < SXHASH_MAX_DEPTH)
4386 for (i = 0;
4387 CONSP (list) && i < SXHASH_MAX_LEN;
4388 list = XCDR (list), ++i)
4389 {
4390 EMACS_UINT hash2 = sxhash (XCAR (list), depth + 1);
4391 hash = sxhash_combine (hash, hash2);
4392 }
4393
4394 if (!NILP (list))
4395 {
4396 EMACS_UINT hash2 = sxhash (list, depth + 1);
4397 hash = sxhash_combine (hash, hash2);
4398 }
4399
4400 return SXHASH_REDUCE (hash);
4401 }
4402
4403
4404 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4405 the Lisp structure. */
4406
4407 static EMACS_UINT
4408 sxhash_vector (Lisp_Object vec, int depth)
4409 {
4410 EMACS_UINT hash = ASIZE (vec);
4411 int i, n;
4412
4413 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4414 for (i = 0; i < n; ++i)
4415 {
4416 EMACS_UINT hash2 = sxhash (AREF (vec, i), depth + 1);
4417 hash = sxhash_combine (hash, hash2);
4418 }
4419
4420 return SXHASH_REDUCE (hash);
4421 }
4422
4423 /* Return a hash for bool-vector VECTOR. */
4424
4425 static EMACS_UINT
4426 sxhash_bool_vector (Lisp_Object vec)
4427 {
4428 EMACS_INT size = bool_vector_size (vec);
4429 EMACS_UINT hash = size;
4430 int i, n;
4431
4432 n = min (SXHASH_MAX_LEN, bool_vector_words (size));
4433 for (i = 0; i < n; ++i)
4434 hash = sxhash_combine (hash, bool_vector_data (vec)[i]);
4435
4436 return SXHASH_REDUCE (hash);
4437 }
4438
4439
4440 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4441 structure. Value is an unsigned integer clipped to INTMASK. */
4442
4443 EMACS_UINT
4444 sxhash (Lisp_Object obj, int depth)
4445 {
4446 EMACS_UINT hash;
4447
4448 if (depth > SXHASH_MAX_DEPTH)
4449 return 0;
4450
4451 switch (XTYPE (obj))
4452 {
4453 case_Lisp_Int:
4454 hash = XUINT (obj);
4455 break;
4456
4457 case Lisp_Misc:
4458 case Lisp_Symbol:
4459 hash = XHASH (obj);
4460 break;
4461
4462 case Lisp_String:
4463 hash = sxhash_string (SSDATA (obj), SBYTES (obj));
4464 break;
4465
4466 /* This can be everything from a vector to an overlay. */
4467 case Lisp_Vectorlike:
4468 if (VECTORP (obj))
4469 /* According to the CL HyperSpec, two arrays are equal only if
4470 they are `eq', except for strings and bit-vectors. In
4471 Emacs, this works differently. We have to compare element
4472 by element. */
4473 hash = sxhash_vector (obj, depth);
4474 else if (BOOL_VECTOR_P (obj))
4475 hash = sxhash_bool_vector (obj);
4476 else
4477 /* Others are `equal' if they are `eq', so let's take their
4478 address as hash. */
4479 hash = XHASH (obj);
4480 break;
4481
4482 case Lisp_Cons:
4483 hash = sxhash_list (obj, depth);
4484 break;
4485
4486 case Lisp_Float:
4487 hash = sxhash_float (XFLOAT_DATA (obj));
4488 break;
4489
4490 default:
4491 emacs_abort ();
4492 }
4493
4494 return hash;
4495 }
4496
4497
4498 \f
4499 /***********************************************************************
4500 Lisp Interface
4501 ***********************************************************************/
4502
4503
4504 DEFUN ("sxhash", Fsxhash, Ssxhash, 1, 1, 0,
4505 doc: /* Compute a hash code for OBJ and return it as integer. */)
4506 (Lisp_Object obj)
4507 {
4508 EMACS_UINT hash = sxhash (obj, 0);
4509 return make_number (hash);
4510 }
4511
4512
4513 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4514 doc: /* Create and return a new hash table.
4515
4516 Arguments are specified as keyword/argument pairs. The following
4517 arguments are defined:
4518
4519 :test TEST -- TEST must be a symbol that specifies how to compare
4520 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4521 `equal'. User-supplied test and hash functions can be specified via
4522 `define-hash-table-test'.
4523
4524 :size SIZE -- A hint as to how many elements will be put in the table.
4525 Default is 65.
4526
4527 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4528 fills up. If REHASH-SIZE is an integer, increase the size by that
4529 amount. If it is a float, it must be > 1.0, and the new size is the
4530 old size multiplied by that factor. Default is 1.5.
4531
4532 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4533 Resize the hash table when the ratio (number of entries / table size)
4534 is greater than or equal to THRESHOLD. Default is 0.8.
4535
4536 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4537 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4538 returned is a weak table. Key/value pairs are removed from a weak
4539 hash table when there are no non-weak references pointing to their
4540 key, value, one of key or value, or both key and value, depending on
4541 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4542 is nil.
4543
4544 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4545 (ptrdiff_t nargs, Lisp_Object *args)
4546 {
4547 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4548 struct hash_table_test testdesc;
4549 ptrdiff_t i;
4550 USE_SAFE_ALLOCA;
4551
4552 /* The vector `used' is used to keep track of arguments that
4553 have been consumed. */
4554 char *used = SAFE_ALLOCA (nargs * sizeof *used);
4555 memset (used, 0, nargs * sizeof *used);
4556
4557 /* See if there's a `:test TEST' among the arguments. */
4558 i = get_key_arg (QCtest, nargs, args, used);
4559 test = i ? args[i] : Qeql;
4560 if (EQ (test, Qeq))
4561 testdesc = hashtest_eq;
4562 else if (EQ (test, Qeql))
4563 testdesc = hashtest_eql;
4564 else if (EQ (test, Qequal))
4565 testdesc = hashtest_equal;
4566 else
4567 {
4568 /* See if it is a user-defined test. */
4569 Lisp_Object prop;
4570
4571 prop = Fget (test, Qhash_table_test);
4572 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4573 signal_error ("Invalid hash table test", test);
4574 testdesc.name = test;
4575 testdesc.user_cmp_function = XCAR (prop);
4576 testdesc.user_hash_function = XCAR (XCDR (prop));
4577 testdesc.hashfn = hashfn_user_defined;
4578 testdesc.cmpfn = cmpfn_user_defined;
4579 }
4580
4581 /* See if there's a `:size SIZE' argument. */
4582 i = get_key_arg (QCsize, nargs, args, used);
4583 size = i ? args[i] : Qnil;
4584 if (NILP (size))
4585 size = make_number (DEFAULT_HASH_SIZE);
4586 else if (!INTEGERP (size) || XINT (size) < 0)
4587 signal_error ("Invalid hash table size", size);
4588
4589 /* Look for `:rehash-size SIZE'. */
4590 i = get_key_arg (QCrehash_size, nargs, args, used);
4591 rehash_size = i ? args[i] : make_float (DEFAULT_REHASH_SIZE);
4592 if (! ((INTEGERP (rehash_size) && 0 < XINT (rehash_size))
4593 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size))))
4594 signal_error ("Invalid hash table rehash size", rehash_size);
4595
4596 /* Look for `:rehash-threshold THRESHOLD'. */
4597 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4598 rehash_threshold = i ? args[i] : make_float (DEFAULT_REHASH_THRESHOLD);
4599 if (! (FLOATP (rehash_threshold)
4600 && 0 < XFLOAT_DATA (rehash_threshold)
4601 && XFLOAT_DATA (rehash_threshold) <= 1))
4602 signal_error ("Invalid hash table rehash threshold", rehash_threshold);
4603
4604 /* Look for `:weakness WEAK'. */
4605 i = get_key_arg (QCweakness, nargs, args, used);
4606 weak = i ? args[i] : Qnil;
4607 if (EQ (weak, Qt))
4608 weak = Qkey_and_value;
4609 if (!NILP (weak)
4610 && !EQ (weak, Qkey)
4611 && !EQ (weak, Qvalue)
4612 && !EQ (weak, Qkey_or_value)
4613 && !EQ (weak, Qkey_and_value))
4614 signal_error ("Invalid hash table weakness", weak);
4615
4616 /* Now, all args should have been used up, or there's a problem. */
4617 for (i = 0; i < nargs; ++i)
4618 if (!used[i])
4619 signal_error ("Invalid argument list", args[i]);
4620
4621 SAFE_FREE ();
4622 return make_hash_table (testdesc, size, rehash_size, rehash_threshold, weak);
4623 }
4624
4625
4626 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4627 doc: /* Return a copy of hash table TABLE. */)
4628 (Lisp_Object table)
4629 {
4630 return copy_hash_table (check_hash_table (table));
4631 }
4632
4633
4634 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4635 doc: /* Return the number of elements in TABLE. */)
4636 (Lisp_Object table)
4637 {
4638 return make_number (check_hash_table (table)->count);
4639 }
4640
4641
4642 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4643 Shash_table_rehash_size, 1, 1, 0,
4644 doc: /* Return the current rehash size of TABLE. */)
4645 (Lisp_Object table)
4646 {
4647 return check_hash_table (table)->rehash_size;
4648 }
4649
4650
4651 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4652 Shash_table_rehash_threshold, 1, 1, 0,
4653 doc: /* Return the current rehash threshold of TABLE. */)
4654 (Lisp_Object table)
4655 {
4656 return check_hash_table (table)->rehash_threshold;
4657 }
4658
4659
4660 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4661 doc: /* Return the size of TABLE.
4662 The size can be used as an argument to `make-hash-table' to create
4663 a hash table than can hold as many elements as TABLE holds
4664 without need for resizing. */)
4665 (Lisp_Object table)
4666 {
4667 struct Lisp_Hash_Table *h = check_hash_table (table);
4668 return make_number (HASH_TABLE_SIZE (h));
4669 }
4670
4671
4672 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4673 doc: /* Return the test TABLE uses. */)
4674 (Lisp_Object table)
4675 {
4676 return check_hash_table (table)->test.name;
4677 }
4678
4679
4680 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4681 1, 1, 0,
4682 doc: /* Return the weakness of TABLE. */)
4683 (Lisp_Object table)
4684 {
4685 return check_hash_table (table)->weak;
4686 }
4687
4688
4689 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4690 doc: /* Return t if OBJ is a Lisp hash table object. */)
4691 (Lisp_Object obj)
4692 {
4693 return HASH_TABLE_P (obj) ? Qt : Qnil;
4694 }
4695
4696
4697 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4698 doc: /* Clear hash table TABLE and return it. */)
4699 (Lisp_Object table)
4700 {
4701 hash_clear (check_hash_table (table));
4702 /* Be compatible with XEmacs. */
4703 return table;
4704 }
4705
4706
4707 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4708 doc: /* Look up KEY in TABLE and return its associated value.
4709 If KEY is not found, return DFLT which defaults to nil. */)
4710 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4711 {
4712 struct Lisp_Hash_Table *h = check_hash_table (table);
4713 ptrdiff_t i = hash_lookup (h, key, NULL);
4714 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4715 }
4716
4717
4718 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4719 doc: /* Associate KEY with VALUE in hash table TABLE.
4720 If KEY is already present in table, replace its current value with
4721 VALUE. In any case, return VALUE. */)
4722 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4723 {
4724 struct Lisp_Hash_Table *h = check_hash_table (table);
4725 ptrdiff_t i;
4726 EMACS_UINT hash;
4727
4728 i = hash_lookup (h, key, &hash);
4729 if (i >= 0)
4730 set_hash_value_slot (h, i, value);
4731 else
4732 hash_put (h, key, value, hash);
4733
4734 return value;
4735 }
4736
4737
4738 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4739 doc: /* Remove KEY from TABLE. */)
4740 (Lisp_Object key, Lisp_Object table)
4741 {
4742 struct Lisp_Hash_Table *h = check_hash_table (table);
4743 hash_remove_from_table (h, key);
4744 return Qnil;
4745 }
4746
4747
4748 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4749 doc: /* Call FUNCTION for all entries in hash table TABLE.
4750 FUNCTION is called with two arguments, KEY and VALUE.
4751 `maphash' always returns nil. */)
4752 (Lisp_Object function, Lisp_Object table)
4753 {
4754 struct Lisp_Hash_Table *h = check_hash_table (table);
4755 Lisp_Object args[3];
4756 ptrdiff_t i;
4757
4758 for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
4759 if (!NILP (HASH_HASH (h, i)))
4760 {
4761 args[0] = function;
4762 args[1] = HASH_KEY (h, i);
4763 args[2] = HASH_VALUE (h, i);
4764 Ffuncall (3, args);
4765 }
4766
4767 return Qnil;
4768 }
4769
4770
4771 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4772 Sdefine_hash_table_test, 3, 3, 0,
4773 doc: /* Define a new hash table test with name NAME, a symbol.
4774
4775 In hash tables created with NAME specified as test, use TEST to
4776 compare keys, and HASH for computing hash codes of keys.
4777
4778 TEST must be a function taking two arguments and returning non-nil if
4779 both arguments are the same. HASH must be a function taking one
4780 argument and returning an object that is the hash code of the argument.
4781 It should be the case that if (eq (funcall HASH x1) (funcall HASH x2))
4782 returns nil, then (funcall TEST x1 x2) also returns nil. */)
4783 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4784 {
4785 return Fput (name, Qhash_table_test, list2 (test, hash));
4786 }
4787
4788
4789 \f
4790 /************************************************************************
4791 MD5, SHA-1, and SHA-2
4792 ************************************************************************/
4793
4794 #include "md5.h"
4795 #include "sha1.h"
4796 #include "sha256.h"
4797 #include "sha512.h"
4798
4799 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4800
4801 static Lisp_Object
4802 secure_hash (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start,
4803 Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror,
4804 Lisp_Object binary)
4805 {
4806 int i;
4807 ptrdiff_t size, start_char = 0, start_byte, end_char = 0, end_byte;
4808 register EMACS_INT b, e;
4809 register struct buffer *bp;
4810 EMACS_INT temp;
4811 int digest_size;
4812 void *(*hash_func) (const char *, size_t, void *);
4813 Lisp_Object digest;
4814
4815 CHECK_SYMBOL (algorithm);
4816
4817 if (STRINGP (object))
4818 {
4819 if (NILP (coding_system))
4820 {
4821 /* Decide the coding-system to encode the data with. */
4822
4823 if (STRING_MULTIBYTE (object))
4824 /* use default, we can't guess correct value */
4825 coding_system = preferred_coding_system ();
4826 else
4827 coding_system = Qraw_text;
4828 }
4829
4830 if (NILP (Fcoding_system_p (coding_system)))
4831 {
4832 /* Invalid coding system. */
4833
4834 if (!NILP (noerror))
4835 coding_system = Qraw_text;
4836 else
4837 xsignal1 (Qcoding_system_error, coding_system);
4838 }
4839
4840 if (STRING_MULTIBYTE (object))
4841 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4842
4843 size = SCHARS (object);
4844 validate_subarray (object, start, end, size, &start_char, &end_char);
4845
4846 start_byte = !start_char ? 0 : string_char_to_byte (object, start_char);
4847 end_byte = (end_char == size
4848 ? SBYTES (object)
4849 : string_char_to_byte (object, end_char));
4850 }
4851 else
4852 {
4853 struct buffer *prev = current_buffer;
4854
4855 record_unwind_current_buffer ();
4856
4857 CHECK_BUFFER (object);
4858
4859 bp = XBUFFER (object);
4860 set_buffer_internal (bp);
4861
4862 if (NILP (start))
4863 b = BEGV;
4864 else
4865 {
4866 CHECK_NUMBER_COERCE_MARKER (start);
4867 b = XINT (start);
4868 }
4869
4870 if (NILP (end))
4871 e = ZV;
4872 else
4873 {
4874 CHECK_NUMBER_COERCE_MARKER (end);
4875 e = XINT (end);
4876 }
4877
4878 if (b > e)
4879 temp = b, b = e, e = temp;
4880
4881 if (!(BEGV <= b && e <= ZV))
4882 args_out_of_range (start, end);
4883
4884 if (NILP (coding_system))
4885 {
4886 /* Decide the coding-system to encode the data with.
4887 See fileio.c:Fwrite-region */
4888
4889 if (!NILP (Vcoding_system_for_write))
4890 coding_system = Vcoding_system_for_write;
4891 else
4892 {
4893 bool force_raw_text = 0;
4894
4895 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4896 if (NILP (coding_system)
4897 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4898 {
4899 coding_system = Qnil;
4900 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4901 force_raw_text = 1;
4902 }
4903
4904 if (NILP (coding_system) && !NILP (Fbuffer_file_name (object)))
4905 {
4906 /* Check file-coding-system-alist. */
4907 Lisp_Object args[4], val;
4908
4909 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4910 args[3] = Fbuffer_file_name (object);
4911 val = Ffind_operation_coding_system (4, args);
4912 if (CONSP (val) && !NILP (XCDR (val)))
4913 coding_system = XCDR (val);
4914 }
4915
4916 if (NILP (coding_system)
4917 && !NILP (BVAR (XBUFFER (object), buffer_file_coding_system)))
4918 {
4919 /* If we still have not decided a coding system, use the
4920 default value of buffer-file-coding-system. */
4921 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4922 }
4923
4924 if (!force_raw_text
4925 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4926 /* Confirm that VAL can surely encode the current region. */
4927 coding_system = call4 (Vselect_safe_coding_system_function,
4928 make_number (b), make_number (e),
4929 coding_system, Qnil);
4930
4931 if (force_raw_text)
4932 coding_system = Qraw_text;
4933 }
4934
4935 if (NILP (Fcoding_system_p (coding_system)))
4936 {
4937 /* Invalid coding system. */
4938
4939 if (!NILP (noerror))
4940 coding_system = Qraw_text;
4941 else
4942 xsignal1 (Qcoding_system_error, coding_system);
4943 }
4944 }
4945
4946 object = make_buffer_string (b, e, 0);
4947 set_buffer_internal (prev);
4948 /* Discard the unwind protect for recovering the current
4949 buffer. */
4950 specpdl_ptr--;
4951
4952 if (STRING_MULTIBYTE (object))
4953 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4954 start_byte = 0;
4955 end_byte = SBYTES (object);
4956 }
4957
4958 if (EQ (algorithm, Qmd5))
4959 {
4960 digest_size = MD5_DIGEST_SIZE;
4961 hash_func = md5_buffer;
4962 }
4963 else if (EQ (algorithm, Qsha1))
4964 {
4965 digest_size = SHA1_DIGEST_SIZE;
4966 hash_func = sha1_buffer;
4967 }
4968 else if (EQ (algorithm, Qsha224))
4969 {
4970 digest_size = SHA224_DIGEST_SIZE;
4971 hash_func = sha224_buffer;
4972 }
4973 else if (EQ (algorithm, Qsha256))
4974 {
4975 digest_size = SHA256_DIGEST_SIZE;
4976 hash_func = sha256_buffer;
4977 }
4978 else if (EQ (algorithm, Qsha384))
4979 {
4980 digest_size = SHA384_DIGEST_SIZE;
4981 hash_func = sha384_buffer;
4982 }
4983 else if (EQ (algorithm, Qsha512))
4984 {
4985 digest_size = SHA512_DIGEST_SIZE;
4986 hash_func = sha512_buffer;
4987 }
4988 else
4989 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm)));
4990
4991 /* allocate 2 x digest_size so that it can be re-used to hold the
4992 hexified value */
4993 digest = make_uninit_string (digest_size * 2);
4994
4995 hash_func (SSDATA (object) + start_byte,
4996 end_byte - start_byte,
4997 SSDATA (digest));
4998
4999 if (NILP (binary))
5000 {
5001 unsigned char *p = SDATA (digest);
5002 for (i = digest_size - 1; i >= 0; i--)
5003 {
5004 static char const hexdigit[16] = "0123456789abcdef";
5005 int p_i = p[i];
5006 p[2 * i] = hexdigit[p_i >> 4];
5007 p[2 * i + 1] = hexdigit[p_i & 0xf];
5008 }
5009 return digest;
5010 }
5011 else
5012 return make_unibyte_string (SSDATA (digest), digest_size);
5013 }
5014
5015 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
5016 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
5017
5018 A message digest is a cryptographic checksum of a document, and the
5019 algorithm to calculate it is defined in RFC 1321.
5020
5021 The two optional arguments START and END are character positions
5022 specifying for which part of OBJECT the message digest should be
5023 computed. If nil or omitted, the digest is computed for the whole
5024 OBJECT.
5025
5026 The MD5 message digest is computed from the result of encoding the
5027 text in a coding system, not directly from the internal Emacs form of
5028 the text. The optional fourth argument CODING-SYSTEM specifies which
5029 coding system to encode the text with. It should be the same coding
5030 system that you used or will use when actually writing the text into a
5031 file.
5032
5033 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
5034 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
5035 system would be chosen by default for writing this text into a file.
5036
5037 If OBJECT is a string, the most preferred coding system (see the
5038 command `prefer-coding-system') is used.
5039
5040 If NOERROR is non-nil, silently assume the `raw-text' coding if the
5041 guesswork fails. Normally, an error is signaled in such case. */)
5042 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
5043 {
5044 return secure_hash (Qmd5, object, start, end, coding_system, noerror, Qnil);
5045 }
5046
5047 DEFUN ("secure-hash", Fsecure_hash, Ssecure_hash, 2, 5, 0,
5048 doc: /* Return the secure hash of OBJECT, a buffer or string.
5049 ALGORITHM is a symbol specifying the hash to use:
5050 md5, sha1, sha224, sha256, sha384 or sha512.
5051
5052 The two optional arguments START and END are positions specifying for
5053 which part of OBJECT to compute the hash. If nil or omitted, uses the
5054 whole OBJECT.
5055
5056 If BINARY is non-nil, returns a string in binary form. */)
5057 (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object binary)
5058 {
5059 return secure_hash (algorithm, object, start, end, Qnil, Qnil, binary);
5060 }
5061 \f
5062 void
5063 syms_of_fns (void)
5064 {
5065 DEFSYM (Qmd5, "md5");
5066 DEFSYM (Qsha1, "sha1");
5067 DEFSYM (Qsha224, "sha224");
5068 DEFSYM (Qsha256, "sha256");
5069 DEFSYM (Qsha384, "sha384");
5070 DEFSYM (Qsha512, "sha512");
5071
5072 /* Hash table stuff. */
5073 DEFSYM (Qhash_table_p, "hash-table-p");
5074 DEFSYM (Qeq, "eq");
5075 DEFSYM (Qeql, "eql");
5076 DEFSYM (Qequal, "equal");
5077 DEFSYM (QCtest, ":test");
5078 DEFSYM (QCsize, ":size");
5079 DEFSYM (QCrehash_size, ":rehash-size");
5080 DEFSYM (QCrehash_threshold, ":rehash-threshold");
5081 DEFSYM (QCweakness, ":weakness");
5082 DEFSYM (Qkey, "key");
5083 DEFSYM (Qvalue, "value");
5084 DEFSYM (Qhash_table_test, "hash-table-test");
5085 DEFSYM (Qkey_or_value, "key-or-value");
5086 DEFSYM (Qkey_and_value, "key-and-value");
5087
5088 defsubr (&Ssxhash);
5089 defsubr (&Smake_hash_table);
5090 defsubr (&Scopy_hash_table);
5091 defsubr (&Shash_table_count);
5092 defsubr (&Shash_table_rehash_size);
5093 defsubr (&Shash_table_rehash_threshold);
5094 defsubr (&Shash_table_size);
5095 defsubr (&Shash_table_test);
5096 defsubr (&Shash_table_weakness);
5097 defsubr (&Shash_table_p);
5098 defsubr (&Sclrhash);
5099 defsubr (&Sgethash);
5100 defsubr (&Sputhash);
5101 defsubr (&Sremhash);
5102 defsubr (&Smaphash);
5103 defsubr (&Sdefine_hash_table_test);
5104
5105 DEFSYM (Qstring_lessp, "string-lessp");
5106 DEFSYM (Qstring_collate_lessp, "string-collate-lessp");
5107 DEFSYM (Qstring_collate_equalp, "string-collate-equalp");
5108 DEFSYM (Qprovide, "provide");
5109 DEFSYM (Qrequire, "require");
5110 DEFSYM (Qyes_or_no_p_history, "yes-or-no-p-history");
5111 DEFSYM (Qcursor_in_echo_area, "cursor-in-echo-area");
5112 DEFSYM (Qwidget_type, "widget-type");
5113
5114 staticpro (&string_char_byte_cache_string);
5115 string_char_byte_cache_string = Qnil;
5116
5117 require_nesting_list = Qnil;
5118 staticpro (&require_nesting_list);
5119
5120 Fset (Qyes_or_no_p_history, Qnil);
5121
5122 DEFVAR_LISP ("features", Vfeatures,
5123 doc: /* A list of symbols which are the features of the executing Emacs.
5124 Used by `featurep' and `require', and altered by `provide'. */);
5125 Vfeatures = list1 (intern_c_string ("emacs"));
5126 DEFSYM (Qsubfeatures, "subfeatures");
5127 DEFSYM (Qfuncall, "funcall");
5128
5129 #ifdef HAVE_LANGINFO_CODESET
5130 DEFSYM (Qcodeset, "codeset");
5131 DEFSYM (Qdays, "days");
5132 DEFSYM (Qmonths, "months");
5133 DEFSYM (Qpaper, "paper");
5134 #endif /* HAVE_LANGINFO_CODESET */
5135
5136 DEFVAR_BOOL ("use-dialog-box", use_dialog_box,
5137 doc: /* Non-nil means mouse commands use dialog boxes to ask questions.
5138 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
5139 invoked by mouse clicks and mouse menu items.
5140
5141 On some platforms, file selection dialogs are also enabled if this is
5142 non-nil. */);
5143 use_dialog_box = 1;
5144
5145 DEFVAR_BOOL ("use-file-dialog", use_file_dialog,
5146 doc: /* Non-nil means mouse commands use a file dialog to ask for files.
5147 This applies to commands from menus and tool bar buttons even when
5148 they are initiated from the keyboard. If `use-dialog-box' is nil,
5149 that disables the use of a file dialog, regardless of the value of
5150 this variable. */);
5151 use_file_dialog = 1;
5152
5153 defsubr (&Sidentity);
5154 defsubr (&Srandom);
5155 defsubr (&Slength);
5156 defsubr (&Ssafe_length);
5157 defsubr (&Sstring_bytes);
5158 defsubr (&Sstring_equal);
5159 defsubr (&Scompare_strings);
5160 defsubr (&Sstring_lessp);
5161 defsubr (&Sstring_collate_lessp);
5162 defsubr (&Sstring_collate_equalp);
5163 defsubr (&Sappend);
5164 defsubr (&Sconcat);
5165 defsubr (&Svconcat);
5166 defsubr (&Scopy_sequence);
5167 defsubr (&Sstring_make_multibyte);
5168 defsubr (&Sstring_make_unibyte);
5169 defsubr (&Sstring_as_multibyte);
5170 defsubr (&Sstring_as_unibyte);
5171 defsubr (&Sstring_to_multibyte);
5172 defsubr (&Sstring_to_unibyte);
5173 defsubr (&Scopy_alist);
5174 defsubr (&Ssubstring);
5175 defsubr (&Ssubstring_no_properties);
5176 defsubr (&Snthcdr);
5177 defsubr (&Snth);
5178 defsubr (&Selt);
5179 defsubr (&Smember);
5180 defsubr (&Smemq);
5181 defsubr (&Smemql);
5182 defsubr (&Sassq);
5183 defsubr (&Sassoc);
5184 defsubr (&Srassq);
5185 defsubr (&Srassoc);
5186 defsubr (&Sdelq);
5187 defsubr (&Sdelete);
5188 defsubr (&Snreverse);
5189 defsubr (&Sreverse);
5190 defsubr (&Ssort);
5191 defsubr (&Splist_get);
5192 defsubr (&Sget);
5193 defsubr (&Splist_put);
5194 defsubr (&Sput);
5195 defsubr (&Slax_plist_get);
5196 defsubr (&Slax_plist_put);
5197 defsubr (&Seql);
5198 defsubr (&Sequal);
5199 defsubr (&Sequal_including_properties);
5200 defsubr (&Sfillarray);
5201 defsubr (&Sclear_string);
5202 defsubr (&Snconc);
5203 defsubr (&Smapcar);
5204 defsubr (&Smapc);
5205 defsubr (&Smapconcat);
5206 defsubr (&Syes_or_no_p);
5207 defsubr (&Sload_average);
5208 defsubr (&Sfeaturep);
5209 defsubr (&Srequire);
5210 defsubr (&Sprovide);
5211 defsubr (&Splist_member);
5212 defsubr (&Swidget_put);
5213 defsubr (&Swidget_get);
5214 defsubr (&Swidget_apply);
5215 defsubr (&Sbase64_encode_region);
5216 defsubr (&Sbase64_decode_region);
5217 defsubr (&Sbase64_encode_string);
5218 defsubr (&Sbase64_decode_string);
5219 defsubr (&Smd5);
5220 defsubr (&Ssecure_hash);
5221 defsubr (&Slocale_info);
5222
5223 hashtest_eq.name = Qeq;
5224 hashtest_eq.user_hash_function = Qnil;
5225 hashtest_eq.user_cmp_function = Qnil;
5226 hashtest_eq.cmpfn = 0;
5227 hashtest_eq.hashfn = hashfn_eq;
5228
5229 hashtest_eql.name = Qeql;
5230 hashtest_eql.user_hash_function = Qnil;
5231 hashtest_eql.user_cmp_function = Qnil;
5232 hashtest_eql.cmpfn = cmpfn_eql;
5233 hashtest_eql.hashfn = hashfn_eql;
5234
5235 hashtest_equal.name = Qequal;
5236 hashtest_equal.user_hash_function = Qnil;
5237 hashtest_equal.user_cmp_function = Qnil;
5238 hashtest_equal.cmpfn = cmpfn_equal;
5239 hashtest_equal.hashfn = hashfn_equal;
5240 }