src/ChangeLog: Add missing bug reference.
[emacs.git] / src / fns.c
blob63bcc9c86de7b99179bb4ec116b9d4a7b7bf00a2
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 Lisp_Object minibuf_window;
65 extern Lisp_Object Vlocale_coding_system;
66 extern int load_in_progress;
68 Lisp_Object Qstring_lessp, Qprovide, Qrequire;
69 Lisp_Object Qyes_or_no_p_history;
70 Lisp_Object Qcursor_in_echo_area;
71 Lisp_Object Qwidget_type;
72 Lisp_Object Qcodeset, Qdays, Qmonths, Qpaper;
74 extern Lisp_Object Qinput_method_function;
76 static int internal_equal (Lisp_Object , Lisp_Object, int, int);
78 extern long get_random (void);
79 extern void seed_random (long);
81 #ifndef HAVE_UNISTD_H
82 extern long time ();
83 #endif
85 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
86 doc: /* Return the argument unchanged. */)
87 (Lisp_Object arg)
89 return arg;
92 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
93 doc: /* Return a pseudo-random number.
94 All integers representable in Lisp are equally likely.
95 On most systems, this is 29 bits' worth.
96 With positive integer LIMIT, return random number in interval [0,LIMIT).
97 With argument t, set the random number seed from the current time and pid.
98 Other values of LIMIT are ignored. */)
99 (Lisp_Object limit)
101 EMACS_INT val;
102 Lisp_Object lispy_val;
103 unsigned long denominator;
105 if (EQ (limit, Qt))
106 seed_random (getpid () + time (NULL));
107 if (NATNUMP (limit) && XFASTINT (limit) != 0)
109 /* Try to take our random number from the higher bits of VAL,
110 not the lower, since (says Gentzel) the low bits of `random'
111 are less random than the higher ones. We do this by using the
112 quotient rather than the remainder. At the high end of the RNG
113 it's possible to get a quotient larger than n; discarding
114 these values eliminates the bias that would otherwise appear
115 when using a large n. */
116 denominator = ((unsigned long)1 << VALBITS) / XFASTINT (limit);
118 val = get_random () / denominator;
119 while (val >= XFASTINT (limit));
121 else
122 val = get_random ();
123 XSETINT (lispy_val, val);
124 return lispy_val;
127 /* Random data-structure functions */
129 DEFUN ("length", Flength, Slength, 1, 1, 0,
130 doc: /* Return the length of vector, list or string SEQUENCE.
131 A byte-code function object is also allowed.
132 If the string contains multibyte characters, this is not necessarily
133 the number of bytes in the string; it is the number of characters.
134 To get the number of bytes, use `string-bytes'. */)
135 (register Lisp_Object sequence)
137 register Lisp_Object val;
138 register int i;
140 if (STRINGP (sequence))
141 XSETFASTINT (val, SCHARS (sequence));
142 else if (VECTORP (sequence))
143 XSETFASTINT (val, ASIZE (sequence));
144 else if (CHAR_TABLE_P (sequence))
145 XSETFASTINT (val, MAX_CHAR);
146 else if (BOOL_VECTOR_P (sequence))
147 XSETFASTINT (val, XBOOL_VECTOR (sequence)->size);
148 else if (COMPILEDP (sequence))
149 XSETFASTINT (val, ASIZE (sequence) & PSEUDOVECTOR_SIZE_MASK);
150 else if (CONSP (sequence))
152 i = 0;
153 while (CONSP (sequence))
155 sequence = XCDR (sequence);
156 ++i;
158 if (!CONSP (sequence))
159 break;
161 sequence = XCDR (sequence);
162 ++i;
163 QUIT;
166 CHECK_LIST_END (sequence, sequence);
168 val = make_number (i);
170 else if (NILP (sequence))
171 XSETFASTINT (val, 0);
172 else
173 wrong_type_argument (Qsequencep, sequence);
175 return val;
178 /* This does not check for quits. That is safe since it must terminate. */
180 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
181 doc: /* Return the length of a list, but avoid error or infinite loop.
182 This function never gets an error. If LIST is not really a list,
183 it returns 0. If LIST is circular, it returns a finite value
184 which is at least the number of distinct elements. */)
185 (Lisp_Object list)
187 Lisp_Object tail, halftail, length;
188 int len = 0;
190 /* halftail is used to detect circular lists. */
191 halftail = list;
192 for (tail = list; CONSP (tail); tail = XCDR (tail))
194 if (EQ (tail, halftail) && len != 0)
195 break;
196 len++;
197 if ((len & 1) == 0)
198 halftail = XCDR (halftail);
201 XSETINT (length, len);
202 return length;
205 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
206 doc: /* Return the number of bytes in STRING.
207 If STRING is multibyte, this may be greater than the length of STRING. */)
208 (Lisp_Object string)
210 CHECK_STRING (string);
211 return make_number (SBYTES (string));
214 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
215 doc: /* Return t if two strings have identical contents.
216 Case is significant, but text properties are ignored.
217 Symbols are also allowed; their print names are used instead. */)
218 (register Lisp_Object s1, Lisp_Object s2)
220 if (SYMBOLP (s1))
221 s1 = SYMBOL_NAME (s1);
222 if (SYMBOLP (s2))
223 s2 = SYMBOL_NAME (s2);
224 CHECK_STRING (s1);
225 CHECK_STRING (s2);
227 if (SCHARS (s1) != SCHARS (s2)
228 || SBYTES (s1) != SBYTES (s2)
229 || memcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
230 return Qnil;
231 return Qt;
234 DEFUN ("compare-strings", Fcompare_strings,
235 Scompare_strings, 6, 7, 0,
236 doc: /* Compare the contents of two strings, converting to multibyte if needed.
237 In string STR1, skip the first START1 characters and stop at END1.
238 In string STR2, skip the first START2 characters and stop at END2.
239 END1 and END2 default to the full lengths of the respective strings.
241 Case is significant in this comparison if IGNORE-CASE is nil.
242 Unibyte strings are converted to multibyte for comparison.
244 The value is t if the strings (or specified portions) match.
245 If string STR1 is less, the value is a negative number N;
246 - 1 - N is the number of characters that match at the beginning.
247 If string STR1 is greater, the value is a positive number N;
248 N - 1 is the number of characters that match at the beginning. */)
249 (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2, Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
251 register int end1_char, end2_char;
252 register int i1, i1_byte, i2, i2_byte;
254 CHECK_STRING (str1);
255 CHECK_STRING (str2);
256 if (NILP (start1))
257 start1 = make_number (0);
258 if (NILP (start2))
259 start2 = make_number (0);
260 CHECK_NATNUM (start1);
261 CHECK_NATNUM (start2);
262 if (! NILP (end1))
263 CHECK_NATNUM (end1);
264 if (! NILP (end2))
265 CHECK_NATNUM (end2);
267 i1 = XINT (start1);
268 i2 = XINT (start2);
270 i1_byte = string_char_to_byte (str1, i1);
271 i2_byte = string_char_to_byte (str2, i2);
273 end1_char = SCHARS (str1);
274 if (! NILP (end1) && end1_char > XINT (end1))
275 end1_char = XINT (end1);
277 end2_char = SCHARS (str2);
278 if (! NILP (end2) && end2_char > XINT (end2))
279 end2_char = XINT (end2);
281 while (i1 < end1_char && i2 < end2_char)
283 /* When we find a mismatch, we must compare the
284 characters, not just the bytes. */
285 int c1, c2;
287 if (STRING_MULTIBYTE (str1))
288 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c1, str1, i1, i1_byte);
289 else
291 c1 = SREF (str1, i1++);
292 MAKE_CHAR_MULTIBYTE (c1);
295 if (STRING_MULTIBYTE (str2))
296 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c2, str2, i2, i2_byte);
297 else
299 c2 = SREF (str2, i2++);
300 MAKE_CHAR_MULTIBYTE (c2);
303 if (c1 == c2)
304 continue;
306 if (! NILP (ignore_case))
308 Lisp_Object tem;
310 tem = Fupcase (make_number (c1));
311 c1 = XINT (tem);
312 tem = Fupcase (make_number (c2));
313 c2 = XINT (tem);
316 if (c1 == c2)
317 continue;
319 /* Note that I1 has already been incremented
320 past the character that we are comparing;
321 hence we don't add or subtract 1 here. */
322 if (c1 < c2)
323 return make_number (- i1 + XINT (start1));
324 else
325 return make_number (i1 - XINT (start1));
328 if (i1 < end1_char)
329 return make_number (i1 - XINT (start1) + 1);
330 if (i2 < end2_char)
331 return make_number (- i1 + XINT (start1) - 1);
333 return Qt;
336 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
337 doc: /* Return t if first arg string is less than second in lexicographic order.
338 Case is significant.
339 Symbols are also allowed; their print names are used instead. */)
340 (register Lisp_Object s1, Lisp_Object s2)
342 register int end;
343 register int i1, i1_byte, i2, i2_byte;
345 if (SYMBOLP (s1))
346 s1 = SYMBOL_NAME (s1);
347 if (SYMBOLP (s2))
348 s2 = SYMBOL_NAME (s2);
349 CHECK_STRING (s1);
350 CHECK_STRING (s2);
352 i1 = i1_byte = i2 = i2_byte = 0;
354 end = SCHARS (s1);
355 if (end > SCHARS (s2))
356 end = SCHARS (s2);
358 while (i1 < end)
360 /* When we find a mismatch, we must compare the
361 characters, not just the bytes. */
362 int c1, c2;
364 FETCH_STRING_CHAR_ADVANCE (c1, s1, i1, i1_byte);
365 FETCH_STRING_CHAR_ADVANCE (c2, s2, i2, i2_byte);
367 if (c1 != c2)
368 return c1 < c2 ? Qt : Qnil;
370 return i1 < SCHARS (s2) ? Qt : Qnil;
373 static Lisp_Object concat (int nargs, Lisp_Object *args,
374 enum Lisp_Type target_type, int last_special);
376 /* ARGSUSED */
377 Lisp_Object
378 concat2 (Lisp_Object s1, Lisp_Object s2)
380 Lisp_Object args[2];
381 args[0] = s1;
382 args[1] = s2;
383 return concat (2, args, Lisp_String, 0);
386 /* ARGSUSED */
387 Lisp_Object
388 concat3 (Lisp_Object s1, Lisp_Object s2, Lisp_Object s3)
390 Lisp_Object args[3];
391 args[0] = s1;
392 args[1] = s2;
393 args[2] = s3;
394 return concat (3, args, Lisp_String, 0);
397 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
398 doc: /* Concatenate all the arguments and make the result a list.
399 The result is a list whose elements are the elements of all the arguments.
400 Each argument may be a list, vector or string.
401 The last argument is not copied, just used as the tail of the new list.
402 usage: (append &rest SEQUENCES) */)
403 (int nargs, Lisp_Object *args)
405 return concat (nargs, args, Lisp_Cons, 1);
408 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
409 doc: /* Concatenate all the arguments and make the result a string.
410 The result is a string whose elements are the elements of all the arguments.
411 Each argument may be a string or a list or vector of characters (integers).
412 usage: (concat &rest SEQUENCES) */)
413 (int nargs, Lisp_Object *args)
415 return concat (nargs, args, Lisp_String, 0);
418 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
419 doc: /* Concatenate all the arguments and make the result a vector.
420 The result is a vector whose elements are the elements of all the arguments.
421 Each argument may be a list, vector or string.
422 usage: (vconcat &rest SEQUENCES) */)
423 (int nargs, Lisp_Object *args)
425 return concat (nargs, args, Lisp_Vectorlike, 0);
429 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
430 doc: /* Return a copy of a list, vector, string or char-table.
431 The elements of a list or vector are not copied; they are shared
432 with the original. */)
433 (Lisp_Object arg)
435 if (NILP (arg)) return arg;
437 if (CHAR_TABLE_P (arg))
439 return copy_char_table (arg);
442 if (BOOL_VECTOR_P (arg))
444 Lisp_Object val;
445 int size_in_chars
446 = ((XBOOL_VECTOR (arg)->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
447 / BOOL_VECTOR_BITS_PER_CHAR);
449 val = Fmake_bool_vector (Flength (arg), Qnil);
450 memcpy (XBOOL_VECTOR (val)->data, XBOOL_VECTOR (arg)->data,
451 size_in_chars);
452 return val;
455 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
456 wrong_type_argument (Qsequencep, arg);
458 return concat (1, &arg, CONSP (arg) ? Lisp_Cons : XTYPE (arg), 0);
461 /* This structure holds information of an argument of `concat' that is
462 a string and has text properties to be copied. */
463 struct textprop_rec
465 int argnum; /* refer to ARGS (arguments of `concat') */
466 int from; /* refer to ARGS[argnum] (argument string) */
467 int to; /* refer to VAL (the target string) */
470 static Lisp_Object
471 concat (int nargs, Lisp_Object *args, enum Lisp_Type target_type, int last_special)
473 Lisp_Object val;
474 register Lisp_Object tail;
475 register Lisp_Object this;
476 int toindex;
477 int toindex_byte = 0;
478 register int result_len;
479 register int result_len_byte;
480 register int argnum;
481 Lisp_Object last_tail;
482 Lisp_Object prev;
483 int some_multibyte;
484 /* When we make a multibyte string, we can't copy text properties
485 while concatinating each string because the length of resulting
486 string can't be decided until we finish the whole concatination.
487 So, we record strings that have text properties to be copied
488 here, and copy the text properties after the concatination. */
489 struct textprop_rec *textprops = NULL;
490 /* Number of elements in textprops. */
491 int num_textprops = 0;
492 USE_SAFE_ALLOCA;
494 tail = Qnil;
496 /* In append, the last arg isn't treated like the others */
497 if (last_special && nargs > 0)
499 nargs--;
500 last_tail = args[nargs];
502 else
503 last_tail = Qnil;
505 /* Check each argument. */
506 for (argnum = 0; argnum < nargs; argnum++)
508 this = args[argnum];
509 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
510 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
511 wrong_type_argument (Qsequencep, this);
514 /* Compute total length in chars of arguments in RESULT_LEN.
515 If desired output is a string, also compute length in bytes
516 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
517 whether the result should be a multibyte string. */
518 result_len_byte = 0;
519 result_len = 0;
520 some_multibyte = 0;
521 for (argnum = 0; argnum < nargs; argnum++)
523 int len;
524 this = args[argnum];
525 len = XFASTINT (Flength (this));
526 if (target_type == Lisp_String)
528 /* We must count the number of bytes needed in the string
529 as well as the number of characters. */
530 int i;
531 Lisp_Object ch;
532 int this_len_byte;
534 if (VECTORP (this))
535 for (i = 0; i < len; i++)
537 ch = AREF (this, i);
538 CHECK_CHARACTER (ch);
539 this_len_byte = CHAR_BYTES (XINT (ch));
540 result_len_byte += this_len_byte;
541 if (! ASCII_CHAR_P (XINT (ch)) && ! CHAR_BYTE8_P (XINT (ch)))
542 some_multibyte = 1;
544 else if (BOOL_VECTOR_P (this) && XBOOL_VECTOR (this)->size > 0)
545 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
546 else if (CONSP (this))
547 for (; CONSP (this); this = XCDR (this))
549 ch = XCAR (this);
550 CHECK_CHARACTER (ch);
551 this_len_byte = CHAR_BYTES (XINT (ch));
552 result_len_byte += this_len_byte;
553 if (! ASCII_CHAR_P (XINT (ch)) && ! CHAR_BYTE8_P (XINT (ch)))
554 some_multibyte = 1;
556 else if (STRINGP (this))
558 if (STRING_MULTIBYTE (this))
560 some_multibyte = 1;
561 result_len_byte += SBYTES (this);
563 else
564 result_len_byte += count_size_as_multibyte (SDATA (this),
565 SCHARS (this));
569 result_len += len;
570 if (result_len < 0)
571 error ("String overflow");
574 if (! some_multibyte)
575 result_len_byte = result_len;
577 /* Create the output object. */
578 if (target_type == Lisp_Cons)
579 val = Fmake_list (make_number (result_len), Qnil);
580 else if (target_type == Lisp_Vectorlike)
581 val = Fmake_vector (make_number (result_len), Qnil);
582 else if (some_multibyte)
583 val = make_uninit_multibyte_string (result_len, result_len_byte);
584 else
585 val = make_uninit_string (result_len);
587 /* In `append', if all but last arg are nil, return last arg. */
588 if (target_type == Lisp_Cons && EQ (val, Qnil))
589 return last_tail;
591 /* Copy the contents of the args into the result. */
592 if (CONSP (val))
593 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
594 else
595 toindex = 0, toindex_byte = 0;
597 prev = Qnil;
598 if (STRINGP (val))
599 SAFE_ALLOCA (textprops, struct textprop_rec *, sizeof (struct textprop_rec) * nargs);
601 for (argnum = 0; argnum < nargs; argnum++)
603 Lisp_Object thislen;
604 int thisleni = 0;
605 register unsigned int thisindex = 0;
606 register unsigned int thisindex_byte = 0;
608 this = args[argnum];
609 if (!CONSP (this))
610 thislen = Flength (this), thisleni = XINT (thislen);
612 /* Between strings of the same kind, copy fast. */
613 if (STRINGP (this) && STRINGP (val)
614 && STRING_MULTIBYTE (this) == some_multibyte)
616 int thislen_byte = SBYTES (this);
618 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
619 if (! NULL_INTERVAL_P (STRING_INTERVALS (this)))
621 textprops[num_textprops].argnum = argnum;
622 textprops[num_textprops].from = 0;
623 textprops[num_textprops++].to = toindex;
625 toindex_byte += thislen_byte;
626 toindex += thisleni;
628 /* Copy a single-byte string to a multibyte string. */
629 else if (STRINGP (this) && STRINGP (val))
631 if (! NULL_INTERVAL_P (STRING_INTERVALS (this)))
633 textprops[num_textprops].argnum = argnum;
634 textprops[num_textprops].from = 0;
635 textprops[num_textprops++].to = toindex;
637 toindex_byte += copy_text (SDATA (this),
638 SDATA (val) + toindex_byte,
639 SCHARS (this), 0, 1);
640 toindex += thisleni;
642 else
643 /* Copy element by element. */
644 while (1)
646 register Lisp_Object elt;
648 /* Fetch next element of `this' arg into `elt', or break if
649 `this' is exhausted. */
650 if (NILP (this)) break;
651 if (CONSP (this))
652 elt = XCAR (this), this = XCDR (this);
653 else if (thisindex >= thisleni)
654 break;
655 else if (STRINGP (this))
657 int c;
658 if (STRING_MULTIBYTE (this))
660 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
661 thisindex,
662 thisindex_byte);
663 XSETFASTINT (elt, c);
665 else
667 XSETFASTINT (elt, SREF (this, thisindex)); thisindex++;
668 if (some_multibyte
669 && !ASCII_CHAR_P (XINT (elt))
670 && XINT (elt) < 0400)
672 c = BYTE8_TO_CHAR (XINT (elt));
673 XSETINT (elt, c);
677 else if (BOOL_VECTOR_P (this))
679 int byte;
680 byte = XBOOL_VECTOR (this)->data[thisindex / BOOL_VECTOR_BITS_PER_CHAR];
681 if (byte & (1 << (thisindex % BOOL_VECTOR_BITS_PER_CHAR)))
682 elt = Qt;
683 else
684 elt = Qnil;
685 thisindex++;
687 else
689 elt = AREF (this, thisindex);
690 thisindex++;
693 /* Store this element into the result. */
694 if (toindex < 0)
696 XSETCAR (tail, elt);
697 prev = tail;
698 tail = XCDR (tail);
700 else if (VECTORP (val))
702 ASET (val, toindex, elt);
703 toindex++;
705 else
707 CHECK_NUMBER (elt);
708 if (some_multibyte)
709 toindex_byte += CHAR_STRING (XINT (elt),
710 SDATA (val) + toindex_byte);
711 else
712 SSET (val, toindex_byte++, XINT (elt));
713 toindex++;
717 if (!NILP (prev))
718 XSETCDR (prev, last_tail);
720 if (num_textprops > 0)
722 Lisp_Object props;
723 int last_to_end = -1;
725 for (argnum = 0; argnum < num_textprops; argnum++)
727 this = args[textprops[argnum].argnum];
728 props = text_property_list (this,
729 make_number (0),
730 make_number (SCHARS (this)),
731 Qnil);
732 /* If successive arguments have properites, be sure that the
733 value of `composition' property be the copy. */
734 if (last_to_end == textprops[argnum].to)
735 make_composition_value_copy (props);
736 add_text_properties_from_list (val, props,
737 make_number (textprops[argnum].to));
738 last_to_end = textprops[argnum].to + SCHARS (this);
742 SAFE_FREE ();
743 return val;
746 static Lisp_Object string_char_byte_cache_string;
747 static EMACS_INT string_char_byte_cache_charpos;
748 static EMACS_INT string_char_byte_cache_bytepos;
750 void
751 clear_string_char_byte_cache (void)
753 string_char_byte_cache_string = Qnil;
756 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
758 EMACS_INT
759 string_char_to_byte (Lisp_Object string, EMACS_INT char_index)
761 EMACS_INT i_byte;
762 EMACS_INT best_below, best_below_byte;
763 EMACS_INT best_above, best_above_byte;
765 best_below = best_below_byte = 0;
766 best_above = SCHARS (string);
767 best_above_byte = SBYTES (string);
768 if (best_above == best_above_byte)
769 return char_index;
771 if (EQ (string, string_char_byte_cache_string))
773 if (string_char_byte_cache_charpos < char_index)
775 best_below = string_char_byte_cache_charpos;
776 best_below_byte = string_char_byte_cache_bytepos;
778 else
780 best_above = string_char_byte_cache_charpos;
781 best_above_byte = string_char_byte_cache_bytepos;
785 if (char_index - best_below < best_above - char_index)
787 unsigned char *p = SDATA (string) + best_below_byte;
789 while (best_below < char_index)
791 p += BYTES_BY_CHAR_HEAD (*p);
792 best_below++;
794 i_byte = p - SDATA (string);
796 else
798 unsigned char *p = SDATA (string) + best_above_byte;
800 while (best_above > char_index)
802 p--;
803 while (!CHAR_HEAD_P (*p)) p--;
804 best_above--;
806 i_byte = p - SDATA (string);
809 string_char_byte_cache_bytepos = i_byte;
810 string_char_byte_cache_charpos = char_index;
811 string_char_byte_cache_string = string;
813 return i_byte;
816 /* Return the character index corresponding to BYTE_INDEX in STRING. */
818 EMACS_INT
819 string_byte_to_char (Lisp_Object string, EMACS_INT byte_index)
821 EMACS_INT i, i_byte;
822 EMACS_INT best_below, best_below_byte;
823 EMACS_INT best_above, best_above_byte;
825 best_below = best_below_byte = 0;
826 best_above = SCHARS (string);
827 best_above_byte = SBYTES (string);
828 if (best_above == best_above_byte)
829 return byte_index;
831 if (EQ (string, string_char_byte_cache_string))
833 if (string_char_byte_cache_bytepos < byte_index)
835 best_below = string_char_byte_cache_charpos;
836 best_below_byte = string_char_byte_cache_bytepos;
838 else
840 best_above = string_char_byte_cache_charpos;
841 best_above_byte = string_char_byte_cache_bytepos;
845 if (byte_index - best_below_byte < best_above_byte - byte_index)
847 unsigned char *p = SDATA (string) + best_below_byte;
848 unsigned char *pend = SDATA (string) + byte_index;
850 while (p < pend)
852 p += BYTES_BY_CHAR_HEAD (*p);
853 best_below++;
855 i = best_below;
856 i_byte = p - SDATA (string);
858 else
860 unsigned char *p = SDATA (string) + best_above_byte;
861 unsigned char *pbeg = SDATA (string) + byte_index;
863 while (p > pbeg)
865 p--;
866 while (!CHAR_HEAD_P (*p)) p--;
867 best_above--;
869 i = best_above;
870 i_byte = p - SDATA (string);
873 string_char_byte_cache_bytepos = i_byte;
874 string_char_byte_cache_charpos = i;
875 string_char_byte_cache_string = string;
877 return i;
880 /* Convert STRING to a multibyte string. */
882 Lisp_Object
883 string_make_multibyte (Lisp_Object string)
885 unsigned char *buf;
886 EMACS_INT nbytes;
887 Lisp_Object ret;
888 USE_SAFE_ALLOCA;
890 if (STRING_MULTIBYTE (string))
891 return string;
893 nbytes = count_size_as_multibyte (SDATA (string),
894 SCHARS (string));
895 /* If all the chars are ASCII, they won't need any more bytes
896 once converted. In that case, we can return STRING itself. */
897 if (nbytes == SBYTES (string))
898 return string;
900 SAFE_ALLOCA (buf, unsigned char *, nbytes);
901 copy_text (SDATA (string), buf, SBYTES (string),
902 0, 1);
904 ret = make_multibyte_string (buf, SCHARS (string), nbytes);
905 SAFE_FREE ();
907 return ret;
911 /* Convert STRING (if unibyte) to a multibyte string without changing
912 the number of characters. Characters 0200 trough 0237 are
913 converted to eight-bit characters. */
915 Lisp_Object
916 string_to_multibyte (Lisp_Object string)
918 unsigned char *buf;
919 EMACS_INT nbytes;
920 Lisp_Object ret;
921 USE_SAFE_ALLOCA;
923 if (STRING_MULTIBYTE (string))
924 return string;
926 nbytes = parse_str_to_multibyte (SDATA (string), SBYTES (string));
927 /* If all the chars are ASCII, they won't need any more bytes once
928 converted. */
929 if (nbytes == SBYTES (string))
930 return make_multibyte_string (SDATA (string), nbytes, nbytes);
932 SAFE_ALLOCA (buf, unsigned char *, nbytes);
933 memcpy (buf, SDATA (string), SBYTES (string));
934 str_to_multibyte (buf, nbytes, SBYTES (string));
936 ret = make_multibyte_string (buf, SCHARS (string), nbytes);
937 SAFE_FREE ();
939 return ret;
943 /* Convert STRING to a single-byte string. */
945 Lisp_Object
946 string_make_unibyte (Lisp_Object string)
948 int nchars;
949 unsigned char *buf;
950 Lisp_Object ret;
951 USE_SAFE_ALLOCA;
953 if (! STRING_MULTIBYTE (string))
954 return string;
956 nchars = SCHARS (string);
958 SAFE_ALLOCA (buf, unsigned char *, nchars);
959 copy_text (SDATA (string), buf, SBYTES (string),
960 1, 0);
962 ret = make_unibyte_string (buf, nchars);
963 SAFE_FREE ();
965 return ret;
968 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
969 1, 1, 0,
970 doc: /* Return the multibyte equivalent of STRING.
971 If STRING is unibyte and contains non-ASCII characters, the function
972 `unibyte-char-to-multibyte' is used to convert each unibyte character
973 to a multibyte character. In this case, the returned string is a
974 newly created string with no text properties. If STRING is multibyte
975 or entirely ASCII, it is returned unchanged. In particular, when
976 STRING is unibyte and entirely ASCII, the returned string is unibyte.
977 \(When the characters are all ASCII, Emacs primitives will treat the
978 string the same way whether it is unibyte or multibyte.) */)
979 (Lisp_Object string)
981 CHECK_STRING (string);
983 return string_make_multibyte (string);
986 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
987 1, 1, 0,
988 doc: /* Return the unibyte equivalent of STRING.
989 Multibyte character codes are converted to unibyte according to
990 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
991 If the lookup in the translation table fails, this function takes just
992 the low 8 bits of each character. */)
993 (Lisp_Object string)
995 CHECK_STRING (string);
997 return string_make_unibyte (string);
1000 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
1001 1, 1, 0,
1002 doc: /* Return a unibyte string with the same individual bytes as STRING.
1003 If STRING is unibyte, the result is STRING itself.
1004 Otherwise it is a newly created string, with no text properties.
1005 If STRING is multibyte and contains a character of charset
1006 `eight-bit', it is converted to the corresponding single byte. */)
1007 (Lisp_Object string)
1009 CHECK_STRING (string);
1011 if (STRING_MULTIBYTE (string))
1013 int bytes = SBYTES (string);
1014 unsigned char *str = (unsigned char *) xmalloc (bytes);
1016 memcpy (str, SDATA (string), bytes);
1017 bytes = str_as_unibyte (str, bytes);
1018 string = make_unibyte_string (str, bytes);
1019 xfree (str);
1021 return string;
1024 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1025 1, 1, 0,
1026 doc: /* Return a multibyte string with the same individual bytes as STRING.
1027 If STRING is multibyte, the result is STRING itself.
1028 Otherwise it is a newly created string, with no text properties.
1030 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1031 part of a correct utf-8 sequence), it is converted to the corresponding
1032 multibyte character of charset `eight-bit'.
1033 See also `string-to-multibyte'.
1035 Beware, this often doesn't really do what you think it does.
1036 It is similar to (decode-coding-string STRING 'utf-8-emacs).
1037 If you're not sure, whether to use `string-as-multibyte' or
1038 `string-to-multibyte', use `string-to-multibyte'. */)
1039 (Lisp_Object string)
1041 CHECK_STRING (string);
1043 if (! STRING_MULTIBYTE (string))
1045 Lisp_Object new_string;
1046 int nchars, nbytes;
1048 parse_str_as_multibyte (SDATA (string),
1049 SBYTES (string),
1050 &nchars, &nbytes);
1051 new_string = make_uninit_multibyte_string (nchars, nbytes);
1052 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1053 if (nbytes != SBYTES (string))
1054 str_as_multibyte (SDATA (new_string), nbytes,
1055 SBYTES (string), NULL);
1056 string = new_string;
1057 STRING_SET_INTERVALS (string, NULL_INTERVAL);
1059 return string;
1062 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1063 1, 1, 0,
1064 doc: /* Return a multibyte string with the same individual chars as STRING.
1065 If STRING is multibyte, the result is STRING itself.
1066 Otherwise it is a newly created string, with no text properties.
1068 If STRING is unibyte and contains an 8-bit byte, it is converted to
1069 the corresponding multibyte character of charset `eight-bit'.
1071 This differs from `string-as-multibyte' by converting each byte of a correct
1072 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1073 correct sequence. */)
1074 (Lisp_Object string)
1076 CHECK_STRING (string);
1078 return string_to_multibyte (string);
1081 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1082 1, 1, 0,
1083 doc: /* Return a unibyte string with the same individual chars as STRING.
1084 If STRING is unibyte, the result is STRING itself.
1085 Otherwise it is a newly created string, with no text properties,
1086 where each `eight-bit' character is converted to the corresponding byte.
1087 If STRING contains a non-ASCII, non-`eight-bit' character,
1088 an error is signaled. */)
1089 (Lisp_Object string)
1091 CHECK_STRING (string);
1093 if (STRING_MULTIBYTE (string))
1095 EMACS_INT chars = SCHARS (string);
1096 unsigned char *str = (unsigned char *) xmalloc (chars);
1097 EMACS_INT converted = str_to_unibyte (SDATA (string), str, chars, 0);
1099 if (converted < chars)
1100 error ("Can't convert the %dth character to unibyte", converted);
1101 string = make_unibyte_string (str, chars);
1102 xfree (str);
1104 return string;
1108 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1109 doc: /* Return a copy of ALIST.
1110 This is an alist which represents the same mapping from objects to objects,
1111 but does not share the alist structure with ALIST.
1112 The objects mapped (cars and cdrs of elements of the alist)
1113 are shared, however.
1114 Elements of ALIST that are not conses are also shared. */)
1115 (Lisp_Object alist)
1117 register Lisp_Object tem;
1119 CHECK_LIST (alist);
1120 if (NILP (alist))
1121 return alist;
1122 alist = concat (1, &alist, Lisp_Cons, 0);
1123 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1125 register Lisp_Object car;
1126 car = XCAR (tem);
1128 if (CONSP (car))
1129 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1131 return alist;
1134 DEFUN ("substring", Fsubstring, Ssubstring, 2, 3, 0,
1135 doc: /* Return a new string whose contents are a substring of STRING.
1136 The returned string consists of the characters between index FROM
1137 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1138 zero-indexed: 0 means the first character of STRING. Negative values
1139 are counted from the end of STRING. If TO is nil, the substring runs
1140 to the end of STRING.
1142 The STRING argument may also be a vector. In that case, the return
1143 value is a new vector that contains the elements between index FROM
1144 \(inclusive) and index TO (exclusive) of that vector argument. */)
1145 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1147 Lisp_Object res;
1148 int size;
1149 int size_byte = 0;
1150 int from_char, to_char;
1151 int from_byte = 0, to_byte = 0;
1153 CHECK_VECTOR_OR_STRING (string);
1154 CHECK_NUMBER (from);
1156 if (STRINGP (string))
1158 size = SCHARS (string);
1159 size_byte = SBYTES (string);
1161 else
1162 size = ASIZE (string);
1164 if (NILP (to))
1166 to_char = size;
1167 to_byte = size_byte;
1169 else
1171 CHECK_NUMBER (to);
1173 to_char = XINT (to);
1174 if (to_char < 0)
1175 to_char += size;
1177 if (STRINGP (string))
1178 to_byte = string_char_to_byte (string, to_char);
1181 from_char = XINT (from);
1182 if (from_char < 0)
1183 from_char += size;
1184 if (STRINGP (string))
1185 from_byte = string_char_to_byte (string, from_char);
1187 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1188 args_out_of_range_3 (string, make_number (from_char),
1189 make_number (to_char));
1191 if (STRINGP (string))
1193 res = make_specified_string (SDATA (string) + from_byte,
1194 to_char - from_char, to_byte - from_byte,
1195 STRING_MULTIBYTE (string));
1196 copy_text_properties (make_number (from_char), make_number (to_char),
1197 string, make_number (0), res, Qnil);
1199 else
1200 res = Fvector (to_char - from_char, &AREF (string, from_char));
1202 return res;
1206 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1207 doc: /* Return a substring of STRING, without text properties.
1208 It starts at index FROM and ending before TO.
1209 TO may be nil or omitted; then the substring runs to the end of STRING.
1210 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1211 If FROM or TO is negative, it counts from the end.
1213 With one argument, just copy STRING without its properties. */)
1214 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1216 int size, size_byte;
1217 int from_char, to_char;
1218 int from_byte, to_byte;
1220 CHECK_STRING (string);
1222 size = SCHARS (string);
1223 size_byte = SBYTES (string);
1225 if (NILP (from))
1226 from_char = from_byte = 0;
1227 else
1229 CHECK_NUMBER (from);
1230 from_char = XINT (from);
1231 if (from_char < 0)
1232 from_char += size;
1234 from_byte = string_char_to_byte (string, from_char);
1237 if (NILP (to))
1239 to_char = size;
1240 to_byte = size_byte;
1242 else
1244 CHECK_NUMBER (to);
1246 to_char = XINT (to);
1247 if (to_char < 0)
1248 to_char += size;
1250 to_byte = string_char_to_byte (string, to_char);
1253 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1254 args_out_of_range_3 (string, make_number (from_char),
1255 make_number (to_char));
1257 return make_specified_string (SDATA (string) + from_byte,
1258 to_char - from_char, to_byte - from_byte,
1259 STRING_MULTIBYTE (string));
1262 /* Extract a substring of STRING, giving start and end positions
1263 both in characters and in bytes. */
1265 Lisp_Object
1266 substring_both (Lisp_Object string, int from, int from_byte, int to, int to_byte)
1268 Lisp_Object res;
1269 int size;
1270 int size_byte;
1272 CHECK_VECTOR_OR_STRING (string);
1274 if (STRINGP (string))
1276 size = SCHARS (string);
1277 size_byte = SBYTES (string);
1279 else
1280 size = ASIZE (string);
1282 if (!(0 <= from && from <= to && to <= size))
1283 args_out_of_range_3 (string, make_number (from), make_number (to));
1285 if (STRINGP (string))
1287 res = make_specified_string (SDATA (string) + from_byte,
1288 to - from, to_byte - from_byte,
1289 STRING_MULTIBYTE (string));
1290 copy_text_properties (make_number (from), make_number (to),
1291 string, make_number (0), res, Qnil);
1293 else
1294 res = Fvector (to - from, &AREF (string, from));
1296 return res;
1299 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1300 doc: /* Take cdr N times on LIST, returns the result. */)
1301 (Lisp_Object n, Lisp_Object list)
1303 register int i, num;
1304 CHECK_NUMBER (n);
1305 num = XINT (n);
1306 for (i = 0; i < num && !NILP (list); i++)
1308 QUIT;
1309 CHECK_LIST_CONS (list, list);
1310 list = XCDR (list);
1312 return list;
1315 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1316 doc: /* Return the Nth element of LIST.
1317 N counts from zero. If LIST is not that long, nil is returned. */)
1318 (Lisp_Object n, Lisp_Object list)
1320 return Fcar (Fnthcdr (n, list));
1323 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1324 doc: /* Return element of SEQUENCE at index N. */)
1325 (register Lisp_Object sequence, Lisp_Object n)
1327 CHECK_NUMBER (n);
1328 if (CONSP (sequence) || NILP (sequence))
1329 return Fcar (Fnthcdr (n, sequence));
1331 /* Faref signals a "not array" error, so check here. */
1332 CHECK_ARRAY (sequence, Qsequencep);
1333 return Faref (sequence, n);
1336 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1337 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1338 The value is actually the tail of LIST whose car is ELT. */)
1339 (register Lisp_Object elt, Lisp_Object list)
1341 register Lisp_Object tail;
1342 for (tail = list; CONSP (tail); tail = XCDR (tail))
1344 register Lisp_Object tem;
1345 CHECK_LIST_CONS (tail, list);
1346 tem = XCAR (tail);
1347 if (! NILP (Fequal (elt, tem)))
1348 return tail;
1349 QUIT;
1351 return Qnil;
1354 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1355 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1356 The value is actually the tail of LIST whose car is ELT. */)
1357 (register Lisp_Object elt, Lisp_Object list)
1359 while (1)
1361 if (!CONSP (list) || EQ (XCAR (list), elt))
1362 break;
1364 list = XCDR (list);
1365 if (!CONSP (list) || EQ (XCAR (list), elt))
1366 break;
1368 list = XCDR (list);
1369 if (!CONSP (list) || EQ (XCAR (list), elt))
1370 break;
1372 list = XCDR (list);
1373 QUIT;
1376 CHECK_LIST (list);
1377 return list;
1380 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1381 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1382 The value is actually the tail of LIST whose car is ELT. */)
1383 (register Lisp_Object elt, Lisp_Object list)
1385 register Lisp_Object tail;
1387 if (!FLOATP (elt))
1388 return Fmemq (elt, list);
1390 for (tail = list; CONSP (tail); tail = XCDR (tail))
1392 register Lisp_Object tem;
1393 CHECK_LIST_CONS (tail, list);
1394 tem = XCAR (tail);
1395 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0))
1396 return tail;
1397 QUIT;
1399 return Qnil;
1402 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1403 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1404 The value is actually the first element of LIST whose car is KEY.
1405 Elements of LIST that are not conses are ignored. */)
1406 (Lisp_Object key, Lisp_Object list)
1408 while (1)
1410 if (!CONSP (list)
1411 || (CONSP (XCAR (list))
1412 && EQ (XCAR (XCAR (list)), key)))
1413 break;
1415 list = XCDR (list);
1416 if (!CONSP (list)
1417 || (CONSP (XCAR (list))
1418 && EQ (XCAR (XCAR (list)), key)))
1419 break;
1421 list = XCDR (list);
1422 if (!CONSP (list)
1423 || (CONSP (XCAR (list))
1424 && EQ (XCAR (XCAR (list)), key)))
1425 break;
1427 list = XCDR (list);
1428 QUIT;
1431 return CAR (list);
1434 /* Like Fassq but never report an error and do not allow quits.
1435 Use only on lists known never to be circular. */
1437 Lisp_Object
1438 assq_no_quit (Lisp_Object key, Lisp_Object list)
1440 while (CONSP (list)
1441 && (!CONSP (XCAR (list))
1442 || !EQ (XCAR (XCAR (list)), key)))
1443 list = XCDR (list);
1445 return CAR_SAFE (list);
1448 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1449 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1450 The value is actually the first element of LIST whose car equals KEY. */)
1451 (Lisp_Object key, Lisp_Object list)
1453 Lisp_Object car;
1455 while (1)
1457 if (!CONSP (list)
1458 || (CONSP (XCAR (list))
1459 && (car = XCAR (XCAR (list)),
1460 EQ (car, key) || !NILP (Fequal (car, key)))))
1461 break;
1463 list = XCDR (list);
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 QUIT;
1481 return CAR (list);
1484 /* Like Fassoc but never report an error and do not allow quits.
1485 Use only on lists known never to be circular. */
1487 Lisp_Object
1488 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1490 while (CONSP (list)
1491 && (!CONSP (XCAR (list))
1492 || (!EQ (XCAR (XCAR (list)), key)
1493 && NILP (Fequal (XCAR (XCAR (list)), key)))))
1494 list = XCDR (list);
1496 return CONSP (list) ? XCAR (list) : Qnil;
1499 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1500 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1501 The value is actually the first element of LIST whose cdr is KEY. */)
1502 (register Lisp_Object key, Lisp_Object list)
1504 while (1)
1506 if (!CONSP (list)
1507 || (CONSP (XCAR (list))
1508 && EQ (XCDR (XCAR (list)), key)))
1509 break;
1511 list = XCDR (list);
1512 if (!CONSP (list)
1513 || (CONSP (XCAR (list))
1514 && EQ (XCDR (XCAR (list)), key)))
1515 break;
1517 list = XCDR (list);
1518 if (!CONSP (list)
1519 || (CONSP (XCAR (list))
1520 && EQ (XCDR (XCAR (list)), key)))
1521 break;
1523 list = XCDR (list);
1524 QUIT;
1527 return CAR (list);
1530 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1531 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1532 The value is actually the first element of LIST whose cdr equals KEY. */)
1533 (Lisp_Object key, Lisp_Object list)
1535 Lisp_Object cdr;
1537 while (1)
1539 if (!CONSP (list)
1540 || (CONSP (XCAR (list))
1541 && (cdr = XCDR (XCAR (list)),
1542 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1543 break;
1545 list = XCDR (list);
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 QUIT;
1563 return CAR (list);
1566 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1567 doc: /* Delete by side effect any occurrences of ELT as a member of LIST.
1568 The modified LIST is returned. Comparison is done with `eq'.
1569 If the first member of LIST is ELT, there is no way to remove it by side effect;
1570 therefore, write `(setq foo (delq element foo))'
1571 to be sure of changing the value of `foo'. */)
1572 (register Lisp_Object elt, Lisp_Object list)
1574 register Lisp_Object tail, prev;
1575 register Lisp_Object tem;
1577 tail = list;
1578 prev = Qnil;
1579 while (!NILP (tail))
1581 CHECK_LIST_CONS (tail, list);
1582 tem = XCAR (tail);
1583 if (EQ (elt, tem))
1585 if (NILP (prev))
1586 list = XCDR (tail);
1587 else
1588 Fsetcdr (prev, XCDR (tail));
1590 else
1591 prev = tail;
1592 tail = XCDR (tail);
1593 QUIT;
1595 return list;
1598 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1599 doc: /* Delete by side effect any occurrences of ELT as a member of SEQ.
1600 SEQ must be a list, a vector, or a string.
1601 The modified SEQ is returned. Comparison is done with `equal'.
1602 If SEQ is not a list, or the first member of SEQ is ELT, deleting it
1603 is not a side effect; it is simply using a different sequence.
1604 Therefore, write `(setq foo (delete element foo))'
1605 to be sure of changing the value of `foo'. */)
1606 (Lisp_Object elt, Lisp_Object seq)
1608 if (VECTORP (seq))
1610 EMACS_INT i, n;
1612 for (i = n = 0; i < ASIZE (seq); ++i)
1613 if (NILP (Fequal (AREF (seq, i), elt)))
1614 ++n;
1616 if (n != ASIZE (seq))
1618 struct Lisp_Vector *p = allocate_vector (n);
1620 for (i = n = 0; i < ASIZE (seq); ++i)
1621 if (NILP (Fequal (AREF (seq, i), elt)))
1622 p->contents[n++] = AREF (seq, i);
1624 XSETVECTOR (seq, p);
1627 else if (STRINGP (seq))
1629 EMACS_INT i, ibyte, nchars, nbytes, cbytes;
1630 int c;
1632 for (i = nchars = nbytes = ibyte = 0;
1633 i < SCHARS (seq);
1634 ++i, ibyte += cbytes)
1636 if (STRING_MULTIBYTE (seq))
1638 c = STRING_CHAR (SDATA (seq) + ibyte);
1639 cbytes = CHAR_BYTES (c);
1641 else
1643 c = SREF (seq, i);
1644 cbytes = 1;
1647 if (!INTEGERP (elt) || c != XINT (elt))
1649 ++nchars;
1650 nbytes += cbytes;
1654 if (nchars != SCHARS (seq))
1656 Lisp_Object tem;
1658 tem = make_uninit_multibyte_string (nchars, nbytes);
1659 if (!STRING_MULTIBYTE (seq))
1660 STRING_SET_UNIBYTE (tem);
1662 for (i = nchars = nbytes = ibyte = 0;
1663 i < SCHARS (seq);
1664 ++i, ibyte += cbytes)
1666 if (STRING_MULTIBYTE (seq))
1668 c = STRING_CHAR (SDATA (seq) + ibyte);
1669 cbytes = CHAR_BYTES (c);
1671 else
1673 c = SREF (seq, i);
1674 cbytes = 1;
1677 if (!INTEGERP (elt) || c != XINT (elt))
1679 unsigned char *from = SDATA (seq) + ibyte;
1680 unsigned char *to = SDATA (tem) + nbytes;
1681 EMACS_INT n;
1683 ++nchars;
1684 nbytes += cbytes;
1686 for (n = cbytes; n--; )
1687 *to++ = *from++;
1691 seq = tem;
1694 else
1696 Lisp_Object tail, prev;
1698 for (tail = seq, prev = Qnil; CONSP (tail); tail = XCDR (tail))
1700 CHECK_LIST_CONS (tail, seq);
1702 if (!NILP (Fequal (elt, XCAR (tail))))
1704 if (NILP (prev))
1705 seq = XCDR (tail);
1706 else
1707 Fsetcdr (prev, XCDR (tail));
1709 else
1710 prev = tail;
1711 QUIT;
1715 return seq;
1718 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1719 doc: /* Reverse LIST by modifying cdr pointers.
1720 Return the reversed list. */)
1721 (Lisp_Object list)
1723 register Lisp_Object prev, tail, next;
1725 if (NILP (list)) return list;
1726 prev = Qnil;
1727 tail = list;
1728 while (!NILP (tail))
1730 QUIT;
1731 CHECK_LIST_CONS (tail, list);
1732 next = XCDR (tail);
1733 Fsetcdr (tail, prev);
1734 prev = tail;
1735 tail = next;
1737 return prev;
1740 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1741 doc: /* Reverse LIST, copying. Return the reversed list.
1742 See also the function `nreverse', which is used more often. */)
1743 (Lisp_Object list)
1745 Lisp_Object new;
1747 for (new = Qnil; CONSP (list); list = XCDR (list))
1749 QUIT;
1750 new = Fcons (XCAR (list), new);
1752 CHECK_LIST_END (list, list);
1753 return new;
1756 Lisp_Object merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred);
1758 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
1759 doc: /* Sort LIST, stably, comparing elements using PREDICATE.
1760 Returns the sorted list. LIST is modified by side effects.
1761 PREDICATE is called with two elements of LIST, and should return non-nil
1762 if the first element should sort before the second. */)
1763 (Lisp_Object list, Lisp_Object predicate)
1765 Lisp_Object front, back;
1766 register Lisp_Object len, tem;
1767 struct gcpro gcpro1, gcpro2;
1768 register int length;
1770 front = list;
1771 len = Flength (list);
1772 length = XINT (len);
1773 if (length < 2)
1774 return list;
1776 XSETINT (len, (length / 2) - 1);
1777 tem = Fnthcdr (len, list);
1778 back = Fcdr (tem);
1779 Fsetcdr (tem, Qnil);
1781 GCPRO2 (front, back);
1782 front = Fsort (front, predicate);
1783 back = Fsort (back, predicate);
1784 UNGCPRO;
1785 return merge (front, back, predicate);
1788 Lisp_Object
1789 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
1791 Lisp_Object value;
1792 register Lisp_Object tail;
1793 Lisp_Object tem;
1794 register Lisp_Object l1, l2;
1795 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1797 l1 = org_l1;
1798 l2 = org_l2;
1799 tail = Qnil;
1800 value = Qnil;
1802 /* It is sufficient to protect org_l1 and org_l2.
1803 When l1 and l2 are updated, we copy the new values
1804 back into the org_ vars. */
1805 GCPRO4 (org_l1, org_l2, pred, value);
1807 while (1)
1809 if (NILP (l1))
1811 UNGCPRO;
1812 if (NILP (tail))
1813 return l2;
1814 Fsetcdr (tail, l2);
1815 return value;
1817 if (NILP (l2))
1819 UNGCPRO;
1820 if (NILP (tail))
1821 return l1;
1822 Fsetcdr (tail, l1);
1823 return value;
1825 tem = call2 (pred, Fcar (l2), Fcar (l1));
1826 if (NILP (tem))
1828 tem = l1;
1829 l1 = Fcdr (l1);
1830 org_l1 = l1;
1832 else
1834 tem = l2;
1835 l2 = Fcdr (l2);
1836 org_l2 = l2;
1838 if (NILP (tail))
1839 value = tem;
1840 else
1841 Fsetcdr (tail, tem);
1842 tail = tem;
1847 /* This does not check for quits. That is safe since it must terminate. */
1849 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
1850 doc: /* Extract a value from a property list.
1851 PLIST is a property list, which is a list of the form
1852 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1853 corresponding to the given PROP, or nil if PROP is not one of the
1854 properties on the list. This function never signals an error. */)
1855 (Lisp_Object plist, Lisp_Object prop)
1857 Lisp_Object tail, halftail;
1859 /* halftail is used to detect circular lists. */
1860 tail = halftail = plist;
1861 while (CONSP (tail) && CONSP (XCDR (tail)))
1863 if (EQ (prop, XCAR (tail)))
1864 return XCAR (XCDR (tail));
1866 tail = XCDR (XCDR (tail));
1867 halftail = XCDR (halftail);
1868 if (EQ (tail, halftail))
1869 break;
1871 #if 0 /* Unsafe version. */
1872 /* This function can be called asynchronously
1873 (setup_coding_system). Don't QUIT in that case. */
1874 if (!interrupt_input_blocked)
1875 QUIT;
1876 #endif
1879 return Qnil;
1882 DEFUN ("get", Fget, Sget, 2, 2, 0,
1883 doc: /* Return the value of SYMBOL's PROPNAME property.
1884 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
1885 (Lisp_Object symbol, Lisp_Object propname)
1887 CHECK_SYMBOL (symbol);
1888 return Fplist_get (XSYMBOL (symbol)->plist, propname);
1891 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
1892 doc: /* Change value in PLIST of PROP to VAL.
1893 PLIST is a property list, which is a list of the form
1894 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
1895 If PROP is already a property on the list, its value is set to VAL,
1896 otherwise the new PROP VAL pair is added. The new plist is returned;
1897 use `(setq x (plist-put x prop val))' to be sure to use the new value.
1898 The PLIST is modified by side effects. */)
1899 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1901 register Lisp_Object tail, prev;
1902 Lisp_Object newcell;
1903 prev = Qnil;
1904 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1905 tail = XCDR (XCDR (tail)))
1907 if (EQ (prop, XCAR (tail)))
1909 Fsetcar (XCDR (tail), val);
1910 return plist;
1913 prev = tail;
1914 QUIT;
1916 newcell = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
1917 if (NILP (prev))
1918 return newcell;
1919 else
1920 Fsetcdr (XCDR (prev), newcell);
1921 return plist;
1924 DEFUN ("put", Fput, Sput, 3, 3, 0,
1925 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
1926 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
1927 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
1929 CHECK_SYMBOL (symbol);
1930 XSYMBOL (symbol)->plist
1931 = Fplist_put (XSYMBOL (symbol)->plist, propname, value);
1932 return value;
1935 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
1936 doc: /* Extract a value from a property list, comparing with `equal'.
1937 PLIST is a property list, which is a list of the form
1938 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1939 corresponding to the given PROP, or nil if PROP is not
1940 one of the properties on the list. */)
1941 (Lisp_Object plist, Lisp_Object prop)
1943 Lisp_Object tail;
1945 for (tail = plist;
1946 CONSP (tail) && CONSP (XCDR (tail));
1947 tail = XCDR (XCDR (tail)))
1949 if (! NILP (Fequal (prop, XCAR (tail))))
1950 return XCAR (XCDR (tail));
1952 QUIT;
1955 CHECK_LIST_END (tail, prop);
1957 return Qnil;
1960 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
1961 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
1962 PLIST is a property list, which is a list of the form
1963 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
1964 If PROP is already a property on the list, its value is set to VAL,
1965 otherwise the new PROP VAL pair is added. The new plist is returned;
1966 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
1967 The PLIST is modified by side effects. */)
1968 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1970 register Lisp_Object tail, prev;
1971 Lisp_Object newcell;
1972 prev = Qnil;
1973 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1974 tail = XCDR (XCDR (tail)))
1976 if (! NILP (Fequal (prop, XCAR (tail))))
1978 Fsetcar (XCDR (tail), val);
1979 return plist;
1982 prev = tail;
1983 QUIT;
1985 newcell = Fcons (prop, Fcons (val, Qnil));
1986 if (NILP (prev))
1987 return newcell;
1988 else
1989 Fsetcdr (XCDR (prev), newcell);
1990 return plist;
1993 DEFUN ("eql", Feql, Seql, 2, 2, 0,
1994 doc: /* Return t if the two args are the same Lisp object.
1995 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
1996 (Lisp_Object obj1, Lisp_Object obj2)
1998 if (FLOATP (obj1))
1999 return internal_equal (obj1, obj2, 0, 0) ? Qt : Qnil;
2000 else
2001 return EQ (obj1, obj2) ? Qt : Qnil;
2004 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
2005 doc: /* Return t if two Lisp objects have similar structure and contents.
2006 They must have the same data type.
2007 Conses are compared by comparing the cars and the cdrs.
2008 Vectors and strings are compared element by element.
2009 Numbers are compared by value, but integers cannot equal floats.
2010 (Use `=' if you want integers and floats to be able to be equal.)
2011 Symbols must match exactly. */)
2012 (register Lisp_Object o1, Lisp_Object o2)
2014 return internal_equal (o1, o2, 0, 0) ? Qt : Qnil;
2017 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
2018 doc: /* Return t if two Lisp objects have similar structure and contents.
2019 This is like `equal' except that it compares the text properties
2020 of strings. (`equal' ignores text properties.) */)
2021 (register Lisp_Object o1, Lisp_Object o2)
2023 return internal_equal (o1, o2, 0, 1) ? Qt : Qnil;
2026 /* DEPTH is current depth of recursion. Signal an error if it
2027 gets too deep.
2028 PROPS, if non-nil, means compare string text properties too. */
2030 static int
2031 internal_equal (register Lisp_Object o1, register Lisp_Object o2, int depth, int props)
2033 if (depth > 200)
2034 error ("Stack overflow in equal");
2036 tail_recurse:
2037 QUIT;
2038 if (EQ (o1, o2))
2039 return 1;
2040 if (XTYPE (o1) != XTYPE (o2))
2041 return 0;
2043 switch (XTYPE (o1))
2045 case Lisp_Float:
2047 double d1, d2;
2049 d1 = extract_float (o1);
2050 d2 = extract_float (o2);
2051 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2052 though they are not =. */
2053 return d1 == d2 || (d1 != d1 && d2 != d2);
2056 case Lisp_Cons:
2057 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1, props))
2058 return 0;
2059 o1 = XCDR (o1);
2060 o2 = XCDR (o2);
2061 goto tail_recurse;
2063 case Lisp_Misc:
2064 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2065 return 0;
2066 if (OVERLAYP (o1))
2068 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2069 depth + 1, props)
2070 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2071 depth + 1, props))
2072 return 0;
2073 o1 = XOVERLAY (o1)->plist;
2074 o2 = XOVERLAY (o2)->plist;
2075 goto tail_recurse;
2077 if (MARKERP (o1))
2079 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2080 && (XMARKER (o1)->buffer == 0
2081 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2083 break;
2085 case Lisp_Vectorlike:
2087 register int i;
2088 EMACS_INT size = ASIZE (o1);
2089 /* Pseudovectors have the type encoded in the size field, so this test
2090 actually checks that the objects have the same type as well as the
2091 same size. */
2092 if (ASIZE (o2) != size)
2093 return 0;
2094 /* Boolvectors are compared much like strings. */
2095 if (BOOL_VECTOR_P (o1))
2097 int size_in_chars
2098 = ((XBOOL_VECTOR (o1)->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
2099 / BOOL_VECTOR_BITS_PER_CHAR);
2101 if (XBOOL_VECTOR (o1)->size != XBOOL_VECTOR (o2)->size)
2102 return 0;
2103 if (memcmp (XBOOL_VECTOR (o1)->data, XBOOL_VECTOR (o2)->data,
2104 size_in_chars))
2105 return 0;
2106 return 1;
2108 if (WINDOW_CONFIGURATIONP (o1))
2109 return compare_window_configurations (o1, o2, 0);
2111 /* Aside from them, only true vectors, char-tables, compiled
2112 functions, and fonts (font-spec, font-entity, font-ojbect)
2113 are sensible to compare, so eliminate the others now. */
2114 if (size & PSEUDOVECTOR_FLAG)
2116 if (!(size & (PVEC_COMPILED
2117 | PVEC_CHAR_TABLE | PVEC_SUB_CHAR_TABLE | PVEC_FONT)))
2118 return 0;
2119 size &= PSEUDOVECTOR_SIZE_MASK;
2121 for (i = 0; i < size; i++)
2123 Lisp_Object v1, v2;
2124 v1 = AREF (o1, i);
2125 v2 = AREF (o2, i);
2126 if (!internal_equal (v1, v2, depth + 1, props))
2127 return 0;
2129 return 1;
2131 break;
2133 case Lisp_String:
2134 if (SCHARS (o1) != SCHARS (o2))
2135 return 0;
2136 if (SBYTES (o1) != SBYTES (o2))
2137 return 0;
2138 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2139 return 0;
2140 if (props && !compare_string_intervals (o1, o2))
2141 return 0;
2142 return 1;
2144 default:
2145 break;
2148 return 0;
2152 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2153 doc: /* Store each element of ARRAY with ITEM.
2154 ARRAY is a vector, string, char-table, or bool-vector. */)
2155 (Lisp_Object array, Lisp_Object item)
2157 register int size, index, charval;
2158 if (VECTORP (array))
2160 register Lisp_Object *p = XVECTOR (array)->contents;
2161 size = ASIZE (array);
2162 for (index = 0; index < size; index++)
2163 p[index] = item;
2165 else if (CHAR_TABLE_P (array))
2167 int i;
2169 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2170 XCHAR_TABLE (array)->contents[i] = item;
2171 XCHAR_TABLE (array)->defalt = item;
2173 else if (STRINGP (array))
2175 register unsigned char *p = SDATA (array);
2176 CHECK_NUMBER (item);
2177 charval = XINT (item);
2178 size = SCHARS (array);
2179 if (STRING_MULTIBYTE (array))
2181 unsigned char str[MAX_MULTIBYTE_LENGTH];
2182 int len = CHAR_STRING (charval, str);
2183 int size_byte = SBYTES (array);
2184 unsigned char *p1 = p, *endp = p + size_byte;
2185 int i;
2187 if (size != size_byte)
2188 while (p1 < endp)
2190 int this_len = BYTES_BY_CHAR_HEAD (*p1);
2191 if (len != this_len)
2192 error ("Attempt to change byte length of a string");
2193 p1 += this_len;
2195 for (i = 0; i < size_byte; i++)
2196 *p++ = str[i % len];
2198 else
2199 for (index = 0; index < size; index++)
2200 p[index] = charval;
2202 else if (BOOL_VECTOR_P (array))
2204 register unsigned char *p = XBOOL_VECTOR (array)->data;
2205 int size_in_chars
2206 = ((XBOOL_VECTOR (array)->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
2207 / BOOL_VECTOR_BITS_PER_CHAR);
2209 charval = (! NILP (item) ? -1 : 0);
2210 for (index = 0; index < size_in_chars - 1; index++)
2211 p[index] = charval;
2212 if (index < size_in_chars)
2214 /* Mask out bits beyond the vector size. */
2215 if (XBOOL_VECTOR (array)->size % BOOL_VECTOR_BITS_PER_CHAR)
2216 charval &= (1 << (XBOOL_VECTOR (array)->size % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2217 p[index] = charval;
2220 else
2221 wrong_type_argument (Qarrayp, array);
2222 return array;
2225 DEFUN ("clear-string", Fclear_string, Sclear_string,
2226 1, 1, 0,
2227 doc: /* Clear the contents of STRING.
2228 This makes STRING unibyte and may change its length. */)
2229 (Lisp_Object string)
2231 int len;
2232 CHECK_STRING (string);
2233 len = SBYTES (string);
2234 memset (SDATA (string), 0, len);
2235 STRING_SET_CHARS (string, len);
2236 STRING_SET_UNIBYTE (string);
2237 return Qnil;
2240 /* ARGSUSED */
2241 Lisp_Object
2242 nconc2 (Lisp_Object s1, Lisp_Object s2)
2244 Lisp_Object args[2];
2245 args[0] = s1;
2246 args[1] = s2;
2247 return Fnconc (2, args);
2250 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2251 doc: /* Concatenate any number of lists by altering them.
2252 Only the last argument is not altered, and need not be a list.
2253 usage: (nconc &rest LISTS) */)
2254 (int nargs, Lisp_Object *args)
2256 register int argnum;
2257 register Lisp_Object tail, tem, val;
2259 val = tail = Qnil;
2261 for (argnum = 0; argnum < nargs; argnum++)
2263 tem = args[argnum];
2264 if (NILP (tem)) continue;
2266 if (NILP (val))
2267 val = tem;
2269 if (argnum + 1 == nargs) break;
2271 CHECK_LIST_CONS (tem, tem);
2273 while (CONSP (tem))
2275 tail = tem;
2276 tem = XCDR (tail);
2277 QUIT;
2280 tem = args[argnum + 1];
2281 Fsetcdr (tail, tem);
2282 if (NILP (tem))
2283 args[argnum + 1] = tail;
2286 return val;
2289 /* This is the guts of all mapping functions.
2290 Apply FN to each element of SEQ, one by one,
2291 storing the results into elements of VALS, a C vector of Lisp_Objects.
2292 LENI is the length of VALS, which should also be the length of SEQ. */
2294 static void
2295 mapcar1 (int leni, Lisp_Object *vals, Lisp_Object fn, Lisp_Object seq)
2297 register Lisp_Object tail;
2298 Lisp_Object dummy;
2299 register int i;
2300 struct gcpro gcpro1, gcpro2, gcpro3;
2302 if (vals)
2304 /* Don't let vals contain any garbage when GC happens. */
2305 for (i = 0; i < leni; i++)
2306 vals[i] = Qnil;
2308 GCPRO3 (dummy, fn, seq);
2309 gcpro1.var = vals;
2310 gcpro1.nvars = leni;
2312 else
2313 GCPRO2 (fn, seq);
2314 /* We need not explicitly protect `tail' because it is used only on lists, and
2315 1) lists are not relocated and 2) the list is marked via `seq' so will not
2316 be freed */
2318 if (VECTORP (seq))
2320 for (i = 0; i < leni; i++)
2322 dummy = call1 (fn, AREF (seq, i));
2323 if (vals)
2324 vals[i] = dummy;
2327 else if (BOOL_VECTOR_P (seq))
2329 for (i = 0; i < leni; i++)
2331 int byte;
2332 byte = XBOOL_VECTOR (seq)->data[i / BOOL_VECTOR_BITS_PER_CHAR];
2333 dummy = (byte & (1 << (i % BOOL_VECTOR_BITS_PER_CHAR))) ? Qt : Qnil;
2334 dummy = call1 (fn, dummy);
2335 if (vals)
2336 vals[i] = dummy;
2339 else if (STRINGP (seq))
2341 int i_byte;
2343 for (i = 0, i_byte = 0; i < leni;)
2345 int c;
2346 int i_before = i;
2348 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2349 XSETFASTINT (dummy, c);
2350 dummy = call1 (fn, dummy);
2351 if (vals)
2352 vals[i_before] = dummy;
2355 else /* Must be a list, since Flength did not get an error */
2357 tail = seq;
2358 for (i = 0; i < leni && CONSP (tail); i++)
2360 dummy = call1 (fn, XCAR (tail));
2361 if (vals)
2362 vals[i] = dummy;
2363 tail = XCDR (tail);
2367 UNGCPRO;
2370 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2371 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2372 In between each pair of results, stick in SEPARATOR. Thus, " " as
2373 SEPARATOR results in spaces between the values returned by FUNCTION.
2374 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2375 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2377 Lisp_Object len;
2378 register int leni;
2379 int nargs;
2380 register Lisp_Object *args;
2381 register int i;
2382 struct gcpro gcpro1;
2383 Lisp_Object ret;
2384 USE_SAFE_ALLOCA;
2386 len = Flength (sequence);
2387 if (CHAR_TABLE_P (sequence))
2388 wrong_type_argument (Qlistp, sequence);
2389 leni = XINT (len);
2390 nargs = leni + leni - 1;
2391 if (nargs < 0) return empty_unibyte_string;
2393 SAFE_ALLOCA_LISP (args, nargs);
2395 GCPRO1 (separator);
2396 mapcar1 (leni, args, function, sequence);
2397 UNGCPRO;
2399 for (i = leni - 1; i > 0; i--)
2400 args[i + i] = args[i];
2402 for (i = 1; i < nargs; i += 2)
2403 args[i] = separator;
2405 ret = Fconcat (nargs, args);
2406 SAFE_FREE ();
2408 return ret;
2411 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2412 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2413 The result is a list just as long as SEQUENCE.
2414 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2415 (Lisp_Object function, Lisp_Object sequence)
2417 register Lisp_Object len;
2418 register int leni;
2419 register Lisp_Object *args;
2420 Lisp_Object ret;
2421 USE_SAFE_ALLOCA;
2423 len = Flength (sequence);
2424 if (CHAR_TABLE_P (sequence))
2425 wrong_type_argument (Qlistp, sequence);
2426 leni = XFASTINT (len);
2428 SAFE_ALLOCA_LISP (args, leni);
2430 mapcar1 (leni, args, function, sequence);
2432 ret = Flist (leni, args);
2433 SAFE_FREE ();
2435 return ret;
2438 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2439 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2440 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2441 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2442 (Lisp_Object function, Lisp_Object sequence)
2444 register int leni;
2446 leni = XFASTINT (Flength (sequence));
2447 if (CHAR_TABLE_P (sequence))
2448 wrong_type_argument (Qlistp, sequence);
2449 mapcar1 (leni, 0, function, sequence);
2451 return sequence;
2454 /* Anything that calls this function must protect from GC! */
2456 DEFUN ("y-or-n-p", Fy_or_n_p, Sy_or_n_p, 1, 1, 0,
2457 doc: /* Ask user a "y or n" question. Return t if answer is "y".
2458 Takes one argument, which is the string to display to ask the question.
2459 It should end in a space; `y-or-n-p' adds `(y or n) ' to it.
2460 No confirmation of the answer is requested; a single character is enough.
2461 Also accepts Space to mean yes, or Delete to mean no. \(Actually, it uses
2462 the bindings in `query-replace-map'; see the documentation of that variable
2463 for more information. In this case, the useful bindings are `act', `skip',
2464 `recenter', and `quit'.\)
2466 Under a windowing system a dialog box will be used if `last-nonmenu-event'
2467 is nil and `use-dialog-box' is non-nil. */)
2468 (Lisp_Object prompt)
2470 register Lisp_Object obj, key, def, map;
2471 register int answer;
2472 Lisp_Object xprompt;
2473 Lisp_Object args[2];
2474 struct gcpro gcpro1, gcpro2;
2475 int count = SPECPDL_INDEX ();
2477 specbind (Qcursor_in_echo_area, Qt);
2479 map = Fsymbol_value (intern ("query-replace-map"));
2481 CHECK_STRING (prompt);
2482 xprompt = prompt;
2483 GCPRO2 (prompt, xprompt);
2485 #ifdef HAVE_WINDOW_SYSTEM
2486 if (display_hourglass_p)
2487 cancel_hourglass ();
2488 #endif
2490 while (1)
2493 #ifdef HAVE_MENUS
2494 if (FRAME_WINDOW_P (SELECTED_FRAME ())
2495 && (NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2496 && use_dialog_box
2497 && have_menus_p ())
2499 Lisp_Object pane, menu;
2500 redisplay_preserve_echo_area (3);
2501 pane = Fcons (Fcons (build_string ("Yes"), Qt),
2502 Fcons (Fcons (build_string ("No"), Qnil),
2503 Qnil));
2504 menu = Fcons (prompt, pane);
2505 obj = Fx_popup_dialog (Qt, menu, Qnil);
2506 answer = !NILP (obj);
2507 break;
2509 #endif /* HAVE_MENUS */
2510 cursor_in_echo_area = 1;
2511 choose_minibuf_frame ();
2514 Lisp_Object pargs[3];
2516 /* Colorize prompt according to `minibuffer-prompt' face. */
2517 pargs[0] = build_string ("%s(y or n) ");
2518 pargs[1] = intern ("face");
2519 pargs[2] = intern ("minibuffer-prompt");
2520 args[0] = Fpropertize (3, pargs);
2521 args[1] = xprompt;
2522 Fmessage (2, args);
2525 if (minibuffer_auto_raise)
2527 Lisp_Object mini_frame;
2529 mini_frame = WINDOW_FRAME (XWINDOW (minibuf_window));
2531 Fraise_frame (mini_frame);
2534 temporarily_switch_to_single_kboard (SELECTED_FRAME ());
2535 obj = read_filtered_event (1, 0, 0, 0, Qnil);
2536 cursor_in_echo_area = 0;
2537 /* If we need to quit, quit with cursor_in_echo_area = 0. */
2538 QUIT;
2540 key = Fmake_vector (make_number (1), obj);
2541 def = Flookup_key (map, key, Qt);
2543 if (EQ (def, intern ("skip")))
2545 answer = 0;
2546 break;
2548 else if (EQ (def, intern ("act")))
2550 answer = 1;
2551 break;
2553 else if (EQ (def, intern ("recenter")))
2555 Frecenter (Qnil);
2556 xprompt = prompt;
2557 continue;
2559 else if (EQ (def, intern ("quit")))
2560 Vquit_flag = Qt;
2561 /* We want to exit this command for exit-prefix,
2562 and this is the only way to do it. */
2563 else if (EQ (def, intern ("exit-prefix")))
2564 Vquit_flag = Qt;
2566 QUIT;
2568 /* If we don't clear this, then the next call to read_char will
2569 return quit_char again, and we'll enter an infinite loop. */
2570 Vquit_flag = Qnil;
2572 Fding (Qnil);
2573 Fdiscard_input ();
2574 if (EQ (xprompt, prompt))
2576 args[0] = build_string ("Please answer y or n. ");
2577 args[1] = prompt;
2578 xprompt = Fconcat (2, args);
2581 UNGCPRO;
2583 if (! noninteractive)
2585 cursor_in_echo_area = -1;
2586 message_with_string (answer ? "%s(y or n) y" : "%s(y or n) n",
2587 xprompt, 0);
2590 unbind_to (count, Qnil);
2591 return answer ? Qt : Qnil;
2594 /* This is how C code calls `yes-or-no-p' and allows the user
2595 to redefined it.
2597 Anything that calls this function must protect from GC! */
2599 Lisp_Object
2600 do_yes_or_no_p (Lisp_Object prompt)
2602 return call1 (intern ("yes-or-no-p"), prompt);
2605 /* Anything that calls this function must protect from GC! */
2607 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2608 doc: /* Ask user a yes-or-no question. Return t if answer is yes.
2609 Takes one argument, which is the string to display to ask the question.
2610 It should end in a space; `yes-or-no-p' adds `(yes or no) ' to it.
2611 The user must confirm the answer with RET,
2612 and can edit it until it has been confirmed.
2614 Under a windowing system a dialog box will be used if `last-nonmenu-event'
2615 is nil, and `use-dialog-box' is non-nil. */)
2616 (Lisp_Object prompt)
2618 register Lisp_Object ans;
2619 Lisp_Object args[2];
2620 struct gcpro gcpro1;
2622 CHECK_STRING (prompt);
2624 #ifdef HAVE_MENUS
2625 if (FRAME_WINDOW_P (SELECTED_FRAME ())
2626 && (NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2627 && use_dialog_box
2628 && have_menus_p ())
2630 Lisp_Object pane, menu, obj;
2631 redisplay_preserve_echo_area (4);
2632 pane = Fcons (Fcons (build_string ("Yes"), Qt),
2633 Fcons (Fcons (build_string ("No"), Qnil),
2634 Qnil));
2635 GCPRO1 (pane);
2636 menu = Fcons (prompt, pane);
2637 obj = Fx_popup_dialog (Qt, menu, Qnil);
2638 UNGCPRO;
2639 return obj;
2641 #endif /* HAVE_MENUS */
2643 args[0] = prompt;
2644 args[1] = build_string ("(yes or no) ");
2645 prompt = Fconcat (2, args);
2647 GCPRO1 (prompt);
2649 while (1)
2651 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2652 Qyes_or_no_p_history, Qnil,
2653 Qnil));
2654 if (SCHARS (ans) == 3 && !strcmp (SDATA (ans), "yes"))
2656 UNGCPRO;
2657 return Qt;
2659 if (SCHARS (ans) == 2 && !strcmp (SDATA (ans), "no"))
2661 UNGCPRO;
2662 return Qnil;
2665 Fding (Qnil);
2666 Fdiscard_input ();
2667 message ("Please answer yes or no.");
2668 Fsleep_for (make_number (2), Qnil);
2672 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2673 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2675 Each of the three load averages is multiplied by 100, then converted
2676 to integer.
2678 When USE-FLOATS is non-nil, floats will be used instead of integers.
2679 These floats are not multiplied by 100.
2681 If the 5-minute or 15-minute load averages are not available, return a
2682 shortened list, containing only those averages which are available.
2684 An error is thrown if the load average can't be obtained. In some
2685 cases making it work would require Emacs being installed setuid or
2686 setgid so that it can read kernel information, and that usually isn't
2687 advisable. */)
2688 (Lisp_Object use_floats)
2690 double load_ave[3];
2691 int loads = getloadavg (load_ave, 3);
2692 Lisp_Object ret = Qnil;
2694 if (loads < 0)
2695 error ("load-average not implemented for this operating system");
2697 while (loads-- > 0)
2699 Lisp_Object load = (NILP (use_floats) ?
2700 make_number ((int) (100.0 * load_ave[loads]))
2701 : make_float (load_ave[loads]));
2702 ret = Fcons (load, ret);
2705 return ret;
2708 Lisp_Object Vfeatures, Qsubfeatures;
2709 extern Lisp_Object Vafter_load_alist;
2711 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2712 doc: /* Returns t if FEATURE is present in this Emacs.
2714 Use this to conditionalize execution of lisp code based on the
2715 presence or absence of Emacs or environment extensions.
2716 Use `provide' to declare that a feature is available. This function
2717 looks at the value of the variable `features'. The optional argument
2718 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2719 (Lisp_Object feature, Lisp_Object subfeature)
2721 register Lisp_Object tem;
2722 CHECK_SYMBOL (feature);
2723 tem = Fmemq (feature, Vfeatures);
2724 if (!NILP (tem) && !NILP (subfeature))
2725 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2726 return (NILP (tem)) ? Qnil : Qt;
2729 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2730 doc: /* Announce that FEATURE is a feature of the current Emacs.
2731 The optional argument SUBFEATURES should be a list of symbols listing
2732 particular subfeatures supported in this version of FEATURE. */)
2733 (Lisp_Object feature, Lisp_Object subfeatures)
2735 register Lisp_Object tem;
2736 CHECK_SYMBOL (feature);
2737 CHECK_LIST (subfeatures);
2738 if (!NILP (Vautoload_queue))
2739 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2740 Vautoload_queue);
2741 tem = Fmemq (feature, Vfeatures);
2742 if (NILP (tem))
2743 Vfeatures = Fcons (feature, Vfeatures);
2744 if (!NILP (subfeatures))
2745 Fput (feature, Qsubfeatures, subfeatures);
2746 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2748 /* Run any load-hooks for this file. */
2749 tem = Fassq (feature, Vafter_load_alist);
2750 if (CONSP (tem))
2751 Fprogn (XCDR (tem));
2753 return feature;
2756 /* `require' and its subroutines. */
2758 /* List of features currently being require'd, innermost first. */
2760 Lisp_Object require_nesting_list;
2762 Lisp_Object
2763 require_unwind (Lisp_Object old_value)
2765 return require_nesting_list = old_value;
2768 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2769 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2770 If FEATURE is not a member of the list `features', then the feature
2771 is not loaded; so load the file FILENAME.
2772 If FILENAME is omitted, the printname of FEATURE is used as the file name,
2773 and `load' will try to load this name appended with the suffix `.elc' or
2774 `.el', in that order. The name without appended suffix will not be used.
2775 If the optional third argument NOERROR is non-nil,
2776 then return nil if the file is not found instead of signaling an error.
2777 Normally the return value is FEATURE.
2778 The normal messages at start and end of loading FILENAME are suppressed. */)
2779 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2781 register Lisp_Object tem;
2782 struct gcpro gcpro1, gcpro2;
2783 int from_file = load_in_progress;
2785 CHECK_SYMBOL (feature);
2787 /* Record the presence of `require' in this file
2788 even if the feature specified is already loaded.
2789 But not more than once in any file,
2790 and not when we aren't loading or reading from a file. */
2791 if (!from_file)
2792 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2793 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2794 from_file = 1;
2796 if (from_file)
2798 tem = Fcons (Qrequire, feature);
2799 if (NILP (Fmember (tem, Vcurrent_load_list)))
2800 LOADHIST_ATTACH (tem);
2802 tem = Fmemq (feature, Vfeatures);
2804 if (NILP (tem))
2806 int count = SPECPDL_INDEX ();
2807 int nesting = 0;
2809 /* This is to make sure that loadup.el gives a clear picture
2810 of what files are preloaded and when. */
2811 if (! NILP (Vpurify_flag))
2812 error ("(require %s) while preparing to dump",
2813 SDATA (SYMBOL_NAME (feature)));
2815 /* A certain amount of recursive `require' is legitimate,
2816 but if we require the same feature recursively 3 times,
2817 signal an error. */
2818 tem = require_nesting_list;
2819 while (! NILP (tem))
2821 if (! NILP (Fequal (feature, XCAR (tem))))
2822 nesting++;
2823 tem = XCDR (tem);
2825 if (nesting > 3)
2826 error ("Recursive `require' for feature `%s'",
2827 SDATA (SYMBOL_NAME (feature)));
2829 /* Update the list for any nested `require's that occur. */
2830 record_unwind_protect (require_unwind, require_nesting_list);
2831 require_nesting_list = Fcons (feature, require_nesting_list);
2833 /* Value saved here is to be restored into Vautoload_queue */
2834 record_unwind_protect (un_autoload, Vautoload_queue);
2835 Vautoload_queue = Qt;
2837 /* Load the file. */
2838 GCPRO2 (feature, filename);
2839 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2840 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2841 UNGCPRO;
2843 /* If load failed entirely, return nil. */
2844 if (NILP (tem))
2845 return unbind_to (count, Qnil);
2847 tem = Fmemq (feature, Vfeatures);
2848 if (NILP (tem))
2849 error ("Required feature `%s' was not provided",
2850 SDATA (SYMBOL_NAME (feature)));
2852 /* Once loading finishes, don't undo it. */
2853 Vautoload_queue = Qt;
2854 feature = unbind_to (count, feature);
2857 return feature;
2860 /* Primitives for work of the "widget" library.
2861 In an ideal world, this section would not have been necessary.
2862 However, lisp function calls being as slow as they are, it turns
2863 out that some functions in the widget library (wid-edit.el) are the
2864 bottleneck of Widget operation. Here is their translation to C,
2865 for the sole reason of efficiency. */
2867 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2868 doc: /* Return non-nil if PLIST has the property PROP.
2869 PLIST is a property list, which is a list of the form
2870 \(PROP1 VALUE1 PROP2 VALUE2 ...\). PROP is a symbol.
2871 Unlike `plist-get', this allows you to distinguish between a missing
2872 property and a property with the value nil.
2873 The value is actually the tail of PLIST whose car is PROP. */)
2874 (Lisp_Object plist, Lisp_Object prop)
2876 while (CONSP (plist) && !EQ (XCAR (plist), prop))
2878 QUIT;
2879 plist = XCDR (plist);
2880 plist = CDR (plist);
2882 return plist;
2885 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2886 doc: /* In WIDGET, set PROPERTY to VALUE.
2887 The value can later be retrieved with `widget-get'. */)
2888 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2890 CHECK_CONS (widget);
2891 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
2892 return value;
2895 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
2896 doc: /* In WIDGET, get the value of PROPERTY.
2897 The value could either be specified when the widget was created, or
2898 later with `widget-put'. */)
2899 (Lisp_Object widget, Lisp_Object property)
2901 Lisp_Object tmp;
2903 while (1)
2905 if (NILP (widget))
2906 return Qnil;
2907 CHECK_CONS (widget);
2908 tmp = Fplist_member (XCDR (widget), property);
2909 if (CONSP (tmp))
2911 tmp = XCDR (tmp);
2912 return CAR (tmp);
2914 tmp = XCAR (widget);
2915 if (NILP (tmp))
2916 return Qnil;
2917 widget = Fget (tmp, Qwidget_type);
2921 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
2922 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2923 ARGS are passed as extra arguments to the function.
2924 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2925 (int nargs, Lisp_Object *args)
2927 /* This function can GC. */
2928 Lisp_Object newargs[3];
2929 struct gcpro gcpro1, gcpro2;
2930 Lisp_Object result;
2932 newargs[0] = Fwidget_get (args[0], args[1]);
2933 newargs[1] = args[0];
2934 newargs[2] = Flist (nargs - 2, args + 2);
2935 GCPRO2 (newargs[0], newargs[2]);
2936 result = Fapply (3, newargs);
2937 UNGCPRO;
2938 return result;
2941 #ifdef HAVE_LANGINFO_CODESET
2942 #include <langinfo.h>
2943 #endif
2945 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
2946 doc: /* Access locale data ITEM for the current C locale, if available.
2947 ITEM should be one of the following:
2949 `codeset', returning the character set as a string (locale item CODESET);
2951 `days', returning a 7-element vector of day names (locale items DAY_n);
2953 `months', returning a 12-element vector of month names (locale items MON_n);
2955 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
2956 both measured in milimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
2958 If the system can't provide such information through a call to
2959 `nl_langinfo', or if ITEM isn't from the list above, return nil.
2961 See also Info node `(libc)Locales'.
2963 The data read from the system are decoded using `locale-coding-system'. */)
2964 (Lisp_Object item)
2966 char *str = NULL;
2967 #ifdef HAVE_LANGINFO_CODESET
2968 Lisp_Object val;
2969 if (EQ (item, Qcodeset))
2971 str = nl_langinfo (CODESET);
2972 return build_string (str);
2974 #ifdef DAY_1
2975 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
2977 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
2978 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
2979 int i;
2980 struct gcpro gcpro1;
2981 GCPRO1 (v);
2982 synchronize_system_time_locale ();
2983 for (i = 0; i < 7; i++)
2985 str = nl_langinfo (days[i]);
2986 val = make_unibyte_string (str, strlen (str));
2987 /* Fixme: Is this coding system necessarily right, even if
2988 it is consistent with CODESET? If not, what to do? */
2989 Faset (v, make_number (i),
2990 code_convert_string_norecord (val, Vlocale_coding_system,
2991 0));
2993 UNGCPRO;
2994 return v;
2996 #endif /* DAY_1 */
2997 #ifdef MON_1
2998 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
3000 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
3001 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
3002 MON_8, MON_9, MON_10, MON_11, MON_12};
3003 int i;
3004 struct gcpro gcpro1;
3005 GCPRO1 (v);
3006 synchronize_system_time_locale ();
3007 for (i = 0; i < 12; i++)
3009 str = nl_langinfo (months[i]);
3010 val = make_unibyte_string (str, strlen (str));
3011 Faset (v, make_number (i),
3012 code_convert_string_norecord (val, Vlocale_coding_system, 0));
3014 UNGCPRO;
3015 return v;
3017 #endif /* MON_1 */
3018 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
3019 but is in the locale files. This could be used by ps-print. */
3020 #ifdef PAPER_WIDTH
3021 else if (EQ (item, Qpaper))
3023 return list2 (make_number (nl_langinfo (PAPER_WIDTH)),
3024 make_number (nl_langinfo (PAPER_HEIGHT)));
3026 #endif /* PAPER_WIDTH */
3027 #endif /* HAVE_LANGINFO_CODESET*/
3028 return Qnil;
3031 /* base64 encode/decode functions (RFC 2045).
3032 Based on code from GNU recode. */
3034 #define MIME_LINE_LENGTH 76
3036 #define IS_ASCII(Character) \
3037 ((Character) < 128)
3038 #define IS_BASE64(Character) \
3039 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
3040 #define IS_BASE64_IGNORABLE(Character) \
3041 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
3042 || (Character) == '\f' || (Character) == '\r')
3044 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
3045 character or return retval if there are no characters left to
3046 process. */
3047 #define READ_QUADRUPLET_BYTE(retval) \
3048 do \
3050 if (i == length) \
3052 if (nchars_return) \
3053 *nchars_return = nchars; \
3054 return (retval); \
3056 c = from[i++]; \
3058 while (IS_BASE64_IGNORABLE (c))
3060 /* Table of characters coding the 64 values. */
3061 static const char base64_value_to_char[64] =
3063 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
3064 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
3065 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
3066 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
3067 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
3068 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
3069 '8', '9', '+', '/' /* 60-63 */
3072 /* Table of base64 values for first 128 characters. */
3073 static const short base64_char_to_value[128] =
3075 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
3076 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
3077 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
3078 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
3079 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
3080 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
3081 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
3082 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
3083 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
3084 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
3085 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
3086 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
3087 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
3090 /* The following diagram shows the logical steps by which three octets
3091 get transformed into four base64 characters.
3093 .--------. .--------. .--------.
3094 |aaaaaabb| |bbbbcccc| |ccdddddd|
3095 `--------' `--------' `--------'
3096 6 2 4 4 2 6
3097 .--------+--------+--------+--------.
3098 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
3099 `--------+--------+--------+--------'
3101 .--------+--------+--------+--------.
3102 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
3103 `--------+--------+--------+--------'
3105 The octets are divided into 6 bit chunks, which are then encoded into
3106 base64 characters. */
3109 static int base64_encode_1 (const char *, char *, int, int, int);
3110 static int base64_decode_1 (const char *, char *, int, int, int *);
3112 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
3113 2, 3, "r",
3114 doc: /* Base64-encode the region between BEG and END.
3115 Return the length of the encoded text.
3116 Optional third argument NO-LINE-BREAK means do not break long lines
3117 into shorter lines. */)
3118 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
3120 char *encoded;
3121 int allength, length;
3122 int ibeg, iend, encoded_length;
3123 int old_pos = PT;
3124 USE_SAFE_ALLOCA;
3126 validate_region (&beg, &end);
3128 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3129 iend = CHAR_TO_BYTE (XFASTINT (end));
3130 move_gap_both (XFASTINT (beg), ibeg);
3132 /* We need to allocate enough room for encoding the text.
3133 We need 33 1/3% more space, plus a newline every 76
3134 characters, and then we round up. */
3135 length = iend - ibeg;
3136 allength = length + length/3 + 1;
3137 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3139 SAFE_ALLOCA (encoded, char *, allength);
3140 encoded_length = base64_encode_1 (BYTE_POS_ADDR (ibeg), encoded, length,
3141 NILP (no_line_break),
3142 !NILP (current_buffer->enable_multibyte_characters));
3143 if (encoded_length > allength)
3144 abort ();
3146 if (encoded_length < 0)
3148 /* The encoding wasn't possible. */
3149 SAFE_FREE ();
3150 error ("Multibyte character in data for base64 encoding");
3153 /* Now we have encoded the region, so we insert the new contents
3154 and delete the old. (Insert first in order to preserve markers.) */
3155 SET_PT_BOTH (XFASTINT (beg), ibeg);
3156 insert (encoded, encoded_length);
3157 SAFE_FREE ();
3158 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
3160 /* If point was outside of the region, restore it exactly; else just
3161 move to the beginning of the region. */
3162 if (old_pos >= XFASTINT (end))
3163 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
3164 else if (old_pos > XFASTINT (beg))
3165 old_pos = XFASTINT (beg);
3166 SET_PT (old_pos);
3168 /* We return the length of the encoded text. */
3169 return make_number (encoded_length);
3172 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
3173 1, 2, 0,
3174 doc: /* Base64-encode STRING and return the result.
3175 Optional second argument NO-LINE-BREAK means do not break long lines
3176 into shorter lines. */)
3177 (Lisp_Object string, Lisp_Object no_line_break)
3179 int allength, length, encoded_length;
3180 char *encoded;
3181 Lisp_Object encoded_string;
3182 USE_SAFE_ALLOCA;
3184 CHECK_STRING (string);
3186 /* We need to allocate enough room for encoding the text.
3187 We need 33 1/3% more space, plus a newline every 76
3188 characters, and then we round up. */
3189 length = SBYTES (string);
3190 allength = length + length/3 + 1;
3191 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3193 /* We need to allocate enough room for decoding the text. */
3194 SAFE_ALLOCA (encoded, char *, allength);
3196 encoded_length = base64_encode_1 (SDATA (string),
3197 encoded, length, NILP (no_line_break),
3198 STRING_MULTIBYTE (string));
3199 if (encoded_length > allength)
3200 abort ();
3202 if (encoded_length < 0)
3204 /* The encoding wasn't possible. */
3205 SAFE_FREE ();
3206 error ("Multibyte character in data for base64 encoding");
3209 encoded_string = make_unibyte_string (encoded, encoded_length);
3210 SAFE_FREE ();
3212 return encoded_string;
3215 static int
3216 base64_encode_1 (const char *from, char *to, int length, int line_break, int multibyte)
3218 int counter = 0, i = 0;
3219 char *e = to;
3220 int c;
3221 unsigned int value;
3222 int bytes;
3224 while (i < length)
3226 if (multibyte)
3228 c = STRING_CHAR_AND_LENGTH (from + i, bytes);
3229 if (CHAR_BYTE8_P (c))
3230 c = CHAR_TO_BYTE8 (c);
3231 else if (c >= 256)
3232 return -1;
3233 i += bytes;
3235 else
3236 c = from[i++];
3238 /* Wrap line every 76 characters. */
3240 if (line_break)
3242 if (counter < MIME_LINE_LENGTH / 4)
3243 counter++;
3244 else
3246 *e++ = '\n';
3247 counter = 1;
3251 /* Process first byte of a triplet. */
3253 *e++ = base64_value_to_char[0x3f & c >> 2];
3254 value = (0x03 & c) << 4;
3256 /* Process second byte of a triplet. */
3258 if (i == length)
3260 *e++ = base64_value_to_char[value];
3261 *e++ = '=';
3262 *e++ = '=';
3263 break;
3266 if (multibyte)
3268 c = STRING_CHAR_AND_LENGTH (from + i, bytes);
3269 if (CHAR_BYTE8_P (c))
3270 c = CHAR_TO_BYTE8 (c);
3271 else if (c >= 256)
3272 return -1;
3273 i += bytes;
3275 else
3276 c = from[i++];
3278 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3279 value = (0x0f & c) << 2;
3281 /* Process third byte of a triplet. */
3283 if (i == length)
3285 *e++ = base64_value_to_char[value];
3286 *e++ = '=';
3287 break;
3290 if (multibyte)
3292 c = STRING_CHAR_AND_LENGTH (from + i, bytes);
3293 if (CHAR_BYTE8_P (c))
3294 c = CHAR_TO_BYTE8 (c);
3295 else if (c >= 256)
3296 return -1;
3297 i += bytes;
3299 else
3300 c = from[i++];
3302 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3303 *e++ = base64_value_to_char[0x3f & c];
3306 return e - to;
3310 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3311 2, 2, "r",
3312 doc: /* Base64-decode the region between BEG and END.
3313 Return the length of the decoded text.
3314 If the region can't be decoded, signal an error and don't modify the buffer. */)
3315 (Lisp_Object beg, Lisp_Object end)
3317 int ibeg, iend, length, allength;
3318 char *decoded;
3319 int old_pos = PT;
3320 int decoded_length;
3321 int inserted_chars;
3322 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
3323 USE_SAFE_ALLOCA;
3325 validate_region (&beg, &end);
3327 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3328 iend = CHAR_TO_BYTE (XFASTINT (end));
3330 length = iend - ibeg;
3332 /* We need to allocate enough room for decoding the text. If we are
3333 working on a multibyte buffer, each decoded code may occupy at
3334 most two bytes. */
3335 allength = multibyte ? length * 2 : length;
3336 SAFE_ALLOCA (decoded, char *, allength);
3338 move_gap_both (XFASTINT (beg), ibeg);
3339 decoded_length = base64_decode_1 (BYTE_POS_ADDR (ibeg), decoded, length,
3340 multibyte, &inserted_chars);
3341 if (decoded_length > allength)
3342 abort ();
3344 if (decoded_length < 0)
3346 /* The decoding wasn't possible. */
3347 SAFE_FREE ();
3348 error ("Invalid base64 data");
3351 /* Now we have decoded the region, so we insert the new contents
3352 and delete the old. (Insert first in order to preserve markers.) */
3353 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3354 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3355 SAFE_FREE ();
3357 /* Delete the original text. */
3358 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3359 iend + decoded_length, 1);
3361 /* If point was outside of the region, restore it exactly; else just
3362 move to the beginning of the region. */
3363 if (old_pos >= XFASTINT (end))
3364 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3365 else if (old_pos > XFASTINT (beg))
3366 old_pos = XFASTINT (beg);
3367 SET_PT (old_pos > ZV ? ZV : old_pos);
3369 return make_number (inserted_chars);
3372 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3373 1, 1, 0,
3374 doc: /* Base64-decode STRING and return the result. */)
3375 (Lisp_Object string)
3377 char *decoded;
3378 int length, decoded_length;
3379 Lisp_Object decoded_string;
3380 USE_SAFE_ALLOCA;
3382 CHECK_STRING (string);
3384 length = SBYTES (string);
3385 /* We need to allocate enough room for decoding the text. */
3386 SAFE_ALLOCA (decoded, char *, length);
3388 /* The decoded result should be unibyte. */
3389 decoded_length = base64_decode_1 (SDATA (string), decoded, length,
3390 0, NULL);
3391 if (decoded_length > length)
3392 abort ();
3393 else if (decoded_length >= 0)
3394 decoded_string = make_unibyte_string (decoded, decoded_length);
3395 else
3396 decoded_string = Qnil;
3398 SAFE_FREE ();
3399 if (!STRINGP (decoded_string))
3400 error ("Invalid base64 data");
3402 return decoded_string;
3405 /* Base64-decode the data at FROM of LENGHT bytes into TO. If
3406 MULTIBYTE is nonzero, the decoded result should be in multibyte
3407 form. If NCHARS_RETRUN is not NULL, store the number of produced
3408 characters in *NCHARS_RETURN. */
3410 static int
3411 base64_decode_1 (const char *from, char *to, int length, int multibyte, int *nchars_return)
3413 int i = 0;
3414 char *e = to;
3415 unsigned char c;
3416 unsigned long value;
3417 int nchars = 0;
3419 while (1)
3421 /* Process first byte of a quadruplet. */
3423 READ_QUADRUPLET_BYTE (e-to);
3425 if (!IS_BASE64 (c))
3426 return -1;
3427 value = base64_char_to_value[c] << 18;
3429 /* Process second byte of a quadruplet. */
3431 READ_QUADRUPLET_BYTE (-1);
3433 if (!IS_BASE64 (c))
3434 return -1;
3435 value |= base64_char_to_value[c] << 12;
3437 c = (unsigned char) (value >> 16);
3438 if (multibyte && c >= 128)
3439 e += BYTE8_STRING (c, e);
3440 else
3441 *e++ = c;
3442 nchars++;
3444 /* Process third byte of a quadruplet. */
3446 READ_QUADRUPLET_BYTE (-1);
3448 if (c == '=')
3450 READ_QUADRUPLET_BYTE (-1);
3452 if (c != '=')
3453 return -1;
3454 continue;
3457 if (!IS_BASE64 (c))
3458 return -1;
3459 value |= base64_char_to_value[c] << 6;
3461 c = (unsigned char) (0xff & value >> 8);
3462 if (multibyte && c >= 128)
3463 e += BYTE8_STRING (c, e);
3464 else
3465 *e++ = c;
3466 nchars++;
3468 /* Process fourth byte of a quadruplet. */
3470 READ_QUADRUPLET_BYTE (-1);
3472 if (c == '=')
3473 continue;
3475 if (!IS_BASE64 (c))
3476 return -1;
3477 value |= base64_char_to_value[c];
3479 c = (unsigned char) (0xff & value);
3480 if (multibyte && c >= 128)
3481 e += BYTE8_STRING (c, e);
3482 else
3483 *e++ = c;
3484 nchars++;
3490 /***********************************************************************
3491 ***** *****
3492 ***** Hash Tables *****
3493 ***** *****
3494 ***********************************************************************/
3496 /* Implemented by gerd@gnu.org. This hash table implementation was
3497 inspired by CMUCL hash tables. */
3499 /* Ideas:
3501 1. For small tables, association lists are probably faster than
3502 hash tables because they have lower overhead.
3504 For uses of hash tables where the O(1) behavior of table
3505 operations is not a requirement, it might therefore be a good idea
3506 not to hash. Instead, we could just do a linear search in the
3507 key_and_value vector of the hash table. This could be done
3508 if a `:linear-search t' argument is given to make-hash-table. */
3511 /* The list of all weak hash tables. Don't staticpro this one. */
3513 struct Lisp_Hash_Table *weak_hash_tables;
3515 /* Various symbols. */
3517 Lisp_Object Qhash_table_p, Qeq, Qeql, Qequal, Qkey, Qvalue;
3518 Lisp_Object QCtest, QCsize, QCrehash_size, QCrehash_threshold, QCweakness;
3519 Lisp_Object Qhash_table_test, Qkey_or_value, Qkey_and_value;
3521 /* Function prototypes. */
3523 static struct Lisp_Hash_Table *check_hash_table (Lisp_Object);
3524 static int get_key_arg (Lisp_Object, int, Lisp_Object *, char *);
3525 static void maybe_resize_hash_table (struct Lisp_Hash_Table *);
3526 static int cmpfn_eql (struct Lisp_Hash_Table *, Lisp_Object, unsigned,
3527 Lisp_Object, unsigned);
3528 static int cmpfn_equal (struct Lisp_Hash_Table *, Lisp_Object, unsigned,
3529 Lisp_Object, unsigned);
3530 static int cmpfn_user_defined (struct Lisp_Hash_Table *, Lisp_Object,
3531 unsigned, Lisp_Object, unsigned);
3532 static unsigned hashfn_eq (struct Lisp_Hash_Table *, Lisp_Object);
3533 static unsigned hashfn_eql (struct Lisp_Hash_Table *, Lisp_Object);
3534 static unsigned hashfn_equal (struct Lisp_Hash_Table *, Lisp_Object);
3535 static unsigned hashfn_user_defined (struct Lisp_Hash_Table *,
3536 Lisp_Object);
3537 static unsigned sxhash_string (unsigned char *, int);
3538 static unsigned sxhash_list (Lisp_Object, int);
3539 static unsigned sxhash_vector (Lisp_Object, int);
3540 static unsigned sxhash_bool_vector (Lisp_Object);
3541 static int sweep_weak_table (struct Lisp_Hash_Table *, int);
3545 /***********************************************************************
3546 Utilities
3547 ***********************************************************************/
3549 /* If OBJ is a Lisp hash table, return a pointer to its struct
3550 Lisp_Hash_Table. Otherwise, signal an error. */
3552 static struct Lisp_Hash_Table *
3553 check_hash_table (Lisp_Object obj)
3555 CHECK_HASH_TABLE (obj);
3556 return XHASH_TABLE (obj);
3560 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3561 number. */
3564 next_almost_prime (int n)
3566 if (n % 2 == 0)
3567 n += 1;
3568 if (n % 3 == 0)
3569 n += 2;
3570 if (n % 7 == 0)
3571 n += 4;
3572 return n;
3576 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3577 which USED[I] is non-zero. If found at index I in ARGS, set
3578 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3579 -1. This function is used to extract a keyword/argument pair from
3580 a DEFUN parameter list. */
3582 static int
3583 get_key_arg (Lisp_Object key, int nargs, Lisp_Object *args, char *used)
3585 int i;
3587 for (i = 0; i < nargs - 1; ++i)
3588 if (!used[i] && EQ (args[i], key))
3589 break;
3591 if (i >= nargs - 1)
3592 i = -1;
3593 else
3595 used[i++] = 1;
3596 used[i] = 1;
3599 return i;
3603 /* Return a Lisp vector which has the same contents as VEC but has
3604 size NEW_SIZE, NEW_SIZE >= VEC->size. Entries in the resulting
3605 vector that are not copied from VEC are set to INIT. */
3607 Lisp_Object
3608 larger_vector (Lisp_Object vec, int new_size, Lisp_Object init)
3610 struct Lisp_Vector *v;
3611 int i, old_size;
3613 xassert (VECTORP (vec));
3614 old_size = ASIZE (vec);
3615 xassert (new_size >= old_size);
3617 v = allocate_vector (new_size);
3618 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3619 for (i = old_size; i < new_size; ++i)
3620 v->contents[i] = init;
3621 XSETVECTOR (vec, v);
3622 return vec;
3626 /***********************************************************************
3627 Low-level Functions
3628 ***********************************************************************/
3630 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3631 HASH2 in hash table H using `eql'. Value is non-zero if KEY1 and
3632 KEY2 are the same. */
3634 static int
3635 cmpfn_eql (struct Lisp_Hash_Table *h, Lisp_Object key1, unsigned int hash1, Lisp_Object key2, unsigned int hash2)
3637 return (FLOATP (key1)
3638 && FLOATP (key2)
3639 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3643 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3644 HASH2 in hash table H using `equal'. Value is non-zero if KEY1 and
3645 KEY2 are the same. */
3647 static int
3648 cmpfn_equal (struct Lisp_Hash_Table *h, Lisp_Object key1, unsigned int hash1, Lisp_Object key2, unsigned int hash2)
3650 return hash1 == hash2 && !NILP (Fequal (key1, key2));
3654 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3655 HASH2 in hash table H using H->user_cmp_function. Value is non-zero
3656 if KEY1 and KEY2 are the same. */
3658 static int
3659 cmpfn_user_defined (struct Lisp_Hash_Table *h, Lisp_Object key1, unsigned int hash1, Lisp_Object key2, unsigned int hash2)
3661 if (hash1 == hash2)
3663 Lisp_Object args[3];
3665 args[0] = h->user_cmp_function;
3666 args[1] = key1;
3667 args[2] = key2;
3668 return !NILP (Ffuncall (3, args));
3670 else
3671 return 0;
3675 /* Value is a hash code for KEY for use in hash table H which uses
3676 `eq' to compare keys. The hash code returned is guaranteed to fit
3677 in a Lisp integer. */
3679 static unsigned
3680 hashfn_eq (struct Lisp_Hash_Table *h, Lisp_Object key)
3682 unsigned hash = XUINT (key) ^ XTYPE (key);
3683 xassert ((hash & ~INTMASK) == 0);
3684 return hash;
3688 /* Value is a hash code for KEY for use in hash table H which uses
3689 `eql' to compare keys. The hash code returned is guaranteed to fit
3690 in a Lisp integer. */
3692 static unsigned
3693 hashfn_eql (struct Lisp_Hash_Table *h, Lisp_Object key)
3695 unsigned hash;
3696 if (FLOATP (key))
3697 hash = sxhash (key, 0);
3698 else
3699 hash = XUINT (key) ^ XTYPE (key);
3700 xassert ((hash & ~INTMASK) == 0);
3701 return hash;
3705 /* Value is a hash code for KEY for use in hash table H which uses
3706 `equal' to compare keys. The hash code returned is guaranteed to fit
3707 in a Lisp integer. */
3709 static unsigned
3710 hashfn_equal (struct Lisp_Hash_Table *h, Lisp_Object key)
3712 unsigned hash = sxhash (key, 0);
3713 xassert ((hash & ~INTMASK) == 0);
3714 return hash;
3718 /* Value is a hash code for KEY for use in hash table H which uses as
3719 user-defined function to compare keys. The hash code returned is
3720 guaranteed to fit in a Lisp integer. */
3722 static unsigned
3723 hashfn_user_defined (struct Lisp_Hash_Table *h, Lisp_Object key)
3725 Lisp_Object args[2], hash;
3727 args[0] = h->user_hash_function;
3728 args[1] = key;
3729 hash = Ffuncall (2, args);
3730 if (!INTEGERP (hash))
3731 signal_error ("Invalid hash code returned from user-supplied hash function", hash);
3732 return XUINT (hash);
3736 /* Create and initialize a new hash table.
3738 TEST specifies the test the hash table will use to compare keys.
3739 It must be either one of the predefined tests `eq', `eql' or
3740 `equal' or a symbol denoting a user-defined test named TEST with
3741 test and hash functions USER_TEST and USER_HASH.
3743 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3745 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3746 new size when it becomes full is computed by adding REHASH_SIZE to
3747 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3748 table's new size is computed by multiplying its old size with
3749 REHASH_SIZE.
3751 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3752 be resized when the ratio of (number of entries in the table) /
3753 (table size) is >= REHASH_THRESHOLD.
3755 WEAK specifies the weakness of the table. If non-nil, it must be
3756 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
3758 Lisp_Object
3759 make_hash_table (Lisp_Object test, Lisp_Object size, Lisp_Object rehash_size,
3760 Lisp_Object rehash_threshold, Lisp_Object weak,
3761 Lisp_Object user_test, Lisp_Object user_hash)
3763 struct Lisp_Hash_Table *h;
3764 Lisp_Object table;
3765 int index_size, i, sz;
3767 /* Preconditions. */
3768 xassert (SYMBOLP (test));
3769 xassert (INTEGERP (size) && XINT (size) >= 0);
3770 xassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3771 || (FLOATP (rehash_size) && XFLOATINT (rehash_size) > 1.0));
3772 xassert (FLOATP (rehash_threshold)
3773 && XFLOATINT (rehash_threshold) > 0
3774 && XFLOATINT (rehash_threshold) <= 1.0);
3776 if (XFASTINT (size) == 0)
3777 size = make_number (1);
3779 /* Allocate a table and initialize it. */
3780 h = allocate_hash_table ();
3782 /* Initialize hash table slots. */
3783 sz = XFASTINT (size);
3785 h->test = test;
3786 if (EQ (test, Qeql))
3788 h->cmpfn = cmpfn_eql;
3789 h->hashfn = hashfn_eql;
3791 else if (EQ (test, Qeq))
3793 h->cmpfn = NULL;
3794 h->hashfn = hashfn_eq;
3796 else if (EQ (test, Qequal))
3798 h->cmpfn = cmpfn_equal;
3799 h->hashfn = hashfn_equal;
3801 else
3803 h->user_cmp_function = user_test;
3804 h->user_hash_function = user_hash;
3805 h->cmpfn = cmpfn_user_defined;
3806 h->hashfn = hashfn_user_defined;
3809 h->weak = weak;
3810 h->rehash_threshold = rehash_threshold;
3811 h->rehash_size = rehash_size;
3812 h->count = 0;
3813 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
3814 h->hash = Fmake_vector (size, Qnil);
3815 h->next = Fmake_vector (size, Qnil);
3816 /* Cast to int here avoids losing with gcc 2.95 on Tru64/Alpha... */
3817 index_size = next_almost_prime ((int) (sz / XFLOATINT (rehash_threshold)));
3818 h->index = Fmake_vector (make_number (index_size), Qnil);
3820 /* Set up the free list. */
3821 for (i = 0; i < sz - 1; ++i)
3822 HASH_NEXT (h, i) = make_number (i + 1);
3823 h->next_free = make_number (0);
3825 XSET_HASH_TABLE (table, h);
3826 xassert (HASH_TABLE_P (table));
3827 xassert (XHASH_TABLE (table) == h);
3829 /* Maybe add this hash table to the list of all weak hash tables. */
3830 if (NILP (h->weak))
3831 h->next_weak = NULL;
3832 else
3834 h->next_weak = weak_hash_tables;
3835 weak_hash_tables = h;
3838 return table;
3842 /* Return a copy of hash table H1. Keys and values are not copied,
3843 only the table itself is. */
3845 Lisp_Object
3846 copy_hash_table (struct Lisp_Hash_Table *h1)
3848 Lisp_Object table;
3849 struct Lisp_Hash_Table *h2;
3850 struct Lisp_Vector *next;
3852 h2 = allocate_hash_table ();
3853 next = h2->vec_next;
3854 memcpy (h2, h1, sizeof *h2);
3855 h2->vec_next = next;
3856 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3857 h2->hash = Fcopy_sequence (h1->hash);
3858 h2->next = Fcopy_sequence (h1->next);
3859 h2->index = Fcopy_sequence (h1->index);
3860 XSET_HASH_TABLE (table, h2);
3862 /* Maybe add this hash table to the list of all weak hash tables. */
3863 if (!NILP (h2->weak))
3865 h2->next_weak = weak_hash_tables;
3866 weak_hash_tables = h2;
3869 return table;
3873 /* Resize hash table H if it's too full. If H cannot be resized
3874 because it's already too large, throw an error. */
3876 static INLINE void
3877 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3879 if (NILP (h->next_free))
3881 int old_size = HASH_TABLE_SIZE (h);
3882 int i, new_size, index_size;
3883 EMACS_INT nsize;
3885 if (INTEGERP (h->rehash_size))
3886 new_size = old_size + XFASTINT (h->rehash_size);
3887 else
3888 new_size = old_size * XFLOATINT (h->rehash_size);
3889 new_size = max (old_size + 1, new_size);
3890 index_size = next_almost_prime ((int)
3891 (new_size
3892 / XFLOATINT (h->rehash_threshold)));
3893 /* Assignment to EMACS_INT stops GCC whining about limited range
3894 of data type. */
3895 nsize = max (index_size, 2 * new_size);
3896 if (nsize > MOST_POSITIVE_FIXNUM)
3897 error ("Hash table too large to resize");
3899 h->key_and_value = larger_vector (h->key_and_value, 2 * new_size, Qnil);
3900 h->next = larger_vector (h->next, new_size, Qnil);
3901 h->hash = larger_vector (h->hash, new_size, Qnil);
3902 h->index = Fmake_vector (make_number (index_size), Qnil);
3904 /* Update the free list. Do it so that new entries are added at
3905 the end of the free list. This makes some operations like
3906 maphash faster. */
3907 for (i = old_size; i < new_size - 1; ++i)
3908 HASH_NEXT (h, i) = make_number (i + 1);
3910 if (!NILP (h->next_free))
3912 Lisp_Object last, next;
3914 last = h->next_free;
3915 while (next = HASH_NEXT (h, XFASTINT (last)),
3916 !NILP (next))
3917 last = next;
3919 HASH_NEXT (h, XFASTINT (last)) = make_number (old_size);
3921 else
3922 XSETFASTINT (h->next_free, old_size);
3924 /* Rehash. */
3925 for (i = 0; i < old_size; ++i)
3926 if (!NILP (HASH_HASH (h, i)))
3928 unsigned hash_code = XUINT (HASH_HASH (h, i));
3929 int start_of_bucket = hash_code % ASIZE (h->index);
3930 HASH_NEXT (h, i) = HASH_INDEX (h, start_of_bucket);
3931 HASH_INDEX (h, start_of_bucket) = make_number (i);
3937 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
3938 the hash code of KEY. Value is the index of the entry in H
3939 matching KEY, or -1 if not found. */
3942 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, unsigned int *hash)
3944 unsigned hash_code;
3945 int start_of_bucket;
3946 Lisp_Object idx;
3948 hash_code = h->hashfn (h, key);
3949 if (hash)
3950 *hash = hash_code;
3952 start_of_bucket = hash_code % ASIZE (h->index);
3953 idx = HASH_INDEX (h, start_of_bucket);
3955 /* We need not gcpro idx since it's either an integer or nil. */
3956 while (!NILP (idx))
3958 int i = XFASTINT (idx);
3959 if (EQ (key, HASH_KEY (h, i))
3960 || (h->cmpfn
3961 && h->cmpfn (h, key, hash_code,
3962 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
3963 break;
3964 idx = HASH_NEXT (h, i);
3967 return NILP (idx) ? -1 : XFASTINT (idx);
3971 /* Put an entry into hash table H that associates KEY with VALUE.
3972 HASH is a previously computed hash code of KEY.
3973 Value is the index of the entry in H matching KEY. */
3976 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value, unsigned int hash)
3978 int start_of_bucket, i;
3980 xassert ((hash & ~INTMASK) == 0);
3982 /* Increment count after resizing because resizing may fail. */
3983 maybe_resize_hash_table (h);
3984 h->count++;
3986 /* Store key/value in the key_and_value vector. */
3987 i = XFASTINT (h->next_free);
3988 h->next_free = HASH_NEXT (h, i);
3989 HASH_KEY (h, i) = key;
3990 HASH_VALUE (h, i) = value;
3992 /* Remember its hash code. */
3993 HASH_HASH (h, i) = make_number (hash);
3995 /* Add new entry to its collision chain. */
3996 start_of_bucket = hash % ASIZE (h->index);
3997 HASH_NEXT (h, i) = HASH_INDEX (h, start_of_bucket);
3998 HASH_INDEX (h, start_of_bucket) = make_number (i);
3999 return i;
4003 /* Remove the entry matching KEY from hash table H, if there is one. */
4005 static void
4006 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
4008 unsigned hash_code;
4009 int start_of_bucket;
4010 Lisp_Object idx, prev;
4012 hash_code = h->hashfn (h, key);
4013 start_of_bucket = hash_code % ASIZE (h->index);
4014 idx = HASH_INDEX (h, start_of_bucket);
4015 prev = Qnil;
4017 /* We need not gcpro idx, prev since they're either integers or nil. */
4018 while (!NILP (idx))
4020 int i = XFASTINT (idx);
4022 if (EQ (key, HASH_KEY (h, i))
4023 || (h->cmpfn
4024 && h->cmpfn (h, key, hash_code,
4025 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
4027 /* Take entry out of collision chain. */
4028 if (NILP (prev))
4029 HASH_INDEX (h, start_of_bucket) = HASH_NEXT (h, i);
4030 else
4031 HASH_NEXT (h, XFASTINT (prev)) = HASH_NEXT (h, i);
4033 /* Clear slots in key_and_value and add the slots to
4034 the free list. */
4035 HASH_KEY (h, i) = HASH_VALUE (h, i) = HASH_HASH (h, i) = Qnil;
4036 HASH_NEXT (h, i) = h->next_free;
4037 h->next_free = make_number (i);
4038 h->count--;
4039 xassert (h->count >= 0);
4040 break;
4042 else
4044 prev = idx;
4045 idx = HASH_NEXT (h, i);
4051 /* Clear hash table H. */
4053 void
4054 hash_clear (struct Lisp_Hash_Table *h)
4056 if (h->count > 0)
4058 int i, size = HASH_TABLE_SIZE (h);
4060 for (i = 0; i < size; ++i)
4062 HASH_NEXT (h, i) = i < size - 1 ? make_number (i + 1) : Qnil;
4063 HASH_KEY (h, i) = Qnil;
4064 HASH_VALUE (h, i) = Qnil;
4065 HASH_HASH (h, i) = Qnil;
4068 for (i = 0; i < ASIZE (h->index); ++i)
4069 ASET (h->index, i, Qnil);
4071 h->next_free = make_number (0);
4072 h->count = 0;
4078 /************************************************************************
4079 Weak Hash Tables
4080 ************************************************************************/
4082 void
4083 init_weak_hash_tables (void)
4085 weak_hash_tables = NULL;
4088 /* Sweep weak hash table H. REMOVE_ENTRIES_P non-zero means remove
4089 entries from the table that don't survive the current GC.
4090 REMOVE_ENTRIES_P zero means mark entries that are in use. Value is
4091 non-zero if anything was marked. */
4093 static int
4094 sweep_weak_table (struct Lisp_Hash_Table *h, int remove_entries_p)
4096 int bucket, n, marked;
4098 n = ASIZE (h->index) & ~ARRAY_MARK_FLAG;
4099 marked = 0;
4101 for (bucket = 0; bucket < n; ++bucket)
4103 Lisp_Object idx, next, prev;
4105 /* Follow collision chain, removing entries that
4106 don't survive this garbage collection. */
4107 prev = Qnil;
4108 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
4110 int i = XFASTINT (idx);
4111 int key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
4112 int value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
4113 int remove_p;
4115 if (EQ (h->weak, Qkey))
4116 remove_p = !key_known_to_survive_p;
4117 else if (EQ (h->weak, Qvalue))
4118 remove_p = !value_known_to_survive_p;
4119 else if (EQ (h->weak, Qkey_or_value))
4120 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
4121 else if (EQ (h->weak, Qkey_and_value))
4122 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
4123 else
4124 abort ();
4126 next = HASH_NEXT (h, i);
4128 if (remove_entries_p)
4130 if (remove_p)
4132 /* Take out of collision chain. */
4133 if (NILP (prev))
4134 HASH_INDEX (h, bucket) = next;
4135 else
4136 HASH_NEXT (h, XFASTINT (prev)) = next;
4138 /* Add to free list. */
4139 HASH_NEXT (h, i) = h->next_free;
4140 h->next_free = idx;
4142 /* Clear key, value, and hash. */
4143 HASH_KEY (h, i) = HASH_VALUE (h, i) = Qnil;
4144 HASH_HASH (h, i) = Qnil;
4146 h->count--;
4148 else
4150 prev = idx;
4153 else
4155 if (!remove_p)
4157 /* Make sure key and value survive. */
4158 if (!key_known_to_survive_p)
4160 mark_object (HASH_KEY (h, i));
4161 marked = 1;
4164 if (!value_known_to_survive_p)
4166 mark_object (HASH_VALUE (h, i));
4167 marked = 1;
4174 return marked;
4177 /* Remove elements from weak hash tables that don't survive the
4178 current garbage collection. Remove weak tables that don't survive
4179 from Vweak_hash_tables. Called from gc_sweep. */
4181 void
4182 sweep_weak_hash_tables (void)
4184 struct Lisp_Hash_Table *h, *used, *next;
4185 int marked;
4187 /* Mark all keys and values that are in use. Keep on marking until
4188 there is no more change. This is necessary for cases like
4189 value-weak table A containing an entry X -> Y, where Y is used in a
4190 key-weak table B, Z -> Y. If B comes after A in the list of weak
4191 tables, X -> Y might be removed from A, although when looking at B
4192 one finds that it shouldn't. */
4195 marked = 0;
4196 for (h = weak_hash_tables; h; h = h->next_weak)
4198 if (h->size & ARRAY_MARK_FLAG)
4199 marked |= sweep_weak_table (h, 0);
4202 while (marked);
4204 /* Remove tables and entries that aren't used. */
4205 for (h = weak_hash_tables, used = NULL; h; h = next)
4207 next = h->next_weak;
4209 if (h->size & ARRAY_MARK_FLAG)
4211 /* TABLE is marked as used. Sweep its contents. */
4212 if (h->count > 0)
4213 sweep_weak_table (h, 1);
4215 /* Add table to the list of used weak hash tables. */
4216 h->next_weak = used;
4217 used = h;
4221 weak_hash_tables = used;
4226 /***********************************************************************
4227 Hash Code Computation
4228 ***********************************************************************/
4230 /* Maximum depth up to which to dive into Lisp structures. */
4232 #define SXHASH_MAX_DEPTH 3
4234 /* Maximum length up to which to take list and vector elements into
4235 account. */
4237 #define SXHASH_MAX_LEN 7
4239 /* Combine two integers X and Y for hashing. */
4241 #define SXHASH_COMBINE(X, Y) \
4242 ((((unsigned)(X) << 4) + (((unsigned)(X) >> 24) & 0x0fffffff)) \
4243 + (unsigned)(Y))
4246 /* Return a hash for string PTR which has length LEN. The hash
4247 code returned is guaranteed to fit in a Lisp integer. */
4249 static unsigned
4250 sxhash_string (unsigned char *ptr, int len)
4252 unsigned char *p = ptr;
4253 unsigned char *end = p + len;
4254 unsigned char c;
4255 unsigned hash = 0;
4257 while (p != end)
4259 c = *p++;
4260 if (c >= 0140)
4261 c -= 40;
4262 hash = ((hash << 4) + (hash >> 28) + c);
4265 return hash & INTMASK;
4269 /* Return a hash for list LIST. DEPTH is the current depth in the
4270 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4272 static unsigned
4273 sxhash_list (Lisp_Object list, int depth)
4275 unsigned hash = 0;
4276 int i;
4278 if (depth < SXHASH_MAX_DEPTH)
4279 for (i = 0;
4280 CONSP (list) && i < SXHASH_MAX_LEN;
4281 list = XCDR (list), ++i)
4283 unsigned hash2 = sxhash (XCAR (list), depth + 1);
4284 hash = SXHASH_COMBINE (hash, hash2);
4287 if (!NILP (list))
4289 unsigned hash2 = sxhash (list, depth + 1);
4290 hash = SXHASH_COMBINE (hash, hash2);
4293 return hash;
4297 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4298 the Lisp structure. */
4300 static unsigned
4301 sxhash_vector (Lisp_Object vec, int depth)
4303 unsigned hash = ASIZE (vec);
4304 int i, n;
4306 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4307 for (i = 0; i < n; ++i)
4309 unsigned hash2 = sxhash (AREF (vec, i), depth + 1);
4310 hash = SXHASH_COMBINE (hash, hash2);
4313 return hash;
4317 /* Return a hash for bool-vector VECTOR. */
4319 static unsigned
4320 sxhash_bool_vector (Lisp_Object vec)
4322 unsigned hash = XBOOL_VECTOR (vec)->size;
4323 int i, n;
4325 n = min (SXHASH_MAX_LEN, XBOOL_VECTOR (vec)->vector_size);
4326 for (i = 0; i < n; ++i)
4327 hash = SXHASH_COMBINE (hash, XBOOL_VECTOR (vec)->data[i]);
4329 return hash;
4333 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4334 structure. Value is an unsigned integer clipped to INTMASK. */
4336 unsigned
4337 sxhash (Lisp_Object obj, int depth)
4339 unsigned hash;
4341 if (depth > SXHASH_MAX_DEPTH)
4342 return 0;
4344 switch (XTYPE (obj))
4346 case_Lisp_Int:
4347 hash = XUINT (obj);
4348 break;
4350 case Lisp_Misc:
4351 hash = XUINT (obj);
4352 break;
4354 case Lisp_Symbol:
4355 obj = SYMBOL_NAME (obj);
4356 /* Fall through. */
4358 case Lisp_String:
4359 hash = sxhash_string (SDATA (obj), SCHARS (obj));
4360 break;
4362 /* This can be everything from a vector to an overlay. */
4363 case Lisp_Vectorlike:
4364 if (VECTORP (obj))
4365 /* According to the CL HyperSpec, two arrays are equal only if
4366 they are `eq', except for strings and bit-vectors. In
4367 Emacs, this works differently. We have to compare element
4368 by element. */
4369 hash = sxhash_vector (obj, depth);
4370 else if (BOOL_VECTOR_P (obj))
4371 hash = sxhash_bool_vector (obj);
4372 else
4373 /* Others are `equal' if they are `eq', so let's take their
4374 address as hash. */
4375 hash = XUINT (obj);
4376 break;
4378 case Lisp_Cons:
4379 hash = sxhash_list (obj, depth);
4380 break;
4382 case Lisp_Float:
4384 double val = XFLOAT_DATA (obj);
4385 unsigned char *p = (unsigned char *) &val;
4386 unsigned char *e = p + sizeof val;
4387 for (hash = 0; p < e; ++p)
4388 hash = SXHASH_COMBINE (hash, *p);
4389 break;
4392 default:
4393 abort ();
4396 return hash & INTMASK;
4401 /***********************************************************************
4402 Lisp Interface
4403 ***********************************************************************/
4406 DEFUN ("sxhash", Fsxhash, Ssxhash, 1, 1, 0,
4407 doc: /* Compute a hash code for OBJ and return it as integer. */)
4408 (Lisp_Object obj)
4410 unsigned hash = sxhash (obj, 0);
4411 return make_number (hash);
4415 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4416 doc: /* Create and return a new hash table.
4418 Arguments are specified as keyword/argument pairs. The following
4419 arguments are defined:
4421 :test TEST -- TEST must be a symbol that specifies how to compare
4422 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4423 `equal'. User-supplied test and hash functions can be specified via
4424 `define-hash-table-test'.
4426 :size SIZE -- A hint as to how many elements will be put in the table.
4427 Default is 65.
4429 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4430 fills up. If REHASH-SIZE is an integer, add that many space. If it
4431 is a float, it must be > 1.0, and the new size is computed by
4432 multiplying the old size with that factor. Default is 1.5.
4434 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4435 Resize the hash table when ratio of the number of entries in the
4436 table. Default is 0.8.
4438 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4439 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4440 returned is a weak table. Key/value pairs are removed from a weak
4441 hash table when there are no non-weak references pointing to their
4442 key, value, one of key or value, or both key and value, depending on
4443 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4444 is nil.
4446 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4447 (int nargs, Lisp_Object *args)
4449 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4450 Lisp_Object user_test, user_hash;
4451 char *used;
4452 int i;
4454 /* The vector `used' is used to keep track of arguments that
4455 have been consumed. */
4456 used = (char *) alloca (nargs * sizeof *used);
4457 memset (used, 0, nargs * sizeof *used);
4459 /* See if there's a `:test TEST' among the arguments. */
4460 i = get_key_arg (QCtest, nargs, args, used);
4461 test = i < 0 ? Qeql : args[i];
4462 if (!EQ (test, Qeq) && !EQ (test, Qeql) && !EQ (test, Qequal))
4464 /* See if it is a user-defined test. */
4465 Lisp_Object prop;
4467 prop = Fget (test, Qhash_table_test);
4468 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4469 signal_error ("Invalid hash table test", test);
4470 user_test = XCAR (prop);
4471 user_hash = XCAR (XCDR (prop));
4473 else
4474 user_test = user_hash = Qnil;
4476 /* See if there's a `:size SIZE' argument. */
4477 i = get_key_arg (QCsize, nargs, args, used);
4478 size = i < 0 ? Qnil : args[i];
4479 if (NILP (size))
4480 size = make_number (DEFAULT_HASH_SIZE);
4481 else if (!INTEGERP (size) || XINT (size) < 0)
4482 signal_error ("Invalid hash table size", size);
4484 /* Look for `:rehash-size SIZE'. */
4485 i = get_key_arg (QCrehash_size, nargs, args, used);
4486 rehash_size = i < 0 ? make_float (DEFAULT_REHASH_SIZE) : args[i];
4487 if (!NUMBERP (rehash_size)
4488 || (INTEGERP (rehash_size) && XINT (rehash_size) <= 0)
4489 || XFLOATINT (rehash_size) <= 1.0)
4490 signal_error ("Invalid hash table rehash size", rehash_size);
4492 /* Look for `:rehash-threshold THRESHOLD'. */
4493 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4494 rehash_threshold = i < 0 ? make_float (DEFAULT_REHASH_THRESHOLD) : args[i];
4495 if (!FLOATP (rehash_threshold)
4496 || XFLOATINT (rehash_threshold) <= 0.0
4497 || XFLOATINT (rehash_threshold) > 1.0)
4498 signal_error ("Invalid hash table rehash threshold", rehash_threshold);
4500 /* Look for `:weakness WEAK'. */
4501 i = get_key_arg (QCweakness, nargs, args, used);
4502 weak = i < 0 ? Qnil : args[i];
4503 if (EQ (weak, Qt))
4504 weak = Qkey_and_value;
4505 if (!NILP (weak)
4506 && !EQ (weak, Qkey)
4507 && !EQ (weak, Qvalue)
4508 && !EQ (weak, Qkey_or_value)
4509 && !EQ (weak, Qkey_and_value))
4510 signal_error ("Invalid hash table weakness", weak);
4512 /* Now, all args should have been used up, or there's a problem. */
4513 for (i = 0; i < nargs; ++i)
4514 if (!used[i])
4515 signal_error ("Invalid argument list", args[i]);
4517 return make_hash_table (test, size, rehash_size, rehash_threshold, weak,
4518 user_test, user_hash);
4522 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4523 doc: /* Return a copy of hash table TABLE. */)
4524 (Lisp_Object table)
4526 return copy_hash_table (check_hash_table (table));
4530 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4531 doc: /* Return the number of elements in TABLE. */)
4532 (Lisp_Object table)
4534 return make_number (check_hash_table (table)->count);
4538 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4539 Shash_table_rehash_size, 1, 1, 0,
4540 doc: /* Return the current rehash size of TABLE. */)
4541 (Lisp_Object table)
4543 return check_hash_table (table)->rehash_size;
4547 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4548 Shash_table_rehash_threshold, 1, 1, 0,
4549 doc: /* Return the current rehash threshold of TABLE. */)
4550 (Lisp_Object table)
4552 return check_hash_table (table)->rehash_threshold;
4556 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4557 doc: /* Return the size of TABLE.
4558 The size can be used as an argument to `make-hash-table' to create
4559 a hash table than can hold as many elements of TABLE holds
4560 without need for resizing. */)
4561 (Lisp_Object table)
4563 struct Lisp_Hash_Table *h = check_hash_table (table);
4564 return make_number (HASH_TABLE_SIZE (h));
4568 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4569 doc: /* Return the test TABLE uses. */)
4570 (Lisp_Object table)
4572 return check_hash_table (table)->test;
4576 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4577 1, 1, 0,
4578 doc: /* Return the weakness of TABLE. */)
4579 (Lisp_Object table)
4581 return check_hash_table (table)->weak;
4585 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4586 doc: /* Return t if OBJ is a Lisp hash table object. */)
4587 (Lisp_Object obj)
4589 return HASH_TABLE_P (obj) ? Qt : Qnil;
4593 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4594 doc: /* Clear hash table TABLE and return it. */)
4595 (Lisp_Object table)
4597 hash_clear (check_hash_table (table));
4598 /* Be compatible with XEmacs. */
4599 return table;
4603 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4604 doc: /* Look up KEY in TABLE and return its associated value.
4605 If KEY is not found, return DFLT which defaults to nil. */)
4606 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4608 struct Lisp_Hash_Table *h = check_hash_table (table);
4609 int i = hash_lookup (h, key, NULL);
4610 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4614 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4615 doc: /* Associate KEY with VALUE in hash table TABLE.
4616 If KEY is already present in table, replace its current value with
4617 VALUE. */)
4618 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4620 struct Lisp_Hash_Table *h = check_hash_table (table);
4621 int i;
4622 unsigned hash;
4624 i = hash_lookup (h, key, &hash);
4625 if (i >= 0)
4626 HASH_VALUE (h, i) = value;
4627 else
4628 hash_put (h, key, value, hash);
4630 return value;
4634 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4635 doc: /* Remove KEY from TABLE. */)
4636 (Lisp_Object key, Lisp_Object table)
4638 struct Lisp_Hash_Table *h = check_hash_table (table);
4639 hash_remove_from_table (h, key);
4640 return Qnil;
4644 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4645 doc: /* Call FUNCTION for all entries in hash table TABLE.
4646 FUNCTION is called with two arguments, KEY and VALUE. */)
4647 (Lisp_Object function, Lisp_Object table)
4649 struct Lisp_Hash_Table *h = check_hash_table (table);
4650 Lisp_Object args[3];
4651 int i;
4653 for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
4654 if (!NILP (HASH_HASH (h, i)))
4656 args[0] = function;
4657 args[1] = HASH_KEY (h, i);
4658 args[2] = HASH_VALUE (h, i);
4659 Ffuncall (3, args);
4662 return Qnil;
4666 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4667 Sdefine_hash_table_test, 3, 3, 0,
4668 doc: /* Define a new hash table test with name NAME, a symbol.
4670 In hash tables created with NAME specified as test, use TEST to
4671 compare keys, and HASH for computing hash codes of keys.
4673 TEST must be a function taking two arguments and returning non-nil if
4674 both arguments are the same. HASH must be a function taking one
4675 argument and return an integer that is the hash code of the argument.
4676 Hash code computation should use the whole value range of integers,
4677 including negative integers. */)
4678 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4680 return Fput (name, Qhash_table_test, list2 (test, hash));
4685 /************************************************************************
4687 ************************************************************************/
4689 #include "md5.h"
4691 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
4692 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
4694 A message digest is a cryptographic checksum of a document, and the
4695 algorithm to calculate it is defined in RFC 1321.
4697 The two optional arguments START and END are character positions
4698 specifying for which part of OBJECT the message digest should be
4699 computed. If nil or omitted, the digest is computed for the whole
4700 OBJECT.
4702 The MD5 message digest is computed from the result of encoding the
4703 text in a coding system, not directly from the internal Emacs form of
4704 the text. The optional fourth argument CODING-SYSTEM specifies which
4705 coding system to encode the text with. It should be the same coding
4706 system that you used or will use when actually writing the text into a
4707 file.
4709 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
4710 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
4711 system would be chosen by default for writing this text into a file.
4713 If OBJECT is a string, the most preferred coding system (see the
4714 command `prefer-coding-system') is used.
4716 If NOERROR is non-nil, silently assume the `raw-text' coding if the
4717 guesswork fails. Normally, an error is signaled in such case. */)
4718 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
4720 unsigned char digest[16];
4721 unsigned char value[33];
4722 int i;
4723 int size;
4724 int size_byte = 0;
4725 int start_char = 0, end_char = 0;
4726 int start_byte = 0, end_byte = 0;
4727 register int b, e;
4728 register struct buffer *bp;
4729 int temp;
4731 if (STRINGP (object))
4733 if (NILP (coding_system))
4735 /* Decide the coding-system to encode the data with. */
4737 if (STRING_MULTIBYTE (object))
4738 /* use default, we can't guess correct value */
4739 coding_system = preferred_coding_system ();
4740 else
4741 coding_system = Qraw_text;
4744 if (NILP (Fcoding_system_p (coding_system)))
4746 /* Invalid coding system. */
4748 if (!NILP (noerror))
4749 coding_system = Qraw_text;
4750 else
4751 xsignal1 (Qcoding_system_error, coding_system);
4754 if (STRING_MULTIBYTE (object))
4755 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4757 size = SCHARS (object);
4758 size_byte = SBYTES (object);
4760 if (!NILP (start))
4762 CHECK_NUMBER (start);
4764 start_char = XINT (start);
4766 if (start_char < 0)
4767 start_char += size;
4769 start_byte = string_char_to_byte (object, start_char);
4772 if (NILP (end))
4774 end_char = size;
4775 end_byte = size_byte;
4777 else
4779 CHECK_NUMBER (end);
4781 end_char = XINT (end);
4783 if (end_char < 0)
4784 end_char += size;
4786 end_byte = string_char_to_byte (object, end_char);
4789 if (!(0 <= start_char && start_char <= end_char && end_char <= size))
4790 args_out_of_range_3 (object, make_number (start_char),
4791 make_number (end_char));
4793 else
4795 struct buffer *prev = current_buffer;
4797 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
4799 CHECK_BUFFER (object);
4801 bp = XBUFFER (object);
4802 if (bp != current_buffer)
4803 set_buffer_internal (bp);
4805 if (NILP (start))
4806 b = BEGV;
4807 else
4809 CHECK_NUMBER_COERCE_MARKER (start);
4810 b = XINT (start);
4813 if (NILP (end))
4814 e = ZV;
4815 else
4817 CHECK_NUMBER_COERCE_MARKER (end);
4818 e = XINT (end);
4821 if (b > e)
4822 temp = b, b = e, e = temp;
4824 if (!(BEGV <= b && e <= ZV))
4825 args_out_of_range (start, end);
4827 if (NILP (coding_system))
4829 /* Decide the coding-system to encode the data with.
4830 See fileio.c:Fwrite-region */
4832 if (!NILP (Vcoding_system_for_write))
4833 coding_system = Vcoding_system_for_write;
4834 else
4836 int force_raw_text = 0;
4838 coding_system = XBUFFER (object)->buffer_file_coding_system;
4839 if (NILP (coding_system)
4840 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4842 coding_system = Qnil;
4843 if (NILP (current_buffer->enable_multibyte_characters))
4844 force_raw_text = 1;
4847 if (NILP (coding_system) && !NILP (Fbuffer_file_name(object)))
4849 /* Check file-coding-system-alist. */
4850 Lisp_Object args[4], val;
4852 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4853 args[3] = Fbuffer_file_name(object);
4854 val = Ffind_operation_coding_system (4, args);
4855 if (CONSP (val) && !NILP (XCDR (val)))
4856 coding_system = XCDR (val);
4859 if (NILP (coding_system)
4860 && !NILP (XBUFFER (object)->buffer_file_coding_system))
4862 /* If we still have not decided a coding system, use the
4863 default value of buffer-file-coding-system. */
4864 coding_system = XBUFFER (object)->buffer_file_coding_system;
4867 if (!force_raw_text
4868 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4869 /* Confirm that VAL can surely encode the current region. */
4870 coding_system = call4 (Vselect_safe_coding_system_function,
4871 make_number (b), make_number (e),
4872 coding_system, Qnil);
4874 if (force_raw_text)
4875 coding_system = Qraw_text;
4878 if (NILP (Fcoding_system_p (coding_system)))
4880 /* Invalid coding system. */
4882 if (!NILP (noerror))
4883 coding_system = Qraw_text;
4884 else
4885 xsignal1 (Qcoding_system_error, coding_system);
4889 object = make_buffer_string (b, e, 0);
4890 if (prev != current_buffer)
4891 set_buffer_internal (prev);
4892 /* Discard the unwind protect for recovering the current
4893 buffer. */
4894 specpdl_ptr--;
4896 if (STRING_MULTIBYTE (object))
4897 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4900 md5_buffer (SDATA (object) + start_byte,
4901 SBYTES (object) - (size_byte - end_byte),
4902 digest);
4904 for (i = 0; i < 16; i++)
4905 sprintf (&value[2 * i], "%02x", digest[i]);
4906 value[32] = '\0';
4908 return make_string (value, 32);
4912 void
4913 syms_of_fns (void)
4915 /* Hash table stuff. */
4916 Qhash_table_p = intern_c_string ("hash-table-p");
4917 staticpro (&Qhash_table_p);
4918 Qeq = intern_c_string ("eq");
4919 staticpro (&Qeq);
4920 Qeql = intern_c_string ("eql");
4921 staticpro (&Qeql);
4922 Qequal = intern_c_string ("equal");
4923 staticpro (&Qequal);
4924 QCtest = intern_c_string (":test");
4925 staticpro (&QCtest);
4926 QCsize = intern_c_string (":size");
4927 staticpro (&QCsize);
4928 QCrehash_size = intern_c_string (":rehash-size");
4929 staticpro (&QCrehash_size);
4930 QCrehash_threshold = intern_c_string (":rehash-threshold");
4931 staticpro (&QCrehash_threshold);
4932 QCweakness = intern_c_string (":weakness");
4933 staticpro (&QCweakness);
4934 Qkey = intern_c_string ("key");
4935 staticpro (&Qkey);
4936 Qvalue = intern_c_string ("value");
4937 staticpro (&Qvalue);
4938 Qhash_table_test = intern_c_string ("hash-table-test");
4939 staticpro (&Qhash_table_test);
4940 Qkey_or_value = intern_c_string ("key-or-value");
4941 staticpro (&Qkey_or_value);
4942 Qkey_and_value = intern_c_string ("key-and-value");
4943 staticpro (&Qkey_and_value);
4945 defsubr (&Ssxhash);
4946 defsubr (&Smake_hash_table);
4947 defsubr (&Scopy_hash_table);
4948 defsubr (&Shash_table_count);
4949 defsubr (&Shash_table_rehash_size);
4950 defsubr (&Shash_table_rehash_threshold);
4951 defsubr (&Shash_table_size);
4952 defsubr (&Shash_table_test);
4953 defsubr (&Shash_table_weakness);
4954 defsubr (&Shash_table_p);
4955 defsubr (&Sclrhash);
4956 defsubr (&Sgethash);
4957 defsubr (&Sputhash);
4958 defsubr (&Sremhash);
4959 defsubr (&Smaphash);
4960 defsubr (&Sdefine_hash_table_test);
4962 Qstring_lessp = intern_c_string ("string-lessp");
4963 staticpro (&Qstring_lessp);
4964 Qprovide = intern_c_string ("provide");
4965 staticpro (&Qprovide);
4966 Qrequire = intern_c_string ("require");
4967 staticpro (&Qrequire);
4968 Qyes_or_no_p_history = intern_c_string ("yes-or-no-p-history");
4969 staticpro (&Qyes_or_no_p_history);
4970 Qcursor_in_echo_area = intern_c_string ("cursor-in-echo-area");
4971 staticpro (&Qcursor_in_echo_area);
4972 Qwidget_type = intern_c_string ("widget-type");
4973 staticpro (&Qwidget_type);
4975 staticpro (&string_char_byte_cache_string);
4976 string_char_byte_cache_string = Qnil;
4978 require_nesting_list = Qnil;
4979 staticpro (&require_nesting_list);
4981 Fset (Qyes_or_no_p_history, Qnil);
4983 DEFVAR_LISP ("features", &Vfeatures,
4984 doc: /* A list of symbols which are the features of the executing Emacs.
4985 Used by `featurep' and `require', and altered by `provide'. */);
4986 Vfeatures = Fcons (intern_c_string ("emacs"), Qnil);
4987 Qsubfeatures = intern_c_string ("subfeatures");
4988 staticpro (&Qsubfeatures);
4990 #ifdef HAVE_LANGINFO_CODESET
4991 Qcodeset = intern_c_string ("codeset");
4992 staticpro (&Qcodeset);
4993 Qdays = intern_c_string ("days");
4994 staticpro (&Qdays);
4995 Qmonths = intern_c_string ("months");
4996 staticpro (&Qmonths);
4997 Qpaper = intern_c_string ("paper");
4998 staticpro (&Qpaper);
4999 #endif /* HAVE_LANGINFO_CODESET */
5001 DEFVAR_BOOL ("use-dialog-box", &use_dialog_box,
5002 doc: /* *Non-nil means mouse commands use dialog boxes to ask questions.
5003 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
5004 invoked by mouse clicks and mouse menu items.
5006 On some platforms, file selection dialogs are also enabled if this is
5007 non-nil. */);
5008 use_dialog_box = 1;
5010 DEFVAR_BOOL ("use-file-dialog", &use_file_dialog,
5011 doc: /* *Non-nil means mouse commands use a file dialog to ask for files.
5012 This applies to commands from menus and tool bar buttons even when
5013 they are initiated from the keyboard. If `use-dialog-box' is nil,
5014 that disables the use of a file dialog, regardless of the value of
5015 this variable. */);
5016 use_file_dialog = 1;
5018 defsubr (&Sidentity);
5019 defsubr (&Srandom);
5020 defsubr (&Slength);
5021 defsubr (&Ssafe_length);
5022 defsubr (&Sstring_bytes);
5023 defsubr (&Sstring_equal);
5024 defsubr (&Scompare_strings);
5025 defsubr (&Sstring_lessp);
5026 defsubr (&Sappend);
5027 defsubr (&Sconcat);
5028 defsubr (&Svconcat);
5029 defsubr (&Scopy_sequence);
5030 defsubr (&Sstring_make_multibyte);
5031 defsubr (&Sstring_make_unibyte);
5032 defsubr (&Sstring_as_multibyte);
5033 defsubr (&Sstring_as_unibyte);
5034 defsubr (&Sstring_to_multibyte);
5035 defsubr (&Sstring_to_unibyte);
5036 defsubr (&Scopy_alist);
5037 defsubr (&Ssubstring);
5038 defsubr (&Ssubstring_no_properties);
5039 defsubr (&Snthcdr);
5040 defsubr (&Snth);
5041 defsubr (&Selt);
5042 defsubr (&Smember);
5043 defsubr (&Smemq);
5044 defsubr (&Smemql);
5045 defsubr (&Sassq);
5046 defsubr (&Sassoc);
5047 defsubr (&Srassq);
5048 defsubr (&Srassoc);
5049 defsubr (&Sdelq);
5050 defsubr (&Sdelete);
5051 defsubr (&Snreverse);
5052 defsubr (&Sreverse);
5053 defsubr (&Ssort);
5054 defsubr (&Splist_get);
5055 defsubr (&Sget);
5056 defsubr (&Splist_put);
5057 defsubr (&Sput);
5058 defsubr (&Slax_plist_get);
5059 defsubr (&Slax_plist_put);
5060 defsubr (&Seql);
5061 defsubr (&Sequal);
5062 defsubr (&Sequal_including_properties);
5063 defsubr (&Sfillarray);
5064 defsubr (&Sclear_string);
5065 defsubr (&Snconc);
5066 defsubr (&Smapcar);
5067 defsubr (&Smapc);
5068 defsubr (&Smapconcat);
5069 defsubr (&Sy_or_n_p);
5070 defsubr (&Syes_or_no_p);
5071 defsubr (&Sload_average);
5072 defsubr (&Sfeaturep);
5073 defsubr (&Srequire);
5074 defsubr (&Sprovide);
5075 defsubr (&Splist_member);
5076 defsubr (&Swidget_put);
5077 defsubr (&Swidget_get);
5078 defsubr (&Swidget_apply);
5079 defsubr (&Sbase64_encode_region);
5080 defsubr (&Sbase64_decode_region);
5081 defsubr (&Sbase64_encode_string);
5082 defsubr (&Sbase64_decode_string);
5083 defsubr (&Smd5);
5084 defsubr (&Slocale_info);
5088 void
5089 init_fns (void)
5093 /* arch-tag: 787f8219-5b74-46bd-8469-7e1cc475fa31
5094 (do not change this comment) */