Merge: Integer signedness and overflow and related fixes.
[bpt/emacs.git] / src / fns.c
1 /* Random utility Lisp functions.
2 Copyright (C) 1985-1987, 1993-1995, 1997-2011
3 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
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 3 of the License, or
10 (at your option) any later version.
11
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.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
19
20 #include <config.h>
21
22 #include <unistd.h>
23 #include <time.h>
24 #include <setjmp.h>
25
26 #include <intprops.h>
27
28 #include "lisp.h"
29 #include "commands.h"
30 #include "character.h"
31 #include "coding.h"
32 #include "buffer.h"
33 #include "keyboard.h"
34 #include "keymap.h"
35 #include "intervals.h"
36 #include "frame.h"
37 #include "window.h"
38 #include "blockinput.h"
39 #ifdef HAVE_MENUS
40 #if defined (HAVE_X_WINDOWS)
41 #include "xterm.h"
42 #endif
43 #endif /* HAVE_MENUS */
44
45 #ifndef NULL
46 #define NULL ((POINTER_TYPE *)0)
47 #endif
48
49 Lisp_Object Qstring_lessp;
50 static Lisp_Object Qprovide, Qrequire;
51 static Lisp_Object Qyes_or_no_p_history;
52 Lisp_Object Qcursor_in_echo_area;
53 static Lisp_Object Qwidget_type;
54 static Lisp_Object Qcodeset, Qdays, Qmonths, Qpaper;
55
56 static Lisp_Object Qmd5, Qsha1, Qsha224, Qsha256, Qsha384, Qsha512;
57
58 static int internal_equal (Lisp_Object , Lisp_Object, int, int);
59
60 #ifndef HAVE_UNISTD_H
61 extern long time ();
62 #endif
63 \f
64 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
65 doc: /* Return the argument unchanged. */)
66 (Lisp_Object arg)
67 {
68 return arg;
69 }
70
71 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
72 doc: /* Return a pseudo-random number.
73 All integers representable in Lisp are equally likely.
74 On most systems, this is 29 bits' worth.
75 With positive integer LIMIT, return random number in interval [0,LIMIT).
76 With argument t, set the random number seed from the current time and pid.
77 Other values of LIMIT are ignored. */)
78 (Lisp_Object limit)
79 {
80 EMACS_INT val;
81 Lisp_Object lispy_val;
82
83 if (EQ (limit, Qt))
84 {
85 EMACS_TIME t;
86 EMACS_GET_TIME (t);
87 seed_random (getpid () ^ EMACS_SECS (t) ^ EMACS_USECS (t));
88 }
89
90 if (NATNUMP (limit) && XFASTINT (limit) != 0)
91 {
92 /* Try to take our random number from the higher bits of VAL,
93 not the lower, since (says Gentzel) the low bits of `random'
94 are less random than the higher ones. We do this by using the
95 quotient rather than the remainder. At the high end of the RNG
96 it's possible to get a quotient larger than n; discarding
97 these values eliminates the bias that would otherwise appear
98 when using a large n. */
99 EMACS_INT denominator = (INTMASK + 1) / XFASTINT (limit);
100 do
101 val = get_random () / denominator;
102 while (val >= XFASTINT (limit));
103 }
104 else
105 val = get_random ();
106 XSETINT (lispy_val, val);
107 return lispy_val;
108 }
109 \f
110 /* Heuristic on how many iterations of a tight loop can be safely done
111 before it's time to do a QUIT. This must be a power of 2. */
112 enum { QUIT_COUNT_HEURISTIC = 1 << 16 };
113
114 /* Random data-structure functions */
115
116 DEFUN ("length", Flength, Slength, 1, 1, 0,
117 doc: /* Return the length of vector, list or string SEQUENCE.
118 A byte-code function object is also allowed.
119 If the string contains multibyte characters, this is not necessarily
120 the number of bytes in the string; it is the number of characters.
121 To get the number of bytes, use `string-bytes'. */)
122 (register Lisp_Object sequence)
123 {
124 register Lisp_Object val;
125
126 if (STRINGP (sequence))
127 XSETFASTINT (val, SCHARS (sequence));
128 else if (VECTORP (sequence))
129 XSETFASTINT (val, ASIZE (sequence));
130 else if (CHAR_TABLE_P (sequence))
131 XSETFASTINT (val, MAX_CHAR);
132 else if (BOOL_VECTOR_P (sequence))
133 XSETFASTINT (val, XBOOL_VECTOR (sequence)->size);
134 else if (COMPILEDP (sequence))
135 XSETFASTINT (val, ASIZE (sequence) & PSEUDOVECTOR_SIZE_MASK);
136 else if (CONSP (sequence))
137 {
138 EMACS_INT i = 0;
139
140 do
141 {
142 ++i;
143 if ((i & (QUIT_COUNT_HEURISTIC - 1)) == 0)
144 {
145 if (MOST_POSITIVE_FIXNUM < i)
146 error ("List too long");
147 QUIT;
148 }
149 sequence = XCDR (sequence);
150 }
151 while (CONSP (sequence));
152
153 CHECK_LIST_END (sequence, sequence);
154
155 val = make_number (i);
156 }
157 else if (NILP (sequence))
158 XSETFASTINT (val, 0);
159 else
160 wrong_type_argument (Qsequencep, sequence);
161
162 return val;
163 }
164
165 /* This does not check for quits. That is safe since it must terminate. */
166
167 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
168 doc: /* Return the length of a list, but avoid error or infinite loop.
169 This function never gets an error. If LIST is not really a list,
170 it returns 0. If LIST is circular, it returns a finite value
171 which is at least the number of distinct elements. */)
172 (Lisp_Object list)
173 {
174 Lisp_Object tail, halftail;
175 double hilen = 0;
176 uintmax_t lolen = 1;
177
178 if (! CONSP (list))
179 return make_number (0);
180
181 /* halftail is used to detect circular lists. */
182 for (tail = halftail = list; ; )
183 {
184 tail = XCDR (tail);
185 if (! CONSP (tail))
186 break;
187 if (EQ (tail, halftail))
188 break;
189 lolen++;
190 if ((lolen & 1) == 0)
191 {
192 halftail = XCDR (halftail);
193 if ((lolen & (QUIT_COUNT_HEURISTIC - 1)) == 0)
194 {
195 QUIT;
196 if (lolen == 0)
197 hilen += UINTMAX_MAX + 1.0;
198 }
199 }
200 }
201
202 /* If the length does not fit into a fixnum, return a float.
203 On all known practical machines this returns an upper bound on
204 the true length. */
205 return hilen ? make_float (hilen + lolen) : make_fixnum_or_float (lolen);
206 }
207
208 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
209 doc: /* Return the number of bytes in STRING.
210 If STRING is multibyte, this may be greater than the length of STRING. */)
211 (Lisp_Object string)
212 {
213 CHECK_STRING (string);
214 return make_number (SBYTES (string));
215 }
216
217 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
218 doc: /* Return t if two strings have identical contents.
219 Case is significant, but text properties are ignored.
220 Symbols are also allowed; their print names are used instead. */)
221 (register Lisp_Object s1, Lisp_Object s2)
222 {
223 if (SYMBOLP (s1))
224 s1 = SYMBOL_NAME (s1);
225 if (SYMBOLP (s2))
226 s2 = SYMBOL_NAME (s2);
227 CHECK_STRING (s1);
228 CHECK_STRING (s2);
229
230 if (SCHARS (s1) != SCHARS (s2)
231 || SBYTES (s1) != SBYTES (s2)
232 || memcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
233 return Qnil;
234 return Qt;
235 }
236
237 DEFUN ("compare-strings", Fcompare_strings, Scompare_strings, 6, 7, 0,
238 doc: /* Compare the contents of two strings, converting to multibyte if needed.
239 In string STR1, skip the first START1 characters and stop at END1.
240 In string STR2, skip the first START2 characters and stop at END2.
241 END1 and END2 default to the full lengths of the respective strings.
242
243 Case is significant in this comparison if IGNORE-CASE is nil.
244 Unibyte strings are converted to multibyte for comparison.
245
246 The value is t if the strings (or specified portions) match.
247 If string STR1 is less, the value is a negative number N;
248 - 1 - N is the number of characters that match at the beginning.
249 If string STR1 is greater, the value is a positive number N;
250 N - 1 is the number of characters that match at the beginning. */)
251 (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2, Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
252 {
253 register EMACS_INT end1_char, end2_char;
254 register EMACS_INT i1, i1_byte, i2, i2_byte;
255
256 CHECK_STRING (str1);
257 CHECK_STRING (str2);
258 if (NILP (start1))
259 start1 = make_number (0);
260 if (NILP (start2))
261 start2 = make_number (0);
262 CHECK_NATNUM (start1);
263 CHECK_NATNUM (start2);
264 if (! NILP (end1))
265 CHECK_NATNUM (end1);
266 if (! NILP (end2))
267 CHECK_NATNUM (end2);
268
269 i1 = XINT (start1);
270 i2 = XINT (start2);
271
272 i1_byte = string_char_to_byte (str1, i1);
273 i2_byte = string_char_to_byte (str2, i2);
274
275 end1_char = SCHARS (str1);
276 if (! NILP (end1) && end1_char > XINT (end1))
277 end1_char = XINT (end1);
278
279 end2_char = SCHARS (str2);
280 if (! NILP (end2) && end2_char > XINT (end2))
281 end2_char = XINT (end2);
282
283 while (i1 < end1_char && i2 < end2_char)
284 {
285 /* When we find a mismatch, we must compare the
286 characters, not just the bytes. */
287 int c1, c2;
288
289 if (STRING_MULTIBYTE (str1))
290 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c1, str1, i1, i1_byte);
291 else
292 {
293 c1 = SREF (str1, i1++);
294 MAKE_CHAR_MULTIBYTE (c1);
295 }
296
297 if (STRING_MULTIBYTE (str2))
298 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c2, str2, i2, i2_byte);
299 else
300 {
301 c2 = SREF (str2, i2++);
302 MAKE_CHAR_MULTIBYTE (c2);
303 }
304
305 if (c1 == c2)
306 continue;
307
308 if (! NILP (ignore_case))
309 {
310 Lisp_Object tem;
311
312 tem = Fupcase (make_number (c1));
313 c1 = XINT (tem);
314 tem = Fupcase (make_number (c2));
315 c2 = XINT (tem);
316 }
317
318 if (c1 == c2)
319 continue;
320
321 /* Note that I1 has already been incremented
322 past the character that we are comparing;
323 hence we don't add or subtract 1 here. */
324 if (c1 < c2)
325 return make_number (- i1 + XINT (start1));
326 else
327 return make_number (i1 - XINT (start1));
328 }
329
330 if (i1 < end1_char)
331 return make_number (i1 - XINT (start1) + 1);
332 if (i2 < end2_char)
333 return make_number (- i1 + XINT (start1) - 1);
334
335 return Qt;
336 }
337
338 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
339 doc: /* Return t if first arg string is less than second in lexicographic order.
340 Case is significant.
341 Symbols are also allowed; their print names are used instead. */)
342 (register Lisp_Object s1, Lisp_Object s2)
343 {
344 register EMACS_INT end;
345 register EMACS_INT i1, i1_byte, i2, i2_byte;
346
347 if (SYMBOLP (s1))
348 s1 = SYMBOL_NAME (s1);
349 if (SYMBOLP (s2))
350 s2 = SYMBOL_NAME (s2);
351 CHECK_STRING (s1);
352 CHECK_STRING (s2);
353
354 i1 = i1_byte = i2 = i2_byte = 0;
355
356 end = SCHARS (s1);
357 if (end > SCHARS (s2))
358 end = SCHARS (s2);
359
360 while (i1 < end)
361 {
362 /* When we find a mismatch, we must compare the
363 characters, not just the bytes. */
364 int c1, c2;
365
366 FETCH_STRING_CHAR_ADVANCE (c1, s1, i1, i1_byte);
367 FETCH_STRING_CHAR_ADVANCE (c2, s2, i2, i2_byte);
368
369 if (c1 != c2)
370 return c1 < c2 ? Qt : Qnil;
371 }
372 return i1 < SCHARS (s2) ? Qt : Qnil;
373 }
374 \f
375 static Lisp_Object concat (ptrdiff_t nargs, Lisp_Object *args,
376 enum Lisp_Type target_type, int last_special);
377
378 /* ARGSUSED */
379 Lisp_Object
380 concat2 (Lisp_Object s1, Lisp_Object s2)
381 {
382 Lisp_Object args[2];
383 args[0] = s1;
384 args[1] = s2;
385 return concat (2, args, Lisp_String, 0);
386 }
387
388 /* ARGSUSED */
389 Lisp_Object
390 concat3 (Lisp_Object s1, Lisp_Object s2, Lisp_Object s3)
391 {
392 Lisp_Object args[3];
393 args[0] = s1;
394 args[1] = s2;
395 args[2] = s3;
396 return concat (3, args, Lisp_String, 0);
397 }
398
399 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
400 doc: /* Concatenate all the arguments and make the result a list.
401 The result is a list whose elements are the elements of all the arguments.
402 Each argument may be a list, vector or string.
403 The last argument is not copied, just used as the tail of the new list.
404 usage: (append &rest SEQUENCES) */)
405 (ptrdiff_t nargs, Lisp_Object *args)
406 {
407 return concat (nargs, args, Lisp_Cons, 1);
408 }
409
410 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
411 doc: /* Concatenate all the arguments and make the result a string.
412 The result is a string whose elements are the elements of all the arguments.
413 Each argument may be a string or a list or vector of characters (integers).
414 usage: (concat &rest SEQUENCES) */)
415 (ptrdiff_t nargs, Lisp_Object *args)
416 {
417 return concat (nargs, args, Lisp_String, 0);
418 }
419
420 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
421 doc: /* Concatenate all the arguments and make the result a vector.
422 The result is a vector whose elements are the elements of all the arguments.
423 Each argument may be a list, vector or string.
424 usage: (vconcat &rest SEQUENCES) */)
425 (ptrdiff_t nargs, Lisp_Object *args)
426 {
427 return concat (nargs, args, Lisp_Vectorlike, 0);
428 }
429
430
431 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
432 doc: /* Return a copy of a list, vector, string or char-table.
433 The elements of a list or vector are not copied; they are shared
434 with the original. */)
435 (Lisp_Object arg)
436 {
437 if (NILP (arg)) return arg;
438
439 if (CHAR_TABLE_P (arg))
440 {
441 return copy_char_table (arg);
442 }
443
444 if (BOOL_VECTOR_P (arg))
445 {
446 Lisp_Object val;
447 ptrdiff_t size_in_chars
448 = ((XBOOL_VECTOR (arg)->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
449 / BOOL_VECTOR_BITS_PER_CHAR);
450
451 val = Fmake_bool_vector (Flength (arg), Qnil);
452 memcpy (XBOOL_VECTOR (val)->data, XBOOL_VECTOR (arg)->data,
453 size_in_chars);
454 return val;
455 }
456
457 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
458 wrong_type_argument (Qsequencep, arg);
459
460 return concat (1, &arg, CONSP (arg) ? Lisp_Cons : XTYPE (arg), 0);
461 }
462
463 /* This structure holds information of an argument of `concat' that is
464 a string and has text properties to be copied. */
465 struct textprop_rec
466 {
467 ptrdiff_t argnum; /* refer to ARGS (arguments of `concat') */
468 EMACS_INT from; /* refer to ARGS[argnum] (argument string) */
469 EMACS_INT to; /* refer to VAL (the target string) */
470 };
471
472 static Lisp_Object
473 concat (ptrdiff_t nargs, Lisp_Object *args,
474 enum Lisp_Type target_type, int last_special)
475 {
476 Lisp_Object val;
477 register Lisp_Object tail;
478 register Lisp_Object this;
479 EMACS_INT toindex;
480 EMACS_INT toindex_byte = 0;
481 register EMACS_INT result_len;
482 register EMACS_INT result_len_byte;
483 ptrdiff_t argnum;
484 Lisp_Object last_tail;
485 Lisp_Object prev;
486 int some_multibyte;
487 /* When we make a multibyte string, we can't copy text properties
488 while concatenating each string because the length of resulting
489 string can't be decided until we finish the whole concatenation.
490 So, we record strings that have text properties to be copied
491 here, and copy the text properties after the concatenation. */
492 struct textprop_rec *textprops = NULL;
493 /* Number of elements in textprops. */
494 ptrdiff_t num_textprops = 0;
495 USE_SAFE_ALLOCA;
496
497 tail = Qnil;
498
499 /* In append, the last arg isn't treated like the others */
500 if (last_special && nargs > 0)
501 {
502 nargs--;
503 last_tail = args[nargs];
504 }
505 else
506 last_tail = Qnil;
507
508 /* Check each argument. */
509 for (argnum = 0; argnum < nargs; argnum++)
510 {
511 this = args[argnum];
512 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
513 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
514 wrong_type_argument (Qsequencep, this);
515 }
516
517 /* Compute total length in chars of arguments in RESULT_LEN.
518 If desired output is a string, also compute length in bytes
519 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
520 whether the result should be a multibyte string. */
521 result_len_byte = 0;
522 result_len = 0;
523 some_multibyte = 0;
524 for (argnum = 0; argnum < nargs; argnum++)
525 {
526 EMACS_INT len;
527 this = args[argnum];
528 len = XFASTINT (Flength (this));
529 if (target_type == Lisp_String)
530 {
531 /* We must count the number of bytes needed in the string
532 as well as the number of characters. */
533 EMACS_INT i;
534 Lisp_Object ch;
535 int c;
536 EMACS_INT this_len_byte;
537
538 if (VECTORP (this) || COMPILEDP (this))
539 for (i = 0; i < len; i++)
540 {
541 ch = AREF (this, i);
542 CHECK_CHARACTER (ch);
543 c = XFASTINT (ch);
544 this_len_byte = CHAR_BYTES (c);
545 result_len_byte += this_len_byte;
546 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
547 some_multibyte = 1;
548 }
549 else if (BOOL_VECTOR_P (this) && XBOOL_VECTOR (this)->size > 0)
550 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
551 else if (CONSP (this))
552 for (; CONSP (this); this = XCDR (this))
553 {
554 ch = XCAR (this);
555 CHECK_CHARACTER (ch);
556 c = XFASTINT (ch);
557 this_len_byte = CHAR_BYTES (c);
558 result_len_byte += this_len_byte;
559 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
560 some_multibyte = 1;
561 }
562 else if (STRINGP (this))
563 {
564 if (STRING_MULTIBYTE (this))
565 {
566 some_multibyte = 1;
567 result_len_byte += SBYTES (this);
568 }
569 else
570 result_len_byte += count_size_as_multibyte (SDATA (this),
571 SCHARS (this));
572 }
573 }
574
575 result_len += len;
576 if (STRING_BYTES_BOUND < result_len)
577 string_overflow ();
578 }
579
580 if (! some_multibyte)
581 result_len_byte = result_len;
582
583 /* Create the output object. */
584 if (target_type == Lisp_Cons)
585 val = Fmake_list (make_number (result_len), Qnil);
586 else if (target_type == Lisp_Vectorlike)
587 val = Fmake_vector (make_number (result_len), Qnil);
588 else if (some_multibyte)
589 val = make_uninit_multibyte_string (result_len, result_len_byte);
590 else
591 val = make_uninit_string (result_len);
592
593 /* In `append', if all but last arg are nil, return last arg. */
594 if (target_type == Lisp_Cons && EQ (val, Qnil))
595 return last_tail;
596
597 /* Copy the contents of the args into the result. */
598 if (CONSP (val))
599 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
600 else
601 toindex = 0, toindex_byte = 0;
602
603 prev = Qnil;
604 if (STRINGP (val))
605 SAFE_ALLOCA (textprops, struct textprop_rec *, sizeof (struct textprop_rec) * nargs);
606
607 for (argnum = 0; argnum < nargs; argnum++)
608 {
609 Lisp_Object thislen;
610 EMACS_INT thisleni = 0;
611 register EMACS_INT thisindex = 0;
612 register EMACS_INT thisindex_byte = 0;
613
614 this = args[argnum];
615 if (!CONSP (this))
616 thislen = Flength (this), thisleni = XINT (thislen);
617
618 /* Between strings of the same kind, copy fast. */
619 if (STRINGP (this) && STRINGP (val)
620 && STRING_MULTIBYTE (this) == some_multibyte)
621 {
622 EMACS_INT thislen_byte = SBYTES (this);
623
624 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
625 if (! NULL_INTERVAL_P (STRING_INTERVALS (this)))
626 {
627 textprops[num_textprops].argnum = argnum;
628 textprops[num_textprops].from = 0;
629 textprops[num_textprops++].to = toindex;
630 }
631 toindex_byte += thislen_byte;
632 toindex += thisleni;
633 }
634 /* Copy a single-byte string to a multibyte string. */
635 else if (STRINGP (this) && STRINGP (val))
636 {
637 if (! NULL_INTERVAL_P (STRING_INTERVALS (this)))
638 {
639 textprops[num_textprops].argnum = argnum;
640 textprops[num_textprops].from = 0;
641 textprops[num_textprops++].to = toindex;
642 }
643 toindex_byte += copy_text (SDATA (this),
644 SDATA (val) + toindex_byte,
645 SCHARS (this), 0, 1);
646 toindex += thisleni;
647 }
648 else
649 /* Copy element by element. */
650 while (1)
651 {
652 register Lisp_Object elt;
653
654 /* Fetch next element of `this' arg into `elt', or break if
655 `this' is exhausted. */
656 if (NILP (this)) break;
657 if (CONSP (this))
658 elt = XCAR (this), this = XCDR (this);
659 else if (thisindex >= thisleni)
660 break;
661 else if (STRINGP (this))
662 {
663 int c;
664 if (STRING_MULTIBYTE (this))
665 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
666 thisindex,
667 thisindex_byte);
668 else
669 {
670 c = SREF (this, thisindex); thisindex++;
671 if (some_multibyte && !ASCII_CHAR_P (c))
672 c = BYTE8_TO_CHAR (c);
673 }
674 XSETFASTINT (elt, c);
675 }
676 else if (BOOL_VECTOR_P (this))
677 {
678 int byte;
679 byte = XBOOL_VECTOR (this)->data[thisindex / BOOL_VECTOR_BITS_PER_CHAR];
680 if (byte & (1 << (thisindex % BOOL_VECTOR_BITS_PER_CHAR)))
681 elt = Qt;
682 else
683 elt = Qnil;
684 thisindex++;
685 }
686 else
687 {
688 elt = AREF (this, thisindex);
689 thisindex++;
690 }
691
692 /* Store this element into the result. */
693 if (toindex < 0)
694 {
695 XSETCAR (tail, elt);
696 prev = tail;
697 tail = XCDR (tail);
698 }
699 else if (VECTORP (val))
700 {
701 ASET (val, toindex, elt);
702 toindex++;
703 }
704 else
705 {
706 int c;
707 CHECK_CHARACTER (elt);
708 c = XFASTINT (elt);
709 if (some_multibyte)
710 toindex_byte += CHAR_STRING (c, SDATA (val) + toindex_byte);
711 else
712 SSET (val, toindex_byte++, c);
713 toindex++;
714 }
715 }
716 }
717 if (!NILP (prev))
718 XSETCDR (prev, last_tail);
719
720 if (num_textprops > 0)
721 {
722 Lisp_Object props;
723 EMACS_INT last_to_end = -1;
724
725 for (argnum = 0; argnum < num_textprops; argnum++)
726 {
727 this = args[textprops[argnum].argnum];
728 props = text_property_list (this,
729 make_number (0),
730 make_number (SCHARS (this)),
731 Qnil);
732 /* If successive arguments have properties, be sure that the
733 value of `composition' property be the copy. */
734 if (last_to_end == textprops[argnum].to)
735 make_composition_value_copy (props);
736 add_text_properties_from_list (val, props,
737 make_number (textprops[argnum].to));
738 last_to_end = textprops[argnum].to + SCHARS (this);
739 }
740 }
741
742 SAFE_FREE ();
743 return val;
744 }
745 \f
746 static Lisp_Object string_char_byte_cache_string;
747 static EMACS_INT string_char_byte_cache_charpos;
748 static EMACS_INT string_char_byte_cache_bytepos;
749
750 void
751 clear_string_char_byte_cache (void)
752 {
753 string_char_byte_cache_string = Qnil;
754 }
755
756 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
757
758 EMACS_INT
759 string_char_to_byte (Lisp_Object string, EMACS_INT char_index)
760 {
761 EMACS_INT i_byte;
762 EMACS_INT best_below, best_below_byte;
763 EMACS_INT best_above, best_above_byte;
764
765 best_below = best_below_byte = 0;
766 best_above = SCHARS (string);
767 best_above_byte = SBYTES (string);
768 if (best_above == best_above_byte)
769 return char_index;
770
771 if (EQ (string, string_char_byte_cache_string))
772 {
773 if (string_char_byte_cache_charpos < char_index)
774 {
775 best_below = string_char_byte_cache_charpos;
776 best_below_byte = string_char_byte_cache_bytepos;
777 }
778 else
779 {
780 best_above = string_char_byte_cache_charpos;
781 best_above_byte = string_char_byte_cache_bytepos;
782 }
783 }
784
785 if (char_index - best_below < best_above - char_index)
786 {
787 unsigned char *p = SDATA (string) + best_below_byte;
788
789 while (best_below < char_index)
790 {
791 p += BYTES_BY_CHAR_HEAD (*p);
792 best_below++;
793 }
794 i_byte = p - SDATA (string);
795 }
796 else
797 {
798 unsigned char *p = SDATA (string) + best_above_byte;
799
800 while (best_above > char_index)
801 {
802 p--;
803 while (!CHAR_HEAD_P (*p)) p--;
804 best_above--;
805 }
806 i_byte = p - SDATA (string);
807 }
808
809 string_char_byte_cache_bytepos = i_byte;
810 string_char_byte_cache_charpos = char_index;
811 string_char_byte_cache_string = string;
812
813 return i_byte;
814 }
815 \f
816 /* Return the character index corresponding to BYTE_INDEX in STRING. */
817
818 EMACS_INT
819 string_byte_to_char (Lisp_Object string, EMACS_INT byte_index)
820 {
821 EMACS_INT i, i_byte;
822 EMACS_INT best_below, best_below_byte;
823 EMACS_INT best_above, best_above_byte;
824
825 best_below = best_below_byte = 0;
826 best_above = SCHARS (string);
827 best_above_byte = SBYTES (string);
828 if (best_above == best_above_byte)
829 return byte_index;
830
831 if (EQ (string, string_char_byte_cache_string))
832 {
833 if (string_char_byte_cache_bytepos < byte_index)
834 {
835 best_below = string_char_byte_cache_charpos;
836 best_below_byte = string_char_byte_cache_bytepos;
837 }
838 else
839 {
840 best_above = string_char_byte_cache_charpos;
841 best_above_byte = string_char_byte_cache_bytepos;
842 }
843 }
844
845 if (byte_index - best_below_byte < best_above_byte - byte_index)
846 {
847 unsigned char *p = SDATA (string) + best_below_byte;
848 unsigned char *pend = SDATA (string) + byte_index;
849
850 while (p < pend)
851 {
852 p += BYTES_BY_CHAR_HEAD (*p);
853 best_below++;
854 }
855 i = best_below;
856 i_byte = p - SDATA (string);
857 }
858 else
859 {
860 unsigned char *p = SDATA (string) + best_above_byte;
861 unsigned char *pbeg = SDATA (string) + byte_index;
862
863 while (p > pbeg)
864 {
865 p--;
866 while (!CHAR_HEAD_P (*p)) p--;
867 best_above--;
868 }
869 i = best_above;
870 i_byte = p - SDATA (string);
871 }
872
873 string_char_byte_cache_bytepos = i_byte;
874 string_char_byte_cache_charpos = i;
875 string_char_byte_cache_string = string;
876
877 return i;
878 }
879 \f
880 /* Convert STRING to a multibyte string. */
881
882 static Lisp_Object
883 string_make_multibyte (Lisp_Object string)
884 {
885 unsigned char *buf;
886 EMACS_INT nbytes;
887 Lisp_Object ret;
888 USE_SAFE_ALLOCA;
889
890 if (STRING_MULTIBYTE (string))
891 return string;
892
893 nbytes = count_size_as_multibyte (SDATA (string),
894 SCHARS (string));
895 /* If all the chars are ASCII, they won't need any more bytes
896 once converted. In that case, we can return STRING itself. */
897 if (nbytes == SBYTES (string))
898 return string;
899
900 SAFE_ALLOCA (buf, unsigned char *, nbytes);
901 copy_text (SDATA (string), buf, SBYTES (string),
902 0, 1);
903
904 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
905 SAFE_FREE ();
906
907 return ret;
908 }
909
910
911 /* Convert STRING (if unibyte) to a multibyte string without changing
912 the number of characters. Characters 0200 trough 0237 are
913 converted to eight-bit characters. */
914
915 Lisp_Object
916 string_to_multibyte (Lisp_Object string)
917 {
918 unsigned char *buf;
919 EMACS_INT nbytes;
920 Lisp_Object ret;
921 USE_SAFE_ALLOCA;
922
923 if (STRING_MULTIBYTE (string))
924 return string;
925
926 nbytes = count_size_as_multibyte (SDATA (string), SBYTES (string));
927 /* If all the chars are ASCII, they won't need any more bytes once
928 converted. */
929 if (nbytes == SBYTES (string))
930 return make_multibyte_string (SSDATA (string), nbytes, nbytes);
931
932 SAFE_ALLOCA (buf, unsigned char *, nbytes);
933 memcpy (buf, SDATA (string), SBYTES (string));
934 str_to_multibyte (buf, nbytes, SBYTES (string));
935
936 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
937 SAFE_FREE ();
938
939 return ret;
940 }
941
942
943 /* Convert STRING to a single-byte string. */
944
945 Lisp_Object
946 string_make_unibyte (Lisp_Object string)
947 {
948 EMACS_INT nchars;
949 unsigned char *buf;
950 Lisp_Object ret;
951 USE_SAFE_ALLOCA;
952
953 if (! STRING_MULTIBYTE (string))
954 return string;
955
956 nchars = SCHARS (string);
957
958 SAFE_ALLOCA (buf, unsigned char *, nchars);
959 copy_text (SDATA (string), buf, SBYTES (string),
960 1, 0);
961
962 ret = make_unibyte_string ((char *) buf, nchars);
963 SAFE_FREE ();
964
965 return ret;
966 }
967
968 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
969 1, 1, 0,
970 doc: /* Return the multibyte equivalent of STRING.
971 If STRING is unibyte and contains non-ASCII characters, the function
972 `unibyte-char-to-multibyte' is used to convert each unibyte character
973 to a multibyte character. In this case, the returned string is a
974 newly created string with no text properties. If STRING is multibyte
975 or entirely ASCII, it is returned unchanged. In particular, when
976 STRING is unibyte and entirely ASCII, the returned string is unibyte.
977 \(When the characters are all ASCII, Emacs primitives will treat the
978 string the same way whether it is unibyte or multibyte.) */)
979 (Lisp_Object string)
980 {
981 CHECK_STRING (string);
982
983 return string_make_multibyte (string);
984 }
985
986 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
987 1, 1, 0,
988 doc: /* Return the unibyte equivalent of STRING.
989 Multibyte character codes are converted to unibyte according to
990 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
991 If the lookup in the translation table fails, this function takes just
992 the low 8 bits of each character. */)
993 (Lisp_Object string)
994 {
995 CHECK_STRING (string);
996
997 return string_make_unibyte (string);
998 }
999
1000 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
1001 1, 1, 0,
1002 doc: /* Return a unibyte string with the same individual bytes as STRING.
1003 If STRING is unibyte, the result is STRING itself.
1004 Otherwise it is a newly created string, with no text properties.
1005 If STRING is multibyte and contains a character of charset
1006 `eight-bit', it is converted to the corresponding single byte. */)
1007 (Lisp_Object string)
1008 {
1009 CHECK_STRING (string);
1010
1011 if (STRING_MULTIBYTE (string))
1012 {
1013 EMACS_INT bytes = SBYTES (string);
1014 unsigned char *str = (unsigned char *) xmalloc (bytes);
1015
1016 memcpy (str, SDATA (string), bytes);
1017 bytes = str_as_unibyte (str, bytes);
1018 string = make_unibyte_string ((char *) str, bytes);
1019 xfree (str);
1020 }
1021 return string;
1022 }
1023
1024 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1025 1, 1, 0,
1026 doc: /* Return a multibyte string with the same individual bytes as STRING.
1027 If STRING is multibyte, the result is STRING itself.
1028 Otherwise it is a newly created string, with no text properties.
1029
1030 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1031 part of a correct utf-8 sequence), it is converted to the corresponding
1032 multibyte character of charset `eight-bit'.
1033 See also `string-to-multibyte'.
1034
1035 Beware, this often doesn't really do what you think it does.
1036 It is similar to (decode-coding-string STRING 'utf-8-emacs).
1037 If you're not sure, whether to use `string-as-multibyte' or
1038 `string-to-multibyte', use `string-to-multibyte'. */)
1039 (Lisp_Object string)
1040 {
1041 CHECK_STRING (string);
1042
1043 if (! STRING_MULTIBYTE (string))
1044 {
1045 Lisp_Object new_string;
1046 EMACS_INT nchars, nbytes;
1047
1048 parse_str_as_multibyte (SDATA (string),
1049 SBYTES (string),
1050 &nchars, &nbytes);
1051 new_string = make_uninit_multibyte_string (nchars, nbytes);
1052 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1053 if (nbytes != SBYTES (string))
1054 str_as_multibyte (SDATA (new_string), nbytes,
1055 SBYTES (string), NULL);
1056 string = new_string;
1057 STRING_SET_INTERVALS (string, NULL_INTERVAL);
1058 }
1059 return string;
1060 }
1061
1062 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1063 1, 1, 0,
1064 doc: /* Return a multibyte string with the same individual chars as STRING.
1065 If STRING is multibyte, the result is STRING itself.
1066 Otherwise it is a newly created string, with no text properties.
1067
1068 If STRING is unibyte and contains an 8-bit byte, it is converted to
1069 the corresponding multibyte character of charset `eight-bit'.
1070
1071 This differs from `string-as-multibyte' by converting each byte of a correct
1072 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1073 correct sequence. */)
1074 (Lisp_Object string)
1075 {
1076 CHECK_STRING (string);
1077
1078 return string_to_multibyte (string);
1079 }
1080
1081 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1082 1, 1, 0,
1083 doc: /* Return a unibyte string with the same individual chars as STRING.
1084 If STRING is unibyte, the result is STRING itself.
1085 Otherwise it is a newly created string, with no text properties,
1086 where each `eight-bit' character is converted to the corresponding byte.
1087 If STRING contains a non-ASCII, non-`eight-bit' character,
1088 an error is signaled. */)
1089 (Lisp_Object string)
1090 {
1091 CHECK_STRING (string);
1092
1093 if (STRING_MULTIBYTE (string))
1094 {
1095 EMACS_INT chars = SCHARS (string);
1096 unsigned char *str = (unsigned char *) xmalloc (chars);
1097 EMACS_INT converted = str_to_unibyte (SDATA (string), str, chars, 0);
1098
1099 if (converted < chars)
1100 error ("Can't convert the %"pI"dth character to unibyte", converted);
1101 string = make_unibyte_string ((char *) str, chars);
1102 xfree (str);
1103 }
1104 return string;
1105 }
1106
1107 \f
1108 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1109 doc: /* Return a copy of ALIST.
1110 This is an alist which represents the same mapping from objects to objects,
1111 but does not share the alist structure with ALIST.
1112 The objects mapped (cars and cdrs of elements of the alist)
1113 are shared, however.
1114 Elements of ALIST that are not conses are also shared. */)
1115 (Lisp_Object alist)
1116 {
1117 register Lisp_Object tem;
1118
1119 CHECK_LIST (alist);
1120 if (NILP (alist))
1121 return alist;
1122 alist = concat (1, &alist, Lisp_Cons, 0);
1123 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1124 {
1125 register Lisp_Object car;
1126 car = XCAR (tem);
1127
1128 if (CONSP (car))
1129 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1130 }
1131 return alist;
1132 }
1133
1134 DEFUN ("substring", Fsubstring, Ssubstring, 2, 3, 0,
1135 doc: /* Return a new string whose contents are a substring of STRING.
1136 The returned string consists of the characters between index FROM
1137 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1138 zero-indexed: 0 means the first character of STRING. Negative values
1139 are counted from the end of STRING. If TO is nil, the substring runs
1140 to the end of STRING.
1141
1142 The STRING argument may also be a vector. In that case, the return
1143 value is a new vector that contains the elements between index FROM
1144 \(inclusive) and index TO (exclusive) of that vector argument. */)
1145 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1146 {
1147 Lisp_Object res;
1148 EMACS_INT size;
1149 EMACS_INT size_byte = 0;
1150 EMACS_INT from_char, to_char;
1151 EMACS_INT from_byte = 0, to_byte = 0;
1152
1153 CHECK_VECTOR_OR_STRING (string);
1154 CHECK_NUMBER (from);
1155
1156 if (STRINGP (string))
1157 {
1158 size = SCHARS (string);
1159 size_byte = SBYTES (string);
1160 }
1161 else
1162 size = ASIZE (string);
1163
1164 if (NILP (to))
1165 {
1166 to_char = size;
1167 to_byte = size_byte;
1168 }
1169 else
1170 {
1171 CHECK_NUMBER (to);
1172
1173 to_char = XINT (to);
1174 if (to_char < 0)
1175 to_char += size;
1176
1177 if (STRINGP (string))
1178 to_byte = string_char_to_byte (string, to_char);
1179 }
1180
1181 from_char = XINT (from);
1182 if (from_char < 0)
1183 from_char += size;
1184 if (STRINGP (string))
1185 from_byte = string_char_to_byte (string, from_char);
1186
1187 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1188 args_out_of_range_3 (string, make_number (from_char),
1189 make_number (to_char));
1190
1191 if (STRINGP (string))
1192 {
1193 res = make_specified_string (SSDATA (string) + from_byte,
1194 to_char - from_char, to_byte - from_byte,
1195 STRING_MULTIBYTE (string));
1196 copy_text_properties (make_number (from_char), make_number (to_char),
1197 string, make_number (0), res, Qnil);
1198 }
1199 else
1200 res = Fvector (to_char - from_char, &AREF (string, from_char));
1201
1202 return res;
1203 }
1204
1205
1206 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1207 doc: /* Return a substring of STRING, without text properties.
1208 It starts at index FROM and ends before TO.
1209 TO may be nil or omitted; then the substring runs to the end of STRING.
1210 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1211 If FROM or TO is negative, it counts from the end.
1212
1213 With one argument, just copy STRING without its properties. */)
1214 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1215 {
1216 EMACS_INT size, size_byte;
1217 EMACS_INT from_char, to_char;
1218 EMACS_INT from_byte, to_byte;
1219
1220 CHECK_STRING (string);
1221
1222 size = SCHARS (string);
1223 size_byte = SBYTES (string);
1224
1225 if (NILP (from))
1226 from_char = from_byte = 0;
1227 else
1228 {
1229 CHECK_NUMBER (from);
1230 from_char = XINT (from);
1231 if (from_char < 0)
1232 from_char += size;
1233
1234 from_byte = string_char_to_byte (string, from_char);
1235 }
1236
1237 if (NILP (to))
1238 {
1239 to_char = size;
1240 to_byte = size_byte;
1241 }
1242 else
1243 {
1244 CHECK_NUMBER (to);
1245
1246 to_char = XINT (to);
1247 if (to_char < 0)
1248 to_char += size;
1249
1250 to_byte = string_char_to_byte (string, to_char);
1251 }
1252
1253 if (!(0 <= from_char && from_char <= to_char && to_char <= size))
1254 args_out_of_range_3 (string, make_number (from_char),
1255 make_number (to_char));
1256
1257 return make_specified_string (SSDATA (string) + from_byte,
1258 to_char - from_char, to_byte - from_byte,
1259 STRING_MULTIBYTE (string));
1260 }
1261
1262 /* Extract a substring of STRING, giving start and end positions
1263 both in characters and in bytes. */
1264
1265 Lisp_Object
1266 substring_both (Lisp_Object string, EMACS_INT from, EMACS_INT from_byte,
1267 EMACS_INT to, EMACS_INT to_byte)
1268 {
1269 Lisp_Object res;
1270 EMACS_INT size;
1271
1272 CHECK_VECTOR_OR_STRING (string);
1273
1274 size = STRINGP (string) ? SCHARS (string) : ASIZE (string);
1275
1276 if (!(0 <= from && from <= to && to <= size))
1277 args_out_of_range_3 (string, make_number (from), make_number (to));
1278
1279 if (STRINGP (string))
1280 {
1281 res = make_specified_string (SSDATA (string) + from_byte,
1282 to - from, to_byte - from_byte,
1283 STRING_MULTIBYTE (string));
1284 copy_text_properties (make_number (from), make_number (to),
1285 string, make_number (0), res, Qnil);
1286 }
1287 else
1288 res = Fvector (to - from, &AREF (string, from));
1289
1290 return res;
1291 }
1292 \f
1293 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1294 doc: /* Take cdr N times on LIST, return the result. */)
1295 (Lisp_Object n, Lisp_Object list)
1296 {
1297 EMACS_INT i, num;
1298 CHECK_NUMBER (n);
1299 num = XINT (n);
1300 for (i = 0; i < num && !NILP (list); i++)
1301 {
1302 QUIT;
1303 CHECK_LIST_CONS (list, list);
1304 list = XCDR (list);
1305 }
1306 return list;
1307 }
1308
1309 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1310 doc: /* Return the Nth element of LIST.
1311 N counts from zero. If LIST is not that long, nil is returned. */)
1312 (Lisp_Object n, Lisp_Object list)
1313 {
1314 return Fcar (Fnthcdr (n, list));
1315 }
1316
1317 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1318 doc: /* Return element of SEQUENCE at index N. */)
1319 (register Lisp_Object sequence, Lisp_Object n)
1320 {
1321 CHECK_NUMBER (n);
1322 if (CONSP (sequence) || NILP (sequence))
1323 return Fcar (Fnthcdr (n, sequence));
1324
1325 /* Faref signals a "not array" error, so check here. */
1326 CHECK_ARRAY (sequence, Qsequencep);
1327 return Faref (sequence, n);
1328 }
1329
1330 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1331 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1332 The value is actually the tail of LIST whose car is ELT. */)
1333 (register Lisp_Object elt, Lisp_Object list)
1334 {
1335 register Lisp_Object tail;
1336 for (tail = list; CONSP (tail); tail = XCDR (tail))
1337 {
1338 register Lisp_Object tem;
1339 CHECK_LIST_CONS (tail, list);
1340 tem = XCAR (tail);
1341 if (! NILP (Fequal (elt, tem)))
1342 return tail;
1343 QUIT;
1344 }
1345 return Qnil;
1346 }
1347
1348 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1349 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1350 The value is actually the tail of LIST whose car is ELT. */)
1351 (register Lisp_Object elt, Lisp_Object list)
1352 {
1353 while (1)
1354 {
1355 if (!CONSP (list) || EQ (XCAR (list), elt))
1356 break;
1357
1358 list = XCDR (list);
1359 if (!CONSP (list) || EQ (XCAR (list), elt))
1360 break;
1361
1362 list = XCDR (list);
1363 if (!CONSP (list) || EQ (XCAR (list), elt))
1364 break;
1365
1366 list = XCDR (list);
1367 QUIT;
1368 }
1369
1370 CHECK_LIST (list);
1371 return list;
1372 }
1373
1374 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1375 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1376 The value is actually the tail of LIST whose car is ELT. */)
1377 (register Lisp_Object elt, Lisp_Object list)
1378 {
1379 register Lisp_Object tail;
1380
1381 if (!FLOATP (elt))
1382 return Fmemq (elt, list);
1383
1384 for (tail = list; CONSP (tail); tail = XCDR (tail))
1385 {
1386 register Lisp_Object tem;
1387 CHECK_LIST_CONS (tail, list);
1388 tem = XCAR (tail);
1389 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0))
1390 return tail;
1391 QUIT;
1392 }
1393 return Qnil;
1394 }
1395
1396 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1397 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1398 The value is actually the first element of LIST whose car is KEY.
1399 Elements of LIST that are not conses are ignored. */)
1400 (Lisp_Object key, Lisp_Object list)
1401 {
1402 while (1)
1403 {
1404 if (!CONSP (list)
1405 || (CONSP (XCAR (list))
1406 && EQ (XCAR (XCAR (list)), key)))
1407 break;
1408
1409 list = XCDR (list);
1410 if (!CONSP (list)
1411 || (CONSP (XCAR (list))
1412 && EQ (XCAR (XCAR (list)), key)))
1413 break;
1414
1415 list = XCDR (list);
1416 if (!CONSP (list)
1417 || (CONSP (XCAR (list))
1418 && EQ (XCAR (XCAR (list)), key)))
1419 break;
1420
1421 list = XCDR (list);
1422 QUIT;
1423 }
1424
1425 return CAR (list);
1426 }
1427
1428 /* Like Fassq but never report an error and do not allow quits.
1429 Use only on lists known never to be circular. */
1430
1431 Lisp_Object
1432 assq_no_quit (Lisp_Object key, Lisp_Object list)
1433 {
1434 while (CONSP (list)
1435 && (!CONSP (XCAR (list))
1436 || !EQ (XCAR (XCAR (list)), key)))
1437 list = XCDR (list);
1438
1439 return CAR_SAFE (list);
1440 }
1441
1442 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1443 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1444 The value is actually the first element of LIST whose car equals KEY. */)
1445 (Lisp_Object key, Lisp_Object list)
1446 {
1447 Lisp_Object car;
1448
1449 while (1)
1450 {
1451 if (!CONSP (list)
1452 || (CONSP (XCAR (list))
1453 && (car = XCAR (XCAR (list)),
1454 EQ (car, key) || !NILP (Fequal (car, key)))))
1455 break;
1456
1457 list = XCDR (list);
1458 if (!CONSP (list)
1459 || (CONSP (XCAR (list))
1460 && (car = XCAR (XCAR (list)),
1461 EQ (car, key) || !NILP (Fequal (car, key)))))
1462 break;
1463
1464 list = XCDR (list);
1465 if (!CONSP (list)
1466 || (CONSP (XCAR (list))
1467 && (car = XCAR (XCAR (list)),
1468 EQ (car, key) || !NILP (Fequal (car, key)))))
1469 break;
1470
1471 list = XCDR (list);
1472 QUIT;
1473 }
1474
1475 return CAR (list);
1476 }
1477
1478 /* Like Fassoc but never report an error and do not allow quits.
1479 Use only on lists known never to be circular. */
1480
1481 Lisp_Object
1482 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1483 {
1484 while (CONSP (list)
1485 && (!CONSP (XCAR (list))
1486 || (!EQ (XCAR (XCAR (list)), key)
1487 && NILP (Fequal (XCAR (XCAR (list)), key)))))
1488 list = XCDR (list);
1489
1490 return CONSP (list) ? XCAR (list) : Qnil;
1491 }
1492
1493 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1494 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1495 The value is actually the first element of LIST whose cdr is KEY. */)
1496 (register Lisp_Object key, Lisp_Object list)
1497 {
1498 while (1)
1499 {
1500 if (!CONSP (list)
1501 || (CONSP (XCAR (list))
1502 && EQ (XCDR (XCAR (list)), key)))
1503 break;
1504
1505 list = XCDR (list);
1506 if (!CONSP (list)
1507 || (CONSP (XCAR (list))
1508 && EQ (XCDR (XCAR (list)), key)))
1509 break;
1510
1511 list = XCDR (list);
1512 if (!CONSP (list)
1513 || (CONSP (XCAR (list))
1514 && EQ (XCDR (XCAR (list)), key)))
1515 break;
1516
1517 list = XCDR (list);
1518 QUIT;
1519 }
1520
1521 return CAR (list);
1522 }
1523
1524 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1525 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1526 The value is actually the first element of LIST whose cdr equals KEY. */)
1527 (Lisp_Object key, Lisp_Object list)
1528 {
1529 Lisp_Object cdr;
1530
1531 while (1)
1532 {
1533 if (!CONSP (list)
1534 || (CONSP (XCAR (list))
1535 && (cdr = XCDR (XCAR (list)),
1536 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1537 break;
1538
1539 list = XCDR (list);
1540 if (!CONSP (list)
1541 || (CONSP (XCAR (list))
1542 && (cdr = XCDR (XCAR (list)),
1543 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1544 break;
1545
1546 list = XCDR (list);
1547 if (!CONSP (list)
1548 || (CONSP (XCAR (list))
1549 && (cdr = XCDR (XCAR (list)),
1550 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1551 break;
1552
1553 list = XCDR (list);
1554 QUIT;
1555 }
1556
1557 return CAR (list);
1558 }
1559 \f
1560 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1561 doc: /* Delete by side effect any occurrences of ELT as a member of LIST.
1562 The modified LIST is returned. Comparison is done with `eq'.
1563 If the first member of LIST is ELT, there is no way to remove it by side effect;
1564 therefore, write `(setq foo (delq element foo))'
1565 to be sure of changing the value of `foo'. */)
1566 (register Lisp_Object elt, Lisp_Object list)
1567 {
1568 register Lisp_Object tail, prev;
1569 register Lisp_Object tem;
1570
1571 tail = list;
1572 prev = Qnil;
1573 while (!NILP (tail))
1574 {
1575 CHECK_LIST_CONS (tail, list);
1576 tem = XCAR (tail);
1577 if (EQ (elt, tem))
1578 {
1579 if (NILP (prev))
1580 list = XCDR (tail);
1581 else
1582 Fsetcdr (prev, XCDR (tail));
1583 }
1584 else
1585 prev = tail;
1586 tail = XCDR (tail);
1587 QUIT;
1588 }
1589 return list;
1590 }
1591
1592 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1593 doc: /* Delete by side effect any occurrences of ELT as a member of SEQ.
1594 SEQ must be a list, a vector, or a string.
1595 The modified SEQ is returned. Comparison is done with `equal'.
1596 If SEQ is not a list, or the first member of SEQ is ELT, deleting it
1597 is not a side effect; it is simply using a different sequence.
1598 Therefore, write `(setq foo (delete element foo))'
1599 to be sure of changing the value of `foo'. */)
1600 (Lisp_Object elt, Lisp_Object seq)
1601 {
1602 if (VECTORP (seq))
1603 {
1604 EMACS_INT i, n;
1605
1606 for (i = n = 0; i < ASIZE (seq); ++i)
1607 if (NILP (Fequal (AREF (seq, i), elt)))
1608 ++n;
1609
1610 if (n != ASIZE (seq))
1611 {
1612 struct Lisp_Vector *p = allocate_vector (n);
1613
1614 for (i = n = 0; i < ASIZE (seq); ++i)
1615 if (NILP (Fequal (AREF (seq, i), elt)))
1616 p->contents[n++] = AREF (seq, i);
1617
1618 XSETVECTOR (seq, p);
1619 }
1620 }
1621 else if (STRINGP (seq))
1622 {
1623 EMACS_INT i, ibyte, nchars, nbytes, cbytes;
1624 int c;
1625
1626 for (i = nchars = nbytes = ibyte = 0;
1627 i < SCHARS (seq);
1628 ++i, ibyte += cbytes)
1629 {
1630 if (STRING_MULTIBYTE (seq))
1631 {
1632 c = STRING_CHAR (SDATA (seq) + ibyte);
1633 cbytes = CHAR_BYTES (c);
1634 }
1635 else
1636 {
1637 c = SREF (seq, i);
1638 cbytes = 1;
1639 }
1640
1641 if (!INTEGERP (elt) || c != XINT (elt))
1642 {
1643 ++nchars;
1644 nbytes += cbytes;
1645 }
1646 }
1647
1648 if (nchars != SCHARS (seq))
1649 {
1650 Lisp_Object tem;
1651
1652 tem = make_uninit_multibyte_string (nchars, nbytes);
1653 if (!STRING_MULTIBYTE (seq))
1654 STRING_SET_UNIBYTE (tem);
1655
1656 for (i = nchars = nbytes = ibyte = 0;
1657 i < SCHARS (seq);
1658 ++i, ibyte += cbytes)
1659 {
1660 if (STRING_MULTIBYTE (seq))
1661 {
1662 c = STRING_CHAR (SDATA (seq) + ibyte);
1663 cbytes = CHAR_BYTES (c);
1664 }
1665 else
1666 {
1667 c = SREF (seq, i);
1668 cbytes = 1;
1669 }
1670
1671 if (!INTEGERP (elt) || c != XINT (elt))
1672 {
1673 unsigned char *from = SDATA (seq) + ibyte;
1674 unsigned char *to = SDATA (tem) + nbytes;
1675 EMACS_INT n;
1676
1677 ++nchars;
1678 nbytes += cbytes;
1679
1680 for (n = cbytes; n--; )
1681 *to++ = *from++;
1682 }
1683 }
1684
1685 seq = tem;
1686 }
1687 }
1688 else
1689 {
1690 Lisp_Object tail, prev;
1691
1692 for (tail = seq, prev = Qnil; CONSP (tail); tail = XCDR (tail))
1693 {
1694 CHECK_LIST_CONS (tail, seq);
1695
1696 if (!NILP (Fequal (elt, XCAR (tail))))
1697 {
1698 if (NILP (prev))
1699 seq = XCDR (tail);
1700 else
1701 Fsetcdr (prev, XCDR (tail));
1702 }
1703 else
1704 prev = tail;
1705 QUIT;
1706 }
1707 }
1708
1709 return seq;
1710 }
1711
1712 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1713 doc: /* Reverse LIST by modifying cdr pointers.
1714 Return the reversed list. */)
1715 (Lisp_Object list)
1716 {
1717 register Lisp_Object prev, tail, next;
1718
1719 if (NILP (list)) return list;
1720 prev = Qnil;
1721 tail = list;
1722 while (!NILP (tail))
1723 {
1724 QUIT;
1725 CHECK_LIST_CONS (tail, list);
1726 next = XCDR (tail);
1727 Fsetcdr (tail, prev);
1728 prev = tail;
1729 tail = next;
1730 }
1731 return prev;
1732 }
1733
1734 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1735 doc: /* Reverse LIST, copying. Return the reversed list.
1736 See also the function `nreverse', which is used more often. */)
1737 (Lisp_Object list)
1738 {
1739 Lisp_Object new;
1740
1741 for (new = Qnil; CONSP (list); list = XCDR (list))
1742 {
1743 QUIT;
1744 new = Fcons (XCAR (list), new);
1745 }
1746 CHECK_LIST_END (list, list);
1747 return new;
1748 }
1749 \f
1750 Lisp_Object merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred);
1751
1752 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
1753 doc: /* Sort LIST, stably, comparing elements using PREDICATE.
1754 Returns the sorted list. LIST is modified by side effects.
1755 PREDICATE is called with two elements of LIST, and should return non-nil
1756 if the first element should sort before the second. */)
1757 (Lisp_Object list, Lisp_Object predicate)
1758 {
1759 Lisp_Object front, back;
1760 register Lisp_Object len, tem;
1761 struct gcpro gcpro1, gcpro2;
1762 EMACS_INT length;
1763
1764 front = list;
1765 len = Flength (list);
1766 length = XINT (len);
1767 if (length < 2)
1768 return list;
1769
1770 XSETINT (len, (length / 2) - 1);
1771 tem = Fnthcdr (len, list);
1772 back = Fcdr (tem);
1773 Fsetcdr (tem, Qnil);
1774
1775 GCPRO2 (front, back);
1776 front = Fsort (front, predicate);
1777 back = Fsort (back, predicate);
1778 UNGCPRO;
1779 return merge (front, back, predicate);
1780 }
1781
1782 Lisp_Object
1783 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
1784 {
1785 Lisp_Object value;
1786 register Lisp_Object tail;
1787 Lisp_Object tem;
1788 register Lisp_Object l1, l2;
1789 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1790
1791 l1 = org_l1;
1792 l2 = org_l2;
1793 tail = Qnil;
1794 value = Qnil;
1795
1796 /* It is sufficient to protect org_l1 and org_l2.
1797 When l1 and l2 are updated, we copy the new values
1798 back into the org_ vars. */
1799 GCPRO4 (org_l1, org_l2, pred, value);
1800
1801 while (1)
1802 {
1803 if (NILP (l1))
1804 {
1805 UNGCPRO;
1806 if (NILP (tail))
1807 return l2;
1808 Fsetcdr (tail, l2);
1809 return value;
1810 }
1811 if (NILP (l2))
1812 {
1813 UNGCPRO;
1814 if (NILP (tail))
1815 return l1;
1816 Fsetcdr (tail, l1);
1817 return value;
1818 }
1819 tem = call2 (pred, Fcar (l2), Fcar (l1));
1820 if (NILP (tem))
1821 {
1822 tem = l1;
1823 l1 = Fcdr (l1);
1824 org_l1 = l1;
1825 }
1826 else
1827 {
1828 tem = l2;
1829 l2 = Fcdr (l2);
1830 org_l2 = l2;
1831 }
1832 if (NILP (tail))
1833 value = tem;
1834 else
1835 Fsetcdr (tail, tem);
1836 tail = tem;
1837 }
1838 }
1839
1840 \f
1841 /* This does not check for quits. That is safe since it must terminate. */
1842
1843 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
1844 doc: /* Extract a value from a property list.
1845 PLIST is a property list, which is a list of the form
1846 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1847 corresponding to the given PROP, or nil if PROP is not one of the
1848 properties on the list. This function never signals an error. */)
1849 (Lisp_Object plist, Lisp_Object prop)
1850 {
1851 Lisp_Object tail, halftail;
1852
1853 /* halftail is used to detect circular lists. */
1854 tail = halftail = plist;
1855 while (CONSP (tail) && CONSP (XCDR (tail)))
1856 {
1857 if (EQ (prop, XCAR (tail)))
1858 return XCAR (XCDR (tail));
1859
1860 tail = XCDR (XCDR (tail));
1861 halftail = XCDR (halftail);
1862 if (EQ (tail, halftail))
1863 break;
1864
1865 #if 0 /* Unsafe version. */
1866 /* This function can be called asynchronously
1867 (setup_coding_system). Don't QUIT in that case. */
1868 if (!interrupt_input_blocked)
1869 QUIT;
1870 #endif
1871 }
1872
1873 return Qnil;
1874 }
1875
1876 DEFUN ("get", Fget, Sget, 2, 2, 0,
1877 doc: /* Return the value of SYMBOL's PROPNAME property.
1878 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
1879 (Lisp_Object symbol, Lisp_Object propname)
1880 {
1881 CHECK_SYMBOL (symbol);
1882 return Fplist_get (XSYMBOL (symbol)->plist, propname);
1883 }
1884
1885 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
1886 doc: /* Change value in PLIST of PROP to VAL.
1887 PLIST is a property list, which is a list of the form
1888 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
1889 If PROP is already a property on the list, its value is set to VAL,
1890 otherwise the new PROP VAL pair is added. The new plist is returned;
1891 use `(setq x (plist-put x prop val))' to be sure to use the new value.
1892 The PLIST is modified by side effects. */)
1893 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1894 {
1895 register Lisp_Object tail, prev;
1896 Lisp_Object newcell;
1897 prev = Qnil;
1898 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1899 tail = XCDR (XCDR (tail)))
1900 {
1901 if (EQ (prop, XCAR (tail)))
1902 {
1903 Fsetcar (XCDR (tail), val);
1904 return plist;
1905 }
1906
1907 prev = tail;
1908 QUIT;
1909 }
1910 newcell = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
1911 if (NILP (prev))
1912 return newcell;
1913 else
1914 Fsetcdr (XCDR (prev), newcell);
1915 return plist;
1916 }
1917
1918 DEFUN ("put", Fput, Sput, 3, 3, 0,
1919 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
1920 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
1921 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
1922 {
1923 CHECK_SYMBOL (symbol);
1924 XSYMBOL (symbol)->plist
1925 = Fplist_put (XSYMBOL (symbol)->plist, propname, value);
1926 return value;
1927 }
1928 \f
1929 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
1930 doc: /* Extract a value from a property list, comparing with `equal'.
1931 PLIST is a property list, which is a list of the form
1932 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1933 corresponding to the given PROP, or nil if PROP is not
1934 one of the properties on the list. */)
1935 (Lisp_Object plist, Lisp_Object prop)
1936 {
1937 Lisp_Object tail;
1938
1939 for (tail = plist;
1940 CONSP (tail) && CONSP (XCDR (tail));
1941 tail = XCDR (XCDR (tail)))
1942 {
1943 if (! NILP (Fequal (prop, XCAR (tail))))
1944 return XCAR (XCDR (tail));
1945
1946 QUIT;
1947 }
1948
1949 CHECK_LIST_END (tail, prop);
1950
1951 return Qnil;
1952 }
1953
1954 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
1955 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
1956 PLIST is a property list, which is a list of the form
1957 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
1958 If PROP is already a property on the list, its value is set to VAL,
1959 otherwise the new PROP VAL pair is added. The new plist is returned;
1960 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
1961 The PLIST is modified by side effects. */)
1962 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
1963 {
1964 register Lisp_Object tail, prev;
1965 Lisp_Object newcell;
1966 prev = Qnil;
1967 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
1968 tail = XCDR (XCDR (tail)))
1969 {
1970 if (! NILP (Fequal (prop, XCAR (tail))))
1971 {
1972 Fsetcar (XCDR (tail), val);
1973 return plist;
1974 }
1975
1976 prev = tail;
1977 QUIT;
1978 }
1979 newcell = Fcons (prop, Fcons (val, Qnil));
1980 if (NILP (prev))
1981 return newcell;
1982 else
1983 Fsetcdr (XCDR (prev), newcell);
1984 return plist;
1985 }
1986 \f
1987 DEFUN ("eql", Feql, Seql, 2, 2, 0,
1988 doc: /* Return t if the two args are the same Lisp object.
1989 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
1990 (Lisp_Object obj1, Lisp_Object obj2)
1991 {
1992 if (FLOATP (obj1))
1993 return internal_equal (obj1, obj2, 0, 0) ? Qt : Qnil;
1994 else
1995 return EQ (obj1, obj2) ? Qt : Qnil;
1996 }
1997
1998 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
1999 doc: /* Return t if two Lisp objects have similar structure and contents.
2000 They must have the same data type.
2001 Conses are compared by comparing the cars and the cdrs.
2002 Vectors and strings are compared element by element.
2003 Numbers are compared by value, but integers cannot equal floats.
2004 (Use `=' if you want integers and floats to be able to be equal.)
2005 Symbols must match exactly. */)
2006 (register Lisp_Object o1, Lisp_Object o2)
2007 {
2008 return internal_equal (o1, o2, 0, 0) ? Qt : Qnil;
2009 }
2010
2011 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
2012 doc: /* Return t if two Lisp objects have similar structure and contents.
2013 This is like `equal' except that it compares the text properties
2014 of strings. (`equal' ignores text properties.) */)
2015 (register Lisp_Object o1, Lisp_Object o2)
2016 {
2017 return internal_equal (o1, o2, 0, 1) ? Qt : Qnil;
2018 }
2019
2020 /* DEPTH is current depth of recursion. Signal an error if it
2021 gets too deep.
2022 PROPS, if non-nil, means compare string text properties too. */
2023
2024 static int
2025 internal_equal (register Lisp_Object o1, register Lisp_Object o2, int depth, int props)
2026 {
2027 if (depth > 200)
2028 error ("Stack overflow in equal");
2029
2030 tail_recurse:
2031 QUIT;
2032 if (EQ (o1, o2))
2033 return 1;
2034 if (XTYPE (o1) != XTYPE (o2))
2035 return 0;
2036
2037 switch (XTYPE (o1))
2038 {
2039 case Lisp_Float:
2040 {
2041 double d1, d2;
2042
2043 d1 = extract_float (o1);
2044 d2 = extract_float (o2);
2045 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2046 though they are not =. */
2047 return d1 == d2 || (d1 != d1 && d2 != d2);
2048 }
2049
2050 case Lisp_Cons:
2051 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1, props))
2052 return 0;
2053 o1 = XCDR (o1);
2054 o2 = XCDR (o2);
2055 goto tail_recurse;
2056
2057 case Lisp_Misc:
2058 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2059 return 0;
2060 if (OVERLAYP (o1))
2061 {
2062 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2063 depth + 1, props)
2064 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2065 depth + 1, props))
2066 return 0;
2067 o1 = XOVERLAY (o1)->plist;
2068 o2 = XOVERLAY (o2)->plist;
2069 goto tail_recurse;
2070 }
2071 if (MARKERP (o1))
2072 {
2073 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2074 && (XMARKER (o1)->buffer == 0
2075 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2076 }
2077 break;
2078
2079 case Lisp_Vectorlike:
2080 {
2081 register int i;
2082 EMACS_INT size = ASIZE (o1);
2083 /* Pseudovectors have the type encoded in the size field, so this test
2084 actually checks that the objects have the same type as well as the
2085 same size. */
2086 if (ASIZE (o2) != size)
2087 return 0;
2088 /* Boolvectors are compared much like strings. */
2089 if (BOOL_VECTOR_P (o1))
2090 {
2091 if (XBOOL_VECTOR (o1)->size != XBOOL_VECTOR (o2)->size)
2092 return 0;
2093 if (memcmp (XBOOL_VECTOR (o1)->data, XBOOL_VECTOR (o2)->data,
2094 ((XBOOL_VECTOR (o1)->size
2095 + BOOL_VECTOR_BITS_PER_CHAR - 1)
2096 / BOOL_VECTOR_BITS_PER_CHAR)))
2097 return 0;
2098 return 1;
2099 }
2100 if (WINDOW_CONFIGURATIONP (o1))
2101 return compare_window_configurations (o1, o2, 0);
2102
2103 /* Aside from them, only true vectors, char-tables, compiled
2104 functions, and fonts (font-spec, font-entity, font-object)
2105 are sensible to compare, so eliminate the others now. */
2106 if (size & PSEUDOVECTOR_FLAG)
2107 {
2108 if (!(size & (PVEC_COMPILED
2109 | PVEC_CHAR_TABLE | PVEC_SUB_CHAR_TABLE | PVEC_FONT)))
2110 return 0;
2111 size &= PSEUDOVECTOR_SIZE_MASK;
2112 }
2113 for (i = 0; i < size; i++)
2114 {
2115 Lisp_Object v1, v2;
2116 v1 = AREF (o1, i);
2117 v2 = AREF (o2, i);
2118 if (!internal_equal (v1, v2, depth + 1, props))
2119 return 0;
2120 }
2121 return 1;
2122 }
2123 break;
2124
2125 case Lisp_String:
2126 if (SCHARS (o1) != SCHARS (o2))
2127 return 0;
2128 if (SBYTES (o1) != SBYTES (o2))
2129 return 0;
2130 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2131 return 0;
2132 if (props && !compare_string_intervals (o1, o2))
2133 return 0;
2134 return 1;
2135
2136 default:
2137 break;
2138 }
2139
2140 return 0;
2141 }
2142 \f
2143
2144 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2145 doc: /* Store each element of ARRAY with ITEM.
2146 ARRAY is a vector, string, char-table, or bool-vector. */)
2147 (Lisp_Object array, Lisp_Object item)
2148 {
2149 register EMACS_INT size, idx;
2150
2151 if (VECTORP (array))
2152 {
2153 register Lisp_Object *p = XVECTOR (array)->contents;
2154 size = ASIZE (array);
2155 for (idx = 0; idx < size; idx++)
2156 p[idx] = item;
2157 }
2158 else if (CHAR_TABLE_P (array))
2159 {
2160 int i;
2161
2162 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2163 XCHAR_TABLE (array)->contents[i] = item;
2164 XCHAR_TABLE (array)->defalt = item;
2165 }
2166 else if (STRINGP (array))
2167 {
2168 register unsigned char *p = SDATA (array);
2169 int charval;
2170 CHECK_CHARACTER (item);
2171 charval = XFASTINT (item);
2172 size = SCHARS (array);
2173 if (STRING_MULTIBYTE (array))
2174 {
2175 unsigned char str[MAX_MULTIBYTE_LENGTH];
2176 int len = CHAR_STRING (charval, str);
2177 EMACS_INT size_byte = SBYTES (array);
2178
2179 if (INT_MULTIPLY_OVERFLOW (SCHARS (array), len)
2180 || SCHARS (array) * len != size_byte)
2181 error ("Attempt to change byte length of a string");
2182 for (idx = 0; idx < size_byte; idx++)
2183 *p++ = str[idx % len];
2184 }
2185 else
2186 for (idx = 0; idx < size; idx++)
2187 p[idx] = charval;
2188 }
2189 else if (BOOL_VECTOR_P (array))
2190 {
2191 register unsigned char *p = XBOOL_VECTOR (array)->data;
2192 EMACS_INT size_in_chars;
2193 size = XBOOL_VECTOR (array)->size;
2194 size_in_chars
2195 = ((size + BOOL_VECTOR_BITS_PER_CHAR - 1)
2196 / BOOL_VECTOR_BITS_PER_CHAR);
2197
2198 if (size_in_chars)
2199 {
2200 memset (p, ! NILP (item) ? -1 : 0, size_in_chars);
2201
2202 /* Clear any extraneous bits in the last byte. */
2203 p[size_in_chars - 1] &= (1 << (size % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2204 }
2205 }
2206 else
2207 wrong_type_argument (Qarrayp, array);
2208 return array;
2209 }
2210
2211 DEFUN ("clear-string", Fclear_string, Sclear_string,
2212 1, 1, 0,
2213 doc: /* Clear the contents of STRING.
2214 This makes STRING unibyte and may change its length. */)
2215 (Lisp_Object string)
2216 {
2217 EMACS_INT len;
2218 CHECK_STRING (string);
2219 len = SBYTES (string);
2220 memset (SDATA (string), 0, len);
2221 STRING_SET_CHARS (string, len);
2222 STRING_SET_UNIBYTE (string);
2223 return Qnil;
2224 }
2225 \f
2226 /* ARGSUSED */
2227 Lisp_Object
2228 nconc2 (Lisp_Object s1, Lisp_Object s2)
2229 {
2230 Lisp_Object args[2];
2231 args[0] = s1;
2232 args[1] = s2;
2233 return Fnconc (2, args);
2234 }
2235
2236 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2237 doc: /* Concatenate any number of lists by altering them.
2238 Only the last argument is not altered, and need not be a list.
2239 usage: (nconc &rest LISTS) */)
2240 (ptrdiff_t nargs, Lisp_Object *args)
2241 {
2242 ptrdiff_t argnum;
2243 register Lisp_Object tail, tem, val;
2244
2245 val = tail = Qnil;
2246
2247 for (argnum = 0; argnum < nargs; argnum++)
2248 {
2249 tem = args[argnum];
2250 if (NILP (tem)) continue;
2251
2252 if (NILP (val))
2253 val = tem;
2254
2255 if (argnum + 1 == nargs) break;
2256
2257 CHECK_LIST_CONS (tem, tem);
2258
2259 while (CONSP (tem))
2260 {
2261 tail = tem;
2262 tem = XCDR (tail);
2263 QUIT;
2264 }
2265
2266 tem = args[argnum + 1];
2267 Fsetcdr (tail, tem);
2268 if (NILP (tem))
2269 args[argnum + 1] = tail;
2270 }
2271
2272 return val;
2273 }
2274 \f
2275 /* This is the guts of all mapping functions.
2276 Apply FN to each element of SEQ, one by one,
2277 storing the results into elements of VALS, a C vector of Lisp_Objects.
2278 LENI is the length of VALS, which should also be the length of SEQ. */
2279
2280 static void
2281 mapcar1 (EMACS_INT leni, Lisp_Object *vals, Lisp_Object fn, Lisp_Object seq)
2282 {
2283 register Lisp_Object tail;
2284 Lisp_Object dummy;
2285 register EMACS_INT i;
2286 struct gcpro gcpro1, gcpro2, gcpro3;
2287
2288 if (vals)
2289 {
2290 /* Don't let vals contain any garbage when GC happens. */
2291 for (i = 0; i < leni; i++)
2292 vals[i] = Qnil;
2293
2294 GCPRO3 (dummy, fn, seq);
2295 gcpro1.var = vals;
2296 gcpro1.nvars = leni;
2297 }
2298 else
2299 GCPRO2 (fn, seq);
2300 /* We need not explicitly protect `tail' because it is used only on lists, and
2301 1) lists are not relocated and 2) the list is marked via `seq' so will not
2302 be freed */
2303
2304 if (VECTORP (seq) || COMPILEDP (seq))
2305 {
2306 for (i = 0; i < leni; i++)
2307 {
2308 dummy = call1 (fn, AREF (seq, i));
2309 if (vals)
2310 vals[i] = dummy;
2311 }
2312 }
2313 else if (BOOL_VECTOR_P (seq))
2314 {
2315 for (i = 0; i < leni; i++)
2316 {
2317 unsigned char byte;
2318 byte = XBOOL_VECTOR (seq)->data[i / BOOL_VECTOR_BITS_PER_CHAR];
2319 dummy = (byte & (1 << (i % BOOL_VECTOR_BITS_PER_CHAR))) ? Qt : Qnil;
2320 dummy = call1 (fn, dummy);
2321 if (vals)
2322 vals[i] = dummy;
2323 }
2324 }
2325 else if (STRINGP (seq))
2326 {
2327 EMACS_INT i_byte;
2328
2329 for (i = 0, i_byte = 0; i < leni;)
2330 {
2331 int c;
2332 EMACS_INT i_before = i;
2333
2334 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2335 XSETFASTINT (dummy, c);
2336 dummy = call1 (fn, dummy);
2337 if (vals)
2338 vals[i_before] = dummy;
2339 }
2340 }
2341 else /* Must be a list, since Flength did not get an error */
2342 {
2343 tail = seq;
2344 for (i = 0; i < leni && CONSP (tail); i++)
2345 {
2346 dummy = call1 (fn, XCAR (tail));
2347 if (vals)
2348 vals[i] = dummy;
2349 tail = XCDR (tail);
2350 }
2351 }
2352
2353 UNGCPRO;
2354 }
2355
2356 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2357 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2358 In between each pair of results, stick in SEPARATOR. Thus, " " as
2359 SEPARATOR results in spaces between the values returned by FUNCTION.
2360 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2361 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2362 {
2363 Lisp_Object len;
2364 register EMACS_INT leni;
2365 ptrdiff_t i, nargs;
2366 register Lisp_Object *args;
2367 struct gcpro gcpro1;
2368 Lisp_Object ret;
2369 USE_SAFE_ALLOCA;
2370
2371 len = Flength (sequence);
2372 if (CHAR_TABLE_P (sequence))
2373 wrong_type_argument (Qlistp, sequence);
2374 leni = XINT (len);
2375 nargs = leni + leni - 1;
2376 if (nargs < 0) return empty_unibyte_string;
2377
2378 SAFE_ALLOCA_LISP (args, nargs);
2379
2380 GCPRO1 (separator);
2381 mapcar1 (leni, args, function, sequence);
2382 UNGCPRO;
2383
2384 for (i = leni - 1; i > 0; i--)
2385 args[i + i] = args[i];
2386
2387 for (i = 1; i < nargs; i += 2)
2388 args[i] = separator;
2389
2390 ret = Fconcat (nargs, args);
2391 SAFE_FREE ();
2392
2393 return ret;
2394 }
2395
2396 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2397 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2398 The result is a list just as long as SEQUENCE.
2399 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2400 (Lisp_Object function, Lisp_Object sequence)
2401 {
2402 register Lisp_Object len;
2403 register EMACS_INT leni;
2404 register Lisp_Object *args;
2405 Lisp_Object ret;
2406 USE_SAFE_ALLOCA;
2407
2408 len = Flength (sequence);
2409 if (CHAR_TABLE_P (sequence))
2410 wrong_type_argument (Qlistp, sequence);
2411 leni = XFASTINT (len);
2412
2413 SAFE_ALLOCA_LISP (args, leni);
2414
2415 mapcar1 (leni, args, function, sequence);
2416
2417 ret = Flist (leni, args);
2418 SAFE_FREE ();
2419
2420 return ret;
2421 }
2422
2423 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2424 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2425 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2426 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2427 (Lisp_Object function, Lisp_Object sequence)
2428 {
2429 register EMACS_INT leni;
2430
2431 leni = XFASTINT (Flength (sequence));
2432 if (CHAR_TABLE_P (sequence))
2433 wrong_type_argument (Qlistp, sequence);
2434 mapcar1 (leni, 0, function, sequence);
2435
2436 return sequence;
2437 }
2438 \f
2439 /* This is how C code calls `yes-or-no-p' and allows the user
2440 to redefined it.
2441
2442 Anything that calls this function must protect from GC! */
2443
2444 Lisp_Object
2445 do_yes_or_no_p (Lisp_Object prompt)
2446 {
2447 return call1 (intern ("yes-or-no-p"), prompt);
2448 }
2449
2450 /* Anything that calls this function must protect from GC! */
2451
2452 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2453 doc: /* Ask user a yes-or-no question. Return t if answer is yes.
2454 PROMPT is the string to display to ask the question. It should end in
2455 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2456
2457 The user must confirm the answer with RET, and can edit it until it
2458 has been confirmed.
2459
2460 Under a windowing system a dialog box will be used if `last-nonmenu-event'
2461 is nil, and `use-dialog-box' is non-nil. */)
2462 (Lisp_Object prompt)
2463 {
2464 register Lisp_Object ans;
2465 Lisp_Object args[2];
2466 struct gcpro gcpro1;
2467
2468 CHECK_STRING (prompt);
2469
2470 #ifdef HAVE_MENUS
2471 if (FRAME_WINDOW_P (SELECTED_FRAME ())
2472 && (NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2473 && use_dialog_box
2474 && have_menus_p ())
2475 {
2476 Lisp_Object pane, menu, obj;
2477 redisplay_preserve_echo_area (4);
2478 pane = Fcons (Fcons (build_string ("Yes"), Qt),
2479 Fcons (Fcons (build_string ("No"), Qnil),
2480 Qnil));
2481 GCPRO1 (pane);
2482 menu = Fcons (prompt, pane);
2483 obj = Fx_popup_dialog (Qt, menu, Qnil);
2484 UNGCPRO;
2485 return obj;
2486 }
2487 #endif /* HAVE_MENUS */
2488
2489 args[0] = prompt;
2490 args[1] = build_string ("(yes or no) ");
2491 prompt = Fconcat (2, args);
2492
2493 GCPRO1 (prompt);
2494
2495 while (1)
2496 {
2497 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2498 Qyes_or_no_p_history, Qnil,
2499 Qnil));
2500 if (SCHARS (ans) == 3 && !strcmp (SSDATA (ans), "yes"))
2501 {
2502 UNGCPRO;
2503 return Qt;
2504 }
2505 if (SCHARS (ans) == 2 && !strcmp (SSDATA (ans), "no"))
2506 {
2507 UNGCPRO;
2508 return Qnil;
2509 }
2510
2511 Fding (Qnil);
2512 Fdiscard_input ();
2513 message ("Please answer yes or no.");
2514 Fsleep_for (make_number (2), Qnil);
2515 }
2516 }
2517 \f
2518 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2519 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2520
2521 Each of the three load averages is multiplied by 100, then converted
2522 to integer.
2523
2524 When USE-FLOATS is non-nil, floats will be used instead of integers.
2525 These floats are not multiplied by 100.
2526
2527 If the 5-minute or 15-minute load averages are not available, return a
2528 shortened list, containing only those averages which are available.
2529
2530 An error is thrown if the load average can't be obtained. In some
2531 cases making it work would require Emacs being installed setuid or
2532 setgid so that it can read kernel information, and that usually isn't
2533 advisable. */)
2534 (Lisp_Object use_floats)
2535 {
2536 double load_ave[3];
2537 int loads = getloadavg (load_ave, 3);
2538 Lisp_Object ret = Qnil;
2539
2540 if (loads < 0)
2541 error ("load-average not implemented for this operating system");
2542
2543 while (loads-- > 0)
2544 {
2545 Lisp_Object load = (NILP (use_floats)
2546 ? make_number (100.0 * load_ave[loads])
2547 : make_float (load_ave[loads]));
2548 ret = Fcons (load, ret);
2549 }
2550
2551 return ret;
2552 }
2553 \f
2554 static Lisp_Object Qsubfeatures;
2555
2556 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2557 doc: /* Return t if FEATURE is present in this Emacs.
2558
2559 Use this to conditionalize execution of lisp code based on the
2560 presence or absence of Emacs or environment extensions.
2561 Use `provide' to declare that a feature is available. This function
2562 looks at the value of the variable `features'. The optional argument
2563 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2564 (Lisp_Object feature, Lisp_Object subfeature)
2565 {
2566 register Lisp_Object tem;
2567 CHECK_SYMBOL (feature);
2568 tem = Fmemq (feature, Vfeatures);
2569 if (!NILP (tem) && !NILP (subfeature))
2570 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2571 return (NILP (tem)) ? Qnil : Qt;
2572 }
2573
2574 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2575 doc: /* Announce that FEATURE is a feature of the current Emacs.
2576 The optional argument SUBFEATURES should be a list of symbols listing
2577 particular subfeatures supported in this version of FEATURE. */)
2578 (Lisp_Object feature, Lisp_Object subfeatures)
2579 {
2580 register Lisp_Object tem;
2581 CHECK_SYMBOL (feature);
2582 CHECK_LIST (subfeatures);
2583 if (!NILP (Vautoload_queue))
2584 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2585 Vautoload_queue);
2586 tem = Fmemq (feature, Vfeatures);
2587 if (NILP (tem))
2588 Vfeatures = Fcons (feature, Vfeatures);
2589 if (!NILP (subfeatures))
2590 Fput (feature, Qsubfeatures, subfeatures);
2591 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2592
2593 /* Run any load-hooks for this file. */
2594 tem = Fassq (feature, Vafter_load_alist);
2595 if (CONSP (tem))
2596 Fprogn (XCDR (tem));
2597
2598 return feature;
2599 }
2600 \f
2601 /* `require' and its subroutines. */
2602
2603 /* List of features currently being require'd, innermost first. */
2604
2605 static Lisp_Object require_nesting_list;
2606
2607 static Lisp_Object
2608 require_unwind (Lisp_Object old_value)
2609 {
2610 return require_nesting_list = old_value;
2611 }
2612
2613 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2614 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2615 If FEATURE is not a member of the list `features', then the feature
2616 is not loaded; so load the file FILENAME.
2617 If FILENAME is omitted, the printname of FEATURE is used as the file name,
2618 and `load' will try to load this name appended with the suffix `.elc' or
2619 `.el', in that order. The name without appended suffix will not be used.
2620 See `get-load-suffixes' for the complete list of suffixes.
2621 If the optional third argument NOERROR is non-nil,
2622 then return nil if the file is not found instead of signaling an error.
2623 Normally the return value is FEATURE.
2624 The normal messages at start and end of loading FILENAME are suppressed. */)
2625 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2626 {
2627 register Lisp_Object tem;
2628 struct gcpro gcpro1, gcpro2;
2629 int from_file = load_in_progress;
2630
2631 CHECK_SYMBOL (feature);
2632
2633 /* Record the presence of `require' in this file
2634 even if the feature specified is already loaded.
2635 But not more than once in any file,
2636 and not when we aren't loading or reading from a file. */
2637 if (!from_file)
2638 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2639 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2640 from_file = 1;
2641
2642 if (from_file)
2643 {
2644 tem = Fcons (Qrequire, feature);
2645 if (NILP (Fmember (tem, Vcurrent_load_list)))
2646 LOADHIST_ATTACH (tem);
2647 }
2648 tem = Fmemq (feature, Vfeatures);
2649
2650 if (NILP (tem))
2651 {
2652 int count = SPECPDL_INDEX ();
2653 int nesting = 0;
2654
2655 /* This is to make sure that loadup.el gives a clear picture
2656 of what files are preloaded and when. */
2657 if (! NILP (Vpurify_flag))
2658 error ("(require %s) while preparing to dump",
2659 SDATA (SYMBOL_NAME (feature)));
2660
2661 /* A certain amount of recursive `require' is legitimate,
2662 but if we require the same feature recursively 3 times,
2663 signal an error. */
2664 tem = require_nesting_list;
2665 while (! NILP (tem))
2666 {
2667 if (! NILP (Fequal (feature, XCAR (tem))))
2668 nesting++;
2669 tem = XCDR (tem);
2670 }
2671 if (nesting > 3)
2672 error ("Recursive `require' for feature `%s'",
2673 SDATA (SYMBOL_NAME (feature)));
2674
2675 /* Update the list for any nested `require's that occur. */
2676 record_unwind_protect (require_unwind, require_nesting_list);
2677 require_nesting_list = Fcons (feature, require_nesting_list);
2678
2679 /* Value saved here is to be restored into Vautoload_queue */
2680 record_unwind_protect (un_autoload, Vautoload_queue);
2681 Vautoload_queue = Qt;
2682
2683 /* Load the file. */
2684 GCPRO2 (feature, filename);
2685 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2686 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2687 UNGCPRO;
2688
2689 /* If load failed entirely, return nil. */
2690 if (NILP (tem))
2691 return unbind_to (count, Qnil);
2692
2693 tem = Fmemq (feature, Vfeatures);
2694 if (NILP (tem))
2695 error ("Required feature `%s' was not provided",
2696 SDATA (SYMBOL_NAME (feature)));
2697
2698 /* Once loading finishes, don't undo it. */
2699 Vautoload_queue = Qt;
2700 feature = unbind_to (count, feature);
2701 }
2702
2703 return feature;
2704 }
2705 \f
2706 /* Primitives for work of the "widget" library.
2707 In an ideal world, this section would not have been necessary.
2708 However, lisp function calls being as slow as they are, it turns
2709 out that some functions in the widget library (wid-edit.el) are the
2710 bottleneck of Widget operation. Here is their translation to C,
2711 for the sole reason of efficiency. */
2712
2713 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2714 doc: /* Return non-nil if PLIST has the property PROP.
2715 PLIST is a property list, which is a list of the form
2716 \(PROP1 VALUE1 PROP2 VALUE2 ...\). PROP is a symbol.
2717 Unlike `plist-get', this allows you to distinguish between a missing
2718 property and a property with the value nil.
2719 The value is actually the tail of PLIST whose car is PROP. */)
2720 (Lisp_Object plist, Lisp_Object prop)
2721 {
2722 while (CONSP (plist) && !EQ (XCAR (plist), prop))
2723 {
2724 QUIT;
2725 plist = XCDR (plist);
2726 plist = CDR (plist);
2727 }
2728 return plist;
2729 }
2730
2731 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2732 doc: /* In WIDGET, set PROPERTY to VALUE.
2733 The value can later be retrieved with `widget-get'. */)
2734 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2735 {
2736 CHECK_CONS (widget);
2737 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
2738 return value;
2739 }
2740
2741 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
2742 doc: /* In WIDGET, get the value of PROPERTY.
2743 The value could either be specified when the widget was created, or
2744 later with `widget-put'. */)
2745 (Lisp_Object widget, Lisp_Object property)
2746 {
2747 Lisp_Object tmp;
2748
2749 while (1)
2750 {
2751 if (NILP (widget))
2752 return Qnil;
2753 CHECK_CONS (widget);
2754 tmp = Fplist_member (XCDR (widget), property);
2755 if (CONSP (tmp))
2756 {
2757 tmp = XCDR (tmp);
2758 return CAR (tmp);
2759 }
2760 tmp = XCAR (widget);
2761 if (NILP (tmp))
2762 return Qnil;
2763 widget = Fget (tmp, Qwidget_type);
2764 }
2765 }
2766
2767 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
2768 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2769 ARGS are passed as extra arguments to the function.
2770 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2771 (ptrdiff_t nargs, Lisp_Object *args)
2772 {
2773 /* This function can GC. */
2774 Lisp_Object newargs[3];
2775 struct gcpro gcpro1, gcpro2;
2776 Lisp_Object result;
2777
2778 newargs[0] = Fwidget_get (args[0], args[1]);
2779 newargs[1] = args[0];
2780 newargs[2] = Flist (nargs - 2, args + 2);
2781 GCPRO2 (newargs[0], newargs[2]);
2782 result = Fapply (3, newargs);
2783 UNGCPRO;
2784 return result;
2785 }
2786
2787 #ifdef HAVE_LANGINFO_CODESET
2788 #include <langinfo.h>
2789 #endif
2790
2791 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
2792 doc: /* Access locale data ITEM for the current C locale, if available.
2793 ITEM should be one of the following:
2794
2795 `codeset', returning the character set as a string (locale item CODESET);
2796
2797 `days', returning a 7-element vector of day names (locale items DAY_n);
2798
2799 `months', returning a 12-element vector of month names (locale items MON_n);
2800
2801 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
2802 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
2803
2804 If the system can't provide such information through a call to
2805 `nl_langinfo', or if ITEM isn't from the list above, return nil.
2806
2807 See also Info node `(libc)Locales'.
2808
2809 The data read from the system are decoded using `locale-coding-system'. */)
2810 (Lisp_Object item)
2811 {
2812 char *str = NULL;
2813 #ifdef HAVE_LANGINFO_CODESET
2814 Lisp_Object val;
2815 if (EQ (item, Qcodeset))
2816 {
2817 str = nl_langinfo (CODESET);
2818 return build_string (str);
2819 }
2820 #ifdef DAY_1
2821 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
2822 {
2823 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
2824 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
2825 int i;
2826 struct gcpro gcpro1;
2827 GCPRO1 (v);
2828 synchronize_system_time_locale ();
2829 for (i = 0; i < 7; i++)
2830 {
2831 str = nl_langinfo (days[i]);
2832 val = make_unibyte_string (str, strlen (str));
2833 /* Fixme: Is this coding system necessarily right, even if
2834 it is consistent with CODESET? If not, what to do? */
2835 Faset (v, make_number (i),
2836 code_convert_string_norecord (val, Vlocale_coding_system,
2837 0));
2838 }
2839 UNGCPRO;
2840 return v;
2841 }
2842 #endif /* DAY_1 */
2843 #ifdef MON_1
2844 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
2845 {
2846 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
2847 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
2848 MON_8, MON_9, MON_10, MON_11, MON_12};
2849 int i;
2850 struct gcpro gcpro1;
2851 GCPRO1 (v);
2852 synchronize_system_time_locale ();
2853 for (i = 0; i < 12; i++)
2854 {
2855 str = nl_langinfo (months[i]);
2856 val = make_unibyte_string (str, strlen (str));
2857 Faset (v, make_number (i),
2858 code_convert_string_norecord (val, Vlocale_coding_system, 0));
2859 }
2860 UNGCPRO;
2861 return v;
2862 }
2863 #endif /* MON_1 */
2864 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
2865 but is in the locale files. This could be used by ps-print. */
2866 #ifdef PAPER_WIDTH
2867 else if (EQ (item, Qpaper))
2868 {
2869 return list2 (make_number (nl_langinfo (PAPER_WIDTH)),
2870 make_number (nl_langinfo (PAPER_HEIGHT)));
2871 }
2872 #endif /* PAPER_WIDTH */
2873 #endif /* HAVE_LANGINFO_CODESET*/
2874 return Qnil;
2875 }
2876 \f
2877 /* base64 encode/decode functions (RFC 2045).
2878 Based on code from GNU recode. */
2879
2880 #define MIME_LINE_LENGTH 76
2881
2882 #define IS_ASCII(Character) \
2883 ((Character) < 128)
2884 #define IS_BASE64(Character) \
2885 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
2886 #define IS_BASE64_IGNORABLE(Character) \
2887 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
2888 || (Character) == '\f' || (Character) == '\r')
2889
2890 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
2891 character or return retval if there are no characters left to
2892 process. */
2893 #define READ_QUADRUPLET_BYTE(retval) \
2894 do \
2895 { \
2896 if (i == length) \
2897 { \
2898 if (nchars_return) \
2899 *nchars_return = nchars; \
2900 return (retval); \
2901 } \
2902 c = from[i++]; \
2903 } \
2904 while (IS_BASE64_IGNORABLE (c))
2905
2906 /* Table of characters coding the 64 values. */
2907 static const char base64_value_to_char[64] =
2908 {
2909 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
2910 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
2911 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
2912 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
2913 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
2914 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
2915 '8', '9', '+', '/' /* 60-63 */
2916 };
2917
2918 /* Table of base64 values for first 128 characters. */
2919 static const short base64_char_to_value[128] =
2920 {
2921 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
2922 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
2923 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
2924 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
2925 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
2926 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
2927 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
2928 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
2929 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
2930 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
2931 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
2932 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
2933 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
2934 };
2935
2936 /* The following diagram shows the logical steps by which three octets
2937 get transformed into four base64 characters.
2938
2939 .--------. .--------. .--------.
2940 |aaaaaabb| |bbbbcccc| |ccdddddd|
2941 `--------' `--------' `--------'
2942 6 2 4 4 2 6
2943 .--------+--------+--------+--------.
2944 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
2945 `--------+--------+--------+--------'
2946
2947 .--------+--------+--------+--------.
2948 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
2949 `--------+--------+--------+--------'
2950
2951 The octets are divided into 6 bit chunks, which are then encoded into
2952 base64 characters. */
2953
2954
2955 static EMACS_INT base64_encode_1 (const char *, char *, EMACS_INT, int, int);
2956 static EMACS_INT base64_decode_1 (const char *, char *, EMACS_INT, int,
2957 EMACS_INT *);
2958
2959 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
2960 2, 3, "r",
2961 doc: /* Base64-encode the region between BEG and END.
2962 Return the length of the encoded text.
2963 Optional third argument NO-LINE-BREAK means do not break long lines
2964 into shorter lines. */)
2965 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
2966 {
2967 char *encoded;
2968 EMACS_INT allength, length;
2969 EMACS_INT ibeg, iend, encoded_length;
2970 EMACS_INT old_pos = PT;
2971 USE_SAFE_ALLOCA;
2972
2973 validate_region (&beg, &end);
2974
2975 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
2976 iend = CHAR_TO_BYTE (XFASTINT (end));
2977 move_gap_both (XFASTINT (beg), ibeg);
2978
2979 /* We need to allocate enough room for encoding the text.
2980 We need 33 1/3% more space, plus a newline every 76
2981 characters, and then we round up. */
2982 length = iend - ibeg;
2983 allength = length + length/3 + 1;
2984 allength += allength / MIME_LINE_LENGTH + 1 + 6;
2985
2986 SAFE_ALLOCA (encoded, char *, allength);
2987 encoded_length = base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg),
2988 encoded, length, NILP (no_line_break),
2989 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
2990 if (encoded_length > allength)
2991 abort ();
2992
2993 if (encoded_length < 0)
2994 {
2995 /* The encoding wasn't possible. */
2996 SAFE_FREE ();
2997 error ("Multibyte character in data for base64 encoding");
2998 }
2999
3000 /* Now we have encoded the region, so we insert the new contents
3001 and delete the old. (Insert first in order to preserve markers.) */
3002 SET_PT_BOTH (XFASTINT (beg), ibeg);
3003 insert (encoded, encoded_length);
3004 SAFE_FREE ();
3005 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
3006
3007 /* If point was outside of the region, restore it exactly; else just
3008 move to the beginning of the region. */
3009 if (old_pos >= XFASTINT (end))
3010 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
3011 else if (old_pos > XFASTINT (beg))
3012 old_pos = XFASTINT (beg);
3013 SET_PT (old_pos);
3014
3015 /* We return the length of the encoded text. */
3016 return make_number (encoded_length);
3017 }
3018
3019 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
3020 1, 2, 0,
3021 doc: /* Base64-encode STRING and return the result.
3022 Optional second argument NO-LINE-BREAK means do not break long lines
3023 into shorter lines. */)
3024 (Lisp_Object string, Lisp_Object no_line_break)
3025 {
3026 EMACS_INT allength, length, encoded_length;
3027 char *encoded;
3028 Lisp_Object encoded_string;
3029 USE_SAFE_ALLOCA;
3030
3031 CHECK_STRING (string);
3032
3033 /* We need to allocate enough room for encoding the text.
3034 We need 33 1/3% more space, plus a newline every 76
3035 characters, and then we round up. */
3036 length = SBYTES (string);
3037 allength = length + length/3 + 1;
3038 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3039
3040 /* We need to allocate enough room for decoding the text. */
3041 SAFE_ALLOCA (encoded, char *, allength);
3042
3043 encoded_length = base64_encode_1 (SSDATA (string),
3044 encoded, length, NILP (no_line_break),
3045 STRING_MULTIBYTE (string));
3046 if (encoded_length > allength)
3047 abort ();
3048
3049 if (encoded_length < 0)
3050 {
3051 /* The encoding wasn't possible. */
3052 SAFE_FREE ();
3053 error ("Multibyte character in data for base64 encoding");
3054 }
3055
3056 encoded_string = make_unibyte_string (encoded, encoded_length);
3057 SAFE_FREE ();
3058
3059 return encoded_string;
3060 }
3061
3062 static EMACS_INT
3063 base64_encode_1 (const char *from, char *to, EMACS_INT length,
3064 int line_break, int multibyte)
3065 {
3066 int counter = 0;
3067 EMACS_INT i = 0;
3068 char *e = to;
3069 int c;
3070 unsigned int value;
3071 int bytes;
3072
3073 while (i < length)
3074 {
3075 if (multibyte)
3076 {
3077 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3078 if (CHAR_BYTE8_P (c))
3079 c = CHAR_TO_BYTE8 (c);
3080 else if (c >= 256)
3081 return -1;
3082 i += bytes;
3083 }
3084 else
3085 c = from[i++];
3086
3087 /* Wrap line every 76 characters. */
3088
3089 if (line_break)
3090 {
3091 if (counter < MIME_LINE_LENGTH / 4)
3092 counter++;
3093 else
3094 {
3095 *e++ = '\n';
3096 counter = 1;
3097 }
3098 }
3099
3100 /* Process first byte of a triplet. */
3101
3102 *e++ = base64_value_to_char[0x3f & c >> 2];
3103 value = (0x03 & c) << 4;
3104
3105 /* Process second byte of a triplet. */
3106
3107 if (i == length)
3108 {
3109 *e++ = base64_value_to_char[value];
3110 *e++ = '=';
3111 *e++ = '=';
3112 break;
3113 }
3114
3115 if (multibyte)
3116 {
3117 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3118 if (CHAR_BYTE8_P (c))
3119 c = CHAR_TO_BYTE8 (c);
3120 else if (c >= 256)
3121 return -1;
3122 i += bytes;
3123 }
3124 else
3125 c = from[i++];
3126
3127 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3128 value = (0x0f & c) << 2;
3129
3130 /* Process third byte of a triplet. */
3131
3132 if (i == length)
3133 {
3134 *e++ = base64_value_to_char[value];
3135 *e++ = '=';
3136 break;
3137 }
3138
3139 if (multibyte)
3140 {
3141 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3142 if (CHAR_BYTE8_P (c))
3143 c = CHAR_TO_BYTE8 (c);
3144 else if (c >= 256)
3145 return -1;
3146 i += bytes;
3147 }
3148 else
3149 c = from[i++];
3150
3151 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3152 *e++ = base64_value_to_char[0x3f & c];
3153 }
3154
3155 return e - to;
3156 }
3157
3158
3159 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3160 2, 2, "r",
3161 doc: /* Base64-decode the region between BEG and END.
3162 Return the length of the decoded text.
3163 If the region can't be decoded, signal an error and don't modify the buffer. */)
3164 (Lisp_Object beg, Lisp_Object end)
3165 {
3166 EMACS_INT ibeg, iend, length, allength;
3167 char *decoded;
3168 EMACS_INT old_pos = PT;
3169 EMACS_INT decoded_length;
3170 EMACS_INT inserted_chars;
3171 int multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3172 USE_SAFE_ALLOCA;
3173
3174 validate_region (&beg, &end);
3175
3176 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3177 iend = CHAR_TO_BYTE (XFASTINT (end));
3178
3179 length = iend - ibeg;
3180
3181 /* We need to allocate enough room for decoding the text. If we are
3182 working on a multibyte buffer, each decoded code may occupy at
3183 most two bytes. */
3184 allength = multibyte ? length * 2 : length;
3185 SAFE_ALLOCA (decoded, char *, allength);
3186
3187 move_gap_both (XFASTINT (beg), ibeg);
3188 decoded_length = base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg),
3189 decoded, length,
3190 multibyte, &inserted_chars);
3191 if (decoded_length > allength)
3192 abort ();
3193
3194 if (decoded_length < 0)
3195 {
3196 /* The decoding wasn't possible. */
3197 SAFE_FREE ();
3198 error ("Invalid base64 data");
3199 }
3200
3201 /* Now we have decoded the region, so we insert the new contents
3202 and delete the old. (Insert first in order to preserve markers.) */
3203 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3204 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3205 SAFE_FREE ();
3206
3207 /* Delete the original text. */
3208 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3209 iend + decoded_length, 1);
3210
3211 /* If point was outside of the region, restore it exactly; else just
3212 move to the beginning of the region. */
3213 if (old_pos >= XFASTINT (end))
3214 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3215 else if (old_pos > XFASTINT (beg))
3216 old_pos = XFASTINT (beg);
3217 SET_PT (old_pos > ZV ? ZV : old_pos);
3218
3219 return make_number (inserted_chars);
3220 }
3221
3222 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3223 1, 1, 0,
3224 doc: /* Base64-decode STRING and return the result. */)
3225 (Lisp_Object string)
3226 {
3227 char *decoded;
3228 EMACS_INT length, decoded_length;
3229 Lisp_Object decoded_string;
3230 USE_SAFE_ALLOCA;
3231
3232 CHECK_STRING (string);
3233
3234 length = SBYTES (string);
3235 /* We need to allocate enough room for decoding the text. */
3236 SAFE_ALLOCA (decoded, char *, length);
3237
3238 /* The decoded result should be unibyte. */
3239 decoded_length = base64_decode_1 (SSDATA (string), decoded, length,
3240 0, NULL);
3241 if (decoded_length > length)
3242 abort ();
3243 else if (decoded_length >= 0)
3244 decoded_string = make_unibyte_string (decoded, decoded_length);
3245 else
3246 decoded_string = Qnil;
3247
3248 SAFE_FREE ();
3249 if (!STRINGP (decoded_string))
3250 error ("Invalid base64 data");
3251
3252 return decoded_string;
3253 }
3254
3255 /* Base64-decode the data at FROM of LENGHT bytes into TO. If
3256 MULTIBYTE is nonzero, the decoded result should be in multibyte
3257 form. If NCHARS_RETRUN is not NULL, store the number of produced
3258 characters in *NCHARS_RETURN. */
3259
3260 static EMACS_INT
3261 base64_decode_1 (const char *from, char *to, EMACS_INT length,
3262 int multibyte, EMACS_INT *nchars_return)
3263 {
3264 EMACS_INT i = 0; /* Used inside READ_QUADRUPLET_BYTE */
3265 char *e = to;
3266 unsigned char c;
3267 unsigned long value;
3268 EMACS_INT nchars = 0;
3269
3270 while (1)
3271 {
3272 /* Process first byte of a quadruplet. */
3273
3274 READ_QUADRUPLET_BYTE (e-to);
3275
3276 if (!IS_BASE64 (c))
3277 return -1;
3278 value = base64_char_to_value[c] << 18;
3279
3280 /* Process second byte of a quadruplet. */
3281
3282 READ_QUADRUPLET_BYTE (-1);
3283
3284 if (!IS_BASE64 (c))
3285 return -1;
3286 value |= base64_char_to_value[c] << 12;
3287
3288 c = (unsigned char) (value >> 16);
3289 if (multibyte && c >= 128)
3290 e += BYTE8_STRING (c, e);
3291 else
3292 *e++ = c;
3293 nchars++;
3294
3295 /* Process third byte of a quadruplet. */
3296
3297 READ_QUADRUPLET_BYTE (-1);
3298
3299 if (c == '=')
3300 {
3301 READ_QUADRUPLET_BYTE (-1);
3302
3303 if (c != '=')
3304 return -1;
3305 continue;
3306 }
3307
3308 if (!IS_BASE64 (c))
3309 return -1;
3310 value |= base64_char_to_value[c] << 6;
3311
3312 c = (unsigned char) (0xff & value >> 8);
3313 if (multibyte && c >= 128)
3314 e += BYTE8_STRING (c, e);
3315 else
3316 *e++ = c;
3317 nchars++;
3318
3319 /* Process fourth byte of a quadruplet. */
3320
3321 READ_QUADRUPLET_BYTE (-1);
3322
3323 if (c == '=')
3324 continue;
3325
3326 if (!IS_BASE64 (c))
3327 return -1;
3328 value |= base64_char_to_value[c];
3329
3330 c = (unsigned char) (0xff & value);
3331 if (multibyte && c >= 128)
3332 e += BYTE8_STRING (c, e);
3333 else
3334 *e++ = c;
3335 nchars++;
3336 }
3337 }
3338
3339
3340 \f
3341 /***********************************************************************
3342 ***** *****
3343 ***** Hash Tables *****
3344 ***** *****
3345 ***********************************************************************/
3346
3347 /* Implemented by gerd@gnu.org. This hash table implementation was
3348 inspired by CMUCL hash tables. */
3349
3350 /* Ideas:
3351
3352 1. For small tables, association lists are probably faster than
3353 hash tables because they have lower overhead.
3354
3355 For uses of hash tables where the O(1) behavior of table
3356 operations is not a requirement, it might therefore be a good idea
3357 not to hash. Instead, we could just do a linear search in the
3358 key_and_value vector of the hash table. This could be done
3359 if a `:linear-search t' argument is given to make-hash-table. */
3360
3361
3362 /* The list of all weak hash tables. Don't staticpro this one. */
3363
3364 static struct Lisp_Hash_Table *weak_hash_tables;
3365
3366 /* Various symbols. */
3367
3368 static Lisp_Object Qhash_table_p, Qkey, Qvalue;
3369 Lisp_Object Qeq, Qeql, Qequal;
3370 Lisp_Object QCtest, QCsize, QCrehash_size, QCrehash_threshold, QCweakness;
3371 static Lisp_Object Qhash_table_test, Qkey_or_value, Qkey_and_value;
3372
3373 /* Function prototypes. */
3374
3375 static struct Lisp_Hash_Table *check_hash_table (Lisp_Object);
3376 static ptrdiff_t get_key_arg (Lisp_Object, ptrdiff_t, Lisp_Object *, char *);
3377 static void maybe_resize_hash_table (struct Lisp_Hash_Table *);
3378 static int sweep_weak_table (struct Lisp_Hash_Table *, int);
3379
3380
3381 \f
3382 /***********************************************************************
3383 Utilities
3384 ***********************************************************************/
3385
3386 /* If OBJ is a Lisp hash table, return a pointer to its struct
3387 Lisp_Hash_Table. Otherwise, signal an error. */
3388
3389 static struct Lisp_Hash_Table *
3390 check_hash_table (Lisp_Object obj)
3391 {
3392 CHECK_HASH_TABLE (obj);
3393 return XHASH_TABLE (obj);
3394 }
3395
3396
3397 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3398 number. */
3399
3400 EMACS_INT
3401 next_almost_prime (EMACS_INT n)
3402 {
3403 for (n |= 1; ; n += 2)
3404 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0)
3405 return n;
3406 }
3407
3408
3409 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3410 which USED[I] is non-zero. If found at index I in ARGS, set
3411 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3412 0. This function is used to extract a keyword/argument pair from
3413 a DEFUN parameter list. */
3414
3415 static ptrdiff_t
3416 get_key_arg (Lisp_Object key, ptrdiff_t nargs, Lisp_Object *args, char *used)
3417 {
3418 ptrdiff_t i;
3419
3420 for (i = 1; i < nargs; i++)
3421 if (!used[i - 1] && EQ (args[i - 1], key))
3422 {
3423 used[i - 1] = 1;
3424 used[i] = 1;
3425 return i;
3426 }
3427
3428 return 0;
3429 }
3430
3431
3432 /* Return a Lisp vector which has the same contents as VEC but has
3433 size NEW_SIZE, NEW_SIZE >= VEC->size. Entries in the resulting
3434 vector that are not copied from VEC are set to INIT. */
3435
3436 Lisp_Object
3437 larger_vector (Lisp_Object vec, EMACS_INT new_size, Lisp_Object init)
3438 {
3439 struct Lisp_Vector *v;
3440 EMACS_INT i, old_size;
3441
3442 xassert (VECTORP (vec));
3443 old_size = ASIZE (vec);
3444 xassert (new_size >= old_size);
3445
3446 v = allocate_vector (new_size);
3447 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3448 for (i = old_size; i < new_size; ++i)
3449 v->contents[i] = init;
3450 XSETVECTOR (vec, v);
3451 return vec;
3452 }
3453
3454
3455 /***********************************************************************
3456 Low-level Functions
3457 ***********************************************************************/
3458
3459 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3460 HASH2 in hash table H using `eql'. Value is non-zero if KEY1 and
3461 KEY2 are the same. */
3462
3463 static int
3464 cmpfn_eql (struct Lisp_Hash_Table *h,
3465 Lisp_Object key1, EMACS_UINT hash1,
3466 Lisp_Object key2, EMACS_UINT hash2)
3467 {
3468 return (FLOATP (key1)
3469 && FLOATP (key2)
3470 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3471 }
3472
3473
3474 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3475 HASH2 in hash table H using `equal'. Value is non-zero if KEY1 and
3476 KEY2 are the same. */
3477
3478 static int
3479 cmpfn_equal (struct Lisp_Hash_Table *h,
3480 Lisp_Object key1, EMACS_UINT hash1,
3481 Lisp_Object key2, EMACS_UINT hash2)
3482 {
3483 return hash1 == hash2 && !NILP (Fequal (key1, key2));
3484 }
3485
3486
3487 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3488 HASH2 in hash table H using H->user_cmp_function. Value is non-zero
3489 if KEY1 and KEY2 are the same. */
3490
3491 static int
3492 cmpfn_user_defined (struct Lisp_Hash_Table *h,
3493 Lisp_Object key1, EMACS_UINT hash1,
3494 Lisp_Object key2, EMACS_UINT hash2)
3495 {
3496 if (hash1 == hash2)
3497 {
3498 Lisp_Object args[3];
3499
3500 args[0] = h->user_cmp_function;
3501 args[1] = key1;
3502 args[2] = key2;
3503 return !NILP (Ffuncall (3, args));
3504 }
3505 else
3506 return 0;
3507 }
3508
3509
3510 /* Value is a hash code for KEY for use in hash table H which uses
3511 `eq' to compare keys. The hash code returned is guaranteed to fit
3512 in a Lisp integer. */
3513
3514 static EMACS_UINT
3515 hashfn_eq (struct Lisp_Hash_Table *h, Lisp_Object key)
3516 {
3517 EMACS_UINT hash = XUINT (key) ^ XTYPE (key);
3518 xassert ((hash & ~INTMASK) == 0);
3519 return hash;
3520 }
3521
3522
3523 /* Value is a hash code for KEY for use in hash table H which uses
3524 `eql' to compare keys. The hash code returned is guaranteed to fit
3525 in a Lisp integer. */
3526
3527 static EMACS_UINT
3528 hashfn_eql (struct Lisp_Hash_Table *h, Lisp_Object key)
3529 {
3530 EMACS_UINT hash;
3531 if (FLOATP (key))
3532 hash = sxhash (key, 0);
3533 else
3534 hash = XUINT (key) ^ XTYPE (key);
3535 xassert ((hash & ~INTMASK) == 0);
3536 return hash;
3537 }
3538
3539
3540 /* Value is a hash code for KEY for use in hash table H which uses
3541 `equal' to compare keys. The hash code returned is guaranteed to fit
3542 in a Lisp integer. */
3543
3544 static EMACS_UINT
3545 hashfn_equal (struct Lisp_Hash_Table *h, Lisp_Object key)
3546 {
3547 EMACS_UINT hash = sxhash (key, 0);
3548 xassert ((hash & ~INTMASK) == 0);
3549 return hash;
3550 }
3551
3552
3553 /* Value is a hash code for KEY for use in hash table H which uses as
3554 user-defined function to compare keys. The hash code returned is
3555 guaranteed to fit in a Lisp integer. */
3556
3557 static EMACS_UINT
3558 hashfn_user_defined (struct Lisp_Hash_Table *h, Lisp_Object key)
3559 {
3560 Lisp_Object args[2], hash;
3561
3562 args[0] = h->user_hash_function;
3563 args[1] = key;
3564 hash = Ffuncall (2, args);
3565 if (!INTEGERP (hash))
3566 signal_error ("Invalid hash code returned from user-supplied hash function", hash);
3567 return XUINT (hash);
3568 }
3569
3570
3571 /* Create and initialize a new hash table.
3572
3573 TEST specifies the test the hash table will use to compare keys.
3574 It must be either one of the predefined tests `eq', `eql' or
3575 `equal' or a symbol denoting a user-defined test named TEST with
3576 test and hash functions USER_TEST and USER_HASH.
3577
3578 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3579
3580 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3581 new size when it becomes full is computed by adding REHASH_SIZE to
3582 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3583 table's new size is computed by multiplying its old size with
3584 REHASH_SIZE.
3585
3586 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3587 be resized when the ratio of (number of entries in the table) /
3588 (table size) is >= REHASH_THRESHOLD.
3589
3590 WEAK specifies the weakness of the table. If non-nil, it must be
3591 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
3592
3593 Lisp_Object
3594 make_hash_table (Lisp_Object test, Lisp_Object size, Lisp_Object rehash_size,
3595 Lisp_Object rehash_threshold, Lisp_Object weak,
3596 Lisp_Object user_test, Lisp_Object user_hash)
3597 {
3598 struct Lisp_Hash_Table *h;
3599 Lisp_Object table;
3600 EMACS_INT index_size, i, sz;
3601 double index_float;
3602
3603 /* Preconditions. */
3604 xassert (SYMBOLP (test));
3605 xassert (INTEGERP (size) && XINT (size) >= 0);
3606 xassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3607 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size)));
3608 xassert (FLOATP (rehash_threshold)
3609 && 0 < XFLOAT_DATA (rehash_threshold)
3610 && XFLOAT_DATA (rehash_threshold) <= 1.0);
3611
3612 if (XFASTINT (size) == 0)
3613 size = make_number (1);
3614
3615 sz = XFASTINT (size);
3616 index_float = sz / XFLOAT_DATA (rehash_threshold);
3617 index_size = (index_float < MOST_POSITIVE_FIXNUM + 1
3618 ? next_almost_prime (index_float)
3619 : MOST_POSITIVE_FIXNUM + 1);
3620 if (MOST_POSITIVE_FIXNUM < max (index_size, 2 * sz))
3621 error ("Hash table too large");
3622
3623 /* Allocate a table and initialize it. */
3624 h = allocate_hash_table ();
3625
3626 /* Initialize hash table slots. */
3627 h->test = test;
3628 if (EQ (test, Qeql))
3629 {
3630 h->cmpfn = cmpfn_eql;
3631 h->hashfn = hashfn_eql;
3632 }
3633 else if (EQ (test, Qeq))
3634 {
3635 h->cmpfn = NULL;
3636 h->hashfn = hashfn_eq;
3637 }
3638 else if (EQ (test, Qequal))
3639 {
3640 h->cmpfn = cmpfn_equal;
3641 h->hashfn = hashfn_equal;
3642 }
3643 else
3644 {
3645 h->user_cmp_function = user_test;
3646 h->user_hash_function = user_hash;
3647 h->cmpfn = cmpfn_user_defined;
3648 h->hashfn = hashfn_user_defined;
3649 }
3650
3651 h->weak = weak;
3652 h->rehash_threshold = rehash_threshold;
3653 h->rehash_size = rehash_size;
3654 h->count = 0;
3655 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
3656 h->hash = Fmake_vector (size, Qnil);
3657 h->next = Fmake_vector (size, Qnil);
3658 h->index = Fmake_vector (make_number (index_size), Qnil);
3659
3660 /* Set up the free list. */
3661 for (i = 0; i < sz - 1; ++i)
3662 HASH_NEXT (h, i) = make_number (i + 1);
3663 h->next_free = make_number (0);
3664
3665 XSET_HASH_TABLE (table, h);
3666 xassert (HASH_TABLE_P (table));
3667 xassert (XHASH_TABLE (table) == h);
3668
3669 /* Maybe add this hash table to the list of all weak hash tables. */
3670 if (NILP (h->weak))
3671 h->next_weak = NULL;
3672 else
3673 {
3674 h->next_weak = weak_hash_tables;
3675 weak_hash_tables = h;
3676 }
3677
3678 return table;
3679 }
3680
3681
3682 /* Return a copy of hash table H1. Keys and values are not copied,
3683 only the table itself is. */
3684
3685 static Lisp_Object
3686 copy_hash_table (struct Lisp_Hash_Table *h1)
3687 {
3688 Lisp_Object table;
3689 struct Lisp_Hash_Table *h2;
3690 struct Lisp_Vector *next;
3691
3692 h2 = allocate_hash_table ();
3693 next = h2->header.next.vector;
3694 memcpy (h2, h1, sizeof *h2);
3695 h2->header.next.vector = next;
3696 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3697 h2->hash = Fcopy_sequence (h1->hash);
3698 h2->next = Fcopy_sequence (h1->next);
3699 h2->index = Fcopy_sequence (h1->index);
3700 XSET_HASH_TABLE (table, h2);
3701
3702 /* Maybe add this hash table to the list of all weak hash tables. */
3703 if (!NILP (h2->weak))
3704 {
3705 h2->next_weak = weak_hash_tables;
3706 weak_hash_tables = h2;
3707 }
3708
3709 return table;
3710 }
3711
3712
3713 /* Resize hash table H if it's too full. If H cannot be resized
3714 because it's already too large, throw an error. */
3715
3716 static inline void
3717 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3718 {
3719 if (NILP (h->next_free))
3720 {
3721 EMACS_INT old_size = HASH_TABLE_SIZE (h);
3722 EMACS_INT i, new_size, index_size;
3723 EMACS_INT nsize;
3724 double index_float;
3725
3726 if (INTEGERP (h->rehash_size))
3727 new_size = old_size + XFASTINT (h->rehash_size);
3728 else
3729 {
3730 double float_new_size = old_size * XFLOAT_DATA (h->rehash_size);
3731 if (float_new_size < MOST_POSITIVE_FIXNUM + 1)
3732 {
3733 new_size = float_new_size;
3734 if (new_size <= old_size)
3735 new_size = old_size + 1;
3736 }
3737 else
3738 new_size = MOST_POSITIVE_FIXNUM + 1;
3739 }
3740 index_float = new_size / XFLOAT_DATA (h->rehash_threshold);
3741 index_size = (index_float < MOST_POSITIVE_FIXNUM + 1
3742 ? next_almost_prime (index_float)
3743 : MOST_POSITIVE_FIXNUM + 1);
3744 nsize = max (index_size, 2 * new_size);
3745 if (nsize > MOST_POSITIVE_FIXNUM)
3746 error ("Hash table too large to resize");
3747
3748 h->key_and_value = larger_vector (h->key_and_value, 2 * new_size, Qnil);
3749 h->next = larger_vector (h->next, new_size, Qnil);
3750 h->hash = larger_vector (h->hash, new_size, Qnil);
3751 h->index = Fmake_vector (make_number (index_size), Qnil);
3752
3753 /* Update the free list. Do it so that new entries are added at
3754 the end of the free list. This makes some operations like
3755 maphash faster. */
3756 for (i = old_size; i < new_size - 1; ++i)
3757 HASH_NEXT (h, i) = make_number (i + 1);
3758
3759 if (!NILP (h->next_free))
3760 {
3761 Lisp_Object last, next;
3762
3763 last = h->next_free;
3764 while (next = HASH_NEXT (h, XFASTINT (last)),
3765 !NILP (next))
3766 last = next;
3767
3768 HASH_NEXT (h, XFASTINT (last)) = make_number (old_size);
3769 }
3770 else
3771 XSETFASTINT (h->next_free, old_size);
3772
3773 /* Rehash. */
3774 for (i = 0; i < old_size; ++i)
3775 if (!NILP (HASH_HASH (h, i)))
3776 {
3777 EMACS_UINT hash_code = XUINT (HASH_HASH (h, i));
3778 EMACS_INT start_of_bucket = hash_code % ASIZE (h->index);
3779 HASH_NEXT (h, i) = HASH_INDEX (h, start_of_bucket);
3780 HASH_INDEX (h, start_of_bucket) = make_number (i);
3781 }
3782 }
3783 }
3784
3785
3786 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
3787 the hash code of KEY. Value is the index of the entry in H
3788 matching KEY, or -1 if not found. */
3789
3790 EMACS_INT
3791 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
3792 {
3793 EMACS_UINT hash_code;
3794 EMACS_INT start_of_bucket;
3795 Lisp_Object idx;
3796
3797 hash_code = h->hashfn (h, key);
3798 if (hash)
3799 *hash = hash_code;
3800
3801 start_of_bucket = hash_code % ASIZE (h->index);
3802 idx = HASH_INDEX (h, start_of_bucket);
3803
3804 /* We need not gcpro idx since it's either an integer or nil. */
3805 while (!NILP (idx))
3806 {
3807 EMACS_INT i = XFASTINT (idx);
3808 if (EQ (key, HASH_KEY (h, i))
3809 || (h->cmpfn
3810 && h->cmpfn (h, key, hash_code,
3811 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
3812 break;
3813 idx = HASH_NEXT (h, i);
3814 }
3815
3816 return NILP (idx) ? -1 : XFASTINT (idx);
3817 }
3818
3819
3820 /* Put an entry into hash table H that associates KEY with VALUE.
3821 HASH is a previously computed hash code of KEY.
3822 Value is the index of the entry in H matching KEY. */
3823
3824 EMACS_INT
3825 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value,
3826 EMACS_UINT hash)
3827 {
3828 EMACS_INT start_of_bucket, i;
3829
3830 xassert ((hash & ~INTMASK) == 0);
3831
3832 /* Increment count after resizing because resizing may fail. */
3833 maybe_resize_hash_table (h);
3834 h->count++;
3835
3836 /* Store key/value in the key_and_value vector. */
3837 i = XFASTINT (h->next_free);
3838 h->next_free = HASH_NEXT (h, i);
3839 HASH_KEY (h, i) = key;
3840 HASH_VALUE (h, i) = value;
3841
3842 /* Remember its hash code. */
3843 HASH_HASH (h, i) = make_number (hash);
3844
3845 /* Add new entry to its collision chain. */
3846 start_of_bucket = hash % ASIZE (h->index);
3847 HASH_NEXT (h, i) = HASH_INDEX (h, start_of_bucket);
3848 HASH_INDEX (h, start_of_bucket) = make_number (i);
3849 return i;
3850 }
3851
3852
3853 /* Remove the entry matching KEY from hash table H, if there is one. */
3854
3855 static void
3856 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
3857 {
3858 EMACS_UINT hash_code;
3859 EMACS_INT start_of_bucket;
3860 Lisp_Object idx, prev;
3861
3862 hash_code = h->hashfn (h, key);
3863 start_of_bucket = hash_code % ASIZE (h->index);
3864 idx = HASH_INDEX (h, start_of_bucket);
3865 prev = Qnil;
3866
3867 /* We need not gcpro idx, prev since they're either integers or nil. */
3868 while (!NILP (idx))
3869 {
3870 EMACS_INT i = XFASTINT (idx);
3871
3872 if (EQ (key, HASH_KEY (h, i))
3873 || (h->cmpfn
3874 && h->cmpfn (h, key, hash_code,
3875 HASH_KEY (h, i), XUINT (HASH_HASH (h, i)))))
3876 {
3877 /* Take entry out of collision chain. */
3878 if (NILP (prev))
3879 HASH_INDEX (h, start_of_bucket) = HASH_NEXT (h, i);
3880 else
3881 HASH_NEXT (h, XFASTINT (prev)) = HASH_NEXT (h, i);
3882
3883 /* Clear slots in key_and_value and add the slots to
3884 the free list. */
3885 HASH_KEY (h, i) = HASH_VALUE (h, i) = HASH_HASH (h, i) = Qnil;
3886 HASH_NEXT (h, i) = h->next_free;
3887 h->next_free = make_number (i);
3888 h->count--;
3889 xassert (h->count >= 0);
3890 break;
3891 }
3892 else
3893 {
3894 prev = idx;
3895 idx = HASH_NEXT (h, i);
3896 }
3897 }
3898 }
3899
3900
3901 /* Clear hash table H. */
3902
3903 static void
3904 hash_clear (struct Lisp_Hash_Table *h)
3905 {
3906 if (h->count > 0)
3907 {
3908 EMACS_INT i, size = HASH_TABLE_SIZE (h);
3909
3910 for (i = 0; i < size; ++i)
3911 {
3912 HASH_NEXT (h, i) = i < size - 1 ? make_number (i + 1) : Qnil;
3913 HASH_KEY (h, i) = Qnil;
3914 HASH_VALUE (h, i) = Qnil;
3915 HASH_HASH (h, i) = Qnil;
3916 }
3917
3918 for (i = 0; i < ASIZE (h->index); ++i)
3919 ASET (h->index, i, Qnil);
3920
3921 h->next_free = make_number (0);
3922 h->count = 0;
3923 }
3924 }
3925
3926
3927 \f
3928 /************************************************************************
3929 Weak Hash Tables
3930 ************************************************************************/
3931
3932 void
3933 init_weak_hash_tables (void)
3934 {
3935 weak_hash_tables = NULL;
3936 }
3937
3938 /* Sweep weak hash table H. REMOVE_ENTRIES_P non-zero means remove
3939 entries from the table that don't survive the current GC.
3940 REMOVE_ENTRIES_P zero means mark entries that are in use. Value is
3941 non-zero if anything was marked. */
3942
3943 static int
3944 sweep_weak_table (struct Lisp_Hash_Table *h, int remove_entries_p)
3945 {
3946 EMACS_INT bucket, n;
3947 int marked;
3948
3949 n = ASIZE (h->index) & ~ARRAY_MARK_FLAG;
3950 marked = 0;
3951
3952 for (bucket = 0; bucket < n; ++bucket)
3953 {
3954 Lisp_Object idx, next, prev;
3955
3956 /* Follow collision chain, removing entries that
3957 don't survive this garbage collection. */
3958 prev = Qnil;
3959 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
3960 {
3961 EMACS_INT i = XFASTINT (idx);
3962 int key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
3963 int value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
3964 int remove_p;
3965
3966 if (EQ (h->weak, Qkey))
3967 remove_p = !key_known_to_survive_p;
3968 else if (EQ (h->weak, Qvalue))
3969 remove_p = !value_known_to_survive_p;
3970 else if (EQ (h->weak, Qkey_or_value))
3971 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
3972 else if (EQ (h->weak, Qkey_and_value))
3973 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
3974 else
3975 abort ();
3976
3977 next = HASH_NEXT (h, i);
3978
3979 if (remove_entries_p)
3980 {
3981 if (remove_p)
3982 {
3983 /* Take out of collision chain. */
3984 if (NILP (prev))
3985 HASH_INDEX (h, bucket) = next;
3986 else
3987 HASH_NEXT (h, XFASTINT (prev)) = next;
3988
3989 /* Add to free list. */
3990 HASH_NEXT (h, i) = h->next_free;
3991 h->next_free = idx;
3992
3993 /* Clear key, value, and hash. */
3994 HASH_KEY (h, i) = HASH_VALUE (h, i) = Qnil;
3995 HASH_HASH (h, i) = Qnil;
3996
3997 h->count--;
3998 }
3999 else
4000 {
4001 prev = idx;
4002 }
4003 }
4004 else
4005 {
4006 if (!remove_p)
4007 {
4008 /* Make sure key and value survive. */
4009 if (!key_known_to_survive_p)
4010 {
4011 mark_object (HASH_KEY (h, i));
4012 marked = 1;
4013 }
4014
4015 if (!value_known_to_survive_p)
4016 {
4017 mark_object (HASH_VALUE (h, i));
4018 marked = 1;
4019 }
4020 }
4021 }
4022 }
4023 }
4024
4025 return marked;
4026 }
4027
4028 /* Remove elements from weak hash tables that don't survive the
4029 current garbage collection. Remove weak tables that don't survive
4030 from Vweak_hash_tables. Called from gc_sweep. */
4031
4032 void
4033 sweep_weak_hash_tables (void)
4034 {
4035 struct Lisp_Hash_Table *h, *used, *next;
4036 int marked;
4037
4038 /* Mark all keys and values that are in use. Keep on marking until
4039 there is no more change. This is necessary for cases like
4040 value-weak table A containing an entry X -> Y, where Y is used in a
4041 key-weak table B, Z -> Y. If B comes after A in the list of weak
4042 tables, X -> Y might be removed from A, although when looking at B
4043 one finds that it shouldn't. */
4044 do
4045 {
4046 marked = 0;
4047 for (h = weak_hash_tables; h; h = h->next_weak)
4048 {
4049 if (h->header.size & ARRAY_MARK_FLAG)
4050 marked |= sweep_weak_table (h, 0);
4051 }
4052 }
4053 while (marked);
4054
4055 /* Remove tables and entries that aren't used. */
4056 for (h = weak_hash_tables, used = NULL; h; h = next)
4057 {
4058 next = h->next_weak;
4059
4060 if (h->header.size & ARRAY_MARK_FLAG)
4061 {
4062 /* TABLE is marked as used. Sweep its contents. */
4063 if (h->count > 0)
4064 sweep_weak_table (h, 1);
4065
4066 /* Add table to the list of used weak hash tables. */
4067 h->next_weak = used;
4068 used = h;
4069 }
4070 }
4071
4072 weak_hash_tables = used;
4073 }
4074
4075
4076 \f
4077 /***********************************************************************
4078 Hash Code Computation
4079 ***********************************************************************/
4080
4081 /* Maximum depth up to which to dive into Lisp structures. */
4082
4083 #define SXHASH_MAX_DEPTH 3
4084
4085 /* Maximum length up to which to take list and vector elements into
4086 account. */
4087
4088 #define SXHASH_MAX_LEN 7
4089
4090 /* Combine two integers X and Y for hashing. The result might not fit
4091 into a Lisp integer. */
4092
4093 #define SXHASH_COMBINE(X, Y) \
4094 ((((EMACS_UINT) (X) << 4) + ((EMACS_UINT) (X) >> (BITS_PER_EMACS_INT - 4))) \
4095 + (EMACS_UINT) (Y))
4096
4097 /* Hash X, returning a value that fits into a Lisp integer. */
4098 #define SXHASH_REDUCE(X) \
4099 ((((X) ^ (X) >> (BITS_PER_EMACS_INT - FIXNUM_BITS))) & INTMASK)
4100
4101 /* Return a hash for string PTR which has length LEN. The hash value
4102 can be any EMACS_UINT value. */
4103
4104 EMACS_UINT
4105 hash_string (char const *ptr, ptrdiff_t len)
4106 {
4107 char const *p = ptr;
4108 char const *end = p + len;
4109 unsigned char c;
4110 EMACS_UINT hash = 0;
4111
4112 while (p != end)
4113 {
4114 c = *p++;
4115 hash = SXHASH_COMBINE (hash, c);
4116 }
4117
4118 return hash;
4119 }
4120
4121 /* Return a hash for string PTR which has length LEN. The hash
4122 code returned is guaranteed to fit in a Lisp integer. */
4123
4124 static EMACS_UINT
4125 sxhash_string (char const *ptr, ptrdiff_t len)
4126 {
4127 EMACS_UINT hash = hash_string (ptr, len);
4128 return SXHASH_REDUCE (hash);
4129 }
4130
4131 /* Return a hash for the floating point value VAL. */
4132
4133 static EMACS_INT
4134 sxhash_float (double val)
4135 {
4136 EMACS_UINT hash = 0;
4137 enum {
4138 WORDS_PER_DOUBLE = (sizeof val / sizeof hash
4139 + (sizeof val % sizeof hash != 0))
4140 };
4141 union {
4142 double val;
4143 EMACS_UINT word[WORDS_PER_DOUBLE];
4144 } u;
4145 int i;
4146 u.val = val;
4147 memset (&u.val + 1, 0, sizeof u - sizeof u.val);
4148 for (i = 0; i < WORDS_PER_DOUBLE; i++)
4149 hash = SXHASH_COMBINE (hash, u.word[i]);
4150 return SXHASH_REDUCE (hash);
4151 }
4152
4153 /* Return a hash for list LIST. DEPTH is the current depth in the
4154 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4155
4156 static EMACS_UINT
4157 sxhash_list (Lisp_Object list, int depth)
4158 {
4159 EMACS_UINT hash = 0;
4160 int i;
4161
4162 if (depth < SXHASH_MAX_DEPTH)
4163 for (i = 0;
4164 CONSP (list) && i < SXHASH_MAX_LEN;
4165 list = XCDR (list), ++i)
4166 {
4167 EMACS_UINT hash2 = sxhash (XCAR (list), depth + 1);
4168 hash = SXHASH_COMBINE (hash, hash2);
4169 }
4170
4171 if (!NILP (list))
4172 {
4173 EMACS_UINT hash2 = sxhash (list, depth + 1);
4174 hash = SXHASH_COMBINE (hash, hash2);
4175 }
4176
4177 return SXHASH_REDUCE (hash);
4178 }
4179
4180
4181 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4182 the Lisp structure. */
4183
4184 static EMACS_UINT
4185 sxhash_vector (Lisp_Object vec, int depth)
4186 {
4187 EMACS_UINT hash = ASIZE (vec);
4188 int i, n;
4189
4190 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4191 for (i = 0; i < n; ++i)
4192 {
4193 EMACS_UINT hash2 = sxhash (AREF (vec, i), depth + 1);
4194 hash = SXHASH_COMBINE (hash, hash2);
4195 }
4196
4197 return SXHASH_REDUCE (hash);
4198 }
4199
4200 /* Return a hash for bool-vector VECTOR. */
4201
4202 static EMACS_UINT
4203 sxhash_bool_vector (Lisp_Object vec)
4204 {
4205 EMACS_UINT hash = XBOOL_VECTOR (vec)->size;
4206 int i, n;
4207
4208 n = min (SXHASH_MAX_LEN, XBOOL_VECTOR (vec)->header.size);
4209 for (i = 0; i < n; ++i)
4210 hash = SXHASH_COMBINE (hash, XBOOL_VECTOR (vec)->data[i]);
4211
4212 return SXHASH_REDUCE (hash);
4213 }
4214
4215
4216 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4217 structure. Value is an unsigned integer clipped to INTMASK. */
4218
4219 EMACS_UINT
4220 sxhash (Lisp_Object obj, int depth)
4221 {
4222 EMACS_UINT hash;
4223
4224 if (depth > SXHASH_MAX_DEPTH)
4225 return 0;
4226
4227 switch (XTYPE (obj))
4228 {
4229 case_Lisp_Int:
4230 hash = XUINT (obj);
4231 break;
4232
4233 case Lisp_Misc:
4234 hash = XUINT (obj);
4235 break;
4236
4237 case Lisp_Symbol:
4238 obj = SYMBOL_NAME (obj);
4239 /* Fall through. */
4240
4241 case Lisp_String:
4242 hash = sxhash_string (SSDATA (obj), SBYTES (obj));
4243 break;
4244
4245 /* This can be everything from a vector to an overlay. */
4246 case Lisp_Vectorlike:
4247 if (VECTORP (obj))
4248 /* According to the CL HyperSpec, two arrays are equal only if
4249 they are `eq', except for strings and bit-vectors. In
4250 Emacs, this works differently. We have to compare element
4251 by element. */
4252 hash = sxhash_vector (obj, depth);
4253 else if (BOOL_VECTOR_P (obj))
4254 hash = sxhash_bool_vector (obj);
4255 else
4256 /* Others are `equal' if they are `eq', so let's take their
4257 address as hash. */
4258 hash = XUINT (obj);
4259 break;
4260
4261 case Lisp_Cons:
4262 hash = sxhash_list (obj, depth);
4263 break;
4264
4265 case Lisp_Float:
4266 hash = sxhash_float (XFLOAT_DATA (obj));
4267 break;
4268
4269 default:
4270 abort ();
4271 }
4272
4273 return hash;
4274 }
4275
4276
4277 \f
4278 /***********************************************************************
4279 Lisp Interface
4280 ***********************************************************************/
4281
4282
4283 DEFUN ("sxhash", Fsxhash, Ssxhash, 1, 1, 0,
4284 doc: /* Compute a hash code for OBJ and return it as integer. */)
4285 (Lisp_Object obj)
4286 {
4287 EMACS_UINT hash = sxhash (obj, 0);
4288 return make_number (hash);
4289 }
4290
4291
4292 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4293 doc: /* Create and return a new hash table.
4294
4295 Arguments are specified as keyword/argument pairs. The following
4296 arguments are defined:
4297
4298 :test TEST -- TEST must be a symbol that specifies how to compare
4299 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4300 `equal'. User-supplied test and hash functions can be specified via
4301 `define-hash-table-test'.
4302
4303 :size SIZE -- A hint as to how many elements will be put in the table.
4304 Default is 65.
4305
4306 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4307 fills up. If REHASH-SIZE is an integer, increase the size by that
4308 amount. If it is a float, it must be > 1.0, and the new size is the
4309 old size multiplied by that factor. Default is 1.5.
4310
4311 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4312 Resize the hash table when the ratio (number of entries / table size)
4313 is greater than or equal to THRESHOLD. Default is 0.8.
4314
4315 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4316 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4317 returned is a weak table. Key/value pairs are removed from a weak
4318 hash table when there are no non-weak references pointing to their
4319 key, value, one of key or value, or both key and value, depending on
4320 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4321 is nil.
4322
4323 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4324 (ptrdiff_t nargs, Lisp_Object *args)
4325 {
4326 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4327 Lisp_Object user_test, user_hash;
4328 char *used;
4329 ptrdiff_t i;
4330
4331 /* The vector `used' is used to keep track of arguments that
4332 have been consumed. */
4333 used = (char *) alloca (nargs * sizeof *used);
4334 memset (used, 0, nargs * sizeof *used);
4335
4336 /* See if there's a `:test TEST' among the arguments. */
4337 i = get_key_arg (QCtest, nargs, args, used);
4338 test = i ? args[i] : Qeql;
4339 if (!EQ (test, Qeq) && !EQ (test, Qeql) && !EQ (test, Qequal))
4340 {
4341 /* See if it is a user-defined test. */
4342 Lisp_Object prop;
4343
4344 prop = Fget (test, Qhash_table_test);
4345 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4346 signal_error ("Invalid hash table test", test);
4347 user_test = XCAR (prop);
4348 user_hash = XCAR (XCDR (prop));
4349 }
4350 else
4351 user_test = user_hash = Qnil;
4352
4353 /* See if there's a `:size SIZE' argument. */
4354 i = get_key_arg (QCsize, nargs, args, used);
4355 size = i ? args[i] : Qnil;
4356 if (NILP (size))
4357 size = make_number (DEFAULT_HASH_SIZE);
4358 else if (!INTEGERP (size) || XINT (size) < 0)
4359 signal_error ("Invalid hash table size", size);
4360
4361 /* Look for `:rehash-size SIZE'. */
4362 i = get_key_arg (QCrehash_size, nargs, args, used);
4363 rehash_size = i ? args[i] : make_float (DEFAULT_REHASH_SIZE);
4364 if (! ((INTEGERP (rehash_size) && 0 < XINT (rehash_size))
4365 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size))))
4366 signal_error ("Invalid hash table rehash size", rehash_size);
4367
4368 /* Look for `:rehash-threshold THRESHOLD'. */
4369 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4370 rehash_threshold = i ? args[i] : make_float (DEFAULT_REHASH_THRESHOLD);
4371 if (! (FLOATP (rehash_threshold)
4372 && 0 < XFLOAT_DATA (rehash_threshold)
4373 && XFLOAT_DATA (rehash_threshold) <= 1))
4374 signal_error ("Invalid hash table rehash threshold", rehash_threshold);
4375
4376 /* Look for `:weakness WEAK'. */
4377 i = get_key_arg (QCweakness, nargs, args, used);
4378 weak = i ? args[i] : Qnil;
4379 if (EQ (weak, Qt))
4380 weak = Qkey_and_value;
4381 if (!NILP (weak)
4382 && !EQ (weak, Qkey)
4383 && !EQ (weak, Qvalue)
4384 && !EQ (weak, Qkey_or_value)
4385 && !EQ (weak, Qkey_and_value))
4386 signal_error ("Invalid hash table weakness", weak);
4387
4388 /* Now, all args should have been used up, or there's a problem. */
4389 for (i = 0; i < nargs; ++i)
4390 if (!used[i])
4391 signal_error ("Invalid argument list", args[i]);
4392
4393 return make_hash_table (test, size, rehash_size, rehash_threshold, weak,
4394 user_test, user_hash);
4395 }
4396
4397
4398 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4399 doc: /* Return a copy of hash table TABLE. */)
4400 (Lisp_Object table)
4401 {
4402 return copy_hash_table (check_hash_table (table));
4403 }
4404
4405
4406 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4407 doc: /* Return the number of elements in TABLE. */)
4408 (Lisp_Object table)
4409 {
4410 return make_number (check_hash_table (table)->count);
4411 }
4412
4413
4414 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4415 Shash_table_rehash_size, 1, 1, 0,
4416 doc: /* Return the current rehash size of TABLE. */)
4417 (Lisp_Object table)
4418 {
4419 return check_hash_table (table)->rehash_size;
4420 }
4421
4422
4423 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4424 Shash_table_rehash_threshold, 1, 1, 0,
4425 doc: /* Return the current rehash threshold of TABLE. */)
4426 (Lisp_Object table)
4427 {
4428 return check_hash_table (table)->rehash_threshold;
4429 }
4430
4431
4432 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4433 doc: /* Return the size of TABLE.
4434 The size can be used as an argument to `make-hash-table' to create
4435 a hash table than can hold as many elements as TABLE holds
4436 without need for resizing. */)
4437 (Lisp_Object table)
4438 {
4439 struct Lisp_Hash_Table *h = check_hash_table (table);
4440 return make_number (HASH_TABLE_SIZE (h));
4441 }
4442
4443
4444 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4445 doc: /* Return the test TABLE uses. */)
4446 (Lisp_Object table)
4447 {
4448 return check_hash_table (table)->test;
4449 }
4450
4451
4452 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4453 1, 1, 0,
4454 doc: /* Return the weakness of TABLE. */)
4455 (Lisp_Object table)
4456 {
4457 return check_hash_table (table)->weak;
4458 }
4459
4460
4461 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4462 doc: /* Return t if OBJ is a Lisp hash table object. */)
4463 (Lisp_Object obj)
4464 {
4465 return HASH_TABLE_P (obj) ? Qt : Qnil;
4466 }
4467
4468
4469 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4470 doc: /* Clear hash table TABLE and return it. */)
4471 (Lisp_Object table)
4472 {
4473 hash_clear (check_hash_table (table));
4474 /* Be compatible with XEmacs. */
4475 return table;
4476 }
4477
4478
4479 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4480 doc: /* Look up KEY in TABLE and return its associated value.
4481 If KEY is not found, return DFLT which defaults to nil. */)
4482 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4483 {
4484 struct Lisp_Hash_Table *h = check_hash_table (table);
4485 EMACS_INT i = hash_lookup (h, key, NULL);
4486 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4487 }
4488
4489
4490 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4491 doc: /* Associate KEY with VALUE in hash table TABLE.
4492 If KEY is already present in table, replace its current value with
4493 VALUE. In any case, return VALUE. */)
4494 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4495 {
4496 struct Lisp_Hash_Table *h = check_hash_table (table);
4497 EMACS_INT i;
4498 EMACS_UINT hash;
4499
4500 i = hash_lookup (h, key, &hash);
4501 if (i >= 0)
4502 HASH_VALUE (h, i) = value;
4503 else
4504 hash_put (h, key, value, hash);
4505
4506 return value;
4507 }
4508
4509
4510 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4511 doc: /* Remove KEY from TABLE. */)
4512 (Lisp_Object key, Lisp_Object table)
4513 {
4514 struct Lisp_Hash_Table *h = check_hash_table (table);
4515 hash_remove_from_table (h, key);
4516 return Qnil;
4517 }
4518
4519
4520 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4521 doc: /* Call FUNCTION for all entries in hash table TABLE.
4522 FUNCTION is called with two arguments, KEY and VALUE. */)
4523 (Lisp_Object function, Lisp_Object table)
4524 {
4525 struct Lisp_Hash_Table *h = check_hash_table (table);
4526 Lisp_Object args[3];
4527 EMACS_INT i;
4528
4529 for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
4530 if (!NILP (HASH_HASH (h, i)))
4531 {
4532 args[0] = function;
4533 args[1] = HASH_KEY (h, i);
4534 args[2] = HASH_VALUE (h, i);
4535 Ffuncall (3, args);
4536 }
4537
4538 return Qnil;
4539 }
4540
4541
4542 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4543 Sdefine_hash_table_test, 3, 3, 0,
4544 doc: /* Define a new hash table test with name NAME, a symbol.
4545
4546 In hash tables created with NAME specified as test, use TEST to
4547 compare keys, and HASH for computing hash codes of keys.
4548
4549 TEST must be a function taking two arguments and returning non-nil if
4550 both arguments are the same. HASH must be a function taking one
4551 argument and return an integer that is the hash code of the argument.
4552 Hash code computation should use the whole value range of integers,
4553 including negative integers. */)
4554 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4555 {
4556 return Fput (name, Qhash_table_test, list2 (test, hash));
4557 }
4558
4559
4560 \f
4561 /************************************************************************
4562 MD5, SHA-1, and SHA-2
4563 ************************************************************************/
4564
4565 #include "md5.h"
4566 #include "sha1.h"
4567 #include "sha256.h"
4568 #include "sha512.h"
4569
4570 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4571
4572 static Lisp_Object
4573 secure_hash (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror, Lisp_Object binary)
4574 {
4575 int i;
4576 EMACS_INT size;
4577 EMACS_INT size_byte = 0;
4578 EMACS_INT start_char = 0, end_char = 0;
4579 EMACS_INT start_byte = 0, end_byte = 0;
4580 register EMACS_INT b, e;
4581 register struct buffer *bp;
4582 EMACS_INT temp;
4583 int digest_size;
4584 void *(*hash_func) (const char *, size_t, void *);
4585 Lisp_Object digest;
4586
4587 CHECK_SYMBOL (algorithm);
4588
4589 if (STRINGP (object))
4590 {
4591 if (NILP (coding_system))
4592 {
4593 /* Decide the coding-system to encode the data with. */
4594
4595 if (STRING_MULTIBYTE (object))
4596 /* use default, we can't guess correct value */
4597 coding_system = preferred_coding_system ();
4598 else
4599 coding_system = Qraw_text;
4600 }
4601
4602 if (NILP (Fcoding_system_p (coding_system)))
4603 {
4604 /* Invalid coding system. */
4605
4606 if (!NILP (noerror))
4607 coding_system = Qraw_text;
4608 else
4609 xsignal1 (Qcoding_system_error, coding_system);
4610 }
4611
4612 if (STRING_MULTIBYTE (object))
4613 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4614
4615 size = SCHARS (object);
4616 size_byte = SBYTES (object);
4617
4618 if (!NILP (start))
4619 {
4620 CHECK_NUMBER (start);
4621
4622 start_char = XINT (start);
4623
4624 if (start_char < 0)
4625 start_char += size;
4626
4627 start_byte = string_char_to_byte (object, start_char);
4628 }
4629
4630 if (NILP (end))
4631 {
4632 end_char = size;
4633 end_byte = size_byte;
4634 }
4635 else
4636 {
4637 CHECK_NUMBER (end);
4638
4639 end_char = XINT (end);
4640
4641 if (end_char < 0)
4642 end_char += size;
4643
4644 end_byte = string_char_to_byte (object, end_char);
4645 }
4646
4647 if (!(0 <= start_char && start_char <= end_char && end_char <= size))
4648 args_out_of_range_3 (object, make_number (start_char),
4649 make_number (end_char));
4650 }
4651 else
4652 {
4653 struct buffer *prev = current_buffer;
4654
4655 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
4656
4657 CHECK_BUFFER (object);
4658
4659 bp = XBUFFER (object);
4660 if (bp != current_buffer)
4661 set_buffer_internal (bp);
4662
4663 if (NILP (start))
4664 b = BEGV;
4665 else
4666 {
4667 CHECK_NUMBER_COERCE_MARKER (start);
4668 b = XINT (start);
4669 }
4670
4671 if (NILP (end))
4672 e = ZV;
4673 else
4674 {
4675 CHECK_NUMBER_COERCE_MARKER (end);
4676 e = XINT (end);
4677 }
4678
4679 if (b > e)
4680 temp = b, b = e, e = temp;
4681
4682 if (!(BEGV <= b && e <= ZV))
4683 args_out_of_range (start, end);
4684
4685 if (NILP (coding_system))
4686 {
4687 /* Decide the coding-system to encode the data with.
4688 See fileio.c:Fwrite-region */
4689
4690 if (!NILP (Vcoding_system_for_write))
4691 coding_system = Vcoding_system_for_write;
4692 else
4693 {
4694 int force_raw_text = 0;
4695
4696 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4697 if (NILP (coding_system)
4698 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4699 {
4700 coding_system = Qnil;
4701 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4702 force_raw_text = 1;
4703 }
4704
4705 if (NILP (coding_system) && !NILP (Fbuffer_file_name(object)))
4706 {
4707 /* Check file-coding-system-alist. */
4708 Lisp_Object args[4], val;
4709
4710 args[0] = Qwrite_region; args[1] = start; args[2] = end;
4711 args[3] = Fbuffer_file_name(object);
4712 val = Ffind_operation_coding_system (4, args);
4713 if (CONSP (val) && !NILP (XCDR (val)))
4714 coding_system = XCDR (val);
4715 }
4716
4717 if (NILP (coding_system)
4718 && !NILP (BVAR (XBUFFER (object), buffer_file_coding_system)))
4719 {
4720 /* If we still have not decided a coding system, use the
4721 default value of buffer-file-coding-system. */
4722 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4723 }
4724
4725 if (!force_raw_text
4726 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4727 /* Confirm that VAL can surely encode the current region. */
4728 coding_system = call4 (Vselect_safe_coding_system_function,
4729 make_number (b), make_number (e),
4730 coding_system, Qnil);
4731
4732 if (force_raw_text)
4733 coding_system = Qraw_text;
4734 }
4735
4736 if (NILP (Fcoding_system_p (coding_system)))
4737 {
4738 /* Invalid coding system. */
4739
4740 if (!NILP (noerror))
4741 coding_system = Qraw_text;
4742 else
4743 xsignal1 (Qcoding_system_error, coding_system);
4744 }
4745 }
4746
4747 object = make_buffer_string (b, e, 0);
4748 if (prev != current_buffer)
4749 set_buffer_internal (prev);
4750 /* Discard the unwind protect for recovering the current
4751 buffer. */
4752 specpdl_ptr--;
4753
4754 if (STRING_MULTIBYTE (object))
4755 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4756 }
4757
4758 if (EQ (algorithm, Qmd5))
4759 {
4760 digest_size = MD5_DIGEST_SIZE;
4761 hash_func = md5_buffer;
4762 }
4763 else if (EQ (algorithm, Qsha1))
4764 {
4765 digest_size = SHA1_DIGEST_SIZE;
4766 hash_func = sha1_buffer;
4767 }
4768 else if (EQ (algorithm, Qsha224))
4769 {
4770 digest_size = SHA224_DIGEST_SIZE;
4771 hash_func = sha224_buffer;
4772 }
4773 else if (EQ (algorithm, Qsha256))
4774 {
4775 digest_size = SHA256_DIGEST_SIZE;
4776 hash_func = sha256_buffer;
4777 }
4778 else if (EQ (algorithm, Qsha384))
4779 {
4780 digest_size = SHA384_DIGEST_SIZE;
4781 hash_func = sha384_buffer;
4782 }
4783 else if (EQ (algorithm, Qsha512))
4784 {
4785 digest_size = SHA512_DIGEST_SIZE;
4786 hash_func = sha512_buffer;
4787 }
4788 else
4789 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm)));
4790
4791 /* allocate 2 x digest_size so that it can be re-used to hold the
4792 hexified value */
4793 digest = make_uninit_string (digest_size * 2);
4794
4795 hash_func (SSDATA (object) + start_byte,
4796 SBYTES (object) - (size_byte - end_byte),
4797 SSDATA (digest));
4798
4799 if (NILP (binary))
4800 {
4801 unsigned char *p = SDATA (digest);
4802 for (i = digest_size - 1; i >= 0; i--)
4803 {
4804 static char const hexdigit[16] = "0123456789abcdef";
4805 int p_i = p[i];
4806 p[2 * i] = hexdigit[p_i >> 4];
4807 p[2 * i + 1] = hexdigit[p_i & 0xf];
4808 }
4809 return digest;
4810 }
4811 else
4812 return make_unibyte_string (SSDATA (digest), digest_size);
4813 }
4814
4815 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
4816 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
4817
4818 A message digest is a cryptographic checksum of a document, and the
4819 algorithm to calculate it is defined in RFC 1321.
4820
4821 The two optional arguments START and END are character positions
4822 specifying for which part of OBJECT the message digest should be
4823 computed. If nil or omitted, the digest is computed for the whole
4824 OBJECT.
4825
4826 The MD5 message digest is computed from the result of encoding the
4827 text in a coding system, not directly from the internal Emacs form of
4828 the text. The optional fourth argument CODING-SYSTEM specifies which
4829 coding system to encode the text with. It should be the same coding
4830 system that you used or will use when actually writing the text into a
4831 file.
4832
4833 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
4834 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
4835 system would be chosen by default for writing this text into a file.
4836
4837 If OBJECT is a string, the most preferred coding system (see the
4838 command `prefer-coding-system') is used.
4839
4840 If NOERROR is non-nil, silently assume the `raw-text' coding if the
4841 guesswork fails. Normally, an error is signaled in such case. */)
4842 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
4843 {
4844 return secure_hash (Qmd5, object, start, end, coding_system, noerror, Qnil);
4845 }
4846
4847 DEFUN ("secure-hash", Fsecure_hash, Ssecure_hash, 2, 5, 0,
4848 doc: /* Return the secure hash of an OBJECT.
4849 ALGORITHM is a symbol: md5, sha1, sha224, sha256, sha384 or sha512.
4850 OBJECT is either a string or a buffer.
4851 Optional arguments START and END are character positions specifying
4852 which portion of OBJECT for computing the hash. If BINARY is non-nil,
4853 return a string in binary form. */)
4854 (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object binary)
4855 {
4856 return secure_hash (algorithm, object, start, end, Qnil, Qnil, binary);
4857 }
4858 \f
4859 void
4860 syms_of_fns (void)
4861 {
4862 DEFSYM (Qmd5, "md5");
4863 DEFSYM (Qsha1, "sha1");
4864 DEFSYM (Qsha224, "sha224");
4865 DEFSYM (Qsha256, "sha256");
4866 DEFSYM (Qsha384, "sha384");
4867 DEFSYM (Qsha512, "sha512");
4868
4869 /* Hash table stuff. */
4870 DEFSYM (Qhash_table_p, "hash-table-p");
4871 DEFSYM (Qeq, "eq");
4872 DEFSYM (Qeql, "eql");
4873 DEFSYM (Qequal, "equal");
4874 DEFSYM (QCtest, ":test");
4875 DEFSYM (QCsize, ":size");
4876 DEFSYM (QCrehash_size, ":rehash-size");
4877 DEFSYM (QCrehash_threshold, ":rehash-threshold");
4878 DEFSYM (QCweakness, ":weakness");
4879 DEFSYM (Qkey, "key");
4880 DEFSYM (Qvalue, "value");
4881 DEFSYM (Qhash_table_test, "hash-table-test");
4882 DEFSYM (Qkey_or_value, "key-or-value");
4883 DEFSYM (Qkey_and_value, "key-and-value");
4884
4885 defsubr (&Ssxhash);
4886 defsubr (&Smake_hash_table);
4887 defsubr (&Scopy_hash_table);
4888 defsubr (&Shash_table_count);
4889 defsubr (&Shash_table_rehash_size);
4890 defsubr (&Shash_table_rehash_threshold);
4891 defsubr (&Shash_table_size);
4892 defsubr (&Shash_table_test);
4893 defsubr (&Shash_table_weakness);
4894 defsubr (&Shash_table_p);
4895 defsubr (&Sclrhash);
4896 defsubr (&Sgethash);
4897 defsubr (&Sputhash);
4898 defsubr (&Sremhash);
4899 defsubr (&Smaphash);
4900 defsubr (&Sdefine_hash_table_test);
4901
4902 DEFSYM (Qstring_lessp, "string-lessp");
4903 DEFSYM (Qprovide, "provide");
4904 DEFSYM (Qrequire, "require");
4905 DEFSYM (Qyes_or_no_p_history, "yes-or-no-p-history");
4906 DEFSYM (Qcursor_in_echo_area, "cursor-in-echo-area");
4907 DEFSYM (Qwidget_type, "widget-type");
4908
4909 staticpro (&string_char_byte_cache_string);
4910 string_char_byte_cache_string = Qnil;
4911
4912 require_nesting_list = Qnil;
4913 staticpro (&require_nesting_list);
4914
4915 Fset (Qyes_or_no_p_history, Qnil);
4916
4917 DEFVAR_LISP ("features", Vfeatures,
4918 doc: /* A list of symbols which are the features of the executing Emacs.
4919 Used by `featurep' and `require', and altered by `provide'. */);
4920 Vfeatures = Fcons (intern_c_string ("emacs"), Qnil);
4921 DEFSYM (Qsubfeatures, "subfeatures");
4922
4923 #ifdef HAVE_LANGINFO_CODESET
4924 DEFSYM (Qcodeset, "codeset");
4925 DEFSYM (Qdays, "days");
4926 DEFSYM (Qmonths, "months");
4927 DEFSYM (Qpaper, "paper");
4928 #endif /* HAVE_LANGINFO_CODESET */
4929
4930 DEFVAR_BOOL ("use-dialog-box", use_dialog_box,
4931 doc: /* *Non-nil means mouse commands use dialog boxes to ask questions.
4932 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
4933 invoked by mouse clicks and mouse menu items.
4934
4935 On some platforms, file selection dialogs are also enabled if this is
4936 non-nil. */);
4937 use_dialog_box = 1;
4938
4939 DEFVAR_BOOL ("use-file-dialog", use_file_dialog,
4940 doc: /* *Non-nil means mouse commands use a file dialog to ask for files.
4941 This applies to commands from menus and tool bar buttons even when
4942 they are initiated from the keyboard. If `use-dialog-box' is nil,
4943 that disables the use of a file dialog, regardless of the value of
4944 this variable. */);
4945 use_file_dialog = 1;
4946
4947 defsubr (&Sidentity);
4948 defsubr (&Srandom);
4949 defsubr (&Slength);
4950 defsubr (&Ssafe_length);
4951 defsubr (&Sstring_bytes);
4952 defsubr (&Sstring_equal);
4953 defsubr (&Scompare_strings);
4954 defsubr (&Sstring_lessp);
4955 defsubr (&Sappend);
4956 defsubr (&Sconcat);
4957 defsubr (&Svconcat);
4958 defsubr (&Scopy_sequence);
4959 defsubr (&Sstring_make_multibyte);
4960 defsubr (&Sstring_make_unibyte);
4961 defsubr (&Sstring_as_multibyte);
4962 defsubr (&Sstring_as_unibyte);
4963 defsubr (&Sstring_to_multibyte);
4964 defsubr (&Sstring_to_unibyte);
4965 defsubr (&Scopy_alist);
4966 defsubr (&Ssubstring);
4967 defsubr (&Ssubstring_no_properties);
4968 defsubr (&Snthcdr);
4969 defsubr (&Snth);
4970 defsubr (&Selt);
4971 defsubr (&Smember);
4972 defsubr (&Smemq);
4973 defsubr (&Smemql);
4974 defsubr (&Sassq);
4975 defsubr (&Sassoc);
4976 defsubr (&Srassq);
4977 defsubr (&Srassoc);
4978 defsubr (&Sdelq);
4979 defsubr (&Sdelete);
4980 defsubr (&Snreverse);
4981 defsubr (&Sreverse);
4982 defsubr (&Ssort);
4983 defsubr (&Splist_get);
4984 defsubr (&Sget);
4985 defsubr (&Splist_put);
4986 defsubr (&Sput);
4987 defsubr (&Slax_plist_get);
4988 defsubr (&Slax_plist_put);
4989 defsubr (&Seql);
4990 defsubr (&Sequal);
4991 defsubr (&Sequal_including_properties);
4992 defsubr (&Sfillarray);
4993 defsubr (&Sclear_string);
4994 defsubr (&Snconc);
4995 defsubr (&Smapcar);
4996 defsubr (&Smapc);
4997 defsubr (&Smapconcat);
4998 defsubr (&Syes_or_no_p);
4999 defsubr (&Sload_average);
5000 defsubr (&Sfeaturep);
5001 defsubr (&Srequire);
5002 defsubr (&Sprovide);
5003 defsubr (&Splist_member);
5004 defsubr (&Swidget_put);
5005 defsubr (&Swidget_get);
5006 defsubr (&Swidget_apply);
5007 defsubr (&Sbase64_encode_region);
5008 defsubr (&Sbase64_decode_region);
5009 defsubr (&Sbase64_encode_string);
5010 defsubr (&Sbase64_decode_string);
5011 defsubr (&Smd5);
5012 defsubr (&Ssecure_hash);
5013 defsubr (&Slocale_info);
5014 }
5015
5016
5017 void
5018 init_fns (void)
5019 {
5020 }