Merge branch 'master' into comment-cache
[emacs.git] / src / fns.c
blobac7c1f265a468b25d431f4fadce5a102c28239ef
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 EMACS_INT i = 0;
115 ++i;
116 if ((i & (QUIT_COUNT_HEURISTIC - 1)) == 0)
118 if (MOST_POSITIVE_FIXNUM < i)
119 error ("List too long");
120 maybe_quit ();
122 sequence = XCDR (sequence);
124 while (CONSP (sequence));
126 CHECK_LIST_END (sequence, sequence);
128 val = make_number (i);
130 else if (NILP (sequence))
131 XSETFASTINT (val, 0);
132 else
133 wrong_type_argument (Qsequencep, sequence);
135 return val;
138 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
139 doc: /* Return the length of a list, but avoid error or infinite loop.
140 This function never gets an error. If LIST is not really a list,
141 it returns 0. If LIST is circular, it returns a finite value
142 which is at least the number of distinct elements. */)
143 (Lisp_Object list)
145 Lisp_Object tail, halftail;
146 double hilen = 0;
147 uintmax_t lolen = 1;
149 if (! CONSP (list))
150 return make_number (0);
152 /* halftail is used to detect circular lists. */
153 for (tail = halftail = list; ; )
155 tail = XCDR (tail);
156 if (! CONSP (tail))
157 break;
158 if (EQ (tail, halftail))
159 break;
160 lolen++;
161 if ((lolen & 1) == 0)
163 halftail = XCDR (halftail);
164 if ((lolen & (QUIT_COUNT_HEURISTIC - 1)) == 0)
166 maybe_quit ();
167 if (lolen == 0)
168 hilen += UINTMAX_MAX + 1.0;
173 /* If the length does not fit into a fixnum, return a float.
174 On all known practical machines this returns an upper bound on
175 the true length. */
176 return hilen ? make_float (hilen + lolen) : make_fixnum_or_float (lolen);
179 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
180 doc: /* Return the number of bytes in STRING.
181 If STRING is multibyte, this may be greater than the length of STRING. */)
182 (Lisp_Object string)
184 CHECK_STRING (string);
185 return make_number (SBYTES (string));
188 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
189 doc: /* Return t if two strings have identical contents.
190 Case is significant, but text properties are ignored.
191 Symbols are also allowed; their print names are used instead. */)
192 (register Lisp_Object s1, Lisp_Object s2)
194 if (SYMBOLP (s1))
195 s1 = SYMBOL_NAME (s1);
196 if (SYMBOLP (s2))
197 s2 = SYMBOL_NAME (s2);
198 CHECK_STRING (s1);
199 CHECK_STRING (s2);
201 if (SCHARS (s1) != SCHARS (s2)
202 || SBYTES (s1) != SBYTES (s2)
203 || memcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
204 return Qnil;
205 return Qt;
208 DEFUN ("compare-strings", Fcompare_strings, Scompare_strings, 6, 7, 0,
209 doc: /* Compare the contents of two strings, converting to multibyte if needed.
210 The arguments START1, END1, START2, and END2, if non-nil, are
211 positions specifying which parts of STR1 or STR2 to compare. In
212 string STR1, compare the part between START1 (inclusive) and END1
213 \(exclusive). If START1 is nil, it defaults to 0, the beginning of
214 the string; if END1 is nil, it defaults to the length of the string.
215 Likewise, in string STR2, compare the part between START2 and END2.
216 Like in `substring', negative values are counted from the end.
218 The strings are compared by the numeric values of their characters.
219 For instance, STR1 is "less than" STR2 if its first differing
220 character has a smaller numeric value. If IGNORE-CASE is non-nil,
221 characters are converted to upper-case before comparing them. Unibyte
222 strings are converted to multibyte for comparison.
224 The value is t if the strings (or specified portions) match.
225 If string STR1 is less, the value is a negative number N;
226 - 1 - N is the number of characters that match at the beginning.
227 If string STR1 is greater, the value is a positive number N;
228 N - 1 is the number of characters that match at the beginning. */)
229 (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2,
230 Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
232 ptrdiff_t from1, to1, from2, to2, i1, i1_byte, i2, i2_byte;
234 CHECK_STRING (str1);
235 CHECK_STRING (str2);
237 /* For backward compatibility, silently bring too-large positive end
238 values into range. */
239 if (INTEGERP (end1) && SCHARS (str1) < XINT (end1))
240 end1 = make_number (SCHARS (str1));
241 if (INTEGERP (end2) && SCHARS (str2) < XINT (end2))
242 end2 = make_number (SCHARS (str2));
244 validate_subarray (str1, start1, end1, SCHARS (str1), &from1, &to1);
245 validate_subarray (str2, start2, end2, SCHARS (str2), &from2, &to2);
247 i1 = from1;
248 i2 = from2;
250 i1_byte = string_char_to_byte (str1, i1);
251 i2_byte = string_char_to_byte (str2, i2);
253 while (i1 < to1 && i2 < to2)
255 /* When we find a mismatch, we must compare the
256 characters, not just the bytes. */
257 int c1, c2;
259 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c1, str1, i1, i1_byte);
260 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c2, str2, i2, i2_byte);
262 if (c1 == c2)
263 continue;
265 if (! NILP (ignore_case))
267 c1 = XINT (Fupcase (make_number (c1)));
268 c2 = XINT (Fupcase (make_number (c2)));
271 if (c1 == c2)
272 continue;
274 /* Note that I1 has already been incremented
275 past the character that we are comparing;
276 hence we don't add or subtract 1 here. */
277 if (c1 < c2)
278 return make_number (- i1 + from1);
279 else
280 return make_number (i1 - from1);
283 if (i1 < to1)
284 return make_number (i1 - from1 + 1);
285 if (i2 < to2)
286 return make_number (- i1 + from1 - 1);
288 return Qt;
291 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
292 doc: /* Return non-nil if STRING1 is less than STRING2 in lexicographic order.
293 Case is significant.
294 Symbols are also allowed; their print names are used instead. */)
295 (register Lisp_Object string1, Lisp_Object string2)
297 register ptrdiff_t end;
298 register ptrdiff_t i1, i1_byte, i2, i2_byte;
300 if (SYMBOLP (string1))
301 string1 = SYMBOL_NAME (string1);
302 if (SYMBOLP (string2))
303 string2 = SYMBOL_NAME (string2);
304 CHECK_STRING (string1);
305 CHECK_STRING (string2);
307 i1 = i1_byte = i2 = i2_byte = 0;
309 end = SCHARS (string1);
310 if (end > SCHARS (string2))
311 end = SCHARS (string2);
313 while (i1 < end)
315 /* When we find a mismatch, we must compare the
316 characters, not just the bytes. */
317 int c1, c2;
319 FETCH_STRING_CHAR_ADVANCE (c1, string1, i1, i1_byte);
320 FETCH_STRING_CHAR_ADVANCE (c2, string2, i2, i2_byte);
322 if (c1 != c2)
323 return c1 < c2 ? Qt : Qnil;
325 return i1 < SCHARS (string2) ? Qt : Qnil;
328 DEFUN ("string-version-lessp", Fstring_version_lessp,
329 Sstring_version_lessp, 2, 2, 0,
330 doc: /* Return non-nil if S1 is less than S2, as version strings.
332 This function compares version strings S1 and S2:
333 1) By prefix lexicographically.
334 2) Then by version (similarly to version comparison of Debian's dpkg).
335 Leading zeros in version numbers are ignored.
336 3) If both prefix and version are equal, compare as ordinary strings.
338 For example, \"foo2.png\" compares less than \"foo12.png\".
339 Case is significant.
340 Symbols are also allowed; their print names are used instead. */)
341 (Lisp_Object string1, Lisp_Object string2)
343 if (SYMBOLP (string1))
344 string1 = SYMBOL_NAME (string1);
345 if (SYMBOLP (string2))
346 string2 = SYMBOL_NAME (string2);
347 CHECK_STRING (string1);
348 CHECK_STRING (string2);
350 char *p1 = SSDATA (string1);
351 char *p2 = SSDATA (string2);
352 char *lim1 = p1 + SBYTES (string1);
353 char *lim2 = p2 + SBYTES (string2);
354 int cmp;
356 while ((cmp = filevercmp (p1, p2)) == 0)
358 /* If the strings are identical through their first null bytes,
359 skip past identical prefixes and try again. */
360 ptrdiff_t size = strlen (p1) + 1;
361 p1 += size;
362 p2 += size;
363 if (lim1 < p1)
364 return lim2 < p2 ? Qnil : Qt;
365 if (lim2 < p2)
366 return Qnil;
369 return cmp < 0 ? Qt : Qnil;
372 DEFUN ("string-collate-lessp", Fstring_collate_lessp, Sstring_collate_lessp, 2, 4, 0,
373 doc: /* Return t if first arg string is less than second in collation order.
374 Symbols are also allowed; their print names are used instead.
376 This function obeys the conventions for collation order in your
377 locale settings. For example, punctuation and whitespace characters
378 might be considered less significant for sorting:
380 \(sort \\='("11" "12" "1 1" "1 2" "1.1" "1.2") \\='string-collate-lessp)
381 => ("11" "1 1" "1.1" "12" "1 2" "1.2")
383 The optional argument LOCALE, a string, overrides the setting of your
384 current locale identifier for collation. The value is system
385 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
386 while it would be, e.g., \"enu_USA.1252\" on MS-Windows systems.
388 If IGNORE-CASE is non-nil, characters are converted to lower-case
389 before comparing them.
391 To emulate Unicode-compliant collation on MS-Windows systems,
392 bind `w32-collate-ignore-punctuation' to a non-nil value, since
393 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
395 If your system does not support a locale environment, this function
396 behaves like `string-lessp'. */)
397 (Lisp_Object s1, Lisp_Object s2, Lisp_Object locale, Lisp_Object ignore_case)
399 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
400 /* Check parameters. */
401 if (SYMBOLP (s1))
402 s1 = SYMBOL_NAME (s1);
403 if (SYMBOLP (s2))
404 s2 = SYMBOL_NAME (s2);
405 CHECK_STRING (s1);
406 CHECK_STRING (s2);
407 if (!NILP (locale))
408 CHECK_STRING (locale);
410 return (str_collate (s1, s2, locale, ignore_case) < 0) ? Qt : Qnil;
412 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
413 return Fstring_lessp (s1, s2);
414 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
417 DEFUN ("string-collate-equalp", Fstring_collate_equalp, Sstring_collate_equalp, 2, 4, 0,
418 doc: /* Return t if two strings have identical contents.
419 Symbols are also allowed; their print names are used instead.
421 This function obeys the conventions for collation order in your locale
422 settings. For example, characters with different coding points but
423 the same meaning might be considered as equal, like different grave
424 accent Unicode characters:
426 \(string-collate-equalp (string ?\\uFF40) (string ?\\u1FEF))
427 => t
429 The optional argument LOCALE, a string, overrides the setting of your
430 current locale identifier for collation. The value is system
431 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
432 while it would be \"enu_USA.1252\" on MS Windows systems.
434 If IGNORE-CASE is non-nil, characters are converted to lower-case
435 before comparing them.
437 To emulate Unicode-compliant collation on MS-Windows systems,
438 bind `w32-collate-ignore-punctuation' to a non-nil value, since
439 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
441 If your system does not support a locale environment, this function
442 behaves like `string-equal'.
444 Do NOT use this function to compare file names for equality. */)
445 (Lisp_Object s1, Lisp_Object s2, Lisp_Object locale, Lisp_Object ignore_case)
447 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
448 /* Check parameters. */
449 if (SYMBOLP (s1))
450 s1 = SYMBOL_NAME (s1);
451 if (SYMBOLP (s2))
452 s2 = SYMBOL_NAME (s2);
453 CHECK_STRING (s1);
454 CHECK_STRING (s2);
455 if (!NILP (locale))
456 CHECK_STRING (locale);
458 return (str_collate (s1, s2, locale, ignore_case) == 0) ? Qt : Qnil;
460 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
461 return Fstring_equal (s1, s2);
462 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
465 static Lisp_Object concat (ptrdiff_t nargs, Lisp_Object *args,
466 enum Lisp_Type target_type, bool last_special);
468 /* ARGSUSED */
469 Lisp_Object
470 concat2 (Lisp_Object s1, Lisp_Object s2)
472 return concat (2, ((Lisp_Object []) {s1, s2}), Lisp_String, 0);
475 /* ARGSUSED */
476 Lisp_Object
477 concat3 (Lisp_Object s1, Lisp_Object s2, Lisp_Object s3)
479 return concat (3, ((Lisp_Object []) {s1, s2, s3}), Lisp_String, 0);
482 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
483 doc: /* Concatenate all the arguments and make the result a list.
484 The result is a list whose elements are the elements of all the arguments.
485 Each argument may be a list, vector or string.
486 The last argument is not copied, just used as the tail of the new list.
487 usage: (append &rest SEQUENCES) */)
488 (ptrdiff_t nargs, Lisp_Object *args)
490 return concat (nargs, args, Lisp_Cons, 1);
493 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
494 doc: /* Concatenate all the arguments and make the result a string.
495 The result is a string whose elements are the elements of all the arguments.
496 Each argument may be a string or a list or vector of characters (integers).
497 usage: (concat &rest SEQUENCES) */)
498 (ptrdiff_t nargs, Lisp_Object *args)
500 return concat (nargs, args, Lisp_String, 0);
503 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
504 doc: /* Concatenate all the arguments and make the result a vector.
505 The result is a vector whose elements are the elements of all the arguments.
506 Each argument may be a list, vector or string.
507 usage: (vconcat &rest SEQUENCES) */)
508 (ptrdiff_t nargs, Lisp_Object *args)
510 return concat (nargs, args, Lisp_Vectorlike, 0);
514 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
515 doc: /* Return a copy of a list, vector, string or char-table.
516 The elements of a list or vector are not copied; they are shared
517 with the original. */)
518 (Lisp_Object arg)
520 if (NILP (arg)) return arg;
522 if (CHAR_TABLE_P (arg))
524 return copy_char_table (arg);
527 if (BOOL_VECTOR_P (arg))
529 EMACS_INT nbits = bool_vector_size (arg);
530 ptrdiff_t nbytes = bool_vector_bytes (nbits);
531 Lisp_Object val = make_uninit_bool_vector (nbits);
532 memcpy (bool_vector_data (val), bool_vector_data (arg), nbytes);
533 return val;
536 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
537 wrong_type_argument (Qsequencep, arg);
539 return concat (1, &arg, XTYPE (arg), 0);
542 /* This structure holds information of an argument of `concat' that is
543 a string and has text properties to be copied. */
544 struct textprop_rec
546 ptrdiff_t argnum; /* refer to ARGS (arguments of `concat') */
547 ptrdiff_t from; /* refer to ARGS[argnum] (argument string) */
548 ptrdiff_t to; /* refer to VAL (the target string) */
551 static Lisp_Object
552 concat (ptrdiff_t nargs, Lisp_Object *args,
553 enum Lisp_Type target_type, bool last_special)
555 Lisp_Object val;
556 Lisp_Object tail;
557 Lisp_Object this;
558 ptrdiff_t toindex;
559 ptrdiff_t toindex_byte = 0;
560 EMACS_INT result_len;
561 EMACS_INT result_len_byte;
562 ptrdiff_t argnum;
563 Lisp_Object last_tail;
564 Lisp_Object prev;
565 bool some_multibyte;
566 /* When we make a multibyte string, we can't copy text properties
567 while concatenating each string because the length of resulting
568 string can't be decided until we finish the whole concatenation.
569 So, we record strings that have text properties to be copied
570 here, and copy the text properties after the concatenation. */
571 struct textprop_rec *textprops = NULL;
572 /* Number of elements in textprops. */
573 ptrdiff_t num_textprops = 0;
574 USE_SAFE_ALLOCA;
576 tail = Qnil;
578 /* In append, the last arg isn't treated like the others */
579 if (last_special && nargs > 0)
581 nargs--;
582 last_tail = args[nargs];
584 else
585 last_tail = Qnil;
587 /* Check each argument. */
588 for (argnum = 0; argnum < nargs; argnum++)
590 this = args[argnum];
591 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
592 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
593 wrong_type_argument (Qsequencep, this);
596 /* Compute total length in chars of arguments in RESULT_LEN.
597 If desired output is a string, also compute length in bytes
598 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
599 whether the result should be a multibyte string. */
600 result_len_byte = 0;
601 result_len = 0;
602 some_multibyte = 0;
603 for (argnum = 0; argnum < nargs; argnum++)
605 EMACS_INT len;
606 this = args[argnum];
607 len = XFASTINT (Flength (this));
608 if (target_type == Lisp_String)
610 /* We must count the number of bytes needed in the string
611 as well as the number of characters. */
612 ptrdiff_t i;
613 Lisp_Object ch;
614 int c;
615 ptrdiff_t this_len_byte;
617 if (VECTORP (this) || COMPILEDP (this))
618 for (i = 0; i < len; i++)
620 ch = AREF (this, i);
621 CHECK_CHARACTER (ch);
622 c = XFASTINT (ch);
623 this_len_byte = CHAR_BYTES (c);
624 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
625 string_overflow ();
626 result_len_byte += this_len_byte;
627 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
628 some_multibyte = 1;
630 else if (BOOL_VECTOR_P (this) && bool_vector_size (this) > 0)
631 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
632 else if (CONSP (this))
633 for (; CONSP (this); this = XCDR (this))
635 ch = XCAR (this);
636 CHECK_CHARACTER (ch);
637 c = XFASTINT (ch);
638 this_len_byte = CHAR_BYTES (c);
639 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
640 string_overflow ();
641 result_len_byte += this_len_byte;
642 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
643 some_multibyte = 1;
645 else if (STRINGP (this))
647 if (STRING_MULTIBYTE (this))
649 some_multibyte = 1;
650 this_len_byte = SBYTES (this);
652 else
653 this_len_byte = count_size_as_multibyte (SDATA (this),
654 SCHARS (this));
655 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
656 string_overflow ();
657 result_len_byte += this_len_byte;
661 result_len += len;
662 if (MOST_POSITIVE_FIXNUM < result_len)
663 memory_full (SIZE_MAX);
666 if (! some_multibyte)
667 result_len_byte = result_len;
669 /* Create the output object. */
670 if (target_type == Lisp_Cons)
671 val = Fmake_list (make_number (result_len), Qnil);
672 else if (target_type == Lisp_Vectorlike)
673 val = Fmake_vector (make_number (result_len), Qnil);
674 else if (some_multibyte)
675 val = make_uninit_multibyte_string (result_len, result_len_byte);
676 else
677 val = make_uninit_string (result_len);
679 /* In `append', if all but last arg are nil, return last arg. */
680 if (target_type == Lisp_Cons && EQ (val, Qnil))
681 return last_tail;
683 /* Copy the contents of the args into the result. */
684 if (CONSP (val))
685 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
686 else
687 toindex = 0, toindex_byte = 0;
689 prev = Qnil;
690 if (STRINGP (val))
691 SAFE_NALLOCA (textprops, 1, nargs);
693 for (argnum = 0; argnum < nargs; argnum++)
695 Lisp_Object thislen;
696 ptrdiff_t thisleni = 0;
697 register ptrdiff_t thisindex = 0;
698 register ptrdiff_t thisindex_byte = 0;
700 this = args[argnum];
701 if (!CONSP (this))
702 thislen = Flength (this), thisleni = XINT (thislen);
704 /* Between strings of the same kind, copy fast. */
705 if (STRINGP (this) && STRINGP (val)
706 && STRING_MULTIBYTE (this) == some_multibyte)
708 ptrdiff_t thislen_byte = SBYTES (this);
710 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
711 if (string_intervals (this))
713 textprops[num_textprops].argnum = argnum;
714 textprops[num_textprops].from = 0;
715 textprops[num_textprops++].to = toindex;
717 toindex_byte += thislen_byte;
718 toindex += thisleni;
720 /* Copy a single-byte string to a multibyte string. */
721 else if (STRINGP (this) && STRINGP (val))
723 if (string_intervals (this))
725 textprops[num_textprops].argnum = argnum;
726 textprops[num_textprops].from = 0;
727 textprops[num_textprops++].to = toindex;
729 toindex_byte += copy_text (SDATA (this),
730 SDATA (val) + toindex_byte,
731 SCHARS (this), 0, 1);
732 toindex += thisleni;
734 else
735 /* Copy element by element. */
736 while (1)
738 register Lisp_Object elt;
740 /* Fetch next element of `this' arg into `elt', or break if
741 `this' is exhausted. */
742 if (NILP (this)) break;
743 if (CONSP (this))
744 elt = XCAR (this), this = XCDR (this);
745 else if (thisindex >= thisleni)
746 break;
747 else if (STRINGP (this))
749 int c;
750 if (STRING_MULTIBYTE (this))
751 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
752 thisindex,
753 thisindex_byte);
754 else
756 c = SREF (this, thisindex); thisindex++;
757 if (some_multibyte && !ASCII_CHAR_P (c))
758 c = BYTE8_TO_CHAR (c);
760 XSETFASTINT (elt, c);
762 else if (BOOL_VECTOR_P (this))
764 elt = bool_vector_ref (this, thisindex);
765 thisindex++;
767 else
769 elt = AREF (this, thisindex);
770 thisindex++;
773 /* Store this element into the result. */
774 if (toindex < 0)
776 XSETCAR (tail, elt);
777 prev = tail;
778 tail = XCDR (tail);
780 else if (VECTORP (val))
782 ASET (val, toindex, elt);
783 toindex++;
785 else
787 int c;
788 CHECK_CHARACTER (elt);
789 c = XFASTINT (elt);
790 if (some_multibyte)
791 toindex_byte += CHAR_STRING (c, SDATA (val) + toindex_byte);
792 else
793 SSET (val, toindex_byte++, c);
794 toindex++;
798 if (!NILP (prev))
799 XSETCDR (prev, last_tail);
801 if (num_textprops > 0)
803 Lisp_Object props;
804 ptrdiff_t last_to_end = -1;
806 for (argnum = 0; argnum < num_textprops; argnum++)
808 this = args[textprops[argnum].argnum];
809 props = text_property_list (this,
810 make_number (0),
811 make_number (SCHARS (this)),
812 Qnil);
813 /* If successive arguments have properties, be sure that the
814 value of `composition' property be the copy. */
815 if (last_to_end == textprops[argnum].to)
816 make_composition_value_copy (props);
817 add_text_properties_from_list (val, props,
818 make_number (textprops[argnum].to));
819 last_to_end = textprops[argnum].to + SCHARS (this);
823 SAFE_FREE ();
824 return val;
827 static Lisp_Object string_char_byte_cache_string;
828 static ptrdiff_t string_char_byte_cache_charpos;
829 static ptrdiff_t string_char_byte_cache_bytepos;
831 void
832 clear_string_char_byte_cache (void)
834 string_char_byte_cache_string = Qnil;
837 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
839 ptrdiff_t
840 string_char_to_byte (Lisp_Object string, ptrdiff_t char_index)
842 ptrdiff_t i_byte;
843 ptrdiff_t best_below, best_below_byte;
844 ptrdiff_t best_above, best_above_byte;
846 best_below = best_below_byte = 0;
847 best_above = SCHARS (string);
848 best_above_byte = SBYTES (string);
849 if (best_above == best_above_byte)
850 return char_index;
852 if (EQ (string, string_char_byte_cache_string))
854 if (string_char_byte_cache_charpos < char_index)
856 best_below = string_char_byte_cache_charpos;
857 best_below_byte = string_char_byte_cache_bytepos;
859 else
861 best_above = string_char_byte_cache_charpos;
862 best_above_byte = string_char_byte_cache_bytepos;
866 if (char_index - best_below < best_above - char_index)
868 unsigned char *p = SDATA (string) + best_below_byte;
870 while (best_below < char_index)
872 p += BYTES_BY_CHAR_HEAD (*p);
873 best_below++;
875 i_byte = p - SDATA (string);
877 else
879 unsigned char *p = SDATA (string) + best_above_byte;
881 while (best_above > char_index)
883 p--;
884 while (!CHAR_HEAD_P (*p)) p--;
885 best_above--;
887 i_byte = p - SDATA (string);
890 string_char_byte_cache_bytepos = i_byte;
891 string_char_byte_cache_charpos = char_index;
892 string_char_byte_cache_string = string;
894 return i_byte;
897 /* Return the character index corresponding to BYTE_INDEX in STRING. */
899 ptrdiff_t
900 string_byte_to_char (Lisp_Object string, ptrdiff_t byte_index)
902 ptrdiff_t i, i_byte;
903 ptrdiff_t best_below, best_below_byte;
904 ptrdiff_t best_above, best_above_byte;
906 best_below = best_below_byte = 0;
907 best_above = SCHARS (string);
908 best_above_byte = SBYTES (string);
909 if (best_above == best_above_byte)
910 return byte_index;
912 if (EQ (string, string_char_byte_cache_string))
914 if (string_char_byte_cache_bytepos < byte_index)
916 best_below = string_char_byte_cache_charpos;
917 best_below_byte = string_char_byte_cache_bytepos;
919 else
921 best_above = string_char_byte_cache_charpos;
922 best_above_byte = string_char_byte_cache_bytepos;
926 if (byte_index - best_below_byte < best_above_byte - byte_index)
928 unsigned char *p = SDATA (string) + best_below_byte;
929 unsigned char *pend = SDATA (string) + byte_index;
931 while (p < pend)
933 p += BYTES_BY_CHAR_HEAD (*p);
934 best_below++;
936 i = best_below;
937 i_byte = p - SDATA (string);
939 else
941 unsigned char *p = SDATA (string) + best_above_byte;
942 unsigned char *pbeg = SDATA (string) + byte_index;
944 while (p > pbeg)
946 p--;
947 while (!CHAR_HEAD_P (*p)) p--;
948 best_above--;
950 i = best_above;
951 i_byte = p - SDATA (string);
954 string_char_byte_cache_bytepos = i_byte;
955 string_char_byte_cache_charpos = i;
956 string_char_byte_cache_string = string;
958 return i;
961 /* Convert STRING to a multibyte string. */
963 static Lisp_Object
964 string_make_multibyte (Lisp_Object string)
966 unsigned char *buf;
967 ptrdiff_t nbytes;
968 Lisp_Object ret;
969 USE_SAFE_ALLOCA;
971 if (STRING_MULTIBYTE (string))
972 return string;
974 nbytes = count_size_as_multibyte (SDATA (string),
975 SCHARS (string));
976 /* If all the chars are ASCII, they won't need any more bytes
977 once converted. In that case, we can return STRING itself. */
978 if (nbytes == SBYTES (string))
979 return string;
981 buf = SAFE_ALLOCA (nbytes);
982 copy_text (SDATA (string), buf, SBYTES (string),
983 0, 1);
985 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
986 SAFE_FREE ();
988 return ret;
992 /* Convert STRING (if unibyte) to a multibyte string without changing
993 the number of characters. Characters 0200 trough 0237 are
994 converted to eight-bit characters. */
996 Lisp_Object
997 string_to_multibyte (Lisp_Object string)
999 unsigned char *buf;
1000 ptrdiff_t nbytes;
1001 Lisp_Object ret;
1002 USE_SAFE_ALLOCA;
1004 if (STRING_MULTIBYTE (string))
1005 return string;
1007 nbytes = count_size_as_multibyte (SDATA (string), SBYTES (string));
1008 /* If all the chars are ASCII, they won't need any more bytes once
1009 converted. */
1010 if (nbytes == SBYTES (string))
1011 return make_multibyte_string (SSDATA (string), nbytes, nbytes);
1013 buf = SAFE_ALLOCA (nbytes);
1014 memcpy (buf, SDATA (string), SBYTES (string));
1015 str_to_multibyte (buf, nbytes, SBYTES (string));
1017 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
1018 SAFE_FREE ();
1020 return ret;
1024 /* Convert STRING to a single-byte string. */
1026 Lisp_Object
1027 string_make_unibyte (Lisp_Object string)
1029 ptrdiff_t nchars;
1030 unsigned char *buf;
1031 Lisp_Object ret;
1032 USE_SAFE_ALLOCA;
1034 if (! STRING_MULTIBYTE (string))
1035 return string;
1037 nchars = SCHARS (string);
1039 buf = SAFE_ALLOCA (nchars);
1040 copy_text (SDATA (string), buf, SBYTES (string),
1041 1, 0);
1043 ret = make_unibyte_string ((char *) buf, nchars);
1044 SAFE_FREE ();
1046 return ret;
1049 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
1050 1, 1, 0,
1051 doc: /* Return the multibyte equivalent of STRING.
1052 If STRING is unibyte and contains non-ASCII characters, the function
1053 `unibyte-char-to-multibyte' is used to convert each unibyte character
1054 to a multibyte character. In this case, the returned string is a
1055 newly created string with no text properties. If STRING is multibyte
1056 or entirely ASCII, it is returned unchanged. In particular, when
1057 STRING is unibyte and entirely ASCII, the returned string is unibyte.
1058 \(When the characters are all ASCII, Emacs primitives will treat the
1059 string the same way whether it is unibyte or multibyte.) */)
1060 (Lisp_Object string)
1062 CHECK_STRING (string);
1064 return string_make_multibyte (string);
1067 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
1068 1, 1, 0,
1069 doc: /* Return the unibyte equivalent of STRING.
1070 Multibyte character codes are converted to unibyte according to
1071 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
1072 If the lookup in the translation table fails, this function takes just
1073 the low 8 bits of each character. */)
1074 (Lisp_Object string)
1076 CHECK_STRING (string);
1078 return string_make_unibyte (string);
1081 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
1082 1, 1, 0,
1083 doc: /* Return a unibyte string with the same individual bytes as STRING.
1084 If STRING is unibyte, the result is STRING itself.
1085 Otherwise it is a newly created string, with no text properties.
1086 If STRING is multibyte and contains a character of charset
1087 `eight-bit', it is converted to the corresponding single byte. */)
1088 (Lisp_Object string)
1090 CHECK_STRING (string);
1092 if (STRING_MULTIBYTE (string))
1094 unsigned char *str = (unsigned char *) xlispstrdup (string);
1095 ptrdiff_t bytes = str_as_unibyte (str, SBYTES (string));
1097 string = make_unibyte_string ((char *) str, bytes);
1098 xfree (str);
1100 return string;
1103 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1104 1, 1, 0,
1105 doc: /* Return a multibyte string with the same individual bytes as STRING.
1106 If STRING is multibyte, the result is STRING itself.
1107 Otherwise it is a newly created string, with no text properties.
1109 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1110 part of a correct utf-8 sequence), it is converted to the corresponding
1111 multibyte character of charset `eight-bit'.
1112 See also `string-to-multibyte'.
1114 Beware, this often doesn't really do what you think it does.
1115 It is similar to (decode-coding-string STRING \\='utf-8-emacs).
1116 If you're not sure, whether to use `string-as-multibyte' or
1117 `string-to-multibyte', use `string-to-multibyte'. */)
1118 (Lisp_Object string)
1120 CHECK_STRING (string);
1122 if (! STRING_MULTIBYTE (string))
1124 Lisp_Object new_string;
1125 ptrdiff_t nchars, nbytes;
1127 parse_str_as_multibyte (SDATA (string),
1128 SBYTES (string),
1129 &nchars, &nbytes);
1130 new_string = make_uninit_multibyte_string (nchars, nbytes);
1131 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1132 if (nbytes != SBYTES (string))
1133 str_as_multibyte (SDATA (new_string), nbytes,
1134 SBYTES (string), NULL);
1135 string = new_string;
1136 set_string_intervals (string, NULL);
1138 return string;
1141 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1142 1, 1, 0,
1143 doc: /* Return a multibyte string with the same individual chars as STRING.
1144 If STRING is multibyte, the result is STRING itself.
1145 Otherwise it is a newly created string, with no text properties.
1147 If STRING is unibyte and contains an 8-bit byte, it is converted to
1148 the corresponding multibyte character of charset `eight-bit'.
1150 This differs from `string-as-multibyte' by converting each byte of a correct
1151 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1152 correct sequence. */)
1153 (Lisp_Object string)
1155 CHECK_STRING (string);
1157 return string_to_multibyte (string);
1160 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1161 1, 1, 0,
1162 doc: /* Return a unibyte string with the same individual chars as STRING.
1163 If STRING is unibyte, the result is STRING itself.
1164 Otherwise it is a newly created string, with no text properties,
1165 where each `eight-bit' character is converted to the corresponding byte.
1166 If STRING contains a non-ASCII, non-`eight-bit' character,
1167 an error is signaled. */)
1168 (Lisp_Object string)
1170 CHECK_STRING (string);
1172 if (STRING_MULTIBYTE (string))
1174 ptrdiff_t chars = SCHARS (string);
1175 unsigned char *str = xmalloc (chars);
1176 ptrdiff_t converted = str_to_unibyte (SDATA (string), str, chars);
1178 if (converted < chars)
1179 error ("Can't convert the %"pD"dth character to unibyte", converted);
1180 string = make_unibyte_string ((char *) str, chars);
1181 xfree (str);
1183 return string;
1187 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1188 doc: /* Return a copy of ALIST.
1189 This is an alist which represents the same mapping from objects to objects,
1190 but does not share the alist structure with ALIST.
1191 The objects mapped (cars and cdrs of elements of the alist)
1192 are shared, however.
1193 Elements of ALIST that are not conses are also shared. */)
1194 (Lisp_Object alist)
1196 if (NILP (alist))
1197 return alist;
1198 alist = concat (1, &alist, Lisp_Cons, false);
1199 for (Lisp_Object tem = alist; !NILP (tem); tem = XCDR (tem))
1201 Lisp_Object car = XCAR (tem);
1202 if (CONSP (car))
1203 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1205 return alist;
1208 /* Check that ARRAY can have a valid subarray [FROM..TO),
1209 given that its size is SIZE.
1210 If FROM is nil, use 0; if TO is nil, use SIZE.
1211 Count negative values backwards from the end.
1212 Set *IFROM and *ITO to the two indexes used. */
1214 void
1215 validate_subarray (Lisp_Object array, Lisp_Object from, Lisp_Object to,
1216 ptrdiff_t size, ptrdiff_t *ifrom, ptrdiff_t *ito)
1218 EMACS_INT f, t;
1220 if (INTEGERP (from))
1222 f = XINT (from);
1223 if (f < 0)
1224 f += size;
1226 else if (NILP (from))
1227 f = 0;
1228 else
1229 wrong_type_argument (Qintegerp, from);
1231 if (INTEGERP (to))
1233 t = XINT (to);
1234 if (t < 0)
1235 t += size;
1237 else if (NILP (to))
1238 t = size;
1239 else
1240 wrong_type_argument (Qintegerp, to);
1242 if (! (0 <= f && f <= t && t <= size))
1243 args_out_of_range_3 (array, from, to);
1245 *ifrom = f;
1246 *ito = t;
1249 DEFUN ("substring", Fsubstring, Ssubstring, 1, 3, 0,
1250 doc: /* Return a new string whose contents are a substring of STRING.
1251 The returned string consists of the characters between index FROM
1252 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1253 zero-indexed: 0 means the first character of STRING. Negative values
1254 are counted from the end of STRING. If TO is nil, the substring runs
1255 to the end of STRING.
1257 The STRING argument may also be a vector. In that case, the return
1258 value is a new vector that contains the elements between index FROM
1259 \(inclusive) and index TO (exclusive) of that vector argument.
1261 With one argument, just copy STRING (with properties, if any). */)
1262 (Lisp_Object string, Lisp_Object from, Lisp_Object to)
1264 Lisp_Object res;
1265 ptrdiff_t size, ifrom, ito;
1267 size = CHECK_VECTOR_OR_STRING (string);
1268 validate_subarray (string, from, to, size, &ifrom, &ito);
1270 if (STRINGP (string))
1272 ptrdiff_t from_byte
1273 = !ifrom ? 0 : string_char_to_byte (string, ifrom);
1274 ptrdiff_t to_byte
1275 = ito == size ? SBYTES (string) : string_char_to_byte (string, ito);
1276 res = make_specified_string (SSDATA (string) + from_byte,
1277 ito - ifrom, to_byte - from_byte,
1278 STRING_MULTIBYTE (string));
1279 copy_text_properties (make_number (ifrom), make_number (ito),
1280 string, make_number (0), res, Qnil);
1282 else
1283 res = Fvector (ito - ifrom, aref_addr (string, ifrom));
1285 return res;
1289 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1290 doc: /* Return a substring of STRING, without text properties.
1291 It starts at index FROM and ends before TO.
1292 TO may be nil or omitted; then the substring runs to the end of STRING.
1293 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1294 If FROM or TO is negative, it counts from the end.
1296 With one argument, just copy STRING without its properties. */)
1297 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1299 ptrdiff_t from_char, to_char, from_byte, to_byte, size;
1301 CHECK_STRING (string);
1303 size = SCHARS (string);
1304 validate_subarray (string, from, to, size, &from_char, &to_char);
1306 from_byte = !from_char ? 0 : string_char_to_byte (string, from_char);
1307 to_byte =
1308 to_char == size ? SBYTES (string) : string_char_to_byte (string, to_char);
1309 return make_specified_string (SSDATA (string) + from_byte,
1310 to_char - from_char, to_byte - from_byte,
1311 STRING_MULTIBYTE (string));
1314 /* Extract a substring of STRING, giving start and end positions
1315 both in characters and in bytes. */
1317 Lisp_Object
1318 substring_both (Lisp_Object string, ptrdiff_t from, ptrdiff_t from_byte,
1319 ptrdiff_t to, ptrdiff_t to_byte)
1321 Lisp_Object res;
1322 ptrdiff_t size = CHECK_VECTOR_OR_STRING (string);
1324 if (!(0 <= from && from <= to && to <= size))
1325 args_out_of_range_3 (string, make_number (from), make_number (to));
1327 if (STRINGP (string))
1329 res = make_specified_string (SSDATA (string) + from_byte,
1330 to - from, to_byte - from_byte,
1331 STRING_MULTIBYTE (string));
1332 copy_text_properties (make_number (from), make_number (to),
1333 string, make_number (0), res, Qnil);
1335 else
1336 res = Fvector (to - from, aref_addr (string, from));
1338 return res;
1341 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1342 doc: /* Take cdr N times on LIST, return the result. */)
1343 (Lisp_Object n, Lisp_Object list)
1345 CHECK_NUMBER (n);
1346 Lisp_Object tail = list;
1347 for (EMACS_INT num = XINT (n); 0 < num; num--)
1349 if (! CONSP (tail))
1351 CHECK_LIST_END (tail, list);
1352 return Qnil;
1354 tail = XCDR (tail);
1355 rarely_quit (num);
1357 return tail;
1360 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1361 doc: /* Return the Nth element of LIST.
1362 N counts from zero. If LIST is not that long, nil is returned. */)
1363 (Lisp_Object n, Lisp_Object list)
1365 return Fcar (Fnthcdr (n, list));
1368 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1369 doc: /* Return element of SEQUENCE at index N. */)
1370 (register Lisp_Object sequence, Lisp_Object n)
1372 CHECK_NUMBER (n);
1373 if (CONSP (sequence) || NILP (sequence))
1374 return Fcar (Fnthcdr (n, sequence));
1376 /* Faref signals a "not array" error, so check here. */
1377 CHECK_ARRAY (sequence, Qsequencep);
1378 return Faref (sequence, n);
1381 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1382 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1383 The value is actually the tail of LIST whose car is ELT. */)
1384 (Lisp_Object elt, Lisp_Object list)
1386 unsigned short int quit_count = 0;
1387 Lisp_Object tail;
1388 for (tail = list; CONSP (tail); tail = XCDR (tail))
1390 if (! NILP (Fequal (elt, XCAR (tail))))
1391 return tail;
1392 rarely_quit (++quit_count);
1394 CHECK_LIST_END (tail, list);
1395 return Qnil;
1398 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1399 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1400 The value is actually the tail of LIST whose car is ELT. */)
1401 (Lisp_Object elt, Lisp_Object list)
1403 unsigned short int quit_count = 0;
1404 Lisp_Object tail;
1405 for (tail = list; CONSP (tail); tail = XCDR (tail))
1407 if (EQ (XCAR (tail), elt))
1408 return tail;
1409 rarely_quit (++quit_count);
1411 CHECK_LIST_END (tail, list);
1412 return Qnil;
1415 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1416 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1417 The value is actually the tail of LIST whose car is ELT. */)
1418 (Lisp_Object elt, Lisp_Object list)
1420 if (!FLOATP (elt))
1421 return Fmemq (elt, list);
1423 unsigned short int quit_count = 0;
1424 Lisp_Object tail;
1425 for (tail = list; CONSP (tail); tail = XCDR (tail))
1427 Lisp_Object tem = XCAR (tail);
1428 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0, Qnil))
1429 return tail;
1430 rarely_quit (++quit_count);
1432 CHECK_LIST_END (tail, list);
1433 return Qnil;
1436 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1437 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1438 The value is actually the first element of LIST whose car is KEY.
1439 Elements of LIST that are not conses are ignored. */)
1440 (Lisp_Object key, Lisp_Object list)
1442 unsigned short int quit_count = 0;
1443 Lisp_Object tail;
1444 for (tail = list; CONSP (tail); tail = XCDR (tail))
1446 if (CONSP (XCAR (tail)) && EQ (XCAR (XCAR (tail)), key))
1447 return XCAR (tail);
1448 rarely_quit (++quit_count);
1450 CHECK_LIST_END (tail, list);
1451 return Qnil;
1454 /* Like Fassq but never report an error and do not allow quits.
1455 Use only on objects known to be non-circular lists. */
1457 Lisp_Object
1458 assq_no_quit (Lisp_Object key, Lisp_Object list)
1460 for (; ! NILP (list); list = XCDR (list))
1461 if (CONSP (XCAR (list)) && EQ (XCAR (XCAR (list)), key))
1462 return XCAR (list);
1463 return Qnil;
1466 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1467 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1468 The value is actually the first element of LIST whose car equals KEY. */)
1469 (Lisp_Object key, Lisp_Object list)
1471 unsigned short int quit_count = 0;
1472 Lisp_Object tail;
1473 for (tail = list; CONSP (tail); tail = XCDR (tail))
1475 Lisp_Object car = XCAR (tail);
1476 if (CONSP (car)
1477 && (EQ (XCAR (car), key) || !NILP (Fequal (XCAR (car), key))))
1478 return car;
1479 rarely_quit (++quit_count);
1481 CHECK_LIST_END (tail, list);
1482 return Qnil;
1485 /* Like Fassoc but never report an error and do not allow quits.
1486 Use only on objects known to be non-circular lists. */
1488 Lisp_Object
1489 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1491 for (; ! NILP (list); list = XCDR (list))
1493 Lisp_Object car = XCAR (list);
1494 if (CONSP (car)
1495 && (EQ (XCAR (car), key) || !NILP (Fequal (XCAR (car), key))))
1496 return car;
1498 return Qnil;
1501 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1502 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1503 The value is actually the first element of LIST whose cdr is KEY. */)
1504 (Lisp_Object key, Lisp_Object list)
1506 unsigned short int quit_count = 0;
1507 Lisp_Object tail;
1508 for (tail = list; CONSP (tail); tail = XCDR (tail))
1510 if (CONSP (XCAR (tail)) && EQ (XCDR (XCAR (tail)), key))
1511 return XCAR (tail);
1512 rarely_quit (++quit_count);
1514 CHECK_LIST_END (tail, list);
1515 return Qnil;
1518 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1519 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1520 The value is actually the first element of LIST whose cdr equals KEY. */)
1521 (Lisp_Object key, Lisp_Object list)
1523 unsigned short int quit_count = 0;
1524 Lisp_Object tail;
1525 for (tail = list; CONSP (tail); tail = XCDR (tail))
1527 Lisp_Object car = XCAR (tail);
1528 if (CONSP (car)
1529 && (EQ (XCDR (car), key) || !NILP (Fequal (XCDR (car), key))))
1530 return car;
1531 rarely_quit (++quit_count);
1533 CHECK_LIST_END (tail, list);
1534 return Qnil;
1537 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1538 doc: /* Delete members of LIST which are `eq' to ELT, and return the result.
1539 More precisely, this function skips any members `eq' to ELT at the
1540 front of LIST, then removes members `eq' to ELT from the remaining
1541 sublist by modifying its list structure, then returns the resulting
1542 list.
1544 Write `(setq foo (delq element foo))' to be sure of correctly changing
1545 the value of a list `foo'. See also `remq', which does not modify the
1546 argument. */)
1547 (register Lisp_Object elt, Lisp_Object list)
1549 Lisp_Object tail, tortoise, prev = Qnil;
1550 bool skip;
1552 FOR_EACH_TAIL (tail, list, tortoise, skip)
1554 Lisp_Object tem = XCAR (tail);
1555 if (EQ (elt, tem))
1557 if (NILP (prev))
1558 list = XCDR (tail);
1559 else
1560 Fsetcdr (prev, XCDR (tail));
1562 else
1563 prev = tail;
1565 CHECK_LIST_END (tail, list);
1566 return list;
1569 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1570 doc: /* Delete members of SEQ which are `equal' to ELT, and return the result.
1571 SEQ must be a sequence (i.e. a list, a vector, or a string).
1572 The return value is a sequence of the same type.
1574 If SEQ is a list, this behaves like `delq', except that it compares
1575 with `equal' instead of `eq'. In particular, it may remove elements
1576 by altering the list structure.
1578 If SEQ is not a list, deletion is never performed destructively;
1579 instead this function creates and returns a new vector or string.
1581 Write `(setq foo (delete element foo))' to be sure of correctly
1582 changing the value of a sequence `foo'. */)
1583 (Lisp_Object elt, Lisp_Object seq)
1585 if (VECTORP (seq))
1587 ptrdiff_t i, n;
1589 for (i = n = 0; i < ASIZE (seq); ++i)
1590 if (NILP (Fequal (AREF (seq, i), elt)))
1591 ++n;
1593 if (n != ASIZE (seq))
1595 struct Lisp_Vector *p = allocate_vector (n);
1597 for (i = n = 0; i < ASIZE (seq); ++i)
1598 if (NILP (Fequal (AREF (seq, i), elt)))
1599 p->contents[n++] = AREF (seq, i);
1601 XSETVECTOR (seq, p);
1604 else if (STRINGP (seq))
1606 ptrdiff_t i, ibyte, nchars, nbytes, cbytes;
1607 int c;
1609 for (i = nchars = nbytes = ibyte = 0;
1610 i < SCHARS (seq);
1611 ++i, ibyte += cbytes)
1613 if (STRING_MULTIBYTE (seq))
1615 c = STRING_CHAR (SDATA (seq) + ibyte);
1616 cbytes = CHAR_BYTES (c);
1618 else
1620 c = SREF (seq, i);
1621 cbytes = 1;
1624 if (!INTEGERP (elt) || c != XINT (elt))
1626 ++nchars;
1627 nbytes += cbytes;
1631 if (nchars != SCHARS (seq))
1633 Lisp_Object tem;
1635 tem = make_uninit_multibyte_string (nchars, nbytes);
1636 if (!STRING_MULTIBYTE (seq))
1637 STRING_SET_UNIBYTE (tem);
1639 for (i = nchars = nbytes = ibyte = 0;
1640 i < SCHARS (seq);
1641 ++i, ibyte += cbytes)
1643 if (STRING_MULTIBYTE (seq))
1645 c = STRING_CHAR (SDATA (seq) + ibyte);
1646 cbytes = CHAR_BYTES (c);
1648 else
1650 c = SREF (seq, i);
1651 cbytes = 1;
1654 if (!INTEGERP (elt) || c != XINT (elt))
1656 unsigned char *from = SDATA (seq) + ibyte;
1657 unsigned char *to = SDATA (tem) + nbytes;
1658 ptrdiff_t n;
1660 ++nchars;
1661 nbytes += cbytes;
1663 for (n = cbytes; n--; )
1664 *to++ = *from++;
1668 seq = tem;
1671 else
1673 unsigned short int quit_count = 0;
1674 Lisp_Object tail, prev;
1676 for (tail = seq, prev = Qnil; CONSP (tail); tail = XCDR (tail))
1678 if (!NILP (Fequal (elt, XCAR (tail))))
1680 if (NILP (prev))
1681 seq = XCDR (tail);
1682 else
1683 Fsetcdr (prev, XCDR (tail));
1685 else
1686 prev = tail;
1687 rarely_quit (++quit_count);
1689 CHECK_LIST_END (tail, seq);
1692 return seq;
1695 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1696 doc: /* Reverse order of items in a list, vector or string SEQ.
1697 If SEQ is a list, it should be nil-terminated.
1698 This function may destructively modify SEQ to produce the value. */)
1699 (Lisp_Object seq)
1701 if (NILP (seq))
1702 return seq;
1703 else if (STRINGP (seq))
1704 return Freverse (seq);
1705 else if (CONSP (seq))
1707 unsigned short int quit_count = 0;
1708 Lisp_Object prev, tail, next;
1710 for (prev = Qnil, tail = seq; CONSP (tail); tail = next)
1712 next = XCDR (tail);
1713 Fsetcdr (tail, prev);
1714 prev = tail;
1715 rarely_quit (++quit_count);
1717 CHECK_LIST_END (tail, seq);
1718 seq = prev;
1720 else if (VECTORP (seq))
1722 ptrdiff_t i, size = ASIZE (seq);
1724 for (i = 0; i < size / 2; i++)
1726 Lisp_Object tem = AREF (seq, i);
1727 ASET (seq, i, AREF (seq, size - i - 1));
1728 ASET (seq, size - i - 1, tem);
1731 else if (BOOL_VECTOR_P (seq))
1733 ptrdiff_t i, size = bool_vector_size (seq);
1735 for (i = 0; i < size / 2; i++)
1737 bool tem = bool_vector_bitref (seq, i);
1738 bool_vector_set (seq, i, bool_vector_bitref (seq, size - i - 1));
1739 bool_vector_set (seq, size - i - 1, tem);
1742 else
1743 wrong_type_argument (Qarrayp, seq);
1744 return seq;
1747 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1748 doc: /* Return the reversed copy of list, vector, or string SEQ.
1749 See also the function `nreverse', which is used more often. */)
1750 (Lisp_Object seq)
1752 Lisp_Object new;
1754 if (NILP (seq))
1755 return Qnil;
1756 else if (CONSP (seq))
1758 unsigned short int quit_count = 0;
1759 for (new = Qnil; CONSP (seq); seq = XCDR (seq))
1761 new = Fcons (XCAR (seq), new);
1762 rarely_quit (++quit_count);
1764 CHECK_LIST_END (seq, seq);
1766 else if (VECTORP (seq))
1768 ptrdiff_t i, size = ASIZE (seq);
1770 new = make_uninit_vector (size);
1771 for (i = 0; i < size; i++)
1772 ASET (new, i, AREF (seq, size - i - 1));
1774 else if (BOOL_VECTOR_P (seq))
1776 ptrdiff_t i;
1777 EMACS_INT nbits = bool_vector_size (seq);
1779 new = make_uninit_bool_vector (nbits);
1780 for (i = 0; i < nbits; i++)
1781 bool_vector_set (new, i, bool_vector_bitref (seq, nbits - i - 1));
1783 else if (STRINGP (seq))
1785 ptrdiff_t size = SCHARS (seq), bytes = SBYTES (seq);
1787 if (size == bytes)
1789 ptrdiff_t i;
1791 new = make_uninit_string (size);
1792 for (i = 0; i < size; i++)
1793 SSET (new, i, SREF (seq, size - i - 1));
1795 else
1797 unsigned char *p, *q;
1799 new = make_uninit_multibyte_string (size, bytes);
1800 p = SDATA (seq), q = SDATA (new) + bytes;
1801 while (q > SDATA (new))
1803 int ch, len;
1805 ch = STRING_CHAR_AND_LENGTH (p, len);
1806 p += len, q -= len;
1807 CHAR_STRING (ch, q);
1811 else
1812 wrong_type_argument (Qsequencep, seq);
1813 return new;
1816 /* Sort LIST using PREDICATE, preserving original order of elements
1817 considered as equal. */
1819 static Lisp_Object
1820 sort_list (Lisp_Object list, Lisp_Object predicate)
1822 Lisp_Object front, back;
1823 Lisp_Object len, tem;
1824 EMACS_INT length;
1826 front = list;
1827 len = Flength (list);
1828 length = XINT (len);
1829 if (length < 2)
1830 return list;
1832 XSETINT (len, (length / 2) - 1);
1833 tem = Fnthcdr (len, list);
1834 back = Fcdr (tem);
1835 Fsetcdr (tem, Qnil);
1837 front = Fsort (front, predicate);
1838 back = Fsort (back, predicate);
1839 return merge (front, back, predicate);
1842 /* Using PRED to compare, return whether A and B are in order.
1843 Compare stably when A appeared before B in the input. */
1844 static bool
1845 inorder (Lisp_Object pred, Lisp_Object a, Lisp_Object b)
1847 return NILP (call2 (pred, b, a));
1850 /* Using PRED to compare, merge from ALEN-length A and BLEN-length B
1851 into DEST. Argument arrays must be nonempty and must not overlap,
1852 except that B might be the last part of DEST. */
1853 static void
1854 merge_vectors (Lisp_Object pred,
1855 ptrdiff_t alen, Lisp_Object const a[restrict VLA_ELEMS (alen)],
1856 ptrdiff_t blen, Lisp_Object const b[VLA_ELEMS (blen)],
1857 Lisp_Object dest[VLA_ELEMS (alen + blen)])
1859 eassume (0 < alen && 0 < blen);
1860 Lisp_Object const *alim = a + alen;
1861 Lisp_Object const *blim = b + blen;
1863 while (true)
1865 if (inorder (pred, a[0], b[0]))
1867 *dest++ = *a++;
1868 if (a == alim)
1870 if (dest != b)
1871 memcpy (dest, b, (blim - b) * sizeof *dest);
1872 return;
1875 else
1877 *dest++ = *b++;
1878 if (b == blim)
1880 memcpy (dest, a, (alim - a) * sizeof *dest);
1881 return;
1887 /* Using PRED to compare, sort LEN-length VEC in place, using TMP for
1888 temporary storage. LEN must be at least 2. */
1889 static void
1890 sort_vector_inplace (Lisp_Object pred, ptrdiff_t len,
1891 Lisp_Object vec[restrict VLA_ELEMS (len)],
1892 Lisp_Object tmp[restrict VLA_ELEMS (len >> 1)])
1894 eassume (2 <= len);
1895 ptrdiff_t halflen = len >> 1;
1896 sort_vector_copy (pred, halflen, vec, tmp);
1897 if (1 < len - halflen)
1898 sort_vector_inplace (pred, len - halflen, vec + halflen, vec);
1899 merge_vectors (pred, halflen, tmp, len - halflen, vec + halflen, vec);
1902 /* Using PRED to compare, sort from LEN-length SRC into DST.
1903 Len must be positive. */
1904 static void
1905 sort_vector_copy (Lisp_Object pred, ptrdiff_t len,
1906 Lisp_Object src[restrict VLA_ELEMS (len)],
1907 Lisp_Object dest[restrict VLA_ELEMS (len)])
1909 eassume (0 < len);
1910 ptrdiff_t halflen = len >> 1;
1911 if (halflen < 1)
1912 dest[0] = src[0];
1913 else
1915 if (1 < halflen)
1916 sort_vector_inplace (pred, halflen, src, dest);
1917 if (1 < len - halflen)
1918 sort_vector_inplace (pred, len - halflen, src + halflen, dest);
1919 merge_vectors (pred, halflen, src, len - halflen, src + halflen, dest);
1923 /* Sort VECTOR in place using PREDICATE, preserving original order of
1924 elements considered as equal. */
1926 static void
1927 sort_vector (Lisp_Object vector, Lisp_Object predicate)
1929 ptrdiff_t len = ASIZE (vector);
1930 if (len < 2)
1931 return;
1932 ptrdiff_t halflen = len >> 1;
1933 Lisp_Object *tmp;
1934 USE_SAFE_ALLOCA;
1935 SAFE_ALLOCA_LISP (tmp, halflen);
1936 for (ptrdiff_t i = 0; i < halflen; i++)
1937 tmp[i] = make_number (0);
1938 sort_vector_inplace (predicate, len, XVECTOR (vector)->contents, tmp);
1939 SAFE_FREE ();
1942 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
1943 doc: /* Sort SEQ, stably, comparing elements using PREDICATE.
1944 Returns the sorted sequence. SEQ should be a list or vector. SEQ is
1945 modified by side effects. PREDICATE is called with two elements of
1946 SEQ, and should return non-nil if the first element should sort before
1947 the second. */)
1948 (Lisp_Object seq, Lisp_Object predicate)
1950 if (CONSP (seq))
1951 seq = sort_list (seq, predicate);
1952 else if (VECTORP (seq))
1953 sort_vector (seq, predicate);
1954 else if (!NILP (seq))
1955 wrong_type_argument (Qsequencep, seq);
1956 return seq;
1959 Lisp_Object
1960 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
1962 Lisp_Object l1 = org_l1;
1963 Lisp_Object l2 = org_l2;
1964 Lisp_Object tail = Qnil;
1965 Lisp_Object value = Qnil;
1967 while (1)
1969 if (NILP (l1))
1971 if (NILP (tail))
1972 return l2;
1973 Fsetcdr (tail, l2);
1974 return value;
1976 if (NILP (l2))
1978 if (NILP (tail))
1979 return l1;
1980 Fsetcdr (tail, l1);
1981 return value;
1984 Lisp_Object tem;
1985 if (inorder (pred, Fcar (l1), Fcar (l2)))
1987 tem = l1;
1988 l1 = Fcdr (l1);
1989 org_l1 = l1;
1991 else
1993 tem = l2;
1994 l2 = Fcdr (l2);
1995 org_l2 = l2;
1997 if (NILP (tail))
1998 value = tem;
1999 else
2000 Fsetcdr (tail, tem);
2001 tail = tem;
2006 /* This does not check for quits. That is safe since it must terminate. */
2008 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
2009 doc: /* Extract a value from a property list.
2010 PLIST is a property list, which is a list of the form
2011 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2012 corresponding to the given PROP, or nil if PROP is not one of the
2013 properties on the list. This function never signals an error. */)
2014 (Lisp_Object plist, Lisp_Object prop)
2016 Lisp_Object tail, halftail;
2018 /* halftail is used to detect circular lists. */
2019 tail = halftail = plist;
2020 while (CONSP (tail) && CONSP (XCDR (tail)))
2022 if (EQ (prop, XCAR (tail)))
2023 return XCAR (XCDR (tail));
2025 tail = XCDR (XCDR (tail));
2026 halftail = XCDR (halftail);
2027 if (EQ (tail, halftail))
2028 break;
2031 return Qnil;
2034 DEFUN ("get", Fget, Sget, 2, 2, 0,
2035 doc: /* Return the value of SYMBOL's PROPNAME property.
2036 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
2037 (Lisp_Object symbol, Lisp_Object propname)
2039 CHECK_SYMBOL (symbol);
2040 return Fplist_get (XSYMBOL (symbol)->plist, propname);
2043 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
2044 doc: /* Change value in PLIST of PROP to VAL.
2045 PLIST is a property list, which is a list of the form
2046 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
2047 If PROP is already a property on the list, its value is set to VAL,
2048 otherwise the new PROP VAL pair is added. The new plist is returned;
2049 use `(setq x (plist-put x prop val))' to be sure to use the new value.
2050 The PLIST is modified by side effects. */)
2051 (Lisp_Object plist, Lisp_Object prop, Lisp_Object val)
2053 unsigned short int quit_count = 0;
2054 Lisp_Object prev = Qnil;
2055 for (Lisp_Object tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2056 tail = XCDR (XCDR (tail)))
2058 if (EQ (prop, XCAR (tail)))
2060 Fsetcar (XCDR (tail), val);
2061 return plist;
2064 prev = tail;
2065 rarely_quit (++quit_count);
2067 Lisp_Object newcell
2068 = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
2069 if (NILP (prev))
2070 return newcell;
2071 Fsetcdr (XCDR (prev), newcell);
2072 return plist;
2075 DEFUN ("put", Fput, Sput, 3, 3, 0,
2076 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
2077 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
2078 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
2080 CHECK_SYMBOL (symbol);
2081 set_symbol_plist
2082 (symbol, Fplist_put (XSYMBOL (symbol)->plist, propname, value));
2083 return value;
2086 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
2087 doc: /* Extract a value from a property list, comparing with `equal'.
2088 PLIST is a property list, which is a list of the form
2089 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2090 corresponding to the given PROP, or nil if PROP is not
2091 one of the properties on the list. */)
2092 (Lisp_Object plist, Lisp_Object prop)
2094 unsigned short int quit_count = 0;
2095 Lisp_Object tail;
2097 for (tail = plist;
2098 CONSP (tail) && CONSP (XCDR (tail));
2099 tail = XCDR (XCDR (tail)))
2101 if (! NILP (Fequal (prop, XCAR (tail))))
2102 return XCAR (XCDR (tail));
2103 rarely_quit (++quit_count);
2106 CHECK_LIST_END (tail, prop);
2108 return Qnil;
2111 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
2112 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
2113 PLIST is a property list, which is a list of the form
2114 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
2115 If PROP is already a property on the list, its value is set to VAL,
2116 otherwise the new PROP VAL pair is added. The new plist is returned;
2117 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
2118 The PLIST is modified by side effects. */)
2119 (Lisp_Object plist, Lisp_Object prop, Lisp_Object val)
2121 unsigned short int quit_count = 0;
2122 Lisp_Object prev = Qnil;
2123 for (Lisp_Object tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2124 tail = XCDR (XCDR (tail)))
2126 if (! NILP (Fequal (prop, XCAR (tail))))
2128 Fsetcar (XCDR (tail), val);
2129 return plist;
2132 prev = tail;
2133 rarely_quit (++quit_count);
2135 Lisp_Object newcell = list2 (prop, val);
2136 if (NILP (prev))
2137 return newcell;
2138 Fsetcdr (XCDR (prev), newcell);
2139 return plist;
2142 DEFUN ("eql", Feql, Seql, 2, 2, 0,
2143 doc: /* Return t if the two args are the same Lisp object.
2144 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
2145 (Lisp_Object obj1, Lisp_Object obj2)
2147 if (FLOATP (obj1))
2148 return internal_equal (obj1, obj2, 0, 0, Qnil) ? Qt : Qnil;
2149 else
2150 return EQ (obj1, obj2) ? Qt : Qnil;
2153 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
2154 doc: /* Return t if two Lisp objects have similar structure and contents.
2155 They must have the same data type.
2156 Conses are compared by comparing the cars and the cdrs.
2157 Vectors and strings are compared element by element.
2158 Numbers are compared by value, but integers cannot equal floats.
2159 (Use `=' if you want integers and floats to be able to be equal.)
2160 Symbols must match exactly. */)
2161 (register Lisp_Object o1, Lisp_Object o2)
2163 return internal_equal (o1, o2, 0, 0, Qnil) ? Qt : Qnil;
2166 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
2167 doc: /* Return t if two Lisp objects have similar structure and contents.
2168 This is like `equal' except that it compares the text properties
2169 of strings. (`equal' ignores text properties.) */)
2170 (register Lisp_Object o1, Lisp_Object o2)
2172 return internal_equal (o1, o2, 0, 1, Qnil) ? Qt : Qnil;
2175 /* DEPTH is current depth of recursion. Signal an error if it
2176 gets too deep.
2177 PROPS means compare string text properties too. */
2179 static bool
2180 internal_equal (Lisp_Object o1, Lisp_Object o2, int depth, bool props,
2181 Lisp_Object ht)
2183 if (depth > 10)
2185 if (depth > 200)
2186 error ("Stack overflow in equal");
2187 if (NILP (ht))
2188 ht = CALLN (Fmake_hash_table, QCtest, Qeq);
2189 switch (XTYPE (o1))
2191 case Lisp_Cons: case Lisp_Misc: case Lisp_Vectorlike:
2193 struct Lisp_Hash_Table *h = XHASH_TABLE (ht);
2194 EMACS_UINT hash;
2195 ptrdiff_t i = hash_lookup (h, o1, &hash);
2196 if (i >= 0)
2197 { /* `o1' was seen already. */
2198 Lisp_Object o2s = HASH_VALUE (h, i);
2199 if (!NILP (Fmemq (o2, o2s)))
2200 return 1;
2201 else
2202 set_hash_value_slot (h, i, Fcons (o2, o2s));
2204 else
2205 hash_put (h, o1, Fcons (o2, Qnil), hash);
2207 default: ;
2211 unsigned short int quit_count = 0;
2212 tail_recurse:
2213 rarely_quit (++quit_count);
2214 if (EQ (o1, o2))
2215 return 1;
2216 if (XTYPE (o1) != XTYPE (o2))
2217 return 0;
2219 switch (XTYPE (o1))
2221 case Lisp_Float:
2223 double d1, d2;
2225 d1 = extract_float (o1);
2226 d2 = extract_float (o2);
2227 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2228 though they are not =. */
2229 return d1 == d2 || (d1 != d1 && d2 != d2);
2232 case Lisp_Cons:
2233 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1, props, ht))
2234 return 0;
2235 o1 = XCDR (o1);
2236 o2 = XCDR (o2);
2237 /* FIXME: This inf-loops in a circular list! */
2238 goto tail_recurse;
2240 case Lisp_Misc:
2241 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2242 return 0;
2243 if (OVERLAYP (o1))
2245 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2246 depth + 1, props, ht)
2247 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2248 depth + 1, props, ht))
2249 return 0;
2250 o1 = XOVERLAY (o1)->plist;
2251 o2 = XOVERLAY (o2)->plist;
2252 goto tail_recurse;
2254 if (MARKERP (o1))
2256 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2257 && (XMARKER (o1)->buffer == 0
2258 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2260 break;
2262 case Lisp_Vectorlike:
2264 register int i;
2265 ptrdiff_t size = ASIZE (o1);
2266 /* Pseudovectors have the type encoded in the size field, so this test
2267 actually checks that the objects have the same type as well as the
2268 same size. */
2269 if (ASIZE (o2) != size)
2270 return 0;
2271 /* Boolvectors are compared much like strings. */
2272 if (BOOL_VECTOR_P (o1))
2274 EMACS_INT size = bool_vector_size (o1);
2275 if (size != bool_vector_size (o2))
2276 return 0;
2277 if (memcmp (bool_vector_data (o1), bool_vector_data (o2),
2278 bool_vector_bytes (size)))
2279 return 0;
2280 return 1;
2282 if (WINDOW_CONFIGURATIONP (o1))
2283 return compare_window_configurations (o1, o2, 0);
2285 /* Aside from them, only true vectors, char-tables, compiled
2286 functions, and fonts (font-spec, font-entity, font-object)
2287 are sensible to compare, so eliminate the others now. */
2288 if (size & PSEUDOVECTOR_FLAG)
2290 if (((size & PVEC_TYPE_MASK) >> PSEUDOVECTOR_AREA_BITS)
2291 < PVEC_COMPILED)
2292 return 0;
2293 size &= PSEUDOVECTOR_SIZE_MASK;
2295 for (i = 0; i < size; i++)
2297 Lisp_Object v1, v2;
2298 v1 = AREF (o1, i);
2299 v2 = AREF (o2, i);
2300 if (!internal_equal (v1, v2, depth + 1, props, ht))
2301 return 0;
2303 return 1;
2305 break;
2307 case Lisp_String:
2308 if (SCHARS (o1) != SCHARS (o2))
2309 return 0;
2310 if (SBYTES (o1) != SBYTES (o2))
2311 return 0;
2312 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2313 return 0;
2314 if (props && !compare_string_intervals (o1, o2))
2315 return 0;
2316 return 1;
2318 default:
2319 break;
2322 return 0;
2326 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2327 doc: /* Store each element of ARRAY with ITEM.
2328 ARRAY is a vector, string, char-table, or bool-vector. */)
2329 (Lisp_Object array, Lisp_Object item)
2331 register ptrdiff_t size, idx;
2333 if (VECTORP (array))
2334 for (idx = 0, size = ASIZE (array); idx < size; idx++)
2335 ASET (array, idx, item);
2336 else if (CHAR_TABLE_P (array))
2338 int i;
2340 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2341 set_char_table_contents (array, i, item);
2342 set_char_table_defalt (array, item);
2344 else if (STRINGP (array))
2346 register unsigned char *p = SDATA (array);
2347 int charval;
2348 CHECK_CHARACTER (item);
2349 charval = XFASTINT (item);
2350 size = SCHARS (array);
2351 if (STRING_MULTIBYTE (array))
2353 unsigned char str[MAX_MULTIBYTE_LENGTH];
2354 int len = CHAR_STRING (charval, str);
2355 ptrdiff_t size_byte = SBYTES (array);
2356 ptrdiff_t product;
2358 if (INT_MULTIPLY_WRAPV (size, len, &product) || product != size_byte)
2359 error ("Attempt to change byte length of a string");
2360 for (idx = 0; idx < size_byte; idx++)
2361 *p++ = str[idx % len];
2363 else
2364 for (idx = 0; idx < size; idx++)
2365 p[idx] = charval;
2367 else if (BOOL_VECTOR_P (array))
2368 return bool_vector_fill (array, item);
2369 else
2370 wrong_type_argument (Qarrayp, array);
2371 return array;
2374 DEFUN ("clear-string", Fclear_string, Sclear_string,
2375 1, 1, 0,
2376 doc: /* Clear the contents of STRING.
2377 This makes STRING unibyte and may change its length. */)
2378 (Lisp_Object string)
2380 ptrdiff_t len;
2381 CHECK_STRING (string);
2382 len = SBYTES (string);
2383 memset (SDATA (string), 0, len);
2384 STRING_SET_CHARS (string, len);
2385 STRING_SET_UNIBYTE (string);
2386 return Qnil;
2389 /* ARGSUSED */
2390 Lisp_Object
2391 nconc2 (Lisp_Object s1, Lisp_Object s2)
2393 return CALLN (Fnconc, s1, s2);
2396 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2397 doc: /* Concatenate any number of lists by altering them.
2398 Only the last argument is not altered, and need not be a list.
2399 usage: (nconc &rest LISTS) */)
2400 (ptrdiff_t nargs, Lisp_Object *args)
2402 unsigned short int quit_count = 0;
2403 Lisp_Object val = Qnil;
2405 for (ptrdiff_t argnum = 0; argnum < nargs; argnum++)
2407 Lisp_Object tem = args[argnum];
2408 if (NILP (tem)) continue;
2410 if (NILP (val))
2411 val = tem;
2413 if (argnum + 1 == nargs) break;
2415 CHECK_CONS (tem);
2417 Lisp_Object tail;
2420 tail = tem;
2421 tem = XCDR (tail);
2422 rarely_quit (++quit_count);
2424 while (CONSP (tem));
2426 tem = args[argnum + 1];
2427 Fsetcdr (tail, tem);
2428 if (NILP (tem))
2429 args[argnum + 1] = tail;
2432 return val;
2435 /* This is the guts of all mapping functions.
2436 Apply FN to each element of SEQ, one by one, storing the results
2437 into elements of VALS, a C vector of Lisp_Objects. LENI is the
2438 length of VALS, which should also be the length of SEQ. Return the
2439 number of results; although this is normally LENI, it can be less
2440 if SEQ is made shorter as a side effect of FN. */
2442 static EMACS_INT
2443 mapcar1 (EMACS_INT leni, Lisp_Object *vals, Lisp_Object fn, Lisp_Object seq)
2445 Lisp_Object tail, dummy;
2446 EMACS_INT i;
2448 if (VECTORP (seq) || COMPILEDP (seq))
2450 for (i = 0; i < leni; i++)
2452 dummy = call1 (fn, AREF (seq, i));
2453 if (vals)
2454 vals[i] = dummy;
2457 else if (BOOL_VECTOR_P (seq))
2459 for (i = 0; i < leni; i++)
2461 dummy = call1 (fn, bool_vector_ref (seq, i));
2462 if (vals)
2463 vals[i] = dummy;
2466 else if (STRINGP (seq))
2468 ptrdiff_t i_byte;
2470 for (i = 0, i_byte = 0; i < leni;)
2472 int c;
2473 ptrdiff_t i_before = i;
2475 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2476 XSETFASTINT (dummy, c);
2477 dummy = call1 (fn, dummy);
2478 if (vals)
2479 vals[i_before] = dummy;
2482 else /* Must be a list, since Flength did not get an error */
2484 tail = seq;
2485 for (i = 0; i < leni; i++)
2487 if (! CONSP (tail))
2488 return i;
2489 dummy = call1 (fn, XCAR (tail));
2490 if (vals)
2491 vals[i] = dummy;
2492 tail = XCDR (tail);
2496 return leni;
2499 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2500 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2501 In between each pair of results, stick in SEPARATOR. Thus, " " as
2502 SEPARATOR results in spaces between the values returned by FUNCTION.
2503 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2504 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2506 USE_SAFE_ALLOCA;
2507 EMACS_INT leni = XFASTINT (Flength (sequence));
2508 if (CHAR_TABLE_P (sequence))
2509 wrong_type_argument (Qlistp, sequence);
2510 EMACS_INT args_alloc = 2 * leni - 1;
2511 if (args_alloc < 0)
2512 return empty_unibyte_string;
2513 Lisp_Object *args;
2514 SAFE_ALLOCA_LISP (args, args_alloc);
2515 ptrdiff_t nmapped = mapcar1 (leni, args, function, sequence);
2516 ptrdiff_t nargs = 2 * nmapped - 1;
2518 for (ptrdiff_t i = nmapped - 1; i > 0; i--)
2519 args[i + i] = args[i];
2521 for (ptrdiff_t i = 1; i < nargs; i += 2)
2522 args[i] = separator;
2524 Lisp_Object ret = Fconcat (nargs, args);
2525 SAFE_FREE ();
2526 return ret;
2529 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2530 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2531 The result is a list just as long as SEQUENCE.
2532 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2533 (Lisp_Object function, Lisp_Object sequence)
2535 USE_SAFE_ALLOCA;
2536 EMACS_INT leni = XFASTINT (Flength (sequence));
2537 if (CHAR_TABLE_P (sequence))
2538 wrong_type_argument (Qlistp, sequence);
2539 Lisp_Object *args;
2540 SAFE_ALLOCA_LISP (args, leni);
2541 ptrdiff_t nmapped = mapcar1 (leni, args, function, sequence);
2542 Lisp_Object ret = Flist (nmapped, args);
2543 SAFE_FREE ();
2544 return ret;
2547 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2548 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2549 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2550 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2551 (Lisp_Object function, Lisp_Object sequence)
2553 register EMACS_INT leni;
2555 leni = XFASTINT (Flength (sequence));
2556 if (CHAR_TABLE_P (sequence))
2557 wrong_type_argument (Qlistp, sequence);
2558 mapcar1 (leni, 0, function, sequence);
2560 return sequence;
2563 DEFUN ("mapcan", Fmapcan, Smapcan, 2, 2, 0,
2564 doc: /* Apply FUNCTION to each element of SEQUENCE, and concatenate
2565 the results by altering them (using `nconc').
2566 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2567 (Lisp_Object function, Lisp_Object sequence)
2569 USE_SAFE_ALLOCA;
2570 EMACS_INT leni = XFASTINT (Flength (sequence));
2571 if (CHAR_TABLE_P (sequence))
2572 wrong_type_argument (Qlistp, sequence);
2573 Lisp_Object *args;
2574 SAFE_ALLOCA_LISP (args, leni);
2575 ptrdiff_t nmapped = mapcar1 (leni, args, function, sequence);
2576 Lisp_Object ret = Fnconc (nmapped, args);
2577 SAFE_FREE ();
2578 return ret;
2581 /* This is how C code calls `yes-or-no-p' and allows the user
2582 to redefine it. */
2584 Lisp_Object
2585 do_yes_or_no_p (Lisp_Object prompt)
2587 return call1 (intern ("yes-or-no-p"), prompt);
2590 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2591 doc: /* Ask user a yes-or-no question.
2592 Return t if answer is yes, and nil if the answer is no.
2593 PROMPT is the string to display to ask the question. It should end in
2594 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2596 The user must confirm the answer with RET, and can edit it until it
2597 has been confirmed.
2599 If dialog boxes are supported, a dialog box will be used
2600 if `last-nonmenu-event' is nil, and `use-dialog-box' is non-nil. */)
2601 (Lisp_Object prompt)
2603 Lisp_Object ans;
2605 CHECK_STRING (prompt);
2607 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2608 && use_dialog_box && ! NILP (last_input_event))
2610 Lisp_Object pane, menu, obj;
2611 redisplay_preserve_echo_area (4);
2612 pane = list2 (Fcons (build_string ("Yes"), Qt),
2613 Fcons (build_string ("No"), Qnil));
2614 menu = Fcons (prompt, pane);
2615 obj = Fx_popup_dialog (Qt, menu, Qnil);
2616 return obj;
2619 AUTO_STRING (yes_or_no, "(yes or no) ");
2620 prompt = CALLN (Fconcat, prompt, yes_or_no);
2622 while (1)
2624 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2625 Qyes_or_no_p_history, Qnil,
2626 Qnil));
2627 if (SCHARS (ans) == 3 && !strcmp (SSDATA (ans), "yes"))
2628 return Qt;
2629 if (SCHARS (ans) == 2 && !strcmp (SSDATA (ans), "no"))
2630 return Qnil;
2632 Fding (Qnil);
2633 Fdiscard_input ();
2634 message1 ("Please answer yes or no.");
2635 Fsleep_for (make_number (2), Qnil);
2639 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2640 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2642 Each of the three load averages is multiplied by 100, then converted
2643 to integer.
2645 When USE-FLOATS is non-nil, floats will be used instead of integers.
2646 These floats are not multiplied by 100.
2648 If the 5-minute or 15-minute load averages are not available, return a
2649 shortened list, containing only those averages which are available.
2651 An error is thrown if the load average can't be obtained. In some
2652 cases making it work would require Emacs being installed setuid or
2653 setgid so that it can read kernel information, and that usually isn't
2654 advisable. */)
2655 (Lisp_Object use_floats)
2657 double load_ave[3];
2658 int loads = getloadavg (load_ave, 3);
2659 Lisp_Object ret = Qnil;
2661 if (loads < 0)
2662 error ("load-average not implemented for this operating system");
2664 while (loads-- > 0)
2666 Lisp_Object load = (NILP (use_floats)
2667 ? make_number (100.0 * load_ave[loads])
2668 : make_float (load_ave[loads]));
2669 ret = Fcons (load, ret);
2672 return ret;
2675 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2676 doc: /* Return t if FEATURE is present in this Emacs.
2678 Use this to conditionalize execution of lisp code based on the
2679 presence or absence of Emacs or environment extensions.
2680 Use `provide' to declare that a feature is available. This function
2681 looks at the value of the variable `features'. The optional argument
2682 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2683 (Lisp_Object feature, Lisp_Object subfeature)
2685 register Lisp_Object tem;
2686 CHECK_SYMBOL (feature);
2687 tem = Fmemq (feature, Vfeatures);
2688 if (!NILP (tem) && !NILP (subfeature))
2689 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2690 return (NILP (tem)) ? Qnil : Qt;
2693 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2694 doc: /* Announce that FEATURE is a feature of the current Emacs.
2695 The optional argument SUBFEATURES should be a list of symbols listing
2696 particular subfeatures supported in this version of FEATURE. */)
2697 (Lisp_Object feature, Lisp_Object subfeatures)
2699 register Lisp_Object tem;
2700 CHECK_SYMBOL (feature);
2701 CHECK_LIST (subfeatures);
2702 if (!NILP (Vautoload_queue))
2703 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2704 Vautoload_queue);
2705 tem = Fmemq (feature, Vfeatures);
2706 if (NILP (tem))
2707 Vfeatures = Fcons (feature, Vfeatures);
2708 if (!NILP (subfeatures))
2709 Fput (feature, Qsubfeatures, subfeatures);
2710 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2712 /* Run any load-hooks for this file. */
2713 tem = Fassq (feature, Vafter_load_alist);
2714 if (CONSP (tem))
2715 Fmapc (Qfuncall, XCDR (tem));
2717 return feature;
2720 /* `require' and its subroutines. */
2722 /* List of features currently being require'd, innermost first. */
2724 static Lisp_Object require_nesting_list;
2726 static void
2727 require_unwind (Lisp_Object old_value)
2729 require_nesting_list = old_value;
2732 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2733 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2734 If FEATURE is not a member of the list `features', then the feature is
2735 not loaded; so load the file FILENAME.
2737 If FILENAME is omitted, the printname of FEATURE is used as the file
2738 name, and `load' will try to load this name appended with the suffix
2739 `.elc', `.el', or the system-dependent suffix for dynamic module
2740 files, in that order. The name without appended suffix will not be
2741 used. See `get-load-suffixes' for the complete list of suffixes.
2743 The directories in `load-path' are searched when trying to find the
2744 file name.
2746 If the optional third argument NOERROR is non-nil, then return nil if
2747 the file is not found instead of signaling an error. Normally the
2748 return value is FEATURE.
2750 The normal messages at start and end of loading FILENAME are
2751 suppressed. */)
2752 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2754 Lisp_Object tem;
2755 bool from_file = load_in_progress;
2757 CHECK_SYMBOL (feature);
2759 /* Record the presence of `require' in this file
2760 even if the feature specified is already loaded.
2761 But not more than once in any file,
2762 and not when we aren't loading or reading from a file. */
2763 if (!from_file)
2764 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2765 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2766 from_file = 1;
2768 if (from_file)
2770 tem = Fcons (Qrequire, feature);
2771 if (NILP (Fmember (tem, Vcurrent_load_list)))
2772 LOADHIST_ATTACH (tem);
2774 tem = Fmemq (feature, Vfeatures);
2776 if (NILP (tem))
2778 ptrdiff_t count = SPECPDL_INDEX ();
2779 int nesting = 0;
2781 /* This is to make sure that loadup.el gives a clear picture
2782 of what files are preloaded and when. */
2783 if (! NILP (Vpurify_flag))
2784 error ("(require %s) while preparing to dump",
2785 SDATA (SYMBOL_NAME (feature)));
2787 /* A certain amount of recursive `require' is legitimate,
2788 but if we require the same feature recursively 3 times,
2789 signal an error. */
2790 tem = require_nesting_list;
2791 while (! NILP (tem))
2793 if (! NILP (Fequal (feature, XCAR (tem))))
2794 nesting++;
2795 tem = XCDR (tem);
2797 if (nesting > 3)
2798 error ("Recursive `require' for feature `%s'",
2799 SDATA (SYMBOL_NAME (feature)));
2801 /* Update the list for any nested `require's that occur. */
2802 record_unwind_protect (require_unwind, require_nesting_list);
2803 require_nesting_list = Fcons (feature, require_nesting_list);
2805 /* Value saved here is to be restored into Vautoload_queue */
2806 record_unwind_protect (un_autoload, Vautoload_queue);
2807 Vautoload_queue = Qt;
2809 /* Load the file. */
2810 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2811 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2813 /* If load failed entirely, return nil. */
2814 if (NILP (tem))
2815 return unbind_to (count, Qnil);
2817 tem = Fmemq (feature, Vfeatures);
2818 if (NILP (tem))
2819 error ("Required feature `%s' was not provided",
2820 SDATA (SYMBOL_NAME (feature)));
2822 /* Once loading finishes, don't undo it. */
2823 Vautoload_queue = Qt;
2824 feature = unbind_to (count, feature);
2827 return feature;
2830 /* Primitives for work of the "widget" library.
2831 In an ideal world, this section would not have been necessary.
2832 However, lisp function calls being as slow as they are, it turns
2833 out that some functions in the widget library (wid-edit.el) are the
2834 bottleneck of Widget operation. Here is their translation to C,
2835 for the sole reason of efficiency. */
2837 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2838 doc: /* Return non-nil if PLIST has the property PROP.
2839 PLIST is a property list, which is a list of the form
2840 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol.
2841 Unlike `plist-get', this allows you to distinguish between a missing
2842 property and a property with the value nil.
2843 The value is actually the tail of PLIST whose car is PROP. */)
2844 (Lisp_Object plist, Lisp_Object prop)
2846 unsigned short int quit_count = 0;
2847 while (CONSP (plist) && !EQ (XCAR (plist), prop))
2849 plist = XCDR (plist);
2850 plist = CDR (plist);
2851 rarely_quit (++quit_count);
2853 return plist;
2856 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2857 doc: /* In WIDGET, set PROPERTY to VALUE.
2858 The value can later be retrieved with `widget-get'. */)
2859 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2861 CHECK_CONS (widget);
2862 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
2863 return value;
2866 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
2867 doc: /* In WIDGET, get the value of PROPERTY.
2868 The value could either be specified when the widget was created, or
2869 later with `widget-put'. */)
2870 (Lisp_Object widget, Lisp_Object property)
2872 Lisp_Object tmp;
2874 while (1)
2876 if (NILP (widget))
2877 return Qnil;
2878 CHECK_CONS (widget);
2879 tmp = Fplist_member (XCDR (widget), property);
2880 if (CONSP (tmp))
2882 tmp = XCDR (tmp);
2883 return CAR (tmp);
2885 tmp = XCAR (widget);
2886 if (NILP (tmp))
2887 return Qnil;
2888 widget = Fget (tmp, Qwidget_type);
2892 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
2893 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2894 ARGS are passed as extra arguments to the function.
2895 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2896 (ptrdiff_t nargs, Lisp_Object *args)
2898 Lisp_Object widget = args[0];
2899 Lisp_Object property = args[1];
2900 Lisp_Object propval = Fwidget_get (widget, property);
2901 Lisp_Object trailing_args = Flist (nargs - 2, args + 2);
2902 Lisp_Object result = CALLN (Fapply, propval, widget, trailing_args);
2903 return result;
2906 #ifdef HAVE_LANGINFO_CODESET
2907 #include <langinfo.h>
2908 #endif
2910 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
2911 doc: /* Access locale data ITEM for the current C locale, if available.
2912 ITEM should be one of the following:
2914 `codeset', returning the character set as a string (locale item CODESET);
2916 `days', returning a 7-element vector of day names (locale items DAY_n);
2918 `months', returning a 12-element vector of month names (locale items MON_n);
2920 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
2921 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
2923 If the system can't provide such information through a call to
2924 `nl_langinfo', or if ITEM isn't from the list above, return nil.
2926 See also Info node `(libc)Locales'.
2928 The data read from the system are decoded using `locale-coding-system'. */)
2929 (Lisp_Object item)
2931 char *str = NULL;
2932 #ifdef HAVE_LANGINFO_CODESET
2933 if (EQ (item, Qcodeset))
2935 str = nl_langinfo (CODESET);
2936 return build_string (str);
2938 #ifdef DAY_1
2939 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
2941 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
2942 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
2943 int i;
2944 synchronize_system_time_locale ();
2945 for (i = 0; i < 7; i++)
2947 str = nl_langinfo (days[i]);
2948 AUTO_STRING (val, str);
2949 /* Fixme: Is this coding system necessarily right, even if
2950 it is consistent with CODESET? If not, what to do? */
2951 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
2952 0));
2954 return v;
2956 #endif /* DAY_1 */
2957 #ifdef MON_1
2958 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
2960 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
2961 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
2962 MON_8, MON_9, MON_10, MON_11, MON_12};
2963 int i;
2964 synchronize_system_time_locale ();
2965 for (i = 0; i < 12; i++)
2967 str = nl_langinfo (months[i]);
2968 AUTO_STRING (val, str);
2969 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
2970 0));
2972 return v;
2974 #endif /* MON_1 */
2975 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
2976 but is in the locale files. This could be used by ps-print. */
2977 #ifdef PAPER_WIDTH
2978 else if (EQ (item, Qpaper))
2979 return list2i (nl_langinfo (PAPER_WIDTH), nl_langinfo (PAPER_HEIGHT));
2980 #endif /* PAPER_WIDTH */
2981 #endif /* HAVE_LANGINFO_CODESET*/
2982 return Qnil;
2985 /* base64 encode/decode functions (RFC 2045).
2986 Based on code from GNU recode. */
2988 #define MIME_LINE_LENGTH 76
2990 #define IS_ASCII(Character) \
2991 ((Character) < 128)
2992 #define IS_BASE64(Character) \
2993 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
2994 #define IS_BASE64_IGNORABLE(Character) \
2995 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
2996 || (Character) == '\f' || (Character) == '\r')
2998 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
2999 character or return retval if there are no characters left to
3000 process. */
3001 #define READ_QUADRUPLET_BYTE(retval) \
3002 do \
3004 if (i == length) \
3006 if (nchars_return) \
3007 *nchars_return = nchars; \
3008 return (retval); \
3010 c = from[i++]; \
3012 while (IS_BASE64_IGNORABLE (c))
3014 /* Table of characters coding the 64 values. */
3015 static const char base64_value_to_char[64] =
3017 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
3018 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
3019 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
3020 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
3021 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
3022 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
3023 '8', '9', '+', '/' /* 60-63 */
3026 /* Table of base64 values for first 128 characters. */
3027 static const short base64_char_to_value[128] =
3029 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
3030 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
3031 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
3032 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
3033 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
3034 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
3035 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
3036 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
3037 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
3038 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
3039 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
3040 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
3041 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
3044 /* The following diagram shows the logical steps by which three octets
3045 get transformed into four base64 characters.
3047 .--------. .--------. .--------.
3048 |aaaaaabb| |bbbbcccc| |ccdddddd|
3049 `--------' `--------' `--------'
3050 6 2 4 4 2 6
3051 .--------+--------+--------+--------.
3052 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
3053 `--------+--------+--------+--------'
3055 .--------+--------+--------+--------.
3056 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
3057 `--------+--------+--------+--------'
3059 The octets are divided into 6 bit chunks, which are then encoded into
3060 base64 characters. */
3063 static ptrdiff_t base64_encode_1 (const char *, char *, ptrdiff_t, bool, bool);
3064 static ptrdiff_t base64_decode_1 (const char *, char *, ptrdiff_t, bool,
3065 ptrdiff_t *);
3067 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
3068 2, 3, "r",
3069 doc: /* Base64-encode the region between BEG and END.
3070 Return the length of the encoded text.
3071 Optional third argument NO-LINE-BREAK means do not break long lines
3072 into shorter lines. */)
3073 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
3075 char *encoded;
3076 ptrdiff_t allength, length;
3077 ptrdiff_t ibeg, iend, encoded_length;
3078 ptrdiff_t old_pos = PT;
3079 USE_SAFE_ALLOCA;
3081 validate_region (&beg, &end);
3083 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3084 iend = CHAR_TO_BYTE (XFASTINT (end));
3085 move_gap_both (XFASTINT (beg), ibeg);
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 = iend - ibeg;
3091 allength = length + length/3 + 1;
3092 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3094 encoded = SAFE_ALLOCA (allength);
3095 encoded_length = base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg),
3096 encoded, length, NILP (no_line_break),
3097 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
3098 if (encoded_length > allength)
3099 emacs_abort ();
3101 if (encoded_length < 0)
3103 /* The encoding wasn't possible. */
3104 SAFE_FREE ();
3105 error ("Multibyte character in data for base64 encoding");
3108 /* Now we have encoded the region, so we insert the new contents
3109 and delete the old. (Insert first in order to preserve markers.) */
3110 SET_PT_BOTH (XFASTINT (beg), ibeg);
3111 insert (encoded, encoded_length);
3112 SAFE_FREE ();
3113 del_range_byte (ibeg + encoded_length, iend + encoded_length);
3115 /* If point was outside of the region, restore it exactly; else just
3116 move to the beginning of the region. */
3117 if (old_pos >= XFASTINT (end))
3118 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
3119 else if (old_pos > XFASTINT (beg))
3120 old_pos = XFASTINT (beg);
3121 SET_PT (old_pos);
3123 /* We return the length of the encoded text. */
3124 return make_number (encoded_length);
3127 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
3128 1, 2, 0,
3129 doc: /* Base64-encode STRING and return the result.
3130 Optional second argument NO-LINE-BREAK means do not break long lines
3131 into shorter lines. */)
3132 (Lisp_Object string, Lisp_Object no_line_break)
3134 ptrdiff_t allength, length, encoded_length;
3135 char *encoded;
3136 Lisp_Object encoded_string;
3137 USE_SAFE_ALLOCA;
3139 CHECK_STRING (string);
3141 /* We need to allocate enough room for encoding the text.
3142 We need 33 1/3% more space, plus a newline every 76
3143 characters, and then we round up. */
3144 length = SBYTES (string);
3145 allength = length + length/3 + 1;
3146 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3148 /* We need to allocate enough room for decoding the text. */
3149 encoded = SAFE_ALLOCA (allength);
3151 encoded_length = base64_encode_1 (SSDATA (string),
3152 encoded, length, NILP (no_line_break),
3153 STRING_MULTIBYTE (string));
3154 if (encoded_length > allength)
3155 emacs_abort ();
3157 if (encoded_length < 0)
3159 /* The encoding wasn't possible. */
3160 error ("Multibyte character in data for base64 encoding");
3163 encoded_string = make_unibyte_string (encoded, encoded_length);
3164 SAFE_FREE ();
3166 return encoded_string;
3169 static ptrdiff_t
3170 base64_encode_1 (const char *from, char *to, ptrdiff_t length,
3171 bool line_break, bool multibyte)
3173 int counter = 0;
3174 ptrdiff_t i = 0;
3175 char *e = to;
3176 int c;
3177 unsigned int value;
3178 int bytes;
3180 while (i < length)
3182 if (multibyte)
3184 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3185 if (CHAR_BYTE8_P (c))
3186 c = CHAR_TO_BYTE8 (c);
3187 else if (c >= 256)
3188 return -1;
3189 i += bytes;
3191 else
3192 c = from[i++];
3194 /* Wrap line every 76 characters. */
3196 if (line_break)
3198 if (counter < MIME_LINE_LENGTH / 4)
3199 counter++;
3200 else
3202 *e++ = '\n';
3203 counter = 1;
3207 /* Process first byte of a triplet. */
3209 *e++ = base64_value_to_char[0x3f & c >> 2];
3210 value = (0x03 & c) << 4;
3212 /* Process second byte of a triplet. */
3214 if (i == length)
3216 *e++ = base64_value_to_char[value];
3217 *e++ = '=';
3218 *e++ = '=';
3219 break;
3222 if (multibyte)
3224 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3225 if (CHAR_BYTE8_P (c))
3226 c = CHAR_TO_BYTE8 (c);
3227 else if (c >= 256)
3228 return -1;
3229 i += bytes;
3231 else
3232 c = from[i++];
3234 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3235 value = (0x0f & c) << 2;
3237 /* Process third byte of a triplet. */
3239 if (i == length)
3241 *e++ = base64_value_to_char[value];
3242 *e++ = '=';
3243 break;
3246 if (multibyte)
3248 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3249 if (CHAR_BYTE8_P (c))
3250 c = CHAR_TO_BYTE8 (c);
3251 else if (c >= 256)
3252 return -1;
3253 i += bytes;
3255 else
3256 c = from[i++];
3258 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3259 *e++ = base64_value_to_char[0x3f & c];
3262 return e - to;
3266 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3267 2, 2, "r",
3268 doc: /* Base64-decode the region between BEG and END.
3269 Return the length of the decoded text.
3270 If the region can't be decoded, signal an error and don't modify the buffer. */)
3271 (Lisp_Object beg, Lisp_Object end)
3273 ptrdiff_t ibeg, iend, length, allength;
3274 char *decoded;
3275 ptrdiff_t old_pos = PT;
3276 ptrdiff_t decoded_length;
3277 ptrdiff_t inserted_chars;
3278 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3279 USE_SAFE_ALLOCA;
3281 validate_region (&beg, &end);
3283 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3284 iend = CHAR_TO_BYTE (XFASTINT (end));
3286 length = iend - ibeg;
3288 /* We need to allocate enough room for decoding the text. If we are
3289 working on a multibyte buffer, each decoded code may occupy at
3290 most two bytes. */
3291 allength = multibyte ? length * 2 : length;
3292 decoded = SAFE_ALLOCA (allength);
3294 move_gap_both (XFASTINT (beg), ibeg);
3295 decoded_length = base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg),
3296 decoded, length,
3297 multibyte, &inserted_chars);
3298 if (decoded_length > allength)
3299 emacs_abort ();
3301 if (decoded_length < 0)
3303 /* The decoding wasn't possible. */
3304 error ("Invalid base64 data");
3307 /* Now we have decoded the region, so we insert the new contents
3308 and delete the old. (Insert first in order to preserve markers.) */
3309 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3310 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3311 SAFE_FREE ();
3313 /* Delete the original text. */
3314 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3315 iend + decoded_length, 1);
3317 /* If point was outside of the region, restore it exactly; else just
3318 move to the beginning of the region. */
3319 if (old_pos >= XFASTINT (end))
3320 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3321 else if (old_pos > XFASTINT (beg))
3322 old_pos = XFASTINT (beg);
3323 SET_PT (old_pos > ZV ? ZV : old_pos);
3325 return make_number (inserted_chars);
3328 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3329 1, 1, 0,
3330 doc: /* Base64-decode STRING and return the result. */)
3331 (Lisp_Object string)
3333 char *decoded;
3334 ptrdiff_t length, decoded_length;
3335 Lisp_Object decoded_string;
3336 USE_SAFE_ALLOCA;
3338 CHECK_STRING (string);
3340 length = SBYTES (string);
3341 /* We need to allocate enough room for decoding the text. */
3342 decoded = SAFE_ALLOCA (length);
3344 /* The decoded result should be unibyte. */
3345 decoded_length = base64_decode_1 (SSDATA (string), decoded, length,
3346 0, NULL);
3347 if (decoded_length > length)
3348 emacs_abort ();
3349 else if (decoded_length >= 0)
3350 decoded_string = make_unibyte_string (decoded, decoded_length);
3351 else
3352 decoded_string = Qnil;
3354 SAFE_FREE ();
3355 if (!STRINGP (decoded_string))
3356 error ("Invalid base64 data");
3358 return decoded_string;
3361 /* Base64-decode the data at FROM of LENGTH bytes into TO. If
3362 MULTIBYTE, the decoded result should be in multibyte
3363 form. If NCHARS_RETURN is not NULL, store the number of produced
3364 characters in *NCHARS_RETURN. */
3366 static ptrdiff_t
3367 base64_decode_1 (const char *from, char *to, ptrdiff_t length,
3368 bool multibyte, ptrdiff_t *nchars_return)
3370 ptrdiff_t i = 0; /* Used inside READ_QUADRUPLET_BYTE */
3371 char *e = to;
3372 unsigned char c;
3373 unsigned long value;
3374 ptrdiff_t nchars = 0;
3376 while (1)
3378 /* Process first byte of a quadruplet. */
3380 READ_QUADRUPLET_BYTE (e-to);
3382 if (!IS_BASE64 (c))
3383 return -1;
3384 value = base64_char_to_value[c] << 18;
3386 /* Process second byte of a quadruplet. */
3388 READ_QUADRUPLET_BYTE (-1);
3390 if (!IS_BASE64 (c))
3391 return -1;
3392 value |= base64_char_to_value[c] << 12;
3394 c = (unsigned char) (value >> 16);
3395 if (multibyte && c >= 128)
3396 e += BYTE8_STRING (c, e);
3397 else
3398 *e++ = c;
3399 nchars++;
3401 /* Process third byte of a quadruplet. */
3403 READ_QUADRUPLET_BYTE (-1);
3405 if (c == '=')
3407 READ_QUADRUPLET_BYTE (-1);
3409 if (c != '=')
3410 return -1;
3411 continue;
3414 if (!IS_BASE64 (c))
3415 return -1;
3416 value |= base64_char_to_value[c] << 6;
3418 c = (unsigned char) (0xff & value >> 8);
3419 if (multibyte && c >= 128)
3420 e += BYTE8_STRING (c, e);
3421 else
3422 *e++ = c;
3423 nchars++;
3425 /* Process fourth byte of a quadruplet. */
3427 READ_QUADRUPLET_BYTE (-1);
3429 if (c == '=')
3430 continue;
3432 if (!IS_BASE64 (c))
3433 return -1;
3434 value |= base64_char_to_value[c];
3436 c = (unsigned char) (0xff & value);
3437 if (multibyte && c >= 128)
3438 e += BYTE8_STRING (c, e);
3439 else
3440 *e++ = c;
3441 nchars++;
3447 /***********************************************************************
3448 ***** *****
3449 ***** Hash Tables *****
3450 ***** *****
3451 ***********************************************************************/
3453 /* Implemented by gerd@gnu.org. This hash table implementation was
3454 inspired by CMUCL hash tables. */
3456 /* Ideas:
3458 1. For small tables, association lists are probably faster than
3459 hash tables because they have lower overhead.
3461 For uses of hash tables where the O(1) behavior of table
3462 operations is not a requirement, it might therefore be a good idea
3463 not to hash. Instead, we could just do a linear search in the
3464 key_and_value vector of the hash table. This could be done
3465 if a `:linear-search t' argument is given to make-hash-table. */
3468 /* The list of all weak hash tables. Don't staticpro this one. */
3470 static struct Lisp_Hash_Table *weak_hash_tables;
3473 /***********************************************************************
3474 Utilities
3475 ***********************************************************************/
3477 static void
3478 CHECK_HASH_TABLE (Lisp_Object x)
3480 CHECK_TYPE (HASH_TABLE_P (x), Qhash_table_p, x);
3483 static void
3484 set_hash_key_and_value (struct Lisp_Hash_Table *h, Lisp_Object key_and_value)
3486 h->key_and_value = key_and_value;
3488 static void
3489 set_hash_next (struct Lisp_Hash_Table *h, Lisp_Object next)
3491 h->next = next;
3493 static void
3494 set_hash_next_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3496 gc_aset (h->next, idx, val);
3498 static void
3499 set_hash_hash (struct Lisp_Hash_Table *h, Lisp_Object hash)
3501 h->hash = hash;
3503 static void
3504 set_hash_hash_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3506 gc_aset (h->hash, idx, val);
3508 static void
3509 set_hash_index (struct Lisp_Hash_Table *h, Lisp_Object index)
3511 h->index = index;
3513 static void
3514 set_hash_index_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3516 gc_aset (h->index, idx, val);
3519 /* If OBJ is a Lisp hash table, return a pointer to its struct
3520 Lisp_Hash_Table. Otherwise, signal an error. */
3522 static struct Lisp_Hash_Table *
3523 check_hash_table (Lisp_Object obj)
3525 CHECK_HASH_TABLE (obj);
3526 return XHASH_TABLE (obj);
3530 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3531 number. A number is "almost" a prime number if it is not divisible
3532 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3534 EMACS_INT
3535 next_almost_prime (EMACS_INT n)
3537 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
3538 for (n |= 1; ; n += 2)
3539 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0)
3540 return n;
3544 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3545 which USED[I] is non-zero. If found at index I in ARGS, set
3546 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3547 0. This function is used to extract a keyword/argument pair from
3548 a DEFUN parameter list. */
3550 static ptrdiff_t
3551 get_key_arg (Lisp_Object key, ptrdiff_t nargs, Lisp_Object *args, char *used)
3553 ptrdiff_t i;
3555 for (i = 1; i < nargs; i++)
3556 if (!used[i - 1] && EQ (args[i - 1], key))
3558 used[i - 1] = 1;
3559 used[i] = 1;
3560 return i;
3563 return 0;
3567 /* Return a Lisp vector which has the same contents as VEC but has
3568 at least INCR_MIN more entries, where INCR_MIN is positive.
3569 If NITEMS_MAX is not -1, do not grow the vector to be any larger
3570 than NITEMS_MAX. Entries in the resulting
3571 vector that are not copied from VEC are set to nil. */
3573 Lisp_Object
3574 larger_vector (Lisp_Object vec, ptrdiff_t incr_min, ptrdiff_t nitems_max)
3576 struct Lisp_Vector *v;
3577 ptrdiff_t incr, incr_max, old_size, new_size;
3578 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / sizeof *v->contents;
3579 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
3580 ? nitems_max : C_language_max);
3581 eassert (VECTORP (vec));
3582 eassert (0 < incr_min && -1 <= nitems_max);
3583 old_size = ASIZE (vec);
3584 incr_max = n_max - old_size;
3585 incr = max (incr_min, min (old_size >> 1, incr_max));
3586 if (incr_max < incr)
3587 memory_full (SIZE_MAX);
3588 new_size = old_size + incr;
3589 v = allocate_vector (new_size);
3590 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3591 memclear (v->contents + old_size, incr * word_size);
3592 XSETVECTOR (vec, v);
3593 return vec;
3597 /***********************************************************************
3598 Low-level Functions
3599 ***********************************************************************/
3601 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3602 HASH2 in hash table H using `eql'. Value is true if KEY1 and
3603 KEY2 are the same. */
3605 static bool
3606 cmpfn_eql (struct hash_table_test *ht,
3607 Lisp_Object key1,
3608 Lisp_Object key2)
3610 return (FLOATP (key1)
3611 && FLOATP (key2)
3612 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3616 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3617 HASH2 in hash table H using `equal'. Value is true if KEY1 and
3618 KEY2 are the same. */
3620 static bool
3621 cmpfn_equal (struct hash_table_test *ht,
3622 Lisp_Object key1,
3623 Lisp_Object key2)
3625 return !NILP (Fequal (key1, key2));
3629 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3630 HASH2 in hash table H using H->user_cmp_function. Value is true
3631 if KEY1 and KEY2 are the same. */
3633 static bool
3634 cmpfn_user_defined (struct hash_table_test *ht,
3635 Lisp_Object key1,
3636 Lisp_Object key2)
3638 return !NILP (call2 (ht->user_cmp_function, key1, key2));
3641 /* Value is a hash code for KEY for use in hash table H which uses
3642 `eq' to compare keys. The hash code returned is guaranteed to fit
3643 in a Lisp integer. */
3645 static EMACS_UINT
3646 hashfn_eq (struct hash_table_test *ht, Lisp_Object key)
3648 return XHASH (key) ^ XTYPE (key);
3651 /* Value is a hash code for KEY for use in hash table H which uses
3652 `equal' to compare keys. The hash code returned is guaranteed to fit
3653 in a Lisp integer. */
3655 static EMACS_UINT
3656 hashfn_equal (struct hash_table_test *ht, Lisp_Object key)
3658 return sxhash (key, 0);
3661 /* Value is a hash code for KEY for use in hash table H which uses
3662 `eql' to compare keys. The hash code returned is guaranteed to fit
3663 in a Lisp integer. */
3665 static EMACS_UINT
3666 hashfn_eql (struct hash_table_test *ht, Lisp_Object key)
3668 return FLOATP (key) ? hashfn_equal (ht, key) : hashfn_eq (ht, key);
3671 /* Value is a hash code for KEY for use in hash table H which uses as
3672 user-defined function to compare keys. The hash code returned is
3673 guaranteed to fit in a Lisp integer. */
3675 static EMACS_UINT
3676 hashfn_user_defined (struct hash_table_test *ht, Lisp_Object key)
3678 Lisp_Object hash = call1 (ht->user_hash_function, key);
3679 return hashfn_eq (ht, hash);
3682 struct hash_table_test const
3683 hashtest_eq = { LISPSYM_INITIALLY (Qeq), LISPSYM_INITIALLY (Qnil),
3684 LISPSYM_INITIALLY (Qnil), 0, hashfn_eq },
3685 hashtest_eql = { LISPSYM_INITIALLY (Qeql), LISPSYM_INITIALLY (Qnil),
3686 LISPSYM_INITIALLY (Qnil), cmpfn_eql, hashfn_eql },
3687 hashtest_equal = { LISPSYM_INITIALLY (Qequal), LISPSYM_INITIALLY (Qnil),
3688 LISPSYM_INITIALLY (Qnil), cmpfn_equal, hashfn_equal };
3690 /* Allocate basically initialized hash table. */
3692 static struct Lisp_Hash_Table *
3693 allocate_hash_table (void)
3695 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table,
3696 count, PVEC_HASH_TABLE);
3699 /* An upper bound on the size of a hash table index. It must fit in
3700 ptrdiff_t and be a valid Emacs fixnum. */
3701 #define INDEX_SIZE_BOUND \
3702 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, PTRDIFF_MAX / word_size))
3704 /* Create and initialize a new hash table.
3706 TEST specifies the test the hash table will use to compare keys.
3707 It must be either one of the predefined tests `eq', `eql' or
3708 `equal' or a symbol denoting a user-defined test named TEST with
3709 test and hash functions USER_TEST and USER_HASH.
3711 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3713 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3714 new size when it becomes full is computed by adding REHASH_SIZE to
3715 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3716 table's new size is computed by multiplying its old size with
3717 REHASH_SIZE.
3719 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3720 be resized when the ratio of (number of entries in the table) /
3721 (table size) is >= REHASH_THRESHOLD.
3723 WEAK specifies the weakness of the table. If non-nil, it must be
3724 one of the symbols `key', `value', `key-or-value', or `key-and-value'.
3726 If PURECOPY is non-nil, the table can be copied to pure storage via
3727 `purecopy' when Emacs is being dumped. Such tables can no longer be
3728 changed after purecopy. */
3730 Lisp_Object
3731 make_hash_table (struct hash_table_test test,
3732 Lisp_Object size, Lisp_Object rehash_size,
3733 Lisp_Object rehash_threshold, Lisp_Object weak,
3734 Lisp_Object pure)
3736 struct Lisp_Hash_Table *h;
3737 Lisp_Object table;
3738 EMACS_INT index_size, sz;
3739 ptrdiff_t i;
3740 double index_float;
3742 /* Preconditions. */
3743 eassert (SYMBOLP (test.name));
3744 eassert (INTEGERP (size) && XINT (size) >= 0);
3745 eassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3746 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size)));
3747 eassert (FLOATP (rehash_threshold)
3748 && 0 < XFLOAT_DATA (rehash_threshold)
3749 && XFLOAT_DATA (rehash_threshold) <= 1.0);
3751 if (XFASTINT (size) == 0)
3752 size = make_number (1);
3754 sz = XFASTINT (size);
3755 index_float = sz / XFLOAT_DATA (rehash_threshold);
3756 index_size = (index_float < INDEX_SIZE_BOUND + 1
3757 ? next_almost_prime (index_float)
3758 : INDEX_SIZE_BOUND + 1);
3759 if (INDEX_SIZE_BOUND < max (index_size, 2 * sz))
3760 error ("Hash table too large");
3762 /* Allocate a table and initialize it. */
3763 h = allocate_hash_table ();
3765 /* Initialize hash table slots. */
3766 h->test = test;
3767 h->weak = weak;
3768 h->rehash_threshold = rehash_threshold;
3769 h->rehash_size = rehash_size;
3770 h->count = 0;
3771 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
3772 h->hash = Fmake_vector (size, Qnil);
3773 h->next = Fmake_vector (size, Qnil);
3774 h->index = Fmake_vector (make_number (index_size), Qnil);
3775 h->pure = pure;
3777 /* Set up the free list. */
3778 for (i = 0; i < sz - 1; ++i)
3779 set_hash_next_slot (h, i, make_number (i + 1));
3780 h->next_free = make_number (0);
3782 XSET_HASH_TABLE (table, h);
3783 eassert (HASH_TABLE_P (table));
3784 eassert (XHASH_TABLE (table) == h);
3786 /* Maybe add this hash table to the list of all weak hash tables. */
3787 if (NILP (h->weak))
3788 h->next_weak = NULL;
3789 else
3791 h->next_weak = weak_hash_tables;
3792 weak_hash_tables = h;
3795 return table;
3799 /* Return a copy of hash table H1. Keys and values are not copied,
3800 only the table itself is. */
3802 static Lisp_Object
3803 copy_hash_table (struct Lisp_Hash_Table *h1)
3805 Lisp_Object table;
3806 struct Lisp_Hash_Table *h2;
3808 h2 = allocate_hash_table ();
3809 *h2 = *h1;
3810 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3811 h2->hash = Fcopy_sequence (h1->hash);
3812 h2->next = Fcopy_sequence (h1->next);
3813 h2->index = Fcopy_sequence (h1->index);
3814 XSET_HASH_TABLE (table, h2);
3816 /* Maybe add this hash table to the list of all weak hash tables. */
3817 if (!NILP (h2->weak))
3819 h2->next_weak = weak_hash_tables;
3820 weak_hash_tables = h2;
3823 return table;
3827 /* Resize hash table H if it's too full. If H cannot be resized
3828 because it's already too large, throw an error. */
3830 static void
3831 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3833 if (NILP (h->next_free))
3835 ptrdiff_t old_size = HASH_TABLE_SIZE (h);
3836 EMACS_INT new_size, index_size, nsize;
3837 ptrdiff_t i;
3838 double index_float;
3840 if (INTEGERP (h->rehash_size))
3841 new_size = old_size + XFASTINT (h->rehash_size);
3842 else
3844 double float_new_size = old_size * XFLOAT_DATA (h->rehash_size);
3845 if (float_new_size < INDEX_SIZE_BOUND + 1)
3847 new_size = float_new_size;
3848 if (new_size <= old_size)
3849 new_size = old_size + 1;
3851 else
3852 new_size = INDEX_SIZE_BOUND + 1;
3854 index_float = new_size / XFLOAT_DATA (h->rehash_threshold);
3855 index_size = (index_float < INDEX_SIZE_BOUND + 1
3856 ? next_almost_prime (index_float)
3857 : INDEX_SIZE_BOUND + 1);
3858 nsize = max (index_size, 2 * new_size);
3859 if (INDEX_SIZE_BOUND < nsize)
3860 error ("Hash table too large to resize");
3862 #ifdef ENABLE_CHECKING
3863 if (HASH_TABLE_P (Vpurify_flag)
3864 && XHASH_TABLE (Vpurify_flag) == h)
3865 message ("Growing hash table to: %"pI"d", new_size);
3866 #endif
3868 set_hash_key_and_value (h, larger_vector (h->key_and_value,
3869 2 * (new_size - old_size), -1));
3870 set_hash_next (h, larger_vector (h->next, new_size - old_size, -1));
3871 set_hash_hash (h, larger_vector (h->hash, new_size - old_size, -1));
3872 set_hash_index (h, Fmake_vector (make_number (index_size), Qnil));
3874 /* Update the free list. Do it so that new entries are added at
3875 the end of the free list. This makes some operations like
3876 maphash faster. */
3877 for (i = old_size; i < new_size - 1; ++i)
3878 set_hash_next_slot (h, i, make_number (i + 1));
3880 if (!NILP (h->next_free))
3882 Lisp_Object last, next;
3884 last = h->next_free;
3885 while (next = HASH_NEXT (h, XFASTINT (last)),
3886 !NILP (next))
3887 last = next;
3889 set_hash_next_slot (h, XFASTINT (last), make_number (old_size));
3891 else
3892 XSETFASTINT (h->next_free, old_size);
3894 /* Rehash. */
3895 for (i = 0; i < old_size; ++i)
3896 if (!NILP (HASH_HASH (h, i)))
3898 EMACS_UINT hash_code = XUINT (HASH_HASH (h, i));
3899 ptrdiff_t start_of_bucket = hash_code % ASIZE (h->index);
3900 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3901 set_hash_index_slot (h, start_of_bucket, make_number (i));
3907 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
3908 the hash code of KEY. Value is the index of the entry in H
3909 matching KEY, or -1 if not found. */
3911 ptrdiff_t
3912 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
3914 EMACS_UINT hash_code;
3915 ptrdiff_t start_of_bucket;
3916 Lisp_Object idx;
3918 hash_code = h->test.hashfn (&h->test, key);
3919 eassert ((hash_code & ~INTMASK) == 0);
3920 if (hash)
3921 *hash = hash_code;
3923 start_of_bucket = hash_code % ASIZE (h->index);
3924 idx = HASH_INDEX (h, start_of_bucket);
3926 while (!NILP (idx))
3928 ptrdiff_t i = XFASTINT (idx);
3929 if (EQ (key, HASH_KEY (h, i))
3930 || (h->test.cmpfn
3931 && hash_code == XUINT (HASH_HASH (h, i))
3932 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
3933 break;
3934 idx = HASH_NEXT (h, i);
3937 return NILP (idx) ? -1 : XFASTINT (idx);
3941 /* Put an entry into hash table H that associates KEY with VALUE.
3942 HASH is a previously computed hash code of KEY.
3943 Value is the index of the entry in H matching KEY. */
3945 ptrdiff_t
3946 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value,
3947 EMACS_UINT hash)
3949 ptrdiff_t start_of_bucket, i;
3951 eassert ((hash & ~INTMASK) == 0);
3953 /* Increment count after resizing because resizing may fail. */
3954 maybe_resize_hash_table (h);
3955 h->count++;
3957 /* Store key/value in the key_and_value vector. */
3958 i = XFASTINT (h->next_free);
3959 h->next_free = HASH_NEXT (h, i);
3960 set_hash_key_slot (h, i, key);
3961 set_hash_value_slot (h, i, value);
3963 /* Remember its hash code. */
3964 set_hash_hash_slot (h, i, make_number (hash));
3966 /* Add new entry to its collision chain. */
3967 start_of_bucket = hash % ASIZE (h->index);
3968 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3969 set_hash_index_slot (h, start_of_bucket, make_number (i));
3970 return i;
3974 /* Remove the entry matching KEY from hash table H, if there is one. */
3976 void
3977 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
3979 EMACS_UINT hash_code;
3980 ptrdiff_t start_of_bucket;
3981 Lisp_Object idx, prev;
3983 hash_code = h->test.hashfn (&h->test, key);
3984 eassert ((hash_code & ~INTMASK) == 0);
3985 start_of_bucket = hash_code % ASIZE (h->index);
3986 idx = HASH_INDEX (h, start_of_bucket);
3987 prev = Qnil;
3989 while (!NILP (idx))
3991 ptrdiff_t i = XFASTINT (idx);
3993 if (EQ (key, HASH_KEY (h, i))
3994 || (h->test.cmpfn
3995 && hash_code == XUINT (HASH_HASH (h, i))
3996 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
3998 /* Take entry out of collision chain. */
3999 if (NILP (prev))
4000 set_hash_index_slot (h, start_of_bucket, HASH_NEXT (h, i));
4001 else
4002 set_hash_next_slot (h, XFASTINT (prev), HASH_NEXT (h, i));
4004 /* Clear slots in key_and_value and add the slots to
4005 the free list. */
4006 set_hash_key_slot (h, i, Qnil);
4007 set_hash_value_slot (h, i, Qnil);
4008 set_hash_hash_slot (h, i, Qnil);
4009 set_hash_next_slot (h, i, h->next_free);
4010 h->next_free = make_number (i);
4011 h->count--;
4012 eassert (h->count >= 0);
4013 break;
4015 else
4017 prev = idx;
4018 idx = HASH_NEXT (h, i);
4024 /* Clear hash table H. */
4026 static void
4027 hash_clear (struct Lisp_Hash_Table *h)
4029 if (h->count > 0)
4031 ptrdiff_t i, size = HASH_TABLE_SIZE (h);
4033 for (i = 0; i < size; ++i)
4035 set_hash_next_slot (h, i, i < size - 1 ? make_number (i + 1) : Qnil);
4036 set_hash_key_slot (h, i, Qnil);
4037 set_hash_value_slot (h, i, Qnil);
4038 set_hash_hash_slot (h, i, Qnil);
4041 for (i = 0; i < ASIZE (h->index); ++i)
4042 ASET (h->index, i, Qnil);
4044 h->next_free = make_number (0);
4045 h->count = 0;
4051 /************************************************************************
4052 Weak Hash Tables
4053 ************************************************************************/
4055 /* Sweep weak hash table H. REMOVE_ENTRIES_P means remove
4056 entries from the table that don't survive the current GC.
4057 !REMOVE_ENTRIES_P means mark entries that are in use. Value is
4058 true if anything was marked. */
4060 static bool
4061 sweep_weak_table (struct Lisp_Hash_Table *h, bool remove_entries_p)
4063 ptrdiff_t n = gc_asize (h->index);
4064 bool marked = false;
4066 for (ptrdiff_t bucket = 0; bucket < n; ++bucket)
4068 Lisp_Object idx, next, prev;
4070 /* Follow collision chain, removing entries that
4071 don't survive this garbage collection. */
4072 prev = Qnil;
4073 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
4075 ptrdiff_t i = XFASTINT (idx);
4076 bool key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
4077 bool value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
4078 bool remove_p;
4080 if (EQ (h->weak, Qkey))
4081 remove_p = !key_known_to_survive_p;
4082 else if (EQ (h->weak, Qvalue))
4083 remove_p = !value_known_to_survive_p;
4084 else if (EQ (h->weak, Qkey_or_value))
4085 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
4086 else if (EQ (h->weak, Qkey_and_value))
4087 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
4088 else
4089 emacs_abort ();
4091 next = HASH_NEXT (h, i);
4093 if (remove_entries_p)
4095 if (remove_p)
4097 /* Take out of collision chain. */
4098 if (NILP (prev))
4099 set_hash_index_slot (h, bucket, next);
4100 else
4101 set_hash_next_slot (h, XFASTINT (prev), next);
4103 /* Add to free list. */
4104 set_hash_next_slot (h, i, h->next_free);
4105 h->next_free = idx;
4107 /* Clear key, value, and hash. */
4108 set_hash_key_slot (h, i, Qnil);
4109 set_hash_value_slot (h, i, Qnil);
4110 set_hash_hash_slot (h, i, Qnil);
4112 h->count--;
4114 else
4116 prev = idx;
4119 else
4121 if (!remove_p)
4123 /* Make sure key and value survive. */
4124 if (!key_known_to_survive_p)
4126 mark_object (HASH_KEY (h, i));
4127 marked = 1;
4130 if (!value_known_to_survive_p)
4132 mark_object (HASH_VALUE (h, i));
4133 marked = 1;
4140 return marked;
4143 /* Remove elements from weak hash tables that don't survive the
4144 current garbage collection. Remove weak tables that don't survive
4145 from Vweak_hash_tables. Called from gc_sweep. */
4147 NO_INLINE /* For better stack traces */
4148 void
4149 sweep_weak_hash_tables (void)
4151 struct Lisp_Hash_Table *h, *used, *next;
4152 bool marked;
4154 /* Mark all keys and values that are in use. Keep on marking until
4155 there is no more change. This is necessary for cases like
4156 value-weak table A containing an entry X -> Y, where Y is used in a
4157 key-weak table B, Z -> Y. If B comes after A in the list of weak
4158 tables, X -> Y might be removed from A, although when looking at B
4159 one finds that it shouldn't. */
4162 marked = 0;
4163 for (h = weak_hash_tables; h; h = h->next_weak)
4165 if (h->header.size & ARRAY_MARK_FLAG)
4166 marked |= sweep_weak_table (h, 0);
4169 while (marked);
4171 /* Remove tables and entries that aren't used. */
4172 for (h = weak_hash_tables, used = NULL; h; h = next)
4174 next = h->next_weak;
4176 if (h->header.size & ARRAY_MARK_FLAG)
4178 /* TABLE is marked as used. Sweep its contents. */
4179 if (h->count > 0)
4180 sweep_weak_table (h, 1);
4182 /* Add table to the list of used weak hash tables. */
4183 h->next_weak = used;
4184 used = h;
4188 weak_hash_tables = used;
4193 /***********************************************************************
4194 Hash Code Computation
4195 ***********************************************************************/
4197 /* Maximum depth up to which to dive into Lisp structures. */
4199 #define SXHASH_MAX_DEPTH 3
4201 /* Maximum length up to which to take list and vector elements into
4202 account. */
4204 #define SXHASH_MAX_LEN 7
4206 /* Return a hash for string PTR which has length LEN. The hash value
4207 can be any EMACS_UINT value. */
4209 EMACS_UINT
4210 hash_string (char const *ptr, ptrdiff_t len)
4212 char const *p = ptr;
4213 char const *end = p + len;
4214 unsigned char c;
4215 EMACS_UINT hash = 0;
4217 while (p != end)
4219 c = *p++;
4220 hash = sxhash_combine (hash, c);
4223 return hash;
4226 /* Return a hash for string PTR which has length LEN. The hash
4227 code returned is guaranteed to fit in a Lisp integer. */
4229 static EMACS_UINT
4230 sxhash_string (char const *ptr, ptrdiff_t len)
4232 EMACS_UINT hash = hash_string (ptr, len);
4233 return SXHASH_REDUCE (hash);
4236 /* Return a hash for the floating point value VAL. */
4238 static EMACS_UINT
4239 sxhash_float (double val)
4241 EMACS_UINT hash = 0;
4242 enum {
4243 WORDS_PER_DOUBLE = (sizeof val / sizeof hash
4244 + (sizeof val % sizeof hash != 0))
4246 union {
4247 double val;
4248 EMACS_UINT word[WORDS_PER_DOUBLE];
4249 } u;
4250 int i;
4251 u.val = val;
4252 memset (&u.val + 1, 0, sizeof u - sizeof u.val);
4253 for (i = 0; i < WORDS_PER_DOUBLE; i++)
4254 hash = sxhash_combine (hash, u.word[i]);
4255 return SXHASH_REDUCE (hash);
4258 /* Return a hash for list LIST. DEPTH is the current depth in the
4259 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4261 static EMACS_UINT
4262 sxhash_list (Lisp_Object list, int depth)
4264 EMACS_UINT hash = 0;
4265 int i;
4267 if (depth < SXHASH_MAX_DEPTH)
4268 for (i = 0;
4269 CONSP (list) && i < SXHASH_MAX_LEN;
4270 list = XCDR (list), ++i)
4272 EMACS_UINT hash2 = sxhash (XCAR (list), depth + 1);
4273 hash = sxhash_combine (hash, hash2);
4276 if (!NILP (list))
4278 EMACS_UINT hash2 = sxhash (list, depth + 1);
4279 hash = sxhash_combine (hash, hash2);
4282 return SXHASH_REDUCE (hash);
4286 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4287 the Lisp structure. */
4289 static EMACS_UINT
4290 sxhash_vector (Lisp_Object vec, int depth)
4292 EMACS_UINT hash = ASIZE (vec);
4293 int i, n;
4295 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4296 for (i = 0; i < n; ++i)
4298 EMACS_UINT hash2 = sxhash (AREF (vec, i), depth + 1);
4299 hash = sxhash_combine (hash, hash2);
4302 return SXHASH_REDUCE (hash);
4305 /* Return a hash for bool-vector VECTOR. */
4307 static EMACS_UINT
4308 sxhash_bool_vector (Lisp_Object vec)
4310 EMACS_INT size = bool_vector_size (vec);
4311 EMACS_UINT hash = size;
4312 int i, n;
4314 n = min (SXHASH_MAX_LEN, bool_vector_words (size));
4315 for (i = 0; i < n; ++i)
4316 hash = sxhash_combine (hash, bool_vector_data (vec)[i]);
4318 return SXHASH_REDUCE (hash);
4322 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4323 structure. Value is an unsigned integer clipped to INTMASK. */
4325 EMACS_UINT
4326 sxhash (Lisp_Object obj, int depth)
4328 EMACS_UINT hash;
4330 if (depth > SXHASH_MAX_DEPTH)
4331 return 0;
4333 switch (XTYPE (obj))
4335 case_Lisp_Int:
4336 hash = XUINT (obj);
4337 break;
4339 case Lisp_Misc:
4340 case Lisp_Symbol:
4341 hash = XHASH (obj);
4342 break;
4344 case Lisp_String:
4345 hash = sxhash_string (SSDATA (obj), SBYTES (obj));
4346 break;
4348 /* This can be everything from a vector to an overlay. */
4349 case Lisp_Vectorlike:
4350 if (VECTORP (obj))
4351 /* According to the CL HyperSpec, two arrays are equal only if
4352 they are `eq', except for strings and bit-vectors. In
4353 Emacs, this works differently. We have to compare element
4354 by element. */
4355 hash = sxhash_vector (obj, depth);
4356 else if (BOOL_VECTOR_P (obj))
4357 hash = sxhash_bool_vector (obj);
4358 else
4359 /* Others are `equal' if they are `eq', so let's take their
4360 address as hash. */
4361 hash = XHASH (obj);
4362 break;
4364 case Lisp_Cons:
4365 hash = sxhash_list (obj, depth);
4366 break;
4368 case Lisp_Float:
4369 hash = sxhash_float (XFLOAT_DATA (obj));
4370 break;
4372 default:
4373 emacs_abort ();
4376 return hash;
4381 /***********************************************************************
4382 Lisp Interface
4383 ***********************************************************************/
4385 DEFUN ("sxhash-eq", Fsxhash_eq, Ssxhash_eq, 1, 1, 0,
4386 doc: /* Return an integer hash code for OBJ suitable for `eq'.
4387 If (eq A B), then (= (sxhash-eq A) (sxhash-eq B)). */)
4388 (Lisp_Object obj)
4390 return make_number (hashfn_eq (NULL, obj));
4393 DEFUN ("sxhash-eql", Fsxhash_eql, Ssxhash_eql, 1, 1, 0,
4394 doc: /* Return an integer hash code for OBJ suitable for `eql'.
4395 If (eql A B), then (= (sxhash-eql A) (sxhash-eql B)). */)
4396 (Lisp_Object obj)
4398 return make_number (hashfn_eql (NULL, obj));
4401 DEFUN ("sxhash-equal", Fsxhash_equal, Ssxhash_equal, 1, 1, 0,
4402 doc: /* Return an integer hash code for OBJ suitable for `equal'.
4403 If (equal A B), then (= (sxhash-equal A) (sxhash-equal B)). */)
4404 (Lisp_Object obj)
4406 return make_number (hashfn_equal (NULL, obj));
4409 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4410 doc: /* Create and return a new hash table.
4412 Arguments are specified as keyword/argument pairs. The following
4413 arguments are defined:
4415 :test TEST -- TEST must be a symbol that specifies how to compare
4416 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4417 `equal'. User-supplied test and hash functions can be specified via
4418 `define-hash-table-test'.
4420 :size SIZE -- A hint as to how many elements will be put in the table.
4421 Default is 65.
4423 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4424 fills up. If REHASH-SIZE is an integer, increase the size by that
4425 amount. If it is a float, it must be > 1.0, and the new size is the
4426 old size multiplied by that factor. Default is 1.5.
4428 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4429 Resize the hash table when the ratio (number of entries / table size)
4430 is greater than or equal to THRESHOLD. Default is 0.8.
4432 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4433 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4434 returned is a weak table. Key/value pairs are removed from a weak
4435 hash table when there are no non-weak references pointing to their
4436 key, value, one of key or value, or both key and value, depending on
4437 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4438 is nil.
4440 :purecopy PURECOPY -- If PURECOPY is non-nil, the table can be copied
4441 to pure storage when Emacs is being dumped, making the contents of the
4442 table read only. Any further changes to purified tables will result
4443 in an error.
4445 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4446 (ptrdiff_t nargs, Lisp_Object *args)
4448 Lisp_Object test, size, rehash_size, rehash_threshold, weak, pure;
4449 struct hash_table_test testdesc;
4450 ptrdiff_t i;
4451 USE_SAFE_ALLOCA;
4453 /* The vector `used' is used to keep track of arguments that
4454 have been consumed. */
4455 char *used = SAFE_ALLOCA (nargs * sizeof *used);
4456 memset (used, 0, nargs * sizeof *used);
4458 /* See if there's a `:test TEST' among the arguments. */
4459 i = get_key_arg (QCtest, nargs, args, used);
4460 test = i ? args[i] : Qeql;
4461 if (EQ (test, Qeq))
4462 testdesc = hashtest_eq;
4463 else if (EQ (test, Qeql))
4464 testdesc = hashtest_eql;
4465 else if (EQ (test, Qequal))
4466 testdesc = hashtest_equal;
4467 else
4469 /* See if it is a user-defined test. */
4470 Lisp_Object prop;
4472 prop = Fget (test, Qhash_table_test);
4473 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4474 signal_error ("Invalid hash table test", test);
4475 testdesc.name = test;
4476 testdesc.user_cmp_function = XCAR (prop);
4477 testdesc.user_hash_function = XCAR (XCDR (prop));
4478 testdesc.hashfn = hashfn_user_defined;
4479 testdesc.cmpfn = cmpfn_user_defined;
4482 /* See if there's a `:purecopy PURECOPY' argument. */
4483 i = get_key_arg (QCpurecopy, nargs, args, used);
4484 pure = i ? args[i] : Qnil;
4485 /* See if there's a `:size SIZE' argument. */
4486 i = get_key_arg (QCsize, nargs, args, used);
4487 size = i ? args[i] : Qnil;
4488 if (NILP (size))
4489 size = make_number (DEFAULT_HASH_SIZE);
4490 else if (!INTEGERP (size) || XINT (size) < 0)
4491 signal_error ("Invalid hash table size", size);
4493 /* Look for `:rehash-size SIZE'. */
4494 i = get_key_arg (QCrehash_size, nargs, args, used);
4495 rehash_size = i ? args[i] : make_float (DEFAULT_REHASH_SIZE);
4496 if (! ((INTEGERP (rehash_size) && 0 < XINT (rehash_size))
4497 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size))))
4498 signal_error ("Invalid hash table rehash size", rehash_size);
4500 /* Look for `:rehash-threshold THRESHOLD'. */
4501 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4502 rehash_threshold = i ? args[i] : make_float (DEFAULT_REHASH_THRESHOLD);
4503 if (! (FLOATP (rehash_threshold)
4504 && 0 < XFLOAT_DATA (rehash_threshold)
4505 && XFLOAT_DATA (rehash_threshold) <= 1))
4506 signal_error ("Invalid hash table rehash threshold", rehash_threshold);
4508 /* Look for `:weakness WEAK'. */
4509 i = get_key_arg (QCweakness, nargs, args, used);
4510 weak = i ? args[i] : Qnil;
4511 if (EQ (weak, Qt))
4512 weak = Qkey_and_value;
4513 if (!NILP (weak)
4514 && !EQ (weak, Qkey)
4515 && !EQ (weak, Qvalue)
4516 && !EQ (weak, Qkey_or_value)
4517 && !EQ (weak, Qkey_and_value))
4518 signal_error ("Invalid hash table weakness", weak);
4520 /* Now, all args should have been used up, or there's a problem. */
4521 for (i = 0; i < nargs; ++i)
4522 if (!used[i])
4523 signal_error ("Invalid argument list", args[i]);
4525 SAFE_FREE ();
4526 return make_hash_table (testdesc, size, rehash_size, rehash_threshold, weak,
4527 pure);
4531 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4532 doc: /* Return a copy of hash table TABLE. */)
4533 (Lisp_Object table)
4535 return copy_hash_table (check_hash_table (table));
4539 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4540 doc: /* Return the number of elements in TABLE. */)
4541 (Lisp_Object table)
4543 return make_number (check_hash_table (table)->count);
4547 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4548 Shash_table_rehash_size, 1, 1, 0,
4549 doc: /* Return the current rehash size of TABLE. */)
4550 (Lisp_Object table)
4552 return check_hash_table (table)->rehash_size;
4556 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4557 Shash_table_rehash_threshold, 1, 1, 0,
4558 doc: /* Return the current rehash threshold of TABLE. */)
4559 (Lisp_Object table)
4561 return check_hash_table (table)->rehash_threshold;
4565 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4566 doc: /* Return the size of TABLE.
4567 The size can be used as an argument to `make-hash-table' to create
4568 a hash table than can hold as many elements as TABLE holds
4569 without need for resizing. */)
4570 (Lisp_Object table)
4572 struct Lisp_Hash_Table *h = check_hash_table (table);
4573 return make_number (HASH_TABLE_SIZE (h));
4577 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4578 doc: /* Return the test TABLE uses. */)
4579 (Lisp_Object table)
4581 return check_hash_table (table)->test.name;
4585 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4586 1, 1, 0,
4587 doc: /* Return the weakness of TABLE. */)
4588 (Lisp_Object table)
4590 return check_hash_table (table)->weak;
4594 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4595 doc: /* Return t if OBJ is a Lisp hash table object. */)
4596 (Lisp_Object obj)
4598 return HASH_TABLE_P (obj) ? Qt : Qnil;
4602 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4603 doc: /* Clear hash table TABLE and return it. */)
4604 (Lisp_Object table)
4606 struct Lisp_Hash_Table *h = check_hash_table (table);
4607 CHECK_IMPURE (table, h);
4608 hash_clear (h);
4609 /* Be compatible with XEmacs. */
4610 return table;
4614 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4615 doc: /* Look up KEY in TABLE and return its associated value.
4616 If KEY is not found, return DFLT which defaults to nil. */)
4617 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4619 struct Lisp_Hash_Table *h = check_hash_table (table);
4620 ptrdiff_t i = hash_lookup (h, key, NULL);
4621 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4625 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4626 doc: /* Associate KEY with VALUE in hash table TABLE.
4627 If KEY is already present in table, replace its current value with
4628 VALUE. In any case, return VALUE. */)
4629 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4631 struct Lisp_Hash_Table *h = check_hash_table (table);
4632 CHECK_IMPURE (table, h);
4634 ptrdiff_t i;
4635 EMACS_UINT hash;
4636 i = hash_lookup (h, key, &hash);
4637 if (i >= 0)
4638 set_hash_value_slot (h, i, value);
4639 else
4640 hash_put (h, key, value, hash);
4642 return value;
4646 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4647 doc: /* Remove KEY from TABLE. */)
4648 (Lisp_Object key, Lisp_Object table)
4650 struct Lisp_Hash_Table *h = check_hash_table (table);
4651 CHECK_IMPURE (table, h);
4652 hash_remove_from_table (h, key);
4653 return Qnil;
4657 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4658 doc: /* Call FUNCTION for all entries in hash table TABLE.
4659 FUNCTION is called with two arguments, KEY and VALUE.
4660 `maphash' always returns nil. */)
4661 (Lisp_Object function, Lisp_Object table)
4663 struct Lisp_Hash_Table *h = check_hash_table (table);
4665 for (ptrdiff_t i = 0; i < HASH_TABLE_SIZE (h); ++i)
4666 if (!NILP (HASH_HASH (h, i)))
4667 call2 (function, HASH_KEY (h, i), HASH_VALUE (h, i));
4669 return Qnil;
4673 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4674 Sdefine_hash_table_test, 3, 3, 0,
4675 doc: /* Define a new hash table test with name NAME, a symbol.
4677 In hash tables created with NAME specified as test, use TEST to
4678 compare keys, and HASH for computing hash codes of keys.
4680 TEST must be a function taking two arguments and returning non-nil if
4681 both arguments are the same. HASH must be a function taking one
4682 argument and returning an object that is the hash code of the argument.
4683 It should be the case that if (eq (funcall HASH x1) (funcall HASH x2))
4684 returns nil, then (funcall TEST x1 x2) also returns nil. */)
4685 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4687 return Fput (name, Qhash_table_test, list2 (test, hash));
4692 /************************************************************************
4693 MD5, SHA-1, and SHA-2
4694 ************************************************************************/
4696 #include "md5.h"
4697 #include "sha1.h"
4698 #include "sha256.h"
4699 #include "sha512.h"
4701 static Lisp_Object
4702 make_digest_string (Lisp_Object digest, int digest_size)
4704 unsigned char *p = SDATA (digest);
4706 for (int i = digest_size - 1; i >= 0; i--)
4708 static char const hexdigit[16] = "0123456789abcdef";
4709 int p_i = p[i];
4710 p[2 * i] = hexdigit[p_i >> 4];
4711 p[2 * i + 1] = hexdigit[p_i & 0xf];
4713 return digest;
4716 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4718 static Lisp_Object
4719 secure_hash (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start,
4720 Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror,
4721 Lisp_Object binary)
4723 ptrdiff_t size, start_char = 0, start_byte, end_char = 0, end_byte;
4724 register EMACS_INT b, e;
4725 register struct buffer *bp;
4726 EMACS_INT temp;
4727 int digest_size;
4728 void *(*hash_func) (const char *, size_t, void *);
4729 Lisp_Object digest;
4731 CHECK_SYMBOL (algorithm);
4733 if (STRINGP (object))
4735 if (NILP (coding_system))
4737 /* Decide the coding-system to encode the data with. */
4739 if (STRING_MULTIBYTE (object))
4740 /* use default, we can't guess correct value */
4741 coding_system = preferred_coding_system ();
4742 else
4743 coding_system = Qraw_text;
4746 if (NILP (Fcoding_system_p (coding_system)))
4748 /* Invalid coding system. */
4750 if (!NILP (noerror))
4751 coding_system = Qraw_text;
4752 else
4753 xsignal1 (Qcoding_system_error, coding_system);
4756 if (STRING_MULTIBYTE (object))
4757 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4759 size = SCHARS (object);
4760 validate_subarray (object, start, end, size, &start_char, &end_char);
4762 start_byte = !start_char ? 0 : string_char_to_byte (object, start_char);
4763 end_byte = (end_char == size
4764 ? SBYTES (object)
4765 : string_char_to_byte (object, end_char));
4767 else
4769 struct buffer *prev = current_buffer;
4771 record_unwind_current_buffer ();
4773 CHECK_BUFFER (object);
4775 bp = XBUFFER (object);
4776 set_buffer_internal (bp);
4778 if (NILP (start))
4779 b = BEGV;
4780 else
4782 CHECK_NUMBER_COERCE_MARKER (start);
4783 b = XINT (start);
4786 if (NILP (end))
4787 e = ZV;
4788 else
4790 CHECK_NUMBER_COERCE_MARKER (end);
4791 e = XINT (end);
4794 if (b > e)
4795 temp = b, b = e, e = temp;
4797 if (!(BEGV <= b && e <= ZV))
4798 args_out_of_range (start, end);
4800 if (NILP (coding_system))
4802 /* Decide the coding-system to encode the data with.
4803 See fileio.c:Fwrite-region */
4805 if (!NILP (Vcoding_system_for_write))
4806 coding_system = Vcoding_system_for_write;
4807 else
4809 bool force_raw_text = 0;
4811 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4812 if (NILP (coding_system)
4813 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4815 coding_system = Qnil;
4816 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4817 force_raw_text = 1;
4820 if (NILP (coding_system) && !NILP (Fbuffer_file_name (object)))
4822 /* Check file-coding-system-alist. */
4823 Lisp_Object val = CALLN (Ffind_operation_coding_system,
4824 Qwrite_region, start, end,
4825 Fbuffer_file_name (object));
4826 if (CONSP (val) && !NILP (XCDR (val)))
4827 coding_system = XCDR (val);
4830 if (NILP (coding_system)
4831 && !NILP (BVAR (XBUFFER (object), buffer_file_coding_system)))
4833 /* If we still have not decided a coding system, use the
4834 default value of buffer-file-coding-system. */
4835 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4838 if (!force_raw_text
4839 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4840 /* Confirm that VAL can surely encode the current region. */
4841 coding_system = call4 (Vselect_safe_coding_system_function,
4842 make_number (b), make_number (e),
4843 coding_system, Qnil);
4845 if (force_raw_text)
4846 coding_system = Qraw_text;
4849 if (NILP (Fcoding_system_p (coding_system)))
4851 /* Invalid coding system. */
4853 if (!NILP (noerror))
4854 coding_system = Qraw_text;
4855 else
4856 xsignal1 (Qcoding_system_error, coding_system);
4860 object = make_buffer_string (b, e, 0);
4861 set_buffer_internal (prev);
4862 /* Discard the unwind protect for recovering the current
4863 buffer. */
4864 specpdl_ptr--;
4866 if (STRING_MULTIBYTE (object))
4867 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4868 start_byte = 0;
4869 end_byte = SBYTES (object);
4872 if (EQ (algorithm, Qmd5))
4874 digest_size = MD5_DIGEST_SIZE;
4875 hash_func = md5_buffer;
4877 else if (EQ (algorithm, Qsha1))
4879 digest_size = SHA1_DIGEST_SIZE;
4880 hash_func = sha1_buffer;
4882 else if (EQ (algorithm, Qsha224))
4884 digest_size = SHA224_DIGEST_SIZE;
4885 hash_func = sha224_buffer;
4887 else if (EQ (algorithm, Qsha256))
4889 digest_size = SHA256_DIGEST_SIZE;
4890 hash_func = sha256_buffer;
4892 else if (EQ (algorithm, Qsha384))
4894 digest_size = SHA384_DIGEST_SIZE;
4895 hash_func = sha384_buffer;
4897 else if (EQ (algorithm, Qsha512))
4899 digest_size = SHA512_DIGEST_SIZE;
4900 hash_func = sha512_buffer;
4902 else
4903 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm)));
4905 /* allocate 2 x digest_size so that it can be re-used to hold the
4906 hexified value */
4907 digest = make_uninit_string (digest_size * 2);
4909 hash_func (SSDATA (object) + start_byte,
4910 end_byte - start_byte,
4911 SSDATA (digest));
4913 if (NILP (binary))
4914 return make_digest_string (digest, digest_size);
4915 else
4916 return make_unibyte_string (SSDATA (digest), digest_size);
4919 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
4920 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
4922 A message digest is a cryptographic checksum of a document, and the
4923 algorithm to calculate it is defined in RFC 1321.
4925 The two optional arguments START and END are character positions
4926 specifying for which part of OBJECT the message digest should be
4927 computed. If nil or omitted, the digest is computed for the whole
4928 OBJECT.
4930 The MD5 message digest is computed from the result of encoding the
4931 text in a coding system, not directly from the internal Emacs form of
4932 the text. The optional fourth argument CODING-SYSTEM specifies which
4933 coding system to encode the text with. It should be the same coding
4934 system that you used or will use when actually writing the text into a
4935 file.
4937 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
4938 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
4939 system would be chosen by default for writing this text into a file.
4941 If OBJECT is a string, the most preferred coding system (see the
4942 command `prefer-coding-system') is used.
4944 If NOERROR is non-nil, silently assume the `raw-text' coding if the
4945 guesswork fails. Normally, an error is signaled in such case. */)
4946 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
4948 return secure_hash (Qmd5, object, start, end, coding_system, noerror, Qnil);
4951 DEFUN ("secure-hash", Fsecure_hash, Ssecure_hash, 2, 5, 0,
4952 doc: /* Return the secure hash of OBJECT, a buffer or string.
4953 ALGORITHM is a symbol specifying the hash to use:
4954 md5, sha1, sha224, sha256, sha384 or sha512.
4956 The two optional arguments START and END are positions specifying for
4957 which part of OBJECT to compute the hash. If nil or omitted, uses the
4958 whole OBJECT.
4960 If BINARY is non-nil, returns a string in binary form. */)
4961 (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object binary)
4963 return secure_hash (algorithm, object, start, end, Qnil, Qnil, binary);
4966 DEFUN ("buffer-hash", Fbuffer_hash, Sbuffer_hash, 0, 1, 0,
4967 doc: /* Return a hash of the contents of BUFFER-OR-NAME.
4968 This hash is performed on the raw internal format of the buffer,
4969 disregarding any coding systems.
4970 If nil, use the current buffer." */ )
4971 (Lisp_Object buffer_or_name)
4973 Lisp_Object buffer;
4974 struct buffer *b;
4975 struct sha1_ctx ctx;
4977 if (NILP (buffer_or_name))
4978 buffer = Fcurrent_buffer ();
4979 else
4980 buffer = Fget_buffer (buffer_or_name);
4981 if (NILP (buffer))
4982 nsberror (buffer_or_name);
4984 b = XBUFFER (buffer);
4985 sha1_init_ctx (&ctx);
4987 /* Process the first part of the buffer. */
4988 sha1_process_bytes (BUF_BEG_ADDR (b),
4989 BUF_GPT_BYTE (b) - BUF_BEG_BYTE (b),
4990 &ctx);
4992 /* If the gap is before the end of the buffer, process the last half
4993 of the buffer. */
4994 if (BUF_GPT_BYTE (b) < BUF_Z_BYTE (b))
4995 sha1_process_bytes (BUF_GAP_END_ADDR (b),
4996 BUF_Z_ADDR (b) - BUF_GAP_END_ADDR (b),
4997 &ctx);
4999 Lisp_Object digest = make_uninit_string (SHA1_DIGEST_SIZE * 2);
5000 sha1_finish_ctx (&ctx, SSDATA (digest));
5001 return make_digest_string (digest, SHA1_DIGEST_SIZE);
5005 void
5006 syms_of_fns (void)
5008 DEFSYM (Qmd5, "md5");
5009 DEFSYM (Qsha1, "sha1");
5010 DEFSYM (Qsha224, "sha224");
5011 DEFSYM (Qsha256, "sha256");
5012 DEFSYM (Qsha384, "sha384");
5013 DEFSYM (Qsha512, "sha512");
5015 /* Hash table stuff. */
5016 DEFSYM (Qhash_table_p, "hash-table-p");
5017 DEFSYM (Qeq, "eq");
5018 DEFSYM (Qeql, "eql");
5019 DEFSYM (Qequal, "equal");
5020 DEFSYM (QCtest, ":test");
5021 DEFSYM (QCsize, ":size");
5022 DEFSYM (QCpurecopy, ":purecopy");
5023 DEFSYM (QCrehash_size, ":rehash-size");
5024 DEFSYM (QCrehash_threshold, ":rehash-threshold");
5025 DEFSYM (QCweakness, ":weakness");
5026 DEFSYM (Qkey, "key");
5027 DEFSYM (Qvalue, "value");
5028 DEFSYM (Qhash_table_test, "hash-table-test");
5029 DEFSYM (Qkey_or_value, "key-or-value");
5030 DEFSYM (Qkey_and_value, "key-and-value");
5032 defsubr (&Ssxhash_eq);
5033 defsubr (&Ssxhash_eql);
5034 defsubr (&Ssxhash_equal);
5035 defsubr (&Smake_hash_table);
5036 defsubr (&Scopy_hash_table);
5037 defsubr (&Shash_table_count);
5038 defsubr (&Shash_table_rehash_size);
5039 defsubr (&Shash_table_rehash_threshold);
5040 defsubr (&Shash_table_size);
5041 defsubr (&Shash_table_test);
5042 defsubr (&Shash_table_weakness);
5043 defsubr (&Shash_table_p);
5044 defsubr (&Sclrhash);
5045 defsubr (&Sgethash);
5046 defsubr (&Sputhash);
5047 defsubr (&Sremhash);
5048 defsubr (&Smaphash);
5049 defsubr (&Sdefine_hash_table_test);
5051 DEFSYM (Qstring_lessp, "string-lessp");
5052 DEFSYM (Qprovide, "provide");
5053 DEFSYM (Qrequire, "require");
5054 DEFSYM (Qyes_or_no_p_history, "yes-or-no-p-history");
5055 DEFSYM (Qcursor_in_echo_area, "cursor-in-echo-area");
5056 DEFSYM (Qwidget_type, "widget-type");
5058 staticpro (&string_char_byte_cache_string);
5059 string_char_byte_cache_string = Qnil;
5061 require_nesting_list = Qnil;
5062 staticpro (&require_nesting_list);
5064 Fset (Qyes_or_no_p_history, Qnil);
5066 DEFVAR_LISP ("features", Vfeatures,
5067 doc: /* A list of symbols which are the features of the executing Emacs.
5068 Used by `featurep' and `require', and altered by `provide'. */);
5069 Vfeatures = list1 (Qemacs);
5070 DEFSYM (Qfeatures, "features");
5071 /* Let people use lexically scoped vars named `features'. */
5072 Fmake_var_non_special (Qfeatures);
5073 DEFSYM (Qsubfeatures, "subfeatures");
5074 DEFSYM (Qfuncall, "funcall");
5076 #ifdef HAVE_LANGINFO_CODESET
5077 DEFSYM (Qcodeset, "codeset");
5078 DEFSYM (Qdays, "days");
5079 DEFSYM (Qmonths, "months");
5080 DEFSYM (Qpaper, "paper");
5081 #endif /* HAVE_LANGINFO_CODESET */
5083 DEFVAR_BOOL ("use-dialog-box", use_dialog_box,
5084 doc: /* Non-nil means mouse commands use dialog boxes to ask questions.
5085 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
5086 invoked by mouse clicks and mouse menu items.
5088 On some platforms, file selection dialogs are also enabled if this is
5089 non-nil. */);
5090 use_dialog_box = 1;
5092 DEFVAR_BOOL ("use-file-dialog", use_file_dialog,
5093 doc: /* Non-nil means mouse commands use a file dialog to ask for files.
5094 This applies to commands from menus and tool bar buttons even when
5095 they are initiated from the keyboard. If `use-dialog-box' is nil,
5096 that disables the use of a file dialog, regardless of the value of
5097 this variable. */);
5098 use_file_dialog = 1;
5100 defsubr (&Sidentity);
5101 defsubr (&Srandom);
5102 defsubr (&Slength);
5103 defsubr (&Ssafe_length);
5104 defsubr (&Sstring_bytes);
5105 defsubr (&Sstring_equal);
5106 defsubr (&Scompare_strings);
5107 defsubr (&Sstring_lessp);
5108 defsubr (&Sstring_version_lessp);
5109 defsubr (&Sstring_collate_lessp);
5110 defsubr (&Sstring_collate_equalp);
5111 defsubr (&Sappend);
5112 defsubr (&Sconcat);
5113 defsubr (&Svconcat);
5114 defsubr (&Scopy_sequence);
5115 defsubr (&Sstring_make_multibyte);
5116 defsubr (&Sstring_make_unibyte);
5117 defsubr (&Sstring_as_multibyte);
5118 defsubr (&Sstring_as_unibyte);
5119 defsubr (&Sstring_to_multibyte);
5120 defsubr (&Sstring_to_unibyte);
5121 defsubr (&Scopy_alist);
5122 defsubr (&Ssubstring);
5123 defsubr (&Ssubstring_no_properties);
5124 defsubr (&Snthcdr);
5125 defsubr (&Snth);
5126 defsubr (&Selt);
5127 defsubr (&Smember);
5128 defsubr (&Smemq);
5129 defsubr (&Smemql);
5130 defsubr (&Sassq);
5131 defsubr (&Sassoc);
5132 defsubr (&Srassq);
5133 defsubr (&Srassoc);
5134 defsubr (&Sdelq);
5135 defsubr (&Sdelete);
5136 defsubr (&Snreverse);
5137 defsubr (&Sreverse);
5138 defsubr (&Ssort);
5139 defsubr (&Splist_get);
5140 defsubr (&Sget);
5141 defsubr (&Splist_put);
5142 defsubr (&Sput);
5143 defsubr (&Slax_plist_get);
5144 defsubr (&Slax_plist_put);
5145 defsubr (&Seql);
5146 defsubr (&Sequal);
5147 defsubr (&Sequal_including_properties);
5148 defsubr (&Sfillarray);
5149 defsubr (&Sclear_string);
5150 defsubr (&Snconc);
5151 defsubr (&Smapcar);
5152 defsubr (&Smapc);
5153 defsubr (&Smapcan);
5154 defsubr (&Smapconcat);
5155 defsubr (&Syes_or_no_p);
5156 defsubr (&Sload_average);
5157 defsubr (&Sfeaturep);
5158 defsubr (&Srequire);
5159 defsubr (&Sprovide);
5160 defsubr (&Splist_member);
5161 defsubr (&Swidget_put);
5162 defsubr (&Swidget_get);
5163 defsubr (&Swidget_apply);
5164 defsubr (&Sbase64_encode_region);
5165 defsubr (&Sbase64_decode_region);
5166 defsubr (&Sbase64_encode_string);
5167 defsubr (&Sbase64_decode_string);
5168 defsubr (&Smd5);
5169 defsubr (&Ssecure_hash);
5170 defsubr (&Sbuffer_hash);
5171 defsubr (&Slocale_info);