Spelling fixes.
[emacs.git] / src / fns.c
blob44b70af6eb56f2a8169b5d2540ab92a8998d2d06
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 Lisp_Object val;
439 ptrdiff_t size_in_chars
440 = ((bool_vector_size (arg) + BOOL_VECTOR_BITS_PER_CHAR - 1)
441 / BOOL_VECTOR_BITS_PER_CHAR);
443 val = Fmake_bool_vector (Flength (arg), Qnil);
444 memcpy (bool_vector_data (val), bool_vector_data (arg), size_in_chars);
445 return val;
448 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
449 wrong_type_argument (Qsequencep, arg);
451 return concat (1, &arg, XTYPE (arg), 0);
454 /* This structure holds information of an argument of `concat' that is
455 a string and has text properties to be copied. */
456 struct textprop_rec
458 ptrdiff_t argnum; /* refer to ARGS (arguments of `concat') */
459 ptrdiff_t from; /* refer to ARGS[argnum] (argument string) */
460 ptrdiff_t to; /* refer to VAL (the target string) */
463 static Lisp_Object
464 concat (ptrdiff_t nargs, Lisp_Object *args,
465 enum Lisp_Type target_type, bool last_special)
467 Lisp_Object val;
468 Lisp_Object tail;
469 Lisp_Object this;
470 ptrdiff_t toindex;
471 ptrdiff_t toindex_byte = 0;
472 EMACS_INT result_len;
473 EMACS_INT result_len_byte;
474 ptrdiff_t argnum;
475 Lisp_Object last_tail;
476 Lisp_Object prev;
477 bool some_multibyte;
478 /* When we make a multibyte string, we can't copy text properties
479 while concatenating each string because the length of resulting
480 string can't be decided until we finish the whole concatenation.
481 So, we record strings that have text properties to be copied
482 here, and copy the text properties after the concatenation. */
483 struct textprop_rec *textprops = NULL;
484 /* Number of elements in textprops. */
485 ptrdiff_t num_textprops = 0;
486 USE_SAFE_ALLOCA;
488 tail = Qnil;
490 /* In append, the last arg isn't treated like the others */
491 if (last_special && nargs > 0)
493 nargs--;
494 last_tail = args[nargs];
496 else
497 last_tail = Qnil;
499 /* Check each argument. */
500 for (argnum = 0; argnum < nargs; argnum++)
502 this = args[argnum];
503 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
504 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
505 wrong_type_argument (Qsequencep, this);
508 /* Compute total length in chars of arguments in RESULT_LEN.
509 If desired output is a string, also compute length in bytes
510 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
511 whether the result should be a multibyte string. */
512 result_len_byte = 0;
513 result_len = 0;
514 some_multibyte = 0;
515 for (argnum = 0; argnum < nargs; argnum++)
517 EMACS_INT len;
518 this = args[argnum];
519 len = XFASTINT (Flength (this));
520 if (target_type == Lisp_String)
522 /* We must count the number of bytes needed in the string
523 as well as the number of characters. */
524 ptrdiff_t i;
525 Lisp_Object ch;
526 int c;
527 ptrdiff_t this_len_byte;
529 if (VECTORP (this) || COMPILEDP (this))
530 for (i = 0; i < len; i++)
532 ch = AREF (this, i);
533 CHECK_CHARACTER (ch);
534 c = XFASTINT (ch);
535 this_len_byte = CHAR_BYTES (c);
536 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
537 string_overflow ();
538 result_len_byte += this_len_byte;
539 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
540 some_multibyte = 1;
542 else if (BOOL_VECTOR_P (this) && bool_vector_size (this) > 0)
543 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
544 else if (CONSP (this))
545 for (; CONSP (this); this = XCDR (this))
547 ch = XCAR (this);
548 CHECK_CHARACTER (ch);
549 c = XFASTINT (ch);
550 this_len_byte = CHAR_BYTES (c);
551 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
552 string_overflow ();
553 result_len_byte += this_len_byte;
554 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
555 some_multibyte = 1;
557 else if (STRINGP (this))
559 if (STRING_MULTIBYTE (this))
561 some_multibyte = 1;
562 this_len_byte = SBYTES (this);
564 else
565 this_len_byte = count_size_as_multibyte (SDATA (this),
566 SCHARS (this));
567 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
568 string_overflow ();
569 result_len_byte += this_len_byte;
573 result_len += len;
574 if (MOST_POSITIVE_FIXNUM < result_len)
575 memory_full (SIZE_MAX);
578 if (! some_multibyte)
579 result_len_byte = result_len;
581 /* Create the output object. */
582 if (target_type == Lisp_Cons)
583 val = Fmake_list (make_number (result_len), Qnil);
584 else if (target_type == Lisp_Vectorlike)
585 val = Fmake_vector (make_number (result_len), Qnil);
586 else if (some_multibyte)
587 val = make_uninit_multibyte_string (result_len, result_len_byte);
588 else
589 val = make_uninit_string (result_len);
591 /* In `append', if all but last arg are nil, return last arg. */
592 if (target_type == Lisp_Cons && EQ (val, Qnil))
593 return last_tail;
595 /* Copy the contents of the args into the result. */
596 if (CONSP (val))
597 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
598 else
599 toindex = 0, toindex_byte = 0;
601 prev = Qnil;
602 if (STRINGP (val))
603 SAFE_NALLOCA (textprops, 1, nargs);
605 for (argnum = 0; argnum < nargs; argnum++)
607 Lisp_Object thislen;
608 ptrdiff_t thisleni = 0;
609 register ptrdiff_t thisindex = 0;
610 register ptrdiff_t thisindex_byte = 0;
612 this = args[argnum];
613 if (!CONSP (this))
614 thislen = Flength (this), thisleni = XINT (thislen);
616 /* Between strings of the same kind, copy fast. */
617 if (STRINGP (this) && STRINGP (val)
618 && STRING_MULTIBYTE (this) == some_multibyte)
620 ptrdiff_t thislen_byte = SBYTES (this);
622 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
623 if (string_intervals (this))
625 textprops[num_textprops].argnum = argnum;
626 textprops[num_textprops].from = 0;
627 textprops[num_textprops++].to = toindex;
629 toindex_byte += thislen_byte;
630 toindex += thisleni;
632 /* Copy a single-byte string to a multibyte string. */
633 else if (STRINGP (this) && STRINGP (val))
635 if (string_intervals (this))
637 textprops[num_textprops].argnum = argnum;
638 textprops[num_textprops].from = 0;
639 textprops[num_textprops++].to = toindex;
641 toindex_byte += copy_text (SDATA (this),
642 SDATA (val) + toindex_byte,
643 SCHARS (this), 0, 1);
644 toindex += thisleni;
646 else
647 /* Copy element by element. */
648 while (1)
650 register Lisp_Object elt;
652 /* Fetch next element of `this' arg into `elt', or break if
653 `this' is exhausted. */
654 if (NILP (this)) break;
655 if (CONSP (this))
656 elt = XCAR (this), this = XCDR (this);
657 else if (thisindex >= thisleni)
658 break;
659 else if (STRINGP (this))
661 int c;
662 if (STRING_MULTIBYTE (this))
663 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
664 thisindex,
665 thisindex_byte);
666 else
668 c = SREF (this, thisindex); thisindex++;
669 if (some_multibyte && !ASCII_CHAR_P (c))
670 c = BYTE8_TO_CHAR (c);
672 XSETFASTINT (elt, c);
674 else if (BOOL_VECTOR_P (this))
676 elt = bool_vector_ref (this, thisindex);
677 thisindex++;
679 else
681 elt = AREF (this, thisindex);
682 thisindex++;
685 /* Store this element into the result. */
686 if (toindex < 0)
688 XSETCAR (tail, elt);
689 prev = tail;
690 tail = XCDR (tail);
692 else if (VECTORP (val))
694 ASET (val, toindex, elt);
695 toindex++;
697 else
699 int c;
700 CHECK_CHARACTER (elt);
701 c = XFASTINT (elt);
702 if (some_multibyte)
703 toindex_byte += CHAR_STRING (c, SDATA (val) + toindex_byte);
704 else
705 SSET (val, toindex_byte++, c);
706 toindex++;
710 if (!NILP (prev))
711 XSETCDR (prev, last_tail);
713 if (num_textprops > 0)
715 Lisp_Object props;
716 ptrdiff_t last_to_end = -1;
718 for (argnum = 0; argnum < num_textprops; argnum++)
720 this = args[textprops[argnum].argnum];
721 props = text_property_list (this,
722 make_number (0),
723 make_number (SCHARS (this)),
724 Qnil);
725 /* If successive arguments have properties, be sure that the
726 value of `composition' property be the copy. */
727 if (last_to_end == textprops[argnum].to)
728 make_composition_value_copy (props);
729 add_text_properties_from_list (val, props,
730 make_number (textprops[argnum].to));
731 last_to_end = textprops[argnum].to + SCHARS (this);
735 SAFE_FREE ();
736 return val;
739 static Lisp_Object string_char_byte_cache_string;
740 static ptrdiff_t string_char_byte_cache_charpos;
741 static ptrdiff_t string_char_byte_cache_bytepos;
743 void
744 clear_string_char_byte_cache (void)
746 string_char_byte_cache_string = Qnil;
749 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
751 ptrdiff_t
752 string_char_to_byte (Lisp_Object string, ptrdiff_t char_index)
754 ptrdiff_t i_byte;
755 ptrdiff_t best_below, best_below_byte;
756 ptrdiff_t best_above, best_above_byte;
758 best_below = best_below_byte = 0;
759 best_above = SCHARS (string);
760 best_above_byte = SBYTES (string);
761 if (best_above == best_above_byte)
762 return char_index;
764 if (EQ (string, string_char_byte_cache_string))
766 if (string_char_byte_cache_charpos < char_index)
768 best_below = string_char_byte_cache_charpos;
769 best_below_byte = string_char_byte_cache_bytepos;
771 else
773 best_above = string_char_byte_cache_charpos;
774 best_above_byte = string_char_byte_cache_bytepos;
778 if (char_index - best_below < best_above - char_index)
780 unsigned char *p = SDATA (string) + best_below_byte;
782 while (best_below < char_index)
784 p += BYTES_BY_CHAR_HEAD (*p);
785 best_below++;
787 i_byte = p - SDATA (string);
789 else
791 unsigned char *p = SDATA (string) + best_above_byte;
793 while (best_above > char_index)
795 p--;
796 while (!CHAR_HEAD_P (*p)) p--;
797 best_above--;
799 i_byte = p - SDATA (string);
802 string_char_byte_cache_bytepos = i_byte;
803 string_char_byte_cache_charpos = char_index;
804 string_char_byte_cache_string = string;
806 return i_byte;
809 /* Return the character index corresponding to BYTE_INDEX in STRING. */
811 ptrdiff_t
812 string_byte_to_char (Lisp_Object string, ptrdiff_t byte_index)
814 ptrdiff_t i, i_byte;
815 ptrdiff_t best_below, best_below_byte;
816 ptrdiff_t best_above, best_above_byte;
818 best_below = best_below_byte = 0;
819 best_above = SCHARS (string);
820 best_above_byte = SBYTES (string);
821 if (best_above == best_above_byte)
822 return byte_index;
824 if (EQ (string, string_char_byte_cache_string))
826 if (string_char_byte_cache_bytepos < byte_index)
828 best_below = string_char_byte_cache_charpos;
829 best_below_byte = string_char_byte_cache_bytepos;
831 else
833 best_above = string_char_byte_cache_charpos;
834 best_above_byte = string_char_byte_cache_bytepos;
838 if (byte_index - best_below_byte < best_above_byte - byte_index)
840 unsigned char *p = SDATA (string) + best_below_byte;
841 unsigned char *pend = SDATA (string) + byte_index;
843 while (p < pend)
845 p += BYTES_BY_CHAR_HEAD (*p);
846 best_below++;
848 i = best_below;
849 i_byte = p - SDATA (string);
851 else
853 unsigned char *p = SDATA (string) + best_above_byte;
854 unsigned char *pbeg = SDATA (string) + byte_index;
856 while (p > pbeg)
858 p--;
859 while (!CHAR_HEAD_P (*p)) p--;
860 best_above--;
862 i = best_above;
863 i_byte = p - SDATA (string);
866 string_char_byte_cache_bytepos = i_byte;
867 string_char_byte_cache_charpos = i;
868 string_char_byte_cache_string = string;
870 return i;
873 /* Convert STRING to a multibyte string. */
875 static Lisp_Object
876 string_make_multibyte (Lisp_Object string)
878 unsigned char *buf;
879 ptrdiff_t nbytes;
880 Lisp_Object ret;
881 USE_SAFE_ALLOCA;
883 if (STRING_MULTIBYTE (string))
884 return string;
886 nbytes = count_size_as_multibyte (SDATA (string),
887 SCHARS (string));
888 /* If all the chars are ASCII, they won't need any more bytes
889 once converted. In that case, we can return STRING itself. */
890 if (nbytes == SBYTES (string))
891 return string;
893 buf = SAFE_ALLOCA (nbytes);
894 copy_text (SDATA (string), buf, SBYTES (string),
895 0, 1);
897 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
898 SAFE_FREE ();
900 return ret;
904 /* Convert STRING (if unibyte) to a multibyte string without changing
905 the number of characters. Characters 0200 trough 0237 are
906 converted to eight-bit characters. */
908 Lisp_Object
909 string_to_multibyte (Lisp_Object string)
911 unsigned char *buf;
912 ptrdiff_t nbytes;
913 Lisp_Object ret;
914 USE_SAFE_ALLOCA;
916 if (STRING_MULTIBYTE (string))
917 return string;
919 nbytes = count_size_as_multibyte (SDATA (string), SBYTES (string));
920 /* If all the chars are ASCII, they won't need any more bytes once
921 converted. */
922 if (nbytes == SBYTES (string))
923 return make_multibyte_string (SSDATA (string), nbytes, nbytes);
925 buf = SAFE_ALLOCA (nbytes);
926 memcpy (buf, SDATA (string), SBYTES (string));
927 str_to_multibyte (buf, nbytes, SBYTES (string));
929 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
930 SAFE_FREE ();
932 return ret;
936 /* Convert STRING to a single-byte string. */
938 Lisp_Object
939 string_make_unibyte (Lisp_Object string)
941 ptrdiff_t nchars;
942 unsigned char *buf;
943 Lisp_Object ret;
944 USE_SAFE_ALLOCA;
946 if (! STRING_MULTIBYTE (string))
947 return string;
949 nchars = SCHARS (string);
951 buf = SAFE_ALLOCA (nchars);
952 copy_text (SDATA (string), buf, SBYTES (string),
953 1, 0);
955 ret = make_unibyte_string ((char *) buf, nchars);
956 SAFE_FREE ();
958 return ret;
961 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
962 1, 1, 0,
963 doc: /* Return the multibyte equivalent of STRING.
964 If STRING is unibyte and contains non-ASCII characters, the function
965 `unibyte-char-to-multibyte' is used to convert each unibyte character
966 to a multibyte character. In this case, the returned string is a
967 newly created string with no text properties. If STRING is multibyte
968 or entirely ASCII, it is returned unchanged. In particular, when
969 STRING is unibyte and entirely ASCII, the returned string is unibyte.
970 \(When the characters are all ASCII, Emacs primitives will treat the
971 string the same way whether it is unibyte or multibyte.) */)
972 (Lisp_Object string)
974 CHECK_STRING (string);
976 return string_make_multibyte (string);
979 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
980 1, 1, 0,
981 doc: /* Return the unibyte equivalent of STRING.
982 Multibyte character codes are converted to unibyte according to
983 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
984 If the lookup in the translation table fails, this function takes just
985 the low 8 bits of each character. */)
986 (Lisp_Object string)
988 CHECK_STRING (string);
990 return string_make_unibyte (string);
993 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
994 1, 1, 0,
995 doc: /* Return a unibyte string with the same individual bytes as STRING.
996 If STRING is unibyte, the result is STRING itself.
997 Otherwise it is a newly created string, with no text properties.
998 If STRING is multibyte and contains a character of charset
999 `eight-bit', it is converted to the corresponding single byte. */)
1000 (Lisp_Object string)
1002 CHECK_STRING (string);
1004 if (STRING_MULTIBYTE (string))
1006 unsigned char *str = (unsigned char *) xlispstrdup (string);
1007 ptrdiff_t bytes = str_as_unibyte (str, SBYTES (string));
1009 string = make_unibyte_string ((char *) str, bytes);
1010 xfree (str);
1012 return string;
1015 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1016 1, 1, 0,
1017 doc: /* Return a multibyte string with the same individual bytes as STRING.
1018 If STRING is multibyte, the result is STRING itself.
1019 Otherwise it is a newly created string, with no text properties.
1021 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1022 part of a correct utf-8 sequence), it is converted to the corresponding
1023 multibyte character of charset `eight-bit'.
1024 See also `string-to-multibyte'.
1026 Beware, this often doesn't really do what you think it does.
1027 It is similar to (decode-coding-string STRING 'utf-8-emacs).
1028 If you're not sure, whether to use `string-as-multibyte' or
1029 `string-to-multibyte', use `string-to-multibyte'. */)
1030 (Lisp_Object string)
1032 CHECK_STRING (string);
1034 if (! STRING_MULTIBYTE (string))
1036 Lisp_Object new_string;
1037 ptrdiff_t nchars, nbytes;
1039 parse_str_as_multibyte (SDATA (string),
1040 SBYTES (string),
1041 &nchars, &nbytes);
1042 new_string = make_uninit_multibyte_string (nchars, nbytes);
1043 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1044 if (nbytes != SBYTES (string))
1045 str_as_multibyte (SDATA (new_string), nbytes,
1046 SBYTES (string), NULL);
1047 string = new_string;
1048 set_string_intervals (string, NULL);
1050 return string;
1053 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1054 1, 1, 0,
1055 doc: /* Return a multibyte string with the same individual chars as STRING.
1056 If STRING is multibyte, the result is STRING itself.
1057 Otherwise it is a newly created string, with no text properties.
1059 If STRING is unibyte and contains an 8-bit byte, it is converted to
1060 the corresponding multibyte character of charset `eight-bit'.
1062 This differs from `string-as-multibyte' by converting each byte of a correct
1063 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1064 correct sequence. */)
1065 (Lisp_Object string)
1067 CHECK_STRING (string);
1069 return string_to_multibyte (string);
1072 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1073 1, 1, 0,
1074 doc: /* Return a unibyte string with the same individual chars as STRING.
1075 If STRING is unibyte, the result is STRING itself.
1076 Otherwise it is a newly created string, with no text properties,
1077 where each `eight-bit' character is converted to the corresponding byte.
1078 If STRING contains a non-ASCII, non-`eight-bit' character,
1079 an error is signaled. */)
1080 (Lisp_Object string)
1082 CHECK_STRING (string);
1084 if (STRING_MULTIBYTE (string))
1086 ptrdiff_t chars = SCHARS (string);
1087 unsigned char *str = xmalloc (chars);
1088 ptrdiff_t converted = str_to_unibyte (SDATA (string), str, chars);
1090 if (converted < chars)
1091 error ("Can't convert the %"pD"dth character to unibyte", converted);
1092 string = make_unibyte_string ((char *) str, chars);
1093 xfree (str);
1095 return string;
1099 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1100 doc: /* Return a copy of ALIST.
1101 This is an alist which represents the same mapping from objects to objects,
1102 but does not share the alist structure with ALIST.
1103 The objects mapped (cars and cdrs of elements of the alist)
1104 are shared, however.
1105 Elements of ALIST that are not conses are also shared. */)
1106 (Lisp_Object alist)
1108 register Lisp_Object tem;
1110 CHECK_LIST (alist);
1111 if (NILP (alist))
1112 return alist;
1113 alist = concat (1, &alist, Lisp_Cons, 0);
1114 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1116 register Lisp_Object car;
1117 car = XCAR (tem);
1119 if (CONSP (car))
1120 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1122 return alist;
1125 DEFUN ("substring", Fsubstring, Ssubstring, 2, 3, 0,
1126 doc: /* Return a new string whose contents are a substring of STRING.
1127 The returned string consists of the characters between index FROM
1128 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1129 zero-indexed: 0 means the first character of STRING. Negative values
1130 are counted from the end of STRING. If TO is nil, the substring runs
1131 to the end of STRING.
1133 The STRING argument may also be a vector. In that case, the return
1134 value is a new vector that contains the elements between index FROM
1135 \(inclusive) and index TO (exclusive) of that vector argument. */)
1136 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1138 Lisp_Object res;
1139 ptrdiff_t size;
1140 EMACS_INT from_char, to_char;
1142 CHECK_VECTOR_OR_STRING (string);
1143 CHECK_NUMBER (from);
1145 if (STRINGP (string))
1146 size = SCHARS (string);
1147 else
1148 size = ASIZE (string);
1150 if (NILP (to))
1151 to_char = size;
1152 else
1154 CHECK_NUMBER (to);
1156 to_char = XINT (to);
1157 if (to_char < 0)
1158 to_char += size;
1161 from_char = XINT (from);
1162 if (from_char < 0)
1163 from_char += size;
1164 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1165 args_out_of_range_3 (string, make_number (from_char),
1166 make_number (to_char));
1168 if (STRINGP (string))
1170 ptrdiff_t to_byte =
1171 (NILP (to) ? SBYTES (string) : string_char_to_byte (string, to_char));
1172 ptrdiff_t from_byte = string_char_to_byte (string, from_char);
1173 res = make_specified_string (SSDATA (string) + from_byte,
1174 to_char - from_char, to_byte - from_byte,
1175 STRING_MULTIBYTE (string));
1176 copy_text_properties (make_number (from_char), make_number (to_char),
1177 string, make_number (0), res, Qnil);
1179 else
1180 res = Fvector (to_char - from_char, aref_addr (string, from_char));
1182 return res;
1186 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1187 doc: /* Return a substring of STRING, without text properties.
1188 It starts at index FROM and ends before TO.
1189 TO may be nil or omitted; then the substring runs to the end of STRING.
1190 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1191 If FROM or TO is negative, it counts from the end.
1193 With one argument, just copy STRING without its properties. */)
1194 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1196 ptrdiff_t size;
1197 EMACS_INT from_char, to_char;
1198 ptrdiff_t from_byte, to_byte;
1200 CHECK_STRING (string);
1202 size = SCHARS (string);
1204 if (NILP (from))
1205 from_char = 0;
1206 else
1208 CHECK_NUMBER (from);
1209 from_char = XINT (from);
1210 if (from_char < 0)
1211 from_char += size;
1214 if (NILP (to))
1215 to_char = size;
1216 else
1218 CHECK_NUMBER (to);
1219 to_char = XINT (to);
1220 if (to_char < 0)
1221 to_char += size;
1224 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1225 args_out_of_range_3 (string, make_number (from_char),
1226 make_number (to_char));
1228 from_byte = NILP (from) ? 0 : string_char_to_byte (string, from_char);
1229 to_byte =
1230 NILP (to) ? SBYTES (string) : string_char_to_byte (string, to_char);
1231 return make_specified_string (SSDATA (string) + from_byte,
1232 to_char - from_char, to_byte - from_byte,
1233 STRING_MULTIBYTE (string));
1236 /* Extract a substring of STRING, giving start and end positions
1237 both in characters and in bytes. */
1239 Lisp_Object
1240 substring_both (Lisp_Object string, ptrdiff_t from, ptrdiff_t from_byte,
1241 ptrdiff_t to, ptrdiff_t to_byte)
1243 Lisp_Object res;
1244 ptrdiff_t size;
1246 CHECK_VECTOR_OR_STRING (string);
1248 size = STRINGP (string) ? SCHARS (string) : ASIZE (string);
1250 if (!(0 <= from && from <= to && to <= size))
1251 args_out_of_range_3 (string, make_number (from), make_number (to));
1253 if (STRINGP (string))
1255 res = make_specified_string (SSDATA (string) + from_byte,
1256 to - from, to_byte - from_byte,
1257 STRING_MULTIBYTE (string));
1258 copy_text_properties (make_number (from), make_number (to),
1259 string, make_number (0), res, Qnil);
1261 else
1262 res = Fvector (to - from, aref_addr (string, from));
1264 return res;
1267 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1268 doc: /* Take cdr N times on LIST, return the result. */)
1269 (Lisp_Object n, Lisp_Object list)
1271 EMACS_INT i, num;
1272 CHECK_NUMBER (n);
1273 num = XINT (n);
1274 for (i = 0; i < num && !NILP (list); i++)
1276 QUIT;
1277 CHECK_LIST_CONS (list, list);
1278 list = XCDR (list);
1280 return list;
1283 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1284 doc: /* Return the Nth element of LIST.
1285 N counts from zero. If LIST is not that long, nil is returned. */)
1286 (Lisp_Object n, Lisp_Object list)
1288 return Fcar (Fnthcdr (n, list));
1291 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1292 doc: /* Return element of SEQUENCE at index N. */)
1293 (register Lisp_Object sequence, Lisp_Object n)
1295 CHECK_NUMBER (n);
1296 if (CONSP (sequence) || NILP (sequence))
1297 return Fcar (Fnthcdr (n, sequence));
1299 /* Faref signals a "not array" error, so check here. */
1300 CHECK_ARRAY (sequence, Qsequencep);
1301 return Faref (sequence, n);
1304 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1305 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1306 The value is actually the tail of LIST whose car is ELT. */)
1307 (register Lisp_Object elt, Lisp_Object list)
1309 register Lisp_Object tail;
1310 for (tail = list; CONSP (tail); tail = XCDR (tail))
1312 register Lisp_Object tem;
1313 CHECK_LIST_CONS (tail, list);
1314 tem = XCAR (tail);
1315 if (! NILP (Fequal (elt, tem)))
1316 return tail;
1317 QUIT;
1319 return Qnil;
1322 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1323 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1324 The value is actually the tail of LIST whose car is ELT. */)
1325 (register Lisp_Object elt, Lisp_Object list)
1327 while (1)
1329 if (!CONSP (list) || EQ (XCAR (list), elt))
1330 break;
1332 list = XCDR (list);
1333 if (!CONSP (list) || EQ (XCAR (list), elt))
1334 break;
1336 list = XCDR (list);
1337 if (!CONSP (list) || EQ (XCAR (list), elt))
1338 break;
1340 list = XCDR (list);
1341 QUIT;
1344 CHECK_LIST (list);
1345 return list;
1348 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1349 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1350 The value is actually the tail of LIST whose car is ELT. */)
1351 (register Lisp_Object elt, Lisp_Object list)
1353 register Lisp_Object tail;
1355 if (!FLOATP (elt))
1356 return Fmemq (elt, list);
1358 for (tail = list; CONSP (tail); tail = XCDR (tail))
1360 register Lisp_Object tem;
1361 CHECK_LIST_CONS (tail, list);
1362 tem = XCAR (tail);
1363 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0))
1364 return tail;
1365 QUIT;
1367 return Qnil;
1370 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1371 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1372 The value is actually the first element of LIST whose car is KEY.
1373 Elements of LIST that are not conses are ignored. */)
1374 (Lisp_Object key, Lisp_Object list)
1376 while (1)
1378 if (!CONSP (list)
1379 || (CONSP (XCAR (list))
1380 && EQ (XCAR (XCAR (list)), key)))
1381 break;
1383 list = XCDR (list);
1384 if (!CONSP (list)
1385 || (CONSP (XCAR (list))
1386 && EQ (XCAR (XCAR (list)), key)))
1387 break;
1389 list = XCDR (list);
1390 if (!CONSP (list)
1391 || (CONSP (XCAR (list))
1392 && EQ (XCAR (XCAR (list)), key)))
1393 break;
1395 list = XCDR (list);
1396 QUIT;
1399 return CAR (list);
1402 /* Like Fassq but never report an error and do not allow quits.
1403 Use only on lists known never to be circular. */
1405 Lisp_Object
1406 assq_no_quit (Lisp_Object key, Lisp_Object list)
1408 while (CONSP (list)
1409 && (!CONSP (XCAR (list))
1410 || !EQ (XCAR (XCAR (list)), key)))
1411 list = XCDR (list);
1413 return CAR_SAFE (list);
1416 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1417 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1418 The value is actually the first element of LIST whose car equals KEY. */)
1419 (Lisp_Object key, Lisp_Object list)
1421 Lisp_Object car;
1423 while (1)
1425 if (!CONSP (list)
1426 || (CONSP (XCAR (list))
1427 && (car = XCAR (XCAR (list)),
1428 EQ (car, key) || !NILP (Fequal (car, key)))))
1429 break;
1431 list = XCDR (list);
1432 if (!CONSP (list)
1433 || (CONSP (XCAR (list))
1434 && (car = XCAR (XCAR (list)),
1435 EQ (car, key) || !NILP (Fequal (car, key)))))
1436 break;
1438 list = XCDR (list);
1439 if (!CONSP (list)
1440 || (CONSP (XCAR (list))
1441 && (car = XCAR (XCAR (list)),
1442 EQ (car, key) || !NILP (Fequal (car, key)))))
1443 break;
1445 list = XCDR (list);
1446 QUIT;
1449 return CAR (list);
1452 /* Like Fassoc but never report an error and do not allow quits.
1453 Use only on lists known never to be circular. */
1455 Lisp_Object
1456 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1458 while (CONSP (list)
1459 && (!CONSP (XCAR (list))
1460 || (!EQ (XCAR (XCAR (list)), key)
1461 && NILP (Fequal (XCAR (XCAR (list)), key)))))
1462 list = XCDR (list);
1464 return CONSP (list) ? XCAR (list) : Qnil;
1467 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1468 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1469 The value is actually the first element of LIST whose cdr is KEY. */)
1470 (register Lisp_Object key, Lisp_Object list)
1472 while (1)
1474 if (!CONSP (list)
1475 || (CONSP (XCAR (list))
1476 && EQ (XCDR (XCAR (list)), key)))
1477 break;
1479 list = XCDR (list);
1480 if (!CONSP (list)
1481 || (CONSP (XCAR (list))
1482 && EQ (XCDR (XCAR (list)), key)))
1483 break;
1485 list = XCDR (list);
1486 if (!CONSP (list)
1487 || (CONSP (XCAR (list))
1488 && EQ (XCDR (XCAR (list)), key)))
1489 break;
1491 list = XCDR (list);
1492 QUIT;
1495 return CAR (list);
1498 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1499 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1500 The value is actually the first element of LIST whose cdr equals KEY. */)
1501 (Lisp_Object key, Lisp_Object list)
1503 Lisp_Object cdr;
1505 while (1)
1507 if (!CONSP (list)
1508 || (CONSP (XCAR (list))
1509 && (cdr = XCDR (XCAR (list)),
1510 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1511 break;
1513 list = XCDR (list);
1514 if (!CONSP (list)
1515 || (CONSP (XCAR (list))
1516 && (cdr = XCDR (XCAR (list)),
1517 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1518 break;
1520 list = XCDR (list);
1521 if (!CONSP (list)
1522 || (CONSP (XCAR (list))
1523 && (cdr = XCDR (XCAR (list)),
1524 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1525 break;
1527 list = XCDR (list);
1528 QUIT;
1531 return CAR (list);
1534 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1535 doc: /* Delete members of LIST which are `eq' to ELT, and return the result.
1536 More precisely, this function skips any members `eq' to ELT at the
1537 front of LIST, then removes members `eq' to ELT from the remaining
1538 sublist by modifying its list structure, then returns the resulting
1539 list.
1541 Write `(setq foo (delq element foo))' to be sure of correctly changing
1542 the value of a list `foo'. */)
1543 (register Lisp_Object elt, Lisp_Object list)
1545 register Lisp_Object tail, prev;
1546 register Lisp_Object tem;
1548 tail = list;
1549 prev = Qnil;
1550 while (CONSP (tail))
1552 CHECK_LIST_CONS (tail, list);
1553 tem = XCAR (tail);
1554 if (EQ (elt, tem))
1556 if (NILP (prev))
1557 list = XCDR (tail);
1558 else
1559 Fsetcdr (prev, XCDR (tail));
1561 else
1562 prev = tail;
1563 tail = XCDR (tail);
1564 QUIT;
1566 return list;
1569 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1570 doc: /* Delete members of SEQ which are `equal' to ELT, and return the result.
1571 SEQ must be a sequence (i.e. a list, a vector, or a string).
1572 The return value is a sequence of the same type.
1574 If SEQ is a list, this behaves like `delq', except that it compares
1575 with `equal' instead of `eq'. In particular, it may remove elements
1576 by altering the list structure.
1578 If SEQ is not a list, deletion is never performed destructively;
1579 instead this function creates and returns a new vector or string.
1581 Write `(setq foo (delete element foo))' to be sure of correctly
1582 changing the value of a sequence `foo'. */)
1583 (Lisp_Object elt, Lisp_Object seq)
1585 if (VECTORP (seq))
1587 ptrdiff_t i, n;
1589 for (i = n = 0; i < ASIZE (seq); ++i)
1590 if (NILP (Fequal (AREF (seq, i), elt)))
1591 ++n;
1593 if (n != ASIZE (seq))
1595 struct Lisp_Vector *p = allocate_vector (n);
1597 for (i = n = 0; i < ASIZE (seq); ++i)
1598 if (NILP (Fequal (AREF (seq, i), elt)))
1599 p->contents[n++] = AREF (seq, i);
1601 XSETVECTOR (seq, p);
1604 else if (STRINGP (seq))
1606 ptrdiff_t i, ibyte, nchars, nbytes, cbytes;
1607 int c;
1609 for (i = nchars = nbytes = ibyte = 0;
1610 i < SCHARS (seq);
1611 ++i, ibyte += cbytes)
1613 if (STRING_MULTIBYTE (seq))
1615 c = STRING_CHAR (SDATA (seq) + ibyte);
1616 cbytes = CHAR_BYTES (c);
1618 else
1620 c = SREF (seq, i);
1621 cbytes = 1;
1624 if (!INTEGERP (elt) || c != XINT (elt))
1626 ++nchars;
1627 nbytes += cbytes;
1631 if (nchars != SCHARS (seq))
1633 Lisp_Object tem;
1635 tem = make_uninit_multibyte_string (nchars, nbytes);
1636 if (!STRING_MULTIBYTE (seq))
1637 STRING_SET_UNIBYTE (tem);
1639 for (i = nchars = nbytes = ibyte = 0;
1640 i < SCHARS (seq);
1641 ++i, ibyte += cbytes)
1643 if (STRING_MULTIBYTE (seq))
1645 c = STRING_CHAR (SDATA (seq) + ibyte);
1646 cbytes = CHAR_BYTES (c);
1648 else
1650 c = SREF (seq, i);
1651 cbytes = 1;
1654 if (!INTEGERP (elt) || c != XINT (elt))
1656 unsigned char *from = SDATA (seq) + ibyte;
1657 unsigned char *to = SDATA (tem) + nbytes;
1658 ptrdiff_t n;
1660 ++nchars;
1661 nbytes += cbytes;
1663 for (n = cbytes; n--; )
1664 *to++ = *from++;
1668 seq = tem;
1671 else
1673 Lisp_Object tail, prev;
1675 for (tail = seq, prev = Qnil; CONSP (tail); tail = XCDR (tail))
1677 CHECK_LIST_CONS (tail, seq);
1679 if (!NILP (Fequal (elt, XCAR (tail))))
1681 if (NILP (prev))
1682 seq = XCDR (tail);
1683 else
1684 Fsetcdr (prev, XCDR (tail));
1686 else
1687 prev = tail;
1688 QUIT;
1692 return seq;
1695 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1696 doc: /* Reverse LIST by modifying cdr pointers.
1697 Return the reversed list. Expects a properly nil-terminated list. */)
1698 (Lisp_Object list)
1700 register Lisp_Object prev, tail, next;
1702 if (NILP (list)) return list;
1703 prev = Qnil;
1704 tail = list;
1705 while (!NILP (tail))
1707 QUIT;
1708 CHECK_LIST_CONS (tail, tail);
1709 next = XCDR (tail);
1710 Fsetcdr (tail, prev);
1711 prev = tail;
1712 tail = next;
1714 return prev;
1717 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1718 doc: /* Reverse LIST, copying. Return the reversed list.
1719 See also the function `nreverse', which is used more often. */)
1720 (Lisp_Object list)
1722 Lisp_Object new;
1724 for (new = Qnil; CONSP (list); list = XCDR (list))
1726 QUIT;
1727 new = Fcons (XCAR (list), new);
1729 CHECK_LIST_END (list, list);
1730 return new;
1733 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
1734 doc: /* Sort LIST, stably, comparing elements using PREDICATE.
1735 Returns the sorted list. LIST is modified by side effects.
1736 PREDICATE is called with two elements of LIST, and should return non-nil
1737 if the first element should sort before the second. */)
1738 (Lisp_Object list, Lisp_Object predicate)
1740 Lisp_Object front, back;
1741 register Lisp_Object len, tem;
1742 struct gcpro gcpro1, gcpro2;
1743 EMACS_INT length;
1745 front = list;
1746 len = Flength (list);
1747 length = XINT (len);
1748 if (length < 2)
1749 return list;
1751 XSETINT (len, (length / 2) - 1);
1752 tem = Fnthcdr (len, list);
1753 back = Fcdr (tem);
1754 Fsetcdr (tem, Qnil);
1756 GCPRO2 (front, back);
1757 front = Fsort (front, predicate);
1758 back = Fsort (back, predicate);
1759 UNGCPRO;
1760 return merge (front, back, predicate);
1763 Lisp_Object
1764 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
1766 Lisp_Object value;
1767 register Lisp_Object tail;
1768 Lisp_Object tem;
1769 register Lisp_Object l1, l2;
1770 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1772 l1 = org_l1;
1773 l2 = org_l2;
1774 tail = Qnil;
1775 value = Qnil;
1777 /* It is sufficient to protect org_l1 and org_l2.
1778 When l1 and l2 are updated, we copy the new values
1779 back into the org_ vars. */
1780 GCPRO4 (org_l1, org_l2, pred, value);
1782 while (1)
1784 if (NILP (l1))
1786 UNGCPRO;
1787 if (NILP (tail))
1788 return l2;
1789 Fsetcdr (tail, l2);
1790 return value;
1792 if (NILP (l2))
1794 UNGCPRO;
1795 if (NILP (tail))
1796 return l1;
1797 Fsetcdr (tail, l1);
1798 return value;
1800 tem = call2 (pred, Fcar (l2), Fcar (l1));
1801 if (NILP (tem))
1803 tem = l1;
1804 l1 = Fcdr (l1);
1805 org_l1 = l1;
1807 else
1809 tem = l2;
1810 l2 = Fcdr (l2);
1811 org_l2 = l2;
1813 if (NILP (tail))
1814 value = tem;
1815 else
1816 Fsetcdr (tail, tem);
1817 tail = tem;
1822 /* This does not check for quits. That is safe since it must terminate. */
1824 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
1825 doc: /* Extract a value from a property list.
1826 PLIST is a property list, which is a list of the form
1827 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1828 corresponding to the given PROP, or nil if PROP is not one of the
1829 properties on the list. This function never signals an error. */)
1830 (Lisp_Object plist, Lisp_Object prop)
1832 Lisp_Object tail, halftail;
1834 /* halftail is used to detect circular lists. */
1835 tail = halftail = plist;
1836 while (CONSP (tail) && CONSP (XCDR (tail)))
1838 if (EQ (prop, XCAR (tail)))
1839 return XCAR (XCDR (tail));
1841 tail = XCDR (XCDR (tail));
1842 halftail = XCDR (halftail);
1843 if (EQ (tail, halftail))
1844 break;
1847 return Qnil;
1850 DEFUN ("get", Fget, Sget, 2, 2, 0,
1851 doc: /* Return the value of SYMBOL's PROPNAME property.
1852 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
1853 (Lisp_Object symbol, Lisp_Object propname)
1855 CHECK_SYMBOL (symbol);
1856 return Fplist_get (XSYMBOL (symbol)->plist, propname);
1859 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
1860 doc: /* Change value in PLIST of PROP to VAL.
1861 PLIST is a property list, which is a list of the form
1862 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
1863 If PROP is already a property on the list, its value is set to VAL,
1864 otherwise the new PROP VAL pair is added. The new plist is returned;
1865 use `(setq x (plist-put x prop val))' to be sure to use the new value.
1866 The PLIST is modified by side effects. */)
1867 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1869 register Lisp_Object tail, prev;
1870 Lisp_Object newcell;
1871 prev = Qnil;
1872 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1873 tail = XCDR (XCDR (tail)))
1875 if (EQ (prop, XCAR (tail)))
1877 Fsetcar (XCDR (tail), val);
1878 return plist;
1881 prev = tail;
1882 QUIT;
1884 newcell = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
1885 if (NILP (prev))
1886 return newcell;
1887 else
1888 Fsetcdr (XCDR (prev), newcell);
1889 return plist;
1892 DEFUN ("put", Fput, Sput, 3, 3, 0,
1893 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
1894 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
1895 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
1897 CHECK_SYMBOL (symbol);
1898 set_symbol_plist
1899 (symbol, Fplist_put (XSYMBOL (symbol)->plist, propname, value));
1900 return value;
1903 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
1904 doc: /* Extract a value from a property list, comparing with `equal'.
1905 PLIST is a property list, which is a list of the form
1906 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1907 corresponding to the given PROP, or nil if PROP is not
1908 one of the properties on the list. */)
1909 (Lisp_Object plist, Lisp_Object prop)
1911 Lisp_Object tail;
1913 for (tail = plist;
1914 CONSP (tail) && CONSP (XCDR (tail));
1915 tail = XCDR (XCDR (tail)))
1917 if (! NILP (Fequal (prop, XCAR (tail))))
1918 return XCAR (XCDR (tail));
1920 QUIT;
1923 CHECK_LIST_END (tail, prop);
1925 return Qnil;
1928 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
1929 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
1930 PLIST is a property list, which is a list of the form
1931 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
1932 If PROP is already a property on the list, its value is set to VAL,
1933 otherwise the new PROP VAL pair is added. The new plist is returned;
1934 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
1935 The PLIST is modified by side effects. */)
1936 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1938 register Lisp_Object tail, prev;
1939 Lisp_Object newcell;
1940 prev = Qnil;
1941 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1942 tail = XCDR (XCDR (tail)))
1944 if (! NILP (Fequal (prop, XCAR (tail))))
1946 Fsetcar (XCDR (tail), val);
1947 return plist;
1950 prev = tail;
1951 QUIT;
1953 newcell = list2 (prop, val);
1954 if (NILP (prev))
1955 return newcell;
1956 else
1957 Fsetcdr (XCDR (prev), newcell);
1958 return plist;
1961 DEFUN ("eql", Feql, Seql, 2, 2, 0,
1962 doc: /* Return t if the two args are the same Lisp object.
1963 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
1964 (Lisp_Object obj1, Lisp_Object obj2)
1966 if (FLOATP (obj1))
1967 return internal_equal (obj1, obj2, 0, 0) ? Qt : Qnil;
1968 else
1969 return EQ (obj1, obj2) ? Qt : Qnil;
1972 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
1973 doc: /* Return t if two Lisp objects have similar structure and contents.
1974 They must have the same data type.
1975 Conses are compared by comparing the cars and the cdrs.
1976 Vectors and strings are compared element by element.
1977 Numbers are compared by value, but integers cannot equal floats.
1978 (Use `=' if you want integers and floats to be able to be equal.)
1979 Symbols must match exactly. */)
1980 (register Lisp_Object o1, Lisp_Object o2)
1982 return internal_equal (o1, o2, 0, 0) ? Qt : Qnil;
1985 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
1986 doc: /* Return t if two Lisp objects have similar structure and contents.
1987 This is like `equal' except that it compares the text properties
1988 of strings. (`equal' ignores text properties.) */)
1989 (register Lisp_Object o1, Lisp_Object o2)
1991 return internal_equal (o1, o2, 0, 1) ? Qt : Qnil;
1994 /* DEPTH is current depth of recursion. Signal an error if it
1995 gets too deep.
1996 PROPS means compare string text properties too. */
1998 static bool
1999 internal_equal (Lisp_Object o1, Lisp_Object o2, int depth, bool props)
2001 if (depth > 200)
2002 error ("Stack overflow in equal");
2004 tail_recurse:
2005 QUIT;
2006 if (EQ (o1, o2))
2007 return 1;
2008 if (XTYPE (o1) != XTYPE (o2))
2009 return 0;
2011 switch (XTYPE (o1))
2013 case Lisp_Float:
2015 double d1, d2;
2017 d1 = extract_float (o1);
2018 d2 = extract_float (o2);
2019 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2020 though they are not =. */
2021 return d1 == d2 || (d1 != d1 && d2 != d2);
2024 case Lisp_Cons:
2025 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1, props))
2026 return 0;
2027 o1 = XCDR (o1);
2028 o2 = XCDR (o2);
2029 goto tail_recurse;
2031 case Lisp_Misc:
2032 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2033 return 0;
2034 if (OVERLAYP (o1))
2036 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2037 depth + 1, props)
2038 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2039 depth + 1, props))
2040 return 0;
2041 o1 = XOVERLAY (o1)->plist;
2042 o2 = XOVERLAY (o2)->plist;
2043 goto tail_recurse;
2045 if (MARKERP (o1))
2047 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2048 && (XMARKER (o1)->buffer == 0
2049 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2051 break;
2053 case Lisp_Vectorlike:
2055 register int i;
2056 ptrdiff_t size = ASIZE (o1);
2057 /* Pseudovectors have the type encoded in the size field, so this test
2058 actually checks that the objects have the same type as well as the
2059 same size. */
2060 if (ASIZE (o2) != size)
2061 return 0;
2062 /* Boolvectors are compared much like strings. */
2063 if (BOOL_VECTOR_P (o1))
2065 EMACS_INT size = bool_vector_size (o1);
2066 if (size != bool_vector_size (o2))
2067 return 0;
2068 if (memcmp (bool_vector_data (o1), bool_vector_data (o2),
2069 ((size + BOOL_VECTOR_BITS_PER_CHAR - 1)
2070 / BOOL_VECTOR_BITS_PER_CHAR)))
2071 return 0;
2072 return 1;
2074 if (WINDOW_CONFIGURATIONP (o1))
2075 return compare_window_configurations (o1, o2, 0);
2077 /* Aside from them, only true vectors, char-tables, compiled
2078 functions, and fonts (font-spec, font-entity, font-object)
2079 are sensible to compare, so eliminate the others now. */
2080 if (size & PSEUDOVECTOR_FLAG)
2082 if (((size & PVEC_TYPE_MASK) >> PSEUDOVECTOR_AREA_BITS)
2083 < PVEC_COMPILED)
2084 return 0;
2085 size &= PSEUDOVECTOR_SIZE_MASK;
2087 for (i = 0; i < size; i++)
2089 Lisp_Object v1, v2;
2090 v1 = AREF (o1, i);
2091 v2 = AREF (o2, i);
2092 if (!internal_equal (v1, v2, depth + 1, props))
2093 return 0;
2095 return 1;
2097 break;
2099 case Lisp_String:
2100 if (SCHARS (o1) != SCHARS (o2))
2101 return 0;
2102 if (SBYTES (o1) != SBYTES (o2))
2103 return 0;
2104 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2105 return 0;
2106 if (props && !compare_string_intervals (o1, o2))
2107 return 0;
2108 return 1;
2110 default:
2111 break;
2114 return 0;
2118 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2119 doc: /* Store each element of ARRAY with ITEM.
2120 ARRAY is a vector, string, char-table, or bool-vector. */)
2121 (Lisp_Object array, Lisp_Object item)
2123 register ptrdiff_t size, idx;
2125 if (VECTORP (array))
2126 for (idx = 0, size = ASIZE (array); idx < size; idx++)
2127 ASET (array, idx, item);
2128 else if (CHAR_TABLE_P (array))
2130 int i;
2132 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2133 set_char_table_contents (array, i, item);
2134 set_char_table_defalt (array, item);
2136 else if (STRINGP (array))
2138 register unsigned char *p = SDATA (array);
2139 int charval;
2140 CHECK_CHARACTER (item);
2141 charval = XFASTINT (item);
2142 size = SCHARS (array);
2143 if (STRING_MULTIBYTE (array))
2145 unsigned char str[MAX_MULTIBYTE_LENGTH];
2146 int len = CHAR_STRING (charval, str);
2147 ptrdiff_t size_byte = SBYTES (array);
2149 if (INT_MULTIPLY_OVERFLOW (SCHARS (array), len)
2150 || SCHARS (array) * len != size_byte)
2151 error ("Attempt to change byte length of a string");
2152 for (idx = 0; idx < size_byte; idx++)
2153 *p++ = str[idx % len];
2155 else
2156 for (idx = 0; idx < size; idx++)
2157 p[idx] = charval;
2159 else if (BOOL_VECTOR_P (array))
2160 bool_vector_fill (array, item);
2161 else
2162 wrong_type_argument (Qarrayp, array);
2163 return array;
2166 DEFUN ("clear-string", Fclear_string, Sclear_string,
2167 1, 1, 0,
2168 doc: /* Clear the contents of STRING.
2169 This makes STRING unibyte and may change its length. */)
2170 (Lisp_Object string)
2172 ptrdiff_t len;
2173 CHECK_STRING (string);
2174 len = SBYTES (string);
2175 memset (SDATA (string), 0, len);
2176 STRING_SET_CHARS (string, len);
2177 STRING_SET_UNIBYTE (string);
2178 return Qnil;
2181 /* ARGSUSED */
2182 Lisp_Object
2183 nconc2 (Lisp_Object s1, Lisp_Object s2)
2185 Lisp_Object args[2];
2186 args[0] = s1;
2187 args[1] = s2;
2188 return Fnconc (2, args);
2191 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2192 doc: /* Concatenate any number of lists by altering them.
2193 Only the last argument is not altered, and need not be a list.
2194 usage: (nconc &rest LISTS) */)
2195 (ptrdiff_t nargs, Lisp_Object *args)
2197 ptrdiff_t argnum;
2198 register Lisp_Object tail, tem, val;
2200 val = tail = Qnil;
2202 for (argnum = 0; argnum < nargs; argnum++)
2204 tem = args[argnum];
2205 if (NILP (tem)) continue;
2207 if (NILP (val))
2208 val = tem;
2210 if (argnum + 1 == nargs) break;
2212 CHECK_LIST_CONS (tem, tem);
2214 while (CONSP (tem))
2216 tail = tem;
2217 tem = XCDR (tail);
2218 QUIT;
2221 tem = args[argnum + 1];
2222 Fsetcdr (tail, tem);
2223 if (NILP (tem))
2224 args[argnum + 1] = tail;
2227 return val;
2230 /* This is the guts of all mapping functions.
2231 Apply FN to each element of SEQ, one by one,
2232 storing the results into elements of VALS, a C vector of Lisp_Objects.
2233 LENI is the length of VALS, which should also be the length of SEQ. */
2235 static void
2236 mapcar1 (EMACS_INT leni, Lisp_Object *vals, Lisp_Object fn, Lisp_Object seq)
2238 register Lisp_Object tail;
2239 Lisp_Object dummy;
2240 register EMACS_INT i;
2241 struct gcpro gcpro1, gcpro2, gcpro3;
2243 if (vals)
2245 /* Don't let vals contain any garbage when GC happens. */
2246 for (i = 0; i < leni; i++)
2247 vals[i] = Qnil;
2249 GCPRO3 (dummy, fn, seq);
2250 gcpro1.var = vals;
2251 gcpro1.nvars = leni;
2253 else
2254 GCPRO2 (fn, seq);
2255 /* We need not explicitly protect `tail' because it is used only on lists, and
2256 1) lists are not relocated and 2) the list is marked via `seq' so will not
2257 be freed */
2259 if (VECTORP (seq) || COMPILEDP (seq))
2261 for (i = 0; i < leni; i++)
2263 dummy = call1 (fn, AREF (seq, i));
2264 if (vals)
2265 vals[i] = dummy;
2268 else if (BOOL_VECTOR_P (seq))
2270 for (i = 0; i < leni; i++)
2272 dummy = call1 (fn, bool_vector_ref (seq, i));
2273 if (vals)
2274 vals[i] = dummy;
2277 else if (STRINGP (seq))
2279 ptrdiff_t i_byte;
2281 for (i = 0, i_byte = 0; i < leni;)
2283 int c;
2284 ptrdiff_t i_before = i;
2286 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2287 XSETFASTINT (dummy, c);
2288 dummy = call1 (fn, dummy);
2289 if (vals)
2290 vals[i_before] = dummy;
2293 else /* Must be a list, since Flength did not get an error */
2295 tail = seq;
2296 for (i = 0; i < leni && CONSP (tail); i++)
2298 dummy = call1 (fn, XCAR (tail));
2299 if (vals)
2300 vals[i] = dummy;
2301 tail = XCDR (tail);
2305 UNGCPRO;
2308 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2309 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2310 In between each pair of results, stick in SEPARATOR. Thus, " " as
2311 SEPARATOR results in spaces between the values returned by FUNCTION.
2312 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2313 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2315 Lisp_Object len;
2316 register EMACS_INT leni;
2317 EMACS_INT nargs;
2318 ptrdiff_t i;
2319 register Lisp_Object *args;
2320 struct gcpro gcpro1;
2321 Lisp_Object ret;
2322 USE_SAFE_ALLOCA;
2324 len = Flength (sequence);
2325 if (CHAR_TABLE_P (sequence))
2326 wrong_type_argument (Qlistp, sequence);
2327 leni = XINT (len);
2328 nargs = leni + leni - 1;
2329 if (nargs < 0) return empty_unibyte_string;
2331 SAFE_ALLOCA_LISP (args, nargs);
2333 GCPRO1 (separator);
2334 mapcar1 (leni, args, function, sequence);
2335 UNGCPRO;
2337 for (i = leni - 1; i > 0; i--)
2338 args[i + i] = args[i];
2340 for (i = 1; i < nargs; i += 2)
2341 args[i] = separator;
2343 ret = Fconcat (nargs, args);
2344 SAFE_FREE ();
2346 return ret;
2349 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2350 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2351 The result is a list just as long as SEQUENCE.
2352 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2353 (Lisp_Object function, Lisp_Object sequence)
2355 register Lisp_Object len;
2356 register EMACS_INT leni;
2357 register Lisp_Object *args;
2358 Lisp_Object ret;
2359 USE_SAFE_ALLOCA;
2361 len = Flength (sequence);
2362 if (CHAR_TABLE_P (sequence))
2363 wrong_type_argument (Qlistp, sequence);
2364 leni = XFASTINT (len);
2366 SAFE_ALLOCA_LISP (args, leni);
2368 mapcar1 (leni, args, function, sequence);
2370 ret = Flist (leni, args);
2371 SAFE_FREE ();
2373 return ret;
2376 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2377 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2378 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2379 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2380 (Lisp_Object function, Lisp_Object sequence)
2382 register EMACS_INT leni;
2384 leni = XFASTINT (Flength (sequence));
2385 if (CHAR_TABLE_P (sequence))
2386 wrong_type_argument (Qlistp, sequence);
2387 mapcar1 (leni, 0, function, sequence);
2389 return sequence;
2392 /* This is how C code calls `yes-or-no-p' and allows the user
2393 to redefined it.
2395 Anything that calls this function must protect from GC! */
2397 Lisp_Object
2398 do_yes_or_no_p (Lisp_Object prompt)
2400 return call1 (intern ("yes-or-no-p"), prompt);
2403 /* Anything that calls this function must protect from GC! */
2405 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2406 doc: /* Ask user a yes-or-no question. Return t if answer is yes.
2407 PROMPT is the string to display to ask the question. It should end in
2408 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2410 The user must confirm the answer with RET, and can edit it until it
2411 has been confirmed.
2413 If dialog boxes are supported, a dialog box will be used
2414 if `last-nonmenu-event' is nil, and `use-dialog-box' is non-nil. */)
2415 (Lisp_Object prompt)
2417 register Lisp_Object ans;
2418 Lisp_Object args[2];
2419 struct gcpro gcpro1;
2421 CHECK_STRING (prompt);
2423 #ifdef HAVE_MENUS
2424 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2425 && use_dialog_box)
2427 Lisp_Object pane, menu, obj;
2428 redisplay_preserve_echo_area (4);
2429 pane = list2 (Fcons (build_string ("Yes"), Qt),
2430 Fcons (build_string ("No"), Qnil));
2431 GCPRO1 (pane);
2432 menu = Fcons (prompt, pane);
2433 obj = Fx_popup_dialog (Qt, menu, Qnil);
2434 UNGCPRO;
2435 return obj;
2437 #endif /* HAVE_MENUS */
2439 args[0] = prompt;
2440 args[1] = build_string ("(yes or no) ");
2441 prompt = Fconcat (2, args);
2443 GCPRO1 (prompt);
2445 while (1)
2447 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2448 Qyes_or_no_p_history, Qnil,
2449 Qnil));
2450 if (SCHARS (ans) == 3 && !strcmp (SSDATA (ans), "yes"))
2452 UNGCPRO;
2453 return Qt;
2455 if (SCHARS (ans) == 2 && !strcmp (SSDATA (ans), "no"))
2457 UNGCPRO;
2458 return Qnil;
2461 Fding (Qnil);
2462 Fdiscard_input ();
2463 message1 ("Please answer yes or no.");
2464 Fsleep_for (make_number (2), Qnil);
2468 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2469 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2471 Each of the three load averages is multiplied by 100, then converted
2472 to integer.
2474 When USE-FLOATS is non-nil, floats will be used instead of integers.
2475 These floats are not multiplied by 100.
2477 If the 5-minute or 15-minute load averages are not available, return a
2478 shortened list, containing only those averages which are available.
2480 An error is thrown if the load average can't be obtained. In some
2481 cases making it work would require Emacs being installed setuid or
2482 setgid so that it can read kernel information, and that usually isn't
2483 advisable. */)
2484 (Lisp_Object use_floats)
2486 double load_ave[3];
2487 int loads = getloadavg (load_ave, 3);
2488 Lisp_Object ret = Qnil;
2490 if (loads < 0)
2491 error ("load-average not implemented for this operating system");
2493 while (loads-- > 0)
2495 Lisp_Object load = (NILP (use_floats)
2496 ? make_number (100.0 * load_ave[loads])
2497 : make_float (load_ave[loads]));
2498 ret = Fcons (load, ret);
2501 return ret;
2504 static Lisp_Object Qsubfeatures;
2506 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2507 doc: /* Return t if FEATURE is present in this Emacs.
2509 Use this to conditionalize execution of lisp code based on the
2510 presence or absence of Emacs or environment extensions.
2511 Use `provide' to declare that a feature is available. This function
2512 looks at the value of the variable `features'. The optional argument
2513 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2514 (Lisp_Object feature, Lisp_Object subfeature)
2516 register Lisp_Object tem;
2517 CHECK_SYMBOL (feature);
2518 tem = Fmemq (feature, Vfeatures);
2519 if (!NILP (tem) && !NILP (subfeature))
2520 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2521 return (NILP (tem)) ? Qnil : Qt;
2524 static Lisp_Object Qfuncall;
2526 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2527 doc: /* Announce that FEATURE is a feature of the current Emacs.
2528 The optional argument SUBFEATURES should be a list of symbols listing
2529 particular subfeatures supported in this version of FEATURE. */)
2530 (Lisp_Object feature, Lisp_Object subfeatures)
2532 register Lisp_Object tem;
2533 CHECK_SYMBOL (feature);
2534 CHECK_LIST (subfeatures);
2535 if (!NILP (Vautoload_queue))
2536 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2537 Vautoload_queue);
2538 tem = Fmemq (feature, Vfeatures);
2539 if (NILP (tem))
2540 Vfeatures = Fcons (feature, Vfeatures);
2541 if (!NILP (subfeatures))
2542 Fput (feature, Qsubfeatures, subfeatures);
2543 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2545 /* Run any load-hooks for this file. */
2546 tem = Fassq (feature, Vafter_load_alist);
2547 if (CONSP (tem))
2548 Fmapc (Qfuncall, XCDR (tem));
2550 return feature;
2553 /* `require' and its subroutines. */
2555 /* List of features currently being require'd, innermost first. */
2557 static Lisp_Object require_nesting_list;
2559 static void
2560 require_unwind (Lisp_Object old_value)
2562 require_nesting_list = old_value;
2565 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2566 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2567 If FEATURE is not a member of the list `features', then the feature
2568 is not loaded; so load the file FILENAME.
2569 If FILENAME is omitted, the printname of FEATURE is used as the file name,
2570 and `load' will try to load this name appended with the suffix `.elc' or
2571 `.el', in that order. The name without appended suffix will not be used.
2572 See `get-load-suffixes' for the complete list of suffixes.
2573 If the optional third argument NOERROR is non-nil,
2574 then return nil if the file is not found instead of signaling an error.
2575 Normally the return value is FEATURE.
2576 The normal messages at start and end of loading FILENAME are suppressed. */)
2577 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2579 Lisp_Object tem;
2580 struct gcpro gcpro1, gcpro2;
2581 bool from_file = load_in_progress;
2583 CHECK_SYMBOL (feature);
2585 /* Record the presence of `require' in this file
2586 even if the feature specified is already loaded.
2587 But not more than once in any file,
2588 and not when we aren't loading or reading from a file. */
2589 if (!from_file)
2590 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2591 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2592 from_file = 1;
2594 if (from_file)
2596 tem = Fcons (Qrequire, feature);
2597 if (NILP (Fmember (tem, Vcurrent_load_list)))
2598 LOADHIST_ATTACH (tem);
2600 tem = Fmemq (feature, Vfeatures);
2602 if (NILP (tem))
2604 ptrdiff_t count = SPECPDL_INDEX ();
2605 int nesting = 0;
2607 /* This is to make sure that loadup.el gives a clear picture
2608 of what files are preloaded and when. */
2609 if (! NILP (Vpurify_flag))
2610 error ("(require %s) while preparing to dump",
2611 SDATA (SYMBOL_NAME (feature)));
2613 /* A certain amount of recursive `require' is legitimate,
2614 but if we require the same feature recursively 3 times,
2615 signal an error. */
2616 tem = require_nesting_list;
2617 while (! NILP (tem))
2619 if (! NILP (Fequal (feature, XCAR (tem))))
2620 nesting++;
2621 tem = XCDR (tem);
2623 if (nesting > 3)
2624 error ("Recursive `require' for feature `%s'",
2625 SDATA (SYMBOL_NAME (feature)));
2627 /* Update the list for any nested `require's that occur. */
2628 record_unwind_protect (require_unwind, require_nesting_list);
2629 require_nesting_list = Fcons (feature, require_nesting_list);
2631 /* Value saved here is to be restored into Vautoload_queue */
2632 record_unwind_protect (un_autoload, Vautoload_queue);
2633 Vautoload_queue = Qt;
2635 /* Load the file. */
2636 GCPRO2 (feature, filename);
2637 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2638 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2639 UNGCPRO;
2641 /* If load failed entirely, return nil. */
2642 if (NILP (tem))
2643 return unbind_to (count, Qnil);
2645 tem = Fmemq (feature, Vfeatures);
2646 if (NILP (tem))
2647 error ("Required feature `%s' was not provided",
2648 SDATA (SYMBOL_NAME (feature)));
2650 /* Once loading finishes, don't undo it. */
2651 Vautoload_queue = Qt;
2652 feature = unbind_to (count, feature);
2655 return feature;
2658 /* Primitives for work of the "widget" library.
2659 In an ideal world, this section would not have been necessary.
2660 However, lisp function calls being as slow as they are, it turns
2661 out that some functions in the widget library (wid-edit.el) are the
2662 bottleneck of Widget operation. Here is their translation to C,
2663 for the sole reason of efficiency. */
2665 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2666 doc: /* Return non-nil if PLIST has the property PROP.
2667 PLIST is a property list, which is a list of the form
2668 \(PROP1 VALUE1 PROP2 VALUE2 ...\). PROP is a symbol.
2669 Unlike `plist-get', this allows you to distinguish between a missing
2670 property and a property with the value nil.
2671 The value is actually the tail of PLIST whose car is PROP. */)
2672 (Lisp_Object plist, Lisp_Object prop)
2674 while (CONSP (plist) && !EQ (XCAR (plist), prop))
2676 QUIT;
2677 plist = XCDR (plist);
2678 plist = CDR (plist);
2680 return plist;
2683 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2684 doc: /* In WIDGET, set PROPERTY to VALUE.
2685 The value can later be retrieved with `widget-get'. */)
2686 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2688 CHECK_CONS (widget);
2689 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
2690 return value;
2693 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
2694 doc: /* In WIDGET, get the value of PROPERTY.
2695 The value could either be specified when the widget was created, or
2696 later with `widget-put'. */)
2697 (Lisp_Object widget, Lisp_Object property)
2699 Lisp_Object tmp;
2701 while (1)
2703 if (NILP (widget))
2704 return Qnil;
2705 CHECK_CONS (widget);
2706 tmp = Fplist_member (XCDR (widget), property);
2707 if (CONSP (tmp))
2709 tmp = XCDR (tmp);
2710 return CAR (tmp);
2712 tmp = XCAR (widget);
2713 if (NILP (tmp))
2714 return Qnil;
2715 widget = Fget (tmp, Qwidget_type);
2719 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
2720 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2721 ARGS are passed as extra arguments to the function.
2722 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2723 (ptrdiff_t nargs, Lisp_Object *args)
2725 /* This function can GC. */
2726 Lisp_Object newargs[3];
2727 struct gcpro gcpro1, gcpro2;
2728 Lisp_Object result;
2730 newargs[0] = Fwidget_get (args[0], args[1]);
2731 newargs[1] = args[0];
2732 newargs[2] = Flist (nargs - 2, args + 2);
2733 GCPRO2 (newargs[0], newargs[2]);
2734 result = Fapply (3, newargs);
2735 UNGCPRO;
2736 return result;
2739 #ifdef HAVE_LANGINFO_CODESET
2740 #include <langinfo.h>
2741 #endif
2743 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
2744 doc: /* Access locale data ITEM for the current C locale, if available.
2745 ITEM should be one of the following:
2747 `codeset', returning the character set as a string (locale item CODESET);
2749 `days', returning a 7-element vector of day names (locale items DAY_n);
2751 `months', returning a 12-element vector of month names (locale items MON_n);
2753 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
2754 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
2756 If the system can't provide such information through a call to
2757 `nl_langinfo', or if ITEM isn't from the list above, return nil.
2759 See also Info node `(libc)Locales'.
2761 The data read from the system are decoded using `locale-coding-system'. */)
2762 (Lisp_Object item)
2764 char *str = NULL;
2765 #ifdef HAVE_LANGINFO_CODESET
2766 Lisp_Object val;
2767 if (EQ (item, Qcodeset))
2769 str = nl_langinfo (CODESET);
2770 return build_string (str);
2772 #ifdef DAY_1
2773 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
2775 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
2776 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
2777 int i;
2778 struct gcpro gcpro1;
2779 GCPRO1 (v);
2780 synchronize_system_time_locale ();
2781 for (i = 0; i < 7; i++)
2783 str = nl_langinfo (days[i]);
2784 val = build_unibyte_string (str);
2785 /* Fixme: Is this coding system necessarily right, even if
2786 it is consistent with CODESET? If not, what to do? */
2787 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
2788 0));
2790 UNGCPRO;
2791 return v;
2793 #endif /* DAY_1 */
2794 #ifdef MON_1
2795 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
2797 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
2798 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
2799 MON_8, MON_9, MON_10, MON_11, MON_12};
2800 int i;
2801 struct gcpro gcpro1;
2802 GCPRO1 (v);
2803 synchronize_system_time_locale ();
2804 for (i = 0; i < 12; i++)
2806 str = nl_langinfo (months[i]);
2807 val = build_unibyte_string (str);
2808 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
2809 0));
2811 UNGCPRO;
2812 return v;
2814 #endif /* MON_1 */
2815 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
2816 but is in the locale files. This could be used by ps-print. */
2817 #ifdef PAPER_WIDTH
2818 else if (EQ (item, Qpaper))
2819 return list2i (nl_langinfo (PAPER_WIDTH), nl_langinfo (PAPER_HEIGHT));
2820 #endif /* PAPER_WIDTH */
2821 #endif /* HAVE_LANGINFO_CODESET*/
2822 return Qnil;
2825 /* base64 encode/decode functions (RFC 2045).
2826 Based on code from GNU recode. */
2828 #define MIME_LINE_LENGTH 76
2830 #define IS_ASCII(Character) \
2831 ((Character) < 128)
2832 #define IS_BASE64(Character) \
2833 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
2834 #define IS_BASE64_IGNORABLE(Character) \
2835 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
2836 || (Character) == '\f' || (Character) == '\r')
2838 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
2839 character or return retval if there are no characters left to
2840 process. */
2841 #define READ_QUADRUPLET_BYTE(retval) \
2842 do \
2844 if (i == length) \
2846 if (nchars_return) \
2847 *nchars_return = nchars; \
2848 return (retval); \
2850 c = from[i++]; \
2852 while (IS_BASE64_IGNORABLE (c))
2854 /* Table of characters coding the 64 values. */
2855 static const char base64_value_to_char[64] =
2857 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
2858 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
2859 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
2860 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
2861 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
2862 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
2863 '8', '9', '+', '/' /* 60-63 */
2866 /* Table of base64 values for first 128 characters. */
2867 static const short base64_char_to_value[128] =
2869 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
2870 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
2871 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
2872 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
2873 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
2874 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
2875 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
2876 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
2877 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
2878 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
2879 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
2880 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
2881 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
2884 /* The following diagram shows the logical steps by which three octets
2885 get transformed into four base64 characters.
2887 .--------. .--------. .--------.
2888 |aaaaaabb| |bbbbcccc| |ccdddddd|
2889 `--------' `--------' `--------'
2890 6 2 4 4 2 6
2891 .--------+--------+--------+--------.
2892 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
2893 `--------+--------+--------+--------'
2895 .--------+--------+--------+--------.
2896 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
2897 `--------+--------+--------+--------'
2899 The octets are divided into 6 bit chunks, which are then encoded into
2900 base64 characters. */
2903 static ptrdiff_t base64_encode_1 (const char *, char *, ptrdiff_t, bool, bool);
2904 static ptrdiff_t base64_decode_1 (const char *, char *, ptrdiff_t, bool,
2905 ptrdiff_t *);
2907 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
2908 2, 3, "r",
2909 doc: /* Base64-encode the region between BEG and END.
2910 Return the length of the encoded text.
2911 Optional third argument NO-LINE-BREAK means do not break long lines
2912 into shorter lines. */)
2913 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
2915 char *encoded;
2916 ptrdiff_t allength, length;
2917 ptrdiff_t ibeg, iend, encoded_length;
2918 ptrdiff_t old_pos = PT;
2919 USE_SAFE_ALLOCA;
2921 validate_region (&beg, &end);
2923 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
2924 iend = CHAR_TO_BYTE (XFASTINT (end));
2925 move_gap_both (XFASTINT (beg), ibeg);
2927 /* We need to allocate enough room for encoding the text.
2928 We need 33 1/3% more space, plus a newline every 76
2929 characters, and then we round up. */
2930 length = iend - ibeg;
2931 allength = length + length/3 + 1;
2932 allength += allength / MIME_LINE_LENGTH + 1 + 6;
2934 encoded = SAFE_ALLOCA (allength);
2935 encoded_length = base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg),
2936 encoded, length, NILP (no_line_break),
2937 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
2938 if (encoded_length > allength)
2939 emacs_abort ();
2941 if (encoded_length < 0)
2943 /* The encoding wasn't possible. */
2944 SAFE_FREE ();
2945 error ("Multibyte character in data for base64 encoding");
2948 /* Now we have encoded the region, so we insert the new contents
2949 and delete the old. (Insert first in order to preserve markers.) */
2950 SET_PT_BOTH (XFASTINT (beg), ibeg);
2951 insert (encoded, encoded_length);
2952 SAFE_FREE ();
2953 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
2955 /* If point was outside of the region, restore it exactly; else just
2956 move to the beginning of the region. */
2957 if (old_pos >= XFASTINT (end))
2958 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
2959 else if (old_pos > XFASTINT (beg))
2960 old_pos = XFASTINT (beg);
2961 SET_PT (old_pos);
2963 /* We return the length of the encoded text. */
2964 return make_number (encoded_length);
2967 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
2968 1, 2, 0,
2969 doc: /* Base64-encode STRING and return the result.
2970 Optional second argument NO-LINE-BREAK means do not break long lines
2971 into shorter lines. */)
2972 (Lisp_Object string, Lisp_Object no_line_break)
2974 ptrdiff_t allength, length, encoded_length;
2975 char *encoded;
2976 Lisp_Object encoded_string;
2977 USE_SAFE_ALLOCA;
2979 CHECK_STRING (string);
2981 /* We need to allocate enough room for encoding the text.
2982 We need 33 1/3% more space, plus a newline every 76
2983 characters, and then we round up. */
2984 length = SBYTES (string);
2985 allength = length + length/3 + 1;
2986 allength += allength / MIME_LINE_LENGTH + 1 + 6;
2988 /* We need to allocate enough room for decoding the text. */
2989 encoded = SAFE_ALLOCA (allength);
2991 encoded_length = base64_encode_1 (SSDATA (string),
2992 encoded, length, NILP (no_line_break),
2993 STRING_MULTIBYTE (string));
2994 if (encoded_length > allength)
2995 emacs_abort ();
2997 if (encoded_length < 0)
2999 /* The encoding wasn't possible. */
3000 SAFE_FREE ();
3001 error ("Multibyte character in data for base64 encoding");
3004 encoded_string = make_unibyte_string (encoded, encoded_length);
3005 SAFE_FREE ();
3007 return encoded_string;
3010 static ptrdiff_t
3011 base64_encode_1 (const char *from, char *to, ptrdiff_t length,
3012 bool line_break, bool multibyte)
3014 int counter = 0;
3015 ptrdiff_t i = 0;
3016 char *e = to;
3017 int c;
3018 unsigned int value;
3019 int bytes;
3021 while (i < length)
3023 if (multibyte)
3025 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3026 if (CHAR_BYTE8_P (c))
3027 c = CHAR_TO_BYTE8 (c);
3028 else if (c >= 256)
3029 return -1;
3030 i += bytes;
3032 else
3033 c = from[i++];
3035 /* Wrap line every 76 characters. */
3037 if (line_break)
3039 if (counter < MIME_LINE_LENGTH / 4)
3040 counter++;
3041 else
3043 *e++ = '\n';
3044 counter = 1;
3048 /* Process first byte of a triplet. */
3050 *e++ = base64_value_to_char[0x3f & c >> 2];
3051 value = (0x03 & c) << 4;
3053 /* Process second byte of a triplet. */
3055 if (i == length)
3057 *e++ = base64_value_to_char[value];
3058 *e++ = '=';
3059 *e++ = '=';
3060 break;
3063 if (multibyte)
3065 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3066 if (CHAR_BYTE8_P (c))
3067 c = CHAR_TO_BYTE8 (c);
3068 else if (c >= 256)
3069 return -1;
3070 i += bytes;
3072 else
3073 c = from[i++];
3075 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3076 value = (0x0f & c) << 2;
3078 /* Process third byte of a triplet. */
3080 if (i == length)
3082 *e++ = base64_value_to_char[value];
3083 *e++ = '=';
3084 break;
3087 if (multibyte)
3089 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3090 if (CHAR_BYTE8_P (c))
3091 c = CHAR_TO_BYTE8 (c);
3092 else if (c >= 256)
3093 return -1;
3094 i += bytes;
3096 else
3097 c = from[i++];
3099 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3100 *e++ = base64_value_to_char[0x3f & c];
3103 return e - to;
3107 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3108 2, 2, "r",
3109 doc: /* Base64-decode the region between BEG and END.
3110 Return the length of the decoded text.
3111 If the region can't be decoded, signal an error and don't modify the buffer. */)
3112 (Lisp_Object beg, Lisp_Object end)
3114 ptrdiff_t ibeg, iend, length, allength;
3115 char *decoded;
3116 ptrdiff_t old_pos = PT;
3117 ptrdiff_t decoded_length;
3118 ptrdiff_t inserted_chars;
3119 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3120 USE_SAFE_ALLOCA;
3122 validate_region (&beg, &end);
3124 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3125 iend = CHAR_TO_BYTE (XFASTINT (end));
3127 length = iend - ibeg;
3129 /* We need to allocate enough room for decoding the text. If we are
3130 working on a multibyte buffer, each decoded code may occupy at
3131 most two bytes. */
3132 allength = multibyte ? length * 2 : length;
3133 decoded = SAFE_ALLOCA (allength);
3135 move_gap_both (XFASTINT (beg), ibeg);
3136 decoded_length = base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg),
3137 decoded, length,
3138 multibyte, &inserted_chars);
3139 if (decoded_length > allength)
3140 emacs_abort ();
3142 if (decoded_length < 0)
3144 /* The decoding wasn't possible. */
3145 SAFE_FREE ();
3146 error ("Invalid base64 data");
3149 /* Now we have decoded the region, so we insert the new contents
3150 and delete the old. (Insert first in order to preserve markers.) */
3151 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3152 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3153 SAFE_FREE ();
3155 /* Delete the original text. */
3156 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3157 iend + decoded_length, 1);
3159 /* If point was outside of the region, restore it exactly; else just
3160 move to the beginning of the region. */
3161 if (old_pos >= XFASTINT (end))
3162 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3163 else if (old_pos > XFASTINT (beg))
3164 old_pos = XFASTINT (beg);
3165 SET_PT (old_pos > ZV ? ZV : old_pos);
3167 return make_number (inserted_chars);
3170 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3171 1, 1, 0,
3172 doc: /* Base64-decode STRING and return the result. */)
3173 (Lisp_Object string)
3175 char *decoded;
3176 ptrdiff_t length, decoded_length;
3177 Lisp_Object decoded_string;
3178 USE_SAFE_ALLOCA;
3180 CHECK_STRING (string);
3182 length = SBYTES (string);
3183 /* We need to allocate enough room for decoding the text. */
3184 decoded = SAFE_ALLOCA (length);
3186 /* The decoded result should be unibyte. */
3187 decoded_length = base64_decode_1 (SSDATA (string), decoded, length,
3188 0, NULL);
3189 if (decoded_length > length)
3190 emacs_abort ();
3191 else if (decoded_length >= 0)
3192 decoded_string = make_unibyte_string (decoded, decoded_length);
3193 else
3194 decoded_string = Qnil;
3196 SAFE_FREE ();
3197 if (!STRINGP (decoded_string))
3198 error ("Invalid base64 data");
3200 return decoded_string;
3203 /* Base64-decode the data at FROM of LENGTH bytes into TO. If
3204 MULTIBYTE, the decoded result should be in multibyte
3205 form. If NCHARS_RETURN is not NULL, store the number of produced
3206 characters in *NCHARS_RETURN. */
3208 static ptrdiff_t
3209 base64_decode_1 (const char *from, char *to, ptrdiff_t length,
3210 bool multibyte, ptrdiff_t *nchars_return)
3212 ptrdiff_t i = 0; /* Used inside READ_QUADRUPLET_BYTE */
3213 char *e = to;
3214 unsigned char c;
3215 unsigned long value;
3216 ptrdiff_t nchars = 0;
3218 while (1)
3220 /* Process first byte of a quadruplet. */
3222 READ_QUADRUPLET_BYTE (e-to);
3224 if (!IS_BASE64 (c))
3225 return -1;
3226 value = base64_char_to_value[c] << 18;
3228 /* Process second byte of a quadruplet. */
3230 READ_QUADRUPLET_BYTE (-1);
3232 if (!IS_BASE64 (c))
3233 return -1;
3234 value |= base64_char_to_value[c] << 12;
3236 c = (unsigned char) (value >> 16);
3237 if (multibyte && c >= 128)
3238 e += BYTE8_STRING (c, e);
3239 else
3240 *e++ = c;
3241 nchars++;
3243 /* Process third byte of a quadruplet. */
3245 READ_QUADRUPLET_BYTE (-1);
3247 if (c == '=')
3249 READ_QUADRUPLET_BYTE (-1);
3251 if (c != '=')
3252 return -1;
3253 continue;
3256 if (!IS_BASE64 (c))
3257 return -1;
3258 value |= base64_char_to_value[c] << 6;
3260 c = (unsigned char) (0xff & value >> 8);
3261 if (multibyte && c >= 128)
3262 e += BYTE8_STRING (c, e);
3263 else
3264 *e++ = c;
3265 nchars++;
3267 /* Process fourth byte of a quadruplet. */
3269 READ_QUADRUPLET_BYTE (-1);
3271 if (c == '=')
3272 continue;
3274 if (!IS_BASE64 (c))
3275 return -1;
3276 value |= base64_char_to_value[c];
3278 c = (unsigned char) (0xff & value);
3279 if (multibyte && c >= 128)
3280 e += BYTE8_STRING (c, e);
3281 else
3282 *e++ = c;
3283 nchars++;
3289 /***********************************************************************
3290 ***** *****
3291 ***** Hash Tables *****
3292 ***** *****
3293 ***********************************************************************/
3295 /* Implemented by gerd@gnu.org. This hash table implementation was
3296 inspired by CMUCL hash tables. */
3298 /* Ideas:
3300 1. For small tables, association lists are probably faster than
3301 hash tables because they have lower overhead.
3303 For uses of hash tables where the O(1) behavior of table
3304 operations is not a requirement, it might therefore be a good idea
3305 not to hash. Instead, we could just do a linear search in the
3306 key_and_value vector of the hash table. This could be done
3307 if a `:linear-search t' argument is given to make-hash-table. */
3310 /* The list of all weak hash tables. Don't staticpro this one. */
3312 static struct Lisp_Hash_Table *weak_hash_tables;
3314 /* Various symbols. */
3316 static Lisp_Object Qhash_table_p;
3317 static Lisp_Object Qkey, Qvalue, Qeql;
3318 Lisp_Object Qeq, Qequal;
3319 Lisp_Object QCtest, QCsize, QCrehash_size, QCrehash_threshold, QCweakness;
3320 static Lisp_Object Qhash_table_test, Qkey_or_value, Qkey_and_value;
3323 /***********************************************************************
3324 Utilities
3325 ***********************************************************************/
3327 static void
3328 CHECK_HASH_TABLE (Lisp_Object x)
3330 CHECK_TYPE (HASH_TABLE_P (x), Qhash_table_p, x);
3333 static void
3334 set_hash_key_and_value (struct Lisp_Hash_Table *h, Lisp_Object key_and_value)
3336 h->key_and_value = key_and_value;
3338 static void
3339 set_hash_next (struct Lisp_Hash_Table *h, Lisp_Object next)
3341 h->next = next;
3343 static void
3344 set_hash_next_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3346 gc_aset (h->next, idx, val);
3348 static void
3349 set_hash_hash (struct Lisp_Hash_Table *h, Lisp_Object hash)
3351 h->hash = hash;
3353 static void
3354 set_hash_hash_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3356 gc_aset (h->hash, idx, val);
3358 static void
3359 set_hash_index (struct Lisp_Hash_Table *h, Lisp_Object index)
3361 h->index = index;
3363 static void
3364 set_hash_index_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3366 gc_aset (h->index, idx, val);
3369 /* If OBJ is a Lisp hash table, return a pointer to its struct
3370 Lisp_Hash_Table. Otherwise, signal an error. */
3372 static struct Lisp_Hash_Table *
3373 check_hash_table (Lisp_Object obj)
3375 CHECK_HASH_TABLE (obj);
3376 return XHASH_TABLE (obj);
3380 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3381 number. A number is "almost" a prime number if it is not divisible
3382 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3384 EMACS_INT
3385 next_almost_prime (EMACS_INT n)
3387 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
3388 for (n |= 1; ; n += 2)
3389 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0)
3390 return n;
3394 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3395 which USED[I] is non-zero. If found at index I in ARGS, set
3396 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3397 0. This function is used to extract a keyword/argument pair from
3398 a DEFUN parameter list. */
3400 static ptrdiff_t
3401 get_key_arg (Lisp_Object key, ptrdiff_t nargs, Lisp_Object *args, char *used)
3403 ptrdiff_t i;
3405 for (i = 1; i < nargs; i++)
3406 if (!used[i - 1] && EQ (args[i - 1], key))
3408 used[i - 1] = 1;
3409 used[i] = 1;
3410 return i;
3413 return 0;
3417 /* Return a Lisp vector which has the same contents as VEC but has
3418 at least INCR_MIN more entries, where INCR_MIN is positive.
3419 If NITEMS_MAX is not -1, do not grow the vector to be any larger
3420 than NITEMS_MAX. Entries in the resulting
3421 vector that are not copied from VEC are set to nil. */
3423 Lisp_Object
3424 larger_vector (Lisp_Object vec, ptrdiff_t incr_min, ptrdiff_t nitems_max)
3426 struct Lisp_Vector *v;
3427 ptrdiff_t i, incr, incr_max, old_size, new_size;
3428 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / sizeof *v->contents;
3429 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
3430 ? nitems_max : C_language_max);
3431 eassert (VECTORP (vec));
3432 eassert (0 < incr_min && -1 <= nitems_max);
3433 old_size = ASIZE (vec);
3434 incr_max = n_max - old_size;
3435 incr = max (incr_min, min (old_size >> 1, incr_max));
3436 if (incr_max < incr)
3437 memory_full (SIZE_MAX);
3438 new_size = old_size + incr;
3439 v = allocate_vector (new_size);
3440 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3441 for (i = old_size; i < new_size; ++i)
3442 v->contents[i] = Qnil;
3443 XSETVECTOR (vec, v);
3444 return vec;
3448 /***********************************************************************
3449 Low-level Functions
3450 ***********************************************************************/
3452 static struct hash_table_test hashtest_eq;
3453 struct hash_table_test hashtest_eql, hashtest_equal;
3455 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3456 HASH2 in hash table H using `eql'. Value is true if KEY1 and
3457 KEY2 are the same. */
3459 static bool
3460 cmpfn_eql (struct hash_table_test *ht,
3461 Lisp_Object key1,
3462 Lisp_Object key2)
3464 return (FLOATP (key1)
3465 && FLOATP (key2)
3466 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3470 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3471 HASH2 in hash table H using `equal'. Value is true if KEY1 and
3472 KEY2 are the same. */
3474 static bool
3475 cmpfn_equal (struct hash_table_test *ht,
3476 Lisp_Object key1,
3477 Lisp_Object key2)
3479 return !NILP (Fequal (key1, key2));
3483 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3484 HASH2 in hash table H using H->user_cmp_function. Value is true
3485 if KEY1 and KEY2 are the same. */
3487 static bool
3488 cmpfn_user_defined (struct hash_table_test *ht,
3489 Lisp_Object key1,
3490 Lisp_Object key2)
3492 Lisp_Object args[3];
3494 args[0] = ht->user_cmp_function;
3495 args[1] = key1;
3496 args[2] = key2;
3497 return !NILP (Ffuncall (3, args));
3501 /* Value is a hash code for KEY for use in hash table H which uses
3502 `eq' to compare keys. The hash code returned is guaranteed to fit
3503 in a Lisp integer. */
3505 static EMACS_UINT
3506 hashfn_eq (struct hash_table_test *ht, Lisp_Object key)
3508 EMACS_UINT hash = XHASH (key) ^ XTYPE (key);
3509 return hash;
3512 /* Value is a hash code for KEY for use in hash table H which uses
3513 `eql' to compare keys. The hash code returned is guaranteed to fit
3514 in a Lisp integer. */
3516 static EMACS_UINT
3517 hashfn_eql (struct hash_table_test *ht, Lisp_Object key)
3519 EMACS_UINT hash;
3520 if (FLOATP (key))
3521 hash = sxhash (key, 0);
3522 else
3523 hash = XHASH (key) ^ XTYPE (key);
3524 return hash;
3527 /* Value is a hash code for KEY for use in hash table H which uses
3528 `equal' to compare keys. The hash code returned is guaranteed to fit
3529 in a Lisp integer. */
3531 static EMACS_UINT
3532 hashfn_equal (struct hash_table_test *ht, Lisp_Object key)
3534 EMACS_UINT hash = sxhash (key, 0);
3535 return hash;
3538 /* Value is a hash code for KEY for use in hash table H which uses as
3539 user-defined function to compare keys. The hash code returned is
3540 guaranteed to fit in a Lisp integer. */
3542 static EMACS_UINT
3543 hashfn_user_defined (struct hash_table_test *ht, Lisp_Object key)
3545 Lisp_Object args[2], hash;
3547 args[0] = ht->user_hash_function;
3548 args[1] = key;
3549 hash = Ffuncall (2, args);
3550 return hashfn_eq (ht, hash);
3553 /* An upper bound on the size of a hash table index. It must fit in
3554 ptrdiff_t and be a valid Emacs fixnum. */
3555 #define INDEX_SIZE_BOUND \
3556 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, PTRDIFF_MAX / word_size))
3558 /* Create and initialize a new hash table.
3560 TEST specifies the test the hash table will use to compare keys.
3561 It must be either one of the predefined tests `eq', `eql' or
3562 `equal' or a symbol denoting a user-defined test named TEST with
3563 test and hash functions USER_TEST and USER_HASH.
3565 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3567 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3568 new size when it becomes full is computed by adding REHASH_SIZE to
3569 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3570 table's new size is computed by multiplying its old size with
3571 REHASH_SIZE.
3573 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3574 be resized when the ratio of (number of entries in the table) /
3575 (table size) is >= REHASH_THRESHOLD.
3577 WEAK specifies the weakness of the table. If non-nil, it must be
3578 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
3580 Lisp_Object
3581 make_hash_table (struct hash_table_test test,
3582 Lisp_Object size, Lisp_Object rehash_size,
3583 Lisp_Object rehash_threshold, Lisp_Object weak)
3585 struct Lisp_Hash_Table *h;
3586 Lisp_Object table;
3587 EMACS_INT index_size, sz;
3588 ptrdiff_t i;
3589 double index_float;
3591 /* Preconditions. */
3592 eassert (SYMBOLP (test.name));
3593 eassert (INTEGERP (size) && XINT (size) >= 0);
3594 eassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3595 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size)));
3596 eassert (FLOATP (rehash_threshold)
3597 && 0 < XFLOAT_DATA (rehash_threshold)
3598 && XFLOAT_DATA (rehash_threshold) <= 1.0);
3600 if (XFASTINT (size) == 0)
3601 size = make_number (1);
3603 sz = XFASTINT (size);
3604 index_float = sz / XFLOAT_DATA (rehash_threshold);
3605 index_size = (index_float < INDEX_SIZE_BOUND + 1
3606 ? next_almost_prime (index_float)
3607 : INDEX_SIZE_BOUND + 1);
3608 if (INDEX_SIZE_BOUND < max (index_size, 2 * sz))
3609 error ("Hash table too large");
3611 /* Allocate a table and initialize it. */
3612 h = allocate_hash_table ();
3614 /* Initialize hash table slots. */
3615 h->test = test;
3616 h->weak = weak;
3617 h->rehash_threshold = rehash_threshold;
3618 h->rehash_size = rehash_size;
3619 h->count = 0;
3620 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
3621 h->hash = Fmake_vector (size, Qnil);
3622 h->next = Fmake_vector (size, Qnil);
3623 h->index = Fmake_vector (make_number (index_size), Qnil);
3625 /* Set up the free list. */
3626 for (i = 0; i < sz - 1; ++i)
3627 set_hash_next_slot (h, i, make_number (i + 1));
3628 h->next_free = make_number (0);
3630 XSET_HASH_TABLE (table, h);
3631 eassert (HASH_TABLE_P (table));
3632 eassert (XHASH_TABLE (table) == h);
3634 /* Maybe add this hash table to the list of all weak hash tables. */
3635 if (NILP (h->weak))
3636 h->next_weak = NULL;
3637 else
3639 h->next_weak = weak_hash_tables;
3640 weak_hash_tables = h;
3643 return table;
3647 /* Return a copy of hash table H1. Keys and values are not copied,
3648 only the table itself is. */
3650 static Lisp_Object
3651 copy_hash_table (struct Lisp_Hash_Table *h1)
3653 Lisp_Object table;
3654 struct Lisp_Hash_Table *h2;
3656 h2 = allocate_hash_table ();
3657 *h2 = *h1;
3658 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3659 h2->hash = Fcopy_sequence (h1->hash);
3660 h2->next = Fcopy_sequence (h1->next);
3661 h2->index = Fcopy_sequence (h1->index);
3662 XSET_HASH_TABLE (table, h2);
3664 /* Maybe add this hash table to the list of all weak hash tables. */
3665 if (!NILP (h2->weak))
3667 h2->next_weak = weak_hash_tables;
3668 weak_hash_tables = h2;
3671 return table;
3675 /* Resize hash table H if it's too full. If H cannot be resized
3676 because it's already too large, throw an error. */
3678 static void
3679 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3681 if (NILP (h->next_free))
3683 ptrdiff_t old_size = HASH_TABLE_SIZE (h);
3684 EMACS_INT new_size, index_size, nsize;
3685 ptrdiff_t i;
3686 double index_float;
3688 if (INTEGERP (h->rehash_size))
3689 new_size = old_size + XFASTINT (h->rehash_size);
3690 else
3692 double float_new_size = old_size * XFLOAT_DATA (h->rehash_size);
3693 if (float_new_size < INDEX_SIZE_BOUND + 1)
3695 new_size = float_new_size;
3696 if (new_size <= old_size)
3697 new_size = old_size + 1;
3699 else
3700 new_size = INDEX_SIZE_BOUND + 1;
3702 index_float = new_size / XFLOAT_DATA (h->rehash_threshold);
3703 index_size = (index_float < INDEX_SIZE_BOUND + 1
3704 ? next_almost_prime (index_float)
3705 : INDEX_SIZE_BOUND + 1);
3706 nsize = max (index_size, 2 * new_size);
3707 if (INDEX_SIZE_BOUND < nsize)
3708 error ("Hash table too large to resize");
3710 #ifdef ENABLE_CHECKING
3711 if (HASH_TABLE_P (Vpurify_flag)
3712 && XHASH_TABLE (Vpurify_flag) == h)
3714 Lisp_Object args[2];
3715 args[0] = build_string ("Growing hash table to: %d");
3716 args[1] = make_number (new_size);
3717 Fmessage (2, args);
3719 #endif
3721 set_hash_key_and_value (h, larger_vector (h->key_and_value,
3722 2 * (new_size - old_size), -1));
3723 set_hash_next (h, larger_vector (h->next, new_size - old_size, -1));
3724 set_hash_hash (h, larger_vector (h->hash, new_size - old_size, -1));
3725 set_hash_index (h, Fmake_vector (make_number (index_size), Qnil));
3727 /* Update the free list. Do it so that new entries are added at
3728 the end of the free list. This makes some operations like
3729 maphash faster. */
3730 for (i = old_size; i < new_size - 1; ++i)
3731 set_hash_next_slot (h, i, make_number (i + 1));
3733 if (!NILP (h->next_free))
3735 Lisp_Object last, next;
3737 last = h->next_free;
3738 while (next = HASH_NEXT (h, XFASTINT (last)),
3739 !NILP (next))
3740 last = next;
3742 set_hash_next_slot (h, XFASTINT (last), make_number (old_size));
3744 else
3745 XSETFASTINT (h->next_free, old_size);
3747 /* Rehash. */
3748 for (i = 0; i < old_size; ++i)
3749 if (!NILP (HASH_HASH (h, i)))
3751 EMACS_UINT hash_code = XUINT (HASH_HASH (h, i));
3752 ptrdiff_t start_of_bucket = hash_code % ASIZE (h->index);
3753 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3754 set_hash_index_slot (h, start_of_bucket, make_number (i));
3760 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
3761 the hash code of KEY. Value is the index of the entry in H
3762 matching KEY, or -1 if not found. */
3764 ptrdiff_t
3765 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
3767 EMACS_UINT hash_code;
3768 ptrdiff_t start_of_bucket;
3769 Lisp_Object idx;
3771 hash_code = h->test.hashfn (&h->test, key);
3772 eassert ((hash_code & ~INTMASK) == 0);
3773 if (hash)
3774 *hash = hash_code;
3776 start_of_bucket = hash_code % ASIZE (h->index);
3777 idx = HASH_INDEX (h, start_of_bucket);
3779 /* We need not gcpro idx since it's either an integer or nil. */
3780 while (!NILP (idx))
3782 ptrdiff_t i = XFASTINT (idx);
3783 if (EQ (key, HASH_KEY (h, i))
3784 || (h->test.cmpfn
3785 && hash_code == XUINT (HASH_HASH (h, i))
3786 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
3787 break;
3788 idx = HASH_NEXT (h, i);
3791 return NILP (idx) ? -1 : XFASTINT (idx);
3795 /* Put an entry into hash table H that associates KEY with VALUE.
3796 HASH is a previously computed hash code of KEY.
3797 Value is the index of the entry in H matching KEY. */
3799 ptrdiff_t
3800 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value,
3801 EMACS_UINT hash)
3803 ptrdiff_t start_of_bucket, i;
3805 eassert ((hash & ~INTMASK) == 0);
3807 /* Increment count after resizing because resizing may fail. */
3808 maybe_resize_hash_table (h);
3809 h->count++;
3811 /* Store key/value in the key_and_value vector. */
3812 i = XFASTINT (h->next_free);
3813 h->next_free = HASH_NEXT (h, i);
3814 set_hash_key_slot (h, i, key);
3815 set_hash_value_slot (h, i, value);
3817 /* Remember its hash code. */
3818 set_hash_hash_slot (h, i, make_number (hash));
3820 /* Add new entry to its collision chain. */
3821 start_of_bucket = hash % ASIZE (h->index);
3822 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
3823 set_hash_index_slot (h, start_of_bucket, make_number (i));
3824 return i;
3828 /* Remove the entry matching KEY from hash table H, if there is one. */
3830 static void
3831 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
3833 EMACS_UINT hash_code;
3834 ptrdiff_t start_of_bucket;
3835 Lisp_Object idx, prev;
3837 hash_code = h->test.hashfn (&h->test, key);
3838 eassert ((hash_code & ~INTMASK) == 0);
3839 start_of_bucket = hash_code % ASIZE (h->index);
3840 idx = HASH_INDEX (h, start_of_bucket);
3841 prev = Qnil;
3843 /* We need not gcpro idx, prev since they're either integers or nil. */
3844 while (!NILP (idx))
3846 ptrdiff_t i = XFASTINT (idx);
3848 if (EQ (key, HASH_KEY (h, i))
3849 || (h->test.cmpfn
3850 && hash_code == XUINT (HASH_HASH (h, i))
3851 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
3853 /* Take entry out of collision chain. */
3854 if (NILP (prev))
3855 set_hash_index_slot (h, start_of_bucket, HASH_NEXT (h, i));
3856 else
3857 set_hash_next_slot (h, XFASTINT (prev), HASH_NEXT (h, i));
3859 /* Clear slots in key_and_value and add the slots to
3860 the free list. */
3861 set_hash_key_slot (h, i, Qnil);
3862 set_hash_value_slot (h, i, Qnil);
3863 set_hash_hash_slot (h, i, Qnil);
3864 set_hash_next_slot (h, i, h->next_free);
3865 h->next_free = make_number (i);
3866 h->count--;
3867 eassert (h->count >= 0);
3868 break;
3870 else
3872 prev = idx;
3873 idx = HASH_NEXT (h, i);
3879 /* Clear hash table H. */
3881 static void
3882 hash_clear (struct Lisp_Hash_Table *h)
3884 if (h->count > 0)
3886 ptrdiff_t i, size = HASH_TABLE_SIZE (h);
3888 for (i = 0; i < size; ++i)
3890 set_hash_next_slot (h, i, i < size - 1 ? make_number (i + 1) : Qnil);
3891 set_hash_key_slot (h, i, Qnil);
3892 set_hash_value_slot (h, i, Qnil);
3893 set_hash_hash_slot (h, i, Qnil);
3896 for (i = 0; i < ASIZE (h->index); ++i)
3897 ASET (h->index, i, Qnil);
3899 h->next_free = make_number (0);
3900 h->count = 0;
3906 /************************************************************************
3907 Weak Hash Tables
3908 ************************************************************************/
3910 /* Sweep weak hash table H. REMOVE_ENTRIES_P means remove
3911 entries from the table that don't survive the current GC.
3912 !REMOVE_ENTRIES_P means mark entries that are in use. Value is
3913 true if anything was marked. */
3915 static bool
3916 sweep_weak_table (struct Lisp_Hash_Table *h, bool remove_entries_p)
3918 ptrdiff_t bucket, n;
3919 bool marked;
3921 n = ASIZE (h->index) & ~ARRAY_MARK_FLAG;
3922 marked = 0;
3924 for (bucket = 0; bucket < n; ++bucket)
3926 Lisp_Object idx, next, prev;
3928 /* Follow collision chain, removing entries that
3929 don't survive this garbage collection. */
3930 prev = Qnil;
3931 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
3933 ptrdiff_t i = XFASTINT (idx);
3934 bool key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
3935 bool value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
3936 bool remove_p;
3938 if (EQ (h->weak, Qkey))
3939 remove_p = !key_known_to_survive_p;
3940 else if (EQ (h->weak, Qvalue))
3941 remove_p = !value_known_to_survive_p;
3942 else if (EQ (h->weak, Qkey_or_value))
3943 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
3944 else if (EQ (h->weak, Qkey_and_value))
3945 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
3946 else
3947 emacs_abort ();
3949 next = HASH_NEXT (h, i);
3951 if (remove_entries_p)
3953 if (remove_p)
3955 /* Take out of collision chain. */
3956 if (NILP (prev))
3957 set_hash_index_slot (h, bucket, next);
3958 else
3959 set_hash_next_slot (h, XFASTINT (prev), next);
3961 /* Add to free list. */
3962 set_hash_next_slot (h, i, h->next_free);
3963 h->next_free = idx;
3965 /* Clear key, value, and hash. */
3966 set_hash_key_slot (h, i, Qnil);
3967 set_hash_value_slot (h, i, Qnil);
3968 set_hash_hash_slot (h, i, Qnil);
3970 h->count--;
3972 else
3974 prev = idx;
3977 else
3979 if (!remove_p)
3981 /* Make sure key and value survive. */
3982 if (!key_known_to_survive_p)
3984 mark_object (HASH_KEY (h, i));
3985 marked = 1;
3988 if (!value_known_to_survive_p)
3990 mark_object (HASH_VALUE (h, i));
3991 marked = 1;
3998 return marked;
4001 /* Remove elements from weak hash tables that don't survive the
4002 current garbage collection. Remove weak tables that don't survive
4003 from Vweak_hash_tables. Called from gc_sweep. */
4005 void
4006 sweep_weak_hash_tables (void)
4008 struct Lisp_Hash_Table *h, *used, *next;
4009 bool marked;
4011 /* Mark all keys and values that are in use. Keep on marking until
4012 there is no more change. This is necessary for cases like
4013 value-weak table A containing an entry X -> Y, where Y is used in a
4014 key-weak table B, Z -> Y. If B comes after A in the list of weak
4015 tables, X -> Y might be removed from A, although when looking at B
4016 one finds that it shouldn't. */
4019 marked = 0;
4020 for (h = weak_hash_tables; h; h = h->next_weak)
4022 if (h->header.size & ARRAY_MARK_FLAG)
4023 marked |= sweep_weak_table (h, 0);
4026 while (marked);
4028 /* Remove tables and entries that aren't used. */
4029 for (h = weak_hash_tables, used = NULL; h; h = next)
4031 next = h->next_weak;
4033 if (h->header.size & ARRAY_MARK_FLAG)
4035 /* TABLE is marked as used. Sweep its contents. */
4036 if (h->count > 0)
4037 sweep_weak_table (h, 1);
4039 /* Add table to the list of used weak hash tables. */
4040 h->next_weak = used;
4041 used = h;
4045 weak_hash_tables = used;
4050 /***********************************************************************
4051 Hash Code Computation
4052 ***********************************************************************/
4054 /* Maximum depth up to which to dive into Lisp structures. */
4056 #define SXHASH_MAX_DEPTH 3
4058 /* Maximum length up to which to take list and vector elements into
4059 account. */
4061 #define SXHASH_MAX_LEN 7
4063 /* Return a hash for string PTR which has length LEN. The hash value
4064 can be any EMACS_UINT value. */
4066 EMACS_UINT
4067 hash_string (char const *ptr, ptrdiff_t len)
4069 char const *p = ptr;
4070 char const *end = p + len;
4071 unsigned char c;
4072 EMACS_UINT hash = 0;
4074 while (p != end)
4076 c = *p++;
4077 hash = sxhash_combine (hash, c);
4080 return hash;
4083 /* Return a hash for string PTR which has length LEN. The hash
4084 code returned is guaranteed to fit in a Lisp integer. */
4086 static EMACS_UINT
4087 sxhash_string (char const *ptr, ptrdiff_t len)
4089 EMACS_UINT hash = hash_string (ptr, len);
4090 return SXHASH_REDUCE (hash);
4093 /* Return a hash for the floating point value VAL. */
4095 static EMACS_UINT
4096 sxhash_float (double val)
4098 EMACS_UINT hash = 0;
4099 enum {
4100 WORDS_PER_DOUBLE = (sizeof val / sizeof hash
4101 + (sizeof val % sizeof hash != 0))
4103 union {
4104 double val;
4105 EMACS_UINT word[WORDS_PER_DOUBLE];
4106 } u;
4107 int i;
4108 u.val = val;
4109 memset (&u.val + 1, 0, sizeof u - sizeof u.val);
4110 for (i = 0; i < WORDS_PER_DOUBLE; i++)
4111 hash = sxhash_combine (hash, u.word[i]);
4112 return SXHASH_REDUCE (hash);
4115 /* Return a hash for list LIST. DEPTH is the current depth in the
4116 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4118 static EMACS_UINT
4119 sxhash_list (Lisp_Object list, int depth)
4121 EMACS_UINT hash = 0;
4122 int i;
4124 if (depth < SXHASH_MAX_DEPTH)
4125 for (i = 0;
4126 CONSP (list) && i < SXHASH_MAX_LEN;
4127 list = XCDR (list), ++i)
4129 EMACS_UINT hash2 = sxhash (XCAR (list), depth + 1);
4130 hash = sxhash_combine (hash, hash2);
4133 if (!NILP (list))
4135 EMACS_UINT hash2 = sxhash (list, depth + 1);
4136 hash = sxhash_combine (hash, hash2);
4139 return SXHASH_REDUCE (hash);
4143 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4144 the Lisp structure. */
4146 static EMACS_UINT
4147 sxhash_vector (Lisp_Object vec, int depth)
4149 EMACS_UINT hash = ASIZE (vec);
4150 int i, n;
4152 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4153 for (i = 0; i < n; ++i)
4155 EMACS_UINT hash2 = sxhash (AREF (vec, i), depth + 1);
4156 hash = sxhash_combine (hash, hash2);
4159 return SXHASH_REDUCE (hash);
4162 /* Return a hash for bool-vector VECTOR. */
4164 static EMACS_UINT
4165 sxhash_bool_vector (Lisp_Object vec)
4167 EMACS_INT size = bool_vector_size (vec);
4168 EMACS_UINT hash = size;
4169 int i, n;
4171 n = min (SXHASH_MAX_LEN, bool_vector_words (size));
4172 for (i = 0; i < n; ++i)
4173 hash = sxhash_combine (hash, bool_vector_data (vec)[i]);
4175 return SXHASH_REDUCE (hash);
4179 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4180 structure. Value is an unsigned integer clipped to INTMASK. */
4182 EMACS_UINT
4183 sxhash (Lisp_Object obj, int depth)
4185 EMACS_UINT hash;
4187 if (depth > SXHASH_MAX_DEPTH)
4188 return 0;
4190 switch (XTYPE (obj))
4192 case_Lisp_Int:
4193 hash = XUINT (obj);
4194 break;
4196 case Lisp_Misc:
4197 hash = XHASH (obj);
4198 break;
4200 case Lisp_Symbol:
4201 obj = SYMBOL_NAME (obj);
4202 /* Fall through. */
4204 case Lisp_String:
4205 hash = sxhash_string (SSDATA (obj), SBYTES (obj));
4206 break;
4208 /* This can be everything from a vector to an overlay. */
4209 case Lisp_Vectorlike:
4210 if (VECTORP (obj))
4211 /* According to the CL HyperSpec, two arrays are equal only if
4212 they are `eq', except for strings and bit-vectors. In
4213 Emacs, this works differently. We have to compare element
4214 by element. */
4215 hash = sxhash_vector (obj, depth);
4216 else if (BOOL_VECTOR_P (obj))
4217 hash = sxhash_bool_vector (obj);
4218 else
4219 /* Others are `equal' if they are `eq', so let's take their
4220 address as hash. */
4221 hash = XHASH (obj);
4222 break;
4224 case Lisp_Cons:
4225 hash = sxhash_list (obj, depth);
4226 break;
4228 case Lisp_Float:
4229 hash = sxhash_float (XFLOAT_DATA (obj));
4230 break;
4232 default:
4233 emacs_abort ();
4236 return hash;
4241 /***********************************************************************
4242 Lisp Interface
4243 ***********************************************************************/
4246 DEFUN ("sxhash", Fsxhash, Ssxhash, 1, 1, 0,
4247 doc: /* Compute a hash code for OBJ and return it as integer. */)
4248 (Lisp_Object obj)
4250 EMACS_UINT hash = sxhash (obj, 0);
4251 return make_number (hash);
4255 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4256 doc: /* Create and return a new hash table.
4258 Arguments are specified as keyword/argument pairs. The following
4259 arguments are defined:
4261 :test TEST -- TEST must be a symbol that specifies how to compare
4262 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4263 `equal'. User-supplied test and hash functions can be specified via
4264 `define-hash-table-test'.
4266 :size SIZE -- A hint as to how many elements will be put in the table.
4267 Default is 65.
4269 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4270 fills up. If REHASH-SIZE is an integer, increase the size by that
4271 amount. If it is a float, it must be > 1.0, and the new size is the
4272 old size multiplied by that factor. Default is 1.5.
4274 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4275 Resize the hash table when the ratio (number of entries / table size)
4276 is greater than or equal to THRESHOLD. Default is 0.8.
4278 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4279 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4280 returned is a weak table. Key/value pairs are removed from a weak
4281 hash table when there are no non-weak references pointing to their
4282 key, value, one of key or value, or both key and value, depending on
4283 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4284 is nil.
4286 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4287 (ptrdiff_t nargs, Lisp_Object *args)
4289 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4290 struct hash_table_test testdesc;
4291 char *used;
4292 ptrdiff_t i;
4294 /* The vector `used' is used to keep track of arguments that
4295 have been consumed. */
4296 used = alloca (nargs * sizeof *used);
4297 memset (used, 0, nargs * sizeof *used);
4299 /* See if there's a `:test TEST' among the arguments. */
4300 i = get_key_arg (QCtest, nargs, args, used);
4301 test = i ? args[i] : Qeql;
4302 if (EQ (test, Qeq))
4303 testdesc = hashtest_eq;
4304 else if (EQ (test, Qeql))
4305 testdesc = hashtest_eql;
4306 else if (EQ (test, Qequal))
4307 testdesc = hashtest_equal;
4308 else
4310 /* See if it is a user-defined test. */
4311 Lisp_Object prop;
4313 prop = Fget (test, Qhash_table_test);
4314 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4315 signal_error ("Invalid hash table test", test);
4316 testdesc.name = test;
4317 testdesc.user_cmp_function = XCAR (prop);
4318 testdesc.user_hash_function = XCAR (XCDR (prop));
4319 testdesc.hashfn = hashfn_user_defined;
4320 testdesc.cmpfn = cmpfn_user_defined;
4323 /* See if there's a `:size SIZE' argument. */
4324 i = get_key_arg (QCsize, nargs, args, used);
4325 size = i ? args[i] : Qnil;
4326 if (NILP (size))
4327 size = make_number (DEFAULT_HASH_SIZE);
4328 else if (!INTEGERP (size) || XINT (size) < 0)
4329 signal_error ("Invalid hash table size", size);
4331 /* Look for `:rehash-size SIZE'. */
4332 i = get_key_arg (QCrehash_size, nargs, args, used);
4333 rehash_size = i ? args[i] : make_float (DEFAULT_REHASH_SIZE);
4334 if (! ((INTEGERP (rehash_size) && 0 < XINT (rehash_size))
4335 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size))))
4336 signal_error ("Invalid hash table rehash size", rehash_size);
4338 /* Look for `:rehash-threshold THRESHOLD'. */
4339 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4340 rehash_threshold = i ? args[i] : make_float (DEFAULT_REHASH_THRESHOLD);
4341 if (! (FLOATP (rehash_threshold)
4342 && 0 < XFLOAT_DATA (rehash_threshold)
4343 && XFLOAT_DATA (rehash_threshold) <= 1))
4344 signal_error ("Invalid hash table rehash threshold", rehash_threshold);
4346 /* Look for `:weakness WEAK'. */
4347 i = get_key_arg (QCweakness, nargs, args, used);
4348 weak = i ? args[i] : Qnil;
4349 if (EQ (weak, Qt))
4350 weak = Qkey_and_value;
4351 if (!NILP (weak)
4352 && !EQ (weak, Qkey)
4353 && !EQ (weak, Qvalue)
4354 && !EQ (weak, Qkey_or_value)
4355 && !EQ (weak, Qkey_and_value))
4356 signal_error ("Invalid hash table weakness", weak);
4358 /* Now, all args should have been used up, or there's a problem. */
4359 for (i = 0; i < nargs; ++i)
4360 if (!used[i])
4361 signal_error ("Invalid argument list", args[i]);
4363 return make_hash_table (testdesc, size, rehash_size, rehash_threshold, weak);
4367 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4368 doc: /* Return a copy of hash table TABLE. */)
4369 (Lisp_Object table)
4371 return copy_hash_table (check_hash_table (table));
4375 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4376 doc: /* Return the number of elements in TABLE. */)
4377 (Lisp_Object table)
4379 return make_number (check_hash_table (table)->count);
4383 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4384 Shash_table_rehash_size, 1, 1, 0,
4385 doc: /* Return the current rehash size of TABLE. */)
4386 (Lisp_Object table)
4388 return check_hash_table (table)->rehash_size;
4392 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4393 Shash_table_rehash_threshold, 1, 1, 0,
4394 doc: /* Return the current rehash threshold of TABLE. */)
4395 (Lisp_Object table)
4397 return check_hash_table (table)->rehash_threshold;
4401 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4402 doc: /* Return the size of TABLE.
4403 The size can be used as an argument to `make-hash-table' to create
4404 a hash table than can hold as many elements as TABLE holds
4405 without need for resizing. */)
4406 (Lisp_Object table)
4408 struct Lisp_Hash_Table *h = check_hash_table (table);
4409 return make_number (HASH_TABLE_SIZE (h));
4413 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4414 doc: /* Return the test TABLE uses. */)
4415 (Lisp_Object table)
4417 return check_hash_table (table)->test.name;
4421 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4422 1, 1, 0,
4423 doc: /* Return the weakness of TABLE. */)
4424 (Lisp_Object table)
4426 return check_hash_table (table)->weak;
4430 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4431 doc: /* Return t if OBJ is a Lisp hash table object. */)
4432 (Lisp_Object obj)
4434 return HASH_TABLE_P (obj) ? Qt : Qnil;
4438 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4439 doc: /* Clear hash table TABLE and return it. */)
4440 (Lisp_Object table)
4442 hash_clear (check_hash_table (table));
4443 /* Be compatible with XEmacs. */
4444 return table;
4448 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4449 doc: /* Look up KEY in TABLE and return its associated value.
4450 If KEY is not found, return DFLT which defaults to nil. */)
4451 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4453 struct Lisp_Hash_Table *h = check_hash_table (table);
4454 ptrdiff_t i = hash_lookup (h, key, NULL);
4455 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4459 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4460 doc: /* Associate KEY with VALUE in hash table TABLE.
4461 If KEY is already present in table, replace its current value with
4462 VALUE. In any case, return VALUE. */)
4463 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4465 struct Lisp_Hash_Table *h = check_hash_table (table);
4466 ptrdiff_t i;
4467 EMACS_UINT hash;
4469 i = hash_lookup (h, key, &hash);
4470 if (i >= 0)
4471 set_hash_value_slot (h, i, value);
4472 else
4473 hash_put (h, key, value, hash);
4475 return value;
4479 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4480 doc: /* Remove KEY from TABLE. */)
4481 (Lisp_Object key, Lisp_Object table)
4483 struct Lisp_Hash_Table *h = check_hash_table (table);
4484 hash_remove_from_table (h, key);
4485 return Qnil;
4489 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4490 doc: /* Call FUNCTION for all entries in hash table TABLE.
4491 FUNCTION is called with two arguments, KEY and VALUE. */)
4492 (Lisp_Object function, Lisp_Object table)
4494 struct Lisp_Hash_Table *h = check_hash_table (table);
4495 Lisp_Object args[3];
4496 ptrdiff_t i;
4498 for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
4499 if (!NILP (HASH_HASH (h, i)))
4501 args[0] = function;
4502 args[1] = HASH_KEY (h, i);
4503 args[2] = HASH_VALUE (h, i);
4504 Ffuncall (3, args);
4507 return Qnil;
4511 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4512 Sdefine_hash_table_test, 3, 3, 0,
4513 doc: /* Define a new hash table test with name NAME, a symbol.
4515 In hash tables created with NAME specified as test, use TEST to
4516 compare keys, and HASH for computing hash codes of keys.
4518 TEST must be a function taking two arguments and returning non-nil if
4519 both arguments are the same. HASH must be a function taking one
4520 argument and returning an object that is the hash code of the argument.
4521 It should be the case that if (eq (funcall HASH x1) (funcall HASH x2))
4522 returns nil, then (funcall TEST x1 x2) also returns nil. */)
4523 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4525 return Fput (name, Qhash_table_test, list2 (test, hash));
4530 /************************************************************************
4531 MD5, SHA-1, and SHA-2
4532 ************************************************************************/
4534 #include "md5.h"
4535 #include "sha1.h"
4536 #include "sha256.h"
4537 #include "sha512.h"
4539 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4541 static Lisp_Object
4542 secure_hash (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror, Lisp_Object binary)
4544 int i;
4545 ptrdiff_t size;
4546 EMACS_INT start_char = 0, end_char = 0;
4547 ptrdiff_t start_byte, end_byte;
4548 register EMACS_INT b, e;
4549 register struct buffer *bp;
4550 EMACS_INT temp;
4551 int digest_size;
4552 void *(*hash_func) (const char *, size_t, void *);
4553 Lisp_Object digest;
4555 CHECK_SYMBOL (algorithm);
4557 if (STRINGP (object))
4559 if (NILP (coding_system))
4561 /* Decide the coding-system to encode the data with. */
4563 if (STRING_MULTIBYTE (object))
4564 /* use default, we can't guess correct value */
4565 coding_system = preferred_coding_system ();
4566 else
4567 coding_system = Qraw_text;
4570 if (NILP (Fcoding_system_p (coding_system)))
4572 /* Invalid coding system. */
4574 if (!NILP (noerror))
4575 coding_system = Qraw_text;
4576 else
4577 xsignal1 (Qcoding_system_error, coding_system);
4580 if (STRING_MULTIBYTE (object))
4581 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4583 size = SCHARS (object);
4585 if (!NILP (start))
4587 CHECK_NUMBER (start);
4589 start_char = XINT (start);
4591 if (start_char < 0)
4592 start_char += size;
4595 if (NILP (end))
4596 end_char = size;
4597 else
4599 CHECK_NUMBER (end);
4601 end_char = XINT (end);
4603 if (end_char < 0)
4604 end_char += size;
4607 if (!(0 <= start_char && start_char <= end_char && end_char <= size))
4608 args_out_of_range_3 (object, make_number (start_char),
4609 make_number (end_char));
4611 start_byte = NILP (start) ? 0 : string_char_to_byte (object, start_char);
4612 end_byte =
4613 NILP (end) ? SBYTES (object) : string_char_to_byte (object, end_char);
4615 else
4617 struct buffer *prev = current_buffer;
4619 record_unwind_current_buffer ();
4621 CHECK_BUFFER (object);
4623 bp = XBUFFER (object);
4624 set_buffer_internal (bp);
4626 if (NILP (start))
4627 b = BEGV;
4628 else
4630 CHECK_NUMBER_COERCE_MARKER (start);
4631 b = XINT (start);
4634 if (NILP (end))
4635 e = ZV;
4636 else
4638 CHECK_NUMBER_COERCE_MARKER (end);
4639 e = XINT (end);
4642 if (b > e)
4643 temp = b, b = e, e = temp;
4645 if (!(BEGV <= b && e <= ZV))
4646 args_out_of_range (start, end);
4648 if (NILP (coding_system))
4650 /* Decide the coding-system to encode the data with.
4651 See fileio.c:Fwrite-region */
4653 if (!NILP (Vcoding_system_for_write))
4654 coding_system = Vcoding_system_for_write;
4655 else
4657 bool force_raw_text = 0;
4659 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4660 if (NILP (coding_system)
4661 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4663 coding_system = Qnil;
4664 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4665 force_raw_text = 1;
4668 if (NILP (coding_system) && !NILP (Fbuffer_file_name (object)))
4670 /* Check file-coding-system-alist. */
4671 Lisp_Object args[4], val;
4673 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4674 args[3] = Fbuffer_file_name (object);
4675 val = Ffind_operation_coding_system (4, args);
4676 if (CONSP (val) && !NILP (XCDR (val)))
4677 coding_system = XCDR (val);
4680 if (NILP (coding_system)
4681 && !NILP (BVAR (XBUFFER (object), buffer_file_coding_system)))
4683 /* If we still have not decided a coding system, use the
4684 default value of buffer-file-coding-system. */
4685 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4688 if (!force_raw_text
4689 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4690 /* Confirm that VAL can surely encode the current region. */
4691 coding_system = call4 (Vselect_safe_coding_system_function,
4692 make_number (b), make_number (e),
4693 coding_system, Qnil);
4695 if (force_raw_text)
4696 coding_system = Qraw_text;
4699 if (NILP (Fcoding_system_p (coding_system)))
4701 /* Invalid coding system. */
4703 if (!NILP (noerror))
4704 coding_system = Qraw_text;
4705 else
4706 xsignal1 (Qcoding_system_error, coding_system);
4710 object = make_buffer_string (b, e, 0);
4711 set_buffer_internal (prev);
4712 /* Discard the unwind protect for recovering the current
4713 buffer. */
4714 specpdl_ptr--;
4716 if (STRING_MULTIBYTE (object))
4717 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4718 start_byte = 0;
4719 end_byte = SBYTES (object);
4722 if (EQ (algorithm, Qmd5))
4724 digest_size = MD5_DIGEST_SIZE;
4725 hash_func = md5_buffer;
4727 else if (EQ (algorithm, Qsha1))
4729 digest_size = SHA1_DIGEST_SIZE;
4730 hash_func = sha1_buffer;
4732 else if (EQ (algorithm, Qsha224))
4734 digest_size = SHA224_DIGEST_SIZE;
4735 hash_func = sha224_buffer;
4737 else if (EQ (algorithm, Qsha256))
4739 digest_size = SHA256_DIGEST_SIZE;
4740 hash_func = sha256_buffer;
4742 else if (EQ (algorithm, Qsha384))
4744 digest_size = SHA384_DIGEST_SIZE;
4745 hash_func = sha384_buffer;
4747 else if (EQ (algorithm, Qsha512))
4749 digest_size = SHA512_DIGEST_SIZE;
4750 hash_func = sha512_buffer;
4752 else
4753 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm)));
4755 /* allocate 2 x digest_size so that it can be re-used to hold the
4756 hexified value */
4757 digest = make_uninit_string (digest_size * 2);
4759 hash_func (SSDATA (object) + start_byte,
4760 end_byte - start_byte,
4761 SSDATA (digest));
4763 if (NILP (binary))
4765 unsigned char *p = SDATA (digest);
4766 for (i = digest_size - 1; i >= 0; i--)
4768 static char const hexdigit[16] = "0123456789abcdef";
4769 int p_i = p[i];
4770 p[2 * i] = hexdigit[p_i >> 4];
4771 p[2 * i + 1] = hexdigit[p_i & 0xf];
4773 return digest;
4775 else
4776 return make_unibyte_string (SSDATA (digest), digest_size);
4779 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
4780 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
4782 A message digest is a cryptographic checksum of a document, and the
4783 algorithm to calculate it is defined in RFC 1321.
4785 The two optional arguments START and END are character positions
4786 specifying for which part of OBJECT the message digest should be
4787 computed. If nil or omitted, the digest is computed for the whole
4788 OBJECT.
4790 The MD5 message digest is computed from the result of encoding the
4791 text in a coding system, not directly from the internal Emacs form of
4792 the text. The optional fourth argument CODING-SYSTEM specifies which
4793 coding system to encode the text with. It should be the same coding
4794 system that you used or will use when actually writing the text into a
4795 file.
4797 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
4798 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
4799 system would be chosen by default for writing this text into a file.
4801 If OBJECT is a string, the most preferred coding system (see the
4802 command `prefer-coding-system') is used.
4804 If NOERROR is non-nil, silently assume the `raw-text' coding if the
4805 guesswork fails. Normally, an error is signaled in such case. */)
4806 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
4808 return secure_hash (Qmd5, object, start, end, coding_system, noerror, Qnil);
4811 DEFUN ("secure-hash", Fsecure_hash, Ssecure_hash, 2, 5, 0,
4812 doc: /* Return the secure hash of OBJECT, a buffer or string.
4813 ALGORITHM is a symbol specifying the hash to use:
4814 md5, sha1, sha224, sha256, sha384 or sha512.
4816 The two optional arguments START and END are positions specifying for
4817 which part of OBJECT to compute the hash. If nil or omitted, uses the
4818 whole OBJECT.
4820 If BINARY is non-nil, returns a string in binary form. */)
4821 (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object binary)
4823 return secure_hash (algorithm, object, start, end, Qnil, Qnil, binary);
4826 void
4827 syms_of_fns (void)
4829 DEFSYM (Qmd5, "md5");
4830 DEFSYM (Qsha1, "sha1");
4831 DEFSYM (Qsha224, "sha224");
4832 DEFSYM (Qsha256, "sha256");
4833 DEFSYM (Qsha384, "sha384");
4834 DEFSYM (Qsha512, "sha512");
4836 /* Hash table stuff. */
4837 DEFSYM (Qhash_table_p, "hash-table-p");
4838 DEFSYM (Qeq, "eq");
4839 DEFSYM (Qeql, "eql");
4840 DEFSYM (Qequal, "equal");
4841 DEFSYM (QCtest, ":test");
4842 DEFSYM (QCsize, ":size");
4843 DEFSYM (QCrehash_size, ":rehash-size");
4844 DEFSYM (QCrehash_threshold, ":rehash-threshold");
4845 DEFSYM (QCweakness, ":weakness");
4846 DEFSYM (Qkey, "key");
4847 DEFSYM (Qvalue, "value");
4848 DEFSYM (Qhash_table_test, "hash-table-test");
4849 DEFSYM (Qkey_or_value, "key-or-value");
4850 DEFSYM (Qkey_and_value, "key-and-value");
4852 defsubr (&Ssxhash);
4853 defsubr (&Smake_hash_table);
4854 defsubr (&Scopy_hash_table);
4855 defsubr (&Shash_table_count);
4856 defsubr (&Shash_table_rehash_size);
4857 defsubr (&Shash_table_rehash_threshold);
4858 defsubr (&Shash_table_size);
4859 defsubr (&Shash_table_test);
4860 defsubr (&Shash_table_weakness);
4861 defsubr (&Shash_table_p);
4862 defsubr (&Sclrhash);
4863 defsubr (&Sgethash);
4864 defsubr (&Sputhash);
4865 defsubr (&Sremhash);
4866 defsubr (&Smaphash);
4867 defsubr (&Sdefine_hash_table_test);
4869 DEFSYM (Qstring_lessp, "string-lessp");
4870 DEFSYM (Qprovide, "provide");
4871 DEFSYM (Qrequire, "require");
4872 DEFSYM (Qyes_or_no_p_history, "yes-or-no-p-history");
4873 DEFSYM (Qcursor_in_echo_area, "cursor-in-echo-area");
4874 DEFSYM (Qwidget_type, "widget-type");
4876 staticpro (&string_char_byte_cache_string);
4877 string_char_byte_cache_string = Qnil;
4879 require_nesting_list = Qnil;
4880 staticpro (&require_nesting_list);
4882 Fset (Qyes_or_no_p_history, Qnil);
4884 DEFVAR_LISP ("features", Vfeatures,
4885 doc: /* A list of symbols which are the features of the executing Emacs.
4886 Used by `featurep' and `require', and altered by `provide'. */);
4887 Vfeatures = list1 (intern_c_string ("emacs"));
4888 DEFSYM (Qsubfeatures, "subfeatures");
4889 DEFSYM (Qfuncall, "funcall");
4891 #ifdef HAVE_LANGINFO_CODESET
4892 DEFSYM (Qcodeset, "codeset");
4893 DEFSYM (Qdays, "days");
4894 DEFSYM (Qmonths, "months");
4895 DEFSYM (Qpaper, "paper");
4896 #endif /* HAVE_LANGINFO_CODESET */
4898 DEFVAR_BOOL ("use-dialog-box", use_dialog_box,
4899 doc: /* Non-nil means mouse commands use dialog boxes to ask questions.
4900 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
4901 invoked by mouse clicks and mouse menu items.
4903 On some platforms, file selection dialogs are also enabled if this is
4904 non-nil. */);
4905 use_dialog_box = 1;
4907 DEFVAR_BOOL ("use-file-dialog", use_file_dialog,
4908 doc: /* Non-nil means mouse commands use a file dialog to ask for files.
4909 This applies to commands from menus and tool bar buttons even when
4910 they are initiated from the keyboard. If `use-dialog-box' is nil,
4911 that disables the use of a file dialog, regardless of the value of
4912 this variable. */);
4913 use_file_dialog = 1;
4915 defsubr (&Sidentity);
4916 defsubr (&Srandom);
4917 defsubr (&Slength);
4918 defsubr (&Ssafe_length);
4919 defsubr (&Sstring_bytes);
4920 defsubr (&Sstring_equal);
4921 defsubr (&Scompare_strings);
4922 defsubr (&Sstring_lessp);
4923 defsubr (&Sappend);
4924 defsubr (&Sconcat);
4925 defsubr (&Svconcat);
4926 defsubr (&Scopy_sequence);
4927 defsubr (&Sstring_make_multibyte);
4928 defsubr (&Sstring_make_unibyte);
4929 defsubr (&Sstring_as_multibyte);
4930 defsubr (&Sstring_as_unibyte);
4931 defsubr (&Sstring_to_multibyte);
4932 defsubr (&Sstring_to_unibyte);
4933 defsubr (&Scopy_alist);
4934 defsubr (&Ssubstring);
4935 defsubr (&Ssubstring_no_properties);
4936 defsubr (&Snthcdr);
4937 defsubr (&Snth);
4938 defsubr (&Selt);
4939 defsubr (&Smember);
4940 defsubr (&Smemq);
4941 defsubr (&Smemql);
4942 defsubr (&Sassq);
4943 defsubr (&Sassoc);
4944 defsubr (&Srassq);
4945 defsubr (&Srassoc);
4946 defsubr (&Sdelq);
4947 defsubr (&Sdelete);
4948 defsubr (&Snreverse);
4949 defsubr (&Sreverse);
4950 defsubr (&Ssort);
4951 defsubr (&Splist_get);
4952 defsubr (&Sget);
4953 defsubr (&Splist_put);
4954 defsubr (&Sput);
4955 defsubr (&Slax_plist_get);
4956 defsubr (&Slax_plist_put);
4957 defsubr (&Seql);
4958 defsubr (&Sequal);
4959 defsubr (&Sequal_including_properties);
4960 defsubr (&Sfillarray);
4961 defsubr (&Sclear_string);
4962 defsubr (&Snconc);
4963 defsubr (&Smapcar);
4964 defsubr (&Smapc);
4965 defsubr (&Smapconcat);
4966 defsubr (&Syes_or_no_p);
4967 defsubr (&Sload_average);
4968 defsubr (&Sfeaturep);
4969 defsubr (&Srequire);
4970 defsubr (&Sprovide);
4971 defsubr (&Splist_member);
4972 defsubr (&Swidget_put);
4973 defsubr (&Swidget_get);
4974 defsubr (&Swidget_apply);
4975 defsubr (&Sbase64_encode_region);
4976 defsubr (&Sbase64_decode_region);
4977 defsubr (&Sbase64_encode_string);
4978 defsubr (&Sbase64_decode_string);
4979 defsubr (&Smd5);
4980 defsubr (&Ssecure_hash);
4981 defsubr (&Slocale_info);
4983 hashtest_eq.name = Qeq;
4984 hashtest_eq.user_hash_function = Qnil;
4985 hashtest_eq.user_cmp_function = Qnil;
4986 hashtest_eq.cmpfn = 0;
4987 hashtest_eq.hashfn = hashfn_eq;
4989 hashtest_eql.name = Qeql;
4990 hashtest_eql.user_hash_function = Qnil;
4991 hashtest_eql.user_cmp_function = Qnil;
4992 hashtest_eql.cmpfn = cmpfn_eql;
4993 hashtest_eql.hashfn = hashfn_eql;
4995 hashtest_equal.name = Qequal;
4996 hashtest_equal.user_hash_function = Qnil;
4997 hashtest_equal.user_cmp_function = Qnil;
4998 hashtest_equal.cmpfn = cmpfn_equal;
4999 hashtest_equal.hashfn = hashfn_equal;