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