Convert DEFUNs to standard C.
[emacs.git] / src / fns.c
blob42e7a715f768f562362664affdb950502bf320ea
1 /* Random utility Lisp functions.
2 Copyright (C) 1985, 1986, 1987, 1993, 1994, 1995, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008, 2009, 2010
5 Free Software Foundation, Inc.
7 This file is part of GNU Emacs.
9 GNU Emacs is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
14 GNU Emacs is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #include <time.h>
28 #include <setjmp.h>
30 /* Note on some machines this defines `vector' as a typedef,
31 so make sure we don't use that name in this file. */
32 #undef vector
33 #define vector *****
35 #include "lisp.h"
36 #include "commands.h"
37 #include "character.h"
38 #include "coding.h"
39 #include "buffer.h"
40 #include "keyboard.h"
41 #include "keymap.h"
42 #include "intervals.h"
43 #include "frame.h"
44 #include "window.h"
45 #include "blockinput.h"
46 #ifdef HAVE_MENUS
47 #if defined (HAVE_X_WINDOWS)
48 #include "xterm.h"
49 #endif
50 #endif /* HAVE_MENUS */
52 #ifndef NULL
53 #define NULL ((POINTER_TYPE *)0)
54 #endif
56 /* Nonzero enables use of dialog boxes for questions
57 asked by mouse commands. */
58 int use_dialog_box;
60 /* Nonzero enables use of a file dialog for file name
61 questions asked by mouse commands. */
62 int use_file_dialog;
64 extern int minibuffer_auto_raise;
65 extern Lisp_Object minibuf_window;
66 extern Lisp_Object Vlocale_coding_system;
67 extern int load_in_progress;
69 Lisp_Object Qstring_lessp, Qprovide, Qrequire;
70 Lisp_Object Qyes_or_no_p_history;
71 Lisp_Object Qcursor_in_echo_area;
72 Lisp_Object Qwidget_type;
73 Lisp_Object Qcodeset, Qdays, Qmonths, Qpaper;
75 extern Lisp_Object Qinput_method_function;
77 static int internal_equal (Lisp_Object , Lisp_Object, int, int);
79 extern long get_random (void);
80 extern void seed_random (long);
82 #ifndef HAVE_UNISTD_H
83 extern long time ();
84 #endif
86 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
87 doc: /* Return the argument unchanged. */)
88 (Lisp_Object arg)
90 return arg;
93 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
94 doc: /* Return a pseudo-random number.
95 All integers representable in Lisp are equally likely.
96 On most systems, this is 29 bits' worth.
97 With positive integer LIMIT, return random number in interval [0,LIMIT).
98 With argument t, set the random number seed from the current time and pid.
99 Other values of LIMIT are ignored. */)
100 (Lisp_Object limit)
102 EMACS_INT val;
103 Lisp_Object lispy_val;
104 unsigned long denominator;
106 if (EQ (limit, Qt))
107 seed_random (getpid () + time (NULL));
108 if (NATNUMP (limit) && XFASTINT (limit) != 0)
110 /* Try to take our random number from the higher bits of VAL,
111 not the lower, since (says Gentzel) the low bits of `random'
112 are less random than the higher ones. We do this by using the
113 quotient rather than the remainder. At the high end of the RNG
114 it's possible to get a quotient larger than n; discarding
115 these values eliminates the bias that would otherwise appear
116 when using a large n. */
117 denominator = ((unsigned long)1 << VALBITS) / XFASTINT (limit);
119 val = get_random () / denominator;
120 while (val >= XFASTINT (limit));
122 else
123 val = get_random ();
124 XSETINT (lispy_val, val);
125 return lispy_val;
128 /* Random data-structure functions */
130 DEFUN ("length", Flength, Slength, 1, 1, 0,
131 doc: /* Return the length of vector, list or string SEQUENCE.
132 A byte-code function object is also allowed.
133 If the string contains multibyte characters, this is not necessarily
134 the number of bytes in the string; it is the number of characters.
135 To get the number of bytes, use `string-bytes'. */)
136 (register Lisp_Object sequence)
138 register Lisp_Object val;
139 register int i;
141 if (STRINGP (sequence))
142 XSETFASTINT (val, SCHARS (sequence));
143 else if (VECTORP (sequence))
144 XSETFASTINT (val, ASIZE (sequence));
145 else if (CHAR_TABLE_P (sequence))
146 XSETFASTINT (val, MAX_CHAR);
147 else if (BOOL_VECTOR_P (sequence))
148 XSETFASTINT (val, XBOOL_VECTOR (sequence)->size);
149 else if (COMPILEDP (sequence))
150 XSETFASTINT (val, ASIZE (sequence) & PSEUDOVECTOR_SIZE_MASK);
151 else if (CONSP (sequence))
153 i = 0;
154 while (CONSP (sequence))
156 sequence = XCDR (sequence);
157 ++i;
159 if (!CONSP (sequence))
160 break;
162 sequence = XCDR (sequence);
163 ++i;
164 QUIT;
167 CHECK_LIST_END (sequence, sequence);
169 val = make_number (i);
171 else if (NILP (sequence))
172 XSETFASTINT (val, 0);
173 else
174 wrong_type_argument (Qsequencep, sequence);
176 return val;
179 /* This does not check for quits. That is safe since it must terminate. */
181 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
182 doc: /* Return the length of a list, but avoid error or infinite loop.
183 This function never gets an error. If LIST is not really a list,
184 it returns 0. If LIST is circular, it returns a finite value
185 which is at least the number of distinct elements. */)
186 (Lisp_Object list)
188 Lisp_Object tail, halftail, length;
189 int len = 0;
191 /* halftail is used to detect circular lists. */
192 halftail = list;
193 for (tail = list; CONSP (tail); tail = XCDR (tail))
195 if (EQ (tail, halftail) && len != 0)
196 break;
197 len++;
198 if ((len & 1) == 0)
199 halftail = XCDR (halftail);
202 XSETINT (length, len);
203 return length;
206 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
207 doc: /* Return the number of bytes in STRING.
208 If STRING is multibyte, this may be greater than the length of STRING. */)
209 (Lisp_Object string)
211 CHECK_STRING (string);
212 return make_number (SBYTES (string));
215 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
216 doc: /* Return t if two strings have identical contents.
217 Case is significant, but text properties are ignored.
218 Symbols are also allowed; their print names are used instead. */)
219 (register Lisp_Object s1, Lisp_Object s2)
221 if (SYMBOLP (s1))
222 s1 = SYMBOL_NAME (s1);
223 if (SYMBOLP (s2))
224 s2 = SYMBOL_NAME (s2);
225 CHECK_STRING (s1);
226 CHECK_STRING (s2);
228 if (SCHARS (s1) != SCHARS (s2)
229 || SBYTES (s1) != SBYTES (s2)
230 || memcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
231 return Qnil;
232 return Qt;
235 DEFUN ("compare-strings", Fcompare_strings,
236 Scompare_strings, 6, 7, 0,
237 doc: /* Compare the contents of two strings, converting to multibyte if needed.
238 In string STR1, skip the first START1 characters and stop at END1.
239 In string STR2, skip the first START2 characters and stop at END2.
240 END1 and END2 default to the full lengths of the respective strings.
242 Case is significant in this comparison if IGNORE-CASE is nil.
243 Unibyte strings are converted to multibyte for comparison.
245 The value is t if the strings (or specified portions) match.
246 If string STR1 is less, the value is a negative number N;
247 - 1 - N is the number of characters that match at the beginning.
248 If string STR1 is greater, the value is a positive number N;
249 N - 1 is the number of characters that match at the beginning. */)
250 (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2, Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
252 register int end1_char, end2_char;
253 register int i1, i1_byte, i2, i2_byte;
255 CHECK_STRING (str1);
256 CHECK_STRING (str2);
257 if (NILP (start1))
258 start1 = make_number (0);
259 if (NILP (start2))
260 start2 = make_number (0);
261 CHECK_NATNUM (start1);
262 CHECK_NATNUM (start2);
263 if (! NILP (end1))
264 CHECK_NATNUM (end1);
265 if (! NILP (end2))
266 CHECK_NATNUM (end2);
268 i1 = XINT (start1);
269 i2 = XINT (start2);
271 i1_byte = string_char_to_byte (str1, i1);
272 i2_byte = string_char_to_byte (str2, i2);
274 end1_char = SCHARS (str1);
275 if (! NILP (end1) && end1_char > XINT (end1))
276 end1_char = XINT (end1);
278 end2_char = SCHARS (str2);
279 if (! NILP (end2) && end2_char > XINT (end2))
280 end2_char = XINT (end2);
282 while (i1 < end1_char && i2 < end2_char)
284 /* When we find a mismatch, we must compare the
285 characters, not just the bytes. */
286 int c1, c2;
288 if (STRING_MULTIBYTE (str1))
289 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c1, str1, i1, i1_byte);
290 else
292 c1 = SREF (str1, i1++);
293 MAKE_CHAR_MULTIBYTE (c1);
296 if (STRING_MULTIBYTE (str2))
297 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c2, str2, i2, i2_byte);
298 else
300 c2 = SREF (str2, i2++);
301 MAKE_CHAR_MULTIBYTE (c2);
304 if (c1 == c2)
305 continue;
307 if (! NILP (ignore_case))
309 Lisp_Object tem;
311 tem = Fupcase (make_number (c1));
312 c1 = XINT (tem);
313 tem = Fupcase (make_number (c2));
314 c2 = XINT (tem);
317 if (c1 == c2)
318 continue;
320 /* Note that I1 has already been incremented
321 past the character that we are comparing;
322 hence we don't add or subtract 1 here. */
323 if (c1 < c2)
324 return make_number (- i1 + XINT (start1));
325 else
326 return make_number (i1 - XINT (start1));
329 if (i1 < end1_char)
330 return make_number (i1 - XINT (start1) + 1);
331 if (i2 < end2_char)
332 return make_number (- i1 + XINT (start1) - 1);
334 return Qt;
337 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
338 doc: /* Return t if first arg string is less than second in lexicographic order.
339 Case is significant.
340 Symbols are also allowed; their print names are used instead. */)
341 (register Lisp_Object s1, Lisp_Object s2)
343 register int end;
344 register int i1, i1_byte, i2, i2_byte;
346 if (SYMBOLP (s1))
347 s1 = SYMBOL_NAME (s1);
348 if (SYMBOLP (s2))
349 s2 = SYMBOL_NAME (s2);
350 CHECK_STRING (s1);
351 CHECK_STRING (s2);
353 i1 = i1_byte = i2 = i2_byte = 0;
355 end = SCHARS (s1);
356 if (end > SCHARS (s2))
357 end = SCHARS (s2);
359 while (i1 < end)
361 /* When we find a mismatch, we must compare the
362 characters, not just the bytes. */
363 int c1, c2;
365 FETCH_STRING_CHAR_ADVANCE (c1, s1, i1, i1_byte);
366 FETCH_STRING_CHAR_ADVANCE (c2, s2, i2, i2_byte);
368 if (c1 != c2)
369 return c1 < c2 ? Qt : Qnil;
371 return i1 < SCHARS (s2) ? Qt : Qnil;
374 #if __GNUC__
375 /* "gcc -O3" enables automatic function inlining, which optimizes out
376 the arguments for the invocations of this function, whereas it
377 expects these values on the stack. */
378 static Lisp_Object concat (int nargs, Lisp_Object *args, enum Lisp_Type target_type, int last_special) __attribute__((noinline));
379 #else /* !__GNUC__ */
380 static Lisp_Object concat (int nargs, Lisp_Object *args, enum Lisp_Type target_type, int last_special);
381 #endif
383 /* ARGSUSED */
384 Lisp_Object
385 concat2 (Lisp_Object s1, Lisp_Object s2)
387 Lisp_Object args[2];
388 args[0] = s1;
389 args[1] = s2;
390 return concat (2, args, Lisp_String, 0);
393 /* ARGSUSED */
394 Lisp_Object
395 concat3 (Lisp_Object s1, Lisp_Object s2, Lisp_Object s3)
397 Lisp_Object args[3];
398 args[0] = s1;
399 args[1] = s2;
400 args[2] = s3;
401 return concat (3, args, Lisp_String, 0);
404 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
405 doc: /* Concatenate all the arguments and make the result a list.
406 The result is a list whose elements are the elements of all the arguments.
407 Each argument may be a list, vector or string.
408 The last argument is not copied, just used as the tail of the new list.
409 usage: (append &rest SEQUENCES) */)
410 (int nargs, Lisp_Object *args)
412 return concat (nargs, args, Lisp_Cons, 1);
415 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
416 doc: /* Concatenate all the arguments and make the result a string.
417 The result is a string whose elements are the elements of all the arguments.
418 Each argument may be a string or a list or vector of characters (integers).
419 usage: (concat &rest SEQUENCES) */)
420 (int nargs, Lisp_Object *args)
422 return concat (nargs, args, Lisp_String, 0);
425 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
426 doc: /* Concatenate all the arguments and make the result a vector.
427 The result is a vector whose elements are the elements of all the arguments.
428 Each argument may be a list, vector or string.
429 usage: (vconcat &rest SEQUENCES) */)
430 (int nargs, Lisp_Object *args)
432 return concat (nargs, args, Lisp_Vectorlike, 0);
436 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
437 doc: /* Return a copy of a list, vector, string or char-table.
438 The elements of a list or vector are not copied; they are shared
439 with the original. */)
440 (Lisp_Object arg)
442 if (NILP (arg)) return arg;
444 if (CHAR_TABLE_P (arg))
446 return copy_char_table (arg);
449 if (BOOL_VECTOR_P (arg))
451 Lisp_Object val;
452 int size_in_chars
453 = ((XBOOL_VECTOR (arg)->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
454 / BOOL_VECTOR_BITS_PER_CHAR);
456 val = Fmake_bool_vector (Flength (arg), Qnil);
457 memcpy (XBOOL_VECTOR (val)->data, XBOOL_VECTOR (arg)->data,
458 size_in_chars);
459 return val;
462 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
463 wrong_type_argument (Qsequencep, arg);
465 return concat (1, &arg, CONSP (arg) ? Lisp_Cons : XTYPE (arg), 0);
468 /* This structure holds information of an argument of `concat' that is
469 a string and has text properties to be copied. */
470 struct textprop_rec
472 int argnum; /* refer to ARGS (arguments of `concat') */
473 int from; /* refer to ARGS[argnum] (argument string) */
474 int to; /* refer to VAL (the target string) */
477 static Lisp_Object
478 concat (int nargs, Lisp_Object *args, enum Lisp_Type target_type, int last_special)
480 Lisp_Object val;
481 register Lisp_Object tail;
482 register Lisp_Object this;
483 int toindex;
484 int toindex_byte = 0;
485 register int result_len;
486 register int result_len_byte;
487 register int argnum;
488 Lisp_Object last_tail;
489 Lisp_Object prev;
490 int some_multibyte;
491 /* When we make a multibyte string, we can't copy text properties
492 while concatinating each string because the length of resulting
493 string can't be decided until we finish the whole concatination.
494 So, we record strings that have text properties to be copied
495 here, and copy the text properties after the concatination. */
496 struct textprop_rec *textprops = NULL;
497 /* Number of elements in textprops. */
498 int num_textprops = 0;
499 USE_SAFE_ALLOCA;
501 tail = Qnil;
503 /* In append, the last arg isn't treated like the others */
504 if (last_special && nargs > 0)
506 nargs--;
507 last_tail = args[nargs];
509 else
510 last_tail = Qnil;
512 /* Check each argument. */
513 for (argnum = 0; argnum < nargs; argnum++)
515 this = args[argnum];
516 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
517 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
518 wrong_type_argument (Qsequencep, this);
521 /* Compute total length in chars of arguments in RESULT_LEN.
522 If desired output is a string, also compute length in bytes
523 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
524 whether the result should be a multibyte string. */
525 result_len_byte = 0;
526 result_len = 0;
527 some_multibyte = 0;
528 for (argnum = 0; argnum < nargs; argnum++)
530 int len;
531 this = args[argnum];
532 len = XFASTINT (Flength (this));
533 if (target_type == Lisp_String)
535 /* We must count the number of bytes needed in the string
536 as well as the number of characters. */
537 int i;
538 Lisp_Object ch;
539 int this_len_byte;
541 if (VECTORP (this))
542 for (i = 0; i < len; i++)
544 ch = AREF (this, i);
545 CHECK_CHARACTER (ch);
546 this_len_byte = CHAR_BYTES (XINT (ch));
547 result_len_byte += this_len_byte;
548 if (! ASCII_CHAR_P (XINT (ch)) && ! CHAR_BYTE8_P (XINT (ch)))
549 some_multibyte = 1;
551 else if (BOOL_VECTOR_P (this) && XBOOL_VECTOR (this)->size > 0)
552 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
553 else if (CONSP (this))
554 for (; CONSP (this); this = XCDR (this))
556 ch = XCAR (this);
557 CHECK_CHARACTER (ch);
558 this_len_byte = CHAR_BYTES (XINT (ch));
559 result_len_byte += this_len_byte;
560 if (! ASCII_CHAR_P (XINT (ch)) && ! CHAR_BYTE8_P (XINT (ch)))
561 some_multibyte = 1;
563 else if (STRINGP (this))
565 if (STRING_MULTIBYTE (this))
567 some_multibyte = 1;
568 result_len_byte += SBYTES (this);
570 else
571 result_len_byte += count_size_as_multibyte (SDATA (this),
572 SCHARS (this));
576 result_len += len;
577 if (result_len < 0)
578 error ("String overflow");
581 if (! some_multibyte)
582 result_len_byte = result_len;
584 /* Create the output object. */
585 if (target_type == Lisp_Cons)
586 val = Fmake_list (make_number (result_len), Qnil);
587 else if (target_type == Lisp_Vectorlike)
588 val = Fmake_vector (make_number (result_len), Qnil);
589 else if (some_multibyte)
590 val = make_uninit_multibyte_string (result_len, result_len_byte);
591 else
592 val = make_uninit_string (result_len);
594 /* In `append', if all but last arg are nil, return last arg. */
595 if (target_type == Lisp_Cons && EQ (val, Qnil))
596 return last_tail;
598 /* Copy the contents of the args into the result. */
599 if (CONSP (val))
600 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
601 else
602 toindex = 0, toindex_byte = 0;
604 prev = Qnil;
605 if (STRINGP (val))
606 SAFE_ALLOCA (textprops, struct textprop_rec *, sizeof (struct textprop_rec) * nargs);
608 for (argnum = 0; argnum < nargs; argnum++)
610 Lisp_Object thislen;
611 int thisleni = 0;
612 register unsigned int thisindex = 0;
613 register unsigned int thisindex_byte = 0;
615 this = args[argnum];
616 if (!CONSP (this))
617 thislen = Flength (this), thisleni = XINT (thislen);
619 /* Between strings of the same kind, copy fast. */
620 if (STRINGP (this) && STRINGP (val)
621 && STRING_MULTIBYTE (this) == some_multibyte)
623 int thislen_byte = SBYTES (this);
625 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
626 if (! NULL_INTERVAL_P (STRING_INTERVALS (this)))
628 textprops[num_textprops].argnum = argnum;
629 textprops[num_textprops].from = 0;
630 textprops[num_textprops++].to = toindex;
632 toindex_byte += thislen_byte;
633 toindex += thisleni;
635 /* Copy a single-byte string to a multibyte string. */
636 else if (STRINGP (this) && STRINGP (val))
638 if (! NULL_INTERVAL_P (STRING_INTERVALS (this)))
640 textprops[num_textprops].argnum = argnum;
641 textprops[num_textprops].from = 0;
642 textprops[num_textprops++].to = toindex;
644 toindex_byte += copy_text (SDATA (this),
645 SDATA (val) + toindex_byte,
646 SCHARS (this), 0, 1);
647 toindex += thisleni;
649 else
650 /* Copy element by element. */
651 while (1)
653 register Lisp_Object elt;
655 /* Fetch next element of `this' arg into `elt', or break if
656 `this' is exhausted. */
657 if (NILP (this)) break;
658 if (CONSP (this))
659 elt = XCAR (this), this = XCDR (this);
660 else if (thisindex >= thisleni)
661 break;
662 else if (STRINGP (this))
664 int c;
665 if (STRING_MULTIBYTE (this))
667 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
668 thisindex,
669 thisindex_byte);
670 XSETFASTINT (elt, c);
672 else
674 XSETFASTINT (elt, SREF (this, thisindex)); thisindex++;
675 if (some_multibyte
676 && !ASCII_CHAR_P (XINT (elt))
677 && XINT (elt) < 0400)
679 c = BYTE8_TO_CHAR (XINT (elt));
680 XSETINT (elt, c);
684 else if (BOOL_VECTOR_P (this))
686 int byte;
687 byte = XBOOL_VECTOR (this)->data[thisindex / BOOL_VECTOR_BITS_PER_CHAR];
688 if (byte & (1 << (thisindex % BOOL_VECTOR_BITS_PER_CHAR)))
689 elt = Qt;
690 else
691 elt = Qnil;
692 thisindex++;
694 else
696 elt = AREF (this, thisindex);
697 thisindex++;
700 /* Store this element into the result. */
701 if (toindex < 0)
703 XSETCAR (tail, elt);
704 prev = tail;
705 tail = XCDR (tail);
707 else if (VECTORP (val))
709 ASET (val, toindex, elt);
710 toindex++;
712 else
714 CHECK_NUMBER (elt);
715 if (some_multibyte)
716 toindex_byte += CHAR_STRING (XINT (elt),
717 SDATA (val) + toindex_byte);
718 else
719 SSET (val, toindex_byte++, XINT (elt));
720 toindex++;
724 if (!NILP (prev))
725 XSETCDR (prev, last_tail);
727 if (num_textprops > 0)
729 Lisp_Object props;
730 int last_to_end = -1;
732 for (argnum = 0; argnum < num_textprops; argnum++)
734 this = args[textprops[argnum].argnum];
735 props = text_property_list (this,
736 make_number (0),
737 make_number (SCHARS (this)),
738 Qnil);
739 /* If successive arguments have properites, be sure that the
740 value of `composition' property be the copy. */
741 if (last_to_end == textprops[argnum].to)
742 make_composition_value_copy (props);
743 add_text_properties_from_list (val, props,
744 make_number (textprops[argnum].to));
745 last_to_end = textprops[argnum].to + SCHARS (this);
749 SAFE_FREE ();
750 return val;
753 static Lisp_Object string_char_byte_cache_string;
754 static EMACS_INT string_char_byte_cache_charpos;
755 static EMACS_INT string_char_byte_cache_bytepos;
757 void
758 clear_string_char_byte_cache (void)
760 string_char_byte_cache_string = Qnil;
763 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
765 EMACS_INT
766 string_char_to_byte (Lisp_Object string, EMACS_INT char_index)
768 EMACS_INT i_byte;
769 EMACS_INT best_below, best_below_byte;
770 EMACS_INT best_above, best_above_byte;
772 best_below = best_below_byte = 0;
773 best_above = SCHARS (string);
774 best_above_byte = SBYTES (string);
775 if (best_above == best_above_byte)
776 return char_index;
778 if (EQ (string, string_char_byte_cache_string))
780 if (string_char_byte_cache_charpos < char_index)
782 best_below = string_char_byte_cache_charpos;
783 best_below_byte = string_char_byte_cache_bytepos;
785 else
787 best_above = string_char_byte_cache_charpos;
788 best_above_byte = string_char_byte_cache_bytepos;
792 if (char_index - best_below < best_above - char_index)
794 unsigned char *p = SDATA (string) + best_below_byte;
796 while (best_below < char_index)
798 p += BYTES_BY_CHAR_HEAD (*p);
799 best_below++;
801 i_byte = p - SDATA (string);
803 else
805 unsigned char *p = SDATA (string) + best_above_byte;
807 while (best_above > char_index)
809 p--;
810 while (!CHAR_HEAD_P (*p)) p--;
811 best_above--;
813 i_byte = p - SDATA (string);
816 string_char_byte_cache_bytepos = i_byte;
817 string_char_byte_cache_charpos = char_index;
818 string_char_byte_cache_string = string;
820 return i_byte;
823 /* Return the character index corresponding to BYTE_INDEX in STRING. */
825 EMACS_INT
826 string_byte_to_char (Lisp_Object string, EMACS_INT byte_index)
828 EMACS_INT i, i_byte;
829 EMACS_INT best_below, best_below_byte;
830 EMACS_INT best_above, best_above_byte;
832 best_below = best_below_byte = 0;
833 best_above = SCHARS (string);
834 best_above_byte = SBYTES (string);
835 if (best_above == best_above_byte)
836 return byte_index;
838 if (EQ (string, string_char_byte_cache_string))
840 if (string_char_byte_cache_bytepos < byte_index)
842 best_below = string_char_byte_cache_charpos;
843 best_below_byte = string_char_byte_cache_bytepos;
845 else
847 best_above = string_char_byte_cache_charpos;
848 best_above_byte = string_char_byte_cache_bytepos;
852 if (byte_index - best_below_byte < best_above_byte - byte_index)
854 unsigned char *p = SDATA (string) + best_below_byte;
855 unsigned char *pend = SDATA (string) + byte_index;
857 while (p < pend)
859 p += BYTES_BY_CHAR_HEAD (*p);
860 best_below++;
862 i = best_below;
863 i_byte = p - SDATA (string);
865 else
867 unsigned char *p = SDATA (string) + best_above_byte;
868 unsigned char *pbeg = SDATA (string) + byte_index;
870 while (p > pbeg)
872 p--;
873 while (!CHAR_HEAD_P (*p)) p--;
874 best_above--;
876 i = best_above;
877 i_byte = p - SDATA (string);
880 string_char_byte_cache_bytepos = i_byte;
881 string_char_byte_cache_charpos = i;
882 string_char_byte_cache_string = string;
884 return i;
887 /* Convert STRING to a multibyte string. */
889 Lisp_Object
890 string_make_multibyte (Lisp_Object string)
892 unsigned char *buf;
893 EMACS_INT nbytes;
894 Lisp_Object ret;
895 USE_SAFE_ALLOCA;
897 if (STRING_MULTIBYTE (string))
898 return string;
900 nbytes = count_size_as_multibyte (SDATA (string),
901 SCHARS (string));
902 /* If all the chars are ASCII, they won't need any more bytes
903 once converted. In that case, we can return STRING itself. */
904 if (nbytes == SBYTES (string))
905 return string;
907 SAFE_ALLOCA (buf, unsigned char *, nbytes);
908 copy_text (SDATA (string), buf, SBYTES (string),
909 0, 1);
911 ret = make_multibyte_string (buf, SCHARS (string), nbytes);
912 SAFE_FREE ();
914 return ret;
918 /* Convert STRING (if unibyte) to a multibyte string without changing
919 the number of characters. Characters 0200 trough 0237 are
920 converted to eight-bit characters. */
922 Lisp_Object
923 string_to_multibyte (Lisp_Object string)
925 unsigned char *buf;
926 EMACS_INT nbytes;
927 Lisp_Object ret;
928 USE_SAFE_ALLOCA;
930 if (STRING_MULTIBYTE (string))
931 return string;
933 nbytes = parse_str_to_multibyte (SDATA (string), SBYTES (string));
934 /* If all the chars are ASCII, they won't need any more bytes once
935 converted. */
936 if (nbytes == SBYTES (string))
937 return make_multibyte_string (SDATA (string), nbytes, nbytes);
939 SAFE_ALLOCA (buf, unsigned char *, nbytes);
940 memcpy (buf, SDATA (string), SBYTES (string));
941 str_to_multibyte (buf, nbytes, SBYTES (string));
943 ret = make_multibyte_string (buf, SCHARS (string), nbytes);
944 SAFE_FREE ();
946 return ret;
950 /* Convert STRING to a single-byte string. */
952 Lisp_Object
953 string_make_unibyte (Lisp_Object string)
955 int nchars;
956 unsigned char *buf;
957 Lisp_Object ret;
958 USE_SAFE_ALLOCA;
960 if (! STRING_MULTIBYTE (string))
961 return string;
963 nchars = SCHARS (string);
965 SAFE_ALLOCA (buf, unsigned char *, nchars);
966 copy_text (SDATA (string), buf, SBYTES (string),
967 1, 0);
969 ret = make_unibyte_string (buf, nchars);
970 SAFE_FREE ();
972 return ret;
975 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
976 1, 1, 0,
977 doc: /* Return the multibyte equivalent of STRING.
978 If STRING is unibyte and contains non-ASCII characters, the function
979 `unibyte-char-to-multibyte' is used to convert each unibyte character
980 to a multibyte character. In this case, the returned string is a
981 newly created string with no text properties. If STRING is multibyte
982 or entirely ASCII, it is returned unchanged. In particular, when
983 STRING is unibyte and entirely ASCII, the returned string is unibyte.
984 \(When the characters are all ASCII, Emacs primitives will treat the
985 string the same way whether it is unibyte or multibyte.) */)
986 (Lisp_Object string)
988 CHECK_STRING (string);
990 return string_make_multibyte (string);
993 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
994 1, 1, 0,
995 doc: /* Return the unibyte equivalent of STRING.
996 Multibyte character codes are converted to unibyte according to
997 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
998 If the lookup in the translation table fails, this function takes just
999 the low 8 bits of each character. */)
1000 (Lisp_Object string)
1002 CHECK_STRING (string);
1004 return string_make_unibyte (string);
1007 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
1008 1, 1, 0,
1009 doc: /* Return a unibyte string with the same individual bytes as STRING.
1010 If STRING is unibyte, the result is STRING itself.
1011 Otherwise it is a newly created string, with no text properties.
1012 If STRING is multibyte and contains a character of charset
1013 `eight-bit', it is converted to the corresponding single byte. */)
1014 (Lisp_Object string)
1016 CHECK_STRING (string);
1018 if (STRING_MULTIBYTE (string))
1020 int bytes = SBYTES (string);
1021 unsigned char *str = (unsigned char *) xmalloc (bytes);
1023 memcpy (str, SDATA (string), bytes);
1024 bytes = str_as_unibyte (str, bytes);
1025 string = make_unibyte_string (str, bytes);
1026 xfree (str);
1028 return string;
1031 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1032 1, 1, 0,
1033 doc: /* Return a multibyte string with the same individual bytes as STRING.
1034 If STRING is multibyte, the result is STRING itself.
1035 Otherwise it is a newly created string, with no text properties.
1037 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1038 part of a correct utf-8 sequence), it is converted to the corresponding
1039 multibyte character of charset `eight-bit'.
1040 See also `string-to-multibyte'.
1042 Beware, this often doesn't really do what you think it does.
1043 It is similar to (decode-coding-string STRING 'utf-8-emacs).
1044 If you're not sure, whether to use `string-as-multibyte' or
1045 `string-to-multibyte', use `string-to-multibyte'. */)
1046 (Lisp_Object string)
1048 CHECK_STRING (string);
1050 if (! STRING_MULTIBYTE (string))
1052 Lisp_Object new_string;
1053 int nchars, nbytes;
1055 parse_str_as_multibyte (SDATA (string),
1056 SBYTES (string),
1057 &nchars, &nbytes);
1058 new_string = make_uninit_multibyte_string (nchars, nbytes);
1059 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1060 if (nbytes != SBYTES (string))
1061 str_as_multibyte (SDATA (new_string), nbytes,
1062 SBYTES (string), NULL);
1063 string = new_string;
1064 STRING_SET_INTERVALS (string, NULL_INTERVAL);
1066 return string;
1069 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1070 1, 1, 0,
1071 doc: /* Return a multibyte string with the same individual chars as STRING.
1072 If STRING is multibyte, the result is STRING itself.
1073 Otherwise it is a newly created string, with no text properties.
1075 If STRING is unibyte and contains an 8-bit byte, it is converted to
1076 the corresponding multibyte character of charset `eight-bit'.
1078 This differs from `string-as-multibyte' by converting each byte of a correct
1079 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1080 correct sequence. */)
1081 (Lisp_Object string)
1083 CHECK_STRING (string);
1085 return string_to_multibyte (string);
1088 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1089 1, 1, 0,
1090 doc: /* Return a unibyte string with the same individual chars as STRING.
1091 If STRING is unibyte, the result is STRING itself.
1092 Otherwise it is a newly created string, with no text properties,
1093 where each `eight-bit' character is converted to the corresponding byte.
1094 If STRING contains a non-ASCII, non-`eight-bit' character,
1095 an error is signaled. */)
1096 (Lisp_Object string)
1098 CHECK_STRING (string);
1100 if (STRING_MULTIBYTE (string))
1102 EMACS_INT chars = SCHARS (string);
1103 unsigned char *str = (unsigned char *) xmalloc (chars);
1104 EMACS_INT converted = str_to_unibyte (SDATA (string), str, chars, 0);
1106 if (converted < chars)
1107 error ("Can't convert the %dth character to unibyte", converted);
1108 string = make_unibyte_string (str, chars);
1109 xfree (str);
1111 return string;
1115 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1116 doc: /* Return a copy of ALIST.
1117 This is an alist which represents the same mapping from objects to objects,
1118 but does not share the alist structure with ALIST.
1119 The objects mapped (cars and cdrs of elements of the alist)
1120 are shared, however.
1121 Elements of ALIST that are not conses are also shared. */)
1122 (Lisp_Object alist)
1124 register Lisp_Object tem;
1126 CHECK_LIST (alist);
1127 if (NILP (alist))
1128 return alist;
1129 alist = concat (1, &alist, Lisp_Cons, 0);
1130 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1132 register Lisp_Object car;
1133 car = XCAR (tem);
1135 if (CONSP (car))
1136 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1138 return alist;
1141 DEFUN ("substring", Fsubstring, Ssubstring, 2, 3, 0,
1142 doc: /* Return a new string whose contents are a substring of STRING.
1143 The returned string consists of the characters between index FROM
1144 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1145 zero-indexed: 0 means the first character of STRING. Negative values
1146 are counted from the end of STRING. If TO is nil, the substring runs
1147 to the end of STRING.
1149 The STRING argument may also be a vector. In that case, the return
1150 value is a new vector that contains the elements between index FROM
1151 \(inclusive) and index TO (exclusive) of that vector argument. */)
1152 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1154 Lisp_Object res;
1155 int size;
1156 int size_byte = 0;
1157 int from_char, to_char;
1158 int from_byte = 0, to_byte = 0;
1160 CHECK_VECTOR_OR_STRING (string);
1161 CHECK_NUMBER (from);
1163 if (STRINGP (string))
1165 size = SCHARS (string);
1166 size_byte = SBYTES (string);
1168 else
1169 size = ASIZE (string);
1171 if (NILP (to))
1173 to_char = size;
1174 to_byte = size_byte;
1176 else
1178 CHECK_NUMBER (to);
1180 to_char = XINT (to);
1181 if (to_char < 0)
1182 to_char += size;
1184 if (STRINGP (string))
1185 to_byte = string_char_to_byte (string, to_char);
1188 from_char = XINT (from);
1189 if (from_char < 0)
1190 from_char += size;
1191 if (STRINGP (string))
1192 from_byte = string_char_to_byte (string, from_char);
1194 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1195 args_out_of_range_3 (string, make_number (from_char),
1196 make_number (to_char));
1198 if (STRINGP (string))
1200 res = make_specified_string (SDATA (string) + from_byte,
1201 to_char - from_char, to_byte - from_byte,
1202 STRING_MULTIBYTE (string));
1203 copy_text_properties (make_number (from_char), make_number (to_char),
1204 string, make_number (0), res, Qnil);
1206 else
1207 res = Fvector (to_char - from_char, &AREF (string, from_char));
1209 return res;
1213 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1214 doc: /* Return a substring of STRING, without text properties.
1215 It starts at index FROM and ending before TO.
1216 TO may be nil or omitted; then the substring runs to the end of STRING.
1217 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1218 If FROM or TO is negative, it counts from the end.
1220 With one argument, just copy STRING without its properties. */)
1221 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1223 int size, size_byte;
1224 int from_char, to_char;
1225 int from_byte, to_byte;
1227 CHECK_STRING (string);
1229 size = SCHARS (string);
1230 size_byte = SBYTES (string);
1232 if (NILP (from))
1233 from_char = from_byte = 0;
1234 else
1236 CHECK_NUMBER (from);
1237 from_char = XINT (from);
1238 if (from_char < 0)
1239 from_char += size;
1241 from_byte = string_char_to_byte (string, from_char);
1244 if (NILP (to))
1246 to_char = size;
1247 to_byte = size_byte;
1249 else
1251 CHECK_NUMBER (to);
1253 to_char = XINT (to);
1254 if (to_char < 0)
1255 to_char += size;
1257 to_byte = string_char_to_byte (string, to_char);
1260 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1261 args_out_of_range_3 (string, make_number (from_char),
1262 make_number (to_char));
1264 return make_specified_string (SDATA (string) + from_byte,
1265 to_char - from_char, to_byte - from_byte,
1266 STRING_MULTIBYTE (string));
1269 /* Extract a substring of STRING, giving start and end positions
1270 both in characters and in bytes. */
1272 Lisp_Object
1273 substring_both (Lisp_Object string, int from, int from_byte, int to, int to_byte)
1275 Lisp_Object res;
1276 int size;
1277 int size_byte;
1279 CHECK_VECTOR_OR_STRING (string);
1281 if (STRINGP (string))
1283 size = SCHARS (string);
1284 size_byte = SBYTES (string);
1286 else
1287 size = ASIZE (string);
1289 if (!(0 <= from && from <= to && to <= size))
1290 args_out_of_range_3 (string, make_number (from), make_number (to));
1292 if (STRINGP (string))
1294 res = make_specified_string (SDATA (string) + from_byte,
1295 to - from, to_byte - from_byte,
1296 STRING_MULTIBYTE (string));
1297 copy_text_properties (make_number (from), make_number (to),
1298 string, make_number (0), res, Qnil);
1300 else
1301 res = Fvector (to - from, &AREF (string, from));
1303 return res;
1306 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1307 doc: /* Take cdr N times on LIST, returns the result. */)
1308 (Lisp_Object n, Lisp_Object list)
1310 register int i, num;
1311 CHECK_NUMBER (n);
1312 num = XINT (n);
1313 for (i = 0; i < num && !NILP (list); i++)
1315 QUIT;
1316 CHECK_LIST_CONS (list, list);
1317 list = XCDR (list);
1319 return list;
1322 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1323 doc: /* Return the Nth element of LIST.
1324 N counts from zero. If LIST is not that long, nil is returned. */)
1325 (Lisp_Object n, Lisp_Object list)
1327 return Fcar (Fnthcdr (n, list));
1330 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1331 doc: /* Return element of SEQUENCE at index N. */)
1332 (register Lisp_Object sequence, Lisp_Object n)
1334 CHECK_NUMBER (n);
1335 if (CONSP (sequence) || NILP (sequence))
1336 return Fcar (Fnthcdr (n, sequence));
1338 /* Faref signals a "not array" error, so check here. */
1339 CHECK_ARRAY (sequence, Qsequencep);
1340 return Faref (sequence, n);
1343 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1344 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1345 The value is actually the tail of LIST whose car is ELT. */)
1346 (register Lisp_Object elt, Lisp_Object list)
1348 register Lisp_Object tail;
1349 for (tail = list; CONSP (tail); tail = XCDR (tail))
1351 register Lisp_Object tem;
1352 CHECK_LIST_CONS (tail, list);
1353 tem = XCAR (tail);
1354 if (! NILP (Fequal (elt, tem)))
1355 return tail;
1356 QUIT;
1358 return Qnil;
1361 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1362 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1363 The value is actually the tail of LIST whose car is ELT. */)
1364 (register Lisp_Object elt, Lisp_Object list)
1366 while (1)
1368 if (!CONSP (list) || EQ (XCAR (list), elt))
1369 break;
1371 list = XCDR (list);
1372 if (!CONSP (list) || EQ (XCAR (list), elt))
1373 break;
1375 list = XCDR (list);
1376 if (!CONSP (list) || EQ (XCAR (list), elt))
1377 break;
1379 list = XCDR (list);
1380 QUIT;
1383 CHECK_LIST (list);
1384 return list;
1387 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1388 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1389 The value is actually the tail of LIST whose car is ELT. */)
1390 (register Lisp_Object elt, Lisp_Object list)
1392 register Lisp_Object tail;
1394 if (!FLOATP (elt))
1395 return Fmemq (elt, list);
1397 for (tail = list; CONSP (tail); tail = XCDR (tail))
1399 register Lisp_Object tem;
1400 CHECK_LIST_CONS (tail, list);
1401 tem = XCAR (tail);
1402 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0))
1403 return tail;
1404 QUIT;
1406 return Qnil;
1409 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1410 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1411 The value is actually the first element of LIST whose car is KEY.
1412 Elements of LIST that are not conses are ignored. */)
1413 (Lisp_Object key, Lisp_Object list)
1415 while (1)
1417 if (!CONSP (list)
1418 || (CONSP (XCAR (list))
1419 && EQ (XCAR (XCAR (list)), key)))
1420 break;
1422 list = XCDR (list);
1423 if (!CONSP (list)
1424 || (CONSP (XCAR (list))
1425 && EQ (XCAR (XCAR (list)), key)))
1426 break;
1428 list = XCDR (list);
1429 if (!CONSP (list)
1430 || (CONSP (XCAR (list))
1431 && EQ (XCAR (XCAR (list)), key)))
1432 break;
1434 list = XCDR (list);
1435 QUIT;
1438 return CAR (list);
1441 /* Like Fassq but never report an error and do not allow quits.
1442 Use only on lists known never to be circular. */
1444 Lisp_Object
1445 assq_no_quit (Lisp_Object key, Lisp_Object list)
1447 while (CONSP (list)
1448 && (!CONSP (XCAR (list))
1449 || !EQ (XCAR (XCAR (list)), key)))
1450 list = XCDR (list);
1452 return CAR_SAFE (list);
1455 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1456 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1457 The value is actually the first element of LIST whose car equals KEY. */)
1458 (Lisp_Object key, Lisp_Object list)
1460 Lisp_Object car;
1462 while (1)
1464 if (!CONSP (list)
1465 || (CONSP (XCAR (list))
1466 && (car = XCAR (XCAR (list)),
1467 EQ (car, key) || !NILP (Fequal (car, key)))))
1468 break;
1470 list = XCDR (list);
1471 if (!CONSP (list)
1472 || (CONSP (XCAR (list))
1473 && (car = XCAR (XCAR (list)),
1474 EQ (car, key) || !NILP (Fequal (car, key)))))
1475 break;
1477 list = XCDR (list);
1478 if (!CONSP (list)
1479 || (CONSP (XCAR (list))
1480 && (car = XCAR (XCAR (list)),
1481 EQ (car, key) || !NILP (Fequal (car, key)))))
1482 break;
1484 list = XCDR (list);
1485 QUIT;
1488 return CAR (list);
1491 /* Like Fassoc but never report an error and do not allow quits.
1492 Use only on lists known never to be circular. */
1494 Lisp_Object
1495 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1497 while (CONSP (list)
1498 && (!CONSP (XCAR (list))
1499 || (!EQ (XCAR (XCAR (list)), key)
1500 && NILP (Fequal (XCAR (XCAR (list)), key)))))
1501 list = XCDR (list);
1503 return CONSP (list) ? XCAR (list) : Qnil;
1506 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1507 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1508 The value is actually the first element of LIST whose cdr is KEY. */)
1509 (register Lisp_Object key, Lisp_Object list)
1511 while (1)
1513 if (!CONSP (list)
1514 || (CONSP (XCAR (list))
1515 && EQ (XCDR (XCAR (list)), key)))
1516 break;
1518 list = XCDR (list);
1519 if (!CONSP (list)
1520 || (CONSP (XCAR (list))
1521 && EQ (XCDR (XCAR (list)), key)))
1522 break;
1524 list = XCDR (list);
1525 if (!CONSP (list)
1526 || (CONSP (XCAR (list))
1527 && EQ (XCDR (XCAR (list)), key)))
1528 break;
1530 list = XCDR (list);
1531 QUIT;
1534 return CAR (list);
1537 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1538 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1539 The value is actually the first element of LIST whose cdr equals KEY. */)
1540 (Lisp_Object key, Lisp_Object list)
1542 Lisp_Object cdr;
1544 while (1)
1546 if (!CONSP (list)
1547 || (CONSP (XCAR (list))
1548 && (cdr = XCDR (XCAR (list)),
1549 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1550 break;
1552 list = XCDR (list);
1553 if (!CONSP (list)
1554 || (CONSP (XCAR (list))
1555 && (cdr = XCDR (XCAR (list)),
1556 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1557 break;
1559 list = XCDR (list);
1560 if (!CONSP (list)
1561 || (CONSP (XCAR (list))
1562 && (cdr = XCDR (XCAR (list)),
1563 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1564 break;
1566 list = XCDR (list);
1567 QUIT;
1570 return CAR (list);
1573 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1574 doc: /* Delete by side effect any occurrences of ELT as a member of LIST.
1575 The modified LIST is returned. Comparison is done with `eq'.
1576 If the first member of LIST is ELT, there is no way to remove it by side effect;
1577 therefore, write `(setq foo (delq element foo))'
1578 to be sure of changing the value of `foo'. */)
1579 (register Lisp_Object elt, Lisp_Object list)
1581 register Lisp_Object tail, prev;
1582 register Lisp_Object tem;
1584 tail = list;
1585 prev = Qnil;
1586 while (!NILP (tail))
1588 CHECK_LIST_CONS (tail, list);
1589 tem = XCAR (tail);
1590 if (EQ (elt, tem))
1592 if (NILP (prev))
1593 list = XCDR (tail);
1594 else
1595 Fsetcdr (prev, XCDR (tail));
1597 else
1598 prev = tail;
1599 tail = XCDR (tail);
1600 QUIT;
1602 return list;
1605 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1606 doc: /* Delete by side effect any occurrences of ELT as a member of SEQ.
1607 SEQ must be a list, a vector, or a string.
1608 The modified SEQ is returned. Comparison is done with `equal'.
1609 If SEQ is not a list, or the first member of SEQ is ELT, deleting it
1610 is not a side effect; it is simply using a different sequence.
1611 Therefore, write `(setq foo (delete element foo))'
1612 to be sure of changing the value of `foo'. */)
1613 (Lisp_Object elt, Lisp_Object seq)
1615 if (VECTORP (seq))
1617 EMACS_INT i, n;
1619 for (i = n = 0; i < ASIZE (seq); ++i)
1620 if (NILP (Fequal (AREF (seq, i), elt)))
1621 ++n;
1623 if (n != ASIZE (seq))
1625 struct Lisp_Vector *p = allocate_vector (n);
1627 for (i = n = 0; i < ASIZE (seq); ++i)
1628 if (NILP (Fequal (AREF (seq, i), elt)))
1629 p->contents[n++] = AREF (seq, i);
1631 XSETVECTOR (seq, p);
1634 else if (STRINGP (seq))
1636 EMACS_INT i, ibyte, nchars, nbytes, cbytes;
1637 int c;
1639 for (i = nchars = nbytes = ibyte = 0;
1640 i < SCHARS (seq);
1641 ++i, ibyte += cbytes)
1643 if (STRING_MULTIBYTE (seq))
1645 c = STRING_CHAR (SDATA (seq) + ibyte);
1646 cbytes = CHAR_BYTES (c);
1648 else
1650 c = SREF (seq, i);
1651 cbytes = 1;
1654 if (!INTEGERP (elt) || c != XINT (elt))
1656 ++nchars;
1657 nbytes += cbytes;
1661 if (nchars != SCHARS (seq))
1663 Lisp_Object tem;
1665 tem = make_uninit_multibyte_string (nchars, nbytes);
1666 if (!STRING_MULTIBYTE (seq))
1667 STRING_SET_UNIBYTE (tem);
1669 for (i = nchars = nbytes = ibyte = 0;
1670 i < SCHARS (seq);
1671 ++i, ibyte += cbytes)
1673 if (STRING_MULTIBYTE (seq))
1675 c = STRING_CHAR (SDATA (seq) + ibyte);
1676 cbytes = CHAR_BYTES (c);
1678 else
1680 c = SREF (seq, i);
1681 cbytes = 1;
1684 if (!INTEGERP (elt) || c != XINT (elt))
1686 unsigned char *from = SDATA (seq) + ibyte;
1687 unsigned char *to = SDATA (tem) + nbytes;
1688 EMACS_INT n;
1690 ++nchars;
1691 nbytes += cbytes;
1693 for (n = cbytes; n--; )
1694 *to++ = *from++;
1698 seq = tem;
1701 else
1703 Lisp_Object tail, prev;
1705 for (tail = seq, prev = Qnil; CONSP (tail); tail = XCDR (tail))
1707 CHECK_LIST_CONS (tail, seq);
1709 if (!NILP (Fequal (elt, XCAR (tail))))
1711 if (NILP (prev))
1712 seq = XCDR (tail);
1713 else
1714 Fsetcdr (prev, XCDR (tail));
1716 else
1717 prev = tail;
1718 QUIT;
1722 return seq;
1725 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1726 doc: /* Reverse LIST by modifying cdr pointers.
1727 Return the reversed list. */)
1728 (Lisp_Object list)
1730 register Lisp_Object prev, tail, next;
1732 if (NILP (list)) return list;
1733 prev = Qnil;
1734 tail = list;
1735 while (!NILP (tail))
1737 QUIT;
1738 CHECK_LIST_CONS (tail, list);
1739 next = XCDR (tail);
1740 Fsetcdr (tail, prev);
1741 prev = tail;
1742 tail = next;
1744 return prev;
1747 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1748 doc: /* Reverse LIST, copying. Return the reversed list.
1749 See also the function `nreverse', which is used more often. */)
1750 (Lisp_Object list)
1752 Lisp_Object new;
1754 for (new = Qnil; CONSP (list); list = XCDR (list))
1756 QUIT;
1757 new = Fcons (XCAR (list), new);
1759 CHECK_LIST_END (list, list);
1760 return new;
1763 Lisp_Object merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred);
1765 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
1766 doc: /* Sort LIST, stably, comparing elements using PREDICATE.
1767 Returns the sorted list. LIST is modified by side effects.
1768 PREDICATE is called with two elements of LIST, and should return non-nil
1769 if the first element should sort before the second. */)
1770 (Lisp_Object list, Lisp_Object predicate)
1772 Lisp_Object front, back;
1773 register Lisp_Object len, tem;
1774 struct gcpro gcpro1, gcpro2;
1775 register int length;
1777 front = list;
1778 len = Flength (list);
1779 length = XINT (len);
1780 if (length < 2)
1781 return list;
1783 XSETINT (len, (length / 2) - 1);
1784 tem = Fnthcdr (len, list);
1785 back = Fcdr (tem);
1786 Fsetcdr (tem, Qnil);
1788 GCPRO2 (front, back);
1789 front = Fsort (front, predicate);
1790 back = Fsort (back, predicate);
1791 UNGCPRO;
1792 return merge (front, back, predicate);
1795 Lisp_Object
1796 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
1798 Lisp_Object value;
1799 register Lisp_Object tail;
1800 Lisp_Object tem;
1801 register Lisp_Object l1, l2;
1802 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1804 l1 = org_l1;
1805 l2 = org_l2;
1806 tail = Qnil;
1807 value = Qnil;
1809 /* It is sufficient to protect org_l1 and org_l2.
1810 When l1 and l2 are updated, we copy the new values
1811 back into the org_ vars. */
1812 GCPRO4 (org_l1, org_l2, pred, value);
1814 while (1)
1816 if (NILP (l1))
1818 UNGCPRO;
1819 if (NILP (tail))
1820 return l2;
1821 Fsetcdr (tail, l2);
1822 return value;
1824 if (NILP (l2))
1826 UNGCPRO;
1827 if (NILP (tail))
1828 return l1;
1829 Fsetcdr (tail, l1);
1830 return value;
1832 tem = call2 (pred, Fcar (l2), Fcar (l1));
1833 if (NILP (tem))
1835 tem = l1;
1836 l1 = Fcdr (l1);
1837 org_l1 = l1;
1839 else
1841 tem = l2;
1842 l2 = Fcdr (l2);
1843 org_l2 = l2;
1845 if (NILP (tail))
1846 value = tem;
1847 else
1848 Fsetcdr (tail, tem);
1849 tail = tem;
1854 /* This does not check for quits. That is safe since it must terminate. */
1856 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
1857 doc: /* Extract a value from a property list.
1858 PLIST is a property list, which is a list of the form
1859 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1860 corresponding to the given PROP, or nil if PROP is not one of the
1861 properties on the list. This function never signals an error. */)
1862 (Lisp_Object plist, Lisp_Object prop)
1864 Lisp_Object tail, halftail;
1866 /* halftail is used to detect circular lists. */
1867 tail = halftail = plist;
1868 while (CONSP (tail) && CONSP (XCDR (tail)))
1870 if (EQ (prop, XCAR (tail)))
1871 return XCAR (XCDR (tail));
1873 tail = XCDR (XCDR (tail));
1874 halftail = XCDR (halftail);
1875 if (EQ (tail, halftail))
1876 break;
1878 #if 0 /* Unsafe version. */
1879 /* This function can be called asynchronously
1880 (setup_coding_system). Don't QUIT in that case. */
1881 if (!interrupt_input_blocked)
1882 QUIT;
1883 #endif
1886 return Qnil;
1889 DEFUN ("get", Fget, Sget, 2, 2, 0,
1890 doc: /* Return the value of SYMBOL's PROPNAME property.
1891 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
1892 (Lisp_Object symbol, Lisp_Object propname)
1894 CHECK_SYMBOL (symbol);
1895 return Fplist_get (XSYMBOL (symbol)->plist, propname);
1898 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
1899 doc: /* Change value in PLIST of PROP to VAL.
1900 PLIST is a property list, which is a list of the form
1901 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
1902 If PROP is already a property on the list, its value is set to VAL,
1903 otherwise the new PROP VAL pair is added. The new plist is returned;
1904 use `(setq x (plist-put x prop val))' to be sure to use the new value.
1905 The PLIST is modified by side effects. */)
1906 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1908 register Lisp_Object tail, prev;
1909 Lisp_Object newcell;
1910 prev = Qnil;
1911 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1912 tail = XCDR (XCDR (tail)))
1914 if (EQ (prop, XCAR (tail)))
1916 Fsetcar (XCDR (tail), val);
1917 return plist;
1920 prev = tail;
1921 QUIT;
1923 newcell = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
1924 if (NILP (prev))
1925 return newcell;
1926 else
1927 Fsetcdr (XCDR (prev), newcell);
1928 return plist;
1931 DEFUN ("put", Fput, Sput, 3, 3, 0,
1932 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
1933 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
1934 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
1936 CHECK_SYMBOL (symbol);
1937 XSYMBOL (symbol)->plist
1938 = Fplist_put (XSYMBOL (symbol)->plist, propname, value);
1939 return value;
1942 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
1943 doc: /* Extract a value from a property list, comparing with `equal'.
1944 PLIST is a property list, which is a list of the form
1945 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1946 corresponding to the given PROP, or nil if PROP is not
1947 one of the properties on the list. */)
1948 (Lisp_Object plist, Lisp_Object prop)
1950 Lisp_Object tail;
1952 for (tail = plist;
1953 CONSP (tail) && CONSP (XCDR (tail));
1954 tail = XCDR (XCDR (tail)))
1956 if (! NILP (Fequal (prop, XCAR (tail))))
1957 return XCAR (XCDR (tail));
1959 QUIT;
1962 CHECK_LIST_END (tail, prop);
1964 return Qnil;
1967 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
1968 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
1969 PLIST is a property list, which is a list of the form
1970 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
1971 If PROP is already a property on the list, its value is set to VAL,
1972 otherwise the new PROP VAL pair is added. The new plist is returned;
1973 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
1974 The PLIST is modified by side effects. */)
1975 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1977 register Lisp_Object tail, prev;
1978 Lisp_Object newcell;
1979 prev = Qnil;
1980 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1981 tail = XCDR (XCDR (tail)))
1983 if (! NILP (Fequal (prop, XCAR (tail))))
1985 Fsetcar (XCDR (tail), val);
1986 return plist;
1989 prev = tail;
1990 QUIT;
1992 newcell = Fcons (prop, Fcons (val, Qnil));
1993 if (NILP (prev))
1994 return newcell;
1995 else
1996 Fsetcdr (XCDR (prev), newcell);
1997 return plist;
2000 DEFUN ("eql", Feql, Seql, 2, 2, 0,
2001 doc: /* Return t if the two args are the same Lisp object.
2002 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
2003 (Lisp_Object obj1, Lisp_Object obj2)
2005 if (FLOATP (obj1))
2006 return internal_equal (obj1, obj2, 0, 0) ? Qt : Qnil;
2007 else
2008 return EQ (obj1, obj2) ? Qt : Qnil;
2011 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
2012 doc: /* Return t if two Lisp objects have similar structure and contents.
2013 They must have the same data type.
2014 Conses are compared by comparing the cars and the cdrs.
2015 Vectors and strings are compared element by element.
2016 Numbers are compared by value, but integers cannot equal floats.
2017 (Use `=' if you want integers and floats to be able to be equal.)
2018 Symbols must match exactly. */)
2019 (register Lisp_Object o1, Lisp_Object o2)
2021 return internal_equal (o1, o2, 0, 0) ? Qt : Qnil;
2024 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
2025 doc: /* Return t if two Lisp objects have similar structure and contents.
2026 This is like `equal' except that it compares the text properties
2027 of strings. (`equal' ignores text properties.) */)
2028 (register Lisp_Object o1, Lisp_Object o2)
2030 return internal_equal (o1, o2, 0, 1) ? Qt : Qnil;
2033 /* DEPTH is current depth of recursion. Signal an error if it
2034 gets too deep.
2035 PROPS, if non-nil, means compare string text properties too. */
2037 static int
2038 internal_equal (register Lisp_Object o1, register Lisp_Object o2, int depth, int props)
2040 if (depth > 200)
2041 error ("Stack overflow in equal");
2043 tail_recurse:
2044 QUIT;
2045 if (EQ (o1, o2))
2046 return 1;
2047 if (XTYPE (o1) != XTYPE (o2))
2048 return 0;
2050 switch (XTYPE (o1))
2052 case Lisp_Float:
2054 double d1, d2;
2056 d1 = extract_float (o1);
2057 d2 = extract_float (o2);
2058 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2059 though they are not =. */
2060 return d1 == d2 || (d1 != d1 && d2 != d2);
2063 case Lisp_Cons:
2064 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1, props))
2065 return 0;
2066 o1 = XCDR (o1);
2067 o2 = XCDR (o2);
2068 goto tail_recurse;
2070 case Lisp_Misc:
2071 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2072 return 0;
2073 if (OVERLAYP (o1))
2075 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2076 depth + 1, props)
2077 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2078 depth + 1, props))
2079 return 0;
2080 o1 = XOVERLAY (o1)->plist;
2081 o2 = XOVERLAY (o2)->plist;
2082 goto tail_recurse;
2084 if (MARKERP (o1))
2086 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2087 && (XMARKER (o1)->buffer == 0
2088 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2090 break;
2092 case Lisp_Vectorlike:
2094 register int i;
2095 EMACS_INT size = ASIZE (o1);
2096 /* Pseudovectors have the type encoded in the size field, so this test
2097 actually checks that the objects have the same type as well as the
2098 same size. */
2099 if (ASIZE (o2) != size)
2100 return 0;
2101 /* Boolvectors are compared much like strings. */
2102 if (BOOL_VECTOR_P (o1))
2104 int size_in_chars
2105 = ((XBOOL_VECTOR (o1)->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
2106 / BOOL_VECTOR_BITS_PER_CHAR);
2108 if (XBOOL_VECTOR (o1)->size != XBOOL_VECTOR (o2)->size)
2109 return 0;
2110 if (memcmp (XBOOL_VECTOR (o1)->data, XBOOL_VECTOR (o2)->data,
2111 size_in_chars))
2112 return 0;
2113 return 1;
2115 if (WINDOW_CONFIGURATIONP (o1))
2116 return compare_window_configurations (o1, o2, 0);
2118 /* Aside from them, only true vectors, char-tables, compiled
2119 functions, and fonts (font-spec, font-entity, font-ojbect)
2120 are sensible to compare, so eliminate the others now. */
2121 if (size & PSEUDOVECTOR_FLAG)
2123 if (!(size & (PVEC_COMPILED
2124 | PVEC_CHAR_TABLE | PVEC_SUB_CHAR_TABLE | PVEC_FONT)))
2125 return 0;
2126 size &= PSEUDOVECTOR_SIZE_MASK;
2128 for (i = 0; i < size; i++)
2130 Lisp_Object v1, v2;
2131 v1 = AREF (o1, i);
2132 v2 = AREF (o2, i);
2133 if (!internal_equal (v1, v2, depth + 1, props))
2134 return 0;
2136 return 1;
2138 break;
2140 case Lisp_String:
2141 if (SCHARS (o1) != SCHARS (o2))
2142 return 0;
2143 if (SBYTES (o1) != SBYTES (o2))
2144 return 0;
2145 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2146 return 0;
2147 if (props && !compare_string_intervals (o1, o2))
2148 return 0;
2149 return 1;
2151 default:
2152 break;
2155 return 0;
2159 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2160 doc: /* Store each element of ARRAY with ITEM.
2161 ARRAY is a vector, string, char-table, or bool-vector. */)
2162 (Lisp_Object array, Lisp_Object item)
2164 register int size, index, charval;
2165 if (VECTORP (array))
2167 register Lisp_Object *p = XVECTOR (array)->contents;
2168 size = ASIZE (array);
2169 for (index = 0; index < size; index++)
2170 p[index] = item;
2172 else if (CHAR_TABLE_P (array))
2174 int i;
2176 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2177 XCHAR_TABLE (array)->contents[i] = item;
2178 XCHAR_TABLE (array)->defalt = item;
2180 else if (STRINGP (array))
2182 register unsigned char *p = SDATA (array);
2183 CHECK_NUMBER (item);
2184 charval = XINT (item);
2185 size = SCHARS (array);
2186 if (STRING_MULTIBYTE (array))
2188 unsigned char str[MAX_MULTIBYTE_LENGTH];
2189 int len = CHAR_STRING (charval, str);
2190 int size_byte = SBYTES (array);
2191 unsigned char *p1 = p, *endp = p + size_byte;
2192 int i;
2194 if (size != size_byte)
2195 while (p1 < endp)
2197 int this_len = BYTES_BY_CHAR_HEAD (*p1);
2198 if (len != this_len)
2199 error ("Attempt to change byte length of a string");
2200 p1 += this_len;
2202 for (i = 0; i < size_byte; i++)
2203 *p++ = str[i % len];
2205 else
2206 for (index = 0; index < size; index++)
2207 p[index] = charval;
2209 else if (BOOL_VECTOR_P (array))
2211 register unsigned char *p = XBOOL_VECTOR (array)->data;
2212 int size_in_chars
2213 = ((XBOOL_VECTOR (array)->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
2214 / BOOL_VECTOR_BITS_PER_CHAR);
2216 charval = (! NILP (item) ? -1 : 0);
2217 for (index = 0; index < size_in_chars - 1; index++)
2218 p[index] = charval;
2219 if (index < size_in_chars)
2221 /* Mask out bits beyond the vector size. */
2222 if (XBOOL_VECTOR (array)->size % BOOL_VECTOR_BITS_PER_CHAR)
2223 charval &= (1 << (XBOOL_VECTOR (array)->size % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2224 p[index] = charval;
2227 else
2228 wrong_type_argument (Qarrayp, array);
2229 return array;
2232 DEFUN ("clear-string", Fclear_string, Sclear_string,
2233 1, 1, 0,
2234 doc: /* Clear the contents of STRING.
2235 This makes STRING unibyte and may change its length. */)
2236 (Lisp_Object string)
2238 int len;
2239 CHECK_STRING (string);
2240 len = SBYTES (string);
2241 memset (SDATA (string), 0, len);
2242 STRING_SET_CHARS (string, len);
2243 STRING_SET_UNIBYTE (string);
2244 return Qnil;
2247 /* ARGSUSED */
2248 Lisp_Object
2249 nconc2 (Lisp_Object s1, Lisp_Object s2)
2251 Lisp_Object args[2];
2252 args[0] = s1;
2253 args[1] = s2;
2254 return Fnconc (2, args);
2257 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2258 doc: /* Concatenate any number of lists by altering them.
2259 Only the last argument is not altered, and need not be a list.
2260 usage: (nconc &rest LISTS) */)
2261 (int nargs, Lisp_Object *args)
2263 register int argnum;
2264 register Lisp_Object tail, tem, val;
2266 val = tail = Qnil;
2268 for (argnum = 0; argnum < nargs; argnum++)
2270 tem = args[argnum];
2271 if (NILP (tem)) continue;
2273 if (NILP (val))
2274 val = tem;
2276 if (argnum + 1 == nargs) break;
2278 CHECK_LIST_CONS (tem, tem);
2280 while (CONSP (tem))
2282 tail = tem;
2283 tem = XCDR (tail);
2284 QUIT;
2287 tem = args[argnum + 1];
2288 Fsetcdr (tail, tem);
2289 if (NILP (tem))
2290 args[argnum + 1] = tail;
2293 return val;
2296 /* This is the guts of all mapping functions.
2297 Apply FN to each element of SEQ, one by one,
2298 storing the results into elements of VALS, a C vector of Lisp_Objects.
2299 LENI is the length of VALS, which should also be the length of SEQ. */
2301 static void
2302 mapcar1 (int leni, Lisp_Object *vals, Lisp_Object fn, Lisp_Object seq)
2304 register Lisp_Object tail;
2305 Lisp_Object dummy;
2306 register int i;
2307 struct gcpro gcpro1, gcpro2, gcpro3;
2309 if (vals)
2311 /* Don't let vals contain any garbage when GC happens. */
2312 for (i = 0; i < leni; i++)
2313 vals[i] = Qnil;
2315 GCPRO3 (dummy, fn, seq);
2316 gcpro1.var = vals;
2317 gcpro1.nvars = leni;
2319 else
2320 GCPRO2 (fn, seq);
2321 /* We need not explicitly protect `tail' because it is used only on lists, and
2322 1) lists are not relocated and 2) the list is marked via `seq' so will not
2323 be freed */
2325 if (VECTORP (seq))
2327 for (i = 0; i < leni; i++)
2329 dummy = call1 (fn, AREF (seq, i));
2330 if (vals)
2331 vals[i] = dummy;
2334 else if (BOOL_VECTOR_P (seq))
2336 for (i = 0; i < leni; i++)
2338 int byte;
2339 byte = XBOOL_VECTOR (seq)->data[i / BOOL_VECTOR_BITS_PER_CHAR];
2340 dummy = (byte & (1 << (i % BOOL_VECTOR_BITS_PER_CHAR))) ? Qt : Qnil;
2341 dummy = call1 (fn, dummy);
2342 if (vals)
2343 vals[i] = dummy;
2346 else if (STRINGP (seq))
2348 int i_byte;
2350 for (i = 0, i_byte = 0; i < leni;)
2352 int c;
2353 int i_before = i;
2355 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2356 XSETFASTINT (dummy, c);
2357 dummy = call1 (fn, dummy);
2358 if (vals)
2359 vals[i_before] = dummy;
2362 else /* Must be a list, since Flength did not get an error */
2364 tail = seq;
2365 for (i = 0; i < leni && CONSP (tail); i++)
2367 dummy = call1 (fn, XCAR (tail));
2368 if (vals)
2369 vals[i] = dummy;
2370 tail = XCDR (tail);
2374 UNGCPRO;
2377 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2378 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2379 In between each pair of results, stick in SEPARATOR. Thus, " " as
2380 SEPARATOR results in spaces between the values returned by FUNCTION.
2381 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2382 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2384 Lisp_Object len;
2385 register int leni;
2386 int nargs;
2387 register Lisp_Object *args;
2388 register int i;
2389 struct gcpro gcpro1;
2390 Lisp_Object ret;
2391 USE_SAFE_ALLOCA;
2393 len = Flength (sequence);
2394 if (CHAR_TABLE_P (sequence))
2395 wrong_type_argument (Qlistp, sequence);
2396 leni = XINT (len);
2397 nargs = leni + leni - 1;
2398 if (nargs < 0) return empty_unibyte_string;
2400 SAFE_ALLOCA_LISP (args, nargs);
2402 GCPRO1 (separator);
2403 mapcar1 (leni, args, function, sequence);
2404 UNGCPRO;
2406 for (i = leni - 1; i > 0; i--)
2407 args[i + i] = args[i];
2409 for (i = 1; i < nargs; i += 2)
2410 args[i] = separator;
2412 ret = Fconcat (nargs, args);
2413 SAFE_FREE ();
2415 return ret;
2418 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2419 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2420 The result is a list just as long as SEQUENCE.
2421 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2422 (Lisp_Object function, Lisp_Object sequence)
2424 register Lisp_Object len;
2425 register int leni;
2426 register Lisp_Object *args;
2427 Lisp_Object ret;
2428 USE_SAFE_ALLOCA;
2430 len = Flength (sequence);
2431 if (CHAR_TABLE_P (sequence))
2432 wrong_type_argument (Qlistp, sequence);
2433 leni = XFASTINT (len);
2435 SAFE_ALLOCA_LISP (args, leni);
2437 mapcar1 (leni, args, function, sequence);
2439 ret = Flist (leni, args);
2440 SAFE_FREE ();
2442 return ret;
2445 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2446 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2447 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2448 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2449 (Lisp_Object function, Lisp_Object sequence)
2451 register int leni;
2453 leni = XFASTINT (Flength (sequence));
2454 if (CHAR_TABLE_P (sequence))
2455 wrong_type_argument (Qlistp, sequence);
2456 mapcar1 (leni, 0, function, sequence);
2458 return sequence;
2461 /* Anything that calls this function must protect from GC! */
2463 DEFUN ("y-or-n-p", Fy_or_n_p, Sy_or_n_p, 1, 1, 0,
2464 doc: /* Ask user a "y or n" question. Return t if answer is "y".
2465 Takes one argument, which is the string to display to ask the question.
2466 It should end in a space; `y-or-n-p' adds `(y or n) ' to it.
2467 No confirmation of the answer is requested; a single character is enough.
2468 Also accepts Space to mean yes, or Delete to mean no. \(Actually, it uses
2469 the bindings in `query-replace-map'; see the documentation of that variable
2470 for more information. In this case, the useful bindings are `act', `skip',
2471 `recenter', and `quit'.\)
2473 Under a windowing system a dialog box will be used if `last-nonmenu-event'
2474 is nil and `use-dialog-box' is non-nil. */)
2475 (Lisp_Object prompt)
2477 register Lisp_Object obj, key, def, map;
2478 register int answer;
2479 Lisp_Object xprompt;
2480 Lisp_Object args[2];
2481 struct gcpro gcpro1, gcpro2;
2482 int count = SPECPDL_INDEX ();
2484 specbind (Qcursor_in_echo_area, Qt);
2486 map = Fsymbol_value (intern ("query-replace-map"));
2488 CHECK_STRING (prompt);
2489 xprompt = prompt;
2490 GCPRO2 (prompt, xprompt);
2492 #ifdef HAVE_WINDOW_SYSTEM
2493 if (display_hourglass_p)
2494 cancel_hourglass ();
2495 #endif
2497 while (1)
2500 #ifdef HAVE_MENUS
2501 if (FRAME_WINDOW_P (SELECTED_FRAME ())
2502 && (NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2503 && use_dialog_box
2504 && have_menus_p ())
2506 Lisp_Object pane, menu;
2507 redisplay_preserve_echo_area (3);
2508 pane = Fcons (Fcons (build_string ("Yes"), Qt),
2509 Fcons (Fcons (build_string ("No"), Qnil),
2510 Qnil));
2511 menu = Fcons (prompt, pane);
2512 obj = Fx_popup_dialog (Qt, menu, Qnil);
2513 answer = !NILP (obj);
2514 break;
2516 #endif /* HAVE_MENUS */
2517 cursor_in_echo_area = 1;
2518 choose_minibuf_frame ();
2521 Lisp_Object pargs[3];
2523 /* Colorize prompt according to `minibuffer-prompt' face. */
2524 pargs[0] = build_string ("%s(y or n) ");
2525 pargs[1] = intern ("face");
2526 pargs[2] = intern ("minibuffer-prompt");
2527 args[0] = Fpropertize (3, pargs);
2528 args[1] = xprompt;
2529 Fmessage (2, args);
2532 if (minibuffer_auto_raise)
2534 Lisp_Object mini_frame;
2536 mini_frame = WINDOW_FRAME (XWINDOW (minibuf_window));
2538 Fraise_frame (mini_frame);
2541 temporarily_switch_to_single_kboard (SELECTED_FRAME ());
2542 obj = read_filtered_event (1, 0, 0, 0, Qnil);
2543 cursor_in_echo_area = 0;
2544 /* If we need to quit, quit with cursor_in_echo_area = 0. */
2545 QUIT;
2547 key = Fmake_vector (make_number (1), obj);
2548 def = Flookup_key (map, key, Qt);
2550 if (EQ (def, intern ("skip")))
2552 answer = 0;
2553 break;
2555 else if (EQ (def, intern ("act")))
2557 answer = 1;
2558 break;
2560 else if (EQ (def, intern ("recenter")))
2562 Frecenter (Qnil);
2563 xprompt = prompt;
2564 continue;
2566 else if (EQ (def, intern ("quit")))
2567 Vquit_flag = Qt;
2568 /* We want to exit this command for exit-prefix,
2569 and this is the only way to do it. */
2570 else if (EQ (def, intern ("exit-prefix")))
2571 Vquit_flag = Qt;
2573 QUIT;
2575 /* If we don't clear this, then the next call to read_char will
2576 return quit_char again, and we'll enter an infinite loop. */
2577 Vquit_flag = Qnil;
2579 Fding (Qnil);
2580 Fdiscard_input ();
2581 if (EQ (xprompt, prompt))
2583 args[0] = build_string ("Please answer y or n. ");
2584 args[1] = prompt;
2585 xprompt = Fconcat (2, args);
2588 UNGCPRO;
2590 if (! noninteractive)
2592 cursor_in_echo_area = -1;
2593 message_with_string (answer ? "%s(y or n) y" : "%s(y or n) n",
2594 xprompt, 0);
2597 unbind_to (count, Qnil);
2598 return answer ? Qt : Qnil;
2601 /* This is how C code calls `yes-or-no-p' and allows the user
2602 to redefined it.
2604 Anything that calls this function must protect from GC! */
2606 Lisp_Object
2607 do_yes_or_no_p (Lisp_Object prompt)
2609 return call1 (intern ("yes-or-no-p"), prompt);
2612 /* Anything that calls this function must protect from GC! */
2614 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2615 doc: /* Ask user a yes-or-no question. Return t if answer is yes.
2616 Takes one argument, which is the string to display to ask the question.
2617 It should end in a space; `yes-or-no-p' adds `(yes or no) ' to it.
2618 The user must confirm the answer with RET,
2619 and can edit it until it has been confirmed.
2621 Under a windowing system a dialog box will be used if `last-nonmenu-event'
2622 is nil, and `use-dialog-box' is non-nil. */)
2623 (Lisp_Object prompt)
2625 register Lisp_Object ans;
2626 Lisp_Object args[2];
2627 struct gcpro gcpro1;
2629 CHECK_STRING (prompt);
2631 #ifdef HAVE_MENUS
2632 if (FRAME_WINDOW_P (SELECTED_FRAME ())
2633 && (NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2634 && use_dialog_box
2635 && have_menus_p ())
2637 Lisp_Object pane, menu, obj;
2638 redisplay_preserve_echo_area (4);
2639 pane = Fcons (Fcons (build_string ("Yes"), Qt),
2640 Fcons (Fcons (build_string ("No"), Qnil),
2641 Qnil));
2642 GCPRO1 (pane);
2643 menu = Fcons (prompt, pane);
2644 obj = Fx_popup_dialog (Qt, menu, Qnil);
2645 UNGCPRO;
2646 return obj;
2648 #endif /* HAVE_MENUS */
2650 args[0] = prompt;
2651 args[1] = build_string ("(yes or no) ");
2652 prompt = Fconcat (2, args);
2654 GCPRO1 (prompt);
2656 while (1)
2658 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2659 Qyes_or_no_p_history, Qnil,
2660 Qnil));
2661 if (SCHARS (ans) == 3 && !strcmp (SDATA (ans), "yes"))
2663 UNGCPRO;
2664 return Qt;
2666 if (SCHARS (ans) == 2 && !strcmp (SDATA (ans), "no"))
2668 UNGCPRO;
2669 return Qnil;
2672 Fding (Qnil);
2673 Fdiscard_input ();
2674 message ("Please answer yes or no.");
2675 Fsleep_for (make_number (2), Qnil);
2679 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2680 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2682 Each of the three load averages is multiplied by 100, then converted
2683 to integer.
2685 When USE-FLOATS is non-nil, floats will be used instead of integers.
2686 These floats are not multiplied by 100.
2688 If the 5-minute or 15-minute load averages are not available, return a
2689 shortened list, containing only those averages which are available.
2691 An error is thrown if the load average can't be obtained. In some
2692 cases making it work would require Emacs being installed setuid or
2693 setgid so that it can read kernel information, and that usually isn't
2694 advisable. */)
2695 (Lisp_Object use_floats)
2697 double load_ave[3];
2698 int loads = getloadavg (load_ave, 3);
2699 Lisp_Object ret = Qnil;
2701 if (loads < 0)
2702 error ("load-average not implemented for this operating system");
2704 while (loads-- > 0)
2706 Lisp_Object load = (NILP (use_floats) ?
2707 make_number ((int) (100.0 * load_ave[loads]))
2708 : make_float (load_ave[loads]));
2709 ret = Fcons (load, ret);
2712 return ret;
2715 Lisp_Object Vfeatures, Qsubfeatures;
2716 extern Lisp_Object Vafter_load_alist;
2718 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2719 doc: /* Returns t if FEATURE is present in this Emacs.
2721 Use this to conditionalize execution of lisp code based on the
2722 presence or absence of Emacs or environment extensions.
2723 Use `provide' to declare that a feature is available. This function
2724 looks at the value of the variable `features'. The optional argument
2725 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2726 (Lisp_Object feature, Lisp_Object subfeature)
2728 register Lisp_Object tem;
2729 CHECK_SYMBOL (feature);
2730 tem = Fmemq (feature, Vfeatures);
2731 if (!NILP (tem) && !NILP (subfeature))
2732 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2733 return (NILP (tem)) ? Qnil : Qt;
2736 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2737 doc: /* Announce that FEATURE is a feature of the current Emacs.
2738 The optional argument SUBFEATURES should be a list of symbols listing
2739 particular subfeatures supported in this version of FEATURE. */)
2740 (Lisp_Object feature, Lisp_Object subfeatures)
2742 register Lisp_Object tem;
2743 CHECK_SYMBOL (feature);
2744 CHECK_LIST (subfeatures);
2745 if (!NILP (Vautoload_queue))
2746 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2747 Vautoload_queue);
2748 tem = Fmemq (feature, Vfeatures);
2749 if (NILP (tem))
2750 Vfeatures = Fcons (feature, Vfeatures);
2751 if (!NILP (subfeatures))
2752 Fput (feature, Qsubfeatures, subfeatures);
2753 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2755 /* Run any load-hooks for this file. */
2756 tem = Fassq (feature, Vafter_load_alist);
2757 if (CONSP (tem))
2758 Fprogn (XCDR (tem));
2760 return feature;
2763 /* `require' and its subroutines. */
2765 /* List of features currently being require'd, innermost first. */
2767 Lisp_Object require_nesting_list;
2769 Lisp_Object
2770 require_unwind (Lisp_Object old_value)
2772 return require_nesting_list = old_value;
2775 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2776 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2777 If FEATURE is not a member of the list `features', then the feature
2778 is not loaded; so load the file FILENAME.
2779 If FILENAME is omitted, the printname of FEATURE is used as the file name,
2780 and `load' will try to load this name appended with the suffix `.elc' or
2781 `.el', in that order. The name without appended suffix will not be used.
2782 If the optional third argument NOERROR is non-nil,
2783 then return nil if the file is not found instead of signaling an error.
2784 Normally the return value is FEATURE.
2785 The normal messages at start and end of loading FILENAME are suppressed. */)
2786 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2788 register Lisp_Object tem;
2789 struct gcpro gcpro1, gcpro2;
2790 int from_file = load_in_progress;
2792 CHECK_SYMBOL (feature);
2794 /* Record the presence of `require' in this file
2795 even if the feature specified is already loaded.
2796 But not more than once in any file,
2797 and not when we aren't loading or reading from a file. */
2798 if (!from_file)
2799 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2800 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2801 from_file = 1;
2803 if (from_file)
2805 tem = Fcons (Qrequire, feature);
2806 if (NILP (Fmember (tem, Vcurrent_load_list)))
2807 LOADHIST_ATTACH (tem);
2809 tem = Fmemq (feature, Vfeatures);
2811 if (NILP (tem))
2813 int count = SPECPDL_INDEX ();
2814 int nesting = 0;
2816 /* This is to make sure that loadup.el gives a clear picture
2817 of what files are preloaded and when. */
2818 if (! NILP (Vpurify_flag))
2819 error ("(require %s) while preparing to dump",
2820 SDATA (SYMBOL_NAME (feature)));
2822 /* A certain amount of recursive `require' is legitimate,
2823 but if we require the same feature recursively 3 times,
2824 signal an error. */
2825 tem = require_nesting_list;
2826 while (! NILP (tem))
2828 if (! NILP (Fequal (feature, XCAR (tem))))
2829 nesting++;
2830 tem = XCDR (tem);
2832 if (nesting > 3)
2833 error ("Recursive `require' for feature `%s'",
2834 SDATA (SYMBOL_NAME (feature)));
2836 /* Update the list for any nested `require's that occur. */
2837 record_unwind_protect (require_unwind, require_nesting_list);
2838 require_nesting_list = Fcons (feature, require_nesting_list);
2840 /* Value saved here is to be restored into Vautoload_queue */
2841 record_unwind_protect (un_autoload, Vautoload_queue);
2842 Vautoload_queue = Qt;
2844 /* Load the file. */
2845 GCPRO2 (feature, filename);
2846 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2847 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2848 UNGCPRO;
2850 /* If load failed entirely, return nil. */
2851 if (NILP (tem))
2852 return unbind_to (count, Qnil);
2854 tem = Fmemq (feature, Vfeatures);
2855 if (NILP (tem))
2856 error ("Required feature `%s' was not provided",
2857 SDATA (SYMBOL_NAME (feature)));
2859 /* Once loading finishes, don't undo it. */
2860 Vautoload_queue = Qt;
2861 feature = unbind_to (count, feature);
2864 return feature;
2867 /* Primitives for work of the "widget" library.
2868 In an ideal world, this section would not have been necessary.
2869 However, lisp function calls being as slow as they are, it turns
2870 out that some functions in the widget library (wid-edit.el) are the
2871 bottleneck of Widget operation. Here is their translation to C,
2872 for the sole reason of efficiency. */
2874 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2875 doc: /* Return non-nil if PLIST has the property PROP.
2876 PLIST is a property list, which is a list of the form
2877 \(PROP1 VALUE1 PROP2 VALUE2 ...\). PROP is a symbol.
2878 Unlike `plist-get', this allows you to distinguish between a missing
2879 property and a property with the value nil.
2880 The value is actually the tail of PLIST whose car is PROP. */)
2881 (Lisp_Object plist, Lisp_Object prop)
2883 while (CONSP (plist) && !EQ (XCAR (plist), prop))
2885 QUIT;
2886 plist = XCDR (plist);
2887 plist = CDR (plist);
2889 return plist;
2892 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2893 doc: /* In WIDGET, set PROPERTY to VALUE.
2894 The value can later be retrieved with `widget-get'. */)
2895 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2897 CHECK_CONS (widget);
2898 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
2899 return value;
2902 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
2903 doc: /* In WIDGET, get the value of PROPERTY.
2904 The value could either be specified when the widget was created, or
2905 later with `widget-put'. */)
2906 (Lisp_Object widget, Lisp_Object property)
2908 Lisp_Object tmp;
2910 while (1)
2912 if (NILP (widget))
2913 return Qnil;
2914 CHECK_CONS (widget);
2915 tmp = Fplist_member (XCDR (widget), property);
2916 if (CONSP (tmp))
2918 tmp = XCDR (tmp);
2919 return CAR (tmp);
2921 tmp = XCAR (widget);
2922 if (NILP (tmp))
2923 return Qnil;
2924 widget = Fget (tmp, Qwidget_type);
2928 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
2929 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2930 ARGS are passed as extra arguments to the function.
2931 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2932 (int nargs, Lisp_Object *args)
2934 /* This function can GC. */
2935 Lisp_Object newargs[3];
2936 struct gcpro gcpro1, gcpro2;
2937 Lisp_Object result;
2939 newargs[0] = Fwidget_get (args[0], args[1]);
2940 newargs[1] = args[0];
2941 newargs[2] = Flist (nargs - 2, args + 2);
2942 GCPRO2 (newargs[0], newargs[2]);
2943 result = Fapply (3, newargs);
2944 UNGCPRO;
2945 return result;
2948 #ifdef HAVE_LANGINFO_CODESET
2949 #include <langinfo.h>
2950 #endif
2952 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
2953 doc: /* Access locale data ITEM for the current C locale, if available.
2954 ITEM should be one of the following:
2956 `codeset', returning the character set as a string (locale item CODESET);
2958 `days', returning a 7-element vector of day names (locale items DAY_n);
2960 `months', returning a 12-element vector of month names (locale items MON_n);
2962 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
2963 both measured in milimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
2965 If the system can't provide such information through a call to
2966 `nl_langinfo', or if ITEM isn't from the list above, return nil.
2968 See also Info node `(libc)Locales'.
2970 The data read from the system are decoded using `locale-coding-system'. */)
2971 (Lisp_Object item)
2973 char *str = NULL;
2974 #ifdef HAVE_LANGINFO_CODESET
2975 Lisp_Object val;
2976 if (EQ (item, Qcodeset))
2978 str = nl_langinfo (CODESET);
2979 return build_string (str);
2981 #ifdef DAY_1
2982 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
2984 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
2985 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
2986 int i;
2987 struct gcpro gcpro1;
2988 GCPRO1 (v);
2989 synchronize_system_time_locale ();
2990 for (i = 0; i < 7; i++)
2992 str = nl_langinfo (days[i]);
2993 val = make_unibyte_string (str, strlen (str));
2994 /* Fixme: Is this coding system necessarily right, even if
2995 it is consistent with CODESET? If not, what to do? */
2996 Faset (v, make_number (i),
2997 code_convert_string_norecord (val, Vlocale_coding_system,
2998 0));
3000 UNGCPRO;
3001 return v;
3003 #endif /* DAY_1 */
3004 #ifdef MON_1
3005 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
3007 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
3008 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
3009 MON_8, MON_9, MON_10, MON_11, MON_12};
3010 int i;
3011 struct gcpro gcpro1;
3012 GCPRO1 (v);
3013 synchronize_system_time_locale ();
3014 for (i = 0; i < 12; i++)
3016 str = nl_langinfo (months[i]);
3017 val = make_unibyte_string (str, strlen (str));
3018 Faset (v, make_number (i),
3019 code_convert_string_norecord (val, Vlocale_coding_system, 0));
3021 UNGCPRO;
3022 return v;
3024 #endif /* MON_1 */
3025 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
3026 but is in the locale files. This could be used by ps-print. */
3027 #ifdef PAPER_WIDTH
3028 else if (EQ (item, Qpaper))
3030 return list2 (make_number (nl_langinfo (PAPER_WIDTH)),
3031 make_number (nl_langinfo (PAPER_HEIGHT)));
3033 #endif /* PAPER_WIDTH */
3034 #endif /* HAVE_LANGINFO_CODESET*/
3035 return Qnil;
3038 /* base64 encode/decode functions (RFC 2045).
3039 Based on code from GNU recode. */
3041 #define MIME_LINE_LENGTH 76
3043 #define IS_ASCII(Character) \
3044 ((Character) < 128)
3045 #define IS_BASE64(Character) \
3046 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
3047 #define IS_BASE64_IGNORABLE(Character) \
3048 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
3049 || (Character) == '\f' || (Character) == '\r')
3051 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
3052 character or return retval if there are no characters left to
3053 process. */
3054 #define READ_QUADRUPLET_BYTE(retval) \
3055 do \
3057 if (i == length) \
3059 if (nchars_return) \
3060 *nchars_return = nchars; \
3061 return (retval); \
3063 c = from[i++]; \
3065 while (IS_BASE64_IGNORABLE (c))
3067 /* Table of characters coding the 64 values. */
3068 static const char base64_value_to_char[64] =
3070 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
3071 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
3072 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
3073 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
3074 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
3075 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
3076 '8', '9', '+', '/' /* 60-63 */
3079 /* Table of base64 values for first 128 characters. */
3080 static const short base64_char_to_value[128] =
3082 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
3083 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
3084 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
3085 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
3086 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
3087 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
3088 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
3089 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
3090 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
3091 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
3092 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
3093 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
3094 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
3097 /* The following diagram shows the logical steps by which three octets
3098 get transformed into four base64 characters.
3100 .--------. .--------. .--------.
3101 |aaaaaabb| |bbbbcccc| |ccdddddd|
3102 `--------' `--------' `--------'
3103 6 2 4 4 2 6
3104 .--------+--------+--------+--------.
3105 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
3106 `--------+--------+--------+--------'
3108 .--------+--------+--------+--------.
3109 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
3110 `--------+--------+--------+--------'
3112 The octets are divided into 6 bit chunks, which are then encoded into
3113 base64 characters. */
3116 static int base64_encode_1 (const char *, char *, int, int, int);
3117 static int base64_decode_1 (const char *, char *, int, int, int *);
3119 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
3120 2, 3, "r",
3121 doc: /* Base64-encode the region between BEG and END.
3122 Return the length of the encoded text.
3123 Optional third argument NO-LINE-BREAK means do not break long lines
3124 into shorter lines. */)
3125 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
3127 char *encoded;
3128 int allength, length;
3129 int ibeg, iend, encoded_length;
3130 int old_pos = PT;
3131 USE_SAFE_ALLOCA;
3133 validate_region (&beg, &end);
3135 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3136 iend = CHAR_TO_BYTE (XFASTINT (end));
3137 move_gap_both (XFASTINT (beg), ibeg);
3139 /* We need to allocate enough room for encoding the text.
3140 We need 33 1/3% more space, plus a newline every 76
3141 characters, and then we round up. */
3142 length = iend - ibeg;
3143 allength = length + length/3 + 1;
3144 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3146 SAFE_ALLOCA (encoded, char *, allength);
3147 encoded_length = base64_encode_1 (BYTE_POS_ADDR (ibeg), encoded, length,
3148 NILP (no_line_break),
3149 !NILP (current_buffer->enable_multibyte_characters));
3150 if (encoded_length > allength)
3151 abort ();
3153 if (encoded_length < 0)
3155 /* The encoding wasn't possible. */
3156 SAFE_FREE ();
3157 error ("Multibyte character in data for base64 encoding");
3160 /* Now we have encoded the region, so we insert the new contents
3161 and delete the old. (Insert first in order to preserve markers.) */
3162 SET_PT_BOTH (XFASTINT (beg), ibeg);
3163 insert (encoded, encoded_length);
3164 SAFE_FREE ();
3165 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
3167 /* If point was outside of the region, restore it exactly; else just
3168 move to the beginning of the region. */
3169 if (old_pos >= XFASTINT (end))
3170 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
3171 else if (old_pos > XFASTINT (beg))
3172 old_pos = XFASTINT (beg);
3173 SET_PT (old_pos);
3175 /* We return the length of the encoded text. */
3176 return make_number (encoded_length);
3179 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
3180 1, 2, 0,
3181 doc: /* Base64-encode STRING and return the result.
3182 Optional second argument NO-LINE-BREAK means do not break long lines
3183 into shorter lines. */)
3184 (Lisp_Object string, Lisp_Object no_line_break)
3186 int allength, length, encoded_length;
3187 char *encoded;
3188 Lisp_Object encoded_string;
3189 USE_SAFE_ALLOCA;
3191 CHECK_STRING (string);
3193 /* We need to allocate enough room for encoding the text.
3194 We need 33 1/3% more space, plus a newline every 76
3195 characters, and then we round up. */
3196 length = SBYTES (string);
3197 allength = length + length/3 + 1;
3198 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3200 /* We need to allocate enough room for decoding the text. */
3201 SAFE_ALLOCA (encoded, char *, allength);
3203 encoded_length = base64_encode_1 (SDATA (string),
3204 encoded, length, NILP (no_line_break),
3205 STRING_MULTIBYTE (string));
3206 if (encoded_length > allength)
3207 abort ();
3209 if (encoded_length < 0)
3211 /* The encoding wasn't possible. */
3212 SAFE_FREE ();
3213 error ("Multibyte character in data for base64 encoding");
3216 encoded_string = make_unibyte_string (encoded, encoded_length);
3217 SAFE_FREE ();
3219 return encoded_string;
3222 static int
3223 base64_encode_1 (const char *from, char *to, int length, int line_break, int multibyte)
3225 int counter = 0, i = 0;
3226 char *e = to;
3227 int c;
3228 unsigned int value;
3229 int bytes;
3231 while (i < length)
3233 if (multibyte)
3235 c = STRING_CHAR_AND_LENGTH (from + i, bytes);
3236 if (CHAR_BYTE8_P (c))
3237 c = CHAR_TO_BYTE8 (c);
3238 else if (c >= 256)
3239 return -1;
3240 i += bytes;
3242 else
3243 c = from[i++];
3245 /* Wrap line every 76 characters. */
3247 if (line_break)
3249 if (counter < MIME_LINE_LENGTH / 4)
3250 counter++;
3251 else
3253 *e++ = '\n';
3254 counter = 1;
3258 /* Process first byte of a triplet. */
3260 *e++ = base64_value_to_char[0x3f & c >> 2];
3261 value = (0x03 & c) << 4;
3263 /* Process second byte of a triplet. */
3265 if (i == length)
3267 *e++ = base64_value_to_char[value];
3268 *e++ = '=';
3269 *e++ = '=';
3270 break;
3273 if (multibyte)
3275 c = STRING_CHAR_AND_LENGTH (from + i, bytes);
3276 if (CHAR_BYTE8_P (c))
3277 c = CHAR_TO_BYTE8 (c);
3278 else if (c >= 256)
3279 return -1;
3280 i += bytes;
3282 else
3283 c = from[i++];
3285 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3286 value = (0x0f & c) << 2;
3288 /* Process third byte of a triplet. */
3290 if (i == length)
3292 *e++ = base64_value_to_char[value];
3293 *e++ = '=';
3294 break;
3297 if (multibyte)
3299 c = STRING_CHAR_AND_LENGTH (from + i, bytes);
3300 if (CHAR_BYTE8_P (c))
3301 c = CHAR_TO_BYTE8 (c);
3302 else if (c >= 256)
3303 return -1;
3304 i += bytes;
3306 else
3307 c = from[i++];
3309 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3310 *e++ = base64_value_to_char[0x3f & c];
3313 return e - to;
3317 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3318 2, 2, "r",
3319 doc: /* Base64-decode the region between BEG and END.
3320 Return the length of the decoded text.
3321 If the region can't be decoded, signal an error and don't modify the buffer. */)
3322 (Lisp_Object beg, Lisp_Object end)
3324 int ibeg, iend, length, allength;
3325 char *decoded;
3326 int old_pos = PT;
3327 int decoded_length;
3328 int inserted_chars;
3329 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
3330 USE_SAFE_ALLOCA;
3332 validate_region (&beg, &end);
3334 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3335 iend = CHAR_TO_BYTE (XFASTINT (end));
3337 length = iend - ibeg;
3339 /* We need to allocate enough room for decoding the text. If we are
3340 working on a multibyte buffer, each decoded code may occupy at
3341 most two bytes. */
3342 allength = multibyte ? length * 2 : length;
3343 SAFE_ALLOCA (decoded, char *, allength);
3345 move_gap_both (XFASTINT (beg), ibeg);
3346 decoded_length = base64_decode_1 (BYTE_POS_ADDR (ibeg), decoded, length,
3347 multibyte, &inserted_chars);
3348 if (decoded_length > allength)
3349 abort ();
3351 if (decoded_length < 0)
3353 /* The decoding wasn't possible. */
3354 SAFE_FREE ();
3355 error ("Invalid base64 data");
3358 /* Now we have decoded the region, so we insert the new contents
3359 and delete the old. (Insert first in order to preserve markers.) */
3360 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3361 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3362 SAFE_FREE ();
3364 /* Delete the original text. */
3365 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3366 iend + decoded_length, 1);
3368 /* If point was outside of the region, restore it exactly; else just
3369 move to the beginning of the region. */
3370 if (old_pos >= XFASTINT (end))
3371 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3372 else if (old_pos > XFASTINT (beg))
3373 old_pos = XFASTINT (beg);
3374 SET_PT (old_pos > ZV ? ZV : old_pos);
3376 return make_number (inserted_chars);
3379 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3380 1, 1, 0,
3381 doc: /* Base64-decode STRING and return the result. */)
3382 (Lisp_Object string)
3384 char *decoded;
3385 int length, decoded_length;
3386 Lisp_Object decoded_string;
3387 USE_SAFE_ALLOCA;
3389 CHECK_STRING (string);
3391 length = SBYTES (string);
3392 /* We need to allocate enough room for decoding the text. */
3393 SAFE_ALLOCA (decoded, char *, length);
3395 /* The decoded result should be unibyte. */
3396 decoded_length = base64_decode_1 (SDATA (string), decoded, length,
3397 0, NULL);
3398 if (decoded_length > length)
3399 abort ();
3400 else if (decoded_length >= 0)
3401 decoded_string = make_unibyte_string (decoded, decoded_length);
3402 else
3403 decoded_string = Qnil;
3405 SAFE_FREE ();
3406 if (!STRINGP (decoded_string))
3407 error ("Invalid base64 data");
3409 return decoded_string;
3412 /* Base64-decode the data at FROM of LENGHT bytes into TO. If
3413 MULTIBYTE is nonzero, the decoded result should be in multibyte
3414 form. If NCHARS_RETRUN is not NULL, store the number of produced
3415 characters in *NCHARS_RETURN. */
3417 static int
3418 base64_decode_1 (const char *from, char *to, int length, int multibyte, int *nchars_return)
3420 int i = 0;
3421 char *e = to;
3422 unsigned char c;
3423 unsigned long value;
3424 int nchars = 0;
3426 while (1)
3428 /* Process first byte of a quadruplet. */
3430 READ_QUADRUPLET_BYTE (e-to);
3432 if (!IS_BASE64 (c))
3433 return -1;
3434 value = base64_char_to_value[c] << 18;
3436 /* Process second byte of a quadruplet. */
3438 READ_QUADRUPLET_BYTE (-1);
3440 if (!IS_BASE64 (c))
3441 return -1;
3442 value |= base64_char_to_value[c] << 12;
3444 c = (unsigned char) (value >> 16);
3445 if (multibyte && c >= 128)
3446 e += BYTE8_STRING (c, e);
3447 else
3448 *e++ = c;
3449 nchars++;
3451 /* Process third byte of a quadruplet. */
3453 READ_QUADRUPLET_BYTE (-1);
3455 if (c == '=')
3457 READ_QUADRUPLET_BYTE (-1);
3459 if (c != '=')
3460 return -1;
3461 continue;
3464 if (!IS_BASE64 (c))
3465 return -1;
3466 value |= base64_char_to_value[c] << 6;
3468 c = (unsigned char) (0xff & value >> 8);
3469 if (multibyte && c >= 128)
3470 e += BYTE8_STRING (c, e);
3471 else
3472 *e++ = c;
3473 nchars++;
3475 /* Process fourth byte of a quadruplet. */
3477 READ_QUADRUPLET_BYTE (-1);
3479 if (c == '=')
3480 continue;
3482 if (!IS_BASE64 (c))
3483 return -1;
3484 value |= base64_char_to_value[c];
3486 c = (unsigned char) (0xff & value);
3487 if (multibyte && c >= 128)
3488 e += BYTE8_STRING (c, e);
3489 else
3490 *e++ = c;
3491 nchars++;
3497 /***********************************************************************
3498 ***** *****
3499 ***** Hash Tables *****
3500 ***** *****
3501 ***********************************************************************/
3503 /* Implemented by gerd@gnu.org. This hash table implementation was
3504 inspired by CMUCL hash tables. */
3506 /* Ideas:
3508 1. For small tables, association lists are probably faster than
3509 hash tables because they have lower overhead.
3511 For uses of hash tables where the O(1) behavior of table
3512 operations is not a requirement, it might therefore be a good idea
3513 not to hash. Instead, we could just do a linear search in the
3514 key_and_value vector of the hash table. This could be done
3515 if a `:linear-search t' argument is given to make-hash-table. */
3518 /* The list of all weak hash tables. Don't staticpro this one. */
3520 struct Lisp_Hash_Table *weak_hash_tables;
3522 /* Various symbols. */
3524 Lisp_Object Qhash_table_p, Qeq, Qeql, Qequal, Qkey, Qvalue;
3525 Lisp_Object QCtest, QCsize, QCrehash_size, QCrehash_threshold, QCweakness;
3526 Lisp_Object Qhash_table_test, Qkey_or_value, Qkey_and_value;
3528 /* Function prototypes. */
3530 static struct Lisp_Hash_Table *check_hash_table (Lisp_Object);
3531 static int get_key_arg (Lisp_Object, int, Lisp_Object *, char *);
3532 static void maybe_resize_hash_table (struct Lisp_Hash_Table *);
3533 static int cmpfn_eql (struct Lisp_Hash_Table *, Lisp_Object, unsigned,
3534 Lisp_Object, unsigned);
3535 static int cmpfn_equal (struct Lisp_Hash_Table *, Lisp_Object, unsigned,
3536 Lisp_Object, unsigned);
3537 static int cmpfn_user_defined (struct Lisp_Hash_Table *, Lisp_Object,
3538 unsigned, Lisp_Object, unsigned);
3539 static unsigned hashfn_eq (struct Lisp_Hash_Table *, Lisp_Object);
3540 static unsigned hashfn_eql (struct Lisp_Hash_Table *, Lisp_Object);
3541 static unsigned hashfn_equal (struct Lisp_Hash_Table *, Lisp_Object);
3542 static unsigned hashfn_user_defined (struct Lisp_Hash_Table *,
3543 Lisp_Object);
3544 static unsigned sxhash_string (unsigned char *, int);
3545 static unsigned sxhash_list (Lisp_Object, int);
3546 static unsigned sxhash_vector (Lisp_Object, int);
3547 static unsigned sxhash_bool_vector (Lisp_Object);
3548 static int sweep_weak_table (struct Lisp_Hash_Table *, int);
3552 /***********************************************************************
3553 Utilities
3554 ***********************************************************************/
3556 /* If OBJ is a Lisp hash table, return a pointer to its struct
3557 Lisp_Hash_Table. Otherwise, signal an error. */
3559 static struct Lisp_Hash_Table *
3560 check_hash_table (Lisp_Object obj)
3562 CHECK_HASH_TABLE (obj);
3563 return XHASH_TABLE (obj);
3567 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3568 number. */
3571 next_almost_prime (int n)
3573 if (n % 2 == 0)
3574 n += 1;
3575 if (n % 3 == 0)
3576 n += 2;
3577 if (n % 7 == 0)
3578 n += 4;
3579 return n;
3583 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3584 which USED[I] is non-zero. If found at index I in ARGS, set
3585 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3586 -1. This function is used to extract a keyword/argument pair from
3587 a DEFUN parameter list. */
3589 static int
3590 get_key_arg (Lisp_Object key, int nargs, Lisp_Object *args, char *used)
3592 int i;
3594 for (i = 0; i < nargs - 1; ++i)
3595 if (!used[i] && EQ (args[i], key))
3596 break;
3598 if (i >= nargs - 1)
3599 i = -1;
3600 else
3602 used[i++] = 1;
3603 used[i] = 1;
3606 return i;
3610 /* Return a Lisp vector which has the same contents as VEC but has
3611 size NEW_SIZE, NEW_SIZE >= VEC->size. Entries in the resulting
3612 vector that are not copied from VEC are set to INIT. */
3614 Lisp_Object
3615 larger_vector (Lisp_Object vec, int new_size, Lisp_Object init)
3617 struct Lisp_Vector *v;
3618 int i, old_size;
3620 xassert (VECTORP (vec));
3621 old_size = ASIZE (vec);
3622 xassert (new_size >= old_size);
3624 v = allocate_vector (new_size);
3625 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3626 for (i = old_size; i < new_size; ++i)
3627 v->contents[i] = init;
3628 XSETVECTOR (vec, v);
3629 return vec;
3633 /***********************************************************************
3634 Low-level Functions
3635 ***********************************************************************/
3637 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3638 HASH2 in hash table H using `eql'. Value is non-zero if KEY1 and
3639 KEY2 are the same. */
3641 static int
3642 cmpfn_eql (struct Lisp_Hash_Table *h, Lisp_Object key1, unsigned int hash1, Lisp_Object key2, unsigned int hash2)
3644 return (FLOATP (key1)
3645 && FLOATP (key2)
3646 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3650 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3651 HASH2 in hash table H using `equal'. Value is non-zero if KEY1 and
3652 KEY2 are the same. */
3654 static int
3655 cmpfn_equal (struct Lisp_Hash_Table *h, Lisp_Object key1, unsigned int hash1, Lisp_Object key2, unsigned int hash2)
3657 return hash1 == hash2 && !NILP (Fequal (key1, key2));
3661 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3662 HASH2 in hash table H using H->user_cmp_function. Value is non-zero
3663 if KEY1 and KEY2 are the same. */
3665 static int
3666 cmpfn_user_defined (struct Lisp_Hash_Table *h, Lisp_Object key1, unsigned int hash1, Lisp_Object key2, unsigned int hash2)
3668 if (hash1 == hash2)
3670 Lisp_Object args[3];
3672 args[0] = h->user_cmp_function;
3673 args[1] = key1;
3674 args[2] = key2;
3675 return !NILP (Ffuncall (3, args));
3677 else
3678 return 0;
3682 /* Value is a hash code for KEY for use in hash table H which uses
3683 `eq' to compare keys. The hash code returned is guaranteed to fit
3684 in a Lisp integer. */
3686 static unsigned
3687 hashfn_eq (struct Lisp_Hash_Table *h, Lisp_Object key)
3689 unsigned hash = XUINT (key) ^ XTYPE (key);
3690 xassert ((hash & ~INTMASK) == 0);
3691 return hash;
3695 /* Value is a hash code for KEY for use in hash table H which uses
3696 `eql' to compare keys. The hash code returned is guaranteed to fit
3697 in a Lisp integer. */
3699 static unsigned
3700 hashfn_eql (struct Lisp_Hash_Table *h, Lisp_Object key)
3702 unsigned hash;
3703 if (FLOATP (key))
3704 hash = sxhash (key, 0);
3705 else
3706 hash = XUINT (key) ^ XTYPE (key);
3707 xassert ((hash & ~INTMASK) == 0);
3708 return hash;
3712 /* Value is a hash code for KEY for use in hash table H which uses
3713 `equal' to compare keys. The hash code returned is guaranteed to fit
3714 in a Lisp integer. */
3716 static unsigned
3717 hashfn_equal (struct Lisp_Hash_Table *h, Lisp_Object key)
3719 unsigned hash = sxhash (key, 0);
3720 xassert ((hash & ~INTMASK) == 0);
3721 return hash;
3725 /* Value is a hash code for KEY for use in hash table H which uses as
3726 user-defined function to compare keys. The hash code returned is
3727 guaranteed to fit in a Lisp integer. */
3729 static unsigned
3730 hashfn_user_defined (struct Lisp_Hash_Table *h, Lisp_Object key)
3732 Lisp_Object args[2], hash;
3734 args[0] = h->user_hash_function;
3735 args[1] = key;
3736 hash = Ffuncall (2, args);
3737 if (!INTEGERP (hash))
3738 signal_error ("Invalid hash code returned from user-supplied hash function", hash);
3739 return XUINT (hash);
3743 /* Create and initialize a new hash table.
3745 TEST specifies the test the hash table will use to compare keys.
3746 It must be either one of the predefined tests `eq', `eql' or
3747 `equal' or a symbol denoting a user-defined test named TEST with
3748 test and hash functions USER_TEST and USER_HASH.
3750 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3752 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3753 new size when it becomes full is computed by adding REHASH_SIZE to
3754 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3755 table's new size is computed by multiplying its old size with
3756 REHASH_SIZE.
3758 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3759 be resized when the ratio of (number of entries in the table) /
3760 (table size) is >= REHASH_THRESHOLD.
3762 WEAK specifies the weakness of the table. If non-nil, it must be
3763 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
3765 Lisp_Object
3766 make_hash_table (test, size, rehash_size, rehash_threshold, weak,
3767 user_test, user_hash)
3768 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
3769 Lisp_Object user_test, user_hash;
3771 struct Lisp_Hash_Table *h;
3772 Lisp_Object table;
3773 int index_size, i, sz;
3775 /* Preconditions. */
3776 xassert (SYMBOLP (test));
3777 xassert (INTEGERP (size) && XINT (size) >= 0);
3778 xassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3779 || (FLOATP (rehash_size) && XFLOATINT (rehash_size) > 1.0));
3780 xassert (FLOATP (rehash_threshold)
3781 && XFLOATINT (rehash_threshold) > 0
3782 && XFLOATINT (rehash_threshold) <= 1.0);
3784 if (XFASTINT (size) == 0)
3785 size = make_number (1);
3787 /* Allocate a table and initialize it. */
3788 h = allocate_hash_table ();
3790 /* Initialize hash table slots. */
3791 sz = XFASTINT (size);
3793 h->test = test;
3794 if (EQ (test, Qeql))
3796 h->cmpfn = cmpfn_eql;
3797 h->hashfn = hashfn_eql;
3799 else if (EQ (test, Qeq))
3801 h->cmpfn = NULL;
3802 h->hashfn = hashfn_eq;
3804 else if (EQ (test, Qequal))
3806 h->cmpfn = cmpfn_equal;
3807 h->hashfn = hashfn_equal;
3809 else
3811 h->user_cmp_function = user_test;
3812 h->user_hash_function = user_hash;
3813 h->cmpfn = cmpfn_user_defined;
3814 h->hashfn = hashfn_user_defined;
3817 h->weak = weak;
3818 h->rehash_threshold = rehash_threshold;
3819 h->rehash_size = rehash_size;
3820 h->count = 0;
3821 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
3822 h->hash = Fmake_vector (size, Qnil);
3823 h->next = Fmake_vector (size, Qnil);
3824 /* Cast to int here avoids losing with gcc 2.95 on Tru64/Alpha... */
3825 index_size = next_almost_prime ((int) (sz / XFLOATINT (rehash_threshold)));
3826 h->index = Fmake_vector (make_number (index_size), Qnil);
3828 /* Set up the free list. */
3829 for (i = 0; i < sz - 1; ++i)
3830 HASH_NEXT (h, i) = make_number (i + 1);
3831 h->next_free = make_number (0);
3833 XSET_HASH_TABLE (table, h);
3834 xassert (HASH_TABLE_P (table));
3835 xassert (XHASH_TABLE (table) == h);
3837 /* Maybe add this hash table to the list of all weak hash tables. */
3838 if (NILP (h->weak))
3839 h->next_weak = NULL;
3840 else
3842 h->next_weak = weak_hash_tables;
3843 weak_hash_tables = h;
3846 return table;
3850 /* Return a copy of hash table H1. Keys and values are not copied,
3851 only the table itself is. */
3853 Lisp_Object
3854 copy_hash_table (struct Lisp_Hash_Table *h1)
3856 Lisp_Object table;
3857 struct Lisp_Hash_Table *h2;
3858 struct Lisp_Vector *next;
3860 h2 = allocate_hash_table ();
3861 next = h2->vec_next;
3862 memcpy (h2, h1, sizeof *h2);
3863 h2->vec_next = next;
3864 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3865 h2->hash = Fcopy_sequence (h1->hash);
3866 h2->next = Fcopy_sequence (h1->next);
3867 h2->index = Fcopy_sequence (h1->index);
3868 XSET_HASH_TABLE (table, h2);
3870 /* Maybe add this hash table to the list of all weak hash tables. */
3871 if (!NILP (h2->weak))
3873 h2->next_weak = weak_hash_tables;
3874 weak_hash_tables = h2;
3877 return table;
3881 /* Resize hash table H if it's too full. If H cannot be resized
3882 because it's already too large, throw an error. */
3884 static INLINE void
3885 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3887 if (NILP (h->next_free))
3889 int old_size = HASH_TABLE_SIZE (h);
3890 int i, new_size, index_size;
3891 EMACS_INT nsize;
3893 if (INTEGERP (h->rehash_size))
3894 new_size = old_size + XFASTINT (h->rehash_size);
3895 else
3896 new_size = old_size * XFLOATINT (h->rehash_size);
3897 new_size = max (old_size + 1, new_size);
3898 index_size = next_almost_prime ((int)
3899 (new_size
3900 / XFLOATINT (h->rehash_threshold)));
3901 /* Assignment to EMACS_INT stops GCC whining about limited range
3902 of data type. */
3903 nsize = max (index_size, 2 * new_size);
3904 if (nsize > MOST_POSITIVE_FIXNUM)
3905 error ("Hash table too large to resize");
3907 h->key_and_value = larger_vector (h->key_and_value, 2 * new_size, Qnil);
3908 h->next = larger_vector (h->next, new_size, Qnil);
3909 h->hash = larger_vector (h->hash, new_size, Qnil);
3910 h->index = Fmake_vector (make_number (index_size), Qnil);
3912 /* Update the free list. Do it so that new entries are added at
3913 the end of the free list. This makes some operations like
3914 maphash faster. */
3915 for (i = old_size; i < new_size - 1; ++i)
3916 HASH_NEXT (h, i) = make_number (i + 1);
3918 if (!NILP (h->next_free))
3920 Lisp_Object last, next;
3922 last = h->next_free;
3923 while (next = HASH_NEXT (h, XFASTINT (last)),
3924 !NILP (next))
3925 last = next;
3927 HASH_NEXT (h, XFASTINT (last)) = make_number (old_size);
3929 else
3930 XSETFASTINT (h->next_free, old_size);
3932 /* Rehash. */
3933 for (i = 0; i < old_size; ++i)
3934 if (!NILP (HASH_HASH (h, i)))
3936 unsigned hash_code = XUINT (HASH_HASH (h, i));
3937 int start_of_bucket = hash_code % ASIZE (h->index);
3938 HASH_NEXT (h, i) = HASH_INDEX (h, start_of_bucket);
3939 HASH_INDEX (h, start_of_bucket) = make_number (i);
3945 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
3946 the hash code of KEY. Value is the index of the entry in H
3947 matching KEY, or -1 if not found. */
3950 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, unsigned int *hash)
3952 unsigned hash_code;
3953 int start_of_bucket;
3954 Lisp_Object idx;
3956 hash_code = h->hashfn (h, key);
3957 if (hash)
3958 *hash = hash_code;
3960 start_of_bucket = hash_code % ASIZE (h->index);
3961 idx = HASH_INDEX (h, start_of_bucket);
3963 /* We need not gcpro idx since it's either an integer or nil. */
3964 while (!NILP (idx))
3966 int i = XFASTINT (idx);
3967 if (EQ (key, HASH_KEY (h, i))
3968 || (h->cmpfn
3969 && h->cmpfn (h, key, hash_code,
3970 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
3971 break;
3972 idx = HASH_NEXT (h, i);
3975 return NILP (idx) ? -1 : XFASTINT (idx);
3979 /* Put an entry into hash table H that associates KEY with VALUE.
3980 HASH is a previously computed hash code of KEY.
3981 Value is the index of the entry in H matching KEY. */
3984 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value, unsigned int hash)
3986 int start_of_bucket, i;
3988 xassert ((hash & ~INTMASK) == 0);
3990 /* Increment count after resizing because resizing may fail. */
3991 maybe_resize_hash_table (h);
3992 h->count++;
3994 /* Store key/value in the key_and_value vector. */
3995 i = XFASTINT (h->next_free);
3996 h->next_free = HASH_NEXT (h, i);
3997 HASH_KEY (h, i) = key;
3998 HASH_VALUE (h, i) = value;
4000 /* Remember its hash code. */
4001 HASH_HASH (h, i) = make_number (hash);
4003 /* Add new entry to its collision chain. */
4004 start_of_bucket = hash % ASIZE (h->index);
4005 HASH_NEXT (h, i) = HASH_INDEX (h, start_of_bucket);
4006 HASH_INDEX (h, start_of_bucket) = make_number (i);
4007 return i;
4011 /* Remove the entry matching KEY from hash table H, if there is one. */
4013 static void
4014 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
4016 unsigned hash_code;
4017 int start_of_bucket;
4018 Lisp_Object idx, prev;
4020 hash_code = h->hashfn (h, key);
4021 start_of_bucket = hash_code % ASIZE (h->index);
4022 idx = HASH_INDEX (h, start_of_bucket);
4023 prev = Qnil;
4025 /* We need not gcpro idx, prev since they're either integers or nil. */
4026 while (!NILP (idx))
4028 int i = XFASTINT (idx);
4030 if (EQ (key, HASH_KEY (h, i))
4031 || (h->cmpfn
4032 && h->cmpfn (h, key, hash_code,
4033 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
4035 /* Take entry out of collision chain. */
4036 if (NILP (prev))
4037 HASH_INDEX (h, start_of_bucket) = HASH_NEXT (h, i);
4038 else
4039 HASH_NEXT (h, XFASTINT (prev)) = HASH_NEXT (h, i);
4041 /* Clear slots in key_and_value and add the slots to
4042 the free list. */
4043 HASH_KEY (h, i) = HASH_VALUE (h, i) = HASH_HASH (h, i) = Qnil;
4044 HASH_NEXT (h, i) = h->next_free;
4045 h->next_free = make_number (i);
4046 h->count--;
4047 xassert (h->count >= 0);
4048 break;
4050 else
4052 prev = idx;
4053 idx = HASH_NEXT (h, i);
4059 /* Clear hash table H. */
4061 void
4062 hash_clear (struct Lisp_Hash_Table *h)
4064 if (h->count > 0)
4066 int i, size = HASH_TABLE_SIZE (h);
4068 for (i = 0; i < size; ++i)
4070 HASH_NEXT (h, i) = i < size - 1 ? make_number (i + 1) : Qnil;
4071 HASH_KEY (h, i) = Qnil;
4072 HASH_VALUE (h, i) = Qnil;
4073 HASH_HASH (h, i) = Qnil;
4076 for (i = 0; i < ASIZE (h->index); ++i)
4077 ASET (h->index, i, Qnil);
4079 h->next_free = make_number (0);
4080 h->count = 0;
4086 /************************************************************************
4087 Weak Hash Tables
4088 ************************************************************************/
4090 void
4091 init_weak_hash_tables (void)
4093 weak_hash_tables = NULL;
4096 /* Sweep weak hash table H. REMOVE_ENTRIES_P non-zero means remove
4097 entries from the table that don't survive the current GC.
4098 REMOVE_ENTRIES_P zero means mark entries that are in use. Value is
4099 non-zero if anything was marked. */
4101 static int
4102 sweep_weak_table (struct Lisp_Hash_Table *h, int remove_entries_p)
4104 int bucket, n, marked;
4106 n = ASIZE (h->index) & ~ARRAY_MARK_FLAG;
4107 marked = 0;
4109 for (bucket = 0; bucket < n; ++bucket)
4111 Lisp_Object idx, next, prev;
4113 /* Follow collision chain, removing entries that
4114 don't survive this garbage collection. */
4115 prev = Qnil;
4116 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
4118 int i = XFASTINT (idx);
4119 int key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
4120 int value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
4121 int remove_p;
4123 if (EQ (h->weak, Qkey))
4124 remove_p = !key_known_to_survive_p;
4125 else if (EQ (h->weak, Qvalue))
4126 remove_p = !value_known_to_survive_p;
4127 else if (EQ (h->weak, Qkey_or_value))
4128 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
4129 else if (EQ (h->weak, Qkey_and_value))
4130 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
4131 else
4132 abort ();
4134 next = HASH_NEXT (h, i);
4136 if (remove_entries_p)
4138 if (remove_p)
4140 /* Take out of collision chain. */
4141 if (NILP (prev))
4142 HASH_INDEX (h, bucket) = next;
4143 else
4144 HASH_NEXT (h, XFASTINT (prev)) = next;
4146 /* Add to free list. */
4147 HASH_NEXT (h, i) = h->next_free;
4148 h->next_free = idx;
4150 /* Clear key, value, and hash. */
4151 HASH_KEY (h, i) = HASH_VALUE (h, i) = Qnil;
4152 HASH_HASH (h, i) = Qnil;
4154 h->count--;
4156 else
4158 prev = idx;
4161 else
4163 if (!remove_p)
4165 /* Make sure key and value survive. */
4166 if (!key_known_to_survive_p)
4168 mark_object (HASH_KEY (h, i));
4169 marked = 1;
4172 if (!value_known_to_survive_p)
4174 mark_object (HASH_VALUE (h, i));
4175 marked = 1;
4182 return marked;
4185 /* Remove elements from weak hash tables that don't survive the
4186 current garbage collection. Remove weak tables that don't survive
4187 from Vweak_hash_tables. Called from gc_sweep. */
4189 void
4190 sweep_weak_hash_tables (void)
4192 struct Lisp_Hash_Table *h, *used, *next;
4193 int marked;
4195 /* Mark all keys and values that are in use. Keep on marking until
4196 there is no more change. This is necessary for cases like
4197 value-weak table A containing an entry X -> Y, where Y is used in a
4198 key-weak table B, Z -> Y. If B comes after A in the list of weak
4199 tables, X -> Y might be removed from A, although when looking at B
4200 one finds that it shouldn't. */
4203 marked = 0;
4204 for (h = weak_hash_tables; h; h = h->next_weak)
4206 if (h->size & ARRAY_MARK_FLAG)
4207 marked |= sweep_weak_table (h, 0);
4210 while (marked);
4212 /* Remove tables and entries that aren't used. */
4213 for (h = weak_hash_tables, used = NULL; h; h = next)
4215 next = h->next_weak;
4217 if (h->size & ARRAY_MARK_FLAG)
4219 /* TABLE is marked as used. Sweep its contents. */
4220 if (h->count > 0)
4221 sweep_weak_table (h, 1);
4223 /* Add table to the list of used weak hash tables. */
4224 h->next_weak = used;
4225 used = h;
4229 weak_hash_tables = used;
4234 /***********************************************************************
4235 Hash Code Computation
4236 ***********************************************************************/
4238 /* Maximum depth up to which to dive into Lisp structures. */
4240 #define SXHASH_MAX_DEPTH 3
4242 /* Maximum length up to which to take list and vector elements into
4243 account. */
4245 #define SXHASH_MAX_LEN 7
4247 /* Combine two integers X and Y for hashing. */
4249 #define SXHASH_COMBINE(X, Y) \
4250 ((((unsigned)(X) << 4) + (((unsigned)(X) >> 24) & 0x0fffffff)) \
4251 + (unsigned)(Y))
4254 /* Return a hash for string PTR which has length LEN. The hash
4255 code returned is guaranteed to fit in a Lisp integer. */
4257 static unsigned
4258 sxhash_string (unsigned char *ptr, int len)
4260 unsigned char *p = ptr;
4261 unsigned char *end = p + len;
4262 unsigned char c;
4263 unsigned hash = 0;
4265 while (p != end)
4267 c = *p++;
4268 if (c >= 0140)
4269 c -= 40;
4270 hash = ((hash << 4) + (hash >> 28) + c);
4273 return hash & INTMASK;
4277 /* Return a hash for list LIST. DEPTH is the current depth in the
4278 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4280 static unsigned
4281 sxhash_list (Lisp_Object list, int depth)
4283 unsigned hash = 0;
4284 int i;
4286 if (depth < SXHASH_MAX_DEPTH)
4287 for (i = 0;
4288 CONSP (list) && i < SXHASH_MAX_LEN;
4289 list = XCDR (list), ++i)
4291 unsigned hash2 = sxhash (XCAR (list), depth + 1);
4292 hash = SXHASH_COMBINE (hash, hash2);
4295 if (!NILP (list))
4297 unsigned hash2 = sxhash (list, depth + 1);
4298 hash = SXHASH_COMBINE (hash, hash2);
4301 return hash;
4305 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4306 the Lisp structure. */
4308 static unsigned
4309 sxhash_vector (Lisp_Object vec, int depth)
4311 unsigned hash = ASIZE (vec);
4312 int i, n;
4314 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4315 for (i = 0; i < n; ++i)
4317 unsigned hash2 = sxhash (AREF (vec, i), depth + 1);
4318 hash = SXHASH_COMBINE (hash, hash2);
4321 return hash;
4325 /* Return a hash for bool-vector VECTOR. */
4327 static unsigned
4328 sxhash_bool_vector (Lisp_Object vec)
4330 unsigned hash = XBOOL_VECTOR (vec)->size;
4331 int i, n;
4333 n = min (SXHASH_MAX_LEN, XBOOL_VECTOR (vec)->vector_size);
4334 for (i = 0; i < n; ++i)
4335 hash = SXHASH_COMBINE (hash, XBOOL_VECTOR (vec)->data[i]);
4337 return hash;
4341 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4342 structure. Value is an unsigned integer clipped to INTMASK. */
4344 unsigned
4345 sxhash (Lisp_Object obj, int depth)
4347 unsigned hash;
4349 if (depth > SXHASH_MAX_DEPTH)
4350 return 0;
4352 switch (XTYPE (obj))
4354 case_Lisp_Int:
4355 hash = XUINT (obj);
4356 break;
4358 case Lisp_Misc:
4359 hash = XUINT (obj);
4360 break;
4362 case Lisp_Symbol:
4363 obj = SYMBOL_NAME (obj);
4364 /* Fall through. */
4366 case Lisp_String:
4367 hash = sxhash_string (SDATA (obj), SCHARS (obj));
4368 break;
4370 /* This can be everything from a vector to an overlay. */
4371 case Lisp_Vectorlike:
4372 if (VECTORP (obj))
4373 /* According to the CL HyperSpec, two arrays are equal only if
4374 they are `eq', except for strings and bit-vectors. In
4375 Emacs, this works differently. We have to compare element
4376 by element. */
4377 hash = sxhash_vector (obj, depth);
4378 else if (BOOL_VECTOR_P (obj))
4379 hash = sxhash_bool_vector (obj);
4380 else
4381 /* Others are `equal' if they are `eq', so let's take their
4382 address as hash. */
4383 hash = XUINT (obj);
4384 break;
4386 case Lisp_Cons:
4387 hash = sxhash_list (obj, depth);
4388 break;
4390 case Lisp_Float:
4392 double val = XFLOAT_DATA (obj);
4393 unsigned char *p = (unsigned char *) &val;
4394 unsigned char *e = p + sizeof val;
4395 for (hash = 0; p < e; ++p)
4396 hash = SXHASH_COMBINE (hash, *p);
4397 break;
4400 default:
4401 abort ();
4404 return hash & INTMASK;
4409 /***********************************************************************
4410 Lisp Interface
4411 ***********************************************************************/
4414 DEFUN ("sxhash", Fsxhash, Ssxhash, 1, 1, 0,
4415 doc: /* Compute a hash code for OBJ and return it as integer. */)
4416 (Lisp_Object obj)
4418 unsigned hash = sxhash (obj, 0);
4419 return make_number (hash);
4423 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4424 doc: /* Create and return a new hash table.
4426 Arguments are specified as keyword/argument pairs. The following
4427 arguments are defined:
4429 :test TEST -- TEST must be a symbol that specifies how to compare
4430 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4431 `equal'. User-supplied test and hash functions can be specified via
4432 `define-hash-table-test'.
4434 :size SIZE -- A hint as to how many elements will be put in the table.
4435 Default is 65.
4437 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4438 fills up. If REHASH-SIZE is an integer, add that many space. If it
4439 is a float, it must be > 1.0, and the new size is computed by
4440 multiplying the old size with that factor. Default is 1.5.
4442 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4443 Resize the hash table when ratio of the number of entries in the
4444 table. Default is 0.8.
4446 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4447 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4448 returned is a weak table. Key/value pairs are removed from a weak
4449 hash table when there are no non-weak references pointing to their
4450 key, value, one of key or value, or both key and value, depending on
4451 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4452 is nil.
4454 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4455 (int nargs, Lisp_Object *args)
4457 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4458 Lisp_Object user_test, user_hash;
4459 char *used;
4460 int i;
4462 /* The vector `used' is used to keep track of arguments that
4463 have been consumed. */
4464 used = (char *) alloca (nargs * sizeof *used);
4465 memset (used, 0, nargs * sizeof *used);
4467 /* See if there's a `:test TEST' among the arguments. */
4468 i = get_key_arg (QCtest, nargs, args, used);
4469 test = i < 0 ? Qeql : args[i];
4470 if (!EQ (test, Qeq) && !EQ (test, Qeql) && !EQ (test, Qequal))
4472 /* See if it is a user-defined test. */
4473 Lisp_Object prop;
4475 prop = Fget (test, Qhash_table_test);
4476 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4477 signal_error ("Invalid hash table test", test);
4478 user_test = XCAR (prop);
4479 user_hash = XCAR (XCDR (prop));
4481 else
4482 user_test = user_hash = Qnil;
4484 /* See if there's a `:size SIZE' argument. */
4485 i = get_key_arg (QCsize, nargs, args, used);
4486 size = i < 0 ? Qnil : args[i];
4487 if (NILP (size))
4488 size = make_number (DEFAULT_HASH_SIZE);
4489 else if (!INTEGERP (size) || XINT (size) < 0)
4490 signal_error ("Invalid hash table size", size);
4492 /* Look for `:rehash-size SIZE'. */
4493 i = get_key_arg (QCrehash_size, nargs, args, used);
4494 rehash_size = i < 0 ? make_float (DEFAULT_REHASH_SIZE) : args[i];
4495 if (!NUMBERP (rehash_size)
4496 || (INTEGERP (rehash_size) && XINT (rehash_size) <= 0)
4497 || XFLOATINT (rehash_size) <= 1.0)
4498 signal_error ("Invalid hash table rehash size", rehash_size);
4500 /* Look for `:rehash-threshold THRESHOLD'. */
4501 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4502 rehash_threshold = i < 0 ? make_float (DEFAULT_REHASH_THRESHOLD) : args[i];
4503 if (!FLOATP (rehash_threshold)
4504 || XFLOATINT (rehash_threshold) <= 0.0
4505 || XFLOATINT (rehash_threshold) > 1.0)
4506 signal_error ("Invalid hash table rehash threshold", rehash_threshold);
4508 /* Look for `:weakness WEAK'. */
4509 i = get_key_arg (QCweakness, nargs, args, used);
4510 weak = i < 0 ? Qnil : args[i];
4511 if (EQ (weak, Qt))
4512 weak = Qkey_and_value;
4513 if (!NILP (weak)
4514 && !EQ (weak, Qkey)
4515 && !EQ (weak, Qvalue)
4516 && !EQ (weak, Qkey_or_value)
4517 && !EQ (weak, Qkey_and_value))
4518 signal_error ("Invalid hash table weakness", weak);
4520 /* Now, all args should have been used up, or there's a problem. */
4521 for (i = 0; i < nargs; ++i)
4522 if (!used[i])
4523 signal_error ("Invalid argument list", args[i]);
4525 return make_hash_table (test, size, rehash_size, rehash_threshold, weak,
4526 user_test, user_hash);
4530 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4531 doc: /* Return a copy of hash table TABLE. */)
4532 (Lisp_Object table)
4534 return copy_hash_table (check_hash_table (table));
4538 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4539 doc: /* Return the number of elements in TABLE. */)
4540 (Lisp_Object table)
4542 return make_number (check_hash_table (table)->count);
4546 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4547 Shash_table_rehash_size, 1, 1, 0,
4548 doc: /* Return the current rehash size of TABLE. */)
4549 (Lisp_Object table)
4551 return check_hash_table (table)->rehash_size;
4555 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4556 Shash_table_rehash_threshold, 1, 1, 0,
4557 doc: /* Return the current rehash threshold of TABLE. */)
4558 (Lisp_Object table)
4560 return check_hash_table (table)->rehash_threshold;
4564 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4565 doc: /* Return the size of TABLE.
4566 The size can be used as an argument to `make-hash-table' to create
4567 a hash table than can hold as many elements of TABLE holds
4568 without need for resizing. */)
4569 (Lisp_Object table)
4571 struct Lisp_Hash_Table *h = check_hash_table (table);
4572 return make_number (HASH_TABLE_SIZE (h));
4576 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4577 doc: /* Return the test TABLE uses. */)
4578 (Lisp_Object table)
4580 return check_hash_table (table)->test;
4584 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4585 1, 1, 0,
4586 doc: /* Return the weakness of TABLE. */)
4587 (Lisp_Object table)
4589 return check_hash_table (table)->weak;
4593 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4594 doc: /* Return t if OBJ is a Lisp hash table object. */)
4595 (Lisp_Object obj)
4597 return HASH_TABLE_P (obj) ? Qt : Qnil;
4601 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4602 doc: /* Clear hash table TABLE and return it. */)
4603 (Lisp_Object table)
4605 hash_clear (check_hash_table (table));
4606 /* Be compatible with XEmacs. */
4607 return table;
4611 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4612 doc: /* Look up KEY in TABLE and return its associated value.
4613 If KEY is not found, return DFLT which defaults to nil. */)
4614 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4616 struct Lisp_Hash_Table *h = check_hash_table (table);
4617 int i = hash_lookup (h, key, NULL);
4618 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4622 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4623 doc: /* Associate KEY with VALUE in hash table TABLE.
4624 If KEY is already present in table, replace its current value with
4625 VALUE. */)
4626 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4628 struct Lisp_Hash_Table *h = check_hash_table (table);
4629 int i;
4630 unsigned hash;
4632 i = hash_lookup (h, key, &hash);
4633 if (i >= 0)
4634 HASH_VALUE (h, i) = value;
4635 else
4636 hash_put (h, key, value, hash);
4638 return value;
4642 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4643 doc: /* Remove KEY from TABLE. */)
4644 (Lisp_Object key, Lisp_Object table)
4646 struct Lisp_Hash_Table *h = check_hash_table (table);
4647 hash_remove_from_table (h, key);
4648 return Qnil;
4652 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4653 doc: /* Call FUNCTION for all entries in hash table TABLE.
4654 FUNCTION is called with two arguments, KEY and VALUE. */)
4655 (Lisp_Object function, Lisp_Object table)
4657 struct Lisp_Hash_Table *h = check_hash_table (table);
4658 Lisp_Object args[3];
4659 int i;
4661 for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
4662 if (!NILP (HASH_HASH (h, i)))
4664 args[0] = function;
4665 args[1] = HASH_KEY (h, i);
4666 args[2] = HASH_VALUE (h, i);
4667 Ffuncall (3, args);
4670 return Qnil;
4674 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4675 Sdefine_hash_table_test, 3, 3, 0,
4676 doc: /* Define a new hash table test with name NAME, a symbol.
4678 In hash tables created with NAME specified as test, use TEST to
4679 compare keys, and HASH for computing hash codes of keys.
4681 TEST must be a function taking two arguments and returning non-nil if
4682 both arguments are the same. HASH must be a function taking one
4683 argument and return an integer that is the hash code of the argument.
4684 Hash code computation should use the whole value range of integers,
4685 including negative integers. */)
4686 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4688 return Fput (name, Qhash_table_test, list2 (test, hash));
4693 /************************************************************************
4695 ************************************************************************/
4697 #include "md5.h"
4699 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
4700 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
4702 A message digest is a cryptographic checksum of a document, and the
4703 algorithm to calculate it is defined in RFC 1321.
4705 The two optional arguments START and END are character positions
4706 specifying for which part of OBJECT the message digest should be
4707 computed. If nil or omitted, the digest is computed for the whole
4708 OBJECT.
4710 The MD5 message digest is computed from the result of encoding the
4711 text in a coding system, not directly from the internal Emacs form of
4712 the text. The optional fourth argument CODING-SYSTEM specifies which
4713 coding system to encode the text with. It should be the same coding
4714 system that you used or will use when actually writing the text into a
4715 file.
4717 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
4718 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
4719 system would be chosen by default for writing this text into a file.
4721 If OBJECT is a string, the most preferred coding system (see the
4722 command `prefer-coding-system') is used.
4724 If NOERROR is non-nil, silently assume the `raw-text' coding if the
4725 guesswork fails. Normally, an error is signaled in such case. */)
4726 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
4728 unsigned char digest[16];
4729 unsigned char value[33];
4730 int i;
4731 int size;
4732 int size_byte = 0;
4733 int start_char = 0, end_char = 0;
4734 int start_byte = 0, end_byte = 0;
4735 register int b, e;
4736 register struct buffer *bp;
4737 int temp;
4739 if (STRINGP (object))
4741 if (NILP (coding_system))
4743 /* Decide the coding-system to encode the data with. */
4745 if (STRING_MULTIBYTE (object))
4746 /* use default, we can't guess correct value */
4747 coding_system = preferred_coding_system ();
4748 else
4749 coding_system = Qraw_text;
4752 if (NILP (Fcoding_system_p (coding_system)))
4754 /* Invalid coding system. */
4756 if (!NILP (noerror))
4757 coding_system = Qraw_text;
4758 else
4759 xsignal1 (Qcoding_system_error, coding_system);
4762 if (STRING_MULTIBYTE (object))
4763 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4765 size = SCHARS (object);
4766 size_byte = SBYTES (object);
4768 if (!NILP (start))
4770 CHECK_NUMBER (start);
4772 start_char = XINT (start);
4774 if (start_char < 0)
4775 start_char += size;
4777 start_byte = string_char_to_byte (object, start_char);
4780 if (NILP (end))
4782 end_char = size;
4783 end_byte = size_byte;
4785 else
4787 CHECK_NUMBER (end);
4789 end_char = XINT (end);
4791 if (end_char < 0)
4792 end_char += size;
4794 end_byte = string_char_to_byte (object, end_char);
4797 if (!(0 <= start_char && start_char <= end_char && end_char <= size))
4798 args_out_of_range_3 (object, make_number (start_char),
4799 make_number (end_char));
4801 else
4803 struct buffer *prev = current_buffer;
4805 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
4807 CHECK_BUFFER (object);
4809 bp = XBUFFER (object);
4810 if (bp != current_buffer)
4811 set_buffer_internal (bp);
4813 if (NILP (start))
4814 b = BEGV;
4815 else
4817 CHECK_NUMBER_COERCE_MARKER (start);
4818 b = XINT (start);
4821 if (NILP (end))
4822 e = ZV;
4823 else
4825 CHECK_NUMBER_COERCE_MARKER (end);
4826 e = XINT (end);
4829 if (b > e)
4830 temp = b, b = e, e = temp;
4832 if (!(BEGV <= b && e <= ZV))
4833 args_out_of_range (start, end);
4835 if (NILP (coding_system))
4837 /* Decide the coding-system to encode the data with.
4838 See fileio.c:Fwrite-region */
4840 if (!NILP (Vcoding_system_for_write))
4841 coding_system = Vcoding_system_for_write;
4842 else
4844 int force_raw_text = 0;
4846 coding_system = XBUFFER (object)->buffer_file_coding_system;
4847 if (NILP (coding_system)
4848 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4850 coding_system = Qnil;
4851 if (NILP (current_buffer->enable_multibyte_characters))
4852 force_raw_text = 1;
4855 if (NILP (coding_system) && !NILP (Fbuffer_file_name(object)))
4857 /* Check file-coding-system-alist. */
4858 Lisp_Object args[4], val;
4860 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4861 args[3] = Fbuffer_file_name(object);
4862 val = Ffind_operation_coding_system (4, args);
4863 if (CONSP (val) && !NILP (XCDR (val)))
4864 coding_system = XCDR (val);
4867 if (NILP (coding_system)
4868 && !NILP (XBUFFER (object)->buffer_file_coding_system))
4870 /* If we still have not decided a coding system, use the
4871 default value of buffer-file-coding-system. */
4872 coding_system = XBUFFER (object)->buffer_file_coding_system;
4875 if (!force_raw_text
4876 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4877 /* Confirm that VAL can surely encode the current region. */
4878 coding_system = call4 (Vselect_safe_coding_system_function,
4879 make_number (b), make_number (e),
4880 coding_system, Qnil);
4882 if (force_raw_text)
4883 coding_system = Qraw_text;
4886 if (NILP (Fcoding_system_p (coding_system)))
4888 /* Invalid coding system. */
4890 if (!NILP (noerror))
4891 coding_system = Qraw_text;
4892 else
4893 xsignal1 (Qcoding_system_error, coding_system);
4897 object = make_buffer_string (b, e, 0);
4898 if (prev != current_buffer)
4899 set_buffer_internal (prev);
4900 /* Discard the unwind protect for recovering the current
4901 buffer. */
4902 specpdl_ptr--;
4904 if (STRING_MULTIBYTE (object))
4905 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4908 md5_buffer (SDATA (object) + start_byte,
4909 SBYTES (object) - (size_byte - end_byte),
4910 digest);
4912 for (i = 0; i < 16; i++)
4913 sprintf (&value[2 * i], "%02x", digest[i]);
4914 value[32] = '\0';
4916 return make_string (value, 32);
4920 void
4921 syms_of_fns (void)
4923 /* Hash table stuff. */
4924 Qhash_table_p = intern_c_string ("hash-table-p");
4925 staticpro (&Qhash_table_p);
4926 Qeq = intern_c_string ("eq");
4927 staticpro (&Qeq);
4928 Qeql = intern_c_string ("eql");
4929 staticpro (&Qeql);
4930 Qequal = intern_c_string ("equal");
4931 staticpro (&Qequal);
4932 QCtest = intern_c_string (":test");
4933 staticpro (&QCtest);
4934 QCsize = intern_c_string (":size");
4935 staticpro (&QCsize);
4936 QCrehash_size = intern_c_string (":rehash-size");
4937 staticpro (&QCrehash_size);
4938 QCrehash_threshold = intern_c_string (":rehash-threshold");
4939 staticpro (&QCrehash_threshold);
4940 QCweakness = intern_c_string (":weakness");
4941 staticpro (&QCweakness);
4942 Qkey = intern_c_string ("key");
4943 staticpro (&Qkey);
4944 Qvalue = intern_c_string ("value");
4945 staticpro (&Qvalue);
4946 Qhash_table_test = intern_c_string ("hash-table-test");
4947 staticpro (&Qhash_table_test);
4948 Qkey_or_value = intern_c_string ("key-or-value");
4949 staticpro (&Qkey_or_value);
4950 Qkey_and_value = intern_c_string ("key-and-value");
4951 staticpro (&Qkey_and_value);
4953 defsubr (&Ssxhash);
4954 defsubr (&Smake_hash_table);
4955 defsubr (&Scopy_hash_table);
4956 defsubr (&Shash_table_count);
4957 defsubr (&Shash_table_rehash_size);
4958 defsubr (&Shash_table_rehash_threshold);
4959 defsubr (&Shash_table_size);
4960 defsubr (&Shash_table_test);
4961 defsubr (&Shash_table_weakness);
4962 defsubr (&Shash_table_p);
4963 defsubr (&Sclrhash);
4964 defsubr (&Sgethash);
4965 defsubr (&Sputhash);
4966 defsubr (&Sremhash);
4967 defsubr (&Smaphash);
4968 defsubr (&Sdefine_hash_table_test);
4970 Qstring_lessp = intern_c_string ("string-lessp");
4971 staticpro (&Qstring_lessp);
4972 Qprovide = intern_c_string ("provide");
4973 staticpro (&Qprovide);
4974 Qrequire = intern_c_string ("require");
4975 staticpro (&Qrequire);
4976 Qyes_or_no_p_history = intern_c_string ("yes-or-no-p-history");
4977 staticpro (&Qyes_or_no_p_history);
4978 Qcursor_in_echo_area = intern_c_string ("cursor-in-echo-area");
4979 staticpro (&Qcursor_in_echo_area);
4980 Qwidget_type = intern_c_string ("widget-type");
4981 staticpro (&Qwidget_type);
4983 staticpro (&string_char_byte_cache_string);
4984 string_char_byte_cache_string = Qnil;
4986 require_nesting_list = Qnil;
4987 staticpro (&require_nesting_list);
4989 Fset (Qyes_or_no_p_history, Qnil);
4991 DEFVAR_LISP ("features", &Vfeatures,
4992 doc: /* A list of symbols which are the features of the executing Emacs.
4993 Used by `featurep' and `require', and altered by `provide'. */);
4994 Vfeatures = Fcons (intern_c_string ("emacs"), Qnil);
4995 Qsubfeatures = intern_c_string ("subfeatures");
4996 staticpro (&Qsubfeatures);
4998 #ifdef HAVE_LANGINFO_CODESET
4999 Qcodeset = intern_c_string ("codeset");
5000 staticpro (&Qcodeset);
5001 Qdays = intern_c_string ("days");
5002 staticpro (&Qdays);
5003 Qmonths = intern_c_string ("months");
5004 staticpro (&Qmonths);
5005 Qpaper = intern_c_string ("paper");
5006 staticpro (&Qpaper);
5007 #endif /* HAVE_LANGINFO_CODESET */
5009 DEFVAR_BOOL ("use-dialog-box", &use_dialog_box,
5010 doc: /* *Non-nil means mouse commands use dialog boxes to ask questions.
5011 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
5012 invoked by mouse clicks and mouse menu items.
5014 On some platforms, file selection dialogs are also enabled if this is
5015 non-nil. */);
5016 use_dialog_box = 1;
5018 DEFVAR_BOOL ("use-file-dialog", &use_file_dialog,
5019 doc: /* *Non-nil means mouse commands use a file dialog to ask for files.
5020 This applies to commands from menus and tool bar buttons even when
5021 they are initiated from the keyboard. If `use-dialog-box' is nil,
5022 that disables the use of a file dialog, regardless of the value of
5023 this variable. */);
5024 use_file_dialog = 1;
5026 defsubr (&Sidentity);
5027 defsubr (&Srandom);
5028 defsubr (&Slength);
5029 defsubr (&Ssafe_length);
5030 defsubr (&Sstring_bytes);
5031 defsubr (&Sstring_equal);
5032 defsubr (&Scompare_strings);
5033 defsubr (&Sstring_lessp);
5034 defsubr (&Sappend);
5035 defsubr (&Sconcat);
5036 defsubr (&Svconcat);
5037 defsubr (&Scopy_sequence);
5038 defsubr (&Sstring_make_multibyte);
5039 defsubr (&Sstring_make_unibyte);
5040 defsubr (&Sstring_as_multibyte);
5041 defsubr (&Sstring_as_unibyte);
5042 defsubr (&Sstring_to_multibyte);
5043 defsubr (&Sstring_to_unibyte);
5044 defsubr (&Scopy_alist);
5045 defsubr (&Ssubstring);
5046 defsubr (&Ssubstring_no_properties);
5047 defsubr (&Snthcdr);
5048 defsubr (&Snth);
5049 defsubr (&Selt);
5050 defsubr (&Smember);
5051 defsubr (&Smemq);
5052 defsubr (&Smemql);
5053 defsubr (&Sassq);
5054 defsubr (&Sassoc);
5055 defsubr (&Srassq);
5056 defsubr (&Srassoc);
5057 defsubr (&Sdelq);
5058 defsubr (&Sdelete);
5059 defsubr (&Snreverse);
5060 defsubr (&Sreverse);
5061 defsubr (&Ssort);
5062 defsubr (&Splist_get);
5063 defsubr (&Sget);
5064 defsubr (&Splist_put);
5065 defsubr (&Sput);
5066 defsubr (&Slax_plist_get);
5067 defsubr (&Slax_plist_put);
5068 defsubr (&Seql);
5069 defsubr (&Sequal);
5070 defsubr (&Sequal_including_properties);
5071 defsubr (&Sfillarray);
5072 defsubr (&Sclear_string);
5073 defsubr (&Snconc);
5074 defsubr (&Smapcar);
5075 defsubr (&Smapc);
5076 defsubr (&Smapconcat);
5077 defsubr (&Sy_or_n_p);
5078 defsubr (&Syes_or_no_p);
5079 defsubr (&Sload_average);
5080 defsubr (&Sfeaturep);
5081 defsubr (&Srequire);
5082 defsubr (&Sprovide);
5083 defsubr (&Splist_member);
5084 defsubr (&Swidget_put);
5085 defsubr (&Swidget_get);
5086 defsubr (&Swidget_apply);
5087 defsubr (&Sbase64_encode_region);
5088 defsubr (&Sbase64_decode_region);
5089 defsubr (&Sbase64_encode_string);
5090 defsubr (&Sbase64_decode_string);
5091 defsubr (&Smd5);
5092 defsubr (&Slocale_info);
5096 void
5097 init_fns (void)
5101 /* arch-tag: 787f8219-5b74-46bd-8469-7e1cc475fa31
5102 (do not change this comment) */