Stick with debbugs-supported tags in triage
[emacs.git] / src / fns.c
blob31f0fd274187ff4710e692aaab4cd22f0f4d3851
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 <unistd.h>
24 #include <filevercmp.h>
25 #include <intprops.h>
26 #include <vla.h>
27 #include <errno.h>
29 #include "lisp.h"
30 #include "character.h"
31 #include "coding.h"
32 #include "composite.h"
33 #include "buffer.h"
34 #include "intervals.h"
35 #include "window.h"
37 static void sort_vector_copy (Lisp_Object, ptrdiff_t,
38 Lisp_Object *restrict, Lisp_Object *restrict);
39 static bool internal_equal (Lisp_Object, Lisp_Object, int, bool, Lisp_Object);
41 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
42 doc: /* Return the argument unchanged. */
43 attributes: const)
44 (Lisp_Object arg)
46 return arg;
49 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
50 doc: /* Return a pseudo-random number.
51 All integers representable in Lisp, i.e. between `most-negative-fixnum'
52 and `most-positive-fixnum', inclusive, are equally likely.
54 With positive integer LIMIT, return random number in interval [0,LIMIT).
55 With argument t, set the random number seed from the system's entropy
56 pool if available, otherwise from less-random volatile data such as the time.
57 With a string argument, set the seed based on the string's contents.
58 Other values of LIMIT are ignored.
60 See Info node `(elisp)Random Numbers' for more details. */)
61 (Lisp_Object limit)
63 EMACS_INT val;
65 if (EQ (limit, Qt))
66 init_random ();
67 else if (STRINGP (limit))
68 seed_random (SSDATA (limit), SBYTES (limit));
70 val = get_random ();
71 if (INTEGERP (limit) && 0 < XINT (limit))
72 while (true)
74 /* Return the remainder, except reject the rare case where
75 get_random returns a number so close to INTMASK that the
76 remainder isn't random. */
77 EMACS_INT remainder = val % XINT (limit);
78 if (val - remainder <= INTMASK - XINT (limit) + 1)
79 return make_number (remainder);
80 val = get_random ();
82 return make_number (val);
85 /* Heuristic on how many iterations of a tight loop can be safely done
86 before it's time to do a QUIT. This must be a power of 2. */
87 enum { QUIT_COUNT_HEURISTIC = 1 << 16 };
89 /* Random data-structure functions. */
91 static void
92 CHECK_LIST_END (Lisp_Object x, Lisp_Object y)
94 CHECK_TYPE (NILP (x), Qlistp, y);
97 DEFUN ("length", Flength, Slength, 1, 1, 0,
98 doc: /* Return the length of vector, list or string SEQUENCE.
99 A byte-code function object is also allowed.
100 If the string contains multibyte characters, this is not necessarily
101 the number of bytes in the string; it is the number of characters.
102 To get the number of bytes, use `string-bytes'. */)
103 (register Lisp_Object sequence)
105 register Lisp_Object val;
107 if (STRINGP (sequence))
108 XSETFASTINT (val, SCHARS (sequence));
109 else if (VECTORP (sequence))
110 XSETFASTINT (val, ASIZE (sequence));
111 else if (CHAR_TABLE_P (sequence))
112 XSETFASTINT (val, MAX_CHAR);
113 else if (BOOL_VECTOR_P (sequence))
114 XSETFASTINT (val, bool_vector_size (sequence));
115 else if (COMPILEDP (sequence))
116 XSETFASTINT (val, ASIZE (sequence) & PSEUDOVECTOR_SIZE_MASK);
117 else if (CONSP (sequence))
119 EMACS_INT i = 0;
123 ++i;
124 if ((i & (QUIT_COUNT_HEURISTIC - 1)) == 0)
126 if (MOST_POSITIVE_FIXNUM < i)
127 error ("List too long");
128 QUIT;
130 sequence = XCDR (sequence);
132 while (CONSP (sequence));
134 CHECK_LIST_END (sequence, sequence);
136 val = make_number (i);
138 else if (NILP (sequence))
139 XSETFASTINT (val, 0);
140 else
141 wrong_type_argument (Qsequencep, sequence);
143 return val;
146 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
147 doc: /* Return the length of a list, but avoid error or infinite loop.
148 This function never gets an error. If LIST is not really a list,
149 it returns 0. If LIST is circular, it returns a finite value
150 which is at least the number of distinct elements. */)
151 (Lisp_Object list)
153 Lisp_Object tail, halftail;
154 double hilen = 0;
155 uintmax_t lolen = 1;
157 if (! CONSP (list))
158 return make_number (0);
160 /* halftail is used to detect circular lists. */
161 for (tail = halftail = list; ; )
163 tail = XCDR (tail);
164 if (! CONSP (tail))
165 break;
166 if (EQ (tail, halftail))
167 break;
168 lolen++;
169 if ((lolen & 1) == 0)
171 halftail = XCDR (halftail);
172 if ((lolen & (QUIT_COUNT_HEURISTIC - 1)) == 0)
174 QUIT;
175 if (lolen == 0)
176 hilen += UINTMAX_MAX + 1.0;
181 /* If the length does not fit into a fixnum, return a float.
182 On all known practical machines this returns an upper bound on
183 the true length. */
184 return hilen ? make_float (hilen + lolen) : make_fixnum_or_float (lolen);
187 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
188 doc: /* Return the number of bytes in STRING.
189 If STRING is multibyte, this may be greater than the length of STRING. */)
190 (Lisp_Object string)
192 CHECK_STRING (string);
193 return make_number (SBYTES (string));
196 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
197 doc: /* Return t if two strings have identical contents.
198 Case is significant, but text properties are ignored.
199 Symbols are also allowed; their print names are used instead. */)
200 (register Lisp_Object s1, Lisp_Object s2)
202 if (SYMBOLP (s1))
203 s1 = SYMBOL_NAME (s1);
204 if (SYMBOLP (s2))
205 s2 = SYMBOL_NAME (s2);
206 CHECK_STRING (s1);
207 CHECK_STRING (s2);
209 if (SCHARS (s1) != SCHARS (s2)
210 || SBYTES (s1) != SBYTES (s2)
211 || memcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
212 return Qnil;
213 return Qt;
216 DEFUN ("compare-strings", Fcompare_strings, Scompare_strings, 6, 7, 0,
217 doc: /* Compare the contents of two strings, converting to multibyte if needed.
218 The arguments START1, END1, START2, and END2, if non-nil, are
219 positions specifying which parts of STR1 or STR2 to compare. In
220 string STR1, compare the part between START1 (inclusive) and END1
221 \(exclusive). If START1 is nil, it defaults to 0, the beginning of
222 the string; if END1 is nil, it defaults to the length of the string.
223 Likewise, in string STR2, compare the part between START2 and END2.
224 Like in `substring', negative values are counted from the end.
226 The strings are compared by the numeric values of their characters.
227 For instance, STR1 is "less than" STR2 if its first differing
228 character has a smaller numeric value. If IGNORE-CASE is non-nil,
229 characters are converted to upper-case before comparing them. Unibyte
230 strings are converted to multibyte for comparison.
232 The value is t if the strings (or specified portions) match.
233 If string STR1 is less, the value is a negative number N;
234 - 1 - N is the number of characters that match at the beginning.
235 If string STR1 is greater, the value is a positive number N;
236 N - 1 is the number of characters that match at the beginning. */)
237 (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2,
238 Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
240 ptrdiff_t from1, to1, from2, to2, i1, i1_byte, i2, i2_byte;
242 CHECK_STRING (str1);
243 CHECK_STRING (str2);
245 /* For backward compatibility, silently bring too-large positive end
246 values into range. */
247 if (INTEGERP (end1) && SCHARS (str1) < XINT (end1))
248 end1 = make_number (SCHARS (str1));
249 if (INTEGERP (end2) && SCHARS (str2) < XINT (end2))
250 end2 = make_number (SCHARS (str2));
252 validate_subarray (str1, start1, end1, SCHARS (str1), &from1, &to1);
253 validate_subarray (str2, start2, end2, SCHARS (str2), &from2, &to2);
255 i1 = from1;
256 i2 = from2;
258 i1_byte = string_char_to_byte (str1, i1);
259 i2_byte = string_char_to_byte (str2, i2);
261 while (i1 < to1 && i2 < to2)
263 /* When we find a mismatch, we must compare the
264 characters, not just the bytes. */
265 int c1, c2;
267 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c1, str1, i1, i1_byte);
268 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c2, str2, i2, i2_byte);
270 if (c1 == c2)
271 continue;
273 if (! NILP (ignore_case))
275 c1 = XINT (Fupcase (make_number (c1)));
276 c2 = XINT (Fupcase (make_number (c2)));
279 if (c1 == c2)
280 continue;
282 /* Note that I1 has already been incremented
283 past the character that we are comparing;
284 hence we don't add or subtract 1 here. */
285 if (c1 < c2)
286 return make_number (- i1 + from1);
287 else
288 return make_number (i1 - from1);
291 if (i1 < to1)
292 return make_number (i1 - from1 + 1);
293 if (i2 < to2)
294 return make_number (- i1 + from1 - 1);
296 return Qt;
299 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
300 doc: /* Return non-nil if STRING1 is less than STRING2 in lexicographic order.
301 Case is significant.
302 Symbols are also allowed; their print names are used instead. */)
303 (register Lisp_Object string1, Lisp_Object string2)
305 register ptrdiff_t end;
306 register ptrdiff_t i1, i1_byte, i2, i2_byte;
308 if (SYMBOLP (string1))
309 string1 = SYMBOL_NAME (string1);
310 if (SYMBOLP (string2))
311 string2 = SYMBOL_NAME (string2);
312 CHECK_STRING (string1);
313 CHECK_STRING (string2);
315 i1 = i1_byte = i2 = i2_byte = 0;
317 end = SCHARS (string1);
318 if (end > SCHARS (string2))
319 end = SCHARS (string2);
321 while (i1 < end)
323 /* When we find a mismatch, we must compare the
324 characters, not just the bytes. */
325 int c1, c2;
327 FETCH_STRING_CHAR_ADVANCE (c1, string1, i1, i1_byte);
328 FETCH_STRING_CHAR_ADVANCE (c2, string2, i2, i2_byte);
330 if (c1 != c2)
331 return c1 < c2 ? Qt : Qnil;
333 return i1 < SCHARS (string2) ? Qt : Qnil;
336 DEFUN ("string-version-lessp", Fstring_version_lessp,
337 Sstring_version_lessp, 2, 2, 0,
338 doc: /* Return non-nil if S1 is less than S2, as version strings.
340 This function compares version strings S1 and S2:
341 1) By prefix lexicographically.
342 2) Then by version (similarly to version comparison of Debian's dpkg).
343 Leading zeros in version numbers are ignored.
344 3) If both prefix and version are equal, compare as ordinary strings.
346 For example, \"foo2.png\" compares less than \"foo12.png\".
347 Case is significant.
348 Symbols are also allowed; their print names are used instead. */)
349 (Lisp_Object string1, Lisp_Object string2)
351 if (SYMBOLP (string1))
352 string1 = SYMBOL_NAME (string1);
353 if (SYMBOLP (string2))
354 string2 = SYMBOL_NAME (string2);
355 CHECK_STRING (string1);
356 CHECK_STRING (string2);
358 char *p1 = SSDATA (string1);
359 char *p2 = SSDATA (string2);
360 char *lim1 = p1 + SBYTES (string1);
361 char *lim2 = p2 + SBYTES (string2);
362 int cmp;
364 while ((cmp = filevercmp (p1, p2)) == 0)
366 /* If the strings are identical through their first null bytes,
367 skip past identical prefixes and try again. */
368 ptrdiff_t size = strlen (p1) + 1;
369 p1 += size;
370 p2 += size;
371 if (lim1 < p1)
372 return lim2 < p2 ? Qnil : Qt;
373 if (lim2 < p2)
374 return Qnil;
377 return cmp < 0 ? Qt : Qnil;
380 DEFUN ("string-collate-lessp", Fstring_collate_lessp, Sstring_collate_lessp, 2, 4, 0,
381 doc: /* Return t if first arg string is less than second in collation order.
382 Symbols are also allowed; their print names are used instead.
384 This function obeys the conventions for collation order in your
385 locale settings. For example, punctuation and whitespace characters
386 might be considered less significant for sorting:
388 \(sort \\='("11" "12" "1 1" "1 2" "1.1" "1.2") \\='string-collate-lessp)
389 => ("11" "1 1" "1.1" "12" "1 2" "1.2")
391 The optional argument LOCALE, a string, overrides the setting of your
392 current locale identifier for collation. The value is system
393 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
394 while it would be, e.g., \"enu_USA.1252\" on MS-Windows systems.
396 If IGNORE-CASE is non-nil, characters are converted to lower-case
397 before comparing them.
399 To emulate Unicode-compliant collation on MS-Windows systems,
400 bind `w32-collate-ignore-punctuation' to a non-nil value, since
401 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
403 If your system does not support a locale environment, this function
404 behaves like `string-lessp'. */)
405 (Lisp_Object s1, Lisp_Object s2, Lisp_Object locale, Lisp_Object ignore_case)
407 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
408 /* Check parameters. */
409 if (SYMBOLP (s1))
410 s1 = SYMBOL_NAME (s1);
411 if (SYMBOLP (s2))
412 s2 = SYMBOL_NAME (s2);
413 CHECK_STRING (s1);
414 CHECK_STRING (s2);
415 if (!NILP (locale))
416 CHECK_STRING (locale);
418 return (str_collate (s1, s2, locale, ignore_case) < 0) ? Qt : Qnil;
420 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
421 return Fstring_lessp (s1, s2);
422 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
425 DEFUN ("string-collate-equalp", Fstring_collate_equalp, Sstring_collate_equalp, 2, 4, 0,
426 doc: /* Return t if two strings have identical contents.
427 Symbols are also allowed; their print names are used instead.
429 This function obeys the conventions for collation order in your locale
430 settings. For example, characters with different coding points but
431 the same meaning might be considered as equal, like different grave
432 accent Unicode characters:
434 \(string-collate-equalp (string ?\\uFF40) (string ?\\u1FEF))
435 => t
437 The optional argument LOCALE, a string, overrides the setting of your
438 current locale identifier for collation. The value is system
439 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
440 while it would be \"enu_USA.1252\" on MS Windows systems.
442 If IGNORE-CASE is non-nil, characters are converted to lower-case
443 before comparing them.
445 To emulate Unicode-compliant collation on MS-Windows systems,
446 bind `w32-collate-ignore-punctuation' to a non-nil value, since
447 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
449 If your system does not support a locale environment, this function
450 behaves like `string-equal'.
452 Do NOT use this function to compare file names for equality. */)
453 (Lisp_Object s1, Lisp_Object s2, Lisp_Object locale, Lisp_Object ignore_case)
455 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
456 /* Check parameters. */
457 if (SYMBOLP (s1))
458 s1 = SYMBOL_NAME (s1);
459 if (SYMBOLP (s2))
460 s2 = SYMBOL_NAME (s2);
461 CHECK_STRING (s1);
462 CHECK_STRING (s2);
463 if (!NILP (locale))
464 CHECK_STRING (locale);
466 return (str_collate (s1, s2, locale, ignore_case) == 0) ? Qt : Qnil;
468 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
469 return Fstring_equal (s1, s2);
470 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
473 static Lisp_Object concat (ptrdiff_t nargs, Lisp_Object *args,
474 enum Lisp_Type target_type, bool last_special);
476 /* ARGSUSED */
477 Lisp_Object
478 concat2 (Lisp_Object s1, Lisp_Object s2)
480 return concat (2, ((Lisp_Object []) {s1, s2}), Lisp_String, 0);
483 /* ARGSUSED */
484 Lisp_Object
485 concat3 (Lisp_Object s1, Lisp_Object s2, Lisp_Object s3)
487 return concat (3, ((Lisp_Object []) {s1, s2, s3}), Lisp_String, 0);
490 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
491 doc: /* Concatenate all the arguments and make the result a list.
492 The result is a list whose elements are the elements of all the arguments.
493 Each argument may be a list, vector or string.
494 The last argument is not copied, just used as the tail of the new list.
495 usage: (append &rest SEQUENCES) */)
496 (ptrdiff_t nargs, Lisp_Object *args)
498 return concat (nargs, args, Lisp_Cons, 1);
501 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
502 doc: /* Concatenate all the arguments and make the result a string.
503 The result is a string whose elements are the elements of all the arguments.
504 Each argument may be a string or a list or vector of characters (integers).
505 usage: (concat &rest SEQUENCES) */)
506 (ptrdiff_t nargs, Lisp_Object *args)
508 return concat (nargs, args, Lisp_String, 0);
511 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
512 doc: /* Concatenate all the arguments and make the result a vector.
513 The result is a vector whose elements are the elements of all the arguments.
514 Each argument may be a list, vector or string.
515 usage: (vconcat &rest SEQUENCES) */)
516 (ptrdiff_t nargs, Lisp_Object *args)
518 return concat (nargs, args, Lisp_Vectorlike, 0);
522 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
523 doc: /* Return a copy of a list, vector, string or char-table.
524 The elements of a list or vector are not copied; they are shared
525 with the original. */)
526 (Lisp_Object arg)
528 if (NILP (arg)) return arg;
530 if (CHAR_TABLE_P (arg))
532 return copy_char_table (arg);
535 if (BOOL_VECTOR_P (arg))
537 EMACS_INT nbits = bool_vector_size (arg);
538 ptrdiff_t nbytes = bool_vector_bytes (nbits);
539 Lisp_Object val = make_uninit_bool_vector (nbits);
540 memcpy (bool_vector_data (val), bool_vector_data (arg), nbytes);
541 return val;
544 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
545 wrong_type_argument (Qsequencep, arg);
547 return concat (1, &arg, XTYPE (arg), 0);
550 /* This structure holds information of an argument of `concat' that is
551 a string and has text properties to be copied. */
552 struct textprop_rec
554 ptrdiff_t argnum; /* refer to ARGS (arguments of `concat') */
555 ptrdiff_t from; /* refer to ARGS[argnum] (argument string) */
556 ptrdiff_t to; /* refer to VAL (the target string) */
559 static Lisp_Object
560 concat (ptrdiff_t nargs, Lisp_Object *args,
561 enum Lisp_Type target_type, bool last_special)
563 Lisp_Object val;
564 Lisp_Object tail;
565 Lisp_Object this;
566 ptrdiff_t toindex;
567 ptrdiff_t toindex_byte = 0;
568 EMACS_INT result_len;
569 EMACS_INT result_len_byte;
570 ptrdiff_t argnum;
571 Lisp_Object last_tail;
572 Lisp_Object prev;
573 bool some_multibyte;
574 /* When we make a multibyte string, we can't copy text properties
575 while concatenating each string because the length of resulting
576 string can't be decided until we finish the whole concatenation.
577 So, we record strings that have text properties to be copied
578 here, and copy the text properties after the concatenation. */
579 struct textprop_rec *textprops = NULL;
580 /* Number of elements in textprops. */
581 ptrdiff_t num_textprops = 0;
582 USE_SAFE_ALLOCA;
584 tail = Qnil;
586 /* In append, the last arg isn't treated like the others */
587 if (last_special && nargs > 0)
589 nargs--;
590 last_tail = args[nargs];
592 else
593 last_tail = Qnil;
595 /* Check each argument. */
596 for (argnum = 0; argnum < nargs; argnum++)
598 this = args[argnum];
599 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
600 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
601 wrong_type_argument (Qsequencep, this);
604 /* Compute total length in chars of arguments in RESULT_LEN.
605 If desired output is a string, also compute length in bytes
606 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
607 whether the result should be a multibyte string. */
608 result_len_byte = 0;
609 result_len = 0;
610 some_multibyte = 0;
611 for (argnum = 0; argnum < nargs; argnum++)
613 EMACS_INT len;
614 this = args[argnum];
615 len = XFASTINT (Flength (this));
616 if (target_type == Lisp_String)
618 /* We must count the number of bytes needed in the string
619 as well as the number of characters. */
620 ptrdiff_t i;
621 Lisp_Object ch;
622 int c;
623 ptrdiff_t this_len_byte;
625 if (VECTORP (this) || COMPILEDP (this))
626 for (i = 0; i < len; i++)
628 ch = AREF (this, i);
629 CHECK_CHARACTER (ch);
630 c = XFASTINT (ch);
631 this_len_byte = CHAR_BYTES (c);
632 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
633 string_overflow ();
634 result_len_byte += this_len_byte;
635 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
636 some_multibyte = 1;
638 else if (BOOL_VECTOR_P (this) && bool_vector_size (this) > 0)
639 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
640 else if (CONSP (this))
641 for (; CONSP (this); this = XCDR (this))
643 ch = XCAR (this);
644 CHECK_CHARACTER (ch);
645 c = XFASTINT (ch);
646 this_len_byte = CHAR_BYTES (c);
647 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
648 string_overflow ();
649 result_len_byte += this_len_byte;
650 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
651 some_multibyte = 1;
653 else if (STRINGP (this))
655 if (STRING_MULTIBYTE (this))
657 some_multibyte = 1;
658 this_len_byte = SBYTES (this);
660 else
661 this_len_byte = count_size_as_multibyte (SDATA (this),
662 SCHARS (this));
663 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
664 string_overflow ();
665 result_len_byte += this_len_byte;
669 result_len += len;
670 if (MOST_POSITIVE_FIXNUM < result_len)
671 memory_full (SIZE_MAX);
674 if (! some_multibyte)
675 result_len_byte = result_len;
677 /* Create the output object. */
678 if (target_type == Lisp_Cons)
679 val = Fmake_list (make_number (result_len), Qnil);
680 else if (target_type == Lisp_Vectorlike)
681 val = Fmake_vector (make_number (result_len), Qnil);
682 else if (some_multibyte)
683 val = make_uninit_multibyte_string (result_len, result_len_byte);
684 else
685 val = make_uninit_string (result_len);
687 /* In `append', if all but last arg are nil, return last arg. */
688 if (target_type == Lisp_Cons && EQ (val, Qnil))
689 return last_tail;
691 /* Copy the contents of the args into the result. */
692 if (CONSP (val))
693 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
694 else
695 toindex = 0, toindex_byte = 0;
697 prev = Qnil;
698 if (STRINGP (val))
699 SAFE_NALLOCA (textprops, 1, nargs);
701 for (argnum = 0; argnum < nargs; argnum++)
703 Lisp_Object thislen;
704 ptrdiff_t thisleni = 0;
705 register ptrdiff_t thisindex = 0;
706 register ptrdiff_t thisindex_byte = 0;
708 this = args[argnum];
709 if (!CONSP (this))
710 thislen = Flength (this), thisleni = XINT (thislen);
712 /* Between strings of the same kind, copy fast. */
713 if (STRINGP (this) && STRINGP (val)
714 && STRING_MULTIBYTE (this) == some_multibyte)
716 ptrdiff_t thislen_byte = SBYTES (this);
718 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
719 if (string_intervals (this))
721 textprops[num_textprops].argnum = argnum;
722 textprops[num_textprops].from = 0;
723 textprops[num_textprops++].to = toindex;
725 toindex_byte += thislen_byte;
726 toindex += thisleni;
728 /* Copy a single-byte string to a multibyte string. */
729 else if (STRINGP (this) && STRINGP (val))
731 if (string_intervals (this))
733 textprops[num_textprops].argnum = argnum;
734 textprops[num_textprops].from = 0;
735 textprops[num_textprops++].to = toindex;
737 toindex_byte += copy_text (SDATA (this),
738 SDATA (val) + toindex_byte,
739 SCHARS (this), 0, 1);
740 toindex += thisleni;
742 else
743 /* Copy element by element. */
744 while (1)
746 register Lisp_Object elt;
748 /* Fetch next element of `this' arg into `elt', or break if
749 `this' is exhausted. */
750 if (NILP (this)) break;
751 if (CONSP (this))
752 elt = XCAR (this), this = XCDR (this);
753 else if (thisindex >= thisleni)
754 break;
755 else if (STRINGP (this))
757 int c;
758 if (STRING_MULTIBYTE (this))
759 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
760 thisindex,
761 thisindex_byte);
762 else
764 c = SREF (this, thisindex); thisindex++;
765 if (some_multibyte && !ASCII_CHAR_P (c))
766 c = BYTE8_TO_CHAR (c);
768 XSETFASTINT (elt, c);
770 else if (BOOL_VECTOR_P (this))
772 elt = bool_vector_ref (this, thisindex);
773 thisindex++;
775 else
777 elt = AREF (this, thisindex);
778 thisindex++;
781 /* Store this element into the result. */
782 if (toindex < 0)
784 XSETCAR (tail, elt);
785 prev = tail;
786 tail = XCDR (tail);
788 else if (VECTORP (val))
790 ASET (val, toindex, elt);
791 toindex++;
793 else
795 int c;
796 CHECK_CHARACTER (elt);
797 c = XFASTINT (elt);
798 if (some_multibyte)
799 toindex_byte += CHAR_STRING (c, SDATA (val) + toindex_byte);
800 else
801 SSET (val, toindex_byte++, c);
802 toindex++;
806 if (!NILP (prev))
807 XSETCDR (prev, last_tail);
809 if (num_textprops > 0)
811 Lisp_Object props;
812 ptrdiff_t last_to_end = -1;
814 for (argnum = 0; argnum < num_textprops; argnum++)
816 this = args[textprops[argnum].argnum];
817 props = text_property_list (this,
818 make_number (0),
819 make_number (SCHARS (this)),
820 Qnil);
821 /* If successive arguments have properties, be sure that the
822 value of `composition' property be the copy. */
823 if (last_to_end == textprops[argnum].to)
824 make_composition_value_copy (props);
825 add_text_properties_from_list (val, props,
826 make_number (textprops[argnum].to));
827 last_to_end = textprops[argnum].to + SCHARS (this);
831 SAFE_FREE ();
832 return val;
835 static Lisp_Object string_char_byte_cache_string;
836 static ptrdiff_t string_char_byte_cache_charpos;
837 static ptrdiff_t string_char_byte_cache_bytepos;
839 void
840 clear_string_char_byte_cache (void)
842 string_char_byte_cache_string = Qnil;
845 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
847 ptrdiff_t
848 string_char_to_byte (Lisp_Object string, ptrdiff_t char_index)
850 ptrdiff_t i_byte;
851 ptrdiff_t best_below, best_below_byte;
852 ptrdiff_t best_above, best_above_byte;
854 best_below = best_below_byte = 0;
855 best_above = SCHARS (string);
856 best_above_byte = SBYTES (string);
857 if (best_above == best_above_byte)
858 return char_index;
860 if (EQ (string, string_char_byte_cache_string))
862 if (string_char_byte_cache_charpos < char_index)
864 best_below = string_char_byte_cache_charpos;
865 best_below_byte = string_char_byte_cache_bytepos;
867 else
869 best_above = string_char_byte_cache_charpos;
870 best_above_byte = string_char_byte_cache_bytepos;
874 if (char_index - best_below < best_above - char_index)
876 unsigned char *p = SDATA (string) + best_below_byte;
878 while (best_below < char_index)
880 p += BYTES_BY_CHAR_HEAD (*p);
881 best_below++;
883 i_byte = p - SDATA (string);
885 else
887 unsigned char *p = SDATA (string) + best_above_byte;
889 while (best_above > char_index)
891 p--;
892 while (!CHAR_HEAD_P (*p)) p--;
893 best_above--;
895 i_byte = p - SDATA (string);
898 string_char_byte_cache_bytepos = i_byte;
899 string_char_byte_cache_charpos = char_index;
900 string_char_byte_cache_string = string;
902 return i_byte;
905 /* Return the character index corresponding to BYTE_INDEX in STRING. */
907 ptrdiff_t
908 string_byte_to_char (Lisp_Object string, ptrdiff_t byte_index)
910 ptrdiff_t i, i_byte;
911 ptrdiff_t best_below, best_below_byte;
912 ptrdiff_t best_above, best_above_byte;
914 best_below = best_below_byte = 0;
915 best_above = SCHARS (string);
916 best_above_byte = SBYTES (string);
917 if (best_above == best_above_byte)
918 return byte_index;
920 if (EQ (string, string_char_byte_cache_string))
922 if (string_char_byte_cache_bytepos < byte_index)
924 best_below = string_char_byte_cache_charpos;
925 best_below_byte = string_char_byte_cache_bytepos;
927 else
929 best_above = string_char_byte_cache_charpos;
930 best_above_byte = string_char_byte_cache_bytepos;
934 if (byte_index - best_below_byte < best_above_byte - byte_index)
936 unsigned char *p = SDATA (string) + best_below_byte;
937 unsigned char *pend = SDATA (string) + byte_index;
939 while (p < pend)
941 p += BYTES_BY_CHAR_HEAD (*p);
942 best_below++;
944 i = best_below;
945 i_byte = p - SDATA (string);
947 else
949 unsigned char *p = SDATA (string) + best_above_byte;
950 unsigned char *pbeg = SDATA (string) + byte_index;
952 while (p > pbeg)
954 p--;
955 while (!CHAR_HEAD_P (*p)) p--;
956 best_above--;
958 i = best_above;
959 i_byte = p - SDATA (string);
962 string_char_byte_cache_bytepos = i_byte;
963 string_char_byte_cache_charpos = i;
964 string_char_byte_cache_string = string;
966 return i;
969 /* Convert STRING to a multibyte string. */
971 static Lisp_Object
972 string_make_multibyte (Lisp_Object string)
974 unsigned char *buf;
975 ptrdiff_t nbytes;
976 Lisp_Object ret;
977 USE_SAFE_ALLOCA;
979 if (STRING_MULTIBYTE (string))
980 return string;
982 nbytes = count_size_as_multibyte (SDATA (string),
983 SCHARS (string));
984 /* If all the chars are ASCII, they won't need any more bytes
985 once converted. In that case, we can return STRING itself. */
986 if (nbytes == SBYTES (string))
987 return string;
989 buf = SAFE_ALLOCA (nbytes);
990 copy_text (SDATA (string), buf, SBYTES (string),
991 0, 1);
993 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
994 SAFE_FREE ();
996 return ret;
1000 /* Convert STRING (if unibyte) to a multibyte string without changing
1001 the number of characters. Characters 0200 trough 0237 are
1002 converted to eight-bit characters. */
1004 Lisp_Object
1005 string_to_multibyte (Lisp_Object string)
1007 unsigned char *buf;
1008 ptrdiff_t nbytes;
1009 Lisp_Object ret;
1010 USE_SAFE_ALLOCA;
1012 if (STRING_MULTIBYTE (string))
1013 return string;
1015 nbytes = count_size_as_multibyte (SDATA (string), SBYTES (string));
1016 /* If all the chars are ASCII, they won't need any more bytes once
1017 converted. */
1018 if (nbytes == SBYTES (string))
1019 return make_multibyte_string (SSDATA (string), nbytes, nbytes);
1021 buf = SAFE_ALLOCA (nbytes);
1022 memcpy (buf, SDATA (string), SBYTES (string));
1023 str_to_multibyte (buf, nbytes, SBYTES (string));
1025 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
1026 SAFE_FREE ();
1028 return ret;
1032 /* Convert STRING to a single-byte string. */
1034 Lisp_Object
1035 string_make_unibyte (Lisp_Object string)
1037 ptrdiff_t nchars;
1038 unsigned char *buf;
1039 Lisp_Object ret;
1040 USE_SAFE_ALLOCA;
1042 if (! STRING_MULTIBYTE (string))
1043 return string;
1045 nchars = SCHARS (string);
1047 buf = SAFE_ALLOCA (nchars);
1048 copy_text (SDATA (string), buf, SBYTES (string),
1049 1, 0);
1051 ret = make_unibyte_string ((char *) buf, nchars);
1052 SAFE_FREE ();
1054 return ret;
1057 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
1058 1, 1, 0,
1059 doc: /* Return the multibyte equivalent of STRING.
1060 If STRING is unibyte and contains non-ASCII characters, the function
1061 `unibyte-char-to-multibyte' is used to convert each unibyte character
1062 to a multibyte character. In this case, the returned string is a
1063 newly created string with no text properties. If STRING is multibyte
1064 or entirely ASCII, it is returned unchanged. In particular, when
1065 STRING is unibyte and entirely ASCII, the returned string is unibyte.
1066 \(When the characters are all ASCII, Emacs primitives will treat the
1067 string the same way whether it is unibyte or multibyte.) */)
1068 (Lisp_Object string)
1070 CHECK_STRING (string);
1072 return string_make_multibyte (string);
1075 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
1076 1, 1, 0,
1077 doc: /* Return the unibyte equivalent of STRING.
1078 Multibyte character codes are converted to unibyte according to
1079 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
1080 If the lookup in the translation table fails, this function takes just
1081 the low 8 bits of each character. */)
1082 (Lisp_Object string)
1084 CHECK_STRING (string);
1086 return string_make_unibyte (string);
1089 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
1090 1, 1, 0,
1091 doc: /* Return a unibyte string with the same individual bytes as STRING.
1092 If STRING is unibyte, the result is STRING itself.
1093 Otherwise it is a newly created string, with no text properties.
1094 If STRING is multibyte and contains a character of charset
1095 `eight-bit', it is converted to the corresponding single byte. */)
1096 (Lisp_Object string)
1098 CHECK_STRING (string);
1100 if (STRING_MULTIBYTE (string))
1102 unsigned char *str = (unsigned char *) xlispstrdup (string);
1103 ptrdiff_t bytes = str_as_unibyte (str, SBYTES (string));
1105 string = make_unibyte_string ((char *) str, bytes);
1106 xfree (str);
1108 return string;
1111 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1112 1, 1, 0,
1113 doc: /* Return a multibyte string with the same individual bytes as STRING.
1114 If STRING is multibyte, the result is STRING itself.
1115 Otherwise it is a newly created string, with no text properties.
1117 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1118 part of a correct utf-8 sequence), it is converted to the corresponding
1119 multibyte character of charset `eight-bit'.
1120 See also `string-to-multibyte'.
1122 Beware, this often doesn't really do what you think it does.
1123 It is similar to (decode-coding-string STRING \\='utf-8-emacs).
1124 If you're not sure, whether to use `string-as-multibyte' or
1125 `string-to-multibyte', use `string-to-multibyte'. */)
1126 (Lisp_Object string)
1128 CHECK_STRING (string);
1130 if (! STRING_MULTIBYTE (string))
1132 Lisp_Object new_string;
1133 ptrdiff_t nchars, nbytes;
1135 parse_str_as_multibyte (SDATA (string),
1136 SBYTES (string),
1137 &nchars, &nbytes);
1138 new_string = make_uninit_multibyte_string (nchars, nbytes);
1139 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1140 if (nbytes != SBYTES (string))
1141 str_as_multibyte (SDATA (new_string), nbytes,
1142 SBYTES (string), NULL);
1143 string = new_string;
1144 set_string_intervals (string, NULL);
1146 return string;
1149 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1150 1, 1, 0,
1151 doc: /* Return a multibyte string with the same individual chars as STRING.
1152 If STRING is multibyte, the result is STRING itself.
1153 Otherwise it is a newly created string, with no text properties.
1155 If STRING is unibyte and contains an 8-bit byte, it is converted to
1156 the corresponding multibyte character of charset `eight-bit'.
1158 This differs from `string-as-multibyte' by converting each byte of a correct
1159 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1160 correct sequence. */)
1161 (Lisp_Object string)
1163 CHECK_STRING (string);
1165 return string_to_multibyte (string);
1168 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1169 1, 1, 0,
1170 doc: /* Return a unibyte string with the same individual chars as STRING.
1171 If STRING is unibyte, the result is STRING itself.
1172 Otherwise it is a newly created string, with no text properties,
1173 where each `eight-bit' character is converted to the corresponding byte.
1174 If STRING contains a non-ASCII, non-`eight-bit' character,
1175 an error is signaled. */)
1176 (Lisp_Object string)
1178 CHECK_STRING (string);
1180 if (STRING_MULTIBYTE (string))
1182 ptrdiff_t chars = SCHARS (string);
1183 unsigned char *str = xmalloc (chars);
1184 ptrdiff_t converted = str_to_unibyte (SDATA (string), str, chars);
1186 if (converted < chars)
1187 error ("Can't convert the %"pD"dth character to unibyte", converted);
1188 string = make_unibyte_string ((char *) str, chars);
1189 xfree (str);
1191 return string;
1195 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1196 doc: /* Return a copy of ALIST.
1197 This is an alist which represents the same mapping from objects to objects,
1198 but does not share the alist structure with ALIST.
1199 The objects mapped (cars and cdrs of elements of the alist)
1200 are shared, however.
1201 Elements of ALIST that are not conses are also shared. */)
1202 (Lisp_Object alist)
1204 register Lisp_Object tem;
1206 CHECK_LIST (alist);
1207 if (NILP (alist))
1208 return alist;
1209 alist = concat (1, &alist, Lisp_Cons, 0);
1210 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1212 register Lisp_Object car;
1213 car = XCAR (tem);
1215 if (CONSP (car))
1216 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1218 return alist;
1221 /* Check that ARRAY can have a valid subarray [FROM..TO),
1222 given that its size is SIZE.
1223 If FROM is nil, use 0; if TO is nil, use SIZE.
1224 Count negative values backwards from the end.
1225 Set *IFROM and *ITO to the two indexes used. */
1227 void
1228 validate_subarray (Lisp_Object array, Lisp_Object from, Lisp_Object to,
1229 ptrdiff_t size, ptrdiff_t *ifrom, ptrdiff_t *ito)
1231 EMACS_INT f, t;
1233 if (INTEGERP (from))
1235 f = XINT (from);
1236 if (f < 0)
1237 f += size;
1239 else if (NILP (from))
1240 f = 0;
1241 else
1242 wrong_type_argument (Qintegerp, from);
1244 if (INTEGERP (to))
1246 t = XINT (to);
1247 if (t < 0)
1248 t += size;
1250 else if (NILP (to))
1251 t = size;
1252 else
1253 wrong_type_argument (Qintegerp, to);
1255 if (! (0 <= f && f <= t && t <= size))
1256 args_out_of_range_3 (array, from, to);
1258 *ifrom = f;
1259 *ito = t;
1262 DEFUN ("substring", Fsubstring, Ssubstring, 1, 3, 0,
1263 doc: /* Return a new string whose contents are a substring of STRING.
1264 The returned string consists of the characters between index FROM
1265 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1266 zero-indexed: 0 means the first character of STRING. Negative values
1267 are counted from the end of STRING. If TO is nil, the substring runs
1268 to the end of STRING.
1270 The STRING argument may also be a vector. In that case, the return
1271 value is a new vector that contains the elements between index FROM
1272 \(inclusive) and index TO (exclusive) of that vector argument.
1274 With one argument, just copy STRING (with properties, if any). */)
1275 (Lisp_Object string, Lisp_Object from, Lisp_Object to)
1277 Lisp_Object res;
1278 ptrdiff_t size, ifrom, ito;
1280 size = CHECK_VECTOR_OR_STRING (string);
1281 validate_subarray (string, from, to, size, &ifrom, &ito);
1283 if (STRINGP (string))
1285 ptrdiff_t from_byte
1286 = !ifrom ? 0 : string_char_to_byte (string, ifrom);
1287 ptrdiff_t to_byte
1288 = ito == size ? SBYTES (string) : string_char_to_byte (string, ito);
1289 res = make_specified_string (SSDATA (string) + from_byte,
1290 ito - ifrom, to_byte - from_byte,
1291 STRING_MULTIBYTE (string));
1292 copy_text_properties (make_number (ifrom), make_number (ito),
1293 string, make_number (0), res, Qnil);
1295 else
1296 res = Fvector (ito - ifrom, aref_addr (string, ifrom));
1298 return res;
1302 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1303 doc: /* Return a substring of STRING, without text properties.
1304 It starts at index FROM and ends before TO.
1305 TO may be nil or omitted; then the substring runs to the end of STRING.
1306 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1307 If FROM or TO is negative, it counts from the end.
1309 With one argument, just copy STRING without its properties. */)
1310 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1312 ptrdiff_t from_char, to_char, from_byte, to_byte, size;
1314 CHECK_STRING (string);
1316 size = SCHARS (string);
1317 validate_subarray (string, from, to, size, &from_char, &to_char);
1319 from_byte = !from_char ? 0 : string_char_to_byte (string, from_char);
1320 to_byte =
1321 to_char == size ? SBYTES (string) : string_char_to_byte (string, to_char);
1322 return make_specified_string (SSDATA (string) + from_byte,
1323 to_char - from_char, to_byte - from_byte,
1324 STRING_MULTIBYTE (string));
1327 /* Extract a substring of STRING, giving start and end positions
1328 both in characters and in bytes. */
1330 Lisp_Object
1331 substring_both (Lisp_Object string, ptrdiff_t from, ptrdiff_t from_byte,
1332 ptrdiff_t to, ptrdiff_t to_byte)
1334 Lisp_Object res;
1335 ptrdiff_t size = CHECK_VECTOR_OR_STRING (string);
1337 if (!(0 <= from && from <= to && to <= size))
1338 args_out_of_range_3 (string, make_number (from), make_number (to));
1340 if (STRINGP (string))
1342 res = make_specified_string (SSDATA (string) + from_byte,
1343 to - from, to_byte - from_byte,
1344 STRING_MULTIBYTE (string));
1345 copy_text_properties (make_number (from), make_number (to),
1346 string, make_number (0), res, Qnil);
1348 else
1349 res = Fvector (to - from, aref_addr (string, from));
1351 return res;
1354 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1355 doc: /* Take cdr N times on LIST, return the result. */)
1356 (Lisp_Object n, Lisp_Object list)
1358 EMACS_INT i, num;
1359 CHECK_NUMBER (n);
1360 num = XINT (n);
1361 for (i = 0; i < num && !NILP (list); i++)
1363 QUIT;
1364 CHECK_LIST_CONS (list, list);
1365 list = XCDR (list);
1367 return list;
1370 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1371 doc: /* Return the Nth element of LIST.
1372 N counts from zero. If LIST is not that long, nil is returned. */)
1373 (Lisp_Object n, Lisp_Object list)
1375 return Fcar (Fnthcdr (n, list));
1378 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1379 doc: /* Return element of SEQUENCE at index N. */)
1380 (register Lisp_Object sequence, Lisp_Object n)
1382 CHECK_NUMBER (n);
1383 if (CONSP (sequence) || NILP (sequence))
1384 return Fcar (Fnthcdr (n, sequence));
1386 /* Faref signals a "not array" error, so check here. */
1387 CHECK_ARRAY (sequence, Qsequencep);
1388 return Faref (sequence, n);
1391 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1392 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1393 The value is actually the tail of LIST whose car is ELT. */)
1394 (register Lisp_Object elt, Lisp_Object list)
1396 register Lisp_Object tail;
1397 for (tail = list; !NILP (tail); tail = XCDR (tail))
1399 register Lisp_Object tem;
1400 CHECK_LIST_CONS (tail, list);
1401 tem = XCAR (tail);
1402 if (! NILP (Fequal (elt, tem)))
1403 return tail;
1404 QUIT;
1406 return Qnil;
1409 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1410 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1411 The value is actually the tail of LIST whose car is ELT. */)
1412 (register Lisp_Object elt, Lisp_Object list)
1414 while (1)
1416 if (!CONSP (list) || EQ (XCAR (list), elt))
1417 break;
1419 list = XCDR (list);
1420 if (!CONSP (list) || EQ (XCAR (list), elt))
1421 break;
1423 list = XCDR (list);
1424 if (!CONSP (list) || EQ (XCAR (list), elt))
1425 break;
1427 list = XCDR (list);
1428 QUIT;
1431 CHECK_LIST (list);
1432 return list;
1435 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1436 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1437 The value is actually the tail of LIST whose car is ELT. */)
1438 (register Lisp_Object elt, Lisp_Object list)
1440 register Lisp_Object tail;
1442 if (!FLOATP (elt))
1443 return Fmemq (elt, list);
1445 for (tail = list; !NILP (tail); tail = XCDR (tail))
1447 register Lisp_Object tem;
1448 CHECK_LIST_CONS (tail, list);
1449 tem = XCAR (tail);
1450 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0, Qnil))
1451 return tail;
1452 QUIT;
1454 return Qnil;
1457 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1458 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1459 The value is actually the first element of LIST whose car is KEY.
1460 Elements of LIST that are not conses are ignored. */)
1461 (Lisp_Object key, Lisp_Object list)
1463 while (1)
1465 if (!CONSP (list)
1466 || (CONSP (XCAR (list))
1467 && EQ (XCAR (XCAR (list)), key)))
1468 break;
1470 list = XCDR (list);
1471 if (!CONSP (list)
1472 || (CONSP (XCAR (list))
1473 && EQ (XCAR (XCAR (list)), key)))
1474 break;
1476 list = XCDR (list);
1477 if (!CONSP (list)
1478 || (CONSP (XCAR (list))
1479 && EQ (XCAR (XCAR (list)), key)))
1480 break;
1482 list = XCDR (list);
1483 QUIT;
1486 return CAR (list);
1489 /* Like Fassq but never report an error and do not allow quits.
1490 Use only on lists known never to be circular. */
1492 Lisp_Object
1493 assq_no_quit (Lisp_Object key, Lisp_Object list)
1495 while (CONSP (list)
1496 && (!CONSP (XCAR (list))
1497 || !EQ (XCAR (XCAR (list)), key)))
1498 list = XCDR (list);
1500 return CAR_SAFE (list);
1503 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1504 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1505 The value is actually the first element of LIST whose car equals KEY. */)
1506 (Lisp_Object key, Lisp_Object list)
1508 Lisp_Object car;
1510 while (1)
1512 if (!CONSP (list)
1513 || (CONSP (XCAR (list))
1514 && (car = XCAR (XCAR (list)),
1515 EQ (car, key) || !NILP (Fequal (car, key)))))
1516 break;
1518 list = XCDR (list);
1519 if (!CONSP (list)
1520 || (CONSP (XCAR (list))
1521 && (car = XCAR (XCAR (list)),
1522 EQ (car, key) || !NILP (Fequal (car, key)))))
1523 break;
1525 list = XCDR (list);
1526 if (!CONSP (list)
1527 || (CONSP (XCAR (list))
1528 && (car = XCAR (XCAR (list)),
1529 EQ (car, key) || !NILP (Fequal (car, key)))))
1530 break;
1532 list = XCDR (list);
1533 QUIT;
1536 return CAR (list);
1539 /* Like Fassoc but never report an error and do not allow quits.
1540 Use only on lists known never to be circular. */
1542 Lisp_Object
1543 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1545 while (CONSP (list)
1546 && (!CONSP (XCAR (list))
1547 || (!EQ (XCAR (XCAR (list)), key)
1548 && NILP (Fequal (XCAR (XCAR (list)), key)))))
1549 list = XCDR (list);
1551 return CONSP (list) ? XCAR (list) : Qnil;
1554 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1555 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1556 The value is actually the first element of LIST whose cdr is KEY. */)
1557 (register Lisp_Object key, Lisp_Object list)
1559 while (1)
1561 if (!CONSP (list)
1562 || (CONSP (XCAR (list))
1563 && EQ (XCDR (XCAR (list)), key)))
1564 break;
1566 list = XCDR (list);
1567 if (!CONSP (list)
1568 || (CONSP (XCAR (list))
1569 && EQ (XCDR (XCAR (list)), key)))
1570 break;
1572 list = XCDR (list);
1573 if (!CONSP (list)
1574 || (CONSP (XCAR (list))
1575 && EQ (XCDR (XCAR (list)), key)))
1576 break;
1578 list = XCDR (list);
1579 QUIT;
1582 return CAR (list);
1585 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1586 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1587 The value is actually the first element of LIST whose cdr equals KEY. */)
1588 (Lisp_Object key, Lisp_Object list)
1590 Lisp_Object cdr;
1592 while (1)
1594 if (!CONSP (list)
1595 || (CONSP (XCAR (list))
1596 && (cdr = XCDR (XCAR (list)),
1597 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1598 break;
1600 list = XCDR (list);
1601 if (!CONSP (list)
1602 || (CONSP (XCAR (list))
1603 && (cdr = XCDR (XCAR (list)),
1604 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1605 break;
1607 list = XCDR (list);
1608 if (!CONSP (list)
1609 || (CONSP (XCAR (list))
1610 && (cdr = XCDR (XCAR (list)),
1611 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1612 break;
1614 list = XCDR (list);
1615 QUIT;
1618 return CAR (list);
1621 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1622 doc: /* Delete members of LIST which are `eq' to ELT, and return the result.
1623 More precisely, this function skips any members `eq' to ELT at the
1624 front of LIST, then removes members `eq' to ELT from the remaining
1625 sublist by modifying its list structure, then returns the resulting
1626 list.
1628 Write `(setq foo (delq element foo))' to be sure of correctly changing
1629 the value of a list `foo'. See also `remq', which does not modify the
1630 argument. */)
1631 (register Lisp_Object elt, Lisp_Object list)
1633 Lisp_Object tail, tortoise, prev = Qnil;
1634 bool skip;
1636 FOR_EACH_TAIL (tail, list, tortoise, skip)
1638 Lisp_Object tem = XCAR (tail);
1639 if (EQ (elt, tem))
1641 if (NILP (prev))
1642 list = XCDR (tail);
1643 else
1644 Fsetcdr (prev, XCDR (tail));
1646 else
1647 prev = tail;
1649 return list;
1652 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1653 doc: /* Delete members of SEQ which are `equal' to ELT, and return the result.
1654 SEQ must be a sequence (i.e. a list, a vector, or a string).
1655 The return value is a sequence of the same type.
1657 If SEQ is a list, this behaves like `delq', except that it compares
1658 with `equal' instead of `eq'. In particular, it may remove elements
1659 by altering the list structure.
1661 If SEQ is not a list, deletion is never performed destructively;
1662 instead this function creates and returns a new vector or string.
1664 Write `(setq foo (delete element foo))' to be sure of correctly
1665 changing the value of a sequence `foo'. */)
1666 (Lisp_Object elt, Lisp_Object seq)
1668 if (VECTORP (seq))
1670 ptrdiff_t i, n;
1672 for (i = n = 0; i < ASIZE (seq); ++i)
1673 if (NILP (Fequal (AREF (seq, i), elt)))
1674 ++n;
1676 if (n != ASIZE (seq))
1678 struct Lisp_Vector *p = allocate_vector (n);
1680 for (i = n = 0; i < ASIZE (seq); ++i)
1681 if (NILP (Fequal (AREF (seq, i), elt)))
1682 p->contents[n++] = AREF (seq, i);
1684 XSETVECTOR (seq, p);
1687 else if (STRINGP (seq))
1689 ptrdiff_t i, ibyte, nchars, nbytes, cbytes;
1690 int c;
1692 for (i = nchars = nbytes = ibyte = 0;
1693 i < SCHARS (seq);
1694 ++i, ibyte += cbytes)
1696 if (STRING_MULTIBYTE (seq))
1698 c = STRING_CHAR (SDATA (seq) + ibyte);
1699 cbytes = CHAR_BYTES (c);
1701 else
1703 c = SREF (seq, i);
1704 cbytes = 1;
1707 if (!INTEGERP (elt) || c != XINT (elt))
1709 ++nchars;
1710 nbytes += cbytes;
1714 if (nchars != SCHARS (seq))
1716 Lisp_Object tem;
1718 tem = make_uninit_multibyte_string (nchars, nbytes);
1719 if (!STRING_MULTIBYTE (seq))
1720 STRING_SET_UNIBYTE (tem);
1722 for (i = nchars = nbytes = ibyte = 0;
1723 i < SCHARS (seq);
1724 ++i, ibyte += cbytes)
1726 if (STRING_MULTIBYTE (seq))
1728 c = STRING_CHAR (SDATA (seq) + ibyte);
1729 cbytes = CHAR_BYTES (c);
1731 else
1733 c = SREF (seq, i);
1734 cbytes = 1;
1737 if (!INTEGERP (elt) || c != XINT (elt))
1739 unsigned char *from = SDATA (seq) + ibyte;
1740 unsigned char *to = SDATA (tem) + nbytes;
1741 ptrdiff_t n;
1743 ++nchars;
1744 nbytes += cbytes;
1746 for (n = cbytes; n--; )
1747 *to++ = *from++;
1751 seq = tem;
1754 else
1756 Lisp_Object tail, prev;
1758 for (tail = seq, prev = Qnil; !NILP (tail); tail = XCDR (tail))
1760 CHECK_LIST_CONS (tail, seq);
1762 if (!NILP (Fequal (elt, XCAR (tail))))
1764 if (NILP (prev))
1765 seq = XCDR (tail);
1766 else
1767 Fsetcdr (prev, XCDR (tail));
1769 else
1770 prev = tail;
1771 QUIT;
1775 return seq;
1778 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1779 doc: /* Reverse order of items in a list, vector or string SEQ.
1780 If SEQ is a list, it should be nil-terminated.
1781 This function may destructively modify SEQ to produce the value. */)
1782 (Lisp_Object seq)
1784 if (NILP (seq))
1785 return seq;
1786 else if (STRINGP (seq))
1787 return Freverse (seq);
1788 else if (CONSP (seq))
1790 Lisp_Object prev, tail, next;
1792 for (prev = Qnil, tail = seq; !NILP (tail); tail = next)
1794 QUIT;
1795 CHECK_LIST_CONS (tail, tail);
1796 next = XCDR (tail);
1797 Fsetcdr (tail, prev);
1798 prev = tail;
1800 seq = prev;
1802 else if (VECTORP (seq))
1804 ptrdiff_t i, size = ASIZE (seq);
1806 for (i = 0; i < size / 2; i++)
1808 Lisp_Object tem = AREF (seq, i);
1809 ASET (seq, i, AREF (seq, size - i - 1));
1810 ASET (seq, size - i - 1, tem);
1813 else if (BOOL_VECTOR_P (seq))
1815 ptrdiff_t i, size = bool_vector_size (seq);
1817 for (i = 0; i < size / 2; i++)
1819 bool tem = bool_vector_bitref (seq, i);
1820 bool_vector_set (seq, i, bool_vector_bitref (seq, size - i - 1));
1821 bool_vector_set (seq, size - i - 1, tem);
1824 else
1825 wrong_type_argument (Qarrayp, seq);
1826 return seq;
1829 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1830 doc: /* Return the reversed copy of list, vector, or string SEQ.
1831 See also the function `nreverse', which is used more often. */)
1832 (Lisp_Object seq)
1834 Lisp_Object new;
1836 if (NILP (seq))
1837 return Qnil;
1838 else if (CONSP (seq))
1840 for (new = Qnil; CONSP (seq); seq = XCDR (seq))
1842 QUIT;
1843 new = Fcons (XCAR (seq), new);
1845 CHECK_LIST_END (seq, seq);
1847 else if (VECTORP (seq))
1849 ptrdiff_t i, size = ASIZE (seq);
1851 new = make_uninit_vector (size);
1852 for (i = 0; i < size; i++)
1853 ASET (new, i, AREF (seq, size - i - 1));
1855 else if (BOOL_VECTOR_P (seq))
1857 ptrdiff_t i;
1858 EMACS_INT nbits = bool_vector_size (seq);
1860 new = make_uninit_bool_vector (nbits);
1861 for (i = 0; i < nbits; i++)
1862 bool_vector_set (new, i, bool_vector_bitref (seq, nbits - i - 1));
1864 else if (STRINGP (seq))
1866 ptrdiff_t size = SCHARS (seq), bytes = SBYTES (seq);
1868 if (size == bytes)
1870 ptrdiff_t i;
1872 new = make_uninit_string (size);
1873 for (i = 0; i < size; i++)
1874 SSET (new, i, SREF (seq, size - i - 1));
1876 else
1878 unsigned char *p, *q;
1880 new = make_uninit_multibyte_string (size, bytes);
1881 p = SDATA (seq), q = SDATA (new) + bytes;
1882 while (q > SDATA (new))
1884 int ch, len;
1886 ch = STRING_CHAR_AND_LENGTH (p, len);
1887 p += len, q -= len;
1888 CHAR_STRING (ch, q);
1892 else
1893 wrong_type_argument (Qsequencep, seq);
1894 return new;
1897 /* Sort LIST using PREDICATE, preserving original order of elements
1898 considered as equal. */
1900 static Lisp_Object
1901 sort_list (Lisp_Object list, Lisp_Object predicate)
1903 Lisp_Object front, back;
1904 Lisp_Object len, tem;
1905 EMACS_INT length;
1907 front = list;
1908 len = Flength (list);
1909 length = XINT (len);
1910 if (length < 2)
1911 return list;
1913 XSETINT (len, (length / 2) - 1);
1914 tem = Fnthcdr (len, list);
1915 back = Fcdr (tem);
1916 Fsetcdr (tem, Qnil);
1918 front = Fsort (front, predicate);
1919 back = Fsort (back, predicate);
1920 return merge (front, back, predicate);
1923 /* Using PRED to compare, return whether A and B are in order.
1924 Compare stably when A appeared before B in the input. */
1925 static bool
1926 inorder (Lisp_Object pred, Lisp_Object a, Lisp_Object b)
1928 return NILP (call2 (pred, b, a));
1931 /* Using PRED to compare, merge from ALEN-length A and BLEN-length B
1932 into DEST. Argument arrays must be nonempty and must not overlap,
1933 except that B might be the last part of DEST. */
1934 static void
1935 merge_vectors (Lisp_Object pred,
1936 ptrdiff_t alen, Lisp_Object const a[restrict VLA_ELEMS (alen)],
1937 ptrdiff_t blen, Lisp_Object const b[VLA_ELEMS (blen)],
1938 Lisp_Object dest[VLA_ELEMS (alen + blen)])
1940 eassume (0 < alen && 0 < blen);
1941 Lisp_Object const *alim = a + alen;
1942 Lisp_Object const *blim = b + blen;
1944 while (true)
1946 if (inorder (pred, a[0], b[0]))
1948 *dest++ = *a++;
1949 if (a == alim)
1951 if (dest != b)
1952 memcpy (dest, b, (blim - b) * sizeof *dest);
1953 return;
1956 else
1958 *dest++ = *b++;
1959 if (b == blim)
1961 memcpy (dest, a, (alim - a) * sizeof *dest);
1962 return;
1968 /* Using PRED to compare, sort LEN-length VEC in place, using TMP for
1969 temporary storage. LEN must be at least 2. */
1970 static void
1971 sort_vector_inplace (Lisp_Object pred, ptrdiff_t len,
1972 Lisp_Object vec[restrict VLA_ELEMS (len)],
1973 Lisp_Object tmp[restrict VLA_ELEMS (len >> 1)])
1975 eassume (2 <= len);
1976 ptrdiff_t halflen = len >> 1;
1977 sort_vector_copy (pred, halflen, vec, tmp);
1978 if (1 < len - halflen)
1979 sort_vector_inplace (pred, len - halflen, vec + halflen, vec);
1980 merge_vectors (pred, halflen, tmp, len - halflen, vec + halflen, vec);
1983 /* Using PRED to compare, sort from LEN-length SRC into DST.
1984 Len must be positive. */
1985 static void
1986 sort_vector_copy (Lisp_Object pred, ptrdiff_t len,
1987 Lisp_Object src[restrict VLA_ELEMS (len)],
1988 Lisp_Object dest[restrict VLA_ELEMS (len)])
1990 eassume (0 < len);
1991 ptrdiff_t halflen = len >> 1;
1992 if (halflen < 1)
1993 dest[0] = src[0];
1994 else
1996 if (1 < halflen)
1997 sort_vector_inplace (pred, halflen, src, dest);
1998 if (1 < len - halflen)
1999 sort_vector_inplace (pred, len - halflen, src + halflen, dest);
2000 merge_vectors (pred, halflen, src, len - halflen, src + halflen, dest);
2004 /* Sort VECTOR in place using PREDICATE, preserving original order of
2005 elements considered as equal. */
2007 static void
2008 sort_vector (Lisp_Object vector, Lisp_Object predicate)
2010 ptrdiff_t len = ASIZE (vector);
2011 if (len < 2)
2012 return;
2013 ptrdiff_t halflen = len >> 1;
2014 Lisp_Object *tmp;
2015 USE_SAFE_ALLOCA;
2016 SAFE_ALLOCA_LISP (tmp, halflen);
2017 for (ptrdiff_t i = 0; i < halflen; i++)
2018 tmp[i] = make_number (0);
2019 sort_vector_inplace (predicate, len, XVECTOR (vector)->contents, tmp);
2020 SAFE_FREE ();
2023 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
2024 doc: /* Sort SEQ, stably, comparing elements using PREDICATE.
2025 Returns the sorted sequence. SEQ should be a list or vector. SEQ is
2026 modified by side effects. PREDICATE is called with two elements of
2027 SEQ, and should return non-nil if the first element should sort before
2028 the second. */)
2029 (Lisp_Object seq, Lisp_Object predicate)
2031 if (CONSP (seq))
2032 seq = sort_list (seq, predicate);
2033 else if (VECTORP (seq))
2034 sort_vector (seq, predicate);
2035 else if (!NILP (seq))
2036 wrong_type_argument (Qsequencep, seq);
2037 return seq;
2040 Lisp_Object
2041 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
2043 Lisp_Object l1 = org_l1;
2044 Lisp_Object l2 = org_l2;
2045 Lisp_Object tail = Qnil;
2046 Lisp_Object value = Qnil;
2048 while (1)
2050 if (NILP (l1))
2052 if (NILP (tail))
2053 return l2;
2054 Fsetcdr (tail, l2);
2055 return value;
2057 if (NILP (l2))
2059 if (NILP (tail))
2060 return l1;
2061 Fsetcdr (tail, l1);
2062 return value;
2065 Lisp_Object tem;
2066 if (inorder (pred, Fcar (l1), Fcar (l2)))
2068 tem = l1;
2069 l1 = Fcdr (l1);
2070 org_l1 = l1;
2072 else
2074 tem = l2;
2075 l2 = Fcdr (l2);
2076 org_l2 = l2;
2078 if (NILP (tail))
2079 value = tem;
2080 else
2081 Fsetcdr (tail, tem);
2082 tail = tem;
2087 /* This does not check for quits. That is safe since it must terminate. */
2089 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
2090 doc: /* Extract a value from a property list.
2091 PLIST is a property list, which is a list of the form
2092 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2093 corresponding to the given PROP, or nil if PROP is not one of the
2094 properties on the list. This function never signals an error. */)
2095 (Lisp_Object plist, Lisp_Object prop)
2097 Lisp_Object tail, halftail;
2099 /* halftail is used to detect circular lists. */
2100 tail = halftail = plist;
2101 while (CONSP (tail) && CONSP (XCDR (tail)))
2103 if (EQ (prop, XCAR (tail)))
2104 return XCAR (XCDR (tail));
2106 tail = XCDR (XCDR (tail));
2107 halftail = XCDR (halftail);
2108 if (EQ (tail, halftail))
2109 break;
2112 return Qnil;
2115 DEFUN ("get", Fget, Sget, 2, 2, 0,
2116 doc: /* Return the value of SYMBOL's PROPNAME property.
2117 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
2118 (Lisp_Object symbol, Lisp_Object propname)
2120 CHECK_SYMBOL (symbol);
2121 return Fplist_get (XSYMBOL (symbol)->plist, propname);
2124 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
2125 doc: /* Change value in PLIST of PROP to VAL.
2126 PLIST is a property list, which is a list of the form
2127 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
2128 If PROP is already a property on the list, its value is set to VAL,
2129 otherwise the new PROP VAL pair is added. The new plist is returned;
2130 use `(setq x (plist-put x prop val))' to be sure to use the new value.
2131 The PLIST is modified by side effects. */)
2132 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
2134 register Lisp_Object tail, prev;
2135 Lisp_Object newcell;
2136 prev = Qnil;
2137 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2138 tail = XCDR (XCDR (tail)))
2140 if (EQ (prop, XCAR (tail)))
2142 Fsetcar (XCDR (tail), val);
2143 return plist;
2146 prev = tail;
2147 QUIT;
2149 newcell = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
2150 if (NILP (prev))
2151 return newcell;
2152 else
2153 Fsetcdr (XCDR (prev), newcell);
2154 return plist;
2157 DEFUN ("put", Fput, Sput, 3, 3, 0,
2158 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
2159 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
2160 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
2162 CHECK_SYMBOL (symbol);
2163 set_symbol_plist
2164 (symbol, Fplist_put (XSYMBOL (symbol)->plist, propname, value));
2165 return value;
2168 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
2169 doc: /* Extract a value from a property list, comparing with `equal'.
2170 PLIST is a property list, which is a list of the form
2171 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2172 corresponding to the given PROP, or nil if PROP is not
2173 one of the properties on the list. */)
2174 (Lisp_Object plist, Lisp_Object prop)
2176 Lisp_Object tail;
2178 for (tail = plist;
2179 CONSP (tail) && CONSP (XCDR (tail));
2180 tail = XCDR (XCDR (tail)))
2182 if (! NILP (Fequal (prop, XCAR (tail))))
2183 return XCAR (XCDR (tail));
2185 QUIT;
2188 CHECK_LIST_END (tail, prop);
2190 return Qnil;
2193 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
2194 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
2195 PLIST is a property list, which is a list of the form
2196 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
2197 If PROP is already a property on the list, its value is set to VAL,
2198 otherwise the new PROP VAL pair is added. The new plist is returned;
2199 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
2200 The PLIST is modified by side effects. */)
2201 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
2203 register Lisp_Object tail, prev;
2204 Lisp_Object newcell;
2205 prev = Qnil;
2206 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2207 tail = XCDR (XCDR (tail)))
2209 if (! NILP (Fequal (prop, XCAR (tail))))
2211 Fsetcar (XCDR (tail), val);
2212 return plist;
2215 prev = tail;
2216 QUIT;
2218 newcell = list2 (prop, val);
2219 if (NILP (prev))
2220 return newcell;
2221 else
2222 Fsetcdr (XCDR (prev), newcell);
2223 return plist;
2226 DEFUN ("eql", Feql, Seql, 2, 2, 0,
2227 doc: /* Return t if the two args are the same Lisp object.
2228 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
2229 (Lisp_Object obj1, Lisp_Object obj2)
2231 if (FLOATP (obj1))
2232 return internal_equal (obj1, obj2, 0, 0, Qnil) ? Qt : Qnil;
2233 else
2234 return EQ (obj1, obj2) ? Qt : Qnil;
2237 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
2238 doc: /* Return t if two Lisp objects have similar structure and contents.
2239 They must have the same data type.
2240 Conses are compared by comparing the cars and the cdrs.
2241 Vectors and strings are compared element by element.
2242 Numbers are compared by value, but integers cannot equal floats.
2243 (Use `=' if you want integers and floats to be able to be equal.)
2244 Symbols must match exactly. */)
2245 (register Lisp_Object o1, Lisp_Object o2)
2247 return internal_equal (o1, o2, 0, 0, Qnil) ? Qt : Qnil;
2250 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
2251 doc: /* Return t if two Lisp objects have similar structure and contents.
2252 This is like `equal' except that it compares the text properties
2253 of strings. (`equal' ignores text properties.) */)
2254 (register Lisp_Object o1, Lisp_Object o2)
2256 return internal_equal (o1, o2, 0, 1, Qnil) ? Qt : Qnil;
2259 /* DEPTH is current depth of recursion. Signal an error if it
2260 gets too deep.
2261 PROPS means compare string text properties too. */
2263 static bool
2264 internal_equal (Lisp_Object o1, Lisp_Object o2, int depth, bool props,
2265 Lisp_Object ht)
2267 if (depth > 10)
2269 if (depth > 200)
2270 error ("Stack overflow in equal");
2271 if (NILP (ht))
2272 ht = CALLN (Fmake_hash_table, QCtest, Qeq);
2273 switch (XTYPE (o1))
2275 case Lisp_Cons: case Lisp_Misc: case Lisp_Vectorlike:
2277 struct Lisp_Hash_Table *h = XHASH_TABLE (ht);
2278 EMACS_UINT hash;
2279 ptrdiff_t i = hash_lookup (h, o1, &hash);
2280 if (i >= 0)
2281 { /* `o1' was seen already. */
2282 Lisp_Object o2s = HASH_VALUE (h, i);
2283 if (!NILP (Fmemq (o2, o2s)))
2284 return 1;
2285 else
2286 set_hash_value_slot (h, i, Fcons (o2, o2s));
2288 else
2289 hash_put (h, o1, Fcons (o2, Qnil), hash);
2291 default: ;
2295 tail_recurse:
2296 QUIT;
2297 if (EQ (o1, o2))
2298 return 1;
2299 if (XTYPE (o1) != XTYPE (o2))
2300 return 0;
2302 switch (XTYPE (o1))
2304 case Lisp_Float:
2306 double d1, d2;
2308 d1 = extract_float (o1);
2309 d2 = extract_float (o2);
2310 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2311 though they are not =. */
2312 return d1 == d2 || (d1 != d1 && d2 != d2);
2315 case Lisp_Cons:
2316 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1, props, ht))
2317 return 0;
2318 o1 = XCDR (o1);
2319 o2 = XCDR (o2);
2320 /* FIXME: This inf-loops in a circular list! */
2321 goto tail_recurse;
2323 case Lisp_Misc:
2324 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2325 return 0;
2326 if (OVERLAYP (o1))
2328 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2329 depth + 1, props, ht)
2330 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2331 depth + 1, props, ht))
2332 return 0;
2333 o1 = XOVERLAY (o1)->plist;
2334 o2 = XOVERLAY (o2)->plist;
2335 goto tail_recurse;
2337 if (MARKERP (o1))
2339 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2340 && (XMARKER (o1)->buffer == 0
2341 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2343 break;
2345 case Lisp_Vectorlike:
2347 register int i;
2348 ptrdiff_t size = ASIZE (o1);
2349 /* Pseudovectors have the type encoded in the size field, so this test
2350 actually checks that the objects have the same type as well as the
2351 same size. */
2352 if (ASIZE (o2) != size)
2353 return 0;
2354 /* Boolvectors are compared much like strings. */
2355 if (BOOL_VECTOR_P (o1))
2357 EMACS_INT size = bool_vector_size (o1);
2358 if (size != bool_vector_size (o2))
2359 return 0;
2360 if (memcmp (bool_vector_data (o1), bool_vector_data (o2),
2361 bool_vector_bytes (size)))
2362 return 0;
2363 return 1;
2365 if (WINDOW_CONFIGURATIONP (o1))
2366 return compare_window_configurations (o1, o2, 0);
2368 /* Aside from them, only true vectors, char-tables, compiled
2369 functions, and fonts (font-spec, font-entity, font-object)
2370 are sensible to compare, so eliminate the others now. */
2371 if (size & PSEUDOVECTOR_FLAG)
2373 if (((size & PVEC_TYPE_MASK) >> PSEUDOVECTOR_AREA_BITS)
2374 < PVEC_COMPILED)
2375 return 0;
2376 size &= PSEUDOVECTOR_SIZE_MASK;
2378 for (i = 0; i < size; i++)
2380 Lisp_Object v1, v2;
2381 v1 = AREF (o1, i);
2382 v2 = AREF (o2, i);
2383 if (!internal_equal (v1, v2, depth + 1, props, ht))
2384 return 0;
2386 return 1;
2388 break;
2390 case Lisp_String:
2391 if (SCHARS (o1) != SCHARS (o2))
2392 return 0;
2393 if (SBYTES (o1) != SBYTES (o2))
2394 return 0;
2395 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2396 return 0;
2397 if (props && !compare_string_intervals (o1, o2))
2398 return 0;
2399 return 1;
2401 default:
2402 break;
2405 return 0;
2409 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2410 doc: /* Store each element of ARRAY with ITEM.
2411 ARRAY is a vector, string, char-table, or bool-vector. */)
2412 (Lisp_Object array, Lisp_Object item)
2414 register ptrdiff_t size, idx;
2416 if (VECTORP (array))
2417 for (idx = 0, size = ASIZE (array); idx < size; idx++)
2418 ASET (array, idx, item);
2419 else if (CHAR_TABLE_P (array))
2421 int i;
2423 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2424 set_char_table_contents (array, i, item);
2425 set_char_table_defalt (array, item);
2427 else if (STRINGP (array))
2429 register unsigned char *p = SDATA (array);
2430 int charval;
2431 CHECK_CHARACTER (item);
2432 charval = XFASTINT (item);
2433 size = SCHARS (array);
2434 if (STRING_MULTIBYTE (array))
2436 unsigned char str[MAX_MULTIBYTE_LENGTH];
2437 int len = CHAR_STRING (charval, str);
2438 ptrdiff_t size_byte = SBYTES (array);
2439 ptrdiff_t product;
2441 if (INT_MULTIPLY_WRAPV (size, len, &product) || product != size_byte)
2442 error ("Attempt to change byte length of a string");
2443 for (idx = 0; idx < size_byte; idx++)
2444 *p++ = str[idx % len];
2446 else
2447 for (idx = 0; idx < size; idx++)
2448 p[idx] = charval;
2450 else if (BOOL_VECTOR_P (array))
2451 return bool_vector_fill (array, item);
2452 else
2453 wrong_type_argument (Qarrayp, array);
2454 return array;
2457 DEFUN ("clear-string", Fclear_string, Sclear_string,
2458 1, 1, 0,
2459 doc: /* Clear the contents of STRING.
2460 This makes STRING unibyte and may change its length. */)
2461 (Lisp_Object string)
2463 ptrdiff_t len;
2464 CHECK_STRING (string);
2465 len = SBYTES (string);
2466 memset (SDATA (string), 0, len);
2467 STRING_SET_CHARS (string, len);
2468 STRING_SET_UNIBYTE (string);
2469 return Qnil;
2472 /* ARGSUSED */
2473 Lisp_Object
2474 nconc2 (Lisp_Object s1, Lisp_Object s2)
2476 return CALLN (Fnconc, s1, s2);
2479 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2480 doc: /* Concatenate any number of lists by altering them.
2481 Only the last argument is not altered, and need not be a list.
2482 usage: (nconc &rest LISTS) */)
2483 (ptrdiff_t nargs, Lisp_Object *args)
2485 ptrdiff_t argnum;
2486 register Lisp_Object tail, tem, val;
2488 val = tail = Qnil;
2490 for (argnum = 0; argnum < nargs; argnum++)
2492 tem = args[argnum];
2493 if (NILP (tem)) continue;
2495 if (NILP (val))
2496 val = tem;
2498 if (argnum + 1 == nargs) break;
2500 CHECK_LIST_CONS (tem, tem);
2502 while (CONSP (tem))
2504 tail = tem;
2505 tem = XCDR (tail);
2506 QUIT;
2509 tem = args[argnum + 1];
2510 Fsetcdr (tail, tem);
2511 if (NILP (tem))
2512 args[argnum + 1] = tail;
2515 return val;
2518 /* This is the guts of all mapping functions.
2519 Apply FN to each element of SEQ, one by one, storing the results
2520 into elements of VALS, a C vector of Lisp_Objects. LENI is the
2521 length of VALS, which should also be the length of SEQ. Return the
2522 number of results; although this is normally LENI, it can be less
2523 if SEQ is made shorter as a side effect of FN. */
2525 static EMACS_INT
2526 mapcar1 (EMACS_INT leni, Lisp_Object *vals, Lisp_Object fn, Lisp_Object seq)
2528 Lisp_Object tail, dummy;
2529 EMACS_INT i;
2531 if (VECTORP (seq) || COMPILEDP (seq))
2533 for (i = 0; i < leni; i++)
2535 dummy = call1 (fn, AREF (seq, i));
2536 if (vals)
2537 vals[i] = dummy;
2540 else if (BOOL_VECTOR_P (seq))
2542 for (i = 0; i < leni; i++)
2544 dummy = call1 (fn, bool_vector_ref (seq, i));
2545 if (vals)
2546 vals[i] = dummy;
2549 else if (STRINGP (seq))
2551 ptrdiff_t i_byte;
2553 for (i = 0, i_byte = 0; i < leni;)
2555 int c;
2556 ptrdiff_t i_before = i;
2558 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2559 XSETFASTINT (dummy, c);
2560 dummy = call1 (fn, dummy);
2561 if (vals)
2562 vals[i_before] = dummy;
2565 else /* Must be a list, since Flength did not get an error */
2567 tail = seq;
2568 for (i = 0; i < leni; i++)
2570 if (! CONSP (tail))
2571 return i;
2572 dummy = call1 (fn, XCAR (tail));
2573 if (vals)
2574 vals[i] = dummy;
2575 tail = XCDR (tail);
2579 return leni;
2582 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2583 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2584 In between each pair of results, stick in SEPARATOR. Thus, " " as
2585 SEPARATOR results in spaces between the values returned by FUNCTION.
2586 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2587 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2589 USE_SAFE_ALLOCA;
2590 EMACS_INT leni = XFASTINT (Flength (sequence));
2591 if (CHAR_TABLE_P (sequence))
2592 wrong_type_argument (Qlistp, sequence);
2593 EMACS_INT args_alloc = 2 * leni - 1;
2594 if (args_alloc < 0)
2595 return empty_unibyte_string;
2596 Lisp_Object *args;
2597 SAFE_ALLOCA_LISP (args, args_alloc);
2598 ptrdiff_t nmapped = mapcar1 (leni, args, function, sequence);
2599 ptrdiff_t nargs = 2 * nmapped - 1;
2601 for (ptrdiff_t i = nmapped - 1; i > 0; i--)
2602 args[i + i] = args[i];
2604 for (ptrdiff_t i = 1; i < nargs; i += 2)
2605 args[i] = separator;
2607 Lisp_Object ret = Fconcat (nargs, args);
2608 SAFE_FREE ();
2609 return ret;
2612 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2613 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2614 The result is a list just as long as SEQUENCE.
2615 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2616 (Lisp_Object function, Lisp_Object sequence)
2618 USE_SAFE_ALLOCA;
2619 EMACS_INT leni = XFASTINT (Flength (sequence));
2620 if (CHAR_TABLE_P (sequence))
2621 wrong_type_argument (Qlistp, sequence);
2622 Lisp_Object *args;
2623 SAFE_ALLOCA_LISP (args, leni);
2624 ptrdiff_t nmapped = mapcar1 (leni, args, function, sequence);
2625 Lisp_Object ret = Flist (nmapped, args);
2626 SAFE_FREE ();
2627 return ret;
2630 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2631 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2632 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2633 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2634 (Lisp_Object function, Lisp_Object sequence)
2636 register EMACS_INT leni;
2638 leni = XFASTINT (Flength (sequence));
2639 if (CHAR_TABLE_P (sequence))
2640 wrong_type_argument (Qlistp, sequence);
2641 mapcar1 (leni, 0, function, sequence);
2643 return sequence;
2646 DEFUN ("mapcan", Fmapcan, Smapcan, 2, 2, 0,
2647 doc: /* Apply FUNCTION to each element of SEQUENCE, and concatenate
2648 the results by altering them (using `nconc').
2649 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2650 (Lisp_Object function, Lisp_Object sequence)
2652 USE_SAFE_ALLOCA;
2653 EMACS_INT leni = XFASTINT (Flength (sequence));
2654 if (CHAR_TABLE_P (sequence))
2655 wrong_type_argument (Qlistp, sequence);
2656 Lisp_Object *args;
2657 SAFE_ALLOCA_LISP (args, leni);
2658 ptrdiff_t nmapped = mapcar1 (leni, args, function, sequence);
2659 Lisp_Object ret = Fnconc (nmapped, args);
2660 SAFE_FREE ();
2661 return ret;
2664 /* This is how C code calls `yes-or-no-p' and allows the user
2665 to redefine it. */
2667 Lisp_Object
2668 do_yes_or_no_p (Lisp_Object prompt)
2670 return call1 (intern ("yes-or-no-p"), prompt);
2673 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2674 doc: /* Ask user a yes-or-no question.
2675 Return t if answer is yes, and nil if the answer is no.
2676 PROMPT is the string to display to ask the question. It should end in
2677 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2679 The user must confirm the answer with RET, and can edit it until it
2680 has been confirmed.
2682 If dialog boxes are supported, a dialog box will be used
2683 if `last-nonmenu-event' is nil, and `use-dialog-box' is non-nil. */)
2684 (Lisp_Object prompt)
2686 Lisp_Object ans;
2688 CHECK_STRING (prompt);
2690 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2691 && use_dialog_box && ! NILP (last_input_event))
2693 Lisp_Object pane, menu, obj;
2694 redisplay_preserve_echo_area (4);
2695 pane = list2 (Fcons (build_string ("Yes"), Qt),
2696 Fcons (build_string ("No"), Qnil));
2697 menu = Fcons (prompt, pane);
2698 obj = Fx_popup_dialog (Qt, menu, Qnil);
2699 return obj;
2702 AUTO_STRING (yes_or_no, "(yes or no) ");
2703 prompt = CALLN (Fconcat, prompt, yes_or_no);
2705 while (1)
2707 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2708 Qyes_or_no_p_history, Qnil,
2709 Qnil));
2710 if (SCHARS (ans) == 3 && !strcmp (SSDATA (ans), "yes"))
2711 return Qt;
2712 if (SCHARS (ans) == 2 && !strcmp (SSDATA (ans), "no"))
2713 return Qnil;
2715 Fding (Qnil);
2716 Fdiscard_input ();
2717 message1 ("Please answer yes or no.");
2718 Fsleep_for (make_number (2), Qnil);
2722 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2723 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2725 Each of the three load averages is multiplied by 100, then converted
2726 to integer.
2728 When USE-FLOATS is non-nil, floats will be used instead of integers.
2729 These floats are not multiplied by 100.
2731 If the 5-minute or 15-minute load averages are not available, return a
2732 shortened list, containing only those averages which are available.
2734 An error is thrown if the load average can't be obtained. In some
2735 cases making it work would require Emacs being installed setuid or
2736 setgid so that it can read kernel information, and that usually isn't
2737 advisable. */)
2738 (Lisp_Object use_floats)
2740 double load_ave[3];
2741 int loads = getloadavg (load_ave, 3);
2742 Lisp_Object ret = Qnil;
2744 if (loads < 0)
2745 error ("load-average not implemented for this operating system");
2747 while (loads-- > 0)
2749 Lisp_Object load = (NILP (use_floats)
2750 ? make_number (100.0 * load_ave[loads])
2751 : make_float (load_ave[loads]));
2752 ret = Fcons (load, ret);
2755 return ret;
2758 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2759 doc: /* Return t if FEATURE is present in this Emacs.
2761 Use this to conditionalize execution of lisp code based on the
2762 presence or absence of Emacs or environment extensions.
2763 Use `provide' to declare that a feature is available. This function
2764 looks at the value of the variable `features'. The optional argument
2765 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2766 (Lisp_Object feature, Lisp_Object subfeature)
2768 register Lisp_Object tem;
2769 CHECK_SYMBOL (feature);
2770 tem = Fmemq (feature, Vfeatures);
2771 if (!NILP (tem) && !NILP (subfeature))
2772 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2773 return (NILP (tem)) ? Qnil : Qt;
2776 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2777 doc: /* Announce that FEATURE is a feature of the current Emacs.
2778 The optional argument SUBFEATURES should be a list of symbols listing
2779 particular subfeatures supported in this version of FEATURE. */)
2780 (Lisp_Object feature, Lisp_Object subfeatures)
2782 register Lisp_Object tem;
2783 CHECK_SYMBOL (feature);
2784 CHECK_LIST (subfeatures);
2785 if (!NILP (Vautoload_queue))
2786 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2787 Vautoload_queue);
2788 tem = Fmemq (feature, Vfeatures);
2789 if (NILP (tem))
2790 Vfeatures = Fcons (feature, Vfeatures);
2791 if (!NILP (subfeatures))
2792 Fput (feature, Qsubfeatures, subfeatures);
2793 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2795 /* Run any load-hooks for this file. */
2796 tem = Fassq (feature, Vafter_load_alist);
2797 if (CONSP (tem))
2798 Fmapc (Qfuncall, XCDR (tem));
2800 return feature;
2803 /* `require' and its subroutines. */
2805 /* List of features currently being require'd, innermost first. */
2807 static Lisp_Object require_nesting_list;
2809 static void
2810 require_unwind (Lisp_Object old_value)
2812 require_nesting_list = old_value;
2815 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2816 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2817 If FEATURE is not a member of the list `features', then the feature is
2818 not loaded; so load the file FILENAME.
2820 If FILENAME is omitted, the printname of FEATURE is used as the file
2821 name, and `load' will try to load this name appended with the suffix
2822 `.elc', `.el', or the system-dependent suffix for dynamic module
2823 files, in that order. The name without appended suffix will not be
2824 used. See `get-load-suffixes' for the complete list of suffixes.
2826 The directories in `load-path' are searched when trying to find the
2827 file name.
2829 If the optional third argument NOERROR is non-nil, then return nil if
2830 the file is not found instead of signaling an error. Normally the
2831 return value is FEATURE.
2833 The normal messages at start and end of loading FILENAME are
2834 suppressed. */)
2835 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2837 Lisp_Object tem;
2838 bool from_file = load_in_progress;
2840 CHECK_SYMBOL (feature);
2842 /* Record the presence of `require' in this file
2843 even if the feature specified is already loaded.
2844 But not more than once in any file,
2845 and not when we aren't loading or reading from a file. */
2846 if (!from_file)
2847 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2848 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2849 from_file = 1;
2851 if (from_file)
2853 tem = Fcons (Qrequire, feature);
2854 if (NILP (Fmember (tem, Vcurrent_load_list)))
2855 LOADHIST_ATTACH (tem);
2857 tem = Fmemq (feature, Vfeatures);
2859 if (NILP (tem))
2861 ptrdiff_t count = SPECPDL_INDEX ();
2862 int nesting = 0;
2864 /* This is to make sure that loadup.el gives a clear picture
2865 of what files are preloaded and when. */
2866 if (! NILP (Vpurify_flag))
2867 error ("(require %s) while preparing to dump",
2868 SDATA (SYMBOL_NAME (feature)));
2870 /* A certain amount of recursive `require' is legitimate,
2871 but if we require the same feature recursively 3 times,
2872 signal an error. */
2873 tem = require_nesting_list;
2874 while (! NILP (tem))
2876 if (! NILP (Fequal (feature, XCAR (tem))))
2877 nesting++;
2878 tem = XCDR (tem);
2880 if (nesting > 3)
2881 error ("Recursive `require' for feature `%s'",
2882 SDATA (SYMBOL_NAME (feature)));
2884 /* Update the list for any nested `require's that occur. */
2885 record_unwind_protect (require_unwind, require_nesting_list);
2886 require_nesting_list = Fcons (feature, require_nesting_list);
2888 /* Value saved here is to be restored into Vautoload_queue */
2889 record_unwind_protect (un_autoload, Vautoload_queue);
2890 Vautoload_queue = Qt;
2892 /* Load the file. */
2893 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2894 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2896 /* If load failed entirely, return nil. */
2897 if (NILP (tem))
2898 return unbind_to (count, Qnil);
2900 tem = Fmemq (feature, Vfeatures);
2901 if (NILP (tem))
2902 error ("Required feature `%s' was not provided",
2903 SDATA (SYMBOL_NAME (feature)));
2905 /* Once loading finishes, don't undo it. */
2906 Vautoload_queue = Qt;
2907 feature = unbind_to (count, feature);
2910 return feature;
2913 /* Primitives for work of the "widget" library.
2914 In an ideal world, this section would not have been necessary.
2915 However, lisp function calls being as slow as they are, it turns
2916 out that some functions in the widget library (wid-edit.el) are the
2917 bottleneck of Widget operation. Here is their translation to C,
2918 for the sole reason of efficiency. */
2920 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2921 doc: /* Return non-nil if PLIST has the property PROP.
2922 PLIST is a property list, which is a list of the form
2923 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol.
2924 Unlike `plist-get', this allows you to distinguish between a missing
2925 property and a property with the value nil.
2926 The value is actually the tail of PLIST whose car is PROP. */)
2927 (Lisp_Object plist, Lisp_Object prop)
2929 while (CONSP (plist) && !EQ (XCAR (plist), prop))
2931 plist = XCDR (plist);
2932 plist = CDR (plist);
2933 QUIT;
2935 return plist;
2938 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2939 doc: /* In WIDGET, set PROPERTY to VALUE.
2940 The value can later be retrieved with `widget-get'. */)
2941 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2943 CHECK_CONS (widget);
2944 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
2945 return value;
2948 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
2949 doc: /* In WIDGET, get the value of PROPERTY.
2950 The value could either be specified when the widget was created, or
2951 later with `widget-put'. */)
2952 (Lisp_Object widget, Lisp_Object property)
2954 Lisp_Object tmp;
2956 while (1)
2958 if (NILP (widget))
2959 return Qnil;
2960 CHECK_CONS (widget);
2961 tmp = Fplist_member (XCDR (widget), property);
2962 if (CONSP (tmp))
2964 tmp = XCDR (tmp);
2965 return CAR (tmp);
2967 tmp = XCAR (widget);
2968 if (NILP (tmp))
2969 return Qnil;
2970 widget = Fget (tmp, Qwidget_type);
2974 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
2975 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2976 ARGS are passed as extra arguments to the function.
2977 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2978 (ptrdiff_t nargs, Lisp_Object *args)
2980 Lisp_Object widget = args[0];
2981 Lisp_Object property = args[1];
2982 Lisp_Object propval = Fwidget_get (widget, property);
2983 Lisp_Object trailing_args = Flist (nargs - 2, args + 2);
2984 Lisp_Object result = CALLN (Fapply, propval, widget, trailing_args);
2985 return result;
2988 #ifdef HAVE_LANGINFO_CODESET
2989 #include <langinfo.h>
2990 #endif
2992 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
2993 doc: /* Access locale data ITEM for the current C locale, if available.
2994 ITEM should be one of the following:
2996 `codeset', returning the character set as a string (locale item CODESET);
2998 `days', returning a 7-element vector of day names (locale items DAY_n);
3000 `months', returning a 12-element vector of month names (locale items MON_n);
3002 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
3003 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
3005 If the system can't provide such information through a call to
3006 `nl_langinfo', or if ITEM isn't from the list above, return nil.
3008 See also Info node `(libc)Locales'.
3010 The data read from the system are decoded using `locale-coding-system'. */)
3011 (Lisp_Object item)
3013 char *str = NULL;
3014 #ifdef HAVE_LANGINFO_CODESET
3015 if (EQ (item, Qcodeset))
3017 str = nl_langinfo (CODESET);
3018 return build_string (str);
3020 #ifdef DAY_1
3021 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
3023 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
3024 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
3025 int i;
3026 synchronize_system_time_locale ();
3027 for (i = 0; i < 7; i++)
3029 str = nl_langinfo (days[i]);
3030 AUTO_STRING (val, str);
3031 /* Fixme: Is this coding system necessarily right, even if
3032 it is consistent with CODESET? If not, what to do? */
3033 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
3034 0));
3036 return v;
3038 #endif /* DAY_1 */
3039 #ifdef MON_1
3040 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
3042 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
3043 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
3044 MON_8, MON_9, MON_10, MON_11, MON_12};
3045 int i;
3046 synchronize_system_time_locale ();
3047 for (i = 0; i < 12; i++)
3049 str = nl_langinfo (months[i]);
3050 AUTO_STRING (val, str);
3051 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
3052 0));
3054 return v;
3056 #endif /* MON_1 */
3057 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
3058 but is in the locale files. This could be used by ps-print. */
3059 #ifdef PAPER_WIDTH
3060 else if (EQ (item, Qpaper))
3061 return list2i (nl_langinfo (PAPER_WIDTH), nl_langinfo (PAPER_HEIGHT));
3062 #endif /* PAPER_WIDTH */
3063 #endif /* HAVE_LANGINFO_CODESET*/
3064 return Qnil;
3067 /* base64 encode/decode functions (RFC 2045).
3068 Based on code from GNU recode. */
3070 #define MIME_LINE_LENGTH 76
3072 #define IS_ASCII(Character) \
3073 ((Character) < 128)
3074 #define IS_BASE64(Character) \
3075 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
3076 #define IS_BASE64_IGNORABLE(Character) \
3077 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
3078 || (Character) == '\f' || (Character) == '\r')
3080 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
3081 character or return retval if there are no characters left to
3082 process. */
3083 #define READ_QUADRUPLET_BYTE(retval) \
3084 do \
3086 if (i == length) \
3088 if (nchars_return) \
3089 *nchars_return = nchars; \
3090 return (retval); \
3092 c = from[i++]; \
3094 while (IS_BASE64_IGNORABLE (c))
3096 /* Table of characters coding the 64 values. */
3097 static const char base64_value_to_char[64] =
3099 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
3100 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
3101 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
3102 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
3103 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
3104 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
3105 '8', '9', '+', '/' /* 60-63 */
3108 /* Table of base64 values for first 128 characters. */
3109 static const short base64_char_to_value[128] =
3111 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
3112 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
3113 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
3114 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
3115 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
3116 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
3117 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
3118 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
3119 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
3120 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
3121 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
3122 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
3123 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
3126 /* The following diagram shows the logical steps by which three octets
3127 get transformed into four base64 characters.
3129 .--------. .--------. .--------.
3130 |aaaaaabb| |bbbbcccc| |ccdddddd|
3131 `--------' `--------' `--------'
3132 6 2 4 4 2 6
3133 .--------+--------+--------+--------.
3134 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
3135 `--------+--------+--------+--------'
3137 .--------+--------+--------+--------.
3138 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
3139 `--------+--------+--------+--------'
3141 The octets are divided into 6 bit chunks, which are then encoded into
3142 base64 characters. */
3145 static ptrdiff_t base64_encode_1 (const char *, char *, ptrdiff_t, bool, bool);
3146 static ptrdiff_t base64_decode_1 (const char *, char *, ptrdiff_t, bool,
3147 ptrdiff_t *);
3149 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
3150 2, 3, "r",
3151 doc: /* Base64-encode the region between BEG and END.
3152 Return the length of the encoded text.
3153 Optional third argument NO-LINE-BREAK means do not break long lines
3154 into shorter lines. */)
3155 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
3157 char *encoded;
3158 ptrdiff_t allength, length;
3159 ptrdiff_t ibeg, iend, encoded_length;
3160 ptrdiff_t old_pos = PT;
3161 USE_SAFE_ALLOCA;
3163 validate_region (&beg, &end);
3165 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3166 iend = CHAR_TO_BYTE (XFASTINT (end));
3167 move_gap_both (XFASTINT (beg), ibeg);
3169 /* We need to allocate enough room for encoding the text.
3170 We need 33 1/3% more space, plus a newline every 76
3171 characters, and then we round up. */
3172 length = iend - ibeg;
3173 allength = length + length/3 + 1;
3174 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3176 encoded = SAFE_ALLOCA (allength);
3177 encoded_length = base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg),
3178 encoded, length, NILP (no_line_break),
3179 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
3180 if (encoded_length > allength)
3181 emacs_abort ();
3183 if (encoded_length < 0)
3185 /* The encoding wasn't possible. */
3186 SAFE_FREE ();
3187 error ("Multibyte character in data for base64 encoding");
3190 /* Now we have encoded the region, so we insert the new contents
3191 and delete the old. (Insert first in order to preserve markers.) */
3192 SET_PT_BOTH (XFASTINT (beg), ibeg);
3193 insert (encoded, encoded_length);
3194 SAFE_FREE ();
3195 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
3197 /* If point was outside of the region, restore it exactly; else just
3198 move to the beginning of the region. */
3199 if (old_pos >= XFASTINT (end))
3200 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
3201 else if (old_pos > XFASTINT (beg))
3202 old_pos = XFASTINT (beg);
3203 SET_PT (old_pos);
3205 /* We return the length of the encoded text. */
3206 return make_number (encoded_length);
3209 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
3210 1, 2, 0,
3211 doc: /* Base64-encode STRING and return the result.
3212 Optional second argument NO-LINE-BREAK means do not break long lines
3213 into shorter lines. */)
3214 (Lisp_Object string, Lisp_Object no_line_break)
3216 ptrdiff_t allength, length, encoded_length;
3217 char *encoded;
3218 Lisp_Object encoded_string;
3219 USE_SAFE_ALLOCA;
3221 CHECK_STRING (string);
3223 /* We need to allocate enough room for encoding the text.
3224 We need 33 1/3% more space, plus a newline every 76
3225 characters, and then we round up. */
3226 length = SBYTES (string);
3227 allength = length + length/3 + 1;
3228 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3230 /* We need to allocate enough room for decoding the text. */
3231 encoded = SAFE_ALLOCA (allength);
3233 encoded_length = base64_encode_1 (SSDATA (string),
3234 encoded, length, NILP (no_line_break),
3235 STRING_MULTIBYTE (string));
3236 if (encoded_length > allength)
3237 emacs_abort ();
3239 if (encoded_length < 0)
3241 /* The encoding wasn't possible. */
3242 error ("Multibyte character in data for base64 encoding");
3245 encoded_string = make_unibyte_string (encoded, encoded_length);
3246 SAFE_FREE ();
3248 return encoded_string;
3251 static ptrdiff_t
3252 base64_encode_1 (const char *from, char *to, ptrdiff_t length,
3253 bool line_break, bool multibyte)
3255 int counter = 0;
3256 ptrdiff_t i = 0;
3257 char *e = to;
3258 int c;
3259 unsigned int value;
3260 int bytes;
3262 while (i < length)
3264 if (multibyte)
3266 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3267 if (CHAR_BYTE8_P (c))
3268 c = CHAR_TO_BYTE8 (c);
3269 else if (c >= 256)
3270 return -1;
3271 i += bytes;
3273 else
3274 c = from[i++];
3276 /* Wrap line every 76 characters. */
3278 if (line_break)
3280 if (counter < MIME_LINE_LENGTH / 4)
3281 counter++;
3282 else
3284 *e++ = '\n';
3285 counter = 1;
3289 /* Process first byte of a triplet. */
3291 *e++ = base64_value_to_char[0x3f & c >> 2];
3292 value = (0x03 & c) << 4;
3294 /* Process second byte of a triplet. */
3296 if (i == length)
3298 *e++ = base64_value_to_char[value];
3299 *e++ = '=';
3300 *e++ = '=';
3301 break;
3304 if (multibyte)
3306 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3307 if (CHAR_BYTE8_P (c))
3308 c = CHAR_TO_BYTE8 (c);
3309 else if (c >= 256)
3310 return -1;
3311 i += bytes;
3313 else
3314 c = from[i++];
3316 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3317 value = (0x0f & c) << 2;
3319 /* Process third byte of a triplet. */
3321 if (i == length)
3323 *e++ = base64_value_to_char[value];
3324 *e++ = '=';
3325 break;
3328 if (multibyte)
3330 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3331 if (CHAR_BYTE8_P (c))
3332 c = CHAR_TO_BYTE8 (c);
3333 else if (c >= 256)
3334 return -1;
3335 i += bytes;
3337 else
3338 c = from[i++];
3340 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3341 *e++ = base64_value_to_char[0x3f & c];
3344 return e - to;
3348 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3349 2, 2, "r",
3350 doc: /* Base64-decode the region between BEG and END.
3351 Return the length of the decoded text.
3352 If the region can't be decoded, signal an error and don't modify the buffer. */)
3353 (Lisp_Object beg, Lisp_Object end)
3355 ptrdiff_t ibeg, iend, length, allength;
3356 char *decoded;
3357 ptrdiff_t old_pos = PT;
3358 ptrdiff_t decoded_length;
3359 ptrdiff_t inserted_chars;
3360 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3361 USE_SAFE_ALLOCA;
3363 validate_region (&beg, &end);
3365 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3366 iend = CHAR_TO_BYTE (XFASTINT (end));
3368 length = iend - ibeg;
3370 /* We need to allocate enough room for decoding the text. If we are
3371 working on a multibyte buffer, each decoded code may occupy at
3372 most two bytes. */
3373 allength = multibyte ? length * 2 : length;
3374 decoded = SAFE_ALLOCA (allength);
3376 move_gap_both (XFASTINT (beg), ibeg);
3377 decoded_length = base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg),
3378 decoded, length,
3379 multibyte, &inserted_chars);
3380 if (decoded_length > allength)
3381 emacs_abort ();
3383 if (decoded_length < 0)
3385 /* The decoding wasn't possible. */
3386 error ("Invalid base64 data");
3389 /* Now we have decoded the region, so we insert the new contents
3390 and delete the old. (Insert first in order to preserve markers.) */
3391 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3392 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3393 SAFE_FREE ();
3395 /* Delete the original text. */
3396 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3397 iend + decoded_length, 1);
3399 /* If point was outside of the region, restore it exactly; else just
3400 move to the beginning of the region. */
3401 if (old_pos >= XFASTINT (end))
3402 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3403 else if (old_pos > XFASTINT (beg))
3404 old_pos = XFASTINT (beg);
3405 SET_PT (old_pos > ZV ? ZV : old_pos);
3407 return make_number (inserted_chars);
3410 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3411 1, 1, 0,
3412 doc: /* Base64-decode STRING and return the result. */)
3413 (Lisp_Object string)
3415 char *decoded;
3416 ptrdiff_t length, decoded_length;
3417 Lisp_Object decoded_string;
3418 USE_SAFE_ALLOCA;
3420 CHECK_STRING (string);
3422 length = SBYTES (string);
3423 /* We need to allocate enough room for decoding the text. */
3424 decoded = SAFE_ALLOCA (length);
3426 /* The decoded result should be unibyte. */
3427 decoded_length = base64_decode_1 (SSDATA (string), decoded, length,
3428 0, NULL);
3429 if (decoded_length > length)
3430 emacs_abort ();
3431 else if (decoded_length >= 0)
3432 decoded_string = make_unibyte_string (decoded, decoded_length);
3433 else
3434 decoded_string = Qnil;
3436 SAFE_FREE ();
3437 if (!STRINGP (decoded_string))
3438 error ("Invalid base64 data");
3440 return decoded_string;
3443 /* Base64-decode the data at FROM of LENGTH bytes into TO. If
3444 MULTIBYTE, the decoded result should be in multibyte
3445 form. If NCHARS_RETURN is not NULL, store the number of produced
3446 characters in *NCHARS_RETURN. */
3448 static ptrdiff_t
3449 base64_decode_1 (const char *from, char *to, ptrdiff_t length,
3450 bool multibyte, ptrdiff_t *nchars_return)
3452 ptrdiff_t i = 0; /* Used inside READ_QUADRUPLET_BYTE */
3453 char *e = to;
3454 unsigned char c;
3455 unsigned long value;
3456 ptrdiff_t nchars = 0;
3458 while (1)
3460 /* Process first byte of a quadruplet. */
3462 READ_QUADRUPLET_BYTE (e-to);
3464 if (!IS_BASE64 (c))
3465 return -1;
3466 value = base64_char_to_value[c] << 18;
3468 /* Process second byte of a quadruplet. */
3470 READ_QUADRUPLET_BYTE (-1);
3472 if (!IS_BASE64 (c))
3473 return -1;
3474 value |= base64_char_to_value[c] << 12;
3476 c = (unsigned char) (value >> 16);
3477 if (multibyte && c >= 128)
3478 e += BYTE8_STRING (c, e);
3479 else
3480 *e++ = c;
3481 nchars++;
3483 /* Process third byte of a quadruplet. */
3485 READ_QUADRUPLET_BYTE (-1);
3487 if (c == '=')
3489 READ_QUADRUPLET_BYTE (-1);
3491 if (c != '=')
3492 return -1;
3493 continue;
3496 if (!IS_BASE64 (c))
3497 return -1;
3498 value |= base64_char_to_value[c] << 6;
3500 c = (unsigned char) (0xff & value >> 8);
3501 if (multibyte && c >= 128)
3502 e += BYTE8_STRING (c, e);
3503 else
3504 *e++ = c;
3505 nchars++;
3507 /* Process fourth byte of a quadruplet. */
3509 READ_QUADRUPLET_BYTE (-1);
3511 if (c == '=')
3512 continue;
3514 if (!IS_BASE64 (c))
3515 return -1;
3516 value |= base64_char_to_value[c];
3518 c = (unsigned char) (0xff & value);
3519 if (multibyte && c >= 128)
3520 e += BYTE8_STRING (c, e);
3521 else
3522 *e++ = c;
3523 nchars++;
3529 /***********************************************************************
3530 ***** *****
3531 ***** Hash Tables *****
3532 ***** *****
3533 ***********************************************************************/
3535 /* Implemented by gerd@gnu.org. This hash table implementation was
3536 inspired by CMUCL hash tables. */
3538 /* Ideas:
3540 1. For small tables, association lists are probably faster than
3541 hash tables because they have lower overhead.
3543 For uses of hash tables where the O(1) behavior of table
3544 operations is not a requirement, it might therefore be a good idea
3545 not to hash. Instead, we could just do a linear search in the
3546 key_and_value vector of the hash table. This could be done
3547 if a `:linear-search t' argument is given to make-hash-table. */
3550 /* The list of all weak hash tables. Don't staticpro this one. */
3552 static struct Lisp_Hash_Table *weak_hash_tables;
3555 /***********************************************************************
3556 Utilities
3557 ***********************************************************************/
3559 static void
3560 CHECK_HASH_TABLE (Lisp_Object x)
3562 CHECK_TYPE (HASH_TABLE_P (x), Qhash_table_p, x);
3565 static void
3566 set_hash_key_and_value (struct Lisp_Hash_Table *h, Lisp_Object key_and_value)
3568 h->key_and_value = key_and_value;
3570 static void
3571 set_hash_next (struct Lisp_Hash_Table *h, Lisp_Object next)
3573 h->next = next;
3575 static void
3576 set_hash_next_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3578 gc_aset (h->next, idx, val);
3580 static void
3581 set_hash_hash (struct Lisp_Hash_Table *h, Lisp_Object hash)
3583 h->hash = hash;
3585 static void
3586 set_hash_hash_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3588 gc_aset (h->hash, idx, val);
3590 static void
3591 set_hash_index (struct Lisp_Hash_Table *h, Lisp_Object index)
3593 h->index = index;
3595 static void
3596 set_hash_index_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3598 gc_aset (h->index, idx, val);
3601 /* If OBJ is a Lisp hash table, return a pointer to its struct
3602 Lisp_Hash_Table. Otherwise, signal an error. */
3604 static struct Lisp_Hash_Table *
3605 check_hash_table (Lisp_Object obj)
3607 CHECK_HASH_TABLE (obj);
3608 return XHASH_TABLE (obj);
3612 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3613 number. A number is "almost" a prime number if it is not divisible
3614 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3616 EMACS_INT
3617 next_almost_prime (EMACS_INT n)
3619 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
3620 for (n |= 1; ; n += 2)
3621 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0)
3622 return n;
3626 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3627 which USED[I] is non-zero. If found at index I in ARGS, set
3628 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3629 0. This function is used to extract a keyword/argument pair from
3630 a DEFUN parameter list. */
3632 static ptrdiff_t
3633 get_key_arg (Lisp_Object key, ptrdiff_t nargs, Lisp_Object *args, char *used)
3635 ptrdiff_t i;
3637 for (i = 1; i < nargs; i++)
3638 if (!used[i - 1] && EQ (args[i - 1], key))
3640 used[i - 1] = 1;
3641 used[i] = 1;
3642 return i;
3645 return 0;
3649 /* Return a Lisp vector which has the same contents as VEC but has
3650 at least INCR_MIN more entries, where INCR_MIN is positive.
3651 If NITEMS_MAX is not -1, do not grow the vector to be any larger
3652 than NITEMS_MAX. Entries in the resulting
3653 vector that are not copied from VEC are set to nil. */
3655 Lisp_Object
3656 larger_vector (Lisp_Object vec, ptrdiff_t incr_min, ptrdiff_t nitems_max)
3658 struct Lisp_Vector *v;
3659 ptrdiff_t incr, incr_max, old_size, new_size;
3660 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / sizeof *v->contents;
3661 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
3662 ? nitems_max : C_language_max);
3663 eassert (VECTORP (vec));
3664 eassert (0 < incr_min && -1 <= nitems_max);
3665 old_size = ASIZE (vec);
3666 incr_max = n_max - old_size;
3667 incr = max (incr_min, min (old_size >> 1, incr_max));
3668 if (incr_max < incr)
3669 memory_full (SIZE_MAX);
3670 new_size = old_size + incr;
3671 v = allocate_vector (new_size);
3672 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3673 memclear (v->contents + old_size, incr * word_size);
3674 XSETVECTOR (vec, v);
3675 return vec;
3679 /***********************************************************************
3680 Low-level Functions
3681 ***********************************************************************/
3683 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3684 HASH2 in hash table H using `eql'. Value is true if KEY1 and
3685 KEY2 are the same. */
3687 static bool
3688 cmpfn_eql (struct hash_table_test *ht,
3689 Lisp_Object key1,
3690 Lisp_Object key2)
3692 return (FLOATP (key1)
3693 && FLOATP (key2)
3694 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3698 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3699 HASH2 in hash table H using `equal'. Value is true if KEY1 and
3700 KEY2 are the same. */
3702 static bool
3703 cmpfn_equal (struct hash_table_test *ht,
3704 Lisp_Object key1,
3705 Lisp_Object key2)
3707 return !NILP (Fequal (key1, key2));
3711 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3712 HASH2 in hash table H using H->user_cmp_function. Value is true
3713 if KEY1 and KEY2 are the same. */
3715 static bool
3716 cmpfn_user_defined (struct hash_table_test *ht,
3717 Lisp_Object key1,
3718 Lisp_Object key2)
3720 return !NILP (call2 (ht->user_cmp_function, key1, key2));
3723 /* Value is a hash code for KEY for use in hash table H which uses
3724 `eq' to compare keys. The hash code returned is guaranteed to fit
3725 in a Lisp integer. */
3727 static EMACS_UINT
3728 hashfn_eq (struct hash_table_test *ht, Lisp_Object key)
3730 return XHASH (key) ^ XTYPE (key);
3733 /* Value is a hash code for KEY for use in hash table H which uses
3734 `equal' to compare keys. The hash code returned is guaranteed to fit
3735 in a Lisp integer. */
3737 static EMACS_UINT
3738 hashfn_equal (struct hash_table_test *ht, Lisp_Object key)
3740 return sxhash (key, 0);
3743 /* Value is a hash code for KEY for use in hash table H which uses
3744 `eql' to compare keys. The hash code returned is guaranteed to fit
3745 in a Lisp integer. */
3747 static EMACS_UINT
3748 hashfn_eql (struct hash_table_test *ht, Lisp_Object key)
3750 return FLOATP (key) ? hashfn_equal (ht, key) : hashfn_eq (ht, key);
3753 /* Value is a hash code for KEY for use in hash table H which uses as
3754 user-defined function to compare keys. The hash code returned is
3755 guaranteed to fit in a Lisp integer. */
3757 static EMACS_UINT
3758 hashfn_user_defined (struct hash_table_test *ht, Lisp_Object key)
3760 Lisp_Object hash = call1 (ht->user_hash_function, key);
3761 return hashfn_eq (ht, hash);
3764 struct hash_table_test const
3765 hashtest_eq = { LISPSYM_INITIALLY (Qeq), LISPSYM_INITIALLY (Qnil),
3766 LISPSYM_INITIALLY (Qnil), 0, hashfn_eq },
3767 hashtest_eql = { LISPSYM_INITIALLY (Qeql), LISPSYM_INITIALLY (Qnil),
3768 LISPSYM_INITIALLY (Qnil), cmpfn_eql, hashfn_eql },
3769 hashtest_equal = { LISPSYM_INITIALLY (Qequal), LISPSYM_INITIALLY (Qnil),
3770 LISPSYM_INITIALLY (Qnil), cmpfn_equal, hashfn_equal };
3772 /* Allocate basically initialized hash table. */
3774 static struct Lisp_Hash_Table *
3775 allocate_hash_table (void)
3777 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table,
3778 count, PVEC_HASH_TABLE);
3781 /* An upper bound on the size of a hash table index. It must fit in
3782 ptrdiff_t and be a valid Emacs fixnum. */
3783 #define INDEX_SIZE_BOUND \
3784 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, PTRDIFF_MAX / word_size))
3786 /* Create and initialize a new hash table.
3788 TEST specifies the test the hash table will use to compare keys.
3789 It must be either one of the predefined tests `eq', `eql' or
3790 `equal' or a symbol denoting a user-defined test named TEST with
3791 test and hash functions USER_TEST and USER_HASH.
3793 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3795 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3796 new size when it becomes full is computed by adding REHASH_SIZE to
3797 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3798 table's new size is computed by multiplying its old size with
3799 REHASH_SIZE.
3801 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3802 be resized when the ratio of (number of entries in the table) /
3803 (table size) is >= REHASH_THRESHOLD.
3805 WEAK specifies the weakness of the table. If non-nil, it must be
3806 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
3808 Lisp_Object
3809 make_hash_table (struct hash_table_test test,
3810 Lisp_Object size, Lisp_Object rehash_size,
3811 Lisp_Object rehash_threshold, Lisp_Object weak)
3813 struct Lisp_Hash_Table *h;
3814 Lisp_Object table;
3815 EMACS_INT index_size, sz;
3816 ptrdiff_t i;
3817 double index_float;
3819 /* Preconditions. */
3820 eassert (SYMBOLP (test.name));
3821 eassert (INTEGERP (size) && XINT (size) >= 0);
3822 eassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3823 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size)));
3824 eassert (FLOATP (rehash_threshold)
3825 && 0 < XFLOAT_DATA (rehash_threshold)
3826 && XFLOAT_DATA (rehash_threshold) <= 1.0);
3828 if (XFASTINT (size) == 0)
3829 size = make_number (1);
3831 sz = XFASTINT (size);
3832 index_float = sz / XFLOAT_DATA (rehash_threshold);
3833 index_size = (index_float < INDEX_SIZE_BOUND + 1
3834 ? next_almost_prime (index_float)
3835 : INDEX_SIZE_BOUND + 1);
3836 if (INDEX_SIZE_BOUND < max (index_size, 2 * sz))
3837 error ("Hash table too large");
3839 /* Allocate a table and initialize it. */
3840 h = allocate_hash_table ();
3842 /* Initialize hash table slots. */
3843 h->test = test;
3844 h->weak = weak;
3845 h->rehash_threshold = rehash_threshold;
3846 h->rehash_size = rehash_size;
3847 h->count = 0;
3848 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
3849 h->hash = Fmake_vector (size, Qnil);
3850 h->next = Fmake_vector (size, Qnil);
3851 h->index = Fmake_vector (make_number (index_size), Qnil);
3853 /* Set up the free list. */
3854 for (i = 0; i < sz - 1; ++i)
3855 set_hash_next_slot (h, i, make_number (i + 1));
3856 h->next_free = make_number (0);
3858 XSET_HASH_TABLE (table, h);
3859 eassert (HASH_TABLE_P (table));
3860 eassert (XHASH_TABLE (table) == h);
3862 /* Maybe add this hash table to the list of all weak hash tables. */
3863 if (NILP (h->weak))
3864 h->next_weak = NULL;
3865 else
3867 h->next_weak = weak_hash_tables;
3868 weak_hash_tables = h;
3871 return table;
3875 /* Return a copy of hash table H1. Keys and values are not copied,
3876 only the table itself is. */
3878 static Lisp_Object
3879 copy_hash_table (struct Lisp_Hash_Table *h1)
3881 Lisp_Object table;
3882 struct Lisp_Hash_Table *h2;
3884 h2 = allocate_hash_table ();
3885 *h2 = *h1;
3886 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3887 h2->hash = Fcopy_sequence (h1->hash);
3888 h2->next = Fcopy_sequence (h1->next);
3889 h2->index = Fcopy_sequence (h1->index);
3890 XSET_HASH_TABLE (table, h2);
3892 /* Maybe add this hash table to the list of all weak hash tables. */
3893 if (!NILP (h2->weak))
3895 h2->next_weak = weak_hash_tables;
3896 weak_hash_tables = h2;
3899 return table;
3903 /* Resize hash table H if it's too full. If H cannot be resized
3904 because it's already too large, throw an error. */
3906 static void
3907 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3909 if (NILP (h->next_free))
3911 ptrdiff_t old_size = HASH_TABLE_SIZE (h);
3912 EMACS_INT new_size, index_size, nsize;
3913 ptrdiff_t i;
3914 double index_float;
3916 if (INTEGERP (h->rehash_size))
3917 new_size = old_size + XFASTINT (h->rehash_size);
3918 else
3920 double float_new_size = old_size * XFLOAT_DATA (h->rehash_size);
3921 if (float_new_size < INDEX_SIZE_BOUND + 1)
3923 new_size = float_new_size;
3924 if (new_size <= old_size)
3925 new_size = old_size + 1;
3927 else
3928 new_size = INDEX_SIZE_BOUND + 1;
3930 index_float = new_size / XFLOAT_DATA (h->rehash_threshold);
3931 index_size = (index_float < INDEX_SIZE_BOUND + 1
3932 ? next_almost_prime (index_float)
3933 : INDEX_SIZE_BOUND + 1);
3934 nsize = max (index_size, 2 * new_size);
3935 if (INDEX_SIZE_BOUND < nsize)
3936 error ("Hash table too large to resize");
3938 #ifdef ENABLE_CHECKING
3939 if (HASH_TABLE_P (Vpurify_flag)
3940 && XHASH_TABLE (Vpurify_flag) == h)
3941 message ("Growing hash table to: %"pI"d", new_size);
3942 #endif
3944 set_hash_key_and_value (h, larger_vector (h->key_and_value,
3945 2 * (new_size - old_size), -1));
3946 set_hash_next (h, larger_vector (h->next, new_size - old_size, -1));
3947 set_hash_hash (h, larger_vector (h->hash, new_size - old_size, -1));
3948 set_hash_index (h, Fmake_vector (make_number (index_size), Qnil));
3950 /* Update the free list. Do it so that new entries are added at
3951 the end of the free list. This makes some operations like
3952 maphash faster. */
3953 for (i = old_size; i < new_size - 1; ++i)
3954 set_hash_next_slot (h, i, make_number (i + 1));
3956 if (!NILP (h->next_free))
3958 Lisp_Object last, next;
3960 last = h->next_free;
3961 while (next = HASH_NEXT (h, XFASTINT (last)),
3962 !NILP (next))
3963 last = next;
3965 set_hash_next_slot (h, XFASTINT (last), make_number (old_size));
3967 else
3968 XSETFASTINT (h->next_free, old_size);
3970 /* Rehash. */
3971 for (i = 0; i < old_size; ++i)
3972 if (!NILP (HASH_HASH (h, i)))
3974 EMACS_UINT hash_code = XUINT (HASH_HASH (h, i));
3975 ptrdiff_t start_of_bucket = hash_code % ASIZE (h->index);
3976 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3977 set_hash_index_slot (h, start_of_bucket, make_number (i));
3983 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
3984 the hash code of KEY. Value is the index of the entry in H
3985 matching KEY, or -1 if not found. */
3987 ptrdiff_t
3988 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
3990 EMACS_UINT hash_code;
3991 ptrdiff_t start_of_bucket;
3992 Lisp_Object idx;
3994 hash_code = h->test.hashfn (&h->test, key);
3995 eassert ((hash_code & ~INTMASK) == 0);
3996 if (hash)
3997 *hash = hash_code;
3999 start_of_bucket = hash_code % ASIZE (h->index);
4000 idx = HASH_INDEX (h, start_of_bucket);
4002 while (!NILP (idx))
4004 ptrdiff_t i = XFASTINT (idx);
4005 if (EQ (key, HASH_KEY (h, i))
4006 || (h->test.cmpfn
4007 && hash_code == XUINT (HASH_HASH (h, i))
4008 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
4009 break;
4010 idx = HASH_NEXT (h, i);
4013 return NILP (idx) ? -1 : XFASTINT (idx);
4017 /* Put an entry into hash table H that associates KEY with VALUE.
4018 HASH is a previously computed hash code of KEY.
4019 Value is the index of the entry in H matching KEY. */
4021 ptrdiff_t
4022 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value,
4023 EMACS_UINT hash)
4025 ptrdiff_t start_of_bucket, i;
4027 eassert ((hash & ~INTMASK) == 0);
4029 /* Increment count after resizing because resizing may fail. */
4030 maybe_resize_hash_table (h);
4031 h->count++;
4033 /* Store key/value in the key_and_value vector. */
4034 i = XFASTINT (h->next_free);
4035 h->next_free = HASH_NEXT (h, i);
4036 set_hash_key_slot (h, i, key);
4037 set_hash_value_slot (h, i, value);
4039 /* Remember its hash code. */
4040 set_hash_hash_slot (h, i, make_number (hash));
4042 /* Add new entry to its collision chain. */
4043 start_of_bucket = hash % ASIZE (h->index);
4044 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
4045 set_hash_index_slot (h, start_of_bucket, make_number (i));
4046 return i;
4050 /* Remove the entry matching KEY from hash table H, if there is one. */
4052 void
4053 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
4055 EMACS_UINT hash_code;
4056 ptrdiff_t start_of_bucket;
4057 Lisp_Object idx, prev;
4059 hash_code = h->test.hashfn (&h->test, key);
4060 eassert ((hash_code & ~INTMASK) == 0);
4061 start_of_bucket = hash_code % ASIZE (h->index);
4062 idx = HASH_INDEX (h, start_of_bucket);
4063 prev = Qnil;
4065 while (!NILP (idx))
4067 ptrdiff_t i = XFASTINT (idx);
4069 if (EQ (key, HASH_KEY (h, i))
4070 || (h->test.cmpfn
4071 && hash_code == XUINT (HASH_HASH (h, i))
4072 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
4074 /* Take entry out of collision chain. */
4075 if (NILP (prev))
4076 set_hash_index_slot (h, start_of_bucket, HASH_NEXT (h, i));
4077 else
4078 set_hash_next_slot (h, XFASTINT (prev), HASH_NEXT (h, i));
4080 /* Clear slots in key_and_value and add the slots to
4081 the free list. */
4082 set_hash_key_slot (h, i, Qnil);
4083 set_hash_value_slot (h, i, Qnil);
4084 set_hash_hash_slot (h, i, Qnil);
4085 set_hash_next_slot (h, i, h->next_free);
4086 h->next_free = make_number (i);
4087 h->count--;
4088 eassert (h->count >= 0);
4089 break;
4091 else
4093 prev = idx;
4094 idx = HASH_NEXT (h, i);
4100 /* Clear hash table H. */
4102 static void
4103 hash_clear (struct Lisp_Hash_Table *h)
4105 if (h->count > 0)
4107 ptrdiff_t i, size = HASH_TABLE_SIZE (h);
4109 for (i = 0; i < size; ++i)
4111 set_hash_next_slot (h, i, i < size - 1 ? make_number (i + 1) : Qnil);
4112 set_hash_key_slot (h, i, Qnil);
4113 set_hash_value_slot (h, i, Qnil);
4114 set_hash_hash_slot (h, i, Qnil);
4117 for (i = 0; i < ASIZE (h->index); ++i)
4118 ASET (h->index, i, Qnil);
4120 h->next_free = make_number (0);
4121 h->count = 0;
4127 /************************************************************************
4128 Weak Hash Tables
4129 ************************************************************************/
4131 /* Sweep weak hash table H. REMOVE_ENTRIES_P means remove
4132 entries from the table that don't survive the current GC.
4133 !REMOVE_ENTRIES_P means mark entries that are in use. Value is
4134 true if anything was marked. */
4136 static bool
4137 sweep_weak_table (struct Lisp_Hash_Table *h, bool remove_entries_p)
4139 ptrdiff_t n = gc_asize (h->index);
4140 bool marked = false;
4142 for (ptrdiff_t bucket = 0; bucket < n; ++bucket)
4144 Lisp_Object idx, next, prev;
4146 /* Follow collision chain, removing entries that
4147 don't survive this garbage collection. */
4148 prev = Qnil;
4149 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
4151 ptrdiff_t i = XFASTINT (idx);
4152 bool key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
4153 bool value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
4154 bool remove_p;
4156 if (EQ (h->weak, Qkey))
4157 remove_p = !key_known_to_survive_p;
4158 else if (EQ (h->weak, Qvalue))
4159 remove_p = !value_known_to_survive_p;
4160 else if (EQ (h->weak, Qkey_or_value))
4161 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
4162 else if (EQ (h->weak, Qkey_and_value))
4163 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
4164 else
4165 emacs_abort ();
4167 next = HASH_NEXT (h, i);
4169 if (remove_entries_p)
4171 if (remove_p)
4173 /* Take out of collision chain. */
4174 if (NILP (prev))
4175 set_hash_index_slot (h, bucket, next);
4176 else
4177 set_hash_next_slot (h, XFASTINT (prev), next);
4179 /* Add to free list. */
4180 set_hash_next_slot (h, i, h->next_free);
4181 h->next_free = idx;
4183 /* Clear key, value, and hash. */
4184 set_hash_key_slot (h, i, Qnil);
4185 set_hash_value_slot (h, i, Qnil);
4186 set_hash_hash_slot (h, i, Qnil);
4188 h->count--;
4190 else
4192 prev = idx;
4195 else
4197 if (!remove_p)
4199 /* Make sure key and value survive. */
4200 if (!key_known_to_survive_p)
4202 mark_object (HASH_KEY (h, i));
4203 marked = 1;
4206 if (!value_known_to_survive_p)
4208 mark_object (HASH_VALUE (h, i));
4209 marked = 1;
4216 return marked;
4219 /* Remove elements from weak hash tables that don't survive the
4220 current garbage collection. Remove weak tables that don't survive
4221 from Vweak_hash_tables. Called from gc_sweep. */
4223 NO_INLINE /* For better stack traces */
4224 void
4225 sweep_weak_hash_tables (void)
4227 struct Lisp_Hash_Table *h, *used, *next;
4228 bool marked;
4230 /* Mark all keys and values that are in use. Keep on marking until
4231 there is no more change. This is necessary for cases like
4232 value-weak table A containing an entry X -> Y, where Y is used in a
4233 key-weak table B, Z -> Y. If B comes after A in the list of weak
4234 tables, X -> Y might be removed from A, although when looking at B
4235 one finds that it shouldn't. */
4238 marked = 0;
4239 for (h = weak_hash_tables; h; h = h->next_weak)
4241 if (h->header.size & ARRAY_MARK_FLAG)
4242 marked |= sweep_weak_table (h, 0);
4245 while (marked);
4247 /* Remove tables and entries that aren't used. */
4248 for (h = weak_hash_tables, used = NULL; h; h = next)
4250 next = h->next_weak;
4252 if (h->header.size & ARRAY_MARK_FLAG)
4254 /* TABLE is marked as used. Sweep its contents. */
4255 if (h->count > 0)
4256 sweep_weak_table (h, 1);
4258 /* Add table to the list of used weak hash tables. */
4259 h->next_weak = used;
4260 used = h;
4264 weak_hash_tables = used;
4269 /***********************************************************************
4270 Hash Code Computation
4271 ***********************************************************************/
4273 /* Maximum depth up to which to dive into Lisp structures. */
4275 #define SXHASH_MAX_DEPTH 3
4277 /* Maximum length up to which to take list and vector elements into
4278 account. */
4280 #define SXHASH_MAX_LEN 7
4282 /* Return a hash for string PTR which has length LEN. The hash value
4283 can be any EMACS_UINT value. */
4285 EMACS_UINT
4286 hash_string (char const *ptr, ptrdiff_t len)
4288 char const *p = ptr;
4289 char const *end = p + len;
4290 unsigned char c;
4291 EMACS_UINT hash = 0;
4293 while (p != end)
4295 c = *p++;
4296 hash = sxhash_combine (hash, c);
4299 return hash;
4302 /* Return a hash for string PTR which has length LEN. The hash
4303 code returned is guaranteed to fit in a Lisp integer. */
4305 static EMACS_UINT
4306 sxhash_string (char const *ptr, ptrdiff_t len)
4308 EMACS_UINT hash = hash_string (ptr, len);
4309 return SXHASH_REDUCE (hash);
4312 /* Return a hash for the floating point value VAL. */
4314 static EMACS_UINT
4315 sxhash_float (double val)
4317 EMACS_UINT hash = 0;
4318 enum {
4319 WORDS_PER_DOUBLE = (sizeof val / sizeof hash
4320 + (sizeof val % sizeof hash != 0))
4322 union {
4323 double val;
4324 EMACS_UINT word[WORDS_PER_DOUBLE];
4325 } u;
4326 int i;
4327 u.val = val;
4328 memset (&u.val + 1, 0, sizeof u - sizeof u.val);
4329 for (i = 0; i < WORDS_PER_DOUBLE; i++)
4330 hash = sxhash_combine (hash, u.word[i]);
4331 return SXHASH_REDUCE (hash);
4334 /* Return a hash for list LIST. DEPTH is the current depth in the
4335 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4337 static EMACS_UINT
4338 sxhash_list (Lisp_Object list, int depth)
4340 EMACS_UINT hash = 0;
4341 int i;
4343 if (depth < SXHASH_MAX_DEPTH)
4344 for (i = 0;
4345 CONSP (list) && i < SXHASH_MAX_LEN;
4346 list = XCDR (list), ++i)
4348 EMACS_UINT hash2 = sxhash (XCAR (list), depth + 1);
4349 hash = sxhash_combine (hash, hash2);
4352 if (!NILP (list))
4354 EMACS_UINT hash2 = sxhash (list, depth + 1);
4355 hash = sxhash_combine (hash, hash2);
4358 return SXHASH_REDUCE (hash);
4362 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4363 the Lisp structure. */
4365 static EMACS_UINT
4366 sxhash_vector (Lisp_Object vec, int depth)
4368 EMACS_UINT hash = ASIZE (vec);
4369 int i, n;
4371 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4372 for (i = 0; i < n; ++i)
4374 EMACS_UINT hash2 = sxhash (AREF (vec, i), depth + 1);
4375 hash = sxhash_combine (hash, hash2);
4378 return SXHASH_REDUCE (hash);
4381 /* Return a hash for bool-vector VECTOR. */
4383 static EMACS_UINT
4384 sxhash_bool_vector (Lisp_Object vec)
4386 EMACS_INT size = bool_vector_size (vec);
4387 EMACS_UINT hash = size;
4388 int i, n;
4390 n = min (SXHASH_MAX_LEN, bool_vector_words (size));
4391 for (i = 0; i < n; ++i)
4392 hash = sxhash_combine (hash, bool_vector_data (vec)[i]);
4394 return SXHASH_REDUCE (hash);
4398 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4399 structure. Value is an unsigned integer clipped to INTMASK. */
4401 EMACS_UINT
4402 sxhash (Lisp_Object obj, int depth)
4404 EMACS_UINT hash;
4406 if (depth > SXHASH_MAX_DEPTH)
4407 return 0;
4409 switch (XTYPE (obj))
4411 case_Lisp_Int:
4412 hash = XUINT (obj);
4413 break;
4415 case Lisp_Misc:
4416 case Lisp_Symbol:
4417 hash = XHASH (obj);
4418 break;
4420 case Lisp_String:
4421 hash = sxhash_string (SSDATA (obj), SBYTES (obj));
4422 break;
4424 /* This can be everything from a vector to an overlay. */
4425 case Lisp_Vectorlike:
4426 if (VECTORP (obj))
4427 /* According to the CL HyperSpec, two arrays are equal only if
4428 they are `eq', except for strings and bit-vectors. In
4429 Emacs, this works differently. We have to compare element
4430 by element. */
4431 hash = sxhash_vector (obj, depth);
4432 else if (BOOL_VECTOR_P (obj))
4433 hash = sxhash_bool_vector (obj);
4434 else
4435 /* Others are `equal' if they are `eq', so let's take their
4436 address as hash. */
4437 hash = XHASH (obj);
4438 break;
4440 case Lisp_Cons:
4441 hash = sxhash_list (obj, depth);
4442 break;
4444 case Lisp_Float:
4445 hash = sxhash_float (XFLOAT_DATA (obj));
4446 break;
4448 default:
4449 emacs_abort ();
4452 return hash;
4457 /***********************************************************************
4458 Lisp Interface
4459 ***********************************************************************/
4461 DEFUN ("sxhash-eq", Fsxhash_eq, Ssxhash_eq, 1, 1, 0,
4462 doc: /* Return an integer hash code for OBJ suitable for `eq'.
4463 If (eq A B), then (= (sxhash-eq A) (sxhash-eq B)). */)
4464 (Lisp_Object obj)
4466 return make_number (hashfn_eq (NULL, obj));
4469 DEFUN ("sxhash-eql", Fsxhash_eql, Ssxhash_eql, 1, 1, 0,
4470 doc: /* Return an integer hash code for OBJ suitable for `eql'.
4471 If (eql A B), then (= (sxhash-eql A) (sxhash-eql B)). */)
4472 (Lisp_Object obj)
4474 return make_number (hashfn_eql (NULL, obj));
4477 DEFUN ("sxhash-equal", Fsxhash_equal, Ssxhash_equal, 1, 1, 0,
4478 doc: /* Return an integer hash code for OBJ suitable for `equal'.
4479 If (equal A B), then (= (sxhash-equal A) (sxhash-equal B)). */)
4480 (Lisp_Object obj)
4482 return make_number (hashfn_equal (NULL, obj));
4485 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4486 doc: /* Create and return a new hash table.
4488 Arguments are specified as keyword/argument pairs. The following
4489 arguments are defined:
4491 :test TEST -- TEST must be a symbol that specifies how to compare
4492 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4493 `equal'. User-supplied test and hash functions can be specified via
4494 `define-hash-table-test'.
4496 :size SIZE -- A hint as to how many elements will be put in the table.
4497 Default is 65.
4499 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4500 fills up. If REHASH-SIZE is an integer, increase the size by that
4501 amount. If it is a float, it must be > 1.0, and the new size is the
4502 old size multiplied by that factor. Default is 1.5.
4504 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4505 Resize the hash table when the ratio (number of entries / table size)
4506 is greater than or equal to THRESHOLD. Default is 0.8.
4508 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4509 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4510 returned is a weak table. Key/value pairs are removed from a weak
4511 hash table when there are no non-weak references pointing to their
4512 key, value, one of key or value, or both key and value, depending on
4513 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4514 is nil.
4516 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4517 (ptrdiff_t nargs, Lisp_Object *args)
4519 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4520 struct hash_table_test testdesc;
4521 ptrdiff_t i;
4522 USE_SAFE_ALLOCA;
4524 /* The vector `used' is used to keep track of arguments that
4525 have been consumed. */
4526 char *used = SAFE_ALLOCA (nargs * sizeof *used);
4527 memset (used, 0, nargs * sizeof *used);
4529 /* See if there's a `:test TEST' among the arguments. */
4530 i = get_key_arg (QCtest, nargs, args, used);
4531 test = i ? args[i] : Qeql;
4532 if (EQ (test, Qeq))
4533 testdesc = hashtest_eq;
4534 else if (EQ (test, Qeql))
4535 testdesc = hashtest_eql;
4536 else if (EQ (test, Qequal))
4537 testdesc = hashtest_equal;
4538 else
4540 /* See if it is a user-defined test. */
4541 Lisp_Object prop;
4543 prop = Fget (test, Qhash_table_test);
4544 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4545 signal_error ("Invalid hash table test", test);
4546 testdesc.name = test;
4547 testdesc.user_cmp_function = XCAR (prop);
4548 testdesc.user_hash_function = XCAR (XCDR (prop));
4549 testdesc.hashfn = hashfn_user_defined;
4550 testdesc.cmpfn = cmpfn_user_defined;
4553 /* See if there's a `:size SIZE' argument. */
4554 i = get_key_arg (QCsize, nargs, args, used);
4555 size = i ? args[i] : Qnil;
4556 if (NILP (size))
4557 size = make_number (DEFAULT_HASH_SIZE);
4558 else if (!INTEGERP (size) || XINT (size) < 0)
4559 signal_error ("Invalid hash table size", size);
4561 /* Look for `:rehash-size SIZE'. */
4562 i = get_key_arg (QCrehash_size, nargs, args, used);
4563 rehash_size = i ? args[i] : make_float (DEFAULT_REHASH_SIZE);
4564 if (! ((INTEGERP (rehash_size) && 0 < XINT (rehash_size))
4565 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size))))
4566 signal_error ("Invalid hash table rehash size", rehash_size);
4568 /* Look for `:rehash-threshold THRESHOLD'. */
4569 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4570 rehash_threshold = i ? args[i] : make_float (DEFAULT_REHASH_THRESHOLD);
4571 if (! (FLOATP (rehash_threshold)
4572 && 0 < XFLOAT_DATA (rehash_threshold)
4573 && XFLOAT_DATA (rehash_threshold) <= 1))
4574 signal_error ("Invalid hash table rehash threshold", rehash_threshold);
4576 /* Look for `:weakness WEAK'. */
4577 i = get_key_arg (QCweakness, nargs, args, used);
4578 weak = i ? args[i] : Qnil;
4579 if (EQ (weak, Qt))
4580 weak = Qkey_and_value;
4581 if (!NILP (weak)
4582 && !EQ (weak, Qkey)
4583 && !EQ (weak, Qvalue)
4584 && !EQ (weak, Qkey_or_value)
4585 && !EQ (weak, Qkey_and_value))
4586 signal_error ("Invalid hash table weakness", weak);
4588 /* Now, all args should have been used up, or there's a problem. */
4589 for (i = 0; i < nargs; ++i)
4590 if (!used[i])
4591 signal_error ("Invalid argument list", args[i]);
4593 SAFE_FREE ();
4594 return make_hash_table (testdesc, size, rehash_size, rehash_threshold, weak);
4598 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4599 doc: /* Return a copy of hash table TABLE. */)
4600 (Lisp_Object table)
4602 return copy_hash_table (check_hash_table (table));
4606 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4607 doc: /* Return the number of elements in TABLE. */)
4608 (Lisp_Object table)
4610 return make_number (check_hash_table (table)->count);
4614 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4615 Shash_table_rehash_size, 1, 1, 0,
4616 doc: /* Return the current rehash size of TABLE. */)
4617 (Lisp_Object table)
4619 return check_hash_table (table)->rehash_size;
4623 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4624 Shash_table_rehash_threshold, 1, 1, 0,
4625 doc: /* Return the current rehash threshold of TABLE. */)
4626 (Lisp_Object table)
4628 return check_hash_table (table)->rehash_threshold;
4632 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4633 doc: /* Return the size of TABLE.
4634 The size can be used as an argument to `make-hash-table' to create
4635 a hash table than can hold as many elements as TABLE holds
4636 without need for resizing. */)
4637 (Lisp_Object table)
4639 struct Lisp_Hash_Table *h = check_hash_table (table);
4640 return make_number (HASH_TABLE_SIZE (h));
4644 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4645 doc: /* Return the test TABLE uses. */)
4646 (Lisp_Object table)
4648 return check_hash_table (table)->test.name;
4652 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4653 1, 1, 0,
4654 doc: /* Return the weakness of TABLE. */)
4655 (Lisp_Object table)
4657 return check_hash_table (table)->weak;
4661 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4662 doc: /* Return t if OBJ is a Lisp hash table object. */)
4663 (Lisp_Object obj)
4665 return HASH_TABLE_P (obj) ? Qt : Qnil;
4669 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4670 doc: /* Clear hash table TABLE and return it. */)
4671 (Lisp_Object table)
4673 hash_clear (check_hash_table (table));
4674 /* Be compatible with XEmacs. */
4675 return table;
4679 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4680 doc: /* Look up KEY in TABLE and return its associated value.
4681 If KEY is not found, return DFLT which defaults to nil. */)
4682 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4684 struct Lisp_Hash_Table *h = check_hash_table (table);
4685 ptrdiff_t i = hash_lookup (h, key, NULL);
4686 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4690 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4691 doc: /* Associate KEY with VALUE in hash table TABLE.
4692 If KEY is already present in table, replace its current value with
4693 VALUE. In any case, return VALUE. */)
4694 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4696 struct Lisp_Hash_Table *h = check_hash_table (table);
4697 ptrdiff_t i;
4698 EMACS_UINT hash;
4700 i = hash_lookup (h, key, &hash);
4701 if (i >= 0)
4702 set_hash_value_slot (h, i, value);
4703 else
4704 hash_put (h, key, value, hash);
4706 return value;
4710 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4711 doc: /* Remove KEY from TABLE. */)
4712 (Lisp_Object key, Lisp_Object table)
4714 struct Lisp_Hash_Table *h = check_hash_table (table);
4715 hash_remove_from_table (h, key);
4716 return Qnil;
4720 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4721 doc: /* Call FUNCTION for all entries in hash table TABLE.
4722 FUNCTION is called with two arguments, KEY and VALUE.
4723 `maphash' always returns nil. */)
4724 (Lisp_Object function, Lisp_Object table)
4726 struct Lisp_Hash_Table *h = check_hash_table (table);
4728 for (ptrdiff_t i = 0; i < HASH_TABLE_SIZE (h); ++i)
4729 if (!NILP (HASH_HASH (h, i)))
4730 call2 (function, HASH_KEY (h, i), HASH_VALUE (h, i));
4732 return Qnil;
4736 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4737 Sdefine_hash_table_test, 3, 3, 0,
4738 doc: /* Define a new hash table test with name NAME, a symbol.
4740 In hash tables created with NAME specified as test, use TEST to
4741 compare keys, and HASH for computing hash codes of keys.
4743 TEST must be a function taking two arguments and returning non-nil if
4744 both arguments are the same. HASH must be a function taking one
4745 argument and returning an object that is the hash code of the argument.
4746 It should be the case that if (eq (funcall HASH x1) (funcall HASH x2))
4747 returns nil, then (funcall TEST x1 x2) also returns nil. */)
4748 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4750 return Fput (name, Qhash_table_test, list2 (test, hash));
4755 /************************************************************************
4756 MD5, SHA-1, and SHA-2
4757 ************************************************************************/
4759 #include "md5.h"
4760 #include "sha1.h"
4761 #include "sha256.h"
4762 #include "sha512.h"
4764 static Lisp_Object
4765 make_digest_string (Lisp_Object digest, int digest_size)
4767 unsigned char *p = SDATA (digest);
4769 for (int i = digest_size - 1; i >= 0; i--)
4771 static char const hexdigit[16] = "0123456789abcdef";
4772 int p_i = p[i];
4773 p[2 * i] = hexdigit[p_i >> 4];
4774 p[2 * i + 1] = hexdigit[p_i & 0xf];
4776 return digest;
4779 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4781 static Lisp_Object
4782 secure_hash (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start,
4783 Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror,
4784 Lisp_Object binary)
4786 ptrdiff_t size, start_char = 0, start_byte, end_char = 0, end_byte;
4787 register EMACS_INT b, e;
4788 register struct buffer *bp;
4789 EMACS_INT temp;
4790 int digest_size;
4791 void *(*hash_func) (const char *, size_t, void *);
4792 Lisp_Object digest;
4794 CHECK_SYMBOL (algorithm);
4796 if (STRINGP (object))
4798 if (NILP (coding_system))
4800 /* Decide the coding-system to encode the data with. */
4802 if (STRING_MULTIBYTE (object))
4803 /* use default, we can't guess correct value */
4804 coding_system = preferred_coding_system ();
4805 else
4806 coding_system = Qraw_text;
4809 if (NILP (Fcoding_system_p (coding_system)))
4811 /* Invalid coding system. */
4813 if (!NILP (noerror))
4814 coding_system = Qraw_text;
4815 else
4816 xsignal1 (Qcoding_system_error, coding_system);
4819 if (STRING_MULTIBYTE (object))
4820 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4822 size = SCHARS (object);
4823 validate_subarray (object, start, end, size, &start_char, &end_char);
4825 start_byte = !start_char ? 0 : string_char_to_byte (object, start_char);
4826 end_byte = (end_char == size
4827 ? SBYTES (object)
4828 : string_char_to_byte (object, end_char));
4830 else
4832 struct buffer *prev = current_buffer;
4834 record_unwind_current_buffer ();
4836 CHECK_BUFFER (object);
4838 bp = XBUFFER (object);
4839 set_buffer_internal (bp);
4841 if (NILP (start))
4842 b = BEGV;
4843 else
4845 CHECK_NUMBER_COERCE_MARKER (start);
4846 b = XINT (start);
4849 if (NILP (end))
4850 e = ZV;
4851 else
4853 CHECK_NUMBER_COERCE_MARKER (end);
4854 e = XINT (end);
4857 if (b > e)
4858 temp = b, b = e, e = temp;
4860 if (!(BEGV <= b && e <= ZV))
4861 args_out_of_range (start, end);
4863 if (NILP (coding_system))
4865 /* Decide the coding-system to encode the data with.
4866 See fileio.c:Fwrite-region */
4868 if (!NILP (Vcoding_system_for_write))
4869 coding_system = Vcoding_system_for_write;
4870 else
4872 bool force_raw_text = 0;
4874 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4875 if (NILP (coding_system)
4876 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4878 coding_system = Qnil;
4879 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4880 force_raw_text = 1;
4883 if (NILP (coding_system) && !NILP (Fbuffer_file_name (object)))
4885 /* Check file-coding-system-alist. */
4886 Lisp_Object val = CALLN (Ffind_operation_coding_system,
4887 Qwrite_region, start, end,
4888 Fbuffer_file_name (object));
4889 if (CONSP (val) && !NILP (XCDR (val)))
4890 coding_system = XCDR (val);
4893 if (NILP (coding_system)
4894 && !NILP (BVAR (XBUFFER (object), buffer_file_coding_system)))
4896 /* If we still have not decided a coding system, use the
4897 default value of buffer-file-coding-system. */
4898 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4901 if (!force_raw_text
4902 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4903 /* Confirm that VAL can surely encode the current region. */
4904 coding_system = call4 (Vselect_safe_coding_system_function,
4905 make_number (b), make_number (e),
4906 coding_system, Qnil);
4908 if (force_raw_text)
4909 coding_system = Qraw_text;
4912 if (NILP (Fcoding_system_p (coding_system)))
4914 /* Invalid coding system. */
4916 if (!NILP (noerror))
4917 coding_system = Qraw_text;
4918 else
4919 xsignal1 (Qcoding_system_error, coding_system);
4923 object = make_buffer_string (b, e, 0);
4924 set_buffer_internal (prev);
4925 /* Discard the unwind protect for recovering the current
4926 buffer. */
4927 specpdl_ptr--;
4929 if (STRING_MULTIBYTE (object))
4930 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4931 start_byte = 0;
4932 end_byte = SBYTES (object);
4935 if (EQ (algorithm, Qmd5))
4937 digest_size = MD5_DIGEST_SIZE;
4938 hash_func = md5_buffer;
4940 else if (EQ (algorithm, Qsha1))
4942 digest_size = SHA1_DIGEST_SIZE;
4943 hash_func = sha1_buffer;
4945 else if (EQ (algorithm, Qsha224))
4947 digest_size = SHA224_DIGEST_SIZE;
4948 hash_func = sha224_buffer;
4950 else if (EQ (algorithm, Qsha256))
4952 digest_size = SHA256_DIGEST_SIZE;
4953 hash_func = sha256_buffer;
4955 else if (EQ (algorithm, Qsha384))
4957 digest_size = SHA384_DIGEST_SIZE;
4958 hash_func = sha384_buffer;
4960 else if (EQ (algorithm, Qsha512))
4962 digest_size = SHA512_DIGEST_SIZE;
4963 hash_func = sha512_buffer;
4965 else
4966 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm)));
4968 /* allocate 2 x digest_size so that it can be re-used to hold the
4969 hexified value */
4970 digest = make_uninit_string (digest_size * 2);
4972 hash_func (SSDATA (object) + start_byte,
4973 end_byte - start_byte,
4974 SSDATA (digest));
4976 if (NILP (binary))
4977 return make_digest_string (digest, digest_size);
4978 else
4979 return make_unibyte_string (SSDATA (digest), digest_size);
4982 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
4983 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
4985 A message digest is a cryptographic checksum of a document, and the
4986 algorithm to calculate it is defined in RFC 1321.
4988 The two optional arguments START and END are character positions
4989 specifying for which part of OBJECT the message digest should be
4990 computed. If nil or omitted, the digest is computed for the whole
4991 OBJECT.
4993 The MD5 message digest is computed from the result of encoding the
4994 text in a coding system, not directly from the internal Emacs form of
4995 the text. The optional fourth argument CODING-SYSTEM specifies which
4996 coding system to encode the text with. It should be the same coding
4997 system that you used or will use when actually writing the text into a
4998 file.
5000 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
5001 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
5002 system would be chosen by default for writing this text into a file.
5004 If OBJECT is a string, the most preferred coding system (see the
5005 command `prefer-coding-system') is used.
5007 If NOERROR is non-nil, silently assume the `raw-text' coding if the
5008 guesswork fails. Normally, an error is signaled in such case. */)
5009 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
5011 return secure_hash (Qmd5, object, start, end, coding_system, noerror, Qnil);
5014 DEFUN ("secure-hash", Fsecure_hash, Ssecure_hash, 2, 5, 0,
5015 doc: /* Return the secure hash of OBJECT, a buffer or string.
5016 ALGORITHM is a symbol specifying the hash to use:
5017 md5, sha1, sha224, sha256, sha384 or sha512.
5019 The two optional arguments START and END are positions specifying for
5020 which part of OBJECT to compute the hash. If nil or omitted, uses the
5021 whole OBJECT.
5023 If BINARY is non-nil, returns a string in binary form. */)
5024 (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object binary)
5026 return secure_hash (algorithm, object, start, end, Qnil, Qnil, binary);
5029 DEFUN ("buffer-hash", Fbuffer_hash, Sbuffer_hash, 0, 1, 0,
5030 doc: /* Return a hash of the contents of BUFFER-OR-NAME.
5031 This hash is performed on the raw internal format of the buffer,
5032 disregarding any coding systems.
5033 If nil, use the current buffer." */ )
5034 (Lisp_Object buffer_or_name)
5036 Lisp_Object buffer;
5037 struct buffer *b;
5038 struct sha1_ctx ctx;
5040 if (NILP (buffer_or_name))
5041 buffer = Fcurrent_buffer ();
5042 else
5043 buffer = Fget_buffer (buffer_or_name);
5044 if (NILP (buffer))
5045 nsberror (buffer_or_name);
5047 b = XBUFFER (buffer);
5048 sha1_init_ctx (&ctx);
5050 /* Process the first part of the buffer. */
5051 sha1_process_bytes (BUF_BEG_ADDR (b),
5052 BUF_GPT_BYTE (b) - BUF_BEG_BYTE (b),
5053 &ctx);
5055 /* If the gap is before the end of the buffer, process the last half
5056 of the buffer. */
5057 if (BUF_GPT_BYTE (b) < BUF_Z_BYTE (b))
5058 sha1_process_bytes (BUF_GAP_END_ADDR (b),
5059 BUF_Z_ADDR (b) - BUF_GAP_END_ADDR (b),
5060 &ctx);
5062 Lisp_Object digest = make_uninit_string (SHA1_DIGEST_SIZE * 2);
5063 sha1_finish_ctx (&ctx, SSDATA (digest));
5064 return make_digest_string (digest, SHA1_DIGEST_SIZE);
5068 void
5069 syms_of_fns (void)
5071 DEFSYM (Qmd5, "md5");
5072 DEFSYM (Qsha1, "sha1");
5073 DEFSYM (Qsha224, "sha224");
5074 DEFSYM (Qsha256, "sha256");
5075 DEFSYM (Qsha384, "sha384");
5076 DEFSYM (Qsha512, "sha512");
5078 /* Hash table stuff. */
5079 DEFSYM (Qhash_table_p, "hash-table-p");
5080 DEFSYM (Qeq, "eq");
5081 DEFSYM (Qeql, "eql");
5082 DEFSYM (Qequal, "equal");
5083 DEFSYM (QCtest, ":test");
5084 DEFSYM (QCsize, ":size");
5085 DEFSYM (QCrehash_size, ":rehash-size");
5086 DEFSYM (QCrehash_threshold, ":rehash-threshold");
5087 DEFSYM (QCweakness, ":weakness");
5088 DEFSYM (Qkey, "key");
5089 DEFSYM (Qvalue, "value");
5090 DEFSYM (Qhash_table_test, "hash-table-test");
5091 DEFSYM (Qkey_or_value, "key-or-value");
5092 DEFSYM (Qkey_and_value, "key-and-value");
5094 defsubr (&Ssxhash_eq);
5095 defsubr (&Ssxhash_eql);
5096 defsubr (&Ssxhash_equal);
5097 defsubr (&Smake_hash_table);
5098 defsubr (&Scopy_hash_table);
5099 defsubr (&Shash_table_count);
5100 defsubr (&Shash_table_rehash_size);
5101 defsubr (&Shash_table_rehash_threshold);
5102 defsubr (&Shash_table_size);
5103 defsubr (&Shash_table_test);
5104 defsubr (&Shash_table_weakness);
5105 defsubr (&Shash_table_p);
5106 defsubr (&Sclrhash);
5107 defsubr (&Sgethash);
5108 defsubr (&Sputhash);
5109 defsubr (&Sremhash);
5110 defsubr (&Smaphash);
5111 defsubr (&Sdefine_hash_table_test);
5113 DEFSYM (Qstring_lessp, "string-lessp");
5114 DEFSYM (Qprovide, "provide");
5115 DEFSYM (Qrequire, "require");
5116 DEFSYM (Qyes_or_no_p_history, "yes-or-no-p-history");
5117 DEFSYM (Qcursor_in_echo_area, "cursor-in-echo-area");
5118 DEFSYM (Qwidget_type, "widget-type");
5120 staticpro (&string_char_byte_cache_string);
5121 string_char_byte_cache_string = Qnil;
5123 require_nesting_list = Qnil;
5124 staticpro (&require_nesting_list);
5126 Fset (Qyes_or_no_p_history, Qnil);
5128 DEFVAR_LISP ("features", Vfeatures,
5129 doc: /* A list of symbols which are the features of the executing Emacs.
5130 Used by `featurep' and `require', and altered by `provide'. */);
5131 Vfeatures = list1 (Qemacs);
5132 DEFSYM (Qfeatures, "features");
5133 /* Let people use lexically scoped vars named `features'. */
5134 Fmake_var_non_special (Qfeatures);
5135 DEFSYM (Qsubfeatures, "subfeatures");
5136 DEFSYM (Qfuncall, "funcall");
5138 #ifdef HAVE_LANGINFO_CODESET
5139 DEFSYM (Qcodeset, "codeset");
5140 DEFSYM (Qdays, "days");
5141 DEFSYM (Qmonths, "months");
5142 DEFSYM (Qpaper, "paper");
5143 #endif /* HAVE_LANGINFO_CODESET */
5145 DEFVAR_BOOL ("use-dialog-box", use_dialog_box,
5146 doc: /* Non-nil means mouse commands use dialog boxes to ask questions.
5147 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
5148 invoked by mouse clicks and mouse menu items.
5150 On some platforms, file selection dialogs are also enabled if this is
5151 non-nil. */);
5152 use_dialog_box = 1;
5154 DEFVAR_BOOL ("use-file-dialog", use_file_dialog,
5155 doc: /* Non-nil means mouse commands use a file dialog to ask for files.
5156 This applies to commands from menus and tool bar buttons even when
5157 they are initiated from the keyboard. If `use-dialog-box' is nil,
5158 that disables the use of a file dialog, regardless of the value of
5159 this variable. */);
5160 use_file_dialog = 1;
5162 defsubr (&Sidentity);
5163 defsubr (&Srandom);
5164 defsubr (&Slength);
5165 defsubr (&Ssafe_length);
5166 defsubr (&Sstring_bytes);
5167 defsubr (&Sstring_equal);
5168 defsubr (&Scompare_strings);
5169 defsubr (&Sstring_lessp);
5170 defsubr (&Sstring_version_lessp);
5171 defsubr (&Sstring_collate_lessp);
5172 defsubr (&Sstring_collate_equalp);
5173 defsubr (&Sappend);
5174 defsubr (&Sconcat);
5175 defsubr (&Svconcat);
5176 defsubr (&Scopy_sequence);
5177 defsubr (&Sstring_make_multibyte);
5178 defsubr (&Sstring_make_unibyte);
5179 defsubr (&Sstring_as_multibyte);
5180 defsubr (&Sstring_as_unibyte);
5181 defsubr (&Sstring_to_multibyte);
5182 defsubr (&Sstring_to_unibyte);
5183 defsubr (&Scopy_alist);
5184 defsubr (&Ssubstring);
5185 defsubr (&Ssubstring_no_properties);
5186 defsubr (&Snthcdr);
5187 defsubr (&Snth);
5188 defsubr (&Selt);
5189 defsubr (&Smember);
5190 defsubr (&Smemq);
5191 defsubr (&Smemql);
5192 defsubr (&Sassq);
5193 defsubr (&Sassoc);
5194 defsubr (&Srassq);
5195 defsubr (&Srassoc);
5196 defsubr (&Sdelq);
5197 defsubr (&Sdelete);
5198 defsubr (&Snreverse);
5199 defsubr (&Sreverse);
5200 defsubr (&Ssort);
5201 defsubr (&Splist_get);
5202 defsubr (&Sget);
5203 defsubr (&Splist_put);
5204 defsubr (&Sput);
5205 defsubr (&Slax_plist_get);
5206 defsubr (&Slax_plist_put);
5207 defsubr (&Seql);
5208 defsubr (&Sequal);
5209 defsubr (&Sequal_including_properties);
5210 defsubr (&Sfillarray);
5211 defsubr (&Sclear_string);
5212 defsubr (&Snconc);
5213 defsubr (&Smapcar);
5214 defsubr (&Smapc);
5215 defsubr (&Smapcan);
5216 defsubr (&Smapconcat);
5217 defsubr (&Syes_or_no_p);
5218 defsubr (&Sload_average);
5219 defsubr (&Sfeaturep);
5220 defsubr (&Srequire);
5221 defsubr (&Sprovide);
5222 defsubr (&Splist_member);
5223 defsubr (&Swidget_put);
5224 defsubr (&Swidget_get);
5225 defsubr (&Swidget_apply);
5226 defsubr (&Sbase64_encode_region);
5227 defsubr (&Sbase64_decode_region);
5228 defsubr (&Sbase64_encode_string);
5229 defsubr (&Sbase64_decode_string);
5230 defsubr (&Smd5);
5231 defsubr (&Ssecure_hash);
5232 defsubr (&Sbuffer_hash);
5233 defsubr (&Slocale_info);