* doc/emacs/custom.texi (Directory Variables): Fix paren typo.
[emacs.git] / src / fns.c
blobfbb3fb5b1617715b2fc94971d413230a90f38f25
1 /* Random utility Lisp functions.
3 Copyright (C) 1985-1987, 1993-1995, 1997-2013 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, i.e. between `most-negative-fixnum'
65 and `most-positive-fixnum', inclusive, are equally likely.
67 With positive integer LIMIT, return random number in interval [0,LIMIT).
68 With argument t, set the random number seed from the current time and pid.
69 With a string argument, set the seed based on the string's contents.
70 Other values of LIMIT are ignored.
72 See Info node `(elisp)Random Numbers' for more details. */)
73 (Lisp_Object limit)
75 EMACS_INT val;
77 if (EQ (limit, Qt))
78 init_random ();
79 else if (STRINGP (limit))
80 seed_random (SSDATA (limit), SBYTES (limit));
82 val = get_random ();
83 if (NATNUMP (limit) && XFASTINT (limit) != 0)
84 val %= XFASTINT (limit);
85 return make_number (val);
88 /* Heuristic on how many iterations of a tight loop can be safely done
89 before it's time to do a QUIT. This must be a power of 2. */
90 enum { QUIT_COUNT_HEURISTIC = 1 << 16 };
92 /* Random data-structure functions */
94 DEFUN ("length", Flength, Slength, 1, 1, 0,
95 doc: /* Return the length of vector, list or string SEQUENCE.
96 A byte-code function object is also allowed.
97 If the string contains multibyte characters, this is not necessarily
98 the number of bytes in the string; it is the number of characters.
99 To get the number of bytes, use `string-bytes'. */)
100 (register Lisp_Object sequence)
102 register Lisp_Object val;
104 if (STRINGP (sequence))
105 XSETFASTINT (val, SCHARS (sequence));
106 else if (VECTORP (sequence))
107 XSETFASTINT (val, ASIZE (sequence));
108 else if (CHAR_TABLE_P (sequence))
109 XSETFASTINT (val, MAX_CHAR);
110 else if (BOOL_VECTOR_P (sequence))
111 XSETFASTINT (val, XBOOL_VECTOR (sequence)->size);
112 else if (COMPILEDP (sequence))
113 XSETFASTINT (val, ASIZE (sequence) & PSEUDOVECTOR_SIZE_MASK);
114 else if (CONSP (sequence))
116 EMACS_INT i = 0;
120 ++i;
121 if ((i & (QUIT_COUNT_HEURISTIC - 1)) == 0)
123 if (MOST_POSITIVE_FIXNUM < i)
124 error ("List too long");
125 QUIT;
127 sequence = XCDR (sequence);
129 while (CONSP (sequence));
131 CHECK_LIST_END (sequence, sequence);
133 val = make_number (i);
135 else if (NILP (sequence))
136 XSETFASTINT (val, 0);
137 else
138 wrong_type_argument (Qsequencep, sequence);
140 return val;
143 /* This does not check for quits. That is safe since it must terminate. */
145 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
146 doc: /* Return the length of a list, but avoid error or infinite loop.
147 This function never gets an error. If LIST is not really a list,
148 it returns 0. If LIST is circular, it returns a finite value
149 which is at least the number of distinct elements. */)
150 (Lisp_Object list)
152 Lisp_Object tail, halftail;
153 double hilen = 0;
154 uintmax_t lolen = 1;
156 if (! CONSP (list))
157 return make_number (0);
159 /* halftail is used to detect circular lists. */
160 for (tail = halftail = list; ; )
162 tail = XCDR (tail);
163 if (! CONSP (tail))
164 break;
165 if (EQ (tail, halftail))
166 break;
167 lolen++;
168 if ((lolen & 1) == 0)
170 halftail = XCDR (halftail);
171 if ((lolen & (QUIT_COUNT_HEURISTIC - 1)) == 0)
173 QUIT;
174 if (lolen == 0)
175 hilen += UINTMAX_MAX + 1.0;
180 /* If the length does not fit into a fixnum, return a float.
181 On all known practical machines this returns an upper bound on
182 the true length. */
183 return hilen ? make_float (hilen + lolen) : make_fixnum_or_float (lolen);
186 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
187 doc: /* Return the number of bytes in STRING.
188 If STRING is multibyte, this may be greater than the length of STRING. */)
189 (Lisp_Object string)
191 CHECK_STRING (string);
192 return make_number (SBYTES (string));
195 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
196 doc: /* Return t if two strings have identical contents.
197 Case is significant, but text properties are ignored.
198 Symbols are also allowed; their print names are used instead. */)
199 (register Lisp_Object s1, Lisp_Object s2)
201 if (SYMBOLP (s1))
202 s1 = SYMBOL_NAME (s1);
203 if (SYMBOLP (s2))
204 s2 = SYMBOL_NAME (s2);
205 CHECK_STRING (s1);
206 CHECK_STRING (s2);
208 if (SCHARS (s1) != SCHARS (s2)
209 || SBYTES (s1) != SBYTES (s2)
210 || memcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
211 return Qnil;
212 return Qt;
215 DEFUN ("compare-strings", Fcompare_strings, Scompare_strings, 6, 7, 0,
216 doc: /* Compare the contents of two strings, converting to multibyte if needed.
217 The arguments START1, END1, START2, and END2, if non-nil, are
218 positions specifying which parts of STR1 or STR2 to compare. In
219 string STR1, compare the part between START1 (inclusive) and END1
220 \(exclusive). If START1 is nil, it defaults to 0, the beginning of
221 the string; if END1 is nil, it defaults to the length of the string.
222 Likewise, in string STR2, compare the part between START2 and END2.
224 The strings are compared by the numeric values of their characters.
225 For instance, STR1 is "less than" STR2 if its first differing
226 character has a smaller numeric value. If IGNORE-CASE is non-nil,
227 characters are converted to lower-case before comparing them. Unibyte
228 strings are converted to multibyte for comparison.
230 The value is t if the strings (or specified portions) match.
231 If string STR1 is less, the value is a negative number N;
232 - 1 - N is the number of characters that match at the beginning.
233 If string STR1 is greater, the value is a positive number N;
234 N - 1 is the number of characters that match at the beginning. */)
235 (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2, Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
237 register ptrdiff_t end1_char, end2_char;
238 register ptrdiff_t i1, i1_byte, i2, i2_byte;
240 CHECK_STRING (str1);
241 CHECK_STRING (str2);
242 if (NILP (start1))
243 start1 = make_number (0);
244 if (NILP (start2))
245 start2 = make_number (0);
246 CHECK_NATNUM (start1);
247 CHECK_NATNUM (start2);
248 if (! NILP (end1))
249 CHECK_NATNUM (end1);
250 if (! NILP (end2))
251 CHECK_NATNUM (end2);
253 end1_char = SCHARS (str1);
254 if (! NILP (end1) && end1_char > XINT (end1))
255 end1_char = XINT (end1);
256 if (end1_char < XINT (start1))
257 args_out_of_range (str1, start1);
259 end2_char = SCHARS (str2);
260 if (! NILP (end2) && end2_char > XINT (end2))
261 end2_char = XINT (end2);
262 if (end2_char < XINT (start2))
263 args_out_of_range (str2, start2);
265 i1 = XINT (start1);
266 i2 = XINT (start2);
268 i1_byte = string_char_to_byte (str1, i1);
269 i2_byte = string_char_to_byte (str2, i2);
271 while (i1 < end1_char && i2 < end2_char)
273 /* When we find a mismatch, we must compare the
274 characters, not just the bytes. */
275 int c1, c2;
277 if (STRING_MULTIBYTE (str1))
278 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c1, str1, i1, i1_byte);
279 else
281 c1 = SREF (str1, i1++);
282 MAKE_CHAR_MULTIBYTE (c1);
285 if (STRING_MULTIBYTE (str2))
286 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c2, str2, i2, i2_byte);
287 else
289 c2 = SREF (str2, i2++);
290 MAKE_CHAR_MULTIBYTE (c2);
293 if (c1 == c2)
294 continue;
296 if (! NILP (ignore_case))
298 Lisp_Object tem;
300 tem = Fupcase (make_number (c1));
301 c1 = XINT (tem);
302 tem = Fupcase (make_number (c2));
303 c2 = XINT (tem);
306 if (c1 == c2)
307 continue;
309 /* Note that I1 has already been incremented
310 past the character that we are comparing;
311 hence we don't add or subtract 1 here. */
312 if (c1 < c2)
313 return make_number (- i1 + XINT (start1));
314 else
315 return make_number (i1 - XINT (start1));
318 if (i1 < end1_char)
319 return make_number (i1 - XINT (start1) + 1);
320 if (i2 < end2_char)
321 return make_number (- i1 + XINT (start1) - 1);
323 return Qt;
326 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
327 doc: /* Return t if first arg string is less than second in lexicographic order.
328 Case is significant.
329 Symbols are also allowed; their print names are used instead. */)
330 (register Lisp_Object s1, Lisp_Object s2)
332 register ptrdiff_t end;
333 register ptrdiff_t i1, i1_byte, i2, i2_byte;
335 if (SYMBOLP (s1))
336 s1 = SYMBOL_NAME (s1);
337 if (SYMBOLP (s2))
338 s2 = SYMBOL_NAME (s2);
339 CHECK_STRING (s1);
340 CHECK_STRING (s2);
342 i1 = i1_byte = i2 = i2_byte = 0;
344 end = SCHARS (s1);
345 if (end > SCHARS (s2))
346 end = SCHARS (s2);
348 while (i1 < end)
350 /* When we find a mismatch, we must compare the
351 characters, not just the bytes. */
352 int c1, c2;
354 FETCH_STRING_CHAR_ADVANCE (c1, s1, i1, i1_byte);
355 FETCH_STRING_CHAR_ADVANCE (c2, s2, i2, i2_byte);
357 if (c1 != c2)
358 return c1 < c2 ? Qt : Qnil;
360 return i1 < SCHARS (s2) ? Qt : Qnil;
363 static Lisp_Object concat (ptrdiff_t nargs, Lisp_Object *args,
364 enum Lisp_Type target_type, bool last_special);
366 /* ARGSUSED */
367 Lisp_Object
368 concat2 (Lisp_Object s1, Lisp_Object s2)
370 Lisp_Object args[2];
371 args[0] = s1;
372 args[1] = s2;
373 return concat (2, args, Lisp_String, 0);
376 /* ARGSUSED */
377 Lisp_Object
378 concat3 (Lisp_Object s1, Lisp_Object s2, Lisp_Object s3)
380 Lisp_Object args[3];
381 args[0] = s1;
382 args[1] = s2;
383 args[2] = s3;
384 return concat (3, args, Lisp_String, 0);
387 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
388 doc: /* Concatenate all the arguments and make the result a list.
389 The result is a list whose elements are the elements of all the arguments.
390 Each argument may be a list, vector or string.
391 The last argument is not copied, just used as the tail of the new list.
392 usage: (append &rest SEQUENCES) */)
393 (ptrdiff_t nargs, Lisp_Object *args)
395 return concat (nargs, args, Lisp_Cons, 1);
398 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
399 doc: /* Concatenate all the arguments and make the result a string.
400 The result is a string whose elements are the elements of all the arguments.
401 Each argument may be a string or a list or vector of characters (integers).
402 usage: (concat &rest SEQUENCES) */)
403 (ptrdiff_t nargs, Lisp_Object *args)
405 return concat (nargs, args, Lisp_String, 0);
408 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
409 doc: /* Concatenate all the arguments and make the result a vector.
410 The result is a vector whose elements are the elements of all the arguments.
411 Each argument may be a list, vector or string.
412 usage: (vconcat &rest SEQUENCES) */)
413 (ptrdiff_t nargs, Lisp_Object *args)
415 return concat (nargs, args, Lisp_Vectorlike, 0);
419 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
420 doc: /* Return a copy of a list, vector, string or char-table.
421 The elements of a list or vector are not copied; they are shared
422 with the original. */)
423 (Lisp_Object arg)
425 if (NILP (arg)) return arg;
427 if (CHAR_TABLE_P (arg))
429 return copy_char_table (arg);
432 if (BOOL_VECTOR_P (arg))
434 Lisp_Object val;
435 ptrdiff_t size_in_chars
436 = ((XBOOL_VECTOR (arg)->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
437 / BOOL_VECTOR_BITS_PER_CHAR);
439 val = Fmake_bool_vector (Flength (arg), Qnil);
440 memcpy (XBOOL_VECTOR (val)->data, XBOOL_VECTOR (arg)->data,
441 size_in_chars);
442 return val;
445 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
446 wrong_type_argument (Qsequencep, arg);
448 return concat (1, &arg, CONSP (arg) ? Lisp_Cons : XTYPE (arg), 0);
451 /* This structure holds information of an argument of `concat' that is
452 a string and has text properties to be copied. */
453 struct textprop_rec
455 ptrdiff_t argnum; /* refer to ARGS (arguments of `concat') */
456 ptrdiff_t from; /* refer to ARGS[argnum] (argument string) */
457 ptrdiff_t to; /* refer to VAL (the target string) */
460 static Lisp_Object
461 concat (ptrdiff_t nargs, Lisp_Object *args,
462 enum Lisp_Type target_type, bool last_special)
464 Lisp_Object val;
465 Lisp_Object tail;
466 Lisp_Object this;
467 ptrdiff_t toindex;
468 ptrdiff_t toindex_byte = 0;
469 EMACS_INT result_len;
470 EMACS_INT result_len_byte;
471 ptrdiff_t argnum;
472 Lisp_Object last_tail;
473 Lisp_Object prev;
474 bool some_multibyte;
475 /* When we make a multibyte string, we can't copy text properties
476 while concatenating each string because the length of resulting
477 string can't be decided until we finish the whole concatenation.
478 So, we record strings that have text properties to be copied
479 here, and copy the text properties after the concatenation. */
480 struct textprop_rec *textprops = NULL;
481 /* Number of elements in textprops. */
482 ptrdiff_t num_textprops = 0;
483 USE_SAFE_ALLOCA;
485 tail = Qnil;
487 /* In append, the last arg isn't treated like the others */
488 if (last_special && nargs > 0)
490 nargs--;
491 last_tail = args[nargs];
493 else
494 last_tail = Qnil;
496 /* Check each argument. */
497 for (argnum = 0; argnum < nargs; argnum++)
499 this = args[argnum];
500 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
501 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
502 wrong_type_argument (Qsequencep, this);
505 /* Compute total length in chars of arguments in RESULT_LEN.
506 If desired output is a string, also compute length in bytes
507 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
508 whether the result should be a multibyte string. */
509 result_len_byte = 0;
510 result_len = 0;
511 some_multibyte = 0;
512 for (argnum = 0; argnum < nargs; argnum++)
514 EMACS_INT len;
515 this = args[argnum];
516 len = XFASTINT (Flength (this));
517 if (target_type == Lisp_String)
519 /* We must count the number of bytes needed in the string
520 as well as the number of characters. */
521 ptrdiff_t i;
522 Lisp_Object ch;
523 int c;
524 ptrdiff_t this_len_byte;
526 if (VECTORP (this) || COMPILEDP (this))
527 for (i = 0; i < len; i++)
529 ch = AREF (this, i);
530 CHECK_CHARACTER (ch);
531 c = XFASTINT (ch);
532 this_len_byte = CHAR_BYTES (c);
533 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
534 string_overflow ();
535 result_len_byte += this_len_byte;
536 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
537 some_multibyte = 1;
539 else if (BOOL_VECTOR_P (this) && XBOOL_VECTOR (this)->size > 0)
540 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
541 else if (CONSP (this))
542 for (; CONSP (this); this = XCDR (this))
544 ch = XCAR (this);
545 CHECK_CHARACTER (ch);
546 c = XFASTINT (ch);
547 this_len_byte = CHAR_BYTES (c);
548 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
549 string_overflow ();
550 result_len_byte += this_len_byte;
551 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
552 some_multibyte = 1;
554 else if (STRINGP (this))
556 if (STRING_MULTIBYTE (this))
558 some_multibyte = 1;
559 this_len_byte = SBYTES (this);
561 else
562 this_len_byte = count_size_as_multibyte (SDATA (this),
563 SCHARS (this));
564 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
565 string_overflow ();
566 result_len_byte += this_len_byte;
570 result_len += len;
571 if (MOST_POSITIVE_FIXNUM < result_len)
572 memory_full (SIZE_MAX);
575 if (! some_multibyte)
576 result_len_byte = result_len;
578 /* Create the output object. */
579 if (target_type == Lisp_Cons)
580 val = Fmake_list (make_number (result_len), Qnil);
581 else if (target_type == Lisp_Vectorlike)
582 val = Fmake_vector (make_number (result_len), Qnil);
583 else if (some_multibyte)
584 val = make_uninit_multibyte_string (result_len, result_len_byte);
585 else
586 val = make_uninit_string (result_len);
588 /* In `append', if all but last arg are nil, return last arg. */
589 if (target_type == Lisp_Cons && EQ (val, Qnil))
590 return last_tail;
592 /* Copy the contents of the args into the result. */
593 if (CONSP (val))
594 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
595 else
596 toindex = 0, toindex_byte = 0;
598 prev = Qnil;
599 if (STRINGP (val))
600 SAFE_NALLOCA (textprops, 1, nargs);
602 for (argnum = 0; argnum < nargs; argnum++)
604 Lisp_Object thislen;
605 ptrdiff_t thisleni = 0;
606 register ptrdiff_t thisindex = 0;
607 register ptrdiff_t thisindex_byte = 0;
609 this = args[argnum];
610 if (!CONSP (this))
611 thislen = Flength (this), thisleni = XINT (thislen);
613 /* Between strings of the same kind, copy fast. */
614 if (STRINGP (this) && STRINGP (val)
615 && STRING_MULTIBYTE (this) == some_multibyte)
617 ptrdiff_t thislen_byte = SBYTES (this);
619 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
620 if (string_intervals (this))
622 textprops[num_textprops].argnum = argnum;
623 textprops[num_textprops].from = 0;
624 textprops[num_textprops++].to = toindex;
626 toindex_byte += thislen_byte;
627 toindex += thisleni;
629 /* Copy a single-byte string to a multibyte string. */
630 else if (STRINGP (this) && STRINGP (val))
632 if (string_intervals (this))
634 textprops[num_textprops].argnum = argnum;
635 textprops[num_textprops].from = 0;
636 textprops[num_textprops++].to = toindex;
638 toindex_byte += copy_text (SDATA (this),
639 SDATA (val) + toindex_byte,
640 SCHARS (this), 0, 1);
641 toindex += thisleni;
643 else
644 /* Copy element by element. */
645 while (1)
647 register Lisp_Object elt;
649 /* Fetch next element of `this' arg into `elt', or break if
650 `this' is exhausted. */
651 if (NILP (this)) break;
652 if (CONSP (this))
653 elt = XCAR (this), this = XCDR (this);
654 else if (thisindex >= thisleni)
655 break;
656 else if (STRINGP (this))
658 int c;
659 if (STRING_MULTIBYTE (this))
660 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
661 thisindex,
662 thisindex_byte);
663 else
665 c = SREF (this, thisindex); thisindex++;
666 if (some_multibyte && !ASCII_CHAR_P (c))
667 c = BYTE8_TO_CHAR (c);
669 XSETFASTINT (elt, c);
671 else if (BOOL_VECTOR_P (this))
673 int byte;
674 byte = XBOOL_VECTOR (this)->data[thisindex / BOOL_VECTOR_BITS_PER_CHAR];
675 if (byte & (1 << (thisindex % BOOL_VECTOR_BITS_PER_CHAR)))
676 elt = Qt;
677 else
678 elt = Qnil;
679 thisindex++;
681 else
683 elt = AREF (this, thisindex);
684 thisindex++;
687 /* Store this element into the result. */
688 if (toindex < 0)
690 XSETCAR (tail, elt);
691 prev = tail;
692 tail = XCDR (tail);
694 else if (VECTORP (val))
696 ASET (val, toindex, elt);
697 toindex++;
699 else
701 int c;
702 CHECK_CHARACTER (elt);
703 c = XFASTINT (elt);
704 if (some_multibyte)
705 toindex_byte += CHAR_STRING (c, SDATA (val) + toindex_byte);
706 else
707 SSET (val, toindex_byte++, c);
708 toindex++;
712 if (!NILP (prev))
713 XSETCDR (prev, last_tail);
715 if (num_textprops > 0)
717 Lisp_Object props;
718 ptrdiff_t last_to_end = -1;
720 for (argnum = 0; argnum < num_textprops; argnum++)
722 this = args[textprops[argnum].argnum];
723 props = text_property_list (this,
724 make_number (0),
725 make_number (SCHARS (this)),
726 Qnil);
727 /* If successive arguments have properties, be sure that the
728 value of `composition' property be the copy. */
729 if (last_to_end == textprops[argnum].to)
730 make_composition_value_copy (props);
731 add_text_properties_from_list (val, props,
732 make_number (textprops[argnum].to));
733 last_to_end = textprops[argnum].to + SCHARS (this);
737 SAFE_FREE ();
738 return val;
741 static Lisp_Object string_char_byte_cache_string;
742 static ptrdiff_t string_char_byte_cache_charpos;
743 static ptrdiff_t string_char_byte_cache_bytepos;
745 void
746 clear_string_char_byte_cache (void)
748 string_char_byte_cache_string = Qnil;
751 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
753 ptrdiff_t
754 string_char_to_byte (Lisp_Object string, ptrdiff_t char_index)
756 ptrdiff_t i_byte;
757 ptrdiff_t best_below, best_below_byte;
758 ptrdiff_t best_above, best_above_byte;
760 best_below = best_below_byte = 0;
761 best_above = SCHARS (string);
762 best_above_byte = SBYTES (string);
763 if (best_above == best_above_byte)
764 return char_index;
766 if (EQ (string, string_char_byte_cache_string))
768 if (string_char_byte_cache_charpos < char_index)
770 best_below = string_char_byte_cache_charpos;
771 best_below_byte = string_char_byte_cache_bytepos;
773 else
775 best_above = string_char_byte_cache_charpos;
776 best_above_byte = string_char_byte_cache_bytepos;
780 if (char_index - best_below < best_above - char_index)
782 unsigned char *p = SDATA (string) + best_below_byte;
784 while (best_below < char_index)
786 p += BYTES_BY_CHAR_HEAD (*p);
787 best_below++;
789 i_byte = p - SDATA (string);
791 else
793 unsigned char *p = SDATA (string) + best_above_byte;
795 while (best_above > char_index)
797 p--;
798 while (!CHAR_HEAD_P (*p)) p--;
799 best_above--;
801 i_byte = p - SDATA (string);
804 string_char_byte_cache_bytepos = i_byte;
805 string_char_byte_cache_charpos = char_index;
806 string_char_byte_cache_string = string;
808 return i_byte;
811 /* Return the character index corresponding to BYTE_INDEX in STRING. */
813 ptrdiff_t
814 string_byte_to_char (Lisp_Object string, ptrdiff_t byte_index)
816 ptrdiff_t i, i_byte;
817 ptrdiff_t best_below, best_below_byte;
818 ptrdiff_t best_above, best_above_byte;
820 best_below = best_below_byte = 0;
821 best_above = SCHARS (string);
822 best_above_byte = SBYTES (string);
823 if (best_above == best_above_byte)
824 return byte_index;
826 if (EQ (string, string_char_byte_cache_string))
828 if (string_char_byte_cache_bytepos < byte_index)
830 best_below = string_char_byte_cache_charpos;
831 best_below_byte = string_char_byte_cache_bytepos;
833 else
835 best_above = string_char_byte_cache_charpos;
836 best_above_byte = string_char_byte_cache_bytepos;
840 if (byte_index - best_below_byte < best_above_byte - byte_index)
842 unsigned char *p = SDATA (string) + best_below_byte;
843 unsigned char *pend = SDATA (string) + byte_index;
845 while (p < pend)
847 p += BYTES_BY_CHAR_HEAD (*p);
848 best_below++;
850 i = best_below;
851 i_byte = p - SDATA (string);
853 else
855 unsigned char *p = SDATA (string) + best_above_byte;
856 unsigned char *pbeg = SDATA (string) + byte_index;
858 while (p > pbeg)
860 p--;
861 while (!CHAR_HEAD_P (*p)) p--;
862 best_above--;
864 i = best_above;
865 i_byte = p - SDATA (string);
868 string_char_byte_cache_bytepos = i_byte;
869 string_char_byte_cache_charpos = i;
870 string_char_byte_cache_string = string;
872 return i;
875 /* Convert STRING to a multibyte string. */
877 static Lisp_Object
878 string_make_multibyte (Lisp_Object string)
880 unsigned char *buf;
881 ptrdiff_t nbytes;
882 Lisp_Object ret;
883 USE_SAFE_ALLOCA;
885 if (STRING_MULTIBYTE (string))
886 return string;
888 nbytes = count_size_as_multibyte (SDATA (string),
889 SCHARS (string));
890 /* If all the chars are ASCII, they won't need any more bytes
891 once converted. In that case, we can return STRING itself. */
892 if (nbytes == SBYTES (string))
893 return string;
895 buf = SAFE_ALLOCA (nbytes);
896 copy_text (SDATA (string), buf, SBYTES (string),
897 0, 1);
899 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
900 SAFE_FREE ();
902 return ret;
906 /* Convert STRING (if unibyte) to a multibyte string without changing
907 the number of characters. Characters 0200 trough 0237 are
908 converted to eight-bit characters. */
910 Lisp_Object
911 string_to_multibyte (Lisp_Object string)
913 unsigned char *buf;
914 ptrdiff_t nbytes;
915 Lisp_Object ret;
916 USE_SAFE_ALLOCA;
918 if (STRING_MULTIBYTE (string))
919 return string;
921 nbytes = count_size_as_multibyte (SDATA (string), SBYTES (string));
922 /* If all the chars are ASCII, they won't need any more bytes once
923 converted. */
924 if (nbytes == SBYTES (string))
925 return make_multibyte_string (SSDATA (string), nbytes, nbytes);
927 buf = SAFE_ALLOCA (nbytes);
928 memcpy (buf, SDATA (string), SBYTES (string));
929 str_to_multibyte (buf, nbytes, SBYTES (string));
931 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
932 SAFE_FREE ();
934 return ret;
938 /* Convert STRING to a single-byte string. */
940 Lisp_Object
941 string_make_unibyte (Lisp_Object string)
943 ptrdiff_t nchars;
944 unsigned char *buf;
945 Lisp_Object ret;
946 USE_SAFE_ALLOCA;
948 if (! STRING_MULTIBYTE (string))
949 return string;
951 nchars = SCHARS (string);
953 buf = SAFE_ALLOCA (nchars);
954 copy_text (SDATA (string), buf, SBYTES (string),
955 1, 0);
957 ret = make_unibyte_string ((char *) buf, nchars);
958 SAFE_FREE ();
960 return ret;
963 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
964 1, 1, 0,
965 doc: /* Return the multibyte equivalent of STRING.
966 If STRING is unibyte and contains non-ASCII characters, the function
967 `unibyte-char-to-multibyte' is used to convert each unibyte character
968 to a multibyte character. In this case, the returned string is a
969 newly created string with no text properties. If STRING is multibyte
970 or entirely ASCII, it is returned unchanged. In particular, when
971 STRING is unibyte and entirely ASCII, the returned string is unibyte.
972 \(When the characters are all ASCII, Emacs primitives will treat the
973 string the same way whether it is unibyte or multibyte.) */)
974 (Lisp_Object string)
976 CHECK_STRING (string);
978 return string_make_multibyte (string);
981 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
982 1, 1, 0,
983 doc: /* Return the unibyte equivalent of STRING.
984 Multibyte character codes are converted to unibyte according to
985 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
986 If the lookup in the translation table fails, this function takes just
987 the low 8 bits of each character. */)
988 (Lisp_Object string)
990 CHECK_STRING (string);
992 return string_make_unibyte (string);
995 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
996 1, 1, 0,
997 doc: /* Return a unibyte string with the same individual bytes as STRING.
998 If STRING is unibyte, the result is STRING itself.
999 Otherwise it is a newly created string, with no text properties.
1000 If STRING is multibyte and contains a character of charset
1001 `eight-bit', it is converted to the corresponding single byte. */)
1002 (Lisp_Object string)
1004 CHECK_STRING (string);
1006 if (STRING_MULTIBYTE (string))
1008 ptrdiff_t bytes = SBYTES (string);
1009 unsigned char *str = xmalloc (bytes);
1011 memcpy (str, SDATA (string), bytes);
1012 bytes = str_as_unibyte (str, bytes);
1013 string = make_unibyte_string ((char *) str, bytes);
1014 xfree (str);
1016 return string;
1019 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1020 1, 1, 0,
1021 doc: /* Return a multibyte string with the same individual bytes as STRING.
1022 If STRING is multibyte, the result is STRING itself.
1023 Otherwise it is a newly created string, with no text properties.
1025 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1026 part of a correct utf-8 sequence), it is converted to the corresponding
1027 multibyte character of charset `eight-bit'.
1028 See also `string-to-multibyte'.
1030 Beware, this often doesn't really do what you think it does.
1031 It is similar to (decode-coding-string STRING 'utf-8-emacs).
1032 If you're not sure, whether to use `string-as-multibyte' or
1033 `string-to-multibyte', use `string-to-multibyte'. */)
1034 (Lisp_Object string)
1036 CHECK_STRING (string);
1038 if (! STRING_MULTIBYTE (string))
1040 Lisp_Object new_string;
1041 ptrdiff_t nchars, nbytes;
1043 parse_str_as_multibyte (SDATA (string),
1044 SBYTES (string),
1045 &nchars, &nbytes);
1046 new_string = make_uninit_multibyte_string (nchars, nbytes);
1047 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1048 if (nbytes != SBYTES (string))
1049 str_as_multibyte (SDATA (new_string), nbytes,
1050 SBYTES (string), NULL);
1051 string = new_string;
1052 set_string_intervals (string, NULL);
1054 return string;
1057 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1058 1, 1, 0,
1059 doc: /* Return a multibyte string with the same individual chars as STRING.
1060 If STRING is multibyte, the result is STRING itself.
1061 Otherwise it is a newly created string, with no text properties.
1063 If STRING is unibyte and contains an 8-bit byte, it is converted to
1064 the corresponding multibyte character of charset `eight-bit'.
1066 This differs from `string-as-multibyte' by converting each byte of a correct
1067 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1068 correct sequence. */)
1069 (Lisp_Object string)
1071 CHECK_STRING (string);
1073 return string_to_multibyte (string);
1076 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1077 1, 1, 0,
1078 doc: /* Return a unibyte string with the same individual chars as STRING.
1079 If STRING is unibyte, the result is STRING itself.
1080 Otherwise it is a newly created string, with no text properties,
1081 where each `eight-bit' character is converted to the corresponding byte.
1082 If STRING contains a non-ASCII, non-`eight-bit' character,
1083 an error is signaled. */)
1084 (Lisp_Object string)
1086 CHECK_STRING (string);
1088 if (STRING_MULTIBYTE (string))
1090 ptrdiff_t chars = SCHARS (string);
1091 unsigned char *str = xmalloc (chars);
1092 ptrdiff_t converted = str_to_unibyte (SDATA (string), str, chars);
1094 if (converted < chars)
1095 error ("Can't convert the %"pD"dth character to unibyte", converted);
1096 string = make_unibyte_string ((char *) str, chars);
1097 xfree (str);
1099 return string;
1103 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1104 doc: /* Return a copy of ALIST.
1105 This is an alist which represents the same mapping from objects to objects,
1106 but does not share the alist structure with ALIST.
1107 The objects mapped (cars and cdrs of elements of the alist)
1108 are shared, however.
1109 Elements of ALIST that are not conses are also shared. */)
1110 (Lisp_Object alist)
1112 register Lisp_Object tem;
1114 CHECK_LIST (alist);
1115 if (NILP (alist))
1116 return alist;
1117 alist = concat (1, &alist, Lisp_Cons, 0);
1118 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1120 register Lisp_Object car;
1121 car = XCAR (tem);
1123 if (CONSP (car))
1124 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1126 return alist;
1129 DEFUN ("substring", Fsubstring, Ssubstring, 2, 3, 0,
1130 doc: /* Return a new string whose contents are a substring of STRING.
1131 The returned string consists of the characters between index FROM
1132 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1133 zero-indexed: 0 means the first character of STRING. Negative values
1134 are counted from the end of STRING. If TO is nil, the substring runs
1135 to the end of STRING.
1137 The STRING argument may also be a vector. In that case, the return
1138 value is a new vector that contains the elements between index FROM
1139 \(inclusive) and index TO (exclusive) of that vector argument. */)
1140 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1142 Lisp_Object res;
1143 ptrdiff_t size;
1144 EMACS_INT from_char, to_char;
1146 CHECK_VECTOR_OR_STRING (string);
1147 CHECK_NUMBER (from);
1149 if (STRINGP (string))
1150 size = SCHARS (string);
1151 else
1152 size = ASIZE (string);
1154 if (NILP (to))
1155 to_char = size;
1156 else
1158 CHECK_NUMBER (to);
1160 to_char = XINT (to);
1161 if (to_char < 0)
1162 to_char += size;
1165 from_char = XINT (from);
1166 if (from_char < 0)
1167 from_char += size;
1168 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1169 args_out_of_range_3 (string, make_number (from_char),
1170 make_number (to_char));
1172 if (STRINGP (string))
1174 ptrdiff_t to_byte =
1175 (NILP (to) ? SBYTES (string) : string_char_to_byte (string, to_char));
1176 ptrdiff_t from_byte = string_char_to_byte (string, from_char);
1177 res = make_specified_string (SSDATA (string) + from_byte,
1178 to_char - from_char, to_byte - from_byte,
1179 STRING_MULTIBYTE (string));
1180 copy_text_properties (make_number (from_char), make_number (to_char),
1181 string, make_number (0), res, Qnil);
1183 else
1184 res = Fvector (to_char - from_char, aref_addr (string, from_char));
1186 return res;
1190 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1191 doc: /* Return a substring of STRING, without text properties.
1192 It starts at index FROM and ends before TO.
1193 TO may be nil or omitted; then the substring runs to the end of STRING.
1194 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1195 If FROM or TO is negative, it counts from the end.
1197 With one argument, just copy STRING without its properties. */)
1198 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1200 ptrdiff_t size;
1201 EMACS_INT from_char, to_char;
1202 ptrdiff_t from_byte, to_byte;
1204 CHECK_STRING (string);
1206 size = SCHARS (string);
1208 if (NILP (from))
1209 from_char = 0;
1210 else
1212 CHECK_NUMBER (from);
1213 from_char = XINT (from);
1214 if (from_char < 0)
1215 from_char += size;
1218 if (NILP (to))
1219 to_char = size;
1220 else
1222 CHECK_NUMBER (to);
1223 to_char = XINT (to);
1224 if (to_char < 0)
1225 to_char += size;
1228 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1229 args_out_of_range_3 (string, make_number (from_char),
1230 make_number (to_char));
1232 from_byte = NILP (from) ? 0 : string_char_to_byte (string, from_char);
1233 to_byte =
1234 NILP (to) ? SBYTES (string) : string_char_to_byte (string, to_char);
1235 return make_specified_string (SSDATA (string) + from_byte,
1236 to_char - from_char, to_byte - from_byte,
1237 STRING_MULTIBYTE (string));
1240 /* Extract a substring of STRING, giving start and end positions
1241 both in characters and in bytes. */
1243 Lisp_Object
1244 substring_both (Lisp_Object string, ptrdiff_t from, ptrdiff_t from_byte,
1245 ptrdiff_t to, ptrdiff_t to_byte)
1247 Lisp_Object res;
1248 ptrdiff_t size;
1250 CHECK_VECTOR_OR_STRING (string);
1252 size = STRINGP (string) ? SCHARS (string) : ASIZE (string);
1254 if (!(0 <= from && from <= to && to <= size))
1255 args_out_of_range_3 (string, make_number (from), make_number (to));
1257 if (STRINGP (string))
1259 res = make_specified_string (SSDATA (string) + from_byte,
1260 to - from, to_byte - from_byte,
1261 STRING_MULTIBYTE (string));
1262 copy_text_properties (make_number (from), make_number (to),
1263 string, make_number (0), res, Qnil);
1265 else
1266 res = Fvector (to - from, aref_addr (string, from));
1268 return res;
1271 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1272 doc: /* Take cdr N times on LIST, return the result. */)
1273 (Lisp_Object n, Lisp_Object list)
1275 EMACS_INT i, num;
1276 CHECK_NUMBER (n);
1277 num = XINT (n);
1278 for (i = 0; i < num && !NILP (list); i++)
1280 QUIT;
1281 CHECK_LIST_CONS (list, list);
1282 list = XCDR (list);
1284 return list;
1287 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1288 doc: /* Return the Nth element of LIST.
1289 N counts from zero. If LIST is not that long, nil is returned. */)
1290 (Lisp_Object n, Lisp_Object list)
1292 return Fcar (Fnthcdr (n, list));
1295 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1296 doc: /* Return element of SEQUENCE at index N. */)
1297 (register Lisp_Object sequence, Lisp_Object n)
1299 CHECK_NUMBER (n);
1300 if (CONSP (sequence) || NILP (sequence))
1301 return Fcar (Fnthcdr (n, sequence));
1303 /* Faref signals a "not array" error, so check here. */
1304 CHECK_ARRAY (sequence, Qsequencep);
1305 return Faref (sequence, n);
1308 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1309 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1310 The value is actually the tail of LIST whose car is ELT. */)
1311 (register Lisp_Object elt, Lisp_Object list)
1313 register Lisp_Object tail;
1314 for (tail = list; CONSP (tail); tail = XCDR (tail))
1316 register Lisp_Object tem;
1317 CHECK_LIST_CONS (tail, list);
1318 tem = XCAR (tail);
1319 if (! NILP (Fequal (elt, tem)))
1320 return tail;
1321 QUIT;
1323 return Qnil;
1326 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1327 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1328 The value is actually the tail of LIST whose car is ELT. */)
1329 (register Lisp_Object elt, Lisp_Object list)
1331 while (1)
1333 if (!CONSP (list) || EQ (XCAR (list), elt))
1334 break;
1336 list = XCDR (list);
1337 if (!CONSP (list) || EQ (XCAR (list), elt))
1338 break;
1340 list = XCDR (list);
1341 if (!CONSP (list) || EQ (XCAR (list), elt))
1342 break;
1344 list = XCDR (list);
1345 QUIT;
1348 CHECK_LIST (list);
1349 return list;
1352 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1353 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1354 The value is actually the tail of LIST whose car is ELT. */)
1355 (register Lisp_Object elt, Lisp_Object list)
1357 register Lisp_Object tail;
1359 if (!FLOATP (elt))
1360 return Fmemq (elt, list);
1362 for (tail = list; CONSP (tail); tail = XCDR (tail))
1364 register Lisp_Object tem;
1365 CHECK_LIST_CONS (tail, list);
1366 tem = XCAR (tail);
1367 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0))
1368 return tail;
1369 QUIT;
1371 return Qnil;
1374 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1375 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1376 The value is actually the first element of LIST whose car is KEY.
1377 Elements of LIST that are not conses are ignored. */)
1378 (Lisp_Object key, Lisp_Object list)
1380 while (1)
1382 if (!CONSP (list)
1383 || (CONSP (XCAR (list))
1384 && EQ (XCAR (XCAR (list)), key)))
1385 break;
1387 list = XCDR (list);
1388 if (!CONSP (list)
1389 || (CONSP (XCAR (list))
1390 && EQ (XCAR (XCAR (list)), key)))
1391 break;
1393 list = XCDR (list);
1394 if (!CONSP (list)
1395 || (CONSP (XCAR (list))
1396 && EQ (XCAR (XCAR (list)), key)))
1397 break;
1399 list = XCDR (list);
1400 QUIT;
1403 return CAR (list);
1406 /* Like Fassq but never report an error and do not allow quits.
1407 Use only on lists known never to be circular. */
1409 Lisp_Object
1410 assq_no_quit (Lisp_Object key, Lisp_Object list)
1412 while (CONSP (list)
1413 && (!CONSP (XCAR (list))
1414 || !EQ (XCAR (XCAR (list)), key)))
1415 list = XCDR (list);
1417 return CAR_SAFE (list);
1420 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1421 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1422 The value is actually the first element of LIST whose car equals KEY. */)
1423 (Lisp_Object key, Lisp_Object list)
1425 Lisp_Object car;
1427 while (1)
1429 if (!CONSP (list)
1430 || (CONSP (XCAR (list))
1431 && (car = XCAR (XCAR (list)),
1432 EQ (car, key) || !NILP (Fequal (car, key)))))
1433 break;
1435 list = XCDR (list);
1436 if (!CONSP (list)
1437 || (CONSP (XCAR (list))
1438 && (car = XCAR (XCAR (list)),
1439 EQ (car, key) || !NILP (Fequal (car, key)))))
1440 break;
1442 list = XCDR (list);
1443 if (!CONSP (list)
1444 || (CONSP (XCAR (list))
1445 && (car = XCAR (XCAR (list)),
1446 EQ (car, key) || !NILP (Fequal (car, key)))))
1447 break;
1449 list = XCDR (list);
1450 QUIT;
1453 return CAR (list);
1456 /* Like Fassoc but never report an error and do not allow quits.
1457 Use only on lists known never to be circular. */
1459 Lisp_Object
1460 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1462 while (CONSP (list)
1463 && (!CONSP (XCAR (list))
1464 || (!EQ (XCAR (XCAR (list)), key)
1465 && NILP (Fequal (XCAR (XCAR (list)), key)))))
1466 list = XCDR (list);
1468 return CONSP (list) ? XCAR (list) : Qnil;
1471 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1472 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1473 The value is actually the first element of LIST whose cdr is KEY. */)
1474 (register Lisp_Object key, Lisp_Object list)
1476 while (1)
1478 if (!CONSP (list)
1479 || (CONSP (XCAR (list))
1480 && EQ (XCDR (XCAR (list)), key)))
1481 break;
1483 list = XCDR (list);
1484 if (!CONSP (list)
1485 || (CONSP (XCAR (list))
1486 && EQ (XCDR (XCAR (list)), key)))
1487 break;
1489 list = XCDR (list);
1490 if (!CONSP (list)
1491 || (CONSP (XCAR (list))
1492 && EQ (XCDR (XCAR (list)), key)))
1493 break;
1495 list = XCDR (list);
1496 QUIT;
1499 return CAR (list);
1502 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1503 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1504 The value is actually the first element of LIST whose cdr equals KEY. */)
1505 (Lisp_Object key, Lisp_Object list)
1507 Lisp_Object cdr;
1509 while (1)
1511 if (!CONSP (list)
1512 || (CONSP (XCAR (list))
1513 && (cdr = XCDR (XCAR (list)),
1514 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1515 break;
1517 list = XCDR (list);
1518 if (!CONSP (list)
1519 || (CONSP (XCAR (list))
1520 && (cdr = XCDR (XCAR (list)),
1521 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1522 break;
1524 list = XCDR (list);
1525 if (!CONSP (list)
1526 || (CONSP (XCAR (list))
1527 && (cdr = XCDR (XCAR (list)),
1528 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1529 break;
1531 list = XCDR (list);
1532 QUIT;
1535 return CAR (list);
1538 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1539 doc: /* Delete members of LIST which are `eq' to ELT, and return the result.
1540 More precisely, this function skips any members `eq' to ELT at the
1541 front of LIST, then removes members `eq' to ELT from the remaining
1542 sublist by modifying its list structure, then returns the resulting
1543 list.
1545 Write `(setq foo (delq element foo))' to be sure of correctly changing
1546 the value of a list `foo'. */)
1547 (register Lisp_Object elt, Lisp_Object list)
1549 register Lisp_Object tail, prev;
1550 register Lisp_Object tem;
1552 tail = list;
1553 prev = Qnil;
1554 while (!NILP (tail))
1556 CHECK_LIST_CONS (tail, list);
1557 tem = XCAR (tail);
1558 if (EQ (elt, tem))
1560 if (NILP (prev))
1561 list = XCDR (tail);
1562 else
1563 Fsetcdr (prev, XCDR (tail));
1565 else
1566 prev = tail;
1567 tail = XCDR (tail);
1568 QUIT;
1570 return list;
1573 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1574 doc: /* Delete members of SEQ which are `equal' to ELT, and return the result.
1575 SEQ must be a sequence (i.e. a list, a vector, or a string).
1576 The return value is a sequence of the same type.
1578 If SEQ is a list, this behaves like `delq', except that it compares
1579 with `equal' instead of `eq'. In particular, it may remove elements
1580 by altering the list structure.
1582 If SEQ is not a list, deletion is never performed destructively;
1583 instead this function creates and returns a new vector or string.
1585 Write `(setq foo (delete element foo))' to be sure of correctly
1586 changing the value of a sequence `foo'. */)
1587 (Lisp_Object elt, Lisp_Object seq)
1589 if (VECTORP (seq))
1591 ptrdiff_t i, n;
1593 for (i = n = 0; i < ASIZE (seq); ++i)
1594 if (NILP (Fequal (AREF (seq, i), elt)))
1595 ++n;
1597 if (n != ASIZE (seq))
1599 struct Lisp_Vector *p = allocate_vector (n);
1601 for (i = n = 0; i < ASIZE (seq); ++i)
1602 if (NILP (Fequal (AREF (seq, i), elt)))
1603 p->contents[n++] = AREF (seq, i);
1605 XSETVECTOR (seq, p);
1608 else if (STRINGP (seq))
1610 ptrdiff_t i, ibyte, nchars, nbytes, cbytes;
1611 int c;
1613 for (i = nchars = nbytes = ibyte = 0;
1614 i < SCHARS (seq);
1615 ++i, ibyte += cbytes)
1617 if (STRING_MULTIBYTE (seq))
1619 c = STRING_CHAR (SDATA (seq) + ibyte);
1620 cbytes = CHAR_BYTES (c);
1622 else
1624 c = SREF (seq, i);
1625 cbytes = 1;
1628 if (!INTEGERP (elt) || c != XINT (elt))
1630 ++nchars;
1631 nbytes += cbytes;
1635 if (nchars != SCHARS (seq))
1637 Lisp_Object tem;
1639 tem = make_uninit_multibyte_string (nchars, nbytes);
1640 if (!STRING_MULTIBYTE (seq))
1641 STRING_SET_UNIBYTE (tem);
1643 for (i = nchars = nbytes = ibyte = 0;
1644 i < SCHARS (seq);
1645 ++i, ibyte += cbytes)
1647 if (STRING_MULTIBYTE (seq))
1649 c = STRING_CHAR (SDATA (seq) + ibyte);
1650 cbytes = CHAR_BYTES (c);
1652 else
1654 c = SREF (seq, i);
1655 cbytes = 1;
1658 if (!INTEGERP (elt) || c != XINT (elt))
1660 unsigned char *from = SDATA (seq) + ibyte;
1661 unsigned char *to = SDATA (tem) + nbytes;
1662 ptrdiff_t n;
1664 ++nchars;
1665 nbytes += cbytes;
1667 for (n = cbytes; n--; )
1668 *to++ = *from++;
1672 seq = tem;
1675 else
1677 Lisp_Object tail, prev;
1679 for (tail = seq, prev = Qnil; CONSP (tail); tail = XCDR (tail))
1681 CHECK_LIST_CONS (tail, seq);
1683 if (!NILP (Fequal (elt, XCAR (tail))))
1685 if (NILP (prev))
1686 seq = XCDR (tail);
1687 else
1688 Fsetcdr (prev, XCDR (tail));
1690 else
1691 prev = tail;
1692 QUIT;
1696 return seq;
1699 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1700 doc: /* Reverse LIST by modifying cdr pointers.
1701 Return the reversed list. Expects a properly nil-terminated list. */)
1702 (Lisp_Object list)
1704 register Lisp_Object prev, tail, next;
1706 if (NILP (list)) return list;
1707 prev = Qnil;
1708 tail = list;
1709 while (!NILP (tail))
1711 QUIT;
1712 CHECK_LIST_CONS (tail, tail);
1713 next = XCDR (tail);
1714 Fsetcdr (tail, prev);
1715 prev = tail;
1716 tail = next;
1718 return prev;
1721 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1722 doc: /* Reverse LIST, copying. Return the reversed list.
1723 See also the function `nreverse', which is used more often. */)
1724 (Lisp_Object list)
1726 Lisp_Object new;
1728 for (new = Qnil; CONSP (list); list = XCDR (list))
1730 QUIT;
1731 new = Fcons (XCAR (list), new);
1733 CHECK_LIST_END (list, list);
1734 return new;
1737 Lisp_Object merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred);
1739 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
1740 doc: /* Sort LIST, stably, comparing elements using PREDICATE.
1741 Returns the sorted list. LIST is modified by side effects.
1742 PREDICATE is called with two elements of LIST, and should return non-nil
1743 if the first element should sort before the second. */)
1744 (Lisp_Object list, Lisp_Object predicate)
1746 Lisp_Object front, back;
1747 register Lisp_Object len, tem;
1748 struct gcpro gcpro1, gcpro2;
1749 EMACS_INT length;
1751 front = list;
1752 len = Flength (list);
1753 length = XINT (len);
1754 if (length < 2)
1755 return list;
1757 XSETINT (len, (length / 2) - 1);
1758 tem = Fnthcdr (len, list);
1759 back = Fcdr (tem);
1760 Fsetcdr (tem, Qnil);
1762 GCPRO2 (front, back);
1763 front = Fsort (front, predicate);
1764 back = Fsort (back, predicate);
1765 UNGCPRO;
1766 return merge (front, back, predicate);
1769 Lisp_Object
1770 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
1772 Lisp_Object value;
1773 register Lisp_Object tail;
1774 Lisp_Object tem;
1775 register Lisp_Object l1, l2;
1776 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1778 l1 = org_l1;
1779 l2 = org_l2;
1780 tail = Qnil;
1781 value = Qnil;
1783 /* It is sufficient to protect org_l1 and org_l2.
1784 When l1 and l2 are updated, we copy the new values
1785 back into the org_ vars. */
1786 GCPRO4 (org_l1, org_l2, pred, value);
1788 while (1)
1790 if (NILP (l1))
1792 UNGCPRO;
1793 if (NILP (tail))
1794 return l2;
1795 Fsetcdr (tail, l2);
1796 return value;
1798 if (NILP (l2))
1800 UNGCPRO;
1801 if (NILP (tail))
1802 return l1;
1803 Fsetcdr (tail, l1);
1804 return value;
1806 tem = call2 (pred, Fcar (l2), Fcar (l1));
1807 if (NILP (tem))
1809 tem = l1;
1810 l1 = Fcdr (l1);
1811 org_l1 = l1;
1813 else
1815 tem = l2;
1816 l2 = Fcdr (l2);
1817 org_l2 = l2;
1819 if (NILP (tail))
1820 value = tem;
1821 else
1822 Fsetcdr (tail, tem);
1823 tail = tem;
1828 /* This does not check for quits. That is safe since it must terminate. */
1830 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
1831 doc: /* Extract a value from a property list.
1832 PLIST is a property list, which is a list of the form
1833 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1834 corresponding to the given PROP, or nil if PROP is not one of the
1835 properties on the list. This function never signals an error. */)
1836 (Lisp_Object plist, Lisp_Object prop)
1838 Lisp_Object tail, halftail;
1840 /* halftail is used to detect circular lists. */
1841 tail = halftail = plist;
1842 while (CONSP (tail) && CONSP (XCDR (tail)))
1844 if (EQ (prop, XCAR (tail)))
1845 return XCAR (XCDR (tail));
1847 tail = XCDR (XCDR (tail));
1848 halftail = XCDR (halftail);
1849 if (EQ (tail, halftail))
1850 break;
1853 return Qnil;
1856 DEFUN ("get", Fget, Sget, 2, 2, 0,
1857 doc: /* Return the value of SYMBOL's PROPNAME property.
1858 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
1859 (Lisp_Object symbol, Lisp_Object propname)
1861 CHECK_SYMBOL (symbol);
1862 return Fplist_get (XSYMBOL (symbol)->plist, propname);
1865 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
1866 doc: /* Change value in PLIST of PROP to VAL.
1867 PLIST is a property list, which is a list of the form
1868 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
1869 If PROP is already a property on the list, its value is set to VAL,
1870 otherwise the new PROP VAL pair is added. The new plist is returned;
1871 use `(setq x (plist-put x prop val))' to be sure to use the new value.
1872 The PLIST is modified by side effects. */)
1873 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1875 register Lisp_Object tail, prev;
1876 Lisp_Object newcell;
1877 prev = Qnil;
1878 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1879 tail = XCDR (XCDR (tail)))
1881 if (EQ (prop, XCAR (tail)))
1883 Fsetcar (XCDR (tail), val);
1884 return plist;
1887 prev = tail;
1888 QUIT;
1890 newcell = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
1891 if (NILP (prev))
1892 return newcell;
1893 else
1894 Fsetcdr (XCDR (prev), newcell);
1895 return plist;
1898 DEFUN ("put", Fput, Sput, 3, 3, 0,
1899 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
1900 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
1901 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
1903 CHECK_SYMBOL (symbol);
1904 set_symbol_plist
1905 (symbol, Fplist_put (XSYMBOL (symbol)->plist, propname, value));
1906 return value;
1909 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
1910 doc: /* Extract a value from a property list, comparing with `equal'.
1911 PLIST is a property list, which is a list of the form
1912 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1913 corresponding to the given PROP, or nil if PROP is not
1914 one of the properties on the list. */)
1915 (Lisp_Object plist, Lisp_Object prop)
1917 Lisp_Object tail;
1919 for (tail = plist;
1920 CONSP (tail) && CONSP (XCDR (tail));
1921 tail = XCDR (XCDR (tail)))
1923 if (! NILP (Fequal (prop, XCAR (tail))))
1924 return XCAR (XCDR (tail));
1926 QUIT;
1929 CHECK_LIST_END (tail, prop);
1931 return Qnil;
1934 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
1935 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
1936 PLIST is a property list, which is a list of the form
1937 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
1938 If PROP is already a property on the list, its value is set to VAL,
1939 otherwise the new PROP VAL pair is added. The new plist is returned;
1940 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
1941 The PLIST is modified by side effects. */)
1942 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1944 register Lisp_Object tail, prev;
1945 Lisp_Object newcell;
1946 prev = Qnil;
1947 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1948 tail = XCDR (XCDR (tail)))
1950 if (! NILP (Fequal (prop, XCAR (tail))))
1952 Fsetcar (XCDR (tail), val);
1953 return plist;
1956 prev = tail;
1957 QUIT;
1959 newcell = Fcons (prop, Fcons (val, Qnil));
1960 if (NILP (prev))
1961 return newcell;
1962 else
1963 Fsetcdr (XCDR (prev), newcell);
1964 return plist;
1967 DEFUN ("eql", Feql, Seql, 2, 2, 0,
1968 doc: /* Return t if the two args are the same Lisp object.
1969 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
1970 (Lisp_Object obj1, Lisp_Object obj2)
1972 if (FLOATP (obj1))
1973 return internal_equal (obj1, obj2, 0, 0) ? Qt : Qnil;
1974 else
1975 return EQ (obj1, obj2) ? Qt : Qnil;
1978 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
1979 doc: /* Return t if two Lisp objects have similar structure and contents.
1980 They must have the same data type.
1981 Conses are compared by comparing the cars and the cdrs.
1982 Vectors and strings are compared element by element.
1983 Numbers are compared by value, but integers cannot equal floats.
1984 (Use `=' if you want integers and floats to be able to be equal.)
1985 Symbols must match exactly. */)
1986 (register Lisp_Object o1, Lisp_Object o2)
1988 return internal_equal (o1, o2, 0, 0) ? Qt : Qnil;
1991 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
1992 doc: /* Return t if two Lisp objects have similar structure and contents.
1993 This is like `equal' except that it compares the text properties
1994 of strings. (`equal' ignores text properties.) */)
1995 (register Lisp_Object o1, Lisp_Object o2)
1997 return internal_equal (o1, o2, 0, 1) ? Qt : Qnil;
2000 /* DEPTH is current depth of recursion. Signal an error if it
2001 gets too deep.
2002 PROPS means compare string text properties too. */
2004 static bool
2005 internal_equal (Lisp_Object o1, Lisp_Object o2, int depth, bool props)
2007 if (depth > 200)
2008 error ("Stack overflow in equal");
2010 tail_recurse:
2011 QUIT;
2012 if (EQ (o1, o2))
2013 return 1;
2014 if (XTYPE (o1) != XTYPE (o2))
2015 return 0;
2017 switch (XTYPE (o1))
2019 case Lisp_Float:
2021 double d1, d2;
2023 d1 = extract_float (o1);
2024 d2 = extract_float (o2);
2025 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2026 though they are not =. */
2027 return d1 == d2 || (d1 != d1 && d2 != d2);
2030 case Lisp_Cons:
2031 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1, props))
2032 return 0;
2033 o1 = XCDR (o1);
2034 o2 = XCDR (o2);
2035 goto tail_recurse;
2037 case Lisp_Misc:
2038 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2039 return 0;
2040 if (OVERLAYP (o1))
2042 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2043 depth + 1, props)
2044 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2045 depth + 1, props))
2046 return 0;
2047 o1 = XOVERLAY (o1)->plist;
2048 o2 = XOVERLAY (o2)->plist;
2049 goto tail_recurse;
2051 if (MARKERP (o1))
2053 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2054 && (XMARKER (o1)->buffer == 0
2055 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2057 break;
2059 case Lisp_Vectorlike:
2061 register int i;
2062 ptrdiff_t size = ASIZE (o1);
2063 /* Pseudovectors have the type encoded in the size field, so this test
2064 actually checks that the objects have the same type as well as the
2065 same size. */
2066 if (ASIZE (o2) != size)
2067 return 0;
2068 /* Boolvectors are compared much like strings. */
2069 if (BOOL_VECTOR_P (o1))
2071 if (XBOOL_VECTOR (o1)->size != XBOOL_VECTOR (o2)->size)
2072 return 0;
2073 if (memcmp (XBOOL_VECTOR (o1)->data, XBOOL_VECTOR (o2)->data,
2074 ((XBOOL_VECTOR (o1)->size
2075 + BOOL_VECTOR_BITS_PER_CHAR - 1)
2076 / BOOL_VECTOR_BITS_PER_CHAR)))
2077 return 0;
2078 return 1;
2080 if (WINDOW_CONFIGURATIONP (o1))
2081 return compare_window_configurations (o1, o2, 0);
2083 /* Aside from them, only true vectors, char-tables, compiled
2084 functions, and fonts (font-spec, font-entity, font-object)
2085 are sensible to compare, so eliminate the others now. */
2086 if (size & PSEUDOVECTOR_FLAG)
2088 if (!(size & ((PVEC_COMPILED | PVEC_CHAR_TABLE
2089 | PVEC_SUB_CHAR_TABLE | PVEC_FONT)
2090 << PSEUDOVECTOR_SIZE_BITS)))
2091 return 0;
2092 size &= PSEUDOVECTOR_SIZE_MASK;
2094 for (i = 0; i < size; i++)
2096 Lisp_Object v1, v2;
2097 v1 = AREF (o1, i);
2098 v2 = AREF (o2, i);
2099 if (!internal_equal (v1, v2, depth + 1, props))
2100 return 0;
2102 return 1;
2104 break;
2106 case Lisp_String:
2107 if (SCHARS (o1) != SCHARS (o2))
2108 return 0;
2109 if (SBYTES (o1) != SBYTES (o2))
2110 return 0;
2111 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2112 return 0;
2113 if (props && !compare_string_intervals (o1, o2))
2114 return 0;
2115 return 1;
2117 default:
2118 break;
2121 return 0;
2125 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2126 doc: /* Store each element of ARRAY with ITEM.
2127 ARRAY is a vector, string, char-table, or bool-vector. */)
2128 (Lisp_Object array, Lisp_Object item)
2130 register ptrdiff_t size, idx;
2132 if (VECTORP (array))
2133 for (idx = 0, size = ASIZE (array); idx < size; idx++)
2134 ASET (array, idx, item);
2135 else if (CHAR_TABLE_P (array))
2137 int i;
2139 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2140 set_char_table_contents (array, i, item);
2141 set_char_table_defalt (array, item);
2143 else if (STRINGP (array))
2145 register unsigned char *p = SDATA (array);
2146 int charval;
2147 CHECK_CHARACTER (item);
2148 charval = XFASTINT (item);
2149 size = SCHARS (array);
2150 if (STRING_MULTIBYTE (array))
2152 unsigned char str[MAX_MULTIBYTE_LENGTH];
2153 int len = CHAR_STRING (charval, str);
2154 ptrdiff_t size_byte = SBYTES (array);
2156 if (INT_MULTIPLY_OVERFLOW (SCHARS (array), len)
2157 || SCHARS (array) * len != size_byte)
2158 error ("Attempt to change byte length of a string");
2159 for (idx = 0; idx < size_byte; idx++)
2160 *p++ = str[idx % len];
2162 else
2163 for (idx = 0; idx < size; idx++)
2164 p[idx] = charval;
2166 else if (BOOL_VECTOR_P (array))
2168 register unsigned char *p = XBOOL_VECTOR (array)->data;
2169 size =
2170 ((XBOOL_VECTOR (array)->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
2171 / BOOL_VECTOR_BITS_PER_CHAR);
2173 if (size)
2175 memset (p, ! NILP (item) ? -1 : 0, size);
2177 /* Clear any extraneous bits in the last byte. */
2178 p[size - 1] &= (1 << (size % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2181 else
2182 wrong_type_argument (Qarrayp, array);
2183 return array;
2186 DEFUN ("clear-string", Fclear_string, Sclear_string,
2187 1, 1, 0,
2188 doc: /* Clear the contents of STRING.
2189 This makes STRING unibyte and may change its length. */)
2190 (Lisp_Object string)
2192 ptrdiff_t len;
2193 CHECK_STRING (string);
2194 len = SBYTES (string);
2195 memset (SDATA (string), 0, len);
2196 STRING_SET_CHARS (string, len);
2197 STRING_SET_UNIBYTE (string);
2198 return Qnil;
2201 /* ARGSUSED */
2202 Lisp_Object
2203 nconc2 (Lisp_Object s1, Lisp_Object s2)
2205 Lisp_Object args[2];
2206 args[0] = s1;
2207 args[1] = s2;
2208 return Fnconc (2, args);
2211 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2212 doc: /* Concatenate any number of lists by altering them.
2213 Only the last argument is not altered, and need not be a list.
2214 usage: (nconc &rest LISTS) */)
2215 (ptrdiff_t nargs, Lisp_Object *args)
2217 ptrdiff_t argnum;
2218 register Lisp_Object tail, tem, val;
2220 val = tail = Qnil;
2222 for (argnum = 0; argnum < nargs; argnum++)
2224 tem = args[argnum];
2225 if (NILP (tem)) continue;
2227 if (NILP (val))
2228 val = tem;
2230 if (argnum + 1 == nargs) break;
2232 CHECK_LIST_CONS (tem, tem);
2234 while (CONSP (tem))
2236 tail = tem;
2237 tem = XCDR (tail);
2238 QUIT;
2241 tem = args[argnum + 1];
2242 Fsetcdr (tail, tem);
2243 if (NILP (tem))
2244 args[argnum + 1] = tail;
2247 return val;
2250 /* This is the guts of all mapping functions.
2251 Apply FN to each element of SEQ, one by one,
2252 storing the results into elements of VALS, a C vector of Lisp_Objects.
2253 LENI is the length of VALS, which should also be the length of SEQ. */
2255 static void
2256 mapcar1 (EMACS_INT leni, Lisp_Object *vals, Lisp_Object fn, Lisp_Object seq)
2258 register Lisp_Object tail;
2259 Lisp_Object dummy;
2260 register EMACS_INT i;
2261 struct gcpro gcpro1, gcpro2, gcpro3;
2263 if (vals)
2265 /* Don't let vals contain any garbage when GC happens. */
2266 for (i = 0; i < leni; i++)
2267 vals[i] = Qnil;
2269 GCPRO3 (dummy, fn, seq);
2270 gcpro1.var = vals;
2271 gcpro1.nvars = leni;
2273 else
2274 GCPRO2 (fn, seq);
2275 /* We need not explicitly protect `tail' because it is used only on lists, and
2276 1) lists are not relocated and 2) the list is marked via `seq' so will not
2277 be freed */
2279 if (VECTORP (seq) || COMPILEDP (seq))
2281 for (i = 0; i < leni; i++)
2283 dummy = call1 (fn, AREF (seq, i));
2284 if (vals)
2285 vals[i] = dummy;
2288 else if (BOOL_VECTOR_P (seq))
2290 for (i = 0; i < leni; i++)
2292 unsigned char byte;
2293 byte = XBOOL_VECTOR (seq)->data[i / BOOL_VECTOR_BITS_PER_CHAR];
2294 dummy = (byte & (1 << (i % BOOL_VECTOR_BITS_PER_CHAR))) ? Qt : Qnil;
2295 dummy = call1 (fn, dummy);
2296 if (vals)
2297 vals[i] = dummy;
2300 else if (STRINGP (seq))
2302 ptrdiff_t i_byte;
2304 for (i = 0, i_byte = 0; i < leni;)
2306 int c;
2307 ptrdiff_t i_before = i;
2309 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2310 XSETFASTINT (dummy, c);
2311 dummy = call1 (fn, dummy);
2312 if (vals)
2313 vals[i_before] = dummy;
2316 else /* Must be a list, since Flength did not get an error */
2318 tail = seq;
2319 for (i = 0; i < leni && CONSP (tail); i++)
2321 dummy = call1 (fn, XCAR (tail));
2322 if (vals)
2323 vals[i] = dummy;
2324 tail = XCDR (tail);
2328 UNGCPRO;
2331 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2332 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2333 In between each pair of results, stick in SEPARATOR. Thus, " " as
2334 SEPARATOR results in spaces between the values returned by FUNCTION.
2335 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2336 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2338 Lisp_Object len;
2339 register EMACS_INT leni;
2340 EMACS_INT nargs;
2341 ptrdiff_t i;
2342 register Lisp_Object *args;
2343 struct gcpro gcpro1;
2344 Lisp_Object ret;
2345 USE_SAFE_ALLOCA;
2347 len = Flength (sequence);
2348 if (CHAR_TABLE_P (sequence))
2349 wrong_type_argument (Qlistp, sequence);
2350 leni = XINT (len);
2351 nargs = leni + leni - 1;
2352 if (nargs < 0) return empty_unibyte_string;
2354 SAFE_ALLOCA_LISP (args, nargs);
2356 GCPRO1 (separator);
2357 mapcar1 (leni, args, function, sequence);
2358 UNGCPRO;
2360 for (i = leni - 1; i > 0; i--)
2361 args[i + i] = args[i];
2363 for (i = 1; i < nargs; i += 2)
2364 args[i] = separator;
2366 ret = Fconcat (nargs, args);
2367 SAFE_FREE ();
2369 return ret;
2372 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2373 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2374 The result is a list just as long as SEQUENCE.
2375 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2376 (Lisp_Object function, Lisp_Object sequence)
2378 register Lisp_Object len;
2379 register EMACS_INT leni;
2380 register Lisp_Object *args;
2381 Lisp_Object ret;
2382 USE_SAFE_ALLOCA;
2384 len = Flength (sequence);
2385 if (CHAR_TABLE_P (sequence))
2386 wrong_type_argument (Qlistp, sequence);
2387 leni = XFASTINT (len);
2389 SAFE_ALLOCA_LISP (args, leni);
2391 mapcar1 (leni, args, function, sequence);
2393 ret = Flist (leni, args);
2394 SAFE_FREE ();
2396 return ret;
2399 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2400 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2401 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2402 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2403 (Lisp_Object function, Lisp_Object sequence)
2405 register EMACS_INT leni;
2407 leni = XFASTINT (Flength (sequence));
2408 if (CHAR_TABLE_P (sequence))
2409 wrong_type_argument (Qlistp, sequence);
2410 mapcar1 (leni, 0, function, sequence);
2412 return sequence;
2415 /* This is how C code calls `yes-or-no-p' and allows the user
2416 to redefined it.
2418 Anything that calls this function must protect from GC! */
2420 Lisp_Object
2421 do_yes_or_no_p (Lisp_Object prompt)
2423 return call1 (intern ("yes-or-no-p"), prompt);
2426 /* Anything that calls this function must protect from GC! */
2428 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2429 doc: /* Ask user a yes-or-no question. Return t if answer is yes.
2430 PROMPT is the string to display to ask the question. It should end in
2431 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2433 The user must confirm the answer with RET, and can edit it until it
2434 has been confirmed.
2436 Under a windowing system a dialog box will be used if `last-nonmenu-event'
2437 is nil, and `use-dialog-box' is non-nil. */)
2438 (Lisp_Object prompt)
2440 register Lisp_Object ans;
2441 Lisp_Object args[2];
2442 struct gcpro gcpro1;
2444 CHECK_STRING (prompt);
2446 #ifdef HAVE_MENUS
2447 if (FRAME_WINDOW_P (SELECTED_FRAME ())
2448 && (NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2449 && use_dialog_box
2450 && have_menus_p ())
2452 Lisp_Object pane, menu, obj;
2453 redisplay_preserve_echo_area (4);
2454 pane = Fcons (Fcons (build_string ("Yes"), Qt),
2455 Fcons (Fcons (build_string ("No"), Qnil),
2456 Qnil));
2457 GCPRO1 (pane);
2458 menu = Fcons (prompt, pane);
2459 obj = Fx_popup_dialog (Qt, menu, Qnil);
2460 UNGCPRO;
2461 return obj;
2463 #endif /* HAVE_MENUS */
2465 args[0] = prompt;
2466 args[1] = build_string ("(yes or no) ");
2467 prompt = Fconcat (2, args);
2469 GCPRO1 (prompt);
2471 while (1)
2473 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2474 Qyes_or_no_p_history, Qnil,
2475 Qnil));
2476 if (SCHARS (ans) == 3 && !strcmp (SSDATA (ans), "yes"))
2478 UNGCPRO;
2479 return Qt;
2481 if (SCHARS (ans) == 2 && !strcmp (SSDATA (ans), "no"))
2483 UNGCPRO;
2484 return Qnil;
2487 Fding (Qnil);
2488 Fdiscard_input ();
2489 message ("Please answer yes or no.");
2490 Fsleep_for (make_number (2), Qnil);
2494 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2495 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2497 Each of the three load averages is multiplied by 100, then converted
2498 to integer.
2500 When USE-FLOATS is non-nil, floats will be used instead of integers.
2501 These floats are not multiplied by 100.
2503 If the 5-minute or 15-minute load averages are not available, return a
2504 shortened list, containing only those averages which are available.
2506 An error is thrown if the load average can't be obtained. In some
2507 cases making it work would require Emacs being installed setuid or
2508 setgid so that it can read kernel information, and that usually isn't
2509 advisable. */)
2510 (Lisp_Object use_floats)
2512 double load_ave[3];
2513 int loads = getloadavg (load_ave, 3);
2514 Lisp_Object ret = Qnil;
2516 if (loads < 0)
2517 error ("load-average not implemented for this operating system");
2519 while (loads-- > 0)
2521 Lisp_Object load = (NILP (use_floats)
2522 ? make_number (100.0 * load_ave[loads])
2523 : make_float (load_ave[loads]));
2524 ret = Fcons (load, ret);
2527 return ret;
2530 static Lisp_Object Qsubfeatures;
2532 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2533 doc: /* Return t if FEATURE is present in this Emacs.
2535 Use this to conditionalize execution of lisp code based on the
2536 presence or absence of Emacs or environment extensions.
2537 Use `provide' to declare that a feature is available. This function
2538 looks at the value of the variable `features'. The optional argument
2539 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2540 (Lisp_Object feature, Lisp_Object subfeature)
2542 register Lisp_Object tem;
2543 CHECK_SYMBOL (feature);
2544 tem = Fmemq (feature, Vfeatures);
2545 if (!NILP (tem) && !NILP (subfeature))
2546 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2547 return (NILP (tem)) ? Qnil : Qt;
2550 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2551 doc: /* Announce that FEATURE is a feature of the current Emacs.
2552 The optional argument SUBFEATURES should be a list of symbols listing
2553 particular subfeatures supported in this version of FEATURE. */)
2554 (Lisp_Object feature, Lisp_Object subfeatures)
2556 register Lisp_Object tem;
2557 CHECK_SYMBOL (feature);
2558 CHECK_LIST (subfeatures);
2559 if (!NILP (Vautoload_queue))
2560 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2561 Vautoload_queue);
2562 tem = Fmemq (feature, Vfeatures);
2563 if (NILP (tem))
2564 Vfeatures = Fcons (feature, Vfeatures);
2565 if (!NILP (subfeatures))
2566 Fput (feature, Qsubfeatures, subfeatures);
2567 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2569 /* Run any load-hooks for this file. */
2570 tem = Fassq (feature, Vafter_load_alist);
2571 if (CONSP (tem))
2572 Fprogn (XCDR (tem));
2574 return feature;
2577 /* `require' and its subroutines. */
2579 /* List of features currently being require'd, innermost first. */
2581 static Lisp_Object require_nesting_list;
2583 static Lisp_Object
2584 require_unwind (Lisp_Object old_value)
2586 return require_nesting_list = old_value;
2589 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2590 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2591 If FEATURE is not a member of the list `features', then the feature
2592 is not loaded; so load the file FILENAME.
2593 If FILENAME is omitted, the printname of FEATURE is used as the file name,
2594 and `load' will try to load this name appended with the suffix `.elc' or
2595 `.el', in that order. The name without appended suffix will not be used.
2596 See `get-load-suffixes' for the complete list of suffixes.
2597 If the optional third argument NOERROR is non-nil,
2598 then return nil if the file is not found instead of signaling an error.
2599 Normally the return value is FEATURE.
2600 The normal messages at start and end of loading FILENAME are suppressed. */)
2601 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2603 Lisp_Object tem;
2604 struct gcpro gcpro1, gcpro2;
2605 bool from_file = load_in_progress;
2607 CHECK_SYMBOL (feature);
2609 /* Record the presence of `require' in this file
2610 even if the feature specified is already loaded.
2611 But not more than once in any file,
2612 and not when we aren't loading or reading from a file. */
2613 if (!from_file)
2614 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2615 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2616 from_file = 1;
2618 if (from_file)
2620 tem = Fcons (Qrequire, feature);
2621 if (NILP (Fmember (tem, Vcurrent_load_list)))
2622 LOADHIST_ATTACH (tem);
2624 tem = Fmemq (feature, Vfeatures);
2626 if (NILP (tem))
2628 ptrdiff_t count = SPECPDL_INDEX ();
2629 int nesting = 0;
2631 /* This is to make sure that loadup.el gives a clear picture
2632 of what files are preloaded and when. */
2633 if (! NILP (Vpurify_flag))
2634 error ("(require %s) while preparing to dump",
2635 SDATA (SYMBOL_NAME (feature)));
2637 /* A certain amount of recursive `require' is legitimate,
2638 but if we require the same feature recursively 3 times,
2639 signal an error. */
2640 tem = require_nesting_list;
2641 while (! NILP (tem))
2643 if (! NILP (Fequal (feature, XCAR (tem))))
2644 nesting++;
2645 tem = XCDR (tem);
2647 if (nesting > 3)
2648 error ("Recursive `require' for feature `%s'",
2649 SDATA (SYMBOL_NAME (feature)));
2651 /* Update the list for any nested `require's that occur. */
2652 record_unwind_protect (require_unwind, require_nesting_list);
2653 require_nesting_list = Fcons (feature, require_nesting_list);
2655 /* Value saved here is to be restored into Vautoload_queue */
2656 record_unwind_protect (un_autoload, Vautoload_queue);
2657 Vautoload_queue = Qt;
2659 /* Load the file. */
2660 GCPRO2 (feature, filename);
2661 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2662 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2663 UNGCPRO;
2665 /* If load failed entirely, return nil. */
2666 if (NILP (tem))
2667 return unbind_to (count, Qnil);
2669 tem = Fmemq (feature, Vfeatures);
2670 if (NILP (tem))
2671 error ("Required feature `%s' was not provided",
2672 SDATA (SYMBOL_NAME (feature)));
2674 /* Once loading finishes, don't undo it. */
2675 Vautoload_queue = Qt;
2676 feature = unbind_to (count, feature);
2679 return feature;
2682 /* Primitives for work of the "widget" library.
2683 In an ideal world, this section would not have been necessary.
2684 However, lisp function calls being as slow as they are, it turns
2685 out that some functions in the widget library (wid-edit.el) are the
2686 bottleneck of Widget operation. Here is their translation to C,
2687 for the sole reason of efficiency. */
2689 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2690 doc: /* Return non-nil if PLIST has the property PROP.
2691 PLIST is a property list, which is a list of the form
2692 \(PROP1 VALUE1 PROP2 VALUE2 ...\). PROP is a symbol.
2693 Unlike `plist-get', this allows you to distinguish between a missing
2694 property and a property with the value nil.
2695 The value is actually the tail of PLIST whose car is PROP. */)
2696 (Lisp_Object plist, Lisp_Object prop)
2698 while (CONSP (plist) && !EQ (XCAR (plist), prop))
2700 QUIT;
2701 plist = XCDR (plist);
2702 plist = CDR (plist);
2704 return plist;
2707 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2708 doc: /* In WIDGET, set PROPERTY to VALUE.
2709 The value can later be retrieved with `widget-get'. */)
2710 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2712 CHECK_CONS (widget);
2713 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
2714 return value;
2717 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
2718 doc: /* In WIDGET, get the value of PROPERTY.
2719 The value could either be specified when the widget was created, or
2720 later with `widget-put'. */)
2721 (Lisp_Object widget, Lisp_Object property)
2723 Lisp_Object tmp;
2725 while (1)
2727 if (NILP (widget))
2728 return Qnil;
2729 CHECK_CONS (widget);
2730 tmp = Fplist_member (XCDR (widget), property);
2731 if (CONSP (tmp))
2733 tmp = XCDR (tmp);
2734 return CAR (tmp);
2736 tmp = XCAR (widget);
2737 if (NILP (tmp))
2738 return Qnil;
2739 widget = Fget (tmp, Qwidget_type);
2743 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
2744 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2745 ARGS are passed as extra arguments to the function.
2746 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2747 (ptrdiff_t nargs, Lisp_Object *args)
2749 /* This function can GC. */
2750 Lisp_Object newargs[3];
2751 struct gcpro gcpro1, gcpro2;
2752 Lisp_Object result;
2754 newargs[0] = Fwidget_get (args[0], args[1]);
2755 newargs[1] = args[0];
2756 newargs[2] = Flist (nargs - 2, args + 2);
2757 GCPRO2 (newargs[0], newargs[2]);
2758 result = Fapply (3, newargs);
2759 UNGCPRO;
2760 return result;
2763 #ifdef HAVE_LANGINFO_CODESET
2764 #include <langinfo.h>
2765 #endif
2767 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
2768 doc: /* Access locale data ITEM for the current C locale, if available.
2769 ITEM should be one of the following:
2771 `codeset', returning the character set as a string (locale item CODESET);
2773 `days', returning a 7-element vector of day names (locale items DAY_n);
2775 `months', returning a 12-element vector of month names (locale items MON_n);
2777 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
2778 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
2780 If the system can't provide such information through a call to
2781 `nl_langinfo', or if ITEM isn't from the list above, return nil.
2783 See also Info node `(libc)Locales'.
2785 The data read from the system are decoded using `locale-coding-system'. */)
2786 (Lisp_Object item)
2788 char *str = NULL;
2789 #ifdef HAVE_LANGINFO_CODESET
2790 Lisp_Object val;
2791 if (EQ (item, Qcodeset))
2793 str = nl_langinfo (CODESET);
2794 return build_string (str);
2796 #ifdef DAY_1
2797 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
2799 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
2800 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
2801 int i;
2802 struct gcpro gcpro1;
2803 GCPRO1 (v);
2804 synchronize_system_time_locale ();
2805 for (i = 0; i < 7; i++)
2807 str = nl_langinfo (days[i]);
2808 val = build_unibyte_string (str);
2809 /* Fixme: Is this coding system necessarily right, even if
2810 it is consistent with CODESET? If not, what to do? */
2811 Faset (v, make_number (i),
2812 code_convert_string_norecord (val, Vlocale_coding_system,
2813 0));
2815 UNGCPRO;
2816 return v;
2818 #endif /* DAY_1 */
2819 #ifdef MON_1
2820 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
2822 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
2823 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
2824 MON_8, MON_9, MON_10, MON_11, MON_12};
2825 int i;
2826 struct gcpro gcpro1;
2827 GCPRO1 (v);
2828 synchronize_system_time_locale ();
2829 for (i = 0; i < 12; i++)
2831 str = nl_langinfo (months[i]);
2832 val = build_unibyte_string (str);
2833 Faset (v, make_number (i),
2834 code_convert_string_norecord (val, Vlocale_coding_system, 0));
2836 UNGCPRO;
2837 return v;
2839 #endif /* MON_1 */
2840 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
2841 but is in the locale files. This could be used by ps-print. */
2842 #ifdef PAPER_WIDTH
2843 else if (EQ (item, Qpaper))
2845 return list2 (make_number (nl_langinfo (PAPER_WIDTH)),
2846 make_number (nl_langinfo (PAPER_HEIGHT)));
2848 #endif /* PAPER_WIDTH */
2849 #endif /* HAVE_LANGINFO_CODESET*/
2850 return Qnil;
2853 /* base64 encode/decode functions (RFC 2045).
2854 Based on code from GNU recode. */
2856 #define MIME_LINE_LENGTH 76
2858 #define IS_ASCII(Character) \
2859 ((Character) < 128)
2860 #define IS_BASE64(Character) \
2861 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
2862 #define IS_BASE64_IGNORABLE(Character) \
2863 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
2864 || (Character) == '\f' || (Character) == '\r')
2866 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
2867 character or return retval if there are no characters left to
2868 process. */
2869 #define READ_QUADRUPLET_BYTE(retval) \
2870 do \
2872 if (i == length) \
2874 if (nchars_return) \
2875 *nchars_return = nchars; \
2876 return (retval); \
2878 c = from[i++]; \
2880 while (IS_BASE64_IGNORABLE (c))
2882 /* Table of characters coding the 64 values. */
2883 static const char base64_value_to_char[64] =
2885 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
2886 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
2887 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
2888 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
2889 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
2890 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
2891 '8', '9', '+', '/' /* 60-63 */
2894 /* Table of base64 values for first 128 characters. */
2895 static const short base64_char_to_value[128] =
2897 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
2898 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
2899 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
2900 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
2901 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
2902 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
2903 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
2904 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
2905 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
2906 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
2907 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
2908 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
2909 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
2912 /* The following diagram shows the logical steps by which three octets
2913 get transformed into four base64 characters.
2915 .--------. .--------. .--------.
2916 |aaaaaabb| |bbbbcccc| |ccdddddd|
2917 `--------' `--------' `--------'
2918 6 2 4 4 2 6
2919 .--------+--------+--------+--------.
2920 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
2921 `--------+--------+--------+--------'
2923 .--------+--------+--------+--------.
2924 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
2925 `--------+--------+--------+--------'
2927 The octets are divided into 6 bit chunks, which are then encoded into
2928 base64 characters. */
2931 static ptrdiff_t base64_encode_1 (const char *, char *, ptrdiff_t, bool, bool);
2932 static ptrdiff_t base64_decode_1 (const char *, char *, ptrdiff_t, bool,
2933 ptrdiff_t *);
2935 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
2936 2, 3, "r",
2937 doc: /* Base64-encode the region between BEG and END.
2938 Return the length of the encoded text.
2939 Optional third argument NO-LINE-BREAK means do not break long lines
2940 into shorter lines. */)
2941 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
2943 char *encoded;
2944 ptrdiff_t allength, length;
2945 ptrdiff_t ibeg, iend, encoded_length;
2946 ptrdiff_t old_pos = PT;
2947 USE_SAFE_ALLOCA;
2949 validate_region (&beg, &end);
2951 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
2952 iend = CHAR_TO_BYTE (XFASTINT (end));
2953 move_gap_both (XFASTINT (beg), ibeg);
2955 /* We need to allocate enough room for encoding the text.
2956 We need 33 1/3% more space, plus a newline every 76
2957 characters, and then we round up. */
2958 length = iend - ibeg;
2959 allength = length + length/3 + 1;
2960 allength += allength / MIME_LINE_LENGTH + 1 + 6;
2962 encoded = SAFE_ALLOCA (allength);
2963 encoded_length = base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg),
2964 encoded, length, NILP (no_line_break),
2965 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
2966 if (encoded_length > allength)
2967 emacs_abort ();
2969 if (encoded_length < 0)
2971 /* The encoding wasn't possible. */
2972 SAFE_FREE ();
2973 error ("Multibyte character in data for base64 encoding");
2976 /* Now we have encoded the region, so we insert the new contents
2977 and delete the old. (Insert first in order to preserve markers.) */
2978 SET_PT_BOTH (XFASTINT (beg), ibeg);
2979 insert (encoded, encoded_length);
2980 SAFE_FREE ();
2981 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
2983 /* If point was outside of the region, restore it exactly; else just
2984 move to the beginning of the region. */
2985 if (old_pos >= XFASTINT (end))
2986 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
2987 else if (old_pos > XFASTINT (beg))
2988 old_pos = XFASTINT (beg);
2989 SET_PT (old_pos);
2991 /* We return the length of the encoded text. */
2992 return make_number (encoded_length);
2995 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
2996 1, 2, 0,
2997 doc: /* Base64-encode STRING and return the result.
2998 Optional second argument NO-LINE-BREAK means do not break long lines
2999 into shorter lines. */)
3000 (Lisp_Object string, Lisp_Object no_line_break)
3002 ptrdiff_t allength, length, encoded_length;
3003 char *encoded;
3004 Lisp_Object encoded_string;
3005 USE_SAFE_ALLOCA;
3007 CHECK_STRING (string);
3009 /* We need to allocate enough room for encoding the text.
3010 We need 33 1/3% more space, plus a newline every 76
3011 characters, and then we round up. */
3012 length = SBYTES (string);
3013 allength = length + length/3 + 1;
3014 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3016 /* We need to allocate enough room for decoding the text. */
3017 encoded = SAFE_ALLOCA (allength);
3019 encoded_length = base64_encode_1 (SSDATA (string),
3020 encoded, length, NILP (no_line_break),
3021 STRING_MULTIBYTE (string));
3022 if (encoded_length > allength)
3023 emacs_abort ();
3025 if (encoded_length < 0)
3027 /* The encoding wasn't possible. */
3028 SAFE_FREE ();
3029 error ("Multibyte character in data for base64 encoding");
3032 encoded_string = make_unibyte_string (encoded, encoded_length);
3033 SAFE_FREE ();
3035 return encoded_string;
3038 static ptrdiff_t
3039 base64_encode_1 (const char *from, char *to, ptrdiff_t length,
3040 bool line_break, bool multibyte)
3042 int counter = 0;
3043 ptrdiff_t i = 0;
3044 char *e = to;
3045 int c;
3046 unsigned int value;
3047 int bytes;
3049 while (i < length)
3051 if (multibyte)
3053 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3054 if (CHAR_BYTE8_P (c))
3055 c = CHAR_TO_BYTE8 (c);
3056 else if (c >= 256)
3057 return -1;
3058 i += bytes;
3060 else
3061 c = from[i++];
3063 /* Wrap line every 76 characters. */
3065 if (line_break)
3067 if (counter < MIME_LINE_LENGTH / 4)
3068 counter++;
3069 else
3071 *e++ = '\n';
3072 counter = 1;
3076 /* Process first byte of a triplet. */
3078 *e++ = base64_value_to_char[0x3f & c >> 2];
3079 value = (0x03 & c) << 4;
3081 /* Process second byte of a triplet. */
3083 if (i == length)
3085 *e++ = base64_value_to_char[value];
3086 *e++ = '=';
3087 *e++ = '=';
3088 break;
3091 if (multibyte)
3093 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3094 if (CHAR_BYTE8_P (c))
3095 c = CHAR_TO_BYTE8 (c);
3096 else if (c >= 256)
3097 return -1;
3098 i += bytes;
3100 else
3101 c = from[i++];
3103 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3104 value = (0x0f & c) << 2;
3106 /* Process third byte of a triplet. */
3108 if (i == length)
3110 *e++ = base64_value_to_char[value];
3111 *e++ = '=';
3112 break;
3115 if (multibyte)
3117 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3118 if (CHAR_BYTE8_P (c))
3119 c = CHAR_TO_BYTE8 (c);
3120 else if (c >= 256)
3121 return -1;
3122 i += bytes;
3124 else
3125 c = from[i++];
3127 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3128 *e++ = base64_value_to_char[0x3f & c];
3131 return e - to;
3135 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3136 2, 2, "r",
3137 doc: /* Base64-decode the region between BEG and END.
3138 Return the length of the decoded text.
3139 If the region can't be decoded, signal an error and don't modify the buffer. */)
3140 (Lisp_Object beg, Lisp_Object end)
3142 ptrdiff_t ibeg, iend, length, allength;
3143 char *decoded;
3144 ptrdiff_t old_pos = PT;
3145 ptrdiff_t decoded_length;
3146 ptrdiff_t inserted_chars;
3147 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3148 USE_SAFE_ALLOCA;
3150 validate_region (&beg, &end);
3152 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3153 iend = CHAR_TO_BYTE (XFASTINT (end));
3155 length = iend - ibeg;
3157 /* We need to allocate enough room for decoding the text. If we are
3158 working on a multibyte buffer, each decoded code may occupy at
3159 most two bytes. */
3160 allength = multibyte ? length * 2 : length;
3161 decoded = SAFE_ALLOCA (allength);
3163 move_gap_both (XFASTINT (beg), ibeg);
3164 decoded_length = base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg),
3165 decoded, length,
3166 multibyte, &inserted_chars);
3167 if (decoded_length > allength)
3168 emacs_abort ();
3170 if (decoded_length < 0)
3172 /* The decoding wasn't possible. */
3173 SAFE_FREE ();
3174 error ("Invalid base64 data");
3177 /* Now we have decoded the region, so we insert the new contents
3178 and delete the old. (Insert first in order to preserve markers.) */
3179 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3180 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3181 SAFE_FREE ();
3183 /* Delete the original text. */
3184 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3185 iend + decoded_length, 1);
3187 /* If point was outside of the region, restore it exactly; else just
3188 move to the beginning of the region. */
3189 if (old_pos >= XFASTINT (end))
3190 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3191 else if (old_pos > XFASTINT (beg))
3192 old_pos = XFASTINT (beg);
3193 SET_PT (old_pos > ZV ? ZV : old_pos);
3195 return make_number (inserted_chars);
3198 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3199 1, 1, 0,
3200 doc: /* Base64-decode STRING and return the result. */)
3201 (Lisp_Object string)
3203 char *decoded;
3204 ptrdiff_t length, decoded_length;
3205 Lisp_Object decoded_string;
3206 USE_SAFE_ALLOCA;
3208 CHECK_STRING (string);
3210 length = SBYTES (string);
3211 /* We need to allocate enough room for decoding the text. */
3212 decoded = SAFE_ALLOCA (length);
3214 /* The decoded result should be unibyte. */
3215 decoded_length = base64_decode_1 (SSDATA (string), decoded, length,
3216 0, NULL);
3217 if (decoded_length > length)
3218 emacs_abort ();
3219 else if (decoded_length >= 0)
3220 decoded_string = make_unibyte_string (decoded, decoded_length);
3221 else
3222 decoded_string = Qnil;
3224 SAFE_FREE ();
3225 if (!STRINGP (decoded_string))
3226 error ("Invalid base64 data");
3228 return decoded_string;
3231 /* Base64-decode the data at FROM of LENGTH bytes into TO. If
3232 MULTIBYTE, the decoded result should be in multibyte
3233 form. If NCHARS_RETURN is not NULL, store the number of produced
3234 characters in *NCHARS_RETURN. */
3236 static ptrdiff_t
3237 base64_decode_1 (const char *from, char *to, ptrdiff_t length,
3238 bool multibyte, ptrdiff_t *nchars_return)
3240 ptrdiff_t i = 0; /* Used inside READ_QUADRUPLET_BYTE */
3241 char *e = to;
3242 unsigned char c;
3243 unsigned long value;
3244 ptrdiff_t nchars = 0;
3246 while (1)
3248 /* Process first byte of a quadruplet. */
3250 READ_QUADRUPLET_BYTE (e-to);
3252 if (!IS_BASE64 (c))
3253 return -1;
3254 value = base64_char_to_value[c] << 18;
3256 /* Process second byte of a quadruplet. */
3258 READ_QUADRUPLET_BYTE (-1);
3260 if (!IS_BASE64 (c))
3261 return -1;
3262 value |= base64_char_to_value[c] << 12;
3264 c = (unsigned char) (value >> 16);
3265 if (multibyte && c >= 128)
3266 e += BYTE8_STRING (c, e);
3267 else
3268 *e++ = c;
3269 nchars++;
3271 /* Process third byte of a quadruplet. */
3273 READ_QUADRUPLET_BYTE (-1);
3275 if (c == '=')
3277 READ_QUADRUPLET_BYTE (-1);
3279 if (c != '=')
3280 return -1;
3281 continue;
3284 if (!IS_BASE64 (c))
3285 return -1;
3286 value |= base64_char_to_value[c] << 6;
3288 c = (unsigned char) (0xff & value >> 8);
3289 if (multibyte && c >= 128)
3290 e += BYTE8_STRING (c, e);
3291 else
3292 *e++ = c;
3293 nchars++;
3295 /* Process fourth byte of a quadruplet. */
3297 READ_QUADRUPLET_BYTE (-1);
3299 if (c == '=')
3300 continue;
3302 if (!IS_BASE64 (c))
3303 return -1;
3304 value |= base64_char_to_value[c];
3306 c = (unsigned char) (0xff & value);
3307 if (multibyte && c >= 128)
3308 e += BYTE8_STRING (c, e);
3309 else
3310 *e++ = c;
3311 nchars++;
3317 /***********************************************************************
3318 ***** *****
3319 ***** Hash Tables *****
3320 ***** *****
3321 ***********************************************************************/
3323 /* Implemented by gerd@gnu.org. This hash table implementation was
3324 inspired by CMUCL hash tables. */
3326 /* Ideas:
3328 1. For small tables, association lists are probably faster than
3329 hash tables because they have lower overhead.
3331 For uses of hash tables where the O(1) behavior of table
3332 operations is not a requirement, it might therefore be a good idea
3333 not to hash. Instead, we could just do a linear search in the
3334 key_and_value vector of the hash table. This could be done
3335 if a `:linear-search t' argument is given to make-hash-table. */
3338 /* The list of all weak hash tables. Don't staticpro this one. */
3340 static struct Lisp_Hash_Table *weak_hash_tables;
3342 /* Various symbols. */
3344 static Lisp_Object Qhash_table_p, Qkey, Qvalue;
3345 Lisp_Object Qeq, Qeql, Qequal;
3346 Lisp_Object QCtest, QCsize, QCrehash_size, QCrehash_threshold, QCweakness;
3347 static Lisp_Object Qhash_table_test, Qkey_or_value, Qkey_and_value;
3350 /***********************************************************************
3351 Utilities
3352 ***********************************************************************/
3354 /* If OBJ is a Lisp hash table, return a pointer to its struct
3355 Lisp_Hash_Table. Otherwise, signal an error. */
3357 static struct Lisp_Hash_Table *
3358 check_hash_table (Lisp_Object obj)
3360 CHECK_HASH_TABLE (obj);
3361 return XHASH_TABLE (obj);
3365 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3366 number. A number is "almost" a prime number if it is not divisible
3367 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3369 EMACS_INT
3370 next_almost_prime (EMACS_INT n)
3372 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
3373 for (n |= 1; ; n += 2)
3374 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0)
3375 return n;
3379 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3380 which USED[I] is non-zero. If found at index I in ARGS, set
3381 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3382 0. This function is used to extract a keyword/argument pair from
3383 a DEFUN parameter list. */
3385 static ptrdiff_t
3386 get_key_arg (Lisp_Object key, ptrdiff_t nargs, Lisp_Object *args, char *used)
3388 ptrdiff_t i;
3390 for (i = 1; i < nargs; i++)
3391 if (!used[i - 1] && EQ (args[i - 1], key))
3393 used[i - 1] = 1;
3394 used[i] = 1;
3395 return i;
3398 return 0;
3402 /* Return a Lisp vector which has the same contents as VEC but has
3403 at least INCR_MIN more entries, where INCR_MIN is positive.
3404 If NITEMS_MAX is not -1, do not grow the vector to be any larger
3405 than NITEMS_MAX. Entries in the resulting
3406 vector that are not copied from VEC are set to nil. */
3408 Lisp_Object
3409 larger_vector (Lisp_Object vec, ptrdiff_t incr_min, ptrdiff_t nitems_max)
3411 struct Lisp_Vector *v;
3412 ptrdiff_t i, incr, incr_max, old_size, new_size;
3413 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / sizeof *v->contents;
3414 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
3415 ? nitems_max : C_language_max);
3416 eassert (VECTORP (vec));
3417 eassert (0 < incr_min && -1 <= nitems_max);
3418 old_size = ASIZE (vec);
3419 incr_max = n_max - old_size;
3420 incr = max (incr_min, min (old_size >> 1, incr_max));
3421 if (incr_max < incr)
3422 memory_full (SIZE_MAX);
3423 new_size = old_size + incr;
3424 v = allocate_vector (new_size);
3425 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3426 for (i = old_size; i < new_size; ++i)
3427 v->contents[i] = Qnil;
3428 XSETVECTOR (vec, v);
3429 return vec;
3433 /***********************************************************************
3434 Low-level Functions
3435 ***********************************************************************/
3437 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3438 HASH2 in hash table H using `eql'. Value is true if KEY1 and
3439 KEY2 are the same. */
3441 static bool
3442 cmpfn_eql (struct Lisp_Hash_Table *h,
3443 Lisp_Object key1, EMACS_UINT hash1,
3444 Lisp_Object key2, EMACS_UINT hash2)
3446 return (FLOATP (key1)
3447 && FLOATP (key2)
3448 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3452 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3453 HASH2 in hash table H using `equal'. Value is true if KEY1 and
3454 KEY2 are the same. */
3456 static bool
3457 cmpfn_equal (struct Lisp_Hash_Table *h,
3458 Lisp_Object key1, EMACS_UINT hash1,
3459 Lisp_Object key2, EMACS_UINT hash2)
3461 return hash1 == hash2 && !NILP (Fequal (key1, key2));
3465 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3466 HASH2 in hash table H using H->user_cmp_function. Value is true
3467 if KEY1 and KEY2 are the same. */
3469 static bool
3470 cmpfn_user_defined (struct Lisp_Hash_Table *h,
3471 Lisp_Object key1, EMACS_UINT hash1,
3472 Lisp_Object key2, EMACS_UINT hash2)
3474 if (hash1 == hash2)
3476 Lisp_Object args[3];
3478 args[0] = h->user_cmp_function;
3479 args[1] = key1;
3480 args[2] = key2;
3481 return !NILP (Ffuncall (3, args));
3483 else
3484 return 0;
3488 /* Value is a hash code for KEY for use in hash table H which uses
3489 `eq' to compare keys. The hash code returned is guaranteed to fit
3490 in a Lisp integer. */
3492 static EMACS_UINT
3493 hashfn_eq (struct Lisp_Hash_Table *h, Lisp_Object key)
3495 EMACS_UINT hash = XUINT (key) ^ XTYPE (key);
3496 eassert ((hash & ~INTMASK) == 0);
3497 return hash;
3501 /* Value is a hash code for KEY for use in hash table H which uses
3502 `eql' to compare keys. The hash code returned is guaranteed to fit
3503 in a Lisp integer. */
3505 static EMACS_UINT
3506 hashfn_eql (struct Lisp_Hash_Table *h, Lisp_Object key)
3508 EMACS_UINT hash;
3509 if (FLOATP (key))
3510 hash = sxhash (key, 0);
3511 else
3512 hash = XUINT (key) ^ XTYPE (key);
3513 eassert ((hash & ~INTMASK) == 0);
3514 return hash;
3518 /* Value is a hash code for KEY for use in hash table H which uses
3519 `equal' to compare keys. The hash code returned is guaranteed to fit
3520 in a Lisp integer. */
3522 static EMACS_UINT
3523 hashfn_equal (struct Lisp_Hash_Table *h, Lisp_Object key)
3525 EMACS_UINT hash = sxhash (key, 0);
3526 eassert ((hash & ~INTMASK) == 0);
3527 return hash;
3531 /* Value is a hash code for KEY for use in hash table H which uses as
3532 user-defined function to compare keys. The hash code returned is
3533 guaranteed to fit in a Lisp integer. */
3535 static EMACS_UINT
3536 hashfn_user_defined (struct Lisp_Hash_Table *h, Lisp_Object key)
3538 Lisp_Object args[2], hash;
3540 args[0] = h->user_hash_function;
3541 args[1] = key;
3542 hash = Ffuncall (2, args);
3543 if (!INTEGERP (hash))
3544 signal_error ("Invalid hash code returned from user-supplied hash function", hash);
3545 return XUINT (hash);
3548 /* An upper bound on the size of a hash table index. It must fit in
3549 ptrdiff_t and be a valid Emacs fixnum. */
3550 #define INDEX_SIZE_BOUND \
3551 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, PTRDIFF_MAX / word_size))
3553 /* Create and initialize a new hash table.
3555 TEST specifies the test the hash table will use to compare keys.
3556 It must be either one of the predefined tests `eq', `eql' or
3557 `equal' or a symbol denoting a user-defined test named TEST with
3558 test and hash functions USER_TEST and USER_HASH.
3560 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3562 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3563 new size when it becomes full is computed by adding REHASH_SIZE to
3564 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3565 table's new size is computed by multiplying its old size with
3566 REHASH_SIZE.
3568 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3569 be resized when the ratio of (number of entries in the table) /
3570 (table size) is >= REHASH_THRESHOLD.
3572 WEAK specifies the weakness of the table. If non-nil, it must be
3573 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
3575 Lisp_Object
3576 make_hash_table (Lisp_Object test, Lisp_Object size, Lisp_Object rehash_size,
3577 Lisp_Object rehash_threshold, Lisp_Object weak,
3578 Lisp_Object user_test, Lisp_Object user_hash)
3580 struct Lisp_Hash_Table *h;
3581 Lisp_Object table;
3582 EMACS_INT index_size, sz;
3583 ptrdiff_t i;
3584 double index_float;
3586 /* Preconditions. */
3587 eassert (SYMBOLP (test));
3588 eassert (INTEGERP (size) && XINT (size) >= 0);
3589 eassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3590 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size)));
3591 eassert (FLOATP (rehash_threshold)
3592 && 0 < XFLOAT_DATA (rehash_threshold)
3593 && XFLOAT_DATA (rehash_threshold) <= 1.0);
3595 if (XFASTINT (size) == 0)
3596 size = make_number (1);
3598 sz = XFASTINT (size);
3599 index_float = sz / XFLOAT_DATA (rehash_threshold);
3600 index_size = (index_float < INDEX_SIZE_BOUND + 1
3601 ? next_almost_prime (index_float)
3602 : INDEX_SIZE_BOUND + 1);
3603 if (INDEX_SIZE_BOUND < max (index_size, 2 * sz))
3604 error ("Hash table too large");
3606 /* Allocate a table and initialize it. */
3607 h = allocate_hash_table ();
3609 /* Initialize hash table slots. */
3610 h->test = test;
3611 if (EQ (test, Qeql))
3613 h->cmpfn = cmpfn_eql;
3614 h->hashfn = hashfn_eql;
3616 else if (EQ (test, Qeq))
3618 h->cmpfn = NULL;
3619 h->hashfn = hashfn_eq;
3621 else if (EQ (test, Qequal))
3623 h->cmpfn = cmpfn_equal;
3624 h->hashfn = hashfn_equal;
3626 else
3628 h->user_cmp_function = user_test;
3629 h->user_hash_function = user_hash;
3630 h->cmpfn = cmpfn_user_defined;
3631 h->hashfn = hashfn_user_defined;
3634 h->weak = weak;
3635 h->rehash_threshold = rehash_threshold;
3636 h->rehash_size = rehash_size;
3637 h->count = 0;
3638 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
3639 h->hash = Fmake_vector (size, Qnil);
3640 h->next = Fmake_vector (size, Qnil);
3641 h->index = Fmake_vector (make_number (index_size), Qnil);
3643 /* Set up the free list. */
3644 for (i = 0; i < sz - 1; ++i)
3645 set_hash_next_slot (h, i, make_number (i + 1));
3646 h->next_free = make_number (0);
3648 XSET_HASH_TABLE (table, h);
3649 eassert (HASH_TABLE_P (table));
3650 eassert (XHASH_TABLE (table) == h);
3652 /* Maybe add this hash table to the list of all weak hash tables. */
3653 if (NILP (h->weak))
3654 h->next_weak = NULL;
3655 else
3657 h->next_weak = weak_hash_tables;
3658 weak_hash_tables = h;
3661 return table;
3665 /* Return a copy of hash table H1. Keys and values are not copied,
3666 only the table itself is. */
3668 static Lisp_Object
3669 copy_hash_table (struct Lisp_Hash_Table *h1)
3671 Lisp_Object table;
3672 struct Lisp_Hash_Table *h2;
3673 struct Lisp_Vector *next;
3675 h2 = allocate_hash_table ();
3676 next = h2->header.next.vector;
3677 *h2 = *h1;
3678 h2->header.next.vector = next;
3679 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3680 h2->hash = Fcopy_sequence (h1->hash);
3681 h2->next = Fcopy_sequence (h1->next);
3682 h2->index = Fcopy_sequence (h1->index);
3683 XSET_HASH_TABLE (table, h2);
3685 /* Maybe add this hash table to the list of all weak hash tables. */
3686 if (!NILP (h2->weak))
3688 h2->next_weak = weak_hash_tables;
3689 weak_hash_tables = h2;
3692 return table;
3696 /* Resize hash table H if it's too full. If H cannot be resized
3697 because it's already too large, throw an error. */
3699 static void
3700 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3702 if (NILP (h->next_free))
3704 ptrdiff_t old_size = HASH_TABLE_SIZE (h);
3705 EMACS_INT new_size, index_size, nsize;
3706 ptrdiff_t i;
3707 double index_float;
3709 if (INTEGERP (h->rehash_size))
3710 new_size = old_size + XFASTINT (h->rehash_size);
3711 else
3713 double float_new_size = old_size * XFLOAT_DATA (h->rehash_size);
3714 if (float_new_size < INDEX_SIZE_BOUND + 1)
3716 new_size = float_new_size;
3717 if (new_size <= old_size)
3718 new_size = old_size + 1;
3720 else
3721 new_size = INDEX_SIZE_BOUND + 1;
3723 index_float = new_size / XFLOAT_DATA (h->rehash_threshold);
3724 index_size = (index_float < INDEX_SIZE_BOUND + 1
3725 ? next_almost_prime (index_float)
3726 : INDEX_SIZE_BOUND + 1);
3727 nsize = max (index_size, 2 * new_size);
3728 if (INDEX_SIZE_BOUND < nsize)
3729 error ("Hash table too large to resize");
3731 #ifdef ENABLE_CHECKING
3732 if (HASH_TABLE_P (Vpurify_flag)
3733 && XHASH_TABLE (Vpurify_flag) == h)
3735 Lisp_Object args[2];
3736 args[0] = build_string ("Growing hash table to: %d");
3737 args[1] = make_number (new_size);
3738 Fmessage (2, args);
3740 #endif
3742 set_hash_key_and_value (h, larger_vector (h->key_and_value,
3743 2 * (new_size - old_size), -1));
3744 set_hash_next (h, larger_vector (h->next, new_size - old_size, -1));
3745 set_hash_hash (h, larger_vector (h->hash, new_size - old_size, -1));
3746 set_hash_index (h, Fmake_vector (make_number (index_size), Qnil));
3748 /* Update the free list. Do it so that new entries are added at
3749 the end of the free list. This makes some operations like
3750 maphash faster. */
3751 for (i = old_size; i < new_size - 1; ++i)
3752 set_hash_next_slot (h, i, make_number (i + 1));
3754 if (!NILP (h->next_free))
3756 Lisp_Object last, next;
3758 last = h->next_free;
3759 while (next = HASH_NEXT (h, XFASTINT (last)),
3760 !NILP (next))
3761 last = next;
3763 set_hash_next_slot (h, XFASTINT (last), make_number (old_size));
3765 else
3766 XSETFASTINT (h->next_free, old_size);
3768 /* Rehash. */
3769 for (i = 0; i < old_size; ++i)
3770 if (!NILP (HASH_HASH (h, i)))
3772 EMACS_UINT hash_code = XUINT (HASH_HASH (h, i));
3773 ptrdiff_t start_of_bucket = hash_code % ASIZE (h->index);
3774 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3775 set_hash_index_slot (h, start_of_bucket, make_number (i));
3781 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
3782 the hash code of KEY. Value is the index of the entry in H
3783 matching KEY, or -1 if not found. */
3785 ptrdiff_t
3786 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
3788 EMACS_UINT hash_code;
3789 ptrdiff_t start_of_bucket;
3790 Lisp_Object idx;
3792 hash_code = h->hashfn (h, key);
3793 if (hash)
3794 *hash = hash_code;
3796 start_of_bucket = hash_code % ASIZE (h->index);
3797 idx = HASH_INDEX (h, start_of_bucket);
3799 /* We need not gcpro idx since it's either an integer or nil. */
3800 while (!NILP (idx))
3802 ptrdiff_t i = XFASTINT (idx);
3803 if (EQ (key, HASH_KEY (h, i))
3804 || (h->cmpfn
3805 && h->cmpfn (h, key, hash_code,
3806 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
3807 break;
3808 idx = HASH_NEXT (h, i);
3811 return NILP (idx) ? -1 : XFASTINT (idx);
3815 /* Put an entry into hash table H that associates KEY with VALUE.
3816 HASH is a previously computed hash code of KEY.
3817 Value is the index of the entry in H matching KEY. */
3819 ptrdiff_t
3820 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value,
3821 EMACS_UINT hash)
3823 ptrdiff_t start_of_bucket, i;
3825 eassert ((hash & ~INTMASK) == 0);
3827 /* Increment count after resizing because resizing may fail. */
3828 maybe_resize_hash_table (h);
3829 h->count++;
3831 /* Store key/value in the key_and_value vector. */
3832 i = XFASTINT (h->next_free);
3833 h->next_free = HASH_NEXT (h, i);
3834 set_hash_key_slot (h, i, key);
3835 set_hash_value_slot (h, i, value);
3837 /* Remember its hash code. */
3838 set_hash_hash_slot (h, i, make_number (hash));
3840 /* Add new entry to its collision chain. */
3841 start_of_bucket = hash % ASIZE (h->index);
3842 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3843 set_hash_index_slot (h, start_of_bucket, make_number (i));
3844 return i;
3848 /* Remove the entry matching KEY from hash table H, if there is one. */
3850 static void
3851 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
3853 EMACS_UINT hash_code;
3854 ptrdiff_t start_of_bucket;
3855 Lisp_Object idx, prev;
3857 hash_code = h->hashfn (h, key);
3858 start_of_bucket = hash_code % ASIZE (h->index);
3859 idx = HASH_INDEX (h, start_of_bucket);
3860 prev = Qnil;
3862 /* We need not gcpro idx, prev since they're either integers or nil. */
3863 while (!NILP (idx))
3865 ptrdiff_t i = XFASTINT (idx);
3867 if (EQ (key, HASH_KEY (h, i))
3868 || (h->cmpfn
3869 && h->cmpfn (h, key, hash_code,
3870 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
3872 /* Take entry out of collision chain. */
3873 if (NILP (prev))
3874 set_hash_index_slot (h, start_of_bucket, HASH_NEXT (h, i));
3875 else
3876 set_hash_next_slot (h, XFASTINT (prev), HASH_NEXT (h, i));
3878 /* Clear slots in key_and_value and add the slots to
3879 the free list. */
3880 set_hash_key_slot (h, i, Qnil);
3881 set_hash_value_slot (h, i, Qnil);
3882 set_hash_hash_slot (h, i, Qnil);
3883 set_hash_next_slot (h, i, h->next_free);
3884 h->next_free = make_number (i);
3885 h->count--;
3886 eassert (h->count >= 0);
3887 break;
3889 else
3891 prev = idx;
3892 idx = HASH_NEXT (h, i);
3898 /* Clear hash table H. */
3900 static void
3901 hash_clear (struct Lisp_Hash_Table *h)
3903 if (h->count > 0)
3905 ptrdiff_t i, size = HASH_TABLE_SIZE (h);
3907 for (i = 0; i < size; ++i)
3909 set_hash_next_slot (h, i, i < size - 1 ? make_number (i + 1) : Qnil);
3910 set_hash_key_slot (h, i, Qnil);
3911 set_hash_value_slot (h, i, Qnil);
3912 set_hash_hash_slot (h, i, Qnil);
3915 for (i = 0; i < ASIZE (h->index); ++i)
3916 ASET (h->index, i, Qnil);
3918 h->next_free = make_number (0);
3919 h->count = 0;
3925 /************************************************************************
3926 Weak Hash Tables
3927 ************************************************************************/
3929 /* Sweep weak hash table H. REMOVE_ENTRIES_P means remove
3930 entries from the table that don't survive the current GC.
3931 !REMOVE_ENTRIES_P means mark entries that are in use. Value is
3932 true if anything was marked. */
3934 static bool
3935 sweep_weak_table (struct Lisp_Hash_Table *h, bool remove_entries_p)
3937 ptrdiff_t bucket, n;
3938 bool marked;
3940 n = ASIZE (h->index) & ~ARRAY_MARK_FLAG;
3941 marked = 0;
3943 for (bucket = 0; bucket < n; ++bucket)
3945 Lisp_Object idx, next, prev;
3947 /* Follow collision chain, removing entries that
3948 don't survive this garbage collection. */
3949 prev = Qnil;
3950 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
3952 ptrdiff_t i = XFASTINT (idx);
3953 bool key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
3954 bool value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
3955 bool remove_p;
3957 if (EQ (h->weak, Qkey))
3958 remove_p = !key_known_to_survive_p;
3959 else if (EQ (h->weak, Qvalue))
3960 remove_p = !value_known_to_survive_p;
3961 else if (EQ (h->weak, Qkey_or_value))
3962 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
3963 else if (EQ (h->weak, Qkey_and_value))
3964 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
3965 else
3966 emacs_abort ();
3968 next = HASH_NEXT (h, i);
3970 if (remove_entries_p)
3972 if (remove_p)
3974 /* Take out of collision chain. */
3975 if (NILP (prev))
3976 set_hash_index_slot (h, bucket, next);
3977 else
3978 set_hash_next_slot (h, XFASTINT (prev), next);
3980 /* Add to free list. */
3981 set_hash_next_slot (h, i, h->next_free);
3982 h->next_free = idx;
3984 /* Clear key, value, and hash. */
3985 set_hash_key_slot (h, i, Qnil);
3986 set_hash_value_slot (h, i, Qnil);
3987 set_hash_hash_slot (h, i, Qnil);
3989 h->count--;
3991 else
3993 prev = idx;
3996 else
3998 if (!remove_p)
4000 /* Make sure key and value survive. */
4001 if (!key_known_to_survive_p)
4003 mark_object (HASH_KEY (h, i));
4004 marked = 1;
4007 if (!value_known_to_survive_p)
4009 mark_object (HASH_VALUE (h, i));
4010 marked = 1;
4017 return marked;
4020 /* Remove elements from weak hash tables that don't survive the
4021 current garbage collection. Remove weak tables that don't survive
4022 from Vweak_hash_tables. Called from gc_sweep. */
4024 void
4025 sweep_weak_hash_tables (void)
4027 struct Lisp_Hash_Table *h, *used, *next;
4028 bool marked;
4030 /* Mark all keys and values that are in use. Keep on marking until
4031 there is no more change. This is necessary for cases like
4032 value-weak table A containing an entry X -> Y, where Y is used in a
4033 key-weak table B, Z -> Y. If B comes after A in the list of weak
4034 tables, X -> Y might be removed from A, although when looking at B
4035 one finds that it shouldn't. */
4038 marked = 0;
4039 for (h = weak_hash_tables; h; h = h->next_weak)
4041 if (h->header.size & ARRAY_MARK_FLAG)
4042 marked |= sweep_weak_table (h, 0);
4045 while (marked);
4047 /* Remove tables and entries that aren't used. */
4048 for (h = weak_hash_tables, used = NULL; h; h = next)
4050 next = h->next_weak;
4052 if (h->header.size & ARRAY_MARK_FLAG)
4054 /* TABLE is marked as used. Sweep its contents. */
4055 if (h->count > 0)
4056 sweep_weak_table (h, 1);
4058 /* Add table to the list of used weak hash tables. */
4059 h->next_weak = used;
4060 used = h;
4064 weak_hash_tables = used;
4069 /***********************************************************************
4070 Hash Code Computation
4071 ***********************************************************************/
4073 /* Maximum depth up to which to dive into Lisp structures. */
4075 #define SXHASH_MAX_DEPTH 3
4077 /* Maximum length up to which to take list and vector elements into
4078 account. */
4080 #define SXHASH_MAX_LEN 7
4082 /* Combine two integers X and Y for hashing. The result might not fit
4083 into a Lisp integer. */
4085 #define SXHASH_COMBINE(X, Y) \
4086 ((((EMACS_UINT) (X) << 4) + ((EMACS_UINT) (X) >> (BITS_PER_EMACS_INT - 4))) \
4087 + (EMACS_UINT) (Y))
4089 /* Hash X, returning a value that fits into a Lisp integer. */
4090 #define SXHASH_REDUCE(X) \
4091 ((((X) ^ (X) >> (BITS_PER_EMACS_INT - FIXNUM_BITS))) & INTMASK)
4093 /* Return a hash for string PTR which has length LEN. The hash value
4094 can be any EMACS_UINT value. */
4096 EMACS_UINT
4097 hash_string (char const *ptr, ptrdiff_t len)
4099 char const *p = ptr;
4100 char const *end = p + len;
4101 unsigned char c;
4102 EMACS_UINT hash = 0;
4104 while (p != end)
4106 c = *p++;
4107 hash = SXHASH_COMBINE (hash, c);
4110 return hash;
4113 /* Return a hash for string PTR which has length LEN. The hash
4114 code returned is guaranteed to fit in a Lisp integer. */
4116 static EMACS_UINT
4117 sxhash_string (char const *ptr, ptrdiff_t len)
4119 EMACS_UINT hash = hash_string (ptr, len);
4120 return SXHASH_REDUCE (hash);
4123 /* Return a hash for the floating point value VAL. */
4125 static EMACS_INT
4126 sxhash_float (double val)
4128 EMACS_UINT hash = 0;
4129 enum {
4130 WORDS_PER_DOUBLE = (sizeof val / sizeof hash
4131 + (sizeof val % sizeof hash != 0))
4133 union {
4134 double val;
4135 EMACS_UINT word[WORDS_PER_DOUBLE];
4136 } u;
4137 int i;
4138 u.val = val;
4139 memset (&u.val + 1, 0, sizeof u - sizeof u.val);
4140 for (i = 0; i < WORDS_PER_DOUBLE; i++)
4141 hash = SXHASH_COMBINE (hash, u.word[i]);
4142 return SXHASH_REDUCE (hash);
4145 /* Return a hash for list LIST. DEPTH is the current depth in the
4146 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4148 static EMACS_UINT
4149 sxhash_list (Lisp_Object list, int depth)
4151 EMACS_UINT hash = 0;
4152 int i;
4154 if (depth < SXHASH_MAX_DEPTH)
4155 for (i = 0;
4156 CONSP (list) && i < SXHASH_MAX_LEN;
4157 list = XCDR (list), ++i)
4159 EMACS_UINT hash2 = sxhash (XCAR (list), depth + 1);
4160 hash = SXHASH_COMBINE (hash, hash2);
4163 if (!NILP (list))
4165 EMACS_UINT hash2 = sxhash (list, depth + 1);
4166 hash = SXHASH_COMBINE (hash, hash2);
4169 return SXHASH_REDUCE (hash);
4173 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4174 the Lisp structure. */
4176 static EMACS_UINT
4177 sxhash_vector (Lisp_Object vec, int depth)
4179 EMACS_UINT hash = ASIZE (vec);
4180 int i, n;
4182 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4183 for (i = 0; i < n; ++i)
4185 EMACS_UINT hash2 = sxhash (AREF (vec, i), depth + 1);
4186 hash = SXHASH_COMBINE (hash, hash2);
4189 return SXHASH_REDUCE (hash);
4192 /* Return a hash for bool-vector VECTOR. */
4194 static EMACS_UINT
4195 sxhash_bool_vector (Lisp_Object vec)
4197 EMACS_UINT hash = XBOOL_VECTOR (vec)->size;
4198 int i, n;
4200 n = min (SXHASH_MAX_LEN, XBOOL_VECTOR (vec)->header.size);
4201 for (i = 0; i < n; ++i)
4202 hash = SXHASH_COMBINE (hash, XBOOL_VECTOR (vec)->data[i]);
4204 return SXHASH_REDUCE (hash);
4208 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4209 structure. Value is an unsigned integer clipped to INTMASK. */
4211 EMACS_UINT
4212 sxhash (Lisp_Object obj, int depth)
4214 EMACS_UINT hash;
4216 if (depth > SXHASH_MAX_DEPTH)
4217 return 0;
4219 switch (XTYPE (obj))
4221 case_Lisp_Int:
4222 hash = XUINT (obj);
4223 break;
4225 case Lisp_Misc:
4226 hash = XUINT (obj);
4227 break;
4229 case Lisp_Symbol:
4230 obj = SYMBOL_NAME (obj);
4231 /* Fall through. */
4233 case Lisp_String:
4234 hash = sxhash_string (SSDATA (obj), SBYTES (obj));
4235 break;
4237 /* This can be everything from a vector to an overlay. */
4238 case Lisp_Vectorlike:
4239 if (VECTORP (obj))
4240 /* According to the CL HyperSpec, two arrays are equal only if
4241 they are `eq', except for strings and bit-vectors. In
4242 Emacs, this works differently. We have to compare element
4243 by element. */
4244 hash = sxhash_vector (obj, depth);
4245 else if (BOOL_VECTOR_P (obj))
4246 hash = sxhash_bool_vector (obj);
4247 else
4248 /* Others are `equal' if they are `eq', so let's take their
4249 address as hash. */
4250 hash = XUINT (obj);
4251 break;
4253 case Lisp_Cons:
4254 hash = sxhash_list (obj, depth);
4255 break;
4257 case Lisp_Float:
4258 hash = sxhash_float (XFLOAT_DATA (obj));
4259 break;
4261 default:
4262 emacs_abort ();
4265 return hash;
4270 /***********************************************************************
4271 Lisp Interface
4272 ***********************************************************************/
4275 DEFUN ("sxhash", Fsxhash, Ssxhash, 1, 1, 0,
4276 doc: /* Compute a hash code for OBJ and return it as integer. */)
4277 (Lisp_Object obj)
4279 EMACS_UINT hash = sxhash (obj, 0);
4280 return make_number (hash);
4284 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4285 doc: /* Create and return a new hash table.
4287 Arguments are specified as keyword/argument pairs. The following
4288 arguments are defined:
4290 :test TEST -- TEST must be a symbol that specifies how to compare
4291 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4292 `equal'. User-supplied test and hash functions can be specified via
4293 `define-hash-table-test'.
4295 :size SIZE -- A hint as to how many elements will be put in the table.
4296 Default is 65.
4298 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4299 fills up. If REHASH-SIZE is an integer, increase the size by that
4300 amount. If it is a float, it must be > 1.0, and the new size is the
4301 old size multiplied by that factor. Default is 1.5.
4303 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4304 Resize the hash table when the ratio (number of entries / table size)
4305 is greater than or equal to THRESHOLD. Default is 0.8.
4307 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4308 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4309 returned is a weak table. Key/value pairs are removed from a weak
4310 hash table when there are no non-weak references pointing to their
4311 key, value, one of key or value, or both key and value, depending on
4312 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4313 is nil.
4315 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4316 (ptrdiff_t nargs, Lisp_Object *args)
4318 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4319 Lisp_Object user_test, user_hash;
4320 char *used;
4321 ptrdiff_t i;
4323 /* The vector `used' is used to keep track of arguments that
4324 have been consumed. */
4325 used = alloca (nargs * sizeof *used);
4326 memset (used, 0, nargs * sizeof *used);
4328 /* See if there's a `:test TEST' among the arguments. */
4329 i = get_key_arg (QCtest, nargs, args, used);
4330 test = i ? args[i] : Qeql;
4331 if (!EQ (test, Qeq) && !EQ (test, Qeql) && !EQ (test, Qequal))
4333 /* See if it is a user-defined test. */
4334 Lisp_Object prop;
4336 prop = Fget (test, Qhash_table_test);
4337 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4338 signal_error ("Invalid hash table test", test);
4339 user_test = XCAR (prop);
4340 user_hash = XCAR (XCDR (prop));
4342 else
4343 user_test = user_hash = Qnil;
4345 /* See if there's a `:size SIZE' argument. */
4346 i = get_key_arg (QCsize, nargs, args, used);
4347 size = i ? args[i] : Qnil;
4348 if (NILP (size))
4349 size = make_number (DEFAULT_HASH_SIZE);
4350 else if (!INTEGERP (size) || XINT (size) < 0)
4351 signal_error ("Invalid hash table size", size);
4353 /* Look for `:rehash-size SIZE'. */
4354 i = get_key_arg (QCrehash_size, nargs, args, used);
4355 rehash_size = i ? args[i] : make_float (DEFAULT_REHASH_SIZE);
4356 if (! ((INTEGERP (rehash_size) && 0 < XINT (rehash_size))
4357 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size))))
4358 signal_error ("Invalid hash table rehash size", rehash_size);
4360 /* Look for `:rehash-threshold THRESHOLD'. */
4361 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4362 rehash_threshold = i ? args[i] : make_float (DEFAULT_REHASH_THRESHOLD);
4363 if (! (FLOATP (rehash_threshold)
4364 && 0 < XFLOAT_DATA (rehash_threshold)
4365 && XFLOAT_DATA (rehash_threshold) <= 1))
4366 signal_error ("Invalid hash table rehash threshold", rehash_threshold);
4368 /* Look for `:weakness WEAK'. */
4369 i = get_key_arg (QCweakness, nargs, args, used);
4370 weak = i ? args[i] : Qnil;
4371 if (EQ (weak, Qt))
4372 weak = Qkey_and_value;
4373 if (!NILP (weak)
4374 && !EQ (weak, Qkey)
4375 && !EQ (weak, Qvalue)
4376 && !EQ (weak, Qkey_or_value)
4377 && !EQ (weak, Qkey_and_value))
4378 signal_error ("Invalid hash table weakness", weak);
4380 /* Now, all args should have been used up, or there's a problem. */
4381 for (i = 0; i < nargs; ++i)
4382 if (!used[i])
4383 signal_error ("Invalid argument list", args[i]);
4385 return make_hash_table (test, size, rehash_size, rehash_threshold, weak,
4386 user_test, user_hash);
4390 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4391 doc: /* Return a copy of hash table TABLE. */)
4392 (Lisp_Object table)
4394 return copy_hash_table (check_hash_table (table));
4398 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4399 doc: /* Return the number of elements in TABLE. */)
4400 (Lisp_Object table)
4402 return make_number (check_hash_table (table)->count);
4406 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4407 Shash_table_rehash_size, 1, 1, 0,
4408 doc: /* Return the current rehash size of TABLE. */)
4409 (Lisp_Object table)
4411 return check_hash_table (table)->rehash_size;
4415 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4416 Shash_table_rehash_threshold, 1, 1, 0,
4417 doc: /* Return the current rehash threshold of TABLE. */)
4418 (Lisp_Object table)
4420 return check_hash_table (table)->rehash_threshold;
4424 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4425 doc: /* Return the size of TABLE.
4426 The size can be used as an argument to `make-hash-table' to create
4427 a hash table than can hold as many elements as TABLE holds
4428 without need for resizing. */)
4429 (Lisp_Object table)
4431 struct Lisp_Hash_Table *h = check_hash_table (table);
4432 return make_number (HASH_TABLE_SIZE (h));
4436 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4437 doc: /* Return the test TABLE uses. */)
4438 (Lisp_Object table)
4440 return check_hash_table (table)->test;
4444 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4445 1, 1, 0,
4446 doc: /* Return the weakness of TABLE. */)
4447 (Lisp_Object table)
4449 return check_hash_table (table)->weak;
4453 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4454 doc: /* Return t if OBJ is a Lisp hash table object. */)
4455 (Lisp_Object obj)
4457 return HASH_TABLE_P (obj) ? Qt : Qnil;
4461 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4462 doc: /* Clear hash table TABLE and return it. */)
4463 (Lisp_Object table)
4465 hash_clear (check_hash_table (table));
4466 /* Be compatible with XEmacs. */
4467 return table;
4471 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4472 doc: /* Look up KEY in TABLE and return its associated value.
4473 If KEY is not found, return DFLT which defaults to nil. */)
4474 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4476 struct Lisp_Hash_Table *h = check_hash_table (table);
4477 ptrdiff_t i = hash_lookup (h, key, NULL);
4478 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4482 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4483 doc: /* Associate KEY with VALUE in hash table TABLE.
4484 If KEY is already present in table, replace its current value with
4485 VALUE. In any case, return VALUE. */)
4486 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4488 struct Lisp_Hash_Table *h = check_hash_table (table);
4489 ptrdiff_t i;
4490 EMACS_UINT hash;
4492 i = hash_lookup (h, key, &hash);
4493 if (i >= 0)
4494 set_hash_value_slot (h, i, value);
4495 else
4496 hash_put (h, key, value, hash);
4498 return value;
4502 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4503 doc: /* Remove KEY from TABLE. */)
4504 (Lisp_Object key, Lisp_Object table)
4506 struct Lisp_Hash_Table *h = check_hash_table (table);
4507 hash_remove_from_table (h, key);
4508 return Qnil;
4512 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4513 doc: /* Call FUNCTION for all entries in hash table TABLE.
4514 FUNCTION is called with two arguments, KEY and VALUE. */)
4515 (Lisp_Object function, Lisp_Object table)
4517 struct Lisp_Hash_Table *h = check_hash_table (table);
4518 Lisp_Object args[3];
4519 ptrdiff_t i;
4521 for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
4522 if (!NILP (HASH_HASH (h, i)))
4524 args[0] = function;
4525 args[1] = HASH_KEY (h, i);
4526 args[2] = HASH_VALUE (h, i);
4527 Ffuncall (3, args);
4530 return Qnil;
4534 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4535 Sdefine_hash_table_test, 3, 3, 0,
4536 doc: /* Define a new hash table test with name NAME, a symbol.
4538 In hash tables created with NAME specified as test, use TEST to
4539 compare keys, and HASH for computing hash codes of keys.
4541 TEST must be a function taking two arguments and returning non-nil if
4542 both arguments are the same. HASH must be a function taking one
4543 argument and return an integer that is the hash code of the argument.
4544 Hash code computation should use the whole value range of integers,
4545 including negative integers. */)
4546 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4548 return Fput (name, Qhash_table_test, list2 (test, hash));
4553 /************************************************************************
4554 MD5, SHA-1, and SHA-2
4555 ************************************************************************/
4557 #include "md5.h"
4558 #include "sha1.h"
4559 #include "sha256.h"
4560 #include "sha512.h"
4562 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4564 static Lisp_Object
4565 secure_hash (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror, Lisp_Object binary)
4567 int i;
4568 ptrdiff_t size;
4569 EMACS_INT start_char = 0, end_char = 0;
4570 ptrdiff_t start_byte, end_byte;
4571 register EMACS_INT b, e;
4572 register struct buffer *bp;
4573 EMACS_INT temp;
4574 int digest_size;
4575 void *(*hash_func) (const char *, size_t, void *);
4576 Lisp_Object digest;
4578 CHECK_SYMBOL (algorithm);
4580 if (STRINGP (object))
4582 if (NILP (coding_system))
4584 /* Decide the coding-system to encode the data with. */
4586 if (STRING_MULTIBYTE (object))
4587 /* use default, we can't guess correct value */
4588 coding_system = preferred_coding_system ();
4589 else
4590 coding_system = Qraw_text;
4593 if (NILP (Fcoding_system_p (coding_system)))
4595 /* Invalid coding system. */
4597 if (!NILP (noerror))
4598 coding_system = Qraw_text;
4599 else
4600 xsignal1 (Qcoding_system_error, coding_system);
4603 if (STRING_MULTIBYTE (object))
4604 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4606 size = SCHARS (object);
4608 if (!NILP (start))
4610 CHECK_NUMBER (start);
4612 start_char = XINT (start);
4614 if (start_char < 0)
4615 start_char += size;
4618 if (NILP (end))
4619 end_char = size;
4620 else
4622 CHECK_NUMBER (end);
4624 end_char = XINT (end);
4626 if (end_char < 0)
4627 end_char += size;
4630 if (!(0 <= start_char && start_char <= end_char && end_char <= size))
4631 args_out_of_range_3 (object, make_number (start_char),
4632 make_number (end_char));
4634 start_byte = NILP (start) ? 0 : string_char_to_byte (object, start_char);
4635 end_byte =
4636 NILP (end) ? SBYTES (object) : string_char_to_byte (object, end_char);
4638 else
4640 struct buffer *prev = current_buffer;
4642 record_unwind_current_buffer ();
4644 CHECK_BUFFER (object);
4646 bp = XBUFFER (object);
4647 set_buffer_internal (bp);
4649 if (NILP (start))
4650 b = BEGV;
4651 else
4653 CHECK_NUMBER_COERCE_MARKER (start);
4654 b = XINT (start);
4657 if (NILP (end))
4658 e = ZV;
4659 else
4661 CHECK_NUMBER_COERCE_MARKER (end);
4662 e = XINT (end);
4665 if (b > e)
4666 temp = b, b = e, e = temp;
4668 if (!(BEGV <= b && e <= ZV))
4669 args_out_of_range (start, end);
4671 if (NILP (coding_system))
4673 /* Decide the coding-system to encode the data with.
4674 See fileio.c:Fwrite-region */
4676 if (!NILP (Vcoding_system_for_write))
4677 coding_system = Vcoding_system_for_write;
4678 else
4680 bool force_raw_text = 0;
4682 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4683 if (NILP (coding_system)
4684 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4686 coding_system = Qnil;
4687 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4688 force_raw_text = 1;
4691 if (NILP (coding_system) && !NILP (Fbuffer_file_name (object)))
4693 /* Check file-coding-system-alist. */
4694 Lisp_Object args[4], val;
4696 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4697 args[3] = Fbuffer_file_name (object);
4698 val = Ffind_operation_coding_system (4, args);
4699 if (CONSP (val) && !NILP (XCDR (val)))
4700 coding_system = XCDR (val);
4703 if (NILP (coding_system)
4704 && !NILP (BVAR (XBUFFER (object), buffer_file_coding_system)))
4706 /* If we still have not decided a coding system, use the
4707 default value of buffer-file-coding-system. */
4708 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4711 if (!force_raw_text
4712 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4713 /* Confirm that VAL can surely encode the current region. */
4714 coding_system = call4 (Vselect_safe_coding_system_function,
4715 make_number (b), make_number (e),
4716 coding_system, Qnil);
4718 if (force_raw_text)
4719 coding_system = Qraw_text;
4722 if (NILP (Fcoding_system_p (coding_system)))
4724 /* Invalid coding system. */
4726 if (!NILP (noerror))
4727 coding_system = Qraw_text;
4728 else
4729 xsignal1 (Qcoding_system_error, coding_system);
4733 object = make_buffer_string (b, e, 0);
4734 set_buffer_internal (prev);
4735 /* Discard the unwind protect for recovering the current
4736 buffer. */
4737 specpdl_ptr--;
4739 if (STRING_MULTIBYTE (object))
4740 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4741 start_byte = 0;
4742 end_byte = SBYTES (object);
4745 if (EQ (algorithm, Qmd5))
4747 digest_size = MD5_DIGEST_SIZE;
4748 hash_func = md5_buffer;
4750 else if (EQ (algorithm, Qsha1))
4752 digest_size = SHA1_DIGEST_SIZE;
4753 hash_func = sha1_buffer;
4755 else if (EQ (algorithm, Qsha224))
4757 digest_size = SHA224_DIGEST_SIZE;
4758 hash_func = sha224_buffer;
4760 else if (EQ (algorithm, Qsha256))
4762 digest_size = SHA256_DIGEST_SIZE;
4763 hash_func = sha256_buffer;
4765 else if (EQ (algorithm, Qsha384))
4767 digest_size = SHA384_DIGEST_SIZE;
4768 hash_func = sha384_buffer;
4770 else if (EQ (algorithm, Qsha512))
4772 digest_size = SHA512_DIGEST_SIZE;
4773 hash_func = sha512_buffer;
4775 else
4776 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm)));
4778 /* allocate 2 x digest_size so that it can be re-used to hold the
4779 hexified value */
4780 digest = make_uninit_string (digest_size * 2);
4782 hash_func (SSDATA (object) + start_byte,
4783 end_byte - start_byte,
4784 SSDATA (digest));
4786 if (NILP (binary))
4788 unsigned char *p = SDATA (digest);
4789 for (i = digest_size - 1; i >= 0; i--)
4791 static char const hexdigit[16] = "0123456789abcdef";
4792 int p_i = p[i];
4793 p[2 * i] = hexdigit[p_i >> 4];
4794 p[2 * i + 1] = hexdigit[p_i & 0xf];
4796 return digest;
4798 else
4799 return make_unibyte_string (SSDATA (digest), digest_size);
4802 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
4803 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
4805 A message digest is a cryptographic checksum of a document, and the
4806 algorithm to calculate it is defined in RFC 1321.
4808 The two optional arguments START and END are character positions
4809 specifying for which part of OBJECT the message digest should be
4810 computed. If nil or omitted, the digest is computed for the whole
4811 OBJECT.
4813 The MD5 message digest is computed from the result of encoding the
4814 text in a coding system, not directly from the internal Emacs form of
4815 the text. The optional fourth argument CODING-SYSTEM specifies which
4816 coding system to encode the text with. It should be the same coding
4817 system that you used or will use when actually writing the text into a
4818 file.
4820 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
4821 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
4822 system would be chosen by default for writing this text into a file.
4824 If OBJECT is a string, the most preferred coding system (see the
4825 command `prefer-coding-system') is used.
4827 If NOERROR is non-nil, silently assume the `raw-text' coding if the
4828 guesswork fails. Normally, an error is signaled in such case. */)
4829 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
4831 return secure_hash (Qmd5, object, start, end, coding_system, noerror, Qnil);
4834 DEFUN ("secure-hash", Fsecure_hash, Ssecure_hash, 2, 5, 0,
4835 doc: /* Return the secure hash of OBJECT, a buffer or string.
4836 ALGORITHM is a symbol specifying the hash to use:
4837 md5, sha1, sha224, sha256, sha384 or sha512.
4839 The two optional arguments START and END are positions specifying for
4840 which part of OBJECT to compute the hash. If nil or omitted, uses the
4841 whole OBJECT.
4843 If BINARY is non-nil, returns a string in binary form. */)
4844 (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object binary)
4846 return secure_hash (algorithm, object, start, end, Qnil, Qnil, binary);
4849 void
4850 syms_of_fns (void)
4852 DEFSYM (Qmd5, "md5");
4853 DEFSYM (Qsha1, "sha1");
4854 DEFSYM (Qsha224, "sha224");
4855 DEFSYM (Qsha256, "sha256");
4856 DEFSYM (Qsha384, "sha384");
4857 DEFSYM (Qsha512, "sha512");
4859 /* Hash table stuff. */
4860 DEFSYM (Qhash_table_p, "hash-table-p");
4861 DEFSYM (Qeq, "eq");
4862 DEFSYM (Qeql, "eql");
4863 DEFSYM (Qequal, "equal");
4864 DEFSYM (QCtest, ":test");
4865 DEFSYM (QCsize, ":size");
4866 DEFSYM (QCrehash_size, ":rehash-size");
4867 DEFSYM (QCrehash_threshold, ":rehash-threshold");
4868 DEFSYM (QCweakness, ":weakness");
4869 DEFSYM (Qkey, "key");
4870 DEFSYM (Qvalue, "value");
4871 DEFSYM (Qhash_table_test, "hash-table-test");
4872 DEFSYM (Qkey_or_value, "key-or-value");
4873 DEFSYM (Qkey_and_value, "key-and-value");
4875 defsubr (&Ssxhash);
4876 defsubr (&Smake_hash_table);
4877 defsubr (&Scopy_hash_table);
4878 defsubr (&Shash_table_count);
4879 defsubr (&Shash_table_rehash_size);
4880 defsubr (&Shash_table_rehash_threshold);
4881 defsubr (&Shash_table_size);
4882 defsubr (&Shash_table_test);
4883 defsubr (&Shash_table_weakness);
4884 defsubr (&Shash_table_p);
4885 defsubr (&Sclrhash);
4886 defsubr (&Sgethash);
4887 defsubr (&Sputhash);
4888 defsubr (&Sremhash);
4889 defsubr (&Smaphash);
4890 defsubr (&Sdefine_hash_table_test);
4892 DEFSYM (Qstring_lessp, "string-lessp");
4893 DEFSYM (Qprovide, "provide");
4894 DEFSYM (Qrequire, "require");
4895 DEFSYM (Qyes_or_no_p_history, "yes-or-no-p-history");
4896 DEFSYM (Qcursor_in_echo_area, "cursor-in-echo-area");
4897 DEFSYM (Qwidget_type, "widget-type");
4899 staticpro (&string_char_byte_cache_string);
4900 string_char_byte_cache_string = Qnil;
4902 require_nesting_list = Qnil;
4903 staticpro (&require_nesting_list);
4905 Fset (Qyes_or_no_p_history, Qnil);
4907 DEFVAR_LISP ("features", Vfeatures,
4908 doc: /* A list of symbols which are the features of the executing Emacs.
4909 Used by `featurep' and `require', and altered by `provide'. */);
4910 Vfeatures = Fcons (intern_c_string ("emacs"), Qnil);
4911 DEFSYM (Qsubfeatures, "subfeatures");
4913 #ifdef HAVE_LANGINFO_CODESET
4914 DEFSYM (Qcodeset, "codeset");
4915 DEFSYM (Qdays, "days");
4916 DEFSYM (Qmonths, "months");
4917 DEFSYM (Qpaper, "paper");
4918 #endif /* HAVE_LANGINFO_CODESET */
4920 DEFVAR_BOOL ("use-dialog-box", use_dialog_box,
4921 doc: /* Non-nil means mouse commands use dialog boxes to ask questions.
4922 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
4923 invoked by mouse clicks and mouse menu items.
4925 On some platforms, file selection dialogs are also enabled if this is
4926 non-nil. */);
4927 use_dialog_box = 1;
4929 DEFVAR_BOOL ("use-file-dialog", use_file_dialog,
4930 doc: /* Non-nil means mouse commands use a file dialog to ask for files.
4931 This applies to commands from menus and tool bar buttons even when
4932 they are initiated from the keyboard. If `use-dialog-box' is nil,
4933 that disables the use of a file dialog, regardless of the value of
4934 this variable. */);
4935 use_file_dialog = 1;
4937 defsubr (&Sidentity);
4938 defsubr (&Srandom);
4939 defsubr (&Slength);
4940 defsubr (&Ssafe_length);
4941 defsubr (&Sstring_bytes);
4942 defsubr (&Sstring_equal);
4943 defsubr (&Scompare_strings);
4944 defsubr (&Sstring_lessp);
4945 defsubr (&Sappend);
4946 defsubr (&Sconcat);
4947 defsubr (&Svconcat);
4948 defsubr (&Scopy_sequence);
4949 defsubr (&Sstring_make_multibyte);
4950 defsubr (&Sstring_make_unibyte);
4951 defsubr (&Sstring_as_multibyte);
4952 defsubr (&Sstring_as_unibyte);
4953 defsubr (&Sstring_to_multibyte);
4954 defsubr (&Sstring_to_unibyte);
4955 defsubr (&Scopy_alist);
4956 defsubr (&Ssubstring);
4957 defsubr (&Ssubstring_no_properties);
4958 defsubr (&Snthcdr);
4959 defsubr (&Snth);
4960 defsubr (&Selt);
4961 defsubr (&Smember);
4962 defsubr (&Smemq);
4963 defsubr (&Smemql);
4964 defsubr (&Sassq);
4965 defsubr (&Sassoc);
4966 defsubr (&Srassq);
4967 defsubr (&Srassoc);
4968 defsubr (&Sdelq);
4969 defsubr (&Sdelete);
4970 defsubr (&Snreverse);
4971 defsubr (&Sreverse);
4972 defsubr (&Ssort);
4973 defsubr (&Splist_get);
4974 defsubr (&Sget);
4975 defsubr (&Splist_put);
4976 defsubr (&Sput);
4977 defsubr (&Slax_plist_get);
4978 defsubr (&Slax_plist_put);
4979 defsubr (&Seql);
4980 defsubr (&Sequal);
4981 defsubr (&Sequal_including_properties);
4982 defsubr (&Sfillarray);
4983 defsubr (&Sclear_string);
4984 defsubr (&Snconc);
4985 defsubr (&Smapcar);
4986 defsubr (&Smapc);
4987 defsubr (&Smapconcat);
4988 defsubr (&Syes_or_no_p);
4989 defsubr (&Sload_average);
4990 defsubr (&Sfeaturep);
4991 defsubr (&Srequire);
4992 defsubr (&Sprovide);
4993 defsubr (&Splist_member);
4994 defsubr (&Swidget_put);
4995 defsubr (&Swidget_get);
4996 defsubr (&Swidget_apply);
4997 defsubr (&Sbase64_encode_region);
4998 defsubr (&Sbase64_decode_region);
4999 defsubr (&Sbase64_encode_string);
5000 defsubr (&Sbase64_decode_string);
5001 defsubr (&Smd5);
5002 defsubr (&Ssecure_hash);
5003 defsubr (&Slocale_info);