(tcl-mode): Set imenu-generic-expression to the value of
[emacs.git] / src / fns.c
blob128b332886ab32cb0b7ce4b47bfdaeb83cf20fae
1 /* Random utility Lisp functions.
2 Copyright (C) 1985, 86, 87, 93, 94, 95, 97, 98, 99, 2000, 2001, 2002
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 extern int minibuffer_auto_raise;
63 extern Lisp_Object minibuf_window;
64 extern Lisp_Object Vlocale_coding_system;
66 Lisp_Object Qstring_lessp, Qprovide, Qrequire;
67 Lisp_Object Qyes_or_no_p_history;
68 Lisp_Object Qcursor_in_echo_area;
69 Lisp_Object Qwidget_type;
70 Lisp_Object Qcodeset, Qdays, Qmonths, Qpaper;
72 extern Lisp_Object Qinput_method_function;
74 static int internal_equal ();
76 extern long get_random ();
77 extern void seed_random ();
79 #ifndef HAVE_UNISTD_H
80 extern long time ();
81 #endif
83 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
84 doc: /* Return the argument unchanged. */)
85 (arg)
86 Lisp_Object arg;
88 return arg;
91 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
92 doc: /* Return a pseudo-random number.
93 All integers representable in Lisp are equally likely.
94 On most systems, this is 28 bits' worth.
95 With positive integer argument N, return random number in interval [0,N).
96 With argument t, set the random number seed from the current time and pid. */)
97 (n)
98 Lisp_Object n;
100 EMACS_INT val;
101 Lisp_Object lispy_val;
102 unsigned long denominator;
104 if (EQ (n, Qt))
105 seed_random (getpid () + time (NULL));
106 if (NATNUMP (n) && XFASTINT (n) != 0)
108 /* Try to take our random number from the higher bits of VAL,
109 not the lower, since (says Gentzel) the low bits of `random'
110 are less random than the higher ones. We do this by using the
111 quotient rather than the remainder. At the high end of the RNG
112 it's possible to get a quotient larger than n; discarding
113 these values eliminates the bias that would otherwise appear
114 when using a large n. */
115 denominator = ((unsigned long)1 << VALBITS) / XFASTINT (n);
117 val = get_random () / denominator;
118 while (val >= XFASTINT (n));
120 else
121 val = get_random ();
122 XSETINT (lispy_val, val);
123 return lispy_val;
126 /* Random data-structure functions */
128 DEFUN ("length", Flength, Slength, 1, 1, 0,
129 doc: /* Return the length of vector, list or string SEQUENCE.
130 A byte-code function object is also allowed.
131 If the string contains multibyte characters, this is not necessarily
132 the number of bytes in the string; it is the number of characters.
133 To get the number of bytes, use `string-bytes'. */)
134 (sequence)
135 register Lisp_Object sequence;
137 register Lisp_Object val;
138 register int i;
140 retry:
141 if (STRINGP (sequence))
142 XSETFASTINT (val, SCHARS (sequence));
143 else if (VECTORP (sequence))
144 XSETFASTINT (val, XVECTOR (sequence)->size);
145 else if (SUB_CHAR_TABLE_P (sequence))
146 XSETFASTINT (val, SUB_CHAR_TABLE_ORDINARY_SLOTS);
147 else if (CHAR_TABLE_P (sequence))
148 XSETFASTINT (val, MAX_CHAR);
149 else if (BOOL_VECTOR_P (sequence))
150 XSETFASTINT (val, XBOOL_VECTOR (sequence)->size);
151 else if (COMPILEDP (sequence))
152 XSETFASTINT (val, XVECTOR (sequence)->size & PSEUDOVECTOR_SIZE_MASK);
153 else if (CONSP (sequence))
155 i = 0;
156 while (CONSP (sequence))
158 sequence = XCDR (sequence);
159 ++i;
161 if (!CONSP (sequence))
162 break;
164 sequence = XCDR (sequence);
165 ++i;
166 QUIT;
169 if (!NILP (sequence))
170 wrong_type_argument (Qlistp, sequence);
172 val = make_number (i);
174 else if (NILP (sequence))
175 XSETFASTINT (val, 0);
176 else
178 sequence = wrong_type_argument (Qsequencep, sequence);
179 goto retry;
181 return val;
184 /* This does not check for quits. That is safe
185 since it must terminate. */
187 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
188 doc: /* Return the length of a list, but avoid error or infinite loop.
189 This function never gets an error. If LIST is not really a list,
190 it returns 0. If LIST is circular, it returns a finite value
191 which is at least the number of distinct elements. */)
192 (list)
193 Lisp_Object list;
195 Lisp_Object tail, halftail, length;
196 int len = 0;
198 /* halftail is used to detect circular lists. */
199 halftail = list;
200 for (tail = list; CONSP (tail); tail = XCDR (tail))
202 if (EQ (tail, halftail) && len != 0)
203 break;
204 len++;
205 if ((len & 1) == 0)
206 halftail = XCDR (halftail);
209 XSETINT (length, len);
210 return length;
213 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
214 doc: /* Return the number of bytes in STRING.
215 If STRING is a multibyte string, this is greater than the length of STRING. */)
216 (string)
217 Lisp_Object string;
219 CHECK_STRING (string);
220 return make_number (SBYTES (string));
223 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
224 doc: /* Return t if two strings have identical contents.
225 Case is significant, but text properties are ignored.
226 Symbols are also allowed; their print names are used instead. */)
227 (s1, s2)
228 register Lisp_Object s1, s2;
230 if (SYMBOLP (s1))
231 s1 = SYMBOL_NAME (s1);
232 if (SYMBOLP (s2))
233 s2 = SYMBOL_NAME (s2);
234 CHECK_STRING (s1);
235 CHECK_STRING (s2);
237 if (SCHARS (s1) != SCHARS (s2)
238 || SBYTES (s1) != SBYTES (s2)
239 || bcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
240 return Qnil;
241 return Qt;
244 DEFUN ("compare-strings", Fcompare_strings,
245 Scompare_strings, 6, 7, 0,
246 doc: /* Compare the contents of two strings, converting to multibyte if needed.
247 In string STR1, skip the first START1 characters and stop at END1.
248 In string STR2, skip the first START2 characters and stop at END2.
249 END1 and END2 default to the full lengths of the respective strings.
251 Case is significant in this comparison if IGNORE-CASE is nil.
252 Unibyte strings are converted to multibyte for comparison.
254 The value is t if the strings (or specified portions) match.
255 If string STR1 is less, the value is a negative number N;
256 - 1 - N is the number of characters that match at the beginning.
257 If string STR1 is greater, the value is a positive number N;
258 N - 1 is the number of characters that match at the beginning. */)
259 (str1, start1, end1, str2, start2, end2, ignore_case)
260 Lisp_Object str1, start1, end1, start2, str2, end2, ignore_case;
262 register int end1_char, end2_char;
263 register int i1, i1_byte, i2, i2_byte;
265 CHECK_STRING (str1);
266 CHECK_STRING (str2);
267 if (NILP (start1))
268 start1 = make_number (0);
269 if (NILP (start2))
270 start2 = make_number (0);
271 CHECK_NATNUM (start1);
272 CHECK_NATNUM (start2);
273 if (! NILP (end1))
274 CHECK_NATNUM (end1);
275 if (! NILP (end2))
276 CHECK_NATNUM (end2);
278 i1 = XINT (start1);
279 i2 = XINT (start2);
281 i1_byte = string_char_to_byte (str1, i1);
282 i2_byte = string_char_to_byte (str2, i2);
284 end1_char = SCHARS (str1);
285 if (! NILP (end1) && end1_char > XINT (end1))
286 end1_char = XINT (end1);
288 end2_char = SCHARS (str2);
289 if (! NILP (end2) && end2_char > XINT (end2))
290 end2_char = XINT (end2);
292 while (i1 < end1_char && i2 < end2_char)
294 /* When we find a mismatch, we must compare the
295 characters, not just the bytes. */
296 int c1, c2;
298 if (STRING_MULTIBYTE (str1))
299 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c1, str1, i1, i1_byte);
300 else
302 c1 = SREF (str1, i1++);
303 c1 = unibyte_char_to_multibyte (c1);
306 if (STRING_MULTIBYTE (str2))
307 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c2, str2, i2, i2_byte);
308 else
310 c2 = SREF (str2, i2++);
311 c2 = unibyte_char_to_multibyte (c2);
314 if (c1 == c2)
315 continue;
317 if (! NILP (ignore_case))
319 Lisp_Object tem;
321 tem = Fupcase (make_number (c1));
322 c1 = XINT (tem);
323 tem = Fupcase (make_number (c2));
324 c2 = XINT (tem);
327 if (c1 == c2)
328 continue;
330 /* Note that I1 has already been incremented
331 past the character that we are comparing;
332 hence we don't add or subtract 1 here. */
333 if (c1 < c2)
334 return make_number (- i1 + XINT (start1));
335 else
336 return make_number (i1 - XINT (start1));
339 if (i1 < end1_char)
340 return make_number (i1 - XINT (start1) + 1);
341 if (i2 < end2_char)
342 return make_number (- i1 + XINT (start1) - 1);
344 return Qt;
347 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
348 doc: /* Return t if first arg string is less than second in lexicographic order.
349 Case is significant.
350 Symbols are also allowed; their print names are used instead. */)
351 (s1, s2)
352 register Lisp_Object s1, s2;
354 register int end;
355 register int i1, i1_byte, i2, i2_byte;
357 if (SYMBOLP (s1))
358 s1 = SYMBOL_NAME (s1);
359 if (SYMBOLP (s2))
360 s2 = SYMBOL_NAME (s2);
361 CHECK_STRING (s1);
362 CHECK_STRING (s2);
364 i1 = i1_byte = i2 = i2_byte = 0;
366 end = SCHARS (s1);
367 if (end > SCHARS (s2))
368 end = SCHARS (s2);
370 while (i1 < end)
372 /* When we find a mismatch, we must compare the
373 characters, not just the bytes. */
374 int c1, c2;
376 FETCH_STRING_CHAR_ADVANCE (c1, s1, i1, i1_byte);
377 FETCH_STRING_CHAR_ADVANCE (c2, s2, i2, i2_byte);
379 if (c1 != c2)
380 return c1 < c2 ? Qt : Qnil;
382 return i1 < SCHARS (s2) ? Qt : Qnil;
385 static Lisp_Object concat ();
387 /* ARGSUSED */
388 Lisp_Object
389 concat2 (s1, s2)
390 Lisp_Object s1, s2;
392 #ifdef NO_ARG_ARRAY
393 Lisp_Object args[2];
394 args[0] = s1;
395 args[1] = s2;
396 return concat (2, args, Lisp_String, 0);
397 #else
398 return concat (2, &s1, Lisp_String, 0);
399 #endif /* NO_ARG_ARRAY */
402 /* ARGSUSED */
403 Lisp_Object
404 concat3 (s1, s2, s3)
405 Lisp_Object s1, s2, s3;
407 #ifdef NO_ARG_ARRAY
408 Lisp_Object args[3];
409 args[0] = s1;
410 args[1] = s2;
411 args[2] = s3;
412 return concat (3, args, Lisp_String, 0);
413 #else
414 return concat (3, &s1, Lisp_String, 0);
415 #endif /* NO_ARG_ARRAY */
418 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
419 doc: /* Concatenate all the arguments and make the result a list.
420 The result is a list whose elements are the elements of all the arguments.
421 Each argument may be a list, vector or string.
422 The last argument is not copied, just used as the tail of the new list.
423 usage: (append &rest SEQUENCES) */)
424 (nargs, args)
425 int nargs;
426 Lisp_Object *args;
428 return concat (nargs, args, Lisp_Cons, 1);
431 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
432 doc: /* Concatenate all the arguments and make the result a string.
433 The result is a string whose elements are the elements of all the arguments.
434 Each argument may be a string or a list or vector of characters (integers).
435 usage: (concat &rest SEQUENCES) */)
436 (nargs, args)
437 int nargs;
438 Lisp_Object *args;
440 return concat (nargs, args, Lisp_String, 0);
443 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
444 doc: /* Concatenate all the arguments and make the result a vector.
445 The result is a vector whose elements are the elements of all the arguments.
446 Each argument may be a list, vector or string.
447 usage: (vconcat &rest SEQUENCES) */)
448 (nargs, args)
449 int nargs;
450 Lisp_Object *args;
452 return concat (nargs, args, Lisp_Vectorlike, 0);
455 /* Return a copy of a sub char table ARG. The elements except for a
456 nested sub char table are not copied. */
457 static Lisp_Object
458 copy_sub_char_table (arg)
459 Lisp_Object arg;
461 Lisp_Object copy = make_sub_char_table (XCHAR_TABLE (arg)->defalt);
462 int i;
464 /* Copy all the contents. */
465 bcopy (XCHAR_TABLE (arg)->contents, XCHAR_TABLE (copy)->contents,
466 SUB_CHAR_TABLE_ORDINARY_SLOTS * sizeof (Lisp_Object));
467 /* Recursively copy any sub char-tables in the ordinary slots. */
468 for (i = 32; i < SUB_CHAR_TABLE_ORDINARY_SLOTS; i++)
469 if (SUB_CHAR_TABLE_P (XCHAR_TABLE (arg)->contents[i]))
470 XCHAR_TABLE (copy)->contents[i]
471 = copy_sub_char_table (XCHAR_TABLE (copy)->contents[i]);
473 return copy;
477 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
478 doc: /* Return a copy of a list, vector, string or char-table.
479 The elements of a list or vector are not copied; they are shared
480 with the original. */)
481 (arg)
482 Lisp_Object arg;
484 if (NILP (arg)) return arg;
486 if (CHAR_TABLE_P (arg))
488 int i;
489 Lisp_Object copy;
491 copy = Fmake_char_table (XCHAR_TABLE (arg)->purpose, Qnil);
492 /* Copy all the slots, including the extra ones. */
493 bcopy (XVECTOR (arg)->contents, XVECTOR (copy)->contents,
494 ((XCHAR_TABLE (arg)->size & PSEUDOVECTOR_SIZE_MASK)
495 * sizeof (Lisp_Object)));
497 /* Recursively copy any sub char tables in the ordinary slots
498 for multibyte characters. */
499 for (i = CHAR_TABLE_SINGLE_BYTE_SLOTS;
500 i < CHAR_TABLE_ORDINARY_SLOTS; i++)
501 if (SUB_CHAR_TABLE_P (XCHAR_TABLE (arg)->contents[i]))
502 XCHAR_TABLE (copy)->contents[i]
503 = copy_sub_char_table (XCHAR_TABLE (copy)->contents[i]);
505 return copy;
508 if (BOOL_VECTOR_P (arg))
510 Lisp_Object val;
511 int size_in_chars
512 = (XBOOL_VECTOR (arg)->size + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
514 val = Fmake_bool_vector (Flength (arg), Qnil);
515 bcopy (XBOOL_VECTOR (arg)->data, XBOOL_VECTOR (val)->data,
516 size_in_chars);
517 return val;
520 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
521 arg = wrong_type_argument (Qsequencep, arg);
522 return concat (1, &arg, CONSP (arg) ? Lisp_Cons : XTYPE (arg), 0);
525 /* In string STR of length LEN, see if bytes before STR[I] combine
526 with bytes after STR[I] to form a single character. If so, return
527 the number of bytes after STR[I] which combine in this way.
528 Otherwize, return 0. */
530 static int
531 count_combining (str, len, i)
532 unsigned char *str;
533 int len, i;
535 int j = i - 1, bytes;
537 if (i == 0 || i == len || CHAR_HEAD_P (str[i]))
538 return 0;
539 while (j >= 0 && !CHAR_HEAD_P (str[j])) j--;
540 if (j < 0 || ! BASE_LEADING_CODE_P (str[j]))
541 return 0;
542 PARSE_MULTIBYTE_SEQ (str + j, len - j, bytes);
543 return (bytes <= i - j ? 0 : bytes - (i - j));
546 /* This structure holds information of an argument of `concat' that is
547 a string and has text properties to be copied. */
548 struct textprop_rec
550 int argnum; /* refer to ARGS (arguments of `concat') */
551 int from; /* refer to ARGS[argnum] (argument string) */
552 int to; /* refer to VAL (the target string) */
555 static Lisp_Object
556 concat (nargs, args, target_type, last_special)
557 int nargs;
558 Lisp_Object *args;
559 enum Lisp_Type target_type;
560 int last_special;
562 Lisp_Object val;
563 register Lisp_Object tail;
564 register Lisp_Object this;
565 int toindex;
566 int toindex_byte = 0;
567 register int result_len;
568 register int result_len_byte;
569 register int argnum;
570 Lisp_Object last_tail;
571 Lisp_Object prev;
572 int some_multibyte;
573 /* When we make a multibyte string, we can't copy text properties
574 while concatinating each string because the length of resulting
575 string can't be decided until we finish the whole concatination.
576 So, we record strings that have text properties to be copied
577 here, and copy the text properties after the concatination. */
578 struct textprop_rec *textprops = NULL;
579 /* Number of elments in textprops. */
580 int num_textprops = 0;
582 tail = Qnil;
584 /* In append, the last arg isn't treated like the others */
585 if (last_special && nargs > 0)
587 nargs--;
588 last_tail = args[nargs];
590 else
591 last_tail = Qnil;
593 /* Canonicalize each argument. */
594 for (argnum = 0; argnum < nargs; argnum++)
596 this = args[argnum];
597 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
598 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
600 args[argnum] = wrong_type_argument (Qsequencep, this);
604 /* Compute total length in chars of arguments in RESULT_LEN.
605 If desired output is a string, also compute length in bytes
606 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
607 whether the result should be a multibyte string. */
608 result_len_byte = 0;
609 result_len = 0;
610 some_multibyte = 0;
611 for (argnum = 0; argnum < nargs; argnum++)
613 int len;
614 this = args[argnum];
615 len = XFASTINT (Flength (this));
616 if (target_type == Lisp_String)
618 /* We must count the number of bytes needed in the string
619 as well as the number of characters. */
620 int i;
621 Lisp_Object ch;
622 int this_len_byte;
624 if (VECTORP (this))
625 for (i = 0; i < len; i++)
627 ch = XVECTOR (this)->contents[i];
628 if (! INTEGERP (ch))
629 wrong_type_argument (Qintegerp, ch);
630 this_len_byte = CHAR_BYTES (XINT (ch));
631 result_len_byte += this_len_byte;
632 if (!SINGLE_BYTE_CHAR_P (XINT (ch)))
633 some_multibyte = 1;
635 else if (BOOL_VECTOR_P (this) && XBOOL_VECTOR (this)->size > 0)
636 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
637 else if (CONSP (this))
638 for (; CONSP (this); this = XCDR (this))
640 ch = XCAR (this);
641 if (! INTEGERP (ch))
642 wrong_type_argument (Qintegerp, ch);
643 this_len_byte = CHAR_BYTES (XINT (ch));
644 result_len_byte += this_len_byte;
645 if (!SINGLE_BYTE_CHAR_P (XINT (ch)))
646 some_multibyte = 1;
648 else if (STRINGP (this))
650 if (STRING_MULTIBYTE (this))
652 some_multibyte = 1;
653 result_len_byte += SBYTES (this);
655 else
656 result_len_byte += count_size_as_multibyte (SDATA (this),
657 SCHARS (this));
661 result_len += len;
664 if (! some_multibyte)
665 result_len_byte = result_len;
667 /* Create the output object. */
668 if (target_type == Lisp_Cons)
669 val = Fmake_list (make_number (result_len), Qnil);
670 else if (target_type == Lisp_Vectorlike)
671 val = Fmake_vector (make_number (result_len), Qnil);
672 else if (some_multibyte)
673 val = make_uninit_multibyte_string (result_len, result_len_byte);
674 else
675 val = make_uninit_string (result_len);
677 /* In `append', if all but last arg are nil, return last arg. */
678 if (target_type == Lisp_Cons && EQ (val, Qnil))
679 return last_tail;
681 /* Copy the contents of the args into the result. */
682 if (CONSP (val))
683 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
684 else
685 toindex = 0, toindex_byte = 0;
687 prev = Qnil;
688 if (STRINGP (val))
689 textprops
690 = (struct textprop_rec *) alloca (sizeof (struct textprop_rec) * nargs);
692 for (argnum = 0; argnum < nargs; argnum++)
694 Lisp_Object thislen;
695 int thisleni = 0;
696 register unsigned int thisindex = 0;
697 register unsigned int thisindex_byte = 0;
699 this = args[argnum];
700 if (!CONSP (this))
701 thislen = Flength (this), thisleni = XINT (thislen);
703 /* Between strings of the same kind, copy fast. */
704 if (STRINGP (this) && STRINGP (val)
705 && STRING_MULTIBYTE (this) == some_multibyte)
707 int thislen_byte = SBYTES (this);
708 int combined;
710 bcopy (SDATA (this), SDATA (val) + toindex_byte,
711 SBYTES (this));
712 combined = (some_multibyte && toindex_byte > 0
713 ? count_combining (SDATA (val),
714 toindex_byte + thislen_byte,
715 toindex_byte)
716 : 0);
717 if (! NULL_INTERVAL_P (STRING_INTERVALS (this)))
719 textprops[num_textprops].argnum = argnum;
720 /* We ignore text properties on characters being combined. */
721 textprops[num_textprops].from = combined;
722 textprops[num_textprops++].to = toindex;
724 toindex_byte += thislen_byte;
725 toindex += thisleni - combined;
726 STRING_SET_CHARS (val, SCHARS (val) - combined);
728 /* Copy a single-byte string to a multibyte string. */
729 else if (STRINGP (this) && STRINGP (val))
731 if (! NULL_INTERVAL_P (STRING_INTERVALS (this)))
733 textprops[num_textprops].argnum = argnum;
734 textprops[num_textprops].from = 0;
735 textprops[num_textprops++].to = toindex;
737 toindex_byte += copy_text (SDATA (this),
738 SDATA (val) + toindex_byte,
739 SCHARS (this), 0, 1);
740 toindex += thisleni;
742 else
743 /* Copy element by element. */
744 while (1)
746 register Lisp_Object elt;
748 /* Fetch next element of `this' arg into `elt', or break if
749 `this' is exhausted. */
750 if (NILP (this)) break;
751 if (CONSP (this))
752 elt = XCAR (this), this = XCDR (this);
753 else if (thisindex >= thisleni)
754 break;
755 else if (STRINGP (this))
757 int c;
758 if (STRING_MULTIBYTE (this))
760 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
761 thisindex,
762 thisindex_byte);
763 XSETFASTINT (elt, c);
765 else
767 XSETFASTINT (elt, SREF (this, thisindex++));
768 if (some_multibyte
769 && (XINT (elt) >= 0240
770 || (XINT (elt) >= 0200
771 && ! NILP (Vnonascii_translation_table)))
772 && XINT (elt) < 0400)
774 c = unibyte_char_to_multibyte (XINT (elt));
775 XSETINT (elt, c);
779 else if (BOOL_VECTOR_P (this))
781 int byte;
782 byte = XBOOL_VECTOR (this)->data[thisindex / BITS_PER_CHAR];
783 if (byte & (1 << (thisindex % BITS_PER_CHAR)))
784 elt = Qt;
785 else
786 elt = Qnil;
787 thisindex++;
789 else
790 elt = XVECTOR (this)->contents[thisindex++];
792 /* Store this element into the result. */
793 if (toindex < 0)
795 XSETCAR (tail, elt);
796 prev = tail;
797 tail = XCDR (tail);
799 else if (VECTORP (val))
800 XVECTOR (val)->contents[toindex++] = elt;
801 else
803 CHECK_NUMBER (elt);
804 if (SINGLE_BYTE_CHAR_P (XINT (elt)))
806 if (some_multibyte)
807 toindex_byte
808 += CHAR_STRING (XINT (elt),
809 SDATA (val) + toindex_byte);
810 else
811 SSET (val, toindex_byte++, XINT (elt));
812 if (some_multibyte
813 && toindex_byte > 0
814 && count_combining (SDATA (val),
815 toindex_byte, toindex_byte - 1))
816 STRING_SET_CHARS (val, SCHARS (val) - 1);
817 else
818 toindex++;
820 else
821 /* If we have any multibyte characters,
822 we already decided to make a multibyte string. */
824 int c = XINT (elt);
825 /* P exists as a variable
826 to avoid a bug on the Masscomp C compiler. */
827 unsigned char *p = SDATA (val) + toindex_byte;
829 toindex_byte += CHAR_STRING (c, p);
830 toindex++;
835 if (!NILP (prev))
836 XSETCDR (prev, last_tail);
838 if (num_textprops > 0)
840 Lisp_Object props;
841 int last_to_end = -1;
843 for (argnum = 0; argnum < num_textprops; argnum++)
845 this = args[textprops[argnum].argnum];
846 props = text_property_list (this,
847 make_number (0),
848 make_number (SCHARS (this)),
849 Qnil);
850 /* If successive arguments have properites, be sure that the
851 value of `composition' property be the copy. */
852 if (last_to_end == textprops[argnum].to)
853 make_composition_value_copy (props);
854 add_text_properties_from_list (val, props,
855 make_number (textprops[argnum].to));
856 last_to_end = textprops[argnum].to + SCHARS (this);
859 return val;
862 static Lisp_Object string_char_byte_cache_string;
863 static int string_char_byte_cache_charpos;
864 static int string_char_byte_cache_bytepos;
866 void
867 clear_string_char_byte_cache ()
869 string_char_byte_cache_string = Qnil;
872 /* Return the character index corresponding to CHAR_INDEX in STRING. */
875 string_char_to_byte (string, char_index)
876 Lisp_Object string;
877 int char_index;
879 int i, i_byte;
880 int best_below, best_below_byte;
881 int best_above, best_above_byte;
883 if (! STRING_MULTIBYTE (string))
884 return char_index;
886 best_below = best_below_byte = 0;
887 best_above = SCHARS (string);
888 best_above_byte = SBYTES (string);
890 if (EQ (string, string_char_byte_cache_string))
892 if (string_char_byte_cache_charpos < char_index)
894 best_below = string_char_byte_cache_charpos;
895 best_below_byte = string_char_byte_cache_bytepos;
897 else
899 best_above = string_char_byte_cache_charpos;
900 best_above_byte = string_char_byte_cache_bytepos;
904 if (char_index - best_below < best_above - char_index)
906 while (best_below < char_index)
908 int c;
909 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, string,
910 best_below, best_below_byte);
912 i = best_below;
913 i_byte = best_below_byte;
915 else
917 while (best_above > char_index)
919 unsigned char *pend = SDATA (string) + best_above_byte;
920 unsigned char *pbeg = pend - best_above_byte;
921 unsigned char *p = pend - 1;
922 int bytes;
924 while (p > pbeg && !CHAR_HEAD_P (*p)) p--;
925 PARSE_MULTIBYTE_SEQ (p, pend - p, bytes);
926 if (bytes == pend - p)
927 best_above_byte -= bytes;
928 else if (bytes > pend - p)
929 best_above_byte -= (pend - p);
930 else
931 best_above_byte--;
932 best_above--;
934 i = best_above;
935 i_byte = best_above_byte;
938 string_char_byte_cache_bytepos = i_byte;
939 string_char_byte_cache_charpos = i;
940 string_char_byte_cache_string = string;
942 return i_byte;
945 /* Return the character index corresponding to BYTE_INDEX in STRING. */
948 string_byte_to_char (string, byte_index)
949 Lisp_Object string;
950 int byte_index;
952 int i, i_byte;
953 int best_below, best_below_byte;
954 int best_above, best_above_byte;
956 if (! STRING_MULTIBYTE (string))
957 return byte_index;
959 best_below = best_below_byte = 0;
960 best_above = SCHARS (string);
961 best_above_byte = SBYTES (string);
963 if (EQ (string, string_char_byte_cache_string))
965 if (string_char_byte_cache_bytepos < byte_index)
967 best_below = string_char_byte_cache_charpos;
968 best_below_byte = string_char_byte_cache_bytepos;
970 else
972 best_above = string_char_byte_cache_charpos;
973 best_above_byte = string_char_byte_cache_bytepos;
977 if (byte_index - best_below_byte < best_above_byte - byte_index)
979 while (best_below_byte < byte_index)
981 int c;
982 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, string,
983 best_below, best_below_byte);
985 i = best_below;
986 i_byte = best_below_byte;
988 else
990 while (best_above_byte > byte_index)
992 unsigned char *pend = SDATA (string) + best_above_byte;
993 unsigned char *pbeg = pend - best_above_byte;
994 unsigned char *p = pend - 1;
995 int bytes;
997 while (p > pbeg && !CHAR_HEAD_P (*p)) p--;
998 PARSE_MULTIBYTE_SEQ (p, pend - p, bytes);
999 if (bytes == pend - p)
1000 best_above_byte -= bytes;
1001 else if (bytes > pend - p)
1002 best_above_byte -= (pend - p);
1003 else
1004 best_above_byte--;
1005 best_above--;
1007 i = best_above;
1008 i_byte = best_above_byte;
1011 string_char_byte_cache_bytepos = i_byte;
1012 string_char_byte_cache_charpos = i;
1013 string_char_byte_cache_string = string;
1015 return i;
1018 /* Convert STRING to a multibyte string.
1019 Single-byte characters 0240 through 0377 are converted
1020 by adding nonascii_insert_offset to each. */
1022 Lisp_Object
1023 string_make_multibyte (string)
1024 Lisp_Object string;
1026 unsigned char *buf;
1027 int nbytes;
1029 if (STRING_MULTIBYTE (string))
1030 return string;
1032 nbytes = count_size_as_multibyte (SDATA (string),
1033 SCHARS (string));
1034 /* If all the chars are ASCII, they won't need any more bytes
1035 once converted. In that case, we can return STRING itself. */
1036 if (nbytes == SBYTES (string))
1037 return string;
1039 buf = (unsigned char *) alloca (nbytes);
1040 copy_text (SDATA (string), buf, SBYTES (string),
1041 0, 1);
1043 return make_multibyte_string (buf, SCHARS (string), nbytes);
1047 /* Convert STRING to a multibyte string without changing each
1048 character codes. Thus, characters 0200 trough 0237 are converted
1049 to eight-bit-control characters, and characters 0240 through 0377
1050 are converted eight-bit-graphic characters. */
1052 Lisp_Object
1053 string_to_multibyte (string)
1054 Lisp_Object string;
1056 unsigned char *buf;
1057 int nbytes;
1059 if (STRING_MULTIBYTE (string))
1060 return string;
1062 nbytes = parse_str_to_multibyte (SDATA (string), SBYTES (string));
1063 /* If all the chars are ASCII or eight-bit-graphic, they won't need
1064 any more bytes once converted. */
1065 if (nbytes == SBYTES (string))
1066 return make_multibyte_string (SDATA (string), nbytes, nbytes);
1068 buf = (unsigned char *) alloca (nbytes);
1069 bcopy (SDATA (string), buf, SBYTES (string));
1070 str_to_multibyte (buf, nbytes, SBYTES (string));
1072 return make_multibyte_string (buf, SCHARS (string), nbytes);
1076 /* Convert STRING to a single-byte string. */
1078 Lisp_Object
1079 string_make_unibyte (string)
1080 Lisp_Object string;
1082 unsigned char *buf;
1084 if (! STRING_MULTIBYTE (string))
1085 return string;
1087 buf = (unsigned char *) alloca (SCHARS (string));
1089 copy_text (SDATA (string), buf, SBYTES (string),
1090 1, 0);
1092 return make_unibyte_string (buf, SCHARS (string));
1095 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
1096 1, 1, 0,
1097 doc: /* Return the multibyte equivalent of STRING.
1098 The function `unibyte-char-to-multibyte' is used to convert
1099 each unibyte character to a multibyte character. */)
1100 (string)
1101 Lisp_Object string;
1103 CHECK_STRING (string);
1105 return string_make_multibyte (string);
1108 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
1109 1, 1, 0,
1110 doc: /* Return the unibyte equivalent of STRING.
1111 Multibyte character codes are converted to unibyte according to
1112 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
1113 If the lookup in the translation table fails, this function takes just
1114 the low 8 bits of each character. */)
1115 (string)
1116 Lisp_Object string;
1118 CHECK_STRING (string);
1120 return string_make_unibyte (string);
1123 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
1124 1, 1, 0,
1125 doc: /* Return a unibyte string with the same individual bytes as STRING.
1126 If STRING is unibyte, the result is STRING itself.
1127 Otherwise it is a newly created string, with no text properties.
1128 If STRING is multibyte and contains a character of charset
1129 `eight-bit-control' or `eight-bit-graphic', it is converted to the
1130 corresponding single byte. */)
1131 (string)
1132 Lisp_Object string;
1134 CHECK_STRING (string);
1136 if (STRING_MULTIBYTE (string))
1138 int bytes = SBYTES (string);
1139 unsigned char *str = (unsigned char *) xmalloc (bytes);
1141 bcopy (SDATA (string), str, bytes);
1142 bytes = str_as_unibyte (str, bytes);
1143 string = make_unibyte_string (str, bytes);
1144 xfree (str);
1146 return string;
1149 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1150 1, 1, 0,
1151 doc: /* Return a multibyte string with the same individual bytes as STRING.
1152 If STRING is multibyte, the result is STRING itself.
1153 Otherwise it is a newly created string, with no text properties.
1154 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1155 part of a multibyte form), it is converted to the corresponding
1156 multibyte character of charset `eight-bit-control' or `eight-bit-graphic'. */)
1157 (string)
1158 Lisp_Object string;
1160 CHECK_STRING (string);
1162 if (! STRING_MULTIBYTE (string))
1164 Lisp_Object new_string;
1165 int nchars, nbytes;
1167 parse_str_as_multibyte (SDATA (string),
1168 SBYTES (string),
1169 &nchars, &nbytes);
1170 new_string = make_uninit_multibyte_string (nchars, nbytes);
1171 bcopy (SDATA (string), SDATA (new_string),
1172 SBYTES (string));
1173 if (nbytes != SBYTES (string))
1174 str_as_multibyte (SDATA (new_string), nbytes,
1175 SBYTES (string), NULL);
1176 string = new_string;
1177 STRING_SET_INTERVALS (string, NULL_INTERVAL);
1179 return string;
1182 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1183 1, 1, 0,
1184 doc: /* Return a multibyte string with the same individual chars as STRING.
1185 If STRING is multibyte, the result is STRING itself.
1186 Otherwise it is a newly created string, with no text properties.
1187 Characters 0200 through 0237 are converted to eight-bit-control
1188 characters of the same character code. Characters 0240 through 0377
1189 are converted to eight-bit-control characters of the same character
1190 codes. */)
1191 (string)
1192 Lisp_Object string;
1194 CHECK_STRING (string);
1196 return string_to_multibyte (string);
1200 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1201 doc: /* Return a copy of ALIST.
1202 This is an alist which represents the same mapping from objects to objects,
1203 but does not share the alist structure with ALIST.
1204 The objects mapped (cars and cdrs of elements of the alist)
1205 are shared, however.
1206 Elements of ALIST that are not conses are also shared. */)
1207 (alist)
1208 Lisp_Object alist;
1210 register Lisp_Object tem;
1212 CHECK_LIST (alist);
1213 if (NILP (alist))
1214 return alist;
1215 alist = concat (1, &alist, Lisp_Cons, 0);
1216 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1218 register Lisp_Object car;
1219 car = XCAR (tem);
1221 if (CONSP (car))
1222 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1224 return alist;
1227 DEFUN ("substring", Fsubstring, Ssubstring, 2, 3, 0,
1228 doc: /* Return a substring of STRING, starting at index FROM and ending before TO.
1229 TO may be nil or omitted; then the substring runs to the end of STRING.
1230 FROM and TO start at 0. If either is negative, it counts from the end.
1232 This function allows vectors as well as strings. */)
1233 (string, from, to)
1234 Lisp_Object string;
1235 register Lisp_Object from, to;
1237 Lisp_Object res;
1238 int size;
1239 int size_byte = 0;
1240 int from_char, to_char;
1241 int from_byte = 0, to_byte = 0;
1243 if (! (STRINGP (string) || VECTORP (string)))
1244 wrong_type_argument (Qarrayp, string);
1246 CHECK_NUMBER (from);
1248 if (STRINGP (string))
1250 size = SCHARS (string);
1251 size_byte = SBYTES (string);
1253 else
1254 size = XVECTOR (string)->size;
1256 if (NILP (to))
1258 to_char = size;
1259 to_byte = size_byte;
1261 else
1263 CHECK_NUMBER (to);
1265 to_char = XINT (to);
1266 if (to_char < 0)
1267 to_char += size;
1269 if (STRINGP (string))
1270 to_byte = string_char_to_byte (string, to_char);
1273 from_char = XINT (from);
1274 if (from_char < 0)
1275 from_char += size;
1276 if (STRINGP (string))
1277 from_byte = string_char_to_byte (string, from_char);
1279 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1280 args_out_of_range_3 (string, make_number (from_char),
1281 make_number (to_char));
1283 if (STRINGP (string))
1285 res = make_specified_string (SDATA (string) + from_byte,
1286 to_char - from_char, to_byte - from_byte,
1287 STRING_MULTIBYTE (string));
1288 copy_text_properties (make_number (from_char), make_number (to_char),
1289 string, make_number (0), res, Qnil);
1291 else
1292 res = Fvector (to_char - from_char,
1293 XVECTOR (string)->contents + from_char);
1295 return res;
1299 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1300 doc: /* Return a substring of STRING, without text properties.
1301 It starts at index FROM and ending before TO.
1302 TO may be nil or omitted; then the substring runs to the end of STRING.
1303 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1304 If FROM or TO is negative, it counts from the end.
1306 With one argument, just copy STRING without its properties. */)
1307 (string, from, to)
1308 Lisp_Object string;
1309 register Lisp_Object from, to;
1311 int size, size_byte;
1312 int from_char, to_char;
1313 int from_byte, to_byte;
1315 CHECK_STRING (string);
1317 size = SCHARS (string);
1318 size_byte = SBYTES (string);
1320 if (NILP (from))
1321 from_char = from_byte = 0;
1322 else
1324 CHECK_NUMBER (from);
1325 from_char = XINT (from);
1326 if (from_char < 0)
1327 from_char += size;
1329 from_byte = string_char_to_byte (string, from_char);
1332 if (NILP (to))
1334 to_char = size;
1335 to_byte = size_byte;
1337 else
1339 CHECK_NUMBER (to);
1341 to_char = XINT (to);
1342 if (to_char < 0)
1343 to_char += size;
1345 to_byte = string_char_to_byte (string, to_char);
1348 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1349 args_out_of_range_3 (string, make_number (from_char),
1350 make_number (to_char));
1352 return make_specified_string (SDATA (string) + from_byte,
1353 to_char - from_char, to_byte - from_byte,
1354 STRING_MULTIBYTE (string));
1357 /* Extract a substring of STRING, giving start and end positions
1358 both in characters and in bytes. */
1360 Lisp_Object
1361 substring_both (string, from, from_byte, to, to_byte)
1362 Lisp_Object string;
1363 int from, from_byte, to, to_byte;
1365 Lisp_Object res;
1366 int size;
1367 int size_byte;
1369 if (! (STRINGP (string) || VECTORP (string)))
1370 wrong_type_argument (Qarrayp, string);
1372 if (STRINGP (string))
1374 size = SCHARS (string);
1375 size_byte = SBYTES (string);
1377 else
1378 size = XVECTOR (string)->size;
1380 if (!(0 <= from && from <= to && to <= size))
1381 args_out_of_range_3 (string, make_number (from), make_number (to));
1383 if (STRINGP (string))
1385 res = make_specified_string (SDATA (string) + from_byte,
1386 to - from, to_byte - from_byte,
1387 STRING_MULTIBYTE (string));
1388 copy_text_properties (make_number (from), make_number (to),
1389 string, make_number (0), res, Qnil);
1391 else
1392 res = Fvector (to - from,
1393 XVECTOR (string)->contents + from);
1395 return res;
1398 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1399 doc: /* Take cdr N times on LIST, returns the result. */)
1400 (n, list)
1401 Lisp_Object n;
1402 register Lisp_Object list;
1404 register int i, num;
1405 CHECK_NUMBER (n);
1406 num = XINT (n);
1407 for (i = 0; i < num && !NILP (list); i++)
1409 QUIT;
1410 if (! CONSP (list))
1411 wrong_type_argument (Qlistp, list);
1412 list = XCDR (list);
1414 return list;
1417 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1418 doc: /* Return the Nth element of LIST.
1419 N counts from zero. If LIST is not that long, nil is returned. */)
1420 (n, list)
1421 Lisp_Object n, list;
1423 return Fcar (Fnthcdr (n, list));
1426 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1427 doc: /* Return element of SEQUENCE at index N. */)
1428 (sequence, n)
1429 register Lisp_Object sequence, n;
1431 CHECK_NUMBER (n);
1432 while (1)
1434 if (CONSP (sequence) || NILP (sequence))
1435 return Fcar (Fnthcdr (n, sequence));
1436 else if (STRINGP (sequence) || VECTORP (sequence)
1437 || BOOL_VECTOR_P (sequence) || CHAR_TABLE_P (sequence))
1438 return Faref (sequence, n);
1439 else
1440 sequence = wrong_type_argument (Qsequencep, sequence);
1444 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1445 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1446 The value is actually the tail of LIST whose car is ELT. */)
1447 (elt, list)
1448 register Lisp_Object elt;
1449 Lisp_Object list;
1451 register Lisp_Object tail;
1452 for (tail = list; !NILP (tail); tail = XCDR (tail))
1454 register Lisp_Object tem;
1455 if (! CONSP (tail))
1456 wrong_type_argument (Qlistp, list);
1457 tem = XCAR (tail);
1458 if (! NILP (Fequal (elt, tem)))
1459 return tail;
1460 QUIT;
1462 return Qnil;
1465 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1466 doc: /* Return non-nil if ELT is an element of LIST.
1467 Comparison done with EQ. The value is actually the tail of LIST
1468 whose car is ELT. */)
1469 (elt, list)
1470 Lisp_Object elt, list;
1472 while (1)
1474 if (!CONSP (list) || EQ (XCAR (list), elt))
1475 break;
1477 list = XCDR (list);
1478 if (!CONSP (list) || EQ (XCAR (list), elt))
1479 break;
1481 list = XCDR (list);
1482 if (!CONSP (list) || EQ (XCAR (list), elt))
1483 break;
1485 list = XCDR (list);
1486 QUIT;
1489 if (!CONSP (list) && !NILP (list))
1490 list = wrong_type_argument (Qlistp, list);
1492 return list;
1495 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1496 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1497 The value is actually the element of LIST whose car is KEY.
1498 Elements of LIST that are not conses are ignored. */)
1499 (key, list)
1500 Lisp_Object key, list;
1502 Lisp_Object result;
1504 while (1)
1506 if (!CONSP (list)
1507 || (CONSP (XCAR (list))
1508 && EQ (XCAR (XCAR (list)), key)))
1509 break;
1511 list = XCDR (list);
1512 if (!CONSP (list)
1513 || (CONSP (XCAR (list))
1514 && EQ (XCAR (XCAR (list)), key)))
1515 break;
1517 list = XCDR (list);
1518 if (!CONSP (list)
1519 || (CONSP (XCAR (list))
1520 && EQ (XCAR (XCAR (list)), key)))
1521 break;
1523 list = XCDR (list);
1524 QUIT;
1527 if (CONSP (list))
1528 result = XCAR (list);
1529 else if (NILP (list))
1530 result = Qnil;
1531 else
1532 result = wrong_type_argument (Qlistp, list);
1534 return result;
1537 /* Like Fassq but never report an error and do not allow quits.
1538 Use only on lists known never to be circular. */
1540 Lisp_Object
1541 assq_no_quit (key, list)
1542 Lisp_Object key, list;
1544 while (CONSP (list)
1545 && (!CONSP (XCAR (list))
1546 || !EQ (XCAR (XCAR (list)), key)))
1547 list = XCDR (list);
1549 return CONSP (list) ? XCAR (list) : Qnil;
1552 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1553 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1554 The value is actually the element of LIST whose car equals KEY. */)
1555 (key, list)
1556 Lisp_Object key, list;
1558 Lisp_Object result, car;
1560 while (1)
1562 if (!CONSP (list)
1563 || (CONSP (XCAR (list))
1564 && (car = XCAR (XCAR (list)),
1565 EQ (car, key) || !NILP (Fequal (car, key)))))
1566 break;
1568 list = XCDR (list);
1569 if (!CONSP (list)
1570 || (CONSP (XCAR (list))
1571 && (car = XCAR (XCAR (list)),
1572 EQ (car, key) || !NILP (Fequal (car, key)))))
1573 break;
1575 list = XCDR (list);
1576 if (!CONSP (list)
1577 || (CONSP (XCAR (list))
1578 && (car = XCAR (XCAR (list)),
1579 EQ (car, key) || !NILP (Fequal (car, key)))))
1580 break;
1582 list = XCDR (list);
1583 QUIT;
1586 if (CONSP (list))
1587 result = XCAR (list);
1588 else if (NILP (list))
1589 result = Qnil;
1590 else
1591 result = wrong_type_argument (Qlistp, list);
1593 return result;
1596 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1597 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1598 The value is actually the element of LIST whose cdr is KEY. */)
1599 (key, list)
1600 register Lisp_Object key;
1601 Lisp_Object list;
1603 Lisp_Object result;
1605 while (1)
1607 if (!CONSP (list)
1608 || (CONSP (XCAR (list))
1609 && EQ (XCDR (XCAR (list)), key)))
1610 break;
1612 list = XCDR (list);
1613 if (!CONSP (list)
1614 || (CONSP (XCAR (list))
1615 && EQ (XCDR (XCAR (list)), key)))
1616 break;
1618 list = XCDR (list);
1619 if (!CONSP (list)
1620 || (CONSP (XCAR (list))
1621 && EQ (XCDR (XCAR (list)), key)))
1622 break;
1624 list = XCDR (list);
1625 QUIT;
1628 if (NILP (list))
1629 result = Qnil;
1630 else if (CONSP (list))
1631 result = XCAR (list);
1632 else
1633 result = wrong_type_argument (Qlistp, list);
1635 return result;
1638 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1639 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1640 The value is actually the element of LIST whose cdr equals KEY. */)
1641 (key, list)
1642 Lisp_Object key, list;
1644 Lisp_Object result, cdr;
1646 while (1)
1648 if (!CONSP (list)
1649 || (CONSP (XCAR (list))
1650 && (cdr = XCDR (XCAR (list)),
1651 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1652 break;
1654 list = XCDR (list);
1655 if (!CONSP (list)
1656 || (CONSP (XCAR (list))
1657 && (cdr = XCDR (XCAR (list)),
1658 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1659 break;
1661 list = XCDR (list);
1662 if (!CONSP (list)
1663 || (CONSP (XCAR (list))
1664 && (cdr = XCDR (XCAR (list)),
1665 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1666 break;
1668 list = XCDR (list);
1669 QUIT;
1672 if (CONSP (list))
1673 result = XCAR (list);
1674 else if (NILP (list))
1675 result = Qnil;
1676 else
1677 result = wrong_type_argument (Qlistp, list);
1679 return result;
1682 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1683 doc: /* Delete by side effect any occurrences of ELT as a member of LIST.
1684 The modified LIST is returned. Comparison is done with `eq'.
1685 If the first member of LIST is ELT, there is no way to remove it by side effect;
1686 therefore, write `(setq foo (delq element foo))'
1687 to be sure of changing the value of `foo'. */)
1688 (elt, list)
1689 register Lisp_Object elt;
1690 Lisp_Object list;
1692 register Lisp_Object tail, prev;
1693 register Lisp_Object tem;
1695 tail = list;
1696 prev = Qnil;
1697 while (!NILP (tail))
1699 if (! CONSP (tail))
1700 wrong_type_argument (Qlistp, list);
1701 tem = XCAR (tail);
1702 if (EQ (elt, tem))
1704 if (NILP (prev))
1705 list = XCDR (tail);
1706 else
1707 Fsetcdr (prev, XCDR (tail));
1709 else
1710 prev = tail;
1711 tail = XCDR (tail);
1712 QUIT;
1714 return list;
1717 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1718 doc: /* Delete by side effect any occurrences of ELT as a member of SEQ.
1719 SEQ must be a list, a vector, or a string.
1720 The modified SEQ is returned. Comparison is done with `equal'.
1721 If SEQ is not a list, or the first member of SEQ is ELT, deleting it
1722 is not a side effect; it is simply using a different sequence.
1723 Therefore, write `(setq foo (delete element foo))'
1724 to be sure of changing the value of `foo'. */)
1725 (elt, seq)
1726 Lisp_Object elt, seq;
1728 if (VECTORP (seq))
1730 EMACS_INT i, n;
1732 for (i = n = 0; i < ASIZE (seq); ++i)
1733 if (NILP (Fequal (AREF (seq, i), elt)))
1734 ++n;
1736 if (n != ASIZE (seq))
1738 struct Lisp_Vector *p = allocate_vector (n);
1740 for (i = n = 0; i < ASIZE (seq); ++i)
1741 if (NILP (Fequal (AREF (seq, i), elt)))
1742 p->contents[n++] = AREF (seq, i);
1744 XSETVECTOR (seq, p);
1747 else if (STRINGP (seq))
1749 EMACS_INT i, ibyte, nchars, nbytes, cbytes;
1750 int c;
1752 for (i = nchars = nbytes = ibyte = 0;
1753 i < SCHARS (seq);
1754 ++i, ibyte += cbytes)
1756 if (STRING_MULTIBYTE (seq))
1758 c = STRING_CHAR (SDATA (seq) + ibyte,
1759 SBYTES (seq) - ibyte);
1760 cbytes = CHAR_BYTES (c);
1762 else
1764 c = SREF (seq, i);
1765 cbytes = 1;
1768 if (!INTEGERP (elt) || c != XINT (elt))
1770 ++nchars;
1771 nbytes += cbytes;
1775 if (nchars != SCHARS (seq))
1777 Lisp_Object tem;
1779 tem = make_uninit_multibyte_string (nchars, nbytes);
1780 if (!STRING_MULTIBYTE (seq))
1781 STRING_SET_UNIBYTE (tem);
1783 for (i = nchars = nbytes = ibyte = 0;
1784 i < SCHARS (seq);
1785 ++i, ibyte += cbytes)
1787 if (STRING_MULTIBYTE (seq))
1789 c = STRING_CHAR (SDATA (seq) + ibyte,
1790 SBYTES (seq) - ibyte);
1791 cbytes = CHAR_BYTES (c);
1793 else
1795 c = SREF (seq, i);
1796 cbytes = 1;
1799 if (!INTEGERP (elt) || c != XINT (elt))
1801 unsigned char *from = SDATA (seq) + ibyte;
1802 unsigned char *to = SDATA (tem) + nbytes;
1803 EMACS_INT n;
1805 ++nchars;
1806 nbytes += cbytes;
1808 for (n = cbytes; n--; )
1809 *to++ = *from++;
1813 seq = tem;
1816 else
1818 Lisp_Object tail, prev;
1820 for (tail = seq, prev = Qnil; !NILP (tail); tail = XCDR (tail))
1822 if (!CONSP (tail))
1823 wrong_type_argument (Qlistp, seq);
1825 if (!NILP (Fequal (elt, XCAR (tail))))
1827 if (NILP (prev))
1828 seq = XCDR (tail);
1829 else
1830 Fsetcdr (prev, XCDR (tail));
1832 else
1833 prev = tail;
1834 QUIT;
1838 return seq;
1841 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1842 doc: /* Reverse LIST by modifying cdr pointers.
1843 Returns the beginning of the reversed list. */)
1844 (list)
1845 Lisp_Object list;
1847 register Lisp_Object prev, tail, next;
1849 if (NILP (list)) return list;
1850 prev = Qnil;
1851 tail = list;
1852 while (!NILP (tail))
1854 QUIT;
1855 if (! CONSP (tail))
1856 wrong_type_argument (Qlistp, list);
1857 next = XCDR (tail);
1858 Fsetcdr (tail, prev);
1859 prev = tail;
1860 tail = next;
1862 return prev;
1865 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1866 doc: /* Reverse LIST, copying. Returns the beginning of the reversed list.
1867 See also the function `nreverse', which is used more often. */)
1868 (list)
1869 Lisp_Object list;
1871 Lisp_Object new;
1873 for (new = Qnil; CONSP (list); list = XCDR (list))
1875 QUIT;
1876 new = Fcons (XCAR (list), new);
1878 if (!NILP (list))
1879 wrong_type_argument (Qconsp, list);
1880 return new;
1883 Lisp_Object merge ();
1885 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
1886 doc: /* Sort LIST, stably, comparing elements using PREDICATE.
1887 Returns the sorted list. LIST is modified by side effects.
1888 PREDICATE is called with two elements of LIST, and should return t
1889 if the first element is "less" than the second. */)
1890 (list, predicate)
1891 Lisp_Object list, predicate;
1893 Lisp_Object front, back;
1894 register Lisp_Object len, tem;
1895 struct gcpro gcpro1, gcpro2;
1896 register int length;
1898 front = list;
1899 len = Flength (list);
1900 length = XINT (len);
1901 if (length < 2)
1902 return list;
1904 XSETINT (len, (length / 2) - 1);
1905 tem = Fnthcdr (len, list);
1906 back = Fcdr (tem);
1907 Fsetcdr (tem, Qnil);
1909 GCPRO2 (front, back);
1910 front = Fsort (front, predicate);
1911 back = Fsort (back, predicate);
1912 UNGCPRO;
1913 return merge (front, back, predicate);
1916 Lisp_Object
1917 merge (org_l1, org_l2, pred)
1918 Lisp_Object org_l1, org_l2;
1919 Lisp_Object pred;
1921 Lisp_Object value;
1922 register Lisp_Object tail;
1923 Lisp_Object tem;
1924 register Lisp_Object l1, l2;
1925 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1927 l1 = org_l1;
1928 l2 = org_l2;
1929 tail = Qnil;
1930 value = Qnil;
1932 /* It is sufficient to protect org_l1 and org_l2.
1933 When l1 and l2 are updated, we copy the new values
1934 back into the org_ vars. */
1935 GCPRO4 (org_l1, org_l2, pred, value);
1937 while (1)
1939 if (NILP (l1))
1941 UNGCPRO;
1942 if (NILP (tail))
1943 return l2;
1944 Fsetcdr (tail, l2);
1945 return value;
1947 if (NILP (l2))
1949 UNGCPRO;
1950 if (NILP (tail))
1951 return l1;
1952 Fsetcdr (tail, l1);
1953 return value;
1955 tem = call2 (pred, Fcar (l2), Fcar (l1));
1956 if (NILP (tem))
1958 tem = l1;
1959 l1 = Fcdr (l1);
1960 org_l1 = l1;
1962 else
1964 tem = l2;
1965 l2 = Fcdr (l2);
1966 org_l2 = l2;
1968 if (NILP (tail))
1969 value = tem;
1970 else
1971 Fsetcdr (tail, tem);
1972 tail = tem;
1977 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
1978 doc: /* Extract a value from a property list.
1979 PLIST is a property list, which is a list of the form
1980 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1981 corresponding to the given PROP, or nil if PROP is not
1982 one of the properties on the list. */)
1983 (plist, prop)
1984 Lisp_Object plist;
1985 Lisp_Object prop;
1987 Lisp_Object tail;
1989 for (tail = plist;
1990 CONSP (tail) && CONSP (XCDR (tail));
1991 tail = XCDR (XCDR (tail)))
1993 if (EQ (prop, XCAR (tail)))
1994 return XCAR (XCDR (tail));
1996 /* This function can be called asynchronously
1997 (setup_coding_system). Don't QUIT in that case. */
1998 if (!interrupt_input_blocked)
1999 QUIT;
2002 if (!NILP (tail))
2003 wrong_type_argument (Qlistp, prop);
2005 return Qnil;
2008 DEFUN ("get", Fget, Sget, 2, 2, 0,
2009 doc: /* Return the value of SYMBOL's PROPNAME property.
2010 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
2011 (symbol, propname)
2012 Lisp_Object symbol, propname;
2014 CHECK_SYMBOL (symbol);
2015 return Fplist_get (XSYMBOL (symbol)->plist, propname);
2018 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
2019 doc: /* Change value in PLIST of PROP to VAL.
2020 PLIST is a property list, which is a list of the form
2021 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
2022 If PROP is already a property on the list, its value is set to VAL,
2023 otherwise the new PROP VAL pair is added. The new plist is returned;
2024 use `(setq x (plist-put x prop val))' to be sure to use the new value.
2025 The PLIST is modified by side effects. */)
2026 (plist, prop, val)
2027 Lisp_Object plist;
2028 register Lisp_Object prop;
2029 Lisp_Object val;
2031 register Lisp_Object tail, prev;
2032 Lisp_Object newcell;
2033 prev = Qnil;
2034 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2035 tail = XCDR (XCDR (tail)))
2037 if (EQ (prop, XCAR (tail)))
2039 Fsetcar (XCDR (tail), val);
2040 return plist;
2043 prev = tail;
2044 QUIT;
2046 newcell = Fcons (prop, Fcons (val, Qnil));
2047 if (NILP (prev))
2048 return newcell;
2049 else
2050 Fsetcdr (XCDR (prev), newcell);
2051 return plist;
2054 DEFUN ("put", Fput, Sput, 3, 3, 0,
2055 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
2056 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
2057 (symbol, propname, value)
2058 Lisp_Object symbol, propname, value;
2060 CHECK_SYMBOL (symbol);
2061 XSYMBOL (symbol)->plist
2062 = Fplist_put (XSYMBOL (symbol)->plist, propname, value);
2063 return value;
2066 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
2067 doc: /* Extract a value from a property list, comparing with `equal'.
2068 PLIST is a property list, which is a list of the form
2069 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2070 corresponding to the given PROP, or nil if PROP is not
2071 one of the properties on the list. */)
2072 (plist, prop)
2073 Lisp_Object plist;
2074 Lisp_Object prop;
2076 Lisp_Object tail;
2078 for (tail = plist;
2079 CONSP (tail) && CONSP (XCDR (tail));
2080 tail = XCDR (XCDR (tail)))
2082 if (! NILP (Fequal (prop, XCAR (tail))))
2083 return XCAR (XCDR (tail));
2085 QUIT;
2088 if (!NILP (tail))
2089 wrong_type_argument (Qlistp, prop);
2091 return Qnil;
2094 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
2095 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
2096 PLIST is a property list, which is a list of the form
2097 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
2098 If PROP is already a property on the list, its value is set to VAL,
2099 otherwise the new PROP VAL pair is added. The new plist is returned;
2100 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
2101 The PLIST is modified by side effects. */)
2102 (plist, prop, val)
2103 Lisp_Object plist;
2104 register Lisp_Object prop;
2105 Lisp_Object val;
2107 register Lisp_Object tail, prev;
2108 Lisp_Object newcell;
2109 prev = Qnil;
2110 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2111 tail = XCDR (XCDR (tail)))
2113 if (! NILP (Fequal (prop, XCAR (tail))))
2115 Fsetcar (XCDR (tail), val);
2116 return plist;
2119 prev = tail;
2120 QUIT;
2122 newcell = Fcons (prop, Fcons (val, Qnil));
2123 if (NILP (prev))
2124 return newcell;
2125 else
2126 Fsetcdr (XCDR (prev), newcell);
2127 return plist;
2130 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
2131 doc: /* Return t if two Lisp objects have similar structure and contents.
2132 They must have the same data type.
2133 Conses are compared by comparing the cars and the cdrs.
2134 Vectors and strings are compared element by element.
2135 Numbers are compared by value, but integers cannot equal floats.
2136 (Use `=' if you want integers and floats to be able to be equal.)
2137 Symbols must match exactly. */)
2138 (o1, o2)
2139 register Lisp_Object o1, o2;
2141 return internal_equal (o1, o2, 0) ? Qt : Qnil;
2144 static int
2145 internal_equal (o1, o2, depth)
2146 register Lisp_Object o1, o2;
2147 int depth;
2149 if (depth > 200)
2150 error ("Stack overflow in equal");
2152 tail_recurse:
2153 QUIT;
2154 if (EQ (o1, o2))
2155 return 1;
2156 if (XTYPE (o1) != XTYPE (o2))
2157 return 0;
2159 switch (XTYPE (o1))
2161 case Lisp_Float:
2162 return (extract_float (o1) == extract_float (o2));
2164 case Lisp_Cons:
2165 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1))
2166 return 0;
2167 o1 = XCDR (o1);
2168 o2 = XCDR (o2);
2169 goto tail_recurse;
2171 case Lisp_Misc:
2172 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2173 return 0;
2174 if (OVERLAYP (o1))
2176 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2177 depth + 1)
2178 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2179 depth + 1))
2180 return 0;
2181 o1 = XOVERLAY (o1)->plist;
2182 o2 = XOVERLAY (o2)->plist;
2183 goto tail_recurse;
2185 if (MARKERP (o1))
2187 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2188 && (XMARKER (o1)->buffer == 0
2189 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2191 break;
2193 case Lisp_Vectorlike:
2195 register int i, size;
2196 size = XVECTOR (o1)->size;
2197 /* Pseudovectors have the type encoded in the size field, so this test
2198 actually checks that the objects have the same type as well as the
2199 same size. */
2200 if (XVECTOR (o2)->size != size)
2201 return 0;
2202 /* Boolvectors are compared much like strings. */
2203 if (BOOL_VECTOR_P (o1))
2205 int size_in_chars
2206 = (XBOOL_VECTOR (o1)->size + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
2208 if (XBOOL_VECTOR (o1)->size != XBOOL_VECTOR (o2)->size)
2209 return 0;
2210 if (bcmp (XBOOL_VECTOR (o1)->data, XBOOL_VECTOR (o2)->data,
2211 size_in_chars))
2212 return 0;
2213 return 1;
2215 if (WINDOW_CONFIGURATIONP (o1))
2216 return compare_window_configurations (o1, o2, 0);
2218 /* Aside from them, only true vectors, char-tables, and compiled
2219 functions are sensible to compare, so eliminate the others now. */
2220 if (size & PSEUDOVECTOR_FLAG)
2222 if (!(size & (PVEC_COMPILED | PVEC_CHAR_TABLE)))
2223 return 0;
2224 size &= PSEUDOVECTOR_SIZE_MASK;
2226 for (i = 0; i < size; i++)
2228 Lisp_Object v1, v2;
2229 v1 = XVECTOR (o1)->contents [i];
2230 v2 = XVECTOR (o2)->contents [i];
2231 if (!internal_equal (v1, v2, depth + 1))
2232 return 0;
2234 return 1;
2236 break;
2238 case Lisp_String:
2239 if (SCHARS (o1) != SCHARS (o2))
2240 return 0;
2241 if (SBYTES (o1) != SBYTES (o2))
2242 return 0;
2243 if (bcmp (SDATA (o1), SDATA (o2),
2244 SBYTES (o1)))
2245 return 0;
2246 return 1;
2248 case Lisp_Int:
2249 case Lisp_Symbol:
2250 case Lisp_Type_Limit:
2251 break;
2254 return 0;
2257 extern Lisp_Object Fmake_char_internal ();
2259 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2260 doc: /* Store each element of ARRAY with ITEM.
2261 ARRAY is a vector, string, char-table, or bool-vector. */)
2262 (array, item)
2263 Lisp_Object array, item;
2265 register int size, index, charval;
2266 retry:
2267 if (VECTORP (array))
2269 register Lisp_Object *p = XVECTOR (array)->contents;
2270 size = XVECTOR (array)->size;
2271 for (index = 0; index < size; index++)
2272 p[index] = item;
2274 else if (CHAR_TABLE_P (array))
2276 register Lisp_Object *p = XCHAR_TABLE (array)->contents;
2277 size = CHAR_TABLE_ORDINARY_SLOTS;
2278 for (index = 0; index < size; index++)
2279 p[index] = item;
2280 XCHAR_TABLE (array)->defalt = Qnil;
2282 else if (STRINGP (array))
2284 register unsigned char *p = SDATA (array);
2285 CHECK_NUMBER (item);
2286 charval = XINT (item);
2287 size = SCHARS (array);
2288 if (STRING_MULTIBYTE (array))
2290 unsigned char str[MAX_MULTIBYTE_LENGTH];
2291 int len = CHAR_STRING (charval, str);
2292 int size_byte = SBYTES (array);
2293 unsigned char *p1 = p, *endp = p + size_byte;
2294 int i;
2296 if (size != size_byte)
2297 while (p1 < endp)
2299 int this_len = MULTIBYTE_FORM_LENGTH (p1, endp - p1);
2300 if (len != this_len)
2301 error ("Attempt to change byte length of a string");
2302 p1 += this_len;
2304 for (i = 0; i < size_byte; i++)
2305 *p++ = str[i % len];
2307 else
2308 for (index = 0; index < size; index++)
2309 p[index] = charval;
2311 else if (BOOL_VECTOR_P (array))
2313 register unsigned char *p = XBOOL_VECTOR (array)->data;
2314 int size_in_chars
2315 = (XBOOL_VECTOR (array)->size + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
2317 charval = (! NILP (item) ? -1 : 0);
2318 for (index = 0; index < size_in_chars; index++)
2319 p[index] = charval;
2321 else
2323 array = wrong_type_argument (Qarrayp, array);
2324 goto retry;
2326 return array;
2329 DEFUN ("char-table-subtype", Fchar_table_subtype, Schar_table_subtype,
2330 1, 1, 0,
2331 doc: /* Return the subtype of char-table CHAR-TABLE. The value is a symbol. */)
2332 (char_table)
2333 Lisp_Object char_table;
2335 CHECK_CHAR_TABLE (char_table);
2337 return XCHAR_TABLE (char_table)->purpose;
2340 DEFUN ("char-table-parent", Fchar_table_parent, Schar_table_parent,
2341 1, 1, 0,
2342 doc: /* Return the parent char-table of CHAR-TABLE.
2343 The value is either nil or another char-table.
2344 If CHAR-TABLE holds nil for a given character,
2345 then the actual applicable value is inherited from the parent char-table
2346 \(or from its parents, if necessary). */)
2347 (char_table)
2348 Lisp_Object char_table;
2350 CHECK_CHAR_TABLE (char_table);
2352 return XCHAR_TABLE (char_table)->parent;
2355 DEFUN ("set-char-table-parent", Fset_char_table_parent, Sset_char_table_parent,
2356 2, 2, 0,
2357 doc: /* Set the parent char-table of CHAR-TABLE to PARENT.
2358 PARENT must be either nil or another char-table. */)
2359 (char_table, parent)
2360 Lisp_Object char_table, parent;
2362 Lisp_Object temp;
2364 CHECK_CHAR_TABLE (char_table);
2366 if (!NILP (parent))
2368 CHECK_CHAR_TABLE (parent);
2370 for (temp = parent; !NILP (temp); temp = XCHAR_TABLE (temp)->parent)
2371 if (EQ (temp, char_table))
2372 error ("Attempt to make a chartable be its own parent");
2375 XCHAR_TABLE (char_table)->parent = parent;
2377 return parent;
2380 DEFUN ("char-table-extra-slot", Fchar_table_extra_slot, Schar_table_extra_slot,
2381 2, 2, 0,
2382 doc: /* Return the value of CHAR-TABLE's extra-slot number N. */)
2383 (char_table, n)
2384 Lisp_Object char_table, n;
2386 CHECK_CHAR_TABLE (char_table);
2387 CHECK_NUMBER (n);
2388 if (XINT (n) < 0
2389 || XINT (n) >= CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (char_table)))
2390 args_out_of_range (char_table, n);
2392 return XCHAR_TABLE (char_table)->extras[XINT (n)];
2395 DEFUN ("set-char-table-extra-slot", Fset_char_table_extra_slot,
2396 Sset_char_table_extra_slot,
2397 3, 3, 0,
2398 doc: /* Set CHAR-TABLE's extra-slot number N to VALUE. */)
2399 (char_table, n, value)
2400 Lisp_Object char_table, n, value;
2402 CHECK_CHAR_TABLE (char_table);
2403 CHECK_NUMBER (n);
2404 if (XINT (n) < 0
2405 || XINT (n) >= CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (char_table)))
2406 args_out_of_range (char_table, n);
2408 return XCHAR_TABLE (char_table)->extras[XINT (n)] = value;
2411 DEFUN ("char-table-range", Fchar_table_range, Schar_table_range,
2412 2, 2, 0,
2413 doc: /* Return the value in CHAR-TABLE for a range of characters RANGE.
2414 RANGE should be nil (for the default value)
2415 a vector which identifies a character set or a row of a character set,
2416 a character set name, or a character code. */)
2417 (char_table, range)
2418 Lisp_Object char_table, range;
2420 CHECK_CHAR_TABLE (char_table);
2422 if (EQ (range, Qnil))
2423 return XCHAR_TABLE (char_table)->defalt;
2424 else if (INTEGERP (range))
2425 return Faref (char_table, range);
2426 else if (SYMBOLP (range))
2428 Lisp_Object charset_info;
2430 charset_info = Fget (range, Qcharset);
2431 CHECK_VECTOR (charset_info);
2433 return Faref (char_table,
2434 make_number (XINT (XVECTOR (charset_info)->contents[0])
2435 + 128));
2437 else if (VECTORP (range))
2439 if (XVECTOR (range)->size == 1)
2440 return Faref (char_table,
2441 make_number (XINT (XVECTOR (range)->contents[0]) + 128));
2442 else
2444 int size = XVECTOR (range)->size;
2445 Lisp_Object *val = XVECTOR (range)->contents;
2446 Lisp_Object ch = Fmake_char_internal (size <= 0 ? Qnil : val[0],
2447 size <= 1 ? Qnil : val[1],
2448 size <= 2 ? Qnil : val[2]);
2449 return Faref (char_table, ch);
2452 else
2453 error ("Invalid RANGE argument to `char-table-range'");
2454 return Qt;
2457 DEFUN ("set-char-table-range", Fset_char_table_range, Sset_char_table_range,
2458 3, 3, 0,
2459 doc: /* Set the value in CHAR-TABLE for a range of characters RANGE to VALUE.
2460 RANGE should be t (for all characters), nil (for the default value)
2461 a vector which identifies a character set or a row of a character set,
2462 a coding system, or a character code. */)
2463 (char_table, range, value)
2464 Lisp_Object char_table, range, value;
2466 int i;
2468 CHECK_CHAR_TABLE (char_table);
2470 if (EQ (range, Qt))
2471 for (i = 0; i < CHAR_TABLE_ORDINARY_SLOTS; i++)
2472 XCHAR_TABLE (char_table)->contents[i] = value;
2473 else if (EQ (range, Qnil))
2474 XCHAR_TABLE (char_table)->defalt = value;
2475 else if (SYMBOLP (range))
2477 Lisp_Object charset_info;
2479 charset_info = Fget (range, Qcharset);
2480 CHECK_VECTOR (charset_info);
2482 return Faset (char_table,
2483 make_number (XINT (XVECTOR (charset_info)->contents[0])
2484 + 128),
2485 value);
2487 else if (INTEGERP (range))
2488 Faset (char_table, range, value);
2489 else if (VECTORP (range))
2491 if (XVECTOR (range)->size == 1)
2492 return Faset (char_table,
2493 make_number (XINT (XVECTOR (range)->contents[0]) + 128),
2494 value);
2495 else
2497 int size = XVECTOR (range)->size;
2498 Lisp_Object *val = XVECTOR (range)->contents;
2499 Lisp_Object ch = Fmake_char_internal (size <= 0 ? Qnil : val[0],
2500 size <= 1 ? Qnil : val[1],
2501 size <= 2 ? Qnil : val[2]);
2502 return Faset (char_table, ch, value);
2505 else
2506 error ("Invalid RANGE argument to `set-char-table-range'");
2508 return value;
2511 DEFUN ("set-char-table-default", Fset_char_table_default,
2512 Sset_char_table_default, 3, 3, 0,
2513 doc: /* Set the default value in CHAR-TABLE for generic character CH to VALUE.
2514 The generic character specifies the group of characters.
2515 See also the documentation of `make-char'. */)
2516 (char_table, ch, value)
2517 Lisp_Object char_table, ch, value;
2519 int c, charset, code1, code2;
2520 Lisp_Object temp;
2522 CHECK_CHAR_TABLE (char_table);
2523 CHECK_NUMBER (ch);
2525 c = XINT (ch);
2526 SPLIT_CHAR (c, charset, code1, code2);
2528 /* Since we may want to set the default value for a character set
2529 not yet defined, we check only if the character set is in the
2530 valid range or not, instead of it is already defined or not. */
2531 if (! CHARSET_VALID_P (charset))
2532 invalid_character (c);
2534 if (charset == CHARSET_ASCII)
2535 return (XCHAR_TABLE (char_table)->defalt = value);
2537 /* Even if C is not a generic char, we had better behave as if a
2538 generic char is specified. */
2539 if (!CHARSET_DEFINED_P (charset) || CHARSET_DIMENSION (charset) == 1)
2540 code1 = 0;
2541 temp = XCHAR_TABLE (char_table)->contents[charset + 128];
2542 if (!code1)
2544 if (SUB_CHAR_TABLE_P (temp))
2545 XCHAR_TABLE (temp)->defalt = value;
2546 else
2547 XCHAR_TABLE (char_table)->contents[charset + 128] = value;
2548 return value;
2550 if (SUB_CHAR_TABLE_P (temp))
2551 char_table = temp;
2552 else
2553 char_table = (XCHAR_TABLE (char_table)->contents[charset + 128]
2554 = make_sub_char_table (temp));
2555 temp = XCHAR_TABLE (char_table)->contents[code1];
2556 if (SUB_CHAR_TABLE_P (temp))
2557 XCHAR_TABLE (temp)->defalt = value;
2558 else
2559 XCHAR_TABLE (char_table)->contents[code1] = value;
2560 return value;
2563 /* Look up the element in TABLE at index CH,
2564 and return it as an integer.
2565 If the element is nil, return CH itself.
2566 (Actually we do that for any non-integer.) */
2569 char_table_translate (table, ch)
2570 Lisp_Object table;
2571 int ch;
2573 Lisp_Object value;
2574 value = Faref (table, make_number (ch));
2575 if (! INTEGERP (value))
2576 return ch;
2577 return XINT (value);
2580 static void
2581 optimize_sub_char_table (table, chars)
2582 Lisp_Object *table;
2583 int chars;
2585 Lisp_Object elt;
2586 int from, to;
2588 if (chars == 94)
2589 from = 33, to = 127;
2590 else
2591 from = 32, to = 128;
2593 if (!SUB_CHAR_TABLE_P (*table))
2594 return;
2595 elt = XCHAR_TABLE (*table)->contents[from++];
2596 for (; from < to; from++)
2597 if (NILP (Fequal (elt, XCHAR_TABLE (*table)->contents[from])))
2598 return;
2599 *table = elt;
2602 DEFUN ("optimize-char-table", Foptimize_char_table, Soptimize_char_table,
2603 1, 1, 0, doc: /* Optimize char table TABLE. */)
2604 (table)
2605 Lisp_Object table;
2607 Lisp_Object elt;
2608 int dim;
2609 int i, j;
2611 CHECK_CHAR_TABLE (table);
2613 for (i = CHAR_TABLE_SINGLE_BYTE_SLOTS; i < CHAR_TABLE_ORDINARY_SLOTS; i++)
2615 elt = XCHAR_TABLE (table)->contents[i];
2616 if (!SUB_CHAR_TABLE_P (elt))
2617 continue;
2618 dim = CHARSET_DIMENSION (i - 128);
2619 if (dim == 2)
2620 for (j = 32; j < SUB_CHAR_TABLE_ORDINARY_SLOTS; j++)
2621 optimize_sub_char_table (XCHAR_TABLE (elt)->contents + j, dim);
2622 optimize_sub_char_table (XCHAR_TABLE (table)->contents + i, dim);
2624 return Qnil;
2628 /* Map C_FUNCTION or FUNCTION over SUBTABLE, calling it for each
2629 character or group of characters that share a value.
2630 DEPTH is the current depth in the originally specified
2631 chartable, and INDICES contains the vector indices
2632 for the levels our callers have descended.
2634 ARG is passed to C_FUNCTION when that is called. */
2636 void
2637 map_char_table (c_function, function, table, subtable, arg, depth, indices)
2638 void (*c_function) P_ ((Lisp_Object, Lisp_Object, Lisp_Object));
2639 Lisp_Object function, table, subtable, arg, *indices;
2640 int depth;
2642 int i, to;
2644 if (depth == 0)
2646 /* At first, handle ASCII and 8-bit European characters. */
2647 for (i = 0; i < CHAR_TABLE_SINGLE_BYTE_SLOTS; i++)
2649 Lisp_Object elt= XCHAR_TABLE (subtable)->contents[i];
2650 if (NILP (elt))
2651 elt = XCHAR_TABLE (subtable)->defalt;
2652 if (NILP (elt))
2653 elt = Faref (subtable, make_number (i));
2654 if (c_function)
2655 (*c_function) (arg, make_number (i), elt);
2656 else
2657 call2 (function, make_number (i), elt);
2659 #if 0 /* If the char table has entries for higher characters,
2660 we should report them. */
2661 if (NILP (current_buffer->enable_multibyte_characters))
2662 return;
2663 #endif
2664 to = CHAR_TABLE_ORDINARY_SLOTS;
2666 else
2668 int charset = XFASTINT (indices[0]) - 128;
2670 i = 32;
2671 to = SUB_CHAR_TABLE_ORDINARY_SLOTS;
2672 if (CHARSET_CHARS (charset) == 94)
2673 i++, to--;
2676 for (; i < to; i++)
2678 Lisp_Object elt;
2679 int charset;
2681 elt = XCHAR_TABLE (subtable)->contents[i];
2682 XSETFASTINT (indices[depth], i);
2683 charset = XFASTINT (indices[0]) - 128;
2684 if (depth == 0
2685 && (!CHARSET_DEFINED_P (charset)
2686 || charset == CHARSET_8_BIT_CONTROL
2687 || charset == CHARSET_8_BIT_GRAPHIC))
2688 continue;
2690 if (SUB_CHAR_TABLE_P (elt))
2692 if (depth >= 3)
2693 error ("Too deep char table");
2694 map_char_table (c_function, function, table, elt, arg, depth + 1, indices);
2696 else
2698 int c1, c2, c;
2700 c1 = depth >= 1 ? XFASTINT (indices[1]) : 0;
2701 c2 = depth >= 2 ? XFASTINT (indices[2]) : 0;
2702 c = MAKE_CHAR (charset, c1, c2);
2704 if (NILP (elt))
2705 elt = XCHAR_TABLE (subtable)->defalt;
2706 if (NILP (elt))
2707 elt = Faref (table, make_number (c));
2709 if (c_function)
2710 (*c_function) (arg, make_number (c), elt);
2711 else
2712 call2 (function, make_number (c), elt);
2717 static void void_call2 P_ ((Lisp_Object a, Lisp_Object b, Lisp_Object c));
2718 static void
2719 void_call2 (a, b, c)
2720 Lisp_Object a, b, c;
2722 call2 (a, b, c);
2725 DEFUN ("map-char-table", Fmap_char_table, Smap_char_table,
2726 2, 2, 0,
2727 doc: /* Call FUNCTION for each (normal and generic) characters in CHAR-TABLE.
2728 FUNCTION is called with two arguments--a key and a value.
2729 The key is always a possible IDX argument to `aref'. */)
2730 (function, char_table)
2731 Lisp_Object function, char_table;
2733 /* The depth of char table is at most 3. */
2734 Lisp_Object indices[3];
2736 CHECK_CHAR_TABLE (char_table);
2738 /* When Lisp_Object is represented as a union, `call2' cannot directly
2739 be passed to map_char_table because it returns a Lisp_Object rather
2740 than returning nothing.
2741 Casting leads to crashes on some architectures. -stef */
2742 map_char_table (void_call2, Qnil, char_table, char_table, function, 0, indices);
2743 return Qnil;
2746 /* Return a value for character C in char-table TABLE. Store the
2747 actual index for that value in *IDX. Ignore the default value of
2748 TABLE. */
2750 Lisp_Object
2751 char_table_ref_and_index (table, c, idx)
2752 Lisp_Object table;
2753 int c, *idx;
2755 int charset, c1, c2;
2756 Lisp_Object elt;
2758 if (SINGLE_BYTE_CHAR_P (c))
2760 *idx = c;
2761 return XCHAR_TABLE (table)->contents[c];
2763 SPLIT_CHAR (c, charset, c1, c2);
2764 elt = XCHAR_TABLE (table)->contents[charset + 128];
2765 *idx = MAKE_CHAR (charset, 0, 0);
2766 if (!SUB_CHAR_TABLE_P (elt))
2767 return elt;
2768 if (c1 < 32 || NILP (XCHAR_TABLE (elt)->contents[c1]))
2769 return XCHAR_TABLE (elt)->defalt;
2770 elt = XCHAR_TABLE (elt)->contents[c1];
2771 *idx = MAKE_CHAR (charset, c1, 0);
2772 if (!SUB_CHAR_TABLE_P (elt))
2773 return elt;
2774 if (c2 < 32 || NILP (XCHAR_TABLE (elt)->contents[c2]))
2775 return XCHAR_TABLE (elt)->defalt;
2776 *idx = c;
2777 return XCHAR_TABLE (elt)->contents[c2];
2781 /* ARGSUSED */
2782 Lisp_Object
2783 nconc2 (s1, s2)
2784 Lisp_Object s1, s2;
2786 #ifdef NO_ARG_ARRAY
2787 Lisp_Object args[2];
2788 args[0] = s1;
2789 args[1] = s2;
2790 return Fnconc (2, args);
2791 #else
2792 return Fnconc (2, &s1);
2793 #endif /* NO_ARG_ARRAY */
2796 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2797 doc: /* Concatenate any number of lists by altering them.
2798 Only the last argument is not altered, and need not be a list.
2799 usage: (nconc &rest LISTS) */)
2800 (nargs, args)
2801 int nargs;
2802 Lisp_Object *args;
2804 register int argnum;
2805 register Lisp_Object tail, tem, val;
2807 val = tail = Qnil;
2809 for (argnum = 0; argnum < nargs; argnum++)
2811 tem = args[argnum];
2812 if (NILP (tem)) continue;
2814 if (NILP (val))
2815 val = tem;
2817 if (argnum + 1 == nargs) break;
2819 if (!CONSP (tem))
2820 tem = wrong_type_argument (Qlistp, tem);
2822 while (CONSP (tem))
2824 tail = tem;
2825 tem = XCDR (tail);
2826 QUIT;
2829 tem = args[argnum + 1];
2830 Fsetcdr (tail, tem);
2831 if (NILP (tem))
2832 args[argnum + 1] = tail;
2835 return val;
2838 /* This is the guts of all mapping functions.
2839 Apply FN to each element of SEQ, one by one,
2840 storing the results into elements of VALS, a C vector of Lisp_Objects.
2841 LENI is the length of VALS, which should also be the length of SEQ. */
2843 static void
2844 mapcar1 (leni, vals, fn, seq)
2845 int leni;
2846 Lisp_Object *vals;
2847 Lisp_Object fn, seq;
2849 register Lisp_Object tail;
2850 Lisp_Object dummy;
2851 register int i;
2852 struct gcpro gcpro1, gcpro2, gcpro3;
2854 if (vals)
2856 /* Don't let vals contain any garbage when GC happens. */
2857 for (i = 0; i < leni; i++)
2858 vals[i] = Qnil;
2860 GCPRO3 (dummy, fn, seq);
2861 gcpro1.var = vals;
2862 gcpro1.nvars = leni;
2864 else
2865 GCPRO2 (fn, seq);
2866 /* We need not explicitly protect `tail' because it is used only on lists, and
2867 1) lists are not relocated and 2) the list is marked via `seq' so will not be freed */
2869 if (VECTORP (seq))
2871 for (i = 0; i < leni; i++)
2873 dummy = XVECTOR (seq)->contents[i];
2874 dummy = call1 (fn, dummy);
2875 if (vals)
2876 vals[i] = dummy;
2879 else if (BOOL_VECTOR_P (seq))
2881 for (i = 0; i < leni; i++)
2883 int byte;
2884 byte = XBOOL_VECTOR (seq)->data[i / BITS_PER_CHAR];
2885 if (byte & (1 << (i % BITS_PER_CHAR)))
2886 dummy = Qt;
2887 else
2888 dummy = Qnil;
2890 dummy = call1 (fn, dummy);
2891 if (vals)
2892 vals[i] = dummy;
2895 else if (STRINGP (seq))
2897 int i_byte;
2899 for (i = 0, i_byte = 0; i < leni;)
2901 int c;
2902 int i_before = i;
2904 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2905 XSETFASTINT (dummy, c);
2906 dummy = call1 (fn, dummy);
2907 if (vals)
2908 vals[i_before] = dummy;
2911 else /* Must be a list, since Flength did not get an error */
2913 tail = seq;
2914 for (i = 0; i < leni; i++)
2916 dummy = call1 (fn, Fcar (tail));
2917 if (vals)
2918 vals[i] = dummy;
2919 tail = XCDR (tail);
2923 UNGCPRO;
2926 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2927 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2928 In between each pair of results, stick in SEPARATOR. Thus, " " as
2929 SEPARATOR results in spaces between the values returned by FUNCTION.
2930 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2931 (function, sequence, separator)
2932 Lisp_Object function, sequence, separator;
2934 Lisp_Object len;
2935 register int leni;
2936 int nargs;
2937 register Lisp_Object *args;
2938 register int i;
2939 struct gcpro gcpro1;
2941 len = Flength (sequence);
2942 leni = XINT (len);
2943 nargs = leni + leni - 1;
2944 if (nargs < 0) return build_string ("");
2946 args = (Lisp_Object *) alloca (nargs * sizeof (Lisp_Object));
2948 GCPRO1 (separator);
2949 mapcar1 (leni, args, function, sequence);
2950 UNGCPRO;
2952 for (i = leni - 1; i >= 0; i--)
2953 args[i + i] = args[i];
2955 for (i = 1; i < nargs; i += 2)
2956 args[i] = separator;
2958 return Fconcat (nargs, args);
2961 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2962 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2963 The result is a list just as long as SEQUENCE.
2964 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2965 (function, sequence)
2966 Lisp_Object function, sequence;
2968 register Lisp_Object len;
2969 register int leni;
2970 register Lisp_Object *args;
2972 len = Flength (sequence);
2973 leni = XFASTINT (len);
2974 args = (Lisp_Object *) alloca (leni * sizeof (Lisp_Object));
2976 mapcar1 (leni, args, function, sequence);
2978 return Flist (leni, args);
2981 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2982 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2983 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2984 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2985 (function, sequence)
2986 Lisp_Object function, sequence;
2988 register int leni;
2990 leni = XFASTINT (Flength (sequence));
2991 mapcar1 (leni, 0, function, sequence);
2993 return sequence;
2996 /* Anything that calls this function must protect from GC! */
2998 DEFUN ("y-or-n-p", Fy_or_n_p, Sy_or_n_p, 1, 1, 0,
2999 doc: /* Ask user a "y or n" question. Return t if answer is "y".
3000 Takes one argument, which is the string to display to ask the question.
3001 It should end in a space; `y-or-n-p' adds `(y or n) ' to it.
3002 No confirmation of the answer is requested; a single character is enough.
3003 Also accepts Space to mean yes, or Delete to mean no. \(Actually, it uses
3004 the bindings in `query-replace-map'; see the documentation of that variable
3005 for more information. In this case, the useful bindings are `act', `skip',
3006 `recenter', and `quit'.\)
3008 Under a windowing system a dialog box will be used if `last-nonmenu-event'
3009 is nil and `use-dialog-box' is non-nil. */)
3010 (prompt)
3011 Lisp_Object prompt;
3013 register Lisp_Object obj, key, def, map;
3014 register int answer;
3015 Lisp_Object xprompt;
3016 Lisp_Object args[2];
3017 struct gcpro gcpro1, gcpro2;
3018 int count = SPECPDL_INDEX ();
3020 specbind (Qcursor_in_echo_area, Qt);
3022 map = Fsymbol_value (intern ("query-replace-map"));
3024 CHECK_STRING (prompt);
3025 xprompt = prompt;
3026 GCPRO2 (prompt, xprompt);
3028 #ifdef HAVE_X_WINDOWS
3029 if (display_hourglass_p)
3030 cancel_hourglass ();
3031 #endif
3033 while (1)
3036 #ifdef HAVE_MENUS
3037 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3038 && use_dialog_box
3039 && have_menus_p ())
3041 Lisp_Object pane, menu;
3042 redisplay_preserve_echo_area (3);
3043 pane = Fcons (Fcons (build_string ("Yes"), Qt),
3044 Fcons (Fcons (build_string ("No"), Qnil),
3045 Qnil));
3046 menu = Fcons (prompt, pane);
3047 obj = Fx_popup_dialog (Qt, menu);
3048 answer = !NILP (obj);
3049 break;
3051 #endif /* HAVE_MENUS */
3052 cursor_in_echo_area = 1;
3053 choose_minibuf_frame ();
3056 Lisp_Object pargs[3];
3058 /* Colorize prompt according to `minibuffer-prompt' face. */
3059 pargs[0] = build_string ("%s(y or n) ");
3060 pargs[1] = intern ("face");
3061 pargs[2] = intern ("minibuffer-prompt");
3062 args[0] = Fpropertize (3, pargs);
3063 args[1] = xprompt;
3064 Fmessage (2, args);
3067 if (minibuffer_auto_raise)
3069 Lisp_Object mini_frame;
3071 mini_frame = WINDOW_FRAME (XWINDOW (minibuf_window));
3073 Fraise_frame (mini_frame);
3076 obj = read_filtered_event (1, 0, 0, 0);
3077 cursor_in_echo_area = 0;
3078 /* If we need to quit, quit with cursor_in_echo_area = 0. */
3079 QUIT;
3081 key = Fmake_vector (make_number (1), obj);
3082 def = Flookup_key (map, key, Qt);
3084 if (EQ (def, intern ("skip")))
3086 answer = 0;
3087 break;
3089 else if (EQ (def, intern ("act")))
3091 answer = 1;
3092 break;
3094 else if (EQ (def, intern ("recenter")))
3096 Frecenter (Qnil);
3097 xprompt = prompt;
3098 continue;
3100 else if (EQ (def, intern ("quit")))
3101 Vquit_flag = Qt;
3102 /* We want to exit this command for exit-prefix,
3103 and this is the only way to do it. */
3104 else if (EQ (def, intern ("exit-prefix")))
3105 Vquit_flag = Qt;
3107 QUIT;
3109 /* If we don't clear this, then the next call to read_char will
3110 return quit_char again, and we'll enter an infinite loop. */
3111 Vquit_flag = Qnil;
3113 Fding (Qnil);
3114 Fdiscard_input ();
3115 if (EQ (xprompt, prompt))
3117 args[0] = build_string ("Please answer y or n. ");
3118 args[1] = prompt;
3119 xprompt = Fconcat (2, args);
3122 UNGCPRO;
3124 if (! noninteractive)
3126 cursor_in_echo_area = -1;
3127 message_with_string (answer ? "%s(y or n) y" : "%s(y or n) n",
3128 xprompt, 0);
3131 unbind_to (count, Qnil);
3132 return answer ? Qt : Qnil;
3135 /* This is how C code calls `yes-or-no-p' and allows the user
3136 to redefined it.
3138 Anything that calls this function must protect from GC! */
3140 Lisp_Object
3141 do_yes_or_no_p (prompt)
3142 Lisp_Object prompt;
3144 return call1 (intern ("yes-or-no-p"), prompt);
3147 /* Anything that calls this function must protect from GC! */
3149 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
3150 doc: /* Ask user a yes-or-no question. Return t if answer is yes.
3151 Takes one argument, which is the string to display to ask the question.
3152 It should end in a space; `yes-or-no-p' adds `(yes or no) ' to it.
3153 The user must confirm the answer with RET,
3154 and can edit it until it has been confirmed.
3156 Under a windowing system a dialog box will be used if `last-nonmenu-event'
3157 is nil, and `use-dialog-box' is non-nil. */)
3158 (prompt)
3159 Lisp_Object prompt;
3161 register Lisp_Object ans;
3162 Lisp_Object args[2];
3163 struct gcpro gcpro1;
3165 CHECK_STRING (prompt);
3167 #ifdef HAVE_MENUS
3168 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3169 && use_dialog_box
3170 && have_menus_p ())
3172 Lisp_Object pane, menu, obj;
3173 redisplay_preserve_echo_area (4);
3174 pane = Fcons (Fcons (build_string ("Yes"), Qt),
3175 Fcons (Fcons (build_string ("No"), Qnil),
3176 Qnil));
3177 GCPRO1 (pane);
3178 menu = Fcons (prompt, pane);
3179 obj = Fx_popup_dialog (Qt, menu);
3180 UNGCPRO;
3181 return obj;
3183 #endif /* HAVE_MENUS */
3185 args[0] = prompt;
3186 args[1] = build_string ("(yes or no) ");
3187 prompt = Fconcat (2, args);
3189 GCPRO1 (prompt);
3191 while (1)
3193 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
3194 Qyes_or_no_p_history, Qnil,
3195 Qnil));
3196 if (SCHARS (ans) == 3 && !strcmp (SDATA (ans), "yes"))
3198 UNGCPRO;
3199 return Qt;
3201 if (SCHARS (ans) == 2 && !strcmp (SDATA (ans), "no"))
3203 UNGCPRO;
3204 return Qnil;
3207 Fding (Qnil);
3208 Fdiscard_input ();
3209 message ("Please answer yes or no.");
3210 Fsleep_for (make_number (2), Qnil);
3214 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
3215 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
3217 Each of the three load averages is multiplied by 100, then converted
3218 to integer.
3220 When USE-FLOATS is non-nil, floats will be used instead of integers.
3221 These floats are not multiplied by 100.
3223 If the 5-minute or 15-minute load averages are not available, return a
3224 shortened list, containing only those averages which are available.
3226 An error is thrown if the load average can't be obtained. In some
3227 cases making it work would require Emacs being installed setuid or
3228 setgid so that it can read kernel information, and that usually isn't
3229 advisable. */)
3230 (use_floats)
3231 Lisp_Object use_floats;
3233 double load_ave[3];
3234 int loads = getloadavg (load_ave, 3);
3235 Lisp_Object ret = Qnil;
3237 if (loads < 0)
3238 error ("load-average not implemented for this operating system");
3240 while (loads-- > 0)
3242 Lisp_Object load = (NILP (use_floats) ?
3243 make_number ((int) (100.0 * load_ave[loads]))
3244 : make_float (load_ave[loads]));
3245 ret = Fcons (load, ret);
3248 return ret;
3251 Lisp_Object Vfeatures, Qsubfeatures;
3252 extern Lisp_Object Vafter_load_alist;
3254 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
3255 doc: /* Returns t if FEATURE is present in this Emacs.
3257 Use this to conditionalize execution of lisp code based on the
3258 presence or absence of emacs or environment extensions.
3259 Use `provide' to declare that a feature is available. This function
3260 looks at the value of the variable `features'. The optional argument
3261 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
3262 (feature, subfeature)
3263 Lisp_Object feature, subfeature;
3265 register Lisp_Object tem;
3266 CHECK_SYMBOL (feature);
3267 tem = Fmemq (feature, Vfeatures);
3268 if (!NILP (tem) && !NILP (subfeature))
3269 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
3270 return (NILP (tem)) ? Qnil : Qt;
3273 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
3274 doc: /* Announce that FEATURE is a feature of the current Emacs.
3275 The optional argument SUBFEATURES should be a list of symbols listing
3276 particular subfeatures supported in this version of FEATURE. */)
3277 (feature, subfeatures)
3278 Lisp_Object feature, subfeatures;
3280 register Lisp_Object tem;
3281 CHECK_SYMBOL (feature);
3282 CHECK_LIST (subfeatures);
3283 if (!NILP (Vautoload_queue))
3284 Vautoload_queue = Fcons (Fcons (Vfeatures, Qnil), Vautoload_queue);
3285 tem = Fmemq (feature, Vfeatures);
3286 if (NILP (tem))
3287 Vfeatures = Fcons (feature, Vfeatures);
3288 if (!NILP (subfeatures))
3289 Fput (feature, Qsubfeatures, subfeatures);
3290 LOADHIST_ATTACH (Fcons (Qprovide, feature));
3292 /* Run any load-hooks for this file. */
3293 tem = Fassq (feature, Vafter_load_alist);
3294 if (CONSP (tem))
3295 Fprogn (XCDR (tem));
3297 return feature;
3300 /* `require' and its subroutines. */
3302 /* List of features currently being require'd, innermost first. */
3304 Lisp_Object require_nesting_list;
3306 Lisp_Object
3307 require_unwind (old_value)
3308 Lisp_Object old_value;
3310 return require_nesting_list = old_value;
3313 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
3314 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
3315 If FEATURE is not a member of the list `features', then the feature
3316 is not loaded; so load the file FILENAME.
3317 If FILENAME is omitted, the printname of FEATURE is used as the file name,
3318 and `load' will try to load this name appended with the suffix `.elc',
3319 `.el' or the unmodified name, in that order.
3320 If the optional third argument NOERROR is non-nil,
3321 then return nil if the file is not found instead of signaling an error.
3322 Normally the return value is FEATURE.
3323 The normal messages at start and end of loading FILENAME are suppressed. */)
3324 (feature, filename, noerror)
3325 Lisp_Object feature, filename, noerror;
3327 register Lisp_Object tem;
3328 struct gcpro gcpro1, gcpro2;
3330 CHECK_SYMBOL (feature);
3332 tem = Fmemq (feature, Vfeatures);
3334 if (NILP (tem))
3336 int count = SPECPDL_INDEX ();
3337 int nesting = 0;
3339 LOADHIST_ATTACH (Fcons (Qrequire, feature));
3341 /* This is to make sure that loadup.el gives a clear picture
3342 of what files are preloaded and when. */
3343 if (! NILP (Vpurify_flag))
3344 error ("(require %s) while preparing to dump",
3345 SDATA (SYMBOL_NAME (feature)));
3347 /* A certain amount of recursive `require' is legitimate,
3348 but if we require the same feature recursively 3 times,
3349 signal an error. */
3350 tem = require_nesting_list;
3351 while (! NILP (tem))
3353 if (! NILP (Fequal (feature, XCAR (tem))))
3354 nesting++;
3355 tem = XCDR (tem);
3357 if (nesting > 3)
3358 error ("Recursive `require' for feature `%s'",
3359 SDATA (SYMBOL_NAME (feature)));
3361 /* Update the list for any nested `require's that occur. */
3362 record_unwind_protect (require_unwind, require_nesting_list);
3363 require_nesting_list = Fcons (feature, require_nesting_list);
3365 /* Value saved here is to be restored into Vautoload_queue */
3366 record_unwind_protect (un_autoload, Vautoload_queue);
3367 Vautoload_queue = Qt;
3369 /* Load the file. */
3370 GCPRO2 (feature, filename);
3371 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
3372 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
3373 UNGCPRO;
3375 /* If load failed entirely, return nil. */
3376 if (NILP (tem))
3377 return unbind_to (count, Qnil);
3379 tem = Fmemq (feature, Vfeatures);
3380 if (NILP (tem))
3381 error ("Required feature `%s' was not provided",
3382 SDATA (SYMBOL_NAME (feature)));
3384 /* Once loading finishes, don't undo it. */
3385 Vautoload_queue = Qt;
3386 feature = unbind_to (count, feature);
3389 return feature;
3392 /* Primitives for work of the "widget" library.
3393 In an ideal world, this section would not have been necessary.
3394 However, lisp function calls being as slow as they are, it turns
3395 out that some functions in the widget library (wid-edit.el) are the
3396 bottleneck of Widget operation. Here is their translation to C,
3397 for the sole reason of efficiency. */
3399 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
3400 doc: /* Return non-nil if PLIST has the property PROP.
3401 PLIST is a property list, which is a list of the form
3402 \(PROP1 VALUE1 PROP2 VALUE2 ...\). PROP is a symbol.
3403 Unlike `plist-get', this allows you to distinguish between a missing
3404 property and a property with the value nil.
3405 The value is actually the tail of PLIST whose car is PROP. */)
3406 (plist, prop)
3407 Lisp_Object plist, prop;
3409 while (CONSP (plist) && !EQ (XCAR (plist), prop))
3411 QUIT;
3412 plist = XCDR (plist);
3413 plist = CDR (plist);
3415 return plist;
3418 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
3419 doc: /* In WIDGET, set PROPERTY to VALUE.
3420 The value can later be retrieved with `widget-get'. */)
3421 (widget, property, value)
3422 Lisp_Object widget, property, value;
3424 CHECK_CONS (widget);
3425 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
3426 return value;
3429 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
3430 doc: /* In WIDGET, get the value of PROPERTY.
3431 The value could either be specified when the widget was created, or
3432 later with `widget-put'. */)
3433 (widget, property)
3434 Lisp_Object widget, property;
3436 Lisp_Object tmp;
3438 while (1)
3440 if (NILP (widget))
3441 return Qnil;
3442 CHECK_CONS (widget);
3443 tmp = Fplist_member (XCDR (widget), property);
3444 if (CONSP (tmp))
3446 tmp = XCDR (tmp);
3447 return CAR (tmp);
3449 tmp = XCAR (widget);
3450 if (NILP (tmp))
3451 return Qnil;
3452 widget = Fget (tmp, Qwidget_type);
3456 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
3457 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
3458 ARGS are passed as extra arguments to the function.
3459 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
3460 (nargs, args)
3461 int nargs;
3462 Lisp_Object *args;
3464 /* This function can GC. */
3465 Lisp_Object newargs[3];
3466 struct gcpro gcpro1, gcpro2;
3467 Lisp_Object result;
3469 newargs[0] = Fwidget_get (args[0], args[1]);
3470 newargs[1] = args[0];
3471 newargs[2] = Flist (nargs - 2, args + 2);
3472 GCPRO2 (newargs[0], newargs[2]);
3473 result = Fapply (3, newargs);
3474 UNGCPRO;
3475 return result;
3478 #ifdef HAVE_LANGINFO_CODESET
3479 #include <langinfo.h>
3480 #endif
3482 DEFUN ("langinfo", Flanginfo, Slanginfo, 1, 1, 0,
3483 doc: /* Access locale data ITEM, if available.
3485 ITEM may be one of the following:
3487 `codeset', returning the character set as a string (locale item CODESET);
3489 `days', returning a 7-element vector of day names (locale items DAY_n);
3491 `months', returning a 12-element vector of month names (locale items MON_n);
3493 `paper', returning a list (WIDTH, HEIGHT) for the default paper size,
3494 where the width and height are in mm (locale items PAPER_WIDTH,
3495 PAPER_HEIGHT).
3497 If the system can't provide such information through a call to
3498 nl_langinfo(3) or if ITEM isn't from the list above, return nil.
3500 See also Info node `(libc)Locales'.
3502 The data read from the system are decoded using `locale-coding-system'. */)
3503 (item)
3504 Lisp_Object item;
3506 char *str = NULL;
3507 #ifdef HAVE_LANGINFO_CODESET
3508 Lisp_Object val;
3509 if (EQ (item, Qcodeset))
3511 str = nl_langinfo (CODESET);
3512 return build_string (str);
3514 #ifdef DAY_1
3515 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
3517 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
3518 int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
3519 int i;
3520 synchronize_system_time_locale ();
3521 for (i = 0; i < 7; i++)
3523 str = nl_langinfo (days[i]);
3524 val = make_unibyte_string (str, strlen (str));
3525 /* Fixme: Is this coding system necessarily right, even if
3526 it is consistent with CODESET? If not, what to do? */
3527 Faset (v, make_number (i),
3528 code_convert_string_norecord (val, Vlocale_coding_system,
3529 0));
3531 return v;
3533 #endif /* DAY_1 */
3534 #ifdef MON_1
3535 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
3537 struct Lisp_Vector *p = allocate_vector (12);
3538 int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
3539 MON_8, MON_9, MON_10, MON_11, MON_12};
3540 int i;
3541 synchronize_system_time_locale ();
3542 for (i = 0; i < 12; i++)
3544 str = nl_langinfo (months[i]);
3545 val = make_unibyte_string (str, strlen (str));
3546 p->contents[i] =
3547 code_convert_string_norecord (val, Vlocale_coding_system, 0);
3549 XSETVECTOR (val, p);
3550 return val;
3552 #endif /* MON_1 */
3553 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
3554 but is in the locale files. This could be used by ps-print. */
3555 #ifdef PAPER_WIDTH
3556 else if (EQ (item, Qpaper))
3558 return list2 (make_number (nl_langinfo (PAPER_WIDTH)),
3559 make_number (nl_langinfo (PAPER_HEIGHT)));
3561 #endif /* PAPER_WIDTH */
3562 #endif /* HAVE_LANGINFO_CODESET*/
3563 return Qnil;
3566 /* base64 encode/decode functions (RFC 2045).
3567 Based on code from GNU recode. */
3569 #define MIME_LINE_LENGTH 76
3571 #define IS_ASCII(Character) \
3572 ((Character) < 128)
3573 #define IS_BASE64(Character) \
3574 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
3575 #define IS_BASE64_IGNORABLE(Character) \
3576 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
3577 || (Character) == '\f' || (Character) == '\r')
3579 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
3580 character or return retval if there are no characters left to
3581 process. */
3582 #define READ_QUADRUPLET_BYTE(retval) \
3583 do \
3585 if (i == length) \
3587 if (nchars_return) \
3588 *nchars_return = nchars; \
3589 return (retval); \
3591 c = from[i++]; \
3593 while (IS_BASE64_IGNORABLE (c))
3595 /* Don't use alloca for regions larger than this, lest we overflow
3596 their stack. */
3597 #define MAX_ALLOCA 16*1024
3599 /* Table of characters coding the 64 values. */
3600 static char base64_value_to_char[64] =
3602 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
3603 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
3604 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
3605 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
3606 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
3607 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
3608 '8', '9', '+', '/' /* 60-63 */
3611 /* Table of base64 values for first 128 characters. */
3612 static short base64_char_to_value[128] =
3614 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
3615 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
3616 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
3617 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
3618 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
3619 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
3620 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
3621 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
3622 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
3623 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
3624 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
3625 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
3626 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
3629 /* The following diagram shows the logical steps by which three octets
3630 get transformed into four base64 characters.
3632 .--------. .--------. .--------.
3633 |aaaaaabb| |bbbbcccc| |ccdddddd|
3634 `--------' `--------' `--------'
3635 6 2 4 4 2 6
3636 .--------+--------+--------+--------.
3637 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
3638 `--------+--------+--------+--------'
3640 .--------+--------+--------+--------.
3641 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
3642 `--------+--------+--------+--------'
3644 The octets are divided into 6 bit chunks, which are then encoded into
3645 base64 characters. */
3648 static int base64_encode_1 P_ ((const char *, char *, int, int, int));
3649 static int base64_decode_1 P_ ((const char *, char *, int, int, int *));
3651 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
3652 2, 3, "r",
3653 doc: /* Base64-encode the region between BEG and END.
3654 Return the length of the encoded text.
3655 Optional third argument NO-LINE-BREAK means do not break long lines
3656 into shorter lines. */)
3657 (beg, end, no_line_break)
3658 Lisp_Object beg, end, no_line_break;
3660 char *encoded;
3661 int allength, length;
3662 int ibeg, iend, encoded_length;
3663 int old_pos = PT;
3665 validate_region (&beg, &end);
3667 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3668 iend = CHAR_TO_BYTE (XFASTINT (end));
3669 move_gap_both (XFASTINT (beg), ibeg);
3671 /* We need to allocate enough room for encoding the text.
3672 We need 33 1/3% more space, plus a newline every 76
3673 characters, and then we round up. */
3674 length = iend - ibeg;
3675 allength = length + length/3 + 1;
3676 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3678 if (allength <= MAX_ALLOCA)
3679 encoded = (char *) alloca (allength);
3680 else
3681 encoded = (char *) xmalloc (allength);
3682 encoded_length = base64_encode_1 (BYTE_POS_ADDR (ibeg), encoded, length,
3683 NILP (no_line_break),
3684 !NILP (current_buffer->enable_multibyte_characters));
3685 if (encoded_length > allength)
3686 abort ();
3688 if (encoded_length < 0)
3690 /* The encoding wasn't possible. */
3691 if (length > MAX_ALLOCA)
3692 xfree (encoded);
3693 error ("Multibyte character in data for base64 encoding");
3696 /* Now we have encoded the region, so we insert the new contents
3697 and delete the old. (Insert first in order to preserve markers.) */
3698 SET_PT_BOTH (XFASTINT (beg), ibeg);
3699 insert (encoded, encoded_length);
3700 if (allength > MAX_ALLOCA)
3701 xfree (encoded);
3702 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
3704 /* If point was outside of the region, restore it exactly; else just
3705 move to the beginning of the region. */
3706 if (old_pos >= XFASTINT (end))
3707 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
3708 else if (old_pos > XFASTINT (beg))
3709 old_pos = XFASTINT (beg);
3710 SET_PT (old_pos);
3712 /* We return the length of the encoded text. */
3713 return make_number (encoded_length);
3716 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
3717 1, 2, 0,
3718 doc: /* Base64-encode STRING and return the result.
3719 Optional second argument NO-LINE-BREAK means do not break long lines
3720 into shorter lines. */)
3721 (string, no_line_break)
3722 Lisp_Object string, no_line_break;
3724 int allength, length, encoded_length;
3725 char *encoded;
3726 Lisp_Object encoded_string;
3728 CHECK_STRING (string);
3730 /* We need to allocate enough room for encoding the text.
3731 We need 33 1/3% more space, plus a newline every 76
3732 characters, and then we round up. */
3733 length = SBYTES (string);
3734 allength = length + length/3 + 1;
3735 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3737 /* We need to allocate enough room for decoding the text. */
3738 if (allength <= MAX_ALLOCA)
3739 encoded = (char *) alloca (allength);
3740 else
3741 encoded = (char *) xmalloc (allength);
3743 encoded_length = base64_encode_1 (SDATA (string),
3744 encoded, length, NILP (no_line_break),
3745 STRING_MULTIBYTE (string));
3746 if (encoded_length > allength)
3747 abort ();
3749 if (encoded_length < 0)
3751 /* The encoding wasn't possible. */
3752 if (length > MAX_ALLOCA)
3753 xfree (encoded);
3754 error ("Multibyte character in data for base64 encoding");
3757 encoded_string = make_unibyte_string (encoded, encoded_length);
3758 if (allength > MAX_ALLOCA)
3759 xfree (encoded);
3761 return encoded_string;
3764 static int
3765 base64_encode_1 (from, to, length, line_break, multibyte)
3766 const char *from;
3767 char *to;
3768 int length;
3769 int line_break;
3770 int multibyte;
3772 int counter = 0, i = 0;
3773 char *e = to;
3774 int c;
3775 unsigned int value;
3776 int bytes;
3778 while (i < length)
3780 if (multibyte)
3782 c = STRING_CHAR_AND_LENGTH (from + i, length - i, bytes);
3783 if (c >= 256)
3784 return -1;
3785 i += bytes;
3787 else
3788 c = from[i++];
3790 /* Wrap line every 76 characters. */
3792 if (line_break)
3794 if (counter < MIME_LINE_LENGTH / 4)
3795 counter++;
3796 else
3798 *e++ = '\n';
3799 counter = 1;
3803 /* Process first byte of a triplet. */
3805 *e++ = base64_value_to_char[0x3f & c >> 2];
3806 value = (0x03 & c) << 4;
3808 /* Process second byte of a triplet. */
3810 if (i == length)
3812 *e++ = base64_value_to_char[value];
3813 *e++ = '=';
3814 *e++ = '=';
3815 break;
3818 if (multibyte)
3820 c = STRING_CHAR_AND_LENGTH (from + i, length - i, bytes);
3821 if (c >= 256)
3822 return -1;
3823 i += bytes;
3825 else
3826 c = from[i++];
3828 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3829 value = (0x0f & c) << 2;
3831 /* Process third byte of a triplet. */
3833 if (i == length)
3835 *e++ = base64_value_to_char[value];
3836 *e++ = '=';
3837 break;
3840 if (multibyte)
3842 c = STRING_CHAR_AND_LENGTH (from + i, length - i, bytes);
3843 if (c >= 256)
3844 return -1;
3845 i += bytes;
3847 else
3848 c = from[i++];
3850 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3851 *e++ = base64_value_to_char[0x3f & c];
3854 return e - to;
3858 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3859 2, 2, "r",
3860 doc: /* Base64-decode the region between BEG and END.
3861 Return the length of the decoded text.
3862 If the region can't be decoded, signal an error and don't modify the buffer. */)
3863 (beg, end)
3864 Lisp_Object beg, end;
3866 int ibeg, iend, length, allength;
3867 char *decoded;
3868 int old_pos = PT;
3869 int decoded_length;
3870 int inserted_chars;
3871 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
3873 validate_region (&beg, &end);
3875 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3876 iend = CHAR_TO_BYTE (XFASTINT (end));
3878 length = iend - ibeg;
3880 /* We need to allocate enough room for decoding the text. If we are
3881 working on a multibyte buffer, each decoded code may occupy at
3882 most two bytes. */
3883 allength = multibyte ? length * 2 : length;
3884 if (allength <= MAX_ALLOCA)
3885 decoded = (char *) alloca (allength);
3886 else
3887 decoded = (char *) xmalloc (allength);
3889 move_gap_both (XFASTINT (beg), ibeg);
3890 decoded_length = base64_decode_1 (BYTE_POS_ADDR (ibeg), decoded, length,
3891 multibyte, &inserted_chars);
3892 if (decoded_length > allength)
3893 abort ();
3895 if (decoded_length < 0)
3897 /* The decoding wasn't possible. */
3898 if (allength > MAX_ALLOCA)
3899 xfree (decoded);
3900 error ("Invalid base64 data");
3903 /* Now we have decoded the region, so we insert the new contents
3904 and delete the old. (Insert first in order to preserve markers.) */
3905 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3906 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3907 if (allength > MAX_ALLOCA)
3908 xfree (decoded);
3909 /* Delete the original text. */
3910 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3911 iend + decoded_length, 1);
3913 /* If point was outside of the region, restore it exactly; else just
3914 move to the beginning of the region. */
3915 if (old_pos >= XFASTINT (end))
3916 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3917 else if (old_pos > XFASTINT (beg))
3918 old_pos = XFASTINT (beg);
3919 SET_PT (old_pos > ZV ? ZV : old_pos);
3921 return make_number (inserted_chars);
3924 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3925 1, 1, 0,
3926 doc: /* Base64-decode STRING and return the result. */)
3927 (string)
3928 Lisp_Object string;
3930 char *decoded;
3931 int length, decoded_length;
3932 Lisp_Object decoded_string;
3934 CHECK_STRING (string);
3936 length = SBYTES (string);
3937 /* We need to allocate enough room for decoding the text. */
3938 if (length <= MAX_ALLOCA)
3939 decoded = (char *) alloca (length);
3940 else
3941 decoded = (char *) xmalloc (length);
3943 /* The decoded result should be unibyte. */
3944 decoded_length = base64_decode_1 (SDATA (string), decoded, length,
3945 0, NULL);
3946 if (decoded_length > length)
3947 abort ();
3948 else if (decoded_length >= 0)
3949 decoded_string = make_unibyte_string (decoded, decoded_length);
3950 else
3951 decoded_string = Qnil;
3953 if (length > MAX_ALLOCA)
3954 xfree (decoded);
3955 if (!STRINGP (decoded_string))
3956 error ("Invalid base64 data");
3958 return decoded_string;
3961 /* Base64-decode the data at FROM of LENGHT bytes into TO. If
3962 MULTIBYTE is nonzero, the decoded result should be in multibyte
3963 form. If NCHARS_RETRUN is not NULL, store the number of produced
3964 characters in *NCHARS_RETURN. */
3966 static int
3967 base64_decode_1 (from, to, length, multibyte, nchars_return)
3968 const char *from;
3969 char *to;
3970 int length;
3971 int multibyte;
3972 int *nchars_return;
3974 int i = 0;
3975 char *e = to;
3976 unsigned char c;
3977 unsigned long value;
3978 int nchars = 0;
3980 while (1)
3982 /* Process first byte of a quadruplet. */
3984 READ_QUADRUPLET_BYTE (e-to);
3986 if (!IS_BASE64 (c))
3987 return -1;
3988 value = base64_char_to_value[c] << 18;
3990 /* Process second byte of a quadruplet. */
3992 READ_QUADRUPLET_BYTE (-1);
3994 if (!IS_BASE64 (c))
3995 return -1;
3996 value |= base64_char_to_value[c] << 12;
3998 c = (unsigned char) (value >> 16);
3999 if (multibyte)
4000 e += CHAR_STRING (c, e);
4001 else
4002 *e++ = c;
4003 nchars++;
4005 /* Process third byte of a quadruplet. */
4007 READ_QUADRUPLET_BYTE (-1);
4009 if (c == '=')
4011 READ_QUADRUPLET_BYTE (-1);
4013 if (c != '=')
4014 return -1;
4015 continue;
4018 if (!IS_BASE64 (c))
4019 return -1;
4020 value |= base64_char_to_value[c] << 6;
4022 c = (unsigned char) (0xff & value >> 8);
4023 if (multibyte)
4024 e += CHAR_STRING (c, e);
4025 else
4026 *e++ = c;
4027 nchars++;
4029 /* Process fourth byte of a quadruplet. */
4031 READ_QUADRUPLET_BYTE (-1);
4033 if (c == '=')
4034 continue;
4036 if (!IS_BASE64 (c))
4037 return -1;
4038 value |= base64_char_to_value[c];
4040 c = (unsigned char) (0xff & value);
4041 if (multibyte)
4042 e += CHAR_STRING (c, e);
4043 else
4044 *e++ = c;
4045 nchars++;
4051 /***********************************************************************
4052 ***** *****
4053 ***** Hash Tables *****
4054 ***** *****
4055 ***********************************************************************/
4057 /* Implemented by gerd@gnu.org. This hash table implementation was
4058 inspired by CMUCL hash tables. */
4060 /* Ideas:
4062 1. For small tables, association lists are probably faster than
4063 hash tables because they have lower overhead.
4065 For uses of hash tables where the O(1) behavior of table
4066 operations is not a requirement, it might therefore be a good idea
4067 not to hash. Instead, we could just do a linear search in the
4068 key_and_value vector of the hash table. This could be done
4069 if a `:linear-search t' argument is given to make-hash-table. */
4072 /* The list of all weak hash tables. Don't staticpro this one. */
4074 Lisp_Object Vweak_hash_tables;
4076 /* Various symbols. */
4078 Lisp_Object Qhash_table_p, Qeq, Qeql, Qequal, Qkey, Qvalue;
4079 Lisp_Object QCtest, QCsize, QCrehash_size, QCrehash_threshold, QCweakness;
4080 Lisp_Object Qhash_table_test, Qkey_or_value, Qkey_and_value;
4082 /* Function prototypes. */
4084 static struct Lisp_Hash_Table *check_hash_table P_ ((Lisp_Object));
4085 static int get_key_arg P_ ((Lisp_Object, int, Lisp_Object *, char *));
4086 static void maybe_resize_hash_table P_ ((struct Lisp_Hash_Table *));
4087 static int cmpfn_eql P_ ((struct Lisp_Hash_Table *, Lisp_Object, unsigned,
4088 Lisp_Object, unsigned));
4089 static int cmpfn_equal P_ ((struct Lisp_Hash_Table *, Lisp_Object, unsigned,
4090 Lisp_Object, unsigned));
4091 static int cmpfn_user_defined P_ ((struct Lisp_Hash_Table *, Lisp_Object,
4092 unsigned, Lisp_Object, unsigned));
4093 static unsigned hashfn_eq P_ ((struct Lisp_Hash_Table *, Lisp_Object));
4094 static unsigned hashfn_eql P_ ((struct Lisp_Hash_Table *, Lisp_Object));
4095 static unsigned hashfn_equal P_ ((struct Lisp_Hash_Table *, Lisp_Object));
4096 static unsigned hashfn_user_defined P_ ((struct Lisp_Hash_Table *,
4097 Lisp_Object));
4098 static unsigned sxhash_string P_ ((unsigned char *, int));
4099 static unsigned sxhash_list P_ ((Lisp_Object, int));
4100 static unsigned sxhash_vector P_ ((Lisp_Object, int));
4101 static unsigned sxhash_bool_vector P_ ((Lisp_Object));
4102 static int sweep_weak_table P_ ((struct Lisp_Hash_Table *, int));
4106 /***********************************************************************
4107 Utilities
4108 ***********************************************************************/
4110 /* If OBJ is a Lisp hash table, return a pointer to its struct
4111 Lisp_Hash_Table. Otherwise, signal an error. */
4113 static struct Lisp_Hash_Table *
4114 check_hash_table (obj)
4115 Lisp_Object obj;
4117 CHECK_HASH_TABLE (obj);
4118 return XHASH_TABLE (obj);
4122 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
4123 number. */
4126 next_almost_prime (n)
4127 int n;
4129 if (n % 2 == 0)
4130 n += 1;
4131 if (n % 3 == 0)
4132 n += 2;
4133 if (n % 7 == 0)
4134 n += 4;
4135 return n;
4139 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
4140 which USED[I] is non-zero. If found at index I in ARGS, set
4141 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
4142 -1. This function is used to extract a keyword/argument pair from
4143 a DEFUN parameter list. */
4145 static int
4146 get_key_arg (key, nargs, args, used)
4147 Lisp_Object key;
4148 int nargs;
4149 Lisp_Object *args;
4150 char *used;
4152 int i;
4154 for (i = 0; i < nargs - 1; ++i)
4155 if (!used[i] && EQ (args[i], key))
4156 break;
4158 if (i >= nargs - 1)
4159 i = -1;
4160 else
4162 used[i++] = 1;
4163 used[i] = 1;
4166 return i;
4170 /* Return a Lisp vector which has the same contents as VEC but has
4171 size NEW_SIZE, NEW_SIZE >= VEC->size. Entries in the resulting
4172 vector that are not copied from VEC are set to INIT. */
4174 Lisp_Object
4175 larger_vector (vec, new_size, init)
4176 Lisp_Object vec;
4177 int new_size;
4178 Lisp_Object init;
4180 struct Lisp_Vector *v;
4181 int i, old_size;
4183 xassert (VECTORP (vec));
4184 old_size = XVECTOR (vec)->size;
4185 xassert (new_size >= old_size);
4187 v = allocate_vector (new_size);
4188 bcopy (XVECTOR (vec)->contents, v->contents,
4189 old_size * sizeof *v->contents);
4190 for (i = old_size; i < new_size; ++i)
4191 v->contents[i] = init;
4192 XSETVECTOR (vec, v);
4193 return vec;
4197 /***********************************************************************
4198 Low-level Functions
4199 ***********************************************************************/
4201 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
4202 HASH2 in hash table H using `eql'. Value is non-zero if KEY1 and
4203 KEY2 are the same. */
4205 static int
4206 cmpfn_eql (h, key1, hash1, key2, hash2)
4207 struct Lisp_Hash_Table *h;
4208 Lisp_Object key1, key2;
4209 unsigned hash1, hash2;
4211 return (FLOATP (key1)
4212 && FLOATP (key2)
4213 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
4217 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
4218 HASH2 in hash table H using `equal'. Value is non-zero if KEY1 and
4219 KEY2 are the same. */
4221 static int
4222 cmpfn_equal (h, key1, hash1, key2, hash2)
4223 struct Lisp_Hash_Table *h;
4224 Lisp_Object key1, key2;
4225 unsigned hash1, hash2;
4227 return hash1 == hash2 && !NILP (Fequal (key1, key2));
4231 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
4232 HASH2 in hash table H using H->user_cmp_function. Value is non-zero
4233 if KEY1 and KEY2 are the same. */
4235 static int
4236 cmpfn_user_defined (h, key1, hash1, key2, hash2)
4237 struct Lisp_Hash_Table *h;
4238 Lisp_Object key1, key2;
4239 unsigned hash1, hash2;
4241 if (hash1 == hash2)
4243 Lisp_Object args[3];
4245 args[0] = h->user_cmp_function;
4246 args[1] = key1;
4247 args[2] = key2;
4248 return !NILP (Ffuncall (3, args));
4250 else
4251 return 0;
4255 /* Value is a hash code for KEY for use in hash table H which uses
4256 `eq' to compare keys. The hash code returned is guaranteed to fit
4257 in a Lisp integer. */
4259 static unsigned
4260 hashfn_eq (h, key)
4261 struct Lisp_Hash_Table *h;
4262 Lisp_Object key;
4264 unsigned hash = XUINT (key) ^ XGCTYPE (key);
4265 xassert ((hash & ~VALMASK) == 0);
4266 return hash;
4270 /* Value is a hash code for KEY for use in hash table H which uses
4271 `eql' to compare keys. The hash code returned is guaranteed to fit
4272 in a Lisp integer. */
4274 static unsigned
4275 hashfn_eql (h, key)
4276 struct Lisp_Hash_Table *h;
4277 Lisp_Object key;
4279 unsigned hash;
4280 if (FLOATP (key))
4281 hash = sxhash (key, 0);
4282 else
4283 hash = XUINT (key) ^ XGCTYPE (key);
4284 xassert ((hash & ~VALMASK) == 0);
4285 return hash;
4289 /* Value is a hash code for KEY for use in hash table H which uses
4290 `equal' to compare keys. The hash code returned is guaranteed to fit
4291 in a Lisp integer. */
4293 static unsigned
4294 hashfn_equal (h, key)
4295 struct Lisp_Hash_Table *h;
4296 Lisp_Object key;
4298 unsigned hash = sxhash (key, 0);
4299 xassert ((hash & ~VALMASK) == 0);
4300 return hash;
4304 /* Value is a hash code for KEY for use in hash table H which uses as
4305 user-defined function to compare keys. The hash code returned is
4306 guaranteed to fit in a Lisp integer. */
4308 static unsigned
4309 hashfn_user_defined (h, key)
4310 struct Lisp_Hash_Table *h;
4311 Lisp_Object key;
4313 Lisp_Object args[2], hash;
4315 args[0] = h->user_hash_function;
4316 args[1] = key;
4317 hash = Ffuncall (2, args);
4318 if (!INTEGERP (hash))
4319 Fsignal (Qerror,
4320 list2 (build_string ("Invalid hash code returned from \
4321 user-supplied hash function"),
4322 hash));
4323 return XUINT (hash);
4327 /* Create and initialize a new hash table.
4329 TEST specifies the test the hash table will use to compare keys.
4330 It must be either one of the predefined tests `eq', `eql' or
4331 `equal' or a symbol denoting a user-defined test named TEST with
4332 test and hash functions USER_TEST and USER_HASH.
4334 Give the table initial capacity SIZE, SIZE >= 0, an integer.
4336 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
4337 new size when it becomes full is computed by adding REHASH_SIZE to
4338 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
4339 table's new size is computed by multiplying its old size with
4340 REHASH_SIZE.
4342 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
4343 be resized when the ratio of (number of entries in the table) /
4344 (table size) is >= REHASH_THRESHOLD.
4346 WEAK specifies the weakness of the table. If non-nil, it must be
4347 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
4349 Lisp_Object
4350 make_hash_table (test, size, rehash_size, rehash_threshold, weak,
4351 user_test, user_hash)
4352 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4353 Lisp_Object user_test, user_hash;
4355 struct Lisp_Hash_Table *h;
4356 Lisp_Object table;
4357 int index_size, i, sz;
4359 /* Preconditions. */
4360 xassert (SYMBOLP (test));
4361 xassert (INTEGERP (size) && XINT (size) >= 0);
4362 xassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
4363 || (FLOATP (rehash_size) && XFLOATINT (rehash_size) > 1.0));
4364 xassert (FLOATP (rehash_threshold)
4365 && XFLOATINT (rehash_threshold) > 0
4366 && XFLOATINT (rehash_threshold) <= 1.0);
4368 if (XFASTINT (size) == 0)
4369 size = make_number (1);
4371 /* Allocate a table and initialize it. */
4372 h = allocate_hash_table ();
4374 /* Initialize hash table slots. */
4375 sz = XFASTINT (size);
4377 h->test = test;
4378 if (EQ (test, Qeql))
4380 h->cmpfn = cmpfn_eql;
4381 h->hashfn = hashfn_eql;
4383 else if (EQ (test, Qeq))
4385 h->cmpfn = NULL;
4386 h->hashfn = hashfn_eq;
4388 else if (EQ (test, Qequal))
4390 h->cmpfn = cmpfn_equal;
4391 h->hashfn = hashfn_equal;
4393 else
4395 h->user_cmp_function = user_test;
4396 h->user_hash_function = user_hash;
4397 h->cmpfn = cmpfn_user_defined;
4398 h->hashfn = hashfn_user_defined;
4401 h->weak = weak;
4402 h->rehash_threshold = rehash_threshold;
4403 h->rehash_size = rehash_size;
4404 h->count = make_number (0);
4405 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
4406 h->hash = Fmake_vector (size, Qnil);
4407 h->next = Fmake_vector (size, Qnil);
4408 /* Cast to int here avoids losing with gcc 2.95 on Tru64/Alpha... */
4409 index_size = next_almost_prime ((int) (sz / XFLOATINT (rehash_threshold)));
4410 h->index = Fmake_vector (make_number (index_size), Qnil);
4412 /* Set up the free list. */
4413 for (i = 0; i < sz - 1; ++i)
4414 HASH_NEXT (h, i) = make_number (i + 1);
4415 h->next_free = make_number (0);
4417 XSET_HASH_TABLE (table, h);
4418 xassert (HASH_TABLE_P (table));
4419 xassert (XHASH_TABLE (table) == h);
4421 /* Maybe add this hash table to the list of all weak hash tables. */
4422 if (NILP (h->weak))
4423 h->next_weak = Qnil;
4424 else
4426 h->next_weak = Vweak_hash_tables;
4427 Vweak_hash_tables = table;
4430 return table;
4434 /* Return a copy of hash table H1. Keys and values are not copied,
4435 only the table itself is. */
4437 Lisp_Object
4438 copy_hash_table (h1)
4439 struct Lisp_Hash_Table *h1;
4441 Lisp_Object table;
4442 struct Lisp_Hash_Table *h2;
4443 struct Lisp_Vector *next;
4445 h2 = allocate_hash_table ();
4446 next = h2->vec_next;
4447 bcopy (h1, h2, sizeof *h2);
4448 h2->vec_next = next;
4449 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
4450 h2->hash = Fcopy_sequence (h1->hash);
4451 h2->next = Fcopy_sequence (h1->next);
4452 h2->index = Fcopy_sequence (h1->index);
4453 XSET_HASH_TABLE (table, h2);
4455 /* Maybe add this hash table to the list of all weak hash tables. */
4456 if (!NILP (h2->weak))
4458 h2->next_weak = Vweak_hash_tables;
4459 Vweak_hash_tables = table;
4462 return table;
4466 /* Resize hash table H if it's too full. If H cannot be resized
4467 because it's already too large, throw an error. */
4469 static INLINE void
4470 maybe_resize_hash_table (h)
4471 struct Lisp_Hash_Table *h;
4473 if (NILP (h->next_free))
4475 int old_size = HASH_TABLE_SIZE (h);
4476 int i, new_size, index_size;
4478 if (INTEGERP (h->rehash_size))
4479 new_size = old_size + XFASTINT (h->rehash_size);
4480 else
4481 new_size = old_size * XFLOATINT (h->rehash_size);
4482 new_size = max (old_size + 1, new_size);
4483 index_size = next_almost_prime ((int)
4484 (new_size
4485 / XFLOATINT (h->rehash_threshold)));
4486 if (max (index_size, 2 * new_size) & ~VALMASK)
4487 error ("Hash table too large to resize");
4489 h->key_and_value = larger_vector (h->key_and_value, 2 * new_size, Qnil);
4490 h->next = larger_vector (h->next, new_size, Qnil);
4491 h->hash = larger_vector (h->hash, new_size, Qnil);
4492 h->index = Fmake_vector (make_number (index_size), Qnil);
4494 /* Update the free list. Do it so that new entries are added at
4495 the end of the free list. This makes some operations like
4496 maphash faster. */
4497 for (i = old_size; i < new_size - 1; ++i)
4498 HASH_NEXT (h, i) = make_number (i + 1);
4500 if (!NILP (h->next_free))
4502 Lisp_Object last, next;
4504 last = h->next_free;
4505 while (next = HASH_NEXT (h, XFASTINT (last)),
4506 !NILP (next))
4507 last = next;
4509 HASH_NEXT (h, XFASTINT (last)) = make_number (old_size);
4511 else
4512 XSETFASTINT (h->next_free, old_size);
4514 /* Rehash. */
4515 for (i = 0; i < old_size; ++i)
4516 if (!NILP (HASH_HASH (h, i)))
4518 unsigned hash_code = XUINT (HASH_HASH (h, i));
4519 int start_of_bucket = hash_code % XVECTOR (h->index)->size;
4520 HASH_NEXT (h, i) = HASH_INDEX (h, start_of_bucket);
4521 HASH_INDEX (h, start_of_bucket) = make_number (i);
4527 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
4528 the hash code of KEY. Value is the index of the entry in H
4529 matching KEY, or -1 if not found. */
4532 hash_lookup (h, key, hash)
4533 struct Lisp_Hash_Table *h;
4534 Lisp_Object key;
4535 unsigned *hash;
4537 unsigned hash_code;
4538 int start_of_bucket;
4539 Lisp_Object idx;
4541 hash_code = h->hashfn (h, key);
4542 if (hash)
4543 *hash = hash_code;
4545 start_of_bucket = hash_code % XVECTOR (h->index)->size;
4546 idx = HASH_INDEX (h, start_of_bucket);
4548 /* We need not gcpro idx since it's either an integer or nil. */
4549 while (!NILP (idx))
4551 int i = XFASTINT (idx);
4552 if (EQ (key, HASH_KEY (h, i))
4553 || (h->cmpfn
4554 && h->cmpfn (h, key, hash_code,
4555 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
4556 break;
4557 idx = HASH_NEXT (h, i);
4560 return NILP (idx) ? -1 : XFASTINT (idx);
4564 /* Put an entry into hash table H that associates KEY with VALUE.
4565 HASH is a previously computed hash code of KEY.
4566 Value is the index of the entry in H matching KEY. */
4569 hash_put (h, key, value, hash)
4570 struct Lisp_Hash_Table *h;
4571 Lisp_Object key, value;
4572 unsigned hash;
4574 int start_of_bucket, i;
4576 xassert ((hash & ~VALMASK) == 0);
4578 /* Increment count after resizing because resizing may fail. */
4579 maybe_resize_hash_table (h);
4580 h->count = make_number (XFASTINT (h->count) + 1);
4582 /* Store key/value in the key_and_value vector. */
4583 i = XFASTINT (h->next_free);
4584 h->next_free = HASH_NEXT (h, i);
4585 HASH_KEY (h, i) = key;
4586 HASH_VALUE (h, i) = value;
4588 /* Remember its hash code. */
4589 HASH_HASH (h, i) = make_number (hash);
4591 /* Add new entry to its collision chain. */
4592 start_of_bucket = hash % XVECTOR (h->index)->size;
4593 HASH_NEXT (h, i) = HASH_INDEX (h, start_of_bucket);
4594 HASH_INDEX (h, start_of_bucket) = make_number (i);
4595 return i;
4599 /* Remove the entry matching KEY from hash table H, if there is one. */
4601 void
4602 hash_remove (h, key)
4603 struct Lisp_Hash_Table *h;
4604 Lisp_Object key;
4606 unsigned hash_code;
4607 int start_of_bucket;
4608 Lisp_Object idx, prev;
4610 hash_code = h->hashfn (h, key);
4611 start_of_bucket = hash_code % XVECTOR (h->index)->size;
4612 idx = HASH_INDEX (h, start_of_bucket);
4613 prev = Qnil;
4615 /* We need not gcpro idx, prev since they're either integers or nil. */
4616 while (!NILP (idx))
4618 int i = XFASTINT (idx);
4620 if (EQ (key, HASH_KEY (h, i))
4621 || (h->cmpfn
4622 && h->cmpfn (h, key, hash_code,
4623 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
4625 /* Take entry out of collision chain. */
4626 if (NILP (prev))
4627 HASH_INDEX (h, start_of_bucket) = HASH_NEXT (h, i);
4628 else
4629 HASH_NEXT (h, XFASTINT (prev)) = HASH_NEXT (h, i);
4631 /* Clear slots in key_and_value and add the slots to
4632 the free list. */
4633 HASH_KEY (h, i) = HASH_VALUE (h, i) = HASH_HASH (h, i) = Qnil;
4634 HASH_NEXT (h, i) = h->next_free;
4635 h->next_free = make_number (i);
4636 h->count = make_number (XFASTINT (h->count) - 1);
4637 xassert (XINT (h->count) >= 0);
4638 break;
4640 else
4642 prev = idx;
4643 idx = HASH_NEXT (h, i);
4649 /* Clear hash table H. */
4651 void
4652 hash_clear (h)
4653 struct Lisp_Hash_Table *h;
4655 if (XFASTINT (h->count) > 0)
4657 int i, size = HASH_TABLE_SIZE (h);
4659 for (i = 0; i < size; ++i)
4661 HASH_NEXT (h, i) = i < size - 1 ? make_number (i + 1) : Qnil;
4662 HASH_KEY (h, i) = Qnil;
4663 HASH_VALUE (h, i) = Qnil;
4664 HASH_HASH (h, i) = Qnil;
4667 for (i = 0; i < XVECTOR (h->index)->size; ++i)
4668 XVECTOR (h->index)->contents[i] = Qnil;
4670 h->next_free = make_number (0);
4671 h->count = make_number (0);
4677 /************************************************************************
4678 Weak Hash Tables
4679 ************************************************************************/
4681 /* Sweep weak hash table H. REMOVE_ENTRIES_P non-zero means remove
4682 entries from the table that don't survive the current GC.
4683 REMOVE_ENTRIES_P zero means mark entries that are in use. Value is
4684 non-zero if anything was marked. */
4686 static int
4687 sweep_weak_table (h, remove_entries_p)
4688 struct Lisp_Hash_Table *h;
4689 int remove_entries_p;
4691 int bucket, n, marked;
4693 n = XVECTOR (h->index)->size & ~ARRAY_MARK_FLAG;
4694 marked = 0;
4696 for (bucket = 0; bucket < n; ++bucket)
4698 Lisp_Object idx, next, prev;
4700 /* Follow collision chain, removing entries that
4701 don't survive this garbage collection. */
4702 prev = Qnil;
4703 for (idx = HASH_INDEX (h, bucket); !GC_NILP (idx); idx = next)
4705 int i = XFASTINT (idx);
4706 int key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
4707 int value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
4708 int remove_p;
4710 if (EQ (h->weak, Qkey))
4711 remove_p = !key_known_to_survive_p;
4712 else if (EQ (h->weak, Qvalue))
4713 remove_p = !value_known_to_survive_p;
4714 else if (EQ (h->weak, Qkey_or_value))
4715 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
4716 else if (EQ (h->weak, Qkey_and_value))
4717 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
4718 else
4719 abort ();
4721 next = HASH_NEXT (h, i);
4723 if (remove_entries_p)
4725 if (remove_p)
4727 /* Take out of collision chain. */
4728 if (GC_NILP (prev))
4729 HASH_INDEX (h, bucket) = next;
4730 else
4731 HASH_NEXT (h, XFASTINT (prev)) = next;
4733 /* Add to free list. */
4734 HASH_NEXT (h, i) = h->next_free;
4735 h->next_free = idx;
4737 /* Clear key, value, and hash. */
4738 HASH_KEY (h, i) = HASH_VALUE (h, i) = Qnil;
4739 HASH_HASH (h, i) = Qnil;
4741 h->count = make_number (XFASTINT (h->count) - 1);
4744 else
4746 if (!remove_p)
4748 /* Make sure key and value survive. */
4749 if (!key_known_to_survive_p)
4751 mark_object (&HASH_KEY (h, i));
4752 marked = 1;
4755 if (!value_known_to_survive_p)
4757 mark_object (&HASH_VALUE (h, i));
4758 marked = 1;
4765 return marked;
4768 /* Remove elements from weak hash tables that don't survive the
4769 current garbage collection. Remove weak tables that don't survive
4770 from Vweak_hash_tables. Called from gc_sweep. */
4772 void
4773 sweep_weak_hash_tables ()
4775 Lisp_Object table, used, next;
4776 struct Lisp_Hash_Table *h;
4777 int marked;
4779 /* Mark all keys and values that are in use. Keep on marking until
4780 there is no more change. This is necessary for cases like
4781 value-weak table A containing an entry X -> Y, where Y is used in a
4782 key-weak table B, Z -> Y. If B comes after A in the list of weak
4783 tables, X -> Y might be removed from A, although when looking at B
4784 one finds that it shouldn't. */
4787 marked = 0;
4788 for (table = Vweak_hash_tables; !GC_NILP (table); table = h->next_weak)
4790 h = XHASH_TABLE (table);
4791 if (h->size & ARRAY_MARK_FLAG)
4792 marked |= sweep_weak_table (h, 0);
4795 while (marked);
4797 /* Remove tables and entries that aren't used. */
4798 for (table = Vweak_hash_tables, used = Qnil; !GC_NILP (table); table = next)
4800 h = XHASH_TABLE (table);
4801 next = h->next_weak;
4803 if (h->size & ARRAY_MARK_FLAG)
4805 /* TABLE is marked as used. Sweep its contents. */
4806 if (XFASTINT (h->count) > 0)
4807 sweep_weak_table (h, 1);
4809 /* Add table to the list of used weak hash tables. */
4810 h->next_weak = used;
4811 used = table;
4815 Vweak_hash_tables = used;
4820 /***********************************************************************
4821 Hash Code Computation
4822 ***********************************************************************/
4824 /* Maximum depth up to which to dive into Lisp structures. */
4826 #define SXHASH_MAX_DEPTH 3
4828 /* Maximum length up to which to take list and vector elements into
4829 account. */
4831 #define SXHASH_MAX_LEN 7
4833 /* Combine two integers X and Y for hashing. */
4835 #define SXHASH_COMBINE(X, Y) \
4836 ((((unsigned)(X) << 4) + (((unsigned)(X) >> 24) & 0x0fffffff)) \
4837 + (unsigned)(Y))
4840 /* Return a hash for string PTR which has length LEN. The hash
4841 code returned is guaranteed to fit in a Lisp integer. */
4843 static unsigned
4844 sxhash_string (ptr, len)
4845 unsigned char *ptr;
4846 int len;
4848 unsigned char *p = ptr;
4849 unsigned char *end = p + len;
4850 unsigned char c;
4851 unsigned hash = 0;
4853 while (p != end)
4855 c = *p++;
4856 if (c >= 0140)
4857 c -= 40;
4858 hash = ((hash << 3) + (hash >> 28) + c);
4861 return hash & VALMASK;
4865 /* Return a hash for list LIST. DEPTH is the current depth in the
4866 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4868 static unsigned
4869 sxhash_list (list, depth)
4870 Lisp_Object list;
4871 int depth;
4873 unsigned hash = 0;
4874 int i;
4876 if (depth < SXHASH_MAX_DEPTH)
4877 for (i = 0;
4878 CONSP (list) && i < SXHASH_MAX_LEN;
4879 list = XCDR (list), ++i)
4881 unsigned hash2 = sxhash (XCAR (list), depth + 1);
4882 hash = SXHASH_COMBINE (hash, hash2);
4885 return hash;
4889 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4890 the Lisp structure. */
4892 static unsigned
4893 sxhash_vector (vec, depth)
4894 Lisp_Object vec;
4895 int depth;
4897 unsigned hash = XVECTOR (vec)->size;
4898 int i, n;
4900 n = min (SXHASH_MAX_LEN, XVECTOR (vec)->size);
4901 for (i = 0; i < n; ++i)
4903 unsigned hash2 = sxhash (XVECTOR (vec)->contents[i], depth + 1);
4904 hash = SXHASH_COMBINE (hash, hash2);
4907 return hash;
4911 /* Return a hash for bool-vector VECTOR. */
4913 static unsigned
4914 sxhash_bool_vector (vec)
4915 Lisp_Object vec;
4917 unsigned hash = XBOOL_VECTOR (vec)->size;
4918 int i, n;
4920 n = min (SXHASH_MAX_LEN, XBOOL_VECTOR (vec)->vector_size);
4921 for (i = 0; i < n; ++i)
4922 hash = SXHASH_COMBINE (hash, XBOOL_VECTOR (vec)->data[i]);
4924 return hash;
4928 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4929 structure. Value is an unsigned integer clipped to VALMASK. */
4931 unsigned
4932 sxhash (obj, depth)
4933 Lisp_Object obj;
4934 int depth;
4936 unsigned hash;
4938 if (depth > SXHASH_MAX_DEPTH)
4939 return 0;
4941 switch (XTYPE (obj))
4943 case Lisp_Int:
4944 hash = XUINT (obj);
4945 break;
4947 case Lisp_Symbol:
4948 hash = sxhash_string (SDATA (SYMBOL_NAME (obj)),
4949 SCHARS (SYMBOL_NAME (obj)));
4950 break;
4952 case Lisp_Misc:
4953 hash = XUINT (obj);
4954 break;
4956 case Lisp_String:
4957 hash = sxhash_string (SDATA (obj), SCHARS (obj));
4958 break;
4960 /* This can be everything from a vector to an overlay. */
4961 case Lisp_Vectorlike:
4962 if (VECTORP (obj))
4963 /* According to the CL HyperSpec, two arrays are equal only if
4964 they are `eq', except for strings and bit-vectors. In
4965 Emacs, this works differently. We have to compare element
4966 by element. */
4967 hash = sxhash_vector (obj, depth);
4968 else if (BOOL_VECTOR_P (obj))
4969 hash = sxhash_bool_vector (obj);
4970 else
4971 /* Others are `equal' if they are `eq', so let's take their
4972 address as hash. */
4973 hash = XUINT (obj);
4974 break;
4976 case Lisp_Cons:
4977 hash = sxhash_list (obj, depth);
4978 break;
4980 case Lisp_Float:
4982 unsigned char *p = (unsigned char *) &XFLOAT_DATA (obj);
4983 unsigned char *e = p + sizeof XFLOAT_DATA (obj);
4984 for (hash = 0; p < e; ++p)
4985 hash = SXHASH_COMBINE (hash, *p);
4986 break;
4989 default:
4990 abort ();
4993 return hash & VALMASK;
4998 /***********************************************************************
4999 Lisp Interface
5000 ***********************************************************************/
5003 DEFUN ("sxhash", Fsxhash, Ssxhash, 1, 1, 0,
5004 doc: /* Compute a hash code for OBJ and return it as integer. */)
5005 (obj)
5006 Lisp_Object obj;
5008 unsigned hash = sxhash (obj, 0);;
5009 return make_number (hash);
5013 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
5014 doc: /* Create and return a new hash table.
5016 Arguments are specified as keyword/argument pairs. The following
5017 arguments are defined:
5019 :test TEST -- TEST must be a symbol that specifies how to compare
5020 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
5021 `equal'. User-supplied test and hash functions can be specified via
5022 `define-hash-table-test'.
5024 :size SIZE -- A hint as to how many elements will be put in the table.
5025 Default is 65.
5027 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
5028 fills up. If REHASH-SIZE is an integer, add that many space. If it
5029 is a float, it must be > 1.0, and the new size is computed by
5030 multiplying the old size with that factor. Default is 1.5.
5032 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
5033 Resize the hash table when ratio of the number of entries in the
5034 table. Default is 0.8.
5036 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
5037 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
5038 returned is a weak table. Key/value pairs are removed from a weak
5039 hash table when there are no non-weak references pointing to their
5040 key, value, one of key or value, or both key and value, depending on
5041 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
5042 is nil.
5044 usage: (make-hash-table &rest KEYWORD-ARGS) */)
5045 (nargs, args)
5046 int nargs;
5047 Lisp_Object *args;
5049 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
5050 Lisp_Object user_test, user_hash;
5051 char *used;
5052 int i;
5054 /* The vector `used' is used to keep track of arguments that
5055 have been consumed. */
5056 used = (char *) alloca (nargs * sizeof *used);
5057 bzero (used, nargs * sizeof *used);
5059 /* See if there's a `:test TEST' among the arguments. */
5060 i = get_key_arg (QCtest, nargs, args, used);
5061 test = i < 0 ? Qeql : args[i];
5062 if (!EQ (test, Qeq) && !EQ (test, Qeql) && !EQ (test, Qequal))
5064 /* See if it is a user-defined test. */
5065 Lisp_Object prop;
5067 prop = Fget (test, Qhash_table_test);
5068 if (!CONSP (prop) || !CONSP (XCDR (prop)))
5069 Fsignal (Qerror, list2 (build_string ("Invalid hash table test"),
5070 test));
5071 user_test = XCAR (prop);
5072 user_hash = XCAR (XCDR (prop));
5074 else
5075 user_test = user_hash = Qnil;
5077 /* See if there's a `:size SIZE' argument. */
5078 i = get_key_arg (QCsize, nargs, args, used);
5079 size = i < 0 ? Qnil : args[i];
5080 if (NILP (size))
5081 size = make_number (DEFAULT_HASH_SIZE);
5082 else if (!INTEGERP (size) || XINT (size) < 0)
5083 Fsignal (Qerror,
5084 list2 (build_string ("Invalid hash table size"),
5085 size));
5087 /* Look for `:rehash-size SIZE'. */
5088 i = get_key_arg (QCrehash_size, nargs, args, used);
5089 rehash_size = i < 0 ? make_float (DEFAULT_REHASH_SIZE) : args[i];
5090 if (!NUMBERP (rehash_size)
5091 || (INTEGERP (rehash_size) && XINT (rehash_size) <= 0)
5092 || XFLOATINT (rehash_size) <= 1.0)
5093 Fsignal (Qerror,
5094 list2 (build_string ("Invalid hash table rehash size"),
5095 rehash_size));
5097 /* Look for `:rehash-threshold THRESHOLD'. */
5098 i = get_key_arg (QCrehash_threshold, nargs, args, used);
5099 rehash_threshold = i < 0 ? make_float (DEFAULT_REHASH_THRESHOLD) : args[i];
5100 if (!FLOATP (rehash_threshold)
5101 || XFLOATINT (rehash_threshold) <= 0.0
5102 || XFLOATINT (rehash_threshold) > 1.0)
5103 Fsignal (Qerror,
5104 list2 (build_string ("Invalid hash table rehash threshold"),
5105 rehash_threshold));
5107 /* Look for `:weakness WEAK'. */
5108 i = get_key_arg (QCweakness, nargs, args, used);
5109 weak = i < 0 ? Qnil : args[i];
5110 if (EQ (weak, Qt))
5111 weak = Qkey_and_value;
5112 if (!NILP (weak)
5113 && !EQ (weak, Qkey)
5114 && !EQ (weak, Qvalue)
5115 && !EQ (weak, Qkey_or_value)
5116 && !EQ (weak, Qkey_and_value))
5117 Fsignal (Qerror, list2 (build_string ("Invalid hash table weakness"),
5118 weak));
5120 /* Now, all args should have been used up, or there's a problem. */
5121 for (i = 0; i < nargs; ++i)
5122 if (!used[i])
5123 Fsignal (Qerror,
5124 list2 (build_string ("Invalid argument list"), args[i]));
5126 return make_hash_table (test, size, rehash_size, rehash_threshold, weak,
5127 user_test, user_hash);
5131 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
5132 doc: /* Return a copy of hash table TABLE. */)
5133 (table)
5134 Lisp_Object table;
5136 return copy_hash_table (check_hash_table (table));
5140 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
5141 doc: /* Return the number of elements in TABLE. */)
5142 (table)
5143 Lisp_Object table;
5145 return check_hash_table (table)->count;
5149 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
5150 Shash_table_rehash_size, 1, 1, 0,
5151 doc: /* Return the current rehash size of TABLE. */)
5152 (table)
5153 Lisp_Object table;
5155 return check_hash_table (table)->rehash_size;
5159 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
5160 Shash_table_rehash_threshold, 1, 1, 0,
5161 doc: /* Return the current rehash threshold of TABLE. */)
5162 (table)
5163 Lisp_Object table;
5165 return check_hash_table (table)->rehash_threshold;
5169 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
5170 doc: /* Return the size of TABLE.
5171 The size can be used as an argument to `make-hash-table' to create
5172 a hash table than can hold as many elements of TABLE holds
5173 without need for resizing. */)
5174 (table)
5175 Lisp_Object table;
5177 struct Lisp_Hash_Table *h = check_hash_table (table);
5178 return make_number (HASH_TABLE_SIZE (h));
5182 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
5183 doc: /* Return the test TABLE uses. */)
5184 (table)
5185 Lisp_Object table;
5187 return check_hash_table (table)->test;
5191 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
5192 1, 1, 0,
5193 doc: /* Return the weakness of TABLE. */)
5194 (table)
5195 Lisp_Object table;
5197 return check_hash_table (table)->weak;
5201 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
5202 doc: /* Return t if OBJ is a Lisp hash table object. */)
5203 (obj)
5204 Lisp_Object obj;
5206 return HASH_TABLE_P (obj) ? Qt : Qnil;
5210 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
5211 doc: /* Clear hash table TABLE. */)
5212 (table)
5213 Lisp_Object table;
5215 hash_clear (check_hash_table (table));
5216 return Qnil;
5220 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
5221 doc: /* Look up KEY in TABLE and return its associated value.
5222 If KEY is not found, return DFLT which defaults to nil. */)
5223 (key, table, dflt)
5224 Lisp_Object key, table, dflt;
5226 struct Lisp_Hash_Table *h = check_hash_table (table);
5227 int i = hash_lookup (h, key, NULL);
5228 return i >= 0 ? HASH_VALUE (h, i) : dflt;
5232 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
5233 doc: /* Associate KEY with VALUE in hash table TABLE.
5234 If KEY is already present in table, replace its current value with
5235 VALUE. */)
5236 (key, value, table)
5237 Lisp_Object key, value, table;
5239 struct Lisp_Hash_Table *h = check_hash_table (table);
5240 int i;
5241 unsigned hash;
5243 i = hash_lookup (h, key, &hash);
5244 if (i >= 0)
5245 HASH_VALUE (h, i) = value;
5246 else
5247 hash_put (h, key, value, hash);
5249 return value;
5253 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
5254 doc: /* Remove KEY from TABLE. */)
5255 (key, table)
5256 Lisp_Object key, table;
5258 struct Lisp_Hash_Table *h = check_hash_table (table);
5259 hash_remove (h, key);
5260 return Qnil;
5264 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
5265 doc: /* Call FUNCTION for all entries in hash table TABLE.
5266 FUNCTION is called with 2 arguments KEY and VALUE. */)
5267 (function, table)
5268 Lisp_Object function, table;
5270 struct Lisp_Hash_Table *h = check_hash_table (table);
5271 Lisp_Object args[3];
5272 int i;
5274 for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
5275 if (!NILP (HASH_HASH (h, i)))
5277 args[0] = function;
5278 args[1] = HASH_KEY (h, i);
5279 args[2] = HASH_VALUE (h, i);
5280 Ffuncall (3, args);
5283 return Qnil;
5287 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
5288 Sdefine_hash_table_test, 3, 3, 0,
5289 doc: /* Define a new hash table test with name NAME, a symbol.
5291 In hash tables created with NAME specified as test, use TEST to
5292 compare keys, and HASH for computing hash codes of keys.
5294 TEST must be a function taking two arguments and returning non-nil if
5295 both arguments are the same. HASH must be a function taking one
5296 argument and return an integer that is the hash code of the argument.
5297 Hash code computation should use the whole value range of integers,
5298 including negative integers. */)
5299 (name, test, hash)
5300 Lisp_Object name, test, hash;
5302 return Fput (name, Qhash_table_test, list2 (test, hash));
5307 /************************************************************************
5309 ************************************************************************/
5311 #include "md5.h"
5312 #include "coding.h"
5314 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
5315 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
5317 A message digest is a cryptographic checksum of a document, and the
5318 algorithm to calculate it is defined in RFC 1321.
5320 The two optional arguments START and END are character positions
5321 specifying for which part of OBJECT the message digest should be
5322 computed. If nil or omitted, the digest is computed for the whole
5323 OBJECT.
5325 The MD5 message digest is computed from the result of encoding the
5326 text in a coding system, not directly from the internal Emacs form of
5327 the text. The optional fourth argument CODING-SYSTEM specifies which
5328 coding system to encode the text with. It should be the same coding
5329 system that you used or will use when actually writing the text into a
5330 file.
5332 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
5333 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
5334 system would be chosen by default for writing this text into a file.
5336 If OBJECT is a string, the most preferred coding system (see the
5337 command `prefer-coding-system') is used.
5339 If NOERROR is non-nil, silently assume the `raw-text' coding if the
5340 guesswork fails. Normally, an error is signaled in such case. */)
5341 (object, start, end, coding_system, noerror)
5342 Lisp_Object object, start, end, coding_system, noerror;
5344 unsigned char digest[16];
5345 unsigned char value[33];
5346 int i;
5347 int size;
5348 int size_byte = 0;
5349 int start_char = 0, end_char = 0;
5350 int start_byte = 0, end_byte = 0;
5351 register int b, e;
5352 register struct buffer *bp;
5353 int temp;
5355 if (STRINGP (object))
5357 if (NILP (coding_system))
5359 /* Decide the coding-system to encode the data with. */
5361 if (STRING_MULTIBYTE (object))
5362 /* use default, we can't guess correct value */
5363 coding_system = SYMBOL_VALUE (XCAR (Vcoding_category_list));
5364 else
5365 coding_system = Qraw_text;
5368 if (NILP (Fcoding_system_p (coding_system)))
5370 /* Invalid coding system. */
5372 if (!NILP (noerror))
5373 coding_system = Qraw_text;
5374 else
5375 while (1)
5376 Fsignal (Qcoding_system_error, Fcons (coding_system, Qnil));
5379 if (STRING_MULTIBYTE (object))
5380 object = code_convert_string1 (object, coding_system, Qnil, 1);
5382 size = SCHARS (object);
5383 size_byte = SBYTES (object);
5385 if (!NILP (start))
5387 CHECK_NUMBER (start);
5389 start_char = XINT (start);
5391 if (start_char < 0)
5392 start_char += size;
5394 start_byte = string_char_to_byte (object, start_char);
5397 if (NILP (end))
5399 end_char = size;
5400 end_byte = size_byte;
5402 else
5404 CHECK_NUMBER (end);
5406 end_char = XINT (end);
5408 if (end_char < 0)
5409 end_char += size;
5411 end_byte = string_char_to_byte (object, end_char);
5414 if (!(0 <= start_char && start_char <= end_char && end_char <= size))
5415 args_out_of_range_3 (object, make_number (start_char),
5416 make_number (end_char));
5418 else
5420 CHECK_BUFFER (object);
5422 bp = XBUFFER (object);
5424 if (NILP (start))
5425 b = BUF_BEGV (bp);
5426 else
5428 CHECK_NUMBER_COERCE_MARKER (start);
5429 b = XINT (start);
5432 if (NILP (end))
5433 e = BUF_ZV (bp);
5434 else
5436 CHECK_NUMBER_COERCE_MARKER (end);
5437 e = XINT (end);
5440 if (b > e)
5441 temp = b, b = e, e = temp;
5443 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
5444 args_out_of_range (start, end);
5446 if (NILP (coding_system))
5448 /* Decide the coding-system to encode the data with.
5449 See fileio.c:Fwrite-region */
5451 if (!NILP (Vcoding_system_for_write))
5452 coding_system = Vcoding_system_for_write;
5453 else
5455 int force_raw_text = 0;
5457 coding_system = XBUFFER (object)->buffer_file_coding_system;
5458 if (NILP (coding_system)
5459 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
5461 coding_system = Qnil;
5462 if (NILP (current_buffer->enable_multibyte_characters))
5463 force_raw_text = 1;
5466 if (NILP (coding_system) && !NILP (Fbuffer_file_name(object)))
5468 /* Check file-coding-system-alist. */
5469 Lisp_Object args[4], val;
5471 args[0] = Qwrite_region; args[1] = start; args[2] = end;
5472 args[3] = Fbuffer_file_name(object);
5473 val = Ffind_operation_coding_system (4, args);
5474 if (CONSP (val) && !NILP (XCDR (val)))
5475 coding_system = XCDR (val);
5478 if (NILP (coding_system)
5479 && !NILP (XBUFFER (object)->buffer_file_coding_system))
5481 /* If we still have not decided a coding system, use the
5482 default value of buffer-file-coding-system. */
5483 coding_system = XBUFFER (object)->buffer_file_coding_system;
5486 if (!force_raw_text
5487 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
5488 /* Confirm that VAL can surely encode the current region. */
5489 coding_system = call4 (Vselect_safe_coding_system_function,
5490 make_number (b), make_number (e),
5491 coding_system, Qnil);
5493 if (force_raw_text)
5494 coding_system = Qraw_text;
5497 if (NILP (Fcoding_system_p (coding_system)))
5499 /* Invalid coding system. */
5501 if (!NILP (noerror))
5502 coding_system = Qraw_text;
5503 else
5504 while (1)
5505 Fsignal (Qcoding_system_error, Fcons (coding_system, Qnil));
5509 object = make_buffer_string (b, e, 0);
5511 if (STRING_MULTIBYTE (object))
5512 object = code_convert_string1 (object, coding_system, Qnil, 1);
5515 md5_buffer (SDATA (object) + start_byte,
5516 SBYTES (object) - (size_byte - end_byte),
5517 digest);
5519 for (i = 0; i < 16; i++)
5520 sprintf (&value[2 * i], "%02x", digest[i]);
5521 value[32] = '\0';
5523 return make_string (value, 32);
5527 void
5528 syms_of_fns ()
5530 /* Hash table stuff. */
5531 Qhash_table_p = intern ("hash-table-p");
5532 staticpro (&Qhash_table_p);
5533 Qeq = intern ("eq");
5534 staticpro (&Qeq);
5535 Qeql = intern ("eql");
5536 staticpro (&Qeql);
5537 Qequal = intern ("equal");
5538 staticpro (&Qequal);
5539 QCtest = intern (":test");
5540 staticpro (&QCtest);
5541 QCsize = intern (":size");
5542 staticpro (&QCsize);
5543 QCrehash_size = intern (":rehash-size");
5544 staticpro (&QCrehash_size);
5545 QCrehash_threshold = intern (":rehash-threshold");
5546 staticpro (&QCrehash_threshold);
5547 QCweakness = intern (":weakness");
5548 staticpro (&QCweakness);
5549 Qkey = intern ("key");
5550 staticpro (&Qkey);
5551 Qvalue = intern ("value");
5552 staticpro (&Qvalue);
5553 Qhash_table_test = intern ("hash-table-test");
5554 staticpro (&Qhash_table_test);
5555 Qkey_or_value = intern ("key-or-value");
5556 staticpro (&Qkey_or_value);
5557 Qkey_and_value = intern ("key-and-value");
5558 staticpro (&Qkey_and_value);
5560 defsubr (&Ssxhash);
5561 defsubr (&Smake_hash_table);
5562 defsubr (&Scopy_hash_table);
5563 defsubr (&Shash_table_count);
5564 defsubr (&Shash_table_rehash_size);
5565 defsubr (&Shash_table_rehash_threshold);
5566 defsubr (&Shash_table_size);
5567 defsubr (&Shash_table_test);
5568 defsubr (&Shash_table_weakness);
5569 defsubr (&Shash_table_p);
5570 defsubr (&Sclrhash);
5571 defsubr (&Sgethash);
5572 defsubr (&Sputhash);
5573 defsubr (&Sremhash);
5574 defsubr (&Smaphash);
5575 defsubr (&Sdefine_hash_table_test);
5577 Qstring_lessp = intern ("string-lessp");
5578 staticpro (&Qstring_lessp);
5579 Qprovide = intern ("provide");
5580 staticpro (&Qprovide);
5581 Qrequire = intern ("require");
5582 staticpro (&Qrequire);
5583 Qyes_or_no_p_history = intern ("yes-or-no-p-history");
5584 staticpro (&Qyes_or_no_p_history);
5585 Qcursor_in_echo_area = intern ("cursor-in-echo-area");
5586 staticpro (&Qcursor_in_echo_area);
5587 Qwidget_type = intern ("widget-type");
5588 staticpro (&Qwidget_type);
5590 staticpro (&string_char_byte_cache_string);
5591 string_char_byte_cache_string = Qnil;
5593 require_nesting_list = Qnil;
5594 staticpro (&require_nesting_list);
5596 Fset (Qyes_or_no_p_history, Qnil);
5598 DEFVAR_LISP ("features", &Vfeatures,
5599 doc: /* A list of symbols which are the features of the executing emacs.
5600 Used by `featurep' and `require', and altered by `provide'. */);
5601 Vfeatures = Qnil;
5602 Qsubfeatures = intern ("subfeatures");
5603 staticpro (&Qsubfeatures);
5605 #ifdef HAVE_LANGINFO_CODESET
5606 Qcodeset = intern ("codeset");
5607 staticpro (&Qcodeset);
5608 Qdays = intern ("days");
5609 staticpro (&Qdays);
5610 Qmonths = intern ("months");
5611 staticpro (&Qmonths);
5612 Qpaper = intern ("paper");
5613 staticpro (&Qpaper);
5614 #endif /* HAVE_LANGINFO_CODESET */
5616 DEFVAR_BOOL ("use-dialog-box", &use_dialog_box,
5617 doc: /* *Non-nil means mouse commands use dialog boxes to ask questions.
5618 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
5619 invoked by mouse clicks and mouse menu items. */);
5620 use_dialog_box = 1;
5622 defsubr (&Sidentity);
5623 defsubr (&Srandom);
5624 defsubr (&Slength);
5625 defsubr (&Ssafe_length);
5626 defsubr (&Sstring_bytes);
5627 defsubr (&Sstring_equal);
5628 defsubr (&Scompare_strings);
5629 defsubr (&Sstring_lessp);
5630 defsubr (&Sappend);
5631 defsubr (&Sconcat);
5632 defsubr (&Svconcat);
5633 defsubr (&Scopy_sequence);
5634 defsubr (&Sstring_make_multibyte);
5635 defsubr (&Sstring_make_unibyte);
5636 defsubr (&Sstring_as_multibyte);
5637 defsubr (&Sstring_as_unibyte);
5638 defsubr (&Sstring_to_multibyte);
5639 defsubr (&Scopy_alist);
5640 defsubr (&Ssubstring);
5641 defsubr (&Ssubstring_no_properties);
5642 defsubr (&Snthcdr);
5643 defsubr (&Snth);
5644 defsubr (&Selt);
5645 defsubr (&Smember);
5646 defsubr (&Smemq);
5647 defsubr (&Sassq);
5648 defsubr (&Sassoc);
5649 defsubr (&Srassq);
5650 defsubr (&Srassoc);
5651 defsubr (&Sdelq);
5652 defsubr (&Sdelete);
5653 defsubr (&Snreverse);
5654 defsubr (&Sreverse);
5655 defsubr (&Ssort);
5656 defsubr (&Splist_get);
5657 defsubr (&Sget);
5658 defsubr (&Splist_put);
5659 defsubr (&Sput);
5660 defsubr (&Slax_plist_get);
5661 defsubr (&Slax_plist_put);
5662 defsubr (&Sequal);
5663 defsubr (&Sfillarray);
5664 defsubr (&Schar_table_subtype);
5665 defsubr (&Schar_table_parent);
5666 defsubr (&Sset_char_table_parent);
5667 defsubr (&Schar_table_extra_slot);
5668 defsubr (&Sset_char_table_extra_slot);
5669 defsubr (&Schar_table_range);
5670 defsubr (&Sset_char_table_range);
5671 defsubr (&Sset_char_table_default);
5672 defsubr (&Soptimize_char_table);
5673 defsubr (&Smap_char_table);
5674 defsubr (&Snconc);
5675 defsubr (&Smapcar);
5676 defsubr (&Smapc);
5677 defsubr (&Smapconcat);
5678 defsubr (&Sy_or_n_p);
5679 defsubr (&Syes_or_no_p);
5680 defsubr (&Sload_average);
5681 defsubr (&Sfeaturep);
5682 defsubr (&Srequire);
5683 defsubr (&Sprovide);
5684 defsubr (&Splist_member);
5685 defsubr (&Swidget_put);
5686 defsubr (&Swidget_get);
5687 defsubr (&Swidget_apply);
5688 defsubr (&Sbase64_encode_region);
5689 defsubr (&Sbase64_decode_region);
5690 defsubr (&Sbase64_encode_string);
5691 defsubr (&Sbase64_decode_string);
5692 defsubr (&Smd5);
5693 defsubr (&Slanginfo);
5697 void
5698 init_fns ()
5700 Vweak_hash_tables = Qnil;