Make pcomplete less eager to add an extra space.
[emacs.git] / src / fns.c
blob42c4f817f2936fc75d8cd35e32317fd17f4864ae
1 /* Random utility Lisp functions.
2 Copyright (C) 1985-1987, 1993-1995, 1997-2012
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #include <unistd.h>
23 #include <time.h>
25 #include <intprops.h>
27 #include "lisp.h"
28 #include "commands.h"
29 #include "character.h"
30 #include "coding.h"
31 #include "buffer.h"
32 #include "keyboard.h"
33 #include "keymap.h"
34 #include "intervals.h"
35 #include "frame.h"
36 #include "window.h"
37 #include "blockinput.h"
38 #ifdef HAVE_MENUS
39 #if defined (HAVE_X_WINDOWS)
40 #include "xterm.h"
41 #endif
42 #endif /* HAVE_MENUS */
44 Lisp_Object Qstring_lessp;
45 static Lisp_Object Qprovide, Qrequire;
46 static Lisp_Object Qyes_or_no_p_history;
47 Lisp_Object Qcursor_in_echo_area;
48 static Lisp_Object Qwidget_type;
49 static Lisp_Object Qcodeset, Qdays, Qmonths, Qpaper;
51 static Lisp_Object Qmd5, Qsha1, Qsha224, Qsha256, Qsha384, Qsha512;
53 static bool internal_equal (Lisp_Object, Lisp_Object, int, bool);
55 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
56 doc: /* Return the argument unchanged. */)
57 (Lisp_Object arg)
59 return arg;
62 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
63 doc: /* Return a pseudo-random number.
64 All integers representable in Lisp are equally likely.
65 On most systems, this is 29 bits' worth.
66 With positive integer LIMIT, return random number in interval [0,LIMIT).
67 With argument t, set the random number seed from the current time and pid.
68 Other values of LIMIT are ignored. */)
69 (Lisp_Object limit)
71 EMACS_INT val;
73 if (EQ (limit, Qt))
74 init_random ();
75 else if (STRINGP (limit))
76 seed_random (SSDATA (limit), SBYTES (limit));
78 val = get_random ();
79 if (NATNUMP (limit) && XFASTINT (limit) != 0)
80 val %= XFASTINT (limit);
81 return make_number (val);
84 /* Heuristic on how many iterations of a tight loop can be safely done
85 before it's time to do a QUIT. This must be a power of 2. */
86 enum { QUIT_COUNT_HEURISTIC = 1 << 16 };
88 /* Random data-structure functions */
90 DEFUN ("length", Flength, Slength, 1, 1, 0,
91 doc: /* Return the length of vector, list or string SEQUENCE.
92 A byte-code function object is also allowed.
93 If the string contains multibyte characters, this is not necessarily
94 the number of bytes in the string; it is the number of characters.
95 To get the number of bytes, use `string-bytes'. */)
96 (register Lisp_Object sequence)
98 register Lisp_Object val;
100 if (STRINGP (sequence))
101 XSETFASTINT (val, SCHARS (sequence));
102 else if (VECTORP (sequence))
103 XSETFASTINT (val, ASIZE (sequence));
104 else if (CHAR_TABLE_P (sequence))
105 XSETFASTINT (val, MAX_CHAR);
106 else if (BOOL_VECTOR_P (sequence))
107 XSETFASTINT (val, XBOOL_VECTOR (sequence)->size);
108 else if (COMPILEDP (sequence))
109 XSETFASTINT (val, ASIZE (sequence) & PSEUDOVECTOR_SIZE_MASK);
110 else if (CONSP (sequence))
112 EMACS_INT i = 0;
116 ++i;
117 if ((i & (QUIT_COUNT_HEURISTIC - 1)) == 0)
119 if (MOST_POSITIVE_FIXNUM < i)
120 error ("List too long");
121 QUIT;
123 sequence = XCDR (sequence);
125 while (CONSP (sequence));
127 CHECK_LIST_END (sequence, sequence);
129 val = make_number (i);
131 else if (NILP (sequence))
132 XSETFASTINT (val, 0);
133 else
134 wrong_type_argument (Qsequencep, sequence);
136 return val;
139 /* This does not check for quits. That is safe since it must terminate. */
141 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
142 doc: /* Return the length of a list, but avoid error or infinite loop.
143 This function never gets an error. If LIST is not really a list,
144 it returns 0. If LIST is circular, it returns a finite value
145 which is at least the number of distinct elements. */)
146 (Lisp_Object list)
148 Lisp_Object tail, halftail;
149 double hilen = 0;
150 uintmax_t lolen = 1;
152 if (! CONSP (list))
153 return make_number (0);
155 /* halftail is used to detect circular lists. */
156 for (tail = halftail = list; ; )
158 tail = XCDR (tail);
159 if (! CONSP (tail))
160 break;
161 if (EQ (tail, halftail))
162 break;
163 lolen++;
164 if ((lolen & 1) == 0)
166 halftail = XCDR (halftail);
167 if ((lolen & (QUIT_COUNT_HEURISTIC - 1)) == 0)
169 QUIT;
170 if (lolen == 0)
171 hilen += UINTMAX_MAX + 1.0;
176 /* If the length does not fit into a fixnum, return a float.
177 On all known practical machines this returns an upper bound on
178 the true length. */
179 return hilen ? make_float (hilen + lolen) : make_fixnum_or_float (lolen);
182 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
183 doc: /* Return the number of bytes in STRING.
184 If STRING is multibyte, this may be greater than the length of STRING. */)
185 (Lisp_Object string)
187 CHECK_STRING (string);
188 return make_number (SBYTES (string));
191 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
192 doc: /* Return t if two strings have identical contents.
193 Case is significant, but text properties are ignored.
194 Symbols are also allowed; their print names are used instead. */)
195 (register Lisp_Object s1, Lisp_Object s2)
197 if (SYMBOLP (s1))
198 s1 = SYMBOL_NAME (s1);
199 if (SYMBOLP (s2))
200 s2 = SYMBOL_NAME (s2);
201 CHECK_STRING (s1);
202 CHECK_STRING (s2);
204 if (SCHARS (s1) != SCHARS (s2)
205 || SBYTES (s1) != SBYTES (s2)
206 || memcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
207 return Qnil;
208 return Qt;
211 DEFUN ("compare-strings", Fcompare_strings, Scompare_strings, 6, 7, 0,
212 doc: /* Compare the contents of two strings, converting to multibyte if needed.
213 In string STR1, skip the first START1 characters and stop at END1.
214 In string STR2, skip the first START2 characters and stop at END2.
215 END1 and END2 default to the full lengths of the respective strings.
217 Case is significant in this comparison if IGNORE-CASE is nil.
218 Unibyte strings are converted to multibyte for comparison.
220 The value is t if the strings (or specified portions) match.
221 If string STR1 is less, the value is a negative number N;
222 - 1 - N is the number of characters that match at the beginning.
223 If string STR1 is greater, the value is a positive number N;
224 N - 1 is the number of characters that match at the beginning. */)
225 (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2, Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
227 register ptrdiff_t end1_char, end2_char;
228 register ptrdiff_t i1, i1_byte, i2, i2_byte;
230 CHECK_STRING (str1);
231 CHECK_STRING (str2);
232 if (NILP (start1))
233 start1 = make_number (0);
234 if (NILP (start2))
235 start2 = make_number (0);
236 CHECK_NATNUM (start1);
237 CHECK_NATNUM (start2);
238 if (! NILP (end1))
239 CHECK_NATNUM (end1);
240 if (! NILP (end2))
241 CHECK_NATNUM (end2);
243 end1_char = SCHARS (str1);
244 if (! NILP (end1) && end1_char > XINT (end1))
245 end1_char = XINT (end1);
246 if (end1_char < XINT (start1))
247 args_out_of_range (str1, start1);
249 end2_char = SCHARS (str2);
250 if (! NILP (end2) && end2_char > XINT (end2))
251 end2_char = XINT (end2);
252 if (end2_char < XINT (start2))
253 args_out_of_range (str2, start2);
255 i1 = XINT (start1);
256 i2 = XINT (start2);
258 i1_byte = string_char_to_byte (str1, i1);
259 i2_byte = string_char_to_byte (str2, i2);
261 while (i1 < end1_char && i2 < end2_char)
263 /* When we find a mismatch, we must compare the
264 characters, not just the bytes. */
265 int c1, c2;
267 if (STRING_MULTIBYTE (str1))
268 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c1, str1, i1, i1_byte);
269 else
271 c1 = SREF (str1, i1++);
272 MAKE_CHAR_MULTIBYTE (c1);
275 if (STRING_MULTIBYTE (str2))
276 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c2, str2, i2, i2_byte);
277 else
279 c2 = SREF (str2, i2++);
280 MAKE_CHAR_MULTIBYTE (c2);
283 if (c1 == c2)
284 continue;
286 if (! NILP (ignore_case))
288 Lisp_Object tem;
290 tem = Fupcase (make_number (c1));
291 c1 = XINT (tem);
292 tem = Fupcase (make_number (c2));
293 c2 = XINT (tem);
296 if (c1 == c2)
297 continue;
299 /* Note that I1 has already been incremented
300 past the character that we are comparing;
301 hence we don't add or subtract 1 here. */
302 if (c1 < c2)
303 return make_number (- i1 + XINT (start1));
304 else
305 return make_number (i1 - XINT (start1));
308 if (i1 < end1_char)
309 return make_number (i1 - XINT (start1) + 1);
310 if (i2 < end2_char)
311 return make_number (- i1 + XINT (start1) - 1);
313 return Qt;
316 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
317 doc: /* Return t if first arg string is less than second in lexicographic order.
318 Case is significant.
319 Symbols are also allowed; their print names are used instead. */)
320 (register Lisp_Object s1, Lisp_Object s2)
322 register ptrdiff_t end;
323 register ptrdiff_t i1, i1_byte, i2, i2_byte;
325 if (SYMBOLP (s1))
326 s1 = SYMBOL_NAME (s1);
327 if (SYMBOLP (s2))
328 s2 = SYMBOL_NAME (s2);
329 CHECK_STRING (s1);
330 CHECK_STRING (s2);
332 i1 = i1_byte = i2 = i2_byte = 0;
334 end = SCHARS (s1);
335 if (end > SCHARS (s2))
336 end = SCHARS (s2);
338 while (i1 < end)
340 /* When we find a mismatch, we must compare the
341 characters, not just the bytes. */
342 int c1, c2;
344 FETCH_STRING_CHAR_ADVANCE (c1, s1, i1, i1_byte);
345 FETCH_STRING_CHAR_ADVANCE (c2, s2, i2, i2_byte);
347 if (c1 != c2)
348 return c1 < c2 ? Qt : Qnil;
350 return i1 < SCHARS (s2) ? Qt : Qnil;
353 static Lisp_Object concat (ptrdiff_t nargs, Lisp_Object *args,
354 enum Lisp_Type target_type, bool last_special);
356 /* ARGSUSED */
357 Lisp_Object
358 concat2 (Lisp_Object s1, Lisp_Object s2)
360 Lisp_Object args[2];
361 args[0] = s1;
362 args[1] = s2;
363 return concat (2, args, Lisp_String, 0);
366 /* ARGSUSED */
367 Lisp_Object
368 concat3 (Lisp_Object s1, Lisp_Object s2, Lisp_Object s3)
370 Lisp_Object args[3];
371 args[0] = s1;
372 args[1] = s2;
373 args[2] = s3;
374 return concat (3, args, Lisp_String, 0);
377 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
378 doc: /* Concatenate all the arguments and make the result a list.
379 The result is a list whose elements are the elements of all the arguments.
380 Each argument may be a list, vector or string.
381 The last argument is not copied, just used as the tail of the new list.
382 usage: (append &rest SEQUENCES) */)
383 (ptrdiff_t nargs, Lisp_Object *args)
385 return concat (nargs, args, Lisp_Cons, 1);
388 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
389 doc: /* Concatenate all the arguments and make the result a string.
390 The result is a string whose elements are the elements of all the arguments.
391 Each argument may be a string or a list or vector of characters (integers).
392 usage: (concat &rest SEQUENCES) */)
393 (ptrdiff_t nargs, Lisp_Object *args)
395 return concat (nargs, args, Lisp_String, 0);
398 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
399 doc: /* Concatenate all the arguments and make the result a vector.
400 The result is a vector whose elements are the elements of all the arguments.
401 Each argument may be a list, vector or string.
402 usage: (vconcat &rest SEQUENCES) */)
403 (ptrdiff_t nargs, Lisp_Object *args)
405 return concat (nargs, args, Lisp_Vectorlike, 0);
409 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
410 doc: /* Return a copy of a list, vector, string or char-table.
411 The elements of a list or vector are not copied; they are shared
412 with the original. */)
413 (Lisp_Object arg)
415 if (NILP (arg)) return arg;
417 if (CHAR_TABLE_P (arg))
419 return copy_char_table (arg);
422 if (BOOL_VECTOR_P (arg))
424 Lisp_Object val;
425 ptrdiff_t size_in_chars
426 = ((XBOOL_VECTOR (arg)->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
427 / BOOL_VECTOR_BITS_PER_CHAR);
429 val = Fmake_bool_vector (Flength (arg), Qnil);
430 memcpy (XBOOL_VECTOR (val)->data, XBOOL_VECTOR (arg)->data,
431 size_in_chars);
432 return val;
435 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
436 wrong_type_argument (Qsequencep, arg);
438 return concat (1, &arg, CONSP (arg) ? Lisp_Cons : XTYPE (arg), 0);
441 /* This structure holds information of an argument of `concat' that is
442 a string and has text properties to be copied. */
443 struct textprop_rec
445 ptrdiff_t argnum; /* refer to ARGS (arguments of `concat') */
446 ptrdiff_t from; /* refer to ARGS[argnum] (argument string) */
447 ptrdiff_t to; /* refer to VAL (the target string) */
450 static Lisp_Object
451 concat (ptrdiff_t nargs, Lisp_Object *args,
452 enum Lisp_Type target_type, bool last_special)
454 Lisp_Object val;
455 Lisp_Object tail;
456 Lisp_Object this;
457 ptrdiff_t toindex;
458 ptrdiff_t toindex_byte = 0;
459 EMACS_INT result_len;
460 EMACS_INT result_len_byte;
461 ptrdiff_t argnum;
462 Lisp_Object last_tail;
463 Lisp_Object prev;
464 bool some_multibyte;
465 /* When we make a multibyte string, we can't copy text properties
466 while concatenating each string because the length of resulting
467 string can't be decided until we finish the whole concatenation.
468 So, we record strings that have text properties to be copied
469 here, and copy the text properties after the concatenation. */
470 struct textprop_rec *textprops = NULL;
471 /* Number of elements in textprops. */
472 ptrdiff_t num_textprops = 0;
473 USE_SAFE_ALLOCA;
475 tail = Qnil;
477 /* In append, the last arg isn't treated like the others */
478 if (last_special && nargs > 0)
480 nargs--;
481 last_tail = args[nargs];
483 else
484 last_tail = Qnil;
486 /* Check each argument. */
487 for (argnum = 0; argnum < nargs; argnum++)
489 this = args[argnum];
490 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
491 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
492 wrong_type_argument (Qsequencep, this);
495 /* Compute total length in chars of arguments in RESULT_LEN.
496 If desired output is a string, also compute length in bytes
497 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
498 whether the result should be a multibyte string. */
499 result_len_byte = 0;
500 result_len = 0;
501 some_multibyte = 0;
502 for (argnum = 0; argnum < nargs; argnum++)
504 EMACS_INT len;
505 this = args[argnum];
506 len = XFASTINT (Flength (this));
507 if (target_type == Lisp_String)
509 /* We must count the number of bytes needed in the string
510 as well as the number of characters. */
511 ptrdiff_t i;
512 Lisp_Object ch;
513 int c;
514 ptrdiff_t this_len_byte;
516 if (VECTORP (this) || COMPILEDP (this))
517 for (i = 0; i < len; i++)
519 ch = AREF (this, i);
520 CHECK_CHARACTER (ch);
521 c = XFASTINT (ch);
522 this_len_byte = CHAR_BYTES (c);
523 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
524 string_overflow ();
525 result_len_byte += this_len_byte;
526 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
527 some_multibyte = 1;
529 else if (BOOL_VECTOR_P (this) && XBOOL_VECTOR (this)->size > 0)
530 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
531 else if (CONSP (this))
532 for (; CONSP (this); this = XCDR (this))
534 ch = XCAR (this);
535 CHECK_CHARACTER (ch);
536 c = XFASTINT (ch);
537 this_len_byte = CHAR_BYTES (c);
538 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
539 string_overflow ();
540 result_len_byte += this_len_byte;
541 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
542 some_multibyte = 1;
544 else if (STRINGP (this))
546 if (STRING_MULTIBYTE (this))
548 some_multibyte = 1;
549 this_len_byte = SBYTES (this);
551 else
552 this_len_byte = count_size_as_multibyte (SDATA (this),
553 SCHARS (this));
554 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
555 string_overflow ();
556 result_len_byte += this_len_byte;
560 result_len += len;
561 if (MOST_POSITIVE_FIXNUM < result_len)
562 memory_full (SIZE_MAX);
565 if (! some_multibyte)
566 result_len_byte = result_len;
568 /* Create the output object. */
569 if (target_type == Lisp_Cons)
570 val = Fmake_list (make_number (result_len), Qnil);
571 else if (target_type == Lisp_Vectorlike)
572 val = Fmake_vector (make_number (result_len), Qnil);
573 else if (some_multibyte)
574 val = make_uninit_multibyte_string (result_len, result_len_byte);
575 else
576 val = make_uninit_string (result_len);
578 /* In `append', if all but last arg are nil, return last arg. */
579 if (target_type == Lisp_Cons && EQ (val, Qnil))
580 return last_tail;
582 /* Copy the contents of the args into the result. */
583 if (CONSP (val))
584 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
585 else
586 toindex = 0, toindex_byte = 0;
588 prev = Qnil;
589 if (STRINGP (val))
590 SAFE_NALLOCA (textprops, 1, nargs);
592 for (argnum = 0; argnum < nargs; argnum++)
594 Lisp_Object thislen;
595 ptrdiff_t thisleni = 0;
596 register ptrdiff_t thisindex = 0;
597 register ptrdiff_t thisindex_byte = 0;
599 this = args[argnum];
600 if (!CONSP (this))
601 thislen = Flength (this), thisleni = XINT (thislen);
603 /* Between strings of the same kind, copy fast. */
604 if (STRINGP (this) && STRINGP (val)
605 && STRING_MULTIBYTE (this) == some_multibyte)
607 ptrdiff_t thislen_byte = SBYTES (this);
609 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
610 if (string_intervals (this))
612 textprops[num_textprops].argnum = argnum;
613 textprops[num_textprops].from = 0;
614 textprops[num_textprops++].to = toindex;
616 toindex_byte += thislen_byte;
617 toindex += thisleni;
619 /* Copy a single-byte string to a multibyte string. */
620 else if (STRINGP (this) && STRINGP (val))
622 if (string_intervals (this))
624 textprops[num_textprops].argnum = argnum;
625 textprops[num_textprops].from = 0;
626 textprops[num_textprops++].to = toindex;
628 toindex_byte += copy_text (SDATA (this),
629 SDATA (val) + toindex_byte,
630 SCHARS (this), 0, 1);
631 toindex += thisleni;
633 else
634 /* Copy element by element. */
635 while (1)
637 register Lisp_Object elt;
639 /* Fetch next element of `this' arg into `elt', or break if
640 `this' is exhausted. */
641 if (NILP (this)) break;
642 if (CONSP (this))
643 elt = XCAR (this), this = XCDR (this);
644 else if (thisindex >= thisleni)
645 break;
646 else if (STRINGP (this))
648 int c;
649 if (STRING_MULTIBYTE (this))
650 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
651 thisindex,
652 thisindex_byte);
653 else
655 c = SREF (this, thisindex); thisindex++;
656 if (some_multibyte && !ASCII_CHAR_P (c))
657 c = BYTE8_TO_CHAR (c);
659 XSETFASTINT (elt, c);
661 else if (BOOL_VECTOR_P (this))
663 int byte;
664 byte = XBOOL_VECTOR (this)->data[thisindex / BOOL_VECTOR_BITS_PER_CHAR];
665 if (byte & (1 << (thisindex % BOOL_VECTOR_BITS_PER_CHAR)))
666 elt = Qt;
667 else
668 elt = Qnil;
669 thisindex++;
671 else
673 elt = AREF (this, thisindex);
674 thisindex++;
677 /* Store this element into the result. */
678 if (toindex < 0)
680 XSETCAR (tail, elt);
681 prev = tail;
682 tail = XCDR (tail);
684 else if (VECTORP (val))
686 ASET (val, toindex, elt);
687 toindex++;
689 else
691 int c;
692 CHECK_CHARACTER (elt);
693 c = XFASTINT (elt);
694 if (some_multibyte)
695 toindex_byte += CHAR_STRING (c, SDATA (val) + toindex_byte);
696 else
697 SSET (val, toindex_byte++, c);
698 toindex++;
702 if (!NILP (prev))
703 XSETCDR (prev, last_tail);
705 if (num_textprops > 0)
707 Lisp_Object props;
708 ptrdiff_t last_to_end = -1;
710 for (argnum = 0; argnum < num_textprops; argnum++)
712 this = args[textprops[argnum].argnum];
713 props = text_property_list (this,
714 make_number (0),
715 make_number (SCHARS (this)),
716 Qnil);
717 /* If successive arguments have properties, be sure that the
718 value of `composition' property be the copy. */
719 if (last_to_end == textprops[argnum].to)
720 make_composition_value_copy (props);
721 add_text_properties_from_list (val, props,
722 make_number (textprops[argnum].to));
723 last_to_end = textprops[argnum].to + SCHARS (this);
727 SAFE_FREE ();
728 return val;
731 static Lisp_Object string_char_byte_cache_string;
732 static ptrdiff_t string_char_byte_cache_charpos;
733 static ptrdiff_t string_char_byte_cache_bytepos;
735 void
736 clear_string_char_byte_cache (void)
738 string_char_byte_cache_string = Qnil;
741 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
743 ptrdiff_t
744 string_char_to_byte (Lisp_Object string, ptrdiff_t char_index)
746 ptrdiff_t i_byte;
747 ptrdiff_t best_below, best_below_byte;
748 ptrdiff_t best_above, best_above_byte;
750 best_below = best_below_byte = 0;
751 best_above = SCHARS (string);
752 best_above_byte = SBYTES (string);
753 if (best_above == best_above_byte)
754 return char_index;
756 if (EQ (string, string_char_byte_cache_string))
758 if (string_char_byte_cache_charpos < char_index)
760 best_below = string_char_byte_cache_charpos;
761 best_below_byte = string_char_byte_cache_bytepos;
763 else
765 best_above = string_char_byte_cache_charpos;
766 best_above_byte = string_char_byte_cache_bytepos;
770 if (char_index - best_below < best_above - char_index)
772 unsigned char *p = SDATA (string) + best_below_byte;
774 while (best_below < char_index)
776 p += BYTES_BY_CHAR_HEAD (*p);
777 best_below++;
779 i_byte = p - SDATA (string);
781 else
783 unsigned char *p = SDATA (string) + best_above_byte;
785 while (best_above > char_index)
787 p--;
788 while (!CHAR_HEAD_P (*p)) p--;
789 best_above--;
791 i_byte = p - SDATA (string);
794 string_char_byte_cache_bytepos = i_byte;
795 string_char_byte_cache_charpos = char_index;
796 string_char_byte_cache_string = string;
798 return i_byte;
801 /* Return the character index corresponding to BYTE_INDEX in STRING. */
803 ptrdiff_t
804 string_byte_to_char (Lisp_Object string, ptrdiff_t byte_index)
806 ptrdiff_t i, i_byte;
807 ptrdiff_t best_below, best_below_byte;
808 ptrdiff_t best_above, best_above_byte;
810 best_below = best_below_byte = 0;
811 best_above = SCHARS (string);
812 best_above_byte = SBYTES (string);
813 if (best_above == best_above_byte)
814 return byte_index;
816 if (EQ (string, string_char_byte_cache_string))
818 if (string_char_byte_cache_bytepos < byte_index)
820 best_below = string_char_byte_cache_charpos;
821 best_below_byte = string_char_byte_cache_bytepos;
823 else
825 best_above = string_char_byte_cache_charpos;
826 best_above_byte = string_char_byte_cache_bytepos;
830 if (byte_index - best_below_byte < best_above_byte - byte_index)
832 unsigned char *p = SDATA (string) + best_below_byte;
833 unsigned char *pend = SDATA (string) + byte_index;
835 while (p < pend)
837 p += BYTES_BY_CHAR_HEAD (*p);
838 best_below++;
840 i = best_below;
841 i_byte = p - SDATA (string);
843 else
845 unsigned char *p = SDATA (string) + best_above_byte;
846 unsigned char *pbeg = SDATA (string) + byte_index;
848 while (p > pbeg)
850 p--;
851 while (!CHAR_HEAD_P (*p)) p--;
852 best_above--;
854 i = best_above;
855 i_byte = p - SDATA (string);
858 string_char_byte_cache_bytepos = i_byte;
859 string_char_byte_cache_charpos = i;
860 string_char_byte_cache_string = string;
862 return i;
865 /* Convert STRING to a multibyte string. */
867 static Lisp_Object
868 string_make_multibyte (Lisp_Object string)
870 unsigned char *buf;
871 ptrdiff_t nbytes;
872 Lisp_Object ret;
873 USE_SAFE_ALLOCA;
875 if (STRING_MULTIBYTE (string))
876 return string;
878 nbytes = count_size_as_multibyte (SDATA (string),
879 SCHARS (string));
880 /* If all the chars are ASCII, they won't need any more bytes
881 once converted. In that case, we can return STRING itself. */
882 if (nbytes == SBYTES (string))
883 return string;
885 buf = SAFE_ALLOCA (nbytes);
886 copy_text (SDATA (string), buf, SBYTES (string),
887 0, 1);
889 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
890 SAFE_FREE ();
892 return ret;
896 /* Convert STRING (if unibyte) to a multibyte string without changing
897 the number of characters. Characters 0200 trough 0237 are
898 converted to eight-bit characters. */
900 Lisp_Object
901 string_to_multibyte (Lisp_Object string)
903 unsigned char *buf;
904 ptrdiff_t nbytes;
905 Lisp_Object ret;
906 USE_SAFE_ALLOCA;
908 if (STRING_MULTIBYTE (string))
909 return string;
911 nbytes = count_size_as_multibyte (SDATA (string), SBYTES (string));
912 /* If all the chars are ASCII, they won't need any more bytes once
913 converted. */
914 if (nbytes == SBYTES (string))
915 return make_multibyte_string (SSDATA (string), nbytes, nbytes);
917 buf = SAFE_ALLOCA (nbytes);
918 memcpy (buf, SDATA (string), SBYTES (string));
919 str_to_multibyte (buf, nbytes, SBYTES (string));
921 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
922 SAFE_FREE ();
924 return ret;
928 /* Convert STRING to a single-byte string. */
930 Lisp_Object
931 string_make_unibyte (Lisp_Object string)
933 ptrdiff_t nchars;
934 unsigned char *buf;
935 Lisp_Object ret;
936 USE_SAFE_ALLOCA;
938 if (! STRING_MULTIBYTE (string))
939 return string;
941 nchars = SCHARS (string);
943 buf = SAFE_ALLOCA (nchars);
944 copy_text (SDATA (string), buf, SBYTES (string),
945 1, 0);
947 ret = make_unibyte_string ((char *) buf, nchars);
948 SAFE_FREE ();
950 return ret;
953 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
954 1, 1, 0,
955 doc: /* Return the multibyte equivalent of STRING.
956 If STRING is unibyte and contains non-ASCII characters, the function
957 `unibyte-char-to-multibyte' is used to convert each unibyte character
958 to a multibyte character. In this case, the returned string is a
959 newly created string with no text properties. If STRING is multibyte
960 or entirely ASCII, it is returned unchanged. In particular, when
961 STRING is unibyte and entirely ASCII, the returned string is unibyte.
962 \(When the characters are all ASCII, Emacs primitives will treat the
963 string the same way whether it is unibyte or multibyte.) */)
964 (Lisp_Object string)
966 CHECK_STRING (string);
968 return string_make_multibyte (string);
971 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
972 1, 1, 0,
973 doc: /* Return the unibyte equivalent of STRING.
974 Multibyte character codes are converted to unibyte according to
975 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
976 If the lookup in the translation table fails, this function takes just
977 the low 8 bits of each character. */)
978 (Lisp_Object string)
980 CHECK_STRING (string);
982 return string_make_unibyte (string);
985 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
986 1, 1, 0,
987 doc: /* Return a unibyte string with the same individual bytes as STRING.
988 If STRING is unibyte, the result is STRING itself.
989 Otherwise it is a newly created string, with no text properties.
990 If STRING is multibyte and contains a character of charset
991 `eight-bit', it is converted to the corresponding single byte. */)
992 (Lisp_Object string)
994 CHECK_STRING (string);
996 if (STRING_MULTIBYTE (string))
998 ptrdiff_t bytes = SBYTES (string);
999 unsigned char *str = xmalloc (bytes);
1001 memcpy (str, SDATA (string), bytes);
1002 bytes = str_as_unibyte (str, bytes);
1003 string = make_unibyte_string ((char *) str, bytes);
1004 xfree (str);
1006 return string;
1009 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1010 1, 1, 0,
1011 doc: /* Return a multibyte string with the same individual bytes as STRING.
1012 If STRING is multibyte, the result is STRING itself.
1013 Otherwise it is a newly created string, with no text properties.
1015 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1016 part of a correct utf-8 sequence), it is converted to the corresponding
1017 multibyte character of charset `eight-bit'.
1018 See also `string-to-multibyte'.
1020 Beware, this often doesn't really do what you think it does.
1021 It is similar to (decode-coding-string STRING 'utf-8-emacs).
1022 If you're not sure, whether to use `string-as-multibyte' or
1023 `string-to-multibyte', use `string-to-multibyte'. */)
1024 (Lisp_Object string)
1026 CHECK_STRING (string);
1028 if (! STRING_MULTIBYTE (string))
1030 Lisp_Object new_string;
1031 ptrdiff_t nchars, nbytes;
1033 parse_str_as_multibyte (SDATA (string),
1034 SBYTES (string),
1035 &nchars, &nbytes);
1036 new_string = make_uninit_multibyte_string (nchars, nbytes);
1037 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1038 if (nbytes != SBYTES (string))
1039 str_as_multibyte (SDATA (new_string), nbytes,
1040 SBYTES (string), NULL);
1041 string = new_string;
1042 set_string_intervals (string, NULL);
1044 return string;
1047 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1048 1, 1, 0,
1049 doc: /* Return a multibyte string with the same individual chars as STRING.
1050 If STRING is multibyte, the result is STRING itself.
1051 Otherwise it is a newly created string, with no text properties.
1053 If STRING is unibyte and contains an 8-bit byte, it is converted to
1054 the corresponding multibyte character of charset `eight-bit'.
1056 This differs from `string-as-multibyte' by converting each byte of a correct
1057 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1058 correct sequence. */)
1059 (Lisp_Object string)
1061 CHECK_STRING (string);
1063 return string_to_multibyte (string);
1066 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1067 1, 1, 0,
1068 doc: /* Return a unibyte string with the same individual chars as STRING.
1069 If STRING is unibyte, the result is STRING itself.
1070 Otherwise it is a newly created string, with no text properties,
1071 where each `eight-bit' character is converted to the corresponding byte.
1072 If STRING contains a non-ASCII, non-`eight-bit' character,
1073 an error is signaled. */)
1074 (Lisp_Object string)
1076 CHECK_STRING (string);
1078 if (STRING_MULTIBYTE (string))
1080 ptrdiff_t chars = SCHARS (string);
1081 unsigned char *str = xmalloc (chars);
1082 ptrdiff_t converted = str_to_unibyte (SDATA (string), str, chars);
1084 if (converted < chars)
1085 error ("Can't convert the %"pD"dth character to unibyte", converted);
1086 string = make_unibyte_string ((char *) str, chars);
1087 xfree (str);
1089 return string;
1093 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1094 doc: /* Return a copy of ALIST.
1095 This is an alist which represents the same mapping from objects to objects,
1096 but does not share the alist structure with ALIST.
1097 The objects mapped (cars and cdrs of elements of the alist)
1098 are shared, however.
1099 Elements of ALIST that are not conses are also shared. */)
1100 (Lisp_Object alist)
1102 register Lisp_Object tem;
1104 CHECK_LIST (alist);
1105 if (NILP (alist))
1106 return alist;
1107 alist = concat (1, &alist, Lisp_Cons, 0);
1108 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1110 register Lisp_Object car;
1111 car = XCAR (tem);
1113 if (CONSP (car))
1114 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1116 return alist;
1119 DEFUN ("substring", Fsubstring, Ssubstring, 2, 3, 0,
1120 doc: /* Return a new string whose contents are a substring of STRING.
1121 The returned string consists of the characters between index FROM
1122 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1123 zero-indexed: 0 means the first character of STRING. Negative values
1124 are counted from the end of STRING. If TO is nil, the substring runs
1125 to the end of STRING.
1127 The STRING argument may also be a vector. In that case, the return
1128 value is a new vector that contains the elements between index FROM
1129 \(inclusive) and index TO (exclusive) of that vector argument. */)
1130 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1132 Lisp_Object res;
1133 ptrdiff_t size;
1134 EMACS_INT from_char, to_char;
1136 CHECK_VECTOR_OR_STRING (string);
1137 CHECK_NUMBER (from);
1139 if (STRINGP (string))
1140 size = SCHARS (string);
1141 else
1142 size = ASIZE (string);
1144 if (NILP (to))
1145 to_char = size;
1146 else
1148 CHECK_NUMBER (to);
1150 to_char = XINT (to);
1151 if (to_char < 0)
1152 to_char += size;
1155 from_char = XINT (from);
1156 if (from_char < 0)
1157 from_char += size;
1158 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1159 args_out_of_range_3 (string, make_number (from_char),
1160 make_number (to_char));
1162 if (STRINGP (string))
1164 ptrdiff_t to_byte =
1165 (NILP (to) ? SBYTES (string) : string_char_to_byte (string, to_char));
1166 ptrdiff_t from_byte = string_char_to_byte (string, from_char);
1167 res = make_specified_string (SSDATA (string) + from_byte,
1168 to_char - from_char, to_byte - from_byte,
1169 STRING_MULTIBYTE (string));
1170 copy_text_properties (make_number (from_char), make_number (to_char),
1171 string, make_number (0), res, Qnil);
1173 else
1174 res = Fvector (to_char - from_char, aref_addr (string, from_char));
1176 return res;
1180 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1181 doc: /* Return a substring of STRING, without text properties.
1182 It starts at index FROM and ends before TO.
1183 TO may be nil or omitted; then the substring runs to the end of STRING.
1184 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1185 If FROM or TO is negative, it counts from the end.
1187 With one argument, just copy STRING without its properties. */)
1188 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1190 ptrdiff_t size;
1191 EMACS_INT from_char, to_char;
1192 ptrdiff_t from_byte, to_byte;
1194 CHECK_STRING (string);
1196 size = SCHARS (string);
1198 if (NILP (from))
1199 from_char = 0;
1200 else
1202 CHECK_NUMBER (from);
1203 from_char = XINT (from);
1204 if (from_char < 0)
1205 from_char += size;
1208 if (NILP (to))
1209 to_char = size;
1210 else
1212 CHECK_NUMBER (to);
1213 to_char = XINT (to);
1214 if (to_char < 0)
1215 to_char += size;
1218 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1219 args_out_of_range_3 (string, make_number (from_char),
1220 make_number (to_char));
1222 from_byte = NILP (from) ? 0 : string_char_to_byte (string, from_char);
1223 to_byte =
1224 NILP (to) ? SBYTES (string) : string_char_to_byte (string, to_char);
1225 return make_specified_string (SSDATA (string) + from_byte,
1226 to_char - from_char, to_byte - from_byte,
1227 STRING_MULTIBYTE (string));
1230 /* Extract a substring of STRING, giving start and end positions
1231 both in characters and in bytes. */
1233 Lisp_Object
1234 substring_both (Lisp_Object string, ptrdiff_t from, ptrdiff_t from_byte,
1235 ptrdiff_t to, ptrdiff_t to_byte)
1237 Lisp_Object res;
1238 ptrdiff_t size;
1240 CHECK_VECTOR_OR_STRING (string);
1242 size = STRINGP (string) ? SCHARS (string) : ASIZE (string);
1244 if (!(0 <= from && from <= to && to <= size))
1245 args_out_of_range_3 (string, make_number (from), make_number (to));
1247 if (STRINGP (string))
1249 res = make_specified_string (SSDATA (string) + from_byte,
1250 to - from, to_byte - from_byte,
1251 STRING_MULTIBYTE (string));
1252 copy_text_properties (make_number (from), make_number (to),
1253 string, make_number (0), res, Qnil);
1255 else
1256 res = Fvector (to - from, aref_addr (string, from));
1258 return res;
1261 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1262 doc: /* Take cdr N times on LIST, return the result. */)
1263 (Lisp_Object n, Lisp_Object list)
1265 EMACS_INT i, num;
1266 CHECK_NUMBER (n);
1267 num = XINT (n);
1268 for (i = 0; i < num && !NILP (list); i++)
1270 QUIT;
1271 CHECK_LIST_CONS (list, list);
1272 list = XCDR (list);
1274 return list;
1277 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1278 doc: /* Return the Nth element of LIST.
1279 N counts from zero. If LIST is not that long, nil is returned. */)
1280 (Lisp_Object n, Lisp_Object list)
1282 return Fcar (Fnthcdr (n, list));
1285 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1286 doc: /* Return element of SEQUENCE at index N. */)
1287 (register Lisp_Object sequence, Lisp_Object n)
1289 CHECK_NUMBER (n);
1290 if (CONSP (sequence) || NILP (sequence))
1291 return Fcar (Fnthcdr (n, sequence));
1293 /* Faref signals a "not array" error, so check here. */
1294 CHECK_ARRAY (sequence, Qsequencep);
1295 return Faref (sequence, n);
1298 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1299 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1300 The value is actually the tail of LIST whose car is ELT. */)
1301 (register Lisp_Object elt, Lisp_Object list)
1303 register Lisp_Object tail;
1304 for (tail = list; CONSP (tail); tail = XCDR (tail))
1306 register Lisp_Object tem;
1307 CHECK_LIST_CONS (tail, list);
1308 tem = XCAR (tail);
1309 if (! NILP (Fequal (elt, tem)))
1310 return tail;
1311 QUIT;
1313 return Qnil;
1316 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1317 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1318 The value is actually the tail of LIST whose car is ELT. */)
1319 (register Lisp_Object elt, Lisp_Object list)
1321 while (1)
1323 if (!CONSP (list) || EQ (XCAR (list), elt))
1324 break;
1326 list = XCDR (list);
1327 if (!CONSP (list) || EQ (XCAR (list), elt))
1328 break;
1330 list = XCDR (list);
1331 if (!CONSP (list) || EQ (XCAR (list), elt))
1332 break;
1334 list = XCDR (list);
1335 QUIT;
1338 CHECK_LIST (list);
1339 return list;
1342 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1343 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1344 The value is actually the tail of LIST whose car is ELT. */)
1345 (register Lisp_Object elt, Lisp_Object list)
1347 register Lisp_Object tail;
1349 if (!FLOATP (elt))
1350 return Fmemq (elt, list);
1352 for (tail = list; CONSP (tail); tail = XCDR (tail))
1354 register Lisp_Object tem;
1355 CHECK_LIST_CONS (tail, list);
1356 tem = XCAR (tail);
1357 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0))
1358 return tail;
1359 QUIT;
1361 return Qnil;
1364 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1365 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1366 The value is actually the first element of LIST whose car is KEY.
1367 Elements of LIST that are not conses are ignored. */)
1368 (Lisp_Object key, Lisp_Object list)
1370 while (1)
1372 if (!CONSP (list)
1373 || (CONSP (XCAR (list))
1374 && EQ (XCAR (XCAR (list)), key)))
1375 break;
1377 list = XCDR (list);
1378 if (!CONSP (list)
1379 || (CONSP (XCAR (list))
1380 && EQ (XCAR (XCAR (list)), key)))
1381 break;
1383 list = XCDR (list);
1384 if (!CONSP (list)
1385 || (CONSP (XCAR (list))
1386 && EQ (XCAR (XCAR (list)), key)))
1387 break;
1389 list = XCDR (list);
1390 QUIT;
1393 return CAR (list);
1396 /* Like Fassq but never report an error and do not allow quits.
1397 Use only on lists known never to be circular. */
1399 Lisp_Object
1400 assq_no_quit (Lisp_Object key, Lisp_Object list)
1402 while (CONSP (list)
1403 && (!CONSP (XCAR (list))
1404 || !EQ (XCAR (XCAR (list)), key)))
1405 list = XCDR (list);
1407 return CAR_SAFE (list);
1410 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1411 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1412 The value is actually the first element of LIST whose car equals KEY. */)
1413 (Lisp_Object key, Lisp_Object list)
1415 Lisp_Object car;
1417 while (1)
1419 if (!CONSP (list)
1420 || (CONSP (XCAR (list))
1421 && (car = XCAR (XCAR (list)),
1422 EQ (car, key) || !NILP (Fequal (car, key)))))
1423 break;
1425 list = XCDR (list);
1426 if (!CONSP (list)
1427 || (CONSP (XCAR (list))
1428 && (car = XCAR (XCAR (list)),
1429 EQ (car, key) || !NILP (Fequal (car, key)))))
1430 break;
1432 list = XCDR (list);
1433 if (!CONSP (list)
1434 || (CONSP (XCAR (list))
1435 && (car = XCAR (XCAR (list)),
1436 EQ (car, key) || !NILP (Fequal (car, key)))))
1437 break;
1439 list = XCDR (list);
1440 QUIT;
1443 return CAR (list);
1446 /* Like Fassoc but never report an error and do not allow quits.
1447 Use only on lists known never to be circular. */
1449 Lisp_Object
1450 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1452 while (CONSP (list)
1453 && (!CONSP (XCAR (list))
1454 || (!EQ (XCAR (XCAR (list)), key)
1455 && NILP (Fequal (XCAR (XCAR (list)), key)))))
1456 list = XCDR (list);
1458 return CONSP (list) ? XCAR (list) : Qnil;
1461 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1462 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1463 The value is actually the first element of LIST whose cdr is KEY. */)
1464 (register Lisp_Object key, Lisp_Object list)
1466 while (1)
1468 if (!CONSP (list)
1469 || (CONSP (XCAR (list))
1470 && EQ (XCDR (XCAR (list)), key)))
1471 break;
1473 list = XCDR (list);
1474 if (!CONSP (list)
1475 || (CONSP (XCAR (list))
1476 && EQ (XCDR (XCAR (list)), key)))
1477 break;
1479 list = XCDR (list);
1480 if (!CONSP (list)
1481 || (CONSP (XCAR (list))
1482 && EQ (XCDR (XCAR (list)), key)))
1483 break;
1485 list = XCDR (list);
1486 QUIT;
1489 return CAR (list);
1492 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1493 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1494 The value is actually the first element of LIST whose cdr equals KEY. */)
1495 (Lisp_Object key, Lisp_Object list)
1497 Lisp_Object cdr;
1499 while (1)
1501 if (!CONSP (list)
1502 || (CONSP (XCAR (list))
1503 && (cdr = XCDR (XCAR (list)),
1504 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1505 break;
1507 list = XCDR (list);
1508 if (!CONSP (list)
1509 || (CONSP (XCAR (list))
1510 && (cdr = XCDR (XCAR (list)),
1511 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1512 break;
1514 list = XCDR (list);
1515 if (!CONSP (list)
1516 || (CONSP (XCAR (list))
1517 && (cdr = XCDR (XCAR (list)),
1518 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1519 break;
1521 list = XCDR (list);
1522 QUIT;
1525 return CAR (list);
1528 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1529 doc: /* Delete members of LIST which are `eq' to ELT, and return the result.
1530 More precisely, this function skips any members `eq' to ELT at the
1531 front of LIST, then removes members `eq' to ELT from the remaining
1532 sublist by modifying its list structure, then returns the resulting
1533 list.
1535 Write `(setq foo (delq element foo))' to be sure of correctly changing
1536 the value of a list `foo'. */)
1537 (register Lisp_Object elt, Lisp_Object list)
1539 register Lisp_Object tail, prev;
1540 register Lisp_Object tem;
1542 tail = list;
1543 prev = Qnil;
1544 while (!NILP (tail))
1546 CHECK_LIST_CONS (tail, list);
1547 tem = XCAR (tail);
1548 if (EQ (elt, tem))
1550 if (NILP (prev))
1551 list = XCDR (tail);
1552 else
1553 Fsetcdr (prev, XCDR (tail));
1555 else
1556 prev = tail;
1557 tail = XCDR (tail);
1558 QUIT;
1560 return list;
1563 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1564 doc: /* Delete members of SEQ which are `equal' to ELT, and return the result.
1565 SEQ must be a sequence (i.e. a list, a vector, or a string).
1566 The return value is a sequence of the same type.
1568 If SEQ is a list, this behaves like `delq', except that it compares
1569 with `equal' instead of `eq'. In particular, it may remove elements
1570 by altering the list structure.
1572 If SEQ is not a list, deletion is never performed destructively;
1573 instead this function creates and returns a new vector or string.
1575 Write `(setq foo (delete element foo))' to be sure of correctly
1576 changing the value of a sequence `foo'. */)
1577 (Lisp_Object elt, Lisp_Object seq)
1579 if (VECTORP (seq))
1581 ptrdiff_t i, n;
1583 for (i = n = 0; i < ASIZE (seq); ++i)
1584 if (NILP (Fequal (AREF (seq, i), elt)))
1585 ++n;
1587 if (n != ASIZE (seq))
1589 struct Lisp_Vector *p = allocate_vector (n);
1591 for (i = n = 0; i < ASIZE (seq); ++i)
1592 if (NILP (Fequal (AREF (seq, i), elt)))
1593 p->contents[n++] = AREF (seq, i);
1595 XSETVECTOR (seq, p);
1598 else if (STRINGP (seq))
1600 ptrdiff_t i, ibyte, nchars, nbytes, cbytes;
1601 int c;
1603 for (i = nchars = nbytes = ibyte = 0;
1604 i < SCHARS (seq);
1605 ++i, ibyte += cbytes)
1607 if (STRING_MULTIBYTE (seq))
1609 c = STRING_CHAR (SDATA (seq) + ibyte);
1610 cbytes = CHAR_BYTES (c);
1612 else
1614 c = SREF (seq, i);
1615 cbytes = 1;
1618 if (!INTEGERP (elt) || c != XINT (elt))
1620 ++nchars;
1621 nbytes += cbytes;
1625 if (nchars != SCHARS (seq))
1627 Lisp_Object tem;
1629 tem = make_uninit_multibyte_string (nchars, nbytes);
1630 if (!STRING_MULTIBYTE (seq))
1631 STRING_SET_UNIBYTE (tem);
1633 for (i = nchars = nbytes = ibyte = 0;
1634 i < SCHARS (seq);
1635 ++i, ibyte += cbytes)
1637 if (STRING_MULTIBYTE (seq))
1639 c = STRING_CHAR (SDATA (seq) + ibyte);
1640 cbytes = CHAR_BYTES (c);
1642 else
1644 c = SREF (seq, i);
1645 cbytes = 1;
1648 if (!INTEGERP (elt) || c != XINT (elt))
1650 unsigned char *from = SDATA (seq) + ibyte;
1651 unsigned char *to = SDATA (tem) + nbytes;
1652 ptrdiff_t n;
1654 ++nchars;
1655 nbytes += cbytes;
1657 for (n = cbytes; n--; )
1658 *to++ = *from++;
1662 seq = tem;
1665 else
1667 Lisp_Object tail, prev;
1669 for (tail = seq, prev = Qnil; CONSP (tail); tail = XCDR (tail))
1671 CHECK_LIST_CONS (tail, seq);
1673 if (!NILP (Fequal (elt, XCAR (tail))))
1675 if (NILP (prev))
1676 seq = XCDR (tail);
1677 else
1678 Fsetcdr (prev, XCDR (tail));
1680 else
1681 prev = tail;
1682 QUIT;
1686 return seq;
1689 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1690 doc: /* Reverse LIST by modifying cdr pointers.
1691 Return the reversed list. */)
1692 (Lisp_Object list)
1694 register Lisp_Object prev, tail, next;
1696 if (NILP (list)) return list;
1697 prev = Qnil;
1698 tail = list;
1699 while (!NILP (tail))
1701 QUIT;
1702 CHECK_LIST_CONS (tail, list);
1703 next = XCDR (tail);
1704 Fsetcdr (tail, prev);
1705 prev = tail;
1706 tail = next;
1708 return prev;
1711 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1712 doc: /* Reverse LIST, copying. Return the reversed list.
1713 See also the function `nreverse', which is used more often. */)
1714 (Lisp_Object list)
1716 Lisp_Object new;
1718 for (new = Qnil; CONSP (list); list = XCDR (list))
1720 QUIT;
1721 new = Fcons (XCAR (list), new);
1723 CHECK_LIST_END (list, list);
1724 return new;
1727 Lisp_Object merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred);
1729 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
1730 doc: /* Sort LIST, stably, comparing elements using PREDICATE.
1731 Returns the sorted list. LIST is modified by side effects.
1732 PREDICATE is called with two elements of LIST, and should return non-nil
1733 if the first element should sort before the second. */)
1734 (Lisp_Object list, Lisp_Object predicate)
1736 Lisp_Object front, back;
1737 register Lisp_Object len, tem;
1738 struct gcpro gcpro1, gcpro2;
1739 EMACS_INT length;
1741 front = list;
1742 len = Flength (list);
1743 length = XINT (len);
1744 if (length < 2)
1745 return list;
1747 XSETINT (len, (length / 2) - 1);
1748 tem = Fnthcdr (len, list);
1749 back = Fcdr (tem);
1750 Fsetcdr (tem, Qnil);
1752 GCPRO2 (front, back);
1753 front = Fsort (front, predicate);
1754 back = Fsort (back, predicate);
1755 UNGCPRO;
1756 return merge (front, back, predicate);
1759 Lisp_Object
1760 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
1762 Lisp_Object value;
1763 register Lisp_Object tail;
1764 Lisp_Object tem;
1765 register Lisp_Object l1, l2;
1766 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1768 l1 = org_l1;
1769 l2 = org_l2;
1770 tail = Qnil;
1771 value = Qnil;
1773 /* It is sufficient to protect org_l1 and org_l2.
1774 When l1 and l2 are updated, we copy the new values
1775 back into the org_ vars. */
1776 GCPRO4 (org_l1, org_l2, pred, value);
1778 while (1)
1780 if (NILP (l1))
1782 UNGCPRO;
1783 if (NILP (tail))
1784 return l2;
1785 Fsetcdr (tail, l2);
1786 return value;
1788 if (NILP (l2))
1790 UNGCPRO;
1791 if (NILP (tail))
1792 return l1;
1793 Fsetcdr (tail, l1);
1794 return value;
1796 tem = call2 (pred, Fcar (l2), Fcar (l1));
1797 if (NILP (tem))
1799 tem = l1;
1800 l1 = Fcdr (l1);
1801 org_l1 = l1;
1803 else
1805 tem = l2;
1806 l2 = Fcdr (l2);
1807 org_l2 = l2;
1809 if (NILP (tail))
1810 value = tem;
1811 else
1812 Fsetcdr (tail, tem);
1813 tail = tem;
1818 /* This does not check for quits. That is safe since it must terminate. */
1820 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
1821 doc: /* Extract a value from a property list.
1822 PLIST is a property list, which is a list of the form
1823 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1824 corresponding to the given PROP, or nil if PROP is not one of the
1825 properties on the list. This function never signals an error. */)
1826 (Lisp_Object plist, Lisp_Object prop)
1828 Lisp_Object tail, halftail;
1830 /* halftail is used to detect circular lists. */
1831 tail = halftail = plist;
1832 while (CONSP (tail) && CONSP (XCDR (tail)))
1834 if (EQ (prop, XCAR (tail)))
1835 return XCAR (XCDR (tail));
1837 tail = XCDR (XCDR (tail));
1838 halftail = XCDR (halftail);
1839 if (EQ (tail, halftail))
1840 break;
1842 #if 0 /* Unsafe version. */
1843 /* This function can be called asynchronously
1844 (setup_coding_system). Don't QUIT in that case. */
1845 if (!interrupt_input_blocked)
1846 QUIT;
1847 #endif
1850 return Qnil;
1853 DEFUN ("get", Fget, Sget, 2, 2, 0,
1854 doc: /* Return the value of SYMBOL's PROPNAME property.
1855 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
1856 (Lisp_Object symbol, Lisp_Object propname)
1858 CHECK_SYMBOL (symbol);
1859 return Fplist_get (XSYMBOL (symbol)->plist, propname);
1862 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
1863 doc: /* Change value in PLIST of PROP to VAL.
1864 PLIST is a property list, which is a list of the form
1865 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
1866 If PROP is already a property on the list, its value is set to VAL,
1867 otherwise the new PROP VAL pair is added. The new plist is returned;
1868 use `(setq x (plist-put x prop val))' to be sure to use the new value.
1869 The PLIST is modified by side effects. */)
1870 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1872 register Lisp_Object tail, prev;
1873 Lisp_Object newcell;
1874 prev = Qnil;
1875 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1876 tail = XCDR (XCDR (tail)))
1878 if (EQ (prop, XCAR (tail)))
1880 Fsetcar (XCDR (tail), val);
1881 return plist;
1884 prev = tail;
1885 QUIT;
1887 newcell = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
1888 if (NILP (prev))
1889 return newcell;
1890 else
1891 Fsetcdr (XCDR (prev), newcell);
1892 return plist;
1895 DEFUN ("put", Fput, Sput, 3, 3, 0,
1896 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
1897 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
1898 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
1900 CHECK_SYMBOL (symbol);
1901 set_symbol_plist
1902 (symbol, Fplist_put (XSYMBOL (symbol)->plist, propname, value));
1903 return value;
1906 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
1907 doc: /* Extract a value from a property list, comparing with `equal'.
1908 PLIST is a property list, which is a list of the form
1909 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1910 corresponding to the given PROP, or nil if PROP is not
1911 one of the properties on the list. */)
1912 (Lisp_Object plist, Lisp_Object prop)
1914 Lisp_Object tail;
1916 for (tail = plist;
1917 CONSP (tail) && CONSP (XCDR (tail));
1918 tail = XCDR (XCDR (tail)))
1920 if (! NILP (Fequal (prop, XCAR (tail))))
1921 return XCAR (XCDR (tail));
1923 QUIT;
1926 CHECK_LIST_END (tail, prop);
1928 return Qnil;
1931 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
1932 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
1933 PLIST is a property list, which is a list of the form
1934 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
1935 If PROP is already a property on the list, its value is set to VAL,
1936 otherwise the new PROP VAL pair is added. The new plist is returned;
1937 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
1938 The PLIST is modified by side effects. */)
1939 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1941 register Lisp_Object tail, prev;
1942 Lisp_Object newcell;
1943 prev = Qnil;
1944 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1945 tail = XCDR (XCDR (tail)))
1947 if (! NILP (Fequal (prop, XCAR (tail))))
1949 Fsetcar (XCDR (tail), val);
1950 return plist;
1953 prev = tail;
1954 QUIT;
1956 newcell = Fcons (prop, Fcons (val, Qnil));
1957 if (NILP (prev))
1958 return newcell;
1959 else
1960 Fsetcdr (XCDR (prev), newcell);
1961 return plist;
1964 DEFUN ("eql", Feql, Seql, 2, 2, 0,
1965 doc: /* Return t if the two args are the same Lisp object.
1966 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
1967 (Lisp_Object obj1, Lisp_Object obj2)
1969 if (FLOATP (obj1))
1970 return internal_equal (obj1, obj2, 0, 0) ? Qt : Qnil;
1971 else
1972 return EQ (obj1, obj2) ? Qt : Qnil;
1975 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
1976 doc: /* Return t if two Lisp objects have similar structure and contents.
1977 They must have the same data type.
1978 Conses are compared by comparing the cars and the cdrs.
1979 Vectors and strings are compared element by element.
1980 Numbers are compared by value, but integers cannot equal floats.
1981 (Use `=' if you want integers and floats to be able to be equal.)
1982 Symbols must match exactly. */)
1983 (register Lisp_Object o1, Lisp_Object o2)
1985 return internal_equal (o1, o2, 0, 0) ? Qt : Qnil;
1988 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
1989 doc: /* Return t if two Lisp objects have similar structure and contents.
1990 This is like `equal' except that it compares the text properties
1991 of strings. (`equal' ignores text properties.) */)
1992 (register Lisp_Object o1, Lisp_Object o2)
1994 return internal_equal (o1, o2, 0, 1) ? Qt : Qnil;
1997 /* DEPTH is current depth of recursion. Signal an error if it
1998 gets too deep.
1999 PROPS means compare string text properties too. */
2001 static bool
2002 internal_equal (Lisp_Object o1, Lisp_Object o2, int depth, bool props)
2004 if (depth > 200)
2005 error ("Stack overflow in equal");
2007 tail_recurse:
2008 QUIT;
2009 if (EQ (o1, o2))
2010 return 1;
2011 if (XTYPE (o1) != XTYPE (o2))
2012 return 0;
2014 switch (XTYPE (o1))
2016 case Lisp_Float:
2018 double d1, d2;
2020 d1 = extract_float (o1);
2021 d2 = extract_float (o2);
2022 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2023 though they are not =. */
2024 return d1 == d2 || (d1 != d1 && d2 != d2);
2027 case Lisp_Cons:
2028 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1, props))
2029 return 0;
2030 o1 = XCDR (o1);
2031 o2 = XCDR (o2);
2032 goto tail_recurse;
2034 case Lisp_Misc:
2035 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2036 return 0;
2037 if (OVERLAYP (o1))
2039 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2040 depth + 1, props)
2041 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2042 depth + 1, props))
2043 return 0;
2044 o1 = XOVERLAY (o1)->plist;
2045 o2 = XOVERLAY (o2)->plist;
2046 goto tail_recurse;
2048 if (MARKERP (o1))
2050 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2051 && (XMARKER (o1)->buffer == 0
2052 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2054 break;
2056 case Lisp_Vectorlike:
2058 register int i;
2059 ptrdiff_t size = ASIZE (o1);
2060 /* Pseudovectors have the type encoded in the size field, so this test
2061 actually checks that the objects have the same type as well as the
2062 same size. */
2063 if (ASIZE (o2) != size)
2064 return 0;
2065 /* Boolvectors are compared much like strings. */
2066 if (BOOL_VECTOR_P (o1))
2068 if (XBOOL_VECTOR (o1)->size != XBOOL_VECTOR (o2)->size)
2069 return 0;
2070 if (memcmp (XBOOL_VECTOR (o1)->data, XBOOL_VECTOR (o2)->data,
2071 ((XBOOL_VECTOR (o1)->size
2072 + BOOL_VECTOR_BITS_PER_CHAR - 1)
2073 / BOOL_VECTOR_BITS_PER_CHAR)))
2074 return 0;
2075 return 1;
2077 if (WINDOW_CONFIGURATIONP (o1))
2078 return compare_window_configurations (o1, o2, 0);
2080 /* Aside from them, only true vectors, char-tables, compiled
2081 functions, and fonts (font-spec, font-entity, font-object)
2082 are sensible to compare, so eliminate the others now. */
2083 if (size & PSEUDOVECTOR_FLAG)
2085 if (!(size & ((PVEC_COMPILED | PVEC_CHAR_TABLE
2086 | PVEC_SUB_CHAR_TABLE | PVEC_FONT)
2087 << PSEUDOVECTOR_SIZE_BITS)))
2088 return 0;
2089 size &= PSEUDOVECTOR_SIZE_MASK;
2091 for (i = 0; i < size; i++)
2093 Lisp_Object v1, v2;
2094 v1 = AREF (o1, i);
2095 v2 = AREF (o2, i);
2096 if (!internal_equal (v1, v2, depth + 1, props))
2097 return 0;
2099 return 1;
2101 break;
2103 case Lisp_String:
2104 if (SCHARS (o1) != SCHARS (o2))
2105 return 0;
2106 if (SBYTES (o1) != SBYTES (o2))
2107 return 0;
2108 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2109 return 0;
2110 if (props && !compare_string_intervals (o1, o2))
2111 return 0;
2112 return 1;
2114 default:
2115 break;
2118 return 0;
2122 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2123 doc: /* Store each element of ARRAY with ITEM.
2124 ARRAY is a vector, string, char-table, or bool-vector. */)
2125 (Lisp_Object array, Lisp_Object item)
2127 register ptrdiff_t size, idx;
2129 if (VECTORP (array))
2130 for (idx = 0, size = ASIZE (array); idx < size; idx++)
2131 ASET (array, idx, item);
2132 else if (CHAR_TABLE_P (array))
2134 int i;
2136 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2137 set_char_table_contents (array, i, item);
2138 set_char_table_defalt (array, item);
2140 else if (STRINGP (array))
2142 register unsigned char *p = SDATA (array);
2143 int charval;
2144 CHECK_CHARACTER (item);
2145 charval = XFASTINT (item);
2146 size = SCHARS (array);
2147 if (STRING_MULTIBYTE (array))
2149 unsigned char str[MAX_MULTIBYTE_LENGTH];
2150 int len = CHAR_STRING (charval, str);
2151 ptrdiff_t size_byte = SBYTES (array);
2153 if (INT_MULTIPLY_OVERFLOW (SCHARS (array), len)
2154 || SCHARS (array) * len != size_byte)
2155 error ("Attempt to change byte length of a string");
2156 for (idx = 0; idx < size_byte; idx++)
2157 *p++ = str[idx % len];
2159 else
2160 for (idx = 0; idx < size; idx++)
2161 p[idx] = charval;
2163 else if (BOOL_VECTOR_P (array))
2165 register unsigned char *p = XBOOL_VECTOR (array)->data;
2166 size =
2167 ((XBOOL_VECTOR (array)->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
2168 / BOOL_VECTOR_BITS_PER_CHAR);
2170 if (size)
2172 memset (p, ! NILP (item) ? -1 : 0, size);
2174 /* Clear any extraneous bits in the last byte. */
2175 p[size - 1] &= (1 << (size % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2178 else
2179 wrong_type_argument (Qarrayp, array);
2180 return array;
2183 DEFUN ("clear-string", Fclear_string, Sclear_string,
2184 1, 1, 0,
2185 doc: /* Clear the contents of STRING.
2186 This makes STRING unibyte and may change its length. */)
2187 (Lisp_Object string)
2189 ptrdiff_t len;
2190 CHECK_STRING (string);
2191 len = SBYTES (string);
2192 memset (SDATA (string), 0, len);
2193 STRING_SET_CHARS (string, len);
2194 STRING_SET_UNIBYTE (string);
2195 return Qnil;
2198 /* ARGSUSED */
2199 Lisp_Object
2200 nconc2 (Lisp_Object s1, Lisp_Object s2)
2202 Lisp_Object args[2];
2203 args[0] = s1;
2204 args[1] = s2;
2205 return Fnconc (2, args);
2208 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2209 doc: /* Concatenate any number of lists by altering them.
2210 Only the last argument is not altered, and need not be a list.
2211 usage: (nconc &rest LISTS) */)
2212 (ptrdiff_t nargs, Lisp_Object *args)
2214 ptrdiff_t argnum;
2215 register Lisp_Object tail, tem, val;
2217 val = tail = Qnil;
2219 for (argnum = 0; argnum < nargs; argnum++)
2221 tem = args[argnum];
2222 if (NILP (tem)) continue;
2224 if (NILP (val))
2225 val = tem;
2227 if (argnum + 1 == nargs) break;
2229 CHECK_LIST_CONS (tem, tem);
2231 while (CONSP (tem))
2233 tail = tem;
2234 tem = XCDR (tail);
2235 QUIT;
2238 tem = args[argnum + 1];
2239 Fsetcdr (tail, tem);
2240 if (NILP (tem))
2241 args[argnum + 1] = tail;
2244 return val;
2247 /* This is the guts of all mapping functions.
2248 Apply FN to each element of SEQ, one by one,
2249 storing the results into elements of VALS, a C vector of Lisp_Objects.
2250 LENI is the length of VALS, which should also be the length of SEQ. */
2252 static void
2253 mapcar1 (EMACS_INT leni, Lisp_Object *vals, Lisp_Object fn, Lisp_Object seq)
2255 register Lisp_Object tail;
2256 Lisp_Object dummy;
2257 register EMACS_INT i;
2258 struct gcpro gcpro1, gcpro2, gcpro3;
2260 if (vals)
2262 /* Don't let vals contain any garbage when GC happens. */
2263 for (i = 0; i < leni; i++)
2264 vals[i] = Qnil;
2266 GCPRO3 (dummy, fn, seq);
2267 gcpro1.var = vals;
2268 gcpro1.nvars = leni;
2270 else
2271 GCPRO2 (fn, seq);
2272 /* We need not explicitly protect `tail' because it is used only on lists, and
2273 1) lists are not relocated and 2) the list is marked via `seq' so will not
2274 be freed */
2276 if (VECTORP (seq) || COMPILEDP (seq))
2278 for (i = 0; i < leni; i++)
2280 dummy = call1 (fn, AREF (seq, i));
2281 if (vals)
2282 vals[i] = dummy;
2285 else if (BOOL_VECTOR_P (seq))
2287 for (i = 0; i < leni; i++)
2289 unsigned char byte;
2290 byte = XBOOL_VECTOR (seq)->data[i / BOOL_VECTOR_BITS_PER_CHAR];
2291 dummy = (byte & (1 << (i % BOOL_VECTOR_BITS_PER_CHAR))) ? Qt : Qnil;
2292 dummy = call1 (fn, dummy);
2293 if (vals)
2294 vals[i] = dummy;
2297 else if (STRINGP (seq))
2299 ptrdiff_t i_byte;
2301 for (i = 0, i_byte = 0; i < leni;)
2303 int c;
2304 ptrdiff_t i_before = i;
2306 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2307 XSETFASTINT (dummy, c);
2308 dummy = call1 (fn, dummy);
2309 if (vals)
2310 vals[i_before] = dummy;
2313 else /* Must be a list, since Flength did not get an error */
2315 tail = seq;
2316 for (i = 0; i < leni && CONSP (tail); i++)
2318 dummy = call1 (fn, XCAR (tail));
2319 if (vals)
2320 vals[i] = dummy;
2321 tail = XCDR (tail);
2325 UNGCPRO;
2328 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2329 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2330 In between each pair of results, stick in SEPARATOR. Thus, " " as
2331 SEPARATOR results in spaces between the values returned by FUNCTION.
2332 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2333 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2335 Lisp_Object len;
2336 register EMACS_INT leni;
2337 EMACS_INT nargs;
2338 ptrdiff_t i;
2339 register Lisp_Object *args;
2340 struct gcpro gcpro1;
2341 Lisp_Object ret;
2342 USE_SAFE_ALLOCA;
2344 len = Flength (sequence);
2345 if (CHAR_TABLE_P (sequence))
2346 wrong_type_argument (Qlistp, sequence);
2347 leni = XINT (len);
2348 nargs = leni + leni - 1;
2349 if (nargs < 0) return empty_unibyte_string;
2351 SAFE_ALLOCA_LISP (args, nargs);
2353 GCPRO1 (separator);
2354 mapcar1 (leni, args, function, sequence);
2355 UNGCPRO;
2357 for (i = leni - 1; i > 0; i--)
2358 args[i + i] = args[i];
2360 for (i = 1; i < nargs; i += 2)
2361 args[i] = separator;
2363 ret = Fconcat (nargs, args);
2364 SAFE_FREE ();
2366 return ret;
2369 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2370 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2371 The result is a list just as long as SEQUENCE.
2372 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2373 (Lisp_Object function, Lisp_Object sequence)
2375 register Lisp_Object len;
2376 register EMACS_INT leni;
2377 register Lisp_Object *args;
2378 Lisp_Object ret;
2379 USE_SAFE_ALLOCA;
2381 len = Flength (sequence);
2382 if (CHAR_TABLE_P (sequence))
2383 wrong_type_argument (Qlistp, sequence);
2384 leni = XFASTINT (len);
2386 SAFE_ALLOCA_LISP (args, leni);
2388 mapcar1 (leni, args, function, sequence);
2390 ret = Flist (leni, args);
2391 SAFE_FREE ();
2393 return ret;
2396 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2397 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2398 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2399 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2400 (Lisp_Object function, Lisp_Object sequence)
2402 register EMACS_INT leni;
2404 leni = XFASTINT (Flength (sequence));
2405 if (CHAR_TABLE_P (sequence))
2406 wrong_type_argument (Qlistp, sequence);
2407 mapcar1 (leni, 0, function, sequence);
2409 return sequence;
2412 /* This is how C code calls `yes-or-no-p' and allows the user
2413 to redefined it.
2415 Anything that calls this function must protect from GC! */
2417 Lisp_Object
2418 do_yes_or_no_p (Lisp_Object prompt)
2420 return call1 (intern ("yes-or-no-p"), prompt);
2423 /* Anything that calls this function must protect from GC! */
2425 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2426 doc: /* Ask user a yes-or-no question. Return t if answer is yes.
2427 PROMPT is the string to display to ask the question. It should end in
2428 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2430 The user must confirm the answer with RET, and can edit it until it
2431 has been confirmed.
2433 Under a windowing system a dialog box will be used if `last-nonmenu-event'
2434 is nil, and `use-dialog-box' is non-nil. */)
2435 (Lisp_Object prompt)
2437 register Lisp_Object ans;
2438 Lisp_Object args[2];
2439 struct gcpro gcpro1;
2441 CHECK_STRING (prompt);
2443 #ifdef HAVE_MENUS
2444 if (FRAME_WINDOW_P (SELECTED_FRAME ())
2445 && (NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2446 && use_dialog_box
2447 && have_menus_p ())
2449 Lisp_Object pane, menu, obj;
2450 redisplay_preserve_echo_area (4);
2451 pane = Fcons (Fcons (build_string ("Yes"), Qt),
2452 Fcons (Fcons (build_string ("No"), Qnil),
2453 Qnil));
2454 GCPRO1 (pane);
2455 menu = Fcons (prompt, pane);
2456 obj = Fx_popup_dialog (Qt, menu, Qnil);
2457 UNGCPRO;
2458 return obj;
2460 #endif /* HAVE_MENUS */
2462 args[0] = prompt;
2463 args[1] = build_string ("(yes or no) ");
2464 prompt = Fconcat (2, args);
2466 GCPRO1 (prompt);
2468 while (1)
2470 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2471 Qyes_or_no_p_history, Qnil,
2472 Qnil));
2473 if (SCHARS (ans) == 3 && !strcmp (SSDATA (ans), "yes"))
2475 UNGCPRO;
2476 return Qt;
2478 if (SCHARS (ans) == 2 && !strcmp (SSDATA (ans), "no"))
2480 UNGCPRO;
2481 return Qnil;
2484 Fding (Qnil);
2485 Fdiscard_input ();
2486 message ("Please answer yes or no.");
2487 Fsleep_for (make_number (2), Qnil);
2491 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2492 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2494 Each of the three load averages is multiplied by 100, then converted
2495 to integer.
2497 When USE-FLOATS is non-nil, floats will be used instead of integers.
2498 These floats are not multiplied by 100.
2500 If the 5-minute or 15-minute load averages are not available, return a
2501 shortened list, containing only those averages which are available.
2503 An error is thrown if the load average can't be obtained. In some
2504 cases making it work would require Emacs being installed setuid or
2505 setgid so that it can read kernel information, and that usually isn't
2506 advisable. */)
2507 (Lisp_Object use_floats)
2509 double load_ave[3];
2510 int loads = getloadavg (load_ave, 3);
2511 Lisp_Object ret = Qnil;
2513 if (loads < 0)
2514 error ("load-average not implemented for this operating system");
2516 while (loads-- > 0)
2518 Lisp_Object load = (NILP (use_floats)
2519 ? make_number (100.0 * load_ave[loads])
2520 : make_float (load_ave[loads]));
2521 ret = Fcons (load, ret);
2524 return ret;
2527 static Lisp_Object Qsubfeatures;
2529 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2530 doc: /* Return t if FEATURE is present in this Emacs.
2532 Use this to conditionalize execution of lisp code based on the
2533 presence or absence of Emacs or environment extensions.
2534 Use `provide' to declare that a feature is available. This function
2535 looks at the value of the variable `features'. The optional argument
2536 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2537 (Lisp_Object feature, Lisp_Object subfeature)
2539 register Lisp_Object tem;
2540 CHECK_SYMBOL (feature);
2541 tem = Fmemq (feature, Vfeatures);
2542 if (!NILP (tem) && !NILP (subfeature))
2543 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2544 return (NILP (tem)) ? Qnil : Qt;
2547 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2548 doc: /* Announce that FEATURE is a feature of the current Emacs.
2549 The optional argument SUBFEATURES should be a list of symbols listing
2550 particular subfeatures supported in this version of FEATURE. */)
2551 (Lisp_Object feature, Lisp_Object subfeatures)
2553 register Lisp_Object tem;
2554 CHECK_SYMBOL (feature);
2555 CHECK_LIST (subfeatures);
2556 if (!NILP (Vautoload_queue))
2557 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2558 Vautoload_queue);
2559 tem = Fmemq (feature, Vfeatures);
2560 if (NILP (tem))
2561 Vfeatures = Fcons (feature, Vfeatures);
2562 if (!NILP (subfeatures))
2563 Fput (feature, Qsubfeatures, subfeatures);
2564 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2566 /* Run any load-hooks for this file. */
2567 tem = Fassq (feature, Vafter_load_alist);
2568 if (CONSP (tem))
2569 Fprogn (XCDR (tem));
2571 return feature;
2574 /* `require' and its subroutines. */
2576 /* List of features currently being require'd, innermost first. */
2578 static Lisp_Object require_nesting_list;
2580 static Lisp_Object
2581 require_unwind (Lisp_Object old_value)
2583 return require_nesting_list = old_value;
2586 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2587 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2588 If FEATURE is not a member of the list `features', then the feature
2589 is not loaded; so load the file FILENAME.
2590 If FILENAME is omitted, the printname of FEATURE is used as the file name,
2591 and `load' will try to load this name appended with the suffix `.elc' or
2592 `.el', in that order. The name without appended suffix will not be used.
2593 See `get-load-suffixes' for the complete list of suffixes.
2594 If the optional third argument NOERROR is non-nil,
2595 then return nil if the file is not found instead of signaling an error.
2596 Normally the return value is FEATURE.
2597 The normal messages at start and end of loading FILENAME are suppressed. */)
2598 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2600 Lisp_Object tem;
2601 struct gcpro gcpro1, gcpro2;
2602 bool from_file = load_in_progress;
2604 CHECK_SYMBOL (feature);
2606 /* Record the presence of `require' in this file
2607 even if the feature specified is already loaded.
2608 But not more than once in any file,
2609 and not when we aren't loading or reading from a file. */
2610 if (!from_file)
2611 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2612 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2613 from_file = 1;
2615 if (from_file)
2617 tem = Fcons (Qrequire, feature);
2618 if (NILP (Fmember (tem, Vcurrent_load_list)))
2619 LOADHIST_ATTACH (tem);
2621 tem = Fmemq (feature, Vfeatures);
2623 if (NILP (tem))
2625 ptrdiff_t count = SPECPDL_INDEX ();
2626 int nesting = 0;
2628 /* This is to make sure that loadup.el gives a clear picture
2629 of what files are preloaded and when. */
2630 if (! NILP (Vpurify_flag))
2631 error ("(require %s) while preparing to dump",
2632 SDATA (SYMBOL_NAME (feature)));
2634 /* A certain amount of recursive `require' is legitimate,
2635 but if we require the same feature recursively 3 times,
2636 signal an error. */
2637 tem = require_nesting_list;
2638 while (! NILP (tem))
2640 if (! NILP (Fequal (feature, XCAR (tem))))
2641 nesting++;
2642 tem = XCDR (tem);
2644 if (nesting > 3)
2645 error ("Recursive `require' for feature `%s'",
2646 SDATA (SYMBOL_NAME (feature)));
2648 /* Update the list for any nested `require's that occur. */
2649 record_unwind_protect (require_unwind, require_nesting_list);
2650 require_nesting_list = Fcons (feature, require_nesting_list);
2652 /* Value saved here is to be restored into Vautoload_queue */
2653 record_unwind_protect (un_autoload, Vautoload_queue);
2654 Vautoload_queue = Qt;
2656 /* Load the file. */
2657 GCPRO2 (feature, filename);
2658 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2659 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2660 UNGCPRO;
2662 /* If load failed entirely, return nil. */
2663 if (NILP (tem))
2664 return unbind_to (count, Qnil);
2666 tem = Fmemq (feature, Vfeatures);
2667 if (NILP (tem))
2668 error ("Required feature `%s' was not provided",
2669 SDATA (SYMBOL_NAME (feature)));
2671 /* Once loading finishes, don't undo it. */
2672 Vautoload_queue = Qt;
2673 feature = unbind_to (count, feature);
2676 return feature;
2679 /* Primitives for work of the "widget" library.
2680 In an ideal world, this section would not have been necessary.
2681 However, lisp function calls being as slow as they are, it turns
2682 out that some functions in the widget library (wid-edit.el) are the
2683 bottleneck of Widget operation. Here is their translation to C,
2684 for the sole reason of efficiency. */
2686 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2687 doc: /* Return non-nil if PLIST has the property PROP.
2688 PLIST is a property list, which is a list of the form
2689 \(PROP1 VALUE1 PROP2 VALUE2 ...\). PROP is a symbol.
2690 Unlike `plist-get', this allows you to distinguish between a missing
2691 property and a property with the value nil.
2692 The value is actually the tail of PLIST whose car is PROP. */)
2693 (Lisp_Object plist, Lisp_Object prop)
2695 while (CONSP (plist) && !EQ (XCAR (plist), prop))
2697 QUIT;
2698 plist = XCDR (plist);
2699 plist = CDR (plist);
2701 return plist;
2704 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2705 doc: /* In WIDGET, set PROPERTY to VALUE.
2706 The value can later be retrieved with `widget-get'. */)
2707 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2709 CHECK_CONS (widget);
2710 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
2711 return value;
2714 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
2715 doc: /* In WIDGET, get the value of PROPERTY.
2716 The value could either be specified when the widget was created, or
2717 later with `widget-put'. */)
2718 (Lisp_Object widget, Lisp_Object property)
2720 Lisp_Object tmp;
2722 while (1)
2724 if (NILP (widget))
2725 return Qnil;
2726 CHECK_CONS (widget);
2727 tmp = Fplist_member (XCDR (widget), property);
2728 if (CONSP (tmp))
2730 tmp = XCDR (tmp);
2731 return CAR (tmp);
2733 tmp = XCAR (widget);
2734 if (NILP (tmp))
2735 return Qnil;
2736 widget = Fget (tmp, Qwidget_type);
2740 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
2741 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2742 ARGS are passed as extra arguments to the function.
2743 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2744 (ptrdiff_t nargs, Lisp_Object *args)
2746 /* This function can GC. */
2747 Lisp_Object newargs[3];
2748 struct gcpro gcpro1, gcpro2;
2749 Lisp_Object result;
2751 newargs[0] = Fwidget_get (args[0], args[1]);
2752 newargs[1] = args[0];
2753 newargs[2] = Flist (nargs - 2, args + 2);
2754 GCPRO2 (newargs[0], newargs[2]);
2755 result = Fapply (3, newargs);
2756 UNGCPRO;
2757 return result;
2760 #ifdef HAVE_LANGINFO_CODESET
2761 #include <langinfo.h>
2762 #endif
2764 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
2765 doc: /* Access locale data ITEM for the current C locale, if available.
2766 ITEM should be one of the following:
2768 `codeset', returning the character set as a string (locale item CODESET);
2770 `days', returning a 7-element vector of day names (locale items DAY_n);
2772 `months', returning a 12-element vector of month names (locale items MON_n);
2774 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
2775 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
2777 If the system can't provide such information through a call to
2778 `nl_langinfo', or if ITEM isn't from the list above, return nil.
2780 See also Info node `(libc)Locales'.
2782 The data read from the system are decoded using `locale-coding-system'. */)
2783 (Lisp_Object item)
2785 char *str = NULL;
2786 #ifdef HAVE_LANGINFO_CODESET
2787 Lisp_Object val;
2788 if (EQ (item, Qcodeset))
2790 str = nl_langinfo (CODESET);
2791 return build_string (str);
2793 #ifdef DAY_1
2794 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
2796 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
2797 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
2798 int i;
2799 struct gcpro gcpro1;
2800 GCPRO1 (v);
2801 synchronize_system_time_locale ();
2802 for (i = 0; i < 7; i++)
2804 str = nl_langinfo (days[i]);
2805 val = build_unibyte_string (str);
2806 /* Fixme: Is this coding system necessarily right, even if
2807 it is consistent with CODESET? If not, what to do? */
2808 Faset (v, make_number (i),
2809 code_convert_string_norecord (val, Vlocale_coding_system,
2810 0));
2812 UNGCPRO;
2813 return v;
2815 #endif /* DAY_1 */
2816 #ifdef MON_1
2817 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
2819 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
2820 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
2821 MON_8, MON_9, MON_10, MON_11, MON_12};
2822 int i;
2823 struct gcpro gcpro1;
2824 GCPRO1 (v);
2825 synchronize_system_time_locale ();
2826 for (i = 0; i < 12; i++)
2828 str = nl_langinfo (months[i]);
2829 val = build_unibyte_string (str);
2830 Faset (v, make_number (i),
2831 code_convert_string_norecord (val, Vlocale_coding_system, 0));
2833 UNGCPRO;
2834 return v;
2836 #endif /* MON_1 */
2837 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
2838 but is in the locale files. This could be used by ps-print. */
2839 #ifdef PAPER_WIDTH
2840 else if (EQ (item, Qpaper))
2842 return list2 (make_number (nl_langinfo (PAPER_WIDTH)),
2843 make_number (nl_langinfo (PAPER_HEIGHT)));
2845 #endif /* PAPER_WIDTH */
2846 #endif /* HAVE_LANGINFO_CODESET*/
2847 return Qnil;
2850 /* base64 encode/decode functions (RFC 2045).
2851 Based on code from GNU recode. */
2853 #define MIME_LINE_LENGTH 76
2855 #define IS_ASCII(Character) \
2856 ((Character) < 128)
2857 #define IS_BASE64(Character) \
2858 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
2859 #define IS_BASE64_IGNORABLE(Character) \
2860 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
2861 || (Character) == '\f' || (Character) == '\r')
2863 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
2864 character or return retval if there are no characters left to
2865 process. */
2866 #define READ_QUADRUPLET_BYTE(retval) \
2867 do \
2869 if (i == length) \
2871 if (nchars_return) \
2872 *nchars_return = nchars; \
2873 return (retval); \
2875 c = from[i++]; \
2877 while (IS_BASE64_IGNORABLE (c))
2879 /* Table of characters coding the 64 values. */
2880 static const char base64_value_to_char[64] =
2882 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
2883 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
2884 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
2885 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
2886 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
2887 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
2888 '8', '9', '+', '/' /* 60-63 */
2891 /* Table of base64 values for first 128 characters. */
2892 static const short base64_char_to_value[128] =
2894 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
2895 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
2896 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
2897 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
2898 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
2899 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
2900 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
2901 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
2902 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
2903 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
2904 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
2905 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
2906 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
2909 /* The following diagram shows the logical steps by which three octets
2910 get transformed into four base64 characters.
2912 .--------. .--------. .--------.
2913 |aaaaaabb| |bbbbcccc| |ccdddddd|
2914 `--------' `--------' `--------'
2915 6 2 4 4 2 6
2916 .--------+--------+--------+--------.
2917 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
2918 `--------+--------+--------+--------'
2920 .--------+--------+--------+--------.
2921 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
2922 `--------+--------+--------+--------'
2924 The octets are divided into 6 bit chunks, which are then encoded into
2925 base64 characters. */
2928 static ptrdiff_t base64_encode_1 (const char *, char *, ptrdiff_t, bool, bool);
2929 static ptrdiff_t base64_decode_1 (const char *, char *, ptrdiff_t, bool,
2930 ptrdiff_t *);
2932 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
2933 2, 3, "r",
2934 doc: /* Base64-encode the region between BEG and END.
2935 Return the length of the encoded text.
2936 Optional third argument NO-LINE-BREAK means do not break long lines
2937 into shorter lines. */)
2938 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
2940 char *encoded;
2941 ptrdiff_t allength, length;
2942 ptrdiff_t ibeg, iend, encoded_length;
2943 ptrdiff_t old_pos = PT;
2944 USE_SAFE_ALLOCA;
2946 validate_region (&beg, &end);
2948 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
2949 iend = CHAR_TO_BYTE (XFASTINT (end));
2950 move_gap_both (XFASTINT (beg), ibeg);
2952 /* We need to allocate enough room for encoding the text.
2953 We need 33 1/3% more space, plus a newline every 76
2954 characters, and then we round up. */
2955 length = iend - ibeg;
2956 allength = length + length/3 + 1;
2957 allength += allength / MIME_LINE_LENGTH + 1 + 6;
2959 encoded = SAFE_ALLOCA (allength);
2960 encoded_length = base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg),
2961 encoded, length, NILP (no_line_break),
2962 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
2963 if (encoded_length > allength)
2964 emacs_abort ();
2966 if (encoded_length < 0)
2968 /* The encoding wasn't possible. */
2969 SAFE_FREE ();
2970 error ("Multibyte character in data for base64 encoding");
2973 /* Now we have encoded the region, so we insert the new contents
2974 and delete the old. (Insert first in order to preserve markers.) */
2975 SET_PT_BOTH (XFASTINT (beg), ibeg);
2976 insert (encoded, encoded_length);
2977 SAFE_FREE ();
2978 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
2980 /* If point was outside of the region, restore it exactly; else just
2981 move to the beginning of the region. */
2982 if (old_pos >= XFASTINT (end))
2983 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
2984 else if (old_pos > XFASTINT (beg))
2985 old_pos = XFASTINT (beg);
2986 SET_PT (old_pos);
2988 /* We return the length of the encoded text. */
2989 return make_number (encoded_length);
2992 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
2993 1, 2, 0,
2994 doc: /* Base64-encode STRING and return the result.
2995 Optional second argument NO-LINE-BREAK means do not break long lines
2996 into shorter lines. */)
2997 (Lisp_Object string, Lisp_Object no_line_break)
2999 ptrdiff_t allength, length, encoded_length;
3000 char *encoded;
3001 Lisp_Object encoded_string;
3002 USE_SAFE_ALLOCA;
3004 CHECK_STRING (string);
3006 /* We need to allocate enough room for encoding the text.
3007 We need 33 1/3% more space, plus a newline every 76
3008 characters, and then we round up. */
3009 length = SBYTES (string);
3010 allength = length + length/3 + 1;
3011 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3013 /* We need to allocate enough room for decoding the text. */
3014 encoded = SAFE_ALLOCA (allength);
3016 encoded_length = base64_encode_1 (SSDATA (string),
3017 encoded, length, NILP (no_line_break),
3018 STRING_MULTIBYTE (string));
3019 if (encoded_length > allength)
3020 emacs_abort ();
3022 if (encoded_length < 0)
3024 /* The encoding wasn't possible. */
3025 SAFE_FREE ();
3026 error ("Multibyte character in data for base64 encoding");
3029 encoded_string = make_unibyte_string (encoded, encoded_length);
3030 SAFE_FREE ();
3032 return encoded_string;
3035 static ptrdiff_t
3036 base64_encode_1 (const char *from, char *to, ptrdiff_t length,
3037 bool line_break, bool multibyte)
3039 int counter = 0;
3040 ptrdiff_t i = 0;
3041 char *e = to;
3042 int c;
3043 unsigned int value;
3044 int bytes;
3046 while (i < length)
3048 if (multibyte)
3050 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3051 if (CHAR_BYTE8_P (c))
3052 c = CHAR_TO_BYTE8 (c);
3053 else if (c >= 256)
3054 return -1;
3055 i += bytes;
3057 else
3058 c = from[i++];
3060 /* Wrap line every 76 characters. */
3062 if (line_break)
3064 if (counter < MIME_LINE_LENGTH / 4)
3065 counter++;
3066 else
3068 *e++ = '\n';
3069 counter = 1;
3073 /* Process first byte of a triplet. */
3075 *e++ = base64_value_to_char[0x3f & c >> 2];
3076 value = (0x03 & c) << 4;
3078 /* Process second byte of a triplet. */
3080 if (i == length)
3082 *e++ = base64_value_to_char[value];
3083 *e++ = '=';
3084 *e++ = '=';
3085 break;
3088 if (multibyte)
3090 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3091 if (CHAR_BYTE8_P (c))
3092 c = CHAR_TO_BYTE8 (c);
3093 else if (c >= 256)
3094 return -1;
3095 i += bytes;
3097 else
3098 c = from[i++];
3100 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3101 value = (0x0f & c) << 2;
3103 /* Process third byte of a triplet. */
3105 if (i == length)
3107 *e++ = base64_value_to_char[value];
3108 *e++ = '=';
3109 break;
3112 if (multibyte)
3114 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3115 if (CHAR_BYTE8_P (c))
3116 c = CHAR_TO_BYTE8 (c);
3117 else if (c >= 256)
3118 return -1;
3119 i += bytes;
3121 else
3122 c = from[i++];
3124 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3125 *e++ = base64_value_to_char[0x3f & c];
3128 return e - to;
3132 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3133 2, 2, "r",
3134 doc: /* Base64-decode the region between BEG and END.
3135 Return the length of the decoded text.
3136 If the region can't be decoded, signal an error and don't modify the buffer. */)
3137 (Lisp_Object beg, Lisp_Object end)
3139 ptrdiff_t ibeg, iend, length, allength;
3140 char *decoded;
3141 ptrdiff_t old_pos = PT;
3142 ptrdiff_t decoded_length;
3143 ptrdiff_t inserted_chars;
3144 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3145 USE_SAFE_ALLOCA;
3147 validate_region (&beg, &end);
3149 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3150 iend = CHAR_TO_BYTE (XFASTINT (end));
3152 length = iend - ibeg;
3154 /* We need to allocate enough room for decoding the text. If we are
3155 working on a multibyte buffer, each decoded code may occupy at
3156 most two bytes. */
3157 allength = multibyte ? length * 2 : length;
3158 decoded = SAFE_ALLOCA (allength);
3160 move_gap_both (XFASTINT (beg), ibeg);
3161 decoded_length = base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg),
3162 decoded, length,
3163 multibyte, &inserted_chars);
3164 if (decoded_length > allength)
3165 emacs_abort ();
3167 if (decoded_length < 0)
3169 /* The decoding wasn't possible. */
3170 SAFE_FREE ();
3171 error ("Invalid base64 data");
3174 /* Now we have decoded the region, so we insert the new contents
3175 and delete the old. (Insert first in order to preserve markers.) */
3176 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3177 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3178 SAFE_FREE ();
3180 /* Delete the original text. */
3181 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3182 iend + decoded_length, 1);
3184 /* If point was outside of the region, restore it exactly; else just
3185 move to the beginning of the region. */
3186 if (old_pos >= XFASTINT (end))
3187 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3188 else if (old_pos > XFASTINT (beg))
3189 old_pos = XFASTINT (beg);
3190 SET_PT (old_pos > ZV ? ZV : old_pos);
3192 return make_number (inserted_chars);
3195 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3196 1, 1, 0,
3197 doc: /* Base64-decode STRING and return the result. */)
3198 (Lisp_Object string)
3200 char *decoded;
3201 ptrdiff_t length, decoded_length;
3202 Lisp_Object decoded_string;
3203 USE_SAFE_ALLOCA;
3205 CHECK_STRING (string);
3207 length = SBYTES (string);
3208 /* We need to allocate enough room for decoding the text. */
3209 decoded = SAFE_ALLOCA (length);
3211 /* The decoded result should be unibyte. */
3212 decoded_length = base64_decode_1 (SSDATA (string), decoded, length,
3213 0, NULL);
3214 if (decoded_length > length)
3215 emacs_abort ();
3216 else if (decoded_length >= 0)
3217 decoded_string = make_unibyte_string (decoded, decoded_length);
3218 else
3219 decoded_string = Qnil;
3221 SAFE_FREE ();
3222 if (!STRINGP (decoded_string))
3223 error ("Invalid base64 data");
3225 return decoded_string;
3228 /* Base64-decode the data at FROM of LENGTH bytes into TO. If
3229 MULTIBYTE, the decoded result should be in multibyte
3230 form. If NCHARS_RETURN is not NULL, store the number of produced
3231 characters in *NCHARS_RETURN. */
3233 static ptrdiff_t
3234 base64_decode_1 (const char *from, char *to, ptrdiff_t length,
3235 bool multibyte, ptrdiff_t *nchars_return)
3237 ptrdiff_t i = 0; /* Used inside READ_QUADRUPLET_BYTE */
3238 char *e = to;
3239 unsigned char c;
3240 unsigned long value;
3241 ptrdiff_t nchars = 0;
3243 while (1)
3245 /* Process first byte of a quadruplet. */
3247 READ_QUADRUPLET_BYTE (e-to);
3249 if (!IS_BASE64 (c))
3250 return -1;
3251 value = base64_char_to_value[c] << 18;
3253 /* Process second byte of a quadruplet. */
3255 READ_QUADRUPLET_BYTE (-1);
3257 if (!IS_BASE64 (c))
3258 return -1;
3259 value |= base64_char_to_value[c] << 12;
3261 c = (unsigned char) (value >> 16);
3262 if (multibyte && c >= 128)
3263 e += BYTE8_STRING (c, e);
3264 else
3265 *e++ = c;
3266 nchars++;
3268 /* Process third byte of a quadruplet. */
3270 READ_QUADRUPLET_BYTE (-1);
3272 if (c == '=')
3274 READ_QUADRUPLET_BYTE (-1);
3276 if (c != '=')
3277 return -1;
3278 continue;
3281 if (!IS_BASE64 (c))
3282 return -1;
3283 value |= base64_char_to_value[c] << 6;
3285 c = (unsigned char) (0xff & value >> 8);
3286 if (multibyte && c >= 128)
3287 e += BYTE8_STRING (c, e);
3288 else
3289 *e++ = c;
3290 nchars++;
3292 /* Process fourth byte of a quadruplet. */
3294 READ_QUADRUPLET_BYTE (-1);
3296 if (c == '=')
3297 continue;
3299 if (!IS_BASE64 (c))
3300 return -1;
3301 value |= base64_char_to_value[c];
3303 c = (unsigned char) (0xff & value);
3304 if (multibyte && c >= 128)
3305 e += BYTE8_STRING (c, e);
3306 else
3307 *e++ = c;
3308 nchars++;
3314 /***********************************************************************
3315 ***** *****
3316 ***** Hash Tables *****
3317 ***** *****
3318 ***********************************************************************/
3320 /* Implemented by gerd@gnu.org. This hash table implementation was
3321 inspired by CMUCL hash tables. */
3323 /* Ideas:
3325 1. For small tables, association lists are probably faster than
3326 hash tables because they have lower overhead.
3328 For uses of hash tables where the O(1) behavior of table
3329 operations is not a requirement, it might therefore be a good idea
3330 not to hash. Instead, we could just do a linear search in the
3331 key_and_value vector of the hash table. This could be done
3332 if a `:linear-search t' argument is given to make-hash-table. */
3335 /* The list of all weak hash tables. Don't staticpro this one. */
3337 static struct Lisp_Hash_Table *weak_hash_tables;
3339 /* Various symbols. */
3341 static Lisp_Object Qhash_table_p, Qkey, Qvalue;
3342 Lisp_Object Qeq, Qeql, Qequal;
3343 Lisp_Object QCtest, QCsize, QCrehash_size, QCrehash_threshold, QCweakness;
3344 static Lisp_Object Qhash_table_test, Qkey_or_value, Qkey_and_value;
3346 /* Function prototypes. */
3348 static struct Lisp_Hash_Table *check_hash_table (Lisp_Object);
3349 static ptrdiff_t get_key_arg (Lisp_Object, ptrdiff_t, Lisp_Object *, char *);
3350 static void maybe_resize_hash_table (struct Lisp_Hash_Table *);
3351 static bool sweep_weak_table (struct Lisp_Hash_Table *, bool);
3355 /***********************************************************************
3356 Utilities
3357 ***********************************************************************/
3359 /* If OBJ is a Lisp hash table, return a pointer to its struct
3360 Lisp_Hash_Table. Otherwise, signal an error. */
3362 static struct Lisp_Hash_Table *
3363 check_hash_table (Lisp_Object obj)
3365 CHECK_HASH_TABLE (obj);
3366 return XHASH_TABLE (obj);
3370 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3371 number. A number is "almost" a prime number if it is not divisible
3372 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3374 EMACS_INT
3375 next_almost_prime (EMACS_INT n)
3377 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
3378 for (n |= 1; ; n += 2)
3379 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0)
3380 return n;
3384 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3385 which USED[I] is non-zero. If found at index I in ARGS, set
3386 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3387 0. This function is used to extract a keyword/argument pair from
3388 a DEFUN parameter list. */
3390 static ptrdiff_t
3391 get_key_arg (Lisp_Object key, ptrdiff_t nargs, Lisp_Object *args, char *used)
3393 ptrdiff_t i;
3395 for (i = 1; i < nargs; i++)
3396 if (!used[i - 1] && EQ (args[i - 1], key))
3398 used[i - 1] = 1;
3399 used[i] = 1;
3400 return i;
3403 return 0;
3407 /* Return a Lisp vector which has the same contents as VEC but has
3408 at least INCR_MIN more entries, where INCR_MIN is positive.
3409 If NITEMS_MAX is not -1, do not grow the vector to be any larger
3410 than NITEMS_MAX. Entries in the resulting
3411 vector that are not copied from VEC are set to nil. */
3413 Lisp_Object
3414 larger_vector (Lisp_Object vec, ptrdiff_t incr_min, ptrdiff_t nitems_max)
3416 struct Lisp_Vector *v;
3417 ptrdiff_t i, incr, incr_max, old_size, new_size;
3418 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / sizeof *v->contents;
3419 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
3420 ? nitems_max : C_language_max);
3421 eassert (VECTORP (vec));
3422 eassert (0 < incr_min && -1 <= nitems_max);
3423 old_size = ASIZE (vec);
3424 incr_max = n_max - old_size;
3425 incr = max (incr_min, min (old_size >> 1, incr_max));
3426 if (incr_max < incr)
3427 memory_full (SIZE_MAX);
3428 new_size = old_size + incr;
3429 v = allocate_vector (new_size);
3430 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3431 for (i = old_size; i < new_size; ++i)
3432 v->contents[i] = Qnil;
3433 XSETVECTOR (vec, v);
3434 return vec;
3438 /***********************************************************************
3439 Low-level Functions
3440 ***********************************************************************/
3442 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3443 HASH2 in hash table H using `eql'. Value is true if KEY1 and
3444 KEY2 are the same. */
3446 static bool
3447 cmpfn_eql (struct Lisp_Hash_Table *h,
3448 Lisp_Object key1, EMACS_UINT hash1,
3449 Lisp_Object key2, EMACS_UINT hash2)
3451 return (FLOATP (key1)
3452 && FLOATP (key2)
3453 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3457 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3458 HASH2 in hash table H using `equal'. Value is true if KEY1 and
3459 KEY2 are the same. */
3461 static bool
3462 cmpfn_equal (struct Lisp_Hash_Table *h,
3463 Lisp_Object key1, EMACS_UINT hash1,
3464 Lisp_Object key2, EMACS_UINT hash2)
3466 return hash1 == hash2 && !NILP (Fequal (key1, key2));
3470 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3471 HASH2 in hash table H using H->user_cmp_function. Value is true
3472 if KEY1 and KEY2 are the same. */
3474 static bool
3475 cmpfn_user_defined (struct Lisp_Hash_Table *h,
3476 Lisp_Object key1, EMACS_UINT hash1,
3477 Lisp_Object key2, EMACS_UINT hash2)
3479 if (hash1 == hash2)
3481 Lisp_Object args[3];
3483 args[0] = h->user_cmp_function;
3484 args[1] = key1;
3485 args[2] = key2;
3486 return !NILP (Ffuncall (3, args));
3488 else
3489 return 0;
3493 /* Value is a hash code for KEY for use in hash table H which uses
3494 `eq' to compare keys. The hash code returned is guaranteed to fit
3495 in a Lisp integer. */
3497 static EMACS_UINT
3498 hashfn_eq (struct Lisp_Hash_Table *h, Lisp_Object key)
3500 EMACS_UINT hash = XUINT (key) ^ XTYPE (key);
3501 eassert ((hash & ~INTMASK) == 0);
3502 return hash;
3506 /* Value is a hash code for KEY for use in hash table H which uses
3507 `eql' to compare keys. The hash code returned is guaranteed to fit
3508 in a Lisp integer. */
3510 static EMACS_UINT
3511 hashfn_eql (struct Lisp_Hash_Table *h, Lisp_Object key)
3513 EMACS_UINT hash;
3514 if (FLOATP (key))
3515 hash = sxhash (key, 0);
3516 else
3517 hash = XUINT (key) ^ XTYPE (key);
3518 eassert ((hash & ~INTMASK) == 0);
3519 return hash;
3523 /* Value is a hash code for KEY for use in hash table H which uses
3524 `equal' to compare keys. The hash code returned is guaranteed to fit
3525 in a Lisp integer. */
3527 static EMACS_UINT
3528 hashfn_equal (struct Lisp_Hash_Table *h, Lisp_Object key)
3530 EMACS_UINT hash = sxhash (key, 0);
3531 eassert ((hash & ~INTMASK) == 0);
3532 return hash;
3536 /* Value is a hash code for KEY for use in hash table H which uses as
3537 user-defined function to compare keys. The hash code returned is
3538 guaranteed to fit in a Lisp integer. */
3540 static EMACS_UINT
3541 hashfn_user_defined (struct Lisp_Hash_Table *h, Lisp_Object key)
3543 Lisp_Object args[2], hash;
3545 args[0] = h->user_hash_function;
3546 args[1] = key;
3547 hash = Ffuncall (2, args);
3548 if (!INTEGERP (hash))
3549 signal_error ("Invalid hash code returned from user-supplied hash function", hash);
3550 return XUINT (hash);
3553 /* An upper bound on the size of a hash table index. It must fit in
3554 ptrdiff_t and be a valid Emacs fixnum. */
3555 #define INDEX_SIZE_BOUND \
3556 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, PTRDIFF_MAX / word_size))
3558 /* Create and initialize a new hash table.
3560 TEST specifies the test the hash table will use to compare keys.
3561 It must be either one of the predefined tests `eq', `eql' or
3562 `equal' or a symbol denoting a user-defined test named TEST with
3563 test and hash functions USER_TEST and USER_HASH.
3565 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3567 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3568 new size when it becomes full is computed by adding REHASH_SIZE to
3569 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3570 table's new size is computed by multiplying its old size with
3571 REHASH_SIZE.
3573 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3574 be resized when the ratio of (number of entries in the table) /
3575 (table size) is >= REHASH_THRESHOLD.
3577 WEAK specifies the weakness of the table. If non-nil, it must be
3578 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
3580 Lisp_Object
3581 make_hash_table (Lisp_Object test, Lisp_Object size, Lisp_Object rehash_size,
3582 Lisp_Object rehash_threshold, Lisp_Object weak,
3583 Lisp_Object user_test, Lisp_Object user_hash)
3585 struct Lisp_Hash_Table *h;
3586 Lisp_Object table;
3587 EMACS_INT index_size, sz;
3588 ptrdiff_t i;
3589 double index_float;
3591 /* Preconditions. */
3592 eassert (SYMBOLP (test));
3593 eassert (INTEGERP (size) && XINT (size) >= 0);
3594 eassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3595 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size)));
3596 eassert (FLOATP (rehash_threshold)
3597 && 0 < XFLOAT_DATA (rehash_threshold)
3598 && XFLOAT_DATA (rehash_threshold) <= 1.0);
3600 if (XFASTINT (size) == 0)
3601 size = make_number (1);
3603 sz = XFASTINT (size);
3604 index_float = sz / XFLOAT_DATA (rehash_threshold);
3605 index_size = (index_float < INDEX_SIZE_BOUND + 1
3606 ? next_almost_prime (index_float)
3607 : INDEX_SIZE_BOUND + 1);
3608 if (INDEX_SIZE_BOUND < max (index_size, 2 * sz))
3609 error ("Hash table too large");
3611 /* Allocate a table and initialize it. */
3612 h = allocate_hash_table ();
3614 /* Initialize hash table slots. */
3615 h->test = test;
3616 if (EQ (test, Qeql))
3618 h->cmpfn = cmpfn_eql;
3619 h->hashfn = hashfn_eql;
3621 else if (EQ (test, Qeq))
3623 h->cmpfn = NULL;
3624 h->hashfn = hashfn_eq;
3626 else if (EQ (test, Qequal))
3628 h->cmpfn = cmpfn_equal;
3629 h->hashfn = hashfn_equal;
3631 else
3633 h->user_cmp_function = user_test;
3634 h->user_hash_function = user_hash;
3635 h->cmpfn = cmpfn_user_defined;
3636 h->hashfn = hashfn_user_defined;
3639 h->weak = weak;
3640 h->rehash_threshold = rehash_threshold;
3641 h->rehash_size = rehash_size;
3642 h->count = 0;
3643 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
3644 h->hash = Fmake_vector (size, Qnil);
3645 h->next = Fmake_vector (size, Qnil);
3646 h->index = Fmake_vector (make_number (index_size), Qnil);
3648 /* Set up the free list. */
3649 for (i = 0; i < sz - 1; ++i)
3650 set_hash_next_slot (h, i, make_number (i + 1));
3651 h->next_free = make_number (0);
3653 XSET_HASH_TABLE (table, h);
3654 eassert (HASH_TABLE_P (table));
3655 eassert (XHASH_TABLE (table) == h);
3657 /* Maybe add this hash table to the list of all weak hash tables. */
3658 if (NILP (h->weak))
3659 h->next_weak = NULL;
3660 else
3662 h->next_weak = weak_hash_tables;
3663 weak_hash_tables = h;
3666 return table;
3670 /* Return a copy of hash table H1. Keys and values are not copied,
3671 only the table itself is. */
3673 static Lisp_Object
3674 copy_hash_table (struct Lisp_Hash_Table *h1)
3676 Lisp_Object table;
3677 struct Lisp_Hash_Table *h2;
3678 struct Lisp_Vector *next;
3680 h2 = allocate_hash_table ();
3681 next = h2->header.next.vector;
3682 *h2 = *h1;
3683 h2->header.next.vector = next;
3684 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3685 h2->hash = Fcopy_sequence (h1->hash);
3686 h2->next = Fcopy_sequence (h1->next);
3687 h2->index = Fcopy_sequence (h1->index);
3688 XSET_HASH_TABLE (table, h2);
3690 /* Maybe add this hash table to the list of all weak hash tables. */
3691 if (!NILP (h2->weak))
3693 h2->next_weak = weak_hash_tables;
3694 weak_hash_tables = h2;
3697 return table;
3701 /* Resize hash table H if it's too full. If H cannot be resized
3702 because it's already too large, throw an error. */
3704 static inline void
3705 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3707 if (NILP (h->next_free))
3709 ptrdiff_t old_size = HASH_TABLE_SIZE (h);
3710 EMACS_INT new_size, index_size, nsize;
3711 ptrdiff_t i;
3712 double index_float;
3714 if (INTEGERP (h->rehash_size))
3715 new_size = old_size + XFASTINT (h->rehash_size);
3716 else
3718 double float_new_size = old_size * XFLOAT_DATA (h->rehash_size);
3719 if (float_new_size < INDEX_SIZE_BOUND + 1)
3721 new_size = float_new_size;
3722 if (new_size <= old_size)
3723 new_size = old_size + 1;
3725 else
3726 new_size = INDEX_SIZE_BOUND + 1;
3728 index_float = new_size / XFLOAT_DATA (h->rehash_threshold);
3729 index_size = (index_float < INDEX_SIZE_BOUND + 1
3730 ? next_almost_prime (index_float)
3731 : INDEX_SIZE_BOUND + 1);
3732 nsize = max (index_size, 2 * new_size);
3733 if (INDEX_SIZE_BOUND < nsize)
3734 error ("Hash table too large to resize");
3736 #ifdef ENABLE_CHECKING
3737 if (HASH_TABLE_P (Vpurify_flag)
3738 && XHASH_TABLE (Vpurify_flag) == h)
3740 Lisp_Object args[2];
3741 args[0] = build_string ("Growing hash table to: %d");
3742 args[1] = make_number (new_size);
3743 Fmessage (2, args);
3745 #endif
3747 set_hash_key_and_value (h, larger_vector (h->key_and_value,
3748 2 * (new_size - old_size), -1));
3749 set_hash_next (h, larger_vector (h->next, new_size - old_size, -1));
3750 set_hash_hash (h, larger_vector (h->hash, new_size - old_size, -1));
3751 set_hash_index (h, Fmake_vector (make_number (index_size), Qnil));
3753 /* Update the free list. Do it so that new entries are added at
3754 the end of the free list. This makes some operations like
3755 maphash faster. */
3756 for (i = old_size; i < new_size - 1; ++i)
3757 set_hash_next_slot (h, i, make_number (i + 1));
3759 if (!NILP (h->next_free))
3761 Lisp_Object last, next;
3763 last = h->next_free;
3764 while (next = HASH_NEXT (h, XFASTINT (last)),
3765 !NILP (next))
3766 last = next;
3768 set_hash_next_slot (h, XFASTINT (last), make_number (old_size));
3770 else
3771 XSETFASTINT (h->next_free, old_size);
3773 /* Rehash. */
3774 for (i = 0; i < old_size; ++i)
3775 if (!NILP (HASH_HASH (h, i)))
3777 EMACS_UINT hash_code = XUINT (HASH_HASH (h, i));
3778 ptrdiff_t start_of_bucket = hash_code % ASIZE (h->index);
3779 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3780 set_hash_index_slot (h, start_of_bucket, make_number (i));
3786 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
3787 the hash code of KEY. Value is the index of the entry in H
3788 matching KEY, or -1 if not found. */
3790 ptrdiff_t
3791 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
3793 EMACS_UINT hash_code;
3794 ptrdiff_t start_of_bucket;
3795 Lisp_Object idx;
3797 hash_code = h->hashfn (h, key);
3798 if (hash)
3799 *hash = hash_code;
3801 start_of_bucket = hash_code % ASIZE (h->index);
3802 idx = HASH_INDEX (h, start_of_bucket);
3804 /* We need not gcpro idx since it's either an integer or nil. */
3805 while (!NILP (idx))
3807 ptrdiff_t i = XFASTINT (idx);
3808 if (EQ (key, HASH_KEY (h, i))
3809 || (h->cmpfn
3810 && h->cmpfn (h, key, hash_code,
3811 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
3812 break;
3813 idx = HASH_NEXT (h, i);
3816 return NILP (idx) ? -1 : XFASTINT (idx);
3820 /* Put an entry into hash table H that associates KEY with VALUE.
3821 HASH is a previously computed hash code of KEY.
3822 Value is the index of the entry in H matching KEY. */
3824 ptrdiff_t
3825 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value,
3826 EMACS_UINT hash)
3828 ptrdiff_t start_of_bucket, i;
3830 eassert ((hash & ~INTMASK) == 0);
3832 /* Increment count after resizing because resizing may fail. */
3833 maybe_resize_hash_table (h);
3834 h->count++;
3836 /* Store key/value in the key_and_value vector. */
3837 i = XFASTINT (h->next_free);
3838 h->next_free = HASH_NEXT (h, i);
3839 set_hash_key_slot (h, i, key);
3840 set_hash_value_slot (h, i, value);
3842 /* Remember its hash code. */
3843 set_hash_hash_slot (h, i, make_number (hash));
3845 /* Add new entry to its collision chain. */
3846 start_of_bucket = hash % ASIZE (h->index);
3847 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3848 set_hash_index_slot (h, start_of_bucket, make_number (i));
3849 return i;
3853 /* Remove the entry matching KEY from hash table H, if there is one. */
3855 static void
3856 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
3858 EMACS_UINT hash_code;
3859 ptrdiff_t start_of_bucket;
3860 Lisp_Object idx, prev;
3862 hash_code = h->hashfn (h, key);
3863 start_of_bucket = hash_code % ASIZE (h->index);
3864 idx = HASH_INDEX (h, start_of_bucket);
3865 prev = Qnil;
3867 /* We need not gcpro idx, prev since they're either integers or nil. */
3868 while (!NILP (idx))
3870 ptrdiff_t i = XFASTINT (idx);
3872 if (EQ (key, HASH_KEY (h, i))
3873 || (h->cmpfn
3874 && h->cmpfn (h, key, hash_code,
3875 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
3877 /* Take entry out of collision chain. */
3878 if (NILP (prev))
3879 set_hash_index_slot (h, start_of_bucket, HASH_NEXT (h, i));
3880 else
3881 set_hash_next_slot (h, XFASTINT (prev), HASH_NEXT (h, i));
3883 /* Clear slots in key_and_value and add the slots to
3884 the free list. */
3885 set_hash_key_slot (h, i, Qnil);
3886 set_hash_value_slot (h, i, Qnil);
3887 set_hash_hash_slot (h, i, Qnil);
3888 set_hash_next_slot (h, i, h->next_free);
3889 h->next_free = make_number (i);
3890 h->count--;
3891 eassert (h->count >= 0);
3892 break;
3894 else
3896 prev = idx;
3897 idx = HASH_NEXT (h, i);
3903 /* Clear hash table H. */
3905 static void
3906 hash_clear (struct Lisp_Hash_Table *h)
3908 if (h->count > 0)
3910 ptrdiff_t i, size = HASH_TABLE_SIZE (h);
3912 for (i = 0; i < size; ++i)
3914 set_hash_next_slot (h, i, i < size - 1 ? make_number (i + 1) : Qnil);
3915 set_hash_key_slot (h, i, Qnil);
3916 set_hash_value_slot (h, i, Qnil);
3917 set_hash_hash_slot (h, i, Qnil);
3920 for (i = 0; i < ASIZE (h->index); ++i)
3921 ASET (h->index, i, Qnil);
3923 h->next_free = make_number (0);
3924 h->count = 0;
3930 /************************************************************************
3931 Weak Hash Tables
3932 ************************************************************************/
3934 /* Sweep weak hash table H. REMOVE_ENTRIES_P means remove
3935 entries from the table that don't survive the current GC.
3936 !REMOVE_ENTRIES_P means mark entries that are in use. Value is
3937 true if anything was marked. */
3939 static bool
3940 sweep_weak_table (struct Lisp_Hash_Table *h, bool remove_entries_p)
3942 ptrdiff_t bucket, n;
3943 bool marked;
3945 n = ASIZE (h->index) & ~ARRAY_MARK_FLAG;
3946 marked = 0;
3948 for (bucket = 0; bucket < n; ++bucket)
3950 Lisp_Object idx, next, prev;
3952 /* Follow collision chain, removing entries that
3953 don't survive this garbage collection. */
3954 prev = Qnil;
3955 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
3957 ptrdiff_t i = XFASTINT (idx);
3958 bool key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
3959 bool value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
3960 bool remove_p;
3962 if (EQ (h->weak, Qkey))
3963 remove_p = !key_known_to_survive_p;
3964 else if (EQ (h->weak, Qvalue))
3965 remove_p = !value_known_to_survive_p;
3966 else if (EQ (h->weak, Qkey_or_value))
3967 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
3968 else if (EQ (h->weak, Qkey_and_value))
3969 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
3970 else
3971 emacs_abort ();
3973 next = HASH_NEXT (h, i);
3975 if (remove_entries_p)
3977 if (remove_p)
3979 /* Take out of collision chain. */
3980 if (NILP (prev))
3981 set_hash_index_slot (h, bucket, next);
3982 else
3983 set_hash_next_slot (h, XFASTINT (prev), next);
3985 /* Add to free list. */
3986 set_hash_next_slot (h, i, h->next_free);
3987 h->next_free = idx;
3989 /* Clear key, value, and hash. */
3990 set_hash_key_slot (h, i, Qnil);
3991 set_hash_value_slot (h, i, Qnil);
3992 set_hash_hash_slot (h, i, Qnil);
3994 h->count--;
3996 else
3998 prev = idx;
4001 else
4003 if (!remove_p)
4005 /* Make sure key and value survive. */
4006 if (!key_known_to_survive_p)
4008 mark_object (HASH_KEY (h, i));
4009 marked = 1;
4012 if (!value_known_to_survive_p)
4014 mark_object (HASH_VALUE (h, i));
4015 marked = 1;
4022 return marked;
4025 /* Remove elements from weak hash tables that don't survive the
4026 current garbage collection. Remove weak tables that don't survive
4027 from Vweak_hash_tables. Called from gc_sweep. */
4029 void
4030 sweep_weak_hash_tables (void)
4032 struct Lisp_Hash_Table *h, *used, *next;
4033 bool marked;
4035 /* Mark all keys and values that are in use. Keep on marking until
4036 there is no more change. This is necessary for cases like
4037 value-weak table A containing an entry X -> Y, where Y is used in a
4038 key-weak table B, Z -> Y. If B comes after A in the list of weak
4039 tables, X -> Y might be removed from A, although when looking at B
4040 one finds that it shouldn't. */
4043 marked = 0;
4044 for (h = weak_hash_tables; h; h = h->next_weak)
4046 if (h->header.size & ARRAY_MARK_FLAG)
4047 marked |= sweep_weak_table (h, 0);
4050 while (marked);
4052 /* Remove tables and entries that aren't used. */
4053 for (h = weak_hash_tables, used = NULL; h; h = next)
4055 next = h->next_weak;
4057 if (h->header.size & ARRAY_MARK_FLAG)
4059 /* TABLE is marked as used. Sweep its contents. */
4060 if (h->count > 0)
4061 sweep_weak_table (h, 1);
4063 /* Add table to the list of used weak hash tables. */
4064 h->next_weak = used;
4065 used = h;
4069 weak_hash_tables = used;
4074 /***********************************************************************
4075 Hash Code Computation
4076 ***********************************************************************/
4078 /* Maximum depth up to which to dive into Lisp structures. */
4080 #define SXHASH_MAX_DEPTH 3
4082 /* Maximum length up to which to take list and vector elements into
4083 account. */
4085 #define SXHASH_MAX_LEN 7
4087 /* Combine two integers X and Y for hashing. The result might not fit
4088 into a Lisp integer. */
4090 #define SXHASH_COMBINE(X, Y) \
4091 ((((EMACS_UINT) (X) << 4) + ((EMACS_UINT) (X) >> (BITS_PER_EMACS_INT - 4))) \
4092 + (EMACS_UINT) (Y))
4094 /* Hash X, returning a value that fits into a Lisp integer. */
4095 #define SXHASH_REDUCE(X) \
4096 ((((X) ^ (X) >> (BITS_PER_EMACS_INT - FIXNUM_BITS))) & INTMASK)
4098 /* Return a hash for string PTR which has length LEN. The hash value
4099 can be any EMACS_UINT value. */
4101 EMACS_UINT
4102 hash_string (char const *ptr, ptrdiff_t len)
4104 char const *p = ptr;
4105 char const *end = p + len;
4106 unsigned char c;
4107 EMACS_UINT hash = 0;
4109 while (p != end)
4111 c = *p++;
4112 hash = SXHASH_COMBINE (hash, c);
4115 return hash;
4118 /* Return a hash for string PTR which has length LEN. The hash
4119 code returned is guaranteed to fit in a Lisp integer. */
4121 static EMACS_UINT
4122 sxhash_string (char const *ptr, ptrdiff_t len)
4124 EMACS_UINT hash = hash_string (ptr, len);
4125 return SXHASH_REDUCE (hash);
4128 /* Return a hash for the floating point value VAL. */
4130 static EMACS_INT
4131 sxhash_float (double val)
4133 EMACS_UINT hash = 0;
4134 enum {
4135 WORDS_PER_DOUBLE = (sizeof val / sizeof hash
4136 + (sizeof val % sizeof hash != 0))
4138 union {
4139 double val;
4140 EMACS_UINT word[WORDS_PER_DOUBLE];
4141 } u;
4142 int i;
4143 u.val = val;
4144 memset (&u.val + 1, 0, sizeof u - sizeof u.val);
4145 for (i = 0; i < WORDS_PER_DOUBLE; i++)
4146 hash = SXHASH_COMBINE (hash, u.word[i]);
4147 return SXHASH_REDUCE (hash);
4150 /* Return a hash for list LIST. DEPTH is the current depth in the
4151 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4153 static EMACS_UINT
4154 sxhash_list (Lisp_Object list, int depth)
4156 EMACS_UINT hash = 0;
4157 int i;
4159 if (depth < SXHASH_MAX_DEPTH)
4160 for (i = 0;
4161 CONSP (list) && i < SXHASH_MAX_LEN;
4162 list = XCDR (list), ++i)
4164 EMACS_UINT hash2 = sxhash (XCAR (list), depth + 1);
4165 hash = SXHASH_COMBINE (hash, hash2);
4168 if (!NILP (list))
4170 EMACS_UINT hash2 = sxhash (list, depth + 1);
4171 hash = SXHASH_COMBINE (hash, hash2);
4174 return SXHASH_REDUCE (hash);
4178 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4179 the Lisp structure. */
4181 static EMACS_UINT
4182 sxhash_vector (Lisp_Object vec, int depth)
4184 EMACS_UINT hash = ASIZE (vec);
4185 int i, n;
4187 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4188 for (i = 0; i < n; ++i)
4190 EMACS_UINT hash2 = sxhash (AREF (vec, i), depth + 1);
4191 hash = SXHASH_COMBINE (hash, hash2);
4194 return SXHASH_REDUCE (hash);
4197 /* Return a hash for bool-vector VECTOR. */
4199 static EMACS_UINT
4200 sxhash_bool_vector (Lisp_Object vec)
4202 EMACS_UINT hash = XBOOL_VECTOR (vec)->size;
4203 int i, n;
4205 n = min (SXHASH_MAX_LEN, XBOOL_VECTOR (vec)->header.size);
4206 for (i = 0; i < n; ++i)
4207 hash = SXHASH_COMBINE (hash, XBOOL_VECTOR (vec)->data[i]);
4209 return SXHASH_REDUCE (hash);
4213 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4214 structure. Value is an unsigned integer clipped to INTMASK. */
4216 EMACS_UINT
4217 sxhash (Lisp_Object obj, int depth)
4219 EMACS_UINT hash;
4221 if (depth > SXHASH_MAX_DEPTH)
4222 return 0;
4224 switch (XTYPE (obj))
4226 case_Lisp_Int:
4227 hash = XUINT (obj);
4228 break;
4230 case Lisp_Misc:
4231 hash = XUINT (obj);
4232 break;
4234 case Lisp_Symbol:
4235 obj = SYMBOL_NAME (obj);
4236 /* Fall through. */
4238 case Lisp_String:
4239 hash = sxhash_string (SSDATA (obj), SBYTES (obj));
4240 break;
4242 /* This can be everything from a vector to an overlay. */
4243 case Lisp_Vectorlike:
4244 if (VECTORP (obj))
4245 /* According to the CL HyperSpec, two arrays are equal only if
4246 they are `eq', except for strings and bit-vectors. In
4247 Emacs, this works differently. We have to compare element
4248 by element. */
4249 hash = sxhash_vector (obj, depth);
4250 else if (BOOL_VECTOR_P (obj))
4251 hash = sxhash_bool_vector (obj);
4252 else
4253 /* Others are `equal' if they are `eq', so let's take their
4254 address as hash. */
4255 hash = XUINT (obj);
4256 break;
4258 case Lisp_Cons:
4259 hash = sxhash_list (obj, depth);
4260 break;
4262 case Lisp_Float:
4263 hash = sxhash_float (XFLOAT_DATA (obj));
4264 break;
4266 default:
4267 emacs_abort ();
4270 return hash;
4275 /***********************************************************************
4276 Lisp Interface
4277 ***********************************************************************/
4280 DEFUN ("sxhash", Fsxhash, Ssxhash, 1, 1, 0,
4281 doc: /* Compute a hash code for OBJ and return it as integer. */)
4282 (Lisp_Object obj)
4284 EMACS_UINT hash = sxhash (obj, 0);
4285 return make_number (hash);
4289 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4290 doc: /* Create and return a new hash table.
4292 Arguments are specified as keyword/argument pairs. The following
4293 arguments are defined:
4295 :test TEST -- TEST must be a symbol that specifies how to compare
4296 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4297 `equal'. User-supplied test and hash functions can be specified via
4298 `define-hash-table-test'.
4300 :size SIZE -- A hint as to how many elements will be put in the table.
4301 Default is 65.
4303 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4304 fills up. If REHASH-SIZE is an integer, increase the size by that
4305 amount. If it is a float, it must be > 1.0, and the new size is the
4306 old size multiplied by that factor. Default is 1.5.
4308 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4309 Resize the hash table when the ratio (number of entries / table size)
4310 is greater than or equal to THRESHOLD. Default is 0.8.
4312 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4313 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4314 returned is a weak table. Key/value pairs are removed from a weak
4315 hash table when there are no non-weak references pointing to their
4316 key, value, one of key or value, or both key and value, depending on
4317 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4318 is nil.
4320 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4321 (ptrdiff_t nargs, Lisp_Object *args)
4323 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4324 Lisp_Object user_test, user_hash;
4325 char *used;
4326 ptrdiff_t i;
4328 /* The vector `used' is used to keep track of arguments that
4329 have been consumed. */
4330 used = alloca (nargs * sizeof *used);
4331 memset (used, 0, nargs * sizeof *used);
4333 /* See if there's a `:test TEST' among the arguments. */
4334 i = get_key_arg (QCtest, nargs, args, used);
4335 test = i ? args[i] : Qeql;
4336 if (!EQ (test, Qeq) && !EQ (test, Qeql) && !EQ (test, Qequal))
4338 /* See if it is a user-defined test. */
4339 Lisp_Object prop;
4341 prop = Fget (test, Qhash_table_test);
4342 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4343 signal_error ("Invalid hash table test", test);
4344 user_test = XCAR (prop);
4345 user_hash = XCAR (XCDR (prop));
4347 else
4348 user_test = user_hash = Qnil;
4350 /* See if there's a `:size SIZE' argument. */
4351 i = get_key_arg (QCsize, nargs, args, used);
4352 size = i ? args[i] : Qnil;
4353 if (NILP (size))
4354 size = make_number (DEFAULT_HASH_SIZE);
4355 else if (!INTEGERP (size) || XINT (size) < 0)
4356 signal_error ("Invalid hash table size", size);
4358 /* Look for `:rehash-size SIZE'. */
4359 i = get_key_arg (QCrehash_size, nargs, args, used);
4360 rehash_size = i ? args[i] : make_float (DEFAULT_REHASH_SIZE);
4361 if (! ((INTEGERP (rehash_size) && 0 < XINT (rehash_size))
4362 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size))))
4363 signal_error ("Invalid hash table rehash size", rehash_size);
4365 /* Look for `:rehash-threshold THRESHOLD'. */
4366 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4367 rehash_threshold = i ? args[i] : make_float (DEFAULT_REHASH_THRESHOLD);
4368 if (! (FLOATP (rehash_threshold)
4369 && 0 < XFLOAT_DATA (rehash_threshold)
4370 && XFLOAT_DATA (rehash_threshold) <= 1))
4371 signal_error ("Invalid hash table rehash threshold", rehash_threshold);
4373 /* Look for `:weakness WEAK'. */
4374 i = get_key_arg (QCweakness, nargs, args, used);
4375 weak = i ? args[i] : Qnil;
4376 if (EQ (weak, Qt))
4377 weak = Qkey_and_value;
4378 if (!NILP (weak)
4379 && !EQ (weak, Qkey)
4380 && !EQ (weak, Qvalue)
4381 && !EQ (weak, Qkey_or_value)
4382 && !EQ (weak, Qkey_and_value))
4383 signal_error ("Invalid hash table weakness", weak);
4385 /* Now, all args should have been used up, or there's a problem. */
4386 for (i = 0; i < nargs; ++i)
4387 if (!used[i])
4388 signal_error ("Invalid argument list", args[i]);
4390 return make_hash_table (test, size, rehash_size, rehash_threshold, weak,
4391 user_test, user_hash);
4395 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4396 doc: /* Return a copy of hash table TABLE. */)
4397 (Lisp_Object table)
4399 return copy_hash_table (check_hash_table (table));
4403 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4404 doc: /* Return the number of elements in TABLE. */)
4405 (Lisp_Object table)
4407 return make_number (check_hash_table (table)->count);
4411 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4412 Shash_table_rehash_size, 1, 1, 0,
4413 doc: /* Return the current rehash size of TABLE. */)
4414 (Lisp_Object table)
4416 return check_hash_table (table)->rehash_size;
4420 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4421 Shash_table_rehash_threshold, 1, 1, 0,
4422 doc: /* Return the current rehash threshold of TABLE. */)
4423 (Lisp_Object table)
4425 return check_hash_table (table)->rehash_threshold;
4429 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4430 doc: /* Return the size of TABLE.
4431 The size can be used as an argument to `make-hash-table' to create
4432 a hash table than can hold as many elements as TABLE holds
4433 without need for resizing. */)
4434 (Lisp_Object table)
4436 struct Lisp_Hash_Table *h = check_hash_table (table);
4437 return make_number (HASH_TABLE_SIZE (h));
4441 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4442 doc: /* Return the test TABLE uses. */)
4443 (Lisp_Object table)
4445 return check_hash_table (table)->test;
4449 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4450 1, 1, 0,
4451 doc: /* Return the weakness of TABLE. */)
4452 (Lisp_Object table)
4454 return check_hash_table (table)->weak;
4458 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4459 doc: /* Return t if OBJ is a Lisp hash table object. */)
4460 (Lisp_Object obj)
4462 return HASH_TABLE_P (obj) ? Qt : Qnil;
4466 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4467 doc: /* Clear hash table TABLE and return it. */)
4468 (Lisp_Object table)
4470 hash_clear (check_hash_table (table));
4471 /* Be compatible with XEmacs. */
4472 return table;
4476 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4477 doc: /* Look up KEY in TABLE and return its associated value.
4478 If KEY is not found, return DFLT which defaults to nil. */)
4479 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4481 struct Lisp_Hash_Table *h = check_hash_table (table);
4482 ptrdiff_t i = hash_lookup (h, key, NULL);
4483 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4487 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4488 doc: /* Associate KEY with VALUE in hash table TABLE.
4489 If KEY is already present in table, replace its current value with
4490 VALUE. In any case, return VALUE. */)
4491 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4493 struct Lisp_Hash_Table *h = check_hash_table (table);
4494 ptrdiff_t i;
4495 EMACS_UINT hash;
4497 i = hash_lookup (h, key, &hash);
4498 if (i >= 0)
4499 set_hash_value_slot (h, i, value);
4500 else
4501 hash_put (h, key, value, hash);
4503 return value;
4507 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4508 doc: /* Remove KEY from TABLE. */)
4509 (Lisp_Object key, Lisp_Object table)
4511 struct Lisp_Hash_Table *h = check_hash_table (table);
4512 hash_remove_from_table (h, key);
4513 return Qnil;
4517 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4518 doc: /* Call FUNCTION for all entries in hash table TABLE.
4519 FUNCTION is called with two arguments, KEY and VALUE. */)
4520 (Lisp_Object function, Lisp_Object table)
4522 struct Lisp_Hash_Table *h = check_hash_table (table);
4523 Lisp_Object args[3];
4524 ptrdiff_t i;
4526 for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
4527 if (!NILP (HASH_HASH (h, i)))
4529 args[0] = function;
4530 args[1] = HASH_KEY (h, i);
4531 args[2] = HASH_VALUE (h, i);
4532 Ffuncall (3, args);
4535 return Qnil;
4539 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4540 Sdefine_hash_table_test, 3, 3, 0,
4541 doc: /* Define a new hash table test with name NAME, a symbol.
4543 In hash tables created with NAME specified as test, use TEST to
4544 compare keys, and HASH for computing hash codes of keys.
4546 TEST must be a function taking two arguments and returning non-nil if
4547 both arguments are the same. HASH must be a function taking one
4548 argument and return an integer that is the hash code of the argument.
4549 Hash code computation should use the whole value range of integers,
4550 including negative integers. */)
4551 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4553 return Fput (name, Qhash_table_test, list2 (test, hash));
4558 /************************************************************************
4559 MD5, SHA-1, and SHA-2
4560 ************************************************************************/
4562 #include "md5.h"
4563 #include "sha1.h"
4564 #include "sha256.h"
4565 #include "sha512.h"
4567 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4569 static Lisp_Object
4570 secure_hash (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror, Lisp_Object binary)
4572 int i;
4573 ptrdiff_t size;
4574 EMACS_INT start_char = 0, end_char = 0;
4575 ptrdiff_t start_byte, end_byte;
4576 register EMACS_INT b, e;
4577 register struct buffer *bp;
4578 EMACS_INT temp;
4579 int digest_size;
4580 void *(*hash_func) (const char *, size_t, void *);
4581 Lisp_Object digest;
4583 CHECK_SYMBOL (algorithm);
4585 if (STRINGP (object))
4587 if (NILP (coding_system))
4589 /* Decide the coding-system to encode the data with. */
4591 if (STRING_MULTIBYTE (object))
4592 /* use default, we can't guess correct value */
4593 coding_system = preferred_coding_system ();
4594 else
4595 coding_system = Qraw_text;
4598 if (NILP (Fcoding_system_p (coding_system)))
4600 /* Invalid coding system. */
4602 if (!NILP (noerror))
4603 coding_system = Qraw_text;
4604 else
4605 xsignal1 (Qcoding_system_error, coding_system);
4608 if (STRING_MULTIBYTE (object))
4609 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4611 size = SCHARS (object);
4613 if (!NILP (start))
4615 CHECK_NUMBER (start);
4617 start_char = XINT (start);
4619 if (start_char < 0)
4620 start_char += size;
4623 if (NILP (end))
4624 end_char = size;
4625 else
4627 CHECK_NUMBER (end);
4629 end_char = XINT (end);
4631 if (end_char < 0)
4632 end_char += size;
4635 if (!(0 <= start_char && start_char <= end_char && end_char <= size))
4636 args_out_of_range_3 (object, make_number (start_char),
4637 make_number (end_char));
4639 start_byte = NILP (start) ? 0 : string_char_to_byte (object, start_char);
4640 end_byte =
4641 NILP (end) ? SBYTES (object) : string_char_to_byte (object, end_char);
4643 else
4645 struct buffer *prev = current_buffer;
4647 record_unwind_current_buffer ();
4649 CHECK_BUFFER (object);
4651 bp = XBUFFER (object);
4652 set_buffer_internal (bp);
4654 if (NILP (start))
4655 b = BEGV;
4656 else
4658 CHECK_NUMBER_COERCE_MARKER (start);
4659 b = XINT (start);
4662 if (NILP (end))
4663 e = ZV;
4664 else
4666 CHECK_NUMBER_COERCE_MARKER (end);
4667 e = XINT (end);
4670 if (b > e)
4671 temp = b, b = e, e = temp;
4673 if (!(BEGV <= b && e <= ZV))
4674 args_out_of_range (start, end);
4676 if (NILP (coding_system))
4678 /* Decide the coding-system to encode the data with.
4679 See fileio.c:Fwrite-region */
4681 if (!NILP (Vcoding_system_for_write))
4682 coding_system = Vcoding_system_for_write;
4683 else
4685 bool force_raw_text = 0;
4687 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4688 if (NILP (coding_system)
4689 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4691 coding_system = Qnil;
4692 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4693 force_raw_text = 1;
4696 if (NILP (coding_system) && !NILP (Fbuffer_file_name (object)))
4698 /* Check file-coding-system-alist. */
4699 Lisp_Object args[4], val;
4701 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4702 args[3] = Fbuffer_file_name (object);
4703 val = Ffind_operation_coding_system (4, args);
4704 if (CONSP (val) && !NILP (XCDR (val)))
4705 coding_system = XCDR (val);
4708 if (NILP (coding_system)
4709 && !NILP (BVAR (XBUFFER (object), buffer_file_coding_system)))
4711 /* If we still have not decided a coding system, use the
4712 default value of buffer-file-coding-system. */
4713 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4716 if (!force_raw_text
4717 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4718 /* Confirm that VAL can surely encode the current region. */
4719 coding_system = call4 (Vselect_safe_coding_system_function,
4720 make_number (b), make_number (e),
4721 coding_system, Qnil);
4723 if (force_raw_text)
4724 coding_system = Qraw_text;
4727 if (NILP (Fcoding_system_p (coding_system)))
4729 /* Invalid coding system. */
4731 if (!NILP (noerror))
4732 coding_system = Qraw_text;
4733 else
4734 xsignal1 (Qcoding_system_error, coding_system);
4738 object = make_buffer_string (b, e, 0);
4739 set_buffer_internal (prev);
4740 /* Discard the unwind protect for recovering the current
4741 buffer. */
4742 specpdl_ptr--;
4744 if (STRING_MULTIBYTE (object))
4745 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4746 start_byte = 0;
4747 end_byte = SBYTES (object);
4750 if (EQ (algorithm, Qmd5))
4752 digest_size = MD5_DIGEST_SIZE;
4753 hash_func = md5_buffer;
4755 else if (EQ (algorithm, Qsha1))
4757 digest_size = SHA1_DIGEST_SIZE;
4758 hash_func = sha1_buffer;
4760 else if (EQ (algorithm, Qsha224))
4762 digest_size = SHA224_DIGEST_SIZE;
4763 hash_func = sha224_buffer;
4765 else if (EQ (algorithm, Qsha256))
4767 digest_size = SHA256_DIGEST_SIZE;
4768 hash_func = sha256_buffer;
4770 else if (EQ (algorithm, Qsha384))
4772 digest_size = SHA384_DIGEST_SIZE;
4773 hash_func = sha384_buffer;
4775 else if (EQ (algorithm, Qsha512))
4777 digest_size = SHA512_DIGEST_SIZE;
4778 hash_func = sha512_buffer;
4780 else
4781 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm)));
4783 /* allocate 2 x digest_size so that it can be re-used to hold the
4784 hexified value */
4785 digest = make_uninit_string (digest_size * 2);
4787 hash_func (SSDATA (object) + start_byte,
4788 end_byte - start_byte,
4789 SSDATA (digest));
4791 if (NILP (binary))
4793 unsigned char *p = SDATA (digest);
4794 for (i = digest_size - 1; i >= 0; i--)
4796 static char const hexdigit[16] = "0123456789abcdef";
4797 int p_i = p[i];
4798 p[2 * i] = hexdigit[p_i >> 4];
4799 p[2 * i + 1] = hexdigit[p_i & 0xf];
4801 return digest;
4803 else
4804 return make_unibyte_string (SSDATA (digest), digest_size);
4807 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
4808 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
4810 A message digest is a cryptographic checksum of a document, and the
4811 algorithm to calculate it is defined in RFC 1321.
4813 The two optional arguments START and END are character positions
4814 specifying for which part of OBJECT the message digest should be
4815 computed. If nil or omitted, the digest is computed for the whole
4816 OBJECT.
4818 The MD5 message digest is computed from the result of encoding the
4819 text in a coding system, not directly from the internal Emacs form of
4820 the text. The optional fourth argument CODING-SYSTEM specifies which
4821 coding system to encode the text with. It should be the same coding
4822 system that you used or will use when actually writing the text into a
4823 file.
4825 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
4826 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
4827 system would be chosen by default for writing this text into a file.
4829 If OBJECT is a string, the most preferred coding system (see the
4830 command `prefer-coding-system') is used.
4832 If NOERROR is non-nil, silently assume the `raw-text' coding if the
4833 guesswork fails. Normally, an error is signaled in such case. */)
4834 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
4836 return secure_hash (Qmd5, object, start, end, coding_system, noerror, Qnil);
4839 DEFUN ("secure-hash", Fsecure_hash, Ssecure_hash, 2, 5, 0,
4840 doc: /* Return the secure hash of OBJECT, a buffer or string.
4841 ALGORITHM is a symbol specifying the hash to use:
4842 md5, sha1, sha224, sha256, sha384 or sha512.
4844 The two optional arguments START and END are positions specifying for
4845 which part of OBJECT to compute the hash. If nil or omitted, uses the
4846 whole OBJECT.
4848 If BINARY is non-nil, returns a string in binary form. */)
4849 (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object binary)
4851 return secure_hash (algorithm, object, start, end, Qnil, Qnil, binary);
4854 void
4855 syms_of_fns (void)
4857 DEFSYM (Qmd5, "md5");
4858 DEFSYM (Qsha1, "sha1");
4859 DEFSYM (Qsha224, "sha224");
4860 DEFSYM (Qsha256, "sha256");
4861 DEFSYM (Qsha384, "sha384");
4862 DEFSYM (Qsha512, "sha512");
4864 /* Hash table stuff. */
4865 DEFSYM (Qhash_table_p, "hash-table-p");
4866 DEFSYM (Qeq, "eq");
4867 DEFSYM (Qeql, "eql");
4868 DEFSYM (Qequal, "equal");
4869 DEFSYM (QCtest, ":test");
4870 DEFSYM (QCsize, ":size");
4871 DEFSYM (QCrehash_size, ":rehash-size");
4872 DEFSYM (QCrehash_threshold, ":rehash-threshold");
4873 DEFSYM (QCweakness, ":weakness");
4874 DEFSYM (Qkey, "key");
4875 DEFSYM (Qvalue, "value");
4876 DEFSYM (Qhash_table_test, "hash-table-test");
4877 DEFSYM (Qkey_or_value, "key-or-value");
4878 DEFSYM (Qkey_and_value, "key-and-value");
4880 defsubr (&Ssxhash);
4881 defsubr (&Smake_hash_table);
4882 defsubr (&Scopy_hash_table);
4883 defsubr (&Shash_table_count);
4884 defsubr (&Shash_table_rehash_size);
4885 defsubr (&Shash_table_rehash_threshold);
4886 defsubr (&Shash_table_size);
4887 defsubr (&Shash_table_test);
4888 defsubr (&Shash_table_weakness);
4889 defsubr (&Shash_table_p);
4890 defsubr (&Sclrhash);
4891 defsubr (&Sgethash);
4892 defsubr (&Sputhash);
4893 defsubr (&Sremhash);
4894 defsubr (&Smaphash);
4895 defsubr (&Sdefine_hash_table_test);
4897 DEFSYM (Qstring_lessp, "string-lessp");
4898 DEFSYM (Qprovide, "provide");
4899 DEFSYM (Qrequire, "require");
4900 DEFSYM (Qyes_or_no_p_history, "yes-or-no-p-history");
4901 DEFSYM (Qcursor_in_echo_area, "cursor-in-echo-area");
4902 DEFSYM (Qwidget_type, "widget-type");
4904 staticpro (&string_char_byte_cache_string);
4905 string_char_byte_cache_string = Qnil;
4907 require_nesting_list = Qnil;
4908 staticpro (&require_nesting_list);
4910 Fset (Qyes_or_no_p_history, Qnil);
4912 DEFVAR_LISP ("features", Vfeatures,
4913 doc: /* A list of symbols which are the features of the executing Emacs.
4914 Used by `featurep' and `require', and altered by `provide'. */);
4915 Vfeatures = Fcons (intern_c_string ("emacs"), Qnil);
4916 DEFSYM (Qsubfeatures, "subfeatures");
4918 #ifdef HAVE_LANGINFO_CODESET
4919 DEFSYM (Qcodeset, "codeset");
4920 DEFSYM (Qdays, "days");
4921 DEFSYM (Qmonths, "months");
4922 DEFSYM (Qpaper, "paper");
4923 #endif /* HAVE_LANGINFO_CODESET */
4925 DEFVAR_BOOL ("use-dialog-box", use_dialog_box,
4926 doc: /* Non-nil means mouse commands use dialog boxes to ask questions.
4927 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
4928 invoked by mouse clicks and mouse menu items.
4930 On some platforms, file selection dialogs are also enabled if this is
4931 non-nil. */);
4932 use_dialog_box = 1;
4934 DEFVAR_BOOL ("use-file-dialog", use_file_dialog,
4935 doc: /* Non-nil means mouse commands use a file dialog to ask for files.
4936 This applies to commands from menus and tool bar buttons even when
4937 they are initiated from the keyboard. If `use-dialog-box' is nil,
4938 that disables the use of a file dialog, regardless of the value of
4939 this variable. */);
4940 use_file_dialog = 1;
4942 defsubr (&Sidentity);
4943 defsubr (&Srandom);
4944 defsubr (&Slength);
4945 defsubr (&Ssafe_length);
4946 defsubr (&Sstring_bytes);
4947 defsubr (&Sstring_equal);
4948 defsubr (&Scompare_strings);
4949 defsubr (&Sstring_lessp);
4950 defsubr (&Sappend);
4951 defsubr (&Sconcat);
4952 defsubr (&Svconcat);
4953 defsubr (&Scopy_sequence);
4954 defsubr (&Sstring_make_multibyte);
4955 defsubr (&Sstring_make_unibyte);
4956 defsubr (&Sstring_as_multibyte);
4957 defsubr (&Sstring_as_unibyte);
4958 defsubr (&Sstring_to_multibyte);
4959 defsubr (&Sstring_to_unibyte);
4960 defsubr (&Scopy_alist);
4961 defsubr (&Ssubstring);
4962 defsubr (&Ssubstring_no_properties);
4963 defsubr (&Snthcdr);
4964 defsubr (&Snth);
4965 defsubr (&Selt);
4966 defsubr (&Smember);
4967 defsubr (&Smemq);
4968 defsubr (&Smemql);
4969 defsubr (&Sassq);
4970 defsubr (&Sassoc);
4971 defsubr (&Srassq);
4972 defsubr (&Srassoc);
4973 defsubr (&Sdelq);
4974 defsubr (&Sdelete);
4975 defsubr (&Snreverse);
4976 defsubr (&Sreverse);
4977 defsubr (&Ssort);
4978 defsubr (&Splist_get);
4979 defsubr (&Sget);
4980 defsubr (&Splist_put);
4981 defsubr (&Sput);
4982 defsubr (&Slax_plist_get);
4983 defsubr (&Slax_plist_put);
4984 defsubr (&Seql);
4985 defsubr (&Sequal);
4986 defsubr (&Sequal_including_properties);
4987 defsubr (&Sfillarray);
4988 defsubr (&Sclear_string);
4989 defsubr (&Snconc);
4990 defsubr (&Smapcar);
4991 defsubr (&Smapc);
4992 defsubr (&Smapconcat);
4993 defsubr (&Syes_or_no_p);
4994 defsubr (&Sload_average);
4995 defsubr (&Sfeaturep);
4996 defsubr (&Srequire);
4997 defsubr (&Sprovide);
4998 defsubr (&Splist_member);
4999 defsubr (&Swidget_put);
5000 defsubr (&Swidget_get);
5001 defsubr (&Swidget_apply);
5002 defsubr (&Sbase64_encode_region);
5003 defsubr (&Sbase64_decode_region);
5004 defsubr (&Sbase64_encode_string);
5005 defsubr (&Sbase64_decode_string);
5006 defsubr (&Smd5);
5007 defsubr (&Ssecure_hash);
5008 defsubr (&Slocale_info);