Spelling fixes.
[emacs.git] / src / fns.c
blob04b51d10d9bb7481519a44037fde5969f3ef17e6
1 /* Random utility Lisp functions.
2 Copyright (C) 1985-1987, 1993-1995, 1997-2011
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #include <unistd.h>
23 #include <time.h>
24 #include <setjmp.h>
26 #include <intprops.h>
28 #include "lisp.h"
29 #include "commands.h"
30 #include "character.h"
31 #include "coding.h"
32 #include "buffer.h"
33 #include "keyboard.h"
34 #include "keymap.h"
35 #include "intervals.h"
36 #include "frame.h"
37 #include "window.h"
38 #include "blockinput.h"
39 #ifdef HAVE_MENUS
40 #if defined (HAVE_X_WINDOWS)
41 #include "xterm.h"
42 #endif
43 #endif /* HAVE_MENUS */
45 #ifndef NULL
46 #define NULL ((POINTER_TYPE *)0)
47 #endif
49 Lisp_Object Qstring_lessp;
50 static Lisp_Object Qprovide, Qrequire;
51 static Lisp_Object Qyes_or_no_p_history;
52 Lisp_Object Qcursor_in_echo_area;
53 static Lisp_Object Qwidget_type;
54 static Lisp_Object Qcodeset, Qdays, Qmonths, Qpaper;
56 static Lisp_Object Qmd5, Qsha1, Qsha224, Qsha256, Qsha384, Qsha512;
58 static int internal_equal (Lisp_Object , Lisp_Object, int, int);
60 #ifndef HAVE_UNISTD_H
61 extern long time ();
62 #endif
64 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
65 doc: /* Return the argument unchanged. */)
66 (Lisp_Object arg)
68 return arg;
71 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
72 doc: /* Return a pseudo-random number.
73 All integers representable in Lisp are equally likely.
74 On most systems, this is 29 bits' worth.
75 With positive integer LIMIT, return random number in interval [0,LIMIT).
76 With argument t, set the random number seed from the current time and pid.
77 Other values of LIMIT are ignored. */)
78 (Lisp_Object limit)
80 EMACS_INT val;
81 Lisp_Object lispy_val;
83 if (EQ (limit, Qt))
85 EMACS_TIME t;
86 EMACS_GET_TIME (t);
87 seed_random (getpid () ^ EMACS_SECS (t) ^ EMACS_USECS (t));
90 if (NATNUMP (limit) && XFASTINT (limit) != 0)
92 /* Try to take our random number from the higher bits of VAL,
93 not the lower, since (says Gentzel) the low bits of `random'
94 are less random than the higher ones. We do this by using the
95 quotient rather than the remainder. At the high end of the RNG
96 it's possible to get a quotient larger than n; discarding
97 these values eliminates the bias that would otherwise appear
98 when using a large n. */
99 EMACS_INT denominator = (INTMASK + 1) / XFASTINT (limit);
101 val = get_random () / denominator;
102 while (val >= XFASTINT (limit));
104 else
105 val = get_random ();
106 XSETINT (lispy_val, val);
107 return lispy_val;
110 /* Heuristic on how many iterations of a tight loop can be safely done
111 before it's time to do a QUIT. This must be a power of 2. */
112 enum { QUIT_COUNT_HEURISTIC = 1 << 16 };
114 /* Random data-structure functions */
116 DEFUN ("length", Flength, Slength, 1, 1, 0,
117 doc: /* Return the length of vector, list or string SEQUENCE.
118 A byte-code function object is also allowed.
119 If the string contains multibyte characters, this is not necessarily
120 the number of bytes in the string; it is the number of characters.
121 To get the number of bytes, use `string-bytes'. */)
122 (register Lisp_Object sequence)
124 register Lisp_Object val;
126 if (STRINGP (sequence))
127 XSETFASTINT (val, SCHARS (sequence));
128 else if (VECTORP (sequence))
129 XSETFASTINT (val, ASIZE (sequence));
130 else if (CHAR_TABLE_P (sequence))
131 XSETFASTINT (val, MAX_CHAR);
132 else if (BOOL_VECTOR_P (sequence))
133 XSETFASTINT (val, XBOOL_VECTOR (sequence)->size);
134 else if (COMPILEDP (sequence))
135 XSETFASTINT (val, ASIZE (sequence) & PSEUDOVECTOR_SIZE_MASK);
136 else if (CONSP (sequence))
138 EMACS_INT i = 0;
142 ++i;
143 if ((i & (QUIT_COUNT_HEURISTIC - 1)) == 0)
145 if (MOST_POSITIVE_FIXNUM < i)
146 error ("List too long");
147 QUIT;
149 sequence = XCDR (sequence);
151 while (CONSP (sequence));
153 CHECK_LIST_END (sequence, sequence);
155 val = make_number (i);
157 else if (NILP (sequence))
158 XSETFASTINT (val, 0);
159 else
160 wrong_type_argument (Qsequencep, sequence);
162 return val;
165 /* This does not check for quits. That is safe since it must terminate. */
167 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
168 doc: /* Return the length of a list, but avoid error or infinite loop.
169 This function never gets an error. If LIST is not really a list,
170 it returns 0. If LIST is circular, it returns a finite value
171 which is at least the number of distinct elements. */)
172 (Lisp_Object list)
174 Lisp_Object tail, halftail;
175 double hilen = 0;
176 uintmax_t lolen = 1;
178 if (! CONSP (list))
179 return make_number (0);
181 /* halftail is used to detect circular lists. */
182 for (tail = halftail = list; ; )
184 tail = XCDR (tail);
185 if (! CONSP (tail))
186 break;
187 if (EQ (tail, halftail))
188 break;
189 lolen++;
190 if ((lolen & 1) == 0)
192 halftail = XCDR (halftail);
193 if ((lolen & (QUIT_COUNT_HEURISTIC - 1)) == 0)
195 QUIT;
196 if (lolen == 0)
197 hilen += UINTMAX_MAX + 1.0;
202 /* If the length does not fit into a fixnum, return a float.
203 On all known practical machines this returns an upper bound on
204 the true length. */
205 return hilen ? make_float (hilen + lolen) : make_fixnum_or_float (lolen);
208 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
209 doc: /* Return the number of bytes in STRING.
210 If STRING is multibyte, this may be greater than the length of STRING. */)
211 (Lisp_Object string)
213 CHECK_STRING (string);
214 return make_number (SBYTES (string));
217 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
218 doc: /* Return t if two strings have identical contents.
219 Case is significant, but text properties are ignored.
220 Symbols are also allowed; their print names are used instead. */)
221 (register Lisp_Object s1, Lisp_Object s2)
223 if (SYMBOLP (s1))
224 s1 = SYMBOL_NAME (s1);
225 if (SYMBOLP (s2))
226 s2 = SYMBOL_NAME (s2);
227 CHECK_STRING (s1);
228 CHECK_STRING (s2);
230 if (SCHARS (s1) != SCHARS (s2)
231 || SBYTES (s1) != SBYTES (s2)
232 || memcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
233 return Qnil;
234 return Qt;
237 DEFUN ("compare-strings", Fcompare_strings, Scompare_strings, 6, 7, 0,
238 doc: /* Compare the contents of two strings, converting to multibyte if needed.
239 In string STR1, skip the first START1 characters and stop at END1.
240 In string STR2, skip the first START2 characters and stop at END2.
241 END1 and END2 default to the full lengths of the respective strings.
243 Case is significant in this comparison if IGNORE-CASE is nil.
244 Unibyte strings are converted to multibyte for comparison.
246 The value is t if the strings (or specified portions) match.
247 If string STR1 is less, the value is a negative number N;
248 - 1 - N is the number of characters that match at the beginning.
249 If string STR1 is greater, the value is a positive number N;
250 N - 1 is the number of characters that match at the beginning. */)
251 (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2, Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
253 register EMACS_INT end1_char, end2_char;
254 register EMACS_INT i1, i1_byte, i2, i2_byte;
256 CHECK_STRING (str1);
257 CHECK_STRING (str2);
258 if (NILP (start1))
259 start1 = make_number (0);
260 if (NILP (start2))
261 start2 = make_number (0);
262 CHECK_NATNUM (start1);
263 CHECK_NATNUM (start2);
264 if (! NILP (end1))
265 CHECK_NATNUM (end1);
266 if (! NILP (end2))
267 CHECK_NATNUM (end2);
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 end1_char = SCHARS (str1);
276 if (! NILP (end1) && end1_char > XINT (end1))
277 end1_char = XINT (end1);
279 end2_char = SCHARS (str2);
280 if (! NILP (end2) && end2_char > XINT (end2))
281 end2_char = XINT (end2);
283 while (i1 < end1_char && i2 < end2_char)
285 /* When we find a mismatch, we must compare the
286 characters, not just the bytes. */
287 int c1, c2;
289 if (STRING_MULTIBYTE (str1))
290 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c1, str1, i1, i1_byte);
291 else
293 c1 = SREF (str1, i1++);
294 MAKE_CHAR_MULTIBYTE (c1);
297 if (STRING_MULTIBYTE (str2))
298 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c2, str2, i2, i2_byte);
299 else
301 c2 = SREF (str2, i2++);
302 MAKE_CHAR_MULTIBYTE (c2);
305 if (c1 == c2)
306 continue;
308 if (! NILP (ignore_case))
310 Lisp_Object tem;
312 tem = Fupcase (make_number (c1));
313 c1 = XINT (tem);
314 tem = Fupcase (make_number (c2));
315 c2 = XINT (tem);
318 if (c1 == c2)
319 continue;
321 /* Note that I1 has already been incremented
322 past the character that we are comparing;
323 hence we don't add or subtract 1 here. */
324 if (c1 < c2)
325 return make_number (- i1 + XINT (start1));
326 else
327 return make_number (i1 - XINT (start1));
330 if (i1 < end1_char)
331 return make_number (i1 - XINT (start1) + 1);
332 if (i2 < end2_char)
333 return make_number (- i1 + XINT (start1) - 1);
335 return Qt;
338 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
339 doc: /* Return t if first arg string is less than second in lexicographic order.
340 Case is significant.
341 Symbols are also allowed; their print names are used instead. */)
342 (register Lisp_Object s1, Lisp_Object s2)
344 register EMACS_INT end;
345 register EMACS_INT i1, i1_byte, i2, i2_byte;
347 if (SYMBOLP (s1))
348 s1 = SYMBOL_NAME (s1);
349 if (SYMBOLP (s2))
350 s2 = SYMBOL_NAME (s2);
351 CHECK_STRING (s1);
352 CHECK_STRING (s2);
354 i1 = i1_byte = i2 = i2_byte = 0;
356 end = SCHARS (s1);
357 if (end > SCHARS (s2))
358 end = SCHARS (s2);
360 while (i1 < end)
362 /* When we find a mismatch, we must compare the
363 characters, not just the bytes. */
364 int c1, c2;
366 FETCH_STRING_CHAR_ADVANCE (c1, s1, i1, i1_byte);
367 FETCH_STRING_CHAR_ADVANCE (c2, s2, i2, i2_byte);
369 if (c1 != c2)
370 return c1 < c2 ? Qt : Qnil;
372 return i1 < SCHARS (s2) ? Qt : Qnil;
375 static Lisp_Object concat (ptrdiff_t nargs, Lisp_Object *args,
376 enum Lisp_Type target_type, int last_special);
378 /* ARGSUSED */
379 Lisp_Object
380 concat2 (Lisp_Object s1, Lisp_Object s2)
382 Lisp_Object args[2];
383 args[0] = s1;
384 args[1] = s2;
385 return concat (2, args, Lisp_String, 0);
388 /* ARGSUSED */
389 Lisp_Object
390 concat3 (Lisp_Object s1, Lisp_Object s2, Lisp_Object s3)
392 Lisp_Object args[3];
393 args[0] = s1;
394 args[1] = s2;
395 args[2] = s3;
396 return concat (3, args, Lisp_String, 0);
399 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
400 doc: /* Concatenate all the arguments and make the result a list.
401 The result is a list whose elements are the elements of all the arguments.
402 Each argument may be a list, vector or string.
403 The last argument is not copied, just used as the tail of the new list.
404 usage: (append &rest SEQUENCES) */)
405 (ptrdiff_t nargs, Lisp_Object *args)
407 return concat (nargs, args, Lisp_Cons, 1);
410 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
411 doc: /* Concatenate all the arguments and make the result a string.
412 The result is a string whose elements are the elements of all the arguments.
413 Each argument may be a string or a list or vector of characters (integers).
414 usage: (concat &rest SEQUENCES) */)
415 (ptrdiff_t nargs, Lisp_Object *args)
417 return concat (nargs, args, Lisp_String, 0);
420 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
421 doc: /* Concatenate all the arguments and make the result a vector.
422 The result is a vector whose elements are the elements of all the arguments.
423 Each argument may be a list, vector or string.
424 usage: (vconcat &rest SEQUENCES) */)
425 (ptrdiff_t nargs, Lisp_Object *args)
427 return concat (nargs, args, Lisp_Vectorlike, 0);
431 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
432 doc: /* Return a copy of a list, vector, string or char-table.
433 The elements of a list or vector are not copied; they are shared
434 with the original. */)
435 (Lisp_Object arg)
437 if (NILP (arg)) return arg;
439 if (CHAR_TABLE_P (arg))
441 return copy_char_table (arg);
444 if (BOOL_VECTOR_P (arg))
446 Lisp_Object val;
447 ptrdiff_t size_in_chars
448 = ((XBOOL_VECTOR (arg)->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
449 / BOOL_VECTOR_BITS_PER_CHAR);
451 val = Fmake_bool_vector (Flength (arg), Qnil);
452 memcpy (XBOOL_VECTOR (val)->data, XBOOL_VECTOR (arg)->data,
453 size_in_chars);
454 return val;
457 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
458 wrong_type_argument (Qsequencep, arg);
460 return concat (1, &arg, CONSP (arg) ? Lisp_Cons : XTYPE (arg), 0);
463 /* This structure holds information of an argument of `concat' that is
464 a string and has text properties to be copied. */
465 struct textprop_rec
467 ptrdiff_t argnum; /* refer to ARGS (arguments of `concat') */
468 EMACS_INT from; /* refer to ARGS[argnum] (argument string) */
469 EMACS_INT to; /* refer to VAL (the target string) */
472 static Lisp_Object
473 concat (ptrdiff_t nargs, Lisp_Object *args,
474 enum Lisp_Type target_type, int last_special)
476 Lisp_Object val;
477 register Lisp_Object tail;
478 register Lisp_Object this;
479 EMACS_INT toindex;
480 EMACS_INT toindex_byte = 0;
481 register EMACS_INT result_len;
482 register EMACS_INT result_len_byte;
483 ptrdiff_t argnum;
484 Lisp_Object last_tail;
485 Lisp_Object prev;
486 int some_multibyte;
487 /* When we make a multibyte string, we can't copy text properties
488 while concatenating each string because the length of resulting
489 string can't be decided until we finish the whole concatenation.
490 So, we record strings that have text properties to be copied
491 here, and copy the text properties after the concatenation. */
492 struct textprop_rec *textprops = NULL;
493 /* Number of elements in textprops. */
494 ptrdiff_t num_textprops = 0;
495 USE_SAFE_ALLOCA;
497 tail = Qnil;
499 /* In append, the last arg isn't treated like the others */
500 if (last_special && nargs > 0)
502 nargs--;
503 last_tail = args[nargs];
505 else
506 last_tail = Qnil;
508 /* Check each argument. */
509 for (argnum = 0; argnum < nargs; argnum++)
511 this = args[argnum];
512 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
513 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
514 wrong_type_argument (Qsequencep, this);
517 /* Compute total length in chars of arguments in RESULT_LEN.
518 If desired output is a string, also compute length in bytes
519 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
520 whether the result should be a multibyte string. */
521 result_len_byte = 0;
522 result_len = 0;
523 some_multibyte = 0;
524 for (argnum = 0; argnum < nargs; argnum++)
526 EMACS_INT len;
527 this = args[argnum];
528 len = XFASTINT (Flength (this));
529 if (target_type == Lisp_String)
531 /* We must count the number of bytes needed in the string
532 as well as the number of characters. */
533 EMACS_INT i;
534 Lisp_Object ch;
535 int c;
536 EMACS_INT this_len_byte;
538 if (VECTORP (this) || COMPILEDP (this))
539 for (i = 0; i < len; i++)
541 ch = AREF (this, i);
542 CHECK_CHARACTER (ch);
543 c = XFASTINT (ch);
544 this_len_byte = CHAR_BYTES (c);
545 result_len_byte += this_len_byte;
546 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
547 some_multibyte = 1;
549 else if (BOOL_VECTOR_P (this) && XBOOL_VECTOR (this)->size > 0)
550 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
551 else if (CONSP (this))
552 for (; CONSP (this); this = XCDR (this))
554 ch = XCAR (this);
555 CHECK_CHARACTER (ch);
556 c = XFASTINT (ch);
557 this_len_byte = CHAR_BYTES (c);
558 result_len_byte += this_len_byte;
559 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
560 some_multibyte = 1;
562 else if (STRINGP (this))
564 if (STRING_MULTIBYTE (this))
566 some_multibyte = 1;
567 result_len_byte += SBYTES (this);
569 else
570 result_len_byte += count_size_as_multibyte (SDATA (this),
571 SCHARS (this));
575 result_len += len;
576 if (STRING_BYTES_BOUND < result_len)
577 string_overflow ();
580 if (! some_multibyte)
581 result_len_byte = result_len;
583 /* Create the output object. */
584 if (target_type == Lisp_Cons)
585 val = Fmake_list (make_number (result_len), Qnil);
586 else if (target_type == Lisp_Vectorlike)
587 val = Fmake_vector (make_number (result_len), Qnil);
588 else if (some_multibyte)
589 val = make_uninit_multibyte_string (result_len, result_len_byte);
590 else
591 val = make_uninit_string (result_len);
593 /* In `append', if all but last arg are nil, return last arg. */
594 if (target_type == Lisp_Cons && EQ (val, Qnil))
595 return last_tail;
597 /* Copy the contents of the args into the result. */
598 if (CONSP (val))
599 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
600 else
601 toindex = 0, toindex_byte = 0;
603 prev = Qnil;
604 if (STRINGP (val))
605 SAFE_NALLOCA (textprops, 1, nargs);
607 for (argnum = 0; argnum < nargs; argnum++)
609 Lisp_Object thislen;
610 EMACS_INT thisleni = 0;
611 register EMACS_INT thisindex = 0;
612 register EMACS_INT thisindex_byte = 0;
614 this = args[argnum];
615 if (!CONSP (this))
616 thislen = Flength (this), thisleni = XINT (thislen);
618 /* Between strings of the same kind, copy fast. */
619 if (STRINGP (this) && STRINGP (val)
620 && STRING_MULTIBYTE (this) == some_multibyte)
622 EMACS_INT thislen_byte = SBYTES (this);
624 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
625 if (! NULL_INTERVAL_P (STRING_INTERVALS (this)))
627 textprops[num_textprops].argnum = argnum;
628 textprops[num_textprops].from = 0;
629 textprops[num_textprops++].to = toindex;
631 toindex_byte += thislen_byte;
632 toindex += thisleni;
634 /* Copy a single-byte string to a multibyte string. */
635 else if (STRINGP (this) && STRINGP (val))
637 if (! NULL_INTERVAL_P (STRING_INTERVALS (this)))
639 textprops[num_textprops].argnum = argnum;
640 textprops[num_textprops].from = 0;
641 textprops[num_textprops++].to = toindex;
643 toindex_byte += copy_text (SDATA (this),
644 SDATA (val) + toindex_byte,
645 SCHARS (this), 0, 1);
646 toindex += thisleni;
648 else
649 /* Copy element by element. */
650 while (1)
652 register Lisp_Object elt;
654 /* Fetch next element of `this' arg into `elt', or break if
655 `this' is exhausted. */
656 if (NILP (this)) break;
657 if (CONSP (this))
658 elt = XCAR (this), this = XCDR (this);
659 else if (thisindex >= thisleni)
660 break;
661 else if (STRINGP (this))
663 int c;
664 if (STRING_MULTIBYTE (this))
665 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
666 thisindex,
667 thisindex_byte);
668 else
670 c = SREF (this, thisindex); thisindex++;
671 if (some_multibyte && !ASCII_CHAR_P (c))
672 c = BYTE8_TO_CHAR (c);
674 XSETFASTINT (elt, c);
676 else if (BOOL_VECTOR_P (this))
678 int byte;
679 byte = XBOOL_VECTOR (this)->data[thisindex / BOOL_VECTOR_BITS_PER_CHAR];
680 if (byte & (1 << (thisindex % BOOL_VECTOR_BITS_PER_CHAR)))
681 elt = Qt;
682 else
683 elt = Qnil;
684 thisindex++;
686 else
688 elt = AREF (this, thisindex);
689 thisindex++;
692 /* Store this element into the result. */
693 if (toindex < 0)
695 XSETCAR (tail, elt);
696 prev = tail;
697 tail = XCDR (tail);
699 else if (VECTORP (val))
701 ASET (val, toindex, elt);
702 toindex++;
704 else
706 int c;
707 CHECK_CHARACTER (elt);
708 c = XFASTINT (elt);
709 if (some_multibyte)
710 toindex_byte += CHAR_STRING (c, SDATA (val) + toindex_byte);
711 else
712 SSET (val, toindex_byte++, c);
713 toindex++;
717 if (!NILP (prev))
718 XSETCDR (prev, last_tail);
720 if (num_textprops > 0)
722 Lisp_Object props;
723 EMACS_INT last_to_end = -1;
725 for (argnum = 0; argnum < num_textprops; argnum++)
727 this = args[textprops[argnum].argnum];
728 props = text_property_list (this,
729 make_number (0),
730 make_number (SCHARS (this)),
731 Qnil);
732 /* If successive arguments have properties, be sure that the
733 value of `composition' property be the copy. */
734 if (last_to_end == textprops[argnum].to)
735 make_composition_value_copy (props);
736 add_text_properties_from_list (val, props,
737 make_number (textprops[argnum].to));
738 last_to_end = textprops[argnum].to + SCHARS (this);
742 SAFE_FREE ();
743 return val;
746 static Lisp_Object string_char_byte_cache_string;
747 static EMACS_INT string_char_byte_cache_charpos;
748 static EMACS_INT string_char_byte_cache_bytepos;
750 void
751 clear_string_char_byte_cache (void)
753 string_char_byte_cache_string = Qnil;
756 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
758 EMACS_INT
759 string_char_to_byte (Lisp_Object string, EMACS_INT char_index)
761 EMACS_INT i_byte;
762 EMACS_INT best_below, best_below_byte;
763 EMACS_INT best_above, best_above_byte;
765 best_below = best_below_byte = 0;
766 best_above = SCHARS (string);
767 best_above_byte = SBYTES (string);
768 if (best_above == best_above_byte)
769 return char_index;
771 if (EQ (string, string_char_byte_cache_string))
773 if (string_char_byte_cache_charpos < char_index)
775 best_below = string_char_byte_cache_charpos;
776 best_below_byte = string_char_byte_cache_bytepos;
778 else
780 best_above = string_char_byte_cache_charpos;
781 best_above_byte = string_char_byte_cache_bytepos;
785 if (char_index - best_below < best_above - char_index)
787 unsigned char *p = SDATA (string) + best_below_byte;
789 while (best_below < char_index)
791 p += BYTES_BY_CHAR_HEAD (*p);
792 best_below++;
794 i_byte = p - SDATA (string);
796 else
798 unsigned char *p = SDATA (string) + best_above_byte;
800 while (best_above > char_index)
802 p--;
803 while (!CHAR_HEAD_P (*p)) p--;
804 best_above--;
806 i_byte = p - SDATA (string);
809 string_char_byte_cache_bytepos = i_byte;
810 string_char_byte_cache_charpos = char_index;
811 string_char_byte_cache_string = string;
813 return i_byte;
816 /* Return the character index corresponding to BYTE_INDEX in STRING. */
818 EMACS_INT
819 string_byte_to_char (Lisp_Object string, EMACS_INT byte_index)
821 EMACS_INT i, i_byte;
822 EMACS_INT best_below, best_below_byte;
823 EMACS_INT best_above, best_above_byte;
825 best_below = best_below_byte = 0;
826 best_above = SCHARS (string);
827 best_above_byte = SBYTES (string);
828 if (best_above == best_above_byte)
829 return byte_index;
831 if (EQ (string, string_char_byte_cache_string))
833 if (string_char_byte_cache_bytepos < byte_index)
835 best_below = string_char_byte_cache_charpos;
836 best_below_byte = string_char_byte_cache_bytepos;
838 else
840 best_above = string_char_byte_cache_charpos;
841 best_above_byte = string_char_byte_cache_bytepos;
845 if (byte_index - best_below_byte < best_above_byte - byte_index)
847 unsigned char *p = SDATA (string) + best_below_byte;
848 unsigned char *pend = SDATA (string) + byte_index;
850 while (p < pend)
852 p += BYTES_BY_CHAR_HEAD (*p);
853 best_below++;
855 i = best_below;
856 i_byte = p - SDATA (string);
858 else
860 unsigned char *p = SDATA (string) + best_above_byte;
861 unsigned char *pbeg = SDATA (string) + byte_index;
863 while (p > pbeg)
865 p--;
866 while (!CHAR_HEAD_P (*p)) p--;
867 best_above--;
869 i = best_above;
870 i_byte = p - SDATA (string);
873 string_char_byte_cache_bytepos = i_byte;
874 string_char_byte_cache_charpos = i;
875 string_char_byte_cache_string = string;
877 return i;
880 /* Convert STRING to a multibyte string. */
882 static Lisp_Object
883 string_make_multibyte (Lisp_Object string)
885 unsigned char *buf;
886 EMACS_INT nbytes;
887 Lisp_Object ret;
888 USE_SAFE_ALLOCA;
890 if (STRING_MULTIBYTE (string))
891 return string;
893 nbytes = count_size_as_multibyte (SDATA (string),
894 SCHARS (string));
895 /* If all the chars are ASCII, they won't need any more bytes
896 once converted. In that case, we can return STRING itself. */
897 if (nbytes == SBYTES (string))
898 return string;
900 SAFE_ALLOCA (buf, unsigned char *, nbytes);
901 copy_text (SDATA (string), buf, SBYTES (string),
902 0, 1);
904 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
905 SAFE_FREE ();
907 return ret;
911 /* Convert STRING (if unibyte) to a multibyte string without changing
912 the number of characters. Characters 0200 trough 0237 are
913 converted to eight-bit characters. */
915 Lisp_Object
916 string_to_multibyte (Lisp_Object string)
918 unsigned char *buf;
919 EMACS_INT nbytes;
920 Lisp_Object ret;
921 USE_SAFE_ALLOCA;
923 if (STRING_MULTIBYTE (string))
924 return string;
926 nbytes = count_size_as_multibyte (SDATA (string), SBYTES (string));
927 /* If all the chars are ASCII, they won't need any more bytes once
928 converted. */
929 if (nbytes == SBYTES (string))
930 return make_multibyte_string (SSDATA (string), nbytes, nbytes);
932 SAFE_ALLOCA (buf, unsigned char *, nbytes);
933 memcpy (buf, SDATA (string), SBYTES (string));
934 str_to_multibyte (buf, nbytes, SBYTES (string));
936 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
937 SAFE_FREE ();
939 return ret;
943 /* Convert STRING to a single-byte string. */
945 Lisp_Object
946 string_make_unibyte (Lisp_Object string)
948 EMACS_INT nchars;
949 unsigned char *buf;
950 Lisp_Object ret;
951 USE_SAFE_ALLOCA;
953 if (! STRING_MULTIBYTE (string))
954 return string;
956 nchars = SCHARS (string);
958 SAFE_ALLOCA (buf, unsigned char *, nchars);
959 copy_text (SDATA (string), buf, SBYTES (string),
960 1, 0);
962 ret = make_unibyte_string ((char *) buf, nchars);
963 SAFE_FREE ();
965 return ret;
968 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
969 1, 1, 0,
970 doc: /* Return the multibyte equivalent of STRING.
971 If STRING is unibyte and contains non-ASCII characters, the function
972 `unibyte-char-to-multibyte' is used to convert each unibyte character
973 to a multibyte character. In this case, the returned string is a
974 newly created string with no text properties. If STRING is multibyte
975 or entirely ASCII, it is returned unchanged. In particular, when
976 STRING is unibyte and entirely ASCII, the returned string is unibyte.
977 \(When the characters are all ASCII, Emacs primitives will treat the
978 string the same way whether it is unibyte or multibyte.) */)
979 (Lisp_Object string)
981 CHECK_STRING (string);
983 return string_make_multibyte (string);
986 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
987 1, 1, 0,
988 doc: /* Return the unibyte equivalent of STRING.
989 Multibyte character codes are converted to unibyte according to
990 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
991 If the lookup in the translation table fails, this function takes just
992 the low 8 bits of each character. */)
993 (Lisp_Object string)
995 CHECK_STRING (string);
997 return string_make_unibyte (string);
1000 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
1001 1, 1, 0,
1002 doc: /* Return a unibyte string with the same individual bytes as STRING.
1003 If STRING is unibyte, the result is STRING itself.
1004 Otherwise it is a newly created string, with no text properties.
1005 If STRING is multibyte and contains a character of charset
1006 `eight-bit', it is converted to the corresponding single byte. */)
1007 (Lisp_Object string)
1009 CHECK_STRING (string);
1011 if (STRING_MULTIBYTE (string))
1013 EMACS_INT bytes = SBYTES (string);
1014 unsigned char *str = (unsigned char *) xmalloc (bytes);
1016 memcpy (str, SDATA (string), bytes);
1017 bytes = str_as_unibyte (str, bytes);
1018 string = make_unibyte_string ((char *) str, bytes);
1019 xfree (str);
1021 return string;
1024 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1025 1, 1, 0,
1026 doc: /* Return a multibyte string with the same individual bytes as STRING.
1027 If STRING is multibyte, the result is STRING itself.
1028 Otherwise it is a newly created string, with no text properties.
1030 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1031 part of a correct utf-8 sequence), it is converted to the corresponding
1032 multibyte character of charset `eight-bit'.
1033 See also `string-to-multibyte'.
1035 Beware, this often doesn't really do what you think it does.
1036 It is similar to (decode-coding-string STRING 'utf-8-emacs).
1037 If you're not sure, whether to use `string-as-multibyte' or
1038 `string-to-multibyte', use `string-to-multibyte'. */)
1039 (Lisp_Object string)
1041 CHECK_STRING (string);
1043 if (! STRING_MULTIBYTE (string))
1045 Lisp_Object new_string;
1046 EMACS_INT nchars, nbytes;
1048 parse_str_as_multibyte (SDATA (string),
1049 SBYTES (string),
1050 &nchars, &nbytes);
1051 new_string = make_uninit_multibyte_string (nchars, nbytes);
1052 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1053 if (nbytes != SBYTES (string))
1054 str_as_multibyte (SDATA (new_string), nbytes,
1055 SBYTES (string), NULL);
1056 string = new_string;
1057 STRING_SET_INTERVALS (string, NULL_INTERVAL);
1059 return string;
1062 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1063 1, 1, 0,
1064 doc: /* Return a multibyte string with the same individual chars as STRING.
1065 If STRING is multibyte, the result is STRING itself.
1066 Otherwise it is a newly created string, with no text properties.
1068 If STRING is unibyte and contains an 8-bit byte, it is converted to
1069 the corresponding multibyte character of charset `eight-bit'.
1071 This differs from `string-as-multibyte' by converting each byte of a correct
1072 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1073 correct sequence. */)
1074 (Lisp_Object string)
1076 CHECK_STRING (string);
1078 return string_to_multibyte (string);
1081 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1082 1, 1, 0,
1083 doc: /* Return a unibyte string with the same individual chars as STRING.
1084 If STRING is unibyte, the result is STRING itself.
1085 Otherwise it is a newly created string, with no text properties,
1086 where each `eight-bit' character is converted to the corresponding byte.
1087 If STRING contains a non-ASCII, non-`eight-bit' character,
1088 an error is signaled. */)
1089 (Lisp_Object string)
1091 CHECK_STRING (string);
1093 if (STRING_MULTIBYTE (string))
1095 EMACS_INT chars = SCHARS (string);
1096 unsigned char *str = (unsigned char *) xmalloc (chars);
1097 EMACS_INT converted = str_to_unibyte (SDATA (string), str, chars, 0);
1099 if (converted < chars)
1100 error ("Can't convert the %"pI"dth character to unibyte", converted);
1101 string = make_unibyte_string ((char *) str, chars);
1102 xfree (str);
1104 return string;
1108 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1109 doc: /* Return a copy of ALIST.
1110 This is an alist which represents the same mapping from objects to objects,
1111 but does not share the alist structure with ALIST.
1112 The objects mapped (cars and cdrs of elements of the alist)
1113 are shared, however.
1114 Elements of ALIST that are not conses are also shared. */)
1115 (Lisp_Object alist)
1117 register Lisp_Object tem;
1119 CHECK_LIST (alist);
1120 if (NILP (alist))
1121 return alist;
1122 alist = concat (1, &alist, Lisp_Cons, 0);
1123 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1125 register Lisp_Object car;
1126 car = XCAR (tem);
1128 if (CONSP (car))
1129 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1131 return alist;
1134 DEFUN ("substring", Fsubstring, Ssubstring, 2, 3, 0,
1135 doc: /* Return a new string whose contents are a substring of STRING.
1136 The returned string consists of the characters between index FROM
1137 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1138 zero-indexed: 0 means the first character of STRING. Negative values
1139 are counted from the end of STRING. If TO is nil, the substring runs
1140 to the end of STRING.
1142 The STRING argument may also be a vector. In that case, the return
1143 value is a new vector that contains the elements between index FROM
1144 \(inclusive) and index TO (exclusive) of that vector argument. */)
1145 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1147 Lisp_Object res;
1148 EMACS_INT size;
1149 EMACS_INT size_byte = 0;
1150 EMACS_INT from_char, to_char;
1151 EMACS_INT from_byte = 0, to_byte = 0;
1153 CHECK_VECTOR_OR_STRING (string);
1154 CHECK_NUMBER (from);
1156 if (STRINGP (string))
1158 size = SCHARS (string);
1159 size_byte = SBYTES (string);
1161 else
1162 size = ASIZE (string);
1164 if (NILP (to))
1166 to_char = size;
1167 to_byte = size_byte;
1169 else
1171 CHECK_NUMBER (to);
1173 to_char = XINT (to);
1174 if (to_char < 0)
1175 to_char += size;
1177 if (STRINGP (string))
1178 to_byte = string_char_to_byte (string, to_char);
1181 from_char = XINT (from);
1182 if (from_char < 0)
1183 from_char += size;
1184 if (STRINGP (string))
1185 from_byte = string_char_to_byte (string, from_char);
1187 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1188 args_out_of_range_3 (string, make_number (from_char),
1189 make_number (to_char));
1191 if (STRINGP (string))
1193 res = make_specified_string (SSDATA (string) + from_byte,
1194 to_char - from_char, to_byte - from_byte,
1195 STRING_MULTIBYTE (string));
1196 copy_text_properties (make_number (from_char), make_number (to_char),
1197 string, make_number (0), res, Qnil);
1199 else
1200 res = Fvector (to_char - from_char, &AREF (string, from_char));
1202 return res;
1206 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1207 doc: /* Return a substring of STRING, without text properties.
1208 It starts at index FROM and ends before TO.
1209 TO may be nil or omitted; then the substring runs to the end of STRING.
1210 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1211 If FROM or TO is negative, it counts from the end.
1213 With one argument, just copy STRING without its properties. */)
1214 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1216 EMACS_INT size, size_byte;
1217 EMACS_INT from_char, to_char;
1218 EMACS_INT from_byte, to_byte;
1220 CHECK_STRING (string);
1222 size = SCHARS (string);
1223 size_byte = SBYTES (string);
1225 if (NILP (from))
1226 from_char = from_byte = 0;
1227 else
1229 CHECK_NUMBER (from);
1230 from_char = XINT (from);
1231 if (from_char < 0)
1232 from_char += size;
1234 from_byte = string_char_to_byte (string, from_char);
1237 if (NILP (to))
1239 to_char = size;
1240 to_byte = size_byte;
1242 else
1244 CHECK_NUMBER (to);
1246 to_char = XINT (to);
1247 if (to_char < 0)
1248 to_char += size;
1250 to_byte = string_char_to_byte (string, to_char);
1253 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1254 args_out_of_range_3 (string, make_number (from_char),
1255 make_number (to_char));
1257 return make_specified_string (SSDATA (string) + from_byte,
1258 to_char - from_char, to_byte - from_byte,
1259 STRING_MULTIBYTE (string));
1262 /* Extract a substring of STRING, giving start and end positions
1263 both in characters and in bytes. */
1265 Lisp_Object
1266 substring_both (Lisp_Object string, EMACS_INT from, EMACS_INT from_byte,
1267 EMACS_INT to, EMACS_INT to_byte)
1269 Lisp_Object res;
1270 EMACS_INT size;
1272 CHECK_VECTOR_OR_STRING (string);
1274 size = STRINGP (string) ? SCHARS (string) : ASIZE (string);
1276 if (!(0 <= from && from <= to && to <= size))
1277 args_out_of_range_3 (string, make_number (from), make_number (to));
1279 if (STRINGP (string))
1281 res = make_specified_string (SSDATA (string) + from_byte,
1282 to - from, to_byte - from_byte,
1283 STRING_MULTIBYTE (string));
1284 copy_text_properties (make_number (from), make_number (to),
1285 string, make_number (0), res, Qnil);
1287 else
1288 res = Fvector (to - from, &AREF (string, from));
1290 return res;
1293 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1294 doc: /* Take cdr N times on LIST, return the result. */)
1295 (Lisp_Object n, Lisp_Object list)
1297 EMACS_INT i, num;
1298 CHECK_NUMBER (n);
1299 num = XINT (n);
1300 for (i = 0; i < num && !NILP (list); i++)
1302 QUIT;
1303 CHECK_LIST_CONS (list, list);
1304 list = XCDR (list);
1306 return list;
1309 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1310 doc: /* Return the Nth element of LIST.
1311 N counts from zero. If LIST is not that long, nil is returned. */)
1312 (Lisp_Object n, Lisp_Object list)
1314 return Fcar (Fnthcdr (n, list));
1317 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1318 doc: /* Return element of SEQUENCE at index N. */)
1319 (register Lisp_Object sequence, Lisp_Object n)
1321 CHECK_NUMBER (n);
1322 if (CONSP (sequence) || NILP (sequence))
1323 return Fcar (Fnthcdr (n, sequence));
1325 /* Faref signals a "not array" error, so check here. */
1326 CHECK_ARRAY (sequence, Qsequencep);
1327 return Faref (sequence, n);
1330 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1331 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1332 The value is actually the tail of LIST whose car is ELT. */)
1333 (register Lisp_Object elt, Lisp_Object list)
1335 register Lisp_Object tail;
1336 for (tail = list; CONSP (tail); tail = XCDR (tail))
1338 register Lisp_Object tem;
1339 CHECK_LIST_CONS (tail, list);
1340 tem = XCAR (tail);
1341 if (! NILP (Fequal (elt, tem)))
1342 return tail;
1343 QUIT;
1345 return Qnil;
1348 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1349 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1350 The value is actually the tail of LIST whose car is ELT. */)
1351 (register Lisp_Object elt, Lisp_Object list)
1353 while (1)
1355 if (!CONSP (list) || EQ (XCAR (list), elt))
1356 break;
1358 list = XCDR (list);
1359 if (!CONSP (list) || EQ (XCAR (list), elt))
1360 break;
1362 list = XCDR (list);
1363 if (!CONSP (list) || EQ (XCAR (list), elt))
1364 break;
1366 list = XCDR (list);
1367 QUIT;
1370 CHECK_LIST (list);
1371 return list;
1374 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1375 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1376 The value is actually the tail of LIST whose car is ELT. */)
1377 (register Lisp_Object elt, Lisp_Object list)
1379 register Lisp_Object tail;
1381 if (!FLOATP (elt))
1382 return Fmemq (elt, list);
1384 for (tail = list; CONSP (tail); tail = XCDR (tail))
1386 register Lisp_Object tem;
1387 CHECK_LIST_CONS (tail, list);
1388 tem = XCAR (tail);
1389 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0))
1390 return tail;
1391 QUIT;
1393 return Qnil;
1396 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1397 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1398 The value is actually the first element of LIST whose car is KEY.
1399 Elements of LIST that are not conses are ignored. */)
1400 (Lisp_Object key, Lisp_Object list)
1402 while (1)
1404 if (!CONSP (list)
1405 || (CONSP (XCAR (list))
1406 && EQ (XCAR (XCAR (list)), key)))
1407 break;
1409 list = XCDR (list);
1410 if (!CONSP (list)
1411 || (CONSP (XCAR (list))
1412 && EQ (XCAR (XCAR (list)), key)))
1413 break;
1415 list = XCDR (list);
1416 if (!CONSP (list)
1417 || (CONSP (XCAR (list))
1418 && EQ (XCAR (XCAR (list)), key)))
1419 break;
1421 list = XCDR (list);
1422 QUIT;
1425 return CAR (list);
1428 /* Like Fassq but never report an error and do not allow quits.
1429 Use only on lists known never to be circular. */
1431 Lisp_Object
1432 assq_no_quit (Lisp_Object key, Lisp_Object list)
1434 while (CONSP (list)
1435 && (!CONSP (XCAR (list))
1436 || !EQ (XCAR (XCAR (list)), key)))
1437 list = XCDR (list);
1439 return CAR_SAFE (list);
1442 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1443 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1444 The value is actually the first element of LIST whose car equals KEY. */)
1445 (Lisp_Object key, Lisp_Object list)
1447 Lisp_Object car;
1449 while (1)
1451 if (!CONSP (list)
1452 || (CONSP (XCAR (list))
1453 && (car = XCAR (XCAR (list)),
1454 EQ (car, key) || !NILP (Fequal (car, key)))))
1455 break;
1457 list = XCDR (list);
1458 if (!CONSP (list)
1459 || (CONSP (XCAR (list))
1460 && (car = XCAR (XCAR (list)),
1461 EQ (car, key) || !NILP (Fequal (car, key)))))
1462 break;
1464 list = XCDR (list);
1465 if (!CONSP (list)
1466 || (CONSP (XCAR (list))
1467 && (car = XCAR (XCAR (list)),
1468 EQ (car, key) || !NILP (Fequal (car, key)))))
1469 break;
1471 list = XCDR (list);
1472 QUIT;
1475 return CAR (list);
1478 /* Like Fassoc but never report an error and do not allow quits.
1479 Use only on lists known never to be circular. */
1481 Lisp_Object
1482 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1484 while (CONSP (list)
1485 && (!CONSP (XCAR (list))
1486 || (!EQ (XCAR (XCAR (list)), key)
1487 && NILP (Fequal (XCAR (XCAR (list)), key)))))
1488 list = XCDR (list);
1490 return CONSP (list) ? XCAR (list) : Qnil;
1493 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1494 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1495 The value is actually the first element of LIST whose cdr is KEY. */)
1496 (register Lisp_Object key, Lisp_Object list)
1498 while (1)
1500 if (!CONSP (list)
1501 || (CONSP (XCAR (list))
1502 && EQ (XCDR (XCAR (list)), key)))
1503 break;
1505 list = XCDR (list);
1506 if (!CONSP (list)
1507 || (CONSP (XCAR (list))
1508 && EQ (XCDR (XCAR (list)), key)))
1509 break;
1511 list = XCDR (list);
1512 if (!CONSP (list)
1513 || (CONSP (XCAR (list))
1514 && EQ (XCDR (XCAR (list)), key)))
1515 break;
1517 list = XCDR (list);
1518 QUIT;
1521 return CAR (list);
1524 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1525 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1526 The value is actually the first element of LIST whose cdr equals KEY. */)
1527 (Lisp_Object key, Lisp_Object list)
1529 Lisp_Object cdr;
1531 while (1)
1533 if (!CONSP (list)
1534 || (CONSP (XCAR (list))
1535 && (cdr = XCDR (XCAR (list)),
1536 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1537 break;
1539 list = XCDR (list);
1540 if (!CONSP (list)
1541 || (CONSP (XCAR (list))
1542 && (cdr = XCDR (XCAR (list)),
1543 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1544 break;
1546 list = XCDR (list);
1547 if (!CONSP (list)
1548 || (CONSP (XCAR (list))
1549 && (cdr = XCDR (XCAR (list)),
1550 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1551 break;
1553 list = XCDR (list);
1554 QUIT;
1557 return CAR (list);
1560 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1561 doc: /* Delete by side effect any occurrences of ELT as a member of LIST.
1562 The modified LIST is returned. Comparison is done with `eq'.
1563 If the first member of LIST is ELT, there is no way to remove it by side effect;
1564 therefore, write `(setq foo (delq element foo))'
1565 to be sure of changing the value of `foo'. */)
1566 (register Lisp_Object elt, Lisp_Object list)
1568 register Lisp_Object tail, prev;
1569 register Lisp_Object tem;
1571 tail = list;
1572 prev = Qnil;
1573 while (!NILP (tail))
1575 CHECK_LIST_CONS (tail, list);
1576 tem = XCAR (tail);
1577 if (EQ (elt, tem))
1579 if (NILP (prev))
1580 list = XCDR (tail);
1581 else
1582 Fsetcdr (prev, XCDR (tail));
1584 else
1585 prev = tail;
1586 tail = XCDR (tail);
1587 QUIT;
1589 return list;
1592 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1593 doc: /* Delete by side effect any occurrences of ELT as a member of SEQ.
1594 SEQ must be a list, a vector, or a string.
1595 The modified SEQ is returned. Comparison is done with `equal'.
1596 If SEQ is not a list, or the first member of SEQ is ELT, deleting it
1597 is not a side effect; it is simply using a different sequence.
1598 Therefore, write `(setq foo (delete element foo))'
1599 to be sure of changing the value of `foo'. */)
1600 (Lisp_Object elt, Lisp_Object seq)
1602 if (VECTORP (seq))
1604 EMACS_INT i, n;
1606 for (i = n = 0; i < ASIZE (seq); ++i)
1607 if (NILP (Fequal (AREF (seq, i), elt)))
1608 ++n;
1610 if (n != ASIZE (seq))
1612 struct Lisp_Vector *p = allocate_vector (n);
1614 for (i = n = 0; i < ASIZE (seq); ++i)
1615 if (NILP (Fequal (AREF (seq, i), elt)))
1616 p->contents[n++] = AREF (seq, i);
1618 XSETVECTOR (seq, p);
1621 else if (STRINGP (seq))
1623 EMACS_INT i, ibyte, nchars, nbytes, cbytes;
1624 int c;
1626 for (i = nchars = nbytes = ibyte = 0;
1627 i < SCHARS (seq);
1628 ++i, ibyte += cbytes)
1630 if (STRING_MULTIBYTE (seq))
1632 c = STRING_CHAR (SDATA (seq) + ibyte);
1633 cbytes = CHAR_BYTES (c);
1635 else
1637 c = SREF (seq, i);
1638 cbytes = 1;
1641 if (!INTEGERP (elt) || c != XINT (elt))
1643 ++nchars;
1644 nbytes += cbytes;
1648 if (nchars != SCHARS (seq))
1650 Lisp_Object tem;
1652 tem = make_uninit_multibyte_string (nchars, nbytes);
1653 if (!STRING_MULTIBYTE (seq))
1654 STRING_SET_UNIBYTE (tem);
1656 for (i = nchars = nbytes = ibyte = 0;
1657 i < SCHARS (seq);
1658 ++i, ibyte += cbytes)
1660 if (STRING_MULTIBYTE (seq))
1662 c = STRING_CHAR (SDATA (seq) + ibyte);
1663 cbytes = CHAR_BYTES (c);
1665 else
1667 c = SREF (seq, i);
1668 cbytes = 1;
1671 if (!INTEGERP (elt) || c != XINT (elt))
1673 unsigned char *from = SDATA (seq) + ibyte;
1674 unsigned char *to = SDATA (tem) + nbytes;
1675 EMACS_INT n;
1677 ++nchars;
1678 nbytes += cbytes;
1680 for (n = cbytes; n--; )
1681 *to++ = *from++;
1685 seq = tem;
1688 else
1690 Lisp_Object tail, prev;
1692 for (tail = seq, prev = Qnil; CONSP (tail); tail = XCDR (tail))
1694 CHECK_LIST_CONS (tail, seq);
1696 if (!NILP (Fequal (elt, XCAR (tail))))
1698 if (NILP (prev))
1699 seq = XCDR (tail);
1700 else
1701 Fsetcdr (prev, XCDR (tail));
1703 else
1704 prev = tail;
1705 QUIT;
1709 return seq;
1712 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1713 doc: /* Reverse LIST by modifying cdr pointers.
1714 Return the reversed list. */)
1715 (Lisp_Object list)
1717 register Lisp_Object prev, tail, next;
1719 if (NILP (list)) return list;
1720 prev = Qnil;
1721 tail = list;
1722 while (!NILP (tail))
1724 QUIT;
1725 CHECK_LIST_CONS (tail, list);
1726 next = XCDR (tail);
1727 Fsetcdr (tail, prev);
1728 prev = tail;
1729 tail = next;
1731 return prev;
1734 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1735 doc: /* Reverse LIST, copying. Return the reversed list.
1736 See also the function `nreverse', which is used more often. */)
1737 (Lisp_Object list)
1739 Lisp_Object new;
1741 for (new = Qnil; CONSP (list); list = XCDR (list))
1743 QUIT;
1744 new = Fcons (XCAR (list), new);
1746 CHECK_LIST_END (list, list);
1747 return new;
1750 Lisp_Object merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred);
1752 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
1753 doc: /* Sort LIST, stably, comparing elements using PREDICATE.
1754 Returns the sorted list. LIST is modified by side effects.
1755 PREDICATE is called with two elements of LIST, and should return non-nil
1756 if the first element should sort before the second. */)
1757 (Lisp_Object list, Lisp_Object predicate)
1759 Lisp_Object front, back;
1760 register Lisp_Object len, tem;
1761 struct gcpro gcpro1, gcpro2;
1762 EMACS_INT length;
1764 front = list;
1765 len = Flength (list);
1766 length = XINT (len);
1767 if (length < 2)
1768 return list;
1770 XSETINT (len, (length / 2) - 1);
1771 tem = Fnthcdr (len, list);
1772 back = Fcdr (tem);
1773 Fsetcdr (tem, Qnil);
1775 GCPRO2 (front, back);
1776 front = Fsort (front, predicate);
1777 back = Fsort (back, predicate);
1778 UNGCPRO;
1779 return merge (front, back, predicate);
1782 Lisp_Object
1783 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
1785 Lisp_Object value;
1786 register Lisp_Object tail;
1787 Lisp_Object tem;
1788 register Lisp_Object l1, l2;
1789 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1791 l1 = org_l1;
1792 l2 = org_l2;
1793 tail = Qnil;
1794 value = Qnil;
1796 /* It is sufficient to protect org_l1 and org_l2.
1797 When l1 and l2 are updated, we copy the new values
1798 back into the org_ vars. */
1799 GCPRO4 (org_l1, org_l2, pred, value);
1801 while (1)
1803 if (NILP (l1))
1805 UNGCPRO;
1806 if (NILP (tail))
1807 return l2;
1808 Fsetcdr (tail, l2);
1809 return value;
1811 if (NILP (l2))
1813 UNGCPRO;
1814 if (NILP (tail))
1815 return l1;
1816 Fsetcdr (tail, l1);
1817 return value;
1819 tem = call2 (pred, Fcar (l2), Fcar (l1));
1820 if (NILP (tem))
1822 tem = l1;
1823 l1 = Fcdr (l1);
1824 org_l1 = l1;
1826 else
1828 tem = l2;
1829 l2 = Fcdr (l2);
1830 org_l2 = l2;
1832 if (NILP (tail))
1833 value = tem;
1834 else
1835 Fsetcdr (tail, tem);
1836 tail = tem;
1841 /* This does not check for quits. That is safe since it must terminate. */
1843 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
1844 doc: /* Extract a value from a property list.
1845 PLIST is a property list, which is a list of the form
1846 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1847 corresponding to the given PROP, or nil if PROP is not one of the
1848 properties on the list. This function never signals an error. */)
1849 (Lisp_Object plist, Lisp_Object prop)
1851 Lisp_Object tail, halftail;
1853 /* halftail is used to detect circular lists. */
1854 tail = halftail = plist;
1855 while (CONSP (tail) && CONSP (XCDR (tail)))
1857 if (EQ (prop, XCAR (tail)))
1858 return XCAR (XCDR (tail));
1860 tail = XCDR (XCDR (tail));
1861 halftail = XCDR (halftail);
1862 if (EQ (tail, halftail))
1863 break;
1865 #if 0 /* Unsafe version. */
1866 /* This function can be called asynchronously
1867 (setup_coding_system). Don't QUIT in that case. */
1868 if (!interrupt_input_blocked)
1869 QUIT;
1870 #endif
1873 return Qnil;
1876 DEFUN ("get", Fget, Sget, 2, 2, 0,
1877 doc: /* Return the value of SYMBOL's PROPNAME property.
1878 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
1879 (Lisp_Object symbol, Lisp_Object propname)
1881 CHECK_SYMBOL (symbol);
1882 return Fplist_get (XSYMBOL (symbol)->plist, propname);
1885 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
1886 doc: /* Change value in PLIST of PROP to VAL.
1887 PLIST is a property list, which is a list of the form
1888 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
1889 If PROP is already a property on the list, its value is set to VAL,
1890 otherwise the new PROP VAL pair is added. The new plist is returned;
1891 use `(setq x (plist-put x prop val))' to be sure to use the new value.
1892 The PLIST is modified by side effects. */)
1893 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1895 register Lisp_Object tail, prev;
1896 Lisp_Object newcell;
1897 prev = Qnil;
1898 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1899 tail = XCDR (XCDR (tail)))
1901 if (EQ (prop, XCAR (tail)))
1903 Fsetcar (XCDR (tail), val);
1904 return plist;
1907 prev = tail;
1908 QUIT;
1910 newcell = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
1911 if (NILP (prev))
1912 return newcell;
1913 else
1914 Fsetcdr (XCDR (prev), newcell);
1915 return plist;
1918 DEFUN ("put", Fput, Sput, 3, 3, 0,
1919 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
1920 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
1921 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
1923 CHECK_SYMBOL (symbol);
1924 XSYMBOL (symbol)->plist
1925 = Fplist_put (XSYMBOL (symbol)->plist, propname, value);
1926 return value;
1929 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
1930 doc: /* Extract a value from a property list, comparing with `equal'.
1931 PLIST is a property list, which is a list of the form
1932 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1933 corresponding to the given PROP, or nil if PROP is not
1934 one of the properties on the list. */)
1935 (Lisp_Object plist, Lisp_Object prop)
1937 Lisp_Object tail;
1939 for (tail = plist;
1940 CONSP (tail) && CONSP (XCDR (tail));
1941 tail = XCDR (XCDR (tail)))
1943 if (! NILP (Fequal (prop, XCAR (tail))))
1944 return XCAR (XCDR (tail));
1946 QUIT;
1949 CHECK_LIST_END (tail, prop);
1951 return Qnil;
1954 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
1955 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
1956 PLIST is a property list, which is a list of the form
1957 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
1958 If PROP is already a property on the list, its value is set to VAL,
1959 otherwise the new PROP VAL pair is added. The new plist is returned;
1960 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
1961 The PLIST is modified by side effects. */)
1962 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1964 register Lisp_Object tail, prev;
1965 Lisp_Object newcell;
1966 prev = Qnil;
1967 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1968 tail = XCDR (XCDR (tail)))
1970 if (! NILP (Fequal (prop, XCAR (tail))))
1972 Fsetcar (XCDR (tail), val);
1973 return plist;
1976 prev = tail;
1977 QUIT;
1979 newcell = Fcons (prop, Fcons (val, Qnil));
1980 if (NILP (prev))
1981 return newcell;
1982 else
1983 Fsetcdr (XCDR (prev), newcell);
1984 return plist;
1987 DEFUN ("eql", Feql, Seql, 2, 2, 0,
1988 doc: /* Return t if the two args are the same Lisp object.
1989 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
1990 (Lisp_Object obj1, Lisp_Object obj2)
1992 if (FLOATP (obj1))
1993 return internal_equal (obj1, obj2, 0, 0) ? Qt : Qnil;
1994 else
1995 return EQ (obj1, obj2) ? Qt : Qnil;
1998 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
1999 doc: /* Return t if two Lisp objects have similar structure and contents.
2000 They must have the same data type.
2001 Conses are compared by comparing the cars and the cdrs.
2002 Vectors and strings are compared element by element.
2003 Numbers are compared by value, but integers cannot equal floats.
2004 (Use `=' if you want integers and floats to be able to be equal.)
2005 Symbols must match exactly. */)
2006 (register Lisp_Object o1, Lisp_Object o2)
2008 return internal_equal (o1, o2, 0, 0) ? Qt : Qnil;
2011 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
2012 doc: /* Return t if two Lisp objects have similar structure and contents.
2013 This is like `equal' except that it compares the text properties
2014 of strings. (`equal' ignores text properties.) */)
2015 (register Lisp_Object o1, Lisp_Object o2)
2017 return internal_equal (o1, o2, 0, 1) ? Qt : Qnil;
2020 /* DEPTH is current depth of recursion. Signal an error if it
2021 gets too deep.
2022 PROPS, if non-nil, means compare string text properties too. */
2024 static int
2025 internal_equal (register Lisp_Object o1, register Lisp_Object o2, int depth, int props)
2027 if (depth > 200)
2028 error ("Stack overflow in equal");
2030 tail_recurse:
2031 QUIT;
2032 if (EQ (o1, o2))
2033 return 1;
2034 if (XTYPE (o1) != XTYPE (o2))
2035 return 0;
2037 switch (XTYPE (o1))
2039 case Lisp_Float:
2041 double d1, d2;
2043 d1 = extract_float (o1);
2044 d2 = extract_float (o2);
2045 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2046 though they are not =. */
2047 return d1 == d2 || (d1 != d1 && d2 != d2);
2050 case Lisp_Cons:
2051 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1, props))
2052 return 0;
2053 o1 = XCDR (o1);
2054 o2 = XCDR (o2);
2055 goto tail_recurse;
2057 case Lisp_Misc:
2058 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2059 return 0;
2060 if (OVERLAYP (o1))
2062 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2063 depth + 1, props)
2064 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2065 depth + 1, props))
2066 return 0;
2067 o1 = XOVERLAY (o1)->plist;
2068 o2 = XOVERLAY (o2)->plist;
2069 goto tail_recurse;
2071 if (MARKERP (o1))
2073 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2074 && (XMARKER (o1)->buffer == 0
2075 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2077 break;
2079 case Lisp_Vectorlike:
2081 register int i;
2082 EMACS_INT size = ASIZE (o1);
2083 /* Pseudovectors have the type encoded in the size field, so this test
2084 actually checks that the objects have the same type as well as the
2085 same size. */
2086 if (ASIZE (o2) != size)
2087 return 0;
2088 /* Boolvectors are compared much like strings. */
2089 if (BOOL_VECTOR_P (o1))
2091 if (XBOOL_VECTOR (o1)->size != XBOOL_VECTOR (o2)->size)
2092 return 0;
2093 if (memcmp (XBOOL_VECTOR (o1)->data, XBOOL_VECTOR (o2)->data,
2094 ((XBOOL_VECTOR (o1)->size
2095 + BOOL_VECTOR_BITS_PER_CHAR - 1)
2096 / BOOL_VECTOR_BITS_PER_CHAR)))
2097 return 0;
2098 return 1;
2100 if (WINDOW_CONFIGURATIONP (o1))
2101 return compare_window_configurations (o1, o2, 0);
2103 /* Aside from them, only true vectors, char-tables, compiled
2104 functions, and fonts (font-spec, font-entity, font-object)
2105 are sensible to compare, so eliminate the others now. */
2106 if (size & PSEUDOVECTOR_FLAG)
2108 if (!(size & (PVEC_COMPILED
2109 | PVEC_CHAR_TABLE | PVEC_SUB_CHAR_TABLE | PVEC_FONT)))
2110 return 0;
2111 size &= PSEUDOVECTOR_SIZE_MASK;
2113 for (i = 0; i < size; i++)
2115 Lisp_Object v1, v2;
2116 v1 = AREF (o1, i);
2117 v2 = AREF (o2, i);
2118 if (!internal_equal (v1, v2, depth + 1, props))
2119 return 0;
2121 return 1;
2123 break;
2125 case Lisp_String:
2126 if (SCHARS (o1) != SCHARS (o2))
2127 return 0;
2128 if (SBYTES (o1) != SBYTES (o2))
2129 return 0;
2130 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2131 return 0;
2132 if (props && !compare_string_intervals (o1, o2))
2133 return 0;
2134 return 1;
2136 default:
2137 break;
2140 return 0;
2144 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2145 doc: /* Store each element of ARRAY with ITEM.
2146 ARRAY is a vector, string, char-table, or bool-vector. */)
2147 (Lisp_Object array, Lisp_Object item)
2149 register EMACS_INT size, idx;
2151 if (VECTORP (array))
2153 register Lisp_Object *p = XVECTOR (array)->contents;
2154 size = ASIZE (array);
2155 for (idx = 0; idx < size; idx++)
2156 p[idx] = item;
2158 else if (CHAR_TABLE_P (array))
2160 int i;
2162 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2163 XCHAR_TABLE (array)->contents[i] = item;
2164 XCHAR_TABLE (array)->defalt = item;
2166 else if (STRINGP (array))
2168 register unsigned char *p = SDATA (array);
2169 int charval;
2170 CHECK_CHARACTER (item);
2171 charval = XFASTINT (item);
2172 size = SCHARS (array);
2173 if (STRING_MULTIBYTE (array))
2175 unsigned char str[MAX_MULTIBYTE_LENGTH];
2176 int len = CHAR_STRING (charval, str);
2177 EMACS_INT size_byte = SBYTES (array);
2179 if (INT_MULTIPLY_OVERFLOW (SCHARS (array), len)
2180 || SCHARS (array) * len != size_byte)
2181 error ("Attempt to change byte length of a string");
2182 for (idx = 0; idx < size_byte; idx++)
2183 *p++ = str[idx % len];
2185 else
2186 for (idx = 0; idx < size; idx++)
2187 p[idx] = charval;
2189 else if (BOOL_VECTOR_P (array))
2191 register unsigned char *p = XBOOL_VECTOR (array)->data;
2192 EMACS_INT size_in_chars;
2193 size = XBOOL_VECTOR (array)->size;
2194 size_in_chars
2195 = ((size + BOOL_VECTOR_BITS_PER_CHAR - 1)
2196 / BOOL_VECTOR_BITS_PER_CHAR);
2198 if (size_in_chars)
2200 memset (p, ! NILP (item) ? -1 : 0, size_in_chars);
2202 /* Clear any extraneous bits in the last byte. */
2203 p[size_in_chars - 1] &= (1 << (size % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2206 else
2207 wrong_type_argument (Qarrayp, array);
2208 return array;
2211 DEFUN ("clear-string", Fclear_string, Sclear_string,
2212 1, 1, 0,
2213 doc: /* Clear the contents of STRING.
2214 This makes STRING unibyte and may change its length. */)
2215 (Lisp_Object string)
2217 EMACS_INT len;
2218 CHECK_STRING (string);
2219 len = SBYTES (string);
2220 memset (SDATA (string), 0, len);
2221 STRING_SET_CHARS (string, len);
2222 STRING_SET_UNIBYTE (string);
2223 return Qnil;
2226 /* ARGSUSED */
2227 Lisp_Object
2228 nconc2 (Lisp_Object s1, Lisp_Object s2)
2230 Lisp_Object args[2];
2231 args[0] = s1;
2232 args[1] = s2;
2233 return Fnconc (2, args);
2236 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2237 doc: /* Concatenate any number of lists by altering them.
2238 Only the last argument is not altered, and need not be a list.
2239 usage: (nconc &rest LISTS) */)
2240 (ptrdiff_t nargs, Lisp_Object *args)
2242 ptrdiff_t argnum;
2243 register Lisp_Object tail, tem, val;
2245 val = tail = Qnil;
2247 for (argnum = 0; argnum < nargs; argnum++)
2249 tem = args[argnum];
2250 if (NILP (tem)) continue;
2252 if (NILP (val))
2253 val = tem;
2255 if (argnum + 1 == nargs) break;
2257 CHECK_LIST_CONS (tem, tem);
2259 while (CONSP (tem))
2261 tail = tem;
2262 tem = XCDR (tail);
2263 QUIT;
2266 tem = args[argnum + 1];
2267 Fsetcdr (tail, tem);
2268 if (NILP (tem))
2269 args[argnum + 1] = tail;
2272 return val;
2275 /* This is the guts of all mapping functions.
2276 Apply FN to each element of SEQ, one by one,
2277 storing the results into elements of VALS, a C vector of Lisp_Objects.
2278 LENI is the length of VALS, which should also be the length of SEQ. */
2280 static void
2281 mapcar1 (EMACS_INT leni, Lisp_Object *vals, Lisp_Object fn, Lisp_Object seq)
2283 register Lisp_Object tail;
2284 Lisp_Object dummy;
2285 register EMACS_INT i;
2286 struct gcpro gcpro1, gcpro2, gcpro3;
2288 if (vals)
2290 /* Don't let vals contain any garbage when GC happens. */
2291 for (i = 0; i < leni; i++)
2292 vals[i] = Qnil;
2294 GCPRO3 (dummy, fn, seq);
2295 gcpro1.var = vals;
2296 gcpro1.nvars = leni;
2298 else
2299 GCPRO2 (fn, seq);
2300 /* We need not explicitly protect `tail' because it is used only on lists, and
2301 1) lists are not relocated and 2) the list is marked via `seq' so will not
2302 be freed */
2304 if (VECTORP (seq) || COMPILEDP (seq))
2306 for (i = 0; i < leni; i++)
2308 dummy = call1 (fn, AREF (seq, i));
2309 if (vals)
2310 vals[i] = dummy;
2313 else if (BOOL_VECTOR_P (seq))
2315 for (i = 0; i < leni; i++)
2317 unsigned char byte;
2318 byte = XBOOL_VECTOR (seq)->data[i / BOOL_VECTOR_BITS_PER_CHAR];
2319 dummy = (byte & (1 << (i % BOOL_VECTOR_BITS_PER_CHAR))) ? Qt : Qnil;
2320 dummy = call1 (fn, dummy);
2321 if (vals)
2322 vals[i] = dummy;
2325 else if (STRINGP (seq))
2327 EMACS_INT i_byte;
2329 for (i = 0, i_byte = 0; i < leni;)
2331 int c;
2332 EMACS_INT i_before = i;
2334 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2335 XSETFASTINT (dummy, c);
2336 dummy = call1 (fn, dummy);
2337 if (vals)
2338 vals[i_before] = dummy;
2341 else /* Must be a list, since Flength did not get an error */
2343 tail = seq;
2344 for (i = 0; i < leni && CONSP (tail); i++)
2346 dummy = call1 (fn, XCAR (tail));
2347 if (vals)
2348 vals[i] = dummy;
2349 tail = XCDR (tail);
2353 UNGCPRO;
2356 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2357 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2358 In between each pair of results, stick in SEPARATOR. Thus, " " as
2359 SEPARATOR results in spaces between the values returned by FUNCTION.
2360 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2361 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2363 Lisp_Object len;
2364 register EMACS_INT leni;
2365 ptrdiff_t i, nargs;
2366 register Lisp_Object *args;
2367 struct gcpro gcpro1;
2368 Lisp_Object ret;
2369 USE_SAFE_ALLOCA;
2371 len = Flength (sequence);
2372 if (CHAR_TABLE_P (sequence))
2373 wrong_type_argument (Qlistp, sequence);
2374 leni = XINT (len);
2375 nargs = leni + leni - 1;
2376 if (nargs < 0) return empty_unibyte_string;
2378 SAFE_ALLOCA_LISP (args, nargs);
2380 GCPRO1 (separator);
2381 mapcar1 (leni, args, function, sequence);
2382 UNGCPRO;
2384 for (i = leni - 1; i > 0; i--)
2385 args[i + i] = args[i];
2387 for (i = 1; i < nargs; i += 2)
2388 args[i] = separator;
2390 ret = Fconcat (nargs, args);
2391 SAFE_FREE ();
2393 return ret;
2396 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2397 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2398 The result is a list just as long as SEQUENCE.
2399 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2400 (Lisp_Object function, Lisp_Object sequence)
2402 register Lisp_Object len;
2403 register EMACS_INT leni;
2404 register Lisp_Object *args;
2405 Lisp_Object ret;
2406 USE_SAFE_ALLOCA;
2408 len = Flength (sequence);
2409 if (CHAR_TABLE_P (sequence))
2410 wrong_type_argument (Qlistp, sequence);
2411 leni = XFASTINT (len);
2413 SAFE_ALLOCA_LISP (args, leni);
2415 mapcar1 (leni, args, function, sequence);
2417 ret = Flist (leni, args);
2418 SAFE_FREE ();
2420 return ret;
2423 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2424 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2425 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2426 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2427 (Lisp_Object function, Lisp_Object sequence)
2429 register EMACS_INT leni;
2431 leni = XFASTINT (Flength (sequence));
2432 if (CHAR_TABLE_P (sequence))
2433 wrong_type_argument (Qlistp, sequence);
2434 mapcar1 (leni, 0, function, sequence);
2436 return sequence;
2439 /* This is how C code calls `yes-or-no-p' and allows the user
2440 to redefined it.
2442 Anything that calls this function must protect from GC! */
2444 Lisp_Object
2445 do_yes_or_no_p (Lisp_Object prompt)
2447 return call1 (intern ("yes-or-no-p"), prompt);
2450 /* Anything that calls this function must protect from GC! */
2452 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2453 doc: /* Ask user a yes-or-no question. Return t if answer is yes.
2454 PROMPT is the string to display to ask the question. It should end in
2455 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2457 The user must confirm the answer with RET, and can edit it until it
2458 has been confirmed.
2460 Under a windowing system a dialog box will be used if `last-nonmenu-event'
2461 is nil, and `use-dialog-box' is non-nil. */)
2462 (Lisp_Object prompt)
2464 register Lisp_Object ans;
2465 Lisp_Object args[2];
2466 struct gcpro gcpro1;
2468 CHECK_STRING (prompt);
2470 #ifdef HAVE_MENUS
2471 if (FRAME_WINDOW_P (SELECTED_FRAME ())
2472 && (NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2473 && use_dialog_box
2474 && have_menus_p ())
2476 Lisp_Object pane, menu, obj;
2477 redisplay_preserve_echo_area (4);
2478 pane = Fcons (Fcons (build_string ("Yes"), Qt),
2479 Fcons (Fcons (build_string ("No"), Qnil),
2480 Qnil));
2481 GCPRO1 (pane);
2482 menu = Fcons (prompt, pane);
2483 obj = Fx_popup_dialog (Qt, menu, Qnil);
2484 UNGCPRO;
2485 return obj;
2487 #endif /* HAVE_MENUS */
2489 args[0] = prompt;
2490 args[1] = build_string ("(yes or no) ");
2491 prompt = Fconcat (2, args);
2493 GCPRO1 (prompt);
2495 while (1)
2497 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2498 Qyes_or_no_p_history, Qnil,
2499 Qnil));
2500 if (SCHARS (ans) == 3 && !strcmp (SSDATA (ans), "yes"))
2502 UNGCPRO;
2503 return Qt;
2505 if (SCHARS (ans) == 2 && !strcmp (SSDATA (ans), "no"))
2507 UNGCPRO;
2508 return Qnil;
2511 Fding (Qnil);
2512 Fdiscard_input ();
2513 message ("Please answer yes or no.");
2514 Fsleep_for (make_number (2), Qnil);
2518 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2519 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2521 Each of the three load averages is multiplied by 100, then converted
2522 to integer.
2524 When USE-FLOATS is non-nil, floats will be used instead of integers.
2525 These floats are not multiplied by 100.
2527 If the 5-minute or 15-minute load averages are not available, return a
2528 shortened list, containing only those averages which are available.
2530 An error is thrown if the load average can't be obtained. In some
2531 cases making it work would require Emacs being installed setuid or
2532 setgid so that it can read kernel information, and that usually isn't
2533 advisable. */)
2534 (Lisp_Object use_floats)
2536 double load_ave[3];
2537 int loads = getloadavg (load_ave, 3);
2538 Lisp_Object ret = Qnil;
2540 if (loads < 0)
2541 error ("load-average not implemented for this operating system");
2543 while (loads-- > 0)
2545 Lisp_Object load = (NILP (use_floats)
2546 ? make_number (100.0 * load_ave[loads])
2547 : make_float (load_ave[loads]));
2548 ret = Fcons (load, ret);
2551 return ret;
2554 static Lisp_Object Qsubfeatures;
2556 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2557 doc: /* Return t if FEATURE is present in this Emacs.
2559 Use this to conditionalize execution of lisp code based on the
2560 presence or absence of Emacs or environment extensions.
2561 Use `provide' to declare that a feature is available. This function
2562 looks at the value of the variable `features'. The optional argument
2563 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2564 (Lisp_Object feature, Lisp_Object subfeature)
2566 register Lisp_Object tem;
2567 CHECK_SYMBOL (feature);
2568 tem = Fmemq (feature, Vfeatures);
2569 if (!NILP (tem) && !NILP (subfeature))
2570 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2571 return (NILP (tem)) ? Qnil : Qt;
2574 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2575 doc: /* Announce that FEATURE is a feature of the current Emacs.
2576 The optional argument SUBFEATURES should be a list of symbols listing
2577 particular subfeatures supported in this version of FEATURE. */)
2578 (Lisp_Object feature, Lisp_Object subfeatures)
2580 register Lisp_Object tem;
2581 CHECK_SYMBOL (feature);
2582 CHECK_LIST (subfeatures);
2583 if (!NILP (Vautoload_queue))
2584 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2585 Vautoload_queue);
2586 tem = Fmemq (feature, Vfeatures);
2587 if (NILP (tem))
2588 Vfeatures = Fcons (feature, Vfeatures);
2589 if (!NILP (subfeatures))
2590 Fput (feature, Qsubfeatures, subfeatures);
2591 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2593 /* Run any load-hooks for this file. */
2594 tem = Fassq (feature, Vafter_load_alist);
2595 if (CONSP (tem))
2596 Fprogn (XCDR (tem));
2598 return feature;
2601 /* `require' and its subroutines. */
2603 /* List of features currently being require'd, innermost first. */
2605 static Lisp_Object require_nesting_list;
2607 static Lisp_Object
2608 require_unwind (Lisp_Object old_value)
2610 return require_nesting_list = old_value;
2613 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2614 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2615 If FEATURE is not a member of the list `features', then the feature
2616 is not loaded; so load the file FILENAME.
2617 If FILENAME is omitted, the printname of FEATURE is used as the file name,
2618 and `load' will try to load this name appended with the suffix `.elc' or
2619 `.el', in that order. The name without appended suffix will not be used.
2620 See `get-load-suffixes' for the complete list of suffixes.
2621 If the optional third argument NOERROR is non-nil,
2622 then return nil if the file is not found instead of signaling an error.
2623 Normally the return value is FEATURE.
2624 The normal messages at start and end of loading FILENAME are suppressed. */)
2625 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2627 register Lisp_Object tem;
2628 struct gcpro gcpro1, gcpro2;
2629 int from_file = load_in_progress;
2631 CHECK_SYMBOL (feature);
2633 /* Record the presence of `require' in this file
2634 even if the feature specified is already loaded.
2635 But not more than once in any file,
2636 and not when we aren't loading or reading from a file. */
2637 if (!from_file)
2638 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2639 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2640 from_file = 1;
2642 if (from_file)
2644 tem = Fcons (Qrequire, feature);
2645 if (NILP (Fmember (tem, Vcurrent_load_list)))
2646 LOADHIST_ATTACH (tem);
2648 tem = Fmemq (feature, Vfeatures);
2650 if (NILP (tem))
2652 int count = SPECPDL_INDEX ();
2653 int nesting = 0;
2655 /* This is to make sure that loadup.el gives a clear picture
2656 of what files are preloaded and when. */
2657 if (! NILP (Vpurify_flag))
2658 error ("(require %s) while preparing to dump",
2659 SDATA (SYMBOL_NAME (feature)));
2661 /* A certain amount of recursive `require' is legitimate,
2662 but if we require the same feature recursively 3 times,
2663 signal an error. */
2664 tem = require_nesting_list;
2665 while (! NILP (tem))
2667 if (! NILP (Fequal (feature, XCAR (tem))))
2668 nesting++;
2669 tem = XCDR (tem);
2671 if (nesting > 3)
2672 error ("Recursive `require' for feature `%s'",
2673 SDATA (SYMBOL_NAME (feature)));
2675 /* Update the list for any nested `require's that occur. */
2676 record_unwind_protect (require_unwind, require_nesting_list);
2677 require_nesting_list = Fcons (feature, require_nesting_list);
2679 /* Value saved here is to be restored into Vautoload_queue */
2680 record_unwind_protect (un_autoload, Vautoload_queue);
2681 Vautoload_queue = Qt;
2683 /* Load the file. */
2684 GCPRO2 (feature, filename);
2685 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2686 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2687 UNGCPRO;
2689 /* If load failed entirely, return nil. */
2690 if (NILP (tem))
2691 return unbind_to (count, Qnil);
2693 tem = Fmemq (feature, Vfeatures);
2694 if (NILP (tem))
2695 error ("Required feature `%s' was not provided",
2696 SDATA (SYMBOL_NAME (feature)));
2698 /* Once loading finishes, don't undo it. */
2699 Vautoload_queue = Qt;
2700 feature = unbind_to (count, feature);
2703 return feature;
2706 /* Primitives for work of the "widget" library.
2707 In an ideal world, this section would not have been necessary.
2708 However, lisp function calls being as slow as they are, it turns
2709 out that some functions in the widget library (wid-edit.el) are the
2710 bottleneck of Widget operation. Here is their translation to C,
2711 for the sole reason of efficiency. */
2713 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2714 doc: /* Return non-nil if PLIST has the property PROP.
2715 PLIST is a property list, which is a list of the form
2716 \(PROP1 VALUE1 PROP2 VALUE2 ...\). PROP is a symbol.
2717 Unlike `plist-get', this allows you to distinguish between a missing
2718 property and a property with the value nil.
2719 The value is actually the tail of PLIST whose car is PROP. */)
2720 (Lisp_Object plist, Lisp_Object prop)
2722 while (CONSP (plist) && !EQ (XCAR (plist), prop))
2724 QUIT;
2725 plist = XCDR (plist);
2726 plist = CDR (plist);
2728 return plist;
2731 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2732 doc: /* In WIDGET, set PROPERTY to VALUE.
2733 The value can later be retrieved with `widget-get'. */)
2734 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2736 CHECK_CONS (widget);
2737 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
2738 return value;
2741 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
2742 doc: /* In WIDGET, get the value of PROPERTY.
2743 The value could either be specified when the widget was created, or
2744 later with `widget-put'. */)
2745 (Lisp_Object widget, Lisp_Object property)
2747 Lisp_Object tmp;
2749 while (1)
2751 if (NILP (widget))
2752 return Qnil;
2753 CHECK_CONS (widget);
2754 tmp = Fplist_member (XCDR (widget), property);
2755 if (CONSP (tmp))
2757 tmp = XCDR (tmp);
2758 return CAR (tmp);
2760 tmp = XCAR (widget);
2761 if (NILP (tmp))
2762 return Qnil;
2763 widget = Fget (tmp, Qwidget_type);
2767 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
2768 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2769 ARGS are passed as extra arguments to the function.
2770 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2771 (ptrdiff_t nargs, Lisp_Object *args)
2773 /* This function can GC. */
2774 Lisp_Object newargs[3];
2775 struct gcpro gcpro1, gcpro2;
2776 Lisp_Object result;
2778 newargs[0] = Fwidget_get (args[0], args[1]);
2779 newargs[1] = args[0];
2780 newargs[2] = Flist (nargs - 2, args + 2);
2781 GCPRO2 (newargs[0], newargs[2]);
2782 result = Fapply (3, newargs);
2783 UNGCPRO;
2784 return result;
2787 #ifdef HAVE_LANGINFO_CODESET
2788 #include <langinfo.h>
2789 #endif
2791 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
2792 doc: /* Access locale data ITEM for the current C locale, if available.
2793 ITEM should be one of the following:
2795 `codeset', returning the character set as a string (locale item CODESET);
2797 `days', returning a 7-element vector of day names (locale items DAY_n);
2799 `months', returning a 12-element vector of month names (locale items MON_n);
2801 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
2802 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
2804 If the system can't provide such information through a call to
2805 `nl_langinfo', or if ITEM isn't from the list above, return nil.
2807 See also Info node `(libc)Locales'.
2809 The data read from the system are decoded using `locale-coding-system'. */)
2810 (Lisp_Object item)
2812 char *str = NULL;
2813 #ifdef HAVE_LANGINFO_CODESET
2814 Lisp_Object val;
2815 if (EQ (item, Qcodeset))
2817 str = nl_langinfo (CODESET);
2818 return build_string (str);
2820 #ifdef DAY_1
2821 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
2823 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
2824 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
2825 int i;
2826 struct gcpro gcpro1;
2827 GCPRO1 (v);
2828 synchronize_system_time_locale ();
2829 for (i = 0; i < 7; i++)
2831 str = nl_langinfo (days[i]);
2832 val = make_unibyte_string (str, strlen (str));
2833 /* Fixme: Is this coding system necessarily right, even if
2834 it is consistent with CODESET? If not, what to do? */
2835 Faset (v, make_number (i),
2836 code_convert_string_norecord (val, Vlocale_coding_system,
2837 0));
2839 UNGCPRO;
2840 return v;
2842 #endif /* DAY_1 */
2843 #ifdef MON_1
2844 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
2846 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
2847 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
2848 MON_8, MON_9, MON_10, MON_11, MON_12};
2849 int i;
2850 struct gcpro gcpro1;
2851 GCPRO1 (v);
2852 synchronize_system_time_locale ();
2853 for (i = 0; i < 12; i++)
2855 str = nl_langinfo (months[i]);
2856 val = make_unibyte_string (str, strlen (str));
2857 Faset (v, make_number (i),
2858 code_convert_string_norecord (val, Vlocale_coding_system, 0));
2860 UNGCPRO;
2861 return v;
2863 #endif /* MON_1 */
2864 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
2865 but is in the locale files. This could be used by ps-print. */
2866 #ifdef PAPER_WIDTH
2867 else if (EQ (item, Qpaper))
2869 return list2 (make_number (nl_langinfo (PAPER_WIDTH)),
2870 make_number (nl_langinfo (PAPER_HEIGHT)));
2872 #endif /* PAPER_WIDTH */
2873 #endif /* HAVE_LANGINFO_CODESET*/
2874 return Qnil;
2877 /* base64 encode/decode functions (RFC 2045).
2878 Based on code from GNU recode. */
2880 #define MIME_LINE_LENGTH 76
2882 #define IS_ASCII(Character) \
2883 ((Character) < 128)
2884 #define IS_BASE64(Character) \
2885 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
2886 #define IS_BASE64_IGNORABLE(Character) \
2887 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
2888 || (Character) == '\f' || (Character) == '\r')
2890 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
2891 character or return retval if there are no characters left to
2892 process. */
2893 #define READ_QUADRUPLET_BYTE(retval) \
2894 do \
2896 if (i == length) \
2898 if (nchars_return) \
2899 *nchars_return = nchars; \
2900 return (retval); \
2902 c = from[i++]; \
2904 while (IS_BASE64_IGNORABLE (c))
2906 /* Table of characters coding the 64 values. */
2907 static const char base64_value_to_char[64] =
2909 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
2910 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
2911 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
2912 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
2913 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
2914 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
2915 '8', '9', '+', '/' /* 60-63 */
2918 /* Table of base64 values for first 128 characters. */
2919 static const short base64_char_to_value[128] =
2921 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
2922 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
2923 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
2924 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
2925 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
2926 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
2927 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
2928 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
2929 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
2930 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
2931 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
2932 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
2933 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
2936 /* The following diagram shows the logical steps by which three octets
2937 get transformed into four base64 characters.
2939 .--------. .--------. .--------.
2940 |aaaaaabb| |bbbbcccc| |ccdddddd|
2941 `--------' `--------' `--------'
2942 6 2 4 4 2 6
2943 .--------+--------+--------+--------.
2944 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
2945 `--------+--------+--------+--------'
2947 .--------+--------+--------+--------.
2948 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
2949 `--------+--------+--------+--------'
2951 The octets are divided into 6 bit chunks, which are then encoded into
2952 base64 characters. */
2955 static EMACS_INT base64_encode_1 (const char *, char *, EMACS_INT, int, int);
2956 static EMACS_INT base64_decode_1 (const char *, char *, EMACS_INT, int,
2957 EMACS_INT *);
2959 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
2960 2, 3, "r",
2961 doc: /* Base64-encode the region between BEG and END.
2962 Return the length of the encoded text.
2963 Optional third argument NO-LINE-BREAK means do not break long lines
2964 into shorter lines. */)
2965 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
2967 char *encoded;
2968 EMACS_INT allength, length;
2969 EMACS_INT ibeg, iend, encoded_length;
2970 EMACS_INT old_pos = PT;
2971 USE_SAFE_ALLOCA;
2973 validate_region (&beg, &end);
2975 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
2976 iend = CHAR_TO_BYTE (XFASTINT (end));
2977 move_gap_both (XFASTINT (beg), ibeg);
2979 /* We need to allocate enough room for encoding the text.
2980 We need 33 1/3% more space, plus a newline every 76
2981 characters, and then we round up. */
2982 length = iend - ibeg;
2983 allength = length + length/3 + 1;
2984 allength += allength / MIME_LINE_LENGTH + 1 + 6;
2986 SAFE_ALLOCA (encoded, char *, allength);
2987 encoded_length = base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg),
2988 encoded, length, NILP (no_line_break),
2989 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
2990 if (encoded_length > allength)
2991 abort ();
2993 if (encoded_length < 0)
2995 /* The encoding wasn't possible. */
2996 SAFE_FREE ();
2997 error ("Multibyte character in data for base64 encoding");
3000 /* Now we have encoded the region, so we insert the new contents
3001 and delete the old. (Insert first in order to preserve markers.) */
3002 SET_PT_BOTH (XFASTINT (beg), ibeg);
3003 insert (encoded, encoded_length);
3004 SAFE_FREE ();
3005 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
3007 /* If point was outside of the region, restore it exactly; else just
3008 move to the beginning of the region. */
3009 if (old_pos >= XFASTINT (end))
3010 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
3011 else if (old_pos > XFASTINT (beg))
3012 old_pos = XFASTINT (beg);
3013 SET_PT (old_pos);
3015 /* We return the length of the encoded text. */
3016 return make_number (encoded_length);
3019 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
3020 1, 2, 0,
3021 doc: /* Base64-encode STRING and return the result.
3022 Optional second argument NO-LINE-BREAK means do not break long lines
3023 into shorter lines. */)
3024 (Lisp_Object string, Lisp_Object no_line_break)
3026 EMACS_INT allength, length, encoded_length;
3027 char *encoded;
3028 Lisp_Object encoded_string;
3029 USE_SAFE_ALLOCA;
3031 CHECK_STRING (string);
3033 /* We need to allocate enough room for encoding the text.
3034 We need 33 1/3% more space, plus a newline every 76
3035 characters, and then we round up. */
3036 length = SBYTES (string);
3037 allength = length + length/3 + 1;
3038 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3040 /* We need to allocate enough room for decoding the text. */
3041 SAFE_ALLOCA (encoded, char *, allength);
3043 encoded_length = base64_encode_1 (SSDATA (string),
3044 encoded, length, NILP (no_line_break),
3045 STRING_MULTIBYTE (string));
3046 if (encoded_length > allength)
3047 abort ();
3049 if (encoded_length < 0)
3051 /* The encoding wasn't possible. */
3052 SAFE_FREE ();
3053 error ("Multibyte character in data for base64 encoding");
3056 encoded_string = make_unibyte_string (encoded, encoded_length);
3057 SAFE_FREE ();
3059 return encoded_string;
3062 static EMACS_INT
3063 base64_encode_1 (const char *from, char *to, EMACS_INT length,
3064 int line_break, int multibyte)
3066 int counter = 0;
3067 EMACS_INT i = 0;
3068 char *e = to;
3069 int c;
3070 unsigned int value;
3071 int bytes;
3073 while (i < length)
3075 if (multibyte)
3077 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3078 if (CHAR_BYTE8_P (c))
3079 c = CHAR_TO_BYTE8 (c);
3080 else if (c >= 256)
3081 return -1;
3082 i += bytes;
3084 else
3085 c = from[i++];
3087 /* Wrap line every 76 characters. */
3089 if (line_break)
3091 if (counter < MIME_LINE_LENGTH / 4)
3092 counter++;
3093 else
3095 *e++ = '\n';
3096 counter = 1;
3100 /* Process first byte of a triplet. */
3102 *e++ = base64_value_to_char[0x3f & c >> 2];
3103 value = (0x03 & c) << 4;
3105 /* Process second byte of a triplet. */
3107 if (i == length)
3109 *e++ = base64_value_to_char[value];
3110 *e++ = '=';
3111 *e++ = '=';
3112 break;
3115 if (multibyte)
3117 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3118 if (CHAR_BYTE8_P (c))
3119 c = CHAR_TO_BYTE8 (c);
3120 else if (c >= 256)
3121 return -1;
3122 i += bytes;
3124 else
3125 c = from[i++];
3127 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3128 value = (0x0f & c) << 2;
3130 /* Process third byte of a triplet. */
3132 if (i == length)
3134 *e++ = base64_value_to_char[value];
3135 *e++ = '=';
3136 break;
3139 if (multibyte)
3141 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3142 if (CHAR_BYTE8_P (c))
3143 c = CHAR_TO_BYTE8 (c);
3144 else if (c >= 256)
3145 return -1;
3146 i += bytes;
3148 else
3149 c = from[i++];
3151 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3152 *e++ = base64_value_to_char[0x3f & c];
3155 return e - to;
3159 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3160 2, 2, "r",
3161 doc: /* Base64-decode the region between BEG and END.
3162 Return the length of the decoded text.
3163 If the region can't be decoded, signal an error and don't modify the buffer. */)
3164 (Lisp_Object beg, Lisp_Object end)
3166 EMACS_INT ibeg, iend, length, allength;
3167 char *decoded;
3168 EMACS_INT old_pos = PT;
3169 EMACS_INT decoded_length;
3170 EMACS_INT inserted_chars;
3171 int multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3172 USE_SAFE_ALLOCA;
3174 validate_region (&beg, &end);
3176 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3177 iend = CHAR_TO_BYTE (XFASTINT (end));
3179 length = iend - ibeg;
3181 /* We need to allocate enough room for decoding the text. If we are
3182 working on a multibyte buffer, each decoded code may occupy at
3183 most two bytes. */
3184 allength = multibyte ? length * 2 : length;
3185 SAFE_ALLOCA (decoded, char *, allength);
3187 move_gap_both (XFASTINT (beg), ibeg);
3188 decoded_length = base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg),
3189 decoded, length,
3190 multibyte, &inserted_chars);
3191 if (decoded_length > allength)
3192 abort ();
3194 if (decoded_length < 0)
3196 /* The decoding wasn't possible. */
3197 SAFE_FREE ();
3198 error ("Invalid base64 data");
3201 /* Now we have decoded the region, so we insert the new contents
3202 and delete the old. (Insert first in order to preserve markers.) */
3203 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3204 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3205 SAFE_FREE ();
3207 /* Delete the original text. */
3208 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3209 iend + decoded_length, 1);
3211 /* If point was outside of the region, restore it exactly; else just
3212 move to the beginning of the region. */
3213 if (old_pos >= XFASTINT (end))
3214 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3215 else if (old_pos > XFASTINT (beg))
3216 old_pos = XFASTINT (beg);
3217 SET_PT (old_pos > ZV ? ZV : old_pos);
3219 return make_number (inserted_chars);
3222 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3223 1, 1, 0,
3224 doc: /* Base64-decode STRING and return the result. */)
3225 (Lisp_Object string)
3227 char *decoded;
3228 EMACS_INT length, decoded_length;
3229 Lisp_Object decoded_string;
3230 USE_SAFE_ALLOCA;
3232 CHECK_STRING (string);
3234 length = SBYTES (string);
3235 /* We need to allocate enough room for decoding the text. */
3236 SAFE_ALLOCA (decoded, char *, length);
3238 /* The decoded result should be unibyte. */
3239 decoded_length = base64_decode_1 (SSDATA (string), decoded, length,
3240 0, NULL);
3241 if (decoded_length > length)
3242 abort ();
3243 else if (decoded_length >= 0)
3244 decoded_string = make_unibyte_string (decoded, decoded_length);
3245 else
3246 decoded_string = Qnil;
3248 SAFE_FREE ();
3249 if (!STRINGP (decoded_string))
3250 error ("Invalid base64 data");
3252 return decoded_string;
3255 /* Base64-decode the data at FROM of LENGTH bytes into TO. If
3256 MULTIBYTE is nonzero, the decoded result should be in multibyte
3257 form. If NCHARS_RETRUN is not NULL, store the number of produced
3258 characters in *NCHARS_RETURN. */
3260 static EMACS_INT
3261 base64_decode_1 (const char *from, char *to, EMACS_INT length,
3262 int multibyte, EMACS_INT *nchars_return)
3264 EMACS_INT i = 0; /* Used inside READ_QUADRUPLET_BYTE */
3265 char *e = to;
3266 unsigned char c;
3267 unsigned long value;
3268 EMACS_INT nchars = 0;
3270 while (1)
3272 /* Process first byte of a quadruplet. */
3274 READ_QUADRUPLET_BYTE (e-to);
3276 if (!IS_BASE64 (c))
3277 return -1;
3278 value = base64_char_to_value[c] << 18;
3280 /* Process second byte of a quadruplet. */
3282 READ_QUADRUPLET_BYTE (-1);
3284 if (!IS_BASE64 (c))
3285 return -1;
3286 value |= base64_char_to_value[c] << 12;
3288 c = (unsigned char) (value >> 16);
3289 if (multibyte && c >= 128)
3290 e += BYTE8_STRING (c, e);
3291 else
3292 *e++ = c;
3293 nchars++;
3295 /* Process third byte of a quadruplet. */
3297 READ_QUADRUPLET_BYTE (-1);
3299 if (c == '=')
3301 READ_QUADRUPLET_BYTE (-1);
3303 if (c != '=')
3304 return -1;
3305 continue;
3308 if (!IS_BASE64 (c))
3309 return -1;
3310 value |= base64_char_to_value[c] << 6;
3312 c = (unsigned char) (0xff & value >> 8);
3313 if (multibyte && c >= 128)
3314 e += BYTE8_STRING (c, e);
3315 else
3316 *e++ = c;
3317 nchars++;
3319 /* Process fourth byte of a quadruplet. */
3321 READ_QUADRUPLET_BYTE (-1);
3323 if (c == '=')
3324 continue;
3326 if (!IS_BASE64 (c))
3327 return -1;
3328 value |= base64_char_to_value[c];
3330 c = (unsigned char) (0xff & value);
3331 if (multibyte && c >= 128)
3332 e += BYTE8_STRING (c, e);
3333 else
3334 *e++ = c;
3335 nchars++;
3341 /***********************************************************************
3342 ***** *****
3343 ***** Hash Tables *****
3344 ***** *****
3345 ***********************************************************************/
3347 /* Implemented by gerd@gnu.org. This hash table implementation was
3348 inspired by CMUCL hash tables. */
3350 /* Ideas:
3352 1. For small tables, association lists are probably faster than
3353 hash tables because they have lower overhead.
3355 For uses of hash tables where the O(1) behavior of table
3356 operations is not a requirement, it might therefore be a good idea
3357 not to hash. Instead, we could just do a linear search in the
3358 key_and_value vector of the hash table. This could be done
3359 if a `:linear-search t' argument is given to make-hash-table. */
3362 /* The list of all weak hash tables. Don't staticpro this one. */
3364 static struct Lisp_Hash_Table *weak_hash_tables;
3366 /* Various symbols. */
3368 static Lisp_Object Qhash_table_p, Qkey, Qvalue;
3369 Lisp_Object Qeq, Qeql, Qequal;
3370 Lisp_Object QCtest, QCsize, QCrehash_size, QCrehash_threshold, QCweakness;
3371 static Lisp_Object Qhash_table_test, Qkey_or_value, Qkey_and_value;
3373 /* Function prototypes. */
3375 static struct Lisp_Hash_Table *check_hash_table (Lisp_Object);
3376 static ptrdiff_t get_key_arg (Lisp_Object, ptrdiff_t, Lisp_Object *, char *);
3377 static void maybe_resize_hash_table (struct Lisp_Hash_Table *);
3378 static int sweep_weak_table (struct Lisp_Hash_Table *, int);
3382 /***********************************************************************
3383 Utilities
3384 ***********************************************************************/
3386 /* If OBJ is a Lisp hash table, return a pointer to its struct
3387 Lisp_Hash_Table. Otherwise, signal an error. */
3389 static struct Lisp_Hash_Table *
3390 check_hash_table (Lisp_Object obj)
3392 CHECK_HASH_TABLE (obj);
3393 return XHASH_TABLE (obj);
3397 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3398 number. A number is "almost" a prime number if it is not divisible
3399 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3401 EMACS_INT
3402 next_almost_prime (EMACS_INT n)
3404 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
3405 for (n |= 1; ; n += 2)
3406 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0)
3407 return n;
3411 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3412 which USED[I] is non-zero. If found at index I in ARGS, set
3413 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3414 0. This function is used to extract a keyword/argument pair from
3415 a DEFUN parameter list. */
3417 static ptrdiff_t
3418 get_key_arg (Lisp_Object key, ptrdiff_t nargs, Lisp_Object *args, char *used)
3420 ptrdiff_t i;
3422 for (i = 1; i < nargs; i++)
3423 if (!used[i - 1] && EQ (args[i - 1], key))
3425 used[i - 1] = 1;
3426 used[i] = 1;
3427 return i;
3430 return 0;
3434 /* Return a Lisp vector which has the same contents as VEC but has
3435 size NEW_SIZE, NEW_SIZE >= VEC->size. Entries in the resulting
3436 vector that are not copied from VEC are set to INIT. */
3438 Lisp_Object
3439 larger_vector (Lisp_Object vec, EMACS_INT new_size, Lisp_Object init)
3441 struct Lisp_Vector *v;
3442 EMACS_INT i, old_size;
3444 xassert (VECTORP (vec));
3445 old_size = ASIZE (vec);
3446 xassert (new_size >= old_size);
3448 v = allocate_vector (new_size);
3449 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3450 for (i = old_size; i < new_size; ++i)
3451 v->contents[i] = init;
3452 XSETVECTOR (vec, v);
3453 return vec;
3457 /***********************************************************************
3458 Low-level Functions
3459 ***********************************************************************/
3461 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3462 HASH2 in hash table H using `eql'. Value is non-zero if KEY1 and
3463 KEY2 are the same. */
3465 static int
3466 cmpfn_eql (struct Lisp_Hash_Table *h,
3467 Lisp_Object key1, EMACS_UINT hash1,
3468 Lisp_Object key2, EMACS_UINT hash2)
3470 return (FLOATP (key1)
3471 && FLOATP (key2)
3472 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3476 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3477 HASH2 in hash table H using `equal'. Value is non-zero if KEY1 and
3478 KEY2 are the same. */
3480 static int
3481 cmpfn_equal (struct Lisp_Hash_Table *h,
3482 Lisp_Object key1, EMACS_UINT hash1,
3483 Lisp_Object key2, EMACS_UINT hash2)
3485 return hash1 == hash2 && !NILP (Fequal (key1, key2));
3489 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3490 HASH2 in hash table H using H->user_cmp_function. Value is non-zero
3491 if KEY1 and KEY2 are the same. */
3493 static int
3494 cmpfn_user_defined (struct Lisp_Hash_Table *h,
3495 Lisp_Object key1, EMACS_UINT hash1,
3496 Lisp_Object key2, EMACS_UINT hash2)
3498 if (hash1 == hash2)
3500 Lisp_Object args[3];
3502 args[0] = h->user_cmp_function;
3503 args[1] = key1;
3504 args[2] = key2;
3505 return !NILP (Ffuncall (3, args));
3507 else
3508 return 0;
3512 /* Value is a hash code for KEY for use in hash table H which uses
3513 `eq' to compare keys. The hash code returned is guaranteed to fit
3514 in a Lisp integer. */
3516 static EMACS_UINT
3517 hashfn_eq (struct Lisp_Hash_Table *h, Lisp_Object key)
3519 EMACS_UINT hash = XUINT (key) ^ XTYPE (key);
3520 xassert ((hash & ~INTMASK) == 0);
3521 return hash;
3525 /* Value is a hash code for KEY for use in hash table H which uses
3526 `eql' to compare keys. The hash code returned is guaranteed to fit
3527 in a Lisp integer. */
3529 static EMACS_UINT
3530 hashfn_eql (struct Lisp_Hash_Table *h, Lisp_Object key)
3532 EMACS_UINT hash;
3533 if (FLOATP (key))
3534 hash = sxhash (key, 0);
3535 else
3536 hash = XUINT (key) ^ XTYPE (key);
3537 xassert ((hash & ~INTMASK) == 0);
3538 return hash;
3542 /* Value is a hash code for KEY for use in hash table H which uses
3543 `equal' to compare keys. The hash code returned is guaranteed to fit
3544 in a Lisp integer. */
3546 static EMACS_UINT
3547 hashfn_equal (struct Lisp_Hash_Table *h, Lisp_Object key)
3549 EMACS_UINT hash = sxhash (key, 0);
3550 xassert ((hash & ~INTMASK) == 0);
3551 return hash;
3555 /* Value is a hash code for KEY for use in hash table H which uses as
3556 user-defined function to compare keys. The hash code returned is
3557 guaranteed to fit in a Lisp integer. */
3559 static EMACS_UINT
3560 hashfn_user_defined (struct Lisp_Hash_Table *h, Lisp_Object key)
3562 Lisp_Object args[2], hash;
3564 args[0] = h->user_hash_function;
3565 args[1] = key;
3566 hash = Ffuncall (2, args);
3567 if (!INTEGERP (hash))
3568 signal_error ("Invalid hash code returned from user-supplied hash function", hash);
3569 return XUINT (hash);
3573 /* Create and initialize a new hash table.
3575 TEST specifies the test the hash table will use to compare keys.
3576 It must be either one of the predefined tests `eq', `eql' or
3577 `equal' or a symbol denoting a user-defined test named TEST with
3578 test and hash functions USER_TEST and USER_HASH.
3580 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3582 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3583 new size when it becomes full is computed by adding REHASH_SIZE to
3584 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3585 table's new size is computed by multiplying its old size with
3586 REHASH_SIZE.
3588 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3589 be resized when the ratio of (number of entries in the table) /
3590 (table size) is >= REHASH_THRESHOLD.
3592 WEAK specifies the weakness of the table. If non-nil, it must be
3593 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
3595 Lisp_Object
3596 make_hash_table (Lisp_Object test, Lisp_Object size, Lisp_Object rehash_size,
3597 Lisp_Object rehash_threshold, Lisp_Object weak,
3598 Lisp_Object user_test, Lisp_Object user_hash)
3600 struct Lisp_Hash_Table *h;
3601 Lisp_Object table;
3602 EMACS_INT index_size, i, sz;
3603 double index_float;
3605 /* Preconditions. */
3606 xassert (SYMBOLP (test));
3607 xassert (INTEGERP (size) && XINT (size) >= 0);
3608 xassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3609 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size)));
3610 xassert (FLOATP (rehash_threshold)
3611 && 0 < XFLOAT_DATA (rehash_threshold)
3612 && XFLOAT_DATA (rehash_threshold) <= 1.0);
3614 if (XFASTINT (size) == 0)
3615 size = make_number (1);
3617 sz = XFASTINT (size);
3618 index_float = sz / XFLOAT_DATA (rehash_threshold);
3619 index_size = (index_float < MOST_POSITIVE_FIXNUM + 1
3620 ? next_almost_prime (index_float)
3621 : MOST_POSITIVE_FIXNUM + 1);
3622 if (MOST_POSITIVE_FIXNUM < max (index_size, 2 * sz))
3623 error ("Hash table too large");
3625 /* Allocate a table and initialize it. */
3626 h = allocate_hash_table ();
3628 /* Initialize hash table slots. */
3629 h->test = test;
3630 if (EQ (test, Qeql))
3632 h->cmpfn = cmpfn_eql;
3633 h->hashfn = hashfn_eql;
3635 else if (EQ (test, Qeq))
3637 h->cmpfn = NULL;
3638 h->hashfn = hashfn_eq;
3640 else if (EQ (test, Qequal))
3642 h->cmpfn = cmpfn_equal;
3643 h->hashfn = hashfn_equal;
3645 else
3647 h->user_cmp_function = user_test;
3648 h->user_hash_function = user_hash;
3649 h->cmpfn = cmpfn_user_defined;
3650 h->hashfn = hashfn_user_defined;
3653 h->weak = weak;
3654 h->rehash_threshold = rehash_threshold;
3655 h->rehash_size = rehash_size;
3656 h->count = 0;
3657 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
3658 h->hash = Fmake_vector (size, Qnil);
3659 h->next = Fmake_vector (size, Qnil);
3660 h->index = Fmake_vector (make_number (index_size), Qnil);
3662 /* Set up the free list. */
3663 for (i = 0; i < sz - 1; ++i)
3664 HASH_NEXT (h, i) = make_number (i + 1);
3665 h->next_free = make_number (0);
3667 XSET_HASH_TABLE (table, h);
3668 xassert (HASH_TABLE_P (table));
3669 xassert (XHASH_TABLE (table) == h);
3671 /* Maybe add this hash table to the list of all weak hash tables. */
3672 if (NILP (h->weak))
3673 h->next_weak = NULL;
3674 else
3676 h->next_weak = weak_hash_tables;
3677 weak_hash_tables = h;
3680 return table;
3684 /* Return a copy of hash table H1. Keys and values are not copied,
3685 only the table itself is. */
3687 static Lisp_Object
3688 copy_hash_table (struct Lisp_Hash_Table *h1)
3690 Lisp_Object table;
3691 struct Lisp_Hash_Table *h2;
3692 struct Lisp_Vector *next;
3694 h2 = allocate_hash_table ();
3695 next = h2->header.next.vector;
3696 memcpy (h2, h1, sizeof *h2);
3697 h2->header.next.vector = next;
3698 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3699 h2->hash = Fcopy_sequence (h1->hash);
3700 h2->next = Fcopy_sequence (h1->next);
3701 h2->index = Fcopy_sequence (h1->index);
3702 XSET_HASH_TABLE (table, h2);
3704 /* Maybe add this hash table to the list of all weak hash tables. */
3705 if (!NILP (h2->weak))
3707 h2->next_weak = weak_hash_tables;
3708 weak_hash_tables = h2;
3711 return table;
3715 /* Resize hash table H if it's too full. If H cannot be resized
3716 because it's already too large, throw an error. */
3718 static inline void
3719 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3721 if (NILP (h->next_free))
3723 EMACS_INT old_size = HASH_TABLE_SIZE (h);
3724 EMACS_INT i, new_size, index_size;
3725 EMACS_INT nsize;
3726 double index_float;
3728 if (INTEGERP (h->rehash_size))
3729 new_size = old_size + XFASTINT (h->rehash_size);
3730 else
3732 double float_new_size = old_size * XFLOAT_DATA (h->rehash_size);
3733 if (float_new_size < MOST_POSITIVE_FIXNUM + 1)
3735 new_size = float_new_size;
3736 if (new_size <= old_size)
3737 new_size = old_size + 1;
3739 else
3740 new_size = MOST_POSITIVE_FIXNUM + 1;
3742 index_float = new_size / XFLOAT_DATA (h->rehash_threshold);
3743 index_size = (index_float < MOST_POSITIVE_FIXNUM + 1
3744 ? next_almost_prime (index_float)
3745 : MOST_POSITIVE_FIXNUM + 1);
3746 nsize = max (index_size, 2 * new_size);
3747 if (nsize > MOST_POSITIVE_FIXNUM)
3748 error ("Hash table too large to resize");
3750 h->key_and_value = larger_vector (h->key_and_value, 2 * new_size, Qnil);
3751 h->next = larger_vector (h->next, new_size, Qnil);
3752 h->hash = larger_vector (h->hash, new_size, Qnil);
3753 h->index = Fmake_vector (make_number (index_size), Qnil);
3755 /* Update the free list. Do it so that new entries are added at
3756 the end of the free list. This makes some operations like
3757 maphash faster. */
3758 for (i = old_size; i < new_size - 1; ++i)
3759 HASH_NEXT (h, i) = make_number (i + 1);
3761 if (!NILP (h->next_free))
3763 Lisp_Object last, next;
3765 last = h->next_free;
3766 while (next = HASH_NEXT (h, XFASTINT (last)),
3767 !NILP (next))
3768 last = next;
3770 HASH_NEXT (h, XFASTINT (last)) = make_number (old_size);
3772 else
3773 XSETFASTINT (h->next_free, old_size);
3775 /* Rehash. */
3776 for (i = 0; i < old_size; ++i)
3777 if (!NILP (HASH_HASH (h, i)))
3779 EMACS_UINT hash_code = XUINT (HASH_HASH (h, i));
3780 EMACS_INT start_of_bucket = hash_code % ASIZE (h->index);
3781 HASH_NEXT (h, i) = HASH_INDEX (h, start_of_bucket);
3782 HASH_INDEX (h, start_of_bucket) = make_number (i);
3788 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
3789 the hash code of KEY. Value is the index of the entry in H
3790 matching KEY, or -1 if not found. */
3792 ptrdiff_t
3793 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
3795 EMACS_UINT hash_code;
3796 ptrdiff_t start_of_bucket;
3797 Lisp_Object idx;
3799 hash_code = h->hashfn (h, key);
3800 if (hash)
3801 *hash = hash_code;
3803 start_of_bucket = hash_code % ASIZE (h->index);
3804 idx = HASH_INDEX (h, start_of_bucket);
3806 /* We need not gcpro idx since it's either an integer or nil. */
3807 while (!NILP (idx))
3809 EMACS_INT i = XFASTINT (idx);
3810 if (EQ (key, HASH_KEY (h, i))
3811 || (h->cmpfn
3812 && h->cmpfn (h, key, hash_code,
3813 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
3814 break;
3815 idx = HASH_NEXT (h, i);
3818 return NILP (idx) ? -1 : XFASTINT (idx);
3822 /* Put an entry into hash table H that associates KEY with VALUE.
3823 HASH is a previously computed hash code of KEY.
3824 Value is the index of the entry in H matching KEY. */
3826 ptrdiff_t
3827 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value,
3828 EMACS_UINT hash)
3830 ptrdiff_t start_of_bucket, i;
3832 xassert ((hash & ~INTMASK) == 0);
3834 /* Increment count after resizing because resizing may fail. */
3835 maybe_resize_hash_table (h);
3836 h->count++;
3838 /* Store key/value in the key_and_value vector. */
3839 i = XFASTINT (h->next_free);
3840 h->next_free = HASH_NEXT (h, i);
3841 HASH_KEY (h, i) = key;
3842 HASH_VALUE (h, i) = value;
3844 /* Remember its hash code. */
3845 HASH_HASH (h, i) = make_number (hash);
3847 /* Add new entry to its collision chain. */
3848 start_of_bucket = hash % ASIZE (h->index);
3849 HASH_NEXT (h, i) = HASH_INDEX (h, start_of_bucket);
3850 HASH_INDEX (h, start_of_bucket) = make_number (i);
3851 return i;
3855 /* Remove the entry matching KEY from hash table H, if there is one. */
3857 static void
3858 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
3860 EMACS_UINT hash_code;
3861 EMACS_INT start_of_bucket;
3862 Lisp_Object idx, prev;
3864 hash_code = h->hashfn (h, key);
3865 start_of_bucket = hash_code % ASIZE (h->index);
3866 idx = HASH_INDEX (h, start_of_bucket);
3867 prev = Qnil;
3869 /* We need not gcpro idx, prev since they're either integers or nil. */
3870 while (!NILP (idx))
3872 EMACS_INT i = XFASTINT (idx);
3874 if (EQ (key, HASH_KEY (h, i))
3875 || (h->cmpfn
3876 && h->cmpfn (h, key, hash_code,
3877 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
3879 /* Take entry out of collision chain. */
3880 if (NILP (prev))
3881 HASH_INDEX (h, start_of_bucket) = HASH_NEXT (h, i);
3882 else
3883 HASH_NEXT (h, XFASTINT (prev)) = HASH_NEXT (h, i);
3885 /* Clear slots in key_and_value and add the slots to
3886 the free list. */
3887 HASH_KEY (h, i) = HASH_VALUE (h, i) = HASH_HASH (h, i) = Qnil;
3888 HASH_NEXT (h, i) = h->next_free;
3889 h->next_free = make_number (i);
3890 h->count--;
3891 xassert (h->count >= 0);
3892 break;
3894 else
3896 prev = idx;
3897 idx = HASH_NEXT (h, i);
3903 /* Clear hash table H. */
3905 static void
3906 hash_clear (struct Lisp_Hash_Table *h)
3908 if (h->count > 0)
3910 EMACS_INT i, size = HASH_TABLE_SIZE (h);
3912 for (i = 0; i < size; ++i)
3914 HASH_NEXT (h, i) = i < size - 1 ? make_number (i + 1) : Qnil;
3915 HASH_KEY (h, i) = Qnil;
3916 HASH_VALUE (h, i) = Qnil;
3917 HASH_HASH (h, i) = Qnil;
3920 for (i = 0; i < ASIZE (h->index); ++i)
3921 ASET (h->index, i, Qnil);
3923 h->next_free = make_number (0);
3924 h->count = 0;
3930 /************************************************************************
3931 Weak Hash Tables
3932 ************************************************************************/
3934 void
3935 init_weak_hash_tables (void)
3937 weak_hash_tables = NULL;
3940 /* Sweep weak hash table H. REMOVE_ENTRIES_P non-zero means remove
3941 entries from the table that don't survive the current GC.
3942 REMOVE_ENTRIES_P zero means mark entries that are in use. Value is
3943 non-zero if anything was marked. */
3945 static int
3946 sweep_weak_table (struct Lisp_Hash_Table *h, int remove_entries_p)
3948 EMACS_INT bucket, n;
3949 int marked;
3951 n = ASIZE (h->index) & ~ARRAY_MARK_FLAG;
3952 marked = 0;
3954 for (bucket = 0; bucket < n; ++bucket)
3956 Lisp_Object idx, next, prev;
3958 /* Follow collision chain, removing entries that
3959 don't survive this garbage collection. */
3960 prev = Qnil;
3961 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
3963 EMACS_INT i = XFASTINT (idx);
3964 int key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
3965 int value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
3966 int remove_p;
3968 if (EQ (h->weak, Qkey))
3969 remove_p = !key_known_to_survive_p;
3970 else if (EQ (h->weak, Qvalue))
3971 remove_p = !value_known_to_survive_p;
3972 else if (EQ (h->weak, Qkey_or_value))
3973 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
3974 else if (EQ (h->weak, Qkey_and_value))
3975 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
3976 else
3977 abort ();
3979 next = HASH_NEXT (h, i);
3981 if (remove_entries_p)
3983 if (remove_p)
3985 /* Take out of collision chain. */
3986 if (NILP (prev))
3987 HASH_INDEX (h, bucket) = next;
3988 else
3989 HASH_NEXT (h, XFASTINT (prev)) = next;
3991 /* Add to free list. */
3992 HASH_NEXT (h, i) = h->next_free;
3993 h->next_free = idx;
3995 /* Clear key, value, and hash. */
3996 HASH_KEY (h, i) = HASH_VALUE (h, i) = Qnil;
3997 HASH_HASH (h, i) = Qnil;
3999 h->count--;
4001 else
4003 prev = idx;
4006 else
4008 if (!remove_p)
4010 /* Make sure key and value survive. */
4011 if (!key_known_to_survive_p)
4013 mark_object (HASH_KEY (h, i));
4014 marked = 1;
4017 if (!value_known_to_survive_p)
4019 mark_object (HASH_VALUE (h, i));
4020 marked = 1;
4027 return marked;
4030 /* Remove elements from weak hash tables that don't survive the
4031 current garbage collection. Remove weak tables that don't survive
4032 from Vweak_hash_tables. Called from gc_sweep. */
4034 void
4035 sweep_weak_hash_tables (void)
4037 struct Lisp_Hash_Table *h, *used, *next;
4038 int marked;
4040 /* Mark all keys and values that are in use. Keep on marking until
4041 there is no more change. This is necessary for cases like
4042 value-weak table A containing an entry X -> Y, where Y is used in a
4043 key-weak table B, Z -> Y. If B comes after A in the list of weak
4044 tables, X -> Y might be removed from A, although when looking at B
4045 one finds that it shouldn't. */
4048 marked = 0;
4049 for (h = weak_hash_tables; h; h = h->next_weak)
4051 if (h->header.size & ARRAY_MARK_FLAG)
4052 marked |= sweep_weak_table (h, 0);
4055 while (marked);
4057 /* Remove tables and entries that aren't used. */
4058 for (h = weak_hash_tables, used = NULL; h; h = next)
4060 next = h->next_weak;
4062 if (h->header.size & ARRAY_MARK_FLAG)
4064 /* TABLE is marked as used. Sweep its contents. */
4065 if (h->count > 0)
4066 sweep_weak_table (h, 1);
4068 /* Add table to the list of used weak hash tables. */
4069 h->next_weak = used;
4070 used = h;
4074 weak_hash_tables = used;
4079 /***********************************************************************
4080 Hash Code Computation
4081 ***********************************************************************/
4083 /* Maximum depth up to which to dive into Lisp structures. */
4085 #define SXHASH_MAX_DEPTH 3
4087 /* Maximum length up to which to take list and vector elements into
4088 account. */
4090 #define SXHASH_MAX_LEN 7
4092 /* Combine two integers X and Y for hashing. The result might not fit
4093 into a Lisp integer. */
4095 #define SXHASH_COMBINE(X, Y) \
4096 ((((EMACS_UINT) (X) << 4) + ((EMACS_UINT) (X) >> (BITS_PER_EMACS_INT - 4))) \
4097 + (EMACS_UINT) (Y))
4099 /* Hash X, returning a value that fits into a Lisp integer. */
4100 #define SXHASH_REDUCE(X) \
4101 ((((X) ^ (X) >> (BITS_PER_EMACS_INT - FIXNUM_BITS))) & INTMASK)
4103 /* Return a hash for string PTR which has length LEN. The hash value
4104 can be any EMACS_UINT value. */
4106 EMACS_UINT
4107 hash_string (char const *ptr, ptrdiff_t len)
4109 char const *p = ptr;
4110 char const *end = p + len;
4111 unsigned char c;
4112 EMACS_UINT hash = 0;
4114 while (p != end)
4116 c = *p++;
4117 hash = SXHASH_COMBINE (hash, c);
4120 return hash;
4123 /* Return a hash for string PTR which has length LEN. The hash
4124 code returned is guaranteed to fit in a Lisp integer. */
4126 static EMACS_UINT
4127 sxhash_string (char const *ptr, ptrdiff_t len)
4129 EMACS_UINT hash = hash_string (ptr, len);
4130 return SXHASH_REDUCE (hash);
4133 /* Return a hash for the floating point value VAL. */
4135 static EMACS_INT
4136 sxhash_float (double val)
4138 EMACS_UINT hash = 0;
4139 enum {
4140 WORDS_PER_DOUBLE = (sizeof val / sizeof hash
4141 + (sizeof val % sizeof hash != 0))
4143 union {
4144 double val;
4145 EMACS_UINT word[WORDS_PER_DOUBLE];
4146 } u;
4147 int i;
4148 u.val = val;
4149 memset (&u.val + 1, 0, sizeof u - sizeof u.val);
4150 for (i = 0; i < WORDS_PER_DOUBLE; i++)
4151 hash = SXHASH_COMBINE (hash, u.word[i]);
4152 return SXHASH_REDUCE (hash);
4155 /* Return a hash for list LIST. DEPTH is the current depth in the
4156 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4158 static EMACS_UINT
4159 sxhash_list (Lisp_Object list, int depth)
4161 EMACS_UINT hash = 0;
4162 int i;
4164 if (depth < SXHASH_MAX_DEPTH)
4165 for (i = 0;
4166 CONSP (list) && i < SXHASH_MAX_LEN;
4167 list = XCDR (list), ++i)
4169 EMACS_UINT hash2 = sxhash (XCAR (list), depth + 1);
4170 hash = SXHASH_COMBINE (hash, hash2);
4173 if (!NILP (list))
4175 EMACS_UINT hash2 = sxhash (list, depth + 1);
4176 hash = SXHASH_COMBINE (hash, hash2);
4179 return SXHASH_REDUCE (hash);
4183 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4184 the Lisp structure. */
4186 static EMACS_UINT
4187 sxhash_vector (Lisp_Object vec, int depth)
4189 EMACS_UINT hash = ASIZE (vec);
4190 int i, n;
4192 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4193 for (i = 0; i < n; ++i)
4195 EMACS_UINT hash2 = sxhash (AREF (vec, i), depth + 1);
4196 hash = SXHASH_COMBINE (hash, hash2);
4199 return SXHASH_REDUCE (hash);
4202 /* Return a hash for bool-vector VECTOR. */
4204 static EMACS_UINT
4205 sxhash_bool_vector (Lisp_Object vec)
4207 EMACS_UINT hash = XBOOL_VECTOR (vec)->size;
4208 int i, n;
4210 n = min (SXHASH_MAX_LEN, XBOOL_VECTOR (vec)->header.size);
4211 for (i = 0; i < n; ++i)
4212 hash = SXHASH_COMBINE (hash, XBOOL_VECTOR (vec)->data[i]);
4214 return SXHASH_REDUCE (hash);
4218 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4219 structure. Value is an unsigned integer clipped to INTMASK. */
4221 EMACS_UINT
4222 sxhash (Lisp_Object obj, int depth)
4224 EMACS_UINT hash;
4226 if (depth > SXHASH_MAX_DEPTH)
4227 return 0;
4229 switch (XTYPE (obj))
4231 case_Lisp_Int:
4232 hash = XUINT (obj);
4233 break;
4235 case Lisp_Misc:
4236 hash = XUINT (obj);
4237 break;
4239 case Lisp_Symbol:
4240 obj = SYMBOL_NAME (obj);
4241 /* Fall through. */
4243 case Lisp_String:
4244 hash = sxhash_string (SSDATA (obj), SBYTES (obj));
4245 break;
4247 /* This can be everything from a vector to an overlay. */
4248 case Lisp_Vectorlike:
4249 if (VECTORP (obj))
4250 /* According to the CL HyperSpec, two arrays are equal only if
4251 they are `eq', except for strings and bit-vectors. In
4252 Emacs, this works differently. We have to compare element
4253 by element. */
4254 hash = sxhash_vector (obj, depth);
4255 else if (BOOL_VECTOR_P (obj))
4256 hash = sxhash_bool_vector (obj);
4257 else
4258 /* Others are `equal' if they are `eq', so let's take their
4259 address as hash. */
4260 hash = XUINT (obj);
4261 break;
4263 case Lisp_Cons:
4264 hash = sxhash_list (obj, depth);
4265 break;
4267 case Lisp_Float:
4268 hash = sxhash_float (XFLOAT_DATA (obj));
4269 break;
4271 default:
4272 abort ();
4275 return hash;
4280 /***********************************************************************
4281 Lisp Interface
4282 ***********************************************************************/
4285 DEFUN ("sxhash", Fsxhash, Ssxhash, 1, 1, 0,
4286 doc: /* Compute a hash code for OBJ and return it as integer. */)
4287 (Lisp_Object obj)
4289 EMACS_UINT hash = sxhash (obj, 0);
4290 return make_number (hash);
4294 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4295 doc: /* Create and return a new hash table.
4297 Arguments are specified as keyword/argument pairs. The following
4298 arguments are defined:
4300 :test TEST -- TEST must be a symbol that specifies how to compare
4301 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4302 `equal'. User-supplied test and hash functions can be specified via
4303 `define-hash-table-test'.
4305 :size SIZE -- A hint as to how many elements will be put in the table.
4306 Default is 65.
4308 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4309 fills up. If REHASH-SIZE is an integer, increase the size by that
4310 amount. If it is a float, it must be > 1.0, and the new size is the
4311 old size multiplied by that factor. Default is 1.5.
4313 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4314 Resize the hash table when the ratio (number of entries / table size)
4315 is greater than or equal to THRESHOLD. Default is 0.8.
4317 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4318 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4319 returned is a weak table. Key/value pairs are removed from a weak
4320 hash table when there are no non-weak references pointing to their
4321 key, value, one of key or value, or both key and value, depending on
4322 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4323 is nil.
4325 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4326 (ptrdiff_t nargs, Lisp_Object *args)
4328 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4329 Lisp_Object user_test, user_hash;
4330 char *used;
4331 ptrdiff_t i;
4333 /* The vector `used' is used to keep track of arguments that
4334 have been consumed. */
4335 used = (char *) alloca (nargs * sizeof *used);
4336 memset (used, 0, nargs * sizeof *used);
4338 /* See if there's a `:test TEST' among the arguments. */
4339 i = get_key_arg (QCtest, nargs, args, used);
4340 test = i ? args[i] : Qeql;
4341 if (!EQ (test, Qeq) && !EQ (test, Qeql) && !EQ (test, Qequal))
4343 /* See if it is a user-defined test. */
4344 Lisp_Object prop;
4346 prop = Fget (test, Qhash_table_test);
4347 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4348 signal_error ("Invalid hash table test", test);
4349 user_test = XCAR (prop);
4350 user_hash = XCAR (XCDR (prop));
4352 else
4353 user_test = user_hash = Qnil;
4355 /* See if there's a `:size SIZE' argument. */
4356 i = get_key_arg (QCsize, nargs, args, used);
4357 size = i ? args[i] : Qnil;
4358 if (NILP (size))
4359 size = make_number (DEFAULT_HASH_SIZE);
4360 else if (!INTEGERP (size) || XINT (size) < 0)
4361 signal_error ("Invalid hash table size", size);
4363 /* Look for `:rehash-size SIZE'. */
4364 i = get_key_arg (QCrehash_size, nargs, args, used);
4365 rehash_size = i ? args[i] : make_float (DEFAULT_REHASH_SIZE);
4366 if (! ((INTEGERP (rehash_size) && 0 < XINT (rehash_size))
4367 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size))))
4368 signal_error ("Invalid hash table rehash size", rehash_size);
4370 /* Look for `:rehash-threshold THRESHOLD'. */
4371 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4372 rehash_threshold = i ? args[i] : make_float (DEFAULT_REHASH_THRESHOLD);
4373 if (! (FLOATP (rehash_threshold)
4374 && 0 < XFLOAT_DATA (rehash_threshold)
4375 && XFLOAT_DATA (rehash_threshold) <= 1))
4376 signal_error ("Invalid hash table rehash threshold", rehash_threshold);
4378 /* Look for `:weakness WEAK'. */
4379 i = get_key_arg (QCweakness, nargs, args, used);
4380 weak = i ? args[i] : Qnil;
4381 if (EQ (weak, Qt))
4382 weak = Qkey_and_value;
4383 if (!NILP (weak)
4384 && !EQ (weak, Qkey)
4385 && !EQ (weak, Qvalue)
4386 && !EQ (weak, Qkey_or_value)
4387 && !EQ (weak, Qkey_and_value))
4388 signal_error ("Invalid hash table weakness", weak);
4390 /* Now, all args should have been used up, or there's a problem. */
4391 for (i = 0; i < nargs; ++i)
4392 if (!used[i])
4393 signal_error ("Invalid argument list", args[i]);
4395 return make_hash_table (test, size, rehash_size, rehash_threshold, weak,
4396 user_test, user_hash);
4400 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4401 doc: /* Return a copy of hash table TABLE. */)
4402 (Lisp_Object table)
4404 return copy_hash_table (check_hash_table (table));
4408 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4409 doc: /* Return the number of elements in TABLE. */)
4410 (Lisp_Object table)
4412 return make_number (check_hash_table (table)->count);
4416 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4417 Shash_table_rehash_size, 1, 1, 0,
4418 doc: /* Return the current rehash size of TABLE. */)
4419 (Lisp_Object table)
4421 return check_hash_table (table)->rehash_size;
4425 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4426 Shash_table_rehash_threshold, 1, 1, 0,
4427 doc: /* Return the current rehash threshold of TABLE. */)
4428 (Lisp_Object table)
4430 return check_hash_table (table)->rehash_threshold;
4434 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4435 doc: /* Return the size of TABLE.
4436 The size can be used as an argument to `make-hash-table' to create
4437 a hash table than can hold as many elements as TABLE holds
4438 without need for resizing. */)
4439 (Lisp_Object table)
4441 struct Lisp_Hash_Table *h = check_hash_table (table);
4442 return make_number (HASH_TABLE_SIZE (h));
4446 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4447 doc: /* Return the test TABLE uses. */)
4448 (Lisp_Object table)
4450 return check_hash_table (table)->test;
4454 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4455 1, 1, 0,
4456 doc: /* Return the weakness of TABLE. */)
4457 (Lisp_Object table)
4459 return check_hash_table (table)->weak;
4463 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4464 doc: /* Return t if OBJ is a Lisp hash table object. */)
4465 (Lisp_Object obj)
4467 return HASH_TABLE_P (obj) ? Qt : Qnil;
4471 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4472 doc: /* Clear hash table TABLE and return it. */)
4473 (Lisp_Object table)
4475 hash_clear (check_hash_table (table));
4476 /* Be compatible with XEmacs. */
4477 return table;
4481 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4482 doc: /* Look up KEY in TABLE and return its associated value.
4483 If KEY is not found, return DFLT which defaults to nil. */)
4484 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4486 struct Lisp_Hash_Table *h = check_hash_table (table);
4487 ptrdiff_t i = hash_lookup (h, key, NULL);
4488 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4492 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4493 doc: /* Associate KEY with VALUE in hash table TABLE.
4494 If KEY is already present in table, replace its current value with
4495 VALUE. In any case, return VALUE. */)
4496 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4498 struct Lisp_Hash_Table *h = check_hash_table (table);
4499 ptrdiff_t i;
4500 EMACS_UINT hash;
4502 i = hash_lookup (h, key, &hash);
4503 if (i >= 0)
4504 HASH_VALUE (h, i) = value;
4505 else
4506 hash_put (h, key, value, hash);
4508 return value;
4512 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4513 doc: /* Remove KEY from TABLE. */)
4514 (Lisp_Object key, Lisp_Object table)
4516 struct Lisp_Hash_Table *h = check_hash_table (table);
4517 hash_remove_from_table (h, key);
4518 return Qnil;
4522 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4523 doc: /* Call FUNCTION for all entries in hash table TABLE.
4524 FUNCTION is called with two arguments, KEY and VALUE. */)
4525 (Lisp_Object function, Lisp_Object table)
4527 struct Lisp_Hash_Table *h = check_hash_table (table);
4528 Lisp_Object args[3];
4529 EMACS_INT i;
4531 for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
4532 if (!NILP (HASH_HASH (h, i)))
4534 args[0] = function;
4535 args[1] = HASH_KEY (h, i);
4536 args[2] = HASH_VALUE (h, i);
4537 Ffuncall (3, args);
4540 return Qnil;
4544 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4545 Sdefine_hash_table_test, 3, 3, 0,
4546 doc: /* Define a new hash table test with name NAME, a symbol.
4548 In hash tables created with NAME specified as test, use TEST to
4549 compare keys, and HASH for computing hash codes of keys.
4551 TEST must be a function taking two arguments and returning non-nil if
4552 both arguments are the same. HASH must be a function taking one
4553 argument and return an integer that is the hash code of the argument.
4554 Hash code computation should use the whole value range of integers,
4555 including negative integers. */)
4556 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4558 return Fput (name, Qhash_table_test, list2 (test, hash));
4563 /************************************************************************
4564 MD5, SHA-1, and SHA-2
4565 ************************************************************************/
4567 #include "md5.h"
4568 #include "sha1.h"
4569 #include "sha256.h"
4570 #include "sha512.h"
4572 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4574 static Lisp_Object
4575 secure_hash (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror, Lisp_Object binary)
4577 int i;
4578 EMACS_INT size;
4579 EMACS_INT size_byte = 0;
4580 EMACS_INT start_char = 0, end_char = 0;
4581 EMACS_INT start_byte = 0, end_byte = 0;
4582 register EMACS_INT b, e;
4583 register struct buffer *bp;
4584 EMACS_INT temp;
4585 int digest_size;
4586 void *(*hash_func) (const char *, size_t, void *);
4587 Lisp_Object digest;
4589 CHECK_SYMBOL (algorithm);
4591 if (STRINGP (object))
4593 if (NILP (coding_system))
4595 /* Decide the coding-system to encode the data with. */
4597 if (STRING_MULTIBYTE (object))
4598 /* use default, we can't guess correct value */
4599 coding_system = preferred_coding_system ();
4600 else
4601 coding_system = Qraw_text;
4604 if (NILP (Fcoding_system_p (coding_system)))
4606 /* Invalid coding system. */
4608 if (!NILP (noerror))
4609 coding_system = Qraw_text;
4610 else
4611 xsignal1 (Qcoding_system_error, coding_system);
4614 if (STRING_MULTIBYTE (object))
4615 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4617 size = SCHARS (object);
4618 size_byte = SBYTES (object);
4620 if (!NILP (start))
4622 CHECK_NUMBER (start);
4624 start_char = XINT (start);
4626 if (start_char < 0)
4627 start_char += size;
4629 start_byte = string_char_to_byte (object, start_char);
4632 if (NILP (end))
4634 end_char = size;
4635 end_byte = size_byte;
4637 else
4639 CHECK_NUMBER (end);
4641 end_char = XINT (end);
4643 if (end_char < 0)
4644 end_char += size;
4646 end_byte = string_char_to_byte (object, end_char);
4649 if (!(0 <= start_char && start_char <= end_char && end_char <= size))
4650 args_out_of_range_3 (object, make_number (start_char),
4651 make_number (end_char));
4653 else
4655 struct buffer *prev = current_buffer;
4657 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
4659 CHECK_BUFFER (object);
4661 bp = XBUFFER (object);
4662 if (bp != current_buffer)
4663 set_buffer_internal (bp);
4665 if (NILP (start))
4666 b = BEGV;
4667 else
4669 CHECK_NUMBER_COERCE_MARKER (start);
4670 b = XINT (start);
4673 if (NILP (end))
4674 e = ZV;
4675 else
4677 CHECK_NUMBER_COERCE_MARKER (end);
4678 e = XINT (end);
4681 if (b > e)
4682 temp = b, b = e, e = temp;
4684 if (!(BEGV <= b && e <= ZV))
4685 args_out_of_range (start, end);
4687 if (NILP (coding_system))
4689 /* Decide the coding-system to encode the data with.
4690 See fileio.c:Fwrite-region */
4692 if (!NILP (Vcoding_system_for_write))
4693 coding_system = Vcoding_system_for_write;
4694 else
4696 int force_raw_text = 0;
4698 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4699 if (NILP (coding_system)
4700 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4702 coding_system = Qnil;
4703 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4704 force_raw_text = 1;
4707 if (NILP (coding_system) && !NILP (Fbuffer_file_name (object)))
4709 /* Check file-coding-system-alist. */
4710 Lisp_Object args[4], val;
4712 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4713 args[3] = Fbuffer_file_name (object);
4714 val = Ffind_operation_coding_system (4, args);
4715 if (CONSP (val) && !NILP (XCDR (val)))
4716 coding_system = XCDR (val);
4719 if (NILP (coding_system)
4720 && !NILP (BVAR (XBUFFER (object), buffer_file_coding_system)))
4722 /* If we still have not decided a coding system, use the
4723 default value of buffer-file-coding-system. */
4724 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4727 if (!force_raw_text
4728 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4729 /* Confirm that VAL can surely encode the current region. */
4730 coding_system = call4 (Vselect_safe_coding_system_function,
4731 make_number (b), make_number (e),
4732 coding_system, Qnil);
4734 if (force_raw_text)
4735 coding_system = Qraw_text;
4738 if (NILP (Fcoding_system_p (coding_system)))
4740 /* Invalid coding system. */
4742 if (!NILP (noerror))
4743 coding_system = Qraw_text;
4744 else
4745 xsignal1 (Qcoding_system_error, coding_system);
4749 object = make_buffer_string (b, e, 0);
4750 if (prev != current_buffer)
4751 set_buffer_internal (prev);
4752 /* Discard the unwind protect for recovering the current
4753 buffer. */
4754 specpdl_ptr--;
4756 if (STRING_MULTIBYTE (object))
4757 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4760 if (EQ (algorithm, Qmd5))
4762 digest_size = MD5_DIGEST_SIZE;
4763 hash_func = md5_buffer;
4765 else if (EQ (algorithm, Qsha1))
4767 digest_size = SHA1_DIGEST_SIZE;
4768 hash_func = sha1_buffer;
4770 else if (EQ (algorithm, Qsha224))
4772 digest_size = SHA224_DIGEST_SIZE;
4773 hash_func = sha224_buffer;
4775 else if (EQ (algorithm, Qsha256))
4777 digest_size = SHA256_DIGEST_SIZE;
4778 hash_func = sha256_buffer;
4780 else if (EQ (algorithm, Qsha384))
4782 digest_size = SHA384_DIGEST_SIZE;
4783 hash_func = sha384_buffer;
4785 else if (EQ (algorithm, Qsha512))
4787 digest_size = SHA512_DIGEST_SIZE;
4788 hash_func = sha512_buffer;
4790 else
4791 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm)));
4793 /* allocate 2 x digest_size so that it can be re-used to hold the
4794 hexified value */
4795 digest = make_uninit_string (digest_size * 2);
4797 hash_func (SSDATA (object) + start_byte,
4798 SBYTES (object) - (size_byte - end_byte),
4799 SSDATA (digest));
4801 if (NILP (binary))
4803 unsigned char *p = SDATA (digest);
4804 for (i = digest_size - 1; i >= 0; i--)
4806 static char const hexdigit[16] = "0123456789abcdef";
4807 int p_i = p[i];
4808 p[2 * i] = hexdigit[p_i >> 4];
4809 p[2 * i + 1] = hexdigit[p_i & 0xf];
4811 return digest;
4813 else
4814 return make_unibyte_string (SSDATA (digest), digest_size);
4817 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
4818 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
4820 A message digest is a cryptographic checksum of a document, and the
4821 algorithm to calculate it is defined in RFC 1321.
4823 The two optional arguments START and END are character positions
4824 specifying for which part of OBJECT the message digest should be
4825 computed. If nil or omitted, the digest is computed for the whole
4826 OBJECT.
4828 The MD5 message digest is computed from the result of encoding the
4829 text in a coding system, not directly from the internal Emacs form of
4830 the text. The optional fourth argument CODING-SYSTEM specifies which
4831 coding system to encode the text with. It should be the same coding
4832 system that you used or will use when actually writing the text into a
4833 file.
4835 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
4836 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
4837 system would be chosen by default for writing this text into a file.
4839 If OBJECT is a string, the most preferred coding system (see the
4840 command `prefer-coding-system') is used.
4842 If NOERROR is non-nil, silently assume the `raw-text' coding if the
4843 guesswork fails. Normally, an error is signaled in such case. */)
4844 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
4846 return secure_hash (Qmd5, object, start, end, coding_system, noerror, Qnil);
4849 DEFUN ("secure-hash", Fsecure_hash, Ssecure_hash, 2, 5, 0,
4850 doc: /* Return the secure hash of an OBJECT.
4851 ALGORITHM is a symbol: md5, sha1, sha224, sha256, sha384 or sha512.
4852 OBJECT is either a string or a buffer.
4853 Optional arguments START and END are character positions specifying
4854 which portion of OBJECT for computing the hash. If BINARY is non-nil,
4855 return a string in binary form. */)
4856 (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object binary)
4858 return secure_hash (algorithm, object, start, end, Qnil, Qnil, binary);
4861 void
4862 syms_of_fns (void)
4864 DEFSYM (Qmd5, "md5");
4865 DEFSYM (Qsha1, "sha1");
4866 DEFSYM (Qsha224, "sha224");
4867 DEFSYM (Qsha256, "sha256");
4868 DEFSYM (Qsha384, "sha384");
4869 DEFSYM (Qsha512, "sha512");
4871 /* Hash table stuff. */
4872 DEFSYM (Qhash_table_p, "hash-table-p");
4873 DEFSYM (Qeq, "eq");
4874 DEFSYM (Qeql, "eql");
4875 DEFSYM (Qequal, "equal");
4876 DEFSYM (QCtest, ":test");
4877 DEFSYM (QCsize, ":size");
4878 DEFSYM (QCrehash_size, ":rehash-size");
4879 DEFSYM (QCrehash_threshold, ":rehash-threshold");
4880 DEFSYM (QCweakness, ":weakness");
4881 DEFSYM (Qkey, "key");
4882 DEFSYM (Qvalue, "value");
4883 DEFSYM (Qhash_table_test, "hash-table-test");
4884 DEFSYM (Qkey_or_value, "key-or-value");
4885 DEFSYM (Qkey_and_value, "key-and-value");
4887 defsubr (&Ssxhash);
4888 defsubr (&Smake_hash_table);
4889 defsubr (&Scopy_hash_table);
4890 defsubr (&Shash_table_count);
4891 defsubr (&Shash_table_rehash_size);
4892 defsubr (&Shash_table_rehash_threshold);
4893 defsubr (&Shash_table_size);
4894 defsubr (&Shash_table_test);
4895 defsubr (&Shash_table_weakness);
4896 defsubr (&Shash_table_p);
4897 defsubr (&Sclrhash);
4898 defsubr (&Sgethash);
4899 defsubr (&Sputhash);
4900 defsubr (&Sremhash);
4901 defsubr (&Smaphash);
4902 defsubr (&Sdefine_hash_table_test);
4904 DEFSYM (Qstring_lessp, "string-lessp");
4905 DEFSYM (Qprovide, "provide");
4906 DEFSYM (Qrequire, "require");
4907 DEFSYM (Qyes_or_no_p_history, "yes-or-no-p-history");
4908 DEFSYM (Qcursor_in_echo_area, "cursor-in-echo-area");
4909 DEFSYM (Qwidget_type, "widget-type");
4911 staticpro (&string_char_byte_cache_string);
4912 string_char_byte_cache_string = Qnil;
4914 require_nesting_list = Qnil;
4915 staticpro (&require_nesting_list);
4917 Fset (Qyes_or_no_p_history, Qnil);
4919 DEFVAR_LISP ("features", Vfeatures,
4920 doc: /* A list of symbols which are the features of the executing Emacs.
4921 Used by `featurep' and `require', and altered by `provide'. */);
4922 Vfeatures = Fcons (intern_c_string ("emacs"), Qnil);
4923 DEFSYM (Qsubfeatures, "subfeatures");
4925 #ifdef HAVE_LANGINFO_CODESET
4926 DEFSYM (Qcodeset, "codeset");
4927 DEFSYM (Qdays, "days");
4928 DEFSYM (Qmonths, "months");
4929 DEFSYM (Qpaper, "paper");
4930 #endif /* HAVE_LANGINFO_CODESET */
4932 DEFVAR_BOOL ("use-dialog-box", use_dialog_box,
4933 doc: /* *Non-nil means mouse commands use dialog boxes to ask questions.
4934 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
4935 invoked by mouse clicks and mouse menu items.
4937 On some platforms, file selection dialogs are also enabled if this is
4938 non-nil. */);
4939 use_dialog_box = 1;
4941 DEFVAR_BOOL ("use-file-dialog", use_file_dialog,
4942 doc: /* *Non-nil means mouse commands use a file dialog to ask for files.
4943 This applies to commands from menus and tool bar buttons even when
4944 they are initiated from the keyboard. If `use-dialog-box' is nil,
4945 that disables the use of a file dialog, regardless of the value of
4946 this variable. */);
4947 use_file_dialog = 1;
4949 defsubr (&Sidentity);
4950 defsubr (&Srandom);
4951 defsubr (&Slength);
4952 defsubr (&Ssafe_length);
4953 defsubr (&Sstring_bytes);
4954 defsubr (&Sstring_equal);
4955 defsubr (&Scompare_strings);
4956 defsubr (&Sstring_lessp);
4957 defsubr (&Sappend);
4958 defsubr (&Sconcat);
4959 defsubr (&Svconcat);
4960 defsubr (&Scopy_sequence);
4961 defsubr (&Sstring_make_multibyte);
4962 defsubr (&Sstring_make_unibyte);
4963 defsubr (&Sstring_as_multibyte);
4964 defsubr (&Sstring_as_unibyte);
4965 defsubr (&Sstring_to_multibyte);
4966 defsubr (&Sstring_to_unibyte);
4967 defsubr (&Scopy_alist);
4968 defsubr (&Ssubstring);
4969 defsubr (&Ssubstring_no_properties);
4970 defsubr (&Snthcdr);
4971 defsubr (&Snth);
4972 defsubr (&Selt);
4973 defsubr (&Smember);
4974 defsubr (&Smemq);
4975 defsubr (&Smemql);
4976 defsubr (&Sassq);
4977 defsubr (&Sassoc);
4978 defsubr (&Srassq);
4979 defsubr (&Srassoc);
4980 defsubr (&Sdelq);
4981 defsubr (&Sdelete);
4982 defsubr (&Snreverse);
4983 defsubr (&Sreverse);
4984 defsubr (&Ssort);
4985 defsubr (&Splist_get);
4986 defsubr (&Sget);
4987 defsubr (&Splist_put);
4988 defsubr (&Sput);
4989 defsubr (&Slax_plist_get);
4990 defsubr (&Slax_plist_put);
4991 defsubr (&Seql);
4992 defsubr (&Sequal);
4993 defsubr (&Sequal_including_properties);
4994 defsubr (&Sfillarray);
4995 defsubr (&Sclear_string);
4996 defsubr (&Snconc);
4997 defsubr (&Smapcar);
4998 defsubr (&Smapc);
4999 defsubr (&Smapconcat);
5000 defsubr (&Syes_or_no_p);
5001 defsubr (&Sload_average);
5002 defsubr (&Sfeaturep);
5003 defsubr (&Srequire);
5004 defsubr (&Sprovide);
5005 defsubr (&Splist_member);
5006 defsubr (&Swidget_put);
5007 defsubr (&Swidget_get);
5008 defsubr (&Swidget_apply);
5009 defsubr (&Sbase64_encode_region);
5010 defsubr (&Sbase64_decode_region);
5011 defsubr (&Sbase64_encode_string);
5012 defsubr (&Sbase64_decode_string);
5013 defsubr (&Smd5);
5014 defsubr (&Ssecure_hash);
5015 defsubr (&Slocale_info);
5019 void
5020 init_fns (void)