Make sure secondary frames are deleted when emacsclient quits.
[emacs.git] / src / fns.c
blobe4252c98ca5fd7517a22d2765c02fd8cadf4fcc9
1 /* Random utility Lisp functions.
2 Copyright (C) 1985, 86, 87, 93, 94, 95, 97, 98, 99, 2000, 2001, 02, 2003
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 #include <config.h>
24 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #include <time.h>
29 #ifndef MAC_OSX
30 /* On Mac OS X, defining this conflicts with precompiled headers. */
32 /* Note on some machines this defines `vector' as a typedef,
33 so make sure we don't use that name in this file. */
34 #undef vector
35 #define vector *****
37 #endif /* ! MAC_OSX */
39 #include "lisp.h"
40 #include "commands.h"
41 #include "charset.h"
42 #include "coding.h"
43 #include "buffer.h"
44 #include "keyboard.h"
45 #include "keymap.h"
46 #include "intervals.h"
47 #include "frame.h"
48 #include "window.h"
49 #include "blockinput.h"
50 #if defined (HAVE_MENUS) && defined (HAVE_X_WINDOWS)
51 #include "xterm.h"
52 #endif
54 #ifndef NULL
55 #define NULL ((POINTER_TYPE *)0)
56 #endif
58 /* Nonzero enables use of dialog boxes for questions
59 asked by mouse commands. */
60 int use_dialog_box;
62 /* Nonzero enables use of a file dialog for file name
63 questions asked by mouse commands. */
64 int use_file_dialog;
66 extern int minibuffer_auto_raise;
67 extern Lisp_Object minibuf_window;
68 extern Lisp_Object Vlocale_coding_system;
70 Lisp_Object Qstring_lessp, Qprovide, Qrequire;
71 Lisp_Object Qyes_or_no_p_history;
72 Lisp_Object Qcursor_in_echo_area;
73 Lisp_Object Qwidget_type;
74 Lisp_Object Qcodeset, Qdays, Qmonths, Qpaper;
76 extern Lisp_Object Qinput_method_function;
78 static int internal_equal ();
80 extern long get_random ();
81 extern void seed_random ();
83 #ifndef HAVE_UNISTD_H
84 extern long time ();
85 #endif
87 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
88 doc: /* Return the argument unchanged. */)
89 (arg)
90 Lisp_Object arg;
92 return arg;
95 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
96 doc: /* Return a pseudo-random number.
97 All integers representable in Lisp are equally likely.
98 On most systems, this is 29 bits' worth.
99 With positive integer argument N, return random number in interval [0,N).
100 With argument t, set the random number seed from the current time and pid. */)
102 Lisp_Object n;
104 EMACS_INT val;
105 Lisp_Object lispy_val;
106 unsigned long denominator;
108 if (EQ (n, Qt))
109 seed_random (getpid () + time (NULL));
110 if (NATNUMP (n) && XFASTINT (n) != 0)
112 /* Try to take our random number from the higher bits of VAL,
113 not the lower, since (says Gentzel) the low bits of `random'
114 are less random than the higher ones. We do this by using the
115 quotient rather than the remainder. At the high end of the RNG
116 it's possible to get a quotient larger than n; discarding
117 these values eliminates the bias that would otherwise appear
118 when using a large n. */
119 denominator = ((unsigned long)1 << VALBITS) / XFASTINT (n);
121 val = get_random () / denominator;
122 while (val >= XFASTINT (n));
124 else
125 val = get_random ();
126 XSETINT (lispy_val, val);
127 return lispy_val;
130 /* Random data-structure functions */
132 DEFUN ("length", Flength, Slength, 1, 1, 0,
133 doc: /* Return the length of vector, list or string SEQUENCE.
134 A byte-code function object is also allowed.
135 If the string contains multibyte characters, this is not necessarily
136 the number of bytes in the string; it is the number of characters.
137 To get the number of bytes, use `string-bytes'. */)
138 (sequence)
139 register Lisp_Object sequence;
141 register Lisp_Object val;
142 register int i;
144 retry:
145 if (STRINGP (sequence))
146 XSETFASTINT (val, SCHARS (sequence));
147 else if (VECTORP (sequence))
148 XSETFASTINT (val, XVECTOR (sequence)->size);
149 else if (SUB_CHAR_TABLE_P (sequence))
150 XSETFASTINT (val, SUB_CHAR_TABLE_ORDINARY_SLOTS);
151 else if (CHAR_TABLE_P (sequence))
152 XSETFASTINT (val, MAX_CHAR);
153 else if (BOOL_VECTOR_P (sequence))
154 XSETFASTINT (val, XBOOL_VECTOR (sequence)->size);
155 else if (COMPILEDP (sequence))
156 XSETFASTINT (val, XVECTOR (sequence)->size & PSEUDOVECTOR_SIZE_MASK);
157 else if (CONSP (sequence))
159 i = 0;
160 while (CONSP (sequence))
162 sequence = XCDR (sequence);
163 ++i;
165 if (!CONSP (sequence))
166 break;
168 sequence = XCDR (sequence);
169 ++i;
170 QUIT;
173 if (!NILP (sequence))
174 wrong_type_argument (Qlistp, sequence);
176 val = make_number (i);
178 else if (NILP (sequence))
179 XSETFASTINT (val, 0);
180 else
182 sequence = wrong_type_argument (Qsequencep, sequence);
183 goto retry;
185 return val;
188 /* This does not check for quits. That is safe
189 since it must terminate. */
191 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
192 doc: /* Return the length of a list, but avoid error or infinite loop.
193 This function never gets an error. If LIST is not really a list,
194 it returns 0. If LIST is circular, it returns a finite value
195 which is at least the number of distinct elements. */)
196 (list)
197 Lisp_Object list;
199 Lisp_Object tail, halftail, length;
200 int len = 0;
202 /* halftail is used to detect circular lists. */
203 halftail = list;
204 for (tail = list; CONSP (tail); tail = XCDR (tail))
206 if (EQ (tail, halftail) && len != 0)
207 break;
208 len++;
209 if ((len & 1) == 0)
210 halftail = XCDR (halftail);
213 XSETINT (length, len);
214 return length;
217 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
218 doc: /* Return the number of bytes in STRING.
219 If STRING is a multibyte string, this is greater than the length of STRING. */)
220 (string)
221 Lisp_Object string;
223 CHECK_STRING (string);
224 return make_number (SBYTES (string));
227 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
228 doc: /* Return t if two strings have identical contents.
229 Case is significant, but text properties are ignored.
230 Symbols are also allowed; their print names are used instead. */)
231 (s1, s2)
232 register Lisp_Object s1, s2;
234 if (SYMBOLP (s1))
235 s1 = SYMBOL_NAME (s1);
236 if (SYMBOLP (s2))
237 s2 = SYMBOL_NAME (s2);
238 CHECK_STRING (s1);
239 CHECK_STRING (s2);
241 if (SCHARS (s1) != SCHARS (s2)
242 || SBYTES (s1) != SBYTES (s2)
243 || bcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
244 return Qnil;
245 return Qt;
248 DEFUN ("compare-strings", Fcompare_strings,
249 Scompare_strings, 6, 7, 0,
250 doc: /* Compare the contents of two strings, converting to multibyte if needed.
251 In string STR1, skip the first START1 characters and stop at END1.
252 In string STR2, skip the first START2 characters and stop at END2.
253 END1 and END2 default to the full lengths of the respective strings.
255 Case is significant in this comparison if IGNORE-CASE is nil.
256 Unibyte strings are converted to multibyte for comparison.
258 The value is t if the strings (or specified portions) match.
259 If string STR1 is less, the value is a negative number N;
260 - 1 - N is the number of characters that match at the beginning.
261 If string STR1 is greater, the value is a positive number N;
262 N - 1 is the number of characters that match at the beginning. */)
263 (str1, start1, end1, str2, start2, end2, ignore_case)
264 Lisp_Object str1, start1, end1, start2, str2, end2, ignore_case;
266 register int end1_char, end2_char;
267 register int i1, i1_byte, i2, i2_byte;
269 CHECK_STRING (str1);
270 CHECK_STRING (str2);
271 if (NILP (start1))
272 start1 = make_number (0);
273 if (NILP (start2))
274 start2 = make_number (0);
275 CHECK_NATNUM (start1);
276 CHECK_NATNUM (start2);
277 if (! NILP (end1))
278 CHECK_NATNUM (end1);
279 if (! NILP (end2))
280 CHECK_NATNUM (end2);
282 i1 = XINT (start1);
283 i2 = XINT (start2);
285 i1_byte = string_char_to_byte (str1, i1);
286 i2_byte = string_char_to_byte (str2, i2);
288 end1_char = SCHARS (str1);
289 if (! NILP (end1) && end1_char > XINT (end1))
290 end1_char = XINT (end1);
292 end2_char = SCHARS (str2);
293 if (! NILP (end2) && end2_char > XINT (end2))
294 end2_char = XINT (end2);
296 while (i1 < end1_char && i2 < end2_char)
298 /* When we find a mismatch, we must compare the
299 characters, not just the bytes. */
300 int c1, c2;
302 if (STRING_MULTIBYTE (str1))
303 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c1, str1, i1, i1_byte);
304 else
306 c1 = SREF (str1, i1++);
307 c1 = unibyte_char_to_multibyte (c1);
310 if (STRING_MULTIBYTE (str2))
311 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c2, str2, i2, i2_byte);
312 else
314 c2 = SREF (str2, i2++);
315 c2 = unibyte_char_to_multibyte (c2);
318 if (c1 == c2)
319 continue;
321 if (! NILP (ignore_case))
323 Lisp_Object tem;
325 tem = Fupcase (make_number (c1));
326 c1 = XINT (tem);
327 tem = Fupcase (make_number (c2));
328 c2 = XINT (tem);
331 if (c1 == c2)
332 continue;
334 /* Note that I1 has already been incremented
335 past the character that we are comparing;
336 hence we don't add or subtract 1 here. */
337 if (c1 < c2)
338 return make_number (- i1 + XINT (start1));
339 else
340 return make_number (i1 - XINT (start1));
343 if (i1 < end1_char)
344 return make_number (i1 - XINT (start1) + 1);
345 if (i2 < end2_char)
346 return make_number (- i1 + XINT (start1) - 1);
348 return Qt;
351 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
352 doc: /* Return t if first arg string is less than second in lexicographic order.
353 Case is significant.
354 Symbols are also allowed; their print names are used instead. */)
355 (s1, s2)
356 register Lisp_Object s1, s2;
358 register int end;
359 register int i1, i1_byte, i2, i2_byte;
361 if (SYMBOLP (s1))
362 s1 = SYMBOL_NAME (s1);
363 if (SYMBOLP (s2))
364 s2 = SYMBOL_NAME (s2);
365 CHECK_STRING (s1);
366 CHECK_STRING (s2);
368 i1 = i1_byte = i2 = i2_byte = 0;
370 end = SCHARS (s1);
371 if (end > SCHARS (s2))
372 end = SCHARS (s2);
374 while (i1 < end)
376 /* When we find a mismatch, we must compare the
377 characters, not just the bytes. */
378 int c1, c2;
380 FETCH_STRING_CHAR_ADVANCE (c1, s1, i1, i1_byte);
381 FETCH_STRING_CHAR_ADVANCE (c2, s2, i2, i2_byte);
383 if (c1 != c2)
384 return c1 < c2 ? Qt : Qnil;
386 return i1 < SCHARS (s2) ? Qt : Qnil;
389 static Lisp_Object concat ();
391 /* ARGSUSED */
392 Lisp_Object
393 concat2 (s1, s2)
394 Lisp_Object s1, s2;
396 #ifdef NO_ARG_ARRAY
397 Lisp_Object args[2];
398 args[0] = s1;
399 args[1] = s2;
400 return concat (2, args, Lisp_String, 0);
401 #else
402 return concat (2, &s1, Lisp_String, 0);
403 #endif /* NO_ARG_ARRAY */
406 /* ARGSUSED */
407 Lisp_Object
408 concat3 (s1, s2, s3)
409 Lisp_Object s1, s2, s3;
411 #ifdef NO_ARG_ARRAY
412 Lisp_Object args[3];
413 args[0] = s1;
414 args[1] = s2;
415 args[2] = s3;
416 return concat (3, args, Lisp_String, 0);
417 #else
418 return concat (3, &s1, Lisp_String, 0);
419 #endif /* NO_ARG_ARRAY */
422 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
423 doc: /* Concatenate all the arguments and make the result a list.
424 The result is a list whose elements are the elements of all the arguments.
425 Each argument may be a list, vector or string.
426 The last argument is not copied, just used as the tail of the new list.
427 usage: (append &rest SEQUENCES) */)
428 (nargs, args)
429 int nargs;
430 Lisp_Object *args;
432 return concat (nargs, args, Lisp_Cons, 1);
435 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
436 doc: /* Concatenate all the arguments and make the result a string.
437 The result is a string whose elements are the elements of all the arguments.
438 Each argument may be a string or a list or vector of characters (integers).
439 usage: (concat &rest SEQUENCES) */)
440 (nargs, args)
441 int nargs;
442 Lisp_Object *args;
444 return concat (nargs, args, Lisp_String, 0);
447 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
448 doc: /* Concatenate all the arguments and make the result a vector.
449 The result is a vector whose elements are the elements of all the arguments.
450 Each argument may be a list, vector or string.
451 usage: (vconcat &rest SEQUENCES) */)
452 (nargs, args)
453 int nargs;
454 Lisp_Object *args;
456 return concat (nargs, args, Lisp_Vectorlike, 0);
459 /* Return a copy of a sub char table ARG. The elements except for a
460 nested sub char table are not copied. */
461 static Lisp_Object
462 copy_sub_char_table (arg)
463 Lisp_Object arg;
465 Lisp_Object copy = make_sub_char_table (XCHAR_TABLE (arg)->defalt);
466 int i;
468 /* Copy all the contents. */
469 bcopy (XCHAR_TABLE (arg)->contents, XCHAR_TABLE (copy)->contents,
470 SUB_CHAR_TABLE_ORDINARY_SLOTS * sizeof (Lisp_Object));
471 /* Recursively copy any sub char-tables in the ordinary slots. */
472 for (i = 32; i < SUB_CHAR_TABLE_ORDINARY_SLOTS; i++)
473 if (SUB_CHAR_TABLE_P (XCHAR_TABLE (arg)->contents[i]))
474 XCHAR_TABLE (copy)->contents[i]
475 = copy_sub_char_table (XCHAR_TABLE (copy)->contents[i]);
477 return copy;
481 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
482 doc: /* Return a copy of a list, vector, string or char-table.
483 The elements of a list or vector are not copied; they are shared
484 with the original. */)
485 (arg)
486 Lisp_Object arg;
488 if (NILP (arg)) return arg;
490 if (CHAR_TABLE_P (arg))
492 int i;
493 Lisp_Object copy;
495 copy = Fmake_char_table (XCHAR_TABLE (arg)->purpose, Qnil);
496 /* Copy all the slots, including the extra ones. */
497 bcopy (XVECTOR (arg)->contents, XVECTOR (copy)->contents,
498 ((XCHAR_TABLE (arg)->size & PSEUDOVECTOR_SIZE_MASK)
499 * sizeof (Lisp_Object)));
501 /* Recursively copy any sub char tables in the ordinary slots
502 for multibyte characters. */
503 for (i = CHAR_TABLE_SINGLE_BYTE_SLOTS;
504 i < CHAR_TABLE_ORDINARY_SLOTS; i++)
505 if (SUB_CHAR_TABLE_P (XCHAR_TABLE (arg)->contents[i]))
506 XCHAR_TABLE (copy)->contents[i]
507 = copy_sub_char_table (XCHAR_TABLE (copy)->contents[i]);
509 return copy;
512 if (BOOL_VECTOR_P (arg))
514 Lisp_Object val;
515 int size_in_chars
516 = (XBOOL_VECTOR (arg)->size + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
518 val = Fmake_bool_vector (Flength (arg), Qnil);
519 bcopy (XBOOL_VECTOR (arg)->data, XBOOL_VECTOR (val)->data,
520 size_in_chars);
521 return val;
524 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
525 arg = wrong_type_argument (Qsequencep, arg);
526 return concat (1, &arg, CONSP (arg) ? Lisp_Cons : XTYPE (arg), 0);
529 /* In string STR of length LEN, see if bytes before STR[I] combine
530 with bytes after STR[I] to form a single character. If so, return
531 the number of bytes after STR[I] which combine in this way.
532 Otherwize, return 0. */
534 static int
535 count_combining (str, len, i)
536 unsigned char *str;
537 int len, i;
539 int j = i - 1, bytes;
541 if (i == 0 || i == len || CHAR_HEAD_P (str[i]))
542 return 0;
543 while (j >= 0 && !CHAR_HEAD_P (str[j])) j--;
544 if (j < 0 || ! BASE_LEADING_CODE_P (str[j]))
545 return 0;
546 PARSE_MULTIBYTE_SEQ (str + j, len - j, bytes);
547 return (bytes <= i - j ? 0 : bytes - (i - j));
550 /* This structure holds information of an argument of `concat' that is
551 a string and has text properties to be copied. */
552 struct textprop_rec
554 int argnum; /* refer to ARGS (arguments of `concat') */
555 int from; /* refer to ARGS[argnum] (argument string) */
556 int to; /* refer to VAL (the target string) */
559 static Lisp_Object
560 concat (nargs, args, target_type, last_special)
561 int nargs;
562 Lisp_Object *args;
563 enum Lisp_Type target_type;
564 int last_special;
566 Lisp_Object val;
567 register Lisp_Object tail;
568 register Lisp_Object this;
569 int toindex;
570 int toindex_byte = 0;
571 register int result_len;
572 register int result_len_byte;
573 register int argnum;
574 Lisp_Object last_tail;
575 Lisp_Object prev;
576 int some_multibyte;
577 /* When we make a multibyte string, we can't copy text properties
578 while concatinating each string because the length of resulting
579 string can't be decided until we finish the whole concatination.
580 So, we record strings that have text properties to be copied
581 here, and copy the text properties after the concatination. */
582 struct textprop_rec *textprops = NULL;
583 /* Number of elments in textprops. */
584 int num_textprops = 0;
586 tail = Qnil;
588 /* In append, the last arg isn't treated like the others */
589 if (last_special && nargs > 0)
591 nargs--;
592 last_tail = args[nargs];
594 else
595 last_tail = Qnil;
597 /* Canonicalize each argument. */
598 for (argnum = 0; argnum < nargs; argnum++)
600 this = args[argnum];
601 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
602 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
604 args[argnum] = wrong_type_argument (Qsequencep, this);
608 /* Compute total length in chars of arguments in RESULT_LEN.
609 If desired output is a string, also compute length in bytes
610 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
611 whether the result should be a multibyte string. */
612 result_len_byte = 0;
613 result_len = 0;
614 some_multibyte = 0;
615 for (argnum = 0; argnum < nargs; argnum++)
617 int len;
618 this = args[argnum];
619 len = XFASTINT (Flength (this));
620 if (target_type == Lisp_String)
622 /* We must count the number of bytes needed in the string
623 as well as the number of characters. */
624 int i;
625 Lisp_Object ch;
626 int this_len_byte;
628 if (VECTORP (this))
629 for (i = 0; i < len; i++)
631 ch = XVECTOR (this)->contents[i];
632 if (! INTEGERP (ch))
633 wrong_type_argument (Qintegerp, ch);
634 this_len_byte = CHAR_BYTES (XINT (ch));
635 result_len_byte += this_len_byte;
636 if (!SINGLE_BYTE_CHAR_P (XINT (ch)))
637 some_multibyte = 1;
639 else if (BOOL_VECTOR_P (this) && XBOOL_VECTOR (this)->size > 0)
640 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
641 else if (CONSP (this))
642 for (; CONSP (this); this = XCDR (this))
644 ch = XCAR (this);
645 if (! INTEGERP (ch))
646 wrong_type_argument (Qintegerp, ch);
647 this_len_byte = CHAR_BYTES (XINT (ch));
648 result_len_byte += this_len_byte;
649 if (!SINGLE_BYTE_CHAR_P (XINT (ch)))
650 some_multibyte = 1;
652 else if (STRINGP (this))
654 if (STRING_MULTIBYTE (this))
656 some_multibyte = 1;
657 result_len_byte += SBYTES (this);
659 else
660 result_len_byte += count_size_as_multibyte (SDATA (this),
661 SCHARS (this));
665 result_len += len;
668 if (! some_multibyte)
669 result_len_byte = result_len;
671 /* Create the output object. */
672 if (target_type == Lisp_Cons)
673 val = Fmake_list (make_number (result_len), Qnil);
674 else if (target_type == Lisp_Vectorlike)
675 val = Fmake_vector (make_number (result_len), Qnil);
676 else if (some_multibyte)
677 val = make_uninit_multibyte_string (result_len, result_len_byte);
678 else
679 val = make_uninit_string (result_len);
681 /* In `append', if all but last arg are nil, return last arg. */
682 if (target_type == Lisp_Cons && EQ (val, Qnil))
683 return last_tail;
685 /* Copy the contents of the args into the result. */
686 if (CONSP (val))
687 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
688 else
689 toindex = 0, toindex_byte = 0;
691 prev = Qnil;
692 if (STRINGP (val))
693 textprops
694 = (struct textprop_rec *) alloca (sizeof (struct textprop_rec) * nargs);
696 for (argnum = 0; argnum < nargs; argnum++)
698 Lisp_Object thislen;
699 int thisleni = 0;
700 register unsigned int thisindex = 0;
701 register unsigned int thisindex_byte = 0;
703 this = args[argnum];
704 if (!CONSP (this))
705 thislen = Flength (this), thisleni = XINT (thislen);
707 /* Between strings of the same kind, copy fast. */
708 if (STRINGP (this) && STRINGP (val)
709 && STRING_MULTIBYTE (this) == some_multibyte)
711 int thislen_byte = SBYTES (this);
712 int combined;
714 bcopy (SDATA (this), SDATA (val) + toindex_byte,
715 SBYTES (this));
716 combined = (some_multibyte && toindex_byte > 0
717 ? count_combining (SDATA (val),
718 toindex_byte + thislen_byte,
719 toindex_byte)
720 : 0);
721 if (! NULL_INTERVAL_P (STRING_INTERVALS (this)))
723 textprops[num_textprops].argnum = argnum;
724 /* We ignore text properties on characters being combined. */
725 textprops[num_textprops].from = combined;
726 textprops[num_textprops++].to = toindex;
728 toindex_byte += thislen_byte;
729 toindex += thisleni - combined;
730 STRING_SET_CHARS (val, SCHARS (val) - combined);
732 /* Copy a single-byte string to a multibyte string. */
733 else if (STRINGP (this) && STRINGP (val))
735 if (! NULL_INTERVAL_P (STRING_INTERVALS (this)))
737 textprops[num_textprops].argnum = argnum;
738 textprops[num_textprops].from = 0;
739 textprops[num_textprops++].to = toindex;
741 toindex_byte += copy_text (SDATA (this),
742 SDATA (val) + toindex_byte,
743 SCHARS (this), 0, 1);
744 toindex += thisleni;
746 else
747 /* Copy element by element. */
748 while (1)
750 register Lisp_Object elt;
752 /* Fetch next element of `this' arg into `elt', or break if
753 `this' is exhausted. */
754 if (NILP (this)) break;
755 if (CONSP (this))
756 elt = XCAR (this), this = XCDR (this);
757 else if (thisindex >= thisleni)
758 break;
759 else if (STRINGP (this))
761 int c;
762 if (STRING_MULTIBYTE (this))
764 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
765 thisindex,
766 thisindex_byte);
767 XSETFASTINT (elt, c);
769 else
771 XSETFASTINT (elt, SREF (this, thisindex++));
772 if (some_multibyte
773 && (XINT (elt) >= 0240
774 || (XINT (elt) >= 0200
775 && ! NILP (Vnonascii_translation_table)))
776 && XINT (elt) < 0400)
778 c = unibyte_char_to_multibyte (XINT (elt));
779 XSETINT (elt, c);
783 else if (BOOL_VECTOR_P (this))
785 int byte;
786 byte = XBOOL_VECTOR (this)->data[thisindex / BITS_PER_CHAR];
787 if (byte & (1 << (thisindex % BITS_PER_CHAR)))
788 elt = Qt;
789 else
790 elt = Qnil;
791 thisindex++;
793 else
794 elt = XVECTOR (this)->contents[thisindex++];
796 /* Store this element into the result. */
797 if (toindex < 0)
799 XSETCAR (tail, elt);
800 prev = tail;
801 tail = XCDR (tail);
803 else if (VECTORP (val))
804 XVECTOR (val)->contents[toindex++] = elt;
805 else
807 CHECK_NUMBER (elt);
808 if (SINGLE_BYTE_CHAR_P (XINT (elt)))
810 if (some_multibyte)
811 toindex_byte
812 += CHAR_STRING (XINT (elt),
813 SDATA (val) + toindex_byte);
814 else
815 SSET (val, toindex_byte++, XINT (elt));
816 if (some_multibyte
817 && toindex_byte > 0
818 && count_combining (SDATA (val),
819 toindex_byte, toindex_byte - 1))
820 STRING_SET_CHARS (val, SCHARS (val) - 1);
821 else
822 toindex++;
824 else
825 /* If we have any multibyte characters,
826 we already decided to make a multibyte string. */
828 int c = XINT (elt);
829 /* P exists as a variable
830 to avoid a bug on the Masscomp C compiler. */
831 unsigned char *p = SDATA (val) + toindex_byte;
833 toindex_byte += CHAR_STRING (c, p);
834 toindex++;
839 if (!NILP (prev))
840 XSETCDR (prev, last_tail);
842 if (num_textprops > 0)
844 Lisp_Object props;
845 int last_to_end = -1;
847 for (argnum = 0; argnum < num_textprops; argnum++)
849 this = args[textprops[argnum].argnum];
850 props = text_property_list (this,
851 make_number (0),
852 make_number (SCHARS (this)),
853 Qnil);
854 /* If successive arguments have properites, be sure that the
855 value of `composition' property be the copy. */
856 if (last_to_end == textprops[argnum].to)
857 make_composition_value_copy (props);
858 add_text_properties_from_list (val, props,
859 make_number (textprops[argnum].to));
860 last_to_end = textprops[argnum].to + SCHARS (this);
863 return val;
866 static Lisp_Object string_char_byte_cache_string;
867 static int string_char_byte_cache_charpos;
868 static int string_char_byte_cache_bytepos;
870 void
871 clear_string_char_byte_cache ()
873 string_char_byte_cache_string = Qnil;
876 /* Return the character index corresponding to CHAR_INDEX in STRING. */
879 string_char_to_byte (string, char_index)
880 Lisp_Object string;
881 int char_index;
883 int i, i_byte;
884 int best_below, best_below_byte;
885 int best_above, best_above_byte;
887 if (! STRING_MULTIBYTE (string))
888 return char_index;
890 best_below = best_below_byte = 0;
891 best_above = SCHARS (string);
892 best_above_byte = SBYTES (string);
894 if (EQ (string, string_char_byte_cache_string))
896 if (string_char_byte_cache_charpos < char_index)
898 best_below = string_char_byte_cache_charpos;
899 best_below_byte = string_char_byte_cache_bytepos;
901 else
903 best_above = string_char_byte_cache_charpos;
904 best_above_byte = string_char_byte_cache_bytepos;
908 if (char_index - best_below < best_above - char_index)
910 while (best_below < char_index)
912 int c;
913 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, string,
914 best_below, best_below_byte);
916 i = best_below;
917 i_byte = best_below_byte;
919 else
921 while (best_above > char_index)
923 unsigned char *pend = SDATA (string) + best_above_byte;
924 unsigned char *pbeg = pend - best_above_byte;
925 unsigned char *p = pend - 1;
926 int bytes;
928 while (p > pbeg && !CHAR_HEAD_P (*p)) p--;
929 PARSE_MULTIBYTE_SEQ (p, pend - p, bytes);
930 if (bytes == pend - p)
931 best_above_byte -= bytes;
932 else if (bytes > pend - p)
933 best_above_byte -= (pend - p);
934 else
935 best_above_byte--;
936 best_above--;
938 i = best_above;
939 i_byte = best_above_byte;
942 string_char_byte_cache_bytepos = i_byte;
943 string_char_byte_cache_charpos = i;
944 string_char_byte_cache_string = string;
946 return i_byte;
949 /* Return the character index corresponding to BYTE_INDEX in STRING. */
952 string_byte_to_char (string, byte_index)
953 Lisp_Object string;
954 int byte_index;
956 int i, i_byte;
957 int best_below, best_below_byte;
958 int best_above, best_above_byte;
960 if (! STRING_MULTIBYTE (string))
961 return byte_index;
963 best_below = best_below_byte = 0;
964 best_above = SCHARS (string);
965 best_above_byte = SBYTES (string);
967 if (EQ (string, string_char_byte_cache_string))
969 if (string_char_byte_cache_bytepos < byte_index)
971 best_below = string_char_byte_cache_charpos;
972 best_below_byte = string_char_byte_cache_bytepos;
974 else
976 best_above = string_char_byte_cache_charpos;
977 best_above_byte = string_char_byte_cache_bytepos;
981 if (byte_index - best_below_byte < best_above_byte - byte_index)
983 while (best_below_byte < byte_index)
985 int c;
986 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, string,
987 best_below, best_below_byte);
989 i = best_below;
990 i_byte = best_below_byte;
992 else
994 while (best_above_byte > byte_index)
996 unsigned char *pend = SDATA (string) + best_above_byte;
997 unsigned char *pbeg = pend - best_above_byte;
998 unsigned char *p = pend - 1;
999 int bytes;
1001 while (p > pbeg && !CHAR_HEAD_P (*p)) p--;
1002 PARSE_MULTIBYTE_SEQ (p, pend - p, bytes);
1003 if (bytes == pend - p)
1004 best_above_byte -= bytes;
1005 else if (bytes > pend - p)
1006 best_above_byte -= (pend - p);
1007 else
1008 best_above_byte--;
1009 best_above--;
1011 i = best_above;
1012 i_byte = best_above_byte;
1015 string_char_byte_cache_bytepos = i_byte;
1016 string_char_byte_cache_charpos = i;
1017 string_char_byte_cache_string = string;
1019 return i;
1022 /* Convert STRING to a multibyte string.
1023 Single-byte characters 0240 through 0377 are converted
1024 by adding nonascii_insert_offset to each. */
1026 Lisp_Object
1027 string_make_multibyte (string)
1028 Lisp_Object string;
1030 unsigned char *buf;
1031 int nbytes;
1033 if (STRING_MULTIBYTE (string))
1034 return string;
1036 nbytes = count_size_as_multibyte (SDATA (string),
1037 SCHARS (string));
1038 /* If all the chars are ASCII, they won't need any more bytes
1039 once converted. In that case, we can return STRING itself. */
1040 if (nbytes == SBYTES (string))
1041 return string;
1043 buf = (unsigned char *) alloca (nbytes);
1044 copy_text (SDATA (string), buf, SBYTES (string),
1045 0, 1);
1047 return make_multibyte_string (buf, SCHARS (string), nbytes);
1051 /* Convert STRING to a multibyte string without changing each
1052 character codes. Thus, characters 0200 trough 0237 are converted
1053 to eight-bit-control characters, and characters 0240 through 0377
1054 are converted eight-bit-graphic characters. */
1056 Lisp_Object
1057 string_to_multibyte (string)
1058 Lisp_Object string;
1060 unsigned char *buf;
1061 int nbytes;
1063 if (STRING_MULTIBYTE (string))
1064 return string;
1066 nbytes = parse_str_to_multibyte (SDATA (string), SBYTES (string));
1067 /* If all the chars are ASCII or eight-bit-graphic, they won't need
1068 any more bytes once converted. */
1069 if (nbytes == SBYTES (string))
1070 return make_multibyte_string (SDATA (string), nbytes, nbytes);
1072 buf = (unsigned char *) alloca (nbytes);
1073 bcopy (SDATA (string), buf, SBYTES (string));
1074 str_to_multibyte (buf, nbytes, SBYTES (string));
1076 return make_multibyte_string (buf, SCHARS (string), nbytes);
1080 /* Convert STRING to a single-byte string. */
1082 Lisp_Object
1083 string_make_unibyte (string)
1084 Lisp_Object string;
1086 unsigned char *buf;
1088 if (! STRING_MULTIBYTE (string))
1089 return string;
1091 buf = (unsigned char *) alloca (SCHARS (string));
1093 copy_text (SDATA (string), buf, SBYTES (string),
1094 1, 0);
1096 return make_unibyte_string (buf, SCHARS (string));
1099 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
1100 1, 1, 0,
1101 doc: /* Return the multibyte equivalent of STRING.
1102 If STRING is unibyte and contains non-ASCII characters, the function
1103 `unibyte-char-to-multibyte' is used to convert each unibyte character
1104 to a multibyte character. In this case, the returned string is a
1105 newly created string with no text properties. If STRING is multibyte
1106 or entirely ASCII, it is returned unchanged. In particular, when
1107 STRING is unibyte and entirely ASCII, the returned string is unibyte.
1108 \(When the characters are all ASCII, Emacs primitives will treat the
1109 string the same way whether it is unibyte or multibyte.) */)
1110 (string)
1111 Lisp_Object string;
1113 CHECK_STRING (string);
1115 return string_make_multibyte (string);
1118 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
1119 1, 1, 0,
1120 doc: /* Return the unibyte equivalent of STRING.
1121 Multibyte character codes are converted to unibyte according to
1122 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
1123 If the lookup in the translation table fails, this function takes just
1124 the low 8 bits of each character. */)
1125 (string)
1126 Lisp_Object string;
1128 CHECK_STRING (string);
1130 return string_make_unibyte (string);
1133 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
1134 1, 1, 0,
1135 doc: /* Return a unibyte string with the same individual bytes as STRING.
1136 If STRING is unibyte, the result is STRING itself.
1137 Otherwise it is a newly created string, with no text properties.
1138 If STRING is multibyte and contains a character of charset
1139 `eight-bit-control' or `eight-bit-graphic', it is converted to the
1140 corresponding single byte. */)
1141 (string)
1142 Lisp_Object string;
1144 CHECK_STRING (string);
1146 if (STRING_MULTIBYTE (string))
1148 int bytes = SBYTES (string);
1149 unsigned char *str = (unsigned char *) xmalloc (bytes);
1151 bcopy (SDATA (string), str, bytes);
1152 bytes = str_as_unibyte (str, bytes);
1153 string = make_unibyte_string (str, bytes);
1154 xfree (str);
1156 return string;
1159 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1160 1, 1, 0,
1161 doc: /* Return a multibyte string with the same individual bytes as STRING.
1162 If STRING is multibyte, the result is STRING itself.
1163 Otherwise it is a newly created string, with no text properties.
1164 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1165 part of a multibyte form), it is converted to the corresponding
1166 multibyte character of charset `eight-bit-control' or `eight-bit-graphic'. */)
1167 (string)
1168 Lisp_Object string;
1170 CHECK_STRING (string);
1172 if (! STRING_MULTIBYTE (string))
1174 Lisp_Object new_string;
1175 int nchars, nbytes;
1177 parse_str_as_multibyte (SDATA (string),
1178 SBYTES (string),
1179 &nchars, &nbytes);
1180 new_string = make_uninit_multibyte_string (nchars, nbytes);
1181 bcopy (SDATA (string), SDATA (new_string),
1182 SBYTES (string));
1183 if (nbytes != SBYTES (string))
1184 str_as_multibyte (SDATA (new_string), nbytes,
1185 SBYTES (string), NULL);
1186 string = new_string;
1187 STRING_SET_INTERVALS (string, NULL_INTERVAL);
1189 return string;
1192 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1193 1, 1, 0,
1194 doc: /* Return a multibyte string with the same individual chars as STRING.
1195 If STRING is multibyte, the result is STRING itself.
1196 Otherwise it is a newly created string, with no text properties.
1197 Characters 0200 through 0237 are converted to eight-bit-control
1198 characters of the same character code. Characters 0240 through 0377
1199 are converted to eight-bit-graphic characters of the same character
1200 codes. */)
1201 (string)
1202 Lisp_Object string;
1204 CHECK_STRING (string);
1206 return string_to_multibyte (string);
1210 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1211 doc: /* Return a copy of ALIST.
1212 This is an alist which represents the same mapping from objects to objects,
1213 but does not share the alist structure with ALIST.
1214 The objects mapped (cars and cdrs of elements of the alist)
1215 are shared, however.
1216 Elements of ALIST that are not conses are also shared. */)
1217 (alist)
1218 Lisp_Object alist;
1220 register Lisp_Object tem;
1222 CHECK_LIST (alist);
1223 if (NILP (alist))
1224 return alist;
1225 alist = concat (1, &alist, Lisp_Cons, 0);
1226 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1228 register Lisp_Object car;
1229 car = XCAR (tem);
1231 if (CONSP (car))
1232 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1234 return alist;
1237 DEFUN ("substring", Fsubstring, Ssubstring, 2, 3, 0,
1238 doc: /* Return a substring of STRING, starting at index FROM and ending before TO.
1239 TO may be nil or omitted; then the substring runs to the end of STRING.
1240 FROM and TO start at 0. If either is negative, it counts from the end.
1242 This function allows vectors as well as strings. */)
1243 (string, from, to)
1244 Lisp_Object string;
1245 register Lisp_Object from, to;
1247 Lisp_Object res;
1248 int size;
1249 int size_byte = 0;
1250 int from_char, to_char;
1251 int from_byte = 0, to_byte = 0;
1253 if (! (STRINGP (string) || VECTORP (string)))
1254 wrong_type_argument (Qarrayp, string);
1256 CHECK_NUMBER (from);
1258 if (STRINGP (string))
1260 size = SCHARS (string);
1261 size_byte = SBYTES (string);
1263 else
1264 size = XVECTOR (string)->size;
1266 if (NILP (to))
1268 to_char = size;
1269 to_byte = size_byte;
1271 else
1273 CHECK_NUMBER (to);
1275 to_char = XINT (to);
1276 if (to_char < 0)
1277 to_char += size;
1279 if (STRINGP (string))
1280 to_byte = string_char_to_byte (string, to_char);
1283 from_char = XINT (from);
1284 if (from_char < 0)
1285 from_char += size;
1286 if (STRINGP (string))
1287 from_byte = string_char_to_byte (string, from_char);
1289 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1290 args_out_of_range_3 (string, make_number (from_char),
1291 make_number (to_char));
1293 if (STRINGP (string))
1295 res = make_specified_string (SDATA (string) + from_byte,
1296 to_char - from_char, to_byte - from_byte,
1297 STRING_MULTIBYTE (string));
1298 copy_text_properties (make_number (from_char), make_number (to_char),
1299 string, make_number (0), res, Qnil);
1301 else
1302 res = Fvector (to_char - from_char,
1303 XVECTOR (string)->contents + from_char);
1305 return res;
1309 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1310 doc: /* Return a substring of STRING, without text properties.
1311 It starts at index FROM and ending before TO.
1312 TO may be nil or omitted; then the substring runs to the end of STRING.
1313 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1314 If FROM or TO is negative, it counts from the end.
1316 With one argument, just copy STRING without its properties. */)
1317 (string, from, to)
1318 Lisp_Object string;
1319 register Lisp_Object from, to;
1321 int size, size_byte;
1322 int from_char, to_char;
1323 int from_byte, to_byte;
1325 CHECK_STRING (string);
1327 size = SCHARS (string);
1328 size_byte = SBYTES (string);
1330 if (NILP (from))
1331 from_char = from_byte = 0;
1332 else
1334 CHECK_NUMBER (from);
1335 from_char = XINT (from);
1336 if (from_char < 0)
1337 from_char += size;
1339 from_byte = string_char_to_byte (string, from_char);
1342 if (NILP (to))
1344 to_char = size;
1345 to_byte = size_byte;
1347 else
1349 CHECK_NUMBER (to);
1351 to_char = XINT (to);
1352 if (to_char < 0)
1353 to_char += size;
1355 to_byte = string_char_to_byte (string, to_char);
1358 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1359 args_out_of_range_3 (string, make_number (from_char),
1360 make_number (to_char));
1362 return make_specified_string (SDATA (string) + from_byte,
1363 to_char - from_char, to_byte - from_byte,
1364 STRING_MULTIBYTE (string));
1367 /* Extract a substring of STRING, giving start and end positions
1368 both in characters and in bytes. */
1370 Lisp_Object
1371 substring_both (string, from, from_byte, to, to_byte)
1372 Lisp_Object string;
1373 int from, from_byte, to, to_byte;
1375 Lisp_Object res;
1376 int size;
1377 int size_byte;
1379 if (! (STRINGP (string) || VECTORP (string)))
1380 wrong_type_argument (Qarrayp, string);
1382 if (STRINGP (string))
1384 size = SCHARS (string);
1385 size_byte = SBYTES (string);
1387 else
1388 size = XVECTOR (string)->size;
1390 if (!(0 <= from && from <= to && to <= size))
1391 args_out_of_range_3 (string, make_number (from), make_number (to));
1393 if (STRINGP (string))
1395 res = make_specified_string (SDATA (string) + from_byte,
1396 to - from, to_byte - from_byte,
1397 STRING_MULTIBYTE (string));
1398 copy_text_properties (make_number (from), make_number (to),
1399 string, make_number (0), res, Qnil);
1401 else
1402 res = Fvector (to - from,
1403 XVECTOR (string)->contents + from);
1405 return res;
1408 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1409 doc: /* Take cdr N times on LIST, returns the result. */)
1410 (n, list)
1411 Lisp_Object n;
1412 register Lisp_Object list;
1414 register int i, num;
1415 CHECK_NUMBER (n);
1416 num = XINT (n);
1417 for (i = 0; i < num && !NILP (list); i++)
1419 QUIT;
1420 if (! CONSP (list))
1421 wrong_type_argument (Qlistp, list);
1422 list = XCDR (list);
1424 return list;
1427 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1428 doc: /* Return the Nth element of LIST.
1429 N counts from zero. If LIST is not that long, nil is returned. */)
1430 (n, list)
1431 Lisp_Object n, list;
1433 return Fcar (Fnthcdr (n, list));
1436 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1437 doc: /* Return element of SEQUENCE at index N. */)
1438 (sequence, n)
1439 register Lisp_Object sequence, n;
1441 CHECK_NUMBER (n);
1442 while (1)
1444 if (CONSP (sequence) || NILP (sequence))
1445 return Fcar (Fnthcdr (n, sequence));
1446 else if (STRINGP (sequence) || VECTORP (sequence)
1447 || BOOL_VECTOR_P (sequence) || CHAR_TABLE_P (sequence))
1448 return Faref (sequence, n);
1449 else
1450 sequence = wrong_type_argument (Qsequencep, sequence);
1454 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1455 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1456 The value is actually the tail of LIST whose car is ELT. */)
1457 (elt, list)
1458 register Lisp_Object elt;
1459 Lisp_Object list;
1461 register Lisp_Object tail;
1462 for (tail = list; !NILP (tail); tail = XCDR (tail))
1464 register Lisp_Object tem;
1465 if (! CONSP (tail))
1466 wrong_type_argument (Qlistp, list);
1467 tem = XCAR (tail);
1468 if (! NILP (Fequal (elt, tem)))
1469 return tail;
1470 QUIT;
1472 return Qnil;
1475 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1476 doc: /* Return non-nil if ELT is an element of LIST.
1477 Comparison done with EQ. The value is actually the tail of LIST
1478 whose car is ELT. */)
1479 (elt, list)
1480 Lisp_Object elt, list;
1482 while (1)
1484 if (!CONSP (list) || EQ (XCAR (list), elt))
1485 break;
1487 list = XCDR (list);
1488 if (!CONSP (list) || EQ (XCAR (list), elt))
1489 break;
1491 list = XCDR (list);
1492 if (!CONSP (list) || EQ (XCAR (list), elt))
1493 break;
1495 list = XCDR (list);
1496 QUIT;
1499 if (!CONSP (list) && !NILP (list))
1500 list = wrong_type_argument (Qlistp, list);
1502 return list;
1505 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1506 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1507 The value is actually the first element of LIST whose car is KEY.
1508 Elements of LIST that are not conses are ignored. */)
1509 (key, list)
1510 Lisp_Object key, list;
1512 Lisp_Object result;
1514 while (1)
1516 if (!CONSP (list)
1517 || (CONSP (XCAR (list))
1518 && EQ (XCAR (XCAR (list)), key)))
1519 break;
1521 list = XCDR (list);
1522 if (!CONSP (list)
1523 || (CONSP (XCAR (list))
1524 && EQ (XCAR (XCAR (list)), key)))
1525 break;
1527 list = XCDR (list);
1528 if (!CONSP (list)
1529 || (CONSP (XCAR (list))
1530 && EQ (XCAR (XCAR (list)), key)))
1531 break;
1533 list = XCDR (list);
1534 QUIT;
1537 if (CONSP (list))
1538 result = XCAR (list);
1539 else if (NILP (list))
1540 result = Qnil;
1541 else
1542 result = wrong_type_argument (Qlistp, list);
1544 return result;
1547 /* Like Fassq but never report an error and do not allow quits.
1548 Use only on lists known never to be circular. */
1550 Lisp_Object
1551 assq_no_quit (key, list)
1552 Lisp_Object key, list;
1554 while (CONSP (list)
1555 && (!CONSP (XCAR (list))
1556 || !EQ (XCAR (XCAR (list)), key)))
1557 list = XCDR (list);
1559 return CONSP (list) ? XCAR (list) : Qnil;
1562 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1563 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1564 The value is actually the first element of LIST whose car equals KEY. */)
1565 (key, list)
1566 Lisp_Object key, list;
1568 Lisp_Object result, car;
1570 while (1)
1572 if (!CONSP (list)
1573 || (CONSP (XCAR (list))
1574 && (car = XCAR (XCAR (list)),
1575 EQ (car, key) || !NILP (Fequal (car, key)))))
1576 break;
1578 list = XCDR (list);
1579 if (!CONSP (list)
1580 || (CONSP (XCAR (list))
1581 && (car = XCAR (XCAR (list)),
1582 EQ (car, key) || !NILP (Fequal (car, key)))))
1583 break;
1585 list = XCDR (list);
1586 if (!CONSP (list)
1587 || (CONSP (XCAR (list))
1588 && (car = XCAR (XCAR (list)),
1589 EQ (car, key) || !NILP (Fequal (car, key)))))
1590 break;
1592 list = XCDR (list);
1593 QUIT;
1596 if (CONSP (list))
1597 result = XCAR (list);
1598 else if (NILP (list))
1599 result = Qnil;
1600 else
1601 result = wrong_type_argument (Qlistp, list);
1603 return result;
1606 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1607 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1608 The value is actually the first element of LIST whose cdr is KEY. */)
1609 (key, list)
1610 register Lisp_Object key;
1611 Lisp_Object list;
1613 Lisp_Object result;
1615 while (1)
1617 if (!CONSP (list)
1618 || (CONSP (XCAR (list))
1619 && EQ (XCDR (XCAR (list)), key)))
1620 break;
1622 list = XCDR (list);
1623 if (!CONSP (list)
1624 || (CONSP (XCAR (list))
1625 && EQ (XCDR (XCAR (list)), key)))
1626 break;
1628 list = XCDR (list);
1629 if (!CONSP (list)
1630 || (CONSP (XCAR (list))
1631 && EQ (XCDR (XCAR (list)), key)))
1632 break;
1634 list = XCDR (list);
1635 QUIT;
1638 if (NILP (list))
1639 result = Qnil;
1640 else if (CONSP (list))
1641 result = XCAR (list);
1642 else
1643 result = wrong_type_argument (Qlistp, list);
1645 return result;
1648 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1649 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1650 The value is actually the first element of LIST whose cdr equals KEY. */)
1651 (key, list)
1652 Lisp_Object key, list;
1654 Lisp_Object result, cdr;
1656 while (1)
1658 if (!CONSP (list)
1659 || (CONSP (XCAR (list))
1660 && (cdr = XCDR (XCAR (list)),
1661 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1662 break;
1664 list = XCDR (list);
1665 if (!CONSP (list)
1666 || (CONSP (XCAR (list))
1667 && (cdr = XCDR (XCAR (list)),
1668 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1669 break;
1671 list = XCDR (list);
1672 if (!CONSP (list)
1673 || (CONSP (XCAR (list))
1674 && (cdr = XCDR (XCAR (list)),
1675 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1676 break;
1678 list = XCDR (list);
1679 QUIT;
1682 if (CONSP (list))
1683 result = XCAR (list);
1684 else if (NILP (list))
1685 result = Qnil;
1686 else
1687 result = wrong_type_argument (Qlistp, list);
1689 return result;
1692 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1693 doc: /* Delete by side effect any occurrences of ELT as a member of LIST.
1694 The modified LIST is returned. Comparison is done with `eq'.
1695 If the first member of LIST is ELT, there is no way to remove it by side effect;
1696 therefore, write `(setq foo (delq element foo))'
1697 to be sure of changing the value of `foo'. */)
1698 (elt, list)
1699 register Lisp_Object elt;
1700 Lisp_Object list;
1702 register Lisp_Object tail, prev;
1703 register Lisp_Object tem;
1705 tail = list;
1706 prev = Qnil;
1707 while (!NILP (tail))
1709 if (! CONSP (tail))
1710 wrong_type_argument (Qlistp, list);
1711 tem = XCAR (tail);
1712 if (EQ (elt, tem))
1714 if (NILP (prev))
1715 list = XCDR (tail);
1716 else
1717 Fsetcdr (prev, XCDR (tail));
1719 else
1720 prev = tail;
1721 tail = XCDR (tail);
1722 QUIT;
1724 return list;
1727 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1728 doc: /* Delete by side effect any occurrences of ELT as a member of SEQ.
1729 SEQ must be a list, a vector, or a string.
1730 The modified SEQ is returned. Comparison is done with `equal'.
1731 If SEQ is not a list, or the first member of SEQ is ELT, deleting it
1732 is not a side effect; it is simply using a different sequence.
1733 Therefore, write `(setq foo (delete element foo))'
1734 to be sure of changing the value of `foo'. */)
1735 (elt, seq)
1736 Lisp_Object elt, seq;
1738 if (VECTORP (seq))
1740 EMACS_INT i, n;
1742 for (i = n = 0; i < ASIZE (seq); ++i)
1743 if (NILP (Fequal (AREF (seq, i), elt)))
1744 ++n;
1746 if (n != ASIZE (seq))
1748 struct Lisp_Vector *p = allocate_vector (n);
1750 for (i = n = 0; i < ASIZE (seq); ++i)
1751 if (NILP (Fequal (AREF (seq, i), elt)))
1752 p->contents[n++] = AREF (seq, i);
1754 XSETVECTOR (seq, p);
1757 else if (STRINGP (seq))
1759 EMACS_INT i, ibyte, nchars, nbytes, cbytes;
1760 int c;
1762 for (i = nchars = nbytes = ibyte = 0;
1763 i < SCHARS (seq);
1764 ++i, ibyte += cbytes)
1766 if (STRING_MULTIBYTE (seq))
1768 c = STRING_CHAR (SDATA (seq) + ibyte,
1769 SBYTES (seq) - ibyte);
1770 cbytes = CHAR_BYTES (c);
1772 else
1774 c = SREF (seq, i);
1775 cbytes = 1;
1778 if (!INTEGERP (elt) || c != XINT (elt))
1780 ++nchars;
1781 nbytes += cbytes;
1785 if (nchars != SCHARS (seq))
1787 Lisp_Object tem;
1789 tem = make_uninit_multibyte_string (nchars, nbytes);
1790 if (!STRING_MULTIBYTE (seq))
1791 STRING_SET_UNIBYTE (tem);
1793 for (i = nchars = nbytes = ibyte = 0;
1794 i < SCHARS (seq);
1795 ++i, ibyte += cbytes)
1797 if (STRING_MULTIBYTE (seq))
1799 c = STRING_CHAR (SDATA (seq) + ibyte,
1800 SBYTES (seq) - ibyte);
1801 cbytes = CHAR_BYTES (c);
1803 else
1805 c = SREF (seq, i);
1806 cbytes = 1;
1809 if (!INTEGERP (elt) || c != XINT (elt))
1811 unsigned char *from = SDATA (seq) + ibyte;
1812 unsigned char *to = SDATA (tem) + nbytes;
1813 EMACS_INT n;
1815 ++nchars;
1816 nbytes += cbytes;
1818 for (n = cbytes; n--; )
1819 *to++ = *from++;
1823 seq = tem;
1826 else
1828 Lisp_Object tail, prev;
1830 for (tail = seq, prev = Qnil; !NILP (tail); tail = XCDR (tail))
1832 if (!CONSP (tail))
1833 wrong_type_argument (Qlistp, seq);
1835 if (!NILP (Fequal (elt, XCAR (tail))))
1837 if (NILP (prev))
1838 seq = XCDR (tail);
1839 else
1840 Fsetcdr (prev, XCDR (tail));
1842 else
1843 prev = tail;
1844 QUIT;
1848 return seq;
1851 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1852 doc: /* Reverse LIST by modifying cdr pointers.
1853 Return the reversed list. */)
1854 (list)
1855 Lisp_Object list;
1857 register Lisp_Object prev, tail, next;
1859 if (NILP (list)) return list;
1860 prev = Qnil;
1861 tail = list;
1862 while (!NILP (tail))
1864 QUIT;
1865 if (! CONSP (tail))
1866 wrong_type_argument (Qlistp, list);
1867 next = XCDR (tail);
1868 Fsetcdr (tail, prev);
1869 prev = tail;
1870 tail = next;
1872 return prev;
1875 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1876 doc: /* Reverse LIST, copying. Return the reversed list.
1877 See also the function `nreverse', which is used more often. */)
1878 (list)
1879 Lisp_Object list;
1881 Lisp_Object new;
1883 for (new = Qnil; CONSP (list); list = XCDR (list))
1885 QUIT;
1886 new = Fcons (XCAR (list), new);
1888 if (!NILP (list))
1889 wrong_type_argument (Qconsp, list);
1890 return new;
1893 Lisp_Object merge ();
1895 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
1896 doc: /* Sort LIST, stably, comparing elements using PREDICATE.
1897 Returns the sorted list. LIST is modified by side effects.
1898 PREDICATE is called with two elements of LIST, and should return t
1899 if the first element is "less" than the second. */)
1900 (list, predicate)
1901 Lisp_Object list, predicate;
1903 Lisp_Object front, back;
1904 register Lisp_Object len, tem;
1905 struct gcpro gcpro1, gcpro2;
1906 register int length;
1908 front = list;
1909 len = Flength (list);
1910 length = XINT (len);
1911 if (length < 2)
1912 return list;
1914 XSETINT (len, (length / 2) - 1);
1915 tem = Fnthcdr (len, list);
1916 back = Fcdr (tem);
1917 Fsetcdr (tem, Qnil);
1919 GCPRO2 (front, back);
1920 front = Fsort (front, predicate);
1921 back = Fsort (back, predicate);
1922 UNGCPRO;
1923 return merge (front, back, predicate);
1926 Lisp_Object
1927 merge (org_l1, org_l2, pred)
1928 Lisp_Object org_l1, org_l2;
1929 Lisp_Object pred;
1931 Lisp_Object value;
1932 register Lisp_Object tail;
1933 Lisp_Object tem;
1934 register Lisp_Object l1, l2;
1935 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1937 l1 = org_l1;
1938 l2 = org_l2;
1939 tail = Qnil;
1940 value = Qnil;
1942 /* It is sufficient to protect org_l1 and org_l2.
1943 When l1 and l2 are updated, we copy the new values
1944 back into the org_ vars. */
1945 GCPRO4 (org_l1, org_l2, pred, value);
1947 while (1)
1949 if (NILP (l1))
1951 UNGCPRO;
1952 if (NILP (tail))
1953 return l2;
1954 Fsetcdr (tail, l2);
1955 return value;
1957 if (NILP (l2))
1959 UNGCPRO;
1960 if (NILP (tail))
1961 return l1;
1962 Fsetcdr (tail, l1);
1963 return value;
1965 tem = call2 (pred, Fcar (l2), Fcar (l1));
1966 if (NILP (tem))
1968 tem = l1;
1969 l1 = Fcdr (l1);
1970 org_l1 = l1;
1972 else
1974 tem = l2;
1975 l2 = Fcdr (l2);
1976 org_l2 = l2;
1978 if (NILP (tail))
1979 value = tem;
1980 else
1981 Fsetcdr (tail, tem);
1982 tail = tem;
1987 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
1988 doc: /* Extract a value from a property list.
1989 PLIST is a property list, which is a list of the form
1990 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1991 corresponding to the given PROP, or nil if PROP is not
1992 one of the properties on the list. */)
1993 (plist, prop)
1994 Lisp_Object plist;
1995 Lisp_Object prop;
1997 Lisp_Object tail;
1999 for (tail = plist;
2000 CONSP (tail) && CONSP (XCDR (tail));
2001 tail = XCDR (XCDR (tail)))
2003 if (EQ (prop, XCAR (tail)))
2004 return XCAR (XCDR (tail));
2006 /* This function can be called asynchronously
2007 (setup_coding_system). Don't QUIT in that case. */
2008 if (!interrupt_input_blocked)
2009 QUIT;
2012 if (!NILP (tail))
2013 wrong_type_argument (Qlistp, prop);
2015 return Qnil;
2018 DEFUN ("get", Fget, Sget, 2, 2, 0,
2019 doc: /* Return the value of SYMBOL's PROPNAME property.
2020 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
2021 (symbol, propname)
2022 Lisp_Object symbol, propname;
2024 CHECK_SYMBOL (symbol);
2025 return Fplist_get (XSYMBOL (symbol)->plist, propname);
2028 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
2029 doc: /* Change value in PLIST of PROP to VAL.
2030 PLIST is a property list, which is a list of the form
2031 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
2032 If PROP is already a property on the list, its value is set to VAL,
2033 otherwise the new PROP VAL pair is added. The new plist is returned;
2034 use `(setq x (plist-put x prop val))' to be sure to use the new value.
2035 The PLIST is modified by side effects. */)
2036 (plist, prop, val)
2037 Lisp_Object plist;
2038 register Lisp_Object prop;
2039 Lisp_Object val;
2041 register Lisp_Object tail, prev;
2042 Lisp_Object newcell;
2043 prev = Qnil;
2044 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2045 tail = XCDR (XCDR (tail)))
2047 if (EQ (prop, XCAR (tail)))
2049 Fsetcar (XCDR (tail), val);
2050 return plist;
2053 prev = tail;
2054 QUIT;
2056 newcell = Fcons (prop, Fcons (val, Qnil));
2057 if (NILP (prev))
2058 return newcell;
2059 else
2060 Fsetcdr (XCDR (prev), newcell);
2061 return plist;
2064 DEFUN ("put", Fput, Sput, 3, 3, 0,
2065 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
2066 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
2067 (symbol, propname, value)
2068 Lisp_Object symbol, propname, value;
2070 CHECK_SYMBOL (symbol);
2071 XSYMBOL (symbol)->plist
2072 = Fplist_put (XSYMBOL (symbol)->plist, propname, value);
2073 return value;
2076 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
2077 doc: /* Extract a value from a property list, comparing with `equal'.
2078 PLIST is a property list, which is a list of the form
2079 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2080 corresponding to the given PROP, or nil if PROP is not
2081 one of the properties on the list. */)
2082 (plist, prop)
2083 Lisp_Object plist;
2084 Lisp_Object prop;
2086 Lisp_Object tail;
2088 for (tail = plist;
2089 CONSP (tail) && CONSP (XCDR (tail));
2090 tail = XCDR (XCDR (tail)))
2092 if (! NILP (Fequal (prop, XCAR (tail))))
2093 return XCAR (XCDR (tail));
2095 QUIT;
2098 if (!NILP (tail))
2099 wrong_type_argument (Qlistp, prop);
2101 return Qnil;
2104 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
2105 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
2106 PLIST is a property list, which is a list of the form
2107 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
2108 If PROP is already a property on the list, its value is set to VAL,
2109 otherwise the new PROP VAL pair is added. The new plist is returned;
2110 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
2111 The PLIST is modified by side effects. */)
2112 (plist, prop, val)
2113 Lisp_Object plist;
2114 register Lisp_Object prop;
2115 Lisp_Object val;
2117 register Lisp_Object tail, prev;
2118 Lisp_Object newcell;
2119 prev = Qnil;
2120 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2121 tail = XCDR (XCDR (tail)))
2123 if (! NILP (Fequal (prop, XCAR (tail))))
2125 Fsetcar (XCDR (tail), val);
2126 return plist;
2129 prev = tail;
2130 QUIT;
2132 newcell = Fcons (prop, Fcons (val, Qnil));
2133 if (NILP (prev))
2134 return newcell;
2135 else
2136 Fsetcdr (XCDR (prev), newcell);
2137 return plist;
2140 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
2141 doc: /* Return t if two Lisp objects have similar structure and contents.
2142 They must have the same data type.
2143 Conses are compared by comparing the cars and the cdrs.
2144 Vectors and strings are compared element by element.
2145 Numbers are compared by value, but integers cannot equal floats.
2146 (Use `=' if you want integers and floats to be able to be equal.)
2147 Symbols must match exactly. */)
2148 (o1, o2)
2149 register Lisp_Object o1, o2;
2151 return internal_equal (o1, o2, 0) ? Qt : Qnil;
2154 static int
2155 internal_equal (o1, o2, depth)
2156 register Lisp_Object o1, o2;
2157 int depth;
2159 if (depth > 200)
2160 error ("Stack overflow in equal");
2162 tail_recurse:
2163 QUIT;
2164 if (EQ (o1, o2))
2165 return 1;
2166 if (XTYPE (o1) != XTYPE (o2))
2167 return 0;
2169 switch (XTYPE (o1))
2171 case Lisp_Float:
2172 return (extract_float (o1) == extract_float (o2));
2174 case Lisp_Cons:
2175 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1))
2176 return 0;
2177 o1 = XCDR (o1);
2178 o2 = XCDR (o2);
2179 goto tail_recurse;
2181 case Lisp_Misc:
2182 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2183 return 0;
2184 if (OVERLAYP (o1))
2186 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2187 depth + 1)
2188 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2189 depth + 1))
2190 return 0;
2191 o1 = XOVERLAY (o1)->plist;
2192 o2 = XOVERLAY (o2)->plist;
2193 goto tail_recurse;
2195 if (MARKERP (o1))
2197 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2198 && (XMARKER (o1)->buffer == 0
2199 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2201 break;
2203 case Lisp_Vectorlike:
2205 register int i;
2206 EMACS_INT size = XVECTOR (o1)->size;
2207 /* Pseudovectors have the type encoded in the size field, so this test
2208 actually checks that the objects have the same type as well as the
2209 same size. */
2210 if (XVECTOR (o2)->size != size)
2211 return 0;
2212 /* Boolvectors are compared much like strings. */
2213 if (BOOL_VECTOR_P (o1))
2215 int size_in_chars
2216 = (XBOOL_VECTOR (o1)->size + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
2218 if (XBOOL_VECTOR (o1)->size != XBOOL_VECTOR (o2)->size)
2219 return 0;
2220 if (bcmp (XBOOL_VECTOR (o1)->data, XBOOL_VECTOR (o2)->data,
2221 size_in_chars))
2222 return 0;
2223 return 1;
2225 if (WINDOW_CONFIGURATIONP (o1))
2226 return compare_window_configurations (o1, o2, 0);
2228 /* Aside from them, only true vectors, char-tables, and compiled
2229 functions are sensible to compare, so eliminate the others now. */
2230 if (size & PSEUDOVECTOR_FLAG)
2232 if (!(size & (PVEC_COMPILED | PVEC_CHAR_TABLE)))
2233 return 0;
2234 size &= PSEUDOVECTOR_SIZE_MASK;
2236 for (i = 0; i < size; i++)
2238 Lisp_Object v1, v2;
2239 v1 = XVECTOR (o1)->contents [i];
2240 v2 = XVECTOR (o2)->contents [i];
2241 if (!internal_equal (v1, v2, depth + 1))
2242 return 0;
2244 return 1;
2246 break;
2248 case Lisp_String:
2249 if (SCHARS (o1) != SCHARS (o2))
2250 return 0;
2251 if (SBYTES (o1) != SBYTES (o2))
2252 return 0;
2253 if (bcmp (SDATA (o1), SDATA (o2),
2254 SBYTES (o1)))
2255 return 0;
2256 return 1;
2258 case Lisp_Int:
2259 case Lisp_Symbol:
2260 case Lisp_Type_Limit:
2261 break;
2264 return 0;
2267 extern Lisp_Object Fmake_char_internal ();
2269 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2270 doc: /* Store each element of ARRAY with ITEM.
2271 ARRAY is a vector, string, char-table, or bool-vector. */)
2272 (array, item)
2273 Lisp_Object array, item;
2275 register int size, index, charval;
2276 retry:
2277 if (VECTORP (array))
2279 register Lisp_Object *p = XVECTOR (array)->contents;
2280 size = XVECTOR (array)->size;
2281 for (index = 0; index < size; index++)
2282 p[index] = item;
2284 else if (CHAR_TABLE_P (array))
2286 register Lisp_Object *p = XCHAR_TABLE (array)->contents;
2287 size = CHAR_TABLE_ORDINARY_SLOTS;
2288 for (index = 0; index < size; index++)
2289 p[index] = item;
2290 XCHAR_TABLE (array)->defalt = Qnil;
2292 else if (STRINGP (array))
2294 register unsigned char *p = SDATA (array);
2295 CHECK_NUMBER (item);
2296 charval = XINT (item);
2297 size = SCHARS (array);
2298 if (STRING_MULTIBYTE (array))
2300 unsigned char str[MAX_MULTIBYTE_LENGTH];
2301 int len = CHAR_STRING (charval, str);
2302 int size_byte = SBYTES (array);
2303 unsigned char *p1 = p, *endp = p + size_byte;
2304 int i;
2306 if (size != size_byte)
2307 while (p1 < endp)
2309 int this_len = MULTIBYTE_FORM_LENGTH (p1, endp - p1);
2310 if (len != this_len)
2311 error ("Attempt to change byte length of a string");
2312 p1 += this_len;
2314 for (i = 0; i < size_byte; i++)
2315 *p++ = str[i % len];
2317 else
2318 for (index = 0; index < size; index++)
2319 p[index] = charval;
2321 else if (BOOL_VECTOR_P (array))
2323 register unsigned char *p = XBOOL_VECTOR (array)->data;
2324 int size_in_chars
2325 = (XBOOL_VECTOR (array)->size + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
2327 charval = (! NILP (item) ? -1 : 0);
2328 for (index = 0; index < size_in_chars - 1; index++)
2329 p[index] = charval;
2330 if (index < size_in_chars)
2332 /* Mask out bits beyond the vector size. */
2333 if (XBOOL_VECTOR (array)->size % BITS_PER_CHAR)
2334 charval &= (1 << (XBOOL_VECTOR (array)->size % BITS_PER_CHAR)) - 1;
2335 p[index] = charval;
2338 else
2340 array = wrong_type_argument (Qarrayp, array);
2341 goto retry;
2343 return array;
2346 DEFUN ("clear-string", Fclear_string, Sclear_string,
2347 1, 1, 0,
2348 doc: /* Clear the contents of STRING.
2349 This makes STRING unibyte and may change its length. */)
2350 (string)
2351 Lisp_Object string;
2353 int len = SBYTES (string);
2354 bzero (SDATA (string), len);
2355 STRING_SET_CHARS (string, len);
2356 STRING_SET_UNIBYTE (string);
2357 return Qnil;
2360 DEFUN ("char-table-subtype", Fchar_table_subtype, Schar_table_subtype,
2361 1, 1, 0,
2362 doc: /* Return the subtype of char-table CHAR-TABLE. The value is a symbol. */)
2363 (char_table)
2364 Lisp_Object char_table;
2366 CHECK_CHAR_TABLE (char_table);
2368 return XCHAR_TABLE (char_table)->purpose;
2371 DEFUN ("char-table-parent", Fchar_table_parent, Schar_table_parent,
2372 1, 1, 0,
2373 doc: /* Return the parent char-table of CHAR-TABLE.
2374 The value is either nil or another char-table.
2375 If CHAR-TABLE holds nil for a given character,
2376 then the actual applicable value is inherited from the parent char-table
2377 \(or from its parents, if necessary). */)
2378 (char_table)
2379 Lisp_Object char_table;
2381 CHECK_CHAR_TABLE (char_table);
2383 return XCHAR_TABLE (char_table)->parent;
2386 DEFUN ("set-char-table-parent", Fset_char_table_parent, Sset_char_table_parent,
2387 2, 2, 0,
2388 doc: /* Set the parent char-table of CHAR-TABLE to PARENT.
2389 Return PARENT. PARENT must be either nil or another char-table. */)
2390 (char_table, parent)
2391 Lisp_Object char_table, parent;
2393 Lisp_Object temp;
2395 CHECK_CHAR_TABLE (char_table);
2397 if (!NILP (parent))
2399 CHECK_CHAR_TABLE (parent);
2401 for (temp = parent; !NILP (temp); temp = XCHAR_TABLE (temp)->parent)
2402 if (EQ (temp, char_table))
2403 error ("Attempt to make a chartable be its own parent");
2406 XCHAR_TABLE (char_table)->parent = parent;
2408 return parent;
2411 DEFUN ("char-table-extra-slot", Fchar_table_extra_slot, Schar_table_extra_slot,
2412 2, 2, 0,
2413 doc: /* Return the value of CHAR-TABLE's extra-slot number N. */)
2414 (char_table, n)
2415 Lisp_Object char_table, n;
2417 CHECK_CHAR_TABLE (char_table);
2418 CHECK_NUMBER (n);
2419 if (XINT (n) < 0
2420 || XINT (n) >= CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (char_table)))
2421 args_out_of_range (char_table, n);
2423 return XCHAR_TABLE (char_table)->extras[XINT (n)];
2426 DEFUN ("set-char-table-extra-slot", Fset_char_table_extra_slot,
2427 Sset_char_table_extra_slot,
2428 3, 3, 0,
2429 doc: /* Set CHAR-TABLE's extra-slot number N to VALUE. */)
2430 (char_table, n, value)
2431 Lisp_Object char_table, n, value;
2433 CHECK_CHAR_TABLE (char_table);
2434 CHECK_NUMBER (n);
2435 if (XINT (n) < 0
2436 || XINT (n) >= CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (char_table)))
2437 args_out_of_range (char_table, n);
2439 return XCHAR_TABLE (char_table)->extras[XINT (n)] = value;
2442 DEFUN ("char-table-range", Fchar_table_range, Schar_table_range,
2443 2, 2, 0,
2444 doc: /* Return the value in CHAR-TABLE for a range of characters RANGE.
2445 RANGE should be nil (for the default value)
2446 a vector which identifies a character set or a row of a character set,
2447 a character set name, or a character code. */)
2448 (char_table, range)
2449 Lisp_Object char_table, range;
2451 CHECK_CHAR_TABLE (char_table);
2453 if (EQ (range, Qnil))
2454 return XCHAR_TABLE (char_table)->defalt;
2455 else if (INTEGERP (range))
2456 return Faref (char_table, range);
2457 else if (SYMBOLP (range))
2459 Lisp_Object charset_info;
2461 charset_info = Fget (range, Qcharset);
2462 CHECK_VECTOR (charset_info);
2464 return Faref (char_table,
2465 make_number (XINT (XVECTOR (charset_info)->contents[0])
2466 + 128));
2468 else if (VECTORP (range))
2470 if (XVECTOR (range)->size == 1)
2471 return Faref (char_table,
2472 make_number (XINT (XVECTOR (range)->contents[0]) + 128));
2473 else
2475 int size = XVECTOR (range)->size;
2476 Lisp_Object *val = XVECTOR (range)->contents;
2477 Lisp_Object ch = Fmake_char_internal (size <= 0 ? Qnil : val[0],
2478 size <= 1 ? Qnil : val[1],
2479 size <= 2 ? Qnil : val[2]);
2480 return Faref (char_table, ch);
2483 else
2484 error ("Invalid RANGE argument to `char-table-range'");
2485 return Qt;
2488 DEFUN ("set-char-table-range", Fset_char_table_range, Sset_char_table_range,
2489 3, 3, 0,
2490 doc: /* Set the value in CHAR-TABLE for a range of characters RANGE to VALUE.
2491 RANGE should be t (for all characters), nil (for the default value),
2492 a character set, a vector which identifies a character set, a row of a
2493 character set, or a character code. Return VALUE. */)
2494 (char_table, range, value)
2495 Lisp_Object char_table, range, value;
2497 int i;
2499 CHECK_CHAR_TABLE (char_table);
2501 if (EQ (range, Qt))
2502 for (i = 0; i < CHAR_TABLE_ORDINARY_SLOTS; i++)
2503 XCHAR_TABLE (char_table)->contents[i] = value;
2504 else if (EQ (range, Qnil))
2505 XCHAR_TABLE (char_table)->defalt = value;
2506 else if (SYMBOLP (range))
2508 Lisp_Object charset_info;
2510 charset_info = Fget (range, Qcharset);
2511 CHECK_VECTOR (charset_info);
2513 return Faset (char_table,
2514 make_number (XINT (XVECTOR (charset_info)->contents[0])
2515 + 128),
2516 value);
2518 else if (INTEGERP (range))
2519 Faset (char_table, range, value);
2520 else if (VECTORP (range))
2522 if (XVECTOR (range)->size == 1)
2523 return Faset (char_table,
2524 make_number (XINT (XVECTOR (range)->contents[0]) + 128),
2525 value);
2526 else
2528 int size = XVECTOR (range)->size;
2529 Lisp_Object *val = XVECTOR (range)->contents;
2530 Lisp_Object ch = Fmake_char_internal (size <= 0 ? Qnil : val[0],
2531 size <= 1 ? Qnil : val[1],
2532 size <= 2 ? Qnil : val[2]);
2533 return Faset (char_table, ch, value);
2536 else
2537 error ("Invalid RANGE argument to `set-char-table-range'");
2539 return value;
2542 DEFUN ("set-char-table-default", Fset_char_table_default,
2543 Sset_char_table_default, 3, 3, 0,
2544 doc: /* Set the default value in CHAR-TABLE for generic character CH to VALUE.
2545 The generic character specifies the group of characters.
2546 See also the documentation of `make-char'. */)
2547 (char_table, ch, value)
2548 Lisp_Object char_table, ch, value;
2550 int c, charset, code1, code2;
2551 Lisp_Object temp;
2553 CHECK_CHAR_TABLE (char_table);
2554 CHECK_NUMBER (ch);
2556 c = XINT (ch);
2557 SPLIT_CHAR (c, charset, code1, code2);
2559 /* Since we may want to set the default value for a character set
2560 not yet defined, we check only if the character set is in the
2561 valid range or not, instead of it is already defined or not. */
2562 if (! CHARSET_VALID_P (charset))
2563 invalid_character (c);
2565 if (charset == CHARSET_ASCII)
2566 return (XCHAR_TABLE (char_table)->defalt = value);
2568 /* Even if C is not a generic char, we had better behave as if a
2569 generic char is specified. */
2570 if (!CHARSET_DEFINED_P (charset) || CHARSET_DIMENSION (charset) == 1)
2571 code1 = 0;
2572 temp = XCHAR_TABLE (char_table)->contents[charset + 128];
2573 if (!code1)
2575 if (SUB_CHAR_TABLE_P (temp))
2576 XCHAR_TABLE (temp)->defalt = value;
2577 else
2578 XCHAR_TABLE (char_table)->contents[charset + 128] = value;
2579 return value;
2581 if (SUB_CHAR_TABLE_P (temp))
2582 char_table = temp;
2583 else
2584 char_table = (XCHAR_TABLE (char_table)->contents[charset + 128]
2585 = make_sub_char_table (temp));
2586 temp = XCHAR_TABLE (char_table)->contents[code1];
2587 if (SUB_CHAR_TABLE_P (temp))
2588 XCHAR_TABLE (temp)->defalt = value;
2589 else
2590 XCHAR_TABLE (char_table)->contents[code1] = value;
2591 return value;
2594 /* Look up the element in TABLE at index CH,
2595 and return it as an integer.
2596 If the element is nil, return CH itself.
2597 (Actually we do that for any non-integer.) */
2600 char_table_translate (table, ch)
2601 Lisp_Object table;
2602 int ch;
2604 Lisp_Object value;
2605 value = Faref (table, make_number (ch));
2606 if (! INTEGERP (value))
2607 return ch;
2608 return XINT (value);
2611 static void
2612 optimize_sub_char_table (table, chars)
2613 Lisp_Object *table;
2614 int chars;
2616 Lisp_Object elt;
2617 int from, to;
2619 if (chars == 94)
2620 from = 33, to = 127;
2621 else
2622 from = 32, to = 128;
2624 if (!SUB_CHAR_TABLE_P (*table))
2625 return;
2626 elt = XCHAR_TABLE (*table)->contents[from++];
2627 for (; from < to; from++)
2628 if (NILP (Fequal (elt, XCHAR_TABLE (*table)->contents[from])))
2629 return;
2630 *table = elt;
2633 DEFUN ("optimize-char-table", Foptimize_char_table, Soptimize_char_table,
2634 1, 1, 0, doc: /* Optimize char table TABLE. */)
2635 (table)
2636 Lisp_Object table;
2638 Lisp_Object elt;
2639 int dim;
2640 int i, j;
2642 CHECK_CHAR_TABLE (table);
2644 for (i = CHAR_TABLE_SINGLE_BYTE_SLOTS; i < CHAR_TABLE_ORDINARY_SLOTS; i++)
2646 elt = XCHAR_TABLE (table)->contents[i];
2647 if (!SUB_CHAR_TABLE_P (elt))
2648 continue;
2649 dim = CHARSET_DIMENSION (i - 128);
2650 if (dim == 2)
2651 for (j = 32; j < SUB_CHAR_TABLE_ORDINARY_SLOTS; j++)
2652 optimize_sub_char_table (XCHAR_TABLE (elt)->contents + j, dim);
2653 optimize_sub_char_table (XCHAR_TABLE (table)->contents + i, dim);
2655 return Qnil;
2659 /* Map C_FUNCTION or FUNCTION over SUBTABLE, calling it for each
2660 character or group of characters that share a value.
2661 DEPTH is the current depth in the originally specified
2662 chartable, and INDICES contains the vector indices
2663 for the levels our callers have descended.
2665 ARG is passed to C_FUNCTION when that is called. */
2667 void
2668 map_char_table (c_function, function, table, subtable, arg, depth, indices)
2669 void (*c_function) P_ ((Lisp_Object, Lisp_Object, Lisp_Object));
2670 Lisp_Object function, table, subtable, arg, *indices;
2671 int depth;
2673 int i, to;
2675 if (depth == 0)
2677 /* At first, handle ASCII and 8-bit European characters. */
2678 for (i = 0; i < CHAR_TABLE_SINGLE_BYTE_SLOTS; i++)
2680 Lisp_Object elt= XCHAR_TABLE (subtable)->contents[i];
2681 if (NILP (elt))
2682 elt = XCHAR_TABLE (subtable)->defalt;
2683 if (NILP (elt))
2684 elt = Faref (subtable, make_number (i));
2685 if (c_function)
2686 (*c_function) (arg, make_number (i), elt);
2687 else
2688 call2 (function, make_number (i), elt);
2690 #if 0 /* If the char table has entries for higher characters,
2691 we should report them. */
2692 if (NILP (current_buffer->enable_multibyte_characters))
2693 return;
2694 #endif
2695 to = CHAR_TABLE_ORDINARY_SLOTS;
2697 else
2699 int charset = XFASTINT (indices[0]) - 128;
2701 i = 32;
2702 to = SUB_CHAR_TABLE_ORDINARY_SLOTS;
2703 if (CHARSET_CHARS (charset) == 94)
2704 i++, to--;
2707 for (; i < to; i++)
2709 Lisp_Object elt;
2710 int charset;
2712 elt = XCHAR_TABLE (subtable)->contents[i];
2713 XSETFASTINT (indices[depth], i);
2714 charset = XFASTINT (indices[0]) - 128;
2715 if (depth == 0
2716 && (!CHARSET_DEFINED_P (charset)
2717 || charset == CHARSET_8_BIT_CONTROL
2718 || charset == CHARSET_8_BIT_GRAPHIC))
2719 continue;
2721 if (SUB_CHAR_TABLE_P (elt))
2723 if (depth >= 3)
2724 error ("Too deep char table");
2725 map_char_table (c_function, function, table, elt, arg, depth + 1, indices);
2727 else
2729 int c1, c2, c;
2731 c1 = depth >= 1 ? XFASTINT (indices[1]) : 0;
2732 c2 = depth >= 2 ? XFASTINT (indices[2]) : 0;
2733 c = MAKE_CHAR (charset, c1, c2);
2735 if (NILP (elt))
2736 elt = XCHAR_TABLE (subtable)->defalt;
2737 if (NILP (elt))
2738 elt = Faref (table, make_number (c));
2740 if (c_function)
2741 (*c_function) (arg, make_number (c), elt);
2742 else
2743 call2 (function, make_number (c), elt);
2748 static void void_call2 P_ ((Lisp_Object a, Lisp_Object b, Lisp_Object c));
2749 static void
2750 void_call2 (a, b, c)
2751 Lisp_Object a, b, c;
2753 call2 (a, b, c);
2756 DEFUN ("map-char-table", Fmap_char_table, Smap_char_table,
2757 2, 2, 0,
2758 doc: /* Call FUNCTION for each (normal and generic) characters in CHAR-TABLE.
2759 FUNCTION is called with two arguments--a key and a value.
2760 The key is always a possible IDX argument to `aref'. */)
2761 (function, char_table)
2762 Lisp_Object function, char_table;
2764 /* The depth of char table is at most 3. */
2765 Lisp_Object indices[3];
2767 CHECK_CHAR_TABLE (char_table);
2769 /* When Lisp_Object is represented as a union, `call2' cannot directly
2770 be passed to map_char_table because it returns a Lisp_Object rather
2771 than returning nothing.
2772 Casting leads to crashes on some architectures. -stef */
2773 map_char_table (void_call2, Qnil, char_table, char_table, function, 0, indices);
2774 return Qnil;
2777 /* Return a value for character C in char-table TABLE. Store the
2778 actual index for that value in *IDX. Ignore the default value of
2779 TABLE. */
2781 Lisp_Object
2782 char_table_ref_and_index (table, c, idx)
2783 Lisp_Object table;
2784 int c, *idx;
2786 int charset, c1, c2;
2787 Lisp_Object elt;
2789 if (SINGLE_BYTE_CHAR_P (c))
2791 *idx = c;
2792 return XCHAR_TABLE (table)->contents[c];
2794 SPLIT_CHAR (c, charset, c1, c2);
2795 elt = XCHAR_TABLE (table)->contents[charset + 128];
2796 *idx = MAKE_CHAR (charset, 0, 0);
2797 if (!SUB_CHAR_TABLE_P (elt))
2798 return elt;
2799 if (c1 < 32 || NILP (XCHAR_TABLE (elt)->contents[c1]))
2800 return XCHAR_TABLE (elt)->defalt;
2801 elt = XCHAR_TABLE (elt)->contents[c1];
2802 *idx = MAKE_CHAR (charset, c1, 0);
2803 if (!SUB_CHAR_TABLE_P (elt))
2804 return elt;
2805 if (c2 < 32 || NILP (XCHAR_TABLE (elt)->contents[c2]))
2806 return XCHAR_TABLE (elt)->defalt;
2807 *idx = c;
2808 return XCHAR_TABLE (elt)->contents[c2];
2812 /* ARGSUSED */
2813 Lisp_Object
2814 nconc2 (s1, s2)
2815 Lisp_Object s1, s2;
2817 #ifdef NO_ARG_ARRAY
2818 Lisp_Object args[2];
2819 args[0] = s1;
2820 args[1] = s2;
2821 return Fnconc (2, args);
2822 #else
2823 return Fnconc (2, &s1);
2824 #endif /* NO_ARG_ARRAY */
2827 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2828 doc: /* Concatenate any number of lists by altering them.
2829 Only the last argument is not altered, and need not be a list.
2830 usage: (nconc &rest LISTS) */)
2831 (nargs, args)
2832 int nargs;
2833 Lisp_Object *args;
2835 register int argnum;
2836 register Lisp_Object tail, tem, val;
2838 val = tail = Qnil;
2840 for (argnum = 0; argnum < nargs; argnum++)
2842 tem = args[argnum];
2843 if (NILP (tem)) continue;
2845 if (NILP (val))
2846 val = tem;
2848 if (argnum + 1 == nargs) break;
2850 if (!CONSP (tem))
2851 tem = wrong_type_argument (Qlistp, tem);
2853 while (CONSP (tem))
2855 tail = tem;
2856 tem = XCDR (tail);
2857 QUIT;
2860 tem = args[argnum + 1];
2861 Fsetcdr (tail, tem);
2862 if (NILP (tem))
2863 args[argnum + 1] = tail;
2866 return val;
2869 /* This is the guts of all mapping functions.
2870 Apply FN to each element of SEQ, one by one,
2871 storing the results into elements of VALS, a C vector of Lisp_Objects.
2872 LENI is the length of VALS, which should also be the length of SEQ. */
2874 static void
2875 mapcar1 (leni, vals, fn, seq)
2876 int leni;
2877 Lisp_Object *vals;
2878 Lisp_Object fn, seq;
2880 register Lisp_Object tail;
2881 Lisp_Object dummy;
2882 register int i;
2883 struct gcpro gcpro1, gcpro2, gcpro3;
2885 if (vals)
2887 /* Don't let vals contain any garbage when GC happens. */
2888 for (i = 0; i < leni; i++)
2889 vals[i] = Qnil;
2891 GCPRO3 (dummy, fn, seq);
2892 gcpro1.var = vals;
2893 gcpro1.nvars = leni;
2895 else
2896 GCPRO2 (fn, seq);
2897 /* We need not explicitly protect `tail' because it is used only on lists, and
2898 1) lists are not relocated and 2) the list is marked via `seq' so will not be freed */
2900 if (VECTORP (seq))
2902 for (i = 0; i < leni; i++)
2904 dummy = XVECTOR (seq)->contents[i];
2905 dummy = call1 (fn, dummy);
2906 if (vals)
2907 vals[i] = dummy;
2910 else if (BOOL_VECTOR_P (seq))
2912 for (i = 0; i < leni; i++)
2914 int byte;
2915 byte = XBOOL_VECTOR (seq)->data[i / BITS_PER_CHAR];
2916 if (byte & (1 << (i % BITS_PER_CHAR)))
2917 dummy = Qt;
2918 else
2919 dummy = Qnil;
2921 dummy = call1 (fn, dummy);
2922 if (vals)
2923 vals[i] = dummy;
2926 else if (STRINGP (seq))
2928 int i_byte;
2930 for (i = 0, i_byte = 0; i < leni;)
2932 int c;
2933 int i_before = i;
2935 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2936 XSETFASTINT (dummy, c);
2937 dummy = call1 (fn, dummy);
2938 if (vals)
2939 vals[i_before] = dummy;
2942 else /* Must be a list, since Flength did not get an error */
2944 tail = seq;
2945 for (i = 0; i < leni; i++)
2947 dummy = call1 (fn, Fcar (tail));
2948 if (vals)
2949 vals[i] = dummy;
2950 tail = XCDR (tail);
2954 UNGCPRO;
2957 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2958 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2959 In between each pair of results, stick in SEPARATOR. Thus, " " as
2960 SEPARATOR results in spaces between the values returned by FUNCTION.
2961 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2962 (function, sequence, separator)
2963 Lisp_Object function, sequence, separator;
2965 Lisp_Object len;
2966 register int leni;
2967 int nargs;
2968 register Lisp_Object *args;
2969 register int i;
2970 struct gcpro gcpro1;
2972 len = Flength (sequence);
2973 leni = XINT (len);
2974 nargs = leni + leni - 1;
2975 if (nargs < 0) return build_string ("");
2977 args = (Lisp_Object *) alloca (nargs * sizeof (Lisp_Object));
2979 GCPRO1 (separator);
2980 mapcar1 (leni, args, function, sequence);
2981 UNGCPRO;
2983 for (i = leni - 1; i >= 0; i--)
2984 args[i + i] = args[i];
2986 for (i = 1; i < nargs; i += 2)
2987 args[i] = separator;
2989 return Fconcat (nargs, args);
2992 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2993 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2994 The result is a list just as long as SEQUENCE.
2995 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2996 (function, sequence)
2997 Lisp_Object function, sequence;
2999 register Lisp_Object len;
3000 register int leni;
3001 register Lisp_Object *args;
3003 len = Flength (sequence);
3004 leni = XFASTINT (len);
3005 args = (Lisp_Object *) alloca (leni * sizeof (Lisp_Object));
3007 mapcar1 (leni, args, function, sequence);
3009 return Flist (leni, args);
3012 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
3013 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
3014 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
3015 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
3016 (function, sequence)
3017 Lisp_Object function, sequence;
3019 register int leni;
3021 leni = XFASTINT (Flength (sequence));
3022 mapcar1 (leni, 0, function, sequence);
3024 return sequence;
3027 /* Anything that calls this function must protect from GC! */
3029 DEFUN ("y-or-n-p", Fy_or_n_p, Sy_or_n_p, 1, 1, 0,
3030 doc: /* Ask user a "y or n" question. Return t if answer is "y".
3031 Takes one argument, which is the string to display to ask the question.
3032 It should end in a space; `y-or-n-p' adds `(y or n) ' to it.
3033 No confirmation of the answer is requested; a single character is enough.
3034 Also accepts Space to mean yes, or Delete to mean no. \(Actually, it uses
3035 the bindings in `query-replace-map'; see the documentation of that variable
3036 for more information. In this case, the useful bindings are `act', `skip',
3037 `recenter', and `quit'.\)
3039 Under a windowing system a dialog box will be used if `last-nonmenu-event'
3040 is nil and `use-dialog-box' is non-nil. */)
3041 (prompt)
3042 Lisp_Object prompt;
3044 register Lisp_Object obj, key, def, map;
3045 register int answer;
3046 Lisp_Object xprompt;
3047 Lisp_Object args[2];
3048 struct gcpro gcpro1, gcpro2;
3049 int count = SPECPDL_INDEX ();
3051 specbind (Qcursor_in_echo_area, Qt);
3053 map = Fsymbol_value (intern ("query-replace-map"));
3055 CHECK_STRING (prompt);
3056 xprompt = prompt;
3057 GCPRO2 (prompt, xprompt);
3059 #ifdef HAVE_X_WINDOWS
3060 if (display_hourglass_p)
3061 cancel_hourglass ();
3062 #endif
3064 while (1)
3067 #ifdef HAVE_MENUS
3068 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3069 && use_dialog_box
3070 && have_menus_p ())
3072 Lisp_Object pane, menu;
3073 redisplay_preserve_echo_area (3);
3074 pane = Fcons (Fcons (build_string ("Yes"), Qt),
3075 Fcons (Fcons (build_string ("No"), Qnil),
3076 Qnil));
3077 menu = Fcons (prompt, pane);
3078 obj = Fx_popup_dialog (Qt, menu);
3079 answer = !NILP (obj);
3080 break;
3082 #endif /* HAVE_MENUS */
3083 cursor_in_echo_area = 1;
3084 choose_minibuf_frame ();
3087 Lisp_Object pargs[3];
3089 /* Colorize prompt according to `minibuffer-prompt' face. */
3090 pargs[0] = build_string ("%s(y or n) ");
3091 pargs[1] = intern ("face");
3092 pargs[2] = intern ("minibuffer-prompt");
3093 args[0] = Fpropertize (3, pargs);
3094 args[1] = xprompt;
3095 Fmessage (2, args);
3098 if (minibuffer_auto_raise)
3100 Lisp_Object mini_frame;
3102 mini_frame = WINDOW_FRAME (XWINDOW (minibuf_window));
3104 Fraise_frame (mini_frame);
3107 obj = read_filtered_event (1, 0, 0, 0);
3108 cursor_in_echo_area = 0;
3109 /* If we need to quit, quit with cursor_in_echo_area = 0. */
3110 QUIT;
3112 key = Fmake_vector (make_number (1), obj);
3113 def = Flookup_key (map, key, Qt);
3115 if (EQ (def, intern ("skip")))
3117 answer = 0;
3118 break;
3120 else if (EQ (def, intern ("act")))
3122 answer = 1;
3123 break;
3125 else if (EQ (def, intern ("recenter")))
3127 Frecenter (Qnil);
3128 xprompt = prompt;
3129 continue;
3131 else if (EQ (def, intern ("quit")))
3132 Vquit_flag = Qt;
3133 /* We want to exit this command for exit-prefix,
3134 and this is the only way to do it. */
3135 else if (EQ (def, intern ("exit-prefix")))
3136 Vquit_flag = Qt;
3138 QUIT;
3140 /* If we don't clear this, then the next call to read_char will
3141 return quit_char again, and we'll enter an infinite loop. */
3142 Vquit_flag = Qnil;
3144 Fding (Qnil);
3145 Fdiscard_input ();
3146 if (EQ (xprompt, prompt))
3148 args[0] = build_string ("Please answer y or n. ");
3149 args[1] = prompt;
3150 xprompt = Fconcat (2, args);
3153 UNGCPRO;
3155 if (! noninteractive)
3157 cursor_in_echo_area = -1;
3158 message_with_string (answer ? "%s(y or n) y" : "%s(y or n) n",
3159 xprompt, 0);
3162 unbind_to (count, Qnil);
3163 return answer ? Qt : Qnil;
3166 /* This is how C code calls `yes-or-no-p' and allows the user
3167 to redefined it.
3169 Anything that calls this function must protect from GC! */
3171 Lisp_Object
3172 do_yes_or_no_p (prompt)
3173 Lisp_Object prompt;
3175 return call1 (intern ("yes-or-no-p"), prompt);
3178 /* Anything that calls this function must protect from GC! */
3180 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
3181 doc: /* Ask user a yes-or-no question. Return t if answer is yes.
3182 Takes one argument, which is the string to display to ask the question.
3183 It should end in a space; `yes-or-no-p' adds `(yes or no) ' to it.
3184 The user must confirm the answer with RET,
3185 and can edit it until it has been confirmed.
3187 Under a windowing system a dialog box will be used if `last-nonmenu-event'
3188 is nil, and `use-dialog-box' is non-nil. */)
3189 (prompt)
3190 Lisp_Object prompt;
3192 register Lisp_Object ans;
3193 Lisp_Object args[2];
3194 struct gcpro gcpro1;
3196 CHECK_STRING (prompt);
3198 #ifdef HAVE_MENUS
3199 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3200 && use_dialog_box
3201 && have_menus_p ())
3203 Lisp_Object pane, menu, obj;
3204 redisplay_preserve_echo_area (4);
3205 pane = Fcons (Fcons (build_string ("Yes"), Qt),
3206 Fcons (Fcons (build_string ("No"), Qnil),
3207 Qnil));
3208 GCPRO1 (pane);
3209 menu = Fcons (prompt, pane);
3210 obj = Fx_popup_dialog (Qt, menu);
3211 UNGCPRO;
3212 return obj;
3214 #endif /* HAVE_MENUS */
3216 args[0] = prompt;
3217 args[1] = build_string ("(yes or no) ");
3218 prompt = Fconcat (2, args);
3220 GCPRO1 (prompt);
3222 while (1)
3224 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
3225 Qyes_or_no_p_history, Qnil,
3226 Qnil));
3227 if (SCHARS (ans) == 3 && !strcmp (SDATA (ans), "yes"))
3229 UNGCPRO;
3230 return Qt;
3232 if (SCHARS (ans) == 2 && !strcmp (SDATA (ans), "no"))
3234 UNGCPRO;
3235 return Qnil;
3238 Fding (Qnil);
3239 Fdiscard_input ();
3240 message ("Please answer yes or no.");
3241 Fsleep_for (make_number (2), Qnil);
3245 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
3246 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
3248 Each of the three load averages is multiplied by 100, then converted
3249 to integer.
3251 When USE-FLOATS is non-nil, floats will be used instead of integers.
3252 These floats are not multiplied by 100.
3254 If the 5-minute or 15-minute load averages are not available, return a
3255 shortened list, containing only those averages which are available.
3257 An error is thrown if the load average can't be obtained. In some
3258 cases making it work would require Emacs being installed setuid or
3259 setgid so that it can read kernel information, and that usually isn't
3260 advisable. */)
3261 (use_floats)
3262 Lisp_Object use_floats;
3264 double load_ave[3];
3265 int loads = getloadavg (load_ave, 3);
3266 Lisp_Object ret = Qnil;
3268 if (loads < 0)
3269 error ("load-average not implemented for this operating system");
3271 while (loads-- > 0)
3273 Lisp_Object load = (NILP (use_floats) ?
3274 make_number ((int) (100.0 * load_ave[loads]))
3275 : make_float (load_ave[loads]));
3276 ret = Fcons (load, ret);
3279 return ret;
3282 Lisp_Object Vfeatures, Qsubfeatures;
3283 extern Lisp_Object Vafter_load_alist;
3285 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
3286 doc: /* Returns t if FEATURE is present in this Emacs.
3288 Use this to conditionalize execution of lisp code based on the
3289 presence or absence of emacs or environment extensions.
3290 Use `provide' to declare that a feature is available. This function
3291 looks at the value of the variable `features'. The optional argument
3292 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
3293 (feature, subfeature)
3294 Lisp_Object feature, subfeature;
3296 register Lisp_Object tem;
3297 CHECK_SYMBOL (feature);
3298 tem = Fmemq (feature, Vfeatures);
3299 if (!NILP (tem) && !NILP (subfeature))
3300 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
3301 return (NILP (tem)) ? Qnil : Qt;
3304 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
3305 doc: /* Announce that FEATURE is a feature of the current Emacs.
3306 The optional argument SUBFEATURES should be a list of symbols listing
3307 particular subfeatures supported in this version of FEATURE. */)
3308 (feature, subfeatures)
3309 Lisp_Object feature, subfeatures;
3311 register Lisp_Object tem;
3312 CHECK_SYMBOL (feature);
3313 CHECK_LIST (subfeatures);
3314 if (!NILP (Vautoload_queue))
3315 Vautoload_queue = Fcons (Fcons (Vfeatures, Qnil), Vautoload_queue);
3316 tem = Fmemq (feature, Vfeatures);
3317 if (NILP (tem))
3318 Vfeatures = Fcons (feature, Vfeatures);
3319 if (!NILP (subfeatures))
3320 Fput (feature, Qsubfeatures, subfeatures);
3321 LOADHIST_ATTACH (Fcons (Qprovide, feature));
3323 /* Run any load-hooks for this file. */
3324 tem = Fassq (feature, Vafter_load_alist);
3325 if (CONSP (tem))
3326 Fprogn (XCDR (tem));
3328 return feature;
3331 /* `require' and its subroutines. */
3333 /* List of features currently being require'd, innermost first. */
3335 Lisp_Object require_nesting_list;
3337 Lisp_Object
3338 require_unwind (old_value)
3339 Lisp_Object old_value;
3341 return require_nesting_list = old_value;
3344 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
3345 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
3346 If FEATURE is not a member of the list `features', then the feature
3347 is not loaded; so load the file FILENAME.
3348 If FILENAME is omitted, the printname of FEATURE is used as the file name,
3349 and `load' will try to load this name appended with the suffix `.elc' or
3350 `.el', in that order. The name without appended suffix will not be used.
3351 If the optional third argument NOERROR is non-nil,
3352 then return nil if the file is not found instead of signaling an error.
3353 Normally the return value is FEATURE.
3354 The normal messages at start and end of loading FILENAME are suppressed. */)
3355 (feature, filename, noerror)
3356 Lisp_Object feature, filename, noerror;
3358 register Lisp_Object tem;
3359 struct gcpro gcpro1, gcpro2;
3361 CHECK_SYMBOL (feature);
3363 tem = Fmemq (feature, Vfeatures);
3365 if (NILP (tem))
3367 int count = SPECPDL_INDEX ();
3368 int nesting = 0;
3370 LOADHIST_ATTACH (Fcons (Qrequire, feature));
3372 /* This is to make sure that loadup.el gives a clear picture
3373 of what files are preloaded and when. */
3374 if (! NILP (Vpurify_flag))
3375 error ("(require %s) while preparing to dump",
3376 SDATA (SYMBOL_NAME (feature)));
3378 /* A certain amount of recursive `require' is legitimate,
3379 but if we require the same feature recursively 3 times,
3380 signal an error. */
3381 tem = require_nesting_list;
3382 while (! NILP (tem))
3384 if (! NILP (Fequal (feature, XCAR (tem))))
3385 nesting++;
3386 tem = XCDR (tem);
3388 if (nesting > 3)
3389 error ("Recursive `require' for feature `%s'",
3390 SDATA (SYMBOL_NAME (feature)));
3392 /* Update the list for any nested `require's that occur. */
3393 record_unwind_protect (require_unwind, require_nesting_list);
3394 require_nesting_list = Fcons (feature, require_nesting_list);
3396 /* Value saved here is to be restored into Vautoload_queue */
3397 record_unwind_protect (un_autoload, Vautoload_queue);
3398 Vautoload_queue = Qt;
3400 /* Load the file. */
3401 GCPRO2 (feature, filename);
3402 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
3403 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
3404 UNGCPRO;
3406 /* If load failed entirely, return nil. */
3407 if (NILP (tem))
3408 return unbind_to (count, Qnil);
3410 tem = Fmemq (feature, Vfeatures);
3411 if (NILP (tem))
3412 error ("Required feature `%s' was not provided",
3413 SDATA (SYMBOL_NAME (feature)));
3415 /* Once loading finishes, don't undo it. */
3416 Vautoload_queue = Qt;
3417 feature = unbind_to (count, feature);
3420 return feature;
3423 /* Primitives for work of the "widget" library.
3424 In an ideal world, this section would not have been necessary.
3425 However, lisp function calls being as slow as they are, it turns
3426 out that some functions in the widget library (wid-edit.el) are the
3427 bottleneck of Widget operation. Here is their translation to C,
3428 for the sole reason of efficiency. */
3430 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
3431 doc: /* Return non-nil if PLIST has the property PROP.
3432 PLIST is a property list, which is a list of the form
3433 \(PROP1 VALUE1 PROP2 VALUE2 ...\). PROP is a symbol.
3434 Unlike `plist-get', this allows you to distinguish between a missing
3435 property and a property with the value nil.
3436 The value is actually the tail of PLIST whose car is PROP. */)
3437 (plist, prop)
3438 Lisp_Object plist, prop;
3440 while (CONSP (plist) && !EQ (XCAR (plist), prop))
3442 QUIT;
3443 plist = XCDR (plist);
3444 plist = CDR (plist);
3446 return plist;
3449 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
3450 doc: /* In WIDGET, set PROPERTY to VALUE.
3451 The value can later be retrieved with `widget-get'. */)
3452 (widget, property, value)
3453 Lisp_Object widget, property, value;
3455 CHECK_CONS (widget);
3456 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
3457 return value;
3460 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
3461 doc: /* In WIDGET, get the value of PROPERTY.
3462 The value could either be specified when the widget was created, or
3463 later with `widget-put'. */)
3464 (widget, property)
3465 Lisp_Object widget, property;
3467 Lisp_Object tmp;
3469 while (1)
3471 if (NILP (widget))
3472 return Qnil;
3473 CHECK_CONS (widget);
3474 tmp = Fplist_member (XCDR (widget), property);
3475 if (CONSP (tmp))
3477 tmp = XCDR (tmp);
3478 return CAR (tmp);
3480 tmp = XCAR (widget);
3481 if (NILP (tmp))
3482 return Qnil;
3483 widget = Fget (tmp, Qwidget_type);
3487 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
3488 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
3489 ARGS are passed as extra arguments to the function.
3490 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
3491 (nargs, args)
3492 int nargs;
3493 Lisp_Object *args;
3495 /* This function can GC. */
3496 Lisp_Object newargs[3];
3497 struct gcpro gcpro1, gcpro2;
3498 Lisp_Object result;
3500 newargs[0] = Fwidget_get (args[0], args[1]);
3501 newargs[1] = args[0];
3502 newargs[2] = Flist (nargs - 2, args + 2);
3503 GCPRO2 (newargs[0], newargs[2]);
3504 result = Fapply (3, newargs);
3505 UNGCPRO;
3506 return result;
3509 #ifdef HAVE_LANGINFO_CODESET
3510 #include <langinfo.h>
3511 #endif
3513 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
3514 doc: /* Access locale data ITEM for the current C locale, if available.
3515 ITEM should be one of the following:
3517 `codeset', returning the character set as a string (locale item CODESET);
3519 `days', returning a 7-element vector of day names (locale items DAY_n);
3521 `months', returning a 12-element vector of month names (locale items MON_n);
3523 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
3524 both measured in milimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
3526 If the system can't provide such information through a call to
3527 `nl_langinfo', or if ITEM isn't from the list above, return nil.
3529 See also Info node `(libc)Locales'.
3531 The data read from the system are decoded using `locale-coding-system'. */)
3532 (item)
3533 Lisp_Object item;
3535 char *str = NULL;
3536 #ifdef HAVE_LANGINFO_CODESET
3537 Lisp_Object val;
3538 if (EQ (item, Qcodeset))
3540 str = nl_langinfo (CODESET);
3541 return build_string (str);
3543 #ifdef DAY_1
3544 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
3546 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
3547 int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
3548 int i;
3549 synchronize_system_time_locale ();
3550 for (i = 0; i < 7; i++)
3552 str = nl_langinfo (days[i]);
3553 val = make_unibyte_string (str, strlen (str));
3554 /* Fixme: Is this coding system necessarily right, even if
3555 it is consistent with CODESET? If not, what to do? */
3556 Faset (v, make_number (i),
3557 code_convert_string_norecord (val, Vlocale_coding_system,
3558 0));
3560 return v;
3562 #endif /* DAY_1 */
3563 #ifdef MON_1
3564 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
3566 struct Lisp_Vector *p = allocate_vector (12);
3567 int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
3568 MON_8, MON_9, MON_10, MON_11, MON_12};
3569 int i;
3570 synchronize_system_time_locale ();
3571 for (i = 0; i < 12; i++)
3573 str = nl_langinfo (months[i]);
3574 val = make_unibyte_string (str, strlen (str));
3575 p->contents[i] =
3576 code_convert_string_norecord (val, Vlocale_coding_system, 0);
3578 XSETVECTOR (val, p);
3579 return val;
3581 #endif /* MON_1 */
3582 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
3583 but is in the locale files. This could be used by ps-print. */
3584 #ifdef PAPER_WIDTH
3585 else if (EQ (item, Qpaper))
3587 return list2 (make_number (nl_langinfo (PAPER_WIDTH)),
3588 make_number (nl_langinfo (PAPER_HEIGHT)));
3590 #endif /* PAPER_WIDTH */
3591 #endif /* HAVE_LANGINFO_CODESET*/
3592 return Qnil;
3595 /* base64 encode/decode functions (RFC 2045).
3596 Based on code from GNU recode. */
3598 #define MIME_LINE_LENGTH 76
3600 #define IS_ASCII(Character) \
3601 ((Character) < 128)
3602 #define IS_BASE64(Character) \
3603 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
3604 #define IS_BASE64_IGNORABLE(Character) \
3605 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
3606 || (Character) == '\f' || (Character) == '\r')
3608 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
3609 character or return retval if there are no characters left to
3610 process. */
3611 #define READ_QUADRUPLET_BYTE(retval) \
3612 do \
3614 if (i == length) \
3616 if (nchars_return) \
3617 *nchars_return = nchars; \
3618 return (retval); \
3620 c = from[i++]; \
3622 while (IS_BASE64_IGNORABLE (c))
3624 /* Don't use alloca for regions larger than this, lest we overflow
3625 their stack. */
3626 #define MAX_ALLOCA 16*1024
3628 /* Table of characters coding the 64 values. */
3629 static char base64_value_to_char[64] =
3631 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
3632 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
3633 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
3634 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
3635 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
3636 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
3637 '8', '9', '+', '/' /* 60-63 */
3640 /* Table of base64 values for first 128 characters. */
3641 static short base64_char_to_value[128] =
3643 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
3644 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
3645 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
3646 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
3647 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
3648 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
3649 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
3650 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
3651 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
3652 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
3653 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
3654 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
3655 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
3658 /* The following diagram shows the logical steps by which three octets
3659 get transformed into four base64 characters.
3661 .--------. .--------. .--------.
3662 |aaaaaabb| |bbbbcccc| |ccdddddd|
3663 `--------' `--------' `--------'
3664 6 2 4 4 2 6
3665 .--------+--------+--------+--------.
3666 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
3667 `--------+--------+--------+--------'
3669 .--------+--------+--------+--------.
3670 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
3671 `--------+--------+--------+--------'
3673 The octets are divided into 6 bit chunks, which are then encoded into
3674 base64 characters. */
3677 static int base64_encode_1 P_ ((const char *, char *, int, int, int));
3678 static int base64_decode_1 P_ ((const char *, char *, int, int, int *));
3680 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
3681 2, 3, "r",
3682 doc: /* Base64-encode the region between BEG and END.
3683 Return the length of the encoded text.
3684 Optional third argument NO-LINE-BREAK means do not break long lines
3685 into shorter lines. */)
3686 (beg, end, no_line_break)
3687 Lisp_Object beg, end, no_line_break;
3689 char *encoded;
3690 int allength, length;
3691 int ibeg, iend, encoded_length;
3692 int old_pos = PT;
3694 validate_region (&beg, &end);
3696 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3697 iend = CHAR_TO_BYTE (XFASTINT (end));
3698 move_gap_both (XFASTINT (beg), ibeg);
3700 /* We need to allocate enough room for encoding the text.
3701 We need 33 1/3% more space, plus a newline every 76
3702 characters, and then we round up. */
3703 length = iend - ibeg;
3704 allength = length + length/3 + 1;
3705 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3707 if (allength <= MAX_ALLOCA)
3708 encoded = (char *) alloca (allength);
3709 else
3710 encoded = (char *) xmalloc (allength);
3711 encoded_length = base64_encode_1 (BYTE_POS_ADDR (ibeg), encoded, length,
3712 NILP (no_line_break),
3713 !NILP (current_buffer->enable_multibyte_characters));
3714 if (encoded_length > allength)
3715 abort ();
3717 if (encoded_length < 0)
3719 /* The encoding wasn't possible. */
3720 if (length > MAX_ALLOCA)
3721 xfree (encoded);
3722 error ("Multibyte character in data for base64 encoding");
3725 /* Now we have encoded the region, so we insert the new contents
3726 and delete the old. (Insert first in order to preserve markers.) */
3727 SET_PT_BOTH (XFASTINT (beg), ibeg);
3728 insert (encoded, encoded_length);
3729 if (allength > MAX_ALLOCA)
3730 xfree (encoded);
3731 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
3733 /* If point was outside of the region, restore it exactly; else just
3734 move to the beginning of the region. */
3735 if (old_pos >= XFASTINT (end))
3736 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
3737 else if (old_pos > XFASTINT (beg))
3738 old_pos = XFASTINT (beg);
3739 SET_PT (old_pos);
3741 /* We return the length of the encoded text. */
3742 return make_number (encoded_length);
3745 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
3746 1, 2, 0,
3747 doc: /* Base64-encode STRING and return the result.
3748 Optional second argument NO-LINE-BREAK means do not break long lines
3749 into shorter lines. */)
3750 (string, no_line_break)
3751 Lisp_Object string, no_line_break;
3753 int allength, length, encoded_length;
3754 char *encoded;
3755 Lisp_Object encoded_string;
3757 CHECK_STRING (string);
3759 /* We need to allocate enough room for encoding the text.
3760 We need 33 1/3% more space, plus a newline every 76
3761 characters, and then we round up. */
3762 length = SBYTES (string);
3763 allength = length + length/3 + 1;
3764 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3766 /* We need to allocate enough room for decoding the text. */
3767 if (allength <= MAX_ALLOCA)
3768 encoded = (char *) alloca (allength);
3769 else
3770 encoded = (char *) xmalloc (allength);
3772 encoded_length = base64_encode_1 (SDATA (string),
3773 encoded, length, NILP (no_line_break),
3774 STRING_MULTIBYTE (string));
3775 if (encoded_length > allength)
3776 abort ();
3778 if (encoded_length < 0)
3780 /* The encoding wasn't possible. */
3781 if (length > MAX_ALLOCA)
3782 xfree (encoded);
3783 error ("Multibyte character in data for base64 encoding");
3786 encoded_string = make_unibyte_string (encoded, encoded_length);
3787 if (allength > MAX_ALLOCA)
3788 xfree (encoded);
3790 return encoded_string;
3793 static int
3794 base64_encode_1 (from, to, length, line_break, multibyte)
3795 const char *from;
3796 char *to;
3797 int length;
3798 int line_break;
3799 int multibyte;
3801 int counter = 0, i = 0;
3802 char *e = to;
3803 int c;
3804 unsigned int value;
3805 int bytes;
3807 while (i < length)
3809 if (multibyte)
3811 c = STRING_CHAR_AND_LENGTH (from + i, length - i, bytes);
3812 if (c >= 256)
3813 return -1;
3814 i += bytes;
3816 else
3817 c = from[i++];
3819 /* Wrap line every 76 characters. */
3821 if (line_break)
3823 if (counter < MIME_LINE_LENGTH / 4)
3824 counter++;
3825 else
3827 *e++ = '\n';
3828 counter = 1;
3832 /* Process first byte of a triplet. */
3834 *e++ = base64_value_to_char[0x3f & c >> 2];
3835 value = (0x03 & c) << 4;
3837 /* Process second byte of a triplet. */
3839 if (i == length)
3841 *e++ = base64_value_to_char[value];
3842 *e++ = '=';
3843 *e++ = '=';
3844 break;
3847 if (multibyte)
3849 c = STRING_CHAR_AND_LENGTH (from + i, length - i, bytes);
3850 if (c >= 256)
3851 return -1;
3852 i += bytes;
3854 else
3855 c = from[i++];
3857 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3858 value = (0x0f & c) << 2;
3860 /* Process third byte of a triplet. */
3862 if (i == length)
3864 *e++ = base64_value_to_char[value];
3865 *e++ = '=';
3866 break;
3869 if (multibyte)
3871 c = STRING_CHAR_AND_LENGTH (from + i, length - i, bytes);
3872 if (c >= 256)
3873 return -1;
3874 i += bytes;
3876 else
3877 c = from[i++];
3879 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3880 *e++ = base64_value_to_char[0x3f & c];
3883 return e - to;
3887 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3888 2, 2, "r",
3889 doc: /* Base64-decode the region between BEG and END.
3890 Return the length of the decoded text.
3891 If the region can't be decoded, signal an error and don't modify the buffer. */)
3892 (beg, end)
3893 Lisp_Object beg, end;
3895 int ibeg, iend, length, allength;
3896 char *decoded;
3897 int old_pos = PT;
3898 int decoded_length;
3899 int inserted_chars;
3900 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
3902 validate_region (&beg, &end);
3904 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3905 iend = CHAR_TO_BYTE (XFASTINT (end));
3907 length = iend - ibeg;
3909 /* We need to allocate enough room for decoding the text. If we are
3910 working on a multibyte buffer, each decoded code may occupy at
3911 most two bytes. */
3912 allength = multibyte ? length * 2 : length;
3913 if (allength <= MAX_ALLOCA)
3914 decoded = (char *) alloca (allength);
3915 else
3916 decoded = (char *) xmalloc (allength);
3918 move_gap_both (XFASTINT (beg), ibeg);
3919 decoded_length = base64_decode_1 (BYTE_POS_ADDR (ibeg), decoded, length,
3920 multibyte, &inserted_chars);
3921 if (decoded_length > allength)
3922 abort ();
3924 if (decoded_length < 0)
3926 /* The decoding wasn't possible. */
3927 if (allength > MAX_ALLOCA)
3928 xfree (decoded);
3929 error ("Invalid base64 data");
3932 /* Now we have decoded the region, so we insert the new contents
3933 and delete the old. (Insert first in order to preserve markers.) */
3934 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3935 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3936 if (allength > MAX_ALLOCA)
3937 xfree (decoded);
3938 /* Delete the original text. */
3939 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3940 iend + decoded_length, 1);
3942 /* If point was outside of the region, restore it exactly; else just
3943 move to the beginning of the region. */
3944 if (old_pos >= XFASTINT (end))
3945 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3946 else if (old_pos > XFASTINT (beg))
3947 old_pos = XFASTINT (beg);
3948 SET_PT (old_pos > ZV ? ZV : old_pos);
3950 return make_number (inserted_chars);
3953 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3954 1, 1, 0,
3955 doc: /* Base64-decode STRING and return the result. */)
3956 (string)
3957 Lisp_Object string;
3959 char *decoded;
3960 int length, decoded_length;
3961 Lisp_Object decoded_string;
3963 CHECK_STRING (string);
3965 length = SBYTES (string);
3966 /* We need to allocate enough room for decoding the text. */
3967 if (length <= MAX_ALLOCA)
3968 decoded = (char *) alloca (length);
3969 else
3970 decoded = (char *) xmalloc (length);
3972 /* The decoded result should be unibyte. */
3973 decoded_length = base64_decode_1 (SDATA (string), decoded, length,
3974 0, NULL);
3975 if (decoded_length > length)
3976 abort ();
3977 else if (decoded_length >= 0)
3978 decoded_string = make_unibyte_string (decoded, decoded_length);
3979 else
3980 decoded_string = Qnil;
3982 if (length > MAX_ALLOCA)
3983 xfree (decoded);
3984 if (!STRINGP (decoded_string))
3985 error ("Invalid base64 data");
3987 return decoded_string;
3990 /* Base64-decode the data at FROM of LENGHT bytes into TO. If
3991 MULTIBYTE is nonzero, the decoded result should be in multibyte
3992 form. If NCHARS_RETRUN is not NULL, store the number of produced
3993 characters in *NCHARS_RETURN. */
3995 static int
3996 base64_decode_1 (from, to, length, multibyte, nchars_return)
3997 const char *from;
3998 char *to;
3999 int length;
4000 int multibyte;
4001 int *nchars_return;
4003 int i = 0;
4004 char *e = to;
4005 unsigned char c;
4006 unsigned long value;
4007 int nchars = 0;
4009 while (1)
4011 /* Process first byte of a quadruplet. */
4013 READ_QUADRUPLET_BYTE (e-to);
4015 if (!IS_BASE64 (c))
4016 return -1;
4017 value = base64_char_to_value[c] << 18;
4019 /* Process second byte of a quadruplet. */
4021 READ_QUADRUPLET_BYTE (-1);
4023 if (!IS_BASE64 (c))
4024 return -1;
4025 value |= base64_char_to_value[c] << 12;
4027 c = (unsigned char) (value >> 16);
4028 if (multibyte)
4029 e += CHAR_STRING (c, e);
4030 else
4031 *e++ = c;
4032 nchars++;
4034 /* Process third byte of a quadruplet. */
4036 READ_QUADRUPLET_BYTE (-1);
4038 if (c == '=')
4040 READ_QUADRUPLET_BYTE (-1);
4042 if (c != '=')
4043 return -1;
4044 continue;
4047 if (!IS_BASE64 (c))
4048 return -1;
4049 value |= base64_char_to_value[c] << 6;
4051 c = (unsigned char) (0xff & value >> 8);
4052 if (multibyte)
4053 e += CHAR_STRING (c, e);
4054 else
4055 *e++ = c;
4056 nchars++;
4058 /* Process fourth byte of a quadruplet. */
4060 READ_QUADRUPLET_BYTE (-1);
4062 if (c == '=')
4063 continue;
4065 if (!IS_BASE64 (c))
4066 return -1;
4067 value |= base64_char_to_value[c];
4069 c = (unsigned char) (0xff & value);
4070 if (multibyte)
4071 e += CHAR_STRING (c, e);
4072 else
4073 *e++ = c;
4074 nchars++;
4080 /***********************************************************************
4081 ***** *****
4082 ***** Hash Tables *****
4083 ***** *****
4084 ***********************************************************************/
4086 /* Implemented by gerd@gnu.org. This hash table implementation was
4087 inspired by CMUCL hash tables. */
4089 /* Ideas:
4091 1. For small tables, association lists are probably faster than
4092 hash tables because they have lower overhead.
4094 For uses of hash tables where the O(1) behavior of table
4095 operations is not a requirement, it might therefore be a good idea
4096 not to hash. Instead, we could just do a linear search in the
4097 key_and_value vector of the hash table. This could be done
4098 if a `:linear-search t' argument is given to make-hash-table. */
4101 /* The list of all weak hash tables. Don't staticpro this one. */
4103 Lisp_Object Vweak_hash_tables;
4105 /* Various symbols. */
4107 Lisp_Object Qhash_table_p, Qeq, Qeql, Qequal, Qkey, Qvalue;
4108 Lisp_Object QCtest, QCsize, QCrehash_size, QCrehash_threshold, QCweakness;
4109 Lisp_Object Qhash_table_test, Qkey_or_value, Qkey_and_value;
4111 /* Function prototypes. */
4113 static struct Lisp_Hash_Table *check_hash_table P_ ((Lisp_Object));
4114 static int get_key_arg P_ ((Lisp_Object, int, Lisp_Object *, char *));
4115 static void maybe_resize_hash_table P_ ((struct Lisp_Hash_Table *));
4116 static int cmpfn_eql P_ ((struct Lisp_Hash_Table *, Lisp_Object, unsigned,
4117 Lisp_Object, unsigned));
4118 static int cmpfn_equal P_ ((struct Lisp_Hash_Table *, Lisp_Object, unsigned,
4119 Lisp_Object, unsigned));
4120 static int cmpfn_user_defined P_ ((struct Lisp_Hash_Table *, Lisp_Object,
4121 unsigned, Lisp_Object, unsigned));
4122 static unsigned hashfn_eq P_ ((struct Lisp_Hash_Table *, Lisp_Object));
4123 static unsigned hashfn_eql P_ ((struct Lisp_Hash_Table *, Lisp_Object));
4124 static unsigned hashfn_equal P_ ((struct Lisp_Hash_Table *, Lisp_Object));
4125 static unsigned hashfn_user_defined P_ ((struct Lisp_Hash_Table *,
4126 Lisp_Object));
4127 static unsigned sxhash_string P_ ((unsigned char *, int));
4128 static unsigned sxhash_list P_ ((Lisp_Object, int));
4129 static unsigned sxhash_vector P_ ((Lisp_Object, int));
4130 static unsigned sxhash_bool_vector P_ ((Lisp_Object));
4131 static int sweep_weak_table P_ ((struct Lisp_Hash_Table *, int));
4135 /***********************************************************************
4136 Utilities
4137 ***********************************************************************/
4139 /* If OBJ is a Lisp hash table, return a pointer to its struct
4140 Lisp_Hash_Table. Otherwise, signal an error. */
4142 static struct Lisp_Hash_Table *
4143 check_hash_table (obj)
4144 Lisp_Object obj;
4146 CHECK_HASH_TABLE (obj);
4147 return XHASH_TABLE (obj);
4151 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
4152 number. */
4155 next_almost_prime (n)
4156 int n;
4158 if (n % 2 == 0)
4159 n += 1;
4160 if (n % 3 == 0)
4161 n += 2;
4162 if (n % 7 == 0)
4163 n += 4;
4164 return n;
4168 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
4169 which USED[I] is non-zero. If found at index I in ARGS, set
4170 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
4171 -1. This function is used to extract a keyword/argument pair from
4172 a DEFUN parameter list. */
4174 static int
4175 get_key_arg (key, nargs, args, used)
4176 Lisp_Object key;
4177 int nargs;
4178 Lisp_Object *args;
4179 char *used;
4181 int i;
4183 for (i = 0; i < nargs - 1; ++i)
4184 if (!used[i] && EQ (args[i], key))
4185 break;
4187 if (i >= nargs - 1)
4188 i = -1;
4189 else
4191 used[i++] = 1;
4192 used[i] = 1;
4195 return i;
4199 /* Return a Lisp vector which has the same contents as VEC but has
4200 size NEW_SIZE, NEW_SIZE >= VEC->size. Entries in the resulting
4201 vector that are not copied from VEC are set to INIT. */
4203 Lisp_Object
4204 larger_vector (vec, new_size, init)
4205 Lisp_Object vec;
4206 int new_size;
4207 Lisp_Object init;
4209 struct Lisp_Vector *v;
4210 int i, old_size;
4212 xassert (VECTORP (vec));
4213 old_size = XVECTOR (vec)->size;
4214 xassert (new_size >= old_size);
4216 v = allocate_vector (new_size);
4217 bcopy (XVECTOR (vec)->contents, v->contents,
4218 old_size * sizeof *v->contents);
4219 for (i = old_size; i < new_size; ++i)
4220 v->contents[i] = init;
4221 XSETVECTOR (vec, v);
4222 return vec;
4226 /***********************************************************************
4227 Low-level Functions
4228 ***********************************************************************/
4230 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
4231 HASH2 in hash table H using `eql'. Value is non-zero if KEY1 and
4232 KEY2 are the same. */
4234 static int
4235 cmpfn_eql (h, key1, hash1, key2, hash2)
4236 struct Lisp_Hash_Table *h;
4237 Lisp_Object key1, key2;
4238 unsigned hash1, hash2;
4240 return (FLOATP (key1)
4241 && FLOATP (key2)
4242 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
4246 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
4247 HASH2 in hash table H using `equal'. Value is non-zero if KEY1 and
4248 KEY2 are the same. */
4250 static int
4251 cmpfn_equal (h, key1, hash1, key2, hash2)
4252 struct Lisp_Hash_Table *h;
4253 Lisp_Object key1, key2;
4254 unsigned hash1, hash2;
4256 return hash1 == hash2 && !NILP (Fequal (key1, key2));
4260 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
4261 HASH2 in hash table H using H->user_cmp_function. Value is non-zero
4262 if KEY1 and KEY2 are the same. */
4264 static int
4265 cmpfn_user_defined (h, key1, hash1, key2, hash2)
4266 struct Lisp_Hash_Table *h;
4267 Lisp_Object key1, key2;
4268 unsigned hash1, hash2;
4270 if (hash1 == hash2)
4272 Lisp_Object args[3];
4274 args[0] = h->user_cmp_function;
4275 args[1] = key1;
4276 args[2] = key2;
4277 return !NILP (Ffuncall (3, args));
4279 else
4280 return 0;
4284 /* Value is a hash code for KEY for use in hash table H which uses
4285 `eq' to compare keys. The hash code returned is guaranteed to fit
4286 in a Lisp integer. */
4288 static unsigned
4289 hashfn_eq (h, key)
4290 struct Lisp_Hash_Table *h;
4291 Lisp_Object key;
4293 unsigned hash = XUINT (key) ^ XGCTYPE (key);
4294 xassert ((hash & ~INTMASK) == 0);
4295 return hash;
4299 /* Value is a hash code for KEY for use in hash table H which uses
4300 `eql' to compare keys. The hash code returned is guaranteed to fit
4301 in a Lisp integer. */
4303 static unsigned
4304 hashfn_eql (h, key)
4305 struct Lisp_Hash_Table *h;
4306 Lisp_Object key;
4308 unsigned hash;
4309 if (FLOATP (key))
4310 hash = sxhash (key, 0);
4311 else
4312 hash = XUINT (key) ^ XGCTYPE (key);
4313 xassert ((hash & ~INTMASK) == 0);
4314 return hash;
4318 /* Value is a hash code for KEY for use in hash table H which uses
4319 `equal' to compare keys. The hash code returned is guaranteed to fit
4320 in a Lisp integer. */
4322 static unsigned
4323 hashfn_equal (h, key)
4324 struct Lisp_Hash_Table *h;
4325 Lisp_Object key;
4327 unsigned hash = sxhash (key, 0);
4328 xassert ((hash & ~INTMASK) == 0);
4329 return hash;
4333 /* Value is a hash code for KEY for use in hash table H which uses as
4334 user-defined function to compare keys. The hash code returned is
4335 guaranteed to fit in a Lisp integer. */
4337 static unsigned
4338 hashfn_user_defined (h, key)
4339 struct Lisp_Hash_Table *h;
4340 Lisp_Object key;
4342 Lisp_Object args[2], hash;
4344 args[0] = h->user_hash_function;
4345 args[1] = key;
4346 hash = Ffuncall (2, args);
4347 if (!INTEGERP (hash))
4348 Fsignal (Qerror,
4349 list2 (build_string ("Invalid hash code returned from \
4350 user-supplied hash function"),
4351 hash));
4352 return XUINT (hash);
4356 /* Create and initialize a new hash table.
4358 TEST specifies the test the hash table will use to compare keys.
4359 It must be either one of the predefined tests `eq', `eql' or
4360 `equal' or a symbol denoting a user-defined test named TEST with
4361 test and hash functions USER_TEST and USER_HASH.
4363 Give the table initial capacity SIZE, SIZE >= 0, an integer.
4365 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
4366 new size when it becomes full is computed by adding REHASH_SIZE to
4367 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
4368 table's new size is computed by multiplying its old size with
4369 REHASH_SIZE.
4371 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
4372 be resized when the ratio of (number of entries in the table) /
4373 (table size) is >= REHASH_THRESHOLD.
4375 WEAK specifies the weakness of the table. If non-nil, it must be
4376 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
4378 Lisp_Object
4379 make_hash_table (test, size, rehash_size, rehash_threshold, weak,
4380 user_test, user_hash)
4381 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4382 Lisp_Object user_test, user_hash;
4384 struct Lisp_Hash_Table *h;
4385 Lisp_Object table;
4386 int index_size, i, sz;
4388 /* Preconditions. */
4389 xassert (SYMBOLP (test));
4390 xassert (INTEGERP (size) && XINT (size) >= 0);
4391 xassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
4392 || (FLOATP (rehash_size) && XFLOATINT (rehash_size) > 1.0));
4393 xassert (FLOATP (rehash_threshold)
4394 && XFLOATINT (rehash_threshold) > 0
4395 && XFLOATINT (rehash_threshold) <= 1.0);
4397 if (XFASTINT (size) == 0)
4398 size = make_number (1);
4400 /* Allocate a table and initialize it. */
4401 h = allocate_hash_table ();
4403 /* Initialize hash table slots. */
4404 sz = XFASTINT (size);
4406 h->test = test;
4407 if (EQ (test, Qeql))
4409 h->cmpfn = cmpfn_eql;
4410 h->hashfn = hashfn_eql;
4412 else if (EQ (test, Qeq))
4414 h->cmpfn = NULL;
4415 h->hashfn = hashfn_eq;
4417 else if (EQ (test, Qequal))
4419 h->cmpfn = cmpfn_equal;
4420 h->hashfn = hashfn_equal;
4422 else
4424 h->user_cmp_function = user_test;
4425 h->user_hash_function = user_hash;
4426 h->cmpfn = cmpfn_user_defined;
4427 h->hashfn = hashfn_user_defined;
4430 h->weak = weak;
4431 h->rehash_threshold = rehash_threshold;
4432 h->rehash_size = rehash_size;
4433 h->count = make_number (0);
4434 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
4435 h->hash = Fmake_vector (size, Qnil);
4436 h->next = Fmake_vector (size, Qnil);
4437 /* Cast to int here avoids losing with gcc 2.95 on Tru64/Alpha... */
4438 index_size = next_almost_prime ((int) (sz / XFLOATINT (rehash_threshold)));
4439 h->index = Fmake_vector (make_number (index_size), Qnil);
4441 /* Set up the free list. */
4442 for (i = 0; i < sz - 1; ++i)
4443 HASH_NEXT (h, i) = make_number (i + 1);
4444 h->next_free = make_number (0);
4446 XSET_HASH_TABLE (table, h);
4447 xassert (HASH_TABLE_P (table));
4448 xassert (XHASH_TABLE (table) == h);
4450 /* Maybe add this hash table to the list of all weak hash tables. */
4451 if (NILP (h->weak))
4452 h->next_weak = Qnil;
4453 else
4455 h->next_weak = Vweak_hash_tables;
4456 Vweak_hash_tables = table;
4459 return table;
4463 /* Return a copy of hash table H1. Keys and values are not copied,
4464 only the table itself is. */
4466 Lisp_Object
4467 copy_hash_table (h1)
4468 struct Lisp_Hash_Table *h1;
4470 Lisp_Object table;
4471 struct Lisp_Hash_Table *h2;
4472 struct Lisp_Vector *next;
4474 h2 = allocate_hash_table ();
4475 next = h2->vec_next;
4476 bcopy (h1, h2, sizeof *h2);
4477 h2->vec_next = next;
4478 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
4479 h2->hash = Fcopy_sequence (h1->hash);
4480 h2->next = Fcopy_sequence (h1->next);
4481 h2->index = Fcopy_sequence (h1->index);
4482 XSET_HASH_TABLE (table, h2);
4484 /* Maybe add this hash table to the list of all weak hash tables. */
4485 if (!NILP (h2->weak))
4487 h2->next_weak = Vweak_hash_tables;
4488 Vweak_hash_tables = table;
4491 return table;
4495 /* Resize hash table H if it's too full. If H cannot be resized
4496 because it's already too large, throw an error. */
4498 static INLINE void
4499 maybe_resize_hash_table (h)
4500 struct Lisp_Hash_Table *h;
4502 if (NILP (h->next_free))
4504 int old_size = HASH_TABLE_SIZE (h);
4505 int i, new_size, index_size;
4507 if (INTEGERP (h->rehash_size))
4508 new_size = old_size + XFASTINT (h->rehash_size);
4509 else
4510 new_size = old_size * XFLOATINT (h->rehash_size);
4511 new_size = max (old_size + 1, new_size);
4512 index_size = next_almost_prime ((int)
4513 (new_size
4514 / XFLOATINT (h->rehash_threshold)));
4515 if (max (index_size, 2 * new_size) > MOST_POSITIVE_FIXNUM)
4516 error ("Hash table too large to resize");
4518 h->key_and_value = larger_vector (h->key_and_value, 2 * new_size, Qnil);
4519 h->next = larger_vector (h->next, new_size, Qnil);
4520 h->hash = larger_vector (h->hash, new_size, Qnil);
4521 h->index = Fmake_vector (make_number (index_size), Qnil);
4523 /* Update the free list. Do it so that new entries are added at
4524 the end of the free list. This makes some operations like
4525 maphash faster. */
4526 for (i = old_size; i < new_size - 1; ++i)
4527 HASH_NEXT (h, i) = make_number (i + 1);
4529 if (!NILP (h->next_free))
4531 Lisp_Object last, next;
4533 last = h->next_free;
4534 while (next = HASH_NEXT (h, XFASTINT (last)),
4535 !NILP (next))
4536 last = next;
4538 HASH_NEXT (h, XFASTINT (last)) = make_number (old_size);
4540 else
4541 XSETFASTINT (h->next_free, old_size);
4543 /* Rehash. */
4544 for (i = 0; i < old_size; ++i)
4545 if (!NILP (HASH_HASH (h, i)))
4547 unsigned hash_code = XUINT (HASH_HASH (h, i));
4548 int start_of_bucket = hash_code % XVECTOR (h->index)->size;
4549 HASH_NEXT (h, i) = HASH_INDEX (h, start_of_bucket);
4550 HASH_INDEX (h, start_of_bucket) = make_number (i);
4556 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
4557 the hash code of KEY. Value is the index of the entry in H
4558 matching KEY, or -1 if not found. */
4561 hash_lookup (h, key, hash)
4562 struct Lisp_Hash_Table *h;
4563 Lisp_Object key;
4564 unsigned *hash;
4566 unsigned hash_code;
4567 int start_of_bucket;
4568 Lisp_Object idx;
4570 hash_code = h->hashfn (h, key);
4571 if (hash)
4572 *hash = hash_code;
4574 start_of_bucket = hash_code % XVECTOR (h->index)->size;
4575 idx = HASH_INDEX (h, start_of_bucket);
4577 /* We need not gcpro idx since it's either an integer or nil. */
4578 while (!NILP (idx))
4580 int i = XFASTINT (idx);
4581 if (EQ (key, HASH_KEY (h, i))
4582 || (h->cmpfn
4583 && h->cmpfn (h, key, hash_code,
4584 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
4585 break;
4586 idx = HASH_NEXT (h, i);
4589 return NILP (idx) ? -1 : XFASTINT (idx);
4593 /* Put an entry into hash table H that associates KEY with VALUE.
4594 HASH is a previously computed hash code of KEY.
4595 Value is the index of the entry in H matching KEY. */
4598 hash_put (h, key, value, hash)
4599 struct Lisp_Hash_Table *h;
4600 Lisp_Object key, value;
4601 unsigned hash;
4603 int start_of_bucket, i;
4605 xassert ((hash & ~INTMASK) == 0);
4607 /* Increment count after resizing because resizing may fail. */
4608 maybe_resize_hash_table (h);
4609 h->count = make_number (XFASTINT (h->count) + 1);
4611 /* Store key/value in the key_and_value vector. */
4612 i = XFASTINT (h->next_free);
4613 h->next_free = HASH_NEXT (h, i);
4614 HASH_KEY (h, i) = key;
4615 HASH_VALUE (h, i) = value;
4617 /* Remember its hash code. */
4618 HASH_HASH (h, i) = make_number (hash);
4620 /* Add new entry to its collision chain. */
4621 start_of_bucket = hash % XVECTOR (h->index)->size;
4622 HASH_NEXT (h, i) = HASH_INDEX (h, start_of_bucket);
4623 HASH_INDEX (h, start_of_bucket) = make_number (i);
4624 return i;
4628 /* Remove the entry matching KEY from hash table H, if there is one. */
4630 void
4631 hash_remove (h, key)
4632 struct Lisp_Hash_Table *h;
4633 Lisp_Object key;
4635 unsigned hash_code;
4636 int start_of_bucket;
4637 Lisp_Object idx, prev;
4639 hash_code = h->hashfn (h, key);
4640 start_of_bucket = hash_code % XVECTOR (h->index)->size;
4641 idx = HASH_INDEX (h, start_of_bucket);
4642 prev = Qnil;
4644 /* We need not gcpro idx, prev since they're either integers or nil. */
4645 while (!NILP (idx))
4647 int i = XFASTINT (idx);
4649 if (EQ (key, HASH_KEY (h, i))
4650 || (h->cmpfn
4651 && h->cmpfn (h, key, hash_code,
4652 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
4654 /* Take entry out of collision chain. */
4655 if (NILP (prev))
4656 HASH_INDEX (h, start_of_bucket) = HASH_NEXT (h, i);
4657 else
4658 HASH_NEXT (h, XFASTINT (prev)) = HASH_NEXT (h, i);
4660 /* Clear slots in key_and_value and add the slots to
4661 the free list. */
4662 HASH_KEY (h, i) = HASH_VALUE (h, i) = HASH_HASH (h, i) = Qnil;
4663 HASH_NEXT (h, i) = h->next_free;
4664 h->next_free = make_number (i);
4665 h->count = make_number (XFASTINT (h->count) - 1);
4666 xassert (XINT (h->count) >= 0);
4667 break;
4669 else
4671 prev = idx;
4672 idx = HASH_NEXT (h, i);
4678 /* Clear hash table H. */
4680 void
4681 hash_clear (h)
4682 struct Lisp_Hash_Table *h;
4684 if (XFASTINT (h->count) > 0)
4686 int i, size = HASH_TABLE_SIZE (h);
4688 for (i = 0; i < size; ++i)
4690 HASH_NEXT (h, i) = i < size - 1 ? make_number (i + 1) : Qnil;
4691 HASH_KEY (h, i) = Qnil;
4692 HASH_VALUE (h, i) = Qnil;
4693 HASH_HASH (h, i) = Qnil;
4696 for (i = 0; i < XVECTOR (h->index)->size; ++i)
4697 XVECTOR (h->index)->contents[i] = Qnil;
4699 h->next_free = make_number (0);
4700 h->count = make_number (0);
4706 /************************************************************************
4707 Weak Hash Tables
4708 ************************************************************************/
4710 /* Sweep weak hash table H. REMOVE_ENTRIES_P non-zero means remove
4711 entries from the table that don't survive the current GC.
4712 REMOVE_ENTRIES_P zero means mark entries that are in use. Value is
4713 non-zero if anything was marked. */
4715 static int
4716 sweep_weak_table (h, remove_entries_p)
4717 struct Lisp_Hash_Table *h;
4718 int remove_entries_p;
4720 int bucket, n, marked;
4722 n = XVECTOR (h->index)->size & ~ARRAY_MARK_FLAG;
4723 marked = 0;
4725 for (bucket = 0; bucket < n; ++bucket)
4727 Lisp_Object idx, next, prev;
4729 /* Follow collision chain, removing entries that
4730 don't survive this garbage collection. */
4731 prev = Qnil;
4732 for (idx = HASH_INDEX (h, bucket); !GC_NILP (idx); idx = next)
4734 int i = XFASTINT (idx);
4735 int key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
4736 int value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
4737 int remove_p;
4739 if (EQ (h->weak, Qkey))
4740 remove_p = !key_known_to_survive_p;
4741 else if (EQ (h->weak, Qvalue))
4742 remove_p = !value_known_to_survive_p;
4743 else if (EQ (h->weak, Qkey_or_value))
4744 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
4745 else if (EQ (h->weak, Qkey_and_value))
4746 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
4747 else
4748 abort ();
4750 next = HASH_NEXT (h, i);
4752 if (remove_entries_p)
4754 if (remove_p)
4756 /* Take out of collision chain. */
4757 if (GC_NILP (prev))
4758 HASH_INDEX (h, bucket) = next;
4759 else
4760 HASH_NEXT (h, XFASTINT (prev)) = next;
4762 /* Add to free list. */
4763 HASH_NEXT (h, i) = h->next_free;
4764 h->next_free = idx;
4766 /* Clear key, value, and hash. */
4767 HASH_KEY (h, i) = HASH_VALUE (h, i) = Qnil;
4768 HASH_HASH (h, i) = Qnil;
4770 h->count = make_number (XFASTINT (h->count) - 1);
4773 else
4775 if (!remove_p)
4777 /* Make sure key and value survive. */
4778 if (!key_known_to_survive_p)
4780 mark_object (HASH_KEY (h, i));
4781 marked = 1;
4784 if (!value_known_to_survive_p)
4786 mark_object (HASH_VALUE (h, i));
4787 marked = 1;
4794 return marked;
4797 /* Remove elements from weak hash tables that don't survive the
4798 current garbage collection. Remove weak tables that don't survive
4799 from Vweak_hash_tables. Called from gc_sweep. */
4801 void
4802 sweep_weak_hash_tables ()
4804 Lisp_Object table, used, next;
4805 struct Lisp_Hash_Table *h;
4806 int marked;
4808 /* Mark all keys and values that are in use. Keep on marking until
4809 there is no more change. This is necessary for cases like
4810 value-weak table A containing an entry X -> Y, where Y is used in a
4811 key-weak table B, Z -> Y. If B comes after A in the list of weak
4812 tables, X -> Y might be removed from A, although when looking at B
4813 one finds that it shouldn't. */
4816 marked = 0;
4817 for (table = Vweak_hash_tables; !GC_NILP (table); table = h->next_weak)
4819 h = XHASH_TABLE (table);
4820 if (h->size & ARRAY_MARK_FLAG)
4821 marked |= sweep_weak_table (h, 0);
4824 while (marked);
4826 /* Remove tables and entries that aren't used. */
4827 for (table = Vweak_hash_tables, used = Qnil; !GC_NILP (table); table = next)
4829 h = XHASH_TABLE (table);
4830 next = h->next_weak;
4832 if (h->size & ARRAY_MARK_FLAG)
4834 /* TABLE is marked as used. Sweep its contents. */
4835 if (XFASTINT (h->count) > 0)
4836 sweep_weak_table (h, 1);
4838 /* Add table to the list of used weak hash tables. */
4839 h->next_weak = used;
4840 used = table;
4844 Vweak_hash_tables = used;
4849 /***********************************************************************
4850 Hash Code Computation
4851 ***********************************************************************/
4853 /* Maximum depth up to which to dive into Lisp structures. */
4855 #define SXHASH_MAX_DEPTH 3
4857 /* Maximum length up to which to take list and vector elements into
4858 account. */
4860 #define SXHASH_MAX_LEN 7
4862 /* Combine two integers X and Y for hashing. */
4864 #define SXHASH_COMBINE(X, Y) \
4865 ((((unsigned)(X) << 4) + (((unsigned)(X) >> 24) & 0x0fffffff)) \
4866 + (unsigned)(Y))
4869 /* Return a hash for string PTR which has length LEN. The hash
4870 code returned is guaranteed to fit in a Lisp integer. */
4872 static unsigned
4873 sxhash_string (ptr, len)
4874 unsigned char *ptr;
4875 int len;
4877 unsigned char *p = ptr;
4878 unsigned char *end = p + len;
4879 unsigned char c;
4880 unsigned hash = 0;
4882 while (p != end)
4884 c = *p++;
4885 if (c >= 0140)
4886 c -= 40;
4887 hash = ((hash << 3) + (hash >> 28) + c);
4890 return hash & INTMASK;
4894 /* Return a hash for list LIST. DEPTH is the current depth in the
4895 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4897 static unsigned
4898 sxhash_list (list, depth)
4899 Lisp_Object list;
4900 int depth;
4902 unsigned hash = 0;
4903 int i;
4905 if (depth < SXHASH_MAX_DEPTH)
4906 for (i = 0;
4907 CONSP (list) && i < SXHASH_MAX_LEN;
4908 list = XCDR (list), ++i)
4910 unsigned hash2 = sxhash (XCAR (list), depth + 1);
4911 hash = SXHASH_COMBINE (hash, hash2);
4914 return hash;
4918 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4919 the Lisp structure. */
4921 static unsigned
4922 sxhash_vector (vec, depth)
4923 Lisp_Object vec;
4924 int depth;
4926 unsigned hash = XVECTOR (vec)->size;
4927 int i, n;
4929 n = min (SXHASH_MAX_LEN, XVECTOR (vec)->size);
4930 for (i = 0; i < n; ++i)
4932 unsigned hash2 = sxhash (XVECTOR (vec)->contents[i], depth + 1);
4933 hash = SXHASH_COMBINE (hash, hash2);
4936 return hash;
4940 /* Return a hash for bool-vector VECTOR. */
4942 static unsigned
4943 sxhash_bool_vector (vec)
4944 Lisp_Object vec;
4946 unsigned hash = XBOOL_VECTOR (vec)->size;
4947 int i, n;
4949 n = min (SXHASH_MAX_LEN, XBOOL_VECTOR (vec)->vector_size);
4950 for (i = 0; i < n; ++i)
4951 hash = SXHASH_COMBINE (hash, XBOOL_VECTOR (vec)->data[i]);
4953 return hash;
4957 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4958 structure. Value is an unsigned integer clipped to INTMASK. */
4960 unsigned
4961 sxhash (obj, depth)
4962 Lisp_Object obj;
4963 int depth;
4965 unsigned hash;
4967 if (depth > SXHASH_MAX_DEPTH)
4968 return 0;
4970 switch (XTYPE (obj))
4972 case Lisp_Int:
4973 hash = XUINT (obj);
4974 break;
4976 case Lisp_Symbol:
4977 hash = sxhash_string (SDATA (SYMBOL_NAME (obj)),
4978 SCHARS (SYMBOL_NAME (obj)));
4979 break;
4981 case Lisp_Misc:
4982 hash = XUINT (obj);
4983 break;
4985 case Lisp_String:
4986 hash = sxhash_string (SDATA (obj), SCHARS (obj));
4987 break;
4989 /* This can be everything from a vector to an overlay. */
4990 case Lisp_Vectorlike:
4991 if (VECTORP (obj))
4992 /* According to the CL HyperSpec, two arrays are equal only if
4993 they are `eq', except for strings and bit-vectors. In
4994 Emacs, this works differently. We have to compare element
4995 by element. */
4996 hash = sxhash_vector (obj, depth);
4997 else if (BOOL_VECTOR_P (obj))
4998 hash = sxhash_bool_vector (obj);
4999 else
5000 /* Others are `equal' if they are `eq', so let's take their
5001 address as hash. */
5002 hash = XUINT (obj);
5003 break;
5005 case Lisp_Cons:
5006 hash = sxhash_list (obj, depth);
5007 break;
5009 case Lisp_Float:
5011 unsigned char *p = (unsigned char *) &XFLOAT_DATA (obj);
5012 unsigned char *e = p + sizeof XFLOAT_DATA (obj);
5013 for (hash = 0; p < e; ++p)
5014 hash = SXHASH_COMBINE (hash, *p);
5015 break;
5018 default:
5019 abort ();
5022 return hash & INTMASK;
5027 /***********************************************************************
5028 Lisp Interface
5029 ***********************************************************************/
5032 DEFUN ("sxhash", Fsxhash, Ssxhash, 1, 1, 0,
5033 doc: /* Compute a hash code for OBJ and return it as integer. */)
5034 (obj)
5035 Lisp_Object obj;
5037 unsigned hash = sxhash (obj, 0);;
5038 return make_number (hash);
5042 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
5043 doc: /* Create and return a new hash table.
5045 Arguments are specified as keyword/argument pairs. The following
5046 arguments are defined:
5048 :test TEST -- TEST must be a symbol that specifies how to compare
5049 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
5050 `equal'. User-supplied test and hash functions can be specified via
5051 `define-hash-table-test'.
5053 :size SIZE -- A hint as to how many elements will be put in the table.
5054 Default is 65.
5056 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
5057 fills up. If REHASH-SIZE is an integer, add that many space. If it
5058 is a float, it must be > 1.0, and the new size is computed by
5059 multiplying the old size with that factor. Default is 1.5.
5061 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
5062 Resize the hash table when ratio of the number of entries in the
5063 table. Default is 0.8.
5065 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
5066 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
5067 returned is a weak table. Key/value pairs are removed from a weak
5068 hash table when there are no non-weak references pointing to their
5069 key, value, one of key or value, or both key and value, depending on
5070 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
5071 is nil.
5073 usage: (make-hash-table &rest KEYWORD-ARGS) */)
5074 (nargs, args)
5075 int nargs;
5076 Lisp_Object *args;
5078 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
5079 Lisp_Object user_test, user_hash;
5080 char *used;
5081 int i;
5083 /* The vector `used' is used to keep track of arguments that
5084 have been consumed. */
5085 used = (char *) alloca (nargs * sizeof *used);
5086 bzero (used, nargs * sizeof *used);
5088 /* See if there's a `:test TEST' among the arguments. */
5089 i = get_key_arg (QCtest, nargs, args, used);
5090 test = i < 0 ? Qeql : args[i];
5091 if (!EQ (test, Qeq) && !EQ (test, Qeql) && !EQ (test, Qequal))
5093 /* See if it is a user-defined test. */
5094 Lisp_Object prop;
5096 prop = Fget (test, Qhash_table_test);
5097 if (!CONSP (prop) || !CONSP (XCDR (prop)))
5098 Fsignal (Qerror, list2 (build_string ("Invalid hash table test"),
5099 test));
5100 user_test = XCAR (prop);
5101 user_hash = XCAR (XCDR (prop));
5103 else
5104 user_test = user_hash = Qnil;
5106 /* See if there's a `:size SIZE' argument. */
5107 i = get_key_arg (QCsize, nargs, args, used);
5108 size = i < 0 ? Qnil : args[i];
5109 if (NILP (size))
5110 size = make_number (DEFAULT_HASH_SIZE);
5111 else if (!INTEGERP (size) || XINT (size) < 0)
5112 Fsignal (Qerror,
5113 list2 (build_string ("Invalid hash table size"),
5114 size));
5116 /* Look for `:rehash-size SIZE'. */
5117 i = get_key_arg (QCrehash_size, nargs, args, used);
5118 rehash_size = i < 0 ? make_float (DEFAULT_REHASH_SIZE) : args[i];
5119 if (!NUMBERP (rehash_size)
5120 || (INTEGERP (rehash_size) && XINT (rehash_size) <= 0)
5121 || XFLOATINT (rehash_size) <= 1.0)
5122 Fsignal (Qerror,
5123 list2 (build_string ("Invalid hash table rehash size"),
5124 rehash_size));
5126 /* Look for `:rehash-threshold THRESHOLD'. */
5127 i = get_key_arg (QCrehash_threshold, nargs, args, used);
5128 rehash_threshold = i < 0 ? make_float (DEFAULT_REHASH_THRESHOLD) : args[i];
5129 if (!FLOATP (rehash_threshold)
5130 || XFLOATINT (rehash_threshold) <= 0.0
5131 || XFLOATINT (rehash_threshold) > 1.0)
5132 Fsignal (Qerror,
5133 list2 (build_string ("Invalid hash table rehash threshold"),
5134 rehash_threshold));
5136 /* Look for `:weakness WEAK'. */
5137 i = get_key_arg (QCweakness, nargs, args, used);
5138 weak = i < 0 ? Qnil : args[i];
5139 if (EQ (weak, Qt))
5140 weak = Qkey_and_value;
5141 if (!NILP (weak)
5142 && !EQ (weak, Qkey)
5143 && !EQ (weak, Qvalue)
5144 && !EQ (weak, Qkey_or_value)
5145 && !EQ (weak, Qkey_and_value))
5146 Fsignal (Qerror, list2 (build_string ("Invalid hash table weakness"),
5147 weak));
5149 /* Now, all args should have been used up, or there's a problem. */
5150 for (i = 0; i < nargs; ++i)
5151 if (!used[i])
5152 Fsignal (Qerror,
5153 list2 (build_string ("Invalid argument list"), args[i]));
5155 return make_hash_table (test, size, rehash_size, rehash_threshold, weak,
5156 user_test, user_hash);
5160 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
5161 doc: /* Return a copy of hash table TABLE. */)
5162 (table)
5163 Lisp_Object table;
5165 return copy_hash_table (check_hash_table (table));
5169 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
5170 doc: /* Return the number of elements in TABLE. */)
5171 (table)
5172 Lisp_Object table;
5174 return check_hash_table (table)->count;
5178 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
5179 Shash_table_rehash_size, 1, 1, 0,
5180 doc: /* Return the current rehash size of TABLE. */)
5181 (table)
5182 Lisp_Object table;
5184 return check_hash_table (table)->rehash_size;
5188 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
5189 Shash_table_rehash_threshold, 1, 1, 0,
5190 doc: /* Return the current rehash threshold of TABLE. */)
5191 (table)
5192 Lisp_Object table;
5194 return check_hash_table (table)->rehash_threshold;
5198 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
5199 doc: /* Return the size of TABLE.
5200 The size can be used as an argument to `make-hash-table' to create
5201 a hash table than can hold as many elements of TABLE holds
5202 without need for resizing. */)
5203 (table)
5204 Lisp_Object table;
5206 struct Lisp_Hash_Table *h = check_hash_table (table);
5207 return make_number (HASH_TABLE_SIZE (h));
5211 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
5212 doc: /* Return the test TABLE uses. */)
5213 (table)
5214 Lisp_Object table;
5216 return check_hash_table (table)->test;
5220 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
5221 1, 1, 0,
5222 doc: /* Return the weakness of TABLE. */)
5223 (table)
5224 Lisp_Object table;
5226 return check_hash_table (table)->weak;
5230 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
5231 doc: /* Return t if OBJ is a Lisp hash table object. */)
5232 (obj)
5233 Lisp_Object obj;
5235 return HASH_TABLE_P (obj) ? Qt : Qnil;
5239 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
5240 doc: /* Clear hash table TABLE. */)
5241 (table)
5242 Lisp_Object table;
5244 hash_clear (check_hash_table (table));
5245 return Qnil;
5249 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
5250 doc: /* Look up KEY in TABLE and return its associated value.
5251 If KEY is not found, return DFLT which defaults to nil. */)
5252 (key, table, dflt)
5253 Lisp_Object key, table, dflt;
5255 struct Lisp_Hash_Table *h = check_hash_table (table);
5256 int i = hash_lookup (h, key, NULL);
5257 return i >= 0 ? HASH_VALUE (h, i) : dflt;
5261 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
5262 doc: /* Associate KEY with VALUE in hash table TABLE.
5263 If KEY is already present in table, replace its current value with
5264 VALUE. */)
5265 (key, value, table)
5266 Lisp_Object key, value, table;
5268 struct Lisp_Hash_Table *h = check_hash_table (table);
5269 int i;
5270 unsigned hash;
5272 i = hash_lookup (h, key, &hash);
5273 if (i >= 0)
5274 HASH_VALUE (h, i) = value;
5275 else
5276 hash_put (h, key, value, hash);
5278 return value;
5282 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
5283 doc: /* Remove KEY from TABLE. */)
5284 (key, table)
5285 Lisp_Object key, table;
5287 struct Lisp_Hash_Table *h = check_hash_table (table);
5288 hash_remove (h, key);
5289 return Qnil;
5293 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
5294 doc: /* Call FUNCTION for all entries in hash table TABLE.
5295 FUNCTION is called with 2 arguments KEY and VALUE. */)
5296 (function, table)
5297 Lisp_Object function, table;
5299 struct Lisp_Hash_Table *h = check_hash_table (table);
5300 Lisp_Object args[3];
5301 int i;
5303 for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
5304 if (!NILP (HASH_HASH (h, i)))
5306 args[0] = function;
5307 args[1] = HASH_KEY (h, i);
5308 args[2] = HASH_VALUE (h, i);
5309 Ffuncall (3, args);
5312 return Qnil;
5316 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
5317 Sdefine_hash_table_test, 3, 3, 0,
5318 doc: /* Define a new hash table test with name NAME, a symbol.
5320 In hash tables created with NAME specified as test, use TEST to
5321 compare keys, and HASH for computing hash codes of keys.
5323 TEST must be a function taking two arguments and returning non-nil if
5324 both arguments are the same. HASH must be a function taking one
5325 argument and return an integer that is the hash code of the argument.
5326 Hash code computation should use the whole value range of integers,
5327 including negative integers. */)
5328 (name, test, hash)
5329 Lisp_Object name, test, hash;
5331 return Fput (name, Qhash_table_test, list2 (test, hash));
5336 /************************************************************************
5338 ************************************************************************/
5340 #include "md5.h"
5341 #include "coding.h"
5343 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
5344 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
5346 A message digest is a cryptographic checksum of a document, and the
5347 algorithm to calculate it is defined in RFC 1321.
5349 The two optional arguments START and END are character positions
5350 specifying for which part of OBJECT the message digest should be
5351 computed. If nil or omitted, the digest is computed for the whole
5352 OBJECT.
5354 The MD5 message digest is computed from the result of encoding the
5355 text in a coding system, not directly from the internal Emacs form of
5356 the text. The optional fourth argument CODING-SYSTEM specifies which
5357 coding system to encode the text with. It should be the same coding
5358 system that you used or will use when actually writing the text into a
5359 file.
5361 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
5362 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
5363 system would be chosen by default for writing this text into a file.
5365 If OBJECT is a string, the most preferred coding system (see the
5366 command `prefer-coding-system') is used.
5368 If NOERROR is non-nil, silently assume the `raw-text' coding if the
5369 guesswork fails. Normally, an error is signaled in such case. */)
5370 (object, start, end, coding_system, noerror)
5371 Lisp_Object object, start, end, coding_system, noerror;
5373 unsigned char digest[16];
5374 unsigned char value[33];
5375 int i;
5376 int size;
5377 int size_byte = 0;
5378 int start_char = 0, end_char = 0;
5379 int start_byte = 0, end_byte = 0;
5380 register int b, e;
5381 register struct buffer *bp;
5382 int temp;
5384 if (STRINGP (object))
5386 if (NILP (coding_system))
5388 /* Decide the coding-system to encode the data with. */
5390 if (STRING_MULTIBYTE (object))
5391 /* use default, we can't guess correct value */
5392 coding_system = SYMBOL_VALUE (XCAR (Vcoding_category_list));
5393 else
5394 coding_system = Qraw_text;
5397 if (NILP (Fcoding_system_p (coding_system)))
5399 /* Invalid coding system. */
5401 if (!NILP (noerror))
5402 coding_system = Qraw_text;
5403 else
5404 while (1)
5405 Fsignal (Qcoding_system_error, Fcons (coding_system, Qnil));
5408 if (STRING_MULTIBYTE (object))
5409 object = code_convert_string1 (object, coding_system, Qnil, 1);
5411 size = SCHARS (object);
5412 size_byte = SBYTES (object);
5414 if (!NILP (start))
5416 CHECK_NUMBER (start);
5418 start_char = XINT (start);
5420 if (start_char < 0)
5421 start_char += size;
5423 start_byte = string_char_to_byte (object, start_char);
5426 if (NILP (end))
5428 end_char = size;
5429 end_byte = size_byte;
5431 else
5433 CHECK_NUMBER (end);
5435 end_char = XINT (end);
5437 if (end_char < 0)
5438 end_char += size;
5440 end_byte = string_char_to_byte (object, end_char);
5443 if (!(0 <= start_char && start_char <= end_char && end_char <= size))
5444 args_out_of_range_3 (object, make_number (start_char),
5445 make_number (end_char));
5447 else
5449 CHECK_BUFFER (object);
5451 bp = XBUFFER (object);
5453 if (NILP (start))
5454 b = BUF_BEGV (bp);
5455 else
5457 CHECK_NUMBER_COERCE_MARKER (start);
5458 b = XINT (start);
5461 if (NILP (end))
5462 e = BUF_ZV (bp);
5463 else
5465 CHECK_NUMBER_COERCE_MARKER (end);
5466 e = XINT (end);
5469 if (b > e)
5470 temp = b, b = e, e = temp;
5472 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
5473 args_out_of_range (start, end);
5475 if (NILP (coding_system))
5477 /* Decide the coding-system to encode the data with.
5478 See fileio.c:Fwrite-region */
5480 if (!NILP (Vcoding_system_for_write))
5481 coding_system = Vcoding_system_for_write;
5482 else
5484 int force_raw_text = 0;
5486 coding_system = XBUFFER (object)->buffer_file_coding_system;
5487 if (NILP (coding_system)
5488 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
5490 coding_system = Qnil;
5491 if (NILP (current_buffer->enable_multibyte_characters))
5492 force_raw_text = 1;
5495 if (NILP (coding_system) && !NILP (Fbuffer_file_name(object)))
5497 /* Check file-coding-system-alist. */
5498 Lisp_Object args[4], val;
5500 args[0] = Qwrite_region; args[1] = start; args[2] = end;
5501 args[3] = Fbuffer_file_name(object);
5502 val = Ffind_operation_coding_system (4, args);
5503 if (CONSP (val) && !NILP (XCDR (val)))
5504 coding_system = XCDR (val);
5507 if (NILP (coding_system)
5508 && !NILP (XBUFFER (object)->buffer_file_coding_system))
5510 /* If we still have not decided a coding system, use the
5511 default value of buffer-file-coding-system. */
5512 coding_system = XBUFFER (object)->buffer_file_coding_system;
5515 if (!force_raw_text
5516 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
5517 /* Confirm that VAL can surely encode the current region. */
5518 coding_system = call4 (Vselect_safe_coding_system_function,
5519 make_number (b), make_number (e),
5520 coding_system, Qnil);
5522 if (force_raw_text)
5523 coding_system = Qraw_text;
5526 if (NILP (Fcoding_system_p (coding_system)))
5528 /* Invalid coding system. */
5530 if (!NILP (noerror))
5531 coding_system = Qraw_text;
5532 else
5533 while (1)
5534 Fsignal (Qcoding_system_error, Fcons (coding_system, Qnil));
5538 object = make_buffer_string (b, e, 0);
5540 if (STRING_MULTIBYTE (object))
5541 object = code_convert_string1 (object, coding_system, Qnil, 1);
5544 md5_buffer (SDATA (object) + start_byte,
5545 SBYTES (object) - (size_byte - end_byte),
5546 digest);
5548 for (i = 0; i < 16; i++)
5549 sprintf (&value[2 * i], "%02x", digest[i]);
5550 value[32] = '\0';
5552 return make_string (value, 32);
5556 void
5557 syms_of_fns ()
5559 /* Hash table stuff. */
5560 Qhash_table_p = intern ("hash-table-p");
5561 staticpro (&Qhash_table_p);
5562 Qeq = intern ("eq");
5563 staticpro (&Qeq);
5564 Qeql = intern ("eql");
5565 staticpro (&Qeql);
5566 Qequal = intern ("equal");
5567 staticpro (&Qequal);
5568 QCtest = intern (":test");
5569 staticpro (&QCtest);
5570 QCsize = intern (":size");
5571 staticpro (&QCsize);
5572 QCrehash_size = intern (":rehash-size");
5573 staticpro (&QCrehash_size);
5574 QCrehash_threshold = intern (":rehash-threshold");
5575 staticpro (&QCrehash_threshold);
5576 QCweakness = intern (":weakness");
5577 staticpro (&QCweakness);
5578 Qkey = intern ("key");
5579 staticpro (&Qkey);
5580 Qvalue = intern ("value");
5581 staticpro (&Qvalue);
5582 Qhash_table_test = intern ("hash-table-test");
5583 staticpro (&Qhash_table_test);
5584 Qkey_or_value = intern ("key-or-value");
5585 staticpro (&Qkey_or_value);
5586 Qkey_and_value = intern ("key-and-value");
5587 staticpro (&Qkey_and_value);
5589 defsubr (&Ssxhash);
5590 defsubr (&Smake_hash_table);
5591 defsubr (&Scopy_hash_table);
5592 defsubr (&Shash_table_count);
5593 defsubr (&Shash_table_rehash_size);
5594 defsubr (&Shash_table_rehash_threshold);
5595 defsubr (&Shash_table_size);
5596 defsubr (&Shash_table_test);
5597 defsubr (&Shash_table_weakness);
5598 defsubr (&Shash_table_p);
5599 defsubr (&Sclrhash);
5600 defsubr (&Sgethash);
5601 defsubr (&Sputhash);
5602 defsubr (&Sremhash);
5603 defsubr (&Smaphash);
5604 defsubr (&Sdefine_hash_table_test);
5606 Qstring_lessp = intern ("string-lessp");
5607 staticpro (&Qstring_lessp);
5608 Qprovide = intern ("provide");
5609 staticpro (&Qprovide);
5610 Qrequire = intern ("require");
5611 staticpro (&Qrequire);
5612 Qyes_or_no_p_history = intern ("yes-or-no-p-history");
5613 staticpro (&Qyes_or_no_p_history);
5614 Qcursor_in_echo_area = intern ("cursor-in-echo-area");
5615 staticpro (&Qcursor_in_echo_area);
5616 Qwidget_type = intern ("widget-type");
5617 staticpro (&Qwidget_type);
5619 staticpro (&string_char_byte_cache_string);
5620 string_char_byte_cache_string = Qnil;
5622 require_nesting_list = Qnil;
5623 staticpro (&require_nesting_list);
5625 Fset (Qyes_or_no_p_history, Qnil);
5627 DEFVAR_LISP ("features", &Vfeatures,
5628 doc: /* A list of symbols which are the features of the executing emacs.
5629 Used by `featurep' and `require', and altered by `provide'. */);
5630 Vfeatures = Qnil;
5631 Qsubfeatures = intern ("subfeatures");
5632 staticpro (&Qsubfeatures);
5634 #ifdef HAVE_LANGINFO_CODESET
5635 Qcodeset = intern ("codeset");
5636 staticpro (&Qcodeset);
5637 Qdays = intern ("days");
5638 staticpro (&Qdays);
5639 Qmonths = intern ("months");
5640 staticpro (&Qmonths);
5641 Qpaper = intern ("paper");
5642 staticpro (&Qpaper);
5643 #endif /* HAVE_LANGINFO_CODESET */
5645 DEFVAR_BOOL ("use-dialog-box", &use_dialog_box,
5646 doc: /* *Non-nil means mouse commands use dialog boxes to ask questions.
5647 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
5648 invoked by mouse clicks and mouse menu items. */);
5649 use_dialog_box = 1;
5651 DEFVAR_BOOL ("use-file-dialog", &use_file_dialog,
5652 doc: /* *Non-nil means mouse commands use a file dialog to ask for files.
5653 This applies to commands from menus and tool bar buttons. The value of
5654 `use-dialog-box' takes precedence over this variable, so a file dialog is only
5655 used if both `use-dialog-box' and this variable are non-nil. */);
5656 use_file_dialog = 1;
5658 defsubr (&Sidentity);
5659 defsubr (&Srandom);
5660 defsubr (&Slength);
5661 defsubr (&Ssafe_length);
5662 defsubr (&Sstring_bytes);
5663 defsubr (&Sstring_equal);
5664 defsubr (&Scompare_strings);
5665 defsubr (&Sstring_lessp);
5666 defsubr (&Sappend);
5667 defsubr (&Sconcat);
5668 defsubr (&Svconcat);
5669 defsubr (&Scopy_sequence);
5670 defsubr (&Sstring_make_multibyte);
5671 defsubr (&Sstring_make_unibyte);
5672 defsubr (&Sstring_as_multibyte);
5673 defsubr (&Sstring_as_unibyte);
5674 defsubr (&Sstring_to_multibyte);
5675 defsubr (&Scopy_alist);
5676 defsubr (&Ssubstring);
5677 defsubr (&Ssubstring_no_properties);
5678 defsubr (&Snthcdr);
5679 defsubr (&Snth);
5680 defsubr (&Selt);
5681 defsubr (&Smember);
5682 defsubr (&Smemq);
5683 defsubr (&Sassq);
5684 defsubr (&Sassoc);
5685 defsubr (&Srassq);
5686 defsubr (&Srassoc);
5687 defsubr (&Sdelq);
5688 defsubr (&Sdelete);
5689 defsubr (&Snreverse);
5690 defsubr (&Sreverse);
5691 defsubr (&Ssort);
5692 defsubr (&Splist_get);
5693 defsubr (&Sget);
5694 defsubr (&Splist_put);
5695 defsubr (&Sput);
5696 defsubr (&Slax_plist_get);
5697 defsubr (&Slax_plist_put);
5698 defsubr (&Sequal);
5699 defsubr (&Sfillarray);
5700 defsubr (&Sclear_string);
5701 defsubr (&Schar_table_subtype);
5702 defsubr (&Schar_table_parent);
5703 defsubr (&Sset_char_table_parent);
5704 defsubr (&Schar_table_extra_slot);
5705 defsubr (&Sset_char_table_extra_slot);
5706 defsubr (&Schar_table_range);
5707 defsubr (&Sset_char_table_range);
5708 defsubr (&Sset_char_table_default);
5709 defsubr (&Soptimize_char_table);
5710 defsubr (&Smap_char_table);
5711 defsubr (&Snconc);
5712 defsubr (&Smapcar);
5713 defsubr (&Smapc);
5714 defsubr (&Smapconcat);
5715 defsubr (&Sy_or_n_p);
5716 defsubr (&Syes_or_no_p);
5717 defsubr (&Sload_average);
5718 defsubr (&Sfeaturep);
5719 defsubr (&Srequire);
5720 defsubr (&Sprovide);
5721 defsubr (&Splist_member);
5722 defsubr (&Swidget_put);
5723 defsubr (&Swidget_get);
5724 defsubr (&Swidget_apply);
5725 defsubr (&Sbase64_encode_region);
5726 defsubr (&Sbase64_decode_region);
5727 defsubr (&Sbase64_encode_string);
5728 defsubr (&Sbase64_decode_string);
5729 defsubr (&Smd5);
5730 defsubr (&Slocale_info);
5734 void
5735 init_fns ()
5737 Vweak_hash_tables = Qnil;
5740 /* arch-tag: 787f8219-5b74-46bd-8469-7e1cc475fa31
5741 (do not change this comment) */