Lisp manaual improvements re docstrings
[emacs.git] / src / fns.c
blob4c082aa84e2baceaf778281825869d11b5103052
1 /* Random utility Lisp functions.
3 Copyright (C) 1985-1987, 1993-1995, 1997-2014 Free Software Foundation,
4 Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
23 #include <unistd.h>
24 #include <time.h>
26 #include <intprops.h>
28 #include "lisp.h"
29 #include "commands.h"
30 #include "character.h"
31 #include "coding.h"
32 #include "buffer.h"
33 #include "keyboard.h"
34 #include "keymap.h"
35 #include "intervals.h"
36 #include "frame.h"
37 #include "window.h"
38 #include "blockinput.h"
39 #if defined (HAVE_X_WINDOWS)
40 #include "xterm.h"
41 #endif
43 Lisp_Object Qstring_lessp;
44 static Lisp_Object Qprovide, Qrequire;
45 static Lisp_Object Qyes_or_no_p_history;
46 Lisp_Object Qcursor_in_echo_area;
47 static Lisp_Object Qwidget_type;
48 static Lisp_Object Qcodeset, Qdays, Qmonths, Qpaper;
50 static Lisp_Object Qmd5, Qsha1, Qsha224, Qsha256, Qsha384, Qsha512;
52 static bool internal_equal (Lisp_Object, Lisp_Object, int, bool, Lisp_Object);
54 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
55 doc: /* Return the argument unchanged. */)
56 (Lisp_Object arg)
58 return arg;
61 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
62 doc: /* Return a pseudo-random number.
63 All integers representable in Lisp, i.e. between `most-negative-fixnum'
64 and `most-positive-fixnum', inclusive, are equally likely.
66 With positive integer LIMIT, return random number in interval [0,LIMIT).
67 With argument t, set the random number seed from the current time and pid.
68 With a string argument, set the seed based on the string's contents.
69 Other values of LIMIT are ignored.
71 See Info node `(elisp)Random Numbers' for more details. */)
72 (Lisp_Object limit)
74 EMACS_INT val;
76 if (EQ (limit, Qt))
77 init_random ();
78 else if (STRINGP (limit))
79 seed_random (SSDATA (limit), SBYTES (limit));
81 val = get_random ();
82 if (NATNUMP (limit) && XFASTINT (limit) != 0)
83 val %= XFASTINT (limit);
84 return make_number (val);
87 /* Heuristic on how many iterations of a tight loop can be safely done
88 before it's time to do a QUIT. This must be a power of 2. */
89 enum { QUIT_COUNT_HEURISTIC = 1 << 16 };
91 /* Random data-structure functions. */
93 static void
94 CHECK_LIST_END (Lisp_Object x, Lisp_Object y)
96 CHECK_TYPE (NILP (x), Qlistp, y);
99 DEFUN ("length", Flength, Slength, 1, 1, 0,
100 doc: /* Return the length of vector, list or string SEQUENCE.
101 A byte-code function object is also allowed.
102 If the string contains multibyte characters, this is not necessarily
103 the number of bytes in the string; it is the number of characters.
104 To get the number of bytes, use `string-bytes'. */)
105 (register Lisp_Object sequence)
107 register Lisp_Object val;
109 if (STRINGP (sequence))
110 XSETFASTINT (val, SCHARS (sequence));
111 else if (VECTORP (sequence))
112 XSETFASTINT (val, ASIZE (sequence));
113 else if (CHAR_TABLE_P (sequence))
114 XSETFASTINT (val, MAX_CHAR);
115 else if (BOOL_VECTOR_P (sequence))
116 XSETFASTINT (val, bool_vector_size (sequence));
117 else if (COMPILEDP (sequence))
118 XSETFASTINT (val, ASIZE (sequence) & PSEUDOVECTOR_SIZE_MASK);
119 else if (CONSP (sequence))
121 EMACS_INT i = 0;
125 ++i;
126 if ((i & (QUIT_COUNT_HEURISTIC - 1)) == 0)
128 if (MOST_POSITIVE_FIXNUM < i)
129 error ("List too long");
130 QUIT;
132 sequence = XCDR (sequence);
134 while (CONSP (sequence));
136 CHECK_LIST_END (sequence, sequence);
138 val = make_number (i);
140 else if (NILP (sequence))
141 XSETFASTINT (val, 0);
142 else
143 wrong_type_argument (Qsequencep, sequence);
145 return val;
148 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
149 doc: /* Return the length of a list, but avoid error or infinite loop.
150 This function never gets an error. If LIST is not really a list,
151 it returns 0. If LIST is circular, it returns a finite value
152 which is at least the number of distinct elements. */)
153 (Lisp_Object list)
155 Lisp_Object tail, halftail;
156 double hilen = 0;
157 uintmax_t lolen = 1;
159 if (! CONSP (list))
160 return make_number (0);
162 /* halftail is used to detect circular lists. */
163 for (tail = halftail = list; ; )
165 tail = XCDR (tail);
166 if (! CONSP (tail))
167 break;
168 if (EQ (tail, halftail))
169 break;
170 lolen++;
171 if ((lolen & 1) == 0)
173 halftail = XCDR (halftail);
174 if ((lolen & (QUIT_COUNT_HEURISTIC - 1)) == 0)
176 QUIT;
177 if (lolen == 0)
178 hilen += UINTMAX_MAX + 1.0;
183 /* If the length does not fit into a fixnum, return a float.
184 On all known practical machines this returns an upper bound on
185 the true length. */
186 return hilen ? make_float (hilen + lolen) : make_fixnum_or_float (lolen);
189 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
190 doc: /* Return the number of bytes in STRING.
191 If STRING is multibyte, this may be greater than the length of STRING. */)
192 (Lisp_Object string)
194 CHECK_STRING (string);
195 return make_number (SBYTES (string));
198 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
199 doc: /* Return t if two strings have identical contents.
200 Case is significant, but text properties are ignored.
201 Symbols are also allowed; their print names are used instead. */)
202 (register Lisp_Object s1, Lisp_Object s2)
204 if (SYMBOLP (s1))
205 s1 = SYMBOL_NAME (s1);
206 if (SYMBOLP (s2))
207 s2 = SYMBOL_NAME (s2);
208 CHECK_STRING (s1);
209 CHECK_STRING (s2);
211 if (SCHARS (s1) != SCHARS (s2)
212 || SBYTES (s1) != SBYTES (s2)
213 || memcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
214 return Qnil;
215 return Qt;
218 DEFUN ("compare-strings", Fcompare_strings, Scompare_strings, 6, 7, 0,
219 doc: /* Compare the contents of two strings, converting to multibyte if needed.
220 The arguments START1, END1, START2, and END2, if non-nil, are
221 positions specifying which parts of STR1 or STR2 to compare. In
222 string STR1, compare the part between START1 (inclusive) and END1
223 \(exclusive). If START1 is nil, it defaults to 0, the beginning of
224 the string; if END1 is nil, it defaults to the length of the string.
225 Likewise, in string STR2, compare the part between START2 and END2.
227 The strings are compared by the numeric values of their characters.
228 For instance, STR1 is "less than" STR2 if its first differing
229 character has a smaller numeric value. If IGNORE-CASE is non-nil,
230 characters are converted to lower-case before comparing them. Unibyte
231 strings are converted to multibyte for comparison.
233 The value is t if the strings (or specified portions) match.
234 If string STR1 is less, the value is a negative number N;
235 - 1 - N is the number of characters that match at the beginning.
236 If string STR1 is greater, the value is a positive number N;
237 N - 1 is the number of characters that match at the beginning. */)
238 (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2, Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
240 register ptrdiff_t end1_char, end2_char;
241 register ptrdiff_t i1, i1_byte, i2, i2_byte;
243 CHECK_STRING (str1);
244 CHECK_STRING (str2);
245 if (NILP (start1))
246 start1 = make_number (0);
247 if (NILP (start2))
248 start2 = make_number (0);
249 CHECK_NATNUM (start1);
250 CHECK_NATNUM (start2);
251 if (! NILP (end1))
252 CHECK_NATNUM (end1);
253 if (! NILP (end2))
254 CHECK_NATNUM (end2);
256 end1_char = SCHARS (str1);
257 if (! NILP (end1) && end1_char > XINT (end1))
258 end1_char = XINT (end1);
259 if (end1_char < XINT (start1))
260 args_out_of_range (str1, start1);
262 end2_char = SCHARS (str2);
263 if (! NILP (end2) && end2_char > XINT (end2))
264 end2_char = XINT (end2);
265 if (end2_char < XINT (start2))
266 args_out_of_range (str2, start2);
268 i1 = XINT (start1);
269 i2 = XINT (start2);
271 i1_byte = string_char_to_byte (str1, i1);
272 i2_byte = string_char_to_byte (str2, i2);
274 while (i1 < end1_char && i2 < end2_char)
276 /* When we find a mismatch, we must compare the
277 characters, not just the bytes. */
278 int c1, c2;
280 if (STRING_MULTIBYTE (str1))
281 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c1, str1, i1, i1_byte);
282 else
284 c1 = SREF (str1, i1++);
285 MAKE_CHAR_MULTIBYTE (c1);
288 if (STRING_MULTIBYTE (str2))
289 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c2, str2, i2, i2_byte);
290 else
292 c2 = SREF (str2, i2++);
293 MAKE_CHAR_MULTIBYTE (c2);
296 if (c1 == c2)
297 continue;
299 if (! NILP (ignore_case))
301 Lisp_Object tem;
303 tem = Fupcase (make_number (c1));
304 c1 = XINT (tem);
305 tem = Fupcase (make_number (c2));
306 c2 = XINT (tem);
309 if (c1 == c2)
310 continue;
312 /* Note that I1 has already been incremented
313 past the character that we are comparing;
314 hence we don't add or subtract 1 here. */
315 if (c1 < c2)
316 return make_number (- i1 + XINT (start1));
317 else
318 return make_number (i1 - XINT (start1));
321 if (i1 < end1_char)
322 return make_number (i1 - XINT (start1) + 1);
323 if (i2 < end2_char)
324 return make_number (- i1 + XINT (start1) - 1);
326 return Qt;
329 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
330 doc: /* Return t if first arg string is less than second in lexicographic order.
331 Case is significant.
332 Symbols are also allowed; their print names are used instead. */)
333 (register Lisp_Object s1, Lisp_Object s2)
335 register ptrdiff_t end;
336 register ptrdiff_t i1, i1_byte, i2, i2_byte;
338 if (SYMBOLP (s1))
339 s1 = SYMBOL_NAME (s1);
340 if (SYMBOLP (s2))
341 s2 = SYMBOL_NAME (s2);
342 CHECK_STRING (s1);
343 CHECK_STRING (s2);
345 i1 = i1_byte = i2 = i2_byte = 0;
347 end = SCHARS (s1);
348 if (end > SCHARS (s2))
349 end = SCHARS (s2);
351 while (i1 < end)
353 /* When we find a mismatch, we must compare the
354 characters, not just the bytes. */
355 int c1, c2;
357 FETCH_STRING_CHAR_ADVANCE (c1, s1, i1, i1_byte);
358 FETCH_STRING_CHAR_ADVANCE (c2, s2, i2, i2_byte);
360 if (c1 != c2)
361 return c1 < c2 ? Qt : Qnil;
363 return i1 < SCHARS (s2) ? Qt : Qnil;
366 static Lisp_Object concat (ptrdiff_t nargs, Lisp_Object *args,
367 enum Lisp_Type target_type, bool last_special);
369 /* ARGSUSED */
370 Lisp_Object
371 concat2 (Lisp_Object s1, Lisp_Object s2)
373 Lisp_Object args[2];
374 args[0] = s1;
375 args[1] = s2;
376 return concat (2, args, Lisp_String, 0);
379 /* ARGSUSED */
380 Lisp_Object
381 concat3 (Lisp_Object s1, Lisp_Object s2, Lisp_Object s3)
383 Lisp_Object args[3];
384 args[0] = s1;
385 args[1] = s2;
386 args[2] = s3;
387 return concat (3, args, Lisp_String, 0);
390 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
391 doc: /* Concatenate all the arguments and make the result a list.
392 The result is a list whose elements are the elements of all the arguments.
393 Each argument may be a list, vector or string.
394 The last argument is not copied, just used as the tail of the new list.
395 usage: (append &rest SEQUENCES) */)
396 (ptrdiff_t nargs, Lisp_Object *args)
398 return concat (nargs, args, Lisp_Cons, 1);
401 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
402 doc: /* Concatenate all the arguments and make the result a string.
403 The result is a string whose elements are the elements of all the arguments.
404 Each argument may be a string or a list or vector of characters (integers).
405 usage: (concat &rest SEQUENCES) */)
406 (ptrdiff_t nargs, Lisp_Object *args)
408 return concat (nargs, args, Lisp_String, 0);
411 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
412 doc: /* Concatenate all the arguments and make the result a vector.
413 The result is a vector whose elements are the elements of all the arguments.
414 Each argument may be a list, vector or string.
415 usage: (vconcat &rest SEQUENCES) */)
416 (ptrdiff_t nargs, Lisp_Object *args)
418 return concat (nargs, args, Lisp_Vectorlike, 0);
422 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
423 doc: /* Return a copy of a list, vector, string or char-table.
424 The elements of a list or vector are not copied; they are shared
425 with the original. */)
426 (Lisp_Object arg)
428 if (NILP (arg)) return arg;
430 if (CHAR_TABLE_P (arg))
432 return copy_char_table (arg);
435 if (BOOL_VECTOR_P (arg))
437 EMACS_INT nbits = bool_vector_size (arg);
438 ptrdiff_t nbytes = bool_vector_bytes (nbits);
439 Lisp_Object val = make_uninit_bool_vector (nbits);
440 memcpy (bool_vector_data (val), bool_vector_data (arg), nbytes);
441 return val;
444 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
445 wrong_type_argument (Qsequencep, arg);
447 return concat (1, &arg, XTYPE (arg), 0);
450 /* This structure holds information of an argument of `concat' that is
451 a string and has text properties to be copied. */
452 struct textprop_rec
454 ptrdiff_t argnum; /* refer to ARGS (arguments of `concat') */
455 ptrdiff_t from; /* refer to ARGS[argnum] (argument string) */
456 ptrdiff_t to; /* refer to VAL (the target string) */
459 static Lisp_Object
460 concat (ptrdiff_t nargs, Lisp_Object *args,
461 enum Lisp_Type target_type, bool last_special)
463 Lisp_Object val;
464 Lisp_Object tail;
465 Lisp_Object this;
466 ptrdiff_t toindex;
467 ptrdiff_t toindex_byte = 0;
468 EMACS_INT result_len;
469 EMACS_INT result_len_byte;
470 ptrdiff_t argnum;
471 Lisp_Object last_tail;
472 Lisp_Object prev;
473 bool some_multibyte;
474 /* When we make a multibyte string, we can't copy text properties
475 while concatenating each string because the length of resulting
476 string can't be decided until we finish the whole concatenation.
477 So, we record strings that have text properties to be copied
478 here, and copy the text properties after the concatenation. */
479 struct textprop_rec *textprops = NULL;
480 /* Number of elements in textprops. */
481 ptrdiff_t num_textprops = 0;
482 USE_SAFE_ALLOCA;
484 tail = Qnil;
486 /* In append, the last arg isn't treated like the others */
487 if (last_special && nargs > 0)
489 nargs--;
490 last_tail = args[nargs];
492 else
493 last_tail = Qnil;
495 /* Check each argument. */
496 for (argnum = 0; argnum < nargs; argnum++)
498 this = args[argnum];
499 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
500 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
501 wrong_type_argument (Qsequencep, this);
504 /* Compute total length in chars of arguments in RESULT_LEN.
505 If desired output is a string, also compute length in bytes
506 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
507 whether the result should be a multibyte string. */
508 result_len_byte = 0;
509 result_len = 0;
510 some_multibyte = 0;
511 for (argnum = 0; argnum < nargs; argnum++)
513 EMACS_INT len;
514 this = args[argnum];
515 len = XFASTINT (Flength (this));
516 if (target_type == Lisp_String)
518 /* We must count the number of bytes needed in the string
519 as well as the number of characters. */
520 ptrdiff_t i;
521 Lisp_Object ch;
522 int c;
523 ptrdiff_t this_len_byte;
525 if (VECTORP (this) || COMPILEDP (this))
526 for (i = 0; i < len; i++)
528 ch = AREF (this, i);
529 CHECK_CHARACTER (ch);
530 c = XFASTINT (ch);
531 this_len_byte = CHAR_BYTES (c);
532 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
533 string_overflow ();
534 result_len_byte += this_len_byte;
535 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
536 some_multibyte = 1;
538 else if (BOOL_VECTOR_P (this) && bool_vector_size (this) > 0)
539 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
540 else if (CONSP (this))
541 for (; CONSP (this); this = XCDR (this))
543 ch = XCAR (this);
544 CHECK_CHARACTER (ch);
545 c = XFASTINT (ch);
546 this_len_byte = CHAR_BYTES (c);
547 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
548 string_overflow ();
549 result_len_byte += this_len_byte;
550 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
551 some_multibyte = 1;
553 else if (STRINGP (this))
555 if (STRING_MULTIBYTE (this))
557 some_multibyte = 1;
558 this_len_byte = SBYTES (this);
560 else
561 this_len_byte = count_size_as_multibyte (SDATA (this),
562 SCHARS (this));
563 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
564 string_overflow ();
565 result_len_byte += this_len_byte;
569 result_len += len;
570 if (MOST_POSITIVE_FIXNUM < result_len)
571 memory_full (SIZE_MAX);
574 if (! some_multibyte)
575 result_len_byte = result_len;
577 /* Create the output object. */
578 if (target_type == Lisp_Cons)
579 val = Fmake_list (make_number (result_len), Qnil);
580 else if (target_type == Lisp_Vectorlike)
581 val = Fmake_vector (make_number (result_len), Qnil);
582 else if (some_multibyte)
583 val = make_uninit_multibyte_string (result_len, result_len_byte);
584 else
585 val = make_uninit_string (result_len);
587 /* In `append', if all but last arg are nil, return last arg. */
588 if (target_type == Lisp_Cons && EQ (val, Qnil))
589 return last_tail;
591 /* Copy the contents of the args into the result. */
592 if (CONSP (val))
593 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
594 else
595 toindex = 0, toindex_byte = 0;
597 prev = Qnil;
598 if (STRINGP (val))
599 SAFE_NALLOCA (textprops, 1, nargs);
601 for (argnum = 0; argnum < nargs; argnum++)
603 Lisp_Object thislen;
604 ptrdiff_t thisleni = 0;
605 register ptrdiff_t thisindex = 0;
606 register ptrdiff_t thisindex_byte = 0;
608 this = args[argnum];
609 if (!CONSP (this))
610 thislen = Flength (this), thisleni = XINT (thislen);
612 /* Between strings of the same kind, copy fast. */
613 if (STRINGP (this) && STRINGP (val)
614 && STRING_MULTIBYTE (this) == some_multibyte)
616 ptrdiff_t thislen_byte = SBYTES (this);
618 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
619 if (string_intervals (this))
621 textprops[num_textprops].argnum = argnum;
622 textprops[num_textprops].from = 0;
623 textprops[num_textprops++].to = toindex;
625 toindex_byte += thislen_byte;
626 toindex += thisleni;
628 /* Copy a single-byte string to a multibyte string. */
629 else if (STRINGP (this) && STRINGP (val))
631 if (string_intervals (this))
633 textprops[num_textprops].argnum = argnum;
634 textprops[num_textprops].from = 0;
635 textprops[num_textprops++].to = toindex;
637 toindex_byte += copy_text (SDATA (this),
638 SDATA (val) + toindex_byte,
639 SCHARS (this), 0, 1);
640 toindex += thisleni;
642 else
643 /* Copy element by element. */
644 while (1)
646 register Lisp_Object elt;
648 /* Fetch next element of `this' arg into `elt', or break if
649 `this' is exhausted. */
650 if (NILP (this)) break;
651 if (CONSP (this))
652 elt = XCAR (this), this = XCDR (this);
653 else if (thisindex >= thisleni)
654 break;
655 else if (STRINGP (this))
657 int c;
658 if (STRING_MULTIBYTE (this))
659 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
660 thisindex,
661 thisindex_byte);
662 else
664 c = SREF (this, thisindex); thisindex++;
665 if (some_multibyte && !ASCII_CHAR_P (c))
666 c = BYTE8_TO_CHAR (c);
668 XSETFASTINT (elt, c);
670 else if (BOOL_VECTOR_P (this))
672 elt = bool_vector_ref (this, thisindex);
673 thisindex++;
675 else
677 elt = AREF (this, thisindex);
678 thisindex++;
681 /* Store this element into the result. */
682 if (toindex < 0)
684 XSETCAR (tail, elt);
685 prev = tail;
686 tail = XCDR (tail);
688 else if (VECTORP (val))
690 ASET (val, toindex, elt);
691 toindex++;
693 else
695 int c;
696 CHECK_CHARACTER (elt);
697 c = XFASTINT (elt);
698 if (some_multibyte)
699 toindex_byte += CHAR_STRING (c, SDATA (val) + toindex_byte);
700 else
701 SSET (val, toindex_byte++, c);
702 toindex++;
706 if (!NILP (prev))
707 XSETCDR (prev, last_tail);
709 if (num_textprops > 0)
711 Lisp_Object props;
712 ptrdiff_t last_to_end = -1;
714 for (argnum = 0; argnum < num_textprops; argnum++)
716 this = args[textprops[argnum].argnum];
717 props = text_property_list (this,
718 make_number (0),
719 make_number (SCHARS (this)),
720 Qnil);
721 /* If successive arguments have properties, be sure that the
722 value of `composition' property be the copy. */
723 if (last_to_end == textprops[argnum].to)
724 make_composition_value_copy (props);
725 add_text_properties_from_list (val, props,
726 make_number (textprops[argnum].to));
727 last_to_end = textprops[argnum].to + SCHARS (this);
731 SAFE_FREE ();
732 return val;
735 static Lisp_Object string_char_byte_cache_string;
736 static ptrdiff_t string_char_byte_cache_charpos;
737 static ptrdiff_t string_char_byte_cache_bytepos;
739 void
740 clear_string_char_byte_cache (void)
742 string_char_byte_cache_string = Qnil;
745 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
747 ptrdiff_t
748 string_char_to_byte (Lisp_Object string, ptrdiff_t char_index)
750 ptrdiff_t i_byte;
751 ptrdiff_t best_below, best_below_byte;
752 ptrdiff_t best_above, best_above_byte;
754 best_below = best_below_byte = 0;
755 best_above = SCHARS (string);
756 best_above_byte = SBYTES (string);
757 if (best_above == best_above_byte)
758 return char_index;
760 if (EQ (string, string_char_byte_cache_string))
762 if (string_char_byte_cache_charpos < char_index)
764 best_below = string_char_byte_cache_charpos;
765 best_below_byte = string_char_byte_cache_bytepos;
767 else
769 best_above = string_char_byte_cache_charpos;
770 best_above_byte = string_char_byte_cache_bytepos;
774 if (char_index - best_below < best_above - char_index)
776 unsigned char *p = SDATA (string) + best_below_byte;
778 while (best_below < char_index)
780 p += BYTES_BY_CHAR_HEAD (*p);
781 best_below++;
783 i_byte = p - SDATA (string);
785 else
787 unsigned char *p = SDATA (string) + best_above_byte;
789 while (best_above > char_index)
791 p--;
792 while (!CHAR_HEAD_P (*p)) p--;
793 best_above--;
795 i_byte = p - SDATA (string);
798 string_char_byte_cache_bytepos = i_byte;
799 string_char_byte_cache_charpos = char_index;
800 string_char_byte_cache_string = string;
802 return i_byte;
805 /* Return the character index corresponding to BYTE_INDEX in STRING. */
807 ptrdiff_t
808 string_byte_to_char (Lisp_Object string, ptrdiff_t byte_index)
810 ptrdiff_t i, i_byte;
811 ptrdiff_t best_below, best_below_byte;
812 ptrdiff_t best_above, best_above_byte;
814 best_below = best_below_byte = 0;
815 best_above = SCHARS (string);
816 best_above_byte = SBYTES (string);
817 if (best_above == best_above_byte)
818 return byte_index;
820 if (EQ (string, string_char_byte_cache_string))
822 if (string_char_byte_cache_bytepos < byte_index)
824 best_below = string_char_byte_cache_charpos;
825 best_below_byte = string_char_byte_cache_bytepos;
827 else
829 best_above = string_char_byte_cache_charpos;
830 best_above_byte = string_char_byte_cache_bytepos;
834 if (byte_index - best_below_byte < best_above_byte - byte_index)
836 unsigned char *p = SDATA (string) + best_below_byte;
837 unsigned char *pend = SDATA (string) + byte_index;
839 while (p < pend)
841 p += BYTES_BY_CHAR_HEAD (*p);
842 best_below++;
844 i = best_below;
845 i_byte = p - SDATA (string);
847 else
849 unsigned char *p = SDATA (string) + best_above_byte;
850 unsigned char *pbeg = SDATA (string) + byte_index;
852 while (p > pbeg)
854 p--;
855 while (!CHAR_HEAD_P (*p)) p--;
856 best_above--;
858 i = best_above;
859 i_byte = p - SDATA (string);
862 string_char_byte_cache_bytepos = i_byte;
863 string_char_byte_cache_charpos = i;
864 string_char_byte_cache_string = string;
866 return i;
869 /* Convert STRING to a multibyte string. */
871 static Lisp_Object
872 string_make_multibyte (Lisp_Object string)
874 unsigned char *buf;
875 ptrdiff_t nbytes;
876 Lisp_Object ret;
877 USE_SAFE_ALLOCA;
879 if (STRING_MULTIBYTE (string))
880 return string;
882 nbytes = count_size_as_multibyte (SDATA (string),
883 SCHARS (string));
884 /* If all the chars are ASCII, they won't need any more bytes
885 once converted. In that case, we can return STRING itself. */
886 if (nbytes == SBYTES (string))
887 return string;
889 buf = SAFE_ALLOCA (nbytes);
890 copy_text (SDATA (string), buf, SBYTES (string),
891 0, 1);
893 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
894 SAFE_FREE ();
896 return ret;
900 /* Convert STRING (if unibyte) to a multibyte string without changing
901 the number of characters. Characters 0200 trough 0237 are
902 converted to eight-bit characters. */
904 Lisp_Object
905 string_to_multibyte (Lisp_Object string)
907 unsigned char *buf;
908 ptrdiff_t nbytes;
909 Lisp_Object ret;
910 USE_SAFE_ALLOCA;
912 if (STRING_MULTIBYTE (string))
913 return string;
915 nbytes = count_size_as_multibyte (SDATA (string), SBYTES (string));
916 /* If all the chars are ASCII, they won't need any more bytes once
917 converted. */
918 if (nbytes == SBYTES (string))
919 return make_multibyte_string (SSDATA (string), nbytes, nbytes);
921 buf = SAFE_ALLOCA (nbytes);
922 memcpy (buf, SDATA (string), SBYTES (string));
923 str_to_multibyte (buf, nbytes, SBYTES (string));
925 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
926 SAFE_FREE ();
928 return ret;
932 /* Convert STRING to a single-byte string. */
934 Lisp_Object
935 string_make_unibyte (Lisp_Object string)
937 ptrdiff_t nchars;
938 unsigned char *buf;
939 Lisp_Object ret;
940 USE_SAFE_ALLOCA;
942 if (! STRING_MULTIBYTE (string))
943 return string;
945 nchars = SCHARS (string);
947 buf = SAFE_ALLOCA (nchars);
948 copy_text (SDATA (string), buf, SBYTES (string),
949 1, 0);
951 ret = make_unibyte_string ((char *) buf, nchars);
952 SAFE_FREE ();
954 return ret;
957 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
958 1, 1, 0,
959 doc: /* Return the multibyte equivalent of STRING.
960 If STRING is unibyte and contains non-ASCII characters, the function
961 `unibyte-char-to-multibyte' is used to convert each unibyte character
962 to a multibyte character. In this case, the returned string is a
963 newly created string with no text properties. If STRING is multibyte
964 or entirely ASCII, it is returned unchanged. In particular, when
965 STRING is unibyte and entirely ASCII, the returned string is unibyte.
966 \(When the characters are all ASCII, Emacs primitives will treat the
967 string the same way whether it is unibyte or multibyte.) */)
968 (Lisp_Object string)
970 CHECK_STRING (string);
972 return string_make_multibyte (string);
975 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
976 1, 1, 0,
977 doc: /* Return the unibyte equivalent of STRING.
978 Multibyte character codes are converted to unibyte according to
979 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
980 If the lookup in the translation table fails, this function takes just
981 the low 8 bits of each character. */)
982 (Lisp_Object string)
984 CHECK_STRING (string);
986 return string_make_unibyte (string);
989 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
990 1, 1, 0,
991 doc: /* Return a unibyte string with the same individual bytes as STRING.
992 If STRING is unibyte, the result is STRING itself.
993 Otherwise it is a newly created string, with no text properties.
994 If STRING is multibyte and contains a character of charset
995 `eight-bit', it is converted to the corresponding single byte. */)
996 (Lisp_Object string)
998 CHECK_STRING (string);
1000 if (STRING_MULTIBYTE (string))
1002 unsigned char *str = (unsigned char *) xlispstrdup (string);
1003 ptrdiff_t bytes = str_as_unibyte (str, SBYTES (string));
1005 string = make_unibyte_string ((char *) str, bytes);
1006 xfree (str);
1008 return string;
1011 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1012 1, 1, 0,
1013 doc: /* Return a multibyte string with the same individual bytes as STRING.
1014 If STRING is multibyte, the result is STRING itself.
1015 Otherwise it is a newly created string, with no text properties.
1017 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1018 part of a correct utf-8 sequence), it is converted to the corresponding
1019 multibyte character of charset `eight-bit'.
1020 See also `string-to-multibyte'.
1022 Beware, this often doesn't really do what you think it does.
1023 It is similar to (decode-coding-string STRING 'utf-8-emacs).
1024 If you're not sure, whether to use `string-as-multibyte' or
1025 `string-to-multibyte', use `string-to-multibyte'. */)
1026 (Lisp_Object string)
1028 CHECK_STRING (string);
1030 if (! STRING_MULTIBYTE (string))
1032 Lisp_Object new_string;
1033 ptrdiff_t nchars, nbytes;
1035 parse_str_as_multibyte (SDATA (string),
1036 SBYTES (string),
1037 &nchars, &nbytes);
1038 new_string = make_uninit_multibyte_string (nchars, nbytes);
1039 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1040 if (nbytes != SBYTES (string))
1041 str_as_multibyte (SDATA (new_string), nbytes,
1042 SBYTES (string), NULL);
1043 string = new_string;
1044 set_string_intervals (string, NULL);
1046 return string;
1049 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1050 1, 1, 0,
1051 doc: /* Return a multibyte string with the same individual chars as STRING.
1052 If STRING is multibyte, the result is STRING itself.
1053 Otherwise it is a newly created string, with no text properties.
1055 If STRING is unibyte and contains an 8-bit byte, it is converted to
1056 the corresponding multibyte character of charset `eight-bit'.
1058 This differs from `string-as-multibyte' by converting each byte of a correct
1059 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1060 correct sequence. */)
1061 (Lisp_Object string)
1063 CHECK_STRING (string);
1065 return string_to_multibyte (string);
1068 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1069 1, 1, 0,
1070 doc: /* Return a unibyte string with the same individual chars as STRING.
1071 If STRING is unibyte, the result is STRING itself.
1072 Otherwise it is a newly created string, with no text properties,
1073 where each `eight-bit' character is converted to the corresponding byte.
1074 If STRING contains a non-ASCII, non-`eight-bit' character,
1075 an error is signaled. */)
1076 (Lisp_Object string)
1078 CHECK_STRING (string);
1080 if (STRING_MULTIBYTE (string))
1082 ptrdiff_t chars = SCHARS (string);
1083 unsigned char *str = xmalloc (chars);
1084 ptrdiff_t converted = str_to_unibyte (SDATA (string), str, chars);
1086 if (converted < chars)
1087 error ("Can't convert the %"pD"dth character to unibyte", converted);
1088 string = make_unibyte_string ((char *) str, chars);
1089 xfree (str);
1091 return string;
1095 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1096 doc: /* Return a copy of ALIST.
1097 This is an alist which represents the same mapping from objects to objects,
1098 but does not share the alist structure with ALIST.
1099 The objects mapped (cars and cdrs of elements of the alist)
1100 are shared, however.
1101 Elements of ALIST that are not conses are also shared. */)
1102 (Lisp_Object alist)
1104 register Lisp_Object tem;
1106 CHECK_LIST (alist);
1107 if (NILP (alist))
1108 return alist;
1109 alist = concat (1, &alist, Lisp_Cons, 0);
1110 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1112 register Lisp_Object car;
1113 car = XCAR (tem);
1115 if (CONSP (car))
1116 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1118 return alist;
1121 DEFUN ("substring", Fsubstring, Ssubstring, 2, 3, 0,
1122 doc: /* Return a new string whose contents are a substring of STRING.
1123 The returned string consists of the characters between index FROM
1124 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1125 zero-indexed: 0 means the first character of STRING. Negative values
1126 are counted from the end of STRING. If TO is nil, the substring runs
1127 to the end of STRING.
1129 The STRING argument may also be a vector. In that case, the return
1130 value is a new vector that contains the elements between index FROM
1131 \(inclusive) and index TO (exclusive) of that vector argument. */)
1132 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1134 Lisp_Object res;
1135 ptrdiff_t size;
1136 EMACS_INT from_char, to_char;
1138 CHECK_VECTOR_OR_STRING (string);
1139 CHECK_NUMBER (from);
1141 if (STRINGP (string))
1142 size = SCHARS (string);
1143 else
1144 size = ASIZE (string);
1146 if (NILP (to))
1147 to_char = size;
1148 else
1150 CHECK_NUMBER (to);
1152 to_char = XINT (to);
1153 if (to_char < 0)
1154 to_char += size;
1157 from_char = XINT (from);
1158 if (from_char < 0)
1159 from_char += size;
1160 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1161 args_out_of_range_3 (string, make_number (from_char),
1162 make_number (to_char));
1164 if (STRINGP (string))
1166 ptrdiff_t to_byte =
1167 (NILP (to) ? SBYTES (string) : string_char_to_byte (string, to_char));
1168 ptrdiff_t from_byte = string_char_to_byte (string, from_char);
1169 res = make_specified_string (SSDATA (string) + from_byte,
1170 to_char - from_char, to_byte - from_byte,
1171 STRING_MULTIBYTE (string));
1172 copy_text_properties (make_number (from_char), make_number (to_char),
1173 string, make_number (0), res, Qnil);
1175 else
1176 res = Fvector (to_char - from_char, aref_addr (string, from_char));
1178 return res;
1182 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1183 doc: /* Return a substring of STRING, without text properties.
1184 It starts at index FROM and ends before TO.
1185 TO may be nil or omitted; then the substring runs to the end of STRING.
1186 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1187 If FROM or TO is negative, it counts from the end.
1189 With one argument, just copy STRING without its properties. */)
1190 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1192 ptrdiff_t size;
1193 EMACS_INT from_char, to_char;
1194 ptrdiff_t from_byte, to_byte;
1196 CHECK_STRING (string);
1198 size = SCHARS (string);
1200 if (NILP (from))
1201 from_char = 0;
1202 else
1204 CHECK_NUMBER (from);
1205 from_char = XINT (from);
1206 if (from_char < 0)
1207 from_char += size;
1210 if (NILP (to))
1211 to_char = size;
1212 else
1214 CHECK_NUMBER (to);
1215 to_char = XINT (to);
1216 if (to_char < 0)
1217 to_char += size;
1220 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1221 args_out_of_range_3 (string, make_number (from_char),
1222 make_number (to_char));
1224 from_byte = NILP (from) ? 0 : string_char_to_byte (string, from_char);
1225 to_byte =
1226 NILP (to) ? SBYTES (string) : string_char_to_byte (string, to_char);
1227 return make_specified_string (SSDATA (string) + from_byte,
1228 to_char - from_char, to_byte - from_byte,
1229 STRING_MULTIBYTE (string));
1232 /* Extract a substring of STRING, giving start and end positions
1233 both in characters and in bytes. */
1235 Lisp_Object
1236 substring_both (Lisp_Object string, ptrdiff_t from, ptrdiff_t from_byte,
1237 ptrdiff_t to, ptrdiff_t to_byte)
1239 Lisp_Object res;
1240 ptrdiff_t size;
1242 CHECK_VECTOR_OR_STRING (string);
1244 size = STRINGP (string) ? SCHARS (string) : ASIZE (string);
1246 if (!(0 <= from && from <= to && to <= size))
1247 args_out_of_range_3 (string, make_number (from), make_number (to));
1249 if (STRINGP (string))
1251 res = make_specified_string (SSDATA (string) + from_byte,
1252 to - from, to_byte - from_byte,
1253 STRING_MULTIBYTE (string));
1254 copy_text_properties (make_number (from), make_number (to),
1255 string, make_number (0), res, Qnil);
1257 else
1258 res = Fvector (to - from, aref_addr (string, from));
1260 return res;
1263 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1264 doc: /* Take cdr N times on LIST, return the result. */)
1265 (Lisp_Object n, Lisp_Object list)
1267 EMACS_INT i, num;
1268 CHECK_NUMBER (n);
1269 num = XINT (n);
1270 for (i = 0; i < num && !NILP (list); i++)
1272 QUIT;
1273 CHECK_LIST_CONS (list, list);
1274 list = XCDR (list);
1276 return list;
1279 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1280 doc: /* Return the Nth element of LIST.
1281 N counts from zero. If LIST is not that long, nil is returned. */)
1282 (Lisp_Object n, Lisp_Object list)
1284 return Fcar (Fnthcdr (n, list));
1287 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1288 doc: /* Return element of SEQUENCE at index N. */)
1289 (register Lisp_Object sequence, Lisp_Object n)
1291 CHECK_NUMBER (n);
1292 if (CONSP (sequence) || NILP (sequence))
1293 return Fcar (Fnthcdr (n, sequence));
1295 /* Faref signals a "not array" error, so check here. */
1296 CHECK_ARRAY (sequence, Qsequencep);
1297 return Faref (sequence, n);
1300 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1301 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1302 The value is actually the tail of LIST whose car is ELT. */)
1303 (register Lisp_Object elt, Lisp_Object list)
1305 register Lisp_Object tail;
1306 for (tail = list; CONSP (tail); tail = XCDR (tail))
1308 register Lisp_Object tem;
1309 CHECK_LIST_CONS (tail, list);
1310 tem = XCAR (tail);
1311 if (! NILP (Fequal (elt, tem)))
1312 return tail;
1313 QUIT;
1315 return Qnil;
1318 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1319 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1320 The value is actually the tail of LIST whose car is ELT. */)
1321 (register Lisp_Object elt, Lisp_Object list)
1323 while (1)
1325 if (!CONSP (list) || EQ (XCAR (list), elt))
1326 break;
1328 list = XCDR (list);
1329 if (!CONSP (list) || EQ (XCAR (list), elt))
1330 break;
1332 list = XCDR (list);
1333 if (!CONSP (list) || EQ (XCAR (list), elt))
1334 break;
1336 list = XCDR (list);
1337 QUIT;
1340 CHECK_LIST (list);
1341 return list;
1344 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1345 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1346 The value is actually the tail of LIST whose car is ELT. */)
1347 (register Lisp_Object elt, Lisp_Object list)
1349 register Lisp_Object tail;
1351 if (!FLOATP (elt))
1352 return Fmemq (elt, list);
1354 for (tail = list; CONSP (tail); tail = XCDR (tail))
1356 register Lisp_Object tem;
1357 CHECK_LIST_CONS (tail, list);
1358 tem = XCAR (tail);
1359 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0, Qnil))
1360 return tail;
1361 QUIT;
1363 return Qnil;
1366 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1367 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1368 The value is actually the first element of LIST whose car is KEY.
1369 Elements of LIST that are not conses are ignored. */)
1370 (Lisp_Object key, Lisp_Object list)
1372 while (1)
1374 if (!CONSP (list)
1375 || (CONSP (XCAR (list))
1376 && EQ (XCAR (XCAR (list)), key)))
1377 break;
1379 list = XCDR (list);
1380 if (!CONSP (list)
1381 || (CONSP (XCAR (list))
1382 && EQ (XCAR (XCAR (list)), key)))
1383 break;
1385 list = XCDR (list);
1386 if (!CONSP (list)
1387 || (CONSP (XCAR (list))
1388 && EQ (XCAR (XCAR (list)), key)))
1389 break;
1391 list = XCDR (list);
1392 QUIT;
1395 return CAR (list);
1398 /* Like Fassq but never report an error and do not allow quits.
1399 Use only on lists known never to be circular. */
1401 Lisp_Object
1402 assq_no_quit (Lisp_Object key, Lisp_Object list)
1404 while (CONSP (list)
1405 && (!CONSP (XCAR (list))
1406 || !EQ (XCAR (XCAR (list)), key)))
1407 list = XCDR (list);
1409 return CAR_SAFE (list);
1412 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1413 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1414 The value is actually the first element of LIST whose car equals KEY. */)
1415 (Lisp_Object key, Lisp_Object list)
1417 Lisp_Object car;
1419 while (1)
1421 if (!CONSP (list)
1422 || (CONSP (XCAR (list))
1423 && (car = XCAR (XCAR (list)),
1424 EQ (car, key) || !NILP (Fequal (car, key)))))
1425 break;
1427 list = XCDR (list);
1428 if (!CONSP (list)
1429 || (CONSP (XCAR (list))
1430 && (car = XCAR (XCAR (list)),
1431 EQ (car, key) || !NILP (Fequal (car, key)))))
1432 break;
1434 list = XCDR (list);
1435 if (!CONSP (list)
1436 || (CONSP (XCAR (list))
1437 && (car = XCAR (XCAR (list)),
1438 EQ (car, key) || !NILP (Fequal (car, key)))))
1439 break;
1441 list = XCDR (list);
1442 QUIT;
1445 return CAR (list);
1448 /* Like Fassoc but never report an error and do not allow quits.
1449 Use only on lists known never to be circular. */
1451 Lisp_Object
1452 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1454 while (CONSP (list)
1455 && (!CONSP (XCAR (list))
1456 || (!EQ (XCAR (XCAR (list)), key)
1457 && NILP (Fequal (XCAR (XCAR (list)), key)))))
1458 list = XCDR (list);
1460 return CONSP (list) ? XCAR (list) : Qnil;
1463 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1464 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1465 The value is actually the first element of LIST whose cdr is KEY. */)
1466 (register Lisp_Object key, Lisp_Object list)
1468 while (1)
1470 if (!CONSP (list)
1471 || (CONSP (XCAR (list))
1472 && EQ (XCDR (XCAR (list)), key)))
1473 break;
1475 list = XCDR (list);
1476 if (!CONSP (list)
1477 || (CONSP (XCAR (list))
1478 && EQ (XCDR (XCAR (list)), key)))
1479 break;
1481 list = XCDR (list);
1482 if (!CONSP (list)
1483 || (CONSP (XCAR (list))
1484 && EQ (XCDR (XCAR (list)), key)))
1485 break;
1487 list = XCDR (list);
1488 QUIT;
1491 return CAR (list);
1494 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1495 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1496 The value is actually the first element of LIST whose cdr equals KEY. */)
1497 (Lisp_Object key, Lisp_Object list)
1499 Lisp_Object cdr;
1501 while (1)
1503 if (!CONSP (list)
1504 || (CONSP (XCAR (list))
1505 && (cdr = XCDR (XCAR (list)),
1506 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1507 break;
1509 list = XCDR (list);
1510 if (!CONSP (list)
1511 || (CONSP (XCAR (list))
1512 && (cdr = XCDR (XCAR (list)),
1513 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1514 break;
1516 list = XCDR (list);
1517 if (!CONSP (list)
1518 || (CONSP (XCAR (list))
1519 && (cdr = XCDR (XCAR (list)),
1520 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1521 break;
1523 list = XCDR (list);
1524 QUIT;
1527 return CAR (list);
1530 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1531 doc: /* Delete members of LIST which are `eq' to ELT, and return the result.
1532 More precisely, this function skips any members `eq' to ELT at the
1533 front of LIST, then removes members `eq' to ELT from the remaining
1534 sublist by modifying its list structure, then returns the resulting
1535 list.
1537 Write `(setq foo (delq element foo))' to be sure of correctly changing
1538 the value of a list `foo'. */)
1539 (register Lisp_Object elt, Lisp_Object list)
1541 Lisp_Object tail, tortoise, prev = Qnil;
1542 bool skip;
1544 FOR_EACH_TAIL (tail, list, tortoise, skip)
1546 Lisp_Object tem = XCAR (tail);
1547 if (EQ (elt, tem))
1549 if (NILP (prev))
1550 list = XCDR (tail);
1551 else
1552 Fsetcdr (prev, XCDR (tail));
1554 else
1555 prev = tail;
1557 return list;
1560 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1561 doc: /* Delete members of SEQ which are `equal' to ELT, and return the result.
1562 SEQ must be a sequence (i.e. a list, a vector, or a string).
1563 The return value is a sequence of the same type.
1565 If SEQ is a list, this behaves like `delq', except that it compares
1566 with `equal' instead of `eq'. In particular, it may remove elements
1567 by altering the list structure.
1569 If SEQ is not a list, deletion is never performed destructively;
1570 instead this function creates and returns a new vector or string.
1572 Write `(setq foo (delete element foo))' to be sure of correctly
1573 changing the value of a sequence `foo'. */)
1574 (Lisp_Object elt, Lisp_Object seq)
1576 if (VECTORP (seq))
1578 ptrdiff_t i, n;
1580 for (i = n = 0; i < ASIZE (seq); ++i)
1581 if (NILP (Fequal (AREF (seq, i), elt)))
1582 ++n;
1584 if (n != ASIZE (seq))
1586 struct Lisp_Vector *p = allocate_vector (n);
1588 for (i = n = 0; i < ASIZE (seq); ++i)
1589 if (NILP (Fequal (AREF (seq, i), elt)))
1590 p->contents[n++] = AREF (seq, i);
1592 XSETVECTOR (seq, p);
1595 else if (STRINGP (seq))
1597 ptrdiff_t i, ibyte, nchars, nbytes, cbytes;
1598 int c;
1600 for (i = nchars = nbytes = ibyte = 0;
1601 i < SCHARS (seq);
1602 ++i, ibyte += cbytes)
1604 if (STRING_MULTIBYTE (seq))
1606 c = STRING_CHAR (SDATA (seq) + ibyte);
1607 cbytes = CHAR_BYTES (c);
1609 else
1611 c = SREF (seq, i);
1612 cbytes = 1;
1615 if (!INTEGERP (elt) || c != XINT (elt))
1617 ++nchars;
1618 nbytes += cbytes;
1622 if (nchars != SCHARS (seq))
1624 Lisp_Object tem;
1626 tem = make_uninit_multibyte_string (nchars, nbytes);
1627 if (!STRING_MULTIBYTE (seq))
1628 STRING_SET_UNIBYTE (tem);
1630 for (i = nchars = nbytes = ibyte = 0;
1631 i < SCHARS (seq);
1632 ++i, ibyte += cbytes)
1634 if (STRING_MULTIBYTE (seq))
1636 c = STRING_CHAR (SDATA (seq) + ibyte);
1637 cbytes = CHAR_BYTES (c);
1639 else
1641 c = SREF (seq, i);
1642 cbytes = 1;
1645 if (!INTEGERP (elt) || c != XINT (elt))
1647 unsigned char *from = SDATA (seq) + ibyte;
1648 unsigned char *to = SDATA (tem) + nbytes;
1649 ptrdiff_t n;
1651 ++nchars;
1652 nbytes += cbytes;
1654 for (n = cbytes; n--; )
1655 *to++ = *from++;
1659 seq = tem;
1662 else
1664 Lisp_Object tail, prev;
1666 for (tail = seq, prev = Qnil; CONSP (tail); tail = XCDR (tail))
1668 CHECK_LIST_CONS (tail, seq);
1670 if (!NILP (Fequal (elt, XCAR (tail))))
1672 if (NILP (prev))
1673 seq = XCDR (tail);
1674 else
1675 Fsetcdr (prev, XCDR (tail));
1677 else
1678 prev = tail;
1679 QUIT;
1683 return seq;
1686 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1687 doc: /* Reverse LIST by modifying cdr pointers.
1688 Return the reversed list. Expects a properly nil-terminated list. */)
1689 (Lisp_Object list)
1691 register Lisp_Object prev, tail, next;
1693 if (NILP (list)) return list;
1694 prev = Qnil;
1695 tail = list;
1696 while (!NILP (tail))
1698 QUIT;
1699 CHECK_LIST_CONS (tail, tail);
1700 next = XCDR (tail);
1701 Fsetcdr (tail, prev);
1702 prev = tail;
1703 tail = next;
1705 return prev;
1708 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1709 doc: /* Reverse LIST, copying. Return the reversed list.
1710 See also the function `nreverse', which is used more often. */)
1711 (Lisp_Object list)
1713 Lisp_Object new;
1715 for (new = Qnil; CONSP (list); list = XCDR (list))
1717 QUIT;
1718 new = Fcons (XCAR (list), new);
1720 CHECK_LIST_END (list, list);
1721 return new;
1724 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
1725 doc: /* Sort LIST, stably, comparing elements using PREDICATE.
1726 Returns the sorted list. LIST is modified by side effects.
1727 PREDICATE is called with two elements of LIST, and should return non-nil
1728 if the first element should sort before the second. */)
1729 (Lisp_Object list, Lisp_Object predicate)
1731 Lisp_Object front, back;
1732 register Lisp_Object len, tem;
1733 struct gcpro gcpro1, gcpro2;
1734 EMACS_INT length;
1736 front = list;
1737 len = Flength (list);
1738 length = XINT (len);
1739 if (length < 2)
1740 return list;
1742 XSETINT (len, (length / 2) - 1);
1743 tem = Fnthcdr (len, list);
1744 back = Fcdr (tem);
1745 Fsetcdr (tem, Qnil);
1747 GCPRO2 (front, back);
1748 front = Fsort (front, predicate);
1749 back = Fsort (back, predicate);
1750 UNGCPRO;
1751 return merge (front, back, predicate);
1754 Lisp_Object
1755 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
1757 Lisp_Object value;
1758 register Lisp_Object tail;
1759 Lisp_Object tem;
1760 register Lisp_Object l1, l2;
1761 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1763 l1 = org_l1;
1764 l2 = org_l2;
1765 tail = Qnil;
1766 value = Qnil;
1768 /* It is sufficient to protect org_l1 and org_l2.
1769 When l1 and l2 are updated, we copy the new values
1770 back into the org_ vars. */
1771 GCPRO4 (org_l1, org_l2, pred, value);
1773 while (1)
1775 if (NILP (l1))
1777 UNGCPRO;
1778 if (NILP (tail))
1779 return l2;
1780 Fsetcdr (tail, l2);
1781 return value;
1783 if (NILP (l2))
1785 UNGCPRO;
1786 if (NILP (tail))
1787 return l1;
1788 Fsetcdr (tail, l1);
1789 return value;
1791 tem = call2 (pred, Fcar (l2), Fcar (l1));
1792 if (NILP (tem))
1794 tem = l1;
1795 l1 = Fcdr (l1);
1796 org_l1 = l1;
1798 else
1800 tem = l2;
1801 l2 = Fcdr (l2);
1802 org_l2 = l2;
1804 if (NILP (tail))
1805 value = tem;
1806 else
1807 Fsetcdr (tail, tem);
1808 tail = tem;
1813 /* This does not check for quits. That is safe since it must terminate. */
1815 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
1816 doc: /* Extract a value from a property list.
1817 PLIST is a property list, which is a list of the form
1818 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1819 corresponding to the given PROP, or nil if PROP is not one of the
1820 properties on the list. This function never signals an error. */)
1821 (Lisp_Object plist, Lisp_Object prop)
1823 Lisp_Object tail, halftail;
1825 /* halftail is used to detect circular lists. */
1826 tail = halftail = plist;
1827 while (CONSP (tail) && CONSP (XCDR (tail)))
1829 if (EQ (prop, XCAR (tail)))
1830 return XCAR (XCDR (tail));
1832 tail = XCDR (XCDR (tail));
1833 halftail = XCDR (halftail);
1834 if (EQ (tail, halftail))
1835 break;
1838 return Qnil;
1841 DEFUN ("get", Fget, Sget, 2, 2, 0,
1842 doc: /* Return the value of SYMBOL's PROPNAME property.
1843 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
1844 (Lisp_Object symbol, Lisp_Object propname)
1846 CHECK_SYMBOL (symbol);
1847 return Fplist_get (XSYMBOL (symbol)->plist, propname);
1850 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
1851 doc: /* Change value in PLIST of PROP to VAL.
1852 PLIST is a property list, which is a list of the form
1853 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
1854 If PROP is already a property on the list, its value is set to VAL,
1855 otherwise the new PROP VAL pair is added. The new plist is returned;
1856 use `(setq x (plist-put x prop val))' to be sure to use the new value.
1857 The PLIST is modified by side effects. */)
1858 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1860 register Lisp_Object tail, prev;
1861 Lisp_Object newcell;
1862 prev = Qnil;
1863 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1864 tail = XCDR (XCDR (tail)))
1866 if (EQ (prop, XCAR (tail)))
1868 Fsetcar (XCDR (tail), val);
1869 return plist;
1872 prev = tail;
1873 QUIT;
1875 newcell = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
1876 if (NILP (prev))
1877 return newcell;
1878 else
1879 Fsetcdr (XCDR (prev), newcell);
1880 return plist;
1883 DEFUN ("put", Fput, Sput, 3, 3, 0,
1884 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
1885 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
1886 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
1888 CHECK_SYMBOL (symbol);
1889 set_symbol_plist
1890 (symbol, Fplist_put (XSYMBOL (symbol)->plist, propname, value));
1891 return value;
1894 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
1895 doc: /* Extract a value from a property list, comparing with `equal'.
1896 PLIST is a property list, which is a list of the form
1897 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1898 corresponding to the given PROP, or nil if PROP is not
1899 one of the properties on the list. */)
1900 (Lisp_Object plist, Lisp_Object prop)
1902 Lisp_Object tail;
1904 for (tail = plist;
1905 CONSP (tail) && CONSP (XCDR (tail));
1906 tail = XCDR (XCDR (tail)))
1908 if (! NILP (Fequal (prop, XCAR (tail))))
1909 return XCAR (XCDR (tail));
1911 QUIT;
1914 CHECK_LIST_END (tail, prop);
1916 return Qnil;
1919 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
1920 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
1921 PLIST is a property list, which is a list of the form
1922 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
1923 If PROP is already a property on the list, its value is set to VAL,
1924 otherwise the new PROP VAL pair is added. The new plist is returned;
1925 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
1926 The PLIST is modified by side effects. */)
1927 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1929 register Lisp_Object tail, prev;
1930 Lisp_Object newcell;
1931 prev = Qnil;
1932 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1933 tail = XCDR (XCDR (tail)))
1935 if (! NILP (Fequal (prop, XCAR (tail))))
1937 Fsetcar (XCDR (tail), val);
1938 return plist;
1941 prev = tail;
1942 QUIT;
1944 newcell = list2 (prop, val);
1945 if (NILP (prev))
1946 return newcell;
1947 else
1948 Fsetcdr (XCDR (prev), newcell);
1949 return plist;
1952 DEFUN ("eql", Feql, Seql, 2, 2, 0,
1953 doc: /* Return t if the two args are the same Lisp object.
1954 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
1955 (Lisp_Object obj1, Lisp_Object obj2)
1957 if (FLOATP (obj1))
1958 return internal_equal (obj1, obj2, 0, 0, Qnil) ? Qt : Qnil;
1959 else
1960 return EQ (obj1, obj2) ? Qt : Qnil;
1963 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
1964 doc: /* Return t if two Lisp objects have similar structure and contents.
1965 They must have the same data type.
1966 Conses are compared by comparing the cars and the cdrs.
1967 Vectors and strings are compared element by element.
1968 Numbers are compared by value, but integers cannot equal floats.
1969 (Use `=' if you want integers and floats to be able to be equal.)
1970 Symbols must match exactly. */)
1971 (register Lisp_Object o1, Lisp_Object o2)
1973 return internal_equal (o1, o2, 0, 0, Qnil) ? Qt : Qnil;
1976 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
1977 doc: /* Return t if two Lisp objects have similar structure and contents.
1978 This is like `equal' except that it compares the text properties
1979 of strings. (`equal' ignores text properties.) */)
1980 (register Lisp_Object o1, Lisp_Object o2)
1982 return internal_equal (o1, o2, 0, 1, Qnil) ? Qt : Qnil;
1985 /* DEPTH is current depth of recursion. Signal an error if it
1986 gets too deep.
1987 PROPS means compare string text properties too. */
1989 static bool
1990 internal_equal (Lisp_Object o1, Lisp_Object o2, int depth, bool props,
1991 Lisp_Object ht)
1993 if (depth > 10)
1995 if (depth > 200)
1996 error ("Stack overflow in equal");
1997 if (NILP (ht))
1999 Lisp_Object args[2] = { QCtest, Qeq };
2000 ht = Fmake_hash_table (2, args);
2002 switch (XTYPE (o1))
2004 case Lisp_Cons: case Lisp_Misc: case Lisp_Vectorlike:
2006 struct Lisp_Hash_Table *h = XHASH_TABLE (ht);
2007 EMACS_UINT hash;
2008 ptrdiff_t i = hash_lookup (h, o1, &hash);
2009 if (i >= 0)
2010 { /* `o1' was seen already. */
2011 Lisp_Object o2s = HASH_VALUE (h, i);
2012 if (!NILP (Fmemq (o2, o2s)))
2013 return 1;
2014 else
2015 set_hash_value_slot (h, i, Fcons (o2, o2s));
2017 else
2018 hash_put (h, o1, Fcons (o2, Qnil), hash);
2020 default: ;
2024 tail_recurse:
2025 QUIT;
2026 if (EQ (o1, o2))
2027 return 1;
2028 if (XTYPE (o1) != XTYPE (o2))
2029 return 0;
2031 switch (XTYPE (o1))
2033 case Lisp_Float:
2035 double d1, d2;
2037 d1 = extract_float (o1);
2038 d2 = extract_float (o2);
2039 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2040 though they are not =. */
2041 return d1 == d2 || (d1 != d1 && d2 != d2);
2044 case Lisp_Cons:
2045 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1, props, ht))
2046 return 0;
2047 o1 = XCDR (o1);
2048 o2 = XCDR (o2);
2049 /* FIXME: This inf-loops in a circular list! */
2050 goto tail_recurse;
2052 case Lisp_Misc:
2053 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2054 return 0;
2055 if (OVERLAYP (o1))
2057 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2058 depth + 1, props, ht)
2059 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2060 depth + 1, props, ht))
2061 return 0;
2062 o1 = XOVERLAY (o1)->plist;
2063 o2 = XOVERLAY (o2)->plist;
2064 goto tail_recurse;
2066 if (MARKERP (o1))
2068 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2069 && (XMARKER (o1)->buffer == 0
2070 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2072 break;
2074 case Lisp_Vectorlike:
2076 register int i;
2077 ptrdiff_t size = ASIZE (o1);
2078 /* Pseudovectors have the type encoded in the size field, so this test
2079 actually checks that the objects have the same type as well as the
2080 same size. */
2081 if (ASIZE (o2) != size)
2082 return 0;
2083 /* Boolvectors are compared much like strings. */
2084 if (BOOL_VECTOR_P (o1))
2086 EMACS_INT size = bool_vector_size (o1);
2087 if (size != bool_vector_size (o2))
2088 return 0;
2089 if (memcmp (bool_vector_data (o1), bool_vector_data (o2),
2090 bool_vector_bytes (size)))
2091 return 0;
2092 return 1;
2094 if (WINDOW_CONFIGURATIONP (o1))
2095 return compare_window_configurations (o1, o2, 0);
2097 /* Aside from them, only true vectors, char-tables, compiled
2098 functions, and fonts (font-spec, font-entity, font-object)
2099 are sensible to compare, so eliminate the others now. */
2100 if (size & PSEUDOVECTOR_FLAG)
2102 if (((size & PVEC_TYPE_MASK) >> PSEUDOVECTOR_AREA_BITS)
2103 < PVEC_COMPILED)
2104 return 0;
2105 size &= PSEUDOVECTOR_SIZE_MASK;
2107 for (i = 0; i < size; i++)
2109 Lisp_Object v1, v2;
2110 v1 = AREF (o1, i);
2111 v2 = AREF (o2, i);
2112 if (!internal_equal (v1, v2, depth + 1, props, ht))
2113 return 0;
2115 return 1;
2117 break;
2119 case Lisp_String:
2120 if (SCHARS (o1) != SCHARS (o2))
2121 return 0;
2122 if (SBYTES (o1) != SBYTES (o2))
2123 return 0;
2124 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2125 return 0;
2126 if (props && !compare_string_intervals (o1, o2))
2127 return 0;
2128 return 1;
2130 default:
2131 break;
2134 return 0;
2138 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2139 doc: /* Store each element of ARRAY with ITEM.
2140 ARRAY is a vector, string, char-table, or bool-vector. */)
2141 (Lisp_Object array, Lisp_Object item)
2143 register ptrdiff_t size, idx;
2145 if (VECTORP (array))
2146 for (idx = 0, size = ASIZE (array); idx < size; idx++)
2147 ASET (array, idx, item);
2148 else if (CHAR_TABLE_P (array))
2150 int i;
2152 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2153 set_char_table_contents (array, i, item);
2154 set_char_table_defalt (array, item);
2156 else if (STRINGP (array))
2158 register unsigned char *p = SDATA (array);
2159 int charval;
2160 CHECK_CHARACTER (item);
2161 charval = XFASTINT (item);
2162 size = SCHARS (array);
2163 if (STRING_MULTIBYTE (array))
2165 unsigned char str[MAX_MULTIBYTE_LENGTH];
2166 int len = CHAR_STRING (charval, str);
2167 ptrdiff_t size_byte = SBYTES (array);
2169 if (INT_MULTIPLY_OVERFLOW (SCHARS (array), len)
2170 || SCHARS (array) * len != size_byte)
2171 error ("Attempt to change byte length of a string");
2172 for (idx = 0; idx < size_byte; idx++)
2173 *p++ = str[idx % len];
2175 else
2176 for (idx = 0; idx < size; idx++)
2177 p[idx] = charval;
2179 else if (BOOL_VECTOR_P (array))
2180 return bool_vector_fill (array, item);
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 dummy = call1 (fn, bool_vector_ref (seq, i));
2293 if (vals)
2294 vals[i] = dummy;
2297 else if (STRINGP (seq))
2299 ptrdiff_t i_byte;
2301 for (i = 0, i_byte = 0; i < leni;)
2303 int c;
2304 ptrdiff_t i_before = i;
2306 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2307 XSETFASTINT (dummy, c);
2308 dummy = call1 (fn, dummy);
2309 if (vals)
2310 vals[i_before] = dummy;
2313 else /* Must be a list, since Flength did not get an error */
2315 tail = seq;
2316 for (i = 0; i < leni && CONSP (tail); i++)
2318 dummy = call1 (fn, XCAR (tail));
2319 if (vals)
2320 vals[i] = dummy;
2321 tail = XCDR (tail);
2325 UNGCPRO;
2328 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2329 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2330 In between each pair of results, stick in SEPARATOR. Thus, " " as
2331 SEPARATOR results in spaces between the values returned by FUNCTION.
2332 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2333 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2335 Lisp_Object len;
2336 register EMACS_INT leni;
2337 EMACS_INT nargs;
2338 ptrdiff_t i;
2339 register Lisp_Object *args;
2340 struct gcpro gcpro1;
2341 Lisp_Object ret;
2342 USE_SAFE_ALLOCA;
2344 len = Flength (sequence);
2345 if (CHAR_TABLE_P (sequence))
2346 wrong_type_argument (Qlistp, sequence);
2347 leni = XINT (len);
2348 nargs = leni + leni - 1;
2349 if (nargs < 0) return empty_unibyte_string;
2351 SAFE_ALLOCA_LISP (args, nargs);
2353 GCPRO1 (separator);
2354 mapcar1 (leni, args, function, sequence);
2355 UNGCPRO;
2357 for (i = leni - 1; i > 0; i--)
2358 args[i + i] = args[i];
2360 for (i = 1; i < nargs; i += 2)
2361 args[i] = separator;
2363 ret = Fconcat (nargs, args);
2364 SAFE_FREE ();
2366 return ret;
2369 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2370 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2371 The result is a list just as long as SEQUENCE.
2372 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2373 (Lisp_Object function, Lisp_Object sequence)
2375 register Lisp_Object len;
2376 register EMACS_INT leni;
2377 register Lisp_Object *args;
2378 Lisp_Object ret;
2379 USE_SAFE_ALLOCA;
2381 len = Flength (sequence);
2382 if (CHAR_TABLE_P (sequence))
2383 wrong_type_argument (Qlistp, sequence);
2384 leni = XFASTINT (len);
2386 SAFE_ALLOCA_LISP (args, leni);
2388 mapcar1 (leni, args, function, sequence);
2390 ret = Flist (leni, args);
2391 SAFE_FREE ();
2393 return ret;
2396 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2397 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2398 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2399 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2400 (Lisp_Object function, Lisp_Object sequence)
2402 register EMACS_INT leni;
2404 leni = XFASTINT (Flength (sequence));
2405 if (CHAR_TABLE_P (sequence))
2406 wrong_type_argument (Qlistp, sequence);
2407 mapcar1 (leni, 0, function, sequence);
2409 return sequence;
2412 /* This is how C code calls `yes-or-no-p' and allows the user
2413 to redefined it.
2415 Anything that calls this function must protect from GC! */
2417 Lisp_Object
2418 do_yes_or_no_p (Lisp_Object prompt)
2420 return call1 (intern ("yes-or-no-p"), prompt);
2423 /* Anything that calls this function must protect from GC! */
2425 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2426 doc: /* Ask user a yes-or-no question. Return t if answer is yes.
2427 PROMPT is the string to display to ask the question. It should end in
2428 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2430 The user must confirm the answer with RET, and can edit it until it
2431 has been confirmed.
2433 If dialog boxes are supported, a dialog box will be used
2434 if `last-nonmenu-event' is nil, and `use-dialog-box' is non-nil. */)
2435 (Lisp_Object prompt)
2437 register Lisp_Object ans;
2438 Lisp_Object args[2];
2439 struct gcpro gcpro1;
2441 CHECK_STRING (prompt);
2443 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2444 && use_dialog_box)
2446 Lisp_Object pane, menu, obj;
2447 redisplay_preserve_echo_area (4);
2448 pane = list2 (Fcons (build_string ("Yes"), Qt),
2449 Fcons (build_string ("No"), Qnil));
2450 GCPRO1 (pane);
2451 menu = Fcons (prompt, pane);
2452 obj = Fx_popup_dialog (Qt, menu, Qnil);
2453 UNGCPRO;
2454 return obj;
2457 args[0] = prompt;
2458 args[1] = build_string ("(yes or no) ");
2459 prompt = Fconcat (2, args);
2461 GCPRO1 (prompt);
2463 while (1)
2465 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2466 Qyes_or_no_p_history, Qnil,
2467 Qnil));
2468 if (SCHARS (ans) == 3 && !strcmp (SSDATA (ans), "yes"))
2470 UNGCPRO;
2471 return Qt;
2473 if (SCHARS (ans) == 2 && !strcmp (SSDATA (ans), "no"))
2475 UNGCPRO;
2476 return Qnil;
2479 Fding (Qnil);
2480 Fdiscard_input ();
2481 message1 ("Please answer yes or no.");
2482 Fsleep_for (make_number (2), Qnil);
2486 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2487 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2489 Each of the three load averages is multiplied by 100, then converted
2490 to integer.
2492 When USE-FLOATS is non-nil, floats will be used instead of integers.
2493 These floats are not multiplied by 100.
2495 If the 5-minute or 15-minute load averages are not available, return a
2496 shortened list, containing only those averages which are available.
2498 An error is thrown if the load average can't be obtained. In some
2499 cases making it work would require Emacs being installed setuid or
2500 setgid so that it can read kernel information, and that usually isn't
2501 advisable. */)
2502 (Lisp_Object use_floats)
2504 double load_ave[3];
2505 int loads = getloadavg (load_ave, 3);
2506 Lisp_Object ret = Qnil;
2508 if (loads < 0)
2509 error ("load-average not implemented for this operating system");
2511 while (loads-- > 0)
2513 Lisp_Object load = (NILP (use_floats)
2514 ? make_number (100.0 * load_ave[loads])
2515 : make_float (load_ave[loads]));
2516 ret = Fcons (load, ret);
2519 return ret;
2522 static Lisp_Object Qsubfeatures;
2524 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2525 doc: /* Return t if FEATURE is present in this Emacs.
2527 Use this to conditionalize execution of lisp code based on the
2528 presence or absence of Emacs or environment extensions.
2529 Use `provide' to declare that a feature is available. This function
2530 looks at the value of the variable `features'. The optional argument
2531 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2532 (Lisp_Object feature, Lisp_Object subfeature)
2534 register Lisp_Object tem;
2535 CHECK_SYMBOL (feature);
2536 tem = Fmemq (feature, Vfeatures);
2537 if (!NILP (tem) && !NILP (subfeature))
2538 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2539 return (NILP (tem)) ? Qnil : Qt;
2542 static Lisp_Object Qfuncall;
2544 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2545 doc: /* Announce that FEATURE is a feature of the current Emacs.
2546 The optional argument SUBFEATURES should be a list of symbols listing
2547 particular subfeatures supported in this version of FEATURE. */)
2548 (Lisp_Object feature, Lisp_Object subfeatures)
2550 register Lisp_Object tem;
2551 CHECK_SYMBOL (feature);
2552 CHECK_LIST (subfeatures);
2553 if (!NILP (Vautoload_queue))
2554 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2555 Vautoload_queue);
2556 tem = Fmemq (feature, Vfeatures);
2557 if (NILP (tem))
2558 Vfeatures = Fcons (feature, Vfeatures);
2559 if (!NILP (subfeatures))
2560 Fput (feature, Qsubfeatures, subfeatures);
2561 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2563 /* Run any load-hooks for this file. */
2564 tem = Fassq (feature, Vafter_load_alist);
2565 if (CONSP (tem))
2566 Fmapc (Qfuncall, XCDR (tem));
2568 return feature;
2571 /* `require' and its subroutines. */
2573 /* List of features currently being require'd, innermost first. */
2575 static Lisp_Object require_nesting_list;
2577 static void
2578 require_unwind (Lisp_Object old_value)
2580 require_nesting_list = old_value;
2583 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2584 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2585 If FEATURE is not a member of the list `features', then the feature
2586 is not loaded; so load the file FILENAME.
2587 If FILENAME is omitted, the printname of FEATURE is used as the file name,
2588 and `load' will try to load this name appended with the suffix `.elc' or
2589 `.el', in that order. The name without appended suffix will not be used.
2590 See `get-load-suffixes' for the complete list of suffixes.
2591 If the optional third argument NOERROR is non-nil,
2592 then return nil if the file is not found instead of signaling an error.
2593 Normally the return value is FEATURE.
2594 The normal messages at start and end of loading FILENAME are suppressed. */)
2595 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2597 Lisp_Object tem;
2598 struct gcpro gcpro1, gcpro2;
2599 bool from_file = load_in_progress;
2601 CHECK_SYMBOL (feature);
2603 /* Record the presence of `require' in this file
2604 even if the feature specified is already loaded.
2605 But not more than once in any file,
2606 and not when we aren't loading or reading from a file. */
2607 if (!from_file)
2608 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2609 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2610 from_file = 1;
2612 if (from_file)
2614 tem = Fcons (Qrequire, feature);
2615 if (NILP (Fmember (tem, Vcurrent_load_list)))
2616 LOADHIST_ATTACH (tem);
2618 tem = Fmemq (feature, Vfeatures);
2620 if (NILP (tem))
2622 ptrdiff_t count = SPECPDL_INDEX ();
2623 int nesting = 0;
2625 /* This is to make sure that loadup.el gives a clear picture
2626 of what files are preloaded and when. */
2627 if (! NILP (Vpurify_flag))
2628 error ("(require %s) while preparing to dump",
2629 SDATA (SYMBOL_NAME (feature)));
2631 /* A certain amount of recursive `require' is legitimate,
2632 but if we require the same feature recursively 3 times,
2633 signal an error. */
2634 tem = require_nesting_list;
2635 while (! NILP (tem))
2637 if (! NILP (Fequal (feature, XCAR (tem))))
2638 nesting++;
2639 tem = XCDR (tem);
2641 if (nesting > 3)
2642 error ("Recursive `require' for feature `%s'",
2643 SDATA (SYMBOL_NAME (feature)));
2645 /* Update the list for any nested `require's that occur. */
2646 record_unwind_protect (require_unwind, require_nesting_list);
2647 require_nesting_list = Fcons (feature, require_nesting_list);
2649 /* Value saved here is to be restored into Vautoload_queue */
2650 record_unwind_protect (un_autoload, Vautoload_queue);
2651 Vautoload_queue = Qt;
2653 /* Load the file. */
2654 GCPRO2 (feature, filename);
2655 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2656 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2657 UNGCPRO;
2659 /* If load failed entirely, return nil. */
2660 if (NILP (tem))
2661 return unbind_to (count, Qnil);
2663 tem = Fmemq (feature, Vfeatures);
2664 if (NILP (tem))
2665 error ("Required feature `%s' was not provided",
2666 SDATA (SYMBOL_NAME (feature)));
2668 /* Once loading finishes, don't undo it. */
2669 Vautoload_queue = Qt;
2670 feature = unbind_to (count, feature);
2673 return feature;
2676 /* Primitives for work of the "widget" library.
2677 In an ideal world, this section would not have been necessary.
2678 However, lisp function calls being as slow as they are, it turns
2679 out that some functions in the widget library (wid-edit.el) are the
2680 bottleneck of Widget operation. Here is their translation to C,
2681 for the sole reason of efficiency. */
2683 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2684 doc: /* Return non-nil if PLIST has the property PROP.
2685 PLIST is a property list, which is a list of the form
2686 \(PROP1 VALUE1 PROP2 VALUE2 ...\). PROP is a symbol.
2687 Unlike `plist-get', this allows you to distinguish between a missing
2688 property and a property with the value nil.
2689 The value is actually the tail of PLIST whose car is PROP. */)
2690 (Lisp_Object plist, Lisp_Object prop)
2692 while (CONSP (plist) && !EQ (XCAR (plist), prop))
2694 QUIT;
2695 plist = XCDR (plist);
2696 plist = CDR (plist);
2698 return plist;
2701 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2702 doc: /* In WIDGET, set PROPERTY to VALUE.
2703 The value can later be retrieved with `widget-get'. */)
2704 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2706 CHECK_CONS (widget);
2707 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
2708 return value;
2711 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
2712 doc: /* In WIDGET, get the value of PROPERTY.
2713 The value could either be specified when the widget was created, or
2714 later with `widget-put'. */)
2715 (Lisp_Object widget, Lisp_Object property)
2717 Lisp_Object tmp;
2719 while (1)
2721 if (NILP (widget))
2722 return Qnil;
2723 CHECK_CONS (widget);
2724 tmp = Fplist_member (XCDR (widget), property);
2725 if (CONSP (tmp))
2727 tmp = XCDR (tmp);
2728 return CAR (tmp);
2730 tmp = XCAR (widget);
2731 if (NILP (tmp))
2732 return Qnil;
2733 widget = Fget (tmp, Qwidget_type);
2737 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
2738 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2739 ARGS are passed as extra arguments to the function.
2740 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2741 (ptrdiff_t nargs, Lisp_Object *args)
2743 /* This function can GC. */
2744 Lisp_Object newargs[3];
2745 struct gcpro gcpro1, gcpro2;
2746 Lisp_Object result;
2748 newargs[0] = Fwidget_get (args[0], args[1]);
2749 newargs[1] = args[0];
2750 newargs[2] = Flist (nargs - 2, args + 2);
2751 GCPRO2 (newargs[0], newargs[2]);
2752 result = Fapply (3, newargs);
2753 UNGCPRO;
2754 return result;
2757 #ifdef HAVE_LANGINFO_CODESET
2758 #include <langinfo.h>
2759 #endif
2761 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
2762 doc: /* Access locale data ITEM for the current C locale, if available.
2763 ITEM should be one of the following:
2765 `codeset', returning the character set as a string (locale item CODESET);
2767 `days', returning a 7-element vector of day names (locale items DAY_n);
2769 `months', returning a 12-element vector of month names (locale items MON_n);
2771 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
2772 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
2774 If the system can't provide such information through a call to
2775 `nl_langinfo', or if ITEM isn't from the list above, return nil.
2777 See also Info node `(libc)Locales'.
2779 The data read from the system are decoded using `locale-coding-system'. */)
2780 (Lisp_Object item)
2782 char *str = NULL;
2783 #ifdef HAVE_LANGINFO_CODESET
2784 Lisp_Object val;
2785 if (EQ (item, Qcodeset))
2787 str = nl_langinfo (CODESET);
2788 return build_string (str);
2790 #ifdef DAY_1
2791 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
2793 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
2794 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
2795 int i;
2796 struct gcpro gcpro1;
2797 GCPRO1 (v);
2798 synchronize_system_time_locale ();
2799 for (i = 0; i < 7; i++)
2801 str = nl_langinfo (days[i]);
2802 val = build_unibyte_string (str);
2803 /* Fixme: Is this coding system necessarily right, even if
2804 it is consistent with CODESET? If not, what to do? */
2805 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
2806 0));
2808 UNGCPRO;
2809 return v;
2811 #endif /* DAY_1 */
2812 #ifdef MON_1
2813 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
2815 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
2816 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
2817 MON_8, MON_9, MON_10, MON_11, MON_12};
2818 int i;
2819 struct gcpro gcpro1;
2820 GCPRO1 (v);
2821 synchronize_system_time_locale ();
2822 for (i = 0; i < 12; i++)
2824 str = nl_langinfo (months[i]);
2825 val = build_unibyte_string (str);
2826 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
2827 0));
2829 UNGCPRO;
2830 return v;
2832 #endif /* MON_1 */
2833 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
2834 but is in the locale files. This could be used by ps-print. */
2835 #ifdef PAPER_WIDTH
2836 else if (EQ (item, Qpaper))
2837 return list2i (nl_langinfo (PAPER_WIDTH), nl_langinfo (PAPER_HEIGHT));
2838 #endif /* PAPER_WIDTH */
2839 #endif /* HAVE_LANGINFO_CODESET*/
2840 return Qnil;
2843 /* base64 encode/decode functions (RFC 2045).
2844 Based on code from GNU recode. */
2846 #define MIME_LINE_LENGTH 76
2848 #define IS_ASCII(Character) \
2849 ((Character) < 128)
2850 #define IS_BASE64(Character) \
2851 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
2852 #define IS_BASE64_IGNORABLE(Character) \
2853 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
2854 || (Character) == '\f' || (Character) == '\r')
2856 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
2857 character or return retval if there are no characters left to
2858 process. */
2859 #define READ_QUADRUPLET_BYTE(retval) \
2860 do \
2862 if (i == length) \
2864 if (nchars_return) \
2865 *nchars_return = nchars; \
2866 return (retval); \
2868 c = from[i++]; \
2870 while (IS_BASE64_IGNORABLE (c))
2872 /* Table of characters coding the 64 values. */
2873 static const char base64_value_to_char[64] =
2875 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
2876 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
2877 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
2878 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
2879 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
2880 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
2881 '8', '9', '+', '/' /* 60-63 */
2884 /* Table of base64 values for first 128 characters. */
2885 static const short base64_char_to_value[128] =
2887 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
2888 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
2889 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
2890 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
2891 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
2892 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
2893 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
2894 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
2895 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
2896 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
2897 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
2898 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
2899 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
2902 /* The following diagram shows the logical steps by which three octets
2903 get transformed into four base64 characters.
2905 .--------. .--------. .--------.
2906 |aaaaaabb| |bbbbcccc| |ccdddddd|
2907 `--------' `--------' `--------'
2908 6 2 4 4 2 6
2909 .--------+--------+--------+--------.
2910 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
2911 `--------+--------+--------+--------'
2913 .--------+--------+--------+--------.
2914 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
2915 `--------+--------+--------+--------'
2917 The octets are divided into 6 bit chunks, which are then encoded into
2918 base64 characters. */
2921 static ptrdiff_t base64_encode_1 (const char *, char *, ptrdiff_t, bool, bool);
2922 static ptrdiff_t base64_decode_1 (const char *, char *, ptrdiff_t, bool,
2923 ptrdiff_t *);
2925 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
2926 2, 3, "r",
2927 doc: /* Base64-encode the region between BEG and END.
2928 Return the length of the encoded text.
2929 Optional third argument NO-LINE-BREAK means do not break long lines
2930 into shorter lines. */)
2931 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
2933 char *encoded;
2934 ptrdiff_t allength, length;
2935 ptrdiff_t ibeg, iend, encoded_length;
2936 ptrdiff_t old_pos = PT;
2937 USE_SAFE_ALLOCA;
2939 validate_region (&beg, &end);
2941 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
2942 iend = CHAR_TO_BYTE (XFASTINT (end));
2943 move_gap_both (XFASTINT (beg), ibeg);
2945 /* We need to allocate enough room for encoding the text.
2946 We need 33 1/3% more space, plus a newline every 76
2947 characters, and then we round up. */
2948 length = iend - ibeg;
2949 allength = length + length/3 + 1;
2950 allength += allength / MIME_LINE_LENGTH + 1 + 6;
2952 encoded = SAFE_ALLOCA (allength);
2953 encoded_length = base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg),
2954 encoded, length, NILP (no_line_break),
2955 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
2956 if (encoded_length > allength)
2957 emacs_abort ();
2959 if (encoded_length < 0)
2961 /* The encoding wasn't possible. */
2962 SAFE_FREE ();
2963 error ("Multibyte character in data for base64 encoding");
2966 /* Now we have encoded the region, so we insert the new contents
2967 and delete the old. (Insert first in order to preserve markers.) */
2968 SET_PT_BOTH (XFASTINT (beg), ibeg);
2969 insert (encoded, encoded_length);
2970 SAFE_FREE ();
2971 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
2973 /* If point was outside of the region, restore it exactly; else just
2974 move to the beginning of the region. */
2975 if (old_pos >= XFASTINT (end))
2976 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
2977 else if (old_pos > XFASTINT (beg))
2978 old_pos = XFASTINT (beg);
2979 SET_PT (old_pos);
2981 /* We return the length of the encoded text. */
2982 return make_number (encoded_length);
2985 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
2986 1, 2, 0,
2987 doc: /* Base64-encode STRING and return the result.
2988 Optional second argument NO-LINE-BREAK means do not break long lines
2989 into shorter lines. */)
2990 (Lisp_Object string, Lisp_Object no_line_break)
2992 ptrdiff_t allength, length, encoded_length;
2993 char *encoded;
2994 Lisp_Object encoded_string;
2995 USE_SAFE_ALLOCA;
2997 CHECK_STRING (string);
2999 /* We need to allocate enough room for encoding the text.
3000 We need 33 1/3% more space, plus a newline every 76
3001 characters, and then we round up. */
3002 length = SBYTES (string);
3003 allength = length + length/3 + 1;
3004 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3006 /* We need to allocate enough room for decoding the text. */
3007 encoded = SAFE_ALLOCA (allength);
3009 encoded_length = base64_encode_1 (SSDATA (string),
3010 encoded, length, NILP (no_line_break),
3011 STRING_MULTIBYTE (string));
3012 if (encoded_length > allength)
3013 emacs_abort ();
3015 if (encoded_length < 0)
3017 /* The encoding wasn't possible. */
3018 SAFE_FREE ();
3019 error ("Multibyte character in data for base64 encoding");
3022 encoded_string = make_unibyte_string (encoded, encoded_length);
3023 SAFE_FREE ();
3025 return encoded_string;
3028 static ptrdiff_t
3029 base64_encode_1 (const char *from, char *to, ptrdiff_t length,
3030 bool line_break, bool multibyte)
3032 int counter = 0;
3033 ptrdiff_t i = 0;
3034 char *e = to;
3035 int c;
3036 unsigned int value;
3037 int bytes;
3039 while (i < length)
3041 if (multibyte)
3043 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3044 if (CHAR_BYTE8_P (c))
3045 c = CHAR_TO_BYTE8 (c);
3046 else if (c >= 256)
3047 return -1;
3048 i += bytes;
3050 else
3051 c = from[i++];
3053 /* Wrap line every 76 characters. */
3055 if (line_break)
3057 if (counter < MIME_LINE_LENGTH / 4)
3058 counter++;
3059 else
3061 *e++ = '\n';
3062 counter = 1;
3066 /* Process first byte of a triplet. */
3068 *e++ = base64_value_to_char[0x3f & c >> 2];
3069 value = (0x03 & c) << 4;
3071 /* Process second byte of a triplet. */
3073 if (i == length)
3075 *e++ = base64_value_to_char[value];
3076 *e++ = '=';
3077 *e++ = '=';
3078 break;
3081 if (multibyte)
3083 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3084 if (CHAR_BYTE8_P (c))
3085 c = CHAR_TO_BYTE8 (c);
3086 else if (c >= 256)
3087 return -1;
3088 i += bytes;
3090 else
3091 c = from[i++];
3093 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3094 value = (0x0f & c) << 2;
3096 /* Process third byte of a triplet. */
3098 if (i == length)
3100 *e++ = base64_value_to_char[value];
3101 *e++ = '=';
3102 break;
3105 if (multibyte)
3107 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3108 if (CHAR_BYTE8_P (c))
3109 c = CHAR_TO_BYTE8 (c);
3110 else if (c >= 256)
3111 return -1;
3112 i += bytes;
3114 else
3115 c = from[i++];
3117 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3118 *e++ = base64_value_to_char[0x3f & c];
3121 return e - to;
3125 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3126 2, 2, "r",
3127 doc: /* Base64-decode the region between BEG and END.
3128 Return the length of the decoded text.
3129 If the region can't be decoded, signal an error and don't modify the buffer. */)
3130 (Lisp_Object beg, Lisp_Object end)
3132 ptrdiff_t ibeg, iend, length, allength;
3133 char *decoded;
3134 ptrdiff_t old_pos = PT;
3135 ptrdiff_t decoded_length;
3136 ptrdiff_t inserted_chars;
3137 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3138 USE_SAFE_ALLOCA;
3140 validate_region (&beg, &end);
3142 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3143 iend = CHAR_TO_BYTE (XFASTINT (end));
3145 length = iend - ibeg;
3147 /* We need to allocate enough room for decoding the text. If we are
3148 working on a multibyte buffer, each decoded code may occupy at
3149 most two bytes. */
3150 allength = multibyte ? length * 2 : length;
3151 decoded = SAFE_ALLOCA (allength);
3153 move_gap_both (XFASTINT (beg), ibeg);
3154 decoded_length = base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg),
3155 decoded, length,
3156 multibyte, &inserted_chars);
3157 if (decoded_length > allength)
3158 emacs_abort ();
3160 if (decoded_length < 0)
3162 /* The decoding wasn't possible. */
3163 SAFE_FREE ();
3164 error ("Invalid base64 data");
3167 /* Now we have decoded the region, so we insert the new contents
3168 and delete the old. (Insert first in order to preserve markers.) */
3169 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3170 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3171 SAFE_FREE ();
3173 /* Delete the original text. */
3174 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3175 iend + decoded_length, 1);
3177 /* If point was outside of the region, restore it exactly; else just
3178 move to the beginning of the region. */
3179 if (old_pos >= XFASTINT (end))
3180 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3181 else if (old_pos > XFASTINT (beg))
3182 old_pos = XFASTINT (beg);
3183 SET_PT (old_pos > ZV ? ZV : old_pos);
3185 return make_number (inserted_chars);
3188 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3189 1, 1, 0,
3190 doc: /* Base64-decode STRING and return the result. */)
3191 (Lisp_Object string)
3193 char *decoded;
3194 ptrdiff_t length, decoded_length;
3195 Lisp_Object decoded_string;
3196 USE_SAFE_ALLOCA;
3198 CHECK_STRING (string);
3200 length = SBYTES (string);
3201 /* We need to allocate enough room for decoding the text. */
3202 decoded = SAFE_ALLOCA (length);
3204 /* The decoded result should be unibyte. */
3205 decoded_length = base64_decode_1 (SSDATA (string), decoded, length,
3206 0, NULL);
3207 if (decoded_length > length)
3208 emacs_abort ();
3209 else if (decoded_length >= 0)
3210 decoded_string = make_unibyte_string (decoded, decoded_length);
3211 else
3212 decoded_string = Qnil;
3214 SAFE_FREE ();
3215 if (!STRINGP (decoded_string))
3216 error ("Invalid base64 data");
3218 return decoded_string;
3221 /* Base64-decode the data at FROM of LENGTH bytes into TO. If
3222 MULTIBYTE, the decoded result should be in multibyte
3223 form. If NCHARS_RETURN is not NULL, store the number of produced
3224 characters in *NCHARS_RETURN. */
3226 static ptrdiff_t
3227 base64_decode_1 (const char *from, char *to, ptrdiff_t length,
3228 bool multibyte, ptrdiff_t *nchars_return)
3230 ptrdiff_t i = 0; /* Used inside READ_QUADRUPLET_BYTE */
3231 char *e = to;
3232 unsigned char c;
3233 unsigned long value;
3234 ptrdiff_t nchars = 0;
3236 while (1)
3238 /* Process first byte of a quadruplet. */
3240 READ_QUADRUPLET_BYTE (e-to);
3242 if (!IS_BASE64 (c))
3243 return -1;
3244 value = base64_char_to_value[c] << 18;
3246 /* Process second byte of a quadruplet. */
3248 READ_QUADRUPLET_BYTE (-1);
3250 if (!IS_BASE64 (c))
3251 return -1;
3252 value |= base64_char_to_value[c] << 12;
3254 c = (unsigned char) (value >> 16);
3255 if (multibyte && c >= 128)
3256 e += BYTE8_STRING (c, e);
3257 else
3258 *e++ = c;
3259 nchars++;
3261 /* Process third byte of a quadruplet. */
3263 READ_QUADRUPLET_BYTE (-1);
3265 if (c == '=')
3267 READ_QUADRUPLET_BYTE (-1);
3269 if (c != '=')
3270 return -1;
3271 continue;
3274 if (!IS_BASE64 (c))
3275 return -1;
3276 value |= base64_char_to_value[c] << 6;
3278 c = (unsigned char) (0xff & value >> 8);
3279 if (multibyte && c >= 128)
3280 e += BYTE8_STRING (c, e);
3281 else
3282 *e++ = c;
3283 nchars++;
3285 /* Process fourth byte of a quadruplet. */
3287 READ_QUADRUPLET_BYTE (-1);
3289 if (c == '=')
3290 continue;
3292 if (!IS_BASE64 (c))
3293 return -1;
3294 value |= base64_char_to_value[c];
3296 c = (unsigned char) (0xff & value);
3297 if (multibyte && c >= 128)
3298 e += BYTE8_STRING (c, e);
3299 else
3300 *e++ = c;
3301 nchars++;
3307 /***********************************************************************
3308 ***** *****
3309 ***** Hash Tables *****
3310 ***** *****
3311 ***********************************************************************/
3313 /* Implemented by gerd@gnu.org. This hash table implementation was
3314 inspired by CMUCL hash tables. */
3316 /* Ideas:
3318 1. For small tables, association lists are probably faster than
3319 hash tables because they have lower overhead.
3321 For uses of hash tables where the O(1) behavior of table
3322 operations is not a requirement, it might therefore be a good idea
3323 not to hash. Instead, we could just do a linear search in the
3324 key_and_value vector of the hash table. This could be done
3325 if a `:linear-search t' argument is given to make-hash-table. */
3328 /* The list of all weak hash tables. Don't staticpro this one. */
3330 static struct Lisp_Hash_Table *weak_hash_tables;
3332 /* Various symbols. */
3334 static Lisp_Object Qhash_table_p;
3335 static Lisp_Object Qkey, Qvalue, Qeql;
3336 Lisp_Object Qeq, Qequal;
3337 Lisp_Object QCtest, QCsize, QCrehash_size, QCrehash_threshold, QCweakness;
3338 static Lisp_Object Qhash_table_test, Qkey_or_value, Qkey_and_value;
3341 /***********************************************************************
3342 Utilities
3343 ***********************************************************************/
3345 static void
3346 CHECK_HASH_TABLE (Lisp_Object x)
3348 CHECK_TYPE (HASH_TABLE_P (x), Qhash_table_p, x);
3351 static void
3352 set_hash_key_and_value (struct Lisp_Hash_Table *h, Lisp_Object key_and_value)
3354 h->key_and_value = key_and_value;
3356 static void
3357 set_hash_next (struct Lisp_Hash_Table *h, Lisp_Object next)
3359 h->next = next;
3361 static void
3362 set_hash_next_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3364 gc_aset (h->next, idx, val);
3366 static void
3367 set_hash_hash (struct Lisp_Hash_Table *h, Lisp_Object hash)
3369 h->hash = hash;
3371 static void
3372 set_hash_hash_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3374 gc_aset (h->hash, idx, val);
3376 static void
3377 set_hash_index (struct Lisp_Hash_Table *h, Lisp_Object index)
3379 h->index = index;
3381 static void
3382 set_hash_index_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3384 gc_aset (h->index, idx, val);
3387 /* If OBJ is a Lisp hash table, return a pointer to its struct
3388 Lisp_Hash_Table. Otherwise, signal an error. */
3390 static struct Lisp_Hash_Table *
3391 check_hash_table (Lisp_Object obj)
3393 CHECK_HASH_TABLE (obj);
3394 return XHASH_TABLE (obj);
3398 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3399 number. A number is "almost" a prime number if it is not divisible
3400 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3402 EMACS_INT
3403 next_almost_prime (EMACS_INT n)
3405 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
3406 for (n |= 1; ; n += 2)
3407 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0)
3408 return n;
3412 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3413 which USED[I] is non-zero. If found at index I in ARGS, set
3414 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3415 0. This function is used to extract a keyword/argument pair from
3416 a DEFUN parameter list. */
3418 static ptrdiff_t
3419 get_key_arg (Lisp_Object key, ptrdiff_t nargs, Lisp_Object *args, char *used)
3421 ptrdiff_t i;
3423 for (i = 1; i < nargs; i++)
3424 if (!used[i - 1] && EQ (args[i - 1], key))
3426 used[i - 1] = 1;
3427 used[i] = 1;
3428 return i;
3431 return 0;
3435 /* Return a Lisp vector which has the same contents as VEC but has
3436 at least INCR_MIN more entries, where INCR_MIN is positive.
3437 If NITEMS_MAX is not -1, do not grow the vector to be any larger
3438 than NITEMS_MAX. Entries in the resulting
3439 vector that are not copied from VEC are set to nil. */
3441 Lisp_Object
3442 larger_vector (Lisp_Object vec, ptrdiff_t incr_min, ptrdiff_t nitems_max)
3444 struct Lisp_Vector *v;
3445 ptrdiff_t i, incr, incr_max, old_size, new_size;
3446 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / sizeof *v->contents;
3447 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
3448 ? nitems_max : C_language_max);
3449 eassert (VECTORP (vec));
3450 eassert (0 < incr_min && -1 <= nitems_max);
3451 old_size = ASIZE (vec);
3452 incr_max = n_max - old_size;
3453 incr = max (incr_min, min (old_size >> 1, incr_max));
3454 if (incr_max < incr)
3455 memory_full (SIZE_MAX);
3456 new_size = old_size + incr;
3457 v = allocate_vector (new_size);
3458 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3459 for (i = old_size; i < new_size; ++i)
3460 v->contents[i] = Qnil;
3461 XSETVECTOR (vec, v);
3462 return vec;
3466 /***********************************************************************
3467 Low-level Functions
3468 ***********************************************************************/
3470 static struct hash_table_test hashtest_eq;
3471 struct hash_table_test hashtest_eql, hashtest_equal;
3473 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3474 HASH2 in hash table H using `eql'. Value is true if KEY1 and
3475 KEY2 are the same. */
3477 static bool
3478 cmpfn_eql (struct hash_table_test *ht,
3479 Lisp_Object key1,
3480 Lisp_Object key2)
3482 return (FLOATP (key1)
3483 && FLOATP (key2)
3484 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3488 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3489 HASH2 in hash table H using `equal'. Value is true if KEY1 and
3490 KEY2 are the same. */
3492 static bool
3493 cmpfn_equal (struct hash_table_test *ht,
3494 Lisp_Object key1,
3495 Lisp_Object key2)
3497 return !NILP (Fequal (key1, key2));
3501 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3502 HASH2 in hash table H using H->user_cmp_function. Value is true
3503 if KEY1 and KEY2 are the same. */
3505 static bool
3506 cmpfn_user_defined (struct hash_table_test *ht,
3507 Lisp_Object key1,
3508 Lisp_Object key2)
3510 Lisp_Object args[3];
3512 args[0] = ht->user_cmp_function;
3513 args[1] = key1;
3514 args[2] = key2;
3515 return !NILP (Ffuncall (3, args));
3519 /* Value is a hash code for KEY for use in hash table H which uses
3520 `eq' to compare keys. The hash code returned is guaranteed to fit
3521 in a Lisp integer. */
3523 static EMACS_UINT
3524 hashfn_eq (struct hash_table_test *ht, Lisp_Object key)
3526 EMACS_UINT hash = XHASH (key) ^ XTYPE (key);
3527 return hash;
3530 /* Value is a hash code for KEY for use in hash table H which uses
3531 `eql' to compare keys. The hash code returned is guaranteed to fit
3532 in a Lisp integer. */
3534 static EMACS_UINT
3535 hashfn_eql (struct hash_table_test *ht, Lisp_Object key)
3537 EMACS_UINT hash;
3538 if (FLOATP (key))
3539 hash = sxhash (key, 0);
3540 else
3541 hash = XHASH (key) ^ XTYPE (key);
3542 return hash;
3545 /* Value is a hash code for KEY for use in hash table H which uses
3546 `equal' to compare keys. The hash code returned is guaranteed to fit
3547 in a Lisp integer. */
3549 static EMACS_UINT
3550 hashfn_equal (struct hash_table_test *ht, Lisp_Object key)
3552 EMACS_UINT hash = sxhash (key, 0);
3553 return hash;
3556 /* Value is a hash code for KEY for use in hash table H which uses as
3557 user-defined function to compare keys. The hash code returned is
3558 guaranteed to fit in a Lisp integer. */
3560 static EMACS_UINT
3561 hashfn_user_defined (struct hash_table_test *ht, Lisp_Object key)
3563 Lisp_Object args[2], hash;
3565 args[0] = ht->user_hash_function;
3566 args[1] = key;
3567 hash = Ffuncall (2, args);
3568 return hashfn_eq (ht, hash);
3571 /* An upper bound on the size of a hash table index. It must fit in
3572 ptrdiff_t and be a valid Emacs fixnum. */
3573 #define INDEX_SIZE_BOUND \
3574 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, PTRDIFF_MAX / word_size))
3576 /* Create and initialize a new hash table.
3578 TEST specifies the test the hash table will use to compare keys.
3579 It must be either one of the predefined tests `eq', `eql' or
3580 `equal' or a symbol denoting a user-defined test named TEST with
3581 test and hash functions USER_TEST and USER_HASH.
3583 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3585 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3586 new size when it becomes full is computed by adding REHASH_SIZE to
3587 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3588 table's new size is computed by multiplying its old size with
3589 REHASH_SIZE.
3591 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3592 be resized when the ratio of (number of entries in the table) /
3593 (table size) is >= REHASH_THRESHOLD.
3595 WEAK specifies the weakness of the table. If non-nil, it must be
3596 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
3598 Lisp_Object
3599 make_hash_table (struct hash_table_test test,
3600 Lisp_Object size, Lisp_Object rehash_size,
3601 Lisp_Object rehash_threshold, Lisp_Object weak)
3603 struct Lisp_Hash_Table *h;
3604 Lisp_Object table;
3605 EMACS_INT index_size, sz;
3606 ptrdiff_t i;
3607 double index_float;
3609 /* Preconditions. */
3610 eassert (SYMBOLP (test.name));
3611 eassert (INTEGERP (size) && XINT (size) >= 0);
3612 eassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3613 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size)));
3614 eassert (FLOATP (rehash_threshold)
3615 && 0 < XFLOAT_DATA (rehash_threshold)
3616 && XFLOAT_DATA (rehash_threshold) <= 1.0);
3618 if (XFASTINT (size) == 0)
3619 size = make_number (1);
3621 sz = XFASTINT (size);
3622 index_float = sz / XFLOAT_DATA (rehash_threshold);
3623 index_size = (index_float < INDEX_SIZE_BOUND + 1
3624 ? next_almost_prime (index_float)
3625 : INDEX_SIZE_BOUND + 1);
3626 if (INDEX_SIZE_BOUND < max (index_size, 2 * sz))
3627 error ("Hash table too large");
3629 /* Allocate a table and initialize it. */
3630 h = allocate_hash_table ();
3632 /* Initialize hash table slots. */
3633 h->test = test;
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;
3674 h2 = allocate_hash_table ();
3675 *h2 = *h1;
3676 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3677 h2->hash = Fcopy_sequence (h1->hash);
3678 h2->next = Fcopy_sequence (h1->next);
3679 h2->index = Fcopy_sequence (h1->index);
3680 XSET_HASH_TABLE (table, h2);
3682 /* Maybe add this hash table to the list of all weak hash tables. */
3683 if (!NILP (h2->weak))
3685 h2->next_weak = weak_hash_tables;
3686 weak_hash_tables = h2;
3689 return table;
3693 /* Resize hash table H if it's too full. If H cannot be resized
3694 because it's already too large, throw an error. */
3696 static void
3697 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3699 if (NILP (h->next_free))
3701 ptrdiff_t old_size = HASH_TABLE_SIZE (h);
3702 EMACS_INT new_size, index_size, nsize;
3703 ptrdiff_t i;
3704 double index_float;
3706 if (INTEGERP (h->rehash_size))
3707 new_size = old_size + XFASTINT (h->rehash_size);
3708 else
3710 double float_new_size = old_size * XFLOAT_DATA (h->rehash_size);
3711 if (float_new_size < INDEX_SIZE_BOUND + 1)
3713 new_size = float_new_size;
3714 if (new_size <= old_size)
3715 new_size = old_size + 1;
3717 else
3718 new_size = INDEX_SIZE_BOUND + 1;
3720 index_float = new_size / XFLOAT_DATA (h->rehash_threshold);
3721 index_size = (index_float < INDEX_SIZE_BOUND + 1
3722 ? next_almost_prime (index_float)
3723 : INDEX_SIZE_BOUND + 1);
3724 nsize = max (index_size, 2 * new_size);
3725 if (INDEX_SIZE_BOUND < nsize)
3726 error ("Hash table too large to resize");
3728 #ifdef ENABLE_CHECKING
3729 if (HASH_TABLE_P (Vpurify_flag)
3730 && XHASH_TABLE (Vpurify_flag) == h)
3732 Lisp_Object args[2];
3733 args[0] = build_string ("Growing hash table to: %d");
3734 args[1] = make_number (new_size);
3735 Fmessage (2, args);
3737 #endif
3739 set_hash_key_and_value (h, larger_vector (h->key_and_value,
3740 2 * (new_size - old_size), -1));
3741 set_hash_next (h, larger_vector (h->next, new_size - old_size, -1));
3742 set_hash_hash (h, larger_vector (h->hash, new_size - old_size, -1));
3743 set_hash_index (h, Fmake_vector (make_number (index_size), Qnil));
3745 /* Update the free list. Do it so that new entries are added at
3746 the end of the free list. This makes some operations like
3747 maphash faster. */
3748 for (i = old_size; i < new_size - 1; ++i)
3749 set_hash_next_slot (h, i, make_number (i + 1));
3751 if (!NILP (h->next_free))
3753 Lisp_Object last, next;
3755 last = h->next_free;
3756 while (next = HASH_NEXT (h, XFASTINT (last)),
3757 !NILP (next))
3758 last = next;
3760 set_hash_next_slot (h, XFASTINT (last), make_number (old_size));
3762 else
3763 XSETFASTINT (h->next_free, old_size);
3765 /* Rehash. */
3766 for (i = 0; i < old_size; ++i)
3767 if (!NILP (HASH_HASH (h, i)))
3769 EMACS_UINT hash_code = XUINT (HASH_HASH (h, i));
3770 ptrdiff_t start_of_bucket = hash_code % ASIZE (h->index);
3771 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3772 set_hash_index_slot (h, start_of_bucket, make_number (i));
3778 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
3779 the hash code of KEY. Value is the index of the entry in H
3780 matching KEY, or -1 if not found. */
3782 ptrdiff_t
3783 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
3785 EMACS_UINT hash_code;
3786 ptrdiff_t start_of_bucket;
3787 Lisp_Object idx;
3789 hash_code = h->test.hashfn (&h->test, key);
3790 eassert ((hash_code & ~INTMASK) == 0);
3791 if (hash)
3792 *hash = hash_code;
3794 start_of_bucket = hash_code % ASIZE (h->index);
3795 idx = HASH_INDEX (h, start_of_bucket);
3797 /* We need not gcpro idx since it's either an integer or nil. */
3798 while (!NILP (idx))
3800 ptrdiff_t i = XFASTINT (idx);
3801 if (EQ (key, HASH_KEY (h, i))
3802 || (h->test.cmpfn
3803 && hash_code == XUINT (HASH_HASH (h, i))
3804 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
3805 break;
3806 idx = HASH_NEXT (h, i);
3809 return NILP (idx) ? -1 : XFASTINT (idx);
3813 /* Put an entry into hash table H that associates KEY with VALUE.
3814 HASH is a previously computed hash code of KEY.
3815 Value is the index of the entry in H matching KEY. */
3817 ptrdiff_t
3818 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value,
3819 EMACS_UINT hash)
3821 ptrdiff_t start_of_bucket, i;
3823 eassert ((hash & ~INTMASK) == 0);
3825 /* Increment count after resizing because resizing may fail. */
3826 maybe_resize_hash_table (h);
3827 h->count++;
3829 /* Store key/value in the key_and_value vector. */
3830 i = XFASTINT (h->next_free);
3831 h->next_free = HASH_NEXT (h, i);
3832 set_hash_key_slot (h, i, key);
3833 set_hash_value_slot (h, i, value);
3835 /* Remember its hash code. */
3836 set_hash_hash_slot (h, i, make_number (hash));
3838 /* Add new entry to its collision chain. */
3839 start_of_bucket = hash % ASIZE (h->index);
3840 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3841 set_hash_index_slot (h, start_of_bucket, make_number (i));
3842 return i;
3846 /* Remove the entry matching KEY from hash table H, if there is one. */
3848 static void
3849 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
3851 EMACS_UINT hash_code;
3852 ptrdiff_t start_of_bucket;
3853 Lisp_Object idx, prev;
3855 hash_code = h->test.hashfn (&h->test, key);
3856 eassert ((hash_code & ~INTMASK) == 0);
3857 start_of_bucket = hash_code % ASIZE (h->index);
3858 idx = HASH_INDEX (h, start_of_bucket);
3859 prev = Qnil;
3861 /* We need not gcpro idx, prev since they're either integers or nil. */
3862 while (!NILP (idx))
3864 ptrdiff_t i = XFASTINT (idx);
3866 if (EQ (key, HASH_KEY (h, i))
3867 || (h->test.cmpfn
3868 && hash_code == XUINT (HASH_HASH (h, i))
3869 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
3871 /* Take entry out of collision chain. */
3872 if (NILP (prev))
3873 set_hash_index_slot (h, start_of_bucket, HASH_NEXT (h, i));
3874 else
3875 set_hash_next_slot (h, XFASTINT (prev), HASH_NEXT (h, i));
3877 /* Clear slots in key_and_value and add the slots to
3878 the free list. */
3879 set_hash_key_slot (h, i, Qnil);
3880 set_hash_value_slot (h, i, Qnil);
3881 set_hash_hash_slot (h, i, Qnil);
3882 set_hash_next_slot (h, i, h->next_free);
3883 h->next_free = make_number (i);
3884 h->count--;
3885 eassert (h->count >= 0);
3886 break;
3888 else
3890 prev = idx;
3891 idx = HASH_NEXT (h, i);
3897 /* Clear hash table H. */
3899 static void
3900 hash_clear (struct Lisp_Hash_Table *h)
3902 if (h->count > 0)
3904 ptrdiff_t i, size = HASH_TABLE_SIZE (h);
3906 for (i = 0; i < size; ++i)
3908 set_hash_next_slot (h, i, i < size - 1 ? make_number (i + 1) : Qnil);
3909 set_hash_key_slot (h, i, Qnil);
3910 set_hash_value_slot (h, i, Qnil);
3911 set_hash_hash_slot (h, i, Qnil);
3914 for (i = 0; i < ASIZE (h->index); ++i)
3915 ASET (h->index, i, Qnil);
3917 h->next_free = make_number (0);
3918 h->count = 0;
3924 /************************************************************************
3925 Weak Hash Tables
3926 ************************************************************************/
3928 /* Sweep weak hash table H. REMOVE_ENTRIES_P means remove
3929 entries from the table that don't survive the current GC.
3930 !REMOVE_ENTRIES_P means mark entries that are in use. Value is
3931 true if anything was marked. */
3933 static bool
3934 sweep_weak_table (struct Lisp_Hash_Table *h, bool remove_entries_p)
3936 ptrdiff_t bucket, n;
3937 bool marked;
3939 n = ASIZE (h->index) & ~ARRAY_MARK_FLAG;
3940 marked = 0;
3942 for (bucket = 0; bucket < n; ++bucket)
3944 Lisp_Object idx, next, prev;
3946 /* Follow collision chain, removing entries that
3947 don't survive this garbage collection. */
3948 prev = Qnil;
3949 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
3951 ptrdiff_t i = XFASTINT (idx);
3952 bool key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
3953 bool value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
3954 bool remove_p;
3956 if (EQ (h->weak, Qkey))
3957 remove_p = !key_known_to_survive_p;
3958 else if (EQ (h->weak, Qvalue))
3959 remove_p = !value_known_to_survive_p;
3960 else if (EQ (h->weak, Qkey_or_value))
3961 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
3962 else if (EQ (h->weak, Qkey_and_value))
3963 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
3964 else
3965 emacs_abort ();
3967 next = HASH_NEXT (h, i);
3969 if (remove_entries_p)
3971 if (remove_p)
3973 /* Take out of collision chain. */
3974 if (NILP (prev))
3975 set_hash_index_slot (h, bucket, next);
3976 else
3977 set_hash_next_slot (h, XFASTINT (prev), next);
3979 /* Add to free list. */
3980 set_hash_next_slot (h, i, h->next_free);
3981 h->next_free = idx;
3983 /* Clear key, value, and hash. */
3984 set_hash_key_slot (h, i, Qnil);
3985 set_hash_value_slot (h, i, Qnil);
3986 set_hash_hash_slot (h, i, Qnil);
3988 h->count--;
3990 else
3992 prev = idx;
3995 else
3997 if (!remove_p)
3999 /* Make sure key and value survive. */
4000 if (!key_known_to_survive_p)
4002 mark_object (HASH_KEY (h, i));
4003 marked = 1;
4006 if (!value_known_to_survive_p)
4008 mark_object (HASH_VALUE (h, i));
4009 marked = 1;
4016 return marked;
4019 /* Remove elements from weak hash tables that don't survive the
4020 current garbage collection. Remove weak tables that don't survive
4021 from Vweak_hash_tables. Called from gc_sweep. */
4023 void
4024 sweep_weak_hash_tables (void)
4026 struct Lisp_Hash_Table *h, *used, *next;
4027 bool marked;
4029 /* Mark all keys and values that are in use. Keep on marking until
4030 there is no more change. This is necessary for cases like
4031 value-weak table A containing an entry X -> Y, where Y is used in a
4032 key-weak table B, Z -> Y. If B comes after A in the list of weak
4033 tables, X -> Y might be removed from A, although when looking at B
4034 one finds that it shouldn't. */
4037 marked = 0;
4038 for (h = weak_hash_tables; h; h = h->next_weak)
4040 if (h->header.size & ARRAY_MARK_FLAG)
4041 marked |= sweep_weak_table (h, 0);
4044 while (marked);
4046 /* Remove tables and entries that aren't used. */
4047 for (h = weak_hash_tables, used = NULL; h; h = next)
4049 next = h->next_weak;
4051 if (h->header.size & ARRAY_MARK_FLAG)
4053 /* TABLE is marked as used. Sweep its contents. */
4054 if (h->count > 0)
4055 sweep_weak_table (h, 1);
4057 /* Add table to the list of used weak hash tables. */
4058 h->next_weak = used;
4059 used = h;
4063 weak_hash_tables = used;
4068 /***********************************************************************
4069 Hash Code Computation
4070 ***********************************************************************/
4072 /* Maximum depth up to which to dive into Lisp structures. */
4074 #define SXHASH_MAX_DEPTH 3
4076 /* Maximum length up to which to take list and vector elements into
4077 account. */
4079 #define SXHASH_MAX_LEN 7
4081 /* Return a hash for string PTR which has length LEN. The hash value
4082 can be any EMACS_UINT value. */
4084 EMACS_UINT
4085 hash_string (char const *ptr, ptrdiff_t len)
4087 char const *p = ptr;
4088 char const *end = p + len;
4089 unsigned char c;
4090 EMACS_UINT hash = 0;
4092 while (p != end)
4094 c = *p++;
4095 hash = sxhash_combine (hash, c);
4098 return hash;
4101 /* Return a hash for string PTR which has length LEN. The hash
4102 code returned is guaranteed to fit in a Lisp integer. */
4104 static EMACS_UINT
4105 sxhash_string (char const *ptr, ptrdiff_t len)
4107 EMACS_UINT hash = hash_string (ptr, len);
4108 return SXHASH_REDUCE (hash);
4111 /* Return a hash for the floating point value VAL. */
4113 static EMACS_UINT
4114 sxhash_float (double val)
4116 EMACS_UINT hash = 0;
4117 enum {
4118 WORDS_PER_DOUBLE = (sizeof val / sizeof hash
4119 + (sizeof val % sizeof hash != 0))
4121 union {
4122 double val;
4123 EMACS_UINT word[WORDS_PER_DOUBLE];
4124 } u;
4125 int i;
4126 u.val = val;
4127 memset (&u.val + 1, 0, sizeof u - sizeof u.val);
4128 for (i = 0; i < WORDS_PER_DOUBLE; i++)
4129 hash = sxhash_combine (hash, u.word[i]);
4130 return SXHASH_REDUCE (hash);
4133 /* Return a hash for list LIST. DEPTH is the current depth in the
4134 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4136 static EMACS_UINT
4137 sxhash_list (Lisp_Object list, int depth)
4139 EMACS_UINT hash = 0;
4140 int i;
4142 if (depth < SXHASH_MAX_DEPTH)
4143 for (i = 0;
4144 CONSP (list) && i < SXHASH_MAX_LEN;
4145 list = XCDR (list), ++i)
4147 EMACS_UINT hash2 = sxhash (XCAR (list), depth + 1);
4148 hash = sxhash_combine (hash, hash2);
4151 if (!NILP (list))
4153 EMACS_UINT hash2 = sxhash (list, depth + 1);
4154 hash = sxhash_combine (hash, hash2);
4157 return SXHASH_REDUCE (hash);
4161 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4162 the Lisp structure. */
4164 static EMACS_UINT
4165 sxhash_vector (Lisp_Object vec, int depth)
4167 EMACS_UINT hash = ASIZE (vec);
4168 int i, n;
4170 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4171 for (i = 0; i < n; ++i)
4173 EMACS_UINT hash2 = sxhash (AREF (vec, i), depth + 1);
4174 hash = sxhash_combine (hash, hash2);
4177 return SXHASH_REDUCE (hash);
4180 /* Return a hash for bool-vector VECTOR. */
4182 static EMACS_UINT
4183 sxhash_bool_vector (Lisp_Object vec)
4185 EMACS_INT size = bool_vector_size (vec);
4186 EMACS_UINT hash = size;
4187 int i, n;
4189 n = min (SXHASH_MAX_LEN, bool_vector_words (size));
4190 for (i = 0; i < n; ++i)
4191 hash = sxhash_combine (hash, bool_vector_data (vec)[i]);
4193 return SXHASH_REDUCE (hash);
4197 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4198 structure. Value is an unsigned integer clipped to INTMASK. */
4200 EMACS_UINT
4201 sxhash (Lisp_Object obj, int depth)
4203 EMACS_UINT hash;
4205 if (depth > SXHASH_MAX_DEPTH)
4206 return 0;
4208 switch (XTYPE (obj))
4210 case_Lisp_Int:
4211 hash = XUINT (obj);
4212 break;
4214 case Lisp_Misc:
4215 hash = XHASH (obj);
4216 break;
4218 case Lisp_Symbol:
4219 obj = SYMBOL_NAME (obj);
4220 /* Fall through. */
4222 case Lisp_String:
4223 hash = sxhash_string (SSDATA (obj), SBYTES (obj));
4224 break;
4226 /* This can be everything from a vector to an overlay. */
4227 case Lisp_Vectorlike:
4228 if (VECTORP (obj))
4229 /* According to the CL HyperSpec, two arrays are equal only if
4230 they are `eq', except for strings and bit-vectors. In
4231 Emacs, this works differently. We have to compare element
4232 by element. */
4233 hash = sxhash_vector (obj, depth);
4234 else if (BOOL_VECTOR_P (obj))
4235 hash = sxhash_bool_vector (obj);
4236 else
4237 /* Others are `equal' if they are `eq', so let's take their
4238 address as hash. */
4239 hash = XHASH (obj);
4240 break;
4242 case Lisp_Cons:
4243 hash = sxhash_list (obj, depth);
4244 break;
4246 case Lisp_Float:
4247 hash = sxhash_float (XFLOAT_DATA (obj));
4248 break;
4250 default:
4251 emacs_abort ();
4254 return hash;
4259 /***********************************************************************
4260 Lisp Interface
4261 ***********************************************************************/
4264 DEFUN ("sxhash", Fsxhash, Ssxhash, 1, 1, 0,
4265 doc: /* Compute a hash code for OBJ and return it as integer. */)
4266 (Lisp_Object obj)
4268 EMACS_UINT hash = sxhash (obj, 0);
4269 return make_number (hash);
4273 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4274 doc: /* Create and return a new hash table.
4276 Arguments are specified as keyword/argument pairs. The following
4277 arguments are defined:
4279 :test TEST -- TEST must be a symbol that specifies how to compare
4280 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4281 `equal'. User-supplied test and hash functions can be specified via
4282 `define-hash-table-test'.
4284 :size SIZE -- A hint as to how many elements will be put in the table.
4285 Default is 65.
4287 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4288 fills up. If REHASH-SIZE is an integer, increase the size by that
4289 amount. If it is a float, it must be > 1.0, and the new size is the
4290 old size multiplied by that factor. Default is 1.5.
4292 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4293 Resize the hash table when the ratio (number of entries / table size)
4294 is greater than or equal to THRESHOLD. Default is 0.8.
4296 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4297 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4298 returned is a weak table. Key/value pairs are removed from a weak
4299 hash table when there are no non-weak references pointing to their
4300 key, value, one of key or value, or both key and value, depending on
4301 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4302 is nil.
4304 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4305 (ptrdiff_t nargs, Lisp_Object *args)
4307 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4308 struct hash_table_test testdesc;
4309 char *used;
4310 ptrdiff_t i;
4312 /* The vector `used' is used to keep track of arguments that
4313 have been consumed. */
4314 used = alloca (nargs * sizeof *used);
4315 memset (used, 0, nargs * sizeof *used);
4317 /* See if there's a `:test TEST' among the arguments. */
4318 i = get_key_arg (QCtest, nargs, args, used);
4319 test = i ? args[i] : Qeql;
4320 if (EQ (test, Qeq))
4321 testdesc = hashtest_eq;
4322 else if (EQ (test, Qeql))
4323 testdesc = hashtest_eql;
4324 else if (EQ (test, Qequal))
4325 testdesc = hashtest_equal;
4326 else
4328 /* See if it is a user-defined test. */
4329 Lisp_Object prop;
4331 prop = Fget (test, Qhash_table_test);
4332 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4333 signal_error ("Invalid hash table test", test);
4334 testdesc.name = test;
4335 testdesc.user_cmp_function = XCAR (prop);
4336 testdesc.user_hash_function = XCAR (XCDR (prop));
4337 testdesc.hashfn = hashfn_user_defined;
4338 testdesc.cmpfn = cmpfn_user_defined;
4341 /* See if there's a `:size SIZE' argument. */
4342 i = get_key_arg (QCsize, nargs, args, used);
4343 size = i ? args[i] : Qnil;
4344 if (NILP (size))
4345 size = make_number (DEFAULT_HASH_SIZE);
4346 else if (!INTEGERP (size) || XINT (size) < 0)
4347 signal_error ("Invalid hash table size", size);
4349 /* Look for `:rehash-size SIZE'. */
4350 i = get_key_arg (QCrehash_size, nargs, args, used);
4351 rehash_size = i ? args[i] : make_float (DEFAULT_REHASH_SIZE);
4352 if (! ((INTEGERP (rehash_size) && 0 < XINT (rehash_size))
4353 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size))))
4354 signal_error ("Invalid hash table rehash size", rehash_size);
4356 /* Look for `:rehash-threshold THRESHOLD'. */
4357 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4358 rehash_threshold = i ? args[i] : make_float (DEFAULT_REHASH_THRESHOLD);
4359 if (! (FLOATP (rehash_threshold)
4360 && 0 < XFLOAT_DATA (rehash_threshold)
4361 && XFLOAT_DATA (rehash_threshold) <= 1))
4362 signal_error ("Invalid hash table rehash threshold", rehash_threshold);
4364 /* Look for `:weakness WEAK'. */
4365 i = get_key_arg (QCweakness, nargs, args, used);
4366 weak = i ? args[i] : Qnil;
4367 if (EQ (weak, Qt))
4368 weak = Qkey_and_value;
4369 if (!NILP (weak)
4370 && !EQ (weak, Qkey)
4371 && !EQ (weak, Qvalue)
4372 && !EQ (weak, Qkey_or_value)
4373 && !EQ (weak, Qkey_and_value))
4374 signal_error ("Invalid hash table weakness", weak);
4376 /* Now, all args should have been used up, or there's a problem. */
4377 for (i = 0; i < nargs; ++i)
4378 if (!used[i])
4379 signal_error ("Invalid argument list", args[i]);
4381 return make_hash_table (testdesc, size, rehash_size, rehash_threshold, weak);
4385 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4386 doc: /* Return a copy of hash table TABLE. */)
4387 (Lisp_Object table)
4389 return copy_hash_table (check_hash_table (table));
4393 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4394 doc: /* Return the number of elements in TABLE. */)
4395 (Lisp_Object table)
4397 return make_number (check_hash_table (table)->count);
4401 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4402 Shash_table_rehash_size, 1, 1, 0,
4403 doc: /* Return the current rehash size of TABLE. */)
4404 (Lisp_Object table)
4406 return check_hash_table (table)->rehash_size;
4410 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4411 Shash_table_rehash_threshold, 1, 1, 0,
4412 doc: /* Return the current rehash threshold of TABLE. */)
4413 (Lisp_Object table)
4415 return check_hash_table (table)->rehash_threshold;
4419 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4420 doc: /* Return the size of TABLE.
4421 The size can be used as an argument to `make-hash-table' to create
4422 a hash table than can hold as many elements as TABLE holds
4423 without need for resizing. */)
4424 (Lisp_Object table)
4426 struct Lisp_Hash_Table *h = check_hash_table (table);
4427 return make_number (HASH_TABLE_SIZE (h));
4431 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4432 doc: /* Return the test TABLE uses. */)
4433 (Lisp_Object table)
4435 return check_hash_table (table)->test.name;
4439 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4440 1, 1, 0,
4441 doc: /* Return the weakness of TABLE. */)
4442 (Lisp_Object table)
4444 return check_hash_table (table)->weak;
4448 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4449 doc: /* Return t if OBJ is a Lisp hash table object. */)
4450 (Lisp_Object obj)
4452 return HASH_TABLE_P (obj) ? Qt : Qnil;
4456 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4457 doc: /* Clear hash table TABLE and return it. */)
4458 (Lisp_Object table)
4460 hash_clear (check_hash_table (table));
4461 /* Be compatible with XEmacs. */
4462 return table;
4466 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4467 doc: /* Look up KEY in TABLE and return its associated value.
4468 If KEY is not found, return DFLT which defaults to nil. */)
4469 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4471 struct Lisp_Hash_Table *h = check_hash_table (table);
4472 ptrdiff_t i = hash_lookup (h, key, NULL);
4473 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4477 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4478 doc: /* Associate KEY with VALUE in hash table TABLE.
4479 If KEY is already present in table, replace its current value with
4480 VALUE. In any case, return VALUE. */)
4481 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4483 struct Lisp_Hash_Table *h = check_hash_table (table);
4484 ptrdiff_t i;
4485 EMACS_UINT hash;
4487 i = hash_lookup (h, key, &hash);
4488 if (i >= 0)
4489 set_hash_value_slot (h, i, value);
4490 else
4491 hash_put (h, key, value, hash);
4493 return value;
4497 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4498 doc: /* Remove KEY from TABLE. */)
4499 (Lisp_Object key, Lisp_Object table)
4501 struct Lisp_Hash_Table *h = check_hash_table (table);
4502 hash_remove_from_table (h, key);
4503 return Qnil;
4507 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4508 doc: /* Call FUNCTION for all entries in hash table TABLE.
4509 FUNCTION is called with two arguments, KEY and VALUE. */)
4510 (Lisp_Object function, Lisp_Object table)
4512 struct Lisp_Hash_Table *h = check_hash_table (table);
4513 Lisp_Object args[3];
4514 ptrdiff_t i;
4516 for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
4517 if (!NILP (HASH_HASH (h, i)))
4519 args[0] = function;
4520 args[1] = HASH_KEY (h, i);
4521 args[2] = HASH_VALUE (h, i);
4522 Ffuncall (3, args);
4525 return Qnil;
4529 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4530 Sdefine_hash_table_test, 3, 3, 0,
4531 doc: /* Define a new hash table test with name NAME, a symbol.
4533 In hash tables created with NAME specified as test, use TEST to
4534 compare keys, and HASH for computing hash codes of keys.
4536 TEST must be a function taking two arguments and returning non-nil if
4537 both arguments are the same. HASH must be a function taking one
4538 argument and returning an object that is the hash code of the argument.
4539 It should be the case that if (eq (funcall HASH x1) (funcall HASH x2))
4540 returns nil, then (funcall TEST x1 x2) also returns nil. */)
4541 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4543 return Fput (name, Qhash_table_test, list2 (test, hash));
4548 /************************************************************************
4549 MD5, SHA-1, and SHA-2
4550 ************************************************************************/
4552 #include "md5.h"
4553 #include "sha1.h"
4554 #include "sha256.h"
4555 #include "sha512.h"
4557 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4559 static Lisp_Object
4560 secure_hash (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror, Lisp_Object binary)
4562 int i;
4563 ptrdiff_t size;
4564 EMACS_INT start_char = 0, end_char = 0;
4565 ptrdiff_t start_byte, end_byte;
4566 register EMACS_INT b, e;
4567 register struct buffer *bp;
4568 EMACS_INT temp;
4569 int digest_size;
4570 void *(*hash_func) (const char *, size_t, void *);
4571 Lisp_Object digest;
4573 CHECK_SYMBOL (algorithm);
4575 if (STRINGP (object))
4577 if (NILP (coding_system))
4579 /* Decide the coding-system to encode the data with. */
4581 if (STRING_MULTIBYTE (object))
4582 /* use default, we can't guess correct value */
4583 coding_system = preferred_coding_system ();
4584 else
4585 coding_system = Qraw_text;
4588 if (NILP (Fcoding_system_p (coding_system)))
4590 /* Invalid coding system. */
4592 if (!NILP (noerror))
4593 coding_system = Qraw_text;
4594 else
4595 xsignal1 (Qcoding_system_error, coding_system);
4598 if (STRING_MULTIBYTE (object))
4599 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4601 size = SCHARS (object);
4603 if (!NILP (start))
4605 CHECK_NUMBER (start);
4607 start_char = XINT (start);
4609 if (start_char < 0)
4610 start_char += size;
4613 if (NILP (end))
4614 end_char = size;
4615 else
4617 CHECK_NUMBER (end);
4619 end_char = XINT (end);
4621 if (end_char < 0)
4622 end_char += size;
4625 if (!(0 <= start_char && start_char <= end_char && end_char <= size))
4626 args_out_of_range_3 (object, make_number (start_char),
4627 make_number (end_char));
4629 start_byte = NILP (start) ? 0 : string_char_to_byte (object, start_char);
4630 end_byte =
4631 NILP (end) ? SBYTES (object) : string_char_to_byte (object, end_char);
4633 else
4635 struct buffer *prev = current_buffer;
4637 record_unwind_current_buffer ();
4639 CHECK_BUFFER (object);
4641 bp = XBUFFER (object);
4642 set_buffer_internal (bp);
4644 if (NILP (start))
4645 b = BEGV;
4646 else
4648 CHECK_NUMBER_COERCE_MARKER (start);
4649 b = XINT (start);
4652 if (NILP (end))
4653 e = ZV;
4654 else
4656 CHECK_NUMBER_COERCE_MARKER (end);
4657 e = XINT (end);
4660 if (b > e)
4661 temp = b, b = e, e = temp;
4663 if (!(BEGV <= b && e <= ZV))
4664 args_out_of_range (start, end);
4666 if (NILP (coding_system))
4668 /* Decide the coding-system to encode the data with.
4669 See fileio.c:Fwrite-region */
4671 if (!NILP (Vcoding_system_for_write))
4672 coding_system = Vcoding_system_for_write;
4673 else
4675 bool force_raw_text = 0;
4677 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4678 if (NILP (coding_system)
4679 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4681 coding_system = Qnil;
4682 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4683 force_raw_text = 1;
4686 if (NILP (coding_system) && !NILP (Fbuffer_file_name (object)))
4688 /* Check file-coding-system-alist. */
4689 Lisp_Object args[4], val;
4691 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4692 args[3] = Fbuffer_file_name (object);
4693 val = Ffind_operation_coding_system (4, args);
4694 if (CONSP (val) && !NILP (XCDR (val)))
4695 coding_system = XCDR (val);
4698 if (NILP (coding_system)
4699 && !NILP (BVAR (XBUFFER (object), buffer_file_coding_system)))
4701 /* If we still have not decided a coding system, use the
4702 default value of buffer-file-coding-system. */
4703 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4706 if (!force_raw_text
4707 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4708 /* Confirm that VAL can surely encode the current region. */
4709 coding_system = call4 (Vselect_safe_coding_system_function,
4710 make_number (b), make_number (e),
4711 coding_system, Qnil);
4713 if (force_raw_text)
4714 coding_system = Qraw_text;
4717 if (NILP (Fcoding_system_p (coding_system)))
4719 /* Invalid coding system. */
4721 if (!NILP (noerror))
4722 coding_system = Qraw_text;
4723 else
4724 xsignal1 (Qcoding_system_error, coding_system);
4728 object = make_buffer_string (b, e, 0);
4729 set_buffer_internal (prev);
4730 /* Discard the unwind protect for recovering the current
4731 buffer. */
4732 specpdl_ptr--;
4734 if (STRING_MULTIBYTE (object))
4735 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4736 start_byte = 0;
4737 end_byte = SBYTES (object);
4740 if (EQ (algorithm, Qmd5))
4742 digest_size = MD5_DIGEST_SIZE;
4743 hash_func = md5_buffer;
4745 else if (EQ (algorithm, Qsha1))
4747 digest_size = SHA1_DIGEST_SIZE;
4748 hash_func = sha1_buffer;
4750 else if (EQ (algorithm, Qsha224))
4752 digest_size = SHA224_DIGEST_SIZE;
4753 hash_func = sha224_buffer;
4755 else if (EQ (algorithm, Qsha256))
4757 digest_size = SHA256_DIGEST_SIZE;
4758 hash_func = sha256_buffer;
4760 else if (EQ (algorithm, Qsha384))
4762 digest_size = SHA384_DIGEST_SIZE;
4763 hash_func = sha384_buffer;
4765 else if (EQ (algorithm, Qsha512))
4767 digest_size = SHA512_DIGEST_SIZE;
4768 hash_func = sha512_buffer;
4770 else
4771 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm)));
4773 /* allocate 2 x digest_size so that it can be re-used to hold the
4774 hexified value */
4775 digest = make_uninit_string (digest_size * 2);
4777 hash_func (SSDATA (object) + start_byte,
4778 end_byte - start_byte,
4779 SSDATA (digest));
4781 if (NILP (binary))
4783 unsigned char *p = SDATA (digest);
4784 for (i = digest_size - 1; i >= 0; i--)
4786 static char const hexdigit[16] = "0123456789abcdef";
4787 int p_i = p[i];
4788 p[2 * i] = hexdigit[p_i >> 4];
4789 p[2 * i + 1] = hexdigit[p_i & 0xf];
4791 return digest;
4793 else
4794 return make_unibyte_string (SSDATA (digest), digest_size);
4797 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
4798 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
4800 A message digest is a cryptographic checksum of a document, and the
4801 algorithm to calculate it is defined in RFC 1321.
4803 The two optional arguments START and END are character positions
4804 specifying for which part of OBJECT the message digest should be
4805 computed. If nil or omitted, the digest is computed for the whole
4806 OBJECT.
4808 The MD5 message digest is computed from the result of encoding the
4809 text in a coding system, not directly from the internal Emacs form of
4810 the text. The optional fourth argument CODING-SYSTEM specifies which
4811 coding system to encode the text with. It should be the same coding
4812 system that you used or will use when actually writing the text into a
4813 file.
4815 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
4816 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
4817 system would be chosen by default for writing this text into a file.
4819 If OBJECT is a string, the most preferred coding system (see the
4820 command `prefer-coding-system') is used.
4822 If NOERROR is non-nil, silently assume the `raw-text' coding if the
4823 guesswork fails. Normally, an error is signaled in such case. */)
4824 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
4826 return secure_hash (Qmd5, object, start, end, coding_system, noerror, Qnil);
4829 DEFUN ("secure-hash", Fsecure_hash, Ssecure_hash, 2, 5, 0,
4830 doc: /* Return the secure hash of OBJECT, a buffer or string.
4831 ALGORITHM is a symbol specifying the hash to use:
4832 md5, sha1, sha224, sha256, sha384 or sha512.
4834 The two optional arguments START and END are positions specifying for
4835 which part of OBJECT to compute the hash. If nil or omitted, uses the
4836 whole OBJECT.
4838 If BINARY is non-nil, returns a string in binary form. */)
4839 (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object binary)
4841 return secure_hash (algorithm, object, start, end, Qnil, Qnil, binary);
4844 void
4845 syms_of_fns (void)
4847 DEFSYM (Qmd5, "md5");
4848 DEFSYM (Qsha1, "sha1");
4849 DEFSYM (Qsha224, "sha224");
4850 DEFSYM (Qsha256, "sha256");
4851 DEFSYM (Qsha384, "sha384");
4852 DEFSYM (Qsha512, "sha512");
4854 /* Hash table stuff. */
4855 DEFSYM (Qhash_table_p, "hash-table-p");
4856 DEFSYM (Qeq, "eq");
4857 DEFSYM (Qeql, "eql");
4858 DEFSYM (Qequal, "equal");
4859 DEFSYM (QCtest, ":test");
4860 DEFSYM (QCsize, ":size");
4861 DEFSYM (QCrehash_size, ":rehash-size");
4862 DEFSYM (QCrehash_threshold, ":rehash-threshold");
4863 DEFSYM (QCweakness, ":weakness");
4864 DEFSYM (Qkey, "key");
4865 DEFSYM (Qvalue, "value");
4866 DEFSYM (Qhash_table_test, "hash-table-test");
4867 DEFSYM (Qkey_or_value, "key-or-value");
4868 DEFSYM (Qkey_and_value, "key-and-value");
4870 defsubr (&Ssxhash);
4871 defsubr (&Smake_hash_table);
4872 defsubr (&Scopy_hash_table);
4873 defsubr (&Shash_table_count);
4874 defsubr (&Shash_table_rehash_size);
4875 defsubr (&Shash_table_rehash_threshold);
4876 defsubr (&Shash_table_size);
4877 defsubr (&Shash_table_test);
4878 defsubr (&Shash_table_weakness);
4879 defsubr (&Shash_table_p);
4880 defsubr (&Sclrhash);
4881 defsubr (&Sgethash);
4882 defsubr (&Sputhash);
4883 defsubr (&Sremhash);
4884 defsubr (&Smaphash);
4885 defsubr (&Sdefine_hash_table_test);
4887 DEFSYM (Qstring_lessp, "string-lessp");
4888 DEFSYM (Qprovide, "provide");
4889 DEFSYM (Qrequire, "require");
4890 DEFSYM (Qyes_or_no_p_history, "yes-or-no-p-history");
4891 DEFSYM (Qcursor_in_echo_area, "cursor-in-echo-area");
4892 DEFSYM (Qwidget_type, "widget-type");
4894 staticpro (&string_char_byte_cache_string);
4895 string_char_byte_cache_string = Qnil;
4897 require_nesting_list = Qnil;
4898 staticpro (&require_nesting_list);
4900 Fset (Qyes_or_no_p_history, Qnil);
4902 DEFVAR_LISP ("features", Vfeatures,
4903 doc: /* A list of symbols which are the features of the executing Emacs.
4904 Used by `featurep' and `require', and altered by `provide'. */);
4905 Vfeatures = list1 (intern_c_string ("emacs"));
4906 DEFSYM (Qsubfeatures, "subfeatures");
4907 DEFSYM (Qfuncall, "funcall");
4909 #ifdef HAVE_LANGINFO_CODESET
4910 DEFSYM (Qcodeset, "codeset");
4911 DEFSYM (Qdays, "days");
4912 DEFSYM (Qmonths, "months");
4913 DEFSYM (Qpaper, "paper");
4914 #endif /* HAVE_LANGINFO_CODESET */
4916 DEFVAR_BOOL ("use-dialog-box", use_dialog_box,
4917 doc: /* Non-nil means mouse commands use dialog boxes to ask questions.
4918 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
4919 invoked by mouse clicks and mouse menu items.
4921 On some platforms, file selection dialogs are also enabled if this is
4922 non-nil. */);
4923 use_dialog_box = 1;
4925 DEFVAR_BOOL ("use-file-dialog", use_file_dialog,
4926 doc: /* Non-nil means mouse commands use a file dialog to ask for files.
4927 This applies to commands from menus and tool bar buttons even when
4928 they are initiated from the keyboard. If `use-dialog-box' is nil,
4929 that disables the use of a file dialog, regardless of the value of
4930 this variable. */);
4931 use_file_dialog = 1;
4933 defsubr (&Sidentity);
4934 defsubr (&Srandom);
4935 defsubr (&Slength);
4936 defsubr (&Ssafe_length);
4937 defsubr (&Sstring_bytes);
4938 defsubr (&Sstring_equal);
4939 defsubr (&Scompare_strings);
4940 defsubr (&Sstring_lessp);
4941 defsubr (&Sappend);
4942 defsubr (&Sconcat);
4943 defsubr (&Svconcat);
4944 defsubr (&Scopy_sequence);
4945 defsubr (&Sstring_make_multibyte);
4946 defsubr (&Sstring_make_unibyte);
4947 defsubr (&Sstring_as_multibyte);
4948 defsubr (&Sstring_as_unibyte);
4949 defsubr (&Sstring_to_multibyte);
4950 defsubr (&Sstring_to_unibyte);
4951 defsubr (&Scopy_alist);
4952 defsubr (&Ssubstring);
4953 defsubr (&Ssubstring_no_properties);
4954 defsubr (&Snthcdr);
4955 defsubr (&Snth);
4956 defsubr (&Selt);
4957 defsubr (&Smember);
4958 defsubr (&Smemq);
4959 defsubr (&Smemql);
4960 defsubr (&Sassq);
4961 defsubr (&Sassoc);
4962 defsubr (&Srassq);
4963 defsubr (&Srassoc);
4964 defsubr (&Sdelq);
4965 defsubr (&Sdelete);
4966 defsubr (&Snreverse);
4967 defsubr (&Sreverse);
4968 defsubr (&Ssort);
4969 defsubr (&Splist_get);
4970 defsubr (&Sget);
4971 defsubr (&Splist_put);
4972 defsubr (&Sput);
4973 defsubr (&Slax_plist_get);
4974 defsubr (&Slax_plist_put);
4975 defsubr (&Seql);
4976 defsubr (&Sequal);
4977 defsubr (&Sequal_including_properties);
4978 defsubr (&Sfillarray);
4979 defsubr (&Sclear_string);
4980 defsubr (&Snconc);
4981 defsubr (&Smapcar);
4982 defsubr (&Smapc);
4983 defsubr (&Smapconcat);
4984 defsubr (&Syes_or_no_p);
4985 defsubr (&Sload_average);
4986 defsubr (&Sfeaturep);
4987 defsubr (&Srequire);
4988 defsubr (&Sprovide);
4989 defsubr (&Splist_member);
4990 defsubr (&Swidget_put);
4991 defsubr (&Swidget_get);
4992 defsubr (&Swidget_apply);
4993 defsubr (&Sbase64_encode_region);
4994 defsubr (&Sbase64_decode_region);
4995 defsubr (&Sbase64_encode_string);
4996 defsubr (&Sbase64_decode_string);
4997 defsubr (&Smd5);
4998 defsubr (&Ssecure_hash);
4999 defsubr (&Slocale_info);
5001 hashtest_eq.name = Qeq;
5002 hashtest_eq.user_hash_function = Qnil;
5003 hashtest_eq.user_cmp_function = Qnil;
5004 hashtest_eq.cmpfn = 0;
5005 hashtest_eq.hashfn = hashfn_eq;
5007 hashtest_eql.name = Qeql;
5008 hashtest_eql.user_hash_function = Qnil;
5009 hashtest_eql.user_cmp_function = Qnil;
5010 hashtest_eql.cmpfn = cmpfn_eql;
5011 hashtest_eql.hashfn = hashfn_eql;
5013 hashtest_equal.name = Qequal;
5014 hashtest_equal.user_hash_function = Qnil;
5015 hashtest_equal.user_cmp_function = Qnil;
5016 hashtest_equal.cmpfn = cmpfn_equal;
5017 hashtest_equal.hashfn = hashfn_equal;