Merge from origin/emacs-25
[emacs.git] / src / fns.c
blobdfc78424dda31e12d0780ae08173b57276f87196
1 /* Random utility Lisp functions.
3 Copyright (C) 1985-1987, 1993-1995, 1997-2016 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"
38 static void sort_vector_copy (Lisp_Object, ptrdiff_t,
39 Lisp_Object *restrict, Lisp_Object *restrict);
40 static bool internal_equal (Lisp_Object, Lisp_Object, int, bool, Lisp_Object);
42 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
43 doc: /* Return the argument unchanged. */
44 attributes: const)
45 (Lisp_Object arg)
47 return arg;
50 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
51 doc: /* Return a pseudo-random number.
52 All integers representable in Lisp, i.e. between `most-negative-fixnum'
53 and `most-positive-fixnum', inclusive, are equally likely.
55 With positive integer LIMIT, return random number in interval [0,LIMIT).
56 With argument t, set the random number seed from the system's entropy
57 pool if available, otherwise from less-random volatile data such as the time.
58 With a string argument, set the seed based on the string's contents.
59 Other values of LIMIT are ignored.
61 See Info node `(elisp)Random Numbers' for more details. */)
62 (Lisp_Object limit)
64 EMACS_INT val;
66 if (EQ (limit, Qt))
67 init_random ();
68 else if (STRINGP (limit))
69 seed_random (SSDATA (limit), SBYTES (limit));
71 val = get_random ();
72 if (INTEGERP (limit) && 0 < XINT (limit))
73 while (true)
75 /* Return the remainder, except reject the rare case where
76 get_random returns a number so close to INTMASK that the
77 remainder isn't random. */
78 EMACS_INT remainder = val % XINT (limit);
79 if (val - remainder <= INTMASK - XINT (limit) + 1)
80 return make_number (remainder);
81 val = get_random ();
83 return make_number (val);
86 /* Heuristic on how many iterations of a tight loop can be safely done
87 before it's time to do a QUIT. This must be a power of 2. */
88 enum { QUIT_COUNT_HEURISTIC = 1 << 16 };
90 /* Random data-structure functions. */
92 static void
93 CHECK_LIST_END (Lisp_Object x, Lisp_Object y)
95 CHECK_TYPE (NILP (x), Qlistp, y);
98 DEFUN ("length", Flength, Slength, 1, 1, 0,
99 doc: /* Return the length of vector, list or string SEQUENCE.
100 A byte-code function object is also allowed.
101 If the string contains multibyte characters, this is not necessarily
102 the number of bytes in the string; it is the number of characters.
103 To get the number of bytes, use `string-bytes'. */)
104 (register Lisp_Object sequence)
106 register Lisp_Object val;
108 if (STRINGP (sequence))
109 XSETFASTINT (val, SCHARS (sequence));
110 else if (VECTORP (sequence))
111 XSETFASTINT (val, ASIZE (sequence));
112 else if (CHAR_TABLE_P (sequence))
113 XSETFASTINT (val, MAX_CHAR);
114 else if (BOOL_VECTOR_P (sequence))
115 XSETFASTINT (val, bool_vector_size (sequence));
116 else if (COMPILEDP (sequence))
117 XSETFASTINT (val, ASIZE (sequence) & PSEUDOVECTOR_SIZE_MASK);
118 else if (CONSP (sequence))
120 EMACS_INT i = 0;
124 ++i;
125 if ((i & (QUIT_COUNT_HEURISTIC - 1)) == 0)
127 if (MOST_POSITIVE_FIXNUM < i)
128 error ("List too long");
129 QUIT;
131 sequence = XCDR (sequence);
133 while (CONSP (sequence));
135 CHECK_LIST_END (sequence, sequence);
137 val = make_number (i);
139 else if (NILP (sequence))
140 XSETFASTINT (val, 0);
141 else
142 wrong_type_argument (Qsequencep, sequence);
144 return val;
147 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
148 doc: /* Return the length of a list, but avoid error or infinite loop.
149 This function never gets an error. If LIST is not really a list,
150 it returns 0. If LIST is circular, it returns a finite value
151 which is at least the number of distinct elements. */)
152 (Lisp_Object list)
154 Lisp_Object tail, halftail;
155 double hilen = 0;
156 uintmax_t lolen = 1;
158 if (! CONSP (list))
159 return make_number (0);
161 /* halftail is used to detect circular lists. */
162 for (tail = halftail = list; ; )
164 tail = XCDR (tail);
165 if (! CONSP (tail))
166 break;
167 if (EQ (tail, halftail))
168 break;
169 lolen++;
170 if ((lolen & 1) == 0)
172 halftail = XCDR (halftail);
173 if ((lolen & (QUIT_COUNT_HEURISTIC - 1)) == 0)
175 QUIT;
176 if (lolen == 0)
177 hilen += UINTMAX_MAX + 1.0;
182 /* If the length does not fit into a fixnum, return a float.
183 On all known practical machines this returns an upper bound on
184 the true length. */
185 return hilen ? make_float (hilen + lolen) : make_fixnum_or_float (lolen);
188 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
189 doc: /* Return the number of bytes in STRING.
190 If STRING is multibyte, this may be greater than the length of STRING. */)
191 (Lisp_Object string)
193 CHECK_STRING (string);
194 return make_number (SBYTES (string));
197 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
198 doc: /* Return t if two strings have identical contents.
199 Case is significant, but text properties are ignored.
200 Symbols are also allowed; their print names are used instead. */)
201 (register Lisp_Object s1, Lisp_Object s2)
203 if (SYMBOLP (s1))
204 s1 = SYMBOL_NAME (s1);
205 if (SYMBOLP (s2))
206 s2 = SYMBOL_NAME (s2);
207 CHECK_STRING (s1);
208 CHECK_STRING (s2);
210 if (SCHARS (s1) != SCHARS (s2)
211 || SBYTES (s1) != SBYTES (s2)
212 || memcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
213 return Qnil;
214 return Qt;
217 DEFUN ("compare-strings", Fcompare_strings, Scompare_strings, 6, 7, 0,
218 doc: /* Compare the contents of two strings, converting to multibyte if needed.
219 The arguments START1, END1, START2, and END2, if non-nil, are
220 positions specifying which parts of STR1 or STR2 to compare. In
221 string STR1, compare the part between START1 (inclusive) and END1
222 \(exclusive). If START1 is nil, it defaults to 0, the beginning of
223 the string; if END1 is nil, it defaults to the length of the string.
224 Likewise, in string STR2, compare the part between START2 and END2.
225 Like in `substring', negative values are counted from the end.
227 The strings are compared by the numeric values of their characters.
228 For instance, STR1 is "less than" STR2 if its first differing
229 character has a smaller numeric value. If IGNORE-CASE is non-nil,
230 characters are converted to upper-case before comparing them. Unibyte
231 strings are converted to multibyte for comparison.
233 The value is t if the strings (or specified portions) match.
234 If string STR1 is less, the value is a negative number N;
235 - 1 - N is the number of characters that match at the beginning.
236 If string STR1 is greater, the value is a positive number N;
237 N - 1 is the number of characters that match at the beginning. */)
238 (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2,
239 Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
241 ptrdiff_t from1, to1, from2, to2, i1, i1_byte, i2, i2_byte;
243 CHECK_STRING (str1);
244 CHECK_STRING (str2);
246 /* For backward compatibility, silently bring too-large positive end
247 values into range. */
248 if (INTEGERP (end1) && SCHARS (str1) < XINT (end1))
249 end1 = make_number (SCHARS (str1));
250 if (INTEGERP (end2) && SCHARS (str2) < XINT (end2))
251 end2 = make_number (SCHARS (str2));
253 validate_subarray (str1, start1, end1, SCHARS (str1), &from1, &to1);
254 validate_subarray (str2, start2, end2, SCHARS (str2), &from2, &to2);
256 i1 = from1;
257 i2 = from2;
259 i1_byte = string_char_to_byte (str1, i1);
260 i2_byte = string_char_to_byte (str2, i2);
262 while (i1 < to1 && i2 < to2)
264 /* When we find a mismatch, we must compare the
265 characters, not just the bytes. */
266 int c1, c2;
268 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c1, str1, i1, i1_byte);
269 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c2, str2, i2, i2_byte);
271 if (c1 == c2)
272 continue;
274 if (! NILP (ignore_case))
276 c1 = XINT (Fupcase (make_number (c1)));
277 c2 = XINT (Fupcase (make_number (c2)));
280 if (c1 == c2)
281 continue;
283 /* Note that I1 has already been incremented
284 past the character that we are comparing;
285 hence we don't add or subtract 1 here. */
286 if (c1 < c2)
287 return make_number (- i1 + from1);
288 else
289 return make_number (i1 - from1);
292 if (i1 < to1)
293 return make_number (i1 - from1 + 1);
294 if (i2 < to2)
295 return make_number (- i1 + from1 - 1);
297 return Qt;
300 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
301 doc: /* Return non-nil if STRING1 is less than STRING2 in lexicographic order.
302 Case is significant.
303 Symbols are also allowed; their print names are used instead. */)
304 (register Lisp_Object string1, Lisp_Object string2)
306 register ptrdiff_t end;
307 register ptrdiff_t i1, i1_byte, i2, i2_byte;
309 if (SYMBOLP (string1))
310 string1 = SYMBOL_NAME (string1);
311 if (SYMBOLP (string2))
312 string2 = SYMBOL_NAME (string2);
313 CHECK_STRING (string1);
314 CHECK_STRING (string2);
316 i1 = i1_byte = i2 = i2_byte = 0;
318 end = SCHARS (string1);
319 if (end > SCHARS (string2))
320 end = SCHARS (string2);
322 while (i1 < end)
324 /* When we find a mismatch, we must compare the
325 characters, not just the bytes. */
326 int c1, c2;
328 FETCH_STRING_CHAR_ADVANCE (c1, string1, i1, i1_byte);
329 FETCH_STRING_CHAR_ADVANCE (c2, string2, i2, i2_byte);
331 if (c1 != c2)
332 return c1 < c2 ? Qt : Qnil;
334 return i1 < SCHARS (string2) ? Qt : Qnil;
337 DEFUN ("string-version-lessp", Fstring_version_lessp,
338 Sstring_version_lessp, 2, 2, 0,
339 doc: /* Return non-nil if S1 is less than S2, as version strings.
341 This function compares version strings S1 and S2:
342 1) By prefix lexicographically.
343 2) Then by version (similarly to version comparison of Debian's dpkg).
344 Leading zeros in version numbers are ignored.
345 3) If both prefix and version are equal, compare as ordinary strings.
347 For example, \"foo2.png\" compares less than \"foo12.png\".
348 Case is significant.
349 Symbols are also allowed; their print names are used instead. */)
350 (Lisp_Object string1, Lisp_Object string2)
352 if (SYMBOLP (string1))
353 string1 = SYMBOL_NAME (string1);
354 if (SYMBOLP (string2))
355 string2 = SYMBOL_NAME (string2);
356 CHECK_STRING (string1);
357 CHECK_STRING (string2);
359 char *p1 = SSDATA (string1);
360 char *p2 = SSDATA (string2);
361 char *lim1 = p1 + SBYTES (string1);
362 char *lim2 = p2 + SBYTES (string2);
363 int cmp;
365 while ((cmp = filevercmp (p1, p2)) == 0)
367 /* If the strings are identical through their first null bytes,
368 skip past identical prefixes and try again. */
369 ptrdiff_t size = strlen (p1) + 1;
370 p1 += size;
371 p2 += size;
372 if (lim1 < p1)
373 return lim2 < p2 ? Qnil : Qt;
374 if (lim2 < p2)
375 return Qnil;
378 return cmp < 0 ? Qt : Qnil;
381 DEFUN ("string-collate-lessp", Fstring_collate_lessp, Sstring_collate_lessp, 2, 4, 0,
382 doc: /* Return t if first arg string is less than second in collation order.
383 Symbols are also allowed; their print names are used instead.
385 This function obeys the conventions for collation order in your
386 locale settings. For example, punctuation and whitespace characters
387 might be considered less significant for sorting:
389 \(sort \\='("11" "12" "1 1" "1 2" "1.1" "1.2") \\='string-collate-lessp)
390 => ("11" "1 1" "1.1" "12" "1 2" "1.2")
392 The optional argument LOCALE, a string, overrides the setting of your
393 current locale identifier for collation. The value is system
394 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
395 while it would be, e.g., \"enu_USA.1252\" on MS-Windows systems.
397 If IGNORE-CASE is non-nil, characters are converted to lower-case
398 before comparing them.
400 To emulate Unicode-compliant collation on MS-Windows systems,
401 bind `w32-collate-ignore-punctuation' to a non-nil value, since
402 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
404 If your system does not support a locale environment, this function
405 behaves like `string-lessp'. */)
406 (Lisp_Object s1, Lisp_Object s2, Lisp_Object locale, Lisp_Object ignore_case)
408 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
409 /* Check parameters. */
410 if (SYMBOLP (s1))
411 s1 = SYMBOL_NAME (s1);
412 if (SYMBOLP (s2))
413 s2 = SYMBOL_NAME (s2);
414 CHECK_STRING (s1);
415 CHECK_STRING (s2);
416 if (!NILP (locale))
417 CHECK_STRING (locale);
419 return (str_collate (s1, s2, locale, ignore_case) < 0) ? Qt : Qnil;
421 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
422 return Fstring_lessp (s1, s2);
423 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
426 DEFUN ("string-collate-equalp", Fstring_collate_equalp, Sstring_collate_equalp, 2, 4, 0,
427 doc: /* Return t if two strings have identical contents.
428 Symbols are also allowed; their print names are used instead.
430 This function obeys the conventions for collation order in your locale
431 settings. For example, characters with different coding points but
432 the same meaning might be considered as equal, like different grave
433 accent Unicode characters:
435 \(string-collate-equalp (string ?\\uFF40) (string ?\\u1FEF))
436 => t
438 The optional argument LOCALE, a string, overrides the setting of your
439 current locale identifier for collation. The value is system
440 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
441 while it would be \"enu_USA.1252\" on MS Windows systems.
443 If IGNORE-CASE is non-nil, characters are converted to lower-case
444 before comparing them.
446 To emulate Unicode-compliant collation on MS-Windows systems,
447 bind `w32-collate-ignore-punctuation' to a non-nil value, since
448 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
450 If your system does not support a locale environment, this function
451 behaves like `string-equal'.
453 Do NOT use this function to compare file names for equality. */)
454 (Lisp_Object s1, Lisp_Object s2, Lisp_Object locale, Lisp_Object ignore_case)
456 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
457 /* Check parameters. */
458 if (SYMBOLP (s1))
459 s1 = SYMBOL_NAME (s1);
460 if (SYMBOLP (s2))
461 s2 = SYMBOL_NAME (s2);
462 CHECK_STRING (s1);
463 CHECK_STRING (s2);
464 if (!NILP (locale))
465 CHECK_STRING (locale);
467 return (str_collate (s1, s2, locale, ignore_case) == 0) ? Qt : Qnil;
469 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
470 return Fstring_equal (s1, s2);
471 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
474 static Lisp_Object concat (ptrdiff_t nargs, Lisp_Object *args,
475 enum Lisp_Type target_type, bool last_special);
477 /* ARGSUSED */
478 Lisp_Object
479 concat2 (Lisp_Object s1, Lisp_Object s2)
481 return concat (2, ((Lisp_Object []) {s1, s2}), Lisp_String, 0);
484 /* ARGSUSED */
485 Lisp_Object
486 concat3 (Lisp_Object s1, Lisp_Object s2, Lisp_Object s3)
488 return concat (3, ((Lisp_Object []) {s1, s2, s3}), Lisp_String, 0);
491 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
492 doc: /* Concatenate all the arguments and make the result a list.
493 The result is a list whose elements are the elements of all the arguments.
494 Each argument may be a list, vector or string.
495 The last argument is not copied, just used as the tail of the new list.
496 usage: (append &rest SEQUENCES) */)
497 (ptrdiff_t nargs, Lisp_Object *args)
499 return concat (nargs, args, Lisp_Cons, 1);
502 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
503 doc: /* Concatenate all the arguments and make the result a string.
504 The result is a string whose elements are the elements of all the arguments.
505 Each argument may be a string or a list or vector of characters (integers).
506 usage: (concat &rest SEQUENCES) */)
507 (ptrdiff_t nargs, Lisp_Object *args)
509 return concat (nargs, args, Lisp_String, 0);
512 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
513 doc: /* Concatenate all the arguments and make the result a vector.
514 The result is a vector whose elements are the elements of all the arguments.
515 Each argument may be a list, vector or string.
516 usage: (vconcat &rest SEQUENCES) */)
517 (ptrdiff_t nargs, Lisp_Object *args)
519 return concat (nargs, args, Lisp_Vectorlike, 0);
523 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
524 doc: /* Return a copy of a list, vector, string or char-table.
525 The elements of a list or vector are not copied; they are shared
526 with the original. */)
527 (Lisp_Object arg)
529 if (NILP (arg)) return arg;
531 if (CHAR_TABLE_P (arg))
533 return copy_char_table (arg);
536 if (BOOL_VECTOR_P (arg))
538 EMACS_INT nbits = bool_vector_size (arg);
539 ptrdiff_t nbytes = bool_vector_bytes (nbits);
540 Lisp_Object val = make_uninit_bool_vector (nbits);
541 memcpy (bool_vector_data (val), bool_vector_data (arg), nbytes);
542 return val;
545 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
546 wrong_type_argument (Qsequencep, arg);
548 return concat (1, &arg, XTYPE (arg), 0);
551 /* This structure holds information of an argument of `concat' that is
552 a string and has text properties to be copied. */
553 struct textprop_rec
555 ptrdiff_t argnum; /* refer to ARGS (arguments of `concat') */
556 ptrdiff_t from; /* refer to ARGS[argnum] (argument string) */
557 ptrdiff_t to; /* refer to VAL (the target string) */
560 static Lisp_Object
561 concat (ptrdiff_t nargs, Lisp_Object *args,
562 enum Lisp_Type target_type, bool last_special)
564 Lisp_Object val;
565 Lisp_Object tail;
566 Lisp_Object this;
567 ptrdiff_t toindex;
568 ptrdiff_t toindex_byte = 0;
569 EMACS_INT result_len;
570 EMACS_INT result_len_byte;
571 ptrdiff_t argnum;
572 Lisp_Object last_tail;
573 Lisp_Object prev;
574 bool some_multibyte;
575 /* When we make a multibyte string, we can't copy text properties
576 while concatenating each string because the length of resulting
577 string can't be decided until we finish the whole concatenation.
578 So, we record strings that have text properties to be copied
579 here, and copy the text properties after the concatenation. */
580 struct textprop_rec *textprops = NULL;
581 /* Number of elements in textprops. */
582 ptrdiff_t num_textprops = 0;
583 USE_SAFE_ALLOCA;
585 tail = Qnil;
587 /* In append, the last arg isn't treated like the others */
588 if (last_special && nargs > 0)
590 nargs--;
591 last_tail = args[nargs];
593 else
594 last_tail = Qnil;
596 /* Check each argument. */
597 for (argnum = 0; argnum < nargs; argnum++)
599 this = args[argnum];
600 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
601 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
602 wrong_type_argument (Qsequencep, this);
605 /* Compute total length in chars of arguments in RESULT_LEN.
606 If desired output is a string, also compute length in bytes
607 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
608 whether the result should be a multibyte string. */
609 result_len_byte = 0;
610 result_len = 0;
611 some_multibyte = 0;
612 for (argnum = 0; argnum < nargs; argnum++)
614 EMACS_INT len;
615 this = args[argnum];
616 len = XFASTINT (Flength (this));
617 if (target_type == Lisp_String)
619 /* We must count the number of bytes needed in the string
620 as well as the number of characters. */
621 ptrdiff_t i;
622 Lisp_Object ch;
623 int c;
624 ptrdiff_t this_len_byte;
626 if (VECTORP (this) || COMPILEDP (this))
627 for (i = 0; i < len; i++)
629 ch = AREF (this, i);
630 CHECK_CHARACTER (ch);
631 c = XFASTINT (ch);
632 this_len_byte = CHAR_BYTES (c);
633 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
634 string_overflow ();
635 result_len_byte += this_len_byte;
636 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
637 some_multibyte = 1;
639 else if (BOOL_VECTOR_P (this) && bool_vector_size (this) > 0)
640 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
641 else if (CONSP (this))
642 for (; CONSP (this); this = XCDR (this))
644 ch = XCAR (this);
645 CHECK_CHARACTER (ch);
646 c = XFASTINT (ch);
647 this_len_byte = CHAR_BYTES (c);
648 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
649 string_overflow ();
650 result_len_byte += this_len_byte;
651 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
652 some_multibyte = 1;
654 else if (STRINGP (this))
656 if (STRING_MULTIBYTE (this))
658 some_multibyte = 1;
659 this_len_byte = SBYTES (this);
661 else
662 this_len_byte = count_size_as_multibyte (SDATA (this),
663 SCHARS (this));
664 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
665 string_overflow ();
666 result_len_byte += this_len_byte;
670 result_len += len;
671 if (MOST_POSITIVE_FIXNUM < result_len)
672 memory_full (SIZE_MAX);
675 if (! some_multibyte)
676 result_len_byte = result_len;
678 /* Create the output object. */
679 if (target_type == Lisp_Cons)
680 val = Fmake_list (make_number (result_len), Qnil);
681 else if (target_type == Lisp_Vectorlike)
682 val = Fmake_vector (make_number (result_len), Qnil);
683 else if (some_multibyte)
684 val = make_uninit_multibyte_string (result_len, result_len_byte);
685 else
686 val = make_uninit_string (result_len);
688 /* In `append', if all but last arg are nil, return last arg. */
689 if (target_type == Lisp_Cons && EQ (val, Qnil))
690 return last_tail;
692 /* Copy the contents of the args into the result. */
693 if (CONSP (val))
694 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
695 else
696 toindex = 0, toindex_byte = 0;
698 prev = Qnil;
699 if (STRINGP (val))
700 SAFE_NALLOCA (textprops, 1, nargs);
702 for (argnum = 0; argnum < nargs; argnum++)
704 Lisp_Object thislen;
705 ptrdiff_t thisleni = 0;
706 register ptrdiff_t thisindex = 0;
707 register ptrdiff_t thisindex_byte = 0;
709 this = args[argnum];
710 if (!CONSP (this))
711 thislen = Flength (this), thisleni = XINT (thislen);
713 /* Between strings of the same kind, copy fast. */
714 if (STRINGP (this) && STRINGP (val)
715 && STRING_MULTIBYTE (this) == some_multibyte)
717 ptrdiff_t thislen_byte = SBYTES (this);
719 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
720 if (string_intervals (this))
722 textprops[num_textprops].argnum = argnum;
723 textprops[num_textprops].from = 0;
724 textprops[num_textprops++].to = toindex;
726 toindex_byte += thislen_byte;
727 toindex += thisleni;
729 /* Copy a single-byte string to a multibyte string. */
730 else if (STRINGP (this) && STRINGP (val))
732 if (string_intervals (this))
734 textprops[num_textprops].argnum = argnum;
735 textprops[num_textprops].from = 0;
736 textprops[num_textprops++].to = toindex;
738 toindex_byte += copy_text (SDATA (this),
739 SDATA (val) + toindex_byte,
740 SCHARS (this), 0, 1);
741 toindex += thisleni;
743 else
744 /* Copy element by element. */
745 while (1)
747 register Lisp_Object elt;
749 /* Fetch next element of `this' arg into `elt', or break if
750 `this' is exhausted. */
751 if (NILP (this)) break;
752 if (CONSP (this))
753 elt = XCAR (this), this = XCDR (this);
754 else if (thisindex >= thisleni)
755 break;
756 else if (STRINGP (this))
758 int c;
759 if (STRING_MULTIBYTE (this))
760 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
761 thisindex,
762 thisindex_byte);
763 else
765 c = SREF (this, thisindex); thisindex++;
766 if (some_multibyte && !ASCII_CHAR_P (c))
767 c = BYTE8_TO_CHAR (c);
769 XSETFASTINT (elt, c);
771 else if (BOOL_VECTOR_P (this))
773 elt = bool_vector_ref (this, thisindex);
774 thisindex++;
776 else
778 elt = AREF (this, thisindex);
779 thisindex++;
782 /* Store this element into the result. */
783 if (toindex < 0)
785 XSETCAR (tail, elt);
786 prev = tail;
787 tail = XCDR (tail);
789 else if (VECTORP (val))
791 ASET (val, toindex, elt);
792 toindex++;
794 else
796 int c;
797 CHECK_CHARACTER (elt);
798 c = XFASTINT (elt);
799 if (some_multibyte)
800 toindex_byte += CHAR_STRING (c, SDATA (val) + toindex_byte);
801 else
802 SSET (val, toindex_byte++, c);
803 toindex++;
807 if (!NILP (prev))
808 XSETCDR (prev, last_tail);
810 if (num_textprops > 0)
812 Lisp_Object props;
813 ptrdiff_t last_to_end = -1;
815 for (argnum = 0; argnum < num_textprops; argnum++)
817 this = args[textprops[argnum].argnum];
818 props = text_property_list (this,
819 make_number (0),
820 make_number (SCHARS (this)),
821 Qnil);
822 /* If successive arguments have properties, be sure that the
823 value of `composition' property be the copy. */
824 if (last_to_end == textprops[argnum].to)
825 make_composition_value_copy (props);
826 add_text_properties_from_list (val, props,
827 make_number (textprops[argnum].to));
828 last_to_end = textprops[argnum].to + SCHARS (this);
832 SAFE_FREE ();
833 return val;
836 static Lisp_Object string_char_byte_cache_string;
837 static ptrdiff_t string_char_byte_cache_charpos;
838 static ptrdiff_t string_char_byte_cache_bytepos;
840 void
841 clear_string_char_byte_cache (void)
843 string_char_byte_cache_string = Qnil;
846 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
848 ptrdiff_t
849 string_char_to_byte (Lisp_Object string, ptrdiff_t char_index)
851 ptrdiff_t i_byte;
852 ptrdiff_t best_below, best_below_byte;
853 ptrdiff_t best_above, best_above_byte;
855 best_below = best_below_byte = 0;
856 best_above = SCHARS (string);
857 best_above_byte = SBYTES (string);
858 if (best_above == best_above_byte)
859 return char_index;
861 if (EQ (string, string_char_byte_cache_string))
863 if (string_char_byte_cache_charpos < char_index)
865 best_below = string_char_byte_cache_charpos;
866 best_below_byte = string_char_byte_cache_bytepos;
868 else
870 best_above = string_char_byte_cache_charpos;
871 best_above_byte = string_char_byte_cache_bytepos;
875 if (char_index - best_below < best_above - char_index)
877 unsigned char *p = SDATA (string) + best_below_byte;
879 while (best_below < char_index)
881 p += BYTES_BY_CHAR_HEAD (*p);
882 best_below++;
884 i_byte = p - SDATA (string);
886 else
888 unsigned char *p = SDATA (string) + best_above_byte;
890 while (best_above > char_index)
892 p--;
893 while (!CHAR_HEAD_P (*p)) p--;
894 best_above--;
896 i_byte = p - SDATA (string);
899 string_char_byte_cache_bytepos = i_byte;
900 string_char_byte_cache_charpos = char_index;
901 string_char_byte_cache_string = string;
903 return i_byte;
906 /* Return the character index corresponding to BYTE_INDEX in STRING. */
908 ptrdiff_t
909 string_byte_to_char (Lisp_Object string, ptrdiff_t byte_index)
911 ptrdiff_t i, i_byte;
912 ptrdiff_t best_below, best_below_byte;
913 ptrdiff_t best_above, best_above_byte;
915 best_below = best_below_byte = 0;
916 best_above = SCHARS (string);
917 best_above_byte = SBYTES (string);
918 if (best_above == best_above_byte)
919 return byte_index;
921 if (EQ (string, string_char_byte_cache_string))
923 if (string_char_byte_cache_bytepos < byte_index)
925 best_below = string_char_byte_cache_charpos;
926 best_below_byte = string_char_byte_cache_bytepos;
928 else
930 best_above = string_char_byte_cache_charpos;
931 best_above_byte = string_char_byte_cache_bytepos;
935 if (byte_index - best_below_byte < best_above_byte - byte_index)
937 unsigned char *p = SDATA (string) + best_below_byte;
938 unsigned char *pend = SDATA (string) + byte_index;
940 while (p < pend)
942 p += BYTES_BY_CHAR_HEAD (*p);
943 best_below++;
945 i = best_below;
946 i_byte = p - SDATA (string);
948 else
950 unsigned char *p = SDATA (string) + best_above_byte;
951 unsigned char *pbeg = SDATA (string) + byte_index;
953 while (p > pbeg)
955 p--;
956 while (!CHAR_HEAD_P (*p)) p--;
957 best_above--;
959 i = best_above;
960 i_byte = p - SDATA (string);
963 string_char_byte_cache_bytepos = i_byte;
964 string_char_byte_cache_charpos = i;
965 string_char_byte_cache_string = string;
967 return i;
970 /* Convert STRING to a multibyte string. */
972 static Lisp_Object
973 string_make_multibyte (Lisp_Object string)
975 unsigned char *buf;
976 ptrdiff_t nbytes;
977 Lisp_Object ret;
978 USE_SAFE_ALLOCA;
980 if (STRING_MULTIBYTE (string))
981 return string;
983 nbytes = count_size_as_multibyte (SDATA (string),
984 SCHARS (string));
985 /* If all the chars are ASCII, they won't need any more bytes
986 once converted. In that case, we can return STRING itself. */
987 if (nbytes == SBYTES (string))
988 return string;
990 buf = SAFE_ALLOCA (nbytes);
991 copy_text (SDATA (string), buf, SBYTES (string),
992 0, 1);
994 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
995 SAFE_FREE ();
997 return ret;
1001 /* Convert STRING (if unibyte) to a multibyte string without changing
1002 the number of characters. Characters 0200 trough 0237 are
1003 converted to eight-bit characters. */
1005 Lisp_Object
1006 string_to_multibyte (Lisp_Object string)
1008 unsigned char *buf;
1009 ptrdiff_t nbytes;
1010 Lisp_Object ret;
1011 USE_SAFE_ALLOCA;
1013 if (STRING_MULTIBYTE (string))
1014 return string;
1016 nbytes = count_size_as_multibyte (SDATA (string), SBYTES (string));
1017 /* If all the chars are ASCII, they won't need any more bytes once
1018 converted. */
1019 if (nbytes == SBYTES (string))
1020 return make_multibyte_string (SSDATA (string), nbytes, nbytes);
1022 buf = SAFE_ALLOCA (nbytes);
1023 memcpy (buf, SDATA (string), SBYTES (string));
1024 str_to_multibyte (buf, nbytes, SBYTES (string));
1026 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
1027 SAFE_FREE ();
1029 return ret;
1033 /* Convert STRING to a single-byte string. */
1035 Lisp_Object
1036 string_make_unibyte (Lisp_Object string)
1038 ptrdiff_t nchars;
1039 unsigned char *buf;
1040 Lisp_Object ret;
1041 USE_SAFE_ALLOCA;
1043 if (! STRING_MULTIBYTE (string))
1044 return string;
1046 nchars = SCHARS (string);
1048 buf = SAFE_ALLOCA (nchars);
1049 copy_text (SDATA (string), buf, SBYTES (string),
1050 1, 0);
1052 ret = make_unibyte_string ((char *) buf, nchars);
1053 SAFE_FREE ();
1055 return ret;
1058 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
1059 1, 1, 0,
1060 doc: /* Return the multibyte equivalent of STRING.
1061 If STRING is unibyte and contains non-ASCII characters, the function
1062 `unibyte-char-to-multibyte' is used to convert each unibyte character
1063 to a multibyte character. In this case, the returned string is a
1064 newly created string with no text properties. If STRING is multibyte
1065 or entirely ASCII, it is returned unchanged. In particular, when
1066 STRING is unibyte and entirely ASCII, the returned string is unibyte.
1067 \(When the characters are all ASCII, Emacs primitives will treat the
1068 string the same way whether it is unibyte or multibyte.) */)
1069 (Lisp_Object string)
1071 CHECK_STRING (string);
1073 return string_make_multibyte (string);
1076 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
1077 1, 1, 0,
1078 doc: /* Return the unibyte equivalent of STRING.
1079 Multibyte character codes are converted to unibyte according to
1080 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
1081 If the lookup in the translation table fails, this function takes just
1082 the low 8 bits of each character. */)
1083 (Lisp_Object string)
1085 CHECK_STRING (string);
1087 return string_make_unibyte (string);
1090 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
1091 1, 1, 0,
1092 doc: /* Return a unibyte string with the same individual bytes as STRING.
1093 If STRING is unibyte, the result is STRING itself.
1094 Otherwise it is a newly created string, with no text properties.
1095 If STRING is multibyte and contains a character of charset
1096 `eight-bit', it is converted to the corresponding single byte. */)
1097 (Lisp_Object string)
1099 CHECK_STRING (string);
1101 if (STRING_MULTIBYTE (string))
1103 unsigned char *str = (unsigned char *) xlispstrdup (string);
1104 ptrdiff_t bytes = str_as_unibyte (str, SBYTES (string));
1106 string = make_unibyte_string ((char *) str, bytes);
1107 xfree (str);
1109 return string;
1112 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1113 1, 1, 0,
1114 doc: /* Return a multibyte string with the same individual bytes as STRING.
1115 If STRING is multibyte, the result is STRING itself.
1116 Otherwise it is a newly created string, with no text properties.
1118 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1119 part of a correct utf-8 sequence), it is converted to the corresponding
1120 multibyte character of charset `eight-bit'.
1121 See also `string-to-multibyte'.
1123 Beware, this often doesn't really do what you think it does.
1124 It is similar to (decode-coding-string STRING \\='utf-8-emacs).
1125 If you're not sure, whether to use `string-as-multibyte' or
1126 `string-to-multibyte', use `string-to-multibyte'. */)
1127 (Lisp_Object string)
1129 CHECK_STRING (string);
1131 if (! STRING_MULTIBYTE (string))
1133 Lisp_Object new_string;
1134 ptrdiff_t nchars, nbytes;
1136 parse_str_as_multibyte (SDATA (string),
1137 SBYTES (string),
1138 &nchars, &nbytes);
1139 new_string = make_uninit_multibyte_string (nchars, nbytes);
1140 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1141 if (nbytes != SBYTES (string))
1142 str_as_multibyte (SDATA (new_string), nbytes,
1143 SBYTES (string), NULL);
1144 string = new_string;
1145 set_string_intervals (string, NULL);
1147 return string;
1150 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1151 1, 1, 0,
1152 doc: /* Return a multibyte string with the same individual chars as STRING.
1153 If STRING is multibyte, the result is STRING itself.
1154 Otherwise it is a newly created string, with no text properties.
1156 If STRING is unibyte and contains an 8-bit byte, it is converted to
1157 the corresponding multibyte character of charset `eight-bit'.
1159 This differs from `string-as-multibyte' by converting each byte of a correct
1160 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1161 correct sequence. */)
1162 (Lisp_Object string)
1164 CHECK_STRING (string);
1166 return string_to_multibyte (string);
1169 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1170 1, 1, 0,
1171 doc: /* Return a unibyte string with the same individual chars as STRING.
1172 If STRING is unibyte, the result is STRING itself.
1173 Otherwise it is a newly created string, with no text properties,
1174 where each `eight-bit' character is converted to the corresponding byte.
1175 If STRING contains a non-ASCII, non-`eight-bit' character,
1176 an error is signaled. */)
1177 (Lisp_Object string)
1179 CHECK_STRING (string);
1181 if (STRING_MULTIBYTE (string))
1183 ptrdiff_t chars = SCHARS (string);
1184 unsigned char *str = xmalloc (chars);
1185 ptrdiff_t converted = str_to_unibyte (SDATA (string), str, chars);
1187 if (converted < chars)
1188 error ("Can't convert the %"pD"dth character to unibyte", converted);
1189 string = make_unibyte_string ((char *) str, chars);
1190 xfree (str);
1192 return string;
1196 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1197 doc: /* Return a copy of ALIST.
1198 This is an alist which represents the same mapping from objects to objects,
1199 but does not share the alist structure with ALIST.
1200 The objects mapped (cars and cdrs of elements of the alist)
1201 are shared, however.
1202 Elements of ALIST that are not conses are also shared. */)
1203 (Lisp_Object alist)
1205 register Lisp_Object tem;
1207 CHECK_LIST (alist);
1208 if (NILP (alist))
1209 return alist;
1210 alist = concat (1, &alist, Lisp_Cons, 0);
1211 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1213 register Lisp_Object car;
1214 car = XCAR (tem);
1216 if (CONSP (car))
1217 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1219 return alist;
1222 /* Check that ARRAY can have a valid subarray [FROM..TO),
1223 given that its size is SIZE.
1224 If FROM is nil, use 0; if TO is nil, use SIZE.
1225 Count negative values backwards from the end.
1226 Set *IFROM and *ITO to the two indexes used. */
1228 void
1229 validate_subarray (Lisp_Object array, Lisp_Object from, Lisp_Object to,
1230 ptrdiff_t size, ptrdiff_t *ifrom, ptrdiff_t *ito)
1232 EMACS_INT f, t;
1234 if (INTEGERP (from))
1236 f = XINT (from);
1237 if (f < 0)
1238 f += size;
1240 else if (NILP (from))
1241 f = 0;
1242 else
1243 wrong_type_argument (Qintegerp, from);
1245 if (INTEGERP (to))
1247 t = XINT (to);
1248 if (t < 0)
1249 t += size;
1251 else if (NILP (to))
1252 t = size;
1253 else
1254 wrong_type_argument (Qintegerp, to);
1256 if (! (0 <= f && f <= t && t <= size))
1257 args_out_of_range_3 (array, from, to);
1259 *ifrom = f;
1260 *ito = t;
1263 DEFUN ("substring", Fsubstring, Ssubstring, 1, 3, 0,
1264 doc: /* Return a new string whose contents are a substring of STRING.
1265 The returned string consists of the characters between index FROM
1266 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1267 zero-indexed: 0 means the first character of STRING. Negative values
1268 are counted from the end of STRING. If TO is nil, the substring runs
1269 to the end of STRING.
1271 The STRING argument may also be a vector. In that case, the return
1272 value is a new vector that contains the elements between index FROM
1273 \(inclusive) and index TO (exclusive) of that vector argument.
1275 With one argument, just copy STRING (with properties, if any). */)
1276 (Lisp_Object string, Lisp_Object from, Lisp_Object to)
1278 Lisp_Object res;
1279 ptrdiff_t size, ifrom, ito;
1281 size = CHECK_VECTOR_OR_STRING (string);
1282 validate_subarray (string, from, to, size, &ifrom, &ito);
1284 if (STRINGP (string))
1286 ptrdiff_t from_byte
1287 = !ifrom ? 0 : string_char_to_byte (string, ifrom);
1288 ptrdiff_t to_byte
1289 = ito == size ? SBYTES (string) : string_char_to_byte (string, ito);
1290 res = make_specified_string (SSDATA (string) + from_byte,
1291 ito - ifrom, to_byte - from_byte,
1292 STRING_MULTIBYTE (string));
1293 copy_text_properties (make_number (ifrom), make_number (ito),
1294 string, make_number (0), res, Qnil);
1296 else
1297 res = Fvector (ito - ifrom, aref_addr (string, ifrom));
1299 return res;
1303 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1304 doc: /* Return a substring of STRING, without text properties.
1305 It starts at index FROM and ends before TO.
1306 TO may be nil or omitted; then the substring runs to the end of STRING.
1307 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1308 If FROM or TO is negative, it counts from the end.
1310 With one argument, just copy STRING without its properties. */)
1311 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1313 ptrdiff_t from_char, to_char, from_byte, to_byte, size;
1315 CHECK_STRING (string);
1317 size = SCHARS (string);
1318 validate_subarray (string, from, to, size, &from_char, &to_char);
1320 from_byte = !from_char ? 0 : string_char_to_byte (string, from_char);
1321 to_byte =
1322 to_char == size ? SBYTES (string) : string_char_to_byte (string, to_char);
1323 return make_specified_string (SSDATA (string) + from_byte,
1324 to_char - from_char, to_byte - from_byte,
1325 STRING_MULTIBYTE (string));
1328 /* Extract a substring of STRING, giving start and end positions
1329 both in characters and in bytes. */
1331 Lisp_Object
1332 substring_both (Lisp_Object string, ptrdiff_t from, ptrdiff_t from_byte,
1333 ptrdiff_t to, ptrdiff_t to_byte)
1335 Lisp_Object res;
1336 ptrdiff_t size = CHECK_VECTOR_OR_STRING (string);
1338 if (!(0 <= from && from <= to && to <= size))
1339 args_out_of_range_3 (string, make_number (from), make_number (to));
1341 if (STRINGP (string))
1343 res = make_specified_string (SSDATA (string) + from_byte,
1344 to - from, to_byte - from_byte,
1345 STRING_MULTIBYTE (string));
1346 copy_text_properties (make_number (from), make_number (to),
1347 string, make_number (0), res, Qnil);
1349 else
1350 res = Fvector (to - from, aref_addr (string, from));
1352 return res;
1355 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1356 doc: /* Take cdr N times on LIST, return the result. */)
1357 (Lisp_Object n, Lisp_Object list)
1359 EMACS_INT i, num;
1360 CHECK_NUMBER (n);
1361 num = XINT (n);
1362 for (i = 0; i < num && !NILP (list); i++)
1364 QUIT;
1365 CHECK_LIST_CONS (list, list);
1366 list = XCDR (list);
1368 return list;
1371 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1372 doc: /* Return the Nth element of LIST.
1373 N counts from zero. If LIST is not that long, nil is returned. */)
1374 (Lisp_Object n, Lisp_Object list)
1376 return Fcar (Fnthcdr (n, list));
1379 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1380 doc: /* Return element of SEQUENCE at index N. */)
1381 (register Lisp_Object sequence, Lisp_Object n)
1383 CHECK_NUMBER (n);
1384 if (CONSP (sequence) || NILP (sequence))
1385 return Fcar (Fnthcdr (n, sequence));
1387 /* Faref signals a "not array" error, so check here. */
1388 CHECK_ARRAY (sequence, Qsequencep);
1389 return Faref (sequence, n);
1392 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1393 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1394 The value is actually the tail of LIST whose car is ELT. */)
1395 (register Lisp_Object elt, Lisp_Object list)
1397 register Lisp_Object tail;
1398 for (tail = list; !NILP (tail); tail = XCDR (tail))
1400 register Lisp_Object tem;
1401 CHECK_LIST_CONS (tail, list);
1402 tem = XCAR (tail);
1403 if (! NILP (Fequal (elt, tem)))
1404 return tail;
1405 QUIT;
1407 return Qnil;
1410 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1411 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1412 The value is actually the tail of LIST whose car is ELT. */)
1413 (register Lisp_Object elt, Lisp_Object list)
1415 while (1)
1417 if (!CONSP (list) || EQ (XCAR (list), elt))
1418 break;
1420 list = XCDR (list);
1421 if (!CONSP (list) || EQ (XCAR (list), elt))
1422 break;
1424 list = XCDR (list);
1425 if (!CONSP (list) || EQ (XCAR (list), elt))
1426 break;
1428 list = XCDR (list);
1429 QUIT;
1432 CHECK_LIST (list);
1433 return list;
1436 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1437 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1438 The value is actually the tail of LIST whose car is ELT. */)
1439 (register Lisp_Object elt, Lisp_Object list)
1441 register Lisp_Object tail;
1443 if (!FLOATP (elt))
1444 return Fmemq (elt, list);
1446 for (tail = list; !NILP (tail); tail = XCDR (tail))
1448 register Lisp_Object tem;
1449 CHECK_LIST_CONS (tail, list);
1450 tem = XCAR (tail);
1451 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0, Qnil))
1452 return tail;
1453 QUIT;
1455 return Qnil;
1458 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1459 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1460 The value is actually the first element of LIST whose car is KEY.
1461 Elements of LIST that are not conses are ignored. */)
1462 (Lisp_Object key, Lisp_Object list)
1464 while (1)
1466 if (!CONSP (list)
1467 || (CONSP (XCAR (list))
1468 && EQ (XCAR (XCAR (list)), key)))
1469 break;
1471 list = XCDR (list);
1472 if (!CONSP (list)
1473 || (CONSP (XCAR (list))
1474 && EQ (XCAR (XCAR (list)), key)))
1475 break;
1477 list = XCDR (list);
1478 if (!CONSP (list)
1479 || (CONSP (XCAR (list))
1480 && EQ (XCAR (XCAR (list)), key)))
1481 break;
1483 list = XCDR (list);
1484 QUIT;
1487 return CAR (list);
1490 /* Like Fassq but never report an error and do not allow quits.
1491 Use only on lists known never to be circular. */
1493 Lisp_Object
1494 assq_no_quit (Lisp_Object key, Lisp_Object list)
1496 while (CONSP (list)
1497 && (!CONSP (XCAR (list))
1498 || !EQ (XCAR (XCAR (list)), key)))
1499 list = XCDR (list);
1501 return CAR_SAFE (list);
1504 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1505 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1506 The value is actually the first element of LIST whose car equals KEY. */)
1507 (Lisp_Object key, Lisp_Object list)
1509 Lisp_Object car;
1511 while (1)
1513 if (!CONSP (list)
1514 || (CONSP (XCAR (list))
1515 && (car = XCAR (XCAR (list)),
1516 EQ (car, key) || !NILP (Fequal (car, key)))))
1517 break;
1519 list = XCDR (list);
1520 if (!CONSP (list)
1521 || (CONSP (XCAR (list))
1522 && (car = XCAR (XCAR (list)),
1523 EQ (car, key) || !NILP (Fequal (car, key)))))
1524 break;
1526 list = XCDR (list);
1527 if (!CONSP (list)
1528 || (CONSP (XCAR (list))
1529 && (car = XCAR (XCAR (list)),
1530 EQ (car, key) || !NILP (Fequal (car, key)))))
1531 break;
1533 list = XCDR (list);
1534 QUIT;
1537 return CAR (list);
1540 /* Like Fassoc but never report an error and do not allow quits.
1541 Use only on lists known never to be circular. */
1543 Lisp_Object
1544 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1546 while (CONSP (list)
1547 && (!CONSP (XCAR (list))
1548 || (!EQ (XCAR (XCAR (list)), key)
1549 && NILP (Fequal (XCAR (XCAR (list)), key)))))
1550 list = XCDR (list);
1552 return CONSP (list) ? XCAR (list) : Qnil;
1555 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1556 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1557 The value is actually the first element of LIST whose cdr is KEY. */)
1558 (register Lisp_Object key, Lisp_Object list)
1560 while (1)
1562 if (!CONSP (list)
1563 || (CONSP (XCAR (list))
1564 && EQ (XCDR (XCAR (list)), key)))
1565 break;
1567 list = XCDR (list);
1568 if (!CONSP (list)
1569 || (CONSP (XCAR (list))
1570 && EQ (XCDR (XCAR (list)), key)))
1571 break;
1573 list = XCDR (list);
1574 if (!CONSP (list)
1575 || (CONSP (XCAR (list))
1576 && EQ (XCDR (XCAR (list)), key)))
1577 break;
1579 list = XCDR (list);
1580 QUIT;
1583 return CAR (list);
1586 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1587 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1588 The value is actually the first element of LIST whose cdr equals KEY. */)
1589 (Lisp_Object key, Lisp_Object list)
1591 Lisp_Object cdr;
1593 while (1)
1595 if (!CONSP (list)
1596 || (CONSP (XCAR (list))
1597 && (cdr = XCDR (XCAR (list)),
1598 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1599 break;
1601 list = XCDR (list);
1602 if (!CONSP (list)
1603 || (CONSP (XCAR (list))
1604 && (cdr = XCDR (XCAR (list)),
1605 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1606 break;
1608 list = XCDR (list);
1609 if (!CONSP (list)
1610 || (CONSP (XCAR (list))
1611 && (cdr = XCDR (XCAR (list)),
1612 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1613 break;
1615 list = XCDR (list);
1616 QUIT;
1619 return CAR (list);
1622 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1623 doc: /* Delete members of LIST which are `eq' to ELT, and return the result.
1624 More precisely, this function skips any members `eq' to ELT at the
1625 front of LIST, then removes members `eq' to ELT from the remaining
1626 sublist by modifying its list structure, then returns the resulting
1627 list.
1629 Write `(setq foo (delq element foo))' to be sure of correctly changing
1630 the value of a list `foo'. See also `remq', which does not modify the
1631 argument. */)
1632 (register Lisp_Object elt, Lisp_Object list)
1634 Lisp_Object tail, tortoise, prev = Qnil;
1635 bool skip;
1637 FOR_EACH_TAIL (tail, list, tortoise, skip)
1639 Lisp_Object tem = XCAR (tail);
1640 if (EQ (elt, tem))
1642 if (NILP (prev))
1643 list = XCDR (tail);
1644 else
1645 Fsetcdr (prev, XCDR (tail));
1647 else
1648 prev = tail;
1650 return list;
1653 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1654 doc: /* Delete members of SEQ which are `equal' to ELT, and return the result.
1655 SEQ must be a sequence (i.e. a list, a vector, or a string).
1656 The return value is a sequence of the same type.
1658 If SEQ is a list, this behaves like `delq', except that it compares
1659 with `equal' instead of `eq'. In particular, it may remove elements
1660 by altering the list structure.
1662 If SEQ is not a list, deletion is never performed destructively;
1663 instead this function creates and returns a new vector or string.
1665 Write `(setq foo (delete element foo))' to be sure of correctly
1666 changing the value of a sequence `foo'. */)
1667 (Lisp_Object elt, Lisp_Object seq)
1669 if (VECTORP (seq))
1671 ptrdiff_t i, n;
1673 for (i = n = 0; i < ASIZE (seq); ++i)
1674 if (NILP (Fequal (AREF (seq, i), elt)))
1675 ++n;
1677 if (n != ASIZE (seq))
1679 struct Lisp_Vector *p = allocate_vector (n);
1681 for (i = n = 0; i < ASIZE (seq); ++i)
1682 if (NILP (Fequal (AREF (seq, i), elt)))
1683 p->contents[n++] = AREF (seq, i);
1685 XSETVECTOR (seq, p);
1688 else if (STRINGP (seq))
1690 ptrdiff_t i, ibyte, nchars, nbytes, cbytes;
1691 int c;
1693 for (i = nchars = nbytes = ibyte = 0;
1694 i < SCHARS (seq);
1695 ++i, ibyte += cbytes)
1697 if (STRING_MULTIBYTE (seq))
1699 c = STRING_CHAR (SDATA (seq) + ibyte);
1700 cbytes = CHAR_BYTES (c);
1702 else
1704 c = SREF (seq, i);
1705 cbytes = 1;
1708 if (!INTEGERP (elt) || c != XINT (elt))
1710 ++nchars;
1711 nbytes += cbytes;
1715 if (nchars != SCHARS (seq))
1717 Lisp_Object tem;
1719 tem = make_uninit_multibyte_string (nchars, nbytes);
1720 if (!STRING_MULTIBYTE (seq))
1721 STRING_SET_UNIBYTE (tem);
1723 for (i = nchars = nbytes = ibyte = 0;
1724 i < SCHARS (seq);
1725 ++i, ibyte += cbytes)
1727 if (STRING_MULTIBYTE (seq))
1729 c = STRING_CHAR (SDATA (seq) + ibyte);
1730 cbytes = CHAR_BYTES (c);
1732 else
1734 c = SREF (seq, i);
1735 cbytes = 1;
1738 if (!INTEGERP (elt) || c != XINT (elt))
1740 unsigned char *from = SDATA (seq) + ibyte;
1741 unsigned char *to = SDATA (tem) + nbytes;
1742 ptrdiff_t n;
1744 ++nchars;
1745 nbytes += cbytes;
1747 for (n = cbytes; n--; )
1748 *to++ = *from++;
1752 seq = tem;
1755 else
1757 Lisp_Object tail, prev;
1759 for (tail = seq, prev = Qnil; !NILP (tail); tail = XCDR (tail))
1761 CHECK_LIST_CONS (tail, seq);
1763 if (!NILP (Fequal (elt, XCAR (tail))))
1765 if (NILP (prev))
1766 seq = XCDR (tail);
1767 else
1768 Fsetcdr (prev, XCDR (tail));
1770 else
1771 prev = tail;
1772 QUIT;
1776 return seq;
1779 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1780 doc: /* Reverse order of items in a list, vector or string SEQ.
1781 If SEQ is a list, it should be nil-terminated.
1782 This function may destructively modify SEQ to produce the value. */)
1783 (Lisp_Object seq)
1785 if (NILP (seq))
1786 return seq;
1787 else if (STRINGP (seq))
1788 return Freverse (seq);
1789 else if (CONSP (seq))
1791 Lisp_Object prev, tail, next;
1793 for (prev = Qnil, tail = seq; !NILP (tail); tail = next)
1795 QUIT;
1796 CHECK_LIST_CONS (tail, tail);
1797 next = XCDR (tail);
1798 Fsetcdr (tail, prev);
1799 prev = tail;
1801 seq = prev;
1803 else if (VECTORP (seq))
1805 ptrdiff_t i, size = ASIZE (seq);
1807 for (i = 0; i < size / 2; i++)
1809 Lisp_Object tem = AREF (seq, i);
1810 ASET (seq, i, AREF (seq, size - i - 1));
1811 ASET (seq, size - i - 1, tem);
1814 else if (BOOL_VECTOR_P (seq))
1816 ptrdiff_t i, size = bool_vector_size (seq);
1818 for (i = 0; i < size / 2; i++)
1820 bool tem = bool_vector_bitref (seq, i);
1821 bool_vector_set (seq, i, bool_vector_bitref (seq, size - i - 1));
1822 bool_vector_set (seq, size - i - 1, tem);
1825 else
1826 wrong_type_argument (Qarrayp, seq);
1827 return seq;
1830 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1831 doc: /* Return the reversed copy of list, vector, or string SEQ.
1832 See also the function `nreverse', which is used more often. */)
1833 (Lisp_Object seq)
1835 Lisp_Object new;
1837 if (NILP (seq))
1838 return Qnil;
1839 else if (CONSP (seq))
1841 for (new = Qnil; CONSP (seq); seq = XCDR (seq))
1843 QUIT;
1844 new = Fcons (XCAR (seq), new);
1846 CHECK_LIST_END (seq, seq);
1848 else if (VECTORP (seq))
1850 ptrdiff_t i, size = ASIZE (seq);
1852 new = make_uninit_vector (size);
1853 for (i = 0; i < size; i++)
1854 ASET (new, i, AREF (seq, size - i - 1));
1856 else if (BOOL_VECTOR_P (seq))
1858 ptrdiff_t i;
1859 EMACS_INT nbits = bool_vector_size (seq);
1861 new = make_uninit_bool_vector (nbits);
1862 for (i = 0; i < nbits; i++)
1863 bool_vector_set (new, i, bool_vector_bitref (seq, nbits - i - 1));
1865 else if (STRINGP (seq))
1867 ptrdiff_t size = SCHARS (seq), bytes = SBYTES (seq);
1869 if (size == bytes)
1871 ptrdiff_t i;
1873 new = make_uninit_string (size);
1874 for (i = 0; i < size; i++)
1875 SSET (new, i, SREF (seq, size - i - 1));
1877 else
1879 unsigned char *p, *q;
1881 new = make_uninit_multibyte_string (size, bytes);
1882 p = SDATA (seq), q = SDATA (new) + bytes;
1883 while (q > SDATA (new))
1885 int ch, len;
1887 ch = STRING_CHAR_AND_LENGTH (p, len);
1888 p += len, q -= len;
1889 CHAR_STRING (ch, q);
1893 else
1894 wrong_type_argument (Qsequencep, seq);
1895 return new;
1898 /* Sort LIST using PREDICATE, preserving original order of elements
1899 considered as equal. */
1901 static Lisp_Object
1902 sort_list (Lisp_Object list, Lisp_Object predicate)
1904 Lisp_Object front, back;
1905 Lisp_Object len, tem;
1906 EMACS_INT length;
1908 front = list;
1909 len = Flength (list);
1910 length = XINT (len);
1911 if (length < 2)
1912 return list;
1914 XSETINT (len, (length / 2) - 1);
1915 tem = Fnthcdr (len, list);
1916 back = Fcdr (tem);
1917 Fsetcdr (tem, Qnil);
1919 front = Fsort (front, predicate);
1920 back = Fsort (back, predicate);
1921 return merge (front, back, predicate);
1924 /* Using PRED to compare, return whether A and B are in order.
1925 Compare stably when A appeared before B in the input. */
1926 static bool
1927 inorder (Lisp_Object pred, Lisp_Object a, Lisp_Object b)
1929 return NILP (call2 (pred, b, a));
1932 /* Using PRED to compare, merge from ALEN-length A and BLEN-length B
1933 into DEST. Argument arrays must be nonempty and must not overlap,
1934 except that B might be the last part of DEST. */
1935 static void
1936 merge_vectors (Lisp_Object pred,
1937 ptrdiff_t alen, Lisp_Object const a[restrict VLA_ELEMS (alen)],
1938 ptrdiff_t blen, Lisp_Object const b[VLA_ELEMS (blen)],
1939 Lisp_Object dest[VLA_ELEMS (alen + blen)])
1941 eassume (0 < alen && 0 < blen);
1942 Lisp_Object const *alim = a + alen;
1943 Lisp_Object const *blim = b + blen;
1945 while (true)
1947 if (inorder (pred, a[0], b[0]))
1949 *dest++ = *a++;
1950 if (a == alim)
1952 if (dest != b)
1953 memcpy (dest, b, (blim - b) * sizeof *dest);
1954 return;
1957 else
1959 *dest++ = *b++;
1960 if (b == blim)
1962 memcpy (dest, a, (alim - a) * sizeof *dest);
1963 return;
1969 /* Using PRED to compare, sort LEN-length VEC in place, using TMP for
1970 temporary storage. LEN must be at least 2. */
1971 static void
1972 sort_vector_inplace (Lisp_Object pred, ptrdiff_t len,
1973 Lisp_Object vec[restrict VLA_ELEMS (len)],
1974 Lisp_Object tmp[restrict VLA_ELEMS (len >> 1)])
1976 eassume (2 <= len);
1977 ptrdiff_t halflen = len >> 1;
1978 sort_vector_copy (pred, halflen, vec, tmp);
1979 if (1 < len - halflen)
1980 sort_vector_inplace (pred, len - halflen, vec + halflen, vec);
1981 merge_vectors (pred, halflen, tmp, len - halflen, vec + halflen, vec);
1984 /* Using PRED to compare, sort from LEN-length SRC into DST.
1985 Len must be positive. */
1986 static void
1987 sort_vector_copy (Lisp_Object pred, ptrdiff_t len,
1988 Lisp_Object src[restrict VLA_ELEMS (len)],
1989 Lisp_Object dest[restrict VLA_ELEMS (len)])
1991 eassume (0 < len);
1992 ptrdiff_t halflen = len >> 1;
1993 if (halflen < 1)
1994 dest[0] = src[0];
1995 else
1997 if (1 < halflen)
1998 sort_vector_inplace (pred, halflen, src, dest);
1999 if (1 < len - halflen)
2000 sort_vector_inplace (pred, len - halflen, src + halflen, dest);
2001 merge_vectors (pred, halflen, src, len - halflen, src + halflen, dest);
2005 /* Sort VECTOR in place using PREDICATE, preserving original order of
2006 elements considered as equal. */
2008 static void
2009 sort_vector (Lisp_Object vector, Lisp_Object predicate)
2011 ptrdiff_t len = ASIZE (vector);
2012 if (len < 2)
2013 return;
2014 ptrdiff_t halflen = len >> 1;
2015 Lisp_Object *tmp;
2016 USE_SAFE_ALLOCA;
2017 SAFE_ALLOCA_LISP (tmp, halflen);
2018 for (ptrdiff_t i = 0; i < halflen; i++)
2019 tmp[i] = make_number (0);
2020 sort_vector_inplace (predicate, len, XVECTOR (vector)->contents, tmp);
2021 SAFE_FREE ();
2024 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
2025 doc: /* Sort SEQ, stably, comparing elements using PREDICATE.
2026 Returns the sorted sequence. SEQ should be a list or vector. SEQ is
2027 modified by side effects. PREDICATE is called with two elements of
2028 SEQ, and should return non-nil if the first element should sort before
2029 the second. */)
2030 (Lisp_Object seq, Lisp_Object predicate)
2032 if (CONSP (seq))
2033 seq = sort_list (seq, predicate);
2034 else if (VECTORP (seq))
2035 sort_vector (seq, predicate);
2036 else if (!NILP (seq))
2037 wrong_type_argument (Qsequencep, seq);
2038 return seq;
2041 Lisp_Object
2042 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
2044 Lisp_Object l1 = org_l1;
2045 Lisp_Object l2 = org_l2;
2046 Lisp_Object tail = Qnil;
2047 Lisp_Object value = Qnil;
2049 while (1)
2051 if (NILP (l1))
2053 if (NILP (tail))
2054 return l2;
2055 Fsetcdr (tail, l2);
2056 return value;
2058 if (NILP (l2))
2060 if (NILP (tail))
2061 return l1;
2062 Fsetcdr (tail, l1);
2063 return value;
2066 Lisp_Object tem;
2067 if (inorder (pred, Fcar (l1), Fcar (l2)))
2069 tem = l1;
2070 l1 = Fcdr (l1);
2071 org_l1 = l1;
2073 else
2075 tem = l2;
2076 l2 = Fcdr (l2);
2077 org_l2 = l2;
2079 if (NILP (tail))
2080 value = tem;
2081 else
2082 Fsetcdr (tail, tem);
2083 tail = tem;
2088 /* This does not check for quits. That is safe since it must terminate. */
2090 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
2091 doc: /* Extract a value from a property list.
2092 PLIST is a property list, which is a list of the form
2093 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2094 corresponding to the given PROP, or nil if PROP is not one of the
2095 properties on the list. This function never signals an error. */)
2096 (Lisp_Object plist, Lisp_Object prop)
2098 Lisp_Object tail, halftail;
2100 /* halftail is used to detect circular lists. */
2101 tail = halftail = plist;
2102 while (CONSP (tail) && CONSP (XCDR (tail)))
2104 if (EQ (prop, XCAR (tail)))
2105 return XCAR (XCDR (tail));
2107 tail = XCDR (XCDR (tail));
2108 halftail = XCDR (halftail);
2109 if (EQ (tail, halftail))
2110 break;
2113 return Qnil;
2116 DEFUN ("get", Fget, Sget, 2, 2, 0,
2117 doc: /* Return the value of SYMBOL's PROPNAME property.
2118 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
2119 (Lisp_Object symbol, Lisp_Object propname)
2121 CHECK_SYMBOL (symbol);
2122 return Fplist_get (XSYMBOL (symbol)->plist, propname);
2125 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
2126 doc: /* Change value in PLIST of PROP to VAL.
2127 PLIST is a property list, which is a list of the form
2128 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
2129 If PROP is already a property on the list, its value is set to VAL,
2130 otherwise the new PROP VAL pair is added. The new plist is returned;
2131 use `(setq x (plist-put x prop val))' to be sure to use the new value.
2132 The PLIST is modified by side effects. */)
2133 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
2135 register Lisp_Object tail, prev;
2136 Lisp_Object newcell;
2137 prev = Qnil;
2138 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2139 tail = XCDR (XCDR (tail)))
2141 if (EQ (prop, XCAR (tail)))
2143 Fsetcar (XCDR (tail), val);
2144 return plist;
2147 prev = tail;
2148 QUIT;
2150 newcell = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
2151 if (NILP (prev))
2152 return newcell;
2153 else
2154 Fsetcdr (XCDR (prev), newcell);
2155 return plist;
2158 DEFUN ("put", Fput, Sput, 3, 3, 0,
2159 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
2160 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
2161 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
2163 CHECK_SYMBOL (symbol);
2164 set_symbol_plist
2165 (symbol, Fplist_put (XSYMBOL (symbol)->plist, propname, value));
2166 return value;
2169 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
2170 doc: /* Extract a value from a property list, comparing with `equal'.
2171 PLIST is a property list, which is a list of the form
2172 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2173 corresponding to the given PROP, or nil if PROP is not
2174 one of the properties on the list. */)
2175 (Lisp_Object plist, Lisp_Object prop)
2177 Lisp_Object tail;
2179 for (tail = plist;
2180 CONSP (tail) && CONSP (XCDR (tail));
2181 tail = XCDR (XCDR (tail)))
2183 if (! NILP (Fequal (prop, XCAR (tail))))
2184 return XCAR (XCDR (tail));
2186 QUIT;
2189 CHECK_LIST_END (tail, prop);
2191 return Qnil;
2194 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
2195 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
2196 PLIST is a property list, which is a list of the form
2197 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
2198 If PROP is already a property on the list, its value is set to VAL,
2199 otherwise the new PROP VAL pair is added. The new plist is returned;
2200 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
2201 The PLIST is modified by side effects. */)
2202 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
2204 register Lisp_Object tail, prev;
2205 Lisp_Object newcell;
2206 prev = Qnil;
2207 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2208 tail = XCDR (XCDR (tail)))
2210 if (! NILP (Fequal (prop, XCAR (tail))))
2212 Fsetcar (XCDR (tail), val);
2213 return plist;
2216 prev = tail;
2217 QUIT;
2219 newcell = list2 (prop, val);
2220 if (NILP (prev))
2221 return newcell;
2222 else
2223 Fsetcdr (XCDR (prev), newcell);
2224 return plist;
2227 DEFUN ("eql", Feql, Seql, 2, 2, 0,
2228 doc: /* Return t if the two args are the same Lisp object.
2229 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
2230 (Lisp_Object obj1, Lisp_Object obj2)
2232 if (FLOATP (obj1))
2233 return internal_equal (obj1, obj2, 0, 0, Qnil) ? Qt : Qnil;
2234 else
2235 return EQ (obj1, obj2) ? Qt : Qnil;
2238 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
2239 doc: /* Return t if two Lisp objects have similar structure and contents.
2240 They must have the same data type.
2241 Conses are compared by comparing the cars and the cdrs.
2242 Vectors and strings are compared element by element.
2243 Numbers are compared by value, but integers cannot equal floats.
2244 (Use `=' if you want integers and floats to be able to be equal.)
2245 Symbols must match exactly. */)
2246 (register Lisp_Object o1, Lisp_Object o2)
2248 return internal_equal (o1, o2, 0, 0, Qnil) ? Qt : Qnil;
2251 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
2252 doc: /* Return t if two Lisp objects have similar structure and contents.
2253 This is like `equal' except that it compares the text properties
2254 of strings. (`equal' ignores text properties.) */)
2255 (register Lisp_Object o1, Lisp_Object o2)
2257 return internal_equal (o1, o2, 0, 1, Qnil) ? Qt : Qnil;
2260 /* DEPTH is current depth of recursion. Signal an error if it
2261 gets too deep.
2262 PROPS means compare string text properties too. */
2264 static bool
2265 internal_equal (Lisp_Object o1, Lisp_Object o2, int depth, bool props,
2266 Lisp_Object ht)
2268 if (depth > 10)
2270 if (depth > 200)
2271 error ("Stack overflow in equal");
2272 if (NILP (ht))
2273 ht = CALLN (Fmake_hash_table, QCtest, Qeq);
2274 switch (XTYPE (o1))
2276 case Lisp_Cons: case Lisp_Misc: case Lisp_Vectorlike:
2278 struct Lisp_Hash_Table *h = XHASH_TABLE (ht);
2279 EMACS_UINT hash;
2280 ptrdiff_t i = hash_lookup (h, o1, &hash);
2281 if (i >= 0)
2282 { /* `o1' was seen already. */
2283 Lisp_Object o2s = HASH_VALUE (h, i);
2284 if (!NILP (Fmemq (o2, o2s)))
2285 return 1;
2286 else
2287 set_hash_value_slot (h, i, Fcons (o2, o2s));
2289 else
2290 hash_put (h, o1, Fcons (o2, Qnil), hash);
2292 default: ;
2296 tail_recurse:
2297 QUIT;
2298 if (EQ (o1, o2))
2299 return 1;
2300 if (XTYPE (o1) != XTYPE (o2))
2301 return 0;
2303 switch (XTYPE (o1))
2305 case Lisp_Float:
2307 double d1, d2;
2309 d1 = extract_float (o1);
2310 d2 = extract_float (o2);
2311 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2312 though they are not =. */
2313 return d1 == d2 || (d1 != d1 && d2 != d2);
2316 case Lisp_Cons:
2317 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1, props, ht))
2318 return 0;
2319 o1 = XCDR (o1);
2320 o2 = XCDR (o2);
2321 /* FIXME: This inf-loops in a circular list! */
2322 goto tail_recurse;
2324 case Lisp_Misc:
2325 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2326 return 0;
2327 if (OVERLAYP (o1))
2329 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2330 depth + 1, props, ht)
2331 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2332 depth + 1, props, ht))
2333 return 0;
2334 o1 = XOVERLAY (o1)->plist;
2335 o2 = XOVERLAY (o2)->plist;
2336 goto tail_recurse;
2338 if (MARKERP (o1))
2340 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2341 && (XMARKER (o1)->buffer == 0
2342 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2344 break;
2346 case Lisp_Vectorlike:
2348 register int i;
2349 ptrdiff_t size = ASIZE (o1);
2350 /* Pseudovectors have the type encoded in the size field, so this test
2351 actually checks that the objects have the same type as well as the
2352 same size. */
2353 if (ASIZE (o2) != size)
2354 return 0;
2355 /* Boolvectors are compared much like strings. */
2356 if (BOOL_VECTOR_P (o1))
2358 EMACS_INT size = bool_vector_size (o1);
2359 if (size != bool_vector_size (o2))
2360 return 0;
2361 if (memcmp (bool_vector_data (o1), bool_vector_data (o2),
2362 bool_vector_bytes (size)))
2363 return 0;
2364 return 1;
2366 if (WINDOW_CONFIGURATIONP (o1))
2367 return compare_window_configurations (o1, o2, 0);
2369 /* Aside from them, only true vectors, char-tables, compiled
2370 functions, and fonts (font-spec, font-entity, font-object)
2371 are sensible to compare, so eliminate the others now. */
2372 if (size & PSEUDOVECTOR_FLAG)
2374 if (((size & PVEC_TYPE_MASK) >> PSEUDOVECTOR_AREA_BITS)
2375 < PVEC_COMPILED)
2376 return 0;
2377 size &= PSEUDOVECTOR_SIZE_MASK;
2379 for (i = 0; i < size; i++)
2381 Lisp_Object v1, v2;
2382 v1 = AREF (o1, i);
2383 v2 = AREF (o2, i);
2384 if (!internal_equal (v1, v2, depth + 1, props, ht))
2385 return 0;
2387 return 1;
2389 break;
2391 case Lisp_String:
2392 if (SCHARS (o1) != SCHARS (o2))
2393 return 0;
2394 if (SBYTES (o1) != SBYTES (o2))
2395 return 0;
2396 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2397 return 0;
2398 if (props && !compare_string_intervals (o1, o2))
2399 return 0;
2400 return 1;
2402 default:
2403 break;
2406 return 0;
2410 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2411 doc: /* Store each element of ARRAY with ITEM.
2412 ARRAY is a vector, string, char-table, or bool-vector. */)
2413 (Lisp_Object array, Lisp_Object item)
2415 register ptrdiff_t size, idx;
2417 if (VECTORP (array))
2418 for (idx = 0, size = ASIZE (array); idx < size; idx++)
2419 ASET (array, idx, item);
2420 else if (CHAR_TABLE_P (array))
2422 int i;
2424 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2425 set_char_table_contents (array, i, item);
2426 set_char_table_defalt (array, item);
2428 else if (STRINGP (array))
2430 register unsigned char *p = SDATA (array);
2431 int charval;
2432 CHECK_CHARACTER (item);
2433 charval = XFASTINT (item);
2434 size = SCHARS (array);
2435 if (STRING_MULTIBYTE (array))
2437 unsigned char str[MAX_MULTIBYTE_LENGTH];
2438 int len = CHAR_STRING (charval, str);
2439 ptrdiff_t size_byte = SBYTES (array);
2440 ptrdiff_t product;
2442 if (INT_MULTIPLY_WRAPV (size, len, &product) || product != size_byte)
2443 error ("Attempt to change byte length of a string");
2444 for (idx = 0; idx < size_byte; idx++)
2445 *p++ = str[idx % len];
2447 else
2448 for (idx = 0; idx < size; idx++)
2449 p[idx] = charval;
2451 else if (BOOL_VECTOR_P (array))
2452 return bool_vector_fill (array, item);
2453 else
2454 wrong_type_argument (Qarrayp, array);
2455 return array;
2458 DEFUN ("clear-string", Fclear_string, Sclear_string,
2459 1, 1, 0,
2460 doc: /* Clear the contents of STRING.
2461 This makes STRING unibyte and may change its length. */)
2462 (Lisp_Object string)
2464 ptrdiff_t len;
2465 CHECK_STRING (string);
2466 len = SBYTES (string);
2467 memset (SDATA (string), 0, len);
2468 STRING_SET_CHARS (string, len);
2469 STRING_SET_UNIBYTE (string);
2470 return Qnil;
2473 /* ARGSUSED */
2474 Lisp_Object
2475 nconc2 (Lisp_Object s1, Lisp_Object s2)
2477 return CALLN (Fnconc, s1, s2);
2480 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2481 doc: /* Concatenate any number of lists by altering them.
2482 Only the last argument is not altered, and need not be a list.
2483 usage: (nconc &rest LISTS) */)
2484 (ptrdiff_t nargs, Lisp_Object *args)
2486 ptrdiff_t argnum;
2487 register Lisp_Object tail, tem, val;
2489 val = tail = Qnil;
2491 for (argnum = 0; argnum < nargs; argnum++)
2493 tem = args[argnum];
2494 if (NILP (tem)) continue;
2496 if (NILP (val))
2497 val = tem;
2499 if (argnum + 1 == nargs) break;
2501 CHECK_LIST_CONS (tem, tem);
2503 while (CONSP (tem))
2505 tail = tem;
2506 tem = XCDR (tail);
2507 QUIT;
2510 tem = args[argnum + 1];
2511 Fsetcdr (tail, tem);
2512 if (NILP (tem))
2513 args[argnum + 1] = tail;
2516 return val;
2519 /* This is the guts of all mapping functions.
2520 Apply FN to each element of SEQ, one by one, storing the results
2521 into elements of VALS, a C vector of Lisp_Objects. LENI is the
2522 length of VALS, which should also be the length of SEQ. Return the
2523 number of results; although this is normally LENI, it can be less
2524 if SEQ is made shorter as a side effect of FN. */
2526 static EMACS_INT
2527 mapcar1 (EMACS_INT leni, Lisp_Object *vals, Lisp_Object fn, Lisp_Object seq)
2529 Lisp_Object tail, dummy;
2530 EMACS_INT i;
2532 if (VECTORP (seq) || COMPILEDP (seq))
2534 for (i = 0; i < leni; i++)
2536 dummy = call1 (fn, AREF (seq, i));
2537 if (vals)
2538 vals[i] = dummy;
2541 else if (BOOL_VECTOR_P (seq))
2543 for (i = 0; i < leni; i++)
2545 dummy = call1 (fn, bool_vector_ref (seq, i));
2546 if (vals)
2547 vals[i] = dummy;
2550 else if (STRINGP (seq))
2552 ptrdiff_t i_byte;
2554 for (i = 0, i_byte = 0; i < leni;)
2556 int c;
2557 ptrdiff_t i_before = i;
2559 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2560 XSETFASTINT (dummy, c);
2561 dummy = call1 (fn, dummy);
2562 if (vals)
2563 vals[i_before] = dummy;
2566 else /* Must be a list, since Flength did not get an error */
2568 tail = seq;
2569 for (i = 0; i < leni; i++)
2571 if (! CONSP (tail))
2572 return i;
2573 dummy = call1 (fn, XCAR (tail));
2574 if (vals)
2575 vals[i] = dummy;
2576 tail = XCDR (tail);
2580 return leni;
2583 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2584 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2585 In between each pair of results, stick in SEPARATOR. Thus, " " as
2586 SEPARATOR results in spaces between the values returned by FUNCTION.
2587 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2588 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2590 USE_SAFE_ALLOCA;
2591 EMACS_INT leni = XFASTINT (Flength (sequence));
2592 if (CHAR_TABLE_P (sequence))
2593 wrong_type_argument (Qlistp, sequence);
2594 EMACS_INT args_alloc = 2 * leni - 1;
2595 if (args_alloc < 0)
2596 return empty_unibyte_string;
2597 Lisp_Object *args;
2598 SAFE_ALLOCA_LISP (args, args_alloc);
2599 ptrdiff_t nmapped = mapcar1 (leni, args, function, sequence);
2600 ptrdiff_t nargs = 2 * nmapped - 1;
2602 for (ptrdiff_t i = nmapped - 1; i > 0; i--)
2603 args[i + i] = args[i];
2605 for (ptrdiff_t i = 1; i < nargs; i += 2)
2606 args[i] = separator;
2608 Lisp_Object ret = Fconcat (nargs, args);
2609 SAFE_FREE ();
2610 return ret;
2613 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2614 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2615 The result is a list just as long as SEQUENCE.
2616 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2617 (Lisp_Object function, Lisp_Object sequence)
2619 USE_SAFE_ALLOCA;
2620 EMACS_INT leni = XFASTINT (Flength (sequence));
2621 if (CHAR_TABLE_P (sequence))
2622 wrong_type_argument (Qlistp, sequence);
2623 Lisp_Object *args;
2624 SAFE_ALLOCA_LISP (args, leni);
2625 ptrdiff_t nmapped = mapcar1 (leni, args, function, sequence);
2626 Lisp_Object ret = Flist (nmapped, args);
2627 SAFE_FREE ();
2628 return ret;
2631 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2632 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2633 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2634 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2635 (Lisp_Object function, Lisp_Object sequence)
2637 register EMACS_INT leni;
2639 leni = XFASTINT (Flength (sequence));
2640 if (CHAR_TABLE_P (sequence))
2641 wrong_type_argument (Qlistp, sequence);
2642 mapcar1 (leni, 0, function, sequence);
2644 return sequence;
2647 DEFUN ("mapcan", Fmapcan, Smapcan, 2, 2, 0,
2648 doc: /* Apply FUNCTION to each element of SEQUENCE, and concatenate
2649 the results by altering them (using `nconc').
2650 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2651 (Lisp_Object function, Lisp_Object sequence)
2653 USE_SAFE_ALLOCA;
2654 EMACS_INT leni = XFASTINT (Flength (sequence));
2655 if (CHAR_TABLE_P (sequence))
2656 wrong_type_argument (Qlistp, sequence);
2657 Lisp_Object *args;
2658 SAFE_ALLOCA_LISP (args, leni);
2659 ptrdiff_t nmapped = mapcar1 (leni, args, function, sequence);
2660 Lisp_Object ret = Fnconc (nmapped, args);
2661 SAFE_FREE ();
2662 return ret;
2665 /* This is how C code calls `yes-or-no-p' and allows the user
2666 to redefine it. */
2668 Lisp_Object
2669 do_yes_or_no_p (Lisp_Object prompt)
2671 return call1 (intern ("yes-or-no-p"), prompt);
2674 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2675 doc: /* Ask user a yes-or-no question.
2676 Return t if answer is yes, and nil if the answer is no.
2677 PROMPT is the string to display to ask the question. It should end in
2678 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2680 The user must confirm the answer with RET, and can edit it until it
2681 has been confirmed.
2683 If dialog boxes are supported, a dialog box will be used
2684 if `last-nonmenu-event' is nil, and `use-dialog-box' is non-nil. */)
2685 (Lisp_Object prompt)
2687 Lisp_Object ans;
2689 CHECK_STRING (prompt);
2691 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2692 && use_dialog_box && ! NILP (last_input_event))
2694 Lisp_Object pane, menu, obj;
2695 redisplay_preserve_echo_area (4);
2696 pane = list2 (Fcons (build_string ("Yes"), Qt),
2697 Fcons (build_string ("No"), Qnil));
2698 menu = Fcons (prompt, pane);
2699 obj = Fx_popup_dialog (Qt, menu, Qnil);
2700 return obj;
2703 AUTO_STRING (yes_or_no, "(yes or no) ");
2704 prompt = CALLN (Fconcat, prompt, yes_or_no);
2706 while (1)
2708 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2709 Qyes_or_no_p_history, Qnil,
2710 Qnil));
2711 if (SCHARS (ans) == 3 && !strcmp (SSDATA (ans), "yes"))
2712 return Qt;
2713 if (SCHARS (ans) == 2 && !strcmp (SSDATA (ans), "no"))
2714 return Qnil;
2716 Fding (Qnil);
2717 Fdiscard_input ();
2718 message1 ("Please answer yes or no.");
2719 Fsleep_for (make_number (2), Qnil);
2723 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2724 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2726 Each of the three load averages is multiplied by 100, then converted
2727 to integer.
2729 When USE-FLOATS is non-nil, floats will be used instead of integers.
2730 These floats are not multiplied by 100.
2732 If the 5-minute or 15-minute load averages are not available, return a
2733 shortened list, containing only those averages which are available.
2735 An error is thrown if the load average can't be obtained. In some
2736 cases making it work would require Emacs being installed setuid or
2737 setgid so that it can read kernel information, and that usually isn't
2738 advisable. */)
2739 (Lisp_Object use_floats)
2741 double load_ave[3];
2742 int loads = getloadavg (load_ave, 3);
2743 Lisp_Object ret = Qnil;
2745 if (loads < 0)
2746 error ("load-average not implemented for this operating system");
2748 while (loads-- > 0)
2750 Lisp_Object load = (NILP (use_floats)
2751 ? make_number (100.0 * load_ave[loads])
2752 : make_float (load_ave[loads]));
2753 ret = Fcons (load, ret);
2756 return ret;
2759 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2760 doc: /* Return t if FEATURE is present in this Emacs.
2762 Use this to conditionalize execution of lisp code based on the
2763 presence or absence of Emacs or environment extensions.
2764 Use `provide' to declare that a feature is available. This function
2765 looks at the value of the variable `features'. The optional argument
2766 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2767 (Lisp_Object feature, Lisp_Object subfeature)
2769 register Lisp_Object tem;
2770 CHECK_SYMBOL (feature);
2771 tem = Fmemq (feature, Vfeatures);
2772 if (!NILP (tem) && !NILP (subfeature))
2773 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2774 return (NILP (tem)) ? Qnil : Qt;
2777 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2778 doc: /* Announce that FEATURE is a feature of the current Emacs.
2779 The optional argument SUBFEATURES should be a list of symbols listing
2780 particular subfeatures supported in this version of FEATURE. */)
2781 (Lisp_Object feature, Lisp_Object subfeatures)
2783 register Lisp_Object tem;
2784 CHECK_SYMBOL (feature);
2785 CHECK_LIST (subfeatures);
2786 if (!NILP (Vautoload_queue))
2787 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2788 Vautoload_queue);
2789 tem = Fmemq (feature, Vfeatures);
2790 if (NILP (tem))
2791 Vfeatures = Fcons (feature, Vfeatures);
2792 if (!NILP (subfeatures))
2793 Fput (feature, Qsubfeatures, subfeatures);
2794 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2796 /* Run any load-hooks for this file. */
2797 tem = Fassq (feature, Vafter_load_alist);
2798 if (CONSP (tem))
2799 Fmapc (Qfuncall, XCDR (tem));
2801 return feature;
2804 /* `require' and its subroutines. */
2806 /* List of features currently being require'd, innermost first. */
2808 static Lisp_Object require_nesting_list;
2810 static void
2811 require_unwind (Lisp_Object old_value)
2813 require_nesting_list = old_value;
2816 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2817 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2818 If FEATURE is not a member of the list `features', then the feature is
2819 not loaded; so load the file FILENAME.
2821 If FILENAME is omitted, the printname of FEATURE is used as the file
2822 name, and `load' will try to load this name appended with the suffix
2823 `.elc', `.el', or the system-dependent suffix for dynamic module
2824 files, in that order. The name without appended suffix will not be
2825 used. See `get-load-suffixes' for the complete list of suffixes.
2827 The directories in `load-path' are searched when trying to find the
2828 file name.
2830 If the optional third argument NOERROR is non-nil, then return nil if
2831 the file is not found instead of signaling an error. Normally the
2832 return value is FEATURE.
2834 The normal messages at start and end of loading FILENAME are
2835 suppressed. */)
2836 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2838 Lisp_Object tem;
2839 bool from_file = load_in_progress;
2841 CHECK_SYMBOL (feature);
2843 /* Record the presence of `require' in this file
2844 even if the feature specified is already loaded.
2845 But not more than once in any file,
2846 and not when we aren't loading or reading from a file. */
2847 if (!from_file)
2848 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2849 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2850 from_file = 1;
2852 if (from_file)
2854 tem = Fcons (Qrequire, feature);
2855 if (NILP (Fmember (tem, Vcurrent_load_list)))
2856 LOADHIST_ATTACH (tem);
2858 tem = Fmemq (feature, Vfeatures);
2860 if (NILP (tem))
2862 ptrdiff_t count = SPECPDL_INDEX ();
2863 int nesting = 0;
2865 /* This is to make sure that loadup.el gives a clear picture
2866 of what files are preloaded and when. */
2867 if (! NILP (Vpurify_flag))
2868 error ("(require %s) while preparing to dump",
2869 SDATA (SYMBOL_NAME (feature)));
2871 /* A certain amount of recursive `require' is legitimate,
2872 but if we require the same feature recursively 3 times,
2873 signal an error. */
2874 tem = require_nesting_list;
2875 while (! NILP (tem))
2877 if (! NILP (Fequal (feature, XCAR (tem))))
2878 nesting++;
2879 tem = XCDR (tem);
2881 if (nesting > 3)
2882 error ("Recursive `require' for feature `%s'",
2883 SDATA (SYMBOL_NAME (feature)));
2885 /* Update the list for any nested `require's that occur. */
2886 record_unwind_protect (require_unwind, require_nesting_list);
2887 require_nesting_list = Fcons (feature, require_nesting_list);
2889 /* Value saved here is to be restored into Vautoload_queue */
2890 record_unwind_protect (un_autoload, Vautoload_queue);
2891 Vautoload_queue = Qt;
2893 /* Load the file. */
2894 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2895 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2897 /* If load failed entirely, return nil. */
2898 if (NILP (tem))
2899 return unbind_to (count, Qnil);
2901 tem = Fmemq (feature, Vfeatures);
2902 if (NILP (tem))
2903 error ("Required feature `%s' was not provided",
2904 SDATA (SYMBOL_NAME (feature)));
2906 /* Once loading finishes, don't undo it. */
2907 Vautoload_queue = Qt;
2908 feature = unbind_to (count, feature);
2911 return feature;
2914 /* Primitives for work of the "widget" library.
2915 In an ideal world, this section would not have been necessary.
2916 However, lisp function calls being as slow as they are, it turns
2917 out that some functions in the widget library (wid-edit.el) are the
2918 bottleneck of Widget operation. Here is their translation to C,
2919 for the sole reason of efficiency. */
2921 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2922 doc: /* Return non-nil if PLIST has the property PROP.
2923 PLIST is a property list, which is a list of the form
2924 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol.
2925 Unlike `plist-get', this allows you to distinguish between a missing
2926 property and a property with the value nil.
2927 The value is actually the tail of PLIST whose car is PROP. */)
2928 (Lisp_Object plist, Lisp_Object prop)
2930 while (CONSP (plist) && !EQ (XCAR (plist), prop))
2932 plist = XCDR (plist);
2933 plist = CDR (plist);
2934 QUIT;
2936 return plist;
2939 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2940 doc: /* In WIDGET, set PROPERTY to VALUE.
2941 The value can later be retrieved with `widget-get'. */)
2942 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2944 CHECK_CONS (widget);
2945 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
2946 return value;
2949 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
2950 doc: /* In WIDGET, get the value of PROPERTY.
2951 The value could either be specified when the widget was created, or
2952 later with `widget-put'. */)
2953 (Lisp_Object widget, Lisp_Object property)
2955 Lisp_Object tmp;
2957 while (1)
2959 if (NILP (widget))
2960 return Qnil;
2961 CHECK_CONS (widget);
2962 tmp = Fplist_member (XCDR (widget), property);
2963 if (CONSP (tmp))
2965 tmp = XCDR (tmp);
2966 return CAR (tmp);
2968 tmp = XCAR (widget);
2969 if (NILP (tmp))
2970 return Qnil;
2971 widget = Fget (tmp, Qwidget_type);
2975 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
2976 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2977 ARGS are passed as extra arguments to the function.
2978 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2979 (ptrdiff_t nargs, Lisp_Object *args)
2981 Lisp_Object widget = args[0];
2982 Lisp_Object property = args[1];
2983 Lisp_Object propval = Fwidget_get (widget, property);
2984 Lisp_Object trailing_args = Flist (nargs - 2, args + 2);
2985 Lisp_Object result = CALLN (Fapply, propval, widget, trailing_args);
2986 return result;
2989 #ifdef HAVE_LANGINFO_CODESET
2990 #include <langinfo.h>
2991 #endif
2993 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
2994 doc: /* Access locale data ITEM for the current C locale, if available.
2995 ITEM should be one of the following:
2997 `codeset', returning the character set as a string (locale item CODESET);
2999 `days', returning a 7-element vector of day names (locale items DAY_n);
3001 `months', returning a 12-element vector of month names (locale items MON_n);
3003 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
3004 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
3006 If the system can't provide such information through a call to
3007 `nl_langinfo', or if ITEM isn't from the list above, return nil.
3009 See also Info node `(libc)Locales'.
3011 The data read from the system are decoded using `locale-coding-system'. */)
3012 (Lisp_Object item)
3014 char *str = NULL;
3015 #ifdef HAVE_LANGINFO_CODESET
3016 if (EQ (item, Qcodeset))
3018 str = nl_langinfo (CODESET);
3019 return build_string (str);
3021 #ifdef DAY_1
3022 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
3024 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
3025 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
3026 int i;
3027 synchronize_system_time_locale ();
3028 for (i = 0; i < 7; i++)
3030 str = nl_langinfo (days[i]);
3031 AUTO_STRING (val, str);
3032 /* Fixme: Is this coding system necessarily right, even if
3033 it is consistent with CODESET? If not, what to do? */
3034 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
3035 0));
3037 return v;
3039 #endif /* DAY_1 */
3040 #ifdef MON_1
3041 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
3043 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
3044 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
3045 MON_8, MON_9, MON_10, MON_11, MON_12};
3046 int i;
3047 synchronize_system_time_locale ();
3048 for (i = 0; i < 12; i++)
3050 str = nl_langinfo (months[i]);
3051 AUTO_STRING (val, str);
3052 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
3053 0));
3055 return v;
3057 #endif /* MON_1 */
3058 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
3059 but is in the locale files. This could be used by ps-print. */
3060 #ifdef PAPER_WIDTH
3061 else if (EQ (item, Qpaper))
3062 return list2i (nl_langinfo (PAPER_WIDTH), nl_langinfo (PAPER_HEIGHT));
3063 #endif /* PAPER_WIDTH */
3064 #endif /* HAVE_LANGINFO_CODESET*/
3065 return Qnil;
3068 /* base64 encode/decode functions (RFC 2045).
3069 Based on code from GNU recode. */
3071 #define MIME_LINE_LENGTH 76
3073 #define IS_ASCII(Character) \
3074 ((Character) < 128)
3075 #define IS_BASE64(Character) \
3076 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
3077 #define IS_BASE64_IGNORABLE(Character) \
3078 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
3079 || (Character) == '\f' || (Character) == '\r')
3081 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
3082 character or return retval if there are no characters left to
3083 process. */
3084 #define READ_QUADRUPLET_BYTE(retval) \
3085 do \
3087 if (i == length) \
3089 if (nchars_return) \
3090 *nchars_return = nchars; \
3091 return (retval); \
3093 c = from[i++]; \
3095 while (IS_BASE64_IGNORABLE (c))
3097 /* Table of characters coding the 64 values. */
3098 static const char base64_value_to_char[64] =
3100 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
3101 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
3102 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
3103 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
3104 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
3105 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
3106 '8', '9', '+', '/' /* 60-63 */
3109 /* Table of base64 values for first 128 characters. */
3110 static const short base64_char_to_value[128] =
3112 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
3113 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
3114 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
3115 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
3116 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
3117 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
3118 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
3119 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
3120 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
3121 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
3122 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
3123 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
3124 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
3127 /* The following diagram shows the logical steps by which three octets
3128 get transformed into four base64 characters.
3130 .--------. .--------. .--------.
3131 |aaaaaabb| |bbbbcccc| |ccdddddd|
3132 `--------' `--------' `--------'
3133 6 2 4 4 2 6
3134 .--------+--------+--------+--------.
3135 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
3136 `--------+--------+--------+--------'
3138 .--------+--------+--------+--------.
3139 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
3140 `--------+--------+--------+--------'
3142 The octets are divided into 6 bit chunks, which are then encoded into
3143 base64 characters. */
3146 static ptrdiff_t base64_encode_1 (const char *, char *, ptrdiff_t, bool, bool);
3147 static ptrdiff_t base64_decode_1 (const char *, char *, ptrdiff_t, bool,
3148 ptrdiff_t *);
3150 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
3151 2, 3, "r",
3152 doc: /* Base64-encode the region between BEG and END.
3153 Return the length of the encoded text.
3154 Optional third argument NO-LINE-BREAK means do not break long lines
3155 into shorter lines. */)
3156 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
3158 char *encoded;
3159 ptrdiff_t allength, length;
3160 ptrdiff_t ibeg, iend, encoded_length;
3161 ptrdiff_t old_pos = PT;
3162 USE_SAFE_ALLOCA;
3164 validate_region (&beg, &end);
3166 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3167 iend = CHAR_TO_BYTE (XFASTINT (end));
3168 move_gap_both (XFASTINT (beg), ibeg);
3170 /* We need to allocate enough room for encoding the text.
3171 We need 33 1/3% more space, plus a newline every 76
3172 characters, and then we round up. */
3173 length = iend - ibeg;
3174 allength = length + length/3 + 1;
3175 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3177 encoded = SAFE_ALLOCA (allength);
3178 encoded_length = base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg),
3179 encoded, length, NILP (no_line_break),
3180 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
3181 if (encoded_length > allength)
3182 emacs_abort ();
3184 if (encoded_length < 0)
3186 /* The encoding wasn't possible. */
3187 SAFE_FREE ();
3188 error ("Multibyte character in data for base64 encoding");
3191 /* Now we have encoded the region, so we insert the new contents
3192 and delete the old. (Insert first in order to preserve markers.) */
3193 SET_PT_BOTH (XFASTINT (beg), ibeg);
3194 insert (encoded, encoded_length);
3195 SAFE_FREE ();
3196 del_range_byte (ibeg + encoded_length, iend + encoded_length);
3198 /* If point was outside of the region, restore it exactly; else just
3199 move to the beginning of the region. */
3200 if (old_pos >= XFASTINT (end))
3201 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
3202 else if (old_pos > XFASTINT (beg))
3203 old_pos = XFASTINT (beg);
3204 SET_PT (old_pos);
3206 /* We return the length of the encoded text. */
3207 return make_number (encoded_length);
3210 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
3211 1, 2, 0,
3212 doc: /* Base64-encode STRING and return the result.
3213 Optional second argument NO-LINE-BREAK means do not break long lines
3214 into shorter lines. */)
3215 (Lisp_Object string, Lisp_Object no_line_break)
3217 ptrdiff_t allength, length, encoded_length;
3218 char *encoded;
3219 Lisp_Object encoded_string;
3220 USE_SAFE_ALLOCA;
3222 CHECK_STRING (string);
3224 /* We need to allocate enough room for encoding the text.
3225 We need 33 1/3% more space, plus a newline every 76
3226 characters, and then we round up. */
3227 length = SBYTES (string);
3228 allength = length + length/3 + 1;
3229 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3231 /* We need to allocate enough room for decoding the text. */
3232 encoded = SAFE_ALLOCA (allength);
3234 encoded_length = base64_encode_1 (SSDATA (string),
3235 encoded, length, NILP (no_line_break),
3236 STRING_MULTIBYTE (string));
3237 if (encoded_length > allength)
3238 emacs_abort ();
3240 if (encoded_length < 0)
3242 /* The encoding wasn't possible. */
3243 error ("Multibyte character in data for base64 encoding");
3246 encoded_string = make_unibyte_string (encoded, encoded_length);
3247 SAFE_FREE ();
3249 return encoded_string;
3252 static ptrdiff_t
3253 base64_encode_1 (const char *from, char *to, ptrdiff_t length,
3254 bool line_break, bool multibyte)
3256 int counter = 0;
3257 ptrdiff_t i = 0;
3258 char *e = to;
3259 int c;
3260 unsigned int value;
3261 int bytes;
3263 while (i < length)
3265 if (multibyte)
3267 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3268 if (CHAR_BYTE8_P (c))
3269 c = CHAR_TO_BYTE8 (c);
3270 else if (c >= 256)
3271 return -1;
3272 i += bytes;
3274 else
3275 c = from[i++];
3277 /* Wrap line every 76 characters. */
3279 if (line_break)
3281 if (counter < MIME_LINE_LENGTH / 4)
3282 counter++;
3283 else
3285 *e++ = '\n';
3286 counter = 1;
3290 /* Process first byte of a triplet. */
3292 *e++ = base64_value_to_char[0x3f & c >> 2];
3293 value = (0x03 & c) << 4;
3295 /* Process second byte of a triplet. */
3297 if (i == length)
3299 *e++ = base64_value_to_char[value];
3300 *e++ = '=';
3301 *e++ = '=';
3302 break;
3305 if (multibyte)
3307 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3308 if (CHAR_BYTE8_P (c))
3309 c = CHAR_TO_BYTE8 (c);
3310 else if (c >= 256)
3311 return -1;
3312 i += bytes;
3314 else
3315 c = from[i++];
3317 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3318 value = (0x0f & c) << 2;
3320 /* Process third byte of a triplet. */
3322 if (i == length)
3324 *e++ = base64_value_to_char[value];
3325 *e++ = '=';
3326 break;
3329 if (multibyte)
3331 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3332 if (CHAR_BYTE8_P (c))
3333 c = CHAR_TO_BYTE8 (c);
3334 else if (c >= 256)
3335 return -1;
3336 i += bytes;
3338 else
3339 c = from[i++];
3341 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3342 *e++ = base64_value_to_char[0x3f & c];
3345 return e - to;
3349 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3350 2, 2, "r",
3351 doc: /* Base64-decode the region between BEG and END.
3352 Return the length of the decoded text.
3353 If the region can't be decoded, signal an error and don't modify the buffer. */)
3354 (Lisp_Object beg, Lisp_Object end)
3356 ptrdiff_t ibeg, iend, length, allength;
3357 char *decoded;
3358 ptrdiff_t old_pos = PT;
3359 ptrdiff_t decoded_length;
3360 ptrdiff_t inserted_chars;
3361 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3362 USE_SAFE_ALLOCA;
3364 validate_region (&beg, &end);
3366 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3367 iend = CHAR_TO_BYTE (XFASTINT (end));
3369 length = iend - ibeg;
3371 /* We need to allocate enough room for decoding the text. If we are
3372 working on a multibyte buffer, each decoded code may occupy at
3373 most two bytes. */
3374 allength = multibyte ? length * 2 : length;
3375 decoded = SAFE_ALLOCA (allength);
3377 move_gap_both (XFASTINT (beg), ibeg);
3378 decoded_length = base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg),
3379 decoded, length,
3380 multibyte, &inserted_chars);
3381 if (decoded_length > allength)
3382 emacs_abort ();
3384 if (decoded_length < 0)
3386 /* The decoding wasn't possible. */
3387 error ("Invalid base64 data");
3390 /* Now we have decoded the region, so we insert the new contents
3391 and delete the old. (Insert first in order to preserve markers.) */
3392 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3393 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3394 SAFE_FREE ();
3396 /* Delete the original text. */
3397 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3398 iend + decoded_length, 1);
3400 /* If point was outside of the region, restore it exactly; else just
3401 move to the beginning of the region. */
3402 if (old_pos >= XFASTINT (end))
3403 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3404 else if (old_pos > XFASTINT (beg))
3405 old_pos = XFASTINT (beg);
3406 SET_PT (old_pos > ZV ? ZV : old_pos);
3408 return make_number (inserted_chars);
3411 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3412 1, 1, 0,
3413 doc: /* Base64-decode STRING and return the result. */)
3414 (Lisp_Object string)
3416 char *decoded;
3417 ptrdiff_t length, decoded_length;
3418 Lisp_Object decoded_string;
3419 USE_SAFE_ALLOCA;
3421 CHECK_STRING (string);
3423 length = SBYTES (string);
3424 /* We need to allocate enough room for decoding the text. */
3425 decoded = SAFE_ALLOCA (length);
3427 /* The decoded result should be unibyte. */
3428 decoded_length = base64_decode_1 (SSDATA (string), decoded, length,
3429 0, NULL);
3430 if (decoded_length > length)
3431 emacs_abort ();
3432 else if (decoded_length >= 0)
3433 decoded_string = make_unibyte_string (decoded, decoded_length);
3434 else
3435 decoded_string = Qnil;
3437 SAFE_FREE ();
3438 if (!STRINGP (decoded_string))
3439 error ("Invalid base64 data");
3441 return decoded_string;
3444 /* Base64-decode the data at FROM of LENGTH bytes into TO. If
3445 MULTIBYTE, the decoded result should be in multibyte
3446 form. If NCHARS_RETURN is not NULL, store the number of produced
3447 characters in *NCHARS_RETURN. */
3449 static ptrdiff_t
3450 base64_decode_1 (const char *from, char *to, ptrdiff_t length,
3451 bool multibyte, ptrdiff_t *nchars_return)
3453 ptrdiff_t i = 0; /* Used inside READ_QUADRUPLET_BYTE */
3454 char *e = to;
3455 unsigned char c;
3456 unsigned long value;
3457 ptrdiff_t nchars = 0;
3459 while (1)
3461 /* Process first byte of a quadruplet. */
3463 READ_QUADRUPLET_BYTE (e-to);
3465 if (!IS_BASE64 (c))
3466 return -1;
3467 value = base64_char_to_value[c] << 18;
3469 /* Process second byte of a quadruplet. */
3471 READ_QUADRUPLET_BYTE (-1);
3473 if (!IS_BASE64 (c))
3474 return -1;
3475 value |= base64_char_to_value[c] << 12;
3477 c = (unsigned char) (value >> 16);
3478 if (multibyte && c >= 128)
3479 e += BYTE8_STRING (c, e);
3480 else
3481 *e++ = c;
3482 nchars++;
3484 /* Process third byte of a quadruplet. */
3486 READ_QUADRUPLET_BYTE (-1);
3488 if (c == '=')
3490 READ_QUADRUPLET_BYTE (-1);
3492 if (c != '=')
3493 return -1;
3494 continue;
3497 if (!IS_BASE64 (c))
3498 return -1;
3499 value |= base64_char_to_value[c] << 6;
3501 c = (unsigned char) (0xff & value >> 8);
3502 if (multibyte && c >= 128)
3503 e += BYTE8_STRING (c, e);
3504 else
3505 *e++ = c;
3506 nchars++;
3508 /* Process fourth byte of a quadruplet. */
3510 READ_QUADRUPLET_BYTE (-1);
3512 if (c == '=')
3513 continue;
3515 if (!IS_BASE64 (c))
3516 return -1;
3517 value |= base64_char_to_value[c];
3519 c = (unsigned char) (0xff & value);
3520 if (multibyte && c >= 128)
3521 e += BYTE8_STRING (c, e);
3522 else
3523 *e++ = c;
3524 nchars++;
3530 /***********************************************************************
3531 ***** *****
3532 ***** Hash Tables *****
3533 ***** *****
3534 ***********************************************************************/
3536 /* Implemented by gerd@gnu.org. This hash table implementation was
3537 inspired by CMUCL hash tables. */
3539 /* Ideas:
3541 1. For small tables, association lists are probably faster than
3542 hash tables because they have lower overhead.
3544 For uses of hash tables where the O(1) behavior of table
3545 operations is not a requirement, it might therefore be a good idea
3546 not to hash. Instead, we could just do a linear search in the
3547 key_and_value vector of the hash table. This could be done
3548 if a `:linear-search t' argument is given to make-hash-table. */
3551 /* The list of all weak hash tables. Don't staticpro this one. */
3553 static struct Lisp_Hash_Table *weak_hash_tables;
3556 /***********************************************************************
3557 Utilities
3558 ***********************************************************************/
3560 static void
3561 CHECK_HASH_TABLE (Lisp_Object x)
3563 CHECK_TYPE (HASH_TABLE_P (x), Qhash_table_p, x);
3566 static void
3567 set_hash_key_and_value (struct Lisp_Hash_Table *h, Lisp_Object key_and_value)
3569 h->key_and_value = key_and_value;
3571 static void
3572 set_hash_next (struct Lisp_Hash_Table *h, Lisp_Object next)
3574 h->next = next;
3576 static void
3577 set_hash_next_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3579 gc_aset (h->next, idx, val);
3581 static void
3582 set_hash_hash (struct Lisp_Hash_Table *h, Lisp_Object hash)
3584 h->hash = hash;
3586 static void
3587 set_hash_hash_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3589 gc_aset (h->hash, idx, val);
3591 static void
3592 set_hash_index (struct Lisp_Hash_Table *h, Lisp_Object index)
3594 h->index = index;
3596 static void
3597 set_hash_index_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3599 gc_aset (h->index, idx, val);
3602 /* If OBJ is a Lisp hash table, return a pointer to its struct
3603 Lisp_Hash_Table. Otherwise, signal an error. */
3605 static struct Lisp_Hash_Table *
3606 check_hash_table (Lisp_Object obj)
3608 CHECK_HASH_TABLE (obj);
3609 return XHASH_TABLE (obj);
3613 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3614 number. A number is "almost" a prime number if it is not divisible
3615 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3617 EMACS_INT
3618 next_almost_prime (EMACS_INT n)
3620 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
3621 for (n |= 1; ; n += 2)
3622 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0)
3623 return n;
3627 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3628 which USED[I] is non-zero. If found at index I in ARGS, set
3629 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3630 0. This function is used to extract a keyword/argument pair from
3631 a DEFUN parameter list. */
3633 static ptrdiff_t
3634 get_key_arg (Lisp_Object key, ptrdiff_t nargs, Lisp_Object *args, char *used)
3636 ptrdiff_t i;
3638 for (i = 1; i < nargs; i++)
3639 if (!used[i - 1] && EQ (args[i - 1], key))
3641 used[i - 1] = 1;
3642 used[i] = 1;
3643 return i;
3646 return 0;
3650 /* Return a Lisp vector which has the same contents as VEC but has
3651 at least INCR_MIN more entries, where INCR_MIN is positive.
3652 If NITEMS_MAX is not -1, do not grow the vector to be any larger
3653 than NITEMS_MAX. Entries in the resulting
3654 vector that are not copied from VEC are set to nil. */
3656 Lisp_Object
3657 larger_vector (Lisp_Object vec, ptrdiff_t incr_min, ptrdiff_t nitems_max)
3659 struct Lisp_Vector *v;
3660 ptrdiff_t incr, incr_max, old_size, new_size;
3661 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / sizeof *v->contents;
3662 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
3663 ? nitems_max : C_language_max);
3664 eassert (VECTORP (vec));
3665 eassert (0 < incr_min && -1 <= nitems_max);
3666 old_size = ASIZE (vec);
3667 incr_max = n_max - old_size;
3668 incr = max (incr_min, min (old_size >> 1, incr_max));
3669 if (incr_max < incr)
3670 memory_full (SIZE_MAX);
3671 new_size = old_size + incr;
3672 v = allocate_vector (new_size);
3673 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3674 memclear (v->contents + old_size, incr * word_size);
3675 XSETVECTOR (vec, v);
3676 return vec;
3680 /***********************************************************************
3681 Low-level Functions
3682 ***********************************************************************/
3684 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3685 HASH2 in hash table H using `eql'. Value is true if KEY1 and
3686 KEY2 are the same. */
3688 static bool
3689 cmpfn_eql (struct hash_table_test *ht,
3690 Lisp_Object key1,
3691 Lisp_Object key2)
3693 return (FLOATP (key1)
3694 && FLOATP (key2)
3695 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3699 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3700 HASH2 in hash table H using `equal'. Value is true if KEY1 and
3701 KEY2 are the same. */
3703 static bool
3704 cmpfn_equal (struct hash_table_test *ht,
3705 Lisp_Object key1,
3706 Lisp_Object key2)
3708 return !NILP (Fequal (key1, key2));
3712 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3713 HASH2 in hash table H using H->user_cmp_function. Value is true
3714 if KEY1 and KEY2 are the same. */
3716 static bool
3717 cmpfn_user_defined (struct hash_table_test *ht,
3718 Lisp_Object key1,
3719 Lisp_Object key2)
3721 return !NILP (call2 (ht->user_cmp_function, key1, key2));
3724 /* Value is a hash code for KEY for use in hash table H which uses
3725 `eq' to compare keys. The hash code returned is guaranteed to fit
3726 in a Lisp integer. */
3728 static EMACS_UINT
3729 hashfn_eq (struct hash_table_test *ht, Lisp_Object key)
3731 return XHASH (key) ^ XTYPE (key);
3734 /* Value is a hash code for KEY for use in hash table H which uses
3735 `equal' to compare keys. The hash code returned is guaranteed to fit
3736 in a Lisp integer. */
3738 static EMACS_UINT
3739 hashfn_equal (struct hash_table_test *ht, Lisp_Object key)
3741 return sxhash (key, 0);
3744 /* Value is a hash code for KEY for use in hash table H which uses
3745 `eql' to compare keys. The hash code returned is guaranteed to fit
3746 in a Lisp integer. */
3748 static EMACS_UINT
3749 hashfn_eql (struct hash_table_test *ht, Lisp_Object key)
3751 return FLOATP (key) ? hashfn_equal (ht, key) : hashfn_eq (ht, key);
3754 /* Value is a hash code for KEY for use in hash table H which uses as
3755 user-defined function to compare keys. The hash code returned is
3756 guaranteed to fit in a Lisp integer. */
3758 static EMACS_UINT
3759 hashfn_user_defined (struct hash_table_test *ht, Lisp_Object key)
3761 Lisp_Object hash = call1 (ht->user_hash_function, key);
3762 return hashfn_eq (ht, hash);
3765 struct hash_table_test const
3766 hashtest_eq = { LISPSYM_INITIALLY (Qeq), LISPSYM_INITIALLY (Qnil),
3767 LISPSYM_INITIALLY (Qnil), 0, hashfn_eq },
3768 hashtest_eql = { LISPSYM_INITIALLY (Qeql), LISPSYM_INITIALLY (Qnil),
3769 LISPSYM_INITIALLY (Qnil), cmpfn_eql, hashfn_eql },
3770 hashtest_equal = { LISPSYM_INITIALLY (Qequal), LISPSYM_INITIALLY (Qnil),
3771 LISPSYM_INITIALLY (Qnil), cmpfn_equal, hashfn_equal };
3773 /* Allocate basically initialized hash table. */
3775 static struct Lisp_Hash_Table *
3776 allocate_hash_table (void)
3778 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table,
3779 count, PVEC_HASH_TABLE);
3782 /* An upper bound on the size of a hash table index. It must fit in
3783 ptrdiff_t and be a valid Emacs fixnum. */
3784 #define INDEX_SIZE_BOUND \
3785 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, PTRDIFF_MAX / word_size))
3787 /* Create and initialize a new hash table.
3789 TEST specifies the test the hash table will use to compare keys.
3790 It must be either one of the predefined tests `eq', `eql' or
3791 `equal' or a symbol denoting a user-defined test named TEST with
3792 test and hash functions USER_TEST and USER_HASH.
3794 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3796 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3797 new size when it becomes full is computed by adding REHASH_SIZE to
3798 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3799 table's new size is computed by multiplying its old size with
3800 REHASH_SIZE.
3802 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3803 be resized when the ratio of (number of entries in the table) /
3804 (table size) is >= REHASH_THRESHOLD.
3806 WEAK specifies the weakness of the table. If non-nil, it must be
3807 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
3809 Lisp_Object
3810 make_hash_table (struct hash_table_test test,
3811 Lisp_Object size, Lisp_Object rehash_size,
3812 Lisp_Object rehash_threshold, Lisp_Object weak)
3814 struct Lisp_Hash_Table *h;
3815 Lisp_Object table;
3816 EMACS_INT index_size, sz;
3817 ptrdiff_t i;
3818 double index_float;
3820 /* Preconditions. */
3821 eassert (SYMBOLP (test.name));
3822 eassert (INTEGERP (size) && XINT (size) >= 0);
3823 eassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3824 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size)));
3825 eassert (FLOATP (rehash_threshold)
3826 && 0 < XFLOAT_DATA (rehash_threshold)
3827 && XFLOAT_DATA (rehash_threshold) <= 1.0);
3829 if (XFASTINT (size) == 0)
3830 size = make_number (1);
3832 sz = XFASTINT (size);
3833 index_float = sz / XFLOAT_DATA (rehash_threshold);
3834 index_size = (index_float < INDEX_SIZE_BOUND + 1
3835 ? next_almost_prime (index_float)
3836 : INDEX_SIZE_BOUND + 1);
3837 if (INDEX_SIZE_BOUND < max (index_size, 2 * sz))
3838 error ("Hash table too large");
3840 /* Allocate a table and initialize it. */
3841 h = allocate_hash_table ();
3843 /* Initialize hash table slots. */
3844 h->test = test;
3845 h->weak = weak;
3846 h->rehash_threshold = rehash_threshold;
3847 h->rehash_size = rehash_size;
3848 h->count = 0;
3849 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
3850 h->hash = Fmake_vector (size, Qnil);
3851 h->next = Fmake_vector (size, Qnil);
3852 h->index = Fmake_vector (make_number (index_size), Qnil);
3854 /* Set up the free list. */
3855 for (i = 0; i < sz - 1; ++i)
3856 set_hash_next_slot (h, i, make_number (i + 1));
3857 h->next_free = make_number (0);
3859 XSET_HASH_TABLE (table, h);
3860 eassert (HASH_TABLE_P (table));
3861 eassert (XHASH_TABLE (table) == h);
3863 /* Maybe add this hash table to the list of all weak hash tables. */
3864 if (NILP (h->weak))
3865 h->next_weak = NULL;
3866 else
3868 h->next_weak = weak_hash_tables;
3869 weak_hash_tables = h;
3872 return table;
3876 /* Return a copy of hash table H1. Keys and values are not copied,
3877 only the table itself is. */
3879 static Lisp_Object
3880 copy_hash_table (struct Lisp_Hash_Table *h1)
3882 Lisp_Object table;
3883 struct Lisp_Hash_Table *h2;
3885 h2 = allocate_hash_table ();
3886 *h2 = *h1;
3887 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3888 h2->hash = Fcopy_sequence (h1->hash);
3889 h2->next = Fcopy_sequence (h1->next);
3890 h2->index = Fcopy_sequence (h1->index);
3891 XSET_HASH_TABLE (table, h2);
3893 /* Maybe add this hash table to the list of all weak hash tables. */
3894 if (!NILP (h2->weak))
3896 h2->next_weak = weak_hash_tables;
3897 weak_hash_tables = h2;
3900 return table;
3904 /* Resize hash table H if it's too full. If H cannot be resized
3905 because it's already too large, throw an error. */
3907 static void
3908 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3910 if (NILP (h->next_free))
3912 ptrdiff_t old_size = HASH_TABLE_SIZE (h);
3913 EMACS_INT new_size, index_size, nsize;
3914 ptrdiff_t i;
3915 double index_float;
3917 if (INTEGERP (h->rehash_size))
3918 new_size = old_size + XFASTINT (h->rehash_size);
3919 else
3921 double float_new_size = old_size * XFLOAT_DATA (h->rehash_size);
3922 if (float_new_size < INDEX_SIZE_BOUND + 1)
3924 new_size = float_new_size;
3925 if (new_size <= old_size)
3926 new_size = old_size + 1;
3928 else
3929 new_size = INDEX_SIZE_BOUND + 1;
3931 index_float = new_size / XFLOAT_DATA (h->rehash_threshold);
3932 index_size = (index_float < INDEX_SIZE_BOUND + 1
3933 ? next_almost_prime (index_float)
3934 : INDEX_SIZE_BOUND + 1);
3935 nsize = max (index_size, 2 * new_size);
3936 if (INDEX_SIZE_BOUND < nsize)
3937 error ("Hash table too large to resize");
3939 #ifdef ENABLE_CHECKING
3940 if (HASH_TABLE_P (Vpurify_flag)
3941 && XHASH_TABLE (Vpurify_flag) == h)
3942 message ("Growing hash table to: %"pI"d", new_size);
3943 #endif
3945 set_hash_key_and_value (h, larger_vector (h->key_and_value,
3946 2 * (new_size - old_size), -1));
3947 set_hash_next (h, larger_vector (h->next, new_size - old_size, -1));
3948 set_hash_hash (h, larger_vector (h->hash, new_size - old_size, -1));
3949 set_hash_index (h, Fmake_vector (make_number (index_size), Qnil));
3951 /* Update the free list. Do it so that new entries are added at
3952 the end of the free list. This makes some operations like
3953 maphash faster. */
3954 for (i = old_size; i < new_size - 1; ++i)
3955 set_hash_next_slot (h, i, make_number (i + 1));
3957 if (!NILP (h->next_free))
3959 Lisp_Object last, next;
3961 last = h->next_free;
3962 while (next = HASH_NEXT (h, XFASTINT (last)),
3963 !NILP (next))
3964 last = next;
3966 set_hash_next_slot (h, XFASTINT (last), make_number (old_size));
3968 else
3969 XSETFASTINT (h->next_free, old_size);
3971 /* Rehash. */
3972 for (i = 0; i < old_size; ++i)
3973 if (!NILP (HASH_HASH (h, i)))
3975 EMACS_UINT hash_code = XUINT (HASH_HASH (h, i));
3976 ptrdiff_t start_of_bucket = hash_code % ASIZE (h->index);
3977 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3978 set_hash_index_slot (h, start_of_bucket, make_number (i));
3984 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
3985 the hash code of KEY. Value is the index of the entry in H
3986 matching KEY, or -1 if not found. */
3988 ptrdiff_t
3989 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
3991 EMACS_UINT hash_code;
3992 ptrdiff_t start_of_bucket;
3993 Lisp_Object idx;
3995 hash_code = h->test.hashfn (&h->test, key);
3996 eassert ((hash_code & ~INTMASK) == 0);
3997 if (hash)
3998 *hash = hash_code;
4000 start_of_bucket = hash_code % ASIZE (h->index);
4001 idx = HASH_INDEX (h, start_of_bucket);
4003 while (!NILP (idx))
4005 ptrdiff_t i = XFASTINT (idx);
4006 if (EQ (key, HASH_KEY (h, i))
4007 || (h->test.cmpfn
4008 && hash_code == XUINT (HASH_HASH (h, i))
4009 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
4010 break;
4011 idx = HASH_NEXT (h, i);
4014 return NILP (idx) ? -1 : XFASTINT (idx);
4018 /* Put an entry into hash table H that associates KEY with VALUE.
4019 HASH is a previously computed hash code of KEY.
4020 Value is the index of the entry in H matching KEY. */
4022 ptrdiff_t
4023 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value,
4024 EMACS_UINT hash)
4026 ptrdiff_t start_of_bucket, i;
4028 eassert ((hash & ~INTMASK) == 0);
4030 /* Increment count after resizing because resizing may fail. */
4031 maybe_resize_hash_table (h);
4032 h->count++;
4034 /* Store key/value in the key_and_value vector. */
4035 i = XFASTINT (h->next_free);
4036 h->next_free = HASH_NEXT (h, i);
4037 set_hash_key_slot (h, i, key);
4038 set_hash_value_slot (h, i, value);
4040 /* Remember its hash code. */
4041 set_hash_hash_slot (h, i, make_number (hash));
4043 /* Add new entry to its collision chain. */
4044 start_of_bucket = hash % ASIZE (h->index);
4045 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
4046 set_hash_index_slot (h, start_of_bucket, make_number (i));
4047 return i;
4051 /* Remove the entry matching KEY from hash table H, if there is one. */
4053 void
4054 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
4056 EMACS_UINT hash_code;
4057 ptrdiff_t start_of_bucket;
4058 Lisp_Object idx, prev;
4060 hash_code = h->test.hashfn (&h->test, key);
4061 eassert ((hash_code & ~INTMASK) == 0);
4062 start_of_bucket = hash_code % ASIZE (h->index);
4063 idx = HASH_INDEX (h, start_of_bucket);
4064 prev = Qnil;
4066 while (!NILP (idx))
4068 ptrdiff_t i = XFASTINT (idx);
4070 if (EQ (key, HASH_KEY (h, i))
4071 || (h->test.cmpfn
4072 && hash_code == XUINT (HASH_HASH (h, i))
4073 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
4075 /* Take entry out of collision chain. */
4076 if (NILP (prev))
4077 set_hash_index_slot (h, start_of_bucket, HASH_NEXT (h, i));
4078 else
4079 set_hash_next_slot (h, XFASTINT (prev), HASH_NEXT (h, i));
4081 /* Clear slots in key_and_value and add the slots to
4082 the free list. */
4083 set_hash_key_slot (h, i, Qnil);
4084 set_hash_value_slot (h, i, Qnil);
4085 set_hash_hash_slot (h, i, Qnil);
4086 set_hash_next_slot (h, i, h->next_free);
4087 h->next_free = make_number (i);
4088 h->count--;
4089 eassert (h->count >= 0);
4090 break;
4092 else
4094 prev = idx;
4095 idx = HASH_NEXT (h, i);
4101 /* Clear hash table H. */
4103 static void
4104 hash_clear (struct Lisp_Hash_Table *h)
4106 if (h->count > 0)
4108 ptrdiff_t i, size = HASH_TABLE_SIZE (h);
4110 for (i = 0; i < size; ++i)
4112 set_hash_next_slot (h, i, i < size - 1 ? make_number (i + 1) : Qnil);
4113 set_hash_key_slot (h, i, Qnil);
4114 set_hash_value_slot (h, i, Qnil);
4115 set_hash_hash_slot (h, i, Qnil);
4118 for (i = 0; i < ASIZE (h->index); ++i)
4119 ASET (h->index, i, Qnil);
4121 h->next_free = make_number (0);
4122 h->count = 0;
4128 /************************************************************************
4129 Weak Hash Tables
4130 ************************************************************************/
4132 /* Sweep weak hash table H. REMOVE_ENTRIES_P means remove
4133 entries from the table that don't survive the current GC.
4134 !REMOVE_ENTRIES_P means mark entries that are in use. Value is
4135 true if anything was marked. */
4137 static bool
4138 sweep_weak_table (struct Lisp_Hash_Table *h, bool remove_entries_p)
4140 ptrdiff_t n = gc_asize (h->index);
4141 bool marked = false;
4143 for (ptrdiff_t bucket = 0; bucket < n; ++bucket)
4145 Lisp_Object idx, next, prev;
4147 /* Follow collision chain, removing entries that
4148 don't survive this garbage collection. */
4149 prev = Qnil;
4150 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
4152 ptrdiff_t i = XFASTINT (idx);
4153 bool key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
4154 bool value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
4155 bool remove_p;
4157 if (EQ (h->weak, Qkey))
4158 remove_p = !key_known_to_survive_p;
4159 else if (EQ (h->weak, Qvalue))
4160 remove_p = !value_known_to_survive_p;
4161 else if (EQ (h->weak, Qkey_or_value))
4162 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
4163 else if (EQ (h->weak, Qkey_and_value))
4164 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
4165 else
4166 emacs_abort ();
4168 next = HASH_NEXT (h, i);
4170 if (remove_entries_p)
4172 if (remove_p)
4174 /* Take out of collision chain. */
4175 if (NILP (prev))
4176 set_hash_index_slot (h, bucket, next);
4177 else
4178 set_hash_next_slot (h, XFASTINT (prev), next);
4180 /* Add to free list. */
4181 set_hash_next_slot (h, i, h->next_free);
4182 h->next_free = idx;
4184 /* Clear key, value, and hash. */
4185 set_hash_key_slot (h, i, Qnil);
4186 set_hash_value_slot (h, i, Qnil);
4187 set_hash_hash_slot (h, i, Qnil);
4189 h->count--;
4191 else
4193 prev = idx;
4196 else
4198 if (!remove_p)
4200 /* Make sure key and value survive. */
4201 if (!key_known_to_survive_p)
4203 mark_object (HASH_KEY (h, i));
4204 marked = 1;
4207 if (!value_known_to_survive_p)
4209 mark_object (HASH_VALUE (h, i));
4210 marked = 1;
4217 return marked;
4220 /* Remove elements from weak hash tables that don't survive the
4221 current garbage collection. Remove weak tables that don't survive
4222 from Vweak_hash_tables. Called from gc_sweep. */
4224 NO_INLINE /* For better stack traces */
4225 void
4226 sweep_weak_hash_tables (void)
4228 struct Lisp_Hash_Table *h, *used, *next;
4229 bool marked;
4231 /* Mark all keys and values that are in use. Keep on marking until
4232 there is no more change. This is necessary for cases like
4233 value-weak table A containing an entry X -> Y, where Y is used in a
4234 key-weak table B, Z -> Y. If B comes after A in the list of weak
4235 tables, X -> Y might be removed from A, although when looking at B
4236 one finds that it shouldn't. */
4239 marked = 0;
4240 for (h = weak_hash_tables; h; h = h->next_weak)
4242 if (h->header.size & ARRAY_MARK_FLAG)
4243 marked |= sweep_weak_table (h, 0);
4246 while (marked);
4248 /* Remove tables and entries that aren't used. */
4249 for (h = weak_hash_tables, used = NULL; h; h = next)
4251 next = h->next_weak;
4253 if (h->header.size & ARRAY_MARK_FLAG)
4255 /* TABLE is marked as used. Sweep its contents. */
4256 if (h->count > 0)
4257 sweep_weak_table (h, 1);
4259 /* Add table to the list of used weak hash tables. */
4260 h->next_weak = used;
4261 used = h;
4265 weak_hash_tables = used;
4270 /***********************************************************************
4271 Hash Code Computation
4272 ***********************************************************************/
4274 /* Maximum depth up to which to dive into Lisp structures. */
4276 #define SXHASH_MAX_DEPTH 3
4278 /* Maximum length up to which to take list and vector elements into
4279 account. */
4281 #define SXHASH_MAX_LEN 7
4283 /* Return a hash for string PTR which has length LEN. The hash value
4284 can be any EMACS_UINT value. */
4286 EMACS_UINT
4287 hash_string (char const *ptr, ptrdiff_t len)
4289 char const *p = ptr;
4290 char const *end = p + len;
4291 unsigned char c;
4292 EMACS_UINT hash = 0;
4294 while (p != end)
4296 c = *p++;
4297 hash = sxhash_combine (hash, c);
4300 return hash;
4303 /* Return a hash for string PTR which has length LEN. The hash
4304 code returned is guaranteed to fit in a Lisp integer. */
4306 static EMACS_UINT
4307 sxhash_string (char const *ptr, ptrdiff_t len)
4309 EMACS_UINT hash = hash_string (ptr, len);
4310 return SXHASH_REDUCE (hash);
4313 /* Return a hash for the floating point value VAL. */
4315 static EMACS_UINT
4316 sxhash_float (double val)
4318 EMACS_UINT hash = 0;
4319 enum {
4320 WORDS_PER_DOUBLE = (sizeof val / sizeof hash
4321 + (sizeof val % sizeof hash != 0))
4323 union {
4324 double val;
4325 EMACS_UINT word[WORDS_PER_DOUBLE];
4326 } u;
4327 int i;
4328 u.val = val;
4329 memset (&u.val + 1, 0, sizeof u - sizeof u.val);
4330 for (i = 0; i < WORDS_PER_DOUBLE; i++)
4331 hash = sxhash_combine (hash, u.word[i]);
4332 return SXHASH_REDUCE (hash);
4335 /* Return a hash for list LIST. DEPTH is the current depth in the
4336 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4338 static EMACS_UINT
4339 sxhash_list (Lisp_Object list, int depth)
4341 EMACS_UINT hash = 0;
4342 int i;
4344 if (depth < SXHASH_MAX_DEPTH)
4345 for (i = 0;
4346 CONSP (list) && i < SXHASH_MAX_LEN;
4347 list = XCDR (list), ++i)
4349 EMACS_UINT hash2 = sxhash (XCAR (list), depth + 1);
4350 hash = sxhash_combine (hash, hash2);
4353 if (!NILP (list))
4355 EMACS_UINT hash2 = sxhash (list, depth + 1);
4356 hash = sxhash_combine (hash, hash2);
4359 return SXHASH_REDUCE (hash);
4363 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4364 the Lisp structure. */
4366 static EMACS_UINT
4367 sxhash_vector (Lisp_Object vec, int depth)
4369 EMACS_UINT hash = ASIZE (vec);
4370 int i, n;
4372 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4373 for (i = 0; i < n; ++i)
4375 EMACS_UINT hash2 = sxhash (AREF (vec, i), depth + 1);
4376 hash = sxhash_combine (hash, hash2);
4379 return SXHASH_REDUCE (hash);
4382 /* Return a hash for bool-vector VECTOR. */
4384 static EMACS_UINT
4385 sxhash_bool_vector (Lisp_Object vec)
4387 EMACS_INT size = bool_vector_size (vec);
4388 EMACS_UINT hash = size;
4389 int i, n;
4391 n = min (SXHASH_MAX_LEN, bool_vector_words (size));
4392 for (i = 0; i < n; ++i)
4393 hash = sxhash_combine (hash, bool_vector_data (vec)[i]);
4395 return SXHASH_REDUCE (hash);
4399 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4400 structure. Value is an unsigned integer clipped to INTMASK. */
4402 EMACS_UINT
4403 sxhash (Lisp_Object obj, int depth)
4405 EMACS_UINT hash;
4407 if (depth > SXHASH_MAX_DEPTH)
4408 return 0;
4410 switch (XTYPE (obj))
4412 case_Lisp_Int:
4413 hash = XUINT (obj);
4414 break;
4416 case Lisp_Misc:
4417 case Lisp_Symbol:
4418 hash = XHASH (obj);
4419 break;
4421 case Lisp_String:
4422 hash = sxhash_string (SSDATA (obj), SBYTES (obj));
4423 break;
4425 /* This can be everything from a vector to an overlay. */
4426 case Lisp_Vectorlike:
4427 if (VECTORP (obj))
4428 /* According to the CL HyperSpec, two arrays are equal only if
4429 they are `eq', except for strings and bit-vectors. In
4430 Emacs, this works differently. We have to compare element
4431 by element. */
4432 hash = sxhash_vector (obj, depth);
4433 else if (BOOL_VECTOR_P (obj))
4434 hash = sxhash_bool_vector (obj);
4435 else
4436 /* Others are `equal' if they are `eq', so let's take their
4437 address as hash. */
4438 hash = XHASH (obj);
4439 break;
4441 case Lisp_Cons:
4442 hash = sxhash_list (obj, depth);
4443 break;
4445 case Lisp_Float:
4446 hash = sxhash_float (XFLOAT_DATA (obj));
4447 break;
4449 default:
4450 emacs_abort ();
4453 return hash;
4458 /***********************************************************************
4459 Lisp Interface
4460 ***********************************************************************/
4462 DEFUN ("sxhash-eq", Fsxhash_eq, Ssxhash_eq, 1, 1, 0,
4463 doc: /* Return an integer hash code for OBJ suitable for `eq'.
4464 If (eq A B), then (= (sxhash-eq A) (sxhash-eq B)). */)
4465 (Lisp_Object obj)
4467 return make_number (hashfn_eq (NULL, obj));
4470 DEFUN ("sxhash-eql", Fsxhash_eql, Ssxhash_eql, 1, 1, 0,
4471 doc: /* Return an integer hash code for OBJ suitable for `eql'.
4472 If (eql A B), then (= (sxhash-eql A) (sxhash-eql B)). */)
4473 (Lisp_Object obj)
4475 return make_number (hashfn_eql (NULL, obj));
4478 DEFUN ("sxhash-equal", Fsxhash_equal, Ssxhash_equal, 1, 1, 0,
4479 doc: /* Return an integer hash code for OBJ suitable for `equal'.
4480 If (equal A B), then (= (sxhash-equal A) (sxhash-equal B)). */)
4481 (Lisp_Object obj)
4483 return make_number (hashfn_equal (NULL, obj));
4486 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4487 doc: /* Create and return a new hash table.
4489 Arguments are specified as keyword/argument pairs. The following
4490 arguments are defined:
4492 :test TEST -- TEST must be a symbol that specifies how to compare
4493 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4494 `equal'. User-supplied test and hash functions can be specified via
4495 `define-hash-table-test'.
4497 :size SIZE -- A hint as to how many elements will be put in the table.
4498 Default is 65.
4500 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4501 fills up. If REHASH-SIZE is an integer, increase the size by that
4502 amount. If it is a float, it must be > 1.0, and the new size is the
4503 old size multiplied by that factor. Default is 1.5.
4505 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4506 Resize the hash table when the ratio (number of entries / table size)
4507 is greater than or equal to THRESHOLD. Default is 0.8.
4509 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4510 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4511 returned is a weak table. Key/value pairs are removed from a weak
4512 hash table when there are no non-weak references pointing to their
4513 key, value, one of key or value, or both key and value, depending on
4514 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4515 is nil.
4517 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4518 (ptrdiff_t nargs, Lisp_Object *args)
4520 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4521 struct hash_table_test testdesc;
4522 ptrdiff_t i;
4523 USE_SAFE_ALLOCA;
4525 /* The vector `used' is used to keep track of arguments that
4526 have been consumed. */
4527 char *used = SAFE_ALLOCA (nargs * sizeof *used);
4528 memset (used, 0, nargs * sizeof *used);
4530 /* See if there's a `:test TEST' among the arguments. */
4531 i = get_key_arg (QCtest, nargs, args, used);
4532 test = i ? args[i] : Qeql;
4533 if (EQ (test, Qeq))
4534 testdesc = hashtest_eq;
4535 else if (EQ (test, Qeql))
4536 testdesc = hashtest_eql;
4537 else if (EQ (test, Qequal))
4538 testdesc = hashtest_equal;
4539 else
4541 /* See if it is a user-defined test. */
4542 Lisp_Object prop;
4544 prop = Fget (test, Qhash_table_test);
4545 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4546 signal_error ("Invalid hash table test", test);
4547 testdesc.name = test;
4548 testdesc.user_cmp_function = XCAR (prop);
4549 testdesc.user_hash_function = XCAR (XCDR (prop));
4550 testdesc.hashfn = hashfn_user_defined;
4551 testdesc.cmpfn = cmpfn_user_defined;
4554 /* See if there's a `:size SIZE' argument. */
4555 i = get_key_arg (QCsize, nargs, args, used);
4556 size = i ? args[i] : Qnil;
4557 if (NILP (size))
4558 size = make_number (DEFAULT_HASH_SIZE);
4559 else if (!INTEGERP (size) || XINT (size) < 0)
4560 signal_error ("Invalid hash table size", size);
4562 /* Look for `:rehash-size SIZE'. */
4563 i = get_key_arg (QCrehash_size, nargs, args, used);
4564 rehash_size = i ? args[i] : make_float (DEFAULT_REHASH_SIZE);
4565 if (! ((INTEGERP (rehash_size) && 0 < XINT (rehash_size))
4566 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size))))
4567 signal_error ("Invalid hash table rehash size", rehash_size);
4569 /* Look for `:rehash-threshold THRESHOLD'. */
4570 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4571 rehash_threshold = i ? args[i] : make_float (DEFAULT_REHASH_THRESHOLD);
4572 if (! (FLOATP (rehash_threshold)
4573 && 0 < XFLOAT_DATA (rehash_threshold)
4574 && XFLOAT_DATA (rehash_threshold) <= 1))
4575 signal_error ("Invalid hash table rehash threshold", rehash_threshold);
4577 /* Look for `:weakness WEAK'. */
4578 i = get_key_arg (QCweakness, nargs, args, used);
4579 weak = i ? args[i] : Qnil;
4580 if (EQ (weak, Qt))
4581 weak = Qkey_and_value;
4582 if (!NILP (weak)
4583 && !EQ (weak, Qkey)
4584 && !EQ (weak, Qvalue)
4585 && !EQ (weak, Qkey_or_value)
4586 && !EQ (weak, Qkey_and_value))
4587 signal_error ("Invalid hash table weakness", weak);
4589 /* Now, all args should have been used up, or there's a problem. */
4590 for (i = 0; i < nargs; ++i)
4591 if (!used[i])
4592 signal_error ("Invalid argument list", args[i]);
4594 SAFE_FREE ();
4595 return make_hash_table (testdesc, size, rehash_size, rehash_threshold, weak);
4599 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4600 doc: /* Return a copy of hash table TABLE. */)
4601 (Lisp_Object table)
4603 return copy_hash_table (check_hash_table (table));
4607 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4608 doc: /* Return the number of elements in TABLE. */)
4609 (Lisp_Object table)
4611 return make_number (check_hash_table (table)->count);
4615 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4616 Shash_table_rehash_size, 1, 1, 0,
4617 doc: /* Return the current rehash size of TABLE. */)
4618 (Lisp_Object table)
4620 return check_hash_table (table)->rehash_size;
4624 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4625 Shash_table_rehash_threshold, 1, 1, 0,
4626 doc: /* Return the current rehash threshold of TABLE. */)
4627 (Lisp_Object table)
4629 return check_hash_table (table)->rehash_threshold;
4633 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4634 doc: /* Return the size of TABLE.
4635 The size can be used as an argument to `make-hash-table' to create
4636 a hash table than can hold as many elements as TABLE holds
4637 without need for resizing. */)
4638 (Lisp_Object table)
4640 struct Lisp_Hash_Table *h = check_hash_table (table);
4641 return make_number (HASH_TABLE_SIZE (h));
4645 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4646 doc: /* Return the test TABLE uses. */)
4647 (Lisp_Object table)
4649 return check_hash_table (table)->test.name;
4653 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4654 1, 1, 0,
4655 doc: /* Return the weakness of TABLE. */)
4656 (Lisp_Object table)
4658 return check_hash_table (table)->weak;
4662 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4663 doc: /* Return t if OBJ is a Lisp hash table object. */)
4664 (Lisp_Object obj)
4666 return HASH_TABLE_P (obj) ? Qt : Qnil;
4670 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4671 doc: /* Clear hash table TABLE and return it. */)
4672 (Lisp_Object table)
4674 hash_clear (check_hash_table (table));
4675 /* Be compatible with XEmacs. */
4676 return table;
4680 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4681 doc: /* Look up KEY in TABLE and return its associated value.
4682 If KEY is not found, return DFLT which defaults to nil. */)
4683 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4685 struct Lisp_Hash_Table *h = check_hash_table (table);
4686 ptrdiff_t i = hash_lookup (h, key, NULL);
4687 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4691 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4692 doc: /* Associate KEY with VALUE in hash table TABLE.
4693 If KEY is already present in table, replace its current value with
4694 VALUE. In any case, return VALUE. */)
4695 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4697 struct Lisp_Hash_Table *h = check_hash_table (table);
4698 ptrdiff_t i;
4699 EMACS_UINT hash;
4701 i = hash_lookup (h, key, &hash);
4702 if (i >= 0)
4703 set_hash_value_slot (h, i, value);
4704 else
4705 hash_put (h, key, value, hash);
4707 return value;
4711 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4712 doc: /* Remove KEY from TABLE. */)
4713 (Lisp_Object key, Lisp_Object table)
4715 struct Lisp_Hash_Table *h = check_hash_table (table);
4716 hash_remove_from_table (h, key);
4717 return Qnil;
4721 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4722 doc: /* Call FUNCTION for all entries in hash table TABLE.
4723 FUNCTION is called with two arguments, KEY and VALUE.
4724 `maphash' always returns nil. */)
4725 (Lisp_Object function, Lisp_Object table)
4727 struct Lisp_Hash_Table *h = check_hash_table (table);
4729 for (ptrdiff_t i = 0; i < HASH_TABLE_SIZE (h); ++i)
4730 if (!NILP (HASH_HASH (h, i)))
4731 call2 (function, HASH_KEY (h, i), HASH_VALUE (h, i));
4733 return Qnil;
4737 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4738 Sdefine_hash_table_test, 3, 3, 0,
4739 doc: /* Define a new hash table test with name NAME, a symbol.
4741 In hash tables created with NAME specified as test, use TEST to
4742 compare keys, and HASH for computing hash codes of keys.
4744 TEST must be a function taking two arguments and returning non-nil if
4745 both arguments are the same. HASH must be a function taking one
4746 argument and returning an object that is the hash code of the argument.
4747 It should be the case that if (eq (funcall HASH x1) (funcall HASH x2))
4748 returns nil, then (funcall TEST x1 x2) also returns nil. */)
4749 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4751 return Fput (name, Qhash_table_test, list2 (test, hash));
4756 /************************************************************************
4757 MD5, SHA-1, and SHA-2
4758 ************************************************************************/
4760 #include "md5.h"
4761 #include "sha1.h"
4762 #include "sha256.h"
4763 #include "sha512.h"
4765 static Lisp_Object
4766 make_digest_string (Lisp_Object digest, int digest_size)
4768 unsigned char *p = SDATA (digest);
4770 for (int i = digest_size - 1; i >= 0; i--)
4772 static char const hexdigit[16] = "0123456789abcdef";
4773 int p_i = p[i];
4774 p[2 * i] = hexdigit[p_i >> 4];
4775 p[2 * i + 1] = hexdigit[p_i & 0xf];
4777 return digest;
4780 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4782 static Lisp_Object
4783 secure_hash (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start,
4784 Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror,
4785 Lisp_Object binary)
4787 ptrdiff_t size, start_char = 0, start_byte, end_char = 0, end_byte;
4788 register EMACS_INT b, e;
4789 register struct buffer *bp;
4790 EMACS_INT temp;
4791 int digest_size;
4792 void *(*hash_func) (const char *, size_t, void *);
4793 Lisp_Object digest;
4795 CHECK_SYMBOL (algorithm);
4797 if (STRINGP (object))
4799 if (NILP (coding_system))
4801 /* Decide the coding-system to encode the data with. */
4803 if (STRING_MULTIBYTE (object))
4804 /* use default, we can't guess correct value */
4805 coding_system = preferred_coding_system ();
4806 else
4807 coding_system = Qraw_text;
4810 if (NILP (Fcoding_system_p (coding_system)))
4812 /* Invalid coding system. */
4814 if (!NILP (noerror))
4815 coding_system = Qraw_text;
4816 else
4817 xsignal1 (Qcoding_system_error, coding_system);
4820 if (STRING_MULTIBYTE (object))
4821 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4823 size = SCHARS (object);
4824 validate_subarray (object, start, end, size, &start_char, &end_char);
4826 start_byte = !start_char ? 0 : string_char_to_byte (object, start_char);
4827 end_byte = (end_char == size
4828 ? SBYTES (object)
4829 : string_char_to_byte (object, end_char));
4831 else
4833 struct buffer *prev = current_buffer;
4835 record_unwind_current_buffer ();
4837 CHECK_BUFFER (object);
4839 bp = XBUFFER (object);
4840 set_buffer_internal (bp);
4842 if (NILP (start))
4843 b = BEGV;
4844 else
4846 CHECK_NUMBER_COERCE_MARKER (start);
4847 b = XINT (start);
4850 if (NILP (end))
4851 e = ZV;
4852 else
4854 CHECK_NUMBER_COERCE_MARKER (end);
4855 e = XINT (end);
4858 if (b > e)
4859 temp = b, b = e, e = temp;
4861 if (!(BEGV <= b && e <= ZV))
4862 args_out_of_range (start, end);
4864 if (NILP (coding_system))
4866 /* Decide the coding-system to encode the data with.
4867 See fileio.c:Fwrite-region */
4869 if (!NILP (Vcoding_system_for_write))
4870 coding_system = Vcoding_system_for_write;
4871 else
4873 bool force_raw_text = 0;
4875 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4876 if (NILP (coding_system)
4877 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4879 coding_system = Qnil;
4880 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4881 force_raw_text = 1;
4884 if (NILP (coding_system) && !NILP (Fbuffer_file_name (object)))
4886 /* Check file-coding-system-alist. */
4887 Lisp_Object val = CALLN (Ffind_operation_coding_system,
4888 Qwrite_region, start, end,
4889 Fbuffer_file_name (object));
4890 if (CONSP (val) && !NILP (XCDR (val)))
4891 coding_system = XCDR (val);
4894 if (NILP (coding_system)
4895 && !NILP (BVAR (XBUFFER (object), buffer_file_coding_system)))
4897 /* If we still have not decided a coding system, use the
4898 default value of buffer-file-coding-system. */
4899 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4902 if (!force_raw_text
4903 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4904 /* Confirm that VAL can surely encode the current region. */
4905 coding_system = call4 (Vselect_safe_coding_system_function,
4906 make_number (b), make_number (e),
4907 coding_system, Qnil);
4909 if (force_raw_text)
4910 coding_system = Qraw_text;
4913 if (NILP (Fcoding_system_p (coding_system)))
4915 /* Invalid coding system. */
4917 if (!NILP (noerror))
4918 coding_system = Qraw_text;
4919 else
4920 xsignal1 (Qcoding_system_error, coding_system);
4924 object = make_buffer_string (b, e, 0);
4925 set_buffer_internal (prev);
4926 /* Discard the unwind protect for recovering the current
4927 buffer. */
4928 specpdl_ptr--;
4930 if (STRING_MULTIBYTE (object))
4931 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4932 start_byte = 0;
4933 end_byte = SBYTES (object);
4936 if (EQ (algorithm, Qmd5))
4938 digest_size = MD5_DIGEST_SIZE;
4939 hash_func = md5_buffer;
4941 else if (EQ (algorithm, Qsha1))
4943 digest_size = SHA1_DIGEST_SIZE;
4944 hash_func = sha1_buffer;
4946 else if (EQ (algorithm, Qsha224))
4948 digest_size = SHA224_DIGEST_SIZE;
4949 hash_func = sha224_buffer;
4951 else if (EQ (algorithm, Qsha256))
4953 digest_size = SHA256_DIGEST_SIZE;
4954 hash_func = sha256_buffer;
4956 else if (EQ (algorithm, Qsha384))
4958 digest_size = SHA384_DIGEST_SIZE;
4959 hash_func = sha384_buffer;
4961 else if (EQ (algorithm, Qsha512))
4963 digest_size = SHA512_DIGEST_SIZE;
4964 hash_func = sha512_buffer;
4966 else
4967 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm)));
4969 /* allocate 2 x digest_size so that it can be re-used to hold the
4970 hexified value */
4971 digest = make_uninit_string (digest_size * 2);
4973 hash_func (SSDATA (object) + start_byte,
4974 end_byte - start_byte,
4975 SSDATA (digest));
4977 if (NILP (binary))
4978 return make_digest_string (digest, digest_size);
4979 else
4980 return make_unibyte_string (SSDATA (digest), digest_size);
4983 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
4984 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
4986 A message digest is a cryptographic checksum of a document, and the
4987 algorithm to calculate it is defined in RFC 1321.
4989 The two optional arguments START and END are character positions
4990 specifying for which part of OBJECT the message digest should be
4991 computed. If nil or omitted, the digest is computed for the whole
4992 OBJECT.
4994 The MD5 message digest is computed from the result of encoding the
4995 text in a coding system, not directly from the internal Emacs form of
4996 the text. The optional fourth argument CODING-SYSTEM specifies which
4997 coding system to encode the text with. It should be the same coding
4998 system that you used or will use when actually writing the text into a
4999 file.
5001 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
5002 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
5003 system would be chosen by default for writing this text into a file.
5005 If OBJECT is a string, the most preferred coding system (see the
5006 command `prefer-coding-system') is used.
5008 If NOERROR is non-nil, silently assume the `raw-text' coding if the
5009 guesswork fails. Normally, an error is signaled in such case. */)
5010 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
5012 return secure_hash (Qmd5, object, start, end, coding_system, noerror, Qnil);
5015 DEFUN ("secure-hash", Fsecure_hash, Ssecure_hash, 2, 5, 0,
5016 doc: /* Return the secure hash of OBJECT, a buffer or string.
5017 ALGORITHM is a symbol specifying the hash to use:
5018 md5, sha1, sha224, sha256, sha384 or sha512.
5020 The two optional arguments START and END are positions specifying for
5021 which part of OBJECT to compute the hash. If nil or omitted, uses the
5022 whole OBJECT.
5024 If BINARY is non-nil, returns a string in binary form. */)
5025 (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object binary)
5027 return secure_hash (algorithm, object, start, end, Qnil, Qnil, binary);
5030 DEFUN ("buffer-hash", Fbuffer_hash, Sbuffer_hash, 0, 1, 0,
5031 doc: /* Return a hash of the contents of BUFFER-OR-NAME.
5032 This hash is performed on the raw internal format of the buffer,
5033 disregarding any coding systems.
5034 If nil, use the current buffer." */ )
5035 (Lisp_Object buffer_or_name)
5037 Lisp_Object buffer;
5038 struct buffer *b;
5039 struct sha1_ctx ctx;
5041 if (NILP (buffer_or_name))
5042 buffer = Fcurrent_buffer ();
5043 else
5044 buffer = Fget_buffer (buffer_or_name);
5045 if (NILP (buffer))
5046 nsberror (buffer_or_name);
5048 b = XBUFFER (buffer);
5049 sha1_init_ctx (&ctx);
5051 /* Process the first part of the buffer. */
5052 sha1_process_bytes (BUF_BEG_ADDR (b),
5053 BUF_GPT_BYTE (b) - BUF_BEG_BYTE (b),
5054 &ctx);
5056 /* If the gap is before the end of the buffer, process the last half
5057 of the buffer. */
5058 if (BUF_GPT_BYTE (b) < BUF_Z_BYTE (b))
5059 sha1_process_bytes (BUF_GAP_END_ADDR (b),
5060 BUF_Z_ADDR (b) - BUF_GAP_END_ADDR (b),
5061 &ctx);
5063 Lisp_Object digest = make_uninit_string (SHA1_DIGEST_SIZE * 2);
5064 sha1_finish_ctx (&ctx, SSDATA (digest));
5065 return make_digest_string (digest, SHA1_DIGEST_SIZE);
5069 void
5070 syms_of_fns (void)
5072 DEFSYM (Qmd5, "md5");
5073 DEFSYM (Qsha1, "sha1");
5074 DEFSYM (Qsha224, "sha224");
5075 DEFSYM (Qsha256, "sha256");
5076 DEFSYM (Qsha384, "sha384");
5077 DEFSYM (Qsha512, "sha512");
5079 /* Hash table stuff. */
5080 DEFSYM (Qhash_table_p, "hash-table-p");
5081 DEFSYM (Qeq, "eq");
5082 DEFSYM (Qeql, "eql");
5083 DEFSYM (Qequal, "equal");
5084 DEFSYM (QCtest, ":test");
5085 DEFSYM (QCsize, ":size");
5086 DEFSYM (QCrehash_size, ":rehash-size");
5087 DEFSYM (QCrehash_threshold, ":rehash-threshold");
5088 DEFSYM (QCweakness, ":weakness");
5089 DEFSYM (Qkey, "key");
5090 DEFSYM (Qvalue, "value");
5091 DEFSYM (Qhash_table_test, "hash-table-test");
5092 DEFSYM (Qkey_or_value, "key-or-value");
5093 DEFSYM (Qkey_and_value, "key-and-value");
5095 defsubr (&Ssxhash_eq);
5096 defsubr (&Ssxhash_eql);
5097 defsubr (&Ssxhash_equal);
5098 defsubr (&Smake_hash_table);
5099 defsubr (&Scopy_hash_table);
5100 defsubr (&Shash_table_count);
5101 defsubr (&Shash_table_rehash_size);
5102 defsubr (&Shash_table_rehash_threshold);
5103 defsubr (&Shash_table_size);
5104 defsubr (&Shash_table_test);
5105 defsubr (&Shash_table_weakness);
5106 defsubr (&Shash_table_p);
5107 defsubr (&Sclrhash);
5108 defsubr (&Sgethash);
5109 defsubr (&Sputhash);
5110 defsubr (&Sremhash);
5111 defsubr (&Smaphash);
5112 defsubr (&Sdefine_hash_table_test);
5114 DEFSYM (Qstring_lessp, "string-lessp");
5115 DEFSYM (Qprovide, "provide");
5116 DEFSYM (Qrequire, "require");
5117 DEFSYM (Qyes_or_no_p_history, "yes-or-no-p-history");
5118 DEFSYM (Qcursor_in_echo_area, "cursor-in-echo-area");
5119 DEFSYM (Qwidget_type, "widget-type");
5121 staticpro (&string_char_byte_cache_string);
5122 string_char_byte_cache_string = Qnil;
5124 require_nesting_list = Qnil;
5125 staticpro (&require_nesting_list);
5127 Fset (Qyes_or_no_p_history, Qnil);
5129 DEFVAR_LISP ("features", Vfeatures,
5130 doc: /* A list of symbols which are the features of the executing Emacs.
5131 Used by `featurep' and `require', and altered by `provide'. */);
5132 Vfeatures = list1 (Qemacs);
5133 DEFSYM (Qfeatures, "features");
5134 /* Let people use lexically scoped vars named `features'. */
5135 Fmake_var_non_special (Qfeatures);
5136 DEFSYM (Qsubfeatures, "subfeatures");
5137 DEFSYM (Qfuncall, "funcall");
5139 #ifdef HAVE_LANGINFO_CODESET
5140 DEFSYM (Qcodeset, "codeset");
5141 DEFSYM (Qdays, "days");
5142 DEFSYM (Qmonths, "months");
5143 DEFSYM (Qpaper, "paper");
5144 #endif /* HAVE_LANGINFO_CODESET */
5146 DEFVAR_BOOL ("use-dialog-box", use_dialog_box,
5147 doc: /* Non-nil means mouse commands use dialog boxes to ask questions.
5148 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
5149 invoked by mouse clicks and mouse menu items.
5151 On some platforms, file selection dialogs are also enabled if this is
5152 non-nil. */);
5153 use_dialog_box = 1;
5155 DEFVAR_BOOL ("use-file-dialog", use_file_dialog,
5156 doc: /* Non-nil means mouse commands use a file dialog to ask for files.
5157 This applies to commands from menus and tool bar buttons even when
5158 they are initiated from the keyboard. If `use-dialog-box' is nil,
5159 that disables the use of a file dialog, regardless of the value of
5160 this variable. */);
5161 use_file_dialog = 1;
5163 defsubr (&Sidentity);
5164 defsubr (&Srandom);
5165 defsubr (&Slength);
5166 defsubr (&Ssafe_length);
5167 defsubr (&Sstring_bytes);
5168 defsubr (&Sstring_equal);
5169 defsubr (&Scompare_strings);
5170 defsubr (&Sstring_lessp);
5171 defsubr (&Sstring_version_lessp);
5172 defsubr (&Sstring_collate_lessp);
5173 defsubr (&Sstring_collate_equalp);
5174 defsubr (&Sappend);
5175 defsubr (&Sconcat);
5176 defsubr (&Svconcat);
5177 defsubr (&Scopy_sequence);
5178 defsubr (&Sstring_make_multibyte);
5179 defsubr (&Sstring_make_unibyte);
5180 defsubr (&Sstring_as_multibyte);
5181 defsubr (&Sstring_as_unibyte);
5182 defsubr (&Sstring_to_multibyte);
5183 defsubr (&Sstring_to_unibyte);
5184 defsubr (&Scopy_alist);
5185 defsubr (&Ssubstring);
5186 defsubr (&Ssubstring_no_properties);
5187 defsubr (&Snthcdr);
5188 defsubr (&Snth);
5189 defsubr (&Selt);
5190 defsubr (&Smember);
5191 defsubr (&Smemq);
5192 defsubr (&Smemql);
5193 defsubr (&Sassq);
5194 defsubr (&Sassoc);
5195 defsubr (&Srassq);
5196 defsubr (&Srassoc);
5197 defsubr (&Sdelq);
5198 defsubr (&Sdelete);
5199 defsubr (&Snreverse);
5200 defsubr (&Sreverse);
5201 defsubr (&Ssort);
5202 defsubr (&Splist_get);
5203 defsubr (&Sget);
5204 defsubr (&Splist_put);
5205 defsubr (&Sput);
5206 defsubr (&Slax_plist_get);
5207 defsubr (&Slax_plist_put);
5208 defsubr (&Seql);
5209 defsubr (&Sequal);
5210 defsubr (&Sequal_including_properties);
5211 defsubr (&Sfillarray);
5212 defsubr (&Sclear_string);
5213 defsubr (&Snconc);
5214 defsubr (&Smapcar);
5215 defsubr (&Smapc);
5216 defsubr (&Smapcan);
5217 defsubr (&Smapconcat);
5218 defsubr (&Syes_or_no_p);
5219 defsubr (&Sload_average);
5220 defsubr (&Sfeaturep);
5221 defsubr (&Srequire);
5222 defsubr (&Sprovide);
5223 defsubr (&Splist_member);
5224 defsubr (&Swidget_put);
5225 defsubr (&Swidget_get);
5226 defsubr (&Swidget_apply);
5227 defsubr (&Sbase64_encode_region);
5228 defsubr (&Sbase64_decode_region);
5229 defsubr (&Sbase64_encode_string);
5230 defsubr (&Sbase64_decode_string);
5231 defsubr (&Smd5);
5232 defsubr (&Ssecure_hash);
5233 defsubr (&Sbuffer_hash);
5234 defsubr (&Slocale_info);