(menu_bar_item): Detect duplicate entries for all items
[emacs.git] / src / fns.c
blob1f53ecb4a04632f6ab2577232a73a979ead77db5
1 /* Random utility Lisp functions.
2 Copyright (C) 1985, 86, 87, 93, 94, 95, 97, 98, 99, 2000 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
22 #include <config.h>
24 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #include <time.h>
29 /* Note on some machines this defines `vector' as a typedef,
30 so make sure we don't use that name in this file. */
31 #undef vector
32 #define vector *****
34 #include "lisp.h"
35 #include "commands.h"
36 #include "charset.h"
38 #include "buffer.h"
39 #include "keyboard.h"
40 #include "intervals.h"
41 #include "frame.h"
42 #include "window.h"
43 #if defined (HAVE_MENUS) && defined (HAVE_X_WINDOWS)
44 #include "xterm.h"
45 #endif
47 #ifndef NULL
48 #define NULL (void *)0
49 #endif
51 #ifndef min
52 #define min(a, b) ((a) < (b) ? (a) : (b))
53 #define max(a, b) ((a) > (b) ? (a) : (b))
54 #endif
56 /* Nonzero enables use of dialog boxes for questions
57 asked by mouse commands. */
58 int use_dialog_box;
60 extern int minibuffer_auto_raise;
61 extern Lisp_Object minibuf_window;
63 Lisp_Object Qstring_lessp, Qprovide, Qrequire;
64 Lisp_Object Qyes_or_no_p_history;
65 Lisp_Object Qcursor_in_echo_area;
66 Lisp_Object Qwidget_type;
68 extern Lisp_Object Qinput_method_function;
70 static int internal_equal ();
72 extern long get_random ();
73 extern void seed_random ();
75 #ifndef HAVE_UNISTD_H
76 extern long time ();
77 #endif
79 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
80 "Return the argument unchanged.")
81 (arg)
82 Lisp_Object arg;
84 return arg;
87 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
88 "Return a pseudo-random number.\n\
89 All integers representable in Lisp are equally likely.\n\
90 On most systems, this is 28 bits' worth.\n\
91 With positive integer argument N, return random number in interval [0,N).\n\
92 With argument t, set the random number seed from the current time and pid.")
93 (n)
94 Lisp_Object n;
96 EMACS_INT val;
97 Lisp_Object lispy_val;
98 unsigned long denominator;
100 if (EQ (n, Qt))
101 seed_random (getpid () + time (NULL));
102 if (NATNUMP (n) && XFASTINT (n) != 0)
104 /* Try to take our random number from the higher bits of VAL,
105 not the lower, since (says Gentzel) the low bits of `random'
106 are less random than the higher ones. We do this by using the
107 quotient rather than the remainder. At the high end of the RNG
108 it's possible to get a quotient larger than n; discarding
109 these values eliminates the bias that would otherwise appear
110 when using a large n. */
111 denominator = ((unsigned long)1 << VALBITS) / XFASTINT (n);
113 val = get_random () / denominator;
114 while (val >= XFASTINT (n));
116 else
117 val = get_random ();
118 XSETINT (lispy_val, val);
119 return lispy_val;
122 /* Random data-structure functions */
124 DEFUN ("length", Flength, Slength, 1, 1, 0,
125 "Return the length of vector, list or string SEQUENCE.\n\
126 A byte-code function object is also allowed.\n\
127 If the string contains multibyte characters, this is not the necessarily\n\
128 the number of bytes in the string; it is the number of characters.\n\
129 To get the number of bytes, use `string-bytes'")
130 (sequence)
131 register Lisp_Object sequence;
133 register Lisp_Object tail, val;
134 register int i;
136 retry:
137 if (STRINGP (sequence))
138 XSETFASTINT (val, XSTRING (sequence)->size);
139 else if (VECTORP (sequence))
140 XSETFASTINT (val, XVECTOR (sequence)->size);
141 else if (CHAR_TABLE_P (sequence))
142 XSETFASTINT (val, MAX_CHAR);
143 else if (BOOL_VECTOR_P (sequence))
144 XSETFASTINT (val, XBOOL_VECTOR (sequence)->size);
145 else if (COMPILEDP (sequence))
146 XSETFASTINT (val, XVECTOR (sequence)->size & PSEUDOVECTOR_SIZE_MASK);
147 else if (CONSP (sequence))
149 i = 0;
150 while (CONSP (sequence))
152 sequence = XCDR (sequence);
153 ++i;
155 if (!CONSP (sequence))
156 break;
158 sequence = XCDR (sequence);
159 ++i;
160 QUIT;
163 if (!NILP (sequence))
164 wrong_type_argument (Qlistp, sequence);
166 val = make_number (i);
168 else if (NILP (sequence))
169 XSETFASTINT (val, 0);
170 else
172 sequence = wrong_type_argument (Qsequencep, sequence);
173 goto retry;
175 return val;
178 /* This does not check for quits. That is safe
179 since it must terminate. */
181 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
182 "Return the length of a list, but avoid error or infinite loop.\n\
183 This function never gets an error. If LIST is not really a list,\n\
184 it returns 0. If LIST is circular, it returns a finite value\n\
185 which is at least the number of distinct elements.")
186 (list)
187 Lisp_Object list;
189 Lisp_Object tail, halftail, length;
190 int len = 0;
192 /* halftail is used to detect circular lists. */
193 halftail = list;
194 for (tail = list; CONSP (tail); tail = XCDR (tail))
196 if (EQ (tail, halftail) && len != 0)
197 break;
198 len++;
199 if ((len & 1) == 0)
200 halftail = XCDR (halftail);
203 XSETINT (length, len);
204 return length;
207 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
208 "Return the number of bytes in STRING.\n\
209 If STRING is a multibyte string, this is greater than the length of STRING.")
210 (string)
211 Lisp_Object string;
213 CHECK_STRING (string, 1);
214 return make_number (STRING_BYTES (XSTRING (string)));
217 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
218 "Return t if two strings have identical contents.\n\
219 Case is significant, but text properties are ignored.\n\
220 Symbols are also allowed; their print names are used instead.")
221 (s1, s2)
222 register Lisp_Object s1, s2;
224 if (SYMBOLP (s1))
225 XSETSTRING (s1, XSYMBOL (s1)->name);
226 if (SYMBOLP (s2))
227 XSETSTRING (s2, XSYMBOL (s2)->name);
228 CHECK_STRING (s1, 0);
229 CHECK_STRING (s2, 1);
231 if (XSTRING (s1)->size != XSTRING (s2)->size
232 || STRING_BYTES (XSTRING (s1)) != STRING_BYTES (XSTRING (s2))
233 || bcmp (XSTRING (s1)->data, XSTRING (s2)->data, STRING_BYTES (XSTRING (s1))))
234 return Qnil;
235 return Qt;
238 DEFUN ("compare-strings", Fcompare_strings,
239 Scompare_strings, 6, 7, 0,
240 "Compare the contents of two strings, converting to multibyte if needed.\n\
241 In string STR1, skip the first START1 characters and stop at END1.\n\
242 In string STR2, skip the first START2 characters and stop at END2.\n\
243 END1 and END2 default to the full lengths of the respective strings.\n\
245 Case is significant in this comparison if IGNORE-CASE is nil.\n\
246 Unibyte strings are converted to multibyte for comparison.\n\
248 The value is t if the strings (or specified portions) match.\n\
249 If string STR1 is less, the value is a negative number N;\n\
250 - 1 - N is the number of characters that match at the beginning.\n\
251 If string STR1 is greater, the value is a positive number N;\n\
252 N - 1 is the number of characters that match at the beginning.")
253 (str1, start1, end1, str2, start2, end2, ignore_case)
254 Lisp_Object str1, start1, end1, start2, str2, end2, ignore_case;
256 register int end1_char, end2_char;
257 register int i1, i1_byte, i2, i2_byte;
259 CHECK_STRING (str1, 0);
260 CHECK_STRING (str2, 1);
261 if (NILP (start1))
262 start1 = make_number (0);
263 if (NILP (start2))
264 start2 = make_number (0);
265 CHECK_NATNUM (start1, 2);
266 CHECK_NATNUM (start2, 3);
267 if (! NILP (end1))
268 CHECK_NATNUM (end1, 4);
269 if (! NILP (end2))
270 CHECK_NATNUM (end2, 4);
272 i1 = XINT (start1);
273 i2 = XINT (start2);
275 i1_byte = string_char_to_byte (str1, i1);
276 i2_byte = string_char_to_byte (str2, i2);
278 end1_char = XSTRING (str1)->size;
279 if (! NILP (end1) && end1_char > XINT (end1))
280 end1_char = XINT (end1);
282 end2_char = XSTRING (str2)->size;
283 if (! NILP (end2) && end2_char > XINT (end2))
284 end2_char = XINT (end2);
286 while (i1 < end1_char && i2 < end2_char)
288 /* When we find a mismatch, we must compare the
289 characters, not just the bytes. */
290 int c1, c2;
292 if (STRING_MULTIBYTE (str1))
293 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c1, str1, i1, i1_byte);
294 else
296 c1 = XSTRING (str1)->data[i1++];
297 c1 = unibyte_char_to_multibyte (c1);
300 if (STRING_MULTIBYTE (str2))
301 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c2, str2, i2, i2_byte);
302 else
304 c2 = XSTRING (str2)->data[i2++];
305 c2 = unibyte_char_to_multibyte (c2);
308 if (c1 == c2)
309 continue;
311 if (! NILP (ignore_case))
313 Lisp_Object tem;
315 tem = Fupcase (make_number (c1));
316 c1 = XINT (tem);
317 tem = Fupcase (make_number (c2));
318 c2 = XINT (tem);
321 if (c1 == c2)
322 continue;
324 /* Note that I1 has already been incremented
325 past the character that we are comparing;
326 hence we don't add or subtract 1 here. */
327 if (c1 < c2)
328 return make_number (- i1);
329 else
330 return make_number (i1);
333 if (i1 < end1_char)
334 return make_number (i1 - XINT (start1) + 1);
335 if (i2 < end2_char)
336 return make_number (- i1 + XINT (start1) - 1);
338 return Qt;
341 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
342 "Return t if first arg string is less than second in lexicographic order.\n\
343 Case is significant.\n\
344 Symbols are also allowed; their print names are used instead.")
345 (s1, s2)
346 register Lisp_Object s1, s2;
348 register int end;
349 register int i1, i1_byte, i2, i2_byte;
351 if (SYMBOLP (s1))
352 XSETSTRING (s1, XSYMBOL (s1)->name);
353 if (SYMBOLP (s2))
354 XSETSTRING (s2, XSYMBOL (s2)->name);
355 CHECK_STRING (s1, 0);
356 CHECK_STRING (s2, 1);
358 i1 = i1_byte = i2 = i2_byte = 0;
360 end = XSTRING (s1)->size;
361 if (end > XSTRING (s2)->size)
362 end = XSTRING (s2)->size;
364 while (i1 < end)
366 /* When we find a mismatch, we must compare the
367 characters, not just the bytes. */
368 int c1, c2;
370 FETCH_STRING_CHAR_ADVANCE (c1, s1, i1, i1_byte);
371 FETCH_STRING_CHAR_ADVANCE (c2, s2, i2, i2_byte);
373 if (c1 != c2)
374 return c1 < c2 ? Qt : Qnil;
376 return i1 < XSTRING (s2)->size ? Qt : Qnil;
379 static Lisp_Object concat ();
381 /* ARGSUSED */
382 Lisp_Object
383 concat2 (s1, s2)
384 Lisp_Object s1, s2;
386 #ifdef NO_ARG_ARRAY
387 Lisp_Object args[2];
388 args[0] = s1;
389 args[1] = s2;
390 return concat (2, args, Lisp_String, 0);
391 #else
392 return concat (2, &s1, Lisp_String, 0);
393 #endif /* NO_ARG_ARRAY */
396 /* ARGSUSED */
397 Lisp_Object
398 concat3 (s1, s2, s3)
399 Lisp_Object s1, s2, s3;
401 #ifdef NO_ARG_ARRAY
402 Lisp_Object args[3];
403 args[0] = s1;
404 args[1] = s2;
405 args[2] = s3;
406 return concat (3, args, Lisp_String, 0);
407 #else
408 return concat (3, &s1, Lisp_String, 0);
409 #endif /* NO_ARG_ARRAY */
412 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
413 "Concatenate all the arguments and make the result a list.\n\
414 The result is a list whose elements are the elements of all the arguments.\n\
415 Each argument may be a list, vector or string.\n\
416 The last argument is not copied, just used as the tail of the new list.")
417 (nargs, args)
418 int nargs;
419 Lisp_Object *args;
421 return concat (nargs, args, Lisp_Cons, 1);
424 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
425 "Concatenate all the arguments and make the result a string.\n\
426 The result is a string whose elements are the elements of all the arguments.\n\
427 Each argument may be a string or a list or vector of characters (integers).")
428 (nargs, args)
429 int nargs;
430 Lisp_Object *args;
432 return concat (nargs, args, Lisp_String, 0);
435 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
436 "Concatenate all the arguments and make the result a vector.\n\
437 The result is a vector whose elements are the elements of all the arguments.\n\
438 Each argument may be a list, vector or string.")
439 (nargs, args)
440 int nargs;
441 Lisp_Object *args;
443 return concat (nargs, args, Lisp_Vectorlike, 0);
446 /* Retrun a copy of a sub char table ARG. The elements except for a
447 nested sub char table are not copied. */
448 static Lisp_Object
449 copy_sub_char_table (arg)
450 Lisp_Object arg;
452 Lisp_Object copy = make_sub_char_table (XCHAR_TABLE (arg)->defalt);
453 int i;
455 /* Copy all the contents. */
456 bcopy (XCHAR_TABLE (arg)->contents, XCHAR_TABLE (copy)->contents,
457 SUB_CHAR_TABLE_ORDINARY_SLOTS * sizeof (Lisp_Object));
458 /* Recursively copy any sub char-tables in the ordinary slots. */
459 for (i = 32; i < SUB_CHAR_TABLE_ORDINARY_SLOTS; i++)
460 if (SUB_CHAR_TABLE_P (XCHAR_TABLE (arg)->contents[i]))
461 XCHAR_TABLE (copy)->contents[i]
462 = copy_sub_char_table (XCHAR_TABLE (copy)->contents[i]);
464 return copy;
468 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
469 "Return a copy of a list, vector or string.\n\
470 The elements of a list or vector are not copied; they are shared\n\
471 with the original.")
472 (arg)
473 Lisp_Object arg;
475 if (NILP (arg)) return arg;
477 if (CHAR_TABLE_P (arg))
479 int i;
480 Lisp_Object copy;
482 copy = Fmake_char_table (XCHAR_TABLE (arg)->purpose, Qnil);
483 /* Copy all the slots, including the extra ones. */
484 bcopy (XVECTOR (arg)->contents, XVECTOR (copy)->contents,
485 ((XCHAR_TABLE (arg)->size & PSEUDOVECTOR_SIZE_MASK)
486 * sizeof (Lisp_Object)));
488 /* Recursively copy any sub char tables in the ordinary slots
489 for multibyte characters. */
490 for (i = CHAR_TABLE_SINGLE_BYTE_SLOTS;
491 i < CHAR_TABLE_ORDINARY_SLOTS; i++)
492 if (SUB_CHAR_TABLE_P (XCHAR_TABLE (arg)->contents[i]))
493 XCHAR_TABLE (copy)->contents[i]
494 = copy_sub_char_table (XCHAR_TABLE (copy)->contents[i]);
496 return copy;
499 if (BOOL_VECTOR_P (arg))
501 Lisp_Object val;
502 int size_in_chars
503 = (XBOOL_VECTOR (arg)->size + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
505 val = Fmake_bool_vector (Flength (arg), Qnil);
506 bcopy (XBOOL_VECTOR (arg)->data, XBOOL_VECTOR (val)->data,
507 size_in_chars);
508 return val;
511 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
512 arg = wrong_type_argument (Qsequencep, arg);
513 return concat (1, &arg, CONSP (arg) ? Lisp_Cons : XTYPE (arg), 0);
516 /* In string STR of length LEN, see if bytes before STR[I] combine
517 with bytes after STR[I] to form a single character. If so, return
518 the number of bytes after STR[I] which combine in this way.
519 Otherwize, return 0. */
521 static int
522 count_combining (str, len, i)
523 unsigned char *str;
524 int len, i;
526 int j = i - 1, bytes;
528 if (i == 0 || i == len || CHAR_HEAD_P (str[i]))
529 return 0;
530 while (j >= 0 && !CHAR_HEAD_P (str[j])) j--;
531 if (j < 0 || ! BASE_LEADING_CODE_P (str[j]))
532 return 0;
533 PARSE_MULTIBYTE_SEQ (str + j, len - j, bytes);
534 return (bytes <= i - j ? 0 : bytes - (i - j));
537 /* This structure holds information of an argument of `concat' that is
538 a string and has text properties to be copied. */
539 struct textprop_rec
541 int argnum; /* refer to ARGS (arguments of `concat') */
542 int from; /* refer to ARGS[argnum] (argument string) */
543 int to; /* refer to VAL (the target string) */
546 static Lisp_Object
547 concat (nargs, args, target_type, last_special)
548 int nargs;
549 Lisp_Object *args;
550 enum Lisp_Type target_type;
551 int last_special;
553 Lisp_Object val;
554 register Lisp_Object tail;
555 register Lisp_Object this;
556 int toindex;
557 int toindex_byte;
558 register int result_len;
559 register int result_len_byte;
560 register int argnum;
561 Lisp_Object last_tail;
562 Lisp_Object prev;
563 int some_multibyte;
564 /* When we make a multibyte string, we can't copy text properties
565 while concatinating each string because the length of resulting
566 string can't be decided until we finish the whole concatination.
567 So, we record strings that have text properties to be copied
568 here, and copy the text properties after the concatination. */
569 struct textprop_rec *textprops;
570 /* Number of elments in textprops. */
571 int num_textprops = 0;
573 /* In append, the last arg isn't treated like the others */
574 if (last_special && nargs > 0)
576 nargs--;
577 last_tail = args[nargs];
579 else
580 last_tail = Qnil;
582 /* Canonicalize each argument. */
583 for (argnum = 0; argnum < nargs; argnum++)
585 this = args[argnum];
586 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
587 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
589 args[argnum] = wrong_type_argument (Qsequencep, this);
593 /* Compute total length in chars of arguments in RESULT_LEN.
594 If desired output is a string, also compute length in bytes
595 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
596 whether the result should be a multibyte string. */
597 result_len_byte = 0;
598 result_len = 0;
599 some_multibyte = 0;
600 for (argnum = 0; argnum < nargs; argnum++)
602 int len;
603 this = args[argnum];
604 len = XFASTINT (Flength (this));
605 if (target_type == Lisp_String)
607 /* We must count the number of bytes needed in the string
608 as well as the number of characters. */
609 int i;
610 Lisp_Object ch;
611 int this_len_byte;
613 if (VECTORP (this))
614 for (i = 0; i < len; i++)
616 ch = XVECTOR (this)->contents[i];
617 if (! INTEGERP (ch))
618 wrong_type_argument (Qintegerp, ch);
619 this_len_byte = CHAR_BYTES (XINT (ch));
620 result_len_byte += this_len_byte;
621 if (!SINGLE_BYTE_CHAR_P (XINT (ch)))
622 some_multibyte = 1;
624 else if (BOOL_VECTOR_P (this) && XBOOL_VECTOR (this)->size > 0)
625 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
626 else if (CONSP (this))
627 for (; CONSP (this); this = XCDR (this))
629 ch = XCAR (this);
630 if (! INTEGERP (ch))
631 wrong_type_argument (Qintegerp, ch);
632 this_len_byte = CHAR_BYTES (XINT (ch));
633 result_len_byte += this_len_byte;
634 if (!SINGLE_BYTE_CHAR_P (XINT (ch)))
635 some_multibyte = 1;
637 else if (STRINGP (this))
639 if (STRING_MULTIBYTE (this))
641 some_multibyte = 1;
642 result_len_byte += STRING_BYTES (XSTRING (this));
644 else
645 result_len_byte += count_size_as_multibyte (XSTRING (this)->data,
646 XSTRING (this)->size);
650 result_len += len;
653 if (! some_multibyte)
654 result_len_byte = result_len;
656 /* Create the output object. */
657 if (target_type == Lisp_Cons)
658 val = Fmake_list (make_number (result_len), Qnil);
659 else if (target_type == Lisp_Vectorlike)
660 val = Fmake_vector (make_number (result_len), Qnil);
661 else if (some_multibyte)
662 val = make_uninit_multibyte_string (result_len, result_len_byte);
663 else
664 val = make_uninit_string (result_len);
666 /* In `append', if all but last arg are nil, return last arg. */
667 if (target_type == Lisp_Cons && EQ (val, Qnil))
668 return last_tail;
670 /* Copy the contents of the args into the result. */
671 if (CONSP (val))
672 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
673 else
674 toindex = 0, toindex_byte = 0;
676 prev = Qnil;
677 if (STRINGP (val))
678 textprops
679 = (struct textprop_rec *) alloca (sizeof (struct textprop_rec) * nargs);
681 for (argnum = 0; argnum < nargs; argnum++)
683 Lisp_Object thislen;
684 int thisleni;
685 register unsigned int thisindex = 0;
686 register unsigned int thisindex_byte = 0;
688 this = args[argnum];
689 if (!CONSP (this))
690 thislen = Flength (this), thisleni = XINT (thislen);
692 /* Between strings of the same kind, copy fast. */
693 if (STRINGP (this) && STRINGP (val)
694 && STRING_MULTIBYTE (this) == some_multibyte)
696 int thislen_byte = STRING_BYTES (XSTRING (this));
697 int combined;
699 bcopy (XSTRING (this)->data, XSTRING (val)->data + toindex_byte,
700 STRING_BYTES (XSTRING (this)));
701 combined = (some_multibyte && toindex_byte > 0
702 ? count_combining (XSTRING (val)->data,
703 toindex_byte + thislen_byte,
704 toindex_byte)
705 : 0);
706 if (! NULL_INTERVAL_P (XSTRING (this)->intervals))
708 textprops[num_textprops].argnum = argnum;
709 /* We ignore text properties on characters being combined. */
710 textprops[num_textprops].from = combined;
711 textprops[num_textprops++].to = toindex;
713 toindex_byte += thislen_byte;
714 toindex += thisleni - combined;
715 XSTRING (val)->size -= combined;
717 /* Copy a single-byte string to a multibyte string. */
718 else if (STRINGP (this) && STRINGP (val))
720 if (! NULL_INTERVAL_P (XSTRING (this)->intervals))
722 textprops[num_textprops].argnum = argnum;
723 textprops[num_textprops].from = 0;
724 textprops[num_textprops++].to = toindex;
726 toindex_byte += copy_text (XSTRING (this)->data,
727 XSTRING (val)->data + toindex_byte,
728 XSTRING (this)->size, 0, 1);
729 toindex += thisleni;
731 else
732 /* Copy element by element. */
733 while (1)
735 register Lisp_Object elt;
737 /* Fetch next element of `this' arg into `elt', or break if
738 `this' is exhausted. */
739 if (NILP (this)) break;
740 if (CONSP (this))
741 elt = XCAR (this), this = XCDR (this);
742 else if (thisindex >= thisleni)
743 break;
744 else if (STRINGP (this))
746 int c;
747 if (STRING_MULTIBYTE (this))
749 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
750 thisindex,
751 thisindex_byte);
752 XSETFASTINT (elt, c);
754 else
756 XSETFASTINT (elt, XSTRING (this)->data[thisindex++]);
757 if (some_multibyte
758 && (XINT (elt) >= 0240
759 || (XINT (elt) >= 0200
760 && ! NILP (Vnonascii_translation_table)))
761 && XINT (elt) < 0400)
763 c = unibyte_char_to_multibyte (XINT (elt));
764 XSETINT (elt, c);
768 else if (BOOL_VECTOR_P (this))
770 int byte;
771 byte = XBOOL_VECTOR (this)->data[thisindex / BITS_PER_CHAR];
772 if (byte & (1 << (thisindex % BITS_PER_CHAR)))
773 elt = Qt;
774 else
775 elt = Qnil;
776 thisindex++;
778 else
779 elt = XVECTOR (this)->contents[thisindex++];
781 /* Store this element into the result. */
782 if (toindex < 0)
784 XCAR (tail) = elt;
785 prev = tail;
786 tail = XCDR (tail);
788 else if (VECTORP (val))
789 XVECTOR (val)->contents[toindex++] = elt;
790 else
792 CHECK_NUMBER (elt, 0);
793 if (SINGLE_BYTE_CHAR_P (XINT (elt)))
795 if (some_multibyte)
796 toindex_byte
797 += CHAR_STRING (XINT (elt),
798 XSTRING (val)->data + toindex_byte);
799 else
800 XSTRING (val)->data[toindex_byte++] = XINT (elt);
801 if (some_multibyte
802 && toindex_byte > 0
803 && count_combining (XSTRING (val)->data,
804 toindex_byte, toindex_byte - 1))
805 XSTRING (val)->size--;
806 else
807 toindex++;
809 else
810 /* If we have any multibyte characters,
811 we already decided to make a multibyte string. */
813 int c = XINT (elt);
814 /* P exists as a variable
815 to avoid a bug on the Masscomp C compiler. */
816 unsigned char *p = & XSTRING (val)->data[toindex_byte];
818 toindex_byte += CHAR_STRING (c, p);
819 toindex++;
824 if (!NILP (prev))
825 XCDR (prev) = last_tail;
827 if (num_textprops > 0)
829 Lisp_Object props;
831 for (argnum = 0; argnum < num_textprops; argnum++)
833 this = args[textprops[argnum].argnum];
834 props = text_property_list (this,
835 make_number (0),
836 make_number (XSTRING (this)->size),
837 Qnil);
838 /* If successive arguments have properites, be sure that the
839 value of `composition' property be the copy. */
840 if (argnum > 0
841 && textprops[argnum - 1].argnum + 1 == textprops[argnum].argnum)
842 make_composition_value_copy (props);
843 add_text_properties_from_list (val, props,
844 make_number (textprops[argnum].to));
847 return val;
850 static Lisp_Object string_char_byte_cache_string;
851 static int string_char_byte_cache_charpos;
852 static int string_char_byte_cache_bytepos;
854 void
855 clear_string_char_byte_cache ()
857 string_char_byte_cache_string = Qnil;
860 /* Return the character index corresponding to CHAR_INDEX in STRING. */
863 string_char_to_byte (string, char_index)
864 Lisp_Object string;
865 int char_index;
867 int i, i_byte;
868 int best_below, best_below_byte;
869 int best_above, best_above_byte;
871 if (! STRING_MULTIBYTE (string))
872 return char_index;
874 best_below = best_below_byte = 0;
875 best_above = XSTRING (string)->size;
876 best_above_byte = STRING_BYTES (XSTRING (string));
878 if (EQ (string, string_char_byte_cache_string))
880 if (string_char_byte_cache_charpos < char_index)
882 best_below = string_char_byte_cache_charpos;
883 best_below_byte = string_char_byte_cache_bytepos;
885 else
887 best_above = string_char_byte_cache_charpos;
888 best_above_byte = string_char_byte_cache_bytepos;
892 if (char_index - best_below < best_above - char_index)
894 while (best_below < char_index)
896 int c;
897 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, string,
898 best_below, best_below_byte);
900 i = best_below;
901 i_byte = best_below_byte;
903 else
905 while (best_above > char_index)
907 unsigned char *pend = XSTRING (string)->data + best_above_byte;
908 unsigned char *pbeg = pend - best_above_byte;
909 unsigned char *p = pend - 1;
910 int bytes;
912 while (p > pbeg && !CHAR_HEAD_P (*p)) p--;
913 PARSE_MULTIBYTE_SEQ (p, pend - p, bytes);
914 if (bytes == pend - p)
915 best_above_byte -= bytes;
916 else if (bytes > pend - p)
917 best_above_byte -= (pend - p);
918 else
919 best_above_byte--;
920 best_above--;
922 i = best_above;
923 i_byte = best_above_byte;
926 string_char_byte_cache_bytepos = i_byte;
927 string_char_byte_cache_charpos = i;
928 string_char_byte_cache_string = string;
930 return i_byte;
933 /* Return the character index corresponding to BYTE_INDEX in STRING. */
936 string_byte_to_char (string, byte_index)
937 Lisp_Object string;
938 int byte_index;
940 int i, i_byte;
941 int best_below, best_below_byte;
942 int best_above, best_above_byte;
944 if (! STRING_MULTIBYTE (string))
945 return byte_index;
947 best_below = best_below_byte = 0;
948 best_above = XSTRING (string)->size;
949 best_above_byte = STRING_BYTES (XSTRING (string));
951 if (EQ (string, string_char_byte_cache_string))
953 if (string_char_byte_cache_bytepos < byte_index)
955 best_below = string_char_byte_cache_charpos;
956 best_below_byte = string_char_byte_cache_bytepos;
958 else
960 best_above = string_char_byte_cache_charpos;
961 best_above_byte = string_char_byte_cache_bytepos;
965 if (byte_index - best_below_byte < best_above_byte - byte_index)
967 while (best_below_byte < byte_index)
969 int c;
970 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, string,
971 best_below, best_below_byte);
973 i = best_below;
974 i_byte = best_below_byte;
976 else
978 while (best_above_byte > byte_index)
980 unsigned char *pend = XSTRING (string)->data + best_above_byte;
981 unsigned char *pbeg = pend - best_above_byte;
982 unsigned char *p = pend - 1;
983 int bytes;
985 while (p > pbeg && !CHAR_HEAD_P (*p)) p--;
986 PARSE_MULTIBYTE_SEQ (p, pend - p, bytes);
987 if (bytes == pend - p)
988 best_above_byte -= bytes;
989 else if (bytes > pend - p)
990 best_above_byte -= (pend - p);
991 else
992 best_above_byte--;
993 best_above--;
995 i = best_above;
996 i_byte = best_above_byte;
999 string_char_byte_cache_bytepos = i_byte;
1000 string_char_byte_cache_charpos = i;
1001 string_char_byte_cache_string = string;
1003 return i;
1006 /* Convert STRING to a multibyte string.
1007 Single-byte characters 0240 through 0377 are converted
1008 by adding nonascii_insert_offset to each. */
1010 Lisp_Object
1011 string_make_multibyte (string)
1012 Lisp_Object string;
1014 unsigned char *buf;
1015 int nbytes;
1017 if (STRING_MULTIBYTE (string))
1018 return string;
1020 nbytes = count_size_as_multibyte (XSTRING (string)->data,
1021 XSTRING (string)->size);
1022 /* If all the chars are ASCII, they won't need any more bytes
1023 once converted. In that case, we can return STRING itself. */
1024 if (nbytes == STRING_BYTES (XSTRING (string)))
1025 return string;
1027 buf = (unsigned char *) alloca (nbytes);
1028 copy_text (XSTRING (string)->data, buf, STRING_BYTES (XSTRING (string)),
1029 0, 1);
1031 return make_multibyte_string (buf, XSTRING (string)->size, nbytes);
1034 /* Convert STRING to a single-byte string. */
1036 Lisp_Object
1037 string_make_unibyte (string)
1038 Lisp_Object string;
1040 unsigned char *buf;
1042 if (! STRING_MULTIBYTE (string))
1043 return string;
1045 buf = (unsigned char *) alloca (XSTRING (string)->size);
1047 copy_text (XSTRING (string)->data, buf, STRING_BYTES (XSTRING (string)),
1048 1, 0);
1050 return make_unibyte_string (buf, XSTRING (string)->size);
1053 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
1054 1, 1, 0,
1055 "Return the multibyte equivalent of STRING.\n\
1056 The function `unibyte-char-to-multibyte' is used to convert\n\
1057 each unibyte character to a multibyte character.")
1058 (string)
1059 Lisp_Object string;
1061 CHECK_STRING (string, 0);
1063 return string_make_multibyte (string);
1066 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
1067 1, 1, 0,
1068 "Return the unibyte equivalent of STRING.\n\
1069 Multibyte character codes are converted to unibyte\n\
1070 by using just the low 8 bits.")
1071 (string)
1072 Lisp_Object string;
1074 CHECK_STRING (string, 0);
1076 return string_make_unibyte (string);
1079 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
1080 1, 1, 0,
1081 "Return a unibyte string with the same individual bytes as STRING.\n\
1082 If STRING is unibyte, the result is STRING itself.\n\
1083 Otherwise it is a newly created string, with no text properties.\n\
1084 If STRING is multibyte and contains a character of charset `binary',\n\
1085 it is converted to the corresponding single byte.")
1086 (string)
1087 Lisp_Object string;
1089 CHECK_STRING (string, 0);
1091 if (STRING_MULTIBYTE (string))
1093 int bytes = STRING_BYTES (XSTRING (string));
1094 unsigned char *str = (unsigned char *) xmalloc (bytes);
1096 bcopy (XSTRING (string)->data, str, bytes);
1097 bytes = str_as_unibyte (str, bytes);
1098 string = make_unibyte_string (str, bytes);
1099 xfree (str);
1101 return string;
1104 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1105 1, 1, 0,
1106 "Return a multibyte string with the same individual bytes as STRING.\n\
1107 If STRING is multibyte, the result is STRING itself.\n\
1108 Otherwise it is a newly created string, with no text properties.\n\
1109 If STRING is unibyte and contains an individual 8-bit byte (i.e. not\n\
1110 part of multibyte form), it is converted to the corresponding\n\
1111 multibyte character of charset `binary'.")
1112 (string)
1113 Lisp_Object string;
1115 CHECK_STRING (string, 0);
1117 if (! STRING_MULTIBYTE (string))
1119 Lisp_Object new_string;
1120 int nchars, nbytes;
1122 parse_str_as_multibyte (XSTRING (string)->data,
1123 STRING_BYTES (XSTRING (string)),
1124 &nchars, &nbytes);
1125 new_string = make_uninit_multibyte_string (nchars, nbytes);
1126 bcopy (XSTRING (string)->data, XSTRING (new_string)->data,
1127 STRING_BYTES (XSTRING (string)));
1128 if (nbytes != STRING_BYTES (XSTRING (string)))
1129 str_as_multibyte (XSTRING (new_string)->data, nbytes,
1130 STRING_BYTES (XSTRING (string)), NULL);
1131 string = new_string;
1132 XSTRING (string)->intervals = NULL_INTERVAL;
1134 return string;
1137 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1138 "Return a copy of ALIST.\n\
1139 This is an alist which represents the same mapping from objects to objects,\n\
1140 but does not share the alist structure with ALIST.\n\
1141 The objects mapped (cars and cdrs of elements of the alist)\n\
1142 are shared, however.\n\
1143 Elements of ALIST that are not conses are also shared.")
1144 (alist)
1145 Lisp_Object alist;
1147 register Lisp_Object tem;
1149 CHECK_LIST (alist, 0);
1150 if (NILP (alist))
1151 return alist;
1152 alist = concat (1, &alist, Lisp_Cons, 0);
1153 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1155 register Lisp_Object car;
1156 car = XCAR (tem);
1158 if (CONSP (car))
1159 XCAR (tem) = Fcons (XCAR (car), XCDR (car));
1161 return alist;
1164 DEFUN ("substring", Fsubstring, Ssubstring, 2, 3, 0,
1165 "Return a substring of STRING, starting at index FROM and ending before TO.\n\
1166 TO may be nil or omitted; then the substring runs to the end of STRING.\n\
1167 If FROM or TO is negative, it counts from the end.\n\
1169 This function allows vectors as well as strings.")
1170 (string, from, to)
1171 Lisp_Object string;
1172 register Lisp_Object from, to;
1174 Lisp_Object res;
1175 int size;
1176 int size_byte;
1177 int from_char, to_char;
1178 int from_byte, to_byte;
1180 if (! (STRINGP (string) || VECTORP (string)))
1181 wrong_type_argument (Qarrayp, string);
1183 CHECK_NUMBER (from, 1);
1185 if (STRINGP (string))
1187 size = XSTRING (string)->size;
1188 size_byte = STRING_BYTES (XSTRING (string));
1190 else
1191 size = XVECTOR (string)->size;
1193 if (NILP (to))
1195 to_char = size;
1196 to_byte = size_byte;
1198 else
1200 CHECK_NUMBER (to, 2);
1202 to_char = XINT (to);
1203 if (to_char < 0)
1204 to_char += size;
1206 if (STRINGP (string))
1207 to_byte = string_char_to_byte (string, to_char);
1210 from_char = XINT (from);
1211 if (from_char < 0)
1212 from_char += size;
1213 if (STRINGP (string))
1214 from_byte = string_char_to_byte (string, from_char);
1216 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1217 args_out_of_range_3 (string, make_number (from_char),
1218 make_number (to_char));
1220 if (STRINGP (string))
1222 res = make_specified_string (XSTRING (string)->data + from_byte,
1223 to_char - from_char, to_byte - from_byte,
1224 STRING_MULTIBYTE (string));
1225 copy_text_properties (make_number (from_char), make_number (to_char),
1226 string, make_number (0), res, Qnil);
1228 else
1229 res = Fvector (to_char - from_char,
1230 XVECTOR (string)->contents + from_char);
1232 return res;
1235 /* Extract a substring of STRING, giving start and end positions
1236 both in characters and in bytes. */
1238 Lisp_Object
1239 substring_both (string, from, from_byte, to, to_byte)
1240 Lisp_Object string;
1241 int from, from_byte, to, to_byte;
1243 Lisp_Object res;
1244 int size;
1245 int size_byte;
1247 if (! (STRINGP (string) || VECTORP (string)))
1248 wrong_type_argument (Qarrayp, string);
1250 if (STRINGP (string))
1252 size = XSTRING (string)->size;
1253 size_byte = STRING_BYTES (XSTRING (string));
1255 else
1256 size = XVECTOR (string)->size;
1258 if (!(0 <= from && from <= to && to <= size))
1259 args_out_of_range_3 (string, make_number (from), make_number (to));
1261 if (STRINGP (string))
1263 res = make_specified_string (XSTRING (string)->data + from_byte,
1264 to - from, to_byte - from_byte,
1265 STRING_MULTIBYTE (string));
1266 copy_text_properties (make_number (from), make_number (to),
1267 string, make_number (0), res, Qnil);
1269 else
1270 res = Fvector (to - from,
1271 XVECTOR (string)->contents + from);
1273 return res;
1276 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1277 "Take cdr N times on LIST, returns the result.")
1278 (n, list)
1279 Lisp_Object n;
1280 register Lisp_Object list;
1282 register int i, num;
1283 CHECK_NUMBER (n, 0);
1284 num = XINT (n);
1285 for (i = 0; i < num && !NILP (list); i++)
1287 QUIT;
1288 if (! CONSP (list))
1289 wrong_type_argument (Qlistp, list);
1290 list = XCDR (list);
1292 return list;
1295 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1296 "Return the Nth element of LIST.\n\
1297 N counts from zero. If LIST is not that long, nil is returned.")
1298 (n, list)
1299 Lisp_Object n, list;
1301 return Fcar (Fnthcdr (n, list));
1304 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1305 "Return element of SEQUENCE at index N.")
1306 (sequence, n)
1307 register Lisp_Object sequence, n;
1309 CHECK_NUMBER (n, 0);
1310 while (1)
1312 if (CONSP (sequence) || NILP (sequence))
1313 return Fcar (Fnthcdr (n, sequence));
1314 else if (STRINGP (sequence) || VECTORP (sequence)
1315 || BOOL_VECTOR_P (sequence) || CHAR_TABLE_P (sequence))
1316 return Faref (sequence, n);
1317 else
1318 sequence = wrong_type_argument (Qsequencep, sequence);
1322 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1323 "Return non-nil if ELT is an element of LIST. Comparison done with `equal'.\n\
1324 The value is actually the tail of LIST whose car is ELT.")
1325 (elt, list)
1326 register Lisp_Object elt;
1327 Lisp_Object list;
1329 register Lisp_Object tail;
1330 for (tail = list; !NILP (tail); tail = XCDR (tail))
1332 register Lisp_Object tem;
1333 if (! CONSP (tail))
1334 wrong_type_argument (Qlistp, list);
1335 tem = XCAR (tail);
1336 if (! NILP (Fequal (elt, tem)))
1337 return tail;
1338 QUIT;
1340 return Qnil;
1343 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1344 "Return non-nil if ELT is an element of LIST.\n\
1345 Comparison done with EQ. The value is actually the tail of LIST\n\
1346 whose car is ELT.")
1347 (elt, list)
1348 Lisp_Object elt, list;
1350 while (1)
1352 if (!CONSP (list) || EQ (XCAR (list), elt))
1353 break;
1355 list = XCDR (list);
1356 if (!CONSP (list) || EQ (XCAR (list), elt))
1357 break;
1359 list = XCDR (list);
1360 if (!CONSP (list) || EQ (XCAR (list), elt))
1361 break;
1363 list = XCDR (list);
1364 QUIT;
1367 if (!CONSP (list) && !NILP (list))
1368 list = wrong_type_argument (Qlistp, list);
1370 return list;
1373 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1374 "Return non-nil if KEY is `eq' to the car of an element of LIST.\n\
1375 The value is actually the element of LIST whose car is KEY.\n\
1376 Elements of LIST that are not conses are ignored.")
1377 (key, list)
1378 Lisp_Object key, list;
1380 Lisp_Object result;
1382 while (1)
1384 if (!CONSP (list)
1385 || (CONSP (XCAR (list))
1386 && EQ (XCAR (XCAR (list)), key)))
1387 break;
1389 list = XCDR (list);
1390 if (!CONSP (list)
1391 || (CONSP (XCAR (list))
1392 && EQ (XCAR (XCAR (list)), key)))
1393 break;
1395 list = XCDR (list);
1396 if (!CONSP (list)
1397 || (CONSP (XCAR (list))
1398 && EQ (XCAR (XCAR (list)), key)))
1399 break;
1401 list = XCDR (list);
1402 QUIT;
1405 if (CONSP (list))
1406 result = XCAR (list);
1407 else if (NILP (list))
1408 result = Qnil;
1409 else
1410 result = wrong_type_argument (Qlistp, list);
1412 return result;
1415 /* Like Fassq but never report an error and do not allow quits.
1416 Use only on lists known never to be circular. */
1418 Lisp_Object
1419 assq_no_quit (key, list)
1420 Lisp_Object key, list;
1422 while (CONSP (list)
1423 && (!CONSP (XCAR (list))
1424 || !EQ (XCAR (XCAR (list)), key)))
1425 list = XCDR (list);
1427 return CONSP (list) ? XCAR (list) : Qnil;
1430 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1431 "Return non-nil if KEY is `equal' to the car of an element of LIST.\n\
1432 The value is actually the element of LIST whose car equals KEY.")
1433 (key, list)
1434 Lisp_Object key, list;
1436 Lisp_Object result, car;
1438 while (1)
1440 if (!CONSP (list)
1441 || (CONSP (XCAR (list))
1442 && (car = XCAR (XCAR (list)),
1443 EQ (car, key) || !NILP (Fequal (car, key)))))
1444 break;
1446 list = XCDR (list);
1447 if (!CONSP (list)
1448 || (CONSP (XCAR (list))
1449 && (car = XCAR (XCAR (list)),
1450 EQ (car, key) || !NILP (Fequal (car, key)))))
1451 break;
1453 list = XCDR (list);
1454 if (!CONSP (list)
1455 || (CONSP (XCAR (list))
1456 && (car = XCAR (XCAR (list)),
1457 EQ (car, key) || !NILP (Fequal (car, key)))))
1458 break;
1460 list = XCDR (list);
1461 QUIT;
1464 if (CONSP (list))
1465 result = XCAR (list);
1466 else if (NILP (list))
1467 result = Qnil;
1468 else
1469 result = wrong_type_argument (Qlistp, list);
1471 return result;
1474 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1475 "Return non-nil if KEY is `eq' to the cdr of an element of LIST.\n\
1476 The value is actually the element of LIST whose cdr is KEY.")
1477 (key, list)
1478 register Lisp_Object key;
1479 Lisp_Object list;
1481 Lisp_Object result;
1483 while (1)
1485 if (!CONSP (list)
1486 || (CONSP (XCAR (list))
1487 && EQ (XCDR (XCAR (list)), key)))
1488 break;
1490 list = XCDR (list);
1491 if (!CONSP (list)
1492 || (CONSP (XCAR (list))
1493 && EQ (XCDR (XCAR (list)), key)))
1494 break;
1496 list = XCDR (list);
1497 if (!CONSP (list)
1498 || (CONSP (XCAR (list))
1499 && EQ (XCDR (XCAR (list)), key)))
1500 break;
1502 list = XCDR (list);
1503 QUIT;
1506 if (NILP (list))
1507 result = Qnil;
1508 else if (CONSP (list))
1509 result = XCAR (list);
1510 else
1511 result = wrong_type_argument (Qlistp, list);
1513 return result;
1516 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1517 "Return non-nil if KEY is `equal' to the cdr of an element of LIST.\n\
1518 The value is actually the element of LIST whose cdr equals KEY.")
1519 (key, list)
1520 Lisp_Object key, list;
1522 Lisp_Object result, cdr;
1524 while (1)
1526 if (!CONSP (list)
1527 || (CONSP (XCAR (list))
1528 && (cdr = XCDR (XCAR (list)),
1529 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1530 break;
1532 list = XCDR (list);
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 QUIT;
1550 if (CONSP (list))
1551 result = XCAR (list);
1552 else if (NILP (list))
1553 result = Qnil;
1554 else
1555 result = wrong_type_argument (Qlistp, list);
1557 return result;
1560 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1561 "Delete by side effect any occurrences of ELT as a member of LIST.\n\
1562 The modified LIST is returned. Comparison is done with `eq'.\n\
1563 If the first member of LIST is ELT, there is no way to remove it by side effect;\n\
1564 therefore, write `(setq foo (delq element foo))'\n\
1565 to be sure of changing the value of `foo'.")
1566 (elt, list)
1567 register Lisp_Object elt;
1568 Lisp_Object list;
1570 register Lisp_Object tail, prev;
1571 register Lisp_Object tem;
1573 tail = list;
1574 prev = Qnil;
1575 while (!NILP (tail))
1577 if (! CONSP (tail))
1578 wrong_type_argument (Qlistp, list);
1579 tem = XCAR (tail);
1580 if (EQ (elt, tem))
1582 if (NILP (prev))
1583 list = XCDR (tail);
1584 else
1585 Fsetcdr (prev, XCDR (tail));
1587 else
1588 prev = tail;
1589 tail = XCDR (tail);
1590 QUIT;
1592 return list;
1595 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1596 "Delete by side effect any occurrences of ELT as a member of SEQ.\n\
1597 SEQ must be a list, a vector, or a string.\n\
1598 The modified SEQ is returned. Comparison is done with `equal'.\n\
1599 If SEQ is not a list, or the first member of SEQ is ELT, deleting it\n\
1600 is not a side effect; it is simply using a different sequence.\n\
1601 Therefore, write `(setq foo (delete element foo))'\n\
1602 to be sure of changing the value of `foo'.")
1603 (elt, seq)
1604 Lisp_Object elt, seq;
1606 if (VECTORP (seq))
1608 EMACS_INT i, n, size;
1610 for (i = n = 0; i < ASIZE (seq); ++i)
1611 if (NILP (Fequal (AREF (seq, i), elt)))
1612 ++n;
1614 if (n != ASIZE (seq))
1616 struct Lisp_Vector *p = allocate_vectorlike (n);
1618 for (i = n = 0; i < ASIZE (seq); ++i)
1619 if (NILP (Fequal (AREF (seq, i), elt)))
1620 p->contents[n++] = AREF (seq, i);
1622 p->size = n;
1623 XSETVECTOR (seq, p);
1626 else if (STRINGP (seq))
1628 EMACS_INT i, ibyte, nchars, nbytes, cbytes;
1629 int c;
1631 for (i = nchars = nbytes = ibyte = 0;
1632 i < XSTRING (seq)->size;
1633 ++i, ibyte += cbytes)
1635 if (STRING_MULTIBYTE (seq))
1637 c = STRING_CHAR (&XSTRING (seq)->data[ibyte],
1638 STRING_BYTES (XSTRING (seq)) - ibyte);
1639 cbytes = CHAR_BYTES (c);
1641 else
1643 c = XSTRING (seq)->data[i];
1644 cbytes = 1;
1647 if (!INTEGERP (elt) || c != XINT (elt))
1649 ++nchars;
1650 nbytes += cbytes;
1654 if (nchars != XSTRING (seq)->size)
1656 Lisp_Object tem;
1658 tem = make_uninit_multibyte_string (nchars, nbytes);
1659 if (!STRING_MULTIBYTE (seq))
1660 SET_STRING_BYTES (XSTRING (tem), -1);
1662 for (i = nchars = nbytes = ibyte = 0;
1663 i < XSTRING (seq)->size;
1664 ++i, ibyte += cbytes)
1666 if (STRING_MULTIBYTE (seq))
1668 c = STRING_CHAR (&XSTRING (seq)->data[ibyte],
1669 STRING_BYTES (XSTRING (seq)) - ibyte);
1670 cbytes = CHAR_BYTES (c);
1672 else
1674 c = XSTRING (seq)->data[i];
1675 cbytes = 1;
1678 if (!INTEGERP (elt) || c != XINT (elt))
1680 unsigned char *from = &XSTRING (seq)->data[ibyte];
1681 unsigned char *to = &XSTRING (tem)->data[nbytes];
1682 EMACS_INT n;
1684 ++nchars;
1685 nbytes += cbytes;
1687 for (n = cbytes; n--; )
1688 *to++ = *from++;
1692 seq = tem;
1695 else
1697 Lisp_Object tail, prev;
1699 for (tail = seq, prev = Qnil; !NILP (tail); tail = XCDR (tail))
1701 if (!CONSP (tail))
1702 wrong_type_argument (Qlistp, seq);
1704 if (!NILP (Fequal (elt, XCAR (tail))))
1706 if (NILP (prev))
1707 seq = XCDR (tail);
1708 else
1709 Fsetcdr (prev, XCDR (tail));
1711 else
1712 prev = tail;
1713 QUIT;
1717 return seq;
1720 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1721 "Reverse LIST by modifying cdr pointers.\n\
1722 Returns the beginning of the reversed list.")
1723 (list)
1724 Lisp_Object list;
1726 register Lisp_Object prev, tail, next;
1728 if (NILP (list)) return list;
1729 prev = Qnil;
1730 tail = list;
1731 while (!NILP (tail))
1733 QUIT;
1734 if (! CONSP (tail))
1735 wrong_type_argument (Qlistp, list);
1736 next = XCDR (tail);
1737 Fsetcdr (tail, prev);
1738 prev = tail;
1739 tail = next;
1741 return prev;
1744 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1745 "Reverse LIST, copying. Returns the beginning of the reversed list.\n\
1746 See also the function `nreverse', which is used more often.")
1747 (list)
1748 Lisp_Object list;
1750 Lisp_Object new;
1752 for (new = Qnil; CONSP (list); list = XCDR (list))
1753 new = Fcons (XCAR (list), new);
1754 if (!NILP (list))
1755 wrong_type_argument (Qconsp, list);
1756 return new;
1759 Lisp_Object merge ();
1761 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
1762 "Sort LIST, stably, comparing elements using PREDICATE.\n\
1763 Returns the sorted list. LIST is modified by side effects.\n\
1764 PREDICATE is called with two elements of LIST, and should return T\n\
1765 if the first element is \"less\" than the second.")
1766 (list, predicate)
1767 Lisp_Object list, predicate;
1769 Lisp_Object front, back;
1770 register Lisp_Object len, tem;
1771 struct gcpro gcpro1, gcpro2;
1772 register int length;
1774 front = list;
1775 len = Flength (list);
1776 length = XINT (len);
1777 if (length < 2)
1778 return list;
1780 XSETINT (len, (length / 2) - 1);
1781 tem = Fnthcdr (len, list);
1782 back = Fcdr (tem);
1783 Fsetcdr (tem, Qnil);
1785 GCPRO2 (front, back);
1786 front = Fsort (front, predicate);
1787 back = Fsort (back, predicate);
1788 UNGCPRO;
1789 return merge (front, back, predicate);
1792 Lisp_Object
1793 merge (org_l1, org_l2, pred)
1794 Lisp_Object org_l1, org_l2;
1795 Lisp_Object pred;
1797 Lisp_Object value;
1798 register Lisp_Object tail;
1799 Lisp_Object tem;
1800 register Lisp_Object l1, l2;
1801 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1803 l1 = org_l1;
1804 l2 = org_l2;
1805 tail = Qnil;
1806 value = Qnil;
1808 /* It is sufficient to protect org_l1 and org_l2.
1809 When l1 and l2 are updated, we copy the new values
1810 back into the org_ vars. */
1811 GCPRO4 (org_l1, org_l2, pred, value);
1813 while (1)
1815 if (NILP (l1))
1817 UNGCPRO;
1818 if (NILP (tail))
1819 return l2;
1820 Fsetcdr (tail, l2);
1821 return value;
1823 if (NILP (l2))
1825 UNGCPRO;
1826 if (NILP (tail))
1827 return l1;
1828 Fsetcdr (tail, l1);
1829 return value;
1831 tem = call2 (pred, Fcar (l2), Fcar (l1));
1832 if (NILP (tem))
1834 tem = l1;
1835 l1 = Fcdr (l1);
1836 org_l1 = l1;
1838 else
1840 tem = l2;
1841 l2 = Fcdr (l2);
1842 org_l2 = l2;
1844 if (NILP (tail))
1845 value = tem;
1846 else
1847 Fsetcdr (tail, tem);
1848 tail = tem;
1853 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
1854 "Extract a value from a property list.\n\
1855 PLIST is a property list, which is a list of the form\n\
1856 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value\n\
1857 corresponding to the given PROP, or nil if PROP is not\n\
1858 one of the properties on the list.")
1859 (plist, prop)
1860 Lisp_Object plist;
1861 register Lisp_Object prop;
1863 register Lisp_Object tail;
1864 for (tail = plist; !NILP (tail); tail = Fcdr (XCDR (tail)))
1866 register Lisp_Object tem;
1867 tem = Fcar (tail);
1868 if (EQ (prop, tem))
1869 return Fcar (XCDR (tail));
1871 return Qnil;
1874 DEFUN ("get", Fget, Sget, 2, 2, 0,
1875 "Return the value of SYMBOL's PROPNAME property.\n\
1876 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'.")
1877 (symbol, propname)
1878 Lisp_Object symbol, propname;
1880 CHECK_SYMBOL (symbol, 0);
1881 return Fplist_get (XSYMBOL (symbol)->plist, propname);
1884 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
1885 "Change value in PLIST of PROP to VAL.\n\
1886 PLIST is a property list, which is a list of the form\n\
1887 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.\n\
1888 If PROP is already a property on the list, its value is set to VAL,\n\
1889 otherwise the new PROP VAL pair is added. The new plist is returned;\n\
1890 use `(setq x (plist-put x prop val))' to be sure to use the new value.\n\
1891 The PLIST is modified by side effects.")
1892 (plist, prop, val)
1893 Lisp_Object plist;
1894 register Lisp_Object prop;
1895 Lisp_Object val;
1897 register Lisp_Object tail, prev;
1898 Lisp_Object newcell;
1899 prev = Qnil;
1900 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1901 tail = XCDR (XCDR (tail)))
1903 if (EQ (prop, XCAR (tail)))
1905 Fsetcar (XCDR (tail), val);
1906 return plist;
1908 prev = tail;
1910 newcell = Fcons (prop, Fcons (val, Qnil));
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 "Store SYMBOL's PROPNAME property with value VALUE.\n\
1920 It can be retrieved with `(get SYMBOL PROPNAME)'.")
1921 (symbol, propname, value)
1922 Lisp_Object symbol, propname, value;
1924 CHECK_SYMBOL (symbol, 0);
1925 XSYMBOL (symbol)->plist
1926 = Fplist_put (XSYMBOL (symbol)->plist, propname, value);
1927 return value;
1930 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
1931 "Return t if two Lisp objects have similar structure and contents.\n\
1932 They must have the same data type.\n\
1933 Conses are compared by comparing the cars and the cdrs.\n\
1934 Vectors and strings are compared element by element.\n\
1935 Numbers are compared by value, but integers cannot equal floats.\n\
1936 (Use `=' if you want integers and floats to be able to be equal.)\n\
1937 Symbols must match exactly.")
1938 (o1, o2)
1939 register Lisp_Object o1, o2;
1941 return internal_equal (o1, o2, 0) ? Qt : Qnil;
1944 static int
1945 internal_equal (o1, o2, depth)
1946 register Lisp_Object o1, o2;
1947 int depth;
1949 if (depth > 200)
1950 error ("Stack overflow in equal");
1952 tail_recurse:
1953 QUIT;
1954 if (EQ (o1, o2))
1955 return 1;
1956 if (XTYPE (o1) != XTYPE (o2))
1957 return 0;
1959 switch (XTYPE (o1))
1961 case Lisp_Float:
1962 return (extract_float (o1) == extract_float (o2));
1964 case Lisp_Cons:
1965 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1))
1966 return 0;
1967 o1 = XCDR (o1);
1968 o2 = XCDR (o2);
1969 goto tail_recurse;
1971 case Lisp_Misc:
1972 if (XMISCTYPE (o1) != XMISCTYPE (o2))
1973 return 0;
1974 if (OVERLAYP (o1))
1976 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
1977 depth + 1)
1978 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
1979 depth + 1))
1980 return 0;
1981 o1 = XOVERLAY (o1)->plist;
1982 o2 = XOVERLAY (o2)->plist;
1983 goto tail_recurse;
1985 if (MARKERP (o1))
1987 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
1988 && (XMARKER (o1)->buffer == 0
1989 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
1991 break;
1993 case Lisp_Vectorlike:
1995 register int i, size;
1996 size = XVECTOR (o1)->size;
1997 /* Pseudovectors have the type encoded in the size field, so this test
1998 actually checks that the objects have the same type as well as the
1999 same size. */
2000 if (XVECTOR (o2)->size != size)
2001 return 0;
2002 /* Boolvectors are compared much like strings. */
2003 if (BOOL_VECTOR_P (o1))
2005 int size_in_chars
2006 = (XBOOL_VECTOR (o1)->size + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
2008 if (XBOOL_VECTOR (o1)->size != XBOOL_VECTOR (o2)->size)
2009 return 0;
2010 if (bcmp (XBOOL_VECTOR (o1)->data, XBOOL_VECTOR (o2)->data,
2011 size_in_chars))
2012 return 0;
2013 return 1;
2015 if (WINDOW_CONFIGURATIONP (o1))
2016 return compare_window_configurations (o1, o2, 0);
2018 /* Aside from them, only true vectors, char-tables, and compiled
2019 functions are sensible to compare, so eliminate the others now. */
2020 if (size & PSEUDOVECTOR_FLAG)
2022 if (!(size & (PVEC_COMPILED | PVEC_CHAR_TABLE)))
2023 return 0;
2024 size &= PSEUDOVECTOR_SIZE_MASK;
2026 for (i = 0; i < size; i++)
2028 Lisp_Object v1, v2;
2029 v1 = XVECTOR (o1)->contents [i];
2030 v2 = XVECTOR (o2)->contents [i];
2031 if (!internal_equal (v1, v2, depth + 1))
2032 return 0;
2034 return 1;
2036 break;
2038 case Lisp_String:
2039 if (XSTRING (o1)->size != XSTRING (o2)->size)
2040 return 0;
2041 if (STRING_BYTES (XSTRING (o1)) != STRING_BYTES (XSTRING (o2)))
2042 return 0;
2043 if (bcmp (XSTRING (o1)->data, XSTRING (o2)->data,
2044 STRING_BYTES (XSTRING (o1))))
2045 return 0;
2046 return 1;
2048 return 0;
2051 extern Lisp_Object Fmake_char_internal ();
2053 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2054 "Store each element of ARRAY with ITEM.\n\
2055 ARRAY is a vector, string, char-table, or bool-vector.")
2056 (array, item)
2057 Lisp_Object array, item;
2059 register int size, index, charval;
2060 retry:
2061 if (VECTORP (array))
2063 register Lisp_Object *p = XVECTOR (array)->contents;
2064 size = XVECTOR (array)->size;
2065 for (index = 0; index < size; index++)
2066 p[index] = item;
2068 else if (CHAR_TABLE_P (array))
2070 register Lisp_Object *p = XCHAR_TABLE (array)->contents;
2071 size = CHAR_TABLE_ORDINARY_SLOTS;
2072 for (index = 0; index < size; index++)
2073 p[index] = item;
2074 XCHAR_TABLE (array)->defalt = Qnil;
2076 else if (STRINGP (array))
2078 register unsigned char *p = XSTRING (array)->data;
2079 CHECK_NUMBER (item, 1);
2080 charval = XINT (item);
2081 size = XSTRING (array)->size;
2082 if (STRING_MULTIBYTE (array))
2084 unsigned char str[MAX_MULTIBYTE_LENGTH];
2085 int len = CHAR_STRING (charval, str);
2086 int size_byte = STRING_BYTES (XSTRING (array));
2087 unsigned char *p1 = p, *endp = p + size_byte;
2088 int i;
2090 if (size != size_byte)
2091 while (p1 < endp)
2093 int this_len = MULTIBYTE_FORM_LENGTH (p1, endp - p1);
2094 if (len != this_len)
2095 error ("Attempt to change byte length of a string");
2096 p1 += this_len;
2098 for (i = 0; i < size_byte; i++)
2099 *p++ = str[i % len];
2101 else
2102 for (index = 0; index < size; index++)
2103 p[index] = charval;
2105 else if (BOOL_VECTOR_P (array))
2107 register unsigned char *p = XBOOL_VECTOR (array)->data;
2108 int size_in_chars
2109 = (XBOOL_VECTOR (array)->size + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
2111 charval = (! NILP (item) ? -1 : 0);
2112 for (index = 0; index < size_in_chars; index++)
2113 p[index] = charval;
2115 else
2117 array = wrong_type_argument (Qarrayp, array);
2118 goto retry;
2120 return array;
2123 DEFUN ("char-table-subtype", Fchar_table_subtype, Schar_table_subtype,
2124 1, 1, 0,
2125 "Return the subtype of char-table CHAR-TABLE. The value is a symbol.")
2126 (char_table)
2127 Lisp_Object char_table;
2129 CHECK_CHAR_TABLE (char_table, 0);
2131 return XCHAR_TABLE (char_table)->purpose;
2134 DEFUN ("char-table-parent", Fchar_table_parent, Schar_table_parent,
2135 1, 1, 0,
2136 "Return the parent char-table of CHAR-TABLE.\n\
2137 The value is either nil or another char-table.\n\
2138 If CHAR-TABLE holds nil for a given character,\n\
2139 then the actual applicable value is inherited from the parent char-table\n\
2140 \(or from its parents, if necessary).")
2141 (char_table)
2142 Lisp_Object char_table;
2144 CHECK_CHAR_TABLE (char_table, 0);
2146 return XCHAR_TABLE (char_table)->parent;
2149 DEFUN ("set-char-table-parent", Fset_char_table_parent, Sset_char_table_parent,
2150 2, 2, 0,
2151 "Set the parent char-table of CHAR-TABLE to PARENT.\n\
2152 PARENT must be either nil or another char-table.")
2153 (char_table, parent)
2154 Lisp_Object char_table, parent;
2156 Lisp_Object temp;
2158 CHECK_CHAR_TABLE (char_table, 0);
2160 if (!NILP (parent))
2162 CHECK_CHAR_TABLE (parent, 0);
2164 for (temp = parent; !NILP (temp); temp = XCHAR_TABLE (temp)->parent)
2165 if (EQ (temp, char_table))
2166 error ("Attempt to make a chartable be its own parent");
2169 XCHAR_TABLE (char_table)->parent = parent;
2171 return parent;
2174 DEFUN ("char-table-extra-slot", Fchar_table_extra_slot, Schar_table_extra_slot,
2175 2, 2, 0,
2176 "Return the value of CHAR-TABLE's extra-slot number N.")
2177 (char_table, n)
2178 Lisp_Object char_table, n;
2180 CHECK_CHAR_TABLE (char_table, 1);
2181 CHECK_NUMBER (n, 2);
2182 if (XINT (n) < 0
2183 || XINT (n) >= CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (char_table)))
2184 args_out_of_range (char_table, n);
2186 return XCHAR_TABLE (char_table)->extras[XINT (n)];
2189 DEFUN ("set-char-table-extra-slot", Fset_char_table_extra_slot,
2190 Sset_char_table_extra_slot,
2191 3, 3, 0,
2192 "Set CHAR-TABLE's extra-slot number N to VALUE.")
2193 (char_table, n, value)
2194 Lisp_Object char_table, n, value;
2196 CHECK_CHAR_TABLE (char_table, 1);
2197 CHECK_NUMBER (n, 2);
2198 if (XINT (n) < 0
2199 || XINT (n) >= CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (char_table)))
2200 args_out_of_range (char_table, n);
2202 return XCHAR_TABLE (char_table)->extras[XINT (n)] = value;
2205 DEFUN ("char-table-range", Fchar_table_range, Schar_table_range,
2206 2, 2, 0,
2207 "Return the value in CHAR-TABLE for a range of characters RANGE.\n\
2208 RANGE should be nil (for the default value)\n\
2209 a vector which identifies a character set or a row of a character set,\n\
2210 a character set name, or a character code.")
2211 (char_table, range)
2212 Lisp_Object char_table, range;
2214 CHECK_CHAR_TABLE (char_table, 0);
2216 if (EQ (range, Qnil))
2217 return XCHAR_TABLE (char_table)->defalt;
2218 else if (INTEGERP (range))
2219 return Faref (char_table, range);
2220 else if (SYMBOLP (range))
2222 Lisp_Object charset_info;
2224 charset_info = Fget (range, Qcharset);
2225 CHECK_VECTOR (charset_info, 0);
2227 return Faref (char_table,
2228 make_number (XINT (XVECTOR (charset_info)->contents[0])
2229 + 128));
2231 else if (VECTORP (range))
2233 if (XVECTOR (range)->size == 1)
2234 return Faref (char_table,
2235 make_number (XINT (XVECTOR (range)->contents[0]) + 128));
2236 else
2238 int size = XVECTOR (range)->size;
2239 Lisp_Object *val = XVECTOR (range)->contents;
2240 Lisp_Object ch = Fmake_char_internal (size <= 0 ? Qnil : val[0],
2241 size <= 1 ? Qnil : val[1],
2242 size <= 2 ? Qnil : val[2]);
2243 return Faref (char_table, ch);
2246 else
2247 error ("Invalid RANGE argument to `char-table-range'");
2248 return Qt;
2251 DEFUN ("set-char-table-range", Fset_char_table_range, Sset_char_table_range,
2252 3, 3, 0,
2253 "Set the value in CHAR-TABLE for a range of characters RANGE to VALUE.\n\
2254 RANGE should be t (for all characters), nil (for the default value)\n\
2255 a vector which identifies a character set or a row of a character set,\n\
2256 a coding system, or a character code.")
2257 (char_table, range, value)
2258 Lisp_Object char_table, range, value;
2260 int i;
2262 CHECK_CHAR_TABLE (char_table, 0);
2264 if (EQ (range, Qt))
2265 for (i = 0; i < CHAR_TABLE_ORDINARY_SLOTS; i++)
2266 XCHAR_TABLE (char_table)->contents[i] = value;
2267 else if (EQ (range, Qnil))
2268 XCHAR_TABLE (char_table)->defalt = value;
2269 else if (SYMBOLP (range))
2271 Lisp_Object charset_info;
2273 charset_info = Fget (range, Qcharset);
2274 CHECK_VECTOR (charset_info, 0);
2276 return Faset (char_table,
2277 make_number (XINT (XVECTOR (charset_info)->contents[0])
2278 + 128),
2279 value);
2281 else if (INTEGERP (range))
2282 Faset (char_table, range, value);
2283 else if (VECTORP (range))
2285 if (XVECTOR (range)->size == 1)
2286 return Faset (char_table,
2287 make_number (XINT (XVECTOR (range)->contents[0]) + 128),
2288 value);
2289 else
2291 int size = XVECTOR (range)->size;
2292 Lisp_Object *val = XVECTOR (range)->contents;
2293 Lisp_Object ch = Fmake_char_internal (size <= 0 ? Qnil : val[0],
2294 size <= 1 ? Qnil : val[1],
2295 size <= 2 ? Qnil : val[2]);
2296 return Faset (char_table, ch, value);
2299 else
2300 error ("Invalid RANGE argument to `set-char-table-range'");
2302 return value;
2305 DEFUN ("set-char-table-default", Fset_char_table_default,
2306 Sset_char_table_default, 3, 3, 0,
2307 "Set the default value in CHAR-TABLE for a generic character CHAR to VALUE.\n\
2308 The generic character specifies the group of characters.\n\
2309 See also the documentation of make-char.")
2310 (char_table, ch, value)
2311 Lisp_Object char_table, ch, value;
2313 int c, charset, code1, code2;
2314 Lisp_Object temp;
2316 CHECK_CHAR_TABLE (char_table, 0);
2317 CHECK_NUMBER (ch, 1);
2319 c = XINT (ch);
2320 SPLIT_CHAR (c, charset, code1, code2);
2322 /* Since we may want to set the default value for a character set
2323 not yet defined, we check only if the character set is in the
2324 valid range or not, instead of it is already defined or not. */
2325 if (! CHARSET_VALID_P (charset))
2326 invalid_character (c);
2328 if (charset == CHARSET_ASCII)
2329 return (XCHAR_TABLE (char_table)->defalt = value);
2331 /* Even if C is not a generic char, we had better behave as if a
2332 generic char is specified. */
2333 if (CHARSET_DIMENSION (charset) == 1)
2334 code1 = 0;
2335 temp = XCHAR_TABLE (char_table)->contents[charset + 128];
2336 if (!code1)
2338 if (SUB_CHAR_TABLE_P (temp))
2339 XCHAR_TABLE (temp)->defalt = value;
2340 else
2341 XCHAR_TABLE (char_table)->contents[charset + 128] = value;
2342 return value;
2344 char_table = temp;
2345 if (! SUB_CHAR_TABLE_P (char_table))
2346 char_table = (XCHAR_TABLE (char_table)->contents[charset + 128]
2347 = make_sub_char_table (temp));
2348 temp = XCHAR_TABLE (char_table)->contents[code1];
2349 if (SUB_CHAR_TABLE_P (temp))
2350 XCHAR_TABLE (temp)->defalt = value;
2351 else
2352 XCHAR_TABLE (char_table)->contents[code1] = value;
2353 return value;
2356 /* Look up the element in TABLE at index CH,
2357 and return it as an integer.
2358 If the element is nil, return CH itself.
2359 (Actually we do that for any non-integer.) */
2362 char_table_translate (table, ch)
2363 Lisp_Object table;
2364 int ch;
2366 Lisp_Object value;
2367 value = Faref (table, make_number (ch));
2368 if (! INTEGERP (value))
2369 return ch;
2370 return XINT (value);
2373 static void
2374 optimize_sub_char_table (table, chars)
2375 Lisp_Object *table;
2376 int chars;
2378 Lisp_Object elt;
2379 int from, to;
2381 if (chars == 94)
2382 from = 33, to = 127;
2383 else
2384 from = 32, to = 128;
2386 if (!SUB_CHAR_TABLE_P (*table))
2387 return;
2388 elt = XCHAR_TABLE (*table)->contents[from++];
2389 for (; from < to; from++)
2390 if (NILP (Fequal (elt, XCHAR_TABLE (*table)->contents[from])))
2391 return;
2392 *table = elt;
2395 DEFUN ("optimize-char-table", Foptimize_char_table, Soptimize_char_table,
2396 1, 1, 0,
2397 "Optimize char table TABLE.")
2398 (table)
2399 Lisp_Object table;
2401 Lisp_Object elt;
2402 int dim;
2403 int i, j;
2405 CHECK_CHAR_TABLE (table, 0);
2407 for (i = CHAR_TABLE_SINGLE_BYTE_SLOTS; i < CHAR_TABLE_ORDINARY_SLOTS; i++)
2409 elt = XCHAR_TABLE (table)->contents[i];
2410 if (!SUB_CHAR_TABLE_P (elt))
2411 continue;
2412 dim = CHARSET_DIMENSION (i);
2413 if (dim == 2)
2414 for (j = 32; j < SUB_CHAR_TABLE_ORDINARY_SLOTS; j++)
2415 optimize_sub_char_table (XCHAR_TABLE (elt)->contents + j, dim);
2416 optimize_sub_char_table (XCHAR_TABLE (table)->contents + i, dim);
2418 return Qnil;
2422 /* Map C_FUNCTION or FUNCTION over SUBTABLE, calling it for each
2423 character or group of characters that share a value.
2424 DEPTH is the current depth in the originally specified
2425 chartable, and INDICES contains the vector indices
2426 for the levels our callers have descended.
2428 ARG is passed to C_FUNCTION when that is called. */
2430 void
2431 map_char_table (c_function, function, subtable, arg, depth, indices)
2432 void (*c_function) P_ ((Lisp_Object, Lisp_Object, Lisp_Object));
2433 Lisp_Object function, subtable, arg, *indices;
2434 int depth;
2436 int i, to;
2438 if (depth == 0)
2440 /* At first, handle ASCII and 8-bit European characters. */
2441 for (i = 0; i < CHAR_TABLE_SINGLE_BYTE_SLOTS; i++)
2443 Lisp_Object elt = XCHAR_TABLE (subtable)->contents[i];
2444 if (c_function)
2445 (*c_function) (arg, make_number (i), elt);
2446 else
2447 call2 (function, make_number (i), elt);
2449 #if 0 /* If the char table has entries for higher characters,
2450 we should report them. */
2451 if (NILP (current_buffer->enable_multibyte_characters))
2452 return;
2453 #endif
2454 to = CHAR_TABLE_ORDINARY_SLOTS;
2456 else
2458 int charset = XFASTINT (indices[0]) - 128;
2460 i = 32;
2461 to = SUB_CHAR_TABLE_ORDINARY_SLOTS;
2462 if (CHARSET_CHARS (charset) == 94)
2463 i++, to--;
2466 for (; i < to; i++)
2468 Lisp_Object elt;
2469 int charset;
2471 elt = XCHAR_TABLE (subtable)->contents[i];
2472 XSETFASTINT (indices[depth], i);
2473 charset = XFASTINT (indices[0]) - 128;
2474 if (depth == 0
2475 && (!CHARSET_DEFINED_P (charset)
2476 || charset == CHARSET_8_BIT_CONTROL
2477 || charset == CHARSET_8_BIT_GRAPHIC))
2478 continue;
2480 if (SUB_CHAR_TABLE_P (elt))
2482 if (depth >= 3)
2483 error ("Too deep char table");
2484 map_char_table (c_function, function, elt, arg, depth + 1, indices);
2486 else
2488 int c1, c2, c;
2490 if (NILP (elt))
2491 elt = XCHAR_TABLE (subtable)->defalt;
2492 c1 = depth >= 1 ? XFASTINT (indices[1]) : 0;
2493 c2 = depth >= 2 ? XFASTINT (indices[2]) : 0;
2494 c = MAKE_CHAR (charset, c1, c2);
2495 if (c_function)
2496 (*c_function) (arg, make_number (c), elt);
2497 else
2498 call2 (function, make_number (c), elt);
2503 DEFUN ("map-char-table", Fmap_char_table, Smap_char_table,
2504 2, 2, 0,
2505 "Call FUNCTION for each (normal and generic) characters in CHAR-TABLE.\n\
2506 FUNCTION is called with two arguments--a key and a value.\n\
2507 The key is always a possible IDX argument to `aref'.")
2508 (function, char_table)
2509 Lisp_Object function, char_table;
2511 /* The depth of char table is at most 3. */
2512 Lisp_Object indices[3];
2514 CHECK_CHAR_TABLE (char_table, 1);
2516 map_char_table (NULL, function, char_table, char_table, 0, indices);
2517 return Qnil;
2520 /* Return a value for character C in char-table TABLE. Store the
2521 actual index for that value in *IDX. Ignore the default value of
2522 TABLE. */
2524 Lisp_Object
2525 char_table_ref_and_index (table, c, idx)
2526 Lisp_Object table;
2527 int c, *idx;
2529 int charset, c1, c2;
2530 Lisp_Object elt;
2532 if (SINGLE_BYTE_CHAR_P (c))
2534 *idx = c;
2535 return XCHAR_TABLE (table)->contents[c];
2537 SPLIT_CHAR (c, charset, c1, c2);
2538 elt = XCHAR_TABLE (table)->contents[charset + 128];
2539 *idx = MAKE_CHAR (charset, 0, 0);
2540 if (!SUB_CHAR_TABLE_P (elt))
2541 return elt;
2542 if (c1 < 32 || NILP (XCHAR_TABLE (elt)->contents[c1]))
2543 return XCHAR_TABLE (elt)->defalt;
2544 elt = XCHAR_TABLE (elt)->contents[c1];
2545 *idx = MAKE_CHAR (charset, c1, 0);
2546 if (!SUB_CHAR_TABLE_P (elt))
2547 return elt;
2548 if (c2 < 32 || NILP (XCHAR_TABLE (elt)->contents[c2]))
2549 return XCHAR_TABLE (elt)->defalt;
2550 *idx = c;
2551 return XCHAR_TABLE (elt)->contents[c2];
2555 /* ARGSUSED */
2556 Lisp_Object
2557 nconc2 (s1, s2)
2558 Lisp_Object s1, s2;
2560 #ifdef NO_ARG_ARRAY
2561 Lisp_Object args[2];
2562 args[0] = s1;
2563 args[1] = s2;
2564 return Fnconc (2, args);
2565 #else
2566 return Fnconc (2, &s1);
2567 #endif /* NO_ARG_ARRAY */
2570 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2571 "Concatenate any number of lists by altering them.\n\
2572 Only the last argument is not altered, and need not be a list.")
2573 (nargs, args)
2574 int nargs;
2575 Lisp_Object *args;
2577 register int argnum;
2578 register Lisp_Object tail, tem, val;
2580 val = Qnil;
2582 for (argnum = 0; argnum < nargs; argnum++)
2584 tem = args[argnum];
2585 if (NILP (tem)) continue;
2587 if (NILP (val))
2588 val = tem;
2590 if (argnum + 1 == nargs) break;
2592 if (!CONSP (tem))
2593 tem = wrong_type_argument (Qlistp, tem);
2595 while (CONSP (tem))
2597 tail = tem;
2598 tem = Fcdr (tail);
2599 QUIT;
2602 tem = args[argnum + 1];
2603 Fsetcdr (tail, tem);
2604 if (NILP (tem))
2605 args[argnum + 1] = tail;
2608 return val;
2611 /* This is the guts of all mapping functions.
2612 Apply FN to each element of SEQ, one by one,
2613 storing the results into elements of VALS, a C vector of Lisp_Objects.
2614 LENI is the length of VALS, which should also be the length of SEQ. */
2616 static void
2617 mapcar1 (leni, vals, fn, seq)
2618 int leni;
2619 Lisp_Object *vals;
2620 Lisp_Object fn, seq;
2622 register Lisp_Object tail;
2623 Lisp_Object dummy;
2624 register int i;
2625 struct gcpro gcpro1, gcpro2, gcpro3;
2627 if (vals)
2629 /* Don't let vals contain any garbage when GC happens. */
2630 for (i = 0; i < leni; i++)
2631 vals[i] = Qnil;
2633 GCPRO3 (dummy, fn, seq);
2634 gcpro1.var = vals;
2635 gcpro1.nvars = leni;
2637 else
2638 GCPRO2 (fn, seq);
2639 /* We need not explicitly protect `tail' because it is used only on lists, and
2640 1) lists are not relocated and 2) the list is marked via `seq' so will not be freed */
2642 if (VECTORP (seq))
2644 for (i = 0; i < leni; i++)
2646 dummy = XVECTOR (seq)->contents[i];
2647 dummy = call1 (fn, dummy);
2648 if (vals)
2649 vals[i] = dummy;
2652 else if (BOOL_VECTOR_P (seq))
2654 for (i = 0; i < leni; i++)
2656 int byte;
2657 byte = XBOOL_VECTOR (seq)->data[i / BITS_PER_CHAR];
2658 if (byte & (1 << (i % BITS_PER_CHAR)))
2659 dummy = Qt;
2660 else
2661 dummy = Qnil;
2663 dummy = call1 (fn, dummy);
2664 if (vals)
2665 vals[i] = dummy;
2668 else if (STRINGP (seq))
2670 int i_byte;
2672 for (i = 0, i_byte = 0; i < leni;)
2674 int c;
2675 int i_before = i;
2677 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2678 XSETFASTINT (dummy, c);
2679 dummy = call1 (fn, dummy);
2680 if (vals)
2681 vals[i_before] = dummy;
2684 else /* Must be a list, since Flength did not get an error */
2686 tail = seq;
2687 for (i = 0; i < leni; i++)
2689 dummy = call1 (fn, Fcar (tail));
2690 if (vals)
2691 vals[i] = dummy;
2692 tail = XCDR (tail);
2696 UNGCPRO;
2699 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2700 "Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.\n\
2701 In between each pair of results, stick in SEPARATOR. Thus, \" \" as\n\
2702 SEPARATOR results in spaces between the values returned by FUNCTION.\n\
2703 SEQUENCE may be a list, a vector, a bool-vector, or a string.")
2704 (function, sequence, separator)
2705 Lisp_Object function, sequence, separator;
2707 Lisp_Object len;
2708 register int leni;
2709 int nargs;
2710 register Lisp_Object *args;
2711 register int i;
2712 struct gcpro gcpro1;
2714 len = Flength (sequence);
2715 leni = XINT (len);
2716 nargs = leni + leni - 1;
2717 if (nargs < 0) return build_string ("");
2719 args = (Lisp_Object *) alloca (nargs * sizeof (Lisp_Object));
2721 GCPRO1 (separator);
2722 mapcar1 (leni, args, function, sequence);
2723 UNGCPRO;
2725 for (i = leni - 1; i >= 0; i--)
2726 args[i + i] = args[i];
2728 for (i = 1; i < nargs; i += 2)
2729 args[i] = separator;
2731 return Fconcat (nargs, args);
2734 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2735 "Apply FUNCTION to each element of SEQUENCE, and make a list of the results.\n\
2736 The result is a list just as long as SEQUENCE.\n\
2737 SEQUENCE may be a list, a vector, a bool-vector, or a string.")
2738 (function, sequence)
2739 Lisp_Object function, sequence;
2741 register Lisp_Object len;
2742 register int leni;
2743 register Lisp_Object *args;
2745 len = Flength (sequence);
2746 leni = XFASTINT (len);
2747 args = (Lisp_Object *) alloca (leni * sizeof (Lisp_Object));
2749 mapcar1 (leni, args, function, sequence);
2751 return Flist (leni, args);
2754 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2755 "Apply FUNCTION to each element of SEQUENCE for side effects only.\n\
2756 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.\n\
2757 SEQUENCE may be a list, a vector, a bool-vector, or a string.")
2758 (function, sequence)
2759 Lisp_Object function, sequence;
2761 register int leni;
2763 leni = XFASTINT (Flength (sequence));
2764 mapcar1 (leni, 0, function, sequence);
2766 return sequence;
2769 /* Anything that calls this function must protect from GC! */
2771 DEFUN ("y-or-n-p", Fy_or_n_p, Sy_or_n_p, 1, 1, 0,
2772 "Ask user a \"y or n\" question. Return t if answer is \"y\".\n\
2773 Takes one argument, which is the string to display to ask the question.\n\
2774 It should end in a space; `y-or-n-p' adds `(y or n) ' to it.\n\
2775 No confirmation of the answer is requested; a single character is enough.\n\
2776 Also accepts Space to mean yes, or Delete to mean no. \(Actually, it uses\n\
2777 the bindings in `query-replace-map'; see the documentation of that variable\n\
2778 for more information. In this case, the useful bindings are `act', `skip',\n\
2779 `recenter', and `quit'.\)\n\
2781 Under a windowing system a dialog box will be used if `last-nonmenu-event'\n\
2782 is nil.")
2783 (prompt)
2784 Lisp_Object prompt;
2786 register Lisp_Object obj, key, def, map;
2787 register int answer;
2788 Lisp_Object xprompt;
2789 Lisp_Object args[2];
2790 struct gcpro gcpro1, gcpro2;
2791 int count = specpdl_ptr - specpdl;
2793 specbind (Qcursor_in_echo_area, Qt);
2795 map = Fsymbol_value (intern ("query-replace-map"));
2797 CHECK_STRING (prompt, 0);
2798 xprompt = prompt;
2799 GCPRO2 (prompt, xprompt);
2801 #ifdef HAVE_X_WINDOWS
2802 if (display_busy_cursor_p)
2803 cancel_busy_cursor ();
2804 #endif
2806 while (1)
2809 #ifdef HAVE_MENUS
2810 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2811 && use_dialog_box
2812 && have_menus_p ())
2814 Lisp_Object pane, menu;
2815 redisplay_preserve_echo_area ();
2816 pane = Fcons (Fcons (build_string ("Yes"), Qt),
2817 Fcons (Fcons (build_string ("No"), Qnil),
2818 Qnil));
2819 menu = Fcons (prompt, pane);
2820 obj = Fx_popup_dialog (Qt, menu);
2821 answer = !NILP (obj);
2822 break;
2824 #endif /* HAVE_MENUS */
2825 cursor_in_echo_area = 1;
2826 choose_minibuf_frame ();
2827 message_with_string ("%s(y or n) ", xprompt, 0);
2829 if (minibuffer_auto_raise)
2831 Lisp_Object mini_frame;
2833 mini_frame = WINDOW_FRAME (XWINDOW (minibuf_window));
2835 Fraise_frame (mini_frame);
2838 obj = read_filtered_event (1, 0, 0, 0);
2839 cursor_in_echo_area = 0;
2840 /* If we need to quit, quit with cursor_in_echo_area = 0. */
2841 QUIT;
2843 key = Fmake_vector (make_number (1), obj);
2844 def = Flookup_key (map, key, Qt);
2846 if (EQ (def, intern ("skip")))
2848 answer = 0;
2849 break;
2851 else if (EQ (def, intern ("act")))
2853 answer = 1;
2854 break;
2856 else if (EQ (def, intern ("recenter")))
2858 Frecenter (Qnil);
2859 xprompt = prompt;
2860 continue;
2862 else if (EQ (def, intern ("quit")))
2863 Vquit_flag = Qt;
2864 /* We want to exit this command for exit-prefix,
2865 and this is the only way to do it. */
2866 else if (EQ (def, intern ("exit-prefix")))
2867 Vquit_flag = Qt;
2869 QUIT;
2871 /* If we don't clear this, then the next call to read_char will
2872 return quit_char again, and we'll enter an infinite loop. */
2873 Vquit_flag = Qnil;
2875 Fding (Qnil);
2876 Fdiscard_input ();
2877 if (EQ (xprompt, prompt))
2879 args[0] = build_string ("Please answer y or n. ");
2880 args[1] = prompt;
2881 xprompt = Fconcat (2, args);
2884 UNGCPRO;
2886 if (! noninteractive)
2888 cursor_in_echo_area = -1;
2889 message_with_string (answer ? "%s(y or n) y" : "%s(y or n) n",
2890 xprompt, 0);
2893 unbind_to (count, Qnil);
2894 return answer ? Qt : Qnil;
2897 /* This is how C code calls `yes-or-no-p' and allows the user
2898 to redefined it.
2900 Anything that calls this function must protect from GC! */
2902 Lisp_Object
2903 do_yes_or_no_p (prompt)
2904 Lisp_Object prompt;
2906 return call1 (intern ("yes-or-no-p"), prompt);
2909 /* Anything that calls this function must protect from GC! */
2911 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2912 "Ask user a yes-or-no question. Return t if answer is yes.\n\
2913 Takes one argument, which is the string to display to ask the question.\n\
2914 It should end in a space; `yes-or-no-p' adds `(yes or no) ' to it.\n\
2915 The user must confirm the answer with RET,\n\
2916 and can edit it until it has been confirmed.\n\
2918 Under a windowing system a dialog box will be used if `last-nonmenu-event'\n\
2919 is nil.")
2920 (prompt)
2921 Lisp_Object prompt;
2923 register Lisp_Object ans;
2924 Lisp_Object args[2];
2925 struct gcpro gcpro1;
2927 CHECK_STRING (prompt, 0);
2929 #ifdef HAVE_MENUS
2930 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2931 && use_dialog_box
2932 && have_menus_p ())
2934 Lisp_Object pane, menu, obj;
2935 redisplay_preserve_echo_area ();
2936 pane = Fcons (Fcons (build_string ("Yes"), Qt),
2937 Fcons (Fcons (build_string ("No"), Qnil),
2938 Qnil));
2939 GCPRO1 (pane);
2940 menu = Fcons (prompt, pane);
2941 obj = Fx_popup_dialog (Qt, menu);
2942 UNGCPRO;
2943 return obj;
2945 #endif /* HAVE_MENUS */
2947 args[0] = prompt;
2948 args[1] = build_string ("(yes or no) ");
2949 prompt = Fconcat (2, args);
2951 GCPRO1 (prompt);
2953 while (1)
2955 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2956 Qyes_or_no_p_history, Qnil,
2957 Qnil));
2958 if (XSTRING (ans)->size == 3 && !strcmp (XSTRING (ans)->data, "yes"))
2960 UNGCPRO;
2961 return Qt;
2963 if (XSTRING (ans)->size == 2 && !strcmp (XSTRING (ans)->data, "no"))
2965 UNGCPRO;
2966 return Qnil;
2969 Fding (Qnil);
2970 Fdiscard_input ();
2971 message ("Please answer yes or no.");
2972 Fsleep_for (make_number (2), Qnil);
2976 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2977 "Return list of 1 minute, 5 minute and 15 minute load averages.\n\
2978 Each of the three load averages is multiplied by 100,\n\
2979 then converted to integer.\n\
2980 When USE-FLOATS is non-nil, floats will be used instead of integers.\n\
2981 These floats are not multiplied by 100.\n\n\
2982 If the 5-minute or 15-minute load averages are not available, return a\n\
2983 shortened list, containing only those averages which are available.")
2984 (use_floats)
2985 Lisp_Object use_floats;
2987 double load_ave[3];
2988 int loads = getloadavg (load_ave, 3);
2989 Lisp_Object ret = Qnil;
2991 if (loads < 0)
2992 error ("load-average not implemented for this operating system");
2994 while (loads-- > 0)
2996 Lisp_Object load = (NILP (use_floats) ?
2997 make_number ((int) (100.0 * load_ave[loads]))
2998 : make_float (load_ave[loads]));
2999 ret = Fcons (load, ret);
3002 return ret;
3005 Lisp_Object Vfeatures;
3007 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 1, 0,
3008 "Returns t if FEATURE is present in this Emacs.\n\
3009 Use this to conditionalize execution of lisp code based on the presence or\n\
3010 absence of emacs or environment extensions.\n\
3011 Use `provide' to declare that a feature is available.\n\
3012 This function looks at the value of the variable `features'.")
3013 (feature)
3014 Lisp_Object feature;
3016 register Lisp_Object tem;
3017 CHECK_SYMBOL (feature, 0);
3018 tem = Fmemq (feature, Vfeatures);
3019 return (NILP (tem)) ? Qnil : Qt;
3022 DEFUN ("provide", Fprovide, Sprovide, 1, 1, 0,
3023 "Announce that FEATURE is a feature of the current Emacs.")
3024 (feature)
3025 Lisp_Object feature;
3027 register Lisp_Object tem;
3028 CHECK_SYMBOL (feature, 0);
3029 if (!NILP (Vautoload_queue))
3030 Vautoload_queue = Fcons (Fcons (Vfeatures, Qnil), Vautoload_queue);
3031 tem = Fmemq (feature, Vfeatures);
3032 if (NILP (tem))
3033 Vfeatures = Fcons (feature, Vfeatures);
3034 LOADHIST_ATTACH (Fcons (Qprovide, feature));
3035 return feature;
3038 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
3039 "If feature FEATURE is not loaded, load it from FILENAME.\n\
3040 If FEATURE is not a member of the list `features', then the feature\n\
3041 is not loaded; so load the file FILENAME.\n\
3042 If FILENAME is omitted, the printname of FEATURE is used as the file name,\n\
3043 but in this case `load' insists on adding the suffix `.el' or `.elc'.\n\
3044 If the optional third argument NOERROR is non-nil,\n\
3045 then return nil if the file is not found.\n\
3046 Normally the return value is FEATURE.")
3047 (feature, file_name, noerror)
3048 Lisp_Object feature, file_name, noerror;
3050 register Lisp_Object tem;
3051 CHECK_SYMBOL (feature, 0);
3052 tem = Fmemq (feature, Vfeatures);
3053 LOADHIST_ATTACH (Fcons (Qrequire, feature));
3054 if (NILP (tem))
3056 int count = specpdl_ptr - specpdl;
3058 /* Value saved here is to be restored into Vautoload_queue */
3059 record_unwind_protect (un_autoload, Vautoload_queue);
3060 Vautoload_queue = Qt;
3062 tem = Fload (NILP (file_name) ? Fsymbol_name (feature) : file_name,
3063 noerror, Qt, Qnil, (NILP (file_name) ? Qt : Qnil));
3064 /* If load failed entirely, return nil. */
3065 if (NILP (tem))
3066 return unbind_to (count, Qnil);
3068 tem = Fmemq (feature, Vfeatures);
3069 if (NILP (tem))
3070 error ("Required feature %s was not provided",
3071 XSYMBOL (feature)->name->data);
3073 /* Once loading finishes, don't undo it. */
3074 Vautoload_queue = Qt;
3075 feature = unbind_to (count, feature);
3077 return feature;
3080 /* Primitives for work of the "widget" library.
3081 In an ideal world, this section would not have been necessary.
3082 However, lisp function calls being as slow as they are, it turns
3083 out that some functions in the widget library (wid-edit.el) are the
3084 bottleneck of Widget operation. Here is their translation to C,
3085 for the sole reason of efficiency. */
3087 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
3088 "Return non-nil if PLIST has the property PROP.\n\
3089 PLIST is a property list, which is a list of the form\n\
3090 \(PROP1 VALUE1 PROP2 VALUE2 ...\). PROP is a symbol.\n\
3091 Unlike `plist-get', this allows you to distinguish between a missing\n\
3092 property and a property with the value nil.\n\
3093 The value is actually the tail of PLIST whose car is PROP.")
3094 (plist, prop)
3095 Lisp_Object plist, prop;
3097 while (CONSP (plist) && !EQ (XCAR (plist), prop))
3099 QUIT;
3100 plist = XCDR (plist);
3101 plist = CDR (plist);
3103 return plist;
3106 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
3107 "In WIDGET, set PROPERTY to VALUE.\n\
3108 The value can later be retrieved with `widget-get'.")
3109 (widget, property, value)
3110 Lisp_Object widget, property, value;
3112 CHECK_CONS (widget, 1);
3113 XCDR (widget) = Fplist_put (XCDR (widget), property, value);
3114 return value;
3117 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
3118 "In WIDGET, get the value of PROPERTY.\n\
3119 The value could either be specified when the widget was created, or\n\
3120 later with `widget-put'.")
3121 (widget, property)
3122 Lisp_Object widget, property;
3124 Lisp_Object tmp;
3126 while (1)
3128 if (NILP (widget))
3129 return Qnil;
3130 CHECK_CONS (widget, 1);
3131 tmp = Fplist_member (XCDR (widget), property);
3132 if (CONSP (tmp))
3134 tmp = XCDR (tmp);
3135 return CAR (tmp);
3137 tmp = XCAR (widget);
3138 if (NILP (tmp))
3139 return Qnil;
3140 widget = Fget (tmp, Qwidget_type);
3144 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
3145 "Apply the value of WIDGET's PROPERTY to the widget itself.\n\
3146 ARGS are passed as extra arguments to the function.")
3147 (nargs, args)
3148 int nargs;
3149 Lisp_Object *args;
3151 /* This function can GC. */
3152 Lisp_Object newargs[3];
3153 struct gcpro gcpro1, gcpro2;
3154 Lisp_Object result;
3156 newargs[0] = Fwidget_get (args[0], args[1]);
3157 newargs[1] = args[0];
3158 newargs[2] = Flist (nargs - 2, args + 2);
3159 GCPRO2 (newargs[0], newargs[2]);
3160 result = Fapply (3, newargs);
3161 UNGCPRO;
3162 return result;
3165 /* base64 encode/decode functions.
3166 Based on code from GNU recode. */
3168 #define MIME_LINE_LENGTH 76
3170 #define IS_ASCII(Character) \
3171 ((Character) < 128)
3172 #define IS_BASE64(Character) \
3173 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
3174 #define IS_BASE64_IGNORABLE(Character) \
3175 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
3176 || (Character) == '\f' || (Character) == '\r')
3178 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
3179 character or return retval if there are no characters left to
3180 process. */
3181 #define READ_QUADRUPLET_BYTE(retval) \
3182 do \
3184 if (i == length) \
3185 return (retval); \
3186 c = from[i++]; \
3188 while (IS_BASE64_IGNORABLE (c))
3190 /* Don't use alloca for regions larger than this, lest we overflow
3191 their stack. */
3192 #define MAX_ALLOCA 16*1024
3194 /* Table of characters coding the 64 values. */
3195 static char base64_value_to_char[64] =
3197 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
3198 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
3199 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
3200 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
3201 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
3202 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
3203 '8', '9', '+', '/' /* 60-63 */
3206 /* Table of base64 values for first 128 characters. */
3207 static short base64_char_to_value[128] =
3209 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
3210 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
3211 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
3212 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
3213 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
3214 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
3215 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
3216 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
3217 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
3218 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
3219 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
3220 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
3221 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
3224 /* The following diagram shows the logical steps by which three octets
3225 get transformed into four base64 characters.
3227 .--------. .--------. .--------.
3228 |aaaaaabb| |bbbbcccc| |ccdddddd|
3229 `--------' `--------' `--------'
3230 6 2 4 4 2 6
3231 .--------+--------+--------+--------.
3232 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
3233 `--------+--------+--------+--------'
3235 .--------+--------+--------+--------.
3236 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
3237 `--------+--------+--------+--------'
3239 The octets are divided into 6 bit chunks, which are then encoded into
3240 base64 characters. */
3243 static int base64_encode_1 P_ ((const char *, char *, int, int, int));
3244 static int base64_decode_1 P_ ((const char *, char *, int));
3246 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
3247 2, 3, "r",
3248 "Base64-encode the region between BEG and END.\n\
3249 Return the length of the encoded text.\n\
3250 Optional third argument NO-LINE-BREAK means do not break long lines\n\
3251 into shorter lines.")
3252 (beg, end, no_line_break)
3253 Lisp_Object beg, end, no_line_break;
3255 char *encoded;
3256 int allength, length;
3257 int ibeg, iend, encoded_length;
3258 int old_pos = PT;
3260 validate_region (&beg, &end);
3262 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3263 iend = CHAR_TO_BYTE (XFASTINT (end));
3264 move_gap_both (XFASTINT (beg), ibeg);
3266 /* We need to allocate enough room for encoding the text.
3267 We need 33 1/3% more space, plus a newline every 76
3268 characters, and then we round up. */
3269 length = iend - ibeg;
3270 allength = length + length/3 + 1;
3271 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3273 if (allength <= MAX_ALLOCA)
3274 encoded = (char *) alloca (allength);
3275 else
3276 encoded = (char *) xmalloc (allength);
3277 encoded_length = base64_encode_1 (BYTE_POS_ADDR (ibeg), encoded, length,
3278 NILP (no_line_break),
3279 !NILP (current_buffer->enable_multibyte_characters));
3280 if (encoded_length > allength)
3281 abort ();
3283 if (encoded_length < 0)
3285 /* The encoding wasn't possible. */
3286 if (length > MAX_ALLOCA)
3287 xfree (encoded);
3288 error ("Base64 encoding failed");
3291 /* Now we have encoded the region, so we insert the new contents
3292 and delete the old. (Insert first in order to preserve markers.) */
3293 SET_PT_BOTH (XFASTINT (beg), ibeg);
3294 insert (encoded, encoded_length);
3295 if (allength > MAX_ALLOCA)
3296 xfree (encoded);
3297 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
3299 /* If point was outside of the region, restore it exactly; else just
3300 move to the beginning of the region. */
3301 if (old_pos >= XFASTINT (end))
3302 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
3303 else if (old_pos > XFASTINT (beg))
3304 old_pos = XFASTINT (beg);
3305 SET_PT (old_pos);
3307 /* We return the length of the encoded text. */
3308 return make_number (encoded_length);
3311 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
3312 1, 2, 0,
3313 "Base64-encode STRING and return the result.\n\
3314 Optional second argument NO-LINE-BREAK means do not break long lines\n\
3315 into shorter lines.")
3316 (string, no_line_break)
3317 Lisp_Object string, no_line_break;
3319 int allength, length, encoded_length;
3320 char *encoded;
3321 Lisp_Object encoded_string;
3323 CHECK_STRING (string, 1);
3325 /* We need to allocate enough room for encoding the text.
3326 We need 33 1/3% more space, plus a newline every 76
3327 characters, and then we round up. */
3328 length = STRING_BYTES (XSTRING (string));
3329 allength = length + length/3 + 1;
3330 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3332 /* We need to allocate enough room for decoding the text. */
3333 if (allength <= MAX_ALLOCA)
3334 encoded = (char *) alloca (allength);
3335 else
3336 encoded = (char *) xmalloc (allength);
3338 encoded_length = base64_encode_1 (XSTRING (string)->data,
3339 encoded, length, NILP (no_line_break),
3340 STRING_MULTIBYTE (string));
3341 if (encoded_length > allength)
3342 abort ();
3344 if (encoded_length < 0)
3346 /* The encoding wasn't possible. */
3347 if (length > MAX_ALLOCA)
3348 xfree (encoded);
3349 error ("Base64 encoding failed");
3352 encoded_string = make_unibyte_string (encoded, encoded_length);
3353 if (allength > MAX_ALLOCA)
3354 xfree (encoded);
3356 return encoded_string;
3359 static int
3360 base64_encode_1 (from, to, length, line_break, multibyte)
3361 const char *from;
3362 char *to;
3363 int length;
3364 int line_break;
3365 int multibyte;
3367 int counter = 0, i = 0;
3368 char *e = to;
3369 unsigned char c;
3370 unsigned int value;
3371 int bytes;
3373 while (i < length)
3375 if (multibyte)
3377 c = STRING_CHAR_AND_LENGTH (from + i, length - i, bytes);
3378 if (!SINGLE_BYTE_CHAR_P (c))
3379 return -1;
3380 i += bytes;
3382 else
3383 c = from[i++];
3385 /* Wrap line every 76 characters. */
3387 if (line_break)
3389 if (counter < MIME_LINE_LENGTH / 4)
3390 counter++;
3391 else
3393 *e++ = '\n';
3394 counter = 1;
3398 /* Process first byte of a triplet. */
3400 *e++ = base64_value_to_char[0x3f & c >> 2];
3401 value = (0x03 & c) << 4;
3403 /* Process second byte of a triplet. */
3405 if (i == length)
3407 *e++ = base64_value_to_char[value];
3408 *e++ = '=';
3409 *e++ = '=';
3410 break;
3413 if (multibyte)
3415 c = STRING_CHAR_AND_LENGTH (from + i, length - i, bytes);
3416 i += bytes;
3418 else
3419 c = from[i++];
3421 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3422 value = (0x0f & c) << 2;
3424 /* Process third byte of a triplet. */
3426 if (i == length)
3428 *e++ = base64_value_to_char[value];
3429 *e++ = '=';
3430 break;
3433 if (multibyte)
3435 c = STRING_CHAR_AND_LENGTH (from + i, length - i, bytes);
3436 i += bytes;
3438 else
3439 c = from[i++];
3441 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3442 *e++ = base64_value_to_char[0x3f & c];
3445 return e - to;
3449 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3450 2, 2, "r",
3451 "Base64-decode the region between BEG and END.\n\
3452 Return the length of the decoded text.\n\
3453 If the region can't be decoded, signal an error and don't modify the buffer.")
3454 (beg, end)
3455 Lisp_Object beg, end;
3457 int ibeg, iend, length;
3458 char *decoded;
3459 int old_pos = PT;
3460 int decoded_length;
3461 int inserted_chars;
3463 validate_region (&beg, &end);
3465 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3466 iend = CHAR_TO_BYTE (XFASTINT (end));
3468 length = iend - ibeg;
3469 /* We need to allocate enough room for decoding the text. */
3470 if (length <= MAX_ALLOCA)
3471 decoded = (char *) alloca (length);
3472 else
3473 decoded = (char *) xmalloc (length);
3475 move_gap_both (XFASTINT (beg), ibeg);
3476 decoded_length = base64_decode_1 (BYTE_POS_ADDR (ibeg), decoded, length);
3477 if (decoded_length > length)
3478 abort ();
3480 if (decoded_length < 0)
3482 /* The decoding wasn't possible. */
3483 if (length > MAX_ALLOCA)
3484 xfree (decoded);
3485 error ("Base64 decoding failed");
3488 inserted_chars = decoded_length;
3489 if (!NILP (current_buffer->enable_multibyte_characters))
3490 decoded_length = str_to_multibyte (decoded, length, decoded_length);
3492 /* Now we have decoded the region, so we insert the new contents
3493 and delete the old. (Insert first in order to preserve markers.) */
3494 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3495 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3496 if (length > MAX_ALLOCA)
3497 xfree (decoded);
3498 /* Delete the original text. */
3499 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3500 iend + decoded_length, 1);
3502 /* If point was outside of the region, restore it exactly; else just
3503 move to the beginning of the region. */
3504 if (old_pos >= XFASTINT (end))
3505 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3506 else if (old_pos > XFASTINT (beg))
3507 old_pos = XFASTINT (beg);
3508 SET_PT (old_pos > ZV ? ZV : old_pos);
3510 return make_number (inserted_chars);
3513 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3514 1, 1, 0,
3515 "Base64-decode STRING and return the result.")
3516 (string)
3517 Lisp_Object string;
3519 char *decoded;
3520 int length, decoded_length;
3521 Lisp_Object decoded_string;
3523 CHECK_STRING (string, 1);
3525 length = STRING_BYTES (XSTRING (string));
3526 /* We need to allocate enough room for decoding the text. */
3527 if (length <= MAX_ALLOCA)
3528 decoded = (char *) alloca (length);
3529 else
3530 decoded = (char *) xmalloc (length);
3532 decoded_length = base64_decode_1 (XSTRING (string)->data, decoded, length);
3533 if (decoded_length > length)
3534 abort ();
3535 else if (decoded_length >= 0)
3536 decoded_string = make_unibyte_string (decoded, decoded_length);
3537 else
3538 decoded_string = Qnil;
3540 if (length > MAX_ALLOCA)
3541 xfree (decoded);
3542 if (!STRINGP (decoded_string))
3543 error ("Base64 decoding failed");
3545 return decoded_string;
3548 static int
3549 base64_decode_1 (from, to, length)
3550 const char *from;
3551 char *to;
3552 int length;
3554 int i = 0;
3555 char *e = to;
3556 unsigned char c;
3557 unsigned long value;
3559 while (1)
3561 /* Process first byte of a quadruplet. */
3563 READ_QUADRUPLET_BYTE (e-to);
3565 if (!IS_BASE64 (c))
3566 return -1;
3567 value = base64_char_to_value[c] << 18;
3569 /* Process second byte of a quadruplet. */
3571 READ_QUADRUPLET_BYTE (-1);
3573 if (!IS_BASE64 (c))
3574 return -1;
3575 value |= base64_char_to_value[c] << 12;
3577 *e++ = (unsigned char) (value >> 16);
3579 /* Process third byte of a quadruplet. */
3581 READ_QUADRUPLET_BYTE (-1);
3583 if (c == '=')
3585 READ_QUADRUPLET_BYTE (-1);
3587 if (c != '=')
3588 return -1;
3589 continue;
3592 if (!IS_BASE64 (c))
3593 return -1;
3594 value |= base64_char_to_value[c] << 6;
3596 *e++ = (unsigned char) (0xff & value >> 8);
3598 /* Process fourth byte of a quadruplet. */
3600 READ_QUADRUPLET_BYTE (-1);
3602 if (c == '=')
3603 continue;
3605 if (!IS_BASE64 (c))
3606 return -1;
3607 value |= base64_char_to_value[c];
3609 *e++ = (unsigned char) (0xff & value);
3615 /***********************************************************************
3616 ***** *****
3617 ***** Hash Tables *****
3618 ***** *****
3619 ***********************************************************************/
3621 /* Implemented by gerd@gnu.org. This hash table implementation was
3622 inspired by CMUCL hash tables. */
3624 /* Ideas:
3626 1. For small tables, association lists are probably faster than
3627 hash tables because they have lower overhead.
3629 For uses of hash tables where the O(1) behavior of table
3630 operations is not a requirement, it might therefore be a good idea
3631 not to hash. Instead, we could just do a linear search in the
3632 key_and_value vector of the hash table. This could be done
3633 if a `:linear-search t' argument is given to make-hash-table. */
3636 /* Value is the key part of entry IDX in hash table H. */
3638 #define HASH_KEY(H, IDX) AREF ((H)->key_and_value, 2 * (IDX))
3640 /* Value is the value part of entry IDX in hash table H. */
3642 #define HASH_VALUE(H, IDX) AREF ((H)->key_and_value, 2 * (IDX) + 1)
3644 /* Value is the index of the next entry following the one at IDX
3645 in hash table H. */
3647 #define HASH_NEXT(H, IDX) AREF ((H)->next, (IDX))
3649 /* Value is the hash code computed for entry IDX in hash table H. */
3651 #define HASH_HASH(H, IDX) AREF ((H)->hash, (IDX))
3653 /* Value is the index of the element in hash table H that is the
3654 start of the collision list at index IDX in the index vector of H. */
3656 #define HASH_INDEX(H, IDX) AREF ((H)->index, (IDX))
3658 /* Value is the size of hash table H. */
3660 #define HASH_TABLE_SIZE(H) XVECTOR ((H)->next)->size
3662 /* The list of all weak hash tables. Don't staticpro this one. */
3664 Lisp_Object Vweak_hash_tables;
3666 /* Various symbols. */
3668 Lisp_Object Qhash_table_p, Qeq, Qeql, Qequal, Qkey, Qvalue;
3669 Lisp_Object QCtest, QCsize, QCrehash_size, QCrehash_threshold, QCweakness;
3670 Lisp_Object Qhash_table_test, Qkey_or_value, Qkey_and_value;
3672 /* Function prototypes. */
3674 static struct Lisp_Hash_Table *check_hash_table P_ ((Lisp_Object));
3675 static int get_key_arg P_ ((Lisp_Object, int, Lisp_Object *, char *));
3676 static void maybe_resize_hash_table P_ ((struct Lisp_Hash_Table *));
3677 static int cmpfn_eql P_ ((struct Lisp_Hash_Table *, Lisp_Object, unsigned,
3678 Lisp_Object, unsigned));
3679 static int cmpfn_equal P_ ((struct Lisp_Hash_Table *, Lisp_Object, unsigned,
3680 Lisp_Object, unsigned));
3681 static int cmpfn_user_defined P_ ((struct Lisp_Hash_Table *, Lisp_Object,
3682 unsigned, Lisp_Object, unsigned));
3683 static unsigned hashfn_eq P_ ((struct Lisp_Hash_Table *, Lisp_Object));
3684 static unsigned hashfn_eql P_ ((struct Lisp_Hash_Table *, Lisp_Object));
3685 static unsigned hashfn_equal P_ ((struct Lisp_Hash_Table *, Lisp_Object));
3686 static unsigned hashfn_user_defined P_ ((struct Lisp_Hash_Table *,
3687 Lisp_Object));
3688 static unsigned sxhash_string P_ ((unsigned char *, int));
3689 static unsigned sxhash_list P_ ((Lisp_Object, int));
3690 static unsigned sxhash_vector P_ ((Lisp_Object, int));
3691 static unsigned sxhash_bool_vector P_ ((Lisp_Object));
3692 static int sweep_weak_table P_ ((struct Lisp_Hash_Table *, int));
3696 /***********************************************************************
3697 Utilities
3698 ***********************************************************************/
3700 /* If OBJ is a Lisp hash table, return a pointer to its struct
3701 Lisp_Hash_Table. Otherwise, signal an error. */
3703 static struct Lisp_Hash_Table *
3704 check_hash_table (obj)
3705 Lisp_Object obj;
3707 CHECK_HASH_TABLE (obj, 0);
3708 return XHASH_TABLE (obj);
3712 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3713 number. */
3716 next_almost_prime (n)
3717 int n;
3719 if (n % 2 == 0)
3720 n += 1;
3721 if (n % 3 == 0)
3722 n += 2;
3723 if (n % 7 == 0)
3724 n += 4;
3725 return n;
3729 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3730 which USED[I] is non-zero. If found at index I in ARGS, set
3731 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3732 -1. This function is used to extract a keyword/argument pair from
3733 a DEFUN parameter list. */
3735 static int
3736 get_key_arg (key, nargs, args, used)
3737 Lisp_Object key;
3738 int nargs;
3739 Lisp_Object *args;
3740 char *used;
3742 int i;
3744 for (i = 0; i < nargs - 1; ++i)
3745 if (!used[i] && EQ (args[i], key))
3746 break;
3748 if (i >= nargs - 1)
3749 i = -1;
3750 else
3752 used[i++] = 1;
3753 used[i] = 1;
3756 return i;
3760 /* Return a Lisp vector which has the same contents as VEC but has
3761 size NEW_SIZE, NEW_SIZE >= VEC->size. Entries in the resulting
3762 vector that are not copied from VEC are set to INIT. */
3764 Lisp_Object
3765 larger_vector (vec, new_size, init)
3766 Lisp_Object vec;
3767 int new_size;
3768 Lisp_Object init;
3770 struct Lisp_Vector *v;
3771 int i, old_size;
3773 xassert (VECTORP (vec));
3774 old_size = XVECTOR (vec)->size;
3775 xassert (new_size >= old_size);
3777 v = allocate_vectorlike (new_size);
3778 v->size = new_size;
3779 bcopy (XVECTOR (vec)->contents, v->contents,
3780 old_size * sizeof *v->contents);
3781 for (i = old_size; i < new_size; ++i)
3782 v->contents[i] = init;
3783 XSETVECTOR (vec, v);
3784 return vec;
3788 /***********************************************************************
3789 Low-level Functions
3790 ***********************************************************************/
3792 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3793 HASH2 in hash table H using `eql'. Value is non-zero if KEY1 and
3794 KEY2 are the same. */
3796 static int
3797 cmpfn_eql (h, key1, hash1, key2, hash2)
3798 struct Lisp_Hash_Table *h;
3799 Lisp_Object key1, key2;
3800 unsigned hash1, hash2;
3802 return (FLOATP (key1)
3803 && FLOATP (key2)
3804 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3808 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3809 HASH2 in hash table H using `equal'. Value is non-zero if KEY1 and
3810 KEY2 are the same. */
3812 static int
3813 cmpfn_equal (h, key1, hash1, key2, hash2)
3814 struct Lisp_Hash_Table *h;
3815 Lisp_Object key1, key2;
3816 unsigned hash1, hash2;
3818 return hash1 == hash2 && !NILP (Fequal (key1, key2));
3822 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3823 HASH2 in hash table H using H->user_cmp_function. Value is non-zero
3824 if KEY1 and KEY2 are the same. */
3826 static int
3827 cmpfn_user_defined (h, key1, hash1, key2, hash2)
3828 struct Lisp_Hash_Table *h;
3829 Lisp_Object key1, key2;
3830 unsigned hash1, hash2;
3832 if (hash1 == hash2)
3834 Lisp_Object args[3];
3836 args[0] = h->user_cmp_function;
3837 args[1] = key1;
3838 args[2] = key2;
3839 return !NILP (Ffuncall (3, args));
3841 else
3842 return 0;
3846 /* Value is a hash code for KEY for use in hash table H which uses
3847 `eq' to compare keys. The hash code returned is guaranteed to fit
3848 in a Lisp integer. */
3850 static unsigned
3851 hashfn_eq (h, key)
3852 struct Lisp_Hash_Table *h;
3853 Lisp_Object key;
3855 unsigned hash = XUINT (key) ^ XGCTYPE (key);
3856 xassert ((hash & ~VALMASK) == 0);
3857 return hash;
3861 /* Value is a hash code for KEY for use in hash table H which uses
3862 `eql' to compare keys. The hash code returned is guaranteed to fit
3863 in a Lisp integer. */
3865 static unsigned
3866 hashfn_eql (h, key)
3867 struct Lisp_Hash_Table *h;
3868 Lisp_Object key;
3870 unsigned hash;
3871 if (FLOATP (key))
3872 hash = sxhash (key, 0);
3873 else
3874 hash = XUINT (key) ^ XGCTYPE (key);
3875 xassert ((hash & ~VALMASK) == 0);
3876 return hash;
3880 /* Value is a hash code for KEY for use in hash table H which uses
3881 `equal' to compare keys. The hash code returned is guaranteed to fit
3882 in a Lisp integer. */
3884 static unsigned
3885 hashfn_equal (h, key)
3886 struct Lisp_Hash_Table *h;
3887 Lisp_Object key;
3889 unsigned hash = sxhash (key, 0);
3890 xassert ((hash & ~VALMASK) == 0);
3891 return hash;
3895 /* Value is a hash code for KEY for use in hash table H which uses as
3896 user-defined function to compare keys. The hash code returned is
3897 guaranteed to fit in a Lisp integer. */
3899 static unsigned
3900 hashfn_user_defined (h, key)
3901 struct Lisp_Hash_Table *h;
3902 Lisp_Object key;
3904 Lisp_Object args[2], hash;
3906 args[0] = h->user_hash_function;
3907 args[1] = key;
3908 hash = Ffuncall (2, args);
3909 if (!INTEGERP (hash))
3910 Fsignal (Qerror,
3911 list2 (build_string ("Invalid hash code returned from \
3912 user-supplied hash function"),
3913 hash));
3914 return XUINT (hash);
3918 /* Create and initialize a new hash table.
3920 TEST specifies the test the hash table will use to compare keys.
3921 It must be either one of the predefined tests `eq', `eql' or
3922 `equal' or a symbol denoting a user-defined test named TEST with
3923 test and hash functions USER_TEST and USER_HASH.
3925 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3927 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3928 new size when it becomes full is computed by adding REHASH_SIZE to
3929 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3930 table's new size is computed by multiplying its old size with
3931 REHASH_SIZE.
3933 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3934 be resized when the ratio of (number of entries in the table) /
3935 (table size) is >= REHASH_THRESHOLD.
3937 WEAK specifies the weakness of the table. If non-nil, it must be
3938 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
3940 Lisp_Object
3941 make_hash_table (test, size, rehash_size, rehash_threshold, weak,
3942 user_test, user_hash)
3943 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
3944 Lisp_Object user_test, user_hash;
3946 struct Lisp_Hash_Table *h;
3947 struct Lisp_Vector *v;
3948 Lisp_Object table;
3949 int index_size, i, len, sz;
3951 /* Preconditions. */
3952 xassert (SYMBOLP (test));
3953 xassert (INTEGERP (size) && XINT (size) >= 0);
3954 xassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3955 || (FLOATP (rehash_size) && XFLOATINT (rehash_size) > 1.0));
3956 xassert (FLOATP (rehash_threshold)
3957 && XFLOATINT (rehash_threshold) > 0
3958 && XFLOATINT (rehash_threshold) <= 1.0);
3960 if (XFASTINT (size) == 0)
3961 size = make_number (1);
3963 /* Allocate a vector, and initialize it. */
3964 len = VECSIZE (struct Lisp_Hash_Table);
3965 v = allocate_vectorlike (len);
3966 v->size = len;
3967 for (i = 0; i < len; ++i)
3968 v->contents[i] = Qnil;
3970 /* Initialize hash table slots. */
3971 sz = XFASTINT (size);
3972 h = (struct Lisp_Hash_Table *) v;
3974 h->test = test;
3975 if (EQ (test, Qeql))
3977 h->cmpfn = cmpfn_eql;
3978 h->hashfn = hashfn_eql;
3980 else if (EQ (test, Qeq))
3982 h->cmpfn = NULL;
3983 h->hashfn = hashfn_eq;
3985 else if (EQ (test, Qequal))
3987 h->cmpfn = cmpfn_equal;
3988 h->hashfn = hashfn_equal;
3990 else
3992 h->user_cmp_function = user_test;
3993 h->user_hash_function = user_hash;
3994 h->cmpfn = cmpfn_user_defined;
3995 h->hashfn = hashfn_user_defined;
3998 h->weak = weak;
3999 h->rehash_threshold = rehash_threshold;
4000 h->rehash_size = rehash_size;
4001 h->count = make_number (0);
4002 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
4003 h->hash = Fmake_vector (size, Qnil);
4004 h->next = Fmake_vector (size, Qnil);
4005 /* Cast to int here avoids losing with gcc 2.95 on Tru64/Alpha... */
4006 index_size = next_almost_prime ((int) (sz / XFLOATINT (rehash_threshold)));
4007 h->index = Fmake_vector (make_number (index_size), Qnil);
4009 /* Set up the free list. */
4010 for (i = 0; i < sz - 1; ++i)
4011 HASH_NEXT (h, i) = make_number (i + 1);
4012 h->next_free = make_number (0);
4014 XSET_HASH_TABLE (table, h);
4015 xassert (HASH_TABLE_P (table));
4016 xassert (XHASH_TABLE (table) == h);
4018 /* Maybe add this hash table to the list of all weak hash tables. */
4019 if (NILP (h->weak))
4020 h->next_weak = Qnil;
4021 else
4023 h->next_weak = Vweak_hash_tables;
4024 Vweak_hash_tables = table;
4027 return table;
4031 /* Return a copy of hash table H1. Keys and values are not copied,
4032 only the table itself is. */
4034 Lisp_Object
4035 copy_hash_table (h1)
4036 struct Lisp_Hash_Table *h1;
4038 Lisp_Object table;
4039 struct Lisp_Hash_Table *h2;
4040 struct Lisp_Vector *v, *next;
4041 int len;
4043 len = VECSIZE (struct Lisp_Hash_Table);
4044 v = allocate_vectorlike (len);
4045 h2 = (struct Lisp_Hash_Table *) v;
4046 next = h2->vec_next;
4047 bcopy (h1, h2, sizeof *h2);
4048 h2->vec_next = next;
4049 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
4050 h2->hash = Fcopy_sequence (h1->hash);
4051 h2->next = Fcopy_sequence (h1->next);
4052 h2->index = Fcopy_sequence (h1->index);
4053 XSET_HASH_TABLE (table, h2);
4055 /* Maybe add this hash table to the list of all weak hash tables. */
4056 if (!NILP (h2->weak))
4058 h2->next_weak = Vweak_hash_tables;
4059 Vweak_hash_tables = table;
4062 return table;
4066 /* Resize hash table H if it's too full. If H cannot be resized
4067 because it's already too large, throw an error. */
4069 static INLINE void
4070 maybe_resize_hash_table (h)
4071 struct Lisp_Hash_Table *h;
4073 if (NILP (h->next_free))
4075 int old_size = HASH_TABLE_SIZE (h);
4076 int i, new_size, index_size;
4078 if (INTEGERP (h->rehash_size))
4079 new_size = old_size + XFASTINT (h->rehash_size);
4080 else
4081 new_size = old_size * XFLOATINT (h->rehash_size);
4082 new_size = max (old_size + 1, new_size);
4083 index_size = next_almost_prime ((int)
4084 (new_size
4085 / XFLOATINT (h->rehash_threshold)));
4086 if (max (index_size, 2 * new_size) & ~VALMASK)
4087 error ("Hash table too large to resize");
4089 h->key_and_value = larger_vector (h->key_and_value, 2 * new_size, Qnil);
4090 h->next = larger_vector (h->next, new_size, Qnil);
4091 h->hash = larger_vector (h->hash, new_size, Qnil);
4092 h->index = Fmake_vector (make_number (index_size), Qnil);
4094 /* Update the free list. Do it so that new entries are added at
4095 the end of the free list. This makes some operations like
4096 maphash faster. */
4097 for (i = old_size; i < new_size - 1; ++i)
4098 HASH_NEXT (h, i) = make_number (i + 1);
4100 if (!NILP (h->next_free))
4102 Lisp_Object last, next;
4104 last = h->next_free;
4105 while (next = HASH_NEXT (h, XFASTINT (last)),
4106 !NILP (next))
4107 last = next;
4109 HASH_NEXT (h, XFASTINT (last)) = make_number (old_size);
4111 else
4112 XSETFASTINT (h->next_free, old_size);
4114 /* Rehash. */
4115 for (i = 0; i < old_size; ++i)
4116 if (!NILP (HASH_HASH (h, i)))
4118 unsigned hash_code = XUINT (HASH_HASH (h, i));
4119 int start_of_bucket = hash_code % XVECTOR (h->index)->size;
4120 HASH_NEXT (h, i) = HASH_INDEX (h, start_of_bucket);
4121 HASH_INDEX (h, start_of_bucket) = make_number (i);
4127 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
4128 the hash code of KEY. Value is the index of the entry in H
4129 matching KEY, or -1 if not found. */
4132 hash_lookup (h, key, hash)
4133 struct Lisp_Hash_Table *h;
4134 Lisp_Object key;
4135 unsigned *hash;
4137 unsigned hash_code;
4138 int start_of_bucket;
4139 Lisp_Object idx;
4141 hash_code = h->hashfn (h, key);
4142 if (hash)
4143 *hash = hash_code;
4145 start_of_bucket = hash_code % XVECTOR (h->index)->size;
4146 idx = HASH_INDEX (h, start_of_bucket);
4148 /* We need not gcpro idx since it's either an integer or nil. */
4149 while (!NILP (idx))
4151 int i = XFASTINT (idx);
4152 if (EQ (key, HASH_KEY (h, i))
4153 || (h->cmpfn
4154 && h->cmpfn (h, key, hash_code,
4155 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
4156 break;
4157 idx = HASH_NEXT (h, i);
4160 return NILP (idx) ? -1 : XFASTINT (idx);
4164 /* Put an entry into hash table H that associates KEY with VALUE.
4165 HASH is a previously computed hash code of KEY.
4166 Value is the index of the entry in H matching KEY. */
4169 hash_put (h, key, value, hash)
4170 struct Lisp_Hash_Table *h;
4171 Lisp_Object key, value;
4172 unsigned hash;
4174 int start_of_bucket, i;
4176 xassert ((hash & ~VALMASK) == 0);
4178 /* Increment count after resizing because resizing may fail. */
4179 maybe_resize_hash_table (h);
4180 h->count = make_number (XFASTINT (h->count) + 1);
4182 /* Store key/value in the key_and_value vector. */
4183 i = XFASTINT (h->next_free);
4184 h->next_free = HASH_NEXT (h, i);
4185 HASH_KEY (h, i) = key;
4186 HASH_VALUE (h, i) = value;
4188 /* Remember its hash code. */
4189 HASH_HASH (h, i) = make_number (hash);
4191 /* Add new entry to its collision chain. */
4192 start_of_bucket = hash % XVECTOR (h->index)->size;
4193 HASH_NEXT (h, i) = HASH_INDEX (h, start_of_bucket);
4194 HASH_INDEX (h, start_of_bucket) = make_number (i);
4195 return i;
4199 /* Remove the entry matching KEY from hash table H, if there is one. */
4201 void
4202 hash_remove (h, key)
4203 struct Lisp_Hash_Table *h;
4204 Lisp_Object key;
4206 unsigned hash_code;
4207 int start_of_bucket;
4208 Lisp_Object idx, prev;
4210 hash_code = h->hashfn (h, key);
4211 start_of_bucket = hash_code % XVECTOR (h->index)->size;
4212 idx = HASH_INDEX (h, start_of_bucket);
4213 prev = Qnil;
4215 /* We need not gcpro idx, prev since they're either integers or nil. */
4216 while (!NILP (idx))
4218 int i = XFASTINT (idx);
4220 if (EQ (key, HASH_KEY (h, i))
4221 || (h->cmpfn
4222 && h->cmpfn (h, key, hash_code,
4223 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
4225 /* Take entry out of collision chain. */
4226 if (NILP (prev))
4227 HASH_INDEX (h, start_of_bucket) = HASH_NEXT (h, i);
4228 else
4229 HASH_NEXT (h, XFASTINT (prev)) = HASH_NEXT (h, i);
4231 /* Clear slots in key_and_value and add the slots to
4232 the free list. */
4233 HASH_KEY (h, i) = HASH_VALUE (h, i) = HASH_HASH (h, i) = Qnil;
4234 HASH_NEXT (h, i) = h->next_free;
4235 h->next_free = make_number (i);
4236 h->count = make_number (XFASTINT (h->count) - 1);
4237 xassert (XINT (h->count) >= 0);
4238 break;
4240 else
4242 prev = idx;
4243 idx = HASH_NEXT (h, i);
4249 /* Clear hash table H. */
4251 void
4252 hash_clear (h)
4253 struct Lisp_Hash_Table *h;
4255 if (XFASTINT (h->count) > 0)
4257 int i, size = HASH_TABLE_SIZE (h);
4259 for (i = 0; i < size; ++i)
4261 HASH_NEXT (h, i) = i < size - 1 ? make_number (i + 1) : Qnil;
4262 HASH_KEY (h, i) = Qnil;
4263 HASH_VALUE (h, i) = Qnil;
4264 HASH_HASH (h, i) = Qnil;
4267 for (i = 0; i < XVECTOR (h->index)->size; ++i)
4268 XVECTOR (h->index)->contents[i] = Qnil;
4270 h->next_free = make_number (0);
4271 h->count = make_number (0);
4277 /************************************************************************
4278 Weak Hash Tables
4279 ************************************************************************/
4281 /* Sweep weak hash table H. REMOVE_ENTRIES_P non-zero means remove
4282 entries from the table that don't survive the current GC.
4283 REMOVE_ENTRIES_P zero means mark entries that are in use. Value is
4284 non-zero if anything was marked. */
4286 static int
4287 sweep_weak_table (h, remove_entries_p)
4288 struct Lisp_Hash_Table *h;
4289 int remove_entries_p;
4291 int bucket, n, marked;
4293 n = XVECTOR (h->index)->size & ~ARRAY_MARK_FLAG;
4294 marked = 0;
4296 for (bucket = 0; bucket < n; ++bucket)
4298 Lisp_Object idx, prev;
4300 /* Follow collision chain, removing entries that
4301 don't survive this garbage collection. */
4302 idx = HASH_INDEX (h, bucket);
4303 prev = Qnil;
4304 while (!GC_NILP (idx))
4306 int remove_p;
4307 int i = XFASTINT (idx);
4308 Lisp_Object next;
4309 int key_known_to_survive_p, value_known_to_survive_p;
4311 key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
4312 value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
4314 if (EQ (h->weak, Qkey))
4315 remove_p = !key_known_to_survive_p;
4316 else if (EQ (h->weak, Qvalue))
4317 remove_p = !value_known_to_survive_p;
4318 else if (EQ (h->weak, Qkey_or_value))
4319 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
4320 else if (EQ (h->weak, Qkey_and_value))
4321 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
4322 else
4323 abort ();
4325 next = HASH_NEXT (h, i);
4327 if (remove_entries_p)
4329 if (remove_p)
4331 /* Take out of collision chain. */
4332 if (GC_NILP (prev))
4333 HASH_INDEX (h, i) = next;
4334 else
4335 HASH_NEXT (h, XFASTINT (prev)) = next;
4337 /* Add to free list. */
4338 HASH_NEXT (h, i) = h->next_free;
4339 h->next_free = idx;
4341 /* Clear key, value, and hash. */
4342 HASH_KEY (h, i) = HASH_VALUE (h, i) = Qnil;
4343 HASH_HASH (h, i) = Qnil;
4345 h->count = make_number (XFASTINT (h->count) - 1);
4348 else
4350 if (!remove_p)
4352 /* Make sure key and value survive. */
4353 if (!key_known_to_survive_p)
4355 mark_object (&HASH_KEY (h, i));
4356 marked = 1;
4359 if (!value_known_to_survive_p)
4361 mark_object (&HASH_VALUE (h, i));
4362 marked = 1;
4367 idx = next;
4371 return marked;
4374 /* Remove elements from weak hash tables that don't survive the
4375 current garbage collection. Remove weak tables that don't survive
4376 from Vweak_hash_tables. Called from gc_sweep. */
4378 void
4379 sweep_weak_hash_tables ()
4381 Lisp_Object table, used, next;
4382 struct Lisp_Hash_Table *h;
4383 int marked;
4385 /* Mark all keys and values that are in use. Keep on marking until
4386 there is no more change. This is necessary for cases like
4387 value-weak table A containing an entry X -> Y, where Y is used in a
4388 key-weak table B, Z -> Y. If B comes after A in the list of weak
4389 tables, X -> Y might be removed from A, although when looking at B
4390 one finds that it shouldn't. */
4393 marked = 0;
4394 for (table = Vweak_hash_tables; !GC_NILP (table); table = h->next_weak)
4396 h = XHASH_TABLE (table);
4397 if (h->size & ARRAY_MARK_FLAG)
4398 marked |= sweep_weak_table (h, 0);
4401 while (marked);
4403 /* Remove tables and entries that aren't used. */
4404 for (table = Vweak_hash_tables, used = Qnil; !GC_NILP (table); table = next)
4406 h = XHASH_TABLE (table);
4407 next = h->next_weak;
4409 if (h->size & ARRAY_MARK_FLAG)
4411 /* TABLE is marked as used. Sweep its contents. */
4412 if (XFASTINT (h->count) > 0)
4413 sweep_weak_table (h, 1);
4415 /* Add table to the list of used weak hash tables. */
4416 h->next_weak = used;
4417 used = table;
4421 Vweak_hash_tables = used;
4426 /***********************************************************************
4427 Hash Code Computation
4428 ***********************************************************************/
4430 /* Maximum depth up to which to dive into Lisp structures. */
4432 #define SXHASH_MAX_DEPTH 3
4434 /* Maximum length up to which to take list and vector elements into
4435 account. */
4437 #define SXHASH_MAX_LEN 7
4439 /* Combine two integers X and Y for hashing. */
4441 #define SXHASH_COMBINE(X, Y) \
4442 ((((unsigned)(X) << 4) + (((unsigned)(X) >> 24) & 0x0fffffff)) \
4443 + (unsigned)(Y))
4446 /* Return a hash for string PTR which has length LEN. The hash
4447 code returned is guaranteed to fit in a Lisp integer. */
4449 static unsigned
4450 sxhash_string (ptr, len)
4451 unsigned char *ptr;
4452 int len;
4454 unsigned char *p = ptr;
4455 unsigned char *end = p + len;
4456 unsigned char c;
4457 unsigned hash = 0;
4459 while (p != end)
4461 c = *p++;
4462 if (c >= 0140)
4463 c -= 40;
4464 hash = ((hash << 3) + (hash >> 28) + c);
4467 return hash & VALMASK;
4471 /* Return a hash for list LIST. DEPTH is the current depth in the
4472 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4474 static unsigned
4475 sxhash_list (list, depth)
4476 Lisp_Object list;
4477 int depth;
4479 unsigned hash = 0;
4480 int i;
4482 if (depth < SXHASH_MAX_DEPTH)
4483 for (i = 0;
4484 CONSP (list) && i < SXHASH_MAX_LEN;
4485 list = XCDR (list), ++i)
4487 unsigned hash2 = sxhash (XCAR (list), depth + 1);
4488 hash = SXHASH_COMBINE (hash, hash2);
4491 return hash;
4495 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4496 the Lisp structure. */
4498 static unsigned
4499 sxhash_vector (vec, depth)
4500 Lisp_Object vec;
4501 int depth;
4503 unsigned hash = XVECTOR (vec)->size;
4504 int i, n;
4506 n = min (SXHASH_MAX_LEN, XVECTOR (vec)->size);
4507 for (i = 0; i < n; ++i)
4509 unsigned hash2 = sxhash (XVECTOR (vec)->contents[i], depth + 1);
4510 hash = SXHASH_COMBINE (hash, hash2);
4513 return hash;
4517 /* Return a hash for bool-vector VECTOR. */
4519 static unsigned
4520 sxhash_bool_vector (vec)
4521 Lisp_Object vec;
4523 unsigned hash = XBOOL_VECTOR (vec)->size;
4524 int i, n;
4526 n = min (SXHASH_MAX_LEN, XBOOL_VECTOR (vec)->vector_size);
4527 for (i = 0; i < n; ++i)
4528 hash = SXHASH_COMBINE (hash, XBOOL_VECTOR (vec)->data[i]);
4530 return hash;
4534 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4535 structure. Value is an unsigned integer clipped to VALMASK. */
4537 unsigned
4538 sxhash (obj, depth)
4539 Lisp_Object obj;
4540 int depth;
4542 unsigned hash;
4544 if (depth > SXHASH_MAX_DEPTH)
4545 return 0;
4547 switch (XTYPE (obj))
4549 case Lisp_Int:
4550 hash = XUINT (obj);
4551 break;
4553 case Lisp_Symbol:
4554 hash = sxhash_string (XSYMBOL (obj)->name->data,
4555 XSYMBOL (obj)->name->size);
4556 break;
4558 case Lisp_Misc:
4559 hash = XUINT (obj);
4560 break;
4562 case Lisp_String:
4563 hash = sxhash_string (XSTRING (obj)->data, XSTRING (obj)->size);
4564 break;
4566 /* This can be everything from a vector to an overlay. */
4567 case Lisp_Vectorlike:
4568 if (VECTORP (obj))
4569 /* According to the CL HyperSpec, two arrays are equal only if
4570 they are `eq', except for strings and bit-vectors. In
4571 Emacs, this works differently. We have to compare element
4572 by element. */
4573 hash = sxhash_vector (obj, depth);
4574 else if (BOOL_VECTOR_P (obj))
4575 hash = sxhash_bool_vector (obj);
4576 else
4577 /* Others are `equal' if they are `eq', so let's take their
4578 address as hash. */
4579 hash = XUINT (obj);
4580 break;
4582 case Lisp_Cons:
4583 hash = sxhash_list (obj, depth);
4584 break;
4586 case Lisp_Float:
4588 unsigned char *p = (unsigned char *) &XFLOAT_DATA (obj);
4589 unsigned char *e = p + sizeof XFLOAT_DATA (obj);
4590 for (hash = 0; p < e; ++p)
4591 hash = SXHASH_COMBINE (hash, *p);
4592 break;
4595 default:
4596 abort ();
4599 return hash & VALMASK;
4604 /***********************************************************************
4605 Lisp Interface
4606 ***********************************************************************/
4609 DEFUN ("sxhash", Fsxhash, Ssxhash, 1, 1, 0,
4610 "Compute a hash code for OBJ and return it as integer.")
4611 (obj)
4612 Lisp_Object obj;
4614 unsigned hash = sxhash (obj, 0);;
4615 return make_number (hash);
4619 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4620 "Create and return a new hash table.\n\
4621 Arguments are specified as keyword/argument pairs. The following\n\
4622 arguments are defined:\n\
4624 :test TEST -- TEST must be a symbol that specifies how to compare keys.\n\
4625 Default is `eql'. Predefined are the tests `eq', `eql', and `equal'.\n\
4626 User-supplied test and hash functions can be specified via\n\
4627 `define-hash-table-test'.\n\
4629 :size SIZE -- A hint as to how many elements will be put in the table.\n\
4630 Default is 65.\n\
4632 :rehash-size REHASH-SIZE - Indicates how to expand the table when\n\
4633 it fills up. If REHASH-SIZE is an integer, add that many space.\n\
4634 If it is a float, it must be > 1.0, and the new size is computed by\n\
4635 multiplying the old size with that factor. Default is 1.5.\n\
4637 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.\n\
4638 Resize the hash table when ratio of the number of entries in the table.\n\
4639 Default is 0.8.\n\
4641 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',\n\
4642 `key-or-value', or `key-and-value'. If WEAK is not nil, the table returned\n\
4643 is a weak table. Key/value pairs are removed from a weak hash table when\n\
4644 there are no non-weak references pointing to their key, value, one of key\n\
4645 or value, or both key and value, depending on WEAK. WEAK t is equivalent\n\
4646 to `key-and-value'. Default value of WEAK is nil.")
4647 (nargs, args)
4648 int nargs;
4649 Lisp_Object *args;
4651 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4652 Lisp_Object user_test, user_hash;
4653 char *used;
4654 int i;
4656 /* The vector `used' is used to keep track of arguments that
4657 have been consumed. */
4658 used = (char *) alloca (nargs * sizeof *used);
4659 bzero (used, nargs * sizeof *used);
4661 /* See if there's a `:test TEST' among the arguments. */
4662 i = get_key_arg (QCtest, nargs, args, used);
4663 test = i < 0 ? Qeql : args[i];
4664 if (!EQ (test, Qeq) && !EQ (test, Qeql) && !EQ (test, Qequal))
4666 /* See if it is a user-defined test. */
4667 Lisp_Object prop;
4669 prop = Fget (test, Qhash_table_test);
4670 if (!CONSP (prop) || XFASTINT (Flength (prop)) < 2)
4671 Fsignal (Qerror, list2 (build_string ("Invalid hash table test"),
4672 test));
4673 user_test = Fnth (make_number (0), prop);
4674 user_hash = Fnth (make_number (1), prop);
4676 else
4677 user_test = user_hash = Qnil;
4679 /* See if there's a `:size SIZE' argument. */
4680 i = get_key_arg (QCsize, nargs, args, used);
4681 size = i < 0 ? make_number (DEFAULT_HASH_SIZE) : args[i];
4682 if (!INTEGERP (size) || XINT (size) < 0)
4683 Fsignal (Qerror,
4684 list2 (build_string ("Invalid hash table size"),
4685 size));
4687 /* Look for `:rehash-size SIZE'. */
4688 i = get_key_arg (QCrehash_size, nargs, args, used);
4689 rehash_size = i < 0 ? make_float (DEFAULT_REHASH_SIZE) : args[i];
4690 if (!NUMBERP (rehash_size)
4691 || (INTEGERP (rehash_size) && XINT (rehash_size) <= 0)
4692 || XFLOATINT (rehash_size) <= 1.0)
4693 Fsignal (Qerror,
4694 list2 (build_string ("Invalid hash table rehash size"),
4695 rehash_size));
4697 /* Look for `:rehash-threshold THRESHOLD'. */
4698 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4699 rehash_threshold = i < 0 ? make_float (DEFAULT_REHASH_THRESHOLD) : args[i];
4700 if (!FLOATP (rehash_threshold)
4701 || XFLOATINT (rehash_threshold) <= 0.0
4702 || XFLOATINT (rehash_threshold) > 1.0)
4703 Fsignal (Qerror,
4704 list2 (build_string ("Invalid hash table rehash threshold"),
4705 rehash_threshold));
4707 /* Look for `:weakness WEAK'. */
4708 i = get_key_arg (QCweakness, nargs, args, used);
4709 weak = i < 0 ? Qnil : args[i];
4710 if (EQ (weak, Qt))
4711 weak = Qkey_and_value;
4712 if (!NILP (weak)
4713 && !EQ (weak, Qkey)
4714 && !EQ (weak, Qvalue)
4715 && !EQ (weak, Qkey_or_value)
4716 && !EQ (weak, Qkey_and_value))
4717 Fsignal (Qerror, list2 (build_string ("Invalid hash table weakness"),
4718 weak));
4720 /* Now, all args should have been used up, or there's a problem. */
4721 for (i = 0; i < nargs; ++i)
4722 if (!used[i])
4723 Fsignal (Qerror,
4724 list2 (build_string ("Invalid argument list"), args[i]));
4726 return make_hash_table (test, size, rehash_size, rehash_threshold, weak,
4727 user_test, user_hash);
4731 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4732 "Return a copy of hash table TABLE.")
4733 (table)
4734 Lisp_Object table;
4736 return copy_hash_table (check_hash_table (table));
4740 DEFUN ("makehash", Fmakehash, Smakehash, 0, 1, 0,
4741 "Create a new hash table.\n\
4742 Optional first argument TEST specifies how to compare keys in\n\
4743 the table. Predefined tests are `eq', `eql', and `equal'. Default\n\
4744 is `eql'. New tests can be defined with `define-hash-table-test'.")
4745 (test)
4746 Lisp_Object test;
4748 Lisp_Object args[2];
4749 args[0] = QCtest;
4750 args[1] = NILP (test) ? Qeql : test;
4751 return Fmake_hash_table (2, args);
4755 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4756 "Return the number of elements in TABLE.")
4757 (table)
4758 Lisp_Object table;
4760 return check_hash_table (table)->count;
4764 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4765 Shash_table_rehash_size, 1, 1, 0,
4766 "Return the current rehash size of TABLE.")
4767 (table)
4768 Lisp_Object table;
4770 return check_hash_table (table)->rehash_size;
4774 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4775 Shash_table_rehash_threshold, 1, 1, 0,
4776 "Return the current rehash threshold of TABLE.")
4777 (table)
4778 Lisp_Object table;
4780 return check_hash_table (table)->rehash_threshold;
4784 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4785 "Return the size of TABLE.\n\
4786 The size can be used as an argument to `make-hash-table' to create\n\
4787 a hash table than can hold as many elements of TABLE holds\n\
4788 without need for resizing.")
4789 (table)
4790 Lisp_Object table;
4792 struct Lisp_Hash_Table *h = check_hash_table (table);
4793 return make_number (HASH_TABLE_SIZE (h));
4797 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4798 "Return the test TABLE uses.")
4799 (table)
4800 Lisp_Object table;
4802 return check_hash_table (table)->test;
4806 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4807 1, 1, 0,
4808 "Return the weakness of TABLE.")
4809 (table)
4810 Lisp_Object table;
4812 return check_hash_table (table)->weak;
4816 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4817 "Return t if OBJ is a Lisp hash table object.")
4818 (obj)
4819 Lisp_Object obj;
4821 return HASH_TABLE_P (obj) ? Qt : Qnil;
4825 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4826 "Clear hash table TABLE.")
4827 (table)
4828 Lisp_Object table;
4830 hash_clear (check_hash_table (table));
4831 return Qnil;
4835 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4836 "Look up KEY in TABLE and return its associated value.\n\
4837 If KEY is not found, return DFLT which defaults to nil.")
4838 (key, table, dflt)
4839 Lisp_Object key, table, dflt;
4841 struct Lisp_Hash_Table *h = check_hash_table (table);
4842 int i = hash_lookup (h, key, NULL);
4843 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4847 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4848 "Associate KEY with VALUE in hash table TABLE.\n\
4849 If KEY is already present in table, replace its current value with\n\
4850 VALUE.")
4851 (key, value, table)
4852 Lisp_Object key, value, table;
4854 struct Lisp_Hash_Table *h = check_hash_table (table);
4855 int i;
4856 unsigned hash;
4858 i = hash_lookup (h, key, &hash);
4859 if (i >= 0)
4860 HASH_VALUE (h, i) = value;
4861 else
4862 hash_put (h, key, value, hash);
4864 return value;
4868 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4869 "Remove KEY from TABLE.")
4870 (key, table)
4871 Lisp_Object key, table;
4873 struct Lisp_Hash_Table *h = check_hash_table (table);
4874 hash_remove (h, key);
4875 return Qnil;
4879 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4880 "Call FUNCTION for all entries in hash table TABLE.\n\
4881 FUNCTION is called with 2 arguments KEY and VALUE.")
4882 (function, table)
4883 Lisp_Object function, table;
4885 struct Lisp_Hash_Table *h = check_hash_table (table);
4886 Lisp_Object args[3];
4887 int i;
4889 for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
4890 if (!NILP (HASH_HASH (h, i)))
4892 args[0] = function;
4893 args[1] = HASH_KEY (h, i);
4894 args[2] = HASH_VALUE (h, i);
4895 Ffuncall (3, args);
4898 return Qnil;
4902 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4903 Sdefine_hash_table_test, 3, 3, 0,
4904 "Define a new hash table test with name NAME, a symbol.\n\
4905 In hash tables create with NAME specified as test, use TEST to compare\n\
4906 keys, and HASH for computing hash codes of keys.\n\
4908 TEST must be a function taking two arguments and returning non-nil\n\
4909 if both arguments are the same. HASH must be a function taking\n\
4910 one argument and return an integer that is the hash code of the\n\
4911 argument. Hash code computation should use the whole value range of\n\
4912 integers, including negative integers.")
4913 (name, test, hash)
4914 Lisp_Object name, test, hash;
4916 return Fput (name, Qhash_table_test, list2 (test, hash));
4922 void
4923 syms_of_fns ()
4925 /* Hash table stuff. */
4926 Qhash_table_p = intern ("hash-table-p");
4927 staticpro (&Qhash_table_p);
4928 Qeq = intern ("eq");
4929 staticpro (&Qeq);
4930 Qeql = intern ("eql");
4931 staticpro (&Qeql);
4932 Qequal = intern ("equal");
4933 staticpro (&Qequal);
4934 QCtest = intern (":test");
4935 staticpro (&QCtest);
4936 QCsize = intern (":size");
4937 staticpro (&QCsize);
4938 QCrehash_size = intern (":rehash-size");
4939 staticpro (&QCrehash_size);
4940 QCrehash_threshold = intern (":rehash-threshold");
4941 staticpro (&QCrehash_threshold);
4942 QCweakness = intern (":weakness");
4943 staticpro (&QCweakness);
4944 Qkey = intern ("key");
4945 staticpro (&Qkey);
4946 Qvalue = intern ("value");
4947 staticpro (&Qvalue);
4948 Qhash_table_test = intern ("hash-table-test");
4949 staticpro (&Qhash_table_test);
4950 Qkey_or_value = intern ("key-or-value");
4951 staticpro (&Qkey_or_value);
4952 Qkey_and_value = intern ("key-and-value");
4953 staticpro (&Qkey_and_value);
4955 defsubr (&Ssxhash);
4956 defsubr (&Smake_hash_table);
4957 defsubr (&Scopy_hash_table);
4958 defsubr (&Smakehash);
4959 defsubr (&Shash_table_count);
4960 defsubr (&Shash_table_rehash_size);
4961 defsubr (&Shash_table_rehash_threshold);
4962 defsubr (&Shash_table_size);
4963 defsubr (&Shash_table_test);
4964 defsubr (&Shash_table_weakness);
4965 defsubr (&Shash_table_p);
4966 defsubr (&Sclrhash);
4967 defsubr (&Sgethash);
4968 defsubr (&Sputhash);
4969 defsubr (&Sremhash);
4970 defsubr (&Smaphash);
4971 defsubr (&Sdefine_hash_table_test);
4973 Qstring_lessp = intern ("string-lessp");
4974 staticpro (&Qstring_lessp);
4975 Qprovide = intern ("provide");
4976 staticpro (&Qprovide);
4977 Qrequire = intern ("require");
4978 staticpro (&Qrequire);
4979 Qyes_or_no_p_history = intern ("yes-or-no-p-history");
4980 staticpro (&Qyes_or_no_p_history);
4981 Qcursor_in_echo_area = intern ("cursor-in-echo-area");
4982 staticpro (&Qcursor_in_echo_area);
4983 Qwidget_type = intern ("widget-type");
4984 staticpro (&Qwidget_type);
4986 staticpro (&string_char_byte_cache_string);
4987 string_char_byte_cache_string = Qnil;
4989 Fset (Qyes_or_no_p_history, Qnil);
4991 DEFVAR_LISP ("features", &Vfeatures,
4992 "A list of symbols which are the features of the executing emacs.\n\
4993 Used by `featurep' and `require', and altered by `provide'.");
4994 Vfeatures = Qnil;
4996 DEFVAR_BOOL ("use-dialog-box", &use_dialog_box,
4997 "*Non-nil means mouse commands use dialog boxes to ask questions.\n\
4998 This applies to y-or-n and yes-or-no questions asked by commands\n\
4999 invoked by mouse clicks and mouse menu items.");
5000 use_dialog_box = 1;
5002 defsubr (&Sidentity);
5003 defsubr (&Srandom);
5004 defsubr (&Slength);
5005 defsubr (&Ssafe_length);
5006 defsubr (&Sstring_bytes);
5007 defsubr (&Sstring_equal);
5008 defsubr (&Scompare_strings);
5009 defsubr (&Sstring_lessp);
5010 defsubr (&Sappend);
5011 defsubr (&Sconcat);
5012 defsubr (&Svconcat);
5013 defsubr (&Scopy_sequence);
5014 defsubr (&Sstring_make_multibyte);
5015 defsubr (&Sstring_make_unibyte);
5016 defsubr (&Sstring_as_multibyte);
5017 defsubr (&Sstring_as_unibyte);
5018 defsubr (&Scopy_alist);
5019 defsubr (&Ssubstring);
5020 defsubr (&Snthcdr);
5021 defsubr (&Snth);
5022 defsubr (&Selt);
5023 defsubr (&Smember);
5024 defsubr (&Smemq);
5025 defsubr (&Sassq);
5026 defsubr (&Sassoc);
5027 defsubr (&Srassq);
5028 defsubr (&Srassoc);
5029 defsubr (&Sdelq);
5030 defsubr (&Sdelete);
5031 defsubr (&Snreverse);
5032 defsubr (&Sreverse);
5033 defsubr (&Ssort);
5034 defsubr (&Splist_get);
5035 defsubr (&Sget);
5036 defsubr (&Splist_put);
5037 defsubr (&Sput);
5038 defsubr (&Sequal);
5039 defsubr (&Sfillarray);
5040 defsubr (&Schar_table_subtype);
5041 defsubr (&Schar_table_parent);
5042 defsubr (&Sset_char_table_parent);
5043 defsubr (&Schar_table_extra_slot);
5044 defsubr (&Sset_char_table_extra_slot);
5045 defsubr (&Schar_table_range);
5046 defsubr (&Sset_char_table_range);
5047 defsubr (&Sset_char_table_default);
5048 defsubr (&Soptimize_char_table);
5049 defsubr (&Smap_char_table);
5050 defsubr (&Snconc);
5051 defsubr (&Smapcar);
5052 defsubr (&Smapc);
5053 defsubr (&Smapconcat);
5054 defsubr (&Sy_or_n_p);
5055 defsubr (&Syes_or_no_p);
5056 defsubr (&Sload_average);
5057 defsubr (&Sfeaturep);
5058 defsubr (&Srequire);
5059 defsubr (&Sprovide);
5060 defsubr (&Splist_member);
5061 defsubr (&Swidget_put);
5062 defsubr (&Swidget_get);
5063 defsubr (&Swidget_apply);
5064 defsubr (&Sbase64_encode_region);
5065 defsubr (&Sbase64_decode_region);
5066 defsubr (&Sbase64_encode_string);
5067 defsubr (&Sbase64_decode_string);
5071 void
5072 init_fns ()
5074 Vweak_hash_tables = Qnil;