Merge from emacs-24; up to 2013-01-03T02:37:57Z!rgm@gnu.org
[emacs.git] / src / fns.c
blob93829fb1d624009931488ea514130d972cce2804
1 /* Random utility Lisp functions.
3 Copyright (C) 1985-1987, 1993-1995, 1997-2013 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #include <unistd.h>
23 #include <time.h>
25 #include <intprops.h>
27 #include "lisp.h"
28 #include "commands.h"
29 #include "character.h"
30 #include "coding.h"
31 #include "buffer.h"
32 #include "keyboard.h"
33 #include "keymap.h"
34 #include "intervals.h"
35 #include "frame.h"
36 #include "window.h"
37 #include "blockinput.h"
38 #ifdef HAVE_MENUS
39 #if defined (HAVE_X_WINDOWS)
40 #include "xterm.h"
41 #endif
42 #endif /* HAVE_MENUS */
44 Lisp_Object Qstring_lessp;
45 static Lisp_Object Qprovide, Qrequire;
46 static Lisp_Object Qyes_or_no_p_history;
47 Lisp_Object Qcursor_in_echo_area;
48 static Lisp_Object Qwidget_type;
49 static Lisp_Object Qcodeset, Qdays, Qmonths, Qpaper;
51 static Lisp_Object Qmd5, Qsha1, Qsha224, Qsha256, Qsha384, Qsha512;
53 static bool internal_equal (Lisp_Object, Lisp_Object, int, bool);
55 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
56 doc: /* Return the argument unchanged. */)
57 (Lisp_Object arg)
59 return arg;
62 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
63 doc: /* Return a pseudo-random number.
64 All integers representable in Lisp, i.e. between `most-negative-fixnum'
65 and `most-positive-fixnum', inclusive, are equally likely.
67 With positive integer LIMIT, return random number in interval [0,LIMIT).
68 With argument t, set the random number seed from the current time and pid.
69 With a string argument, set the seed based on the string's contents.
70 Other values of LIMIT are ignored.
72 See Info node `(elisp)Random Numbers' for more details. */)
73 (Lisp_Object limit)
75 EMACS_INT val;
77 if (EQ (limit, Qt))
78 init_random ();
79 else if (STRINGP (limit))
80 seed_random (SSDATA (limit), SBYTES (limit));
82 val = get_random ();
83 if (NATNUMP (limit) && XFASTINT (limit) != 0)
84 val %= XFASTINT (limit);
85 return make_number (val);
88 /* Heuristic on how many iterations of a tight loop can be safely done
89 before it's time to do a QUIT. This must be a power of 2. */
90 enum { QUIT_COUNT_HEURISTIC = 1 << 16 };
92 /* Random data-structure functions. */
94 static void
95 CHECK_LIST_END (Lisp_Object x, Lisp_Object y)
97 CHECK_TYPE (NILP (x), Qlistp, y);
100 DEFUN ("length", Flength, Slength, 1, 1, 0,
101 doc: /* Return the length of vector, list or string SEQUENCE.
102 A byte-code function object is also allowed.
103 If the string contains multibyte characters, this is not necessarily
104 the number of bytes in the string; it is the number of characters.
105 To get the number of bytes, use `string-bytes'. */)
106 (register Lisp_Object sequence)
108 register Lisp_Object val;
110 if (STRINGP (sequence))
111 XSETFASTINT (val, SCHARS (sequence));
112 else if (VECTORP (sequence))
113 XSETFASTINT (val, ASIZE (sequence));
114 else if (CHAR_TABLE_P (sequence))
115 XSETFASTINT (val, MAX_CHAR);
116 else if (BOOL_VECTOR_P (sequence))
117 XSETFASTINT (val, bool_vector_size (sequence));
118 else if (COMPILEDP (sequence))
119 XSETFASTINT (val, ASIZE (sequence) & PSEUDOVECTOR_SIZE_MASK);
120 else if (CONSP (sequence))
122 EMACS_INT i = 0;
126 ++i;
127 if ((i & (QUIT_COUNT_HEURISTIC - 1)) == 0)
129 if (MOST_POSITIVE_FIXNUM < i)
130 error ("List too long");
131 QUIT;
133 sequence = XCDR (sequence);
135 while (CONSP (sequence));
137 CHECK_LIST_END (sequence, sequence);
139 val = make_number (i);
141 else if (NILP (sequence))
142 XSETFASTINT (val, 0);
143 else
144 wrong_type_argument (Qsequencep, sequence);
146 return val;
149 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
150 doc: /* Return the length of a list, but avoid error or infinite loop.
151 This function never gets an error. If LIST is not really a list,
152 it returns 0. If LIST is circular, it returns a finite value
153 which is at least the number of distinct elements. */)
154 (Lisp_Object list)
156 Lisp_Object tail, halftail;
157 double hilen = 0;
158 uintmax_t lolen = 1;
160 if (! CONSP (list))
161 return make_number (0);
163 /* halftail is used to detect circular lists. */
164 for (tail = halftail = list; ; )
166 tail = XCDR (tail);
167 if (! CONSP (tail))
168 break;
169 if (EQ (tail, halftail))
170 break;
171 lolen++;
172 if ((lolen & 1) == 0)
174 halftail = XCDR (halftail);
175 if ((lolen & (QUIT_COUNT_HEURISTIC - 1)) == 0)
177 QUIT;
178 if (lolen == 0)
179 hilen += UINTMAX_MAX + 1.0;
184 /* If the length does not fit into a fixnum, return a float.
185 On all known practical machines this returns an upper bound on
186 the true length. */
187 return hilen ? make_float (hilen + lolen) : make_fixnum_or_float (lolen);
190 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
191 doc: /* Return the number of bytes in STRING.
192 If STRING is multibyte, this may be greater than the length of STRING. */)
193 (Lisp_Object string)
195 CHECK_STRING (string);
196 return make_number (SBYTES (string));
199 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
200 doc: /* Return t if two strings have identical contents.
201 Case is significant, but text properties are ignored.
202 Symbols are also allowed; their print names are used instead. */)
203 (register Lisp_Object s1, Lisp_Object s2)
205 if (SYMBOLP (s1))
206 s1 = SYMBOL_NAME (s1);
207 if (SYMBOLP (s2))
208 s2 = SYMBOL_NAME (s2);
209 CHECK_STRING (s1);
210 CHECK_STRING (s2);
212 if (SCHARS (s1) != SCHARS (s2)
213 || SBYTES (s1) != SBYTES (s2)
214 || memcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
215 return Qnil;
216 return Qt;
219 DEFUN ("compare-strings", Fcompare_strings, Scompare_strings, 6, 7, 0,
220 doc: /* Compare the contents of two strings, converting to multibyte if needed.
221 The arguments START1, END1, START2, and END2, if non-nil, are
222 positions specifying which parts of STR1 or STR2 to compare. In
223 string STR1, compare the part between START1 (inclusive) and END1
224 \(exclusive). If START1 is nil, it defaults to 0, the beginning of
225 the string; if END1 is nil, it defaults to the length of the string.
226 Likewise, in string STR2, compare the part between START2 and END2.
228 The strings are compared by the numeric values of their characters.
229 For instance, STR1 is "less than" STR2 if its first differing
230 character has a smaller numeric value. If IGNORE-CASE is non-nil,
231 characters are converted to lower-case before comparing them. Unibyte
232 strings are converted to multibyte for comparison.
234 The value is t if the strings (or specified portions) match.
235 If string STR1 is less, the value is a negative number N;
236 - 1 - N is the number of characters that match at the beginning.
237 If string STR1 is greater, the value is a positive number N;
238 N - 1 is the number of characters that match at the beginning. */)
239 (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2, Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
241 register ptrdiff_t end1_char, end2_char;
242 register ptrdiff_t i1, i1_byte, i2, i2_byte;
244 CHECK_STRING (str1);
245 CHECK_STRING (str2);
246 if (NILP (start1))
247 start1 = make_number (0);
248 if (NILP (start2))
249 start2 = make_number (0);
250 CHECK_NATNUM (start1);
251 CHECK_NATNUM (start2);
252 if (! NILP (end1))
253 CHECK_NATNUM (end1);
254 if (! NILP (end2))
255 CHECK_NATNUM (end2);
257 end1_char = SCHARS (str1);
258 if (! NILP (end1) && end1_char > XINT (end1))
259 end1_char = XINT (end1);
260 if (end1_char < XINT (start1))
261 args_out_of_range (str1, start1);
263 end2_char = SCHARS (str2);
264 if (! NILP (end2) && end2_char > XINT (end2))
265 end2_char = XINT (end2);
266 if (end2_char < XINT (start2))
267 args_out_of_range (str2, start2);
269 i1 = XINT (start1);
270 i2 = XINT (start2);
272 i1_byte = string_char_to_byte (str1, i1);
273 i2_byte = string_char_to_byte (str2, i2);
275 while (i1 < end1_char && i2 < end2_char)
277 /* When we find a mismatch, we must compare the
278 characters, not just the bytes. */
279 int c1, c2;
281 if (STRING_MULTIBYTE (str1))
282 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c1, str1, i1, i1_byte);
283 else
285 c1 = SREF (str1, i1++);
286 MAKE_CHAR_MULTIBYTE (c1);
289 if (STRING_MULTIBYTE (str2))
290 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c2, str2, i2, i2_byte);
291 else
293 c2 = SREF (str2, i2++);
294 MAKE_CHAR_MULTIBYTE (c2);
297 if (c1 == c2)
298 continue;
300 if (! NILP (ignore_case))
302 Lisp_Object tem;
304 tem = Fupcase (make_number (c1));
305 c1 = XINT (tem);
306 tem = Fupcase (make_number (c2));
307 c2 = XINT (tem);
310 if (c1 == c2)
311 continue;
313 /* Note that I1 has already been incremented
314 past the character that we are comparing;
315 hence we don't add or subtract 1 here. */
316 if (c1 < c2)
317 return make_number (- i1 + XINT (start1));
318 else
319 return make_number (i1 - XINT (start1));
322 if (i1 < end1_char)
323 return make_number (i1 - XINT (start1) + 1);
324 if (i2 < end2_char)
325 return make_number (- i1 + XINT (start1) - 1);
327 return Qt;
330 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
331 doc: /* Return t if first arg string is less than second in lexicographic order.
332 Case is significant.
333 Symbols are also allowed; their print names are used instead. */)
334 (register Lisp_Object s1, Lisp_Object s2)
336 register ptrdiff_t end;
337 register ptrdiff_t i1, i1_byte, i2, i2_byte;
339 if (SYMBOLP (s1))
340 s1 = SYMBOL_NAME (s1);
341 if (SYMBOLP (s2))
342 s2 = SYMBOL_NAME (s2);
343 CHECK_STRING (s1);
344 CHECK_STRING (s2);
346 i1 = i1_byte = i2 = i2_byte = 0;
348 end = SCHARS (s1);
349 if (end > SCHARS (s2))
350 end = SCHARS (s2);
352 while (i1 < end)
354 /* When we find a mismatch, we must compare the
355 characters, not just the bytes. */
356 int c1, c2;
358 FETCH_STRING_CHAR_ADVANCE (c1, s1, i1, i1_byte);
359 FETCH_STRING_CHAR_ADVANCE (c2, s2, i2, i2_byte);
361 if (c1 != c2)
362 return c1 < c2 ? Qt : Qnil;
364 return i1 < SCHARS (s2) ? Qt : Qnil;
367 static Lisp_Object concat (ptrdiff_t nargs, Lisp_Object *args,
368 enum Lisp_Type target_type, bool last_special);
370 /* ARGSUSED */
371 Lisp_Object
372 concat2 (Lisp_Object s1, Lisp_Object s2)
374 Lisp_Object args[2];
375 args[0] = s1;
376 args[1] = s2;
377 return concat (2, args, Lisp_String, 0);
380 /* ARGSUSED */
381 Lisp_Object
382 concat3 (Lisp_Object s1, Lisp_Object s2, Lisp_Object s3)
384 Lisp_Object args[3];
385 args[0] = s1;
386 args[1] = s2;
387 args[2] = s3;
388 return concat (3, args, Lisp_String, 0);
391 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
392 doc: /* Concatenate all the arguments and make the result a list.
393 The result is a list whose elements are the elements of all the arguments.
394 Each argument may be a list, vector or string.
395 The last argument is not copied, just used as the tail of the new list.
396 usage: (append &rest SEQUENCES) */)
397 (ptrdiff_t nargs, Lisp_Object *args)
399 return concat (nargs, args, Lisp_Cons, 1);
402 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
403 doc: /* Concatenate all the arguments and make the result a string.
404 The result is a string whose elements are the elements of all the arguments.
405 Each argument may be a string or a list or vector of characters (integers).
406 usage: (concat &rest SEQUENCES) */)
407 (ptrdiff_t nargs, Lisp_Object *args)
409 return concat (nargs, args, Lisp_String, 0);
412 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
413 doc: /* Concatenate all the arguments and make the result a vector.
414 The result is a vector whose elements are the elements of all the arguments.
415 Each argument may be a list, vector or string.
416 usage: (vconcat &rest SEQUENCES) */)
417 (ptrdiff_t nargs, Lisp_Object *args)
419 return concat (nargs, args, Lisp_Vectorlike, 0);
423 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
424 doc: /* Return a copy of a list, vector, string or char-table.
425 The elements of a list or vector are not copied; they are shared
426 with the original. */)
427 (Lisp_Object arg)
429 if (NILP (arg)) return arg;
431 if (CHAR_TABLE_P (arg))
433 return copy_char_table (arg);
436 if (BOOL_VECTOR_P (arg))
438 EMACS_INT nbits = bool_vector_size (arg);
439 ptrdiff_t nbytes = bool_vector_bytes (nbits);
440 Lisp_Object val = make_uninit_bool_vector (nbits);
441 memcpy (bool_vector_data (val), bool_vector_data (arg), nbytes);
442 return val;
445 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
446 wrong_type_argument (Qsequencep, arg);
448 return concat (1, &arg, XTYPE (arg), 0);
451 /* This structure holds information of an argument of `concat' that is
452 a string and has text properties to be copied. */
453 struct textprop_rec
455 ptrdiff_t argnum; /* refer to ARGS (arguments of `concat') */
456 ptrdiff_t from; /* refer to ARGS[argnum] (argument string) */
457 ptrdiff_t to; /* refer to VAL (the target string) */
460 static Lisp_Object
461 concat (ptrdiff_t nargs, Lisp_Object *args,
462 enum Lisp_Type target_type, bool last_special)
464 Lisp_Object val;
465 Lisp_Object tail;
466 Lisp_Object this;
467 ptrdiff_t toindex;
468 ptrdiff_t toindex_byte = 0;
469 EMACS_INT result_len;
470 EMACS_INT result_len_byte;
471 ptrdiff_t argnum;
472 Lisp_Object last_tail;
473 Lisp_Object prev;
474 bool some_multibyte;
475 /* When we make a multibyte string, we can't copy text properties
476 while concatenating each string because the length of resulting
477 string can't be decided until we finish the whole concatenation.
478 So, we record strings that have text properties to be copied
479 here, and copy the text properties after the concatenation. */
480 struct textprop_rec *textprops = NULL;
481 /* Number of elements in textprops. */
482 ptrdiff_t num_textprops = 0;
483 USE_SAFE_ALLOCA;
485 tail = Qnil;
487 /* In append, the last arg isn't treated like the others */
488 if (last_special && nargs > 0)
490 nargs--;
491 last_tail = args[nargs];
493 else
494 last_tail = Qnil;
496 /* Check each argument. */
497 for (argnum = 0; argnum < nargs; argnum++)
499 this = args[argnum];
500 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
501 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
502 wrong_type_argument (Qsequencep, this);
505 /* Compute total length in chars of arguments in RESULT_LEN.
506 If desired output is a string, also compute length in bytes
507 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
508 whether the result should be a multibyte string. */
509 result_len_byte = 0;
510 result_len = 0;
511 some_multibyte = 0;
512 for (argnum = 0; argnum < nargs; argnum++)
514 EMACS_INT len;
515 this = args[argnum];
516 len = XFASTINT (Flength (this));
517 if (target_type == Lisp_String)
519 /* We must count the number of bytes needed in the string
520 as well as the number of characters. */
521 ptrdiff_t i;
522 Lisp_Object ch;
523 int c;
524 ptrdiff_t this_len_byte;
526 if (VECTORP (this) || COMPILEDP (this))
527 for (i = 0; i < len; i++)
529 ch = AREF (this, i);
530 CHECK_CHARACTER (ch);
531 c = XFASTINT (ch);
532 this_len_byte = CHAR_BYTES (c);
533 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
534 string_overflow ();
535 result_len_byte += this_len_byte;
536 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
537 some_multibyte = 1;
539 else if (BOOL_VECTOR_P (this) && bool_vector_size (this) > 0)
540 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
541 else if (CONSP (this))
542 for (; CONSP (this); this = XCDR (this))
544 ch = XCAR (this);
545 CHECK_CHARACTER (ch);
546 c = XFASTINT (ch);
547 this_len_byte = CHAR_BYTES (c);
548 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
549 string_overflow ();
550 result_len_byte += this_len_byte;
551 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
552 some_multibyte = 1;
554 else if (STRINGP (this))
556 if (STRING_MULTIBYTE (this))
558 some_multibyte = 1;
559 this_len_byte = SBYTES (this);
561 else
562 this_len_byte = count_size_as_multibyte (SDATA (this),
563 SCHARS (this));
564 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
565 string_overflow ();
566 result_len_byte += this_len_byte;
570 result_len += len;
571 if (MOST_POSITIVE_FIXNUM < result_len)
572 memory_full (SIZE_MAX);
575 if (! some_multibyte)
576 result_len_byte = result_len;
578 /* Create the output object. */
579 if (target_type == Lisp_Cons)
580 val = Fmake_list (make_number (result_len), Qnil);
581 else if (target_type == Lisp_Vectorlike)
582 val = Fmake_vector (make_number (result_len), Qnil);
583 else if (some_multibyte)
584 val = make_uninit_multibyte_string (result_len, result_len_byte);
585 else
586 val = make_uninit_string (result_len);
588 /* In `append', if all but last arg are nil, return last arg. */
589 if (target_type == Lisp_Cons && EQ (val, Qnil))
590 return last_tail;
592 /* Copy the contents of the args into the result. */
593 if (CONSP (val))
594 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
595 else
596 toindex = 0, toindex_byte = 0;
598 prev = Qnil;
599 if (STRINGP (val))
600 SAFE_NALLOCA (textprops, 1, nargs);
602 for (argnum = 0; argnum < nargs; argnum++)
604 Lisp_Object thislen;
605 ptrdiff_t thisleni = 0;
606 register ptrdiff_t thisindex = 0;
607 register ptrdiff_t thisindex_byte = 0;
609 this = args[argnum];
610 if (!CONSP (this))
611 thislen = Flength (this), thisleni = XINT (thislen);
613 /* Between strings of the same kind, copy fast. */
614 if (STRINGP (this) && STRINGP (val)
615 && STRING_MULTIBYTE (this) == some_multibyte)
617 ptrdiff_t thislen_byte = SBYTES (this);
619 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
620 if (string_intervals (this))
622 textprops[num_textprops].argnum = argnum;
623 textprops[num_textprops].from = 0;
624 textprops[num_textprops++].to = toindex;
626 toindex_byte += thislen_byte;
627 toindex += thisleni;
629 /* Copy a single-byte string to a multibyte string. */
630 else if (STRINGP (this) && STRINGP (val))
632 if (string_intervals (this))
634 textprops[num_textprops].argnum = argnum;
635 textprops[num_textprops].from = 0;
636 textprops[num_textprops++].to = toindex;
638 toindex_byte += copy_text (SDATA (this),
639 SDATA (val) + toindex_byte,
640 SCHARS (this), 0, 1);
641 toindex += thisleni;
643 else
644 /* Copy element by element. */
645 while (1)
647 register Lisp_Object elt;
649 /* Fetch next element of `this' arg into `elt', or break if
650 `this' is exhausted. */
651 if (NILP (this)) break;
652 if (CONSP (this))
653 elt = XCAR (this), this = XCDR (this);
654 else if (thisindex >= thisleni)
655 break;
656 else if (STRINGP (this))
658 int c;
659 if (STRING_MULTIBYTE (this))
660 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
661 thisindex,
662 thisindex_byte);
663 else
665 c = SREF (this, thisindex); thisindex++;
666 if (some_multibyte && !ASCII_CHAR_P (c))
667 c = BYTE8_TO_CHAR (c);
669 XSETFASTINT (elt, c);
671 else if (BOOL_VECTOR_P (this))
673 elt = bool_vector_ref (this, thisindex);
674 thisindex++;
676 else
678 elt = AREF (this, thisindex);
679 thisindex++;
682 /* Store this element into the result. */
683 if (toindex < 0)
685 XSETCAR (tail, elt);
686 prev = tail;
687 tail = XCDR (tail);
689 else if (VECTORP (val))
691 ASET (val, toindex, elt);
692 toindex++;
694 else
696 int c;
697 CHECK_CHARACTER (elt);
698 c = XFASTINT (elt);
699 if (some_multibyte)
700 toindex_byte += CHAR_STRING (c, SDATA (val) + toindex_byte);
701 else
702 SSET (val, toindex_byte++, c);
703 toindex++;
707 if (!NILP (prev))
708 XSETCDR (prev, last_tail);
710 if (num_textprops > 0)
712 Lisp_Object props;
713 ptrdiff_t last_to_end = -1;
715 for (argnum = 0; argnum < num_textprops; argnum++)
717 this = args[textprops[argnum].argnum];
718 props = text_property_list (this,
719 make_number (0),
720 make_number (SCHARS (this)),
721 Qnil);
722 /* If successive arguments have properties, be sure that the
723 value of `composition' property be the copy. */
724 if (last_to_end == textprops[argnum].to)
725 make_composition_value_copy (props);
726 add_text_properties_from_list (val, props,
727 make_number (textprops[argnum].to));
728 last_to_end = textprops[argnum].to + SCHARS (this);
732 SAFE_FREE ();
733 return val;
736 static Lisp_Object string_char_byte_cache_string;
737 static ptrdiff_t string_char_byte_cache_charpos;
738 static ptrdiff_t string_char_byte_cache_bytepos;
740 void
741 clear_string_char_byte_cache (void)
743 string_char_byte_cache_string = Qnil;
746 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
748 ptrdiff_t
749 string_char_to_byte (Lisp_Object string, ptrdiff_t char_index)
751 ptrdiff_t i_byte;
752 ptrdiff_t best_below, best_below_byte;
753 ptrdiff_t best_above, best_above_byte;
755 best_below = best_below_byte = 0;
756 best_above = SCHARS (string);
757 best_above_byte = SBYTES (string);
758 if (best_above == best_above_byte)
759 return char_index;
761 if (EQ (string, string_char_byte_cache_string))
763 if (string_char_byte_cache_charpos < char_index)
765 best_below = string_char_byte_cache_charpos;
766 best_below_byte = string_char_byte_cache_bytepos;
768 else
770 best_above = string_char_byte_cache_charpos;
771 best_above_byte = string_char_byte_cache_bytepos;
775 if (char_index - best_below < best_above - char_index)
777 unsigned char *p = SDATA (string) + best_below_byte;
779 while (best_below < char_index)
781 p += BYTES_BY_CHAR_HEAD (*p);
782 best_below++;
784 i_byte = p - SDATA (string);
786 else
788 unsigned char *p = SDATA (string) + best_above_byte;
790 while (best_above > char_index)
792 p--;
793 while (!CHAR_HEAD_P (*p)) p--;
794 best_above--;
796 i_byte = p - SDATA (string);
799 string_char_byte_cache_bytepos = i_byte;
800 string_char_byte_cache_charpos = char_index;
801 string_char_byte_cache_string = string;
803 return i_byte;
806 /* Return the character index corresponding to BYTE_INDEX in STRING. */
808 ptrdiff_t
809 string_byte_to_char (Lisp_Object string, ptrdiff_t byte_index)
811 ptrdiff_t i, i_byte;
812 ptrdiff_t best_below, best_below_byte;
813 ptrdiff_t best_above, best_above_byte;
815 best_below = best_below_byte = 0;
816 best_above = SCHARS (string);
817 best_above_byte = SBYTES (string);
818 if (best_above == best_above_byte)
819 return byte_index;
821 if (EQ (string, string_char_byte_cache_string))
823 if (string_char_byte_cache_bytepos < byte_index)
825 best_below = string_char_byte_cache_charpos;
826 best_below_byte = string_char_byte_cache_bytepos;
828 else
830 best_above = string_char_byte_cache_charpos;
831 best_above_byte = string_char_byte_cache_bytepos;
835 if (byte_index - best_below_byte < best_above_byte - byte_index)
837 unsigned char *p = SDATA (string) + best_below_byte;
838 unsigned char *pend = SDATA (string) + byte_index;
840 while (p < pend)
842 p += BYTES_BY_CHAR_HEAD (*p);
843 best_below++;
845 i = best_below;
846 i_byte = p - SDATA (string);
848 else
850 unsigned char *p = SDATA (string) + best_above_byte;
851 unsigned char *pbeg = SDATA (string) + byte_index;
853 while (p > pbeg)
855 p--;
856 while (!CHAR_HEAD_P (*p)) p--;
857 best_above--;
859 i = best_above;
860 i_byte = p - SDATA (string);
863 string_char_byte_cache_bytepos = i_byte;
864 string_char_byte_cache_charpos = i;
865 string_char_byte_cache_string = string;
867 return i;
870 /* Convert STRING to a multibyte string. */
872 static Lisp_Object
873 string_make_multibyte (Lisp_Object string)
875 unsigned char *buf;
876 ptrdiff_t nbytes;
877 Lisp_Object ret;
878 USE_SAFE_ALLOCA;
880 if (STRING_MULTIBYTE (string))
881 return string;
883 nbytes = count_size_as_multibyte (SDATA (string),
884 SCHARS (string));
885 /* If all the chars are ASCII, they won't need any more bytes
886 once converted. In that case, we can return STRING itself. */
887 if (nbytes == SBYTES (string))
888 return string;
890 buf = SAFE_ALLOCA (nbytes);
891 copy_text (SDATA (string), buf, SBYTES (string),
892 0, 1);
894 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
895 SAFE_FREE ();
897 return ret;
901 /* Convert STRING (if unibyte) to a multibyte string without changing
902 the number of characters. Characters 0200 trough 0237 are
903 converted to eight-bit characters. */
905 Lisp_Object
906 string_to_multibyte (Lisp_Object string)
908 unsigned char *buf;
909 ptrdiff_t nbytes;
910 Lisp_Object ret;
911 USE_SAFE_ALLOCA;
913 if (STRING_MULTIBYTE (string))
914 return string;
916 nbytes = count_size_as_multibyte (SDATA (string), SBYTES (string));
917 /* If all the chars are ASCII, they won't need any more bytes once
918 converted. */
919 if (nbytes == SBYTES (string))
920 return make_multibyte_string (SSDATA (string), nbytes, nbytes);
922 buf = SAFE_ALLOCA (nbytes);
923 memcpy (buf, SDATA (string), SBYTES (string));
924 str_to_multibyte (buf, nbytes, SBYTES (string));
926 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
927 SAFE_FREE ();
929 return ret;
933 /* Convert STRING to a single-byte string. */
935 Lisp_Object
936 string_make_unibyte (Lisp_Object string)
938 ptrdiff_t nchars;
939 unsigned char *buf;
940 Lisp_Object ret;
941 USE_SAFE_ALLOCA;
943 if (! STRING_MULTIBYTE (string))
944 return string;
946 nchars = SCHARS (string);
948 buf = SAFE_ALLOCA (nchars);
949 copy_text (SDATA (string), buf, SBYTES (string),
950 1, 0);
952 ret = make_unibyte_string ((char *) buf, nchars);
953 SAFE_FREE ();
955 return ret;
958 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
959 1, 1, 0,
960 doc: /* Return the multibyte equivalent of STRING.
961 If STRING is unibyte and contains non-ASCII characters, the function
962 `unibyte-char-to-multibyte' is used to convert each unibyte character
963 to a multibyte character. In this case, the returned string is a
964 newly created string with no text properties. If STRING is multibyte
965 or entirely ASCII, it is returned unchanged. In particular, when
966 STRING is unibyte and entirely ASCII, the returned string is unibyte.
967 \(When the characters are all ASCII, Emacs primitives will treat the
968 string the same way whether it is unibyte or multibyte.) */)
969 (Lisp_Object string)
971 CHECK_STRING (string);
973 return string_make_multibyte (string);
976 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
977 1, 1, 0,
978 doc: /* Return the unibyte equivalent of STRING.
979 Multibyte character codes are converted to unibyte according to
980 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
981 If the lookup in the translation table fails, this function takes just
982 the low 8 bits of each character. */)
983 (Lisp_Object string)
985 CHECK_STRING (string);
987 return string_make_unibyte (string);
990 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
991 1, 1, 0,
992 doc: /* Return a unibyte string with the same individual bytes as STRING.
993 If STRING is unibyte, the result is STRING itself.
994 Otherwise it is a newly created string, with no text properties.
995 If STRING is multibyte and contains a character of charset
996 `eight-bit', it is converted to the corresponding single byte. */)
997 (Lisp_Object string)
999 CHECK_STRING (string);
1001 if (STRING_MULTIBYTE (string))
1003 unsigned char *str = (unsigned char *) xlispstrdup (string);
1004 ptrdiff_t bytes = str_as_unibyte (str, SBYTES (string));
1006 string = make_unibyte_string ((char *) str, bytes);
1007 xfree (str);
1009 return string;
1012 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1013 1, 1, 0,
1014 doc: /* Return a multibyte string with the same individual bytes as STRING.
1015 If STRING is multibyte, the result is STRING itself.
1016 Otherwise it is a newly created string, with no text properties.
1018 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1019 part of a correct utf-8 sequence), it is converted to the corresponding
1020 multibyte character of charset `eight-bit'.
1021 See also `string-to-multibyte'.
1023 Beware, this often doesn't really do what you think it does.
1024 It is similar to (decode-coding-string STRING 'utf-8-emacs).
1025 If you're not sure, whether to use `string-as-multibyte' or
1026 `string-to-multibyte', use `string-to-multibyte'. */)
1027 (Lisp_Object string)
1029 CHECK_STRING (string);
1031 if (! STRING_MULTIBYTE (string))
1033 Lisp_Object new_string;
1034 ptrdiff_t nchars, nbytes;
1036 parse_str_as_multibyte (SDATA (string),
1037 SBYTES (string),
1038 &nchars, &nbytes);
1039 new_string = make_uninit_multibyte_string (nchars, nbytes);
1040 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1041 if (nbytes != SBYTES (string))
1042 str_as_multibyte (SDATA (new_string), nbytes,
1043 SBYTES (string), NULL);
1044 string = new_string;
1045 set_string_intervals (string, NULL);
1047 return string;
1050 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1051 1, 1, 0,
1052 doc: /* Return a multibyte string with the same individual chars as STRING.
1053 If STRING is multibyte, the result is STRING itself.
1054 Otherwise it is a newly created string, with no text properties.
1056 If STRING is unibyte and contains an 8-bit byte, it is converted to
1057 the corresponding multibyte character of charset `eight-bit'.
1059 This differs from `string-as-multibyte' by converting each byte of a correct
1060 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1061 correct sequence. */)
1062 (Lisp_Object string)
1064 CHECK_STRING (string);
1066 return string_to_multibyte (string);
1069 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1070 1, 1, 0,
1071 doc: /* Return a unibyte string with the same individual chars as STRING.
1072 If STRING is unibyte, the result is STRING itself.
1073 Otherwise it is a newly created string, with no text properties,
1074 where each `eight-bit' character is converted to the corresponding byte.
1075 If STRING contains a non-ASCII, non-`eight-bit' character,
1076 an error is signaled. */)
1077 (Lisp_Object string)
1079 CHECK_STRING (string);
1081 if (STRING_MULTIBYTE (string))
1083 ptrdiff_t chars = SCHARS (string);
1084 unsigned char *str = xmalloc (chars);
1085 ptrdiff_t converted = str_to_unibyte (SDATA (string), str, chars);
1087 if (converted < chars)
1088 error ("Can't convert the %"pD"dth character to unibyte", converted);
1089 string = make_unibyte_string ((char *) str, chars);
1090 xfree (str);
1092 return string;
1096 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1097 doc: /* Return a copy of ALIST.
1098 This is an alist which represents the same mapping from objects to objects,
1099 but does not share the alist structure with ALIST.
1100 The objects mapped (cars and cdrs of elements of the alist)
1101 are shared, however.
1102 Elements of ALIST that are not conses are also shared. */)
1103 (Lisp_Object alist)
1105 register Lisp_Object tem;
1107 CHECK_LIST (alist);
1108 if (NILP (alist))
1109 return alist;
1110 alist = concat (1, &alist, Lisp_Cons, 0);
1111 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1113 register Lisp_Object car;
1114 car = XCAR (tem);
1116 if (CONSP (car))
1117 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1119 return alist;
1122 DEFUN ("substring", Fsubstring, Ssubstring, 2, 3, 0,
1123 doc: /* Return a new string whose contents are a substring of STRING.
1124 The returned string consists of the characters between index FROM
1125 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1126 zero-indexed: 0 means the first character of STRING. Negative values
1127 are counted from the end of STRING. If TO is nil, the substring runs
1128 to the end of STRING.
1130 The STRING argument may also be a vector. In that case, the return
1131 value is a new vector that contains the elements between index FROM
1132 \(inclusive) and index TO (exclusive) of that vector argument. */)
1133 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1135 Lisp_Object res;
1136 ptrdiff_t size;
1137 EMACS_INT from_char, to_char;
1139 CHECK_VECTOR_OR_STRING (string);
1140 CHECK_NUMBER (from);
1142 if (STRINGP (string))
1143 size = SCHARS (string);
1144 else
1145 size = ASIZE (string);
1147 if (NILP (to))
1148 to_char = size;
1149 else
1151 CHECK_NUMBER (to);
1153 to_char = XINT (to);
1154 if (to_char < 0)
1155 to_char += size;
1158 from_char = XINT (from);
1159 if (from_char < 0)
1160 from_char += size;
1161 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1162 args_out_of_range_3 (string, make_number (from_char),
1163 make_number (to_char));
1165 if (STRINGP (string))
1167 ptrdiff_t to_byte =
1168 (NILP (to) ? SBYTES (string) : string_char_to_byte (string, to_char));
1169 ptrdiff_t from_byte = string_char_to_byte (string, from_char);
1170 res = make_specified_string (SSDATA (string) + from_byte,
1171 to_char - from_char, to_byte - from_byte,
1172 STRING_MULTIBYTE (string));
1173 copy_text_properties (make_number (from_char), make_number (to_char),
1174 string, make_number (0), res, Qnil);
1176 else
1177 res = Fvector (to_char - from_char, aref_addr (string, from_char));
1179 return res;
1183 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1184 doc: /* Return a substring of STRING, without text properties.
1185 It starts at index FROM and ends before TO.
1186 TO may be nil or omitted; then the substring runs to the end of STRING.
1187 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1188 If FROM or TO is negative, it counts from the end.
1190 With one argument, just copy STRING without its properties. */)
1191 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1193 ptrdiff_t size;
1194 EMACS_INT from_char, to_char;
1195 ptrdiff_t from_byte, to_byte;
1197 CHECK_STRING (string);
1199 size = SCHARS (string);
1201 if (NILP (from))
1202 from_char = 0;
1203 else
1205 CHECK_NUMBER (from);
1206 from_char = XINT (from);
1207 if (from_char < 0)
1208 from_char += size;
1211 if (NILP (to))
1212 to_char = size;
1213 else
1215 CHECK_NUMBER (to);
1216 to_char = XINT (to);
1217 if (to_char < 0)
1218 to_char += size;
1221 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1222 args_out_of_range_3 (string, make_number (from_char),
1223 make_number (to_char));
1225 from_byte = NILP (from) ? 0 : string_char_to_byte (string, from_char);
1226 to_byte =
1227 NILP (to) ? SBYTES (string) : string_char_to_byte (string, to_char);
1228 return make_specified_string (SSDATA (string) + from_byte,
1229 to_char - from_char, to_byte - from_byte,
1230 STRING_MULTIBYTE (string));
1233 /* Extract a substring of STRING, giving start and end positions
1234 both in characters and in bytes. */
1236 Lisp_Object
1237 substring_both (Lisp_Object string, ptrdiff_t from, ptrdiff_t from_byte,
1238 ptrdiff_t to, ptrdiff_t to_byte)
1240 Lisp_Object res;
1241 ptrdiff_t size;
1243 CHECK_VECTOR_OR_STRING (string);
1245 size = STRINGP (string) ? SCHARS (string) : ASIZE (string);
1247 if (!(0 <= from && from <= to && to <= size))
1248 args_out_of_range_3 (string, make_number (from), make_number (to));
1250 if (STRINGP (string))
1252 res = make_specified_string (SSDATA (string) + from_byte,
1253 to - from, to_byte - from_byte,
1254 STRING_MULTIBYTE (string));
1255 copy_text_properties (make_number (from), make_number (to),
1256 string, make_number (0), res, Qnil);
1258 else
1259 res = Fvector (to - from, aref_addr (string, from));
1261 return res;
1264 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1265 doc: /* Take cdr N times on LIST, return the result. */)
1266 (Lisp_Object n, Lisp_Object list)
1268 EMACS_INT i, num;
1269 CHECK_NUMBER (n);
1270 num = XINT (n);
1271 for (i = 0; i < num && !NILP (list); i++)
1273 QUIT;
1274 CHECK_LIST_CONS (list, list);
1275 list = XCDR (list);
1277 return list;
1280 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1281 doc: /* Return the Nth element of LIST.
1282 N counts from zero. If LIST is not that long, nil is returned. */)
1283 (Lisp_Object n, Lisp_Object list)
1285 return Fcar (Fnthcdr (n, list));
1288 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1289 doc: /* Return element of SEQUENCE at index N. */)
1290 (register Lisp_Object sequence, Lisp_Object n)
1292 CHECK_NUMBER (n);
1293 if (CONSP (sequence) || NILP (sequence))
1294 return Fcar (Fnthcdr (n, sequence));
1296 /* Faref signals a "not array" error, so check here. */
1297 CHECK_ARRAY (sequence, Qsequencep);
1298 return Faref (sequence, n);
1301 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1302 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1303 The value is actually the tail of LIST whose car is ELT. */)
1304 (register Lisp_Object elt, Lisp_Object list)
1306 register Lisp_Object tail;
1307 for (tail = list; CONSP (tail); tail = XCDR (tail))
1309 register Lisp_Object tem;
1310 CHECK_LIST_CONS (tail, list);
1311 tem = XCAR (tail);
1312 if (! NILP (Fequal (elt, tem)))
1313 return tail;
1314 QUIT;
1316 return Qnil;
1319 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1320 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1321 The value is actually the tail of LIST whose car is ELT. */)
1322 (register Lisp_Object elt, Lisp_Object list)
1324 while (1)
1326 if (!CONSP (list) || EQ (XCAR (list), elt))
1327 break;
1329 list = XCDR (list);
1330 if (!CONSP (list) || EQ (XCAR (list), elt))
1331 break;
1333 list = XCDR (list);
1334 if (!CONSP (list) || EQ (XCAR (list), elt))
1335 break;
1337 list = XCDR (list);
1338 QUIT;
1341 CHECK_LIST (list);
1342 return list;
1345 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1346 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1347 The value is actually the tail of LIST whose car is ELT. */)
1348 (register Lisp_Object elt, Lisp_Object list)
1350 register Lisp_Object tail;
1352 if (!FLOATP (elt))
1353 return Fmemq (elt, list);
1355 for (tail = list; CONSP (tail); tail = XCDR (tail))
1357 register Lisp_Object tem;
1358 CHECK_LIST_CONS (tail, list);
1359 tem = XCAR (tail);
1360 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0))
1361 return tail;
1362 QUIT;
1364 return Qnil;
1367 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1368 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1369 The value is actually the first element of LIST whose car is KEY.
1370 Elements of LIST that are not conses are ignored. */)
1371 (Lisp_Object key, Lisp_Object list)
1373 while (1)
1375 if (!CONSP (list)
1376 || (CONSP (XCAR (list))
1377 && EQ (XCAR (XCAR (list)), key)))
1378 break;
1380 list = XCDR (list);
1381 if (!CONSP (list)
1382 || (CONSP (XCAR (list))
1383 && EQ (XCAR (XCAR (list)), key)))
1384 break;
1386 list = XCDR (list);
1387 if (!CONSP (list)
1388 || (CONSP (XCAR (list))
1389 && EQ (XCAR (XCAR (list)), key)))
1390 break;
1392 list = XCDR (list);
1393 QUIT;
1396 return CAR (list);
1399 /* Like Fassq but never report an error and do not allow quits.
1400 Use only on lists known never to be circular. */
1402 Lisp_Object
1403 assq_no_quit (Lisp_Object key, Lisp_Object list)
1405 while (CONSP (list)
1406 && (!CONSP (XCAR (list))
1407 || !EQ (XCAR (XCAR (list)), key)))
1408 list = XCDR (list);
1410 return CAR_SAFE (list);
1413 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1414 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1415 The value is actually the first element of LIST whose car equals KEY. */)
1416 (Lisp_Object key, Lisp_Object list)
1418 Lisp_Object car;
1420 while (1)
1422 if (!CONSP (list)
1423 || (CONSP (XCAR (list))
1424 && (car = XCAR (XCAR (list)),
1425 EQ (car, key) || !NILP (Fequal (car, key)))))
1426 break;
1428 list = XCDR (list);
1429 if (!CONSP (list)
1430 || (CONSP (XCAR (list))
1431 && (car = XCAR (XCAR (list)),
1432 EQ (car, key) || !NILP (Fequal (car, key)))))
1433 break;
1435 list = XCDR (list);
1436 if (!CONSP (list)
1437 || (CONSP (XCAR (list))
1438 && (car = XCAR (XCAR (list)),
1439 EQ (car, key) || !NILP (Fequal (car, key)))))
1440 break;
1442 list = XCDR (list);
1443 QUIT;
1446 return CAR (list);
1449 /* Like Fassoc but never report an error and do not allow quits.
1450 Use only on lists known never to be circular. */
1452 Lisp_Object
1453 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1455 while (CONSP (list)
1456 && (!CONSP (XCAR (list))
1457 || (!EQ (XCAR (XCAR (list)), key)
1458 && NILP (Fequal (XCAR (XCAR (list)), key)))))
1459 list = XCDR (list);
1461 return CONSP (list) ? XCAR (list) : Qnil;
1464 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1465 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1466 The value is actually the first element of LIST whose cdr is KEY. */)
1467 (register Lisp_Object key, Lisp_Object list)
1469 while (1)
1471 if (!CONSP (list)
1472 || (CONSP (XCAR (list))
1473 && EQ (XCDR (XCAR (list)), key)))
1474 break;
1476 list = XCDR (list);
1477 if (!CONSP (list)
1478 || (CONSP (XCAR (list))
1479 && EQ (XCDR (XCAR (list)), key)))
1480 break;
1482 list = XCDR (list);
1483 if (!CONSP (list)
1484 || (CONSP (XCAR (list))
1485 && EQ (XCDR (XCAR (list)), key)))
1486 break;
1488 list = XCDR (list);
1489 QUIT;
1492 return CAR (list);
1495 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1496 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1497 The value is actually the first element of LIST whose cdr equals KEY. */)
1498 (Lisp_Object key, Lisp_Object list)
1500 Lisp_Object cdr;
1502 while (1)
1504 if (!CONSP (list)
1505 || (CONSP (XCAR (list))
1506 && (cdr = XCDR (XCAR (list)),
1507 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1508 break;
1510 list = XCDR (list);
1511 if (!CONSP (list)
1512 || (CONSP (XCAR (list))
1513 && (cdr = XCDR (XCAR (list)),
1514 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1515 break;
1517 list = XCDR (list);
1518 if (!CONSP (list)
1519 || (CONSP (XCAR (list))
1520 && (cdr = XCDR (XCAR (list)),
1521 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1522 break;
1524 list = XCDR (list);
1525 QUIT;
1528 return CAR (list);
1531 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1532 doc: /* Delete members of LIST which are `eq' to ELT, and return the result.
1533 More precisely, this function skips any members `eq' to ELT at the
1534 front of LIST, then removes members `eq' to ELT from the remaining
1535 sublist by modifying its list structure, then returns the resulting
1536 list.
1538 Write `(setq foo (delq element foo))' to be sure of correctly changing
1539 the value of a list `foo'. */)
1540 (register Lisp_Object elt, Lisp_Object list)
1542 register Lisp_Object tail, prev;
1543 register Lisp_Object tem;
1545 tail = list;
1546 prev = Qnil;
1547 while (CONSP (tail))
1549 CHECK_LIST_CONS (tail, list);
1550 tem = XCAR (tail);
1551 if (EQ (elt, tem))
1553 if (NILP (prev))
1554 list = XCDR (tail);
1555 else
1556 Fsetcdr (prev, XCDR (tail));
1558 else
1559 prev = tail;
1560 tail = XCDR (tail);
1561 QUIT;
1563 return list;
1566 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1567 doc: /* Delete members of SEQ which are `equal' to ELT, and return the result.
1568 SEQ must be a sequence (i.e. a list, a vector, or a string).
1569 The return value is a sequence of the same type.
1571 If SEQ is a list, this behaves like `delq', except that it compares
1572 with `equal' instead of `eq'. In particular, it may remove elements
1573 by altering the list structure.
1575 If SEQ is not a list, deletion is never performed destructively;
1576 instead this function creates and returns a new vector or string.
1578 Write `(setq foo (delete element foo))' to be sure of correctly
1579 changing the value of a sequence `foo'. */)
1580 (Lisp_Object elt, Lisp_Object seq)
1582 if (VECTORP (seq))
1584 ptrdiff_t i, n;
1586 for (i = n = 0; i < ASIZE (seq); ++i)
1587 if (NILP (Fequal (AREF (seq, i), elt)))
1588 ++n;
1590 if (n != ASIZE (seq))
1592 struct Lisp_Vector *p = allocate_vector (n);
1594 for (i = n = 0; i < ASIZE (seq); ++i)
1595 if (NILP (Fequal (AREF (seq, i), elt)))
1596 p->contents[n++] = AREF (seq, i);
1598 XSETVECTOR (seq, p);
1601 else if (STRINGP (seq))
1603 ptrdiff_t i, ibyte, nchars, nbytes, cbytes;
1604 int c;
1606 for (i = nchars = nbytes = ibyte = 0;
1607 i < SCHARS (seq);
1608 ++i, ibyte += cbytes)
1610 if (STRING_MULTIBYTE (seq))
1612 c = STRING_CHAR (SDATA (seq) + ibyte);
1613 cbytes = CHAR_BYTES (c);
1615 else
1617 c = SREF (seq, i);
1618 cbytes = 1;
1621 if (!INTEGERP (elt) || c != XINT (elt))
1623 ++nchars;
1624 nbytes += cbytes;
1628 if (nchars != SCHARS (seq))
1630 Lisp_Object tem;
1632 tem = make_uninit_multibyte_string (nchars, nbytes);
1633 if (!STRING_MULTIBYTE (seq))
1634 STRING_SET_UNIBYTE (tem);
1636 for (i = nchars = nbytes = ibyte = 0;
1637 i < SCHARS (seq);
1638 ++i, ibyte += cbytes)
1640 if (STRING_MULTIBYTE (seq))
1642 c = STRING_CHAR (SDATA (seq) + ibyte);
1643 cbytes = CHAR_BYTES (c);
1645 else
1647 c = SREF (seq, i);
1648 cbytes = 1;
1651 if (!INTEGERP (elt) || c != XINT (elt))
1653 unsigned char *from = SDATA (seq) + ibyte;
1654 unsigned char *to = SDATA (tem) + nbytes;
1655 ptrdiff_t n;
1657 ++nchars;
1658 nbytes += cbytes;
1660 for (n = cbytes; n--; )
1661 *to++ = *from++;
1665 seq = tem;
1668 else
1670 Lisp_Object tail, prev;
1672 for (tail = seq, prev = Qnil; CONSP (tail); tail = XCDR (tail))
1674 CHECK_LIST_CONS (tail, seq);
1676 if (!NILP (Fequal (elt, XCAR (tail))))
1678 if (NILP (prev))
1679 seq = XCDR (tail);
1680 else
1681 Fsetcdr (prev, XCDR (tail));
1683 else
1684 prev = tail;
1685 QUIT;
1689 return seq;
1692 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1693 doc: /* Reverse LIST by modifying cdr pointers.
1694 Return the reversed list. Expects a properly nil-terminated list. */)
1695 (Lisp_Object list)
1697 register Lisp_Object prev, tail, next;
1699 if (NILP (list)) return list;
1700 prev = Qnil;
1701 tail = list;
1702 while (!NILP (tail))
1704 QUIT;
1705 CHECK_LIST_CONS (tail, tail);
1706 next = XCDR (tail);
1707 Fsetcdr (tail, prev);
1708 prev = tail;
1709 tail = next;
1711 return prev;
1714 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1715 doc: /* Reverse LIST, copying. Return the reversed list.
1716 See also the function `nreverse', which is used more often. */)
1717 (Lisp_Object list)
1719 Lisp_Object new;
1721 for (new = Qnil; CONSP (list); list = XCDR (list))
1723 QUIT;
1724 new = Fcons (XCAR (list), new);
1726 CHECK_LIST_END (list, list);
1727 return new;
1730 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
1731 doc: /* Sort LIST, stably, comparing elements using PREDICATE.
1732 Returns the sorted list. LIST is modified by side effects.
1733 PREDICATE is called with two elements of LIST, and should return non-nil
1734 if the first element should sort before the second. */)
1735 (Lisp_Object list, Lisp_Object predicate)
1737 Lisp_Object front, back;
1738 register Lisp_Object len, tem;
1739 struct gcpro gcpro1, gcpro2;
1740 EMACS_INT length;
1742 front = list;
1743 len = Flength (list);
1744 length = XINT (len);
1745 if (length < 2)
1746 return list;
1748 XSETINT (len, (length / 2) - 1);
1749 tem = Fnthcdr (len, list);
1750 back = Fcdr (tem);
1751 Fsetcdr (tem, Qnil);
1753 GCPRO2 (front, back);
1754 front = Fsort (front, predicate);
1755 back = Fsort (back, predicate);
1756 UNGCPRO;
1757 return merge (front, back, predicate);
1760 Lisp_Object
1761 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
1763 Lisp_Object value;
1764 register Lisp_Object tail;
1765 Lisp_Object tem;
1766 register Lisp_Object l1, l2;
1767 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1769 l1 = org_l1;
1770 l2 = org_l2;
1771 tail = Qnil;
1772 value = Qnil;
1774 /* It is sufficient to protect org_l1 and org_l2.
1775 When l1 and l2 are updated, we copy the new values
1776 back into the org_ vars. */
1777 GCPRO4 (org_l1, org_l2, pred, value);
1779 while (1)
1781 if (NILP (l1))
1783 UNGCPRO;
1784 if (NILP (tail))
1785 return l2;
1786 Fsetcdr (tail, l2);
1787 return value;
1789 if (NILP (l2))
1791 UNGCPRO;
1792 if (NILP (tail))
1793 return l1;
1794 Fsetcdr (tail, l1);
1795 return value;
1797 tem = call2 (pred, Fcar (l2), Fcar (l1));
1798 if (NILP (tem))
1800 tem = l1;
1801 l1 = Fcdr (l1);
1802 org_l1 = l1;
1804 else
1806 tem = l2;
1807 l2 = Fcdr (l2);
1808 org_l2 = l2;
1810 if (NILP (tail))
1811 value = tem;
1812 else
1813 Fsetcdr (tail, tem);
1814 tail = tem;
1819 /* This does not check for quits. That is safe since it must terminate. */
1821 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
1822 doc: /* Extract a value from a property list.
1823 PLIST is a property list, which is a list of the form
1824 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1825 corresponding to the given PROP, or nil if PROP is not one of the
1826 properties on the list. This function never signals an error. */)
1827 (Lisp_Object plist, Lisp_Object prop)
1829 Lisp_Object tail, halftail;
1831 /* halftail is used to detect circular lists. */
1832 tail = halftail = plist;
1833 while (CONSP (tail) && CONSP (XCDR (tail)))
1835 if (EQ (prop, XCAR (tail)))
1836 return XCAR (XCDR (tail));
1838 tail = XCDR (XCDR (tail));
1839 halftail = XCDR (halftail);
1840 if (EQ (tail, halftail))
1841 break;
1844 return Qnil;
1847 DEFUN ("get", Fget, Sget, 2, 2, 0,
1848 doc: /* Return the value of SYMBOL's PROPNAME property.
1849 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
1850 (Lisp_Object symbol, Lisp_Object propname)
1852 CHECK_SYMBOL (symbol);
1853 return Fplist_get (XSYMBOL (symbol)->plist, propname);
1856 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
1857 doc: /* Change value in PLIST of PROP to VAL.
1858 PLIST is a property list, which is a list of the form
1859 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
1860 If PROP is already a property on the list, its value is set to VAL,
1861 otherwise the new PROP VAL pair is added. The new plist is returned;
1862 use `(setq x (plist-put x prop val))' to be sure to use the new value.
1863 The PLIST is modified by side effects. */)
1864 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1866 register Lisp_Object tail, prev;
1867 Lisp_Object newcell;
1868 prev = Qnil;
1869 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1870 tail = XCDR (XCDR (tail)))
1872 if (EQ (prop, XCAR (tail)))
1874 Fsetcar (XCDR (tail), val);
1875 return plist;
1878 prev = tail;
1879 QUIT;
1881 newcell = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
1882 if (NILP (prev))
1883 return newcell;
1884 else
1885 Fsetcdr (XCDR (prev), newcell);
1886 return plist;
1889 DEFUN ("put", Fput, Sput, 3, 3, 0,
1890 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
1891 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
1892 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
1894 CHECK_SYMBOL (symbol);
1895 set_symbol_plist
1896 (symbol, Fplist_put (XSYMBOL (symbol)->plist, propname, value));
1897 return value;
1900 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
1901 doc: /* Extract a value from a property list, comparing with `equal'.
1902 PLIST is a property list, which is a list of the form
1903 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1904 corresponding to the given PROP, or nil if PROP is not
1905 one of the properties on the list. */)
1906 (Lisp_Object plist, Lisp_Object prop)
1908 Lisp_Object tail;
1910 for (tail = plist;
1911 CONSP (tail) && CONSP (XCDR (tail));
1912 tail = XCDR (XCDR (tail)))
1914 if (! NILP (Fequal (prop, XCAR (tail))))
1915 return XCAR (XCDR (tail));
1917 QUIT;
1920 CHECK_LIST_END (tail, prop);
1922 return Qnil;
1925 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
1926 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
1927 PLIST is a property list, which is a list of the form
1928 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
1929 If PROP is already a property on the list, its value is set to VAL,
1930 otherwise the new PROP VAL pair is added. The new plist is returned;
1931 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
1932 The PLIST is modified by side effects. */)
1933 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1935 register Lisp_Object tail, prev;
1936 Lisp_Object newcell;
1937 prev = Qnil;
1938 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1939 tail = XCDR (XCDR (tail)))
1941 if (! NILP (Fequal (prop, XCAR (tail))))
1943 Fsetcar (XCDR (tail), val);
1944 return plist;
1947 prev = tail;
1948 QUIT;
1950 newcell = list2 (prop, val);
1951 if (NILP (prev))
1952 return newcell;
1953 else
1954 Fsetcdr (XCDR (prev), newcell);
1955 return plist;
1958 DEFUN ("eql", Feql, Seql, 2, 2, 0,
1959 doc: /* Return t if the two args are the same Lisp object.
1960 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
1961 (Lisp_Object obj1, Lisp_Object obj2)
1963 if (FLOATP (obj1))
1964 return internal_equal (obj1, obj2, 0, 0) ? Qt : Qnil;
1965 else
1966 return EQ (obj1, obj2) ? Qt : Qnil;
1969 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
1970 doc: /* Return t if two Lisp objects have similar structure and contents.
1971 They must have the same data type.
1972 Conses are compared by comparing the cars and the cdrs.
1973 Vectors and strings are compared element by element.
1974 Numbers are compared by value, but integers cannot equal floats.
1975 (Use `=' if you want integers and floats to be able to be equal.)
1976 Symbols must match exactly. */)
1977 (register Lisp_Object o1, Lisp_Object o2)
1979 return internal_equal (o1, o2, 0, 0) ? Qt : Qnil;
1982 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
1983 doc: /* Return t if two Lisp objects have similar structure and contents.
1984 This is like `equal' except that it compares the text properties
1985 of strings. (`equal' ignores text properties.) */)
1986 (register Lisp_Object o1, Lisp_Object o2)
1988 return internal_equal (o1, o2, 0, 1) ? Qt : Qnil;
1991 /* DEPTH is current depth of recursion. Signal an error if it
1992 gets too deep.
1993 PROPS means compare string text properties too. */
1995 static bool
1996 internal_equal (Lisp_Object o1, Lisp_Object o2, int depth, bool props)
1998 if (depth > 200)
1999 error ("Stack overflow in equal");
2001 tail_recurse:
2002 QUIT;
2003 if (EQ (o1, o2))
2004 return 1;
2005 if (XTYPE (o1) != XTYPE (o2))
2006 return 0;
2008 switch (XTYPE (o1))
2010 case Lisp_Float:
2012 double d1, d2;
2014 d1 = extract_float (o1);
2015 d2 = extract_float (o2);
2016 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2017 though they are not =. */
2018 return d1 == d2 || (d1 != d1 && d2 != d2);
2021 case Lisp_Cons:
2022 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1, props))
2023 return 0;
2024 o1 = XCDR (o1);
2025 o2 = XCDR (o2);
2026 goto tail_recurse;
2028 case Lisp_Misc:
2029 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2030 return 0;
2031 if (OVERLAYP (o1))
2033 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2034 depth + 1, props)
2035 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2036 depth + 1, props))
2037 return 0;
2038 o1 = XOVERLAY (o1)->plist;
2039 o2 = XOVERLAY (o2)->plist;
2040 goto tail_recurse;
2042 if (MARKERP (o1))
2044 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2045 && (XMARKER (o1)->buffer == 0
2046 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2048 break;
2050 case Lisp_Vectorlike:
2052 register int i;
2053 ptrdiff_t size = ASIZE (o1);
2054 /* Pseudovectors have the type encoded in the size field, so this test
2055 actually checks that the objects have the same type as well as the
2056 same size. */
2057 if (ASIZE (o2) != size)
2058 return 0;
2059 /* Boolvectors are compared much like strings. */
2060 if (BOOL_VECTOR_P (o1))
2062 EMACS_INT size = bool_vector_size (o1);
2063 if (size != bool_vector_size (o2))
2064 return 0;
2065 if (memcmp (bool_vector_data (o1), bool_vector_data (o2),
2066 bool_vector_bytes (size)))
2067 return 0;
2068 return 1;
2070 if (WINDOW_CONFIGURATIONP (o1))
2071 return compare_window_configurations (o1, o2, 0);
2073 /* Aside from them, only true vectors, char-tables, compiled
2074 functions, and fonts (font-spec, font-entity, font-object)
2075 are sensible to compare, so eliminate the others now. */
2076 if (size & PSEUDOVECTOR_FLAG)
2078 if (((size & PVEC_TYPE_MASK) >> PSEUDOVECTOR_AREA_BITS)
2079 < PVEC_COMPILED)
2080 return 0;
2081 size &= PSEUDOVECTOR_SIZE_MASK;
2083 for (i = 0; i < size; i++)
2085 Lisp_Object v1, v2;
2086 v1 = AREF (o1, i);
2087 v2 = AREF (o2, i);
2088 if (!internal_equal (v1, v2, depth + 1, props))
2089 return 0;
2091 return 1;
2093 break;
2095 case Lisp_String:
2096 if (SCHARS (o1) != SCHARS (o2))
2097 return 0;
2098 if (SBYTES (o1) != SBYTES (o2))
2099 return 0;
2100 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2101 return 0;
2102 if (props && !compare_string_intervals (o1, o2))
2103 return 0;
2104 return 1;
2106 default:
2107 break;
2110 return 0;
2114 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2115 doc: /* Store each element of ARRAY with ITEM.
2116 ARRAY is a vector, string, char-table, or bool-vector. */)
2117 (Lisp_Object array, Lisp_Object item)
2119 register ptrdiff_t size, idx;
2121 if (VECTORP (array))
2122 for (idx = 0, size = ASIZE (array); idx < size; idx++)
2123 ASET (array, idx, item);
2124 else if (CHAR_TABLE_P (array))
2126 int i;
2128 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2129 set_char_table_contents (array, i, item);
2130 set_char_table_defalt (array, item);
2132 else if (STRINGP (array))
2134 register unsigned char *p = SDATA (array);
2135 int charval;
2136 CHECK_CHARACTER (item);
2137 charval = XFASTINT (item);
2138 size = SCHARS (array);
2139 if (STRING_MULTIBYTE (array))
2141 unsigned char str[MAX_MULTIBYTE_LENGTH];
2142 int len = CHAR_STRING (charval, str);
2143 ptrdiff_t size_byte = SBYTES (array);
2145 if (INT_MULTIPLY_OVERFLOW (SCHARS (array), len)
2146 || SCHARS (array) * len != size_byte)
2147 error ("Attempt to change byte length of a string");
2148 for (idx = 0; idx < size_byte; idx++)
2149 *p++ = str[idx % len];
2151 else
2152 for (idx = 0; idx < size; idx++)
2153 p[idx] = charval;
2155 else if (BOOL_VECTOR_P (array))
2156 return bool_vector_fill (array, item);
2157 else
2158 wrong_type_argument (Qarrayp, array);
2159 return array;
2162 DEFUN ("clear-string", Fclear_string, Sclear_string,
2163 1, 1, 0,
2164 doc: /* Clear the contents of STRING.
2165 This makes STRING unibyte and may change its length. */)
2166 (Lisp_Object string)
2168 ptrdiff_t len;
2169 CHECK_STRING (string);
2170 len = SBYTES (string);
2171 memset (SDATA (string), 0, len);
2172 STRING_SET_CHARS (string, len);
2173 STRING_SET_UNIBYTE (string);
2174 return Qnil;
2177 /* ARGSUSED */
2178 Lisp_Object
2179 nconc2 (Lisp_Object s1, Lisp_Object s2)
2181 Lisp_Object args[2];
2182 args[0] = s1;
2183 args[1] = s2;
2184 return Fnconc (2, args);
2187 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2188 doc: /* Concatenate any number of lists by altering them.
2189 Only the last argument is not altered, and need not be a list.
2190 usage: (nconc &rest LISTS) */)
2191 (ptrdiff_t nargs, Lisp_Object *args)
2193 ptrdiff_t argnum;
2194 register Lisp_Object tail, tem, val;
2196 val = tail = Qnil;
2198 for (argnum = 0; argnum < nargs; argnum++)
2200 tem = args[argnum];
2201 if (NILP (tem)) continue;
2203 if (NILP (val))
2204 val = tem;
2206 if (argnum + 1 == nargs) break;
2208 CHECK_LIST_CONS (tem, tem);
2210 while (CONSP (tem))
2212 tail = tem;
2213 tem = XCDR (tail);
2214 QUIT;
2217 tem = args[argnum + 1];
2218 Fsetcdr (tail, tem);
2219 if (NILP (tem))
2220 args[argnum + 1] = tail;
2223 return val;
2226 /* This is the guts of all mapping functions.
2227 Apply FN to each element of SEQ, one by one,
2228 storing the results into elements of VALS, a C vector of Lisp_Objects.
2229 LENI is the length of VALS, which should also be the length of SEQ. */
2231 static void
2232 mapcar1 (EMACS_INT leni, Lisp_Object *vals, Lisp_Object fn, Lisp_Object seq)
2234 register Lisp_Object tail;
2235 Lisp_Object dummy;
2236 register EMACS_INT i;
2237 struct gcpro gcpro1, gcpro2, gcpro3;
2239 if (vals)
2241 /* Don't let vals contain any garbage when GC happens. */
2242 for (i = 0; i < leni; i++)
2243 vals[i] = Qnil;
2245 GCPRO3 (dummy, fn, seq);
2246 gcpro1.var = vals;
2247 gcpro1.nvars = leni;
2249 else
2250 GCPRO2 (fn, seq);
2251 /* We need not explicitly protect `tail' because it is used only on lists, and
2252 1) lists are not relocated and 2) the list is marked via `seq' so will not
2253 be freed */
2255 if (VECTORP (seq) || COMPILEDP (seq))
2257 for (i = 0; i < leni; i++)
2259 dummy = call1 (fn, AREF (seq, i));
2260 if (vals)
2261 vals[i] = dummy;
2264 else if (BOOL_VECTOR_P (seq))
2266 for (i = 0; i < leni; i++)
2268 dummy = call1 (fn, bool_vector_ref (seq, i));
2269 if (vals)
2270 vals[i] = dummy;
2273 else if (STRINGP (seq))
2275 ptrdiff_t i_byte;
2277 for (i = 0, i_byte = 0; i < leni;)
2279 int c;
2280 ptrdiff_t i_before = i;
2282 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2283 XSETFASTINT (dummy, c);
2284 dummy = call1 (fn, dummy);
2285 if (vals)
2286 vals[i_before] = dummy;
2289 else /* Must be a list, since Flength did not get an error */
2291 tail = seq;
2292 for (i = 0; i < leni && CONSP (tail); i++)
2294 dummy = call1 (fn, XCAR (tail));
2295 if (vals)
2296 vals[i] = dummy;
2297 tail = XCDR (tail);
2301 UNGCPRO;
2304 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2305 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2306 In between each pair of results, stick in SEPARATOR. Thus, " " as
2307 SEPARATOR results in spaces between the values returned by FUNCTION.
2308 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2309 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2311 Lisp_Object len;
2312 register EMACS_INT leni;
2313 EMACS_INT nargs;
2314 ptrdiff_t i;
2315 register Lisp_Object *args;
2316 struct gcpro gcpro1;
2317 Lisp_Object ret;
2318 USE_SAFE_ALLOCA;
2320 len = Flength (sequence);
2321 if (CHAR_TABLE_P (sequence))
2322 wrong_type_argument (Qlistp, sequence);
2323 leni = XINT (len);
2324 nargs = leni + leni - 1;
2325 if (nargs < 0) return empty_unibyte_string;
2327 SAFE_ALLOCA_LISP (args, nargs);
2329 GCPRO1 (separator);
2330 mapcar1 (leni, args, function, sequence);
2331 UNGCPRO;
2333 for (i = leni - 1; i > 0; i--)
2334 args[i + i] = args[i];
2336 for (i = 1; i < nargs; i += 2)
2337 args[i] = separator;
2339 ret = Fconcat (nargs, args);
2340 SAFE_FREE ();
2342 return ret;
2345 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2346 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2347 The result is a list just as long as SEQUENCE.
2348 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2349 (Lisp_Object function, Lisp_Object sequence)
2351 register Lisp_Object len;
2352 register EMACS_INT leni;
2353 register Lisp_Object *args;
2354 Lisp_Object ret;
2355 USE_SAFE_ALLOCA;
2357 len = Flength (sequence);
2358 if (CHAR_TABLE_P (sequence))
2359 wrong_type_argument (Qlistp, sequence);
2360 leni = XFASTINT (len);
2362 SAFE_ALLOCA_LISP (args, leni);
2364 mapcar1 (leni, args, function, sequence);
2366 ret = Flist (leni, args);
2367 SAFE_FREE ();
2369 return ret;
2372 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2373 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2374 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2375 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2376 (Lisp_Object function, Lisp_Object sequence)
2378 register EMACS_INT leni;
2380 leni = XFASTINT (Flength (sequence));
2381 if (CHAR_TABLE_P (sequence))
2382 wrong_type_argument (Qlistp, sequence);
2383 mapcar1 (leni, 0, function, sequence);
2385 return sequence;
2388 /* This is how C code calls `yes-or-no-p' and allows the user
2389 to redefined it.
2391 Anything that calls this function must protect from GC! */
2393 Lisp_Object
2394 do_yes_or_no_p (Lisp_Object prompt)
2396 return call1 (intern ("yes-or-no-p"), prompt);
2399 /* Anything that calls this function must protect from GC! */
2401 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2402 doc: /* Ask user a yes-or-no question. Return t if answer is yes.
2403 PROMPT is the string to display to ask the question. It should end in
2404 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2406 The user must confirm the answer with RET, and can edit it until it
2407 has been confirmed.
2409 If dialog boxes are supported, a dialog box will be used
2410 if `last-nonmenu-event' is nil, and `use-dialog-box' is non-nil. */)
2411 (Lisp_Object prompt)
2413 register Lisp_Object ans;
2414 Lisp_Object args[2];
2415 struct gcpro gcpro1;
2417 CHECK_STRING (prompt);
2419 #ifdef HAVE_MENUS
2420 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2421 && use_dialog_box)
2423 Lisp_Object pane, menu, obj;
2424 redisplay_preserve_echo_area (4);
2425 pane = list2 (Fcons (build_string ("Yes"), Qt),
2426 Fcons (build_string ("No"), Qnil));
2427 GCPRO1 (pane);
2428 menu = Fcons (prompt, pane);
2429 obj = Fx_popup_dialog (Qt, menu, Qnil);
2430 UNGCPRO;
2431 return obj;
2433 #endif /* HAVE_MENUS */
2435 args[0] = prompt;
2436 args[1] = build_string ("(yes or no) ");
2437 prompt = Fconcat (2, args);
2439 GCPRO1 (prompt);
2441 while (1)
2443 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2444 Qyes_or_no_p_history, Qnil,
2445 Qnil));
2446 if (SCHARS (ans) == 3 && !strcmp (SSDATA (ans), "yes"))
2448 UNGCPRO;
2449 return Qt;
2451 if (SCHARS (ans) == 2 && !strcmp (SSDATA (ans), "no"))
2453 UNGCPRO;
2454 return Qnil;
2457 Fding (Qnil);
2458 Fdiscard_input ();
2459 message1 ("Please answer yes or no.");
2460 Fsleep_for (make_number (2), Qnil);
2464 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2465 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2467 Each of the three load averages is multiplied by 100, then converted
2468 to integer.
2470 When USE-FLOATS is non-nil, floats will be used instead of integers.
2471 These floats are not multiplied by 100.
2473 If the 5-minute or 15-minute load averages are not available, return a
2474 shortened list, containing only those averages which are available.
2476 An error is thrown if the load average can't be obtained. In some
2477 cases making it work would require Emacs being installed setuid or
2478 setgid so that it can read kernel information, and that usually isn't
2479 advisable. */)
2480 (Lisp_Object use_floats)
2482 double load_ave[3];
2483 int loads = getloadavg (load_ave, 3);
2484 Lisp_Object ret = Qnil;
2486 if (loads < 0)
2487 error ("load-average not implemented for this operating system");
2489 while (loads-- > 0)
2491 Lisp_Object load = (NILP (use_floats)
2492 ? make_number (100.0 * load_ave[loads])
2493 : make_float (load_ave[loads]));
2494 ret = Fcons (load, ret);
2497 return ret;
2500 static Lisp_Object Qsubfeatures;
2502 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2503 doc: /* Return t if FEATURE is present in this Emacs.
2505 Use this to conditionalize execution of lisp code based on the
2506 presence or absence of Emacs or environment extensions.
2507 Use `provide' to declare that a feature is available. This function
2508 looks at the value of the variable `features'. The optional argument
2509 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2510 (Lisp_Object feature, Lisp_Object subfeature)
2512 register Lisp_Object tem;
2513 CHECK_SYMBOL (feature);
2514 tem = Fmemq (feature, Vfeatures);
2515 if (!NILP (tem) && !NILP (subfeature))
2516 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2517 return (NILP (tem)) ? Qnil : Qt;
2520 static Lisp_Object Qfuncall;
2522 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2523 doc: /* Announce that FEATURE is a feature of the current Emacs.
2524 The optional argument SUBFEATURES should be a list of symbols listing
2525 particular subfeatures supported in this version of FEATURE. */)
2526 (Lisp_Object feature, Lisp_Object subfeatures)
2528 register Lisp_Object tem;
2529 CHECK_SYMBOL (feature);
2530 CHECK_LIST (subfeatures);
2531 if (!NILP (Vautoload_queue))
2532 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2533 Vautoload_queue);
2534 tem = Fmemq (feature, Vfeatures);
2535 if (NILP (tem))
2536 Vfeatures = Fcons (feature, Vfeatures);
2537 if (!NILP (subfeatures))
2538 Fput (feature, Qsubfeatures, subfeatures);
2539 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2541 /* Run any load-hooks for this file. */
2542 tem = Fassq (feature, Vafter_load_alist);
2543 if (CONSP (tem))
2544 Fmapc (Qfuncall, XCDR (tem));
2546 return feature;
2549 /* `require' and its subroutines. */
2551 /* List of features currently being require'd, innermost first. */
2553 static Lisp_Object require_nesting_list;
2555 static void
2556 require_unwind (Lisp_Object old_value)
2558 require_nesting_list = old_value;
2561 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2562 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2563 If FEATURE is not a member of the list `features', then the feature
2564 is not loaded; so load the file FILENAME.
2565 If FILENAME is omitted, the printname of FEATURE is used as the file name,
2566 and `load' will try to load this name appended with the suffix `.elc' or
2567 `.el', in that order. The name without appended suffix will not be used.
2568 See `get-load-suffixes' for the complete list of suffixes.
2569 If the optional third argument NOERROR is non-nil,
2570 then return nil if the file is not found instead of signaling an error.
2571 Normally the return value is FEATURE.
2572 The normal messages at start and end of loading FILENAME are suppressed. */)
2573 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2575 Lisp_Object tem;
2576 struct gcpro gcpro1, gcpro2;
2577 bool from_file = load_in_progress;
2579 CHECK_SYMBOL (feature);
2581 /* Record the presence of `require' in this file
2582 even if the feature specified is already loaded.
2583 But not more than once in any file,
2584 and not when we aren't loading or reading from a file. */
2585 if (!from_file)
2586 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2587 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2588 from_file = 1;
2590 if (from_file)
2592 tem = Fcons (Qrequire, feature);
2593 if (NILP (Fmember (tem, Vcurrent_load_list)))
2594 LOADHIST_ATTACH (tem);
2596 tem = Fmemq (feature, Vfeatures);
2598 if (NILP (tem))
2600 ptrdiff_t count = SPECPDL_INDEX ();
2601 int nesting = 0;
2603 /* This is to make sure that loadup.el gives a clear picture
2604 of what files are preloaded and when. */
2605 if (! NILP (Vpurify_flag))
2606 error ("(require %s) while preparing to dump",
2607 SDATA (SYMBOL_NAME (feature)));
2609 /* A certain amount of recursive `require' is legitimate,
2610 but if we require the same feature recursively 3 times,
2611 signal an error. */
2612 tem = require_nesting_list;
2613 while (! NILP (tem))
2615 if (! NILP (Fequal (feature, XCAR (tem))))
2616 nesting++;
2617 tem = XCDR (tem);
2619 if (nesting > 3)
2620 error ("Recursive `require' for feature `%s'",
2621 SDATA (SYMBOL_NAME (feature)));
2623 /* Update the list for any nested `require's that occur. */
2624 record_unwind_protect (require_unwind, require_nesting_list);
2625 require_nesting_list = Fcons (feature, require_nesting_list);
2627 /* Value saved here is to be restored into Vautoload_queue */
2628 record_unwind_protect (un_autoload, Vautoload_queue);
2629 Vautoload_queue = Qt;
2631 /* Load the file. */
2632 GCPRO2 (feature, filename);
2633 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2634 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2635 UNGCPRO;
2637 /* If load failed entirely, return nil. */
2638 if (NILP (tem))
2639 return unbind_to (count, Qnil);
2641 tem = Fmemq (feature, Vfeatures);
2642 if (NILP (tem))
2643 error ("Required feature `%s' was not provided",
2644 SDATA (SYMBOL_NAME (feature)));
2646 /* Once loading finishes, don't undo it. */
2647 Vautoload_queue = Qt;
2648 feature = unbind_to (count, feature);
2651 return feature;
2654 /* Primitives for work of the "widget" library.
2655 In an ideal world, this section would not have been necessary.
2656 However, lisp function calls being as slow as they are, it turns
2657 out that some functions in the widget library (wid-edit.el) are the
2658 bottleneck of Widget operation. Here is their translation to C,
2659 for the sole reason of efficiency. */
2661 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2662 doc: /* Return non-nil if PLIST has the property PROP.
2663 PLIST is a property list, which is a list of the form
2664 \(PROP1 VALUE1 PROP2 VALUE2 ...\). PROP is a symbol.
2665 Unlike `plist-get', this allows you to distinguish between a missing
2666 property and a property with the value nil.
2667 The value is actually the tail of PLIST whose car is PROP. */)
2668 (Lisp_Object plist, Lisp_Object prop)
2670 while (CONSP (plist) && !EQ (XCAR (plist), prop))
2672 QUIT;
2673 plist = XCDR (plist);
2674 plist = CDR (plist);
2676 return plist;
2679 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2680 doc: /* In WIDGET, set PROPERTY to VALUE.
2681 The value can later be retrieved with `widget-get'. */)
2682 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2684 CHECK_CONS (widget);
2685 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
2686 return value;
2689 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
2690 doc: /* In WIDGET, get the value of PROPERTY.
2691 The value could either be specified when the widget was created, or
2692 later with `widget-put'. */)
2693 (Lisp_Object widget, Lisp_Object property)
2695 Lisp_Object tmp;
2697 while (1)
2699 if (NILP (widget))
2700 return Qnil;
2701 CHECK_CONS (widget);
2702 tmp = Fplist_member (XCDR (widget), property);
2703 if (CONSP (tmp))
2705 tmp = XCDR (tmp);
2706 return CAR (tmp);
2708 tmp = XCAR (widget);
2709 if (NILP (tmp))
2710 return Qnil;
2711 widget = Fget (tmp, Qwidget_type);
2715 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
2716 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2717 ARGS are passed as extra arguments to the function.
2718 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2719 (ptrdiff_t nargs, Lisp_Object *args)
2721 /* This function can GC. */
2722 Lisp_Object newargs[3];
2723 struct gcpro gcpro1, gcpro2;
2724 Lisp_Object result;
2726 newargs[0] = Fwidget_get (args[0], args[1]);
2727 newargs[1] = args[0];
2728 newargs[2] = Flist (nargs - 2, args + 2);
2729 GCPRO2 (newargs[0], newargs[2]);
2730 result = Fapply (3, newargs);
2731 UNGCPRO;
2732 return result;
2735 #ifdef HAVE_LANGINFO_CODESET
2736 #include <langinfo.h>
2737 #endif
2739 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
2740 doc: /* Access locale data ITEM for the current C locale, if available.
2741 ITEM should be one of the following:
2743 `codeset', returning the character set as a string (locale item CODESET);
2745 `days', returning a 7-element vector of day names (locale items DAY_n);
2747 `months', returning a 12-element vector of month names (locale items MON_n);
2749 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
2750 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
2752 If the system can't provide such information through a call to
2753 `nl_langinfo', or if ITEM isn't from the list above, return nil.
2755 See also Info node `(libc)Locales'.
2757 The data read from the system are decoded using `locale-coding-system'. */)
2758 (Lisp_Object item)
2760 char *str = NULL;
2761 #ifdef HAVE_LANGINFO_CODESET
2762 Lisp_Object val;
2763 if (EQ (item, Qcodeset))
2765 str = nl_langinfo (CODESET);
2766 return build_string (str);
2768 #ifdef DAY_1
2769 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
2771 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
2772 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
2773 int i;
2774 struct gcpro gcpro1;
2775 GCPRO1 (v);
2776 synchronize_system_time_locale ();
2777 for (i = 0; i < 7; i++)
2779 str = nl_langinfo (days[i]);
2780 val = build_unibyte_string (str);
2781 /* Fixme: Is this coding system necessarily right, even if
2782 it is consistent with CODESET? If not, what to do? */
2783 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
2784 0));
2786 UNGCPRO;
2787 return v;
2789 #endif /* DAY_1 */
2790 #ifdef MON_1
2791 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
2793 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
2794 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
2795 MON_8, MON_9, MON_10, MON_11, MON_12};
2796 int i;
2797 struct gcpro gcpro1;
2798 GCPRO1 (v);
2799 synchronize_system_time_locale ();
2800 for (i = 0; i < 12; i++)
2802 str = nl_langinfo (months[i]);
2803 val = build_unibyte_string (str);
2804 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
2805 0));
2807 UNGCPRO;
2808 return v;
2810 #endif /* MON_1 */
2811 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
2812 but is in the locale files. This could be used by ps-print. */
2813 #ifdef PAPER_WIDTH
2814 else if (EQ (item, Qpaper))
2815 return list2i (nl_langinfo (PAPER_WIDTH), nl_langinfo (PAPER_HEIGHT));
2816 #endif /* PAPER_WIDTH */
2817 #endif /* HAVE_LANGINFO_CODESET*/
2818 return Qnil;
2821 /* base64 encode/decode functions (RFC 2045).
2822 Based on code from GNU recode. */
2824 #define MIME_LINE_LENGTH 76
2826 #define IS_ASCII(Character) \
2827 ((Character) < 128)
2828 #define IS_BASE64(Character) \
2829 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
2830 #define IS_BASE64_IGNORABLE(Character) \
2831 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
2832 || (Character) == '\f' || (Character) == '\r')
2834 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
2835 character or return retval if there are no characters left to
2836 process. */
2837 #define READ_QUADRUPLET_BYTE(retval) \
2838 do \
2840 if (i == length) \
2842 if (nchars_return) \
2843 *nchars_return = nchars; \
2844 return (retval); \
2846 c = from[i++]; \
2848 while (IS_BASE64_IGNORABLE (c))
2850 /* Table of characters coding the 64 values. */
2851 static const char base64_value_to_char[64] =
2853 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
2854 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
2855 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
2856 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
2857 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
2858 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
2859 '8', '9', '+', '/' /* 60-63 */
2862 /* Table of base64 values for first 128 characters. */
2863 static const short base64_char_to_value[128] =
2865 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
2866 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
2867 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
2868 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
2869 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
2870 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
2871 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
2872 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
2873 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
2874 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
2875 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
2876 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
2877 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
2880 /* The following diagram shows the logical steps by which three octets
2881 get transformed into four base64 characters.
2883 .--------. .--------. .--------.
2884 |aaaaaabb| |bbbbcccc| |ccdddddd|
2885 `--------' `--------' `--------'
2886 6 2 4 4 2 6
2887 .--------+--------+--------+--------.
2888 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
2889 `--------+--------+--------+--------'
2891 .--------+--------+--------+--------.
2892 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
2893 `--------+--------+--------+--------'
2895 The octets are divided into 6 bit chunks, which are then encoded into
2896 base64 characters. */
2899 static ptrdiff_t base64_encode_1 (const char *, char *, ptrdiff_t, bool, bool);
2900 static ptrdiff_t base64_decode_1 (const char *, char *, ptrdiff_t, bool,
2901 ptrdiff_t *);
2903 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
2904 2, 3, "r",
2905 doc: /* Base64-encode the region between BEG and END.
2906 Return the length of the encoded text.
2907 Optional third argument NO-LINE-BREAK means do not break long lines
2908 into shorter lines. */)
2909 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
2911 char *encoded;
2912 ptrdiff_t allength, length;
2913 ptrdiff_t ibeg, iend, encoded_length;
2914 ptrdiff_t old_pos = PT;
2915 USE_SAFE_ALLOCA;
2917 validate_region (&beg, &end);
2919 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
2920 iend = CHAR_TO_BYTE (XFASTINT (end));
2921 move_gap_both (XFASTINT (beg), ibeg);
2923 /* We need to allocate enough room for encoding the text.
2924 We need 33 1/3% more space, plus a newline every 76
2925 characters, and then we round up. */
2926 length = iend - ibeg;
2927 allength = length + length/3 + 1;
2928 allength += allength / MIME_LINE_LENGTH + 1 + 6;
2930 encoded = SAFE_ALLOCA (allength);
2931 encoded_length = base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg),
2932 encoded, length, NILP (no_line_break),
2933 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
2934 if (encoded_length > allength)
2935 emacs_abort ();
2937 if (encoded_length < 0)
2939 /* The encoding wasn't possible. */
2940 SAFE_FREE ();
2941 error ("Multibyte character in data for base64 encoding");
2944 /* Now we have encoded the region, so we insert the new contents
2945 and delete the old. (Insert first in order to preserve markers.) */
2946 SET_PT_BOTH (XFASTINT (beg), ibeg);
2947 insert (encoded, encoded_length);
2948 SAFE_FREE ();
2949 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
2951 /* If point was outside of the region, restore it exactly; else just
2952 move to the beginning of the region. */
2953 if (old_pos >= XFASTINT (end))
2954 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
2955 else if (old_pos > XFASTINT (beg))
2956 old_pos = XFASTINT (beg);
2957 SET_PT (old_pos);
2959 /* We return the length of the encoded text. */
2960 return make_number (encoded_length);
2963 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
2964 1, 2, 0,
2965 doc: /* Base64-encode STRING and return the result.
2966 Optional second argument NO-LINE-BREAK means do not break long lines
2967 into shorter lines. */)
2968 (Lisp_Object string, Lisp_Object no_line_break)
2970 ptrdiff_t allength, length, encoded_length;
2971 char *encoded;
2972 Lisp_Object encoded_string;
2973 USE_SAFE_ALLOCA;
2975 CHECK_STRING (string);
2977 /* We need to allocate enough room for encoding the text.
2978 We need 33 1/3% more space, plus a newline every 76
2979 characters, and then we round up. */
2980 length = SBYTES (string);
2981 allength = length + length/3 + 1;
2982 allength += allength / MIME_LINE_LENGTH + 1 + 6;
2984 /* We need to allocate enough room for decoding the text. */
2985 encoded = SAFE_ALLOCA (allength);
2987 encoded_length = base64_encode_1 (SSDATA (string),
2988 encoded, length, NILP (no_line_break),
2989 STRING_MULTIBYTE (string));
2990 if (encoded_length > allength)
2991 emacs_abort ();
2993 if (encoded_length < 0)
2995 /* The encoding wasn't possible. */
2996 SAFE_FREE ();
2997 error ("Multibyte character in data for base64 encoding");
3000 encoded_string = make_unibyte_string (encoded, encoded_length);
3001 SAFE_FREE ();
3003 return encoded_string;
3006 static ptrdiff_t
3007 base64_encode_1 (const char *from, char *to, ptrdiff_t length,
3008 bool line_break, bool multibyte)
3010 int counter = 0;
3011 ptrdiff_t i = 0;
3012 char *e = to;
3013 int c;
3014 unsigned int value;
3015 int bytes;
3017 while (i < length)
3019 if (multibyte)
3021 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3022 if (CHAR_BYTE8_P (c))
3023 c = CHAR_TO_BYTE8 (c);
3024 else if (c >= 256)
3025 return -1;
3026 i += bytes;
3028 else
3029 c = from[i++];
3031 /* Wrap line every 76 characters. */
3033 if (line_break)
3035 if (counter < MIME_LINE_LENGTH / 4)
3036 counter++;
3037 else
3039 *e++ = '\n';
3040 counter = 1;
3044 /* Process first byte of a triplet. */
3046 *e++ = base64_value_to_char[0x3f & c >> 2];
3047 value = (0x03 & c) << 4;
3049 /* Process second byte of a triplet. */
3051 if (i == length)
3053 *e++ = base64_value_to_char[value];
3054 *e++ = '=';
3055 *e++ = '=';
3056 break;
3059 if (multibyte)
3061 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3062 if (CHAR_BYTE8_P (c))
3063 c = CHAR_TO_BYTE8 (c);
3064 else if (c >= 256)
3065 return -1;
3066 i += bytes;
3068 else
3069 c = from[i++];
3071 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3072 value = (0x0f & c) << 2;
3074 /* Process third byte of a triplet. */
3076 if (i == length)
3078 *e++ = base64_value_to_char[value];
3079 *e++ = '=';
3080 break;
3083 if (multibyte)
3085 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3086 if (CHAR_BYTE8_P (c))
3087 c = CHAR_TO_BYTE8 (c);
3088 else if (c >= 256)
3089 return -1;
3090 i += bytes;
3092 else
3093 c = from[i++];
3095 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3096 *e++ = base64_value_to_char[0x3f & c];
3099 return e - to;
3103 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3104 2, 2, "r",
3105 doc: /* Base64-decode the region between BEG and END.
3106 Return the length of the decoded text.
3107 If the region can't be decoded, signal an error and don't modify the buffer. */)
3108 (Lisp_Object beg, Lisp_Object end)
3110 ptrdiff_t ibeg, iend, length, allength;
3111 char *decoded;
3112 ptrdiff_t old_pos = PT;
3113 ptrdiff_t decoded_length;
3114 ptrdiff_t inserted_chars;
3115 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3116 USE_SAFE_ALLOCA;
3118 validate_region (&beg, &end);
3120 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3121 iend = CHAR_TO_BYTE (XFASTINT (end));
3123 length = iend - ibeg;
3125 /* We need to allocate enough room for decoding the text. If we are
3126 working on a multibyte buffer, each decoded code may occupy at
3127 most two bytes. */
3128 allength = multibyte ? length * 2 : length;
3129 decoded = SAFE_ALLOCA (allength);
3131 move_gap_both (XFASTINT (beg), ibeg);
3132 decoded_length = base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg),
3133 decoded, length,
3134 multibyte, &inserted_chars);
3135 if (decoded_length > allength)
3136 emacs_abort ();
3138 if (decoded_length < 0)
3140 /* The decoding wasn't possible. */
3141 SAFE_FREE ();
3142 error ("Invalid base64 data");
3145 /* Now we have decoded the region, so we insert the new contents
3146 and delete the old. (Insert first in order to preserve markers.) */
3147 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3148 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3149 SAFE_FREE ();
3151 /* Delete the original text. */
3152 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3153 iend + decoded_length, 1);
3155 /* If point was outside of the region, restore it exactly; else just
3156 move to the beginning of the region. */
3157 if (old_pos >= XFASTINT (end))
3158 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3159 else if (old_pos > XFASTINT (beg))
3160 old_pos = XFASTINT (beg);
3161 SET_PT (old_pos > ZV ? ZV : old_pos);
3163 return make_number (inserted_chars);
3166 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3167 1, 1, 0,
3168 doc: /* Base64-decode STRING and return the result. */)
3169 (Lisp_Object string)
3171 char *decoded;
3172 ptrdiff_t length, decoded_length;
3173 Lisp_Object decoded_string;
3174 USE_SAFE_ALLOCA;
3176 CHECK_STRING (string);
3178 length = SBYTES (string);
3179 /* We need to allocate enough room for decoding the text. */
3180 decoded = SAFE_ALLOCA (length);
3182 /* The decoded result should be unibyte. */
3183 decoded_length = base64_decode_1 (SSDATA (string), decoded, length,
3184 0, NULL);
3185 if (decoded_length > length)
3186 emacs_abort ();
3187 else if (decoded_length >= 0)
3188 decoded_string = make_unibyte_string (decoded, decoded_length);
3189 else
3190 decoded_string = Qnil;
3192 SAFE_FREE ();
3193 if (!STRINGP (decoded_string))
3194 error ("Invalid base64 data");
3196 return decoded_string;
3199 /* Base64-decode the data at FROM of LENGTH bytes into TO. If
3200 MULTIBYTE, the decoded result should be in multibyte
3201 form. If NCHARS_RETURN is not NULL, store the number of produced
3202 characters in *NCHARS_RETURN. */
3204 static ptrdiff_t
3205 base64_decode_1 (const char *from, char *to, ptrdiff_t length,
3206 bool multibyte, ptrdiff_t *nchars_return)
3208 ptrdiff_t i = 0; /* Used inside READ_QUADRUPLET_BYTE */
3209 char *e = to;
3210 unsigned char c;
3211 unsigned long value;
3212 ptrdiff_t nchars = 0;
3214 while (1)
3216 /* Process first byte of a quadruplet. */
3218 READ_QUADRUPLET_BYTE (e-to);
3220 if (!IS_BASE64 (c))
3221 return -1;
3222 value = base64_char_to_value[c] << 18;
3224 /* Process second byte of a quadruplet. */
3226 READ_QUADRUPLET_BYTE (-1);
3228 if (!IS_BASE64 (c))
3229 return -1;
3230 value |= base64_char_to_value[c] << 12;
3232 c = (unsigned char) (value >> 16);
3233 if (multibyte && c >= 128)
3234 e += BYTE8_STRING (c, e);
3235 else
3236 *e++ = c;
3237 nchars++;
3239 /* Process third byte of a quadruplet. */
3241 READ_QUADRUPLET_BYTE (-1);
3243 if (c == '=')
3245 READ_QUADRUPLET_BYTE (-1);
3247 if (c != '=')
3248 return -1;
3249 continue;
3252 if (!IS_BASE64 (c))
3253 return -1;
3254 value |= base64_char_to_value[c] << 6;
3256 c = (unsigned char) (0xff & value >> 8);
3257 if (multibyte && c >= 128)
3258 e += BYTE8_STRING (c, e);
3259 else
3260 *e++ = c;
3261 nchars++;
3263 /* Process fourth byte of a quadruplet. */
3265 READ_QUADRUPLET_BYTE (-1);
3267 if (c == '=')
3268 continue;
3270 if (!IS_BASE64 (c))
3271 return -1;
3272 value |= base64_char_to_value[c];
3274 c = (unsigned char) (0xff & value);
3275 if (multibyte && c >= 128)
3276 e += BYTE8_STRING (c, e);
3277 else
3278 *e++ = c;
3279 nchars++;
3285 /***********************************************************************
3286 ***** *****
3287 ***** Hash Tables *****
3288 ***** *****
3289 ***********************************************************************/
3291 /* Implemented by gerd@gnu.org. This hash table implementation was
3292 inspired by CMUCL hash tables. */
3294 /* Ideas:
3296 1. For small tables, association lists are probably faster than
3297 hash tables because they have lower overhead.
3299 For uses of hash tables where the O(1) behavior of table
3300 operations is not a requirement, it might therefore be a good idea
3301 not to hash. Instead, we could just do a linear search in the
3302 key_and_value vector of the hash table. This could be done
3303 if a `:linear-search t' argument is given to make-hash-table. */
3306 /* The list of all weak hash tables. Don't staticpro this one. */
3308 static struct Lisp_Hash_Table *weak_hash_tables;
3310 /* Various symbols. */
3312 static Lisp_Object Qhash_table_p;
3313 static Lisp_Object Qkey, Qvalue, Qeql;
3314 Lisp_Object Qeq, Qequal;
3315 Lisp_Object QCtest, QCsize, QCrehash_size, QCrehash_threshold, QCweakness;
3316 static Lisp_Object Qhash_table_test, Qkey_or_value, Qkey_and_value;
3319 /***********************************************************************
3320 Utilities
3321 ***********************************************************************/
3323 static void
3324 CHECK_HASH_TABLE (Lisp_Object x)
3326 CHECK_TYPE (HASH_TABLE_P (x), Qhash_table_p, x);
3329 static void
3330 set_hash_key_and_value (struct Lisp_Hash_Table *h, Lisp_Object key_and_value)
3332 h->key_and_value = key_and_value;
3334 static void
3335 set_hash_next (struct Lisp_Hash_Table *h, Lisp_Object next)
3337 h->next = next;
3339 static void
3340 set_hash_next_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3342 gc_aset (h->next, idx, val);
3344 static void
3345 set_hash_hash (struct Lisp_Hash_Table *h, Lisp_Object hash)
3347 h->hash = hash;
3349 static void
3350 set_hash_hash_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3352 gc_aset (h->hash, idx, val);
3354 static void
3355 set_hash_index (struct Lisp_Hash_Table *h, Lisp_Object index)
3357 h->index = index;
3359 static void
3360 set_hash_index_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3362 gc_aset (h->index, idx, val);
3365 /* If OBJ is a Lisp hash table, return a pointer to its struct
3366 Lisp_Hash_Table. Otherwise, signal an error. */
3368 static struct Lisp_Hash_Table *
3369 check_hash_table (Lisp_Object obj)
3371 CHECK_HASH_TABLE (obj);
3372 return XHASH_TABLE (obj);
3376 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3377 number. A number is "almost" a prime number if it is not divisible
3378 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3380 EMACS_INT
3381 next_almost_prime (EMACS_INT n)
3383 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
3384 for (n |= 1; ; n += 2)
3385 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0)
3386 return n;
3390 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3391 which USED[I] is non-zero. If found at index I in ARGS, set
3392 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3393 0. This function is used to extract a keyword/argument pair from
3394 a DEFUN parameter list. */
3396 static ptrdiff_t
3397 get_key_arg (Lisp_Object key, ptrdiff_t nargs, Lisp_Object *args, char *used)
3399 ptrdiff_t i;
3401 for (i = 1; i < nargs; i++)
3402 if (!used[i - 1] && EQ (args[i - 1], key))
3404 used[i - 1] = 1;
3405 used[i] = 1;
3406 return i;
3409 return 0;
3413 /* Return a Lisp vector which has the same contents as VEC but has
3414 at least INCR_MIN more entries, where INCR_MIN is positive.
3415 If NITEMS_MAX is not -1, do not grow the vector to be any larger
3416 than NITEMS_MAX. Entries in the resulting
3417 vector that are not copied from VEC are set to nil. */
3419 Lisp_Object
3420 larger_vector (Lisp_Object vec, ptrdiff_t incr_min, ptrdiff_t nitems_max)
3422 struct Lisp_Vector *v;
3423 ptrdiff_t i, incr, incr_max, old_size, new_size;
3424 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / sizeof *v->contents;
3425 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
3426 ? nitems_max : C_language_max);
3427 eassert (VECTORP (vec));
3428 eassert (0 < incr_min && -1 <= nitems_max);
3429 old_size = ASIZE (vec);
3430 incr_max = n_max - old_size;
3431 incr = max (incr_min, min (old_size >> 1, incr_max));
3432 if (incr_max < incr)
3433 memory_full (SIZE_MAX);
3434 new_size = old_size + incr;
3435 v = allocate_vector (new_size);
3436 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3437 for (i = old_size; i < new_size; ++i)
3438 v->contents[i] = Qnil;
3439 XSETVECTOR (vec, v);
3440 return vec;
3444 /***********************************************************************
3445 Low-level Functions
3446 ***********************************************************************/
3448 static struct hash_table_test hashtest_eq;
3449 struct hash_table_test hashtest_eql, hashtest_equal;
3451 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3452 HASH2 in hash table H using `eql'. Value is true if KEY1 and
3453 KEY2 are the same. */
3455 static bool
3456 cmpfn_eql (struct hash_table_test *ht,
3457 Lisp_Object key1,
3458 Lisp_Object key2)
3460 return (FLOATP (key1)
3461 && FLOATP (key2)
3462 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3466 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3467 HASH2 in hash table H using `equal'. Value is true if KEY1 and
3468 KEY2 are the same. */
3470 static bool
3471 cmpfn_equal (struct hash_table_test *ht,
3472 Lisp_Object key1,
3473 Lisp_Object key2)
3475 return !NILP (Fequal (key1, key2));
3479 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3480 HASH2 in hash table H using H->user_cmp_function. Value is true
3481 if KEY1 and KEY2 are the same. */
3483 static bool
3484 cmpfn_user_defined (struct hash_table_test *ht,
3485 Lisp_Object key1,
3486 Lisp_Object key2)
3488 Lisp_Object args[3];
3490 args[0] = ht->user_cmp_function;
3491 args[1] = key1;
3492 args[2] = key2;
3493 return !NILP (Ffuncall (3, args));
3497 /* Value is a hash code for KEY for use in hash table H which uses
3498 `eq' to compare keys. The hash code returned is guaranteed to fit
3499 in a Lisp integer. */
3501 static EMACS_UINT
3502 hashfn_eq (struct hash_table_test *ht, Lisp_Object key)
3504 EMACS_UINT hash = XHASH (key) ^ XTYPE (key);
3505 return hash;
3508 /* Value is a hash code for KEY for use in hash table H which uses
3509 `eql' to compare keys. The hash code returned is guaranteed to fit
3510 in a Lisp integer. */
3512 static EMACS_UINT
3513 hashfn_eql (struct hash_table_test *ht, Lisp_Object key)
3515 EMACS_UINT hash;
3516 if (FLOATP (key))
3517 hash = sxhash (key, 0);
3518 else
3519 hash = XHASH (key) ^ XTYPE (key);
3520 return hash;
3523 /* Value is a hash code for KEY for use in hash table H which uses
3524 `equal' to compare keys. The hash code returned is guaranteed to fit
3525 in a Lisp integer. */
3527 static EMACS_UINT
3528 hashfn_equal (struct hash_table_test *ht, Lisp_Object key)
3530 EMACS_UINT hash = sxhash (key, 0);
3531 return hash;
3534 /* Value is a hash code for KEY for use in hash table H which uses as
3535 user-defined function to compare keys. The hash code returned is
3536 guaranteed to fit in a Lisp integer. */
3538 static EMACS_UINT
3539 hashfn_user_defined (struct hash_table_test *ht, Lisp_Object key)
3541 Lisp_Object args[2], hash;
3543 args[0] = ht->user_hash_function;
3544 args[1] = key;
3545 hash = Ffuncall (2, args);
3546 return hashfn_eq (ht, hash);
3549 /* An upper bound on the size of a hash table index. It must fit in
3550 ptrdiff_t and be a valid Emacs fixnum. */
3551 #define INDEX_SIZE_BOUND \
3552 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, PTRDIFF_MAX / word_size))
3554 /* Create and initialize a new hash table.
3556 TEST specifies the test the hash table will use to compare keys.
3557 It must be either one of the predefined tests `eq', `eql' or
3558 `equal' or a symbol denoting a user-defined test named TEST with
3559 test and hash functions USER_TEST and USER_HASH.
3561 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3563 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3564 new size when it becomes full is computed by adding REHASH_SIZE to
3565 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3566 table's new size is computed by multiplying its old size with
3567 REHASH_SIZE.
3569 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3570 be resized when the ratio of (number of entries in the table) /
3571 (table size) is >= REHASH_THRESHOLD.
3573 WEAK specifies the weakness of the table. If non-nil, it must be
3574 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
3576 Lisp_Object
3577 make_hash_table (struct hash_table_test test,
3578 Lisp_Object size, Lisp_Object rehash_size,
3579 Lisp_Object rehash_threshold, Lisp_Object weak)
3581 struct Lisp_Hash_Table *h;
3582 Lisp_Object table;
3583 EMACS_INT index_size, sz;
3584 ptrdiff_t i;
3585 double index_float;
3587 /* Preconditions. */
3588 eassert (SYMBOLP (test.name));
3589 eassert (INTEGERP (size) && XINT (size) >= 0);
3590 eassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3591 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size)));
3592 eassert (FLOATP (rehash_threshold)
3593 && 0 < XFLOAT_DATA (rehash_threshold)
3594 && XFLOAT_DATA (rehash_threshold) <= 1.0);
3596 if (XFASTINT (size) == 0)
3597 size = make_number (1);
3599 sz = XFASTINT (size);
3600 index_float = sz / XFLOAT_DATA (rehash_threshold);
3601 index_size = (index_float < INDEX_SIZE_BOUND + 1
3602 ? next_almost_prime (index_float)
3603 : INDEX_SIZE_BOUND + 1);
3604 if (INDEX_SIZE_BOUND < max (index_size, 2 * sz))
3605 error ("Hash table too large");
3607 /* Allocate a table and initialize it. */
3608 h = allocate_hash_table ();
3610 /* Initialize hash table slots. */
3611 h->test = test;
3612 h->weak = weak;
3613 h->rehash_threshold = rehash_threshold;
3614 h->rehash_size = rehash_size;
3615 h->count = 0;
3616 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
3617 h->hash = Fmake_vector (size, Qnil);
3618 h->next = Fmake_vector (size, Qnil);
3619 h->index = Fmake_vector (make_number (index_size), Qnil);
3621 /* Set up the free list. */
3622 for (i = 0; i < sz - 1; ++i)
3623 set_hash_next_slot (h, i, make_number (i + 1));
3624 h->next_free = make_number (0);
3626 XSET_HASH_TABLE (table, h);
3627 eassert (HASH_TABLE_P (table));
3628 eassert (XHASH_TABLE (table) == h);
3630 /* Maybe add this hash table to the list of all weak hash tables. */
3631 if (NILP (h->weak))
3632 h->next_weak = NULL;
3633 else
3635 h->next_weak = weak_hash_tables;
3636 weak_hash_tables = h;
3639 return table;
3643 /* Return a copy of hash table H1. Keys and values are not copied,
3644 only the table itself is. */
3646 static Lisp_Object
3647 copy_hash_table (struct Lisp_Hash_Table *h1)
3649 Lisp_Object table;
3650 struct Lisp_Hash_Table *h2;
3652 h2 = allocate_hash_table ();
3653 *h2 = *h1;
3654 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3655 h2->hash = Fcopy_sequence (h1->hash);
3656 h2->next = Fcopy_sequence (h1->next);
3657 h2->index = Fcopy_sequence (h1->index);
3658 XSET_HASH_TABLE (table, h2);
3660 /* Maybe add this hash table to the list of all weak hash tables. */
3661 if (!NILP (h2->weak))
3663 h2->next_weak = weak_hash_tables;
3664 weak_hash_tables = h2;
3667 return table;
3671 /* Resize hash table H if it's too full. If H cannot be resized
3672 because it's already too large, throw an error. */
3674 static void
3675 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3677 if (NILP (h->next_free))
3679 ptrdiff_t old_size = HASH_TABLE_SIZE (h);
3680 EMACS_INT new_size, index_size, nsize;
3681 ptrdiff_t i;
3682 double index_float;
3684 if (INTEGERP (h->rehash_size))
3685 new_size = old_size + XFASTINT (h->rehash_size);
3686 else
3688 double float_new_size = old_size * XFLOAT_DATA (h->rehash_size);
3689 if (float_new_size < INDEX_SIZE_BOUND + 1)
3691 new_size = float_new_size;
3692 if (new_size <= old_size)
3693 new_size = old_size + 1;
3695 else
3696 new_size = INDEX_SIZE_BOUND + 1;
3698 index_float = new_size / XFLOAT_DATA (h->rehash_threshold);
3699 index_size = (index_float < INDEX_SIZE_BOUND + 1
3700 ? next_almost_prime (index_float)
3701 : INDEX_SIZE_BOUND + 1);
3702 nsize = max (index_size, 2 * new_size);
3703 if (INDEX_SIZE_BOUND < nsize)
3704 error ("Hash table too large to resize");
3706 #ifdef ENABLE_CHECKING
3707 if (HASH_TABLE_P (Vpurify_flag)
3708 && XHASH_TABLE (Vpurify_flag) == h)
3710 Lisp_Object args[2];
3711 args[0] = build_string ("Growing hash table to: %d");
3712 args[1] = make_number (new_size);
3713 Fmessage (2, args);
3715 #endif
3717 set_hash_key_and_value (h, larger_vector (h->key_and_value,
3718 2 * (new_size - old_size), -1));
3719 set_hash_next (h, larger_vector (h->next, new_size - old_size, -1));
3720 set_hash_hash (h, larger_vector (h->hash, new_size - old_size, -1));
3721 set_hash_index (h, Fmake_vector (make_number (index_size), Qnil));
3723 /* Update the free list. Do it so that new entries are added at
3724 the end of the free list. This makes some operations like
3725 maphash faster. */
3726 for (i = old_size; i < new_size - 1; ++i)
3727 set_hash_next_slot (h, i, make_number (i + 1));
3729 if (!NILP (h->next_free))
3731 Lisp_Object last, next;
3733 last = h->next_free;
3734 while (next = HASH_NEXT (h, XFASTINT (last)),
3735 !NILP (next))
3736 last = next;
3738 set_hash_next_slot (h, XFASTINT (last), make_number (old_size));
3740 else
3741 XSETFASTINT (h->next_free, old_size);
3743 /* Rehash. */
3744 for (i = 0; i < old_size; ++i)
3745 if (!NILP (HASH_HASH (h, i)))
3747 EMACS_UINT hash_code = XUINT (HASH_HASH (h, i));
3748 ptrdiff_t start_of_bucket = hash_code % ASIZE (h->index);
3749 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3750 set_hash_index_slot (h, start_of_bucket, make_number (i));
3756 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
3757 the hash code of KEY. Value is the index of the entry in H
3758 matching KEY, or -1 if not found. */
3760 ptrdiff_t
3761 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
3763 EMACS_UINT hash_code;
3764 ptrdiff_t start_of_bucket;
3765 Lisp_Object idx;
3767 hash_code = h->test.hashfn (&h->test, key);
3768 eassert ((hash_code & ~INTMASK) == 0);
3769 if (hash)
3770 *hash = hash_code;
3772 start_of_bucket = hash_code % ASIZE (h->index);
3773 idx = HASH_INDEX (h, start_of_bucket);
3775 /* We need not gcpro idx since it's either an integer or nil. */
3776 while (!NILP (idx))
3778 ptrdiff_t i = XFASTINT (idx);
3779 if (EQ (key, HASH_KEY (h, i))
3780 || (h->test.cmpfn
3781 && hash_code == XUINT (HASH_HASH (h, i))
3782 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
3783 break;
3784 idx = HASH_NEXT (h, i);
3787 return NILP (idx) ? -1 : XFASTINT (idx);
3791 /* Put an entry into hash table H that associates KEY with VALUE.
3792 HASH is a previously computed hash code of KEY.
3793 Value is the index of the entry in H matching KEY. */
3795 ptrdiff_t
3796 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value,
3797 EMACS_UINT hash)
3799 ptrdiff_t start_of_bucket, i;
3801 eassert ((hash & ~INTMASK) == 0);
3803 /* Increment count after resizing because resizing may fail. */
3804 maybe_resize_hash_table (h);
3805 h->count++;
3807 /* Store key/value in the key_and_value vector. */
3808 i = XFASTINT (h->next_free);
3809 h->next_free = HASH_NEXT (h, i);
3810 set_hash_key_slot (h, i, key);
3811 set_hash_value_slot (h, i, value);
3813 /* Remember its hash code. */
3814 set_hash_hash_slot (h, i, make_number (hash));
3816 /* Add new entry to its collision chain. */
3817 start_of_bucket = hash % ASIZE (h->index);
3818 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3819 set_hash_index_slot (h, start_of_bucket, make_number (i));
3820 return i;
3824 /* Remove the entry matching KEY from hash table H, if there is one. */
3826 static void
3827 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
3829 EMACS_UINT hash_code;
3830 ptrdiff_t start_of_bucket;
3831 Lisp_Object idx, prev;
3833 hash_code = h->test.hashfn (&h->test, key);
3834 eassert ((hash_code & ~INTMASK) == 0);
3835 start_of_bucket = hash_code % ASIZE (h->index);
3836 idx = HASH_INDEX (h, start_of_bucket);
3837 prev = Qnil;
3839 /* We need not gcpro idx, prev since they're either integers or nil. */
3840 while (!NILP (idx))
3842 ptrdiff_t i = XFASTINT (idx);
3844 if (EQ (key, HASH_KEY (h, i))
3845 || (h->test.cmpfn
3846 && hash_code == XUINT (HASH_HASH (h, i))
3847 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
3849 /* Take entry out of collision chain. */
3850 if (NILP (prev))
3851 set_hash_index_slot (h, start_of_bucket, HASH_NEXT (h, i));
3852 else
3853 set_hash_next_slot (h, XFASTINT (prev), HASH_NEXT (h, i));
3855 /* Clear slots in key_and_value and add the slots to
3856 the free list. */
3857 set_hash_key_slot (h, i, Qnil);
3858 set_hash_value_slot (h, i, Qnil);
3859 set_hash_hash_slot (h, i, Qnil);
3860 set_hash_next_slot (h, i, h->next_free);
3861 h->next_free = make_number (i);
3862 h->count--;
3863 eassert (h->count >= 0);
3864 break;
3866 else
3868 prev = idx;
3869 idx = HASH_NEXT (h, i);
3875 /* Clear hash table H. */
3877 static void
3878 hash_clear (struct Lisp_Hash_Table *h)
3880 if (h->count > 0)
3882 ptrdiff_t i, size = HASH_TABLE_SIZE (h);
3884 for (i = 0; i < size; ++i)
3886 set_hash_next_slot (h, i, i < size - 1 ? make_number (i + 1) : Qnil);
3887 set_hash_key_slot (h, i, Qnil);
3888 set_hash_value_slot (h, i, Qnil);
3889 set_hash_hash_slot (h, i, Qnil);
3892 for (i = 0; i < ASIZE (h->index); ++i)
3893 ASET (h->index, i, Qnil);
3895 h->next_free = make_number (0);
3896 h->count = 0;
3902 /************************************************************************
3903 Weak Hash Tables
3904 ************************************************************************/
3906 /* Sweep weak hash table H. REMOVE_ENTRIES_P means remove
3907 entries from the table that don't survive the current GC.
3908 !REMOVE_ENTRIES_P means mark entries that are in use. Value is
3909 true if anything was marked. */
3911 static bool
3912 sweep_weak_table (struct Lisp_Hash_Table *h, bool remove_entries_p)
3914 ptrdiff_t bucket, n;
3915 bool marked;
3917 n = ASIZE (h->index) & ~ARRAY_MARK_FLAG;
3918 marked = 0;
3920 for (bucket = 0; bucket < n; ++bucket)
3922 Lisp_Object idx, next, prev;
3924 /* Follow collision chain, removing entries that
3925 don't survive this garbage collection. */
3926 prev = Qnil;
3927 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
3929 ptrdiff_t i = XFASTINT (idx);
3930 bool key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
3931 bool value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
3932 bool remove_p;
3934 if (EQ (h->weak, Qkey))
3935 remove_p = !key_known_to_survive_p;
3936 else if (EQ (h->weak, Qvalue))
3937 remove_p = !value_known_to_survive_p;
3938 else if (EQ (h->weak, Qkey_or_value))
3939 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
3940 else if (EQ (h->weak, Qkey_and_value))
3941 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
3942 else
3943 emacs_abort ();
3945 next = HASH_NEXT (h, i);
3947 if (remove_entries_p)
3949 if (remove_p)
3951 /* Take out of collision chain. */
3952 if (NILP (prev))
3953 set_hash_index_slot (h, bucket, next);
3954 else
3955 set_hash_next_slot (h, XFASTINT (prev), next);
3957 /* Add to free list. */
3958 set_hash_next_slot (h, i, h->next_free);
3959 h->next_free = idx;
3961 /* Clear key, value, and hash. */
3962 set_hash_key_slot (h, i, Qnil);
3963 set_hash_value_slot (h, i, Qnil);
3964 set_hash_hash_slot (h, i, Qnil);
3966 h->count--;
3968 else
3970 prev = idx;
3973 else
3975 if (!remove_p)
3977 /* Make sure key and value survive. */
3978 if (!key_known_to_survive_p)
3980 mark_object (HASH_KEY (h, i));
3981 marked = 1;
3984 if (!value_known_to_survive_p)
3986 mark_object (HASH_VALUE (h, i));
3987 marked = 1;
3994 return marked;
3997 /* Remove elements from weak hash tables that don't survive the
3998 current garbage collection. Remove weak tables that don't survive
3999 from Vweak_hash_tables. Called from gc_sweep. */
4001 void
4002 sweep_weak_hash_tables (void)
4004 struct Lisp_Hash_Table *h, *used, *next;
4005 bool marked;
4007 /* Mark all keys and values that are in use. Keep on marking until
4008 there is no more change. This is necessary for cases like
4009 value-weak table A containing an entry X -> Y, where Y is used in a
4010 key-weak table B, Z -> Y. If B comes after A in the list of weak
4011 tables, X -> Y might be removed from A, although when looking at B
4012 one finds that it shouldn't. */
4015 marked = 0;
4016 for (h = weak_hash_tables; h; h = h->next_weak)
4018 if (h->header.size & ARRAY_MARK_FLAG)
4019 marked |= sweep_weak_table (h, 0);
4022 while (marked);
4024 /* Remove tables and entries that aren't used. */
4025 for (h = weak_hash_tables, used = NULL; h; h = next)
4027 next = h->next_weak;
4029 if (h->header.size & ARRAY_MARK_FLAG)
4031 /* TABLE is marked as used. Sweep its contents. */
4032 if (h->count > 0)
4033 sweep_weak_table (h, 1);
4035 /* Add table to the list of used weak hash tables. */
4036 h->next_weak = used;
4037 used = h;
4041 weak_hash_tables = used;
4046 /***********************************************************************
4047 Hash Code Computation
4048 ***********************************************************************/
4050 /* Maximum depth up to which to dive into Lisp structures. */
4052 #define SXHASH_MAX_DEPTH 3
4054 /* Maximum length up to which to take list and vector elements into
4055 account. */
4057 #define SXHASH_MAX_LEN 7
4059 /* Return a hash for string PTR which has length LEN. The hash value
4060 can be any EMACS_UINT value. */
4062 EMACS_UINT
4063 hash_string (char const *ptr, ptrdiff_t len)
4065 char const *p = ptr;
4066 char const *end = p + len;
4067 unsigned char c;
4068 EMACS_UINT hash = 0;
4070 while (p != end)
4072 c = *p++;
4073 hash = sxhash_combine (hash, c);
4076 return hash;
4079 /* Return a hash for string PTR which has length LEN. The hash
4080 code returned is guaranteed to fit in a Lisp integer. */
4082 static EMACS_UINT
4083 sxhash_string (char const *ptr, ptrdiff_t len)
4085 EMACS_UINT hash = hash_string (ptr, len);
4086 return SXHASH_REDUCE (hash);
4089 /* Return a hash for the floating point value VAL. */
4091 static EMACS_UINT
4092 sxhash_float (double val)
4094 EMACS_UINT hash = 0;
4095 enum {
4096 WORDS_PER_DOUBLE = (sizeof val / sizeof hash
4097 + (sizeof val % sizeof hash != 0))
4099 union {
4100 double val;
4101 EMACS_UINT word[WORDS_PER_DOUBLE];
4102 } u;
4103 int i;
4104 u.val = val;
4105 memset (&u.val + 1, 0, sizeof u - sizeof u.val);
4106 for (i = 0; i < WORDS_PER_DOUBLE; i++)
4107 hash = sxhash_combine (hash, u.word[i]);
4108 return SXHASH_REDUCE (hash);
4111 /* Return a hash for list LIST. DEPTH is the current depth in the
4112 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4114 static EMACS_UINT
4115 sxhash_list (Lisp_Object list, int depth)
4117 EMACS_UINT hash = 0;
4118 int i;
4120 if (depth < SXHASH_MAX_DEPTH)
4121 for (i = 0;
4122 CONSP (list) && i < SXHASH_MAX_LEN;
4123 list = XCDR (list), ++i)
4125 EMACS_UINT hash2 = sxhash (XCAR (list), depth + 1);
4126 hash = sxhash_combine (hash, hash2);
4129 if (!NILP (list))
4131 EMACS_UINT hash2 = sxhash (list, depth + 1);
4132 hash = sxhash_combine (hash, hash2);
4135 return SXHASH_REDUCE (hash);
4139 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4140 the Lisp structure. */
4142 static EMACS_UINT
4143 sxhash_vector (Lisp_Object vec, int depth)
4145 EMACS_UINT hash = ASIZE (vec);
4146 int i, n;
4148 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4149 for (i = 0; i < n; ++i)
4151 EMACS_UINT hash2 = sxhash (AREF (vec, i), depth + 1);
4152 hash = sxhash_combine (hash, hash2);
4155 return SXHASH_REDUCE (hash);
4158 /* Return a hash for bool-vector VECTOR. */
4160 static EMACS_UINT
4161 sxhash_bool_vector (Lisp_Object vec)
4163 EMACS_INT size = bool_vector_size (vec);
4164 EMACS_UINT hash = size;
4165 int i, n;
4167 n = min (SXHASH_MAX_LEN, bool_vector_words (size));
4168 for (i = 0; i < n; ++i)
4169 hash = sxhash_combine (hash, bool_vector_data (vec)[i]);
4171 return SXHASH_REDUCE (hash);
4175 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4176 structure. Value is an unsigned integer clipped to INTMASK. */
4178 EMACS_UINT
4179 sxhash (Lisp_Object obj, int depth)
4181 EMACS_UINT hash;
4183 if (depth > SXHASH_MAX_DEPTH)
4184 return 0;
4186 switch (XTYPE (obj))
4188 case_Lisp_Int:
4189 hash = XUINT (obj);
4190 break;
4192 case Lisp_Misc:
4193 hash = XHASH (obj);
4194 break;
4196 case Lisp_Symbol:
4197 obj = SYMBOL_NAME (obj);
4198 /* Fall through. */
4200 case Lisp_String:
4201 hash = sxhash_string (SSDATA (obj), SBYTES (obj));
4202 break;
4204 /* This can be everything from a vector to an overlay. */
4205 case Lisp_Vectorlike:
4206 if (VECTORP (obj))
4207 /* According to the CL HyperSpec, two arrays are equal only if
4208 they are `eq', except for strings and bit-vectors. In
4209 Emacs, this works differently. We have to compare element
4210 by element. */
4211 hash = sxhash_vector (obj, depth);
4212 else if (BOOL_VECTOR_P (obj))
4213 hash = sxhash_bool_vector (obj);
4214 else
4215 /* Others are `equal' if they are `eq', so let's take their
4216 address as hash. */
4217 hash = XHASH (obj);
4218 break;
4220 case Lisp_Cons:
4221 hash = sxhash_list (obj, depth);
4222 break;
4224 case Lisp_Float:
4225 hash = sxhash_float (XFLOAT_DATA (obj));
4226 break;
4228 default:
4229 emacs_abort ();
4232 return hash;
4237 /***********************************************************************
4238 Lisp Interface
4239 ***********************************************************************/
4242 DEFUN ("sxhash", Fsxhash, Ssxhash, 1, 1, 0,
4243 doc: /* Compute a hash code for OBJ and return it as integer. */)
4244 (Lisp_Object obj)
4246 EMACS_UINT hash = sxhash (obj, 0);
4247 return make_number (hash);
4251 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4252 doc: /* Create and return a new hash table.
4254 Arguments are specified as keyword/argument pairs. The following
4255 arguments are defined:
4257 :test TEST -- TEST must be a symbol that specifies how to compare
4258 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4259 `equal'. User-supplied test and hash functions can be specified via
4260 `define-hash-table-test'.
4262 :size SIZE -- A hint as to how many elements will be put in the table.
4263 Default is 65.
4265 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4266 fills up. If REHASH-SIZE is an integer, increase the size by that
4267 amount. If it is a float, it must be > 1.0, and the new size is the
4268 old size multiplied by that factor. Default is 1.5.
4270 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4271 Resize the hash table when the ratio (number of entries / table size)
4272 is greater than or equal to THRESHOLD. Default is 0.8.
4274 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4275 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4276 returned is a weak table. Key/value pairs are removed from a weak
4277 hash table when there are no non-weak references pointing to their
4278 key, value, one of key or value, or both key and value, depending on
4279 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4280 is nil.
4282 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4283 (ptrdiff_t nargs, Lisp_Object *args)
4285 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4286 struct hash_table_test testdesc;
4287 char *used;
4288 ptrdiff_t i;
4290 /* The vector `used' is used to keep track of arguments that
4291 have been consumed. */
4292 used = alloca (nargs * sizeof *used);
4293 memset (used, 0, nargs * sizeof *used);
4295 /* See if there's a `:test TEST' among the arguments. */
4296 i = get_key_arg (QCtest, nargs, args, used);
4297 test = i ? args[i] : Qeql;
4298 if (EQ (test, Qeq))
4299 testdesc = hashtest_eq;
4300 else if (EQ (test, Qeql))
4301 testdesc = hashtest_eql;
4302 else if (EQ (test, Qequal))
4303 testdesc = hashtest_equal;
4304 else
4306 /* See if it is a user-defined test. */
4307 Lisp_Object prop;
4309 prop = Fget (test, Qhash_table_test);
4310 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4311 signal_error ("Invalid hash table test", test);
4312 testdesc.name = test;
4313 testdesc.user_cmp_function = XCAR (prop);
4314 testdesc.user_hash_function = XCAR (XCDR (prop));
4315 testdesc.hashfn = hashfn_user_defined;
4316 testdesc.cmpfn = cmpfn_user_defined;
4319 /* See if there's a `:size SIZE' argument. */
4320 i = get_key_arg (QCsize, nargs, args, used);
4321 size = i ? args[i] : Qnil;
4322 if (NILP (size))
4323 size = make_number (DEFAULT_HASH_SIZE);
4324 else if (!INTEGERP (size) || XINT (size) < 0)
4325 signal_error ("Invalid hash table size", size);
4327 /* Look for `:rehash-size SIZE'. */
4328 i = get_key_arg (QCrehash_size, nargs, args, used);
4329 rehash_size = i ? args[i] : make_float (DEFAULT_REHASH_SIZE);
4330 if (! ((INTEGERP (rehash_size) && 0 < XINT (rehash_size))
4331 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size))))
4332 signal_error ("Invalid hash table rehash size", rehash_size);
4334 /* Look for `:rehash-threshold THRESHOLD'. */
4335 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4336 rehash_threshold = i ? args[i] : make_float (DEFAULT_REHASH_THRESHOLD);
4337 if (! (FLOATP (rehash_threshold)
4338 && 0 < XFLOAT_DATA (rehash_threshold)
4339 && XFLOAT_DATA (rehash_threshold) <= 1))
4340 signal_error ("Invalid hash table rehash threshold", rehash_threshold);
4342 /* Look for `:weakness WEAK'. */
4343 i = get_key_arg (QCweakness, nargs, args, used);
4344 weak = i ? args[i] : Qnil;
4345 if (EQ (weak, Qt))
4346 weak = Qkey_and_value;
4347 if (!NILP (weak)
4348 && !EQ (weak, Qkey)
4349 && !EQ (weak, Qvalue)
4350 && !EQ (weak, Qkey_or_value)
4351 && !EQ (weak, Qkey_and_value))
4352 signal_error ("Invalid hash table weakness", weak);
4354 /* Now, all args should have been used up, or there's a problem. */
4355 for (i = 0; i < nargs; ++i)
4356 if (!used[i])
4357 signal_error ("Invalid argument list", args[i]);
4359 return make_hash_table (testdesc, size, rehash_size, rehash_threshold, weak);
4363 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4364 doc: /* Return a copy of hash table TABLE. */)
4365 (Lisp_Object table)
4367 return copy_hash_table (check_hash_table (table));
4371 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4372 doc: /* Return the number of elements in TABLE. */)
4373 (Lisp_Object table)
4375 return make_number (check_hash_table (table)->count);
4379 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4380 Shash_table_rehash_size, 1, 1, 0,
4381 doc: /* Return the current rehash size of TABLE. */)
4382 (Lisp_Object table)
4384 return check_hash_table (table)->rehash_size;
4388 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4389 Shash_table_rehash_threshold, 1, 1, 0,
4390 doc: /* Return the current rehash threshold of TABLE. */)
4391 (Lisp_Object table)
4393 return check_hash_table (table)->rehash_threshold;
4397 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4398 doc: /* Return the size of TABLE.
4399 The size can be used as an argument to `make-hash-table' to create
4400 a hash table than can hold as many elements as TABLE holds
4401 without need for resizing. */)
4402 (Lisp_Object table)
4404 struct Lisp_Hash_Table *h = check_hash_table (table);
4405 return make_number (HASH_TABLE_SIZE (h));
4409 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4410 doc: /* Return the test TABLE uses. */)
4411 (Lisp_Object table)
4413 return check_hash_table (table)->test.name;
4417 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4418 1, 1, 0,
4419 doc: /* Return the weakness of TABLE. */)
4420 (Lisp_Object table)
4422 return check_hash_table (table)->weak;
4426 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4427 doc: /* Return t if OBJ is a Lisp hash table object. */)
4428 (Lisp_Object obj)
4430 return HASH_TABLE_P (obj) ? Qt : Qnil;
4434 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4435 doc: /* Clear hash table TABLE and return it. */)
4436 (Lisp_Object table)
4438 hash_clear (check_hash_table (table));
4439 /* Be compatible with XEmacs. */
4440 return table;
4444 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4445 doc: /* Look up KEY in TABLE and return its associated value.
4446 If KEY is not found, return DFLT which defaults to nil. */)
4447 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4449 struct Lisp_Hash_Table *h = check_hash_table (table);
4450 ptrdiff_t i = hash_lookup (h, key, NULL);
4451 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4455 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4456 doc: /* Associate KEY with VALUE in hash table TABLE.
4457 If KEY is already present in table, replace its current value with
4458 VALUE. In any case, return VALUE. */)
4459 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4461 struct Lisp_Hash_Table *h = check_hash_table (table);
4462 ptrdiff_t i;
4463 EMACS_UINT hash;
4465 i = hash_lookup (h, key, &hash);
4466 if (i >= 0)
4467 set_hash_value_slot (h, i, value);
4468 else
4469 hash_put (h, key, value, hash);
4471 return value;
4475 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4476 doc: /* Remove KEY from TABLE. */)
4477 (Lisp_Object key, Lisp_Object table)
4479 struct Lisp_Hash_Table *h = check_hash_table (table);
4480 hash_remove_from_table (h, key);
4481 return Qnil;
4485 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4486 doc: /* Call FUNCTION for all entries in hash table TABLE.
4487 FUNCTION is called with two arguments, KEY and VALUE. */)
4488 (Lisp_Object function, Lisp_Object table)
4490 struct Lisp_Hash_Table *h = check_hash_table (table);
4491 Lisp_Object args[3];
4492 ptrdiff_t i;
4494 for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
4495 if (!NILP (HASH_HASH (h, i)))
4497 args[0] = function;
4498 args[1] = HASH_KEY (h, i);
4499 args[2] = HASH_VALUE (h, i);
4500 Ffuncall (3, args);
4503 return Qnil;
4507 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4508 Sdefine_hash_table_test, 3, 3, 0,
4509 doc: /* Define a new hash table test with name NAME, a symbol.
4511 In hash tables created with NAME specified as test, use TEST to
4512 compare keys, and HASH for computing hash codes of keys.
4514 TEST must be a function taking two arguments and returning non-nil if
4515 both arguments are the same. HASH must be a function taking one
4516 argument and returning an object that is the hash code of the argument.
4517 It should be the case that if (eq (funcall HASH x1) (funcall HASH x2))
4518 returns nil, then (funcall TEST x1 x2) also returns nil. */)
4519 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4521 return Fput (name, Qhash_table_test, list2 (test, hash));
4526 /************************************************************************
4527 MD5, SHA-1, and SHA-2
4528 ************************************************************************/
4530 #include "md5.h"
4531 #include "sha1.h"
4532 #include "sha256.h"
4533 #include "sha512.h"
4535 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4537 static Lisp_Object
4538 secure_hash (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror, Lisp_Object binary)
4540 int i;
4541 ptrdiff_t size;
4542 EMACS_INT start_char = 0, end_char = 0;
4543 ptrdiff_t start_byte, end_byte;
4544 register EMACS_INT b, e;
4545 register struct buffer *bp;
4546 EMACS_INT temp;
4547 int digest_size;
4548 void *(*hash_func) (const char *, size_t, void *);
4549 Lisp_Object digest;
4551 CHECK_SYMBOL (algorithm);
4553 if (STRINGP (object))
4555 if (NILP (coding_system))
4557 /* Decide the coding-system to encode the data with. */
4559 if (STRING_MULTIBYTE (object))
4560 /* use default, we can't guess correct value */
4561 coding_system = preferred_coding_system ();
4562 else
4563 coding_system = Qraw_text;
4566 if (NILP (Fcoding_system_p (coding_system)))
4568 /* Invalid coding system. */
4570 if (!NILP (noerror))
4571 coding_system = Qraw_text;
4572 else
4573 xsignal1 (Qcoding_system_error, coding_system);
4576 if (STRING_MULTIBYTE (object))
4577 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4579 size = SCHARS (object);
4581 if (!NILP (start))
4583 CHECK_NUMBER (start);
4585 start_char = XINT (start);
4587 if (start_char < 0)
4588 start_char += size;
4591 if (NILP (end))
4592 end_char = size;
4593 else
4595 CHECK_NUMBER (end);
4597 end_char = XINT (end);
4599 if (end_char < 0)
4600 end_char += size;
4603 if (!(0 <= start_char && start_char <= end_char && end_char <= size))
4604 args_out_of_range_3 (object, make_number (start_char),
4605 make_number (end_char));
4607 start_byte = NILP (start) ? 0 : string_char_to_byte (object, start_char);
4608 end_byte =
4609 NILP (end) ? SBYTES (object) : string_char_to_byte (object, end_char);
4611 else
4613 struct buffer *prev = current_buffer;
4615 record_unwind_current_buffer ();
4617 CHECK_BUFFER (object);
4619 bp = XBUFFER (object);
4620 set_buffer_internal (bp);
4622 if (NILP (start))
4623 b = BEGV;
4624 else
4626 CHECK_NUMBER_COERCE_MARKER (start);
4627 b = XINT (start);
4630 if (NILP (end))
4631 e = ZV;
4632 else
4634 CHECK_NUMBER_COERCE_MARKER (end);
4635 e = XINT (end);
4638 if (b > e)
4639 temp = b, b = e, e = temp;
4641 if (!(BEGV <= b && e <= ZV))
4642 args_out_of_range (start, end);
4644 if (NILP (coding_system))
4646 /* Decide the coding-system to encode the data with.
4647 See fileio.c:Fwrite-region */
4649 if (!NILP (Vcoding_system_for_write))
4650 coding_system = Vcoding_system_for_write;
4651 else
4653 bool force_raw_text = 0;
4655 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4656 if (NILP (coding_system)
4657 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4659 coding_system = Qnil;
4660 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4661 force_raw_text = 1;
4664 if (NILP (coding_system) && !NILP (Fbuffer_file_name (object)))
4666 /* Check file-coding-system-alist. */
4667 Lisp_Object args[4], val;
4669 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4670 args[3] = Fbuffer_file_name (object);
4671 val = Ffind_operation_coding_system (4, args);
4672 if (CONSP (val) && !NILP (XCDR (val)))
4673 coding_system = XCDR (val);
4676 if (NILP (coding_system)
4677 && !NILP (BVAR (XBUFFER (object), buffer_file_coding_system)))
4679 /* If we still have not decided a coding system, use the
4680 default value of buffer-file-coding-system. */
4681 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4684 if (!force_raw_text
4685 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4686 /* Confirm that VAL can surely encode the current region. */
4687 coding_system = call4 (Vselect_safe_coding_system_function,
4688 make_number (b), make_number (e),
4689 coding_system, Qnil);
4691 if (force_raw_text)
4692 coding_system = Qraw_text;
4695 if (NILP (Fcoding_system_p (coding_system)))
4697 /* Invalid coding system. */
4699 if (!NILP (noerror))
4700 coding_system = Qraw_text;
4701 else
4702 xsignal1 (Qcoding_system_error, coding_system);
4706 object = make_buffer_string (b, e, 0);
4707 set_buffer_internal (prev);
4708 /* Discard the unwind protect for recovering the current
4709 buffer. */
4710 specpdl_ptr--;
4712 if (STRING_MULTIBYTE (object))
4713 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4714 start_byte = 0;
4715 end_byte = SBYTES (object);
4718 if (EQ (algorithm, Qmd5))
4720 digest_size = MD5_DIGEST_SIZE;
4721 hash_func = md5_buffer;
4723 else if (EQ (algorithm, Qsha1))
4725 digest_size = SHA1_DIGEST_SIZE;
4726 hash_func = sha1_buffer;
4728 else if (EQ (algorithm, Qsha224))
4730 digest_size = SHA224_DIGEST_SIZE;
4731 hash_func = sha224_buffer;
4733 else if (EQ (algorithm, Qsha256))
4735 digest_size = SHA256_DIGEST_SIZE;
4736 hash_func = sha256_buffer;
4738 else if (EQ (algorithm, Qsha384))
4740 digest_size = SHA384_DIGEST_SIZE;
4741 hash_func = sha384_buffer;
4743 else if (EQ (algorithm, Qsha512))
4745 digest_size = SHA512_DIGEST_SIZE;
4746 hash_func = sha512_buffer;
4748 else
4749 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm)));
4751 /* allocate 2 x digest_size so that it can be re-used to hold the
4752 hexified value */
4753 digest = make_uninit_string (digest_size * 2);
4755 hash_func (SSDATA (object) + start_byte,
4756 end_byte - start_byte,
4757 SSDATA (digest));
4759 if (NILP (binary))
4761 unsigned char *p = SDATA (digest);
4762 for (i = digest_size - 1; i >= 0; i--)
4764 static char const hexdigit[16] = "0123456789abcdef";
4765 int p_i = p[i];
4766 p[2 * i] = hexdigit[p_i >> 4];
4767 p[2 * i + 1] = hexdigit[p_i & 0xf];
4769 return digest;
4771 else
4772 return make_unibyte_string (SSDATA (digest), digest_size);
4775 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
4776 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
4778 A message digest is a cryptographic checksum of a document, and the
4779 algorithm to calculate it is defined in RFC 1321.
4781 The two optional arguments START and END are character positions
4782 specifying for which part of OBJECT the message digest should be
4783 computed. If nil or omitted, the digest is computed for the whole
4784 OBJECT.
4786 The MD5 message digest is computed from the result of encoding the
4787 text in a coding system, not directly from the internal Emacs form of
4788 the text. The optional fourth argument CODING-SYSTEM specifies which
4789 coding system to encode the text with. It should be the same coding
4790 system that you used or will use when actually writing the text into a
4791 file.
4793 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
4794 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
4795 system would be chosen by default for writing this text into a file.
4797 If OBJECT is a string, the most preferred coding system (see the
4798 command `prefer-coding-system') is used.
4800 If NOERROR is non-nil, silently assume the `raw-text' coding if the
4801 guesswork fails. Normally, an error is signaled in such case. */)
4802 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
4804 return secure_hash (Qmd5, object, start, end, coding_system, noerror, Qnil);
4807 DEFUN ("secure-hash", Fsecure_hash, Ssecure_hash, 2, 5, 0,
4808 doc: /* Return the secure hash of OBJECT, a buffer or string.
4809 ALGORITHM is a symbol specifying the hash to use:
4810 md5, sha1, sha224, sha256, sha384 or sha512.
4812 The two optional arguments START and END are positions specifying for
4813 which part of OBJECT to compute the hash. If nil or omitted, uses the
4814 whole OBJECT.
4816 If BINARY is non-nil, returns a string in binary form. */)
4817 (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object binary)
4819 return secure_hash (algorithm, object, start, end, Qnil, Qnil, binary);
4822 void
4823 syms_of_fns (void)
4825 DEFSYM (Qmd5, "md5");
4826 DEFSYM (Qsha1, "sha1");
4827 DEFSYM (Qsha224, "sha224");
4828 DEFSYM (Qsha256, "sha256");
4829 DEFSYM (Qsha384, "sha384");
4830 DEFSYM (Qsha512, "sha512");
4832 /* Hash table stuff. */
4833 DEFSYM (Qhash_table_p, "hash-table-p");
4834 DEFSYM (Qeq, "eq");
4835 DEFSYM (Qeql, "eql");
4836 DEFSYM (Qequal, "equal");
4837 DEFSYM (QCtest, ":test");
4838 DEFSYM (QCsize, ":size");
4839 DEFSYM (QCrehash_size, ":rehash-size");
4840 DEFSYM (QCrehash_threshold, ":rehash-threshold");
4841 DEFSYM (QCweakness, ":weakness");
4842 DEFSYM (Qkey, "key");
4843 DEFSYM (Qvalue, "value");
4844 DEFSYM (Qhash_table_test, "hash-table-test");
4845 DEFSYM (Qkey_or_value, "key-or-value");
4846 DEFSYM (Qkey_and_value, "key-and-value");
4848 defsubr (&Ssxhash);
4849 defsubr (&Smake_hash_table);
4850 defsubr (&Scopy_hash_table);
4851 defsubr (&Shash_table_count);
4852 defsubr (&Shash_table_rehash_size);
4853 defsubr (&Shash_table_rehash_threshold);
4854 defsubr (&Shash_table_size);
4855 defsubr (&Shash_table_test);
4856 defsubr (&Shash_table_weakness);
4857 defsubr (&Shash_table_p);
4858 defsubr (&Sclrhash);
4859 defsubr (&Sgethash);
4860 defsubr (&Sputhash);
4861 defsubr (&Sremhash);
4862 defsubr (&Smaphash);
4863 defsubr (&Sdefine_hash_table_test);
4865 DEFSYM (Qstring_lessp, "string-lessp");
4866 DEFSYM (Qprovide, "provide");
4867 DEFSYM (Qrequire, "require");
4868 DEFSYM (Qyes_or_no_p_history, "yes-or-no-p-history");
4869 DEFSYM (Qcursor_in_echo_area, "cursor-in-echo-area");
4870 DEFSYM (Qwidget_type, "widget-type");
4872 staticpro (&string_char_byte_cache_string);
4873 string_char_byte_cache_string = Qnil;
4875 require_nesting_list = Qnil;
4876 staticpro (&require_nesting_list);
4878 Fset (Qyes_or_no_p_history, Qnil);
4880 DEFVAR_LISP ("features", Vfeatures,
4881 doc: /* A list of symbols which are the features of the executing Emacs.
4882 Used by `featurep' and `require', and altered by `provide'. */);
4883 Vfeatures = list1 (intern_c_string ("emacs"));
4884 DEFSYM (Qsubfeatures, "subfeatures");
4885 DEFSYM (Qfuncall, "funcall");
4887 #ifdef HAVE_LANGINFO_CODESET
4888 DEFSYM (Qcodeset, "codeset");
4889 DEFSYM (Qdays, "days");
4890 DEFSYM (Qmonths, "months");
4891 DEFSYM (Qpaper, "paper");
4892 #endif /* HAVE_LANGINFO_CODESET */
4894 DEFVAR_BOOL ("use-dialog-box", use_dialog_box,
4895 doc: /* Non-nil means mouse commands use dialog boxes to ask questions.
4896 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
4897 invoked by mouse clicks and mouse menu items.
4899 On some platforms, file selection dialogs are also enabled if this is
4900 non-nil. */);
4901 use_dialog_box = 1;
4903 DEFVAR_BOOL ("use-file-dialog", use_file_dialog,
4904 doc: /* Non-nil means mouse commands use a file dialog to ask for files.
4905 This applies to commands from menus and tool bar buttons even when
4906 they are initiated from the keyboard. If `use-dialog-box' is nil,
4907 that disables the use of a file dialog, regardless of the value of
4908 this variable. */);
4909 use_file_dialog = 1;
4911 defsubr (&Sidentity);
4912 defsubr (&Srandom);
4913 defsubr (&Slength);
4914 defsubr (&Ssafe_length);
4915 defsubr (&Sstring_bytes);
4916 defsubr (&Sstring_equal);
4917 defsubr (&Scompare_strings);
4918 defsubr (&Sstring_lessp);
4919 defsubr (&Sappend);
4920 defsubr (&Sconcat);
4921 defsubr (&Svconcat);
4922 defsubr (&Scopy_sequence);
4923 defsubr (&Sstring_make_multibyte);
4924 defsubr (&Sstring_make_unibyte);
4925 defsubr (&Sstring_as_multibyte);
4926 defsubr (&Sstring_as_unibyte);
4927 defsubr (&Sstring_to_multibyte);
4928 defsubr (&Sstring_to_unibyte);
4929 defsubr (&Scopy_alist);
4930 defsubr (&Ssubstring);
4931 defsubr (&Ssubstring_no_properties);
4932 defsubr (&Snthcdr);
4933 defsubr (&Snth);
4934 defsubr (&Selt);
4935 defsubr (&Smember);
4936 defsubr (&Smemq);
4937 defsubr (&Smemql);
4938 defsubr (&Sassq);
4939 defsubr (&Sassoc);
4940 defsubr (&Srassq);
4941 defsubr (&Srassoc);
4942 defsubr (&Sdelq);
4943 defsubr (&Sdelete);
4944 defsubr (&Snreverse);
4945 defsubr (&Sreverse);
4946 defsubr (&Ssort);
4947 defsubr (&Splist_get);
4948 defsubr (&Sget);
4949 defsubr (&Splist_put);
4950 defsubr (&Sput);
4951 defsubr (&Slax_plist_get);
4952 defsubr (&Slax_plist_put);
4953 defsubr (&Seql);
4954 defsubr (&Sequal);
4955 defsubr (&Sequal_including_properties);
4956 defsubr (&Sfillarray);
4957 defsubr (&Sclear_string);
4958 defsubr (&Snconc);
4959 defsubr (&Smapcar);
4960 defsubr (&Smapc);
4961 defsubr (&Smapconcat);
4962 defsubr (&Syes_or_no_p);
4963 defsubr (&Sload_average);
4964 defsubr (&Sfeaturep);
4965 defsubr (&Srequire);
4966 defsubr (&Sprovide);
4967 defsubr (&Splist_member);
4968 defsubr (&Swidget_put);
4969 defsubr (&Swidget_get);
4970 defsubr (&Swidget_apply);
4971 defsubr (&Sbase64_encode_region);
4972 defsubr (&Sbase64_decode_region);
4973 defsubr (&Sbase64_encode_string);
4974 defsubr (&Sbase64_decode_string);
4975 defsubr (&Smd5);
4976 defsubr (&Ssecure_hash);
4977 defsubr (&Slocale_info);
4979 hashtest_eq.name = Qeq;
4980 hashtest_eq.user_hash_function = Qnil;
4981 hashtest_eq.user_cmp_function = Qnil;
4982 hashtest_eq.cmpfn = 0;
4983 hashtest_eq.hashfn = hashfn_eq;
4985 hashtest_eql.name = Qeql;
4986 hashtest_eql.user_hash_function = Qnil;
4987 hashtest_eql.user_cmp_function = Qnil;
4988 hashtest_eql.cmpfn = cmpfn_eql;
4989 hashtest_eql.hashfn = hashfn_eql;
4991 hashtest_equal.name = Qequal;
4992 hashtest_equal.user_hash_function = Qnil;
4993 hashtest_equal.user_cmp_function = Qnil;
4994 hashtest_equal.cmpfn = cmpfn_equal;
4995 hashtest_equal.hashfn = hashfn_equal;