; * src/fns.c (Fmake_hash_table): Prefer 'double' to 'float'.
[emacs.git] / src / fns.c
blobbe00bfd86814b701d64e4ec8e1b5cb9509bb5550
1 /* Random utility Lisp functions.
3 Copyright (C) 1985-1987, 1993-1995, 1997-2017 Free Software Foundation,
4 Inc.
6 This file is part of GNU Emacs.
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 (at
11 your option) any later version.
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.
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/>. */
21 #include <config.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <filevercmp.h>
26 #include <intprops.h>
27 #include <vla.h>
28 #include <errno.h>
30 #include "lisp.h"
31 #include "character.h"
32 #include "coding.h"
33 #include "composite.h"
34 #include "buffer.h"
35 #include "intervals.h"
36 #include "window.h"
37 #include "puresize.h"
39 static void sort_vector_copy (Lisp_Object, ptrdiff_t,
40 Lisp_Object *restrict, Lisp_Object *restrict);
41 static bool internal_equal (Lisp_Object, Lisp_Object, int, bool, Lisp_Object);
43 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
44 doc: /* Return the argument unchanged. */
45 attributes: const)
46 (Lisp_Object arg)
48 return arg;
51 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
52 doc: /* Return a pseudo-random number.
53 All integers representable in Lisp, i.e. between `most-negative-fixnum'
54 and `most-positive-fixnum', inclusive, are equally likely.
56 With positive integer LIMIT, return random number in interval [0,LIMIT).
57 With argument t, set the random number seed from the system's entropy
58 pool if available, otherwise from less-random volatile data such as the time.
59 With a string argument, set the seed based on the string's contents.
60 Other values of LIMIT are ignored.
62 See Info node `(elisp)Random Numbers' for more details. */)
63 (Lisp_Object limit)
65 EMACS_INT val;
67 if (EQ (limit, Qt))
68 init_random ();
69 else if (STRINGP (limit))
70 seed_random (SSDATA (limit), SBYTES (limit));
72 val = get_random ();
73 if (INTEGERP (limit) && 0 < XINT (limit))
74 while (true)
76 /* Return the remainder, except reject the rare case where
77 get_random returns a number so close to INTMASK that the
78 remainder isn't random. */
79 EMACS_INT remainder = val % XINT (limit);
80 if (val - remainder <= INTMASK - XINT (limit) + 1)
81 return make_number (remainder);
82 val = get_random ();
84 return make_number (val);
87 /* Random data-structure functions. */
89 DEFUN ("length", Flength, Slength, 1, 1, 0,
90 doc: /* Return the length of vector, list or string SEQUENCE.
91 A byte-code function object is also allowed.
92 If the string contains multibyte characters, this is not necessarily
93 the number of bytes in the string; it is the number of characters.
94 To get the number of bytes, use `string-bytes'. */)
95 (register Lisp_Object sequence)
97 register Lisp_Object val;
99 if (STRINGP (sequence))
100 XSETFASTINT (val, SCHARS (sequence));
101 else if (VECTORP (sequence))
102 XSETFASTINT (val, ASIZE (sequence));
103 else if (CHAR_TABLE_P (sequence))
104 XSETFASTINT (val, MAX_CHAR);
105 else if (BOOL_VECTOR_P (sequence))
106 XSETFASTINT (val, bool_vector_size (sequence));
107 else if (COMPILEDP (sequence))
108 XSETFASTINT (val, ASIZE (sequence) & PSEUDOVECTOR_SIZE_MASK);
109 else if (CONSP (sequence))
111 intptr_t i = 0;
112 FOR_EACH_TAIL (sequence)
113 i++;
114 CHECK_LIST_END (sequence, sequence);
115 if (MOST_POSITIVE_FIXNUM < i)
116 error ("List too long");
117 val = make_number (i);
119 else if (NILP (sequence))
120 XSETFASTINT (val, 0);
121 else
122 wrong_type_argument (Qsequencep, sequence);
124 return val;
127 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
128 doc: /* Return the length of a list, but avoid error or infinite loop.
129 This function never gets an error. If LIST is not really a list,
130 it returns 0. If LIST is circular, it returns a finite value
131 which is at least the number of distinct elements. */)
132 (Lisp_Object list)
134 intptr_t len = 0;
135 FOR_EACH_TAIL_SAFE (list)
136 len++;
137 return make_fixnum_or_float (len);
140 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
141 doc: /* Return the number of bytes in STRING.
142 If STRING is multibyte, this may be greater than the length of STRING. */)
143 (Lisp_Object string)
145 CHECK_STRING (string);
146 return make_number (SBYTES (string));
149 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
150 doc: /* Return t if two strings have identical contents.
151 Case is significant, but text properties are ignored.
152 Symbols are also allowed; their print names are used instead. */)
153 (register Lisp_Object s1, Lisp_Object s2)
155 if (SYMBOLP (s1))
156 s1 = SYMBOL_NAME (s1);
157 if (SYMBOLP (s2))
158 s2 = SYMBOL_NAME (s2);
159 CHECK_STRING (s1);
160 CHECK_STRING (s2);
162 if (SCHARS (s1) != SCHARS (s2)
163 || SBYTES (s1) != SBYTES (s2)
164 || memcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
165 return Qnil;
166 return Qt;
169 DEFUN ("compare-strings", Fcompare_strings, Scompare_strings, 6, 7, 0,
170 doc: /* Compare the contents of two strings, converting to multibyte if needed.
171 The arguments START1, END1, START2, and END2, if non-nil, are
172 positions specifying which parts of STR1 or STR2 to compare. In
173 string STR1, compare the part between START1 (inclusive) and END1
174 \(exclusive). If START1 is nil, it defaults to 0, the beginning of
175 the string; if END1 is nil, it defaults to the length of the string.
176 Likewise, in string STR2, compare the part between START2 and END2.
177 Like in `substring', negative values are counted from the end.
179 The strings are compared by the numeric values of their characters.
180 For instance, STR1 is "less than" STR2 if its first differing
181 character has a smaller numeric value. If IGNORE-CASE is non-nil,
182 characters are converted to upper-case before comparing them. Unibyte
183 strings are converted to multibyte for comparison.
185 The value is t if the strings (or specified portions) match.
186 If string STR1 is less, the value is a negative number N;
187 - 1 - N is the number of characters that match at the beginning.
188 If string STR1 is greater, the value is a positive number N;
189 N - 1 is the number of characters that match at the beginning. */)
190 (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2,
191 Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
193 ptrdiff_t from1, to1, from2, to2, i1, i1_byte, i2, i2_byte;
195 CHECK_STRING (str1);
196 CHECK_STRING (str2);
198 /* For backward compatibility, silently bring too-large positive end
199 values into range. */
200 if (INTEGERP (end1) && SCHARS (str1) < XINT (end1))
201 end1 = make_number (SCHARS (str1));
202 if (INTEGERP (end2) && SCHARS (str2) < XINT (end2))
203 end2 = make_number (SCHARS (str2));
205 validate_subarray (str1, start1, end1, SCHARS (str1), &from1, &to1);
206 validate_subarray (str2, start2, end2, SCHARS (str2), &from2, &to2);
208 i1 = from1;
209 i2 = from2;
211 i1_byte = string_char_to_byte (str1, i1);
212 i2_byte = string_char_to_byte (str2, i2);
214 while (i1 < to1 && i2 < to2)
216 /* When we find a mismatch, we must compare the
217 characters, not just the bytes. */
218 int c1, c2;
220 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c1, str1, i1, i1_byte);
221 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c2, str2, i2, i2_byte);
223 if (c1 == c2)
224 continue;
226 if (! NILP (ignore_case))
228 c1 = XINT (Fupcase (make_number (c1)));
229 c2 = XINT (Fupcase (make_number (c2)));
232 if (c1 == c2)
233 continue;
235 /* Note that I1 has already been incremented
236 past the character that we are comparing;
237 hence we don't add or subtract 1 here. */
238 if (c1 < c2)
239 return make_number (- i1 + from1);
240 else
241 return make_number (i1 - from1);
244 if (i1 < to1)
245 return make_number (i1 - from1 + 1);
246 if (i2 < to2)
247 return make_number (- i1 + from1 - 1);
249 return Qt;
252 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
253 doc: /* Return non-nil if STRING1 is less than STRING2 in lexicographic order.
254 Case is significant.
255 Symbols are also allowed; their print names are used instead. */)
256 (register Lisp_Object string1, Lisp_Object string2)
258 register ptrdiff_t end;
259 register ptrdiff_t i1, i1_byte, i2, i2_byte;
261 if (SYMBOLP (string1))
262 string1 = SYMBOL_NAME (string1);
263 if (SYMBOLP (string2))
264 string2 = SYMBOL_NAME (string2);
265 CHECK_STRING (string1);
266 CHECK_STRING (string2);
268 i1 = i1_byte = i2 = i2_byte = 0;
270 end = SCHARS (string1);
271 if (end > SCHARS (string2))
272 end = SCHARS (string2);
274 while (i1 < end)
276 /* When we find a mismatch, we must compare the
277 characters, not just the bytes. */
278 int c1, c2;
280 FETCH_STRING_CHAR_ADVANCE (c1, string1, i1, i1_byte);
281 FETCH_STRING_CHAR_ADVANCE (c2, string2, i2, i2_byte);
283 if (c1 != c2)
284 return c1 < c2 ? Qt : Qnil;
286 return i1 < SCHARS (string2) ? Qt : Qnil;
289 DEFUN ("string-version-lessp", Fstring_version_lessp,
290 Sstring_version_lessp, 2, 2, 0,
291 doc: /* Return non-nil if S1 is less than S2, as version strings.
293 This function compares version strings S1 and S2:
294 1) By prefix lexicographically.
295 2) Then by version (similarly to version comparison of Debian's dpkg).
296 Leading zeros in version numbers are ignored.
297 3) If both prefix and version are equal, compare as ordinary strings.
299 For example, \"foo2.png\" compares less than \"foo12.png\".
300 Case is significant.
301 Symbols are also allowed; their print names are used instead. */)
302 (Lisp_Object string1, Lisp_Object string2)
304 if (SYMBOLP (string1))
305 string1 = SYMBOL_NAME (string1);
306 if (SYMBOLP (string2))
307 string2 = SYMBOL_NAME (string2);
308 CHECK_STRING (string1);
309 CHECK_STRING (string2);
311 char *p1 = SSDATA (string1);
312 char *p2 = SSDATA (string2);
313 char *lim1 = p1 + SBYTES (string1);
314 char *lim2 = p2 + SBYTES (string2);
315 int cmp;
317 while ((cmp = filevercmp (p1, p2)) == 0)
319 /* If the strings are identical through their first null bytes,
320 skip past identical prefixes and try again. */
321 ptrdiff_t size = strlen (p1) + 1;
322 p1 += size;
323 p2 += size;
324 if (lim1 < p1)
325 return lim2 < p2 ? Qnil : Qt;
326 if (lim2 < p2)
327 return Qnil;
330 return cmp < 0 ? Qt : Qnil;
333 DEFUN ("string-collate-lessp", Fstring_collate_lessp, Sstring_collate_lessp, 2, 4, 0,
334 doc: /* Return t if first arg string is less than second in collation order.
335 Symbols are also allowed; their print names are used instead.
337 This function obeys the conventions for collation order in your
338 locale settings. For example, punctuation and whitespace characters
339 might be considered less significant for sorting:
341 \(sort \\='("11" "12" "1 1" "1 2" "1.1" "1.2") \\='string-collate-lessp)
342 => ("11" "1 1" "1.1" "12" "1 2" "1.2")
344 The optional argument LOCALE, a string, overrides the setting of your
345 current locale identifier for collation. The value is system
346 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
347 while it would be, e.g., \"enu_USA.1252\" on MS-Windows systems.
349 If IGNORE-CASE is non-nil, characters are converted to lower-case
350 before comparing them.
352 To emulate Unicode-compliant collation on MS-Windows systems,
353 bind `w32-collate-ignore-punctuation' to a non-nil value, since
354 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
356 If your system does not support a locale environment, this function
357 behaves like `string-lessp'. */)
358 (Lisp_Object s1, Lisp_Object s2, Lisp_Object locale, Lisp_Object ignore_case)
360 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
361 /* Check parameters. */
362 if (SYMBOLP (s1))
363 s1 = SYMBOL_NAME (s1);
364 if (SYMBOLP (s2))
365 s2 = SYMBOL_NAME (s2);
366 CHECK_STRING (s1);
367 CHECK_STRING (s2);
368 if (!NILP (locale))
369 CHECK_STRING (locale);
371 return (str_collate (s1, s2, locale, ignore_case) < 0) ? Qt : Qnil;
373 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
374 return Fstring_lessp (s1, s2);
375 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
378 DEFUN ("string-collate-equalp", Fstring_collate_equalp, Sstring_collate_equalp, 2, 4, 0,
379 doc: /* Return t if two strings have identical contents.
380 Symbols are also allowed; their print names are used instead.
382 This function obeys the conventions for collation order in your locale
383 settings. For example, characters with different coding points but
384 the same meaning might be considered as equal, like different grave
385 accent Unicode characters:
387 \(string-collate-equalp (string ?\\uFF40) (string ?\\u1FEF))
388 => t
390 The optional argument LOCALE, a string, overrides the setting of your
391 current locale identifier for collation. The value is system
392 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
393 while it would be \"enu_USA.1252\" on MS Windows systems.
395 If IGNORE-CASE is non-nil, characters are converted to lower-case
396 before comparing them.
398 To emulate Unicode-compliant collation on MS-Windows systems,
399 bind `w32-collate-ignore-punctuation' to a non-nil value, since
400 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
402 If your system does not support a locale environment, this function
403 behaves like `string-equal'.
405 Do NOT use this function to compare file names for equality. */)
406 (Lisp_Object s1, Lisp_Object s2, Lisp_Object locale, Lisp_Object ignore_case)
408 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
409 /* Check parameters. */
410 if (SYMBOLP (s1))
411 s1 = SYMBOL_NAME (s1);
412 if (SYMBOLP (s2))
413 s2 = SYMBOL_NAME (s2);
414 CHECK_STRING (s1);
415 CHECK_STRING (s2);
416 if (!NILP (locale))
417 CHECK_STRING (locale);
419 return (str_collate (s1, s2, locale, ignore_case) == 0) ? Qt : Qnil;
421 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
422 return Fstring_equal (s1, s2);
423 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
426 static Lisp_Object concat (ptrdiff_t nargs, Lisp_Object *args,
427 enum Lisp_Type target_type, bool last_special);
429 /* ARGSUSED */
430 Lisp_Object
431 concat2 (Lisp_Object s1, Lisp_Object s2)
433 return concat (2, ((Lisp_Object []) {s1, s2}), Lisp_String, 0);
436 /* ARGSUSED */
437 Lisp_Object
438 concat3 (Lisp_Object s1, Lisp_Object s2, Lisp_Object s3)
440 return concat (3, ((Lisp_Object []) {s1, s2, s3}), Lisp_String, 0);
443 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
444 doc: /* Concatenate all the arguments and make the result a list.
445 The result is a list whose elements are the elements of all the arguments.
446 Each argument may be a list, vector or string.
447 The last argument is not copied, just used as the tail of the new list.
448 usage: (append &rest SEQUENCES) */)
449 (ptrdiff_t nargs, Lisp_Object *args)
451 return concat (nargs, args, Lisp_Cons, 1);
454 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
455 doc: /* Concatenate all the arguments and make the result a string.
456 The result is a string whose elements are the elements of all the arguments.
457 Each argument may be a string or a list or vector of characters (integers).
458 usage: (concat &rest SEQUENCES) */)
459 (ptrdiff_t nargs, Lisp_Object *args)
461 return concat (nargs, args, Lisp_String, 0);
464 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
465 doc: /* Concatenate all the arguments and make the result a vector.
466 The result is a vector whose elements are the elements of all the arguments.
467 Each argument may be a list, vector or string.
468 usage: (vconcat &rest SEQUENCES) */)
469 (ptrdiff_t nargs, Lisp_Object *args)
471 return concat (nargs, args, Lisp_Vectorlike, 0);
475 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
476 doc: /* Return a copy of a list, vector, string or char-table.
477 The elements of a list or vector are not copied; they are shared
478 with the original. */)
479 (Lisp_Object arg)
481 if (NILP (arg)) return arg;
483 if (CHAR_TABLE_P (arg))
485 return copy_char_table (arg);
488 if (BOOL_VECTOR_P (arg))
490 EMACS_INT nbits = bool_vector_size (arg);
491 ptrdiff_t nbytes = bool_vector_bytes (nbits);
492 Lisp_Object val = make_uninit_bool_vector (nbits);
493 memcpy (bool_vector_data (val), bool_vector_data (arg), nbytes);
494 return val;
497 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
498 wrong_type_argument (Qsequencep, arg);
500 return concat (1, &arg, XTYPE (arg), 0);
503 /* This structure holds information of an argument of `concat' that is
504 a string and has text properties to be copied. */
505 struct textprop_rec
507 ptrdiff_t argnum; /* refer to ARGS (arguments of `concat') */
508 ptrdiff_t from; /* refer to ARGS[argnum] (argument string) */
509 ptrdiff_t to; /* refer to VAL (the target string) */
512 static Lisp_Object
513 concat (ptrdiff_t nargs, Lisp_Object *args,
514 enum Lisp_Type target_type, bool last_special)
516 Lisp_Object val;
517 Lisp_Object tail;
518 Lisp_Object this;
519 ptrdiff_t toindex;
520 ptrdiff_t toindex_byte = 0;
521 EMACS_INT result_len;
522 EMACS_INT result_len_byte;
523 ptrdiff_t argnum;
524 Lisp_Object last_tail;
525 Lisp_Object prev;
526 bool some_multibyte;
527 /* When we make a multibyte string, we can't copy text properties
528 while concatenating each string because the length of resulting
529 string can't be decided until we finish the whole concatenation.
530 So, we record strings that have text properties to be copied
531 here, and copy the text properties after the concatenation. */
532 struct textprop_rec *textprops = NULL;
533 /* Number of elements in textprops. */
534 ptrdiff_t num_textprops = 0;
535 USE_SAFE_ALLOCA;
537 tail = Qnil;
539 /* In append, the last arg isn't treated like the others */
540 if (last_special && nargs > 0)
542 nargs--;
543 last_tail = args[nargs];
545 else
546 last_tail = Qnil;
548 /* Check each argument. */
549 for (argnum = 0; argnum < nargs; argnum++)
551 this = args[argnum];
552 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
553 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
554 wrong_type_argument (Qsequencep, this);
557 /* Compute total length in chars of arguments in RESULT_LEN.
558 If desired output is a string, also compute length in bytes
559 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
560 whether the result should be a multibyte string. */
561 result_len_byte = 0;
562 result_len = 0;
563 some_multibyte = 0;
564 for (argnum = 0; argnum < nargs; argnum++)
566 EMACS_INT len;
567 this = args[argnum];
568 len = XFASTINT (Flength (this));
569 if (target_type == Lisp_String)
571 /* We must count the number of bytes needed in the string
572 as well as the number of characters. */
573 ptrdiff_t i;
574 Lisp_Object ch;
575 int c;
576 ptrdiff_t this_len_byte;
578 if (VECTORP (this) || COMPILEDP (this))
579 for (i = 0; i < len; i++)
581 ch = AREF (this, i);
582 CHECK_CHARACTER (ch);
583 c = XFASTINT (ch);
584 this_len_byte = CHAR_BYTES (c);
585 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
586 string_overflow ();
587 result_len_byte += this_len_byte;
588 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
589 some_multibyte = 1;
591 else if (BOOL_VECTOR_P (this) && bool_vector_size (this) > 0)
592 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
593 else if (CONSP (this))
594 for (; CONSP (this); this = XCDR (this))
596 ch = XCAR (this);
597 CHECK_CHARACTER (ch);
598 c = XFASTINT (ch);
599 this_len_byte = CHAR_BYTES (c);
600 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
601 string_overflow ();
602 result_len_byte += this_len_byte;
603 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
604 some_multibyte = 1;
606 else if (STRINGP (this))
608 if (STRING_MULTIBYTE (this))
610 some_multibyte = 1;
611 this_len_byte = SBYTES (this);
613 else
614 this_len_byte = count_size_as_multibyte (SDATA (this),
615 SCHARS (this));
616 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
617 string_overflow ();
618 result_len_byte += this_len_byte;
622 result_len += len;
623 if (MOST_POSITIVE_FIXNUM < result_len)
624 memory_full (SIZE_MAX);
627 if (! some_multibyte)
628 result_len_byte = result_len;
630 /* Create the output object. */
631 if (target_type == Lisp_Cons)
632 val = Fmake_list (make_number (result_len), Qnil);
633 else if (target_type == Lisp_Vectorlike)
634 val = Fmake_vector (make_number (result_len), Qnil);
635 else if (some_multibyte)
636 val = make_uninit_multibyte_string (result_len, result_len_byte);
637 else
638 val = make_uninit_string (result_len);
640 /* In `append', if all but last arg are nil, return last arg. */
641 if (target_type == Lisp_Cons && EQ (val, Qnil))
642 return last_tail;
644 /* Copy the contents of the args into the result. */
645 if (CONSP (val))
646 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
647 else
648 toindex = 0, toindex_byte = 0;
650 prev = Qnil;
651 if (STRINGP (val))
652 SAFE_NALLOCA (textprops, 1, nargs);
654 for (argnum = 0; argnum < nargs; argnum++)
656 Lisp_Object thislen;
657 ptrdiff_t thisleni = 0;
658 register ptrdiff_t thisindex = 0;
659 register ptrdiff_t thisindex_byte = 0;
661 this = args[argnum];
662 if (!CONSP (this))
663 thislen = Flength (this), thisleni = XINT (thislen);
665 /* Between strings of the same kind, copy fast. */
666 if (STRINGP (this) && STRINGP (val)
667 && STRING_MULTIBYTE (this) == some_multibyte)
669 ptrdiff_t thislen_byte = SBYTES (this);
671 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
672 if (string_intervals (this))
674 textprops[num_textprops].argnum = argnum;
675 textprops[num_textprops].from = 0;
676 textprops[num_textprops++].to = toindex;
678 toindex_byte += thislen_byte;
679 toindex += thisleni;
681 /* Copy a single-byte string to a multibyte string. */
682 else if (STRINGP (this) && STRINGP (val))
684 if (string_intervals (this))
686 textprops[num_textprops].argnum = argnum;
687 textprops[num_textprops].from = 0;
688 textprops[num_textprops++].to = toindex;
690 toindex_byte += copy_text (SDATA (this),
691 SDATA (val) + toindex_byte,
692 SCHARS (this), 0, 1);
693 toindex += thisleni;
695 else
696 /* Copy element by element. */
697 while (1)
699 register Lisp_Object elt;
701 /* Fetch next element of `this' arg into `elt', or break if
702 `this' is exhausted. */
703 if (NILP (this)) break;
704 if (CONSP (this))
705 elt = XCAR (this), this = XCDR (this);
706 else if (thisindex >= thisleni)
707 break;
708 else if (STRINGP (this))
710 int c;
711 if (STRING_MULTIBYTE (this))
712 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
713 thisindex,
714 thisindex_byte);
715 else
717 c = SREF (this, thisindex); thisindex++;
718 if (some_multibyte && !ASCII_CHAR_P (c))
719 c = BYTE8_TO_CHAR (c);
721 XSETFASTINT (elt, c);
723 else if (BOOL_VECTOR_P (this))
725 elt = bool_vector_ref (this, thisindex);
726 thisindex++;
728 else
730 elt = AREF (this, thisindex);
731 thisindex++;
734 /* Store this element into the result. */
735 if (toindex < 0)
737 XSETCAR (tail, elt);
738 prev = tail;
739 tail = XCDR (tail);
741 else if (VECTORP (val))
743 ASET (val, toindex, elt);
744 toindex++;
746 else
748 int c;
749 CHECK_CHARACTER (elt);
750 c = XFASTINT (elt);
751 if (some_multibyte)
752 toindex_byte += CHAR_STRING (c, SDATA (val) + toindex_byte);
753 else
754 SSET (val, toindex_byte++, c);
755 toindex++;
759 if (!NILP (prev))
760 XSETCDR (prev, last_tail);
762 if (num_textprops > 0)
764 Lisp_Object props;
765 ptrdiff_t last_to_end = -1;
767 for (argnum = 0; argnum < num_textprops; argnum++)
769 this = args[textprops[argnum].argnum];
770 props = text_property_list (this,
771 make_number (0),
772 make_number (SCHARS (this)),
773 Qnil);
774 /* If successive arguments have properties, be sure that the
775 value of `composition' property be the copy. */
776 if (last_to_end == textprops[argnum].to)
777 make_composition_value_copy (props);
778 add_text_properties_from_list (val, props,
779 make_number (textprops[argnum].to));
780 last_to_end = textprops[argnum].to + SCHARS (this);
784 SAFE_FREE ();
785 return val;
788 static Lisp_Object string_char_byte_cache_string;
789 static ptrdiff_t string_char_byte_cache_charpos;
790 static ptrdiff_t string_char_byte_cache_bytepos;
792 void
793 clear_string_char_byte_cache (void)
795 string_char_byte_cache_string = Qnil;
798 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
800 ptrdiff_t
801 string_char_to_byte (Lisp_Object string, ptrdiff_t char_index)
803 ptrdiff_t i_byte;
804 ptrdiff_t best_below, best_below_byte;
805 ptrdiff_t best_above, best_above_byte;
807 best_below = best_below_byte = 0;
808 best_above = SCHARS (string);
809 best_above_byte = SBYTES (string);
810 if (best_above == best_above_byte)
811 return char_index;
813 if (EQ (string, string_char_byte_cache_string))
815 if (string_char_byte_cache_charpos < char_index)
817 best_below = string_char_byte_cache_charpos;
818 best_below_byte = string_char_byte_cache_bytepos;
820 else
822 best_above = string_char_byte_cache_charpos;
823 best_above_byte = string_char_byte_cache_bytepos;
827 if (char_index - best_below < best_above - char_index)
829 unsigned char *p = SDATA (string) + best_below_byte;
831 while (best_below < char_index)
833 p += BYTES_BY_CHAR_HEAD (*p);
834 best_below++;
836 i_byte = p - SDATA (string);
838 else
840 unsigned char *p = SDATA (string) + best_above_byte;
842 while (best_above > char_index)
844 p--;
845 while (!CHAR_HEAD_P (*p)) p--;
846 best_above--;
848 i_byte = p - SDATA (string);
851 string_char_byte_cache_bytepos = i_byte;
852 string_char_byte_cache_charpos = char_index;
853 string_char_byte_cache_string = string;
855 return i_byte;
858 /* Return the character index corresponding to BYTE_INDEX in STRING. */
860 ptrdiff_t
861 string_byte_to_char (Lisp_Object string, ptrdiff_t byte_index)
863 ptrdiff_t i, i_byte;
864 ptrdiff_t best_below, best_below_byte;
865 ptrdiff_t best_above, best_above_byte;
867 best_below = best_below_byte = 0;
868 best_above = SCHARS (string);
869 best_above_byte = SBYTES (string);
870 if (best_above == best_above_byte)
871 return byte_index;
873 if (EQ (string, string_char_byte_cache_string))
875 if (string_char_byte_cache_bytepos < byte_index)
877 best_below = string_char_byte_cache_charpos;
878 best_below_byte = string_char_byte_cache_bytepos;
880 else
882 best_above = string_char_byte_cache_charpos;
883 best_above_byte = string_char_byte_cache_bytepos;
887 if (byte_index - best_below_byte < best_above_byte - byte_index)
889 unsigned char *p = SDATA (string) + best_below_byte;
890 unsigned char *pend = SDATA (string) + byte_index;
892 while (p < pend)
894 p += BYTES_BY_CHAR_HEAD (*p);
895 best_below++;
897 i = best_below;
898 i_byte = p - SDATA (string);
900 else
902 unsigned char *p = SDATA (string) + best_above_byte;
903 unsigned char *pbeg = SDATA (string) + byte_index;
905 while (p > pbeg)
907 p--;
908 while (!CHAR_HEAD_P (*p)) p--;
909 best_above--;
911 i = best_above;
912 i_byte = p - SDATA (string);
915 string_char_byte_cache_bytepos = i_byte;
916 string_char_byte_cache_charpos = i;
917 string_char_byte_cache_string = string;
919 return i;
922 /* Convert STRING to a multibyte string. */
924 static Lisp_Object
925 string_make_multibyte (Lisp_Object string)
927 unsigned char *buf;
928 ptrdiff_t nbytes;
929 Lisp_Object ret;
930 USE_SAFE_ALLOCA;
932 if (STRING_MULTIBYTE (string))
933 return string;
935 nbytes = count_size_as_multibyte (SDATA (string),
936 SCHARS (string));
937 /* If all the chars are ASCII, they won't need any more bytes
938 once converted. In that case, we can return STRING itself. */
939 if (nbytes == SBYTES (string))
940 return string;
942 buf = SAFE_ALLOCA (nbytes);
943 copy_text (SDATA (string), buf, SBYTES (string),
944 0, 1);
946 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
947 SAFE_FREE ();
949 return ret;
953 /* Convert STRING (if unibyte) to a multibyte string without changing
954 the number of characters. Characters 0200 trough 0237 are
955 converted to eight-bit characters. */
957 Lisp_Object
958 string_to_multibyte (Lisp_Object string)
960 unsigned char *buf;
961 ptrdiff_t nbytes;
962 Lisp_Object ret;
963 USE_SAFE_ALLOCA;
965 if (STRING_MULTIBYTE (string))
966 return string;
968 nbytes = count_size_as_multibyte (SDATA (string), SBYTES (string));
969 /* If all the chars are ASCII, they won't need any more bytes once
970 converted. */
971 if (nbytes == SBYTES (string))
972 return make_multibyte_string (SSDATA (string), nbytes, nbytes);
974 buf = SAFE_ALLOCA (nbytes);
975 memcpy (buf, SDATA (string), SBYTES (string));
976 str_to_multibyte (buf, nbytes, SBYTES (string));
978 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
979 SAFE_FREE ();
981 return ret;
985 /* Convert STRING to a single-byte string. */
987 Lisp_Object
988 string_make_unibyte (Lisp_Object string)
990 ptrdiff_t nchars;
991 unsigned char *buf;
992 Lisp_Object ret;
993 USE_SAFE_ALLOCA;
995 if (! STRING_MULTIBYTE (string))
996 return string;
998 nchars = SCHARS (string);
1000 buf = SAFE_ALLOCA (nchars);
1001 copy_text (SDATA (string), buf, SBYTES (string),
1002 1, 0);
1004 ret = make_unibyte_string ((char *) buf, nchars);
1005 SAFE_FREE ();
1007 return ret;
1010 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
1011 1, 1, 0,
1012 doc: /* Return the multibyte equivalent of STRING.
1013 If STRING is unibyte and contains non-ASCII characters, the function
1014 `unibyte-char-to-multibyte' is used to convert each unibyte character
1015 to a multibyte character. In this case, the returned string is a
1016 newly created string with no text properties. If STRING is multibyte
1017 or entirely ASCII, it is returned unchanged. In particular, when
1018 STRING is unibyte and entirely ASCII, the returned string is unibyte.
1019 \(When the characters are all ASCII, Emacs primitives will treat the
1020 string the same way whether it is unibyte or multibyte.) */)
1021 (Lisp_Object string)
1023 CHECK_STRING (string);
1025 return string_make_multibyte (string);
1028 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
1029 1, 1, 0,
1030 doc: /* Return the unibyte equivalent of STRING.
1031 Multibyte character codes are converted to unibyte according to
1032 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
1033 If the lookup in the translation table fails, this function takes just
1034 the low 8 bits of each character. */)
1035 (Lisp_Object string)
1037 CHECK_STRING (string);
1039 return string_make_unibyte (string);
1042 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
1043 1, 1, 0,
1044 doc: /* Return a unibyte string with the same individual bytes as STRING.
1045 If STRING is unibyte, the result is STRING itself.
1046 Otherwise it is a newly created string, with no text properties.
1047 If STRING is multibyte and contains a character of charset
1048 `eight-bit', it is converted to the corresponding single byte. */)
1049 (Lisp_Object string)
1051 CHECK_STRING (string);
1053 if (STRING_MULTIBYTE (string))
1055 unsigned char *str = (unsigned char *) xlispstrdup (string);
1056 ptrdiff_t bytes = str_as_unibyte (str, SBYTES (string));
1058 string = make_unibyte_string ((char *) str, bytes);
1059 xfree (str);
1061 return string;
1064 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1065 1, 1, 0,
1066 doc: /* Return a multibyte string with the same individual bytes as STRING.
1067 If STRING is multibyte, the result is STRING itself.
1068 Otherwise it is a newly created string, with no text properties.
1070 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1071 part of a correct utf-8 sequence), it is converted to the corresponding
1072 multibyte character of charset `eight-bit'.
1073 See also `string-to-multibyte'.
1075 Beware, this often doesn't really do what you think it does.
1076 It is similar to (decode-coding-string STRING \\='utf-8-emacs).
1077 If you're not sure, whether to use `string-as-multibyte' or
1078 `string-to-multibyte', use `string-to-multibyte'. */)
1079 (Lisp_Object string)
1081 CHECK_STRING (string);
1083 if (! STRING_MULTIBYTE (string))
1085 Lisp_Object new_string;
1086 ptrdiff_t nchars, nbytes;
1088 parse_str_as_multibyte (SDATA (string),
1089 SBYTES (string),
1090 &nchars, &nbytes);
1091 new_string = make_uninit_multibyte_string (nchars, nbytes);
1092 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1093 if (nbytes != SBYTES (string))
1094 str_as_multibyte (SDATA (new_string), nbytes,
1095 SBYTES (string), NULL);
1096 string = new_string;
1097 set_string_intervals (string, NULL);
1099 return string;
1102 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1103 1, 1, 0,
1104 doc: /* Return a multibyte string with the same individual chars as STRING.
1105 If STRING is multibyte, the result is STRING itself.
1106 Otherwise it is a newly created string, with no text properties.
1108 If STRING is unibyte and contains an 8-bit byte, it is converted to
1109 the corresponding multibyte character of charset `eight-bit'.
1111 This differs from `string-as-multibyte' by converting each byte of a correct
1112 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1113 correct sequence. */)
1114 (Lisp_Object string)
1116 CHECK_STRING (string);
1118 return string_to_multibyte (string);
1121 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1122 1, 1, 0,
1123 doc: /* Return a unibyte string with the same individual chars as STRING.
1124 If STRING is unibyte, the result is STRING itself.
1125 Otherwise it is a newly created string, with no text properties,
1126 where each `eight-bit' character is converted to the corresponding byte.
1127 If STRING contains a non-ASCII, non-`eight-bit' character,
1128 an error is signaled. */)
1129 (Lisp_Object string)
1131 CHECK_STRING (string);
1133 if (STRING_MULTIBYTE (string))
1135 ptrdiff_t chars = SCHARS (string);
1136 unsigned char *str = xmalloc (chars);
1137 ptrdiff_t converted = str_to_unibyte (SDATA (string), str, chars);
1139 if (converted < chars)
1140 error ("Can't convert the %"pD"dth character to unibyte", converted);
1141 string = make_unibyte_string ((char *) str, chars);
1142 xfree (str);
1144 return string;
1148 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1149 doc: /* Return a copy of ALIST.
1150 This is an alist which represents the same mapping from objects to objects,
1151 but does not share the alist structure with ALIST.
1152 The objects mapped (cars and cdrs of elements of the alist)
1153 are shared, however.
1154 Elements of ALIST that are not conses are also shared. */)
1155 (Lisp_Object alist)
1157 if (NILP (alist))
1158 return alist;
1159 alist = concat (1, &alist, Lisp_Cons, false);
1160 for (Lisp_Object tem = alist; !NILP (tem); tem = XCDR (tem))
1162 Lisp_Object car = XCAR (tem);
1163 if (CONSP (car))
1164 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1166 return alist;
1169 /* Check that ARRAY can have a valid subarray [FROM..TO),
1170 given that its size is SIZE.
1171 If FROM is nil, use 0; if TO is nil, use SIZE.
1172 Count negative values backwards from the end.
1173 Set *IFROM and *ITO to the two indexes used. */
1175 void
1176 validate_subarray (Lisp_Object array, Lisp_Object from, Lisp_Object to,
1177 ptrdiff_t size, ptrdiff_t *ifrom, ptrdiff_t *ito)
1179 EMACS_INT f, t;
1181 if (INTEGERP (from))
1183 f = XINT (from);
1184 if (f < 0)
1185 f += size;
1187 else if (NILP (from))
1188 f = 0;
1189 else
1190 wrong_type_argument (Qintegerp, from);
1192 if (INTEGERP (to))
1194 t = XINT (to);
1195 if (t < 0)
1196 t += size;
1198 else if (NILP (to))
1199 t = size;
1200 else
1201 wrong_type_argument (Qintegerp, to);
1203 if (! (0 <= f && f <= t && t <= size))
1204 args_out_of_range_3 (array, from, to);
1206 *ifrom = f;
1207 *ito = t;
1210 DEFUN ("substring", Fsubstring, Ssubstring, 1, 3, 0,
1211 doc: /* Return a new string whose contents are a substring of STRING.
1212 The returned string consists of the characters between index FROM
1213 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1214 zero-indexed: 0 means the first character of STRING. Negative values
1215 are counted from the end of STRING. If TO is nil, the substring runs
1216 to the end of STRING.
1218 The STRING argument may also be a vector. In that case, the return
1219 value is a new vector that contains the elements between index FROM
1220 \(inclusive) and index TO (exclusive) of that vector argument.
1222 With one argument, just copy STRING (with properties, if any). */)
1223 (Lisp_Object string, Lisp_Object from, Lisp_Object to)
1225 Lisp_Object res;
1226 ptrdiff_t size, ifrom, ito;
1228 size = CHECK_VECTOR_OR_STRING (string);
1229 validate_subarray (string, from, to, size, &ifrom, &ito);
1231 if (STRINGP (string))
1233 ptrdiff_t from_byte
1234 = !ifrom ? 0 : string_char_to_byte (string, ifrom);
1235 ptrdiff_t to_byte
1236 = ito == size ? SBYTES (string) : string_char_to_byte (string, ito);
1237 res = make_specified_string (SSDATA (string) + from_byte,
1238 ito - ifrom, to_byte - from_byte,
1239 STRING_MULTIBYTE (string));
1240 copy_text_properties (make_number (ifrom), make_number (ito),
1241 string, make_number (0), res, Qnil);
1243 else
1244 res = Fvector (ito - ifrom, aref_addr (string, ifrom));
1246 return res;
1250 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1251 doc: /* Return a substring of STRING, without text properties.
1252 It starts at index FROM and ends before TO.
1253 TO may be nil or omitted; then the substring runs to the end of STRING.
1254 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1255 If FROM or TO is negative, it counts from the end.
1257 With one argument, just copy STRING without its properties. */)
1258 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1260 ptrdiff_t from_char, to_char, from_byte, to_byte, size;
1262 CHECK_STRING (string);
1264 size = SCHARS (string);
1265 validate_subarray (string, from, to, size, &from_char, &to_char);
1267 from_byte = !from_char ? 0 : string_char_to_byte (string, from_char);
1268 to_byte =
1269 to_char == size ? SBYTES (string) : string_char_to_byte (string, to_char);
1270 return make_specified_string (SSDATA (string) + from_byte,
1271 to_char - from_char, to_byte - from_byte,
1272 STRING_MULTIBYTE (string));
1275 /* Extract a substring of STRING, giving start and end positions
1276 both in characters and in bytes. */
1278 Lisp_Object
1279 substring_both (Lisp_Object string, ptrdiff_t from, ptrdiff_t from_byte,
1280 ptrdiff_t to, ptrdiff_t to_byte)
1282 Lisp_Object res;
1283 ptrdiff_t size = CHECK_VECTOR_OR_STRING (string);
1285 if (!(0 <= from && from <= to && to <= size))
1286 args_out_of_range_3 (string, make_number (from), make_number (to));
1288 if (STRINGP (string))
1290 res = make_specified_string (SSDATA (string) + from_byte,
1291 to - from, to_byte - from_byte,
1292 STRING_MULTIBYTE (string));
1293 copy_text_properties (make_number (from), make_number (to),
1294 string, make_number (0), res, Qnil);
1296 else
1297 res = Fvector (to - from, aref_addr (string, from));
1299 return res;
1302 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1303 doc: /* Take cdr N times on LIST, return the result. */)
1304 (Lisp_Object n, Lisp_Object list)
1306 CHECK_NUMBER (n);
1307 Lisp_Object tail = list;
1308 for (EMACS_INT num = XINT (n); 0 < num; num--)
1310 if (! CONSP (tail))
1312 CHECK_LIST_END (tail, list);
1313 return Qnil;
1315 tail = XCDR (tail);
1316 rarely_quit (num);
1318 return tail;
1321 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1322 doc: /* Return the Nth element of LIST.
1323 N counts from zero. If LIST is not that long, nil is returned. */)
1324 (Lisp_Object n, Lisp_Object list)
1326 return Fcar (Fnthcdr (n, list));
1329 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1330 doc: /* Return element of SEQUENCE at index N. */)
1331 (register Lisp_Object sequence, Lisp_Object n)
1333 CHECK_NUMBER (n);
1334 if (CONSP (sequence) || NILP (sequence))
1335 return Fcar (Fnthcdr (n, sequence));
1337 /* Faref signals a "not array" error, so check here. */
1338 CHECK_ARRAY (sequence, Qsequencep);
1339 return Faref (sequence, n);
1342 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1343 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1344 The value is actually the tail of LIST whose car is ELT. */)
1345 (Lisp_Object elt, Lisp_Object list)
1347 Lisp_Object tail = list;
1348 FOR_EACH_TAIL (tail)
1349 if (! NILP (Fequal (elt, XCAR (tail))))
1350 return tail;
1351 CHECK_LIST_END (tail, list);
1352 return Qnil;
1355 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1356 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1357 The value is actually the tail of LIST whose car is ELT. */)
1358 (Lisp_Object elt, Lisp_Object list)
1360 Lisp_Object tail = list;
1361 FOR_EACH_TAIL (tail)
1362 if (EQ (XCAR (tail), elt))
1363 return tail;
1364 CHECK_LIST_END (tail, list);
1365 return Qnil;
1368 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1369 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1370 The value is actually the tail of LIST whose car is ELT. */)
1371 (Lisp_Object elt, Lisp_Object list)
1373 if (!FLOATP (elt))
1374 return Fmemq (elt, list);
1376 Lisp_Object tail = list;
1377 FOR_EACH_TAIL (tail)
1379 Lisp_Object tem = XCAR (tail);
1380 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0, Qnil))
1381 return tail;
1383 CHECK_LIST_END (tail, list);
1384 return Qnil;
1387 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1388 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1389 The value is actually the first element of LIST whose car is KEY.
1390 Elements of LIST that are not conses are ignored. */)
1391 (Lisp_Object key, Lisp_Object list)
1393 Lisp_Object tail = list;
1394 FOR_EACH_TAIL (tail)
1395 if (CONSP (XCAR (tail)) && EQ (XCAR (XCAR (tail)), key))
1396 return XCAR (tail);
1397 CHECK_LIST_END (tail, list);
1398 return Qnil;
1401 /* Like Fassq but never report an error and do not allow quits.
1402 Use only on objects known to be non-circular lists. */
1404 Lisp_Object
1405 assq_no_quit (Lisp_Object key, Lisp_Object list)
1407 for (; ! NILP (list); list = XCDR (list))
1408 if (CONSP (XCAR (list)) && EQ (XCAR (XCAR (list)), key))
1409 return XCAR (list);
1410 return Qnil;
1413 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1414 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1415 The value is actually the first element of LIST whose car equals KEY. */)
1416 (Lisp_Object key, Lisp_Object list)
1418 Lisp_Object tail = list;
1419 FOR_EACH_TAIL (tail)
1421 Lisp_Object car = XCAR (tail);
1422 if (CONSP (car)
1423 && (EQ (XCAR (car), key) || !NILP (Fequal (XCAR (car), key))))
1424 return car;
1426 CHECK_LIST_END (tail, list);
1427 return Qnil;
1430 /* Like Fassoc but never report an error and do not allow quits.
1431 Use only on objects known to be non-circular lists. */
1433 Lisp_Object
1434 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1436 for (; ! NILP (list); list = XCDR (list))
1438 Lisp_Object car = XCAR (list);
1439 if (CONSP (car)
1440 && (EQ (XCAR (car), key) || !NILP (Fequal (XCAR (car), key))))
1441 return car;
1443 return Qnil;
1446 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1447 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1448 The value is actually the first element of LIST whose cdr is KEY. */)
1449 (Lisp_Object key, Lisp_Object list)
1451 Lisp_Object tail = list;
1452 FOR_EACH_TAIL (tail)
1453 if (CONSP (XCAR (tail)) && EQ (XCDR (XCAR (tail)), key))
1454 return XCAR (tail);
1455 CHECK_LIST_END (tail, list);
1456 return Qnil;
1459 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1460 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1461 The value is actually the first element of LIST whose cdr equals KEY. */)
1462 (Lisp_Object key, Lisp_Object list)
1464 Lisp_Object tail = list;
1465 FOR_EACH_TAIL (tail)
1467 Lisp_Object car = XCAR (tail);
1468 if (CONSP (car)
1469 && (EQ (XCDR (car), key) || !NILP (Fequal (XCDR (car), key))))
1470 return car;
1472 CHECK_LIST_END (tail, list);
1473 return Qnil;
1476 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1477 doc: /* Delete members of LIST which are `eq' to ELT, and return the result.
1478 More precisely, this function skips any members `eq' to ELT at the
1479 front of LIST, then removes members `eq' to ELT from the remaining
1480 sublist by modifying its list structure, then returns the resulting
1481 list.
1483 Write `(setq foo (delq element foo))' to be sure of correctly changing
1484 the value of a list `foo'. See also `remq', which does not modify the
1485 argument. */)
1486 (Lisp_Object elt, Lisp_Object list)
1488 Lisp_Object prev = Qnil, tail = list;
1490 FOR_EACH_TAIL (tail)
1492 Lisp_Object tem = XCAR (tail);
1493 if (EQ (elt, tem))
1495 if (NILP (prev))
1496 list = XCDR (tail);
1497 else
1498 Fsetcdr (prev, XCDR (tail));
1500 else
1501 prev = tail;
1503 CHECK_LIST_END (tail, list);
1504 return list;
1507 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1508 doc: /* Delete members of SEQ which are `equal' to ELT, and return the result.
1509 SEQ must be a sequence (i.e. a list, a vector, or a string).
1510 The return value is a sequence of the same type.
1512 If SEQ is a list, this behaves like `delq', except that it compares
1513 with `equal' instead of `eq'. In particular, it may remove elements
1514 by altering the list structure.
1516 If SEQ is not a list, deletion is never performed destructively;
1517 instead this function creates and returns a new vector or string.
1519 Write `(setq foo (delete element foo))' to be sure of correctly
1520 changing the value of a sequence `foo'. */)
1521 (Lisp_Object elt, Lisp_Object seq)
1523 if (VECTORP (seq))
1525 ptrdiff_t i, n;
1527 for (i = n = 0; i < ASIZE (seq); ++i)
1528 if (NILP (Fequal (AREF (seq, i), elt)))
1529 ++n;
1531 if (n != ASIZE (seq))
1533 struct Lisp_Vector *p = allocate_vector (n);
1535 for (i = n = 0; i < ASIZE (seq); ++i)
1536 if (NILP (Fequal (AREF (seq, i), elt)))
1537 p->contents[n++] = AREF (seq, i);
1539 XSETVECTOR (seq, p);
1542 else if (STRINGP (seq))
1544 ptrdiff_t i, ibyte, nchars, nbytes, cbytes;
1545 int c;
1547 for (i = nchars = nbytes = ibyte = 0;
1548 i < SCHARS (seq);
1549 ++i, ibyte += cbytes)
1551 if (STRING_MULTIBYTE (seq))
1553 c = STRING_CHAR (SDATA (seq) + ibyte);
1554 cbytes = CHAR_BYTES (c);
1556 else
1558 c = SREF (seq, i);
1559 cbytes = 1;
1562 if (!INTEGERP (elt) || c != XINT (elt))
1564 ++nchars;
1565 nbytes += cbytes;
1569 if (nchars != SCHARS (seq))
1571 Lisp_Object tem;
1573 tem = make_uninit_multibyte_string (nchars, nbytes);
1574 if (!STRING_MULTIBYTE (seq))
1575 STRING_SET_UNIBYTE (tem);
1577 for (i = nchars = nbytes = ibyte = 0;
1578 i < SCHARS (seq);
1579 ++i, ibyte += cbytes)
1581 if (STRING_MULTIBYTE (seq))
1583 c = STRING_CHAR (SDATA (seq) + ibyte);
1584 cbytes = CHAR_BYTES (c);
1586 else
1588 c = SREF (seq, i);
1589 cbytes = 1;
1592 if (!INTEGERP (elt) || c != XINT (elt))
1594 unsigned char *from = SDATA (seq) + ibyte;
1595 unsigned char *to = SDATA (tem) + nbytes;
1596 ptrdiff_t n;
1598 ++nchars;
1599 nbytes += cbytes;
1601 for (n = cbytes; n--; )
1602 *to++ = *from++;
1606 seq = tem;
1609 else
1611 Lisp_Object prev = Qnil, tail = seq;
1613 FOR_EACH_TAIL (tail)
1615 if (!NILP (Fequal (elt, XCAR (tail))))
1617 if (NILP (prev))
1618 seq = XCDR (tail);
1619 else
1620 Fsetcdr (prev, XCDR (tail));
1622 else
1623 prev = tail;
1625 CHECK_LIST_END (tail, seq);
1628 return seq;
1631 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1632 doc: /* Reverse order of items in a list, vector or string SEQ.
1633 If SEQ is a list, it should be nil-terminated.
1634 This function may destructively modify SEQ to produce the value. */)
1635 (Lisp_Object seq)
1637 if (NILP (seq))
1638 return seq;
1639 else if (STRINGP (seq))
1640 return Freverse (seq);
1641 else if (CONSP (seq))
1643 Lisp_Object prev, tail, next;
1645 for (prev = Qnil, tail = seq; CONSP (tail); tail = next)
1647 next = XCDR (tail);
1648 /* If SEQ contains a cycle, attempting to reverse it
1649 in-place will inevitably come back to SEQ. */
1650 if (EQ (next, seq))
1651 circular_list (seq);
1652 Fsetcdr (tail, prev);
1653 prev = tail;
1655 CHECK_LIST_END (tail, seq);
1656 seq = prev;
1658 else if (VECTORP (seq))
1660 ptrdiff_t i, size = ASIZE (seq);
1662 for (i = 0; i < size / 2; i++)
1664 Lisp_Object tem = AREF (seq, i);
1665 ASET (seq, i, AREF (seq, size - i - 1));
1666 ASET (seq, size - i - 1, tem);
1669 else if (BOOL_VECTOR_P (seq))
1671 ptrdiff_t i, size = bool_vector_size (seq);
1673 for (i = 0; i < size / 2; i++)
1675 bool tem = bool_vector_bitref (seq, i);
1676 bool_vector_set (seq, i, bool_vector_bitref (seq, size - i - 1));
1677 bool_vector_set (seq, size - i - 1, tem);
1680 else
1681 wrong_type_argument (Qarrayp, seq);
1682 return seq;
1685 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1686 doc: /* Return the reversed copy of list, vector, or string SEQ.
1687 See also the function `nreverse', which is used more often. */)
1688 (Lisp_Object seq)
1690 Lisp_Object new;
1692 if (NILP (seq))
1693 return Qnil;
1694 else if (CONSP (seq))
1696 new = Qnil;
1697 FOR_EACH_TAIL (seq)
1698 new = Fcons (XCAR (seq), new);
1699 CHECK_LIST_END (seq, seq);
1701 else if (VECTORP (seq))
1703 ptrdiff_t i, size = ASIZE (seq);
1705 new = make_uninit_vector (size);
1706 for (i = 0; i < size; i++)
1707 ASET (new, i, AREF (seq, size - i - 1));
1709 else if (BOOL_VECTOR_P (seq))
1711 ptrdiff_t i;
1712 EMACS_INT nbits = bool_vector_size (seq);
1714 new = make_uninit_bool_vector (nbits);
1715 for (i = 0; i < nbits; i++)
1716 bool_vector_set (new, i, bool_vector_bitref (seq, nbits - i - 1));
1718 else if (STRINGP (seq))
1720 ptrdiff_t size = SCHARS (seq), bytes = SBYTES (seq);
1722 if (size == bytes)
1724 ptrdiff_t i;
1726 new = make_uninit_string (size);
1727 for (i = 0; i < size; i++)
1728 SSET (new, i, SREF (seq, size - i - 1));
1730 else
1732 unsigned char *p, *q;
1734 new = make_uninit_multibyte_string (size, bytes);
1735 p = SDATA (seq), q = SDATA (new) + bytes;
1736 while (q > SDATA (new))
1738 int ch, len;
1740 ch = STRING_CHAR_AND_LENGTH (p, len);
1741 p += len, q -= len;
1742 CHAR_STRING (ch, q);
1746 else
1747 wrong_type_argument (Qsequencep, seq);
1748 return new;
1751 /* Sort LIST using PREDICATE, preserving original order of elements
1752 considered as equal. */
1754 static Lisp_Object
1755 sort_list (Lisp_Object list, Lisp_Object predicate)
1757 Lisp_Object front, back;
1758 Lisp_Object len, tem;
1759 EMACS_INT length;
1761 front = list;
1762 len = Flength (list);
1763 length = XINT (len);
1764 if (length < 2)
1765 return list;
1767 XSETINT (len, (length / 2) - 1);
1768 tem = Fnthcdr (len, list);
1769 back = Fcdr (tem);
1770 Fsetcdr (tem, Qnil);
1772 front = Fsort (front, predicate);
1773 back = Fsort (back, predicate);
1774 return merge (front, back, predicate);
1777 /* Using PRED to compare, return whether A and B are in order.
1778 Compare stably when A appeared before B in the input. */
1779 static bool
1780 inorder (Lisp_Object pred, Lisp_Object a, Lisp_Object b)
1782 return NILP (call2 (pred, b, a));
1785 /* Using PRED to compare, merge from ALEN-length A and BLEN-length B
1786 into DEST. Argument arrays must be nonempty and must not overlap,
1787 except that B might be the last part of DEST. */
1788 static void
1789 merge_vectors (Lisp_Object pred,
1790 ptrdiff_t alen, Lisp_Object const a[restrict VLA_ELEMS (alen)],
1791 ptrdiff_t blen, Lisp_Object const b[VLA_ELEMS (blen)],
1792 Lisp_Object dest[VLA_ELEMS (alen + blen)])
1794 eassume (0 < alen && 0 < blen);
1795 Lisp_Object const *alim = a + alen;
1796 Lisp_Object const *blim = b + blen;
1798 while (true)
1800 if (inorder (pred, a[0], b[0]))
1802 *dest++ = *a++;
1803 if (a == alim)
1805 if (dest != b)
1806 memcpy (dest, b, (blim - b) * sizeof *dest);
1807 return;
1810 else
1812 *dest++ = *b++;
1813 if (b == blim)
1815 memcpy (dest, a, (alim - a) * sizeof *dest);
1816 return;
1822 /* Using PRED to compare, sort LEN-length VEC in place, using TMP for
1823 temporary storage. LEN must be at least 2. */
1824 static void
1825 sort_vector_inplace (Lisp_Object pred, ptrdiff_t len,
1826 Lisp_Object vec[restrict VLA_ELEMS (len)],
1827 Lisp_Object tmp[restrict VLA_ELEMS (len >> 1)])
1829 eassume (2 <= len);
1830 ptrdiff_t halflen = len >> 1;
1831 sort_vector_copy (pred, halflen, vec, tmp);
1832 if (1 < len - halflen)
1833 sort_vector_inplace (pred, len - halflen, vec + halflen, vec);
1834 merge_vectors (pred, halflen, tmp, len - halflen, vec + halflen, vec);
1837 /* Using PRED to compare, sort from LEN-length SRC into DST.
1838 Len must be positive. */
1839 static void
1840 sort_vector_copy (Lisp_Object pred, ptrdiff_t len,
1841 Lisp_Object src[restrict VLA_ELEMS (len)],
1842 Lisp_Object dest[restrict VLA_ELEMS (len)])
1844 eassume (0 < len);
1845 ptrdiff_t halflen = len >> 1;
1846 if (halflen < 1)
1847 dest[0] = src[0];
1848 else
1850 if (1 < halflen)
1851 sort_vector_inplace (pred, halflen, src, dest);
1852 if (1 < len - halflen)
1853 sort_vector_inplace (pred, len - halflen, src + halflen, dest);
1854 merge_vectors (pred, halflen, src, len - halflen, src + halflen, dest);
1858 /* Sort VECTOR in place using PREDICATE, preserving original order of
1859 elements considered as equal. */
1861 static void
1862 sort_vector (Lisp_Object vector, Lisp_Object predicate)
1864 ptrdiff_t len = ASIZE (vector);
1865 if (len < 2)
1866 return;
1867 ptrdiff_t halflen = len >> 1;
1868 Lisp_Object *tmp;
1869 USE_SAFE_ALLOCA;
1870 SAFE_ALLOCA_LISP (tmp, halflen);
1871 for (ptrdiff_t i = 0; i < halflen; i++)
1872 tmp[i] = make_number (0);
1873 sort_vector_inplace (predicate, len, XVECTOR (vector)->contents, tmp);
1874 SAFE_FREE ();
1877 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
1878 doc: /* Sort SEQ, stably, comparing elements using PREDICATE.
1879 Returns the sorted sequence. SEQ should be a list or vector. SEQ is
1880 modified by side effects. PREDICATE is called with two elements of
1881 SEQ, and should return non-nil if the first element should sort before
1882 the second. */)
1883 (Lisp_Object seq, Lisp_Object predicate)
1885 if (CONSP (seq))
1886 seq = sort_list (seq, predicate);
1887 else if (VECTORP (seq))
1888 sort_vector (seq, predicate);
1889 else if (!NILP (seq))
1890 wrong_type_argument (Qsequencep, seq);
1891 return seq;
1894 Lisp_Object
1895 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
1897 Lisp_Object l1 = org_l1;
1898 Lisp_Object l2 = org_l2;
1899 Lisp_Object tail = Qnil;
1900 Lisp_Object value = Qnil;
1902 while (1)
1904 if (NILP (l1))
1906 if (NILP (tail))
1907 return l2;
1908 Fsetcdr (tail, l2);
1909 return value;
1911 if (NILP (l2))
1913 if (NILP (tail))
1914 return l1;
1915 Fsetcdr (tail, l1);
1916 return value;
1919 Lisp_Object tem;
1920 if (inorder (pred, Fcar (l1), Fcar (l2)))
1922 tem = l1;
1923 l1 = Fcdr (l1);
1924 org_l1 = l1;
1926 else
1928 tem = l2;
1929 l2 = Fcdr (l2);
1930 org_l2 = l2;
1932 if (NILP (tail))
1933 value = tem;
1934 else
1935 Fsetcdr (tail, tem);
1936 tail = tem;
1941 /* This does not check for quits. That is safe since it must terminate. */
1943 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
1944 doc: /* Extract a value from a property list.
1945 PLIST is a property list, which is a list of the form
1946 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1947 corresponding to the given PROP, or nil if PROP is not one of the
1948 properties on the list. This function never signals an error. */)
1949 (Lisp_Object plist, Lisp_Object prop)
1951 Lisp_Object tail = plist;
1952 FOR_EACH_TAIL_SAFE (tail)
1954 if (! CONSP (XCDR (tail)))
1955 break;
1956 if (EQ (prop, XCAR (tail)))
1957 return XCAR (XCDR (tail));
1958 tail = XCDR (tail);
1959 if (EQ (tail, li.tortoise))
1960 break;
1963 return Qnil;
1966 DEFUN ("get", Fget, Sget, 2, 2, 0,
1967 doc: /* Return the value of SYMBOL's PROPNAME property.
1968 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
1969 (Lisp_Object symbol, Lisp_Object propname)
1971 CHECK_SYMBOL (symbol);
1972 return Fplist_get (XSYMBOL (symbol)->plist, propname);
1975 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
1976 doc: /* Change value in PLIST of PROP to VAL.
1977 PLIST is a property list, which is a list of the form
1978 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
1979 If PROP is already a property on the list, its value is set to VAL,
1980 otherwise the new PROP VAL pair is added. The new plist is returned;
1981 use `(setq x (plist-put x prop val))' to be sure to use the new value.
1982 The PLIST is modified by side effects. */)
1983 (Lisp_Object plist, Lisp_Object prop, Lisp_Object val)
1985 Lisp_Object prev = Qnil, tail = plist;
1986 FOR_EACH_TAIL (tail)
1988 if (! CONSP (XCDR (tail)))
1989 break;
1991 if (EQ (prop, XCAR (tail)))
1993 Fsetcar (XCDR (tail), val);
1994 return plist;
1997 prev = tail;
1998 tail = XCDR (tail);
1999 if (EQ (tail, li.tortoise))
2000 circular_list (plist);
2002 CHECK_LIST_END (tail, plist);
2003 Lisp_Object newcell
2004 = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
2005 if (NILP (prev))
2006 return newcell;
2007 Fsetcdr (XCDR (prev), newcell);
2008 return plist;
2011 DEFUN ("put", Fput, Sput, 3, 3, 0,
2012 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
2013 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
2014 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
2016 CHECK_SYMBOL (symbol);
2017 set_symbol_plist
2018 (symbol, Fplist_put (XSYMBOL (symbol)->plist, propname, value));
2019 return value;
2022 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
2023 doc: /* Extract a value from a property list, comparing with `equal'.
2024 PLIST is a property list, which is a list of the form
2025 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2026 corresponding to the given PROP, or nil if PROP is not
2027 one of the properties on the list. */)
2028 (Lisp_Object plist, Lisp_Object prop)
2030 Lisp_Object tail = plist;
2031 FOR_EACH_TAIL (tail)
2033 if (! CONSP (XCDR (tail)))
2034 break;
2035 if (! NILP (Fequal (prop, XCAR (tail))))
2036 return XCAR (XCDR (tail));
2037 tail = XCDR (tail);
2038 if (EQ (tail, li.tortoise))
2039 circular_list (plist);
2042 CHECK_LIST_END (tail, plist);
2044 return Qnil;
2047 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
2048 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
2049 PLIST is a property list, which is a list of the form
2050 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
2051 If PROP is already a property on the list, its value is set to VAL,
2052 otherwise the new PROP VAL pair is added. The new plist is returned;
2053 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
2054 The PLIST is modified by side effects. */)
2055 (Lisp_Object plist, Lisp_Object prop, Lisp_Object val)
2057 Lisp_Object prev = Qnil, tail = plist;
2058 FOR_EACH_TAIL (tail)
2060 if (! CONSP (XCDR (tail)))
2061 break;
2063 if (! NILP (Fequal (prop, XCAR (tail))))
2065 Fsetcar (XCDR (tail), val);
2066 return plist;
2069 prev = tail;
2070 tail = XCDR (tail);
2071 if (EQ (tail, li.tortoise))
2072 circular_list (plist);
2074 CHECK_LIST_END (tail, plist);
2075 Lisp_Object newcell = list2 (prop, val);
2076 if (NILP (prev))
2077 return newcell;
2078 Fsetcdr (XCDR (prev), newcell);
2079 return plist;
2082 DEFUN ("eql", Feql, Seql, 2, 2, 0,
2083 doc: /* Return t if the two args are the same Lisp object.
2084 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
2085 (Lisp_Object obj1, Lisp_Object obj2)
2087 if (FLOATP (obj1))
2088 return internal_equal (obj1, obj2, 0, 0, Qnil) ? Qt : Qnil;
2089 else
2090 return EQ (obj1, obj2) ? Qt : Qnil;
2093 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
2094 doc: /* Return t if two Lisp objects have similar structure and contents.
2095 They must have the same data type.
2096 Conses are compared by comparing the cars and the cdrs.
2097 Vectors and strings are compared element by element.
2098 Numbers are compared by value, but integers cannot equal floats.
2099 (Use `=' if you want integers and floats to be able to be equal.)
2100 Symbols must match exactly. */)
2101 (register Lisp_Object o1, Lisp_Object o2)
2103 return internal_equal (o1, o2, 0, 0, Qnil) ? Qt : Qnil;
2106 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
2107 doc: /* Return t if two Lisp objects have similar structure and contents.
2108 This is like `equal' except that it compares the text properties
2109 of strings. (`equal' ignores text properties.) */)
2110 (register Lisp_Object o1, Lisp_Object o2)
2112 return internal_equal (o1, o2, 0, 1, Qnil) ? Qt : Qnil;
2115 /* DEPTH is current depth of recursion. Signal an error if it
2116 gets too deep.
2117 PROPS means compare string text properties too. */
2119 static bool
2120 internal_equal (Lisp_Object o1, Lisp_Object o2, int depth, bool props,
2121 Lisp_Object ht)
2123 tail_recurse:
2124 if (depth > 10)
2126 if (depth > 200)
2127 error ("Stack overflow in equal");
2128 if (NILP (ht))
2129 ht = CALLN (Fmake_hash_table, QCtest, Qeq);
2130 switch (XTYPE (o1))
2132 case Lisp_Cons: case Lisp_Misc: case Lisp_Vectorlike:
2134 struct Lisp_Hash_Table *h = XHASH_TABLE (ht);
2135 EMACS_UINT hash;
2136 ptrdiff_t i = hash_lookup (h, o1, &hash);
2137 if (i >= 0)
2138 { /* `o1' was seen already. */
2139 Lisp_Object o2s = HASH_VALUE (h, i);
2140 if (!NILP (Fmemq (o2, o2s)))
2141 return 1;
2142 else
2143 set_hash_value_slot (h, i, Fcons (o2, o2s));
2145 else
2146 hash_put (h, o1, Fcons (o2, Qnil), hash);
2148 default: ;
2152 if (EQ (o1, o2))
2153 return 1;
2154 if (XTYPE (o1) != XTYPE (o2))
2155 return 0;
2157 switch (XTYPE (o1))
2159 case Lisp_Float:
2161 double d1, d2;
2163 d1 = extract_float (o1);
2164 d2 = extract_float (o2);
2165 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2166 though they are not =. */
2167 return d1 == d2 || (d1 != d1 && d2 != d2);
2170 case Lisp_Cons:
2172 FOR_EACH_TAIL (o1)
2174 if (! CONSP (o2))
2175 return false;
2176 if (! internal_equal (XCAR (o1), XCAR (o2), depth + 1, props, ht))
2177 return false;
2178 o2 = XCDR (o2);
2179 if (EQ (XCDR (o1), o2))
2180 return true;
2182 depth++;
2183 goto tail_recurse;
2186 case Lisp_Misc:
2187 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2188 return 0;
2189 if (OVERLAYP (o1))
2191 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2192 depth + 1, props, ht)
2193 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2194 depth + 1, props, ht))
2195 return 0;
2196 o1 = XOVERLAY (o1)->plist;
2197 o2 = XOVERLAY (o2)->plist;
2198 depth++;
2199 goto tail_recurse;
2201 if (MARKERP (o1))
2203 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2204 && (XMARKER (o1)->buffer == 0
2205 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2207 break;
2209 case Lisp_Vectorlike:
2211 register int i;
2212 ptrdiff_t size = ASIZE (o1);
2213 /* Pseudovectors have the type encoded in the size field, so this test
2214 actually checks that the objects have the same type as well as the
2215 same size. */
2216 if (ASIZE (o2) != size)
2217 return 0;
2218 /* Boolvectors are compared much like strings. */
2219 if (BOOL_VECTOR_P (o1))
2221 EMACS_INT size = bool_vector_size (o1);
2222 if (size != bool_vector_size (o2))
2223 return 0;
2224 if (memcmp (bool_vector_data (o1), bool_vector_data (o2),
2225 bool_vector_bytes (size)))
2226 return 0;
2227 return 1;
2229 if (WINDOW_CONFIGURATIONP (o1))
2230 return compare_window_configurations (o1, o2, 0);
2232 /* Aside from them, only true vectors, char-tables, compiled
2233 functions, and fonts (font-spec, font-entity, font-object)
2234 are sensible to compare, so eliminate the others now. */
2235 if (size & PSEUDOVECTOR_FLAG)
2237 if (((size & PVEC_TYPE_MASK) >> PSEUDOVECTOR_AREA_BITS)
2238 < PVEC_COMPILED)
2239 return 0;
2240 size &= PSEUDOVECTOR_SIZE_MASK;
2242 for (i = 0; i < size; i++)
2244 Lisp_Object v1, v2;
2245 v1 = AREF (o1, i);
2246 v2 = AREF (o2, i);
2247 if (!internal_equal (v1, v2, depth + 1, props, ht))
2248 return 0;
2250 return 1;
2252 break;
2254 case Lisp_String:
2255 if (SCHARS (o1) != SCHARS (o2))
2256 return 0;
2257 if (SBYTES (o1) != SBYTES (o2))
2258 return 0;
2259 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2260 return 0;
2261 if (props && !compare_string_intervals (o1, o2))
2262 return 0;
2263 return 1;
2265 default:
2266 break;
2269 return 0;
2273 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2274 doc: /* Store each element of ARRAY with ITEM.
2275 ARRAY is a vector, string, char-table, or bool-vector. */)
2276 (Lisp_Object array, Lisp_Object item)
2278 register ptrdiff_t size, idx;
2280 if (VECTORP (array))
2281 for (idx = 0, size = ASIZE (array); idx < size; idx++)
2282 ASET (array, idx, item);
2283 else if (CHAR_TABLE_P (array))
2285 int i;
2287 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2288 set_char_table_contents (array, i, item);
2289 set_char_table_defalt (array, item);
2291 else if (STRINGP (array))
2293 register unsigned char *p = SDATA (array);
2294 int charval;
2295 CHECK_CHARACTER (item);
2296 charval = XFASTINT (item);
2297 size = SCHARS (array);
2298 if (STRING_MULTIBYTE (array))
2300 unsigned char str[MAX_MULTIBYTE_LENGTH];
2301 int len = CHAR_STRING (charval, str);
2302 ptrdiff_t size_byte = SBYTES (array);
2303 ptrdiff_t product;
2305 if (INT_MULTIPLY_WRAPV (size, len, &product) || product != size_byte)
2306 error ("Attempt to change byte length of a string");
2307 for (idx = 0; idx < size_byte; idx++)
2308 *p++ = str[idx % len];
2310 else
2311 for (idx = 0; idx < size; idx++)
2312 p[idx] = charval;
2314 else if (BOOL_VECTOR_P (array))
2315 return bool_vector_fill (array, item);
2316 else
2317 wrong_type_argument (Qarrayp, array);
2318 return array;
2321 DEFUN ("clear-string", Fclear_string, Sclear_string,
2322 1, 1, 0,
2323 doc: /* Clear the contents of STRING.
2324 This makes STRING unibyte and may change its length. */)
2325 (Lisp_Object string)
2327 ptrdiff_t len;
2328 CHECK_STRING (string);
2329 len = SBYTES (string);
2330 memset (SDATA (string), 0, len);
2331 STRING_SET_CHARS (string, len);
2332 STRING_SET_UNIBYTE (string);
2333 return Qnil;
2336 /* ARGSUSED */
2337 Lisp_Object
2338 nconc2 (Lisp_Object s1, Lisp_Object s2)
2340 return CALLN (Fnconc, s1, s2);
2343 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2344 doc: /* Concatenate any number of lists by altering them.
2345 Only the last argument is not altered, and need not be a list.
2346 usage: (nconc &rest LISTS) */)
2347 (ptrdiff_t nargs, Lisp_Object *args)
2349 Lisp_Object val = Qnil;
2351 for (ptrdiff_t argnum = 0; argnum < nargs; argnum++)
2353 Lisp_Object tem = args[argnum];
2354 if (NILP (tem)) continue;
2356 if (NILP (val))
2357 val = tem;
2359 if (argnum + 1 == nargs) break;
2361 CHECK_CONS (tem);
2363 Lisp_Object tail;
2364 FOR_EACH_TAIL (tem)
2365 tail = tem;
2367 tem = args[argnum + 1];
2368 Fsetcdr (tail, tem);
2369 if (NILP (tem))
2370 args[argnum + 1] = tail;
2373 return val;
2376 /* This is the guts of all mapping functions.
2377 Apply FN to each element of SEQ, one by one, storing the results
2378 into elements of VALS, a C vector of Lisp_Objects. LENI is the
2379 length of VALS, which should also be the length of SEQ. Return the
2380 number of results; although this is normally LENI, it can be less
2381 if SEQ is made shorter as a side effect of FN. */
2383 static EMACS_INT
2384 mapcar1 (EMACS_INT leni, Lisp_Object *vals, Lisp_Object fn, Lisp_Object seq)
2386 Lisp_Object tail, dummy;
2387 EMACS_INT i;
2389 if (VECTORP (seq) || COMPILEDP (seq))
2391 for (i = 0; i < leni; i++)
2393 dummy = call1 (fn, AREF (seq, i));
2394 if (vals)
2395 vals[i] = dummy;
2398 else if (BOOL_VECTOR_P (seq))
2400 for (i = 0; i < leni; i++)
2402 dummy = call1 (fn, bool_vector_ref (seq, i));
2403 if (vals)
2404 vals[i] = dummy;
2407 else if (STRINGP (seq))
2409 ptrdiff_t i_byte;
2411 for (i = 0, i_byte = 0; i < leni;)
2413 int c;
2414 ptrdiff_t i_before = i;
2416 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2417 XSETFASTINT (dummy, c);
2418 dummy = call1 (fn, dummy);
2419 if (vals)
2420 vals[i_before] = dummy;
2423 else /* Must be a list, since Flength did not get an error */
2425 tail = seq;
2426 for (i = 0; i < leni; i++)
2428 if (! CONSP (tail))
2429 return i;
2430 dummy = call1 (fn, XCAR (tail));
2431 if (vals)
2432 vals[i] = dummy;
2433 tail = XCDR (tail);
2437 return leni;
2440 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2441 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2442 In between each pair of results, stick in SEPARATOR. Thus, " " as
2443 SEPARATOR results in spaces between the values returned by FUNCTION.
2444 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2445 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2447 USE_SAFE_ALLOCA;
2448 EMACS_INT leni = XFASTINT (Flength (sequence));
2449 if (CHAR_TABLE_P (sequence))
2450 wrong_type_argument (Qlistp, sequence);
2451 EMACS_INT args_alloc = 2 * leni - 1;
2452 if (args_alloc < 0)
2453 return empty_unibyte_string;
2454 Lisp_Object *args;
2455 SAFE_ALLOCA_LISP (args, args_alloc);
2456 ptrdiff_t nmapped = mapcar1 (leni, args, function, sequence);
2457 ptrdiff_t nargs = 2 * nmapped - 1;
2459 for (ptrdiff_t i = nmapped - 1; i > 0; i--)
2460 args[i + i] = args[i];
2462 for (ptrdiff_t i = 1; i < nargs; i += 2)
2463 args[i] = separator;
2465 Lisp_Object ret = Fconcat (nargs, args);
2466 SAFE_FREE ();
2467 return ret;
2470 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2471 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2472 The result is a list just as long as SEQUENCE.
2473 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2474 (Lisp_Object function, Lisp_Object sequence)
2476 USE_SAFE_ALLOCA;
2477 EMACS_INT leni = XFASTINT (Flength (sequence));
2478 if (CHAR_TABLE_P (sequence))
2479 wrong_type_argument (Qlistp, sequence);
2480 Lisp_Object *args;
2481 SAFE_ALLOCA_LISP (args, leni);
2482 ptrdiff_t nmapped = mapcar1 (leni, args, function, sequence);
2483 Lisp_Object ret = Flist (nmapped, args);
2484 SAFE_FREE ();
2485 return ret;
2488 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2489 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2490 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2491 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2492 (Lisp_Object function, Lisp_Object sequence)
2494 register EMACS_INT leni;
2496 leni = XFASTINT (Flength (sequence));
2497 if (CHAR_TABLE_P (sequence))
2498 wrong_type_argument (Qlistp, sequence);
2499 mapcar1 (leni, 0, function, sequence);
2501 return sequence;
2504 DEFUN ("mapcan", Fmapcan, Smapcan, 2, 2, 0,
2505 doc: /* Apply FUNCTION to each element of SEQUENCE, and concatenate
2506 the results by altering them (using `nconc').
2507 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2508 (Lisp_Object function, Lisp_Object sequence)
2510 USE_SAFE_ALLOCA;
2511 EMACS_INT leni = XFASTINT (Flength (sequence));
2512 if (CHAR_TABLE_P (sequence))
2513 wrong_type_argument (Qlistp, sequence);
2514 Lisp_Object *args;
2515 SAFE_ALLOCA_LISP (args, leni);
2516 ptrdiff_t nmapped = mapcar1 (leni, args, function, sequence);
2517 Lisp_Object ret = Fnconc (nmapped, args);
2518 SAFE_FREE ();
2519 return ret;
2522 /* This is how C code calls `yes-or-no-p' and allows the user
2523 to redefine it. */
2525 Lisp_Object
2526 do_yes_or_no_p (Lisp_Object prompt)
2528 return call1 (intern ("yes-or-no-p"), prompt);
2531 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2532 doc: /* Ask user a yes-or-no question.
2533 Return t if answer is yes, and nil if the answer is no.
2534 PROMPT is the string to display to ask the question. It should end in
2535 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2537 The user must confirm the answer with RET, and can edit it until it
2538 has been confirmed.
2540 If dialog boxes are supported, a dialog box will be used
2541 if `last-nonmenu-event' is nil, and `use-dialog-box' is non-nil. */)
2542 (Lisp_Object prompt)
2544 Lisp_Object ans;
2546 CHECK_STRING (prompt);
2548 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2549 && use_dialog_box && ! NILP (last_input_event))
2551 Lisp_Object pane, menu, obj;
2552 redisplay_preserve_echo_area (4);
2553 pane = list2 (Fcons (build_string ("Yes"), Qt),
2554 Fcons (build_string ("No"), Qnil));
2555 menu = Fcons (prompt, pane);
2556 obj = Fx_popup_dialog (Qt, menu, Qnil);
2557 return obj;
2560 AUTO_STRING (yes_or_no, "(yes or no) ");
2561 prompt = CALLN (Fconcat, prompt, yes_or_no);
2563 while (1)
2565 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2566 Qyes_or_no_p_history, Qnil,
2567 Qnil));
2568 if (SCHARS (ans) == 3 && !strcmp (SSDATA (ans), "yes"))
2569 return Qt;
2570 if (SCHARS (ans) == 2 && !strcmp (SSDATA (ans), "no"))
2571 return Qnil;
2573 Fding (Qnil);
2574 Fdiscard_input ();
2575 message1 ("Please answer yes or no.");
2576 Fsleep_for (make_number (2), Qnil);
2580 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2581 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2583 Each of the three load averages is multiplied by 100, then converted
2584 to integer.
2586 When USE-FLOATS is non-nil, floats will be used instead of integers.
2587 These floats are not multiplied by 100.
2589 If the 5-minute or 15-minute load averages are not available, return a
2590 shortened list, containing only those averages which are available.
2592 An error is thrown if the load average can't be obtained. In some
2593 cases making it work would require Emacs being installed setuid or
2594 setgid so that it can read kernel information, and that usually isn't
2595 advisable. */)
2596 (Lisp_Object use_floats)
2598 double load_ave[3];
2599 int loads = getloadavg (load_ave, 3);
2600 Lisp_Object ret = Qnil;
2602 if (loads < 0)
2603 error ("load-average not implemented for this operating system");
2605 while (loads-- > 0)
2607 Lisp_Object load = (NILP (use_floats)
2608 ? make_number (100.0 * load_ave[loads])
2609 : make_float (load_ave[loads]));
2610 ret = Fcons (load, ret);
2613 return ret;
2616 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2617 doc: /* Return t if FEATURE is present in this Emacs.
2619 Use this to conditionalize execution of lisp code based on the
2620 presence or absence of Emacs or environment extensions.
2621 Use `provide' to declare that a feature is available. This function
2622 looks at the value of the variable `features'. The optional argument
2623 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2624 (Lisp_Object feature, Lisp_Object subfeature)
2626 register Lisp_Object tem;
2627 CHECK_SYMBOL (feature);
2628 tem = Fmemq (feature, Vfeatures);
2629 if (!NILP (tem) && !NILP (subfeature))
2630 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2631 return (NILP (tem)) ? Qnil : Qt;
2634 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2635 doc: /* Announce that FEATURE is a feature of the current Emacs.
2636 The optional argument SUBFEATURES should be a list of symbols listing
2637 particular subfeatures supported in this version of FEATURE. */)
2638 (Lisp_Object feature, Lisp_Object subfeatures)
2640 register Lisp_Object tem;
2641 CHECK_SYMBOL (feature);
2642 CHECK_LIST (subfeatures);
2643 if (!NILP (Vautoload_queue))
2644 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2645 Vautoload_queue);
2646 tem = Fmemq (feature, Vfeatures);
2647 if (NILP (tem))
2648 Vfeatures = Fcons (feature, Vfeatures);
2649 if (!NILP (subfeatures))
2650 Fput (feature, Qsubfeatures, subfeatures);
2651 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2653 /* Run any load-hooks for this file. */
2654 tem = Fassq (feature, Vafter_load_alist);
2655 if (CONSP (tem))
2656 Fmapc (Qfuncall, XCDR (tem));
2658 return feature;
2661 /* `require' and its subroutines. */
2663 /* List of features currently being require'd, innermost first. */
2665 static Lisp_Object require_nesting_list;
2667 static void
2668 require_unwind (Lisp_Object old_value)
2670 require_nesting_list = old_value;
2673 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2674 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2675 If FEATURE is not a member of the list `features', then the feature is
2676 not loaded; so load the file FILENAME.
2678 If FILENAME is omitted, the printname of FEATURE is used as the file
2679 name, and `load' will try to load this name appended with the suffix
2680 `.elc', `.el', or the system-dependent suffix for dynamic module
2681 files, in that order. The name without appended suffix will not be
2682 used. See `get-load-suffixes' for the complete list of suffixes.
2684 The directories in `load-path' are searched when trying to find the
2685 file name.
2687 If the optional third argument NOERROR is non-nil, then return nil if
2688 the file is not found instead of signaling an error. Normally the
2689 return value is FEATURE.
2691 The normal messages at start and end of loading FILENAME are
2692 suppressed. */)
2693 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2695 Lisp_Object tem;
2696 bool from_file = load_in_progress;
2698 CHECK_SYMBOL (feature);
2700 /* Record the presence of `require' in this file
2701 even if the feature specified is already loaded.
2702 But not more than once in any file,
2703 and not when we aren't loading or reading from a file. */
2704 if (!from_file)
2705 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2706 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2707 from_file = 1;
2709 if (from_file)
2711 tem = Fcons (Qrequire, feature);
2712 if (NILP (Fmember (tem, Vcurrent_load_list)))
2713 LOADHIST_ATTACH (tem);
2715 tem = Fmemq (feature, Vfeatures);
2717 if (NILP (tem))
2719 ptrdiff_t count = SPECPDL_INDEX ();
2720 int nesting = 0;
2722 /* This is to make sure that loadup.el gives a clear picture
2723 of what files are preloaded and when. */
2724 if (! NILP (Vpurify_flag))
2725 error ("(require %s) while preparing to dump",
2726 SDATA (SYMBOL_NAME (feature)));
2728 /* A certain amount of recursive `require' is legitimate,
2729 but if we require the same feature recursively 3 times,
2730 signal an error. */
2731 tem = require_nesting_list;
2732 while (! NILP (tem))
2734 if (! NILP (Fequal (feature, XCAR (tem))))
2735 nesting++;
2736 tem = XCDR (tem);
2738 if (nesting > 3)
2739 error ("Recursive `require' for feature `%s'",
2740 SDATA (SYMBOL_NAME (feature)));
2742 /* Update the list for any nested `require's that occur. */
2743 record_unwind_protect (require_unwind, require_nesting_list);
2744 require_nesting_list = Fcons (feature, require_nesting_list);
2746 /* Value saved here is to be restored into Vautoload_queue */
2747 record_unwind_protect (un_autoload, Vautoload_queue);
2748 Vautoload_queue = Qt;
2750 /* Load the file. */
2751 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2752 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2754 /* If load failed entirely, return nil. */
2755 if (NILP (tem))
2756 return unbind_to (count, Qnil);
2758 tem = Fmemq (feature, Vfeatures);
2759 if (NILP (tem))
2760 error ("Required feature `%s' was not provided",
2761 SDATA (SYMBOL_NAME (feature)));
2763 /* Once loading finishes, don't undo it. */
2764 Vautoload_queue = Qt;
2765 feature = unbind_to (count, feature);
2768 return feature;
2771 /* Primitives for work of the "widget" library.
2772 In an ideal world, this section would not have been necessary.
2773 However, lisp function calls being as slow as they are, it turns
2774 out that some functions in the widget library (wid-edit.el) are the
2775 bottleneck of Widget operation. Here is their translation to C,
2776 for the sole reason of efficiency. */
2778 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2779 doc: /* Return non-nil if PLIST has the property PROP.
2780 PLIST is a property list, which is a list of the form
2781 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol.
2782 Unlike `plist-get', this allows you to distinguish between a missing
2783 property and a property with the value nil.
2784 The value is actually the tail of PLIST whose car is PROP. */)
2785 (Lisp_Object plist, Lisp_Object prop)
2787 Lisp_Object tail = plist;
2788 FOR_EACH_TAIL (tail)
2790 if (EQ (XCAR (tail), prop))
2791 return tail;
2792 tail = XCDR (tail);
2793 if (! CONSP (tail))
2794 break;
2795 if (EQ (tail, li.tortoise))
2796 circular_list (tail);
2798 CHECK_LIST_END (tail, plist);
2799 return Qnil;
2802 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2803 doc: /* In WIDGET, set PROPERTY to VALUE.
2804 The value can later be retrieved with `widget-get'. */)
2805 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2807 CHECK_CONS (widget);
2808 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
2809 return value;
2812 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
2813 doc: /* In WIDGET, get the value of PROPERTY.
2814 The value could either be specified when the widget was created, or
2815 later with `widget-put'. */)
2816 (Lisp_Object widget, Lisp_Object property)
2818 Lisp_Object tmp;
2820 while (1)
2822 if (NILP (widget))
2823 return Qnil;
2824 CHECK_CONS (widget);
2825 tmp = Fplist_member (XCDR (widget), property);
2826 if (CONSP (tmp))
2828 tmp = XCDR (tmp);
2829 return CAR (tmp);
2831 tmp = XCAR (widget);
2832 if (NILP (tmp))
2833 return Qnil;
2834 widget = Fget (tmp, Qwidget_type);
2838 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
2839 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2840 ARGS are passed as extra arguments to the function.
2841 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2842 (ptrdiff_t nargs, Lisp_Object *args)
2844 Lisp_Object widget = args[0];
2845 Lisp_Object property = args[1];
2846 Lisp_Object propval = Fwidget_get (widget, property);
2847 Lisp_Object trailing_args = Flist (nargs - 2, args + 2);
2848 Lisp_Object result = CALLN (Fapply, propval, widget, trailing_args);
2849 return result;
2852 #ifdef HAVE_LANGINFO_CODESET
2853 #include <langinfo.h>
2854 #endif
2856 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
2857 doc: /* Access locale data ITEM for the current C locale, if available.
2858 ITEM should be one of the following:
2860 `codeset', returning the character set as a string (locale item CODESET);
2862 `days', returning a 7-element vector of day names (locale items DAY_n);
2864 `months', returning a 12-element vector of month names (locale items MON_n);
2866 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
2867 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
2869 If the system can't provide such information through a call to
2870 `nl_langinfo', or if ITEM isn't from the list above, return nil.
2872 See also Info node `(libc)Locales'.
2874 The data read from the system are decoded using `locale-coding-system'. */)
2875 (Lisp_Object item)
2877 char *str = NULL;
2878 #ifdef HAVE_LANGINFO_CODESET
2879 if (EQ (item, Qcodeset))
2881 str = nl_langinfo (CODESET);
2882 return build_string (str);
2884 #ifdef DAY_1
2885 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
2887 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
2888 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
2889 int i;
2890 synchronize_system_time_locale ();
2891 for (i = 0; i < 7; i++)
2893 str = nl_langinfo (days[i]);
2894 AUTO_STRING (val, str);
2895 /* Fixme: Is this coding system necessarily right, even if
2896 it is consistent with CODESET? If not, what to do? */
2897 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
2898 0));
2900 return v;
2902 #endif /* DAY_1 */
2903 #ifdef MON_1
2904 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
2906 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
2907 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
2908 MON_8, MON_9, MON_10, MON_11, MON_12};
2909 int i;
2910 synchronize_system_time_locale ();
2911 for (i = 0; i < 12; i++)
2913 str = nl_langinfo (months[i]);
2914 AUTO_STRING (val, str);
2915 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
2916 0));
2918 return v;
2920 #endif /* MON_1 */
2921 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
2922 but is in the locale files. This could be used by ps-print. */
2923 #ifdef PAPER_WIDTH
2924 else if (EQ (item, Qpaper))
2925 return list2i (nl_langinfo (PAPER_WIDTH), nl_langinfo (PAPER_HEIGHT));
2926 #endif /* PAPER_WIDTH */
2927 #endif /* HAVE_LANGINFO_CODESET*/
2928 return Qnil;
2931 /* base64 encode/decode functions (RFC 2045).
2932 Based on code from GNU recode. */
2934 #define MIME_LINE_LENGTH 76
2936 #define IS_ASCII(Character) \
2937 ((Character) < 128)
2938 #define IS_BASE64(Character) \
2939 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
2940 #define IS_BASE64_IGNORABLE(Character) \
2941 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
2942 || (Character) == '\f' || (Character) == '\r')
2944 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
2945 character or return retval if there are no characters left to
2946 process. */
2947 #define READ_QUADRUPLET_BYTE(retval) \
2948 do \
2950 if (i == length) \
2952 if (nchars_return) \
2953 *nchars_return = nchars; \
2954 return (retval); \
2956 c = from[i++]; \
2958 while (IS_BASE64_IGNORABLE (c))
2960 /* Table of characters coding the 64 values. */
2961 static const char base64_value_to_char[64] =
2963 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
2964 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
2965 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
2966 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
2967 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
2968 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
2969 '8', '9', '+', '/' /* 60-63 */
2972 /* Table of base64 values for first 128 characters. */
2973 static const short base64_char_to_value[128] =
2975 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
2976 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
2977 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
2978 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
2979 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
2980 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
2981 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
2982 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
2983 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
2984 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
2985 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
2986 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
2987 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
2990 /* The following diagram shows the logical steps by which three octets
2991 get transformed into four base64 characters.
2993 .--------. .--------. .--------.
2994 |aaaaaabb| |bbbbcccc| |ccdddddd|
2995 `--------' `--------' `--------'
2996 6 2 4 4 2 6
2997 .--------+--------+--------+--------.
2998 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
2999 `--------+--------+--------+--------'
3001 .--------+--------+--------+--------.
3002 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
3003 `--------+--------+--------+--------'
3005 The octets are divided into 6 bit chunks, which are then encoded into
3006 base64 characters. */
3009 static ptrdiff_t base64_encode_1 (const char *, char *, ptrdiff_t, bool, bool);
3010 static ptrdiff_t base64_decode_1 (const char *, char *, ptrdiff_t, bool,
3011 ptrdiff_t *);
3013 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
3014 2, 3, "r",
3015 doc: /* Base64-encode the region between BEG and END.
3016 Return the length of the encoded text.
3017 Optional third argument NO-LINE-BREAK means do not break long lines
3018 into shorter lines. */)
3019 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
3021 char *encoded;
3022 ptrdiff_t allength, length;
3023 ptrdiff_t ibeg, iend, encoded_length;
3024 ptrdiff_t old_pos = PT;
3025 USE_SAFE_ALLOCA;
3027 validate_region (&beg, &end);
3029 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3030 iend = CHAR_TO_BYTE (XFASTINT (end));
3031 move_gap_both (XFASTINT (beg), ibeg);
3033 /* We need to allocate enough room for encoding the text.
3034 We need 33 1/3% more space, plus a newline every 76
3035 characters, and then we round up. */
3036 length = iend - ibeg;
3037 allength = length + length/3 + 1;
3038 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3040 encoded = SAFE_ALLOCA (allength);
3041 encoded_length = base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg),
3042 encoded, length, NILP (no_line_break),
3043 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
3044 if (encoded_length > allength)
3045 emacs_abort ();
3047 if (encoded_length < 0)
3049 /* The encoding wasn't possible. */
3050 SAFE_FREE ();
3051 error ("Multibyte character in data for base64 encoding");
3054 /* Now we have encoded the region, so we insert the new contents
3055 and delete the old. (Insert first in order to preserve markers.) */
3056 SET_PT_BOTH (XFASTINT (beg), ibeg);
3057 insert (encoded, encoded_length);
3058 SAFE_FREE ();
3059 del_range_byte (ibeg + encoded_length, iend + encoded_length);
3061 /* If point was outside of the region, restore it exactly; else just
3062 move to the beginning of the region. */
3063 if (old_pos >= XFASTINT (end))
3064 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
3065 else if (old_pos > XFASTINT (beg))
3066 old_pos = XFASTINT (beg);
3067 SET_PT (old_pos);
3069 /* We return the length of the encoded text. */
3070 return make_number (encoded_length);
3073 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
3074 1, 2, 0,
3075 doc: /* Base64-encode STRING and return the result.
3076 Optional second argument NO-LINE-BREAK means do not break long lines
3077 into shorter lines. */)
3078 (Lisp_Object string, Lisp_Object no_line_break)
3080 ptrdiff_t allength, length, encoded_length;
3081 char *encoded;
3082 Lisp_Object encoded_string;
3083 USE_SAFE_ALLOCA;
3085 CHECK_STRING (string);
3087 /* We need to allocate enough room for encoding the text.
3088 We need 33 1/3% more space, plus a newline every 76
3089 characters, and then we round up. */
3090 length = SBYTES (string);
3091 allength = length + length/3 + 1;
3092 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3094 /* We need to allocate enough room for decoding the text. */
3095 encoded = SAFE_ALLOCA (allength);
3097 encoded_length = base64_encode_1 (SSDATA (string),
3098 encoded, length, NILP (no_line_break),
3099 STRING_MULTIBYTE (string));
3100 if (encoded_length > allength)
3101 emacs_abort ();
3103 if (encoded_length < 0)
3105 /* The encoding wasn't possible. */
3106 error ("Multibyte character in data for base64 encoding");
3109 encoded_string = make_unibyte_string (encoded, encoded_length);
3110 SAFE_FREE ();
3112 return encoded_string;
3115 static ptrdiff_t
3116 base64_encode_1 (const char *from, char *to, ptrdiff_t length,
3117 bool line_break, bool multibyte)
3119 int counter = 0;
3120 ptrdiff_t i = 0;
3121 char *e = to;
3122 int c;
3123 unsigned int value;
3124 int bytes;
3126 while (i < length)
3128 if (multibyte)
3130 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3131 if (CHAR_BYTE8_P (c))
3132 c = CHAR_TO_BYTE8 (c);
3133 else if (c >= 256)
3134 return -1;
3135 i += bytes;
3137 else
3138 c = from[i++];
3140 /* Wrap line every 76 characters. */
3142 if (line_break)
3144 if (counter < MIME_LINE_LENGTH / 4)
3145 counter++;
3146 else
3148 *e++ = '\n';
3149 counter = 1;
3153 /* Process first byte of a triplet. */
3155 *e++ = base64_value_to_char[0x3f & c >> 2];
3156 value = (0x03 & c) << 4;
3158 /* Process second byte of a triplet. */
3160 if (i == length)
3162 *e++ = base64_value_to_char[value];
3163 *e++ = '=';
3164 *e++ = '=';
3165 break;
3168 if (multibyte)
3170 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3171 if (CHAR_BYTE8_P (c))
3172 c = CHAR_TO_BYTE8 (c);
3173 else if (c >= 256)
3174 return -1;
3175 i += bytes;
3177 else
3178 c = from[i++];
3180 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3181 value = (0x0f & c) << 2;
3183 /* Process third byte of a triplet. */
3185 if (i == length)
3187 *e++ = base64_value_to_char[value];
3188 *e++ = '=';
3189 break;
3192 if (multibyte)
3194 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3195 if (CHAR_BYTE8_P (c))
3196 c = CHAR_TO_BYTE8 (c);
3197 else if (c >= 256)
3198 return -1;
3199 i += bytes;
3201 else
3202 c = from[i++];
3204 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3205 *e++ = base64_value_to_char[0x3f & c];
3208 return e - to;
3212 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3213 2, 2, "r",
3214 doc: /* Base64-decode the region between BEG and END.
3215 Return the length of the decoded text.
3216 If the region can't be decoded, signal an error and don't modify the buffer. */)
3217 (Lisp_Object beg, Lisp_Object end)
3219 ptrdiff_t ibeg, iend, length, allength;
3220 char *decoded;
3221 ptrdiff_t old_pos = PT;
3222 ptrdiff_t decoded_length;
3223 ptrdiff_t inserted_chars;
3224 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3225 USE_SAFE_ALLOCA;
3227 validate_region (&beg, &end);
3229 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3230 iend = CHAR_TO_BYTE (XFASTINT (end));
3232 length = iend - ibeg;
3234 /* We need to allocate enough room for decoding the text. If we are
3235 working on a multibyte buffer, each decoded code may occupy at
3236 most two bytes. */
3237 allength = multibyte ? length * 2 : length;
3238 decoded = SAFE_ALLOCA (allength);
3240 move_gap_both (XFASTINT (beg), ibeg);
3241 decoded_length = base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg),
3242 decoded, length,
3243 multibyte, &inserted_chars);
3244 if (decoded_length > allength)
3245 emacs_abort ();
3247 if (decoded_length < 0)
3249 /* The decoding wasn't possible. */
3250 error ("Invalid base64 data");
3253 /* Now we have decoded the region, so we insert the new contents
3254 and delete the old. (Insert first in order to preserve markers.) */
3255 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3256 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3257 SAFE_FREE ();
3259 /* Delete the original text. */
3260 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3261 iend + decoded_length, 1);
3263 /* If point was outside of the region, restore it exactly; else just
3264 move to the beginning of the region. */
3265 if (old_pos >= XFASTINT (end))
3266 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3267 else if (old_pos > XFASTINT (beg))
3268 old_pos = XFASTINT (beg);
3269 SET_PT (old_pos > ZV ? ZV : old_pos);
3271 return make_number (inserted_chars);
3274 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3275 1, 1, 0,
3276 doc: /* Base64-decode STRING and return the result. */)
3277 (Lisp_Object string)
3279 char *decoded;
3280 ptrdiff_t length, decoded_length;
3281 Lisp_Object decoded_string;
3282 USE_SAFE_ALLOCA;
3284 CHECK_STRING (string);
3286 length = SBYTES (string);
3287 /* We need to allocate enough room for decoding the text. */
3288 decoded = SAFE_ALLOCA (length);
3290 /* The decoded result should be unibyte. */
3291 decoded_length = base64_decode_1 (SSDATA (string), decoded, length,
3292 0, NULL);
3293 if (decoded_length > length)
3294 emacs_abort ();
3295 else if (decoded_length >= 0)
3296 decoded_string = make_unibyte_string (decoded, decoded_length);
3297 else
3298 decoded_string = Qnil;
3300 SAFE_FREE ();
3301 if (!STRINGP (decoded_string))
3302 error ("Invalid base64 data");
3304 return decoded_string;
3307 /* Base64-decode the data at FROM of LENGTH bytes into TO. If
3308 MULTIBYTE, the decoded result should be in multibyte
3309 form. If NCHARS_RETURN is not NULL, store the number of produced
3310 characters in *NCHARS_RETURN. */
3312 static ptrdiff_t
3313 base64_decode_1 (const char *from, char *to, ptrdiff_t length,
3314 bool multibyte, ptrdiff_t *nchars_return)
3316 ptrdiff_t i = 0; /* Used inside READ_QUADRUPLET_BYTE */
3317 char *e = to;
3318 unsigned char c;
3319 unsigned long value;
3320 ptrdiff_t nchars = 0;
3322 while (1)
3324 /* Process first byte of a quadruplet. */
3326 READ_QUADRUPLET_BYTE (e-to);
3328 if (!IS_BASE64 (c))
3329 return -1;
3330 value = base64_char_to_value[c] << 18;
3332 /* Process second byte of a quadruplet. */
3334 READ_QUADRUPLET_BYTE (-1);
3336 if (!IS_BASE64 (c))
3337 return -1;
3338 value |= base64_char_to_value[c] << 12;
3340 c = (unsigned char) (value >> 16);
3341 if (multibyte && c >= 128)
3342 e += BYTE8_STRING (c, e);
3343 else
3344 *e++ = c;
3345 nchars++;
3347 /* Process third byte of a quadruplet. */
3349 READ_QUADRUPLET_BYTE (-1);
3351 if (c == '=')
3353 READ_QUADRUPLET_BYTE (-1);
3355 if (c != '=')
3356 return -1;
3357 continue;
3360 if (!IS_BASE64 (c))
3361 return -1;
3362 value |= base64_char_to_value[c] << 6;
3364 c = (unsigned char) (0xff & value >> 8);
3365 if (multibyte && c >= 128)
3366 e += BYTE8_STRING (c, e);
3367 else
3368 *e++ = c;
3369 nchars++;
3371 /* Process fourth byte of a quadruplet. */
3373 READ_QUADRUPLET_BYTE (-1);
3375 if (c == '=')
3376 continue;
3378 if (!IS_BASE64 (c))
3379 return -1;
3380 value |= base64_char_to_value[c];
3382 c = (unsigned char) (0xff & value);
3383 if (multibyte && c >= 128)
3384 e += BYTE8_STRING (c, e);
3385 else
3386 *e++ = c;
3387 nchars++;
3393 /***********************************************************************
3394 ***** *****
3395 ***** Hash Tables *****
3396 ***** *****
3397 ***********************************************************************/
3399 /* Implemented by gerd@gnu.org. This hash table implementation was
3400 inspired by CMUCL hash tables. */
3402 /* Ideas:
3404 1. For small tables, association lists are probably faster than
3405 hash tables because they have lower overhead.
3407 For uses of hash tables where the O(1) behavior of table
3408 operations is not a requirement, it might therefore be a good idea
3409 not to hash. Instead, we could just do a linear search in the
3410 key_and_value vector of the hash table. This could be done
3411 if a `:linear-search t' argument is given to make-hash-table. */
3414 /* The list of all weak hash tables. Don't staticpro this one. */
3416 static struct Lisp_Hash_Table *weak_hash_tables;
3419 /***********************************************************************
3420 Utilities
3421 ***********************************************************************/
3423 static void
3424 CHECK_HASH_TABLE (Lisp_Object x)
3426 CHECK_TYPE (HASH_TABLE_P (x), Qhash_table_p, x);
3429 static void
3430 set_hash_key_and_value (struct Lisp_Hash_Table *h, Lisp_Object key_and_value)
3432 h->key_and_value = key_and_value;
3434 static void
3435 set_hash_next (struct Lisp_Hash_Table *h, Lisp_Object next)
3437 h->next = next;
3439 static void
3440 set_hash_next_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3442 gc_aset (h->next, idx, val);
3444 static void
3445 set_hash_hash (struct Lisp_Hash_Table *h, Lisp_Object hash)
3447 h->hash = hash;
3449 static void
3450 set_hash_hash_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3452 gc_aset (h->hash, idx, val);
3454 static void
3455 set_hash_index (struct Lisp_Hash_Table *h, Lisp_Object index)
3457 h->index = index;
3459 static void
3460 set_hash_index_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3462 gc_aset (h->index, idx, val);
3465 /* If OBJ is a Lisp hash table, return a pointer to its struct
3466 Lisp_Hash_Table. Otherwise, signal an error. */
3468 static struct Lisp_Hash_Table *
3469 check_hash_table (Lisp_Object obj)
3471 CHECK_HASH_TABLE (obj);
3472 return XHASH_TABLE (obj);
3476 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3477 number. A number is "almost" a prime number if it is not divisible
3478 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3480 EMACS_INT
3481 next_almost_prime (EMACS_INT n)
3483 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
3484 for (n |= 1; ; n += 2)
3485 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0)
3486 return n;
3490 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3491 which USED[I] is non-zero. If found at index I in ARGS, set
3492 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3493 0. This function is used to extract a keyword/argument pair from
3494 a DEFUN parameter list. */
3496 static ptrdiff_t
3497 get_key_arg (Lisp_Object key, ptrdiff_t nargs, Lisp_Object *args, char *used)
3499 ptrdiff_t i;
3501 for (i = 1; i < nargs; i++)
3502 if (!used[i - 1] && EQ (args[i - 1], key))
3504 used[i - 1] = 1;
3505 used[i] = 1;
3506 return i;
3509 return 0;
3513 /* Return a Lisp vector which has the same contents as VEC but has
3514 at least INCR_MIN more entries, where INCR_MIN is positive.
3515 If NITEMS_MAX is not -1, do not grow the vector to be any larger
3516 than NITEMS_MAX. Entries in the resulting
3517 vector that are not copied from VEC are set to nil. */
3519 Lisp_Object
3520 larger_vector (Lisp_Object vec, ptrdiff_t incr_min, ptrdiff_t nitems_max)
3522 struct Lisp_Vector *v;
3523 ptrdiff_t incr, incr_max, old_size, new_size;
3524 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / sizeof *v->contents;
3525 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
3526 ? nitems_max : C_language_max);
3527 eassert (VECTORP (vec));
3528 eassert (0 < incr_min && -1 <= nitems_max);
3529 old_size = ASIZE (vec);
3530 incr_max = n_max - old_size;
3531 incr = max (incr_min, min (old_size >> 1, incr_max));
3532 if (incr_max < incr)
3533 memory_full (SIZE_MAX);
3534 new_size = old_size + incr;
3535 v = allocate_vector (new_size);
3536 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3537 memclear (v->contents + old_size, incr * word_size);
3538 XSETVECTOR (vec, v);
3539 return vec;
3543 /***********************************************************************
3544 Low-level Functions
3545 ***********************************************************************/
3547 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3548 HASH2 in hash table H using `eql'. Value is true if KEY1 and
3549 KEY2 are the same. */
3551 static bool
3552 cmpfn_eql (struct hash_table_test *ht,
3553 Lisp_Object key1,
3554 Lisp_Object key2)
3556 return (FLOATP (key1)
3557 && FLOATP (key2)
3558 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3562 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3563 HASH2 in hash table H using `equal'. Value is true if KEY1 and
3564 KEY2 are the same. */
3566 static bool
3567 cmpfn_equal (struct hash_table_test *ht,
3568 Lisp_Object key1,
3569 Lisp_Object key2)
3571 return !NILP (Fequal (key1, key2));
3575 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3576 HASH2 in hash table H using H->user_cmp_function. Value is true
3577 if KEY1 and KEY2 are the same. */
3579 static bool
3580 cmpfn_user_defined (struct hash_table_test *ht,
3581 Lisp_Object key1,
3582 Lisp_Object key2)
3584 return !NILP (call2 (ht->user_cmp_function, key1, key2));
3587 /* Value is a hash code for KEY for use in hash table H which uses
3588 `eq' to compare keys. The hash code returned is guaranteed to fit
3589 in a Lisp integer. */
3591 static EMACS_UINT
3592 hashfn_eq (struct hash_table_test *ht, Lisp_Object key)
3594 return XHASH (key) ^ XTYPE (key);
3597 /* Value is a hash code for KEY for use in hash table H which uses
3598 `equal' to compare keys. The hash code returned is guaranteed to fit
3599 in a Lisp integer. */
3601 static EMACS_UINT
3602 hashfn_equal (struct hash_table_test *ht, Lisp_Object key)
3604 return sxhash (key, 0);
3607 /* Value is a hash code for KEY for use in hash table H which uses
3608 `eql' to compare keys. The hash code returned is guaranteed to fit
3609 in a Lisp integer. */
3611 static EMACS_UINT
3612 hashfn_eql (struct hash_table_test *ht, Lisp_Object key)
3614 return FLOATP (key) ? hashfn_equal (ht, key) : hashfn_eq (ht, key);
3617 /* Value is a hash code for KEY for use in hash table H which uses as
3618 user-defined function to compare keys. The hash code returned is
3619 guaranteed to fit in a Lisp integer. */
3621 static EMACS_UINT
3622 hashfn_user_defined (struct hash_table_test *ht, Lisp_Object key)
3624 Lisp_Object hash = call1 (ht->user_hash_function, key);
3625 return hashfn_eq (ht, hash);
3628 struct hash_table_test const
3629 hashtest_eq = { LISPSYM_INITIALLY (Qeq), LISPSYM_INITIALLY (Qnil),
3630 LISPSYM_INITIALLY (Qnil), 0, hashfn_eq },
3631 hashtest_eql = { LISPSYM_INITIALLY (Qeql), LISPSYM_INITIALLY (Qnil),
3632 LISPSYM_INITIALLY (Qnil), cmpfn_eql, hashfn_eql },
3633 hashtest_equal = { LISPSYM_INITIALLY (Qequal), LISPSYM_INITIALLY (Qnil),
3634 LISPSYM_INITIALLY (Qnil), cmpfn_equal, hashfn_equal };
3636 /* Allocate basically initialized hash table. */
3638 static struct Lisp_Hash_Table *
3639 allocate_hash_table (void)
3641 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table,
3642 count, PVEC_HASH_TABLE);
3645 /* An upper bound on the size of a hash table index. It must fit in
3646 ptrdiff_t and be a valid Emacs fixnum. */
3647 #define INDEX_SIZE_BOUND \
3648 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, PTRDIFF_MAX / word_size))
3650 /* Create and initialize a new hash table.
3652 TEST specifies the test the hash table will use to compare keys.
3653 It must be either one of the predefined tests `eq', `eql' or
3654 `equal' or a symbol denoting a user-defined test named TEST with
3655 test and hash functions USER_TEST and USER_HASH.
3657 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3659 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3660 new size when it becomes full is computed by adding REHASH_SIZE to
3661 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3662 table's new size is computed by multiplying its old size with
3663 REHASH_SIZE.
3665 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3666 be resized when the ratio of (number of entries in the table) /
3667 (table size) is >= REHASH_THRESHOLD.
3669 WEAK specifies the weakness of the table. If non-nil, it must be
3670 one of the symbols `key', `value', `key-or-value', or `key-and-value'.
3672 If PURECOPY is non-nil, the table can be copied to pure storage via
3673 `purecopy' when Emacs is being dumped. Such tables can no longer be
3674 changed after purecopy. */
3676 Lisp_Object
3677 make_hash_table (struct hash_table_test test,
3678 Lisp_Object size, Lisp_Object rehash_size,
3679 double rehash_threshold, Lisp_Object weak,
3680 bool pure)
3682 struct Lisp_Hash_Table *h;
3683 Lisp_Object table;
3684 EMACS_INT index_size, sz;
3685 ptrdiff_t i;
3686 double index_float;
3688 /* Preconditions. */
3689 eassert (SYMBOLP (test.name));
3690 eassert (INTEGERP (size) && XINT (size) >= 0);
3691 eassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3692 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size)));
3693 eassert (0 < rehash_threshold && rehash_threshold <= 1.0);
3695 if (XFASTINT (size) == 0)
3696 size = make_number (1);
3698 sz = XFASTINT (size);
3699 index_float = sz / rehash_threshold;
3700 index_size = (index_float < INDEX_SIZE_BOUND + 1
3701 ? next_almost_prime (index_float)
3702 : INDEX_SIZE_BOUND + 1);
3703 if (INDEX_SIZE_BOUND < max (index_size, 2 * sz))
3704 error ("Hash table too large");
3706 /* Allocate a table and initialize it. */
3707 h = allocate_hash_table ();
3709 /* Initialize hash table slots. */
3710 h->test = test;
3711 h->weak = weak;
3712 h->rehash_threshold = rehash_threshold;
3713 h->rehash_size = rehash_size;
3714 h->count = 0;
3715 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
3716 h->hash = Fmake_vector (size, Qnil);
3717 h->next = Fmake_vector (size, Qnil);
3718 h->index = Fmake_vector (make_number (index_size), Qnil);
3719 h->pure = pure;
3721 /* Set up the free list. */
3722 for (i = 0; i < sz - 1; ++i)
3723 set_hash_next_slot (h, i, make_number (i + 1));
3724 h->next_free = make_number (0);
3726 XSET_HASH_TABLE (table, h);
3727 eassert (HASH_TABLE_P (table));
3728 eassert (XHASH_TABLE (table) == h);
3730 /* Maybe add this hash table to the list of all weak hash tables. */
3731 if (NILP (h->weak))
3732 h->next_weak = NULL;
3733 else
3735 h->next_weak = weak_hash_tables;
3736 weak_hash_tables = h;
3739 return table;
3743 /* Return a copy of hash table H1. Keys and values are not copied,
3744 only the table itself is. */
3746 static Lisp_Object
3747 copy_hash_table (struct Lisp_Hash_Table *h1)
3749 Lisp_Object table;
3750 struct Lisp_Hash_Table *h2;
3752 h2 = allocate_hash_table ();
3753 *h2 = *h1;
3754 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3755 h2->hash = Fcopy_sequence (h1->hash);
3756 h2->next = Fcopy_sequence (h1->next);
3757 h2->index = Fcopy_sequence (h1->index);
3758 XSET_HASH_TABLE (table, h2);
3760 /* Maybe add this hash table to the list of all weak hash tables. */
3761 if (!NILP (h2->weak))
3763 h2->next_weak = weak_hash_tables;
3764 weak_hash_tables = h2;
3767 return table;
3771 /* Resize hash table H if it's too full. If H cannot be resized
3772 because it's already too large, throw an error. */
3774 static void
3775 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3777 if (NILP (h->next_free))
3779 ptrdiff_t old_size = HASH_TABLE_SIZE (h);
3780 EMACS_INT new_size, index_size, nsize;
3781 ptrdiff_t i;
3782 double index_float;
3784 if (INTEGERP (h->rehash_size))
3785 new_size = old_size + XFASTINT (h->rehash_size);
3786 else
3788 double float_new_size = old_size * XFLOAT_DATA (h->rehash_size);
3789 if (float_new_size < INDEX_SIZE_BOUND + 1)
3791 new_size = float_new_size;
3792 if (new_size <= old_size)
3793 new_size = old_size + 1;
3795 else
3796 new_size = INDEX_SIZE_BOUND + 1;
3798 index_float = new_size / h->rehash_threshold;
3799 index_size = (index_float < INDEX_SIZE_BOUND + 1
3800 ? next_almost_prime (index_float)
3801 : INDEX_SIZE_BOUND + 1);
3802 nsize = max (index_size, 2 * new_size);
3803 if (INDEX_SIZE_BOUND < nsize)
3804 error ("Hash table too large to resize");
3806 #ifdef ENABLE_CHECKING
3807 if (HASH_TABLE_P (Vpurify_flag)
3808 && XHASH_TABLE (Vpurify_flag) == h)
3809 message ("Growing hash table to: %"pI"d", new_size);
3810 #endif
3812 set_hash_key_and_value (h, larger_vector (h->key_and_value,
3813 2 * (new_size - old_size), -1));
3814 set_hash_next (h, larger_vector (h->next, new_size - old_size, -1));
3815 set_hash_hash (h, larger_vector (h->hash, new_size - old_size, -1));
3816 set_hash_index (h, Fmake_vector (make_number (index_size), Qnil));
3818 /* Update the free list. Do it so that new entries are added at
3819 the end of the free list. This makes some operations like
3820 maphash faster. */
3821 for (i = old_size; i < new_size - 1; ++i)
3822 set_hash_next_slot (h, i, make_number (i + 1));
3824 if (!NILP (h->next_free))
3826 Lisp_Object last, next;
3828 last = h->next_free;
3829 while (next = HASH_NEXT (h, XFASTINT (last)),
3830 !NILP (next))
3831 last = next;
3833 set_hash_next_slot (h, XFASTINT (last), make_number (old_size));
3835 else
3836 XSETFASTINT (h->next_free, old_size);
3838 /* Rehash. */
3839 for (i = 0; i < old_size; ++i)
3840 if (!NILP (HASH_HASH (h, i)))
3842 EMACS_UINT hash_code = XUINT (HASH_HASH (h, i));
3843 ptrdiff_t start_of_bucket = hash_code % ASIZE (h->index);
3844 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3845 set_hash_index_slot (h, start_of_bucket, make_number (i));
3851 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
3852 the hash code of KEY. Value is the index of the entry in H
3853 matching KEY, or -1 if not found. */
3855 ptrdiff_t
3856 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
3858 EMACS_UINT hash_code;
3859 ptrdiff_t start_of_bucket;
3860 Lisp_Object idx;
3862 hash_code = h->test.hashfn (&h->test, key);
3863 eassert ((hash_code & ~INTMASK) == 0);
3864 if (hash)
3865 *hash = hash_code;
3867 start_of_bucket = hash_code % ASIZE (h->index);
3868 idx = HASH_INDEX (h, start_of_bucket);
3870 while (!NILP (idx))
3872 ptrdiff_t i = XFASTINT (idx);
3873 if (EQ (key, HASH_KEY (h, i))
3874 || (h->test.cmpfn
3875 && hash_code == XUINT (HASH_HASH (h, i))
3876 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
3877 break;
3878 idx = HASH_NEXT (h, i);
3881 return NILP (idx) ? -1 : XFASTINT (idx);
3885 /* Put an entry into hash table H that associates KEY with VALUE.
3886 HASH is a previously computed hash code of KEY.
3887 Value is the index of the entry in H matching KEY. */
3889 ptrdiff_t
3890 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value,
3891 EMACS_UINT hash)
3893 ptrdiff_t start_of_bucket, i;
3895 eassert ((hash & ~INTMASK) == 0);
3897 /* Increment count after resizing because resizing may fail. */
3898 maybe_resize_hash_table (h);
3899 h->count++;
3901 /* Store key/value in the key_and_value vector. */
3902 i = XFASTINT (h->next_free);
3903 h->next_free = HASH_NEXT (h, i);
3904 set_hash_key_slot (h, i, key);
3905 set_hash_value_slot (h, i, value);
3907 /* Remember its hash code. */
3908 set_hash_hash_slot (h, i, make_number (hash));
3910 /* Add new entry to its collision chain. */
3911 start_of_bucket = hash % ASIZE (h->index);
3912 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3913 set_hash_index_slot (h, start_of_bucket, make_number (i));
3914 return i;
3918 /* Remove the entry matching KEY from hash table H, if there is one. */
3920 void
3921 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
3923 EMACS_UINT hash_code;
3924 ptrdiff_t start_of_bucket;
3925 Lisp_Object idx, prev;
3927 hash_code = h->test.hashfn (&h->test, key);
3928 eassert ((hash_code & ~INTMASK) == 0);
3929 start_of_bucket = hash_code % ASIZE (h->index);
3930 idx = HASH_INDEX (h, start_of_bucket);
3931 prev = Qnil;
3933 while (!NILP (idx))
3935 ptrdiff_t i = XFASTINT (idx);
3937 if (EQ (key, HASH_KEY (h, i))
3938 || (h->test.cmpfn
3939 && hash_code == XUINT (HASH_HASH (h, i))
3940 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
3942 /* Take entry out of collision chain. */
3943 if (NILP (prev))
3944 set_hash_index_slot (h, start_of_bucket, HASH_NEXT (h, i));
3945 else
3946 set_hash_next_slot (h, XFASTINT (prev), HASH_NEXT (h, i));
3948 /* Clear slots in key_and_value and add the slots to
3949 the free list. */
3950 set_hash_key_slot (h, i, Qnil);
3951 set_hash_value_slot (h, i, Qnil);
3952 set_hash_hash_slot (h, i, Qnil);
3953 set_hash_next_slot (h, i, h->next_free);
3954 h->next_free = make_number (i);
3955 h->count--;
3956 eassert (h->count >= 0);
3957 break;
3959 else
3961 prev = idx;
3962 idx = HASH_NEXT (h, i);
3968 /* Clear hash table H. */
3970 static void
3971 hash_clear (struct Lisp_Hash_Table *h)
3973 if (h->count > 0)
3975 ptrdiff_t i, size = HASH_TABLE_SIZE (h);
3977 for (i = 0; i < size; ++i)
3979 set_hash_next_slot (h, i, i < size - 1 ? make_number (i + 1) : Qnil);
3980 set_hash_key_slot (h, i, Qnil);
3981 set_hash_value_slot (h, i, Qnil);
3982 set_hash_hash_slot (h, i, Qnil);
3985 for (i = 0; i < ASIZE (h->index); ++i)
3986 ASET (h->index, i, Qnil);
3988 h->next_free = make_number (0);
3989 h->count = 0;
3995 /************************************************************************
3996 Weak Hash Tables
3997 ************************************************************************/
3999 /* Sweep weak hash table H. REMOVE_ENTRIES_P means remove
4000 entries from the table that don't survive the current GC.
4001 !REMOVE_ENTRIES_P means mark entries that are in use. Value is
4002 true if anything was marked. */
4004 static bool
4005 sweep_weak_table (struct Lisp_Hash_Table *h, bool remove_entries_p)
4007 ptrdiff_t n = gc_asize (h->index);
4008 bool marked = false;
4010 for (ptrdiff_t bucket = 0; bucket < n; ++bucket)
4012 Lisp_Object idx, next, prev;
4014 /* Follow collision chain, removing entries that
4015 don't survive this garbage collection. */
4016 prev = Qnil;
4017 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
4019 ptrdiff_t i = XFASTINT (idx);
4020 bool key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
4021 bool value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
4022 bool remove_p;
4024 if (EQ (h->weak, Qkey))
4025 remove_p = !key_known_to_survive_p;
4026 else if (EQ (h->weak, Qvalue))
4027 remove_p = !value_known_to_survive_p;
4028 else if (EQ (h->weak, Qkey_or_value))
4029 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
4030 else if (EQ (h->weak, Qkey_and_value))
4031 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
4032 else
4033 emacs_abort ();
4035 next = HASH_NEXT (h, i);
4037 if (remove_entries_p)
4039 if (remove_p)
4041 /* Take out of collision chain. */
4042 if (NILP (prev))
4043 set_hash_index_slot (h, bucket, next);
4044 else
4045 set_hash_next_slot (h, XFASTINT (prev), next);
4047 /* Add to free list. */
4048 set_hash_next_slot (h, i, h->next_free);
4049 h->next_free = idx;
4051 /* Clear key, value, and hash. */
4052 set_hash_key_slot (h, i, Qnil);
4053 set_hash_value_slot (h, i, Qnil);
4054 set_hash_hash_slot (h, i, Qnil);
4056 h->count--;
4058 else
4060 prev = idx;
4063 else
4065 if (!remove_p)
4067 /* Make sure key and value survive. */
4068 if (!key_known_to_survive_p)
4070 mark_object (HASH_KEY (h, i));
4071 marked = 1;
4074 if (!value_known_to_survive_p)
4076 mark_object (HASH_VALUE (h, i));
4077 marked = 1;
4084 return marked;
4087 /* Remove elements from weak hash tables that don't survive the
4088 current garbage collection. Remove weak tables that don't survive
4089 from Vweak_hash_tables. Called from gc_sweep. */
4091 NO_INLINE /* For better stack traces */
4092 void
4093 sweep_weak_hash_tables (void)
4095 struct Lisp_Hash_Table *h, *used, *next;
4096 bool marked;
4098 /* Mark all keys and values that are in use. Keep on marking until
4099 there is no more change. This is necessary for cases like
4100 value-weak table A containing an entry X -> Y, where Y is used in a
4101 key-weak table B, Z -> Y. If B comes after A in the list of weak
4102 tables, X -> Y might be removed from A, although when looking at B
4103 one finds that it shouldn't. */
4106 marked = 0;
4107 for (h = weak_hash_tables; h; h = h->next_weak)
4109 if (h->header.size & ARRAY_MARK_FLAG)
4110 marked |= sweep_weak_table (h, 0);
4113 while (marked);
4115 /* Remove tables and entries that aren't used. */
4116 for (h = weak_hash_tables, used = NULL; h; h = next)
4118 next = h->next_weak;
4120 if (h->header.size & ARRAY_MARK_FLAG)
4122 /* TABLE is marked as used. Sweep its contents. */
4123 if (h->count > 0)
4124 sweep_weak_table (h, 1);
4126 /* Add table to the list of used weak hash tables. */
4127 h->next_weak = used;
4128 used = h;
4132 weak_hash_tables = used;
4137 /***********************************************************************
4138 Hash Code Computation
4139 ***********************************************************************/
4141 /* Maximum depth up to which to dive into Lisp structures. */
4143 #define SXHASH_MAX_DEPTH 3
4145 /* Maximum length up to which to take list and vector elements into
4146 account. */
4148 #define SXHASH_MAX_LEN 7
4150 /* Return a hash for string PTR which has length LEN. The hash value
4151 can be any EMACS_UINT value. */
4153 EMACS_UINT
4154 hash_string (char const *ptr, ptrdiff_t len)
4156 char const *p = ptr;
4157 char const *end = p + len;
4158 unsigned char c;
4159 EMACS_UINT hash = 0;
4161 while (p != end)
4163 c = *p++;
4164 hash = sxhash_combine (hash, c);
4167 return hash;
4170 /* Return a hash for string PTR which has length LEN. The hash
4171 code returned is guaranteed to fit in a Lisp integer. */
4173 static EMACS_UINT
4174 sxhash_string (char const *ptr, ptrdiff_t len)
4176 EMACS_UINT hash = hash_string (ptr, len);
4177 return SXHASH_REDUCE (hash);
4180 /* Return a hash for the floating point value VAL. */
4182 static EMACS_UINT
4183 sxhash_float (double val)
4185 EMACS_UINT hash = 0;
4186 enum {
4187 WORDS_PER_DOUBLE = (sizeof val / sizeof hash
4188 + (sizeof val % sizeof hash != 0))
4190 union {
4191 double val;
4192 EMACS_UINT word[WORDS_PER_DOUBLE];
4193 } u;
4194 int i;
4195 u.val = val;
4196 memset (&u.val + 1, 0, sizeof u - sizeof u.val);
4197 for (i = 0; i < WORDS_PER_DOUBLE; i++)
4198 hash = sxhash_combine (hash, u.word[i]);
4199 return SXHASH_REDUCE (hash);
4202 /* Return a hash for list LIST. DEPTH is the current depth in the
4203 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4205 static EMACS_UINT
4206 sxhash_list (Lisp_Object list, int depth)
4208 EMACS_UINT hash = 0;
4209 int i;
4211 if (depth < SXHASH_MAX_DEPTH)
4212 for (i = 0;
4213 CONSP (list) && i < SXHASH_MAX_LEN;
4214 list = XCDR (list), ++i)
4216 EMACS_UINT hash2 = sxhash (XCAR (list), depth + 1);
4217 hash = sxhash_combine (hash, hash2);
4220 if (!NILP (list))
4222 EMACS_UINT hash2 = sxhash (list, depth + 1);
4223 hash = sxhash_combine (hash, hash2);
4226 return SXHASH_REDUCE (hash);
4230 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4231 the Lisp structure. */
4233 static EMACS_UINT
4234 sxhash_vector (Lisp_Object vec, int depth)
4236 EMACS_UINT hash = ASIZE (vec);
4237 int i, n;
4239 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4240 for (i = 0; i < n; ++i)
4242 EMACS_UINT hash2 = sxhash (AREF (vec, i), depth + 1);
4243 hash = sxhash_combine (hash, hash2);
4246 return SXHASH_REDUCE (hash);
4249 /* Return a hash for bool-vector VECTOR. */
4251 static EMACS_UINT
4252 sxhash_bool_vector (Lisp_Object vec)
4254 EMACS_INT size = bool_vector_size (vec);
4255 EMACS_UINT hash = size;
4256 int i, n;
4258 n = min (SXHASH_MAX_LEN, bool_vector_words (size));
4259 for (i = 0; i < n; ++i)
4260 hash = sxhash_combine (hash, bool_vector_data (vec)[i]);
4262 return SXHASH_REDUCE (hash);
4266 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4267 structure. Value is an unsigned integer clipped to INTMASK. */
4269 EMACS_UINT
4270 sxhash (Lisp_Object obj, int depth)
4272 EMACS_UINT hash;
4274 if (depth > SXHASH_MAX_DEPTH)
4275 return 0;
4277 switch (XTYPE (obj))
4279 case_Lisp_Int:
4280 hash = XUINT (obj);
4281 break;
4283 case Lisp_Misc:
4284 case Lisp_Symbol:
4285 hash = XHASH (obj);
4286 break;
4288 case Lisp_String:
4289 hash = sxhash_string (SSDATA (obj), SBYTES (obj));
4290 break;
4292 /* This can be everything from a vector to an overlay. */
4293 case Lisp_Vectorlike:
4294 if (VECTORP (obj))
4295 /* According to the CL HyperSpec, two arrays are equal only if
4296 they are `eq', except for strings and bit-vectors. In
4297 Emacs, this works differently. We have to compare element
4298 by element. */
4299 hash = sxhash_vector (obj, depth);
4300 else if (BOOL_VECTOR_P (obj))
4301 hash = sxhash_bool_vector (obj);
4302 else
4303 /* Others are `equal' if they are `eq', so let's take their
4304 address as hash. */
4305 hash = XHASH (obj);
4306 break;
4308 case Lisp_Cons:
4309 hash = sxhash_list (obj, depth);
4310 break;
4312 case Lisp_Float:
4313 hash = sxhash_float (XFLOAT_DATA (obj));
4314 break;
4316 default:
4317 emacs_abort ();
4320 return hash;
4325 /***********************************************************************
4326 Lisp Interface
4327 ***********************************************************************/
4329 DEFUN ("sxhash-eq", Fsxhash_eq, Ssxhash_eq, 1, 1, 0,
4330 doc: /* Return an integer hash code for OBJ suitable for `eq'.
4331 If (eq A B), then (= (sxhash-eq A) (sxhash-eq B)). */)
4332 (Lisp_Object obj)
4334 return make_number (hashfn_eq (NULL, obj));
4337 DEFUN ("sxhash-eql", Fsxhash_eql, Ssxhash_eql, 1, 1, 0,
4338 doc: /* Return an integer hash code for OBJ suitable for `eql'.
4339 If (eql A B), then (= (sxhash-eql A) (sxhash-eql B)). */)
4340 (Lisp_Object obj)
4342 return make_number (hashfn_eql (NULL, obj));
4345 DEFUN ("sxhash-equal", Fsxhash_equal, Ssxhash_equal, 1, 1, 0,
4346 doc: /* Return an integer hash code for OBJ suitable for `equal'.
4347 If (equal A B), then (= (sxhash-equal A) (sxhash-equal B)). */)
4348 (Lisp_Object obj)
4350 return make_number (hashfn_equal (NULL, obj));
4353 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4354 doc: /* Create and return a new hash table.
4356 Arguments are specified as keyword/argument pairs. The following
4357 arguments are defined:
4359 :test TEST -- TEST must be a symbol that specifies how to compare
4360 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4361 `equal'. User-supplied test and hash functions can be specified via
4362 `define-hash-table-test'.
4364 :size SIZE -- A hint as to how many elements will be put in the table.
4365 Default is 65.
4367 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4368 fills up. If REHASH-SIZE is an integer, increase the size by that
4369 amount. If it is a float, it must be > 1.0, and the new size is the
4370 old size multiplied by that factor. Default is 1.5.
4372 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4373 Resize the hash table when the ratio (number of entries / table size)
4374 is greater than or equal to THRESHOLD. Default is 0.8.
4376 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4377 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4378 returned is a weak table. Key/value pairs are removed from a weak
4379 hash table when there are no non-weak references pointing to their
4380 key, value, one of key or value, or both key and value, depending on
4381 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4382 is nil.
4384 :purecopy PURECOPY -- If PURECOPY is non-nil, the table can be copied
4385 to pure storage when Emacs is being dumped, making the contents of the
4386 table read only. Any further changes to purified tables will result
4387 in an error.
4389 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4390 (ptrdiff_t nargs, Lisp_Object *args)
4392 Lisp_Object test, size, rehash_size, weak;
4393 double rehash_threshold;
4394 bool pure;
4395 struct hash_table_test testdesc;
4396 ptrdiff_t i;
4397 USE_SAFE_ALLOCA;
4399 /* The vector `used' is used to keep track of arguments that
4400 have been consumed. */
4401 char *used = SAFE_ALLOCA (nargs * sizeof *used);
4402 memset (used, 0, nargs * sizeof *used);
4404 /* See if there's a `:test TEST' among the arguments. */
4405 i = get_key_arg (QCtest, nargs, args, used);
4406 test = i ? args[i] : Qeql;
4407 if (EQ (test, Qeq))
4408 testdesc = hashtest_eq;
4409 else if (EQ (test, Qeql))
4410 testdesc = hashtest_eql;
4411 else if (EQ (test, Qequal))
4412 testdesc = hashtest_equal;
4413 else
4415 /* See if it is a user-defined test. */
4416 Lisp_Object prop;
4418 prop = Fget (test, Qhash_table_test);
4419 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4420 signal_error ("Invalid hash table test", test);
4421 testdesc.name = test;
4422 testdesc.user_cmp_function = XCAR (prop);
4423 testdesc.user_hash_function = XCAR (XCDR (prop));
4424 testdesc.hashfn = hashfn_user_defined;
4425 testdesc.cmpfn = cmpfn_user_defined;
4428 /* See if there's a `:purecopy PURECOPY' argument. */
4429 i = get_key_arg (QCpurecopy, nargs, args, used);
4430 pure = i && !NILP (args[i]);
4431 /* See if there's a `:size SIZE' argument. */
4432 i = get_key_arg (QCsize, nargs, args, used);
4433 size = i ? args[i] : Qnil;
4434 if (NILP (size))
4435 size = make_number (DEFAULT_HASH_SIZE);
4436 else if (!INTEGERP (size) || XINT (size) < 0)
4437 signal_error ("Invalid hash table size", size);
4439 /* Look for `:rehash-size SIZE'. */
4440 i = get_key_arg (QCrehash_size, nargs, args, used);
4441 rehash_size = i ? args[i] : make_float (DEFAULT_REHASH_SIZE);
4442 if (! ((INTEGERP (rehash_size) && 0 < XINT (rehash_size))
4443 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size))))
4444 signal_error ("Invalid hash table rehash size", rehash_size);
4446 /* Look for `:rehash-threshold THRESHOLD'. */
4447 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4448 rehash_threshold =
4449 i ? (FLOATP (args[i]) ? XFLOAT_DATA (args[i]) : -1.0)
4450 : DEFAULT_REHASH_THRESHOLD;
4451 if (! (0 < rehash_threshold && rehash_threshold <= 1))
4452 signal_error ("Invalid hash table rehash threshold", args[i]);
4454 /* Look for `:weakness WEAK'. */
4455 i = get_key_arg (QCweakness, nargs, args, used);
4456 weak = i ? args[i] : Qnil;
4457 if (EQ (weak, Qt))
4458 weak = Qkey_and_value;
4459 if (!NILP (weak)
4460 && !EQ (weak, Qkey)
4461 && !EQ (weak, Qvalue)
4462 && !EQ (weak, Qkey_or_value)
4463 && !EQ (weak, Qkey_and_value))
4464 signal_error ("Invalid hash table weakness", weak);
4466 /* Now, all args should have been used up, or there's a problem. */
4467 for (i = 0; i < nargs; ++i)
4468 if (!used[i])
4469 signal_error ("Invalid argument list", args[i]);
4471 SAFE_FREE ();
4472 return make_hash_table (testdesc, size, rehash_size, rehash_threshold, weak,
4473 pure);
4477 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4478 doc: /* Return a copy of hash table TABLE. */)
4479 (Lisp_Object table)
4481 return copy_hash_table (check_hash_table (table));
4485 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4486 doc: /* Return the number of elements in TABLE. */)
4487 (Lisp_Object table)
4489 return make_number (check_hash_table (table)->count);
4493 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4494 Shash_table_rehash_size, 1, 1, 0,
4495 doc: /* Return the current rehash size of TABLE. */)
4496 (Lisp_Object table)
4498 return check_hash_table (table)->rehash_size;
4502 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4503 Shash_table_rehash_threshold, 1, 1, 0,
4504 doc: /* Return the current rehash threshold of TABLE. */)
4505 (Lisp_Object table)
4507 return make_float (check_hash_table (table)->rehash_threshold);
4511 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4512 doc: /* Return the size of TABLE.
4513 The size can be used as an argument to `make-hash-table' to create
4514 a hash table than can hold as many elements as TABLE holds
4515 without need for resizing. */)
4516 (Lisp_Object table)
4518 struct Lisp_Hash_Table *h = check_hash_table (table);
4519 return make_number (HASH_TABLE_SIZE (h));
4523 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4524 doc: /* Return the test TABLE uses. */)
4525 (Lisp_Object table)
4527 return check_hash_table (table)->test.name;
4531 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4532 1, 1, 0,
4533 doc: /* Return the weakness of TABLE. */)
4534 (Lisp_Object table)
4536 return check_hash_table (table)->weak;
4540 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4541 doc: /* Return t if OBJ is a Lisp hash table object. */)
4542 (Lisp_Object obj)
4544 return HASH_TABLE_P (obj) ? Qt : Qnil;
4548 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4549 doc: /* Clear hash table TABLE and return it. */)
4550 (Lisp_Object table)
4552 struct Lisp_Hash_Table *h = check_hash_table (table);
4553 CHECK_IMPURE (table, h);
4554 hash_clear (h);
4555 /* Be compatible with XEmacs. */
4556 return table;
4560 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4561 doc: /* Look up KEY in TABLE and return its associated value.
4562 If KEY is not found, return DFLT which defaults to nil. */)
4563 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4565 struct Lisp_Hash_Table *h = check_hash_table (table);
4566 ptrdiff_t i = hash_lookup (h, key, NULL);
4567 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4571 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4572 doc: /* Associate KEY with VALUE in hash table TABLE.
4573 If KEY is already present in table, replace its current value with
4574 VALUE. In any case, return VALUE. */)
4575 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4577 struct Lisp_Hash_Table *h = check_hash_table (table);
4578 CHECK_IMPURE (table, h);
4580 ptrdiff_t i;
4581 EMACS_UINT hash;
4582 i = hash_lookup (h, key, &hash);
4583 if (i >= 0)
4584 set_hash_value_slot (h, i, value);
4585 else
4586 hash_put (h, key, value, hash);
4588 return value;
4592 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4593 doc: /* Remove KEY from TABLE. */)
4594 (Lisp_Object key, Lisp_Object table)
4596 struct Lisp_Hash_Table *h = check_hash_table (table);
4597 CHECK_IMPURE (table, h);
4598 hash_remove_from_table (h, key);
4599 return Qnil;
4603 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4604 doc: /* Call FUNCTION for all entries in hash table TABLE.
4605 FUNCTION is called with two arguments, KEY and VALUE.
4606 `maphash' always returns nil. */)
4607 (Lisp_Object function, Lisp_Object table)
4609 struct Lisp_Hash_Table *h = check_hash_table (table);
4611 for (ptrdiff_t i = 0; i < HASH_TABLE_SIZE (h); ++i)
4612 if (!NILP (HASH_HASH (h, i)))
4613 call2 (function, HASH_KEY (h, i), HASH_VALUE (h, i));
4615 return Qnil;
4619 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4620 Sdefine_hash_table_test, 3, 3, 0,
4621 doc: /* Define a new hash table test with name NAME, a symbol.
4623 In hash tables created with NAME specified as test, use TEST to
4624 compare keys, and HASH for computing hash codes of keys.
4626 TEST must be a function taking two arguments and returning non-nil if
4627 both arguments are the same. HASH must be a function taking one
4628 argument and returning an object that is the hash code of the argument.
4629 It should be the case that if (eq (funcall HASH x1) (funcall HASH x2))
4630 returns nil, then (funcall TEST x1 x2) also returns nil. */)
4631 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4633 return Fput (name, Qhash_table_test, list2 (test, hash));
4638 /************************************************************************
4639 MD5, SHA-1, and SHA-2
4640 ************************************************************************/
4642 #include "md5.h"
4643 #include "sha1.h"
4644 #include "sha256.h"
4645 #include "sha512.h"
4647 static Lisp_Object
4648 make_digest_string (Lisp_Object digest, int digest_size)
4650 unsigned char *p = SDATA (digest);
4652 for (int i = digest_size - 1; i >= 0; i--)
4654 static char const hexdigit[16] = "0123456789abcdef";
4655 int p_i = p[i];
4656 p[2 * i] = hexdigit[p_i >> 4];
4657 p[2 * i + 1] = hexdigit[p_i & 0xf];
4659 return digest;
4662 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4664 static Lisp_Object
4665 secure_hash (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start,
4666 Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror,
4667 Lisp_Object binary)
4669 ptrdiff_t size, start_char = 0, start_byte, end_char = 0, end_byte;
4670 register EMACS_INT b, e;
4671 register struct buffer *bp;
4672 EMACS_INT temp;
4673 int digest_size;
4674 void *(*hash_func) (const char *, size_t, void *);
4675 Lisp_Object digest;
4677 CHECK_SYMBOL (algorithm);
4679 if (STRINGP (object))
4681 if (NILP (coding_system))
4683 /* Decide the coding-system to encode the data with. */
4685 if (STRING_MULTIBYTE (object))
4686 /* use default, we can't guess correct value */
4687 coding_system = preferred_coding_system ();
4688 else
4689 coding_system = Qraw_text;
4692 if (NILP (Fcoding_system_p (coding_system)))
4694 /* Invalid coding system. */
4696 if (!NILP (noerror))
4697 coding_system = Qraw_text;
4698 else
4699 xsignal1 (Qcoding_system_error, coding_system);
4702 if (STRING_MULTIBYTE (object))
4703 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4705 size = SCHARS (object);
4706 validate_subarray (object, start, end, size, &start_char, &end_char);
4708 start_byte = !start_char ? 0 : string_char_to_byte (object, start_char);
4709 end_byte = (end_char == size
4710 ? SBYTES (object)
4711 : string_char_to_byte (object, end_char));
4713 else
4715 struct buffer *prev = current_buffer;
4717 record_unwind_current_buffer ();
4719 CHECK_BUFFER (object);
4721 bp = XBUFFER (object);
4722 set_buffer_internal (bp);
4724 if (NILP (start))
4725 b = BEGV;
4726 else
4728 CHECK_NUMBER_COERCE_MARKER (start);
4729 b = XINT (start);
4732 if (NILP (end))
4733 e = ZV;
4734 else
4736 CHECK_NUMBER_COERCE_MARKER (end);
4737 e = XINT (end);
4740 if (b > e)
4741 temp = b, b = e, e = temp;
4743 if (!(BEGV <= b && e <= ZV))
4744 args_out_of_range (start, end);
4746 if (NILP (coding_system))
4748 /* Decide the coding-system to encode the data with.
4749 See fileio.c:Fwrite-region */
4751 if (!NILP (Vcoding_system_for_write))
4752 coding_system = Vcoding_system_for_write;
4753 else
4755 bool force_raw_text = 0;
4757 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4758 if (NILP (coding_system)
4759 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4761 coding_system = Qnil;
4762 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4763 force_raw_text = 1;
4766 if (NILP (coding_system) && !NILP (Fbuffer_file_name (object)))
4768 /* Check file-coding-system-alist. */
4769 Lisp_Object val = CALLN (Ffind_operation_coding_system,
4770 Qwrite_region, start, end,
4771 Fbuffer_file_name (object));
4772 if (CONSP (val) && !NILP (XCDR (val)))
4773 coding_system = XCDR (val);
4776 if (NILP (coding_system)
4777 && !NILP (BVAR (XBUFFER (object), buffer_file_coding_system)))
4779 /* If we still have not decided a coding system, use the
4780 default value of buffer-file-coding-system. */
4781 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4784 if (!force_raw_text
4785 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4786 /* Confirm that VAL can surely encode the current region. */
4787 coding_system = call4 (Vselect_safe_coding_system_function,
4788 make_number (b), make_number (e),
4789 coding_system, Qnil);
4791 if (force_raw_text)
4792 coding_system = Qraw_text;
4795 if (NILP (Fcoding_system_p (coding_system)))
4797 /* Invalid coding system. */
4799 if (!NILP (noerror))
4800 coding_system = Qraw_text;
4801 else
4802 xsignal1 (Qcoding_system_error, coding_system);
4806 object = make_buffer_string (b, e, 0);
4807 set_buffer_internal (prev);
4808 /* Discard the unwind protect for recovering the current
4809 buffer. */
4810 specpdl_ptr--;
4812 if (STRING_MULTIBYTE (object))
4813 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4814 start_byte = 0;
4815 end_byte = SBYTES (object);
4818 if (EQ (algorithm, Qmd5))
4820 digest_size = MD5_DIGEST_SIZE;
4821 hash_func = md5_buffer;
4823 else if (EQ (algorithm, Qsha1))
4825 digest_size = SHA1_DIGEST_SIZE;
4826 hash_func = sha1_buffer;
4828 else if (EQ (algorithm, Qsha224))
4830 digest_size = SHA224_DIGEST_SIZE;
4831 hash_func = sha224_buffer;
4833 else if (EQ (algorithm, Qsha256))
4835 digest_size = SHA256_DIGEST_SIZE;
4836 hash_func = sha256_buffer;
4838 else if (EQ (algorithm, Qsha384))
4840 digest_size = SHA384_DIGEST_SIZE;
4841 hash_func = sha384_buffer;
4843 else if (EQ (algorithm, Qsha512))
4845 digest_size = SHA512_DIGEST_SIZE;
4846 hash_func = sha512_buffer;
4848 else
4849 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm)));
4851 /* allocate 2 x digest_size so that it can be re-used to hold the
4852 hexified value */
4853 digest = make_uninit_string (digest_size * 2);
4855 hash_func (SSDATA (object) + start_byte,
4856 end_byte - start_byte,
4857 SSDATA (digest));
4859 if (NILP (binary))
4860 return make_digest_string (digest, digest_size);
4861 else
4862 return make_unibyte_string (SSDATA (digest), digest_size);
4865 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
4866 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
4868 A message digest is a cryptographic checksum of a document, and the
4869 algorithm to calculate it is defined in RFC 1321.
4871 The two optional arguments START and END are character positions
4872 specifying for which part of OBJECT the message digest should be
4873 computed. If nil or omitted, the digest is computed for the whole
4874 OBJECT.
4876 The MD5 message digest is computed from the result of encoding the
4877 text in a coding system, not directly from the internal Emacs form of
4878 the text. The optional fourth argument CODING-SYSTEM specifies which
4879 coding system to encode the text with. It should be the same coding
4880 system that you used or will use when actually writing the text into a
4881 file.
4883 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
4884 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
4885 system would be chosen by default for writing this text into a file.
4887 If OBJECT is a string, the most preferred coding system (see the
4888 command `prefer-coding-system') is used.
4890 If NOERROR is non-nil, silently assume the `raw-text' coding if the
4891 guesswork fails. Normally, an error is signaled in such case. */)
4892 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
4894 return secure_hash (Qmd5, object, start, end, coding_system, noerror, Qnil);
4897 DEFUN ("secure-hash", Fsecure_hash, Ssecure_hash, 2, 5, 0,
4898 doc: /* Return the secure hash of OBJECT, a buffer or string.
4899 ALGORITHM is a symbol specifying the hash to use:
4900 md5, sha1, sha224, sha256, sha384 or sha512.
4902 The two optional arguments START and END are positions specifying for
4903 which part of OBJECT to compute the hash. If nil or omitted, uses the
4904 whole OBJECT.
4906 If BINARY is non-nil, returns a string in binary form. */)
4907 (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object binary)
4909 return secure_hash (algorithm, object, start, end, Qnil, Qnil, binary);
4912 DEFUN ("buffer-hash", Fbuffer_hash, Sbuffer_hash, 0, 1, 0,
4913 doc: /* Return a hash of the contents of BUFFER-OR-NAME.
4914 This hash is performed on the raw internal format of the buffer,
4915 disregarding any coding systems.
4916 If nil, use the current buffer." */ )
4917 (Lisp_Object buffer_or_name)
4919 Lisp_Object buffer;
4920 struct buffer *b;
4921 struct sha1_ctx ctx;
4923 if (NILP (buffer_or_name))
4924 buffer = Fcurrent_buffer ();
4925 else
4926 buffer = Fget_buffer (buffer_or_name);
4927 if (NILP (buffer))
4928 nsberror (buffer_or_name);
4930 b = XBUFFER (buffer);
4931 sha1_init_ctx (&ctx);
4933 /* Process the first part of the buffer. */
4934 sha1_process_bytes (BUF_BEG_ADDR (b),
4935 BUF_GPT_BYTE (b) - BUF_BEG_BYTE (b),
4936 &ctx);
4938 /* If the gap is before the end of the buffer, process the last half
4939 of the buffer. */
4940 if (BUF_GPT_BYTE (b) < BUF_Z_BYTE (b))
4941 sha1_process_bytes (BUF_GAP_END_ADDR (b),
4942 BUF_Z_ADDR (b) - BUF_GAP_END_ADDR (b),
4943 &ctx);
4945 Lisp_Object digest = make_uninit_string (SHA1_DIGEST_SIZE * 2);
4946 sha1_finish_ctx (&ctx, SSDATA (digest));
4947 return make_digest_string (digest, SHA1_DIGEST_SIZE);
4951 void
4952 syms_of_fns (void)
4954 DEFSYM (Qmd5, "md5");
4955 DEFSYM (Qsha1, "sha1");
4956 DEFSYM (Qsha224, "sha224");
4957 DEFSYM (Qsha256, "sha256");
4958 DEFSYM (Qsha384, "sha384");
4959 DEFSYM (Qsha512, "sha512");
4961 /* Hash table stuff. */
4962 DEFSYM (Qhash_table_p, "hash-table-p");
4963 DEFSYM (Qeq, "eq");
4964 DEFSYM (Qeql, "eql");
4965 DEFSYM (Qequal, "equal");
4966 DEFSYM (QCtest, ":test");
4967 DEFSYM (QCsize, ":size");
4968 DEFSYM (QCpurecopy, ":purecopy");
4969 DEFSYM (QCrehash_size, ":rehash-size");
4970 DEFSYM (QCrehash_threshold, ":rehash-threshold");
4971 DEFSYM (QCweakness, ":weakness");
4972 DEFSYM (Qkey, "key");
4973 DEFSYM (Qvalue, "value");
4974 DEFSYM (Qhash_table_test, "hash-table-test");
4975 DEFSYM (Qkey_or_value, "key-or-value");
4976 DEFSYM (Qkey_and_value, "key-and-value");
4978 defsubr (&Ssxhash_eq);
4979 defsubr (&Ssxhash_eql);
4980 defsubr (&Ssxhash_equal);
4981 defsubr (&Smake_hash_table);
4982 defsubr (&Scopy_hash_table);
4983 defsubr (&Shash_table_count);
4984 defsubr (&Shash_table_rehash_size);
4985 defsubr (&Shash_table_rehash_threshold);
4986 defsubr (&Shash_table_size);
4987 defsubr (&Shash_table_test);
4988 defsubr (&Shash_table_weakness);
4989 defsubr (&Shash_table_p);
4990 defsubr (&Sclrhash);
4991 defsubr (&Sgethash);
4992 defsubr (&Sputhash);
4993 defsubr (&Sremhash);
4994 defsubr (&Smaphash);
4995 defsubr (&Sdefine_hash_table_test);
4997 DEFSYM (Qstring_lessp, "string-lessp");
4998 DEFSYM (Qprovide, "provide");
4999 DEFSYM (Qrequire, "require");
5000 DEFSYM (Qyes_or_no_p_history, "yes-or-no-p-history");
5001 DEFSYM (Qcursor_in_echo_area, "cursor-in-echo-area");
5002 DEFSYM (Qwidget_type, "widget-type");
5004 staticpro (&string_char_byte_cache_string);
5005 string_char_byte_cache_string = Qnil;
5007 require_nesting_list = Qnil;
5008 staticpro (&require_nesting_list);
5010 Fset (Qyes_or_no_p_history, Qnil);
5012 DEFVAR_LISP ("features", Vfeatures,
5013 doc: /* A list of symbols which are the features of the executing Emacs.
5014 Used by `featurep' and `require', and altered by `provide'. */);
5015 Vfeatures = list1 (Qemacs);
5016 DEFSYM (Qfeatures, "features");
5017 /* Let people use lexically scoped vars named `features'. */
5018 Fmake_var_non_special (Qfeatures);
5019 DEFSYM (Qsubfeatures, "subfeatures");
5020 DEFSYM (Qfuncall, "funcall");
5022 #ifdef HAVE_LANGINFO_CODESET
5023 DEFSYM (Qcodeset, "codeset");
5024 DEFSYM (Qdays, "days");
5025 DEFSYM (Qmonths, "months");
5026 DEFSYM (Qpaper, "paper");
5027 #endif /* HAVE_LANGINFO_CODESET */
5029 DEFVAR_BOOL ("use-dialog-box", use_dialog_box,
5030 doc: /* Non-nil means mouse commands use dialog boxes to ask questions.
5031 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
5032 invoked by mouse clicks and mouse menu items.
5034 On some platforms, file selection dialogs are also enabled if this is
5035 non-nil. */);
5036 use_dialog_box = 1;
5038 DEFVAR_BOOL ("use-file-dialog", use_file_dialog,
5039 doc: /* Non-nil means mouse commands use a file dialog to ask for files.
5040 This applies to commands from menus and tool bar buttons even when
5041 they are initiated from the keyboard. If `use-dialog-box' is nil,
5042 that disables the use of a file dialog, regardless of the value of
5043 this variable. */);
5044 use_file_dialog = 1;
5046 defsubr (&Sidentity);
5047 defsubr (&Srandom);
5048 defsubr (&Slength);
5049 defsubr (&Ssafe_length);
5050 defsubr (&Sstring_bytes);
5051 defsubr (&Sstring_equal);
5052 defsubr (&Scompare_strings);
5053 defsubr (&Sstring_lessp);
5054 defsubr (&Sstring_version_lessp);
5055 defsubr (&Sstring_collate_lessp);
5056 defsubr (&Sstring_collate_equalp);
5057 defsubr (&Sappend);
5058 defsubr (&Sconcat);
5059 defsubr (&Svconcat);
5060 defsubr (&Scopy_sequence);
5061 defsubr (&Sstring_make_multibyte);
5062 defsubr (&Sstring_make_unibyte);
5063 defsubr (&Sstring_as_multibyte);
5064 defsubr (&Sstring_as_unibyte);
5065 defsubr (&Sstring_to_multibyte);
5066 defsubr (&Sstring_to_unibyte);
5067 defsubr (&Scopy_alist);
5068 defsubr (&Ssubstring);
5069 defsubr (&Ssubstring_no_properties);
5070 defsubr (&Snthcdr);
5071 defsubr (&Snth);
5072 defsubr (&Selt);
5073 defsubr (&Smember);
5074 defsubr (&Smemq);
5075 defsubr (&Smemql);
5076 defsubr (&Sassq);
5077 defsubr (&Sassoc);
5078 defsubr (&Srassq);
5079 defsubr (&Srassoc);
5080 defsubr (&Sdelq);
5081 defsubr (&Sdelete);
5082 defsubr (&Snreverse);
5083 defsubr (&Sreverse);
5084 defsubr (&Ssort);
5085 defsubr (&Splist_get);
5086 defsubr (&Sget);
5087 defsubr (&Splist_put);
5088 defsubr (&Sput);
5089 defsubr (&Slax_plist_get);
5090 defsubr (&Slax_plist_put);
5091 defsubr (&Seql);
5092 defsubr (&Sequal);
5093 defsubr (&Sequal_including_properties);
5094 defsubr (&Sfillarray);
5095 defsubr (&Sclear_string);
5096 defsubr (&Snconc);
5097 defsubr (&Smapcar);
5098 defsubr (&Smapc);
5099 defsubr (&Smapcan);
5100 defsubr (&Smapconcat);
5101 defsubr (&Syes_or_no_p);
5102 defsubr (&Sload_average);
5103 defsubr (&Sfeaturep);
5104 defsubr (&Srequire);
5105 defsubr (&Sprovide);
5106 defsubr (&Splist_member);
5107 defsubr (&Swidget_put);
5108 defsubr (&Swidget_get);
5109 defsubr (&Swidget_apply);
5110 defsubr (&Sbase64_encode_region);
5111 defsubr (&Sbase64_decode_region);
5112 defsubr (&Sbase64_encode_string);
5113 defsubr (&Sbase64_decode_string);
5114 defsubr (&Smd5);
5115 defsubr (&Ssecure_hash);
5116 defsubr (&Sbuffer_hash);
5117 defsubr (&Slocale_info);