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