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