1 /* Random utility Lisp functions.
3 Copyright (C) 1985-1987, 1993-1995, 1997-2017 Free Software Foundation,
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
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.
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/>. */
25 #include <filevercmp.h>
31 #include "character.h"
33 #include "composite.h"
35 #include "intervals.h"
39 static void sort_vector_copy (Lisp_Object
, ptrdiff_t,
40 Lisp_Object
*restrict
, Lisp_Object
*restrict
);
41 enum equal_kind
{ EQUAL_NO_QUIT
, EQUAL_PLAIN
, EQUAL_INCLUDING_PROPERTIES
};
42 static bool internal_equal (Lisp_Object
, Lisp_Object
,
43 enum equal_kind
, int, Lisp_Object
);
45 DEFUN ("identity", Fidentity
, Sidentity
, 1, 1, 0,
46 doc
: /* Return the argument unchanged. */
53 DEFUN ("random", Frandom
, Srandom
, 0, 1, 0,
54 doc
: /* Return a pseudo-random number.
55 All integers representable in Lisp, i.e. between `most-negative-fixnum'
56 and `most-positive-fixnum', inclusive, are equally likely.
58 With positive integer LIMIT, return random number in interval [0,LIMIT).
59 With argument t, set the random number seed from the system's entropy
60 pool if available, otherwise from less-random volatile data such as the time.
61 With a string argument, set the seed based on the string's contents.
62 Other values of LIMIT are ignored.
64 See Info node `(elisp)Random Numbers' for more details. */)
71 else if (STRINGP (limit
))
72 seed_random (SSDATA (limit
), SBYTES (limit
));
75 if (INTEGERP (limit
) && 0 < XINT (limit
))
78 /* Return the remainder, except reject the rare case where
79 get_random returns a number so close to INTMASK that the
80 remainder isn't random. */
81 EMACS_INT remainder
= val
% XINT (limit
);
82 if (val
- remainder
<= INTMASK
- XINT (limit
) + 1)
83 return make_number (remainder
);
86 return make_number (val
);
89 /* Random data-structure functions. */
91 DEFUN ("length", Flength
, Slength
, 1, 1, 0,
92 doc
: /* Return the length of vector, list or string SEQUENCE.
93 A byte-code function object is also allowed.
94 If the string contains multibyte characters, this is not necessarily
95 the number of bytes in the string; it is the number of characters.
96 To get the number of bytes, use `string-bytes'. */)
97 (register Lisp_Object sequence
)
99 register Lisp_Object val
;
101 if (STRINGP (sequence
))
102 XSETFASTINT (val
, SCHARS (sequence
));
103 else if (VECTORP (sequence
))
104 XSETFASTINT (val
, ASIZE (sequence
));
105 else if (CHAR_TABLE_P (sequence
))
106 XSETFASTINT (val
, MAX_CHAR
);
107 else if (BOOL_VECTOR_P (sequence
))
108 XSETFASTINT (val
, bool_vector_size (sequence
));
109 else if (COMPILEDP (sequence
) || RECORDP (sequence
))
110 XSETFASTINT (val
, PVSIZE (sequence
));
111 else if (CONSP (sequence
))
114 FOR_EACH_TAIL (sequence
)
116 CHECK_LIST_END (sequence
, sequence
);
117 if (MOST_POSITIVE_FIXNUM
< i
)
118 error ("List too long");
119 val
= make_number (i
);
121 else if (NILP (sequence
))
122 XSETFASTINT (val
, 0);
124 wrong_type_argument (Qsequencep
, sequence
);
129 DEFUN ("safe-length", Fsafe_length
, Ssafe_length
, 1, 1, 0,
130 doc
: /* Return the length of a list, but avoid error or infinite loop.
131 This function never gets an error. If LIST is not really a list,
132 it returns 0. If LIST is circular, it returns a finite value
133 which is at least the number of distinct elements. */)
137 FOR_EACH_TAIL_SAFE (list
)
139 return make_fixnum_or_float (len
);
142 DEFUN ("string-bytes", Fstring_bytes
, Sstring_bytes
, 1, 1, 0,
143 doc
: /* Return the number of bytes in STRING.
144 If STRING is multibyte, this may be greater than the length of STRING. */)
147 CHECK_STRING (string
);
148 return make_number (SBYTES (string
));
151 DEFUN ("string-equal", Fstring_equal
, Sstring_equal
, 2, 2, 0,
152 doc
: /* Return t if two strings have identical contents.
153 Case is significant, but text properties are ignored.
154 Symbols are also allowed; their print names are used instead. */)
155 (register Lisp_Object s1
, Lisp_Object s2
)
158 s1
= SYMBOL_NAME (s1
);
160 s2
= SYMBOL_NAME (s2
);
164 if (SCHARS (s1
) != SCHARS (s2
)
165 || SBYTES (s1
) != SBYTES (s2
)
166 || memcmp (SDATA (s1
), SDATA (s2
), SBYTES (s1
)))
171 DEFUN ("compare-strings", Fcompare_strings
, Scompare_strings
, 6, 7, 0,
172 doc
: /* Compare the contents of two strings, converting to multibyte if needed.
173 The arguments START1, END1, START2, and END2, if non-nil, are
174 positions specifying which parts of STR1 or STR2 to compare. In
175 string STR1, compare the part between START1 (inclusive) and END1
176 \(exclusive). If START1 is nil, it defaults to 0, the beginning of
177 the string; if END1 is nil, it defaults to the length of the string.
178 Likewise, in string STR2, compare the part between START2 and END2.
179 Like in `substring', negative values are counted from the end.
181 The strings are compared by the numeric values of their characters.
182 For instance, STR1 is "less than" STR2 if its first differing
183 character has a smaller numeric value. If IGNORE-CASE is non-nil,
184 characters are converted to upper-case before comparing them. Unibyte
185 strings are converted to multibyte for comparison.
187 The value is t if the strings (or specified portions) match.
188 If string STR1 is less, the value is a negative number N;
189 - 1 - N is the number of characters that match at the beginning.
190 If string STR1 is greater, the value is a positive number N;
191 N - 1 is the number of characters that match at the beginning. */)
192 (Lisp_Object str1
, Lisp_Object start1
, Lisp_Object end1
, Lisp_Object str2
,
193 Lisp_Object start2
, Lisp_Object end2
, Lisp_Object ignore_case
)
195 ptrdiff_t from1
, to1
, from2
, to2
, i1
, i1_byte
, i2
, i2_byte
;
200 /* For backward compatibility, silently bring too-large positive end
201 values into range. */
202 if (INTEGERP (end1
) && SCHARS (str1
) < XINT (end1
))
203 end1
= make_number (SCHARS (str1
));
204 if (INTEGERP (end2
) && SCHARS (str2
) < XINT (end2
))
205 end2
= make_number (SCHARS (str2
));
207 validate_subarray (str1
, start1
, end1
, SCHARS (str1
), &from1
, &to1
);
208 validate_subarray (str2
, start2
, end2
, SCHARS (str2
), &from2
, &to2
);
213 i1_byte
= string_char_to_byte (str1
, i1
);
214 i2_byte
= string_char_to_byte (str2
, i2
);
216 while (i1
< to1
&& i2
< to2
)
218 /* When we find a mismatch, we must compare the
219 characters, not just the bytes. */
222 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c1
, str1
, i1
, i1_byte
);
223 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c2
, str2
, i2
, i2_byte
);
228 if (! NILP (ignore_case
))
230 c1
= XINT (Fupcase (make_number (c1
)));
231 c2
= XINT (Fupcase (make_number (c2
)));
237 /* Note that I1 has already been incremented
238 past the character that we are comparing;
239 hence we don't add or subtract 1 here. */
241 return make_number (- i1
+ from1
);
243 return make_number (i1
- from1
);
247 return make_number (i1
- from1
+ 1);
249 return make_number (- i1
+ from1
- 1);
254 DEFUN ("string-lessp", Fstring_lessp
, Sstring_lessp
, 2, 2, 0,
255 doc
: /* Return non-nil if STRING1 is less than STRING2 in lexicographic order.
257 Symbols are also allowed; their print names are used instead. */)
258 (register Lisp_Object string1
, Lisp_Object string2
)
260 register ptrdiff_t end
;
261 register ptrdiff_t i1
, i1_byte
, i2
, i2_byte
;
263 if (SYMBOLP (string1
))
264 string1
= SYMBOL_NAME (string1
);
265 if (SYMBOLP (string2
))
266 string2
= SYMBOL_NAME (string2
);
267 CHECK_STRING (string1
);
268 CHECK_STRING (string2
);
270 i1
= i1_byte
= i2
= i2_byte
= 0;
272 end
= SCHARS (string1
);
273 if (end
> SCHARS (string2
))
274 end
= SCHARS (string2
);
278 /* When we find a mismatch, we must compare the
279 characters, not just the bytes. */
282 FETCH_STRING_CHAR_ADVANCE (c1
, string1
, i1
, i1_byte
);
283 FETCH_STRING_CHAR_ADVANCE (c2
, string2
, i2
, i2_byte
);
286 return c1
< c2
? Qt
: Qnil
;
288 return i1
< SCHARS (string2
) ? Qt
: Qnil
;
291 DEFUN ("string-version-lessp", Fstring_version_lessp
,
292 Sstring_version_lessp
, 2, 2, 0,
293 doc
: /* Return non-nil if S1 is less than S2, as version strings.
295 This function compares version strings S1 and S2:
296 1) By prefix lexicographically.
297 2) Then by version (similarly to version comparison of Debian's dpkg).
298 Leading zeros in version numbers are ignored.
299 3) If both prefix and version are equal, compare as ordinary strings.
301 For example, \"foo2.png\" compares less than \"foo12.png\".
303 Symbols are also allowed; their print names are used instead. */)
304 (Lisp_Object string1
, Lisp_Object string2
)
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
);
313 char *p1
= SSDATA (string1
);
314 char *p2
= SSDATA (string2
);
315 char *lim1
= p1
+ SBYTES (string1
);
316 char *lim2
= p2
+ SBYTES (string2
);
319 while ((cmp
= filevercmp (p1
, p2
)) == 0)
321 /* If the strings are identical through their first null bytes,
322 skip past identical prefixes and try again. */
323 ptrdiff_t size
= strlen (p1
) + 1;
327 return lim2
< p2
? Qnil
: Qt
;
332 return cmp
< 0 ? Qt
: Qnil
;
335 DEFUN ("string-collate-lessp", Fstring_collate_lessp
, Sstring_collate_lessp
, 2, 4, 0,
336 doc
: /* Return t if first arg string is less than second in collation order.
337 Symbols are also allowed; their print names are used instead.
339 This function obeys the conventions for collation order in your
340 locale settings. For example, punctuation and whitespace characters
341 might be considered less significant for sorting:
343 \(sort \\='("11" "12" "1 1" "1 2" "1.1" "1.2") \\='string-collate-lessp)
344 => ("11" "1 1" "1.1" "12" "1 2" "1.2")
346 The optional argument LOCALE, a string, overrides the setting of your
347 current locale identifier for collation. The value is system
348 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
349 while it would be, e.g., \"enu_USA.1252\" on MS-Windows systems.
351 If IGNORE-CASE is non-nil, characters are converted to lower-case
352 before comparing them.
354 To emulate Unicode-compliant collation on MS-Windows systems,
355 bind `w32-collate-ignore-punctuation' to a non-nil value, since
356 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
358 If your system does not support a locale environment, this function
359 behaves like `string-lessp'. */)
360 (Lisp_Object s1
, Lisp_Object s2
, Lisp_Object locale
, Lisp_Object ignore_case
)
362 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
363 /* Check parameters. */
365 s1
= SYMBOL_NAME (s1
);
367 s2
= SYMBOL_NAME (s2
);
371 CHECK_STRING (locale
);
373 return (str_collate (s1
, s2
, locale
, ignore_case
) < 0) ? Qt
: Qnil
;
375 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
376 return Fstring_lessp (s1
, s2
);
377 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
380 DEFUN ("string-collate-equalp", Fstring_collate_equalp
, Sstring_collate_equalp
, 2, 4, 0,
381 doc
: /* Return t if two strings have identical contents.
382 Symbols are also allowed; their print names are used instead.
384 This function obeys the conventions for collation order in your locale
385 settings. For example, characters with different coding points but
386 the same meaning might be considered as equal, like different grave
387 accent Unicode characters:
389 \(string-collate-equalp (string ?\\uFF40) (string ?\\u1FEF))
392 The optional argument LOCALE, a string, overrides the setting of your
393 current locale identifier for collation. The value is system
394 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
395 while it would be \"enu_USA.1252\" on MS Windows systems.
397 If IGNORE-CASE is non-nil, characters are converted to lower-case
398 before comparing them.
400 To emulate Unicode-compliant collation on MS-Windows systems,
401 bind `w32-collate-ignore-punctuation' to a non-nil value, since
402 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
404 If your system does not support a locale environment, this function
405 behaves like `string-equal'.
407 Do NOT use this function to compare file names for equality. */)
408 (Lisp_Object s1
, Lisp_Object s2
, Lisp_Object locale
, Lisp_Object ignore_case
)
410 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
411 /* Check parameters. */
413 s1
= SYMBOL_NAME (s1
);
415 s2
= SYMBOL_NAME (s2
);
419 CHECK_STRING (locale
);
421 return (str_collate (s1
, s2
, locale
, ignore_case
) == 0) ? Qt
: Qnil
;
423 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
424 return Fstring_equal (s1
, s2
);
425 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
428 static Lisp_Object
concat (ptrdiff_t nargs
, Lisp_Object
*args
,
429 enum Lisp_Type target_type
, bool last_special
);
433 concat2 (Lisp_Object s1
, Lisp_Object s2
)
435 return concat (2, ((Lisp_Object
[]) {s1
, s2
}), Lisp_String
, 0);
440 concat3 (Lisp_Object s1
, Lisp_Object s2
, Lisp_Object s3
)
442 return concat (3, ((Lisp_Object
[]) {s1
, s2
, s3
}), Lisp_String
, 0);
445 DEFUN ("append", Fappend
, Sappend
, 0, MANY
, 0,
446 doc
: /* Concatenate all the arguments and make the result a list.
447 The result is a list whose elements are the elements of all the arguments.
448 Each argument may be a list, vector or string.
449 The last argument is not copied, just used as the tail of the new list.
450 usage: (append &rest SEQUENCES) */)
451 (ptrdiff_t nargs
, Lisp_Object
*args
)
453 return concat (nargs
, args
, Lisp_Cons
, 1);
456 DEFUN ("concat", Fconcat
, Sconcat
, 0, MANY
, 0,
457 doc
: /* Concatenate all the arguments and make the result a string.
458 The result is a string whose elements are the elements of all the arguments.
459 Each argument may be a string or a list or vector of characters (integers).
460 usage: (concat &rest SEQUENCES) */)
461 (ptrdiff_t nargs
, Lisp_Object
*args
)
463 return concat (nargs
, args
, Lisp_String
, 0);
466 DEFUN ("vconcat", Fvconcat
, Svconcat
, 0, MANY
, 0,
467 doc
: /* Concatenate all the arguments and make the result a vector.
468 The result is a vector whose elements are the elements of all the arguments.
469 Each argument may be a list, vector or string.
470 usage: (vconcat &rest SEQUENCES) */)
471 (ptrdiff_t nargs
, Lisp_Object
*args
)
473 return concat (nargs
, args
, Lisp_Vectorlike
, 0);
477 DEFUN ("copy-sequence", Fcopy_sequence
, Scopy_sequence
, 1, 1, 0,
478 doc
: /* Return a copy of a list, vector, string, char-table or record.
479 The elements of a list, vector or record are not copied; they are
480 shared with the original. */)
483 if (NILP (arg
)) return arg
;
487 return Frecord (PVSIZE (arg
), XVECTOR (arg
)->contents
);
490 if (CHAR_TABLE_P (arg
))
492 return copy_char_table (arg
);
495 if (BOOL_VECTOR_P (arg
))
497 EMACS_INT nbits
= bool_vector_size (arg
);
498 ptrdiff_t nbytes
= bool_vector_bytes (nbits
);
499 Lisp_Object val
= make_uninit_bool_vector (nbits
);
500 memcpy (bool_vector_data (val
), bool_vector_data (arg
), nbytes
);
504 if (!CONSP (arg
) && !VECTORP (arg
) && !STRINGP (arg
))
505 wrong_type_argument (Qsequencep
, arg
);
507 return concat (1, &arg
, XTYPE (arg
), 0);
510 /* This structure holds information of an argument of `concat' that is
511 a string and has text properties to be copied. */
514 ptrdiff_t argnum
; /* refer to ARGS (arguments of `concat') */
515 ptrdiff_t from
; /* refer to ARGS[argnum] (argument string) */
516 ptrdiff_t to
; /* refer to VAL (the target string) */
520 concat (ptrdiff_t nargs
, Lisp_Object
*args
,
521 enum Lisp_Type target_type
, bool last_special
)
527 ptrdiff_t toindex_byte
= 0;
528 EMACS_INT result_len
;
529 EMACS_INT result_len_byte
;
531 Lisp_Object last_tail
;
534 /* When we make a multibyte string, we can't copy text properties
535 while concatenating each string because the length of resulting
536 string can't be decided until we finish the whole concatenation.
537 So, we record strings that have text properties to be copied
538 here, and copy the text properties after the concatenation. */
539 struct textprop_rec
*textprops
= NULL
;
540 /* Number of elements in textprops. */
541 ptrdiff_t num_textprops
= 0;
546 /* In append, the last arg isn't treated like the others */
547 if (last_special
&& nargs
> 0)
550 last_tail
= args
[nargs
];
555 /* Check each argument. */
556 for (argnum
= 0; argnum
< nargs
; argnum
++)
559 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
560 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
561 wrong_type_argument (Qsequencep
, this);
564 /* Compute total length in chars of arguments in RESULT_LEN.
565 If desired output is a string, also compute length in bytes
566 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
567 whether the result should be a multibyte string. */
571 for (argnum
= 0; argnum
< nargs
; argnum
++)
575 len
= XFASTINT (Flength (this));
576 if (target_type
== Lisp_String
)
578 /* We must count the number of bytes needed in the string
579 as well as the number of characters. */
583 ptrdiff_t this_len_byte
;
585 if (VECTORP (this) || COMPILEDP (this))
586 for (i
= 0; i
< len
; i
++)
589 CHECK_CHARACTER (ch
);
591 this_len_byte
= CHAR_BYTES (c
);
592 if (STRING_BYTES_BOUND
- result_len_byte
< this_len_byte
)
594 result_len_byte
+= this_len_byte
;
595 if (! ASCII_CHAR_P (c
) && ! CHAR_BYTE8_P (c
))
598 else if (BOOL_VECTOR_P (this) && bool_vector_size (this) > 0)
599 wrong_type_argument (Qintegerp
, Faref (this, make_number (0)));
600 else if (CONSP (this))
601 for (; CONSP (this); this = XCDR (this))
604 CHECK_CHARACTER (ch
);
606 this_len_byte
= CHAR_BYTES (c
);
607 if (STRING_BYTES_BOUND
- result_len_byte
< this_len_byte
)
609 result_len_byte
+= this_len_byte
;
610 if (! ASCII_CHAR_P (c
) && ! CHAR_BYTE8_P (c
))
613 else if (STRINGP (this))
615 if (STRING_MULTIBYTE (this))
618 this_len_byte
= SBYTES (this);
621 this_len_byte
= count_size_as_multibyte (SDATA (this),
623 if (STRING_BYTES_BOUND
- result_len_byte
< this_len_byte
)
625 result_len_byte
+= this_len_byte
;
630 if (MOST_POSITIVE_FIXNUM
< result_len
)
631 memory_full (SIZE_MAX
);
634 if (! some_multibyte
)
635 result_len_byte
= result_len
;
637 /* Create the output object. */
638 if (target_type
== Lisp_Cons
)
639 val
= Fmake_list (make_number (result_len
), Qnil
);
640 else if (target_type
== Lisp_Vectorlike
)
641 val
= Fmake_vector (make_number (result_len
), Qnil
);
642 else if (some_multibyte
)
643 val
= make_uninit_multibyte_string (result_len
, result_len_byte
);
645 val
= make_uninit_string (result_len
);
647 /* In `append', if all but last arg are nil, return last arg. */
648 if (target_type
== Lisp_Cons
&& EQ (val
, Qnil
))
651 /* Copy the contents of the args into the result. */
653 tail
= val
, toindex
= -1; /* -1 in toindex is flag we are making a list */
655 toindex
= 0, toindex_byte
= 0;
659 SAFE_NALLOCA (textprops
, 1, nargs
);
661 for (argnum
= 0; argnum
< nargs
; argnum
++)
664 ptrdiff_t thisleni
= 0;
665 register ptrdiff_t thisindex
= 0;
666 register ptrdiff_t thisindex_byte
= 0;
670 thislen
= Flength (this), thisleni
= XINT (thislen
);
672 /* Between strings of the same kind, copy fast. */
673 if (STRINGP (this) && STRINGP (val
)
674 && STRING_MULTIBYTE (this) == some_multibyte
)
676 ptrdiff_t thislen_byte
= SBYTES (this);
678 memcpy (SDATA (val
) + toindex_byte
, SDATA (this), SBYTES (this));
679 if (string_intervals (this))
681 textprops
[num_textprops
].argnum
= argnum
;
682 textprops
[num_textprops
].from
= 0;
683 textprops
[num_textprops
++].to
= toindex
;
685 toindex_byte
+= thislen_byte
;
688 /* Copy a single-byte string to a multibyte string. */
689 else if (STRINGP (this) && STRINGP (val
))
691 if (string_intervals (this))
693 textprops
[num_textprops
].argnum
= argnum
;
694 textprops
[num_textprops
].from
= 0;
695 textprops
[num_textprops
++].to
= toindex
;
697 toindex_byte
+= copy_text (SDATA (this),
698 SDATA (val
) + toindex_byte
,
699 SCHARS (this), 0, 1);
703 /* Copy element by element. */
706 register Lisp_Object elt
;
708 /* Fetch next element of `this' arg into `elt', or break if
709 `this' is exhausted. */
710 if (NILP (this)) break;
712 elt
= XCAR (this), this = XCDR (this);
713 else if (thisindex
>= thisleni
)
715 else if (STRINGP (this))
718 if (STRING_MULTIBYTE (this))
719 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c
, this,
724 c
= SREF (this, thisindex
); thisindex
++;
725 if (some_multibyte
&& !ASCII_CHAR_P (c
))
726 c
= BYTE8_TO_CHAR (c
);
728 XSETFASTINT (elt
, c
);
730 else if (BOOL_VECTOR_P (this))
732 elt
= bool_vector_ref (this, thisindex
);
737 elt
= AREF (this, thisindex
);
741 /* Store this element into the result. */
748 else if (VECTORP (val
))
750 ASET (val
, toindex
, elt
);
756 CHECK_CHARACTER (elt
);
759 toindex_byte
+= CHAR_STRING (c
, SDATA (val
) + toindex_byte
);
761 SSET (val
, toindex_byte
++, c
);
767 XSETCDR (prev
, last_tail
);
769 if (num_textprops
> 0)
772 ptrdiff_t last_to_end
= -1;
774 for (argnum
= 0; argnum
< num_textprops
; argnum
++)
776 this = args
[textprops
[argnum
].argnum
];
777 props
= text_property_list (this,
779 make_number (SCHARS (this)),
781 /* If successive arguments have properties, be sure that the
782 value of `composition' property be the copy. */
783 if (last_to_end
== textprops
[argnum
].to
)
784 make_composition_value_copy (props
);
785 add_text_properties_from_list (val
, props
,
786 make_number (textprops
[argnum
].to
));
787 last_to_end
= textprops
[argnum
].to
+ SCHARS (this);
795 static Lisp_Object string_char_byte_cache_string
;
796 static ptrdiff_t string_char_byte_cache_charpos
;
797 static ptrdiff_t string_char_byte_cache_bytepos
;
800 clear_string_char_byte_cache (void)
802 string_char_byte_cache_string
= Qnil
;
805 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
808 string_char_to_byte (Lisp_Object string
, ptrdiff_t char_index
)
811 ptrdiff_t best_below
, best_below_byte
;
812 ptrdiff_t best_above
, best_above_byte
;
814 best_below
= best_below_byte
= 0;
815 best_above
= SCHARS (string
);
816 best_above_byte
= SBYTES (string
);
817 if (best_above
== best_above_byte
)
820 if (EQ (string
, string_char_byte_cache_string
))
822 if (string_char_byte_cache_charpos
< char_index
)
824 best_below
= string_char_byte_cache_charpos
;
825 best_below_byte
= string_char_byte_cache_bytepos
;
829 best_above
= string_char_byte_cache_charpos
;
830 best_above_byte
= string_char_byte_cache_bytepos
;
834 if (char_index
- best_below
< best_above
- char_index
)
836 unsigned char *p
= SDATA (string
) + best_below_byte
;
838 while (best_below
< char_index
)
840 p
+= BYTES_BY_CHAR_HEAD (*p
);
843 i_byte
= p
- SDATA (string
);
847 unsigned char *p
= SDATA (string
) + best_above_byte
;
849 while (best_above
> char_index
)
852 while (!CHAR_HEAD_P (*p
)) p
--;
855 i_byte
= p
- SDATA (string
);
858 string_char_byte_cache_bytepos
= i_byte
;
859 string_char_byte_cache_charpos
= char_index
;
860 string_char_byte_cache_string
= string
;
865 /* Return the character index corresponding to BYTE_INDEX in STRING. */
868 string_byte_to_char (Lisp_Object string
, ptrdiff_t byte_index
)
871 ptrdiff_t best_below
, best_below_byte
;
872 ptrdiff_t best_above
, best_above_byte
;
874 best_below
= best_below_byte
= 0;
875 best_above
= SCHARS (string
);
876 best_above_byte
= SBYTES (string
);
877 if (best_above
== best_above_byte
)
880 if (EQ (string
, string_char_byte_cache_string
))
882 if (string_char_byte_cache_bytepos
< byte_index
)
884 best_below
= string_char_byte_cache_charpos
;
885 best_below_byte
= string_char_byte_cache_bytepos
;
889 best_above
= string_char_byte_cache_charpos
;
890 best_above_byte
= string_char_byte_cache_bytepos
;
894 if (byte_index
- best_below_byte
< best_above_byte
- byte_index
)
896 unsigned char *p
= SDATA (string
) + best_below_byte
;
897 unsigned char *pend
= SDATA (string
) + byte_index
;
901 p
+= BYTES_BY_CHAR_HEAD (*p
);
905 i_byte
= p
- SDATA (string
);
909 unsigned char *p
= SDATA (string
) + best_above_byte
;
910 unsigned char *pbeg
= SDATA (string
) + byte_index
;
915 while (!CHAR_HEAD_P (*p
)) p
--;
919 i_byte
= p
- SDATA (string
);
922 string_char_byte_cache_bytepos
= i_byte
;
923 string_char_byte_cache_charpos
= i
;
924 string_char_byte_cache_string
= string
;
929 /* Convert STRING to a multibyte string. */
932 string_make_multibyte (Lisp_Object string
)
939 if (STRING_MULTIBYTE (string
))
942 nbytes
= count_size_as_multibyte (SDATA (string
),
944 /* If all the chars are ASCII, they won't need any more bytes
945 once converted. In that case, we can return STRING itself. */
946 if (nbytes
== SBYTES (string
))
949 buf
= SAFE_ALLOCA (nbytes
);
950 copy_text (SDATA (string
), buf
, SBYTES (string
),
953 ret
= make_multibyte_string ((char *) buf
, SCHARS (string
), nbytes
);
960 /* Convert STRING (if unibyte) to a multibyte string without changing
961 the number of characters. Characters 0200 trough 0237 are
962 converted to eight-bit characters. */
965 string_to_multibyte (Lisp_Object string
)
972 if (STRING_MULTIBYTE (string
))
975 nbytes
= count_size_as_multibyte (SDATA (string
), SBYTES (string
));
976 /* If all the chars are ASCII, they won't need any more bytes once
978 if (nbytes
== SBYTES (string
))
979 return make_multibyte_string (SSDATA (string
), nbytes
, nbytes
);
981 buf
= SAFE_ALLOCA (nbytes
);
982 memcpy (buf
, SDATA (string
), SBYTES (string
));
983 str_to_multibyte (buf
, nbytes
, SBYTES (string
));
985 ret
= make_multibyte_string ((char *) buf
, SCHARS (string
), nbytes
);
992 /* Convert STRING to a single-byte string. */
995 string_make_unibyte (Lisp_Object string
)
1002 if (! STRING_MULTIBYTE (string
))
1005 nchars
= SCHARS (string
);
1007 buf
= SAFE_ALLOCA (nchars
);
1008 copy_text (SDATA (string
), buf
, SBYTES (string
),
1011 ret
= make_unibyte_string ((char *) buf
, nchars
);
1017 DEFUN ("string-make-multibyte", Fstring_make_multibyte
, Sstring_make_multibyte
,
1019 doc
: /* Return the multibyte equivalent of STRING.
1020 If STRING is unibyte and contains non-ASCII characters, the function
1021 `unibyte-char-to-multibyte' is used to convert each unibyte character
1022 to a multibyte character. In this case, the returned string is a
1023 newly created string with no text properties. If STRING is multibyte
1024 or entirely ASCII, it is returned unchanged. In particular, when
1025 STRING is unibyte and entirely ASCII, the returned string is unibyte.
1026 \(When the characters are all ASCII, Emacs primitives will treat the
1027 string the same way whether it is unibyte or multibyte.) */)
1028 (Lisp_Object string
)
1030 CHECK_STRING (string
);
1032 return string_make_multibyte (string
);
1035 DEFUN ("string-make-unibyte", Fstring_make_unibyte
, Sstring_make_unibyte
,
1037 doc
: /* Return the unibyte equivalent of STRING.
1038 Multibyte character codes are converted to unibyte according to
1039 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
1040 If the lookup in the translation table fails, this function takes just
1041 the low 8 bits of each character. */)
1042 (Lisp_Object string
)
1044 CHECK_STRING (string
);
1046 return string_make_unibyte (string
);
1049 DEFUN ("string-as-unibyte", Fstring_as_unibyte
, Sstring_as_unibyte
,
1051 doc
: /* Return a unibyte string with the same individual bytes as STRING.
1052 If STRING is unibyte, the result is STRING itself.
1053 Otherwise it is a newly created string, with no text properties.
1054 If STRING is multibyte and contains a character of charset
1055 `eight-bit', it is converted to the corresponding single byte. */)
1056 (Lisp_Object string
)
1058 CHECK_STRING (string
);
1060 if (STRING_MULTIBYTE (string
))
1062 unsigned char *str
= (unsigned char *) xlispstrdup (string
);
1063 ptrdiff_t bytes
= str_as_unibyte (str
, SBYTES (string
));
1065 string
= make_unibyte_string ((char *) str
, bytes
);
1071 DEFUN ("string-as-multibyte", Fstring_as_multibyte
, Sstring_as_multibyte
,
1073 doc
: /* Return a multibyte string with the same individual bytes as STRING.
1074 If STRING is multibyte, the result is STRING itself.
1075 Otherwise it is a newly created string, with no text properties.
1077 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1078 part of a correct utf-8 sequence), it is converted to the corresponding
1079 multibyte character of charset `eight-bit'.
1080 See also `string-to-multibyte'.
1082 Beware, this often doesn't really do what you think it does.
1083 It is similar to (decode-coding-string STRING \\='utf-8-emacs).
1084 If you're not sure, whether to use `string-as-multibyte' or
1085 `string-to-multibyte', use `string-to-multibyte'. */)
1086 (Lisp_Object string
)
1088 CHECK_STRING (string
);
1090 if (! STRING_MULTIBYTE (string
))
1092 Lisp_Object new_string
;
1093 ptrdiff_t nchars
, nbytes
;
1095 parse_str_as_multibyte (SDATA (string
),
1098 new_string
= make_uninit_multibyte_string (nchars
, nbytes
);
1099 memcpy (SDATA (new_string
), SDATA (string
), SBYTES (string
));
1100 if (nbytes
!= SBYTES (string
))
1101 str_as_multibyte (SDATA (new_string
), nbytes
,
1102 SBYTES (string
), NULL
);
1103 string
= new_string
;
1104 set_string_intervals (string
, NULL
);
1109 DEFUN ("string-to-multibyte", Fstring_to_multibyte
, Sstring_to_multibyte
,
1111 doc
: /* Return a multibyte string with the same individual chars as STRING.
1112 If STRING is multibyte, the result is STRING itself.
1113 Otherwise it is a newly created string, with no text properties.
1115 If STRING is unibyte and contains an 8-bit byte, it is converted to
1116 the corresponding multibyte character of charset `eight-bit'.
1118 This differs from `string-as-multibyte' by converting each byte of a correct
1119 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1120 correct sequence. */)
1121 (Lisp_Object string
)
1123 CHECK_STRING (string
);
1125 return string_to_multibyte (string
);
1128 DEFUN ("string-to-unibyte", Fstring_to_unibyte
, Sstring_to_unibyte
,
1130 doc
: /* Return a unibyte string with the same individual chars as STRING.
1131 If STRING is unibyte, the result is STRING itself.
1132 Otherwise it is a newly created string, with no text properties,
1133 where each `eight-bit' character is converted to the corresponding byte.
1134 If STRING contains a non-ASCII, non-`eight-bit' character,
1135 an error is signaled. */)
1136 (Lisp_Object string
)
1138 CHECK_STRING (string
);
1140 if (STRING_MULTIBYTE (string
))
1142 ptrdiff_t chars
= SCHARS (string
);
1143 unsigned char *str
= xmalloc (chars
);
1144 ptrdiff_t converted
= str_to_unibyte (SDATA (string
), str
, chars
);
1146 if (converted
< chars
)
1147 error ("Can't convert the %"pD
"dth character to unibyte", converted
);
1148 string
= make_unibyte_string ((char *) str
, chars
);
1155 DEFUN ("copy-alist", Fcopy_alist
, Scopy_alist
, 1, 1, 0,
1156 doc
: /* Return a copy of ALIST.
1157 This is an alist which represents the same mapping from objects to objects,
1158 but does not share the alist structure with ALIST.
1159 The objects mapped (cars and cdrs of elements of the alist)
1160 are shared, however.
1161 Elements of ALIST that are not conses are also shared. */)
1166 alist
= concat (1, &alist
, Lisp_Cons
, false);
1167 for (Lisp_Object tem
= alist
; !NILP (tem
); tem
= XCDR (tem
))
1169 Lisp_Object car
= XCAR (tem
);
1171 XSETCAR (tem
, Fcons (XCAR (car
), XCDR (car
)));
1176 /* Check that ARRAY can have a valid subarray [FROM..TO),
1177 given that its size is SIZE.
1178 If FROM is nil, use 0; if TO is nil, use SIZE.
1179 Count negative values backwards from the end.
1180 Set *IFROM and *ITO to the two indexes used. */
1183 validate_subarray (Lisp_Object array
, Lisp_Object from
, Lisp_Object to
,
1184 ptrdiff_t size
, ptrdiff_t *ifrom
, ptrdiff_t *ito
)
1188 if (INTEGERP (from
))
1194 else if (NILP (from
))
1197 wrong_type_argument (Qintegerp
, from
);
1208 wrong_type_argument (Qintegerp
, to
);
1210 if (! (0 <= f
&& f
<= t
&& t
<= size
))
1211 args_out_of_range_3 (array
, from
, to
);
1217 DEFUN ("substring", Fsubstring
, Ssubstring
, 1, 3, 0,
1218 doc
: /* Return a new string whose contents are a substring of STRING.
1219 The returned string consists of the characters between index FROM
1220 \(inclusive) and index TO (exclusive) of STRING. FROM and TO are
1221 zero-indexed: 0 means the first character of STRING. Negative values
1222 are counted from the end of STRING. If TO is nil, the substring runs
1223 to the end of STRING.
1225 The STRING argument may also be a vector. In that case, the return
1226 value is a new vector that contains the elements between index FROM
1227 \(inclusive) and index TO (exclusive) of that vector argument.
1229 With one argument, just copy STRING (with properties, if any). */)
1230 (Lisp_Object string
, Lisp_Object from
, Lisp_Object to
)
1233 ptrdiff_t size
, ifrom
, ito
;
1235 size
= CHECK_VECTOR_OR_STRING (string
);
1236 validate_subarray (string
, from
, to
, size
, &ifrom
, &ito
);
1238 if (STRINGP (string
))
1241 = !ifrom
? 0 : string_char_to_byte (string
, ifrom
);
1243 = ito
== size
? SBYTES (string
) : string_char_to_byte (string
, ito
);
1244 res
= make_specified_string (SSDATA (string
) + from_byte
,
1245 ito
- ifrom
, to_byte
- from_byte
,
1246 STRING_MULTIBYTE (string
));
1247 copy_text_properties (make_number (ifrom
), make_number (ito
),
1248 string
, make_number (0), res
, Qnil
);
1251 res
= Fvector (ito
- ifrom
, aref_addr (string
, ifrom
));
1257 DEFUN ("substring-no-properties", Fsubstring_no_properties
, Ssubstring_no_properties
, 1, 3, 0,
1258 doc
: /* Return a substring of STRING, without text properties.
1259 It starts at index FROM and ends before TO.
1260 TO may be nil or omitted; then the substring runs to the end of STRING.
1261 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1262 If FROM or TO is negative, it counts from the end.
1264 With one argument, just copy STRING without its properties. */)
1265 (Lisp_Object string
, register Lisp_Object from
, Lisp_Object to
)
1267 ptrdiff_t from_char
, to_char
, from_byte
, to_byte
, size
;
1269 CHECK_STRING (string
);
1271 size
= SCHARS (string
);
1272 validate_subarray (string
, from
, to
, size
, &from_char
, &to_char
);
1274 from_byte
= !from_char
? 0 : string_char_to_byte (string
, from_char
);
1276 to_char
== size
? SBYTES (string
) : string_char_to_byte (string
, to_char
);
1277 return make_specified_string (SSDATA (string
) + from_byte
,
1278 to_char
- from_char
, to_byte
- from_byte
,
1279 STRING_MULTIBYTE (string
));
1282 /* Extract a substring of STRING, giving start and end positions
1283 both in characters and in bytes. */
1286 substring_both (Lisp_Object string
, ptrdiff_t from
, ptrdiff_t from_byte
,
1287 ptrdiff_t to
, ptrdiff_t to_byte
)
1290 ptrdiff_t size
= CHECK_VECTOR_OR_STRING (string
);
1292 if (!(0 <= from
&& from
<= to
&& to
<= size
))
1293 args_out_of_range_3 (string
, make_number (from
), make_number (to
));
1295 if (STRINGP (string
))
1297 res
= make_specified_string (SSDATA (string
) + from_byte
,
1298 to
- from
, to_byte
- from_byte
,
1299 STRING_MULTIBYTE (string
));
1300 copy_text_properties (make_number (from
), make_number (to
),
1301 string
, make_number (0), res
, Qnil
);
1304 res
= Fvector (to
- from
, aref_addr (string
, from
));
1309 DEFUN ("nthcdr", Fnthcdr
, Snthcdr
, 2, 2, 0,
1310 doc
: /* Take cdr N times on LIST, return the result. */)
1311 (Lisp_Object n
, Lisp_Object list
)
1314 Lisp_Object tail
= list
;
1315 for (EMACS_INT num
= XINT (n
); 0 < num
; num
--)
1319 CHECK_LIST_END (tail
, list
);
1328 DEFUN ("nth", Fnth
, Snth
, 2, 2, 0,
1329 doc
: /* Return the Nth element of LIST.
1330 N counts from zero. If LIST is not that long, nil is returned. */)
1331 (Lisp_Object n
, Lisp_Object list
)
1333 return Fcar (Fnthcdr (n
, list
));
1336 DEFUN ("elt", Felt
, Selt
, 2, 2, 0,
1337 doc
: /* Return element of SEQUENCE at index N. */)
1338 (register Lisp_Object sequence
, Lisp_Object n
)
1341 if (CONSP (sequence
) || NILP (sequence
))
1342 return Fcar (Fnthcdr (n
, sequence
));
1344 /* Faref signals a "not array" error, so check here. */
1345 CHECK_ARRAY (sequence
, Qsequencep
);
1346 return Faref (sequence
, n
);
1349 DEFUN ("member", Fmember
, Smember
, 2, 2, 0,
1350 doc
: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1351 The value is actually the tail of LIST whose car is ELT. */)
1352 (Lisp_Object elt
, Lisp_Object list
)
1354 Lisp_Object tail
= list
;
1355 FOR_EACH_TAIL (tail
)
1356 if (! NILP (Fequal (elt
, XCAR (tail
))))
1358 CHECK_LIST_END (tail
, list
);
1362 DEFUN ("memq", Fmemq
, Smemq
, 2, 2, 0,
1363 doc
: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1364 The value is actually the tail of LIST whose car is ELT. */)
1365 (Lisp_Object elt
, Lisp_Object list
)
1367 Lisp_Object tail
= list
;
1368 FOR_EACH_TAIL (tail
)
1369 if (EQ (XCAR (tail
), elt
))
1371 CHECK_LIST_END (tail
, list
);
1375 DEFUN ("memql", Fmemql
, Smemql
, 2, 2, 0,
1376 doc
: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1377 The value is actually the tail of LIST whose car is ELT. */)
1378 (Lisp_Object elt
, Lisp_Object list
)
1381 return Fmemq (elt
, list
);
1383 Lisp_Object tail
= list
;
1384 FOR_EACH_TAIL (tail
)
1386 Lisp_Object tem
= XCAR (tail
);
1387 if (FLOATP (tem
) && equal_no_quit (elt
, tem
))
1390 CHECK_LIST_END (tail
, list
);
1394 DEFUN ("assq", Fassq
, Sassq
, 2, 2, 0,
1395 doc
: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1396 The value is actually the first element of LIST whose car is KEY.
1397 Elements of LIST that are not conses are ignored. */)
1398 (Lisp_Object key
, Lisp_Object list
)
1400 Lisp_Object tail
= list
;
1401 FOR_EACH_TAIL (tail
)
1402 if (CONSP (XCAR (tail
)) && EQ (XCAR (XCAR (tail
)), key
))
1404 CHECK_LIST_END (tail
, list
);
1408 /* Like Fassq but never report an error and do not allow quits.
1409 Use only on objects known to be non-circular lists. */
1412 assq_no_quit (Lisp_Object key
, Lisp_Object list
)
1414 for (; ! NILP (list
); list
= XCDR (list
))
1415 if (CONSP (XCAR (list
)) && EQ (XCAR (XCAR (list
)), key
))
1420 DEFUN ("assoc", Fassoc
, Sassoc
, 2, 2, 0,
1421 doc
: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1422 The value is actually the first element of LIST whose car equals KEY. */)
1423 (Lisp_Object key
, Lisp_Object list
)
1425 Lisp_Object tail
= list
;
1426 FOR_EACH_TAIL (tail
)
1428 Lisp_Object car
= XCAR (tail
);
1430 && (EQ (XCAR (car
), key
) || !NILP (Fequal (XCAR (car
), key
))))
1433 CHECK_LIST_END (tail
, list
);
1437 /* Like Fassoc but never report an error and do not allow quits.
1438 Use only on keys and lists known to be non-circular, and on keys
1439 that are not too deep and are not window configurations. */
1442 assoc_no_quit (Lisp_Object key
, Lisp_Object list
)
1444 for (; ! NILP (list
); list
= XCDR (list
))
1446 Lisp_Object car
= XCAR (list
);
1448 && (EQ (XCAR (car
), key
) || equal_no_quit (XCAR (car
), key
)))
1454 DEFUN ("rassq", Frassq
, Srassq
, 2, 2, 0,
1455 doc
: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1456 The value is actually the first element of LIST whose cdr is KEY. */)
1457 (Lisp_Object key
, Lisp_Object list
)
1459 Lisp_Object tail
= list
;
1460 FOR_EACH_TAIL (tail
)
1461 if (CONSP (XCAR (tail
)) && EQ (XCDR (XCAR (tail
)), key
))
1463 CHECK_LIST_END (tail
, list
);
1467 DEFUN ("rassoc", Frassoc
, Srassoc
, 2, 2, 0,
1468 doc
: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1469 The value is actually the first element of LIST whose cdr equals KEY. */)
1470 (Lisp_Object key
, Lisp_Object list
)
1472 Lisp_Object tail
= list
;
1473 FOR_EACH_TAIL (tail
)
1475 Lisp_Object car
= XCAR (tail
);
1477 && (EQ (XCDR (car
), key
) || !NILP (Fequal (XCDR (car
), key
))))
1480 CHECK_LIST_END (tail
, list
);
1484 DEFUN ("delq", Fdelq
, Sdelq
, 2, 2, 0,
1485 doc
: /* Delete members of LIST which are `eq' to ELT, and return the result.
1486 More precisely, this function skips any members `eq' to ELT at the
1487 front of LIST, then removes members `eq' to ELT from the remaining
1488 sublist by modifying its list structure, then returns the resulting
1491 Write `(setq foo (delq element foo))' to be sure of correctly changing
1492 the value of a list `foo'. See also `remq', which does not modify the
1494 (Lisp_Object elt
, Lisp_Object list
)
1496 Lisp_Object prev
= Qnil
, tail
= list
;
1498 FOR_EACH_TAIL (tail
)
1500 Lisp_Object tem
= XCAR (tail
);
1506 Fsetcdr (prev
, XCDR (tail
));
1511 CHECK_LIST_END (tail
, list
);
1515 DEFUN ("delete", Fdelete
, Sdelete
, 2, 2, 0,
1516 doc
: /* Delete members of SEQ which are `equal' to ELT, and return the result.
1517 SEQ must be a sequence (i.e. a list, a vector, or a string).
1518 The return value is a sequence of the same type.
1520 If SEQ is a list, this behaves like `delq', except that it compares
1521 with `equal' instead of `eq'. In particular, it may remove elements
1522 by altering the list structure.
1524 If SEQ is not a list, deletion is never performed destructively;
1525 instead this function creates and returns a new vector or string.
1527 Write `(setq foo (delete element foo))' to be sure of correctly
1528 changing the value of a sequence `foo'. */)
1529 (Lisp_Object elt
, Lisp_Object seq
)
1535 for (i
= n
= 0; i
< ASIZE (seq
); ++i
)
1536 if (NILP (Fequal (AREF (seq
, i
), elt
)))
1539 if (n
!= ASIZE (seq
))
1541 struct Lisp_Vector
*p
= allocate_vector (n
);
1543 for (i
= n
= 0; i
< ASIZE (seq
); ++i
)
1544 if (NILP (Fequal (AREF (seq
, i
), elt
)))
1545 p
->contents
[n
++] = AREF (seq
, i
);
1547 XSETVECTOR (seq
, p
);
1550 else if (STRINGP (seq
))
1552 ptrdiff_t i
, ibyte
, nchars
, nbytes
, cbytes
;
1555 for (i
= nchars
= nbytes
= ibyte
= 0;
1557 ++i
, ibyte
+= cbytes
)
1559 if (STRING_MULTIBYTE (seq
))
1561 c
= STRING_CHAR (SDATA (seq
) + ibyte
);
1562 cbytes
= CHAR_BYTES (c
);
1570 if (!INTEGERP (elt
) || c
!= XINT (elt
))
1577 if (nchars
!= SCHARS (seq
))
1581 tem
= make_uninit_multibyte_string (nchars
, nbytes
);
1582 if (!STRING_MULTIBYTE (seq
))
1583 STRING_SET_UNIBYTE (tem
);
1585 for (i
= nchars
= nbytes
= ibyte
= 0;
1587 ++i
, ibyte
+= cbytes
)
1589 if (STRING_MULTIBYTE (seq
))
1591 c
= STRING_CHAR (SDATA (seq
) + ibyte
);
1592 cbytes
= CHAR_BYTES (c
);
1600 if (!INTEGERP (elt
) || c
!= XINT (elt
))
1602 unsigned char *from
= SDATA (seq
) + ibyte
;
1603 unsigned char *to
= SDATA (tem
) + nbytes
;
1609 for (n
= cbytes
; n
--; )
1619 Lisp_Object prev
= Qnil
, tail
= seq
;
1621 FOR_EACH_TAIL (tail
)
1623 if (!NILP (Fequal (elt
, XCAR (tail
))))
1628 Fsetcdr (prev
, XCDR (tail
));
1633 CHECK_LIST_END (tail
, seq
);
1639 DEFUN ("nreverse", Fnreverse
, Snreverse
, 1, 1, 0,
1640 doc
: /* Reverse order of items in a list, vector or string SEQ.
1641 If SEQ is a list, it should be nil-terminated.
1642 This function may destructively modify SEQ to produce the value. */)
1647 else if (STRINGP (seq
))
1648 return Freverse (seq
);
1649 else if (CONSP (seq
))
1651 Lisp_Object prev
, tail
, next
;
1653 for (prev
= Qnil
, tail
= seq
; CONSP (tail
); tail
= next
)
1656 /* If SEQ contains a cycle, attempting to reverse it
1657 in-place will inevitably come back to SEQ. */
1659 circular_list (seq
);
1660 Fsetcdr (tail
, prev
);
1663 CHECK_LIST_END (tail
, seq
);
1666 else if (VECTORP (seq
))
1668 ptrdiff_t i
, size
= ASIZE (seq
);
1670 for (i
= 0; i
< size
/ 2; i
++)
1672 Lisp_Object tem
= AREF (seq
, i
);
1673 ASET (seq
, i
, AREF (seq
, size
- i
- 1));
1674 ASET (seq
, size
- i
- 1, tem
);
1677 else if (BOOL_VECTOR_P (seq
))
1679 ptrdiff_t i
, size
= bool_vector_size (seq
);
1681 for (i
= 0; i
< size
/ 2; i
++)
1683 bool tem
= bool_vector_bitref (seq
, i
);
1684 bool_vector_set (seq
, i
, bool_vector_bitref (seq
, size
- i
- 1));
1685 bool_vector_set (seq
, size
- i
- 1, tem
);
1689 wrong_type_argument (Qarrayp
, seq
);
1693 DEFUN ("reverse", Freverse
, Sreverse
, 1, 1, 0,
1694 doc
: /* Return the reversed copy of list, vector, or string SEQ.
1695 See also the function `nreverse', which is used more often. */)
1702 else if (CONSP (seq
))
1706 new = Fcons (XCAR (seq
), new);
1707 CHECK_LIST_END (seq
, seq
);
1709 else if (VECTORP (seq
))
1711 ptrdiff_t i
, size
= ASIZE (seq
);
1713 new = make_uninit_vector (size
);
1714 for (i
= 0; i
< size
; i
++)
1715 ASET (new, i
, AREF (seq
, size
- i
- 1));
1717 else if (BOOL_VECTOR_P (seq
))
1720 EMACS_INT nbits
= bool_vector_size (seq
);
1722 new = make_uninit_bool_vector (nbits
);
1723 for (i
= 0; i
< nbits
; i
++)
1724 bool_vector_set (new, i
, bool_vector_bitref (seq
, nbits
- i
- 1));
1726 else if (STRINGP (seq
))
1728 ptrdiff_t size
= SCHARS (seq
), bytes
= SBYTES (seq
);
1734 new = make_uninit_string (size
);
1735 for (i
= 0; i
< size
; i
++)
1736 SSET (new, i
, SREF (seq
, size
- i
- 1));
1740 unsigned char *p
, *q
;
1742 new = make_uninit_multibyte_string (size
, bytes
);
1743 p
= SDATA (seq
), q
= SDATA (new) + bytes
;
1744 while (q
> SDATA (new))
1748 ch
= STRING_CHAR_AND_LENGTH (p
, len
);
1750 CHAR_STRING (ch
, q
);
1755 wrong_type_argument (Qsequencep
, seq
);
1759 /* Sort LIST using PREDICATE, preserving original order of elements
1760 considered as equal. */
1763 sort_list (Lisp_Object list
, Lisp_Object predicate
)
1765 Lisp_Object front
, back
;
1766 Lisp_Object len
, tem
;
1770 len
= Flength (list
);
1771 length
= XINT (len
);
1775 XSETINT (len
, (length
/ 2) - 1);
1776 tem
= Fnthcdr (len
, list
);
1778 Fsetcdr (tem
, Qnil
);
1780 front
= Fsort (front
, predicate
);
1781 back
= Fsort (back
, predicate
);
1782 return merge (front
, back
, predicate
);
1785 /* Using PRED to compare, return whether A and B are in order.
1786 Compare stably when A appeared before B in the input. */
1788 inorder (Lisp_Object pred
, Lisp_Object a
, Lisp_Object b
)
1790 return NILP (call2 (pred
, b
, a
));
1793 /* Using PRED to compare, merge from ALEN-length A and BLEN-length B
1794 into DEST. Argument arrays must be nonempty and must not overlap,
1795 except that B might be the last part of DEST. */
1797 merge_vectors (Lisp_Object pred
,
1798 ptrdiff_t alen
, Lisp_Object
const a
[restrict
VLA_ELEMS (alen
)],
1799 ptrdiff_t blen
, Lisp_Object
const b
[VLA_ELEMS (blen
)],
1800 Lisp_Object dest
[VLA_ELEMS (alen
+ blen
)])
1802 eassume (0 < alen
&& 0 < blen
);
1803 Lisp_Object
const *alim
= a
+ alen
;
1804 Lisp_Object
const *blim
= b
+ blen
;
1808 if (inorder (pred
, a
[0], b
[0]))
1814 memcpy (dest
, b
, (blim
- b
) * sizeof *dest
);
1823 memcpy (dest
, a
, (alim
- a
) * sizeof *dest
);
1830 /* Using PRED to compare, sort LEN-length VEC in place, using TMP for
1831 temporary storage. LEN must be at least 2. */
1833 sort_vector_inplace (Lisp_Object pred
, ptrdiff_t len
,
1834 Lisp_Object vec
[restrict
VLA_ELEMS (len
)],
1835 Lisp_Object tmp
[restrict
VLA_ELEMS (len
>> 1)])
1838 ptrdiff_t halflen
= len
>> 1;
1839 sort_vector_copy (pred
, halflen
, vec
, tmp
);
1840 if (1 < len
- halflen
)
1841 sort_vector_inplace (pred
, len
- halflen
, vec
+ halflen
, vec
);
1842 merge_vectors (pred
, halflen
, tmp
, len
- halflen
, vec
+ halflen
, vec
);
1845 /* Using PRED to compare, sort from LEN-length SRC into DST.
1846 Len must be positive. */
1848 sort_vector_copy (Lisp_Object pred
, ptrdiff_t len
,
1849 Lisp_Object src
[restrict
VLA_ELEMS (len
)],
1850 Lisp_Object dest
[restrict
VLA_ELEMS (len
)])
1853 ptrdiff_t halflen
= len
>> 1;
1859 sort_vector_inplace (pred
, halflen
, src
, dest
);
1860 if (1 < len
- halflen
)
1861 sort_vector_inplace (pred
, len
- halflen
, src
+ halflen
, dest
);
1862 merge_vectors (pred
, halflen
, src
, len
- halflen
, src
+ halflen
, dest
);
1866 /* Sort VECTOR in place using PREDICATE, preserving original order of
1867 elements considered as equal. */
1870 sort_vector (Lisp_Object vector
, Lisp_Object predicate
)
1872 ptrdiff_t len
= ASIZE (vector
);
1875 ptrdiff_t halflen
= len
>> 1;
1878 SAFE_ALLOCA_LISP (tmp
, halflen
);
1879 for (ptrdiff_t i
= 0; i
< halflen
; i
++)
1880 tmp
[i
] = make_number (0);
1881 sort_vector_inplace (predicate
, len
, XVECTOR (vector
)->contents
, tmp
);
1885 DEFUN ("sort", Fsort
, Ssort
, 2, 2, 0,
1886 doc
: /* Sort SEQ, stably, comparing elements using PREDICATE.
1887 Returns the sorted sequence. SEQ should be a list or vector. SEQ is
1888 modified by side effects. PREDICATE is called with two elements of
1889 SEQ, and should return non-nil if the first element should sort before
1891 (Lisp_Object seq
, Lisp_Object predicate
)
1894 seq
= sort_list (seq
, predicate
);
1895 else if (VECTORP (seq
))
1896 sort_vector (seq
, predicate
);
1897 else if (!NILP (seq
))
1898 wrong_type_argument (Qsequencep
, seq
);
1903 merge (Lisp_Object org_l1
, Lisp_Object org_l2
, Lisp_Object pred
)
1905 Lisp_Object l1
= org_l1
;
1906 Lisp_Object l2
= org_l2
;
1907 Lisp_Object tail
= Qnil
;
1908 Lisp_Object value
= Qnil
;
1928 if (inorder (pred
, Fcar (l1
), Fcar (l2
)))
1943 Fsetcdr (tail
, tem
);
1949 /* This does not check for quits. That is safe since it must terminate. */
1951 DEFUN ("plist-get", Fplist_get
, Splist_get
, 2, 2, 0,
1952 doc
: /* Extract a value from a property list.
1953 PLIST is a property list, which is a list of the form
1954 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
1955 corresponding to the given PROP, or nil if PROP is not one of the
1956 properties on the list. This function never signals an error. */)
1957 (Lisp_Object plist
, Lisp_Object prop
)
1959 Lisp_Object tail
= plist
;
1960 FOR_EACH_TAIL_SAFE (tail
)
1962 if (! CONSP (XCDR (tail
)))
1964 if (EQ (prop
, XCAR (tail
)))
1965 return XCAR (XCDR (tail
));
1967 if (EQ (tail
, li
.tortoise
))
1974 DEFUN ("get", Fget
, Sget
, 2, 2, 0,
1975 doc
: /* Return the value of SYMBOL's PROPNAME property.
1976 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
1977 (Lisp_Object symbol
, Lisp_Object propname
)
1979 CHECK_SYMBOL (symbol
);
1980 return Fplist_get (XSYMBOL (symbol
)->plist
, propname
);
1983 DEFUN ("plist-put", Fplist_put
, Splist_put
, 3, 3, 0,
1984 doc
: /* Change value in PLIST of PROP to VAL.
1985 PLIST is a property list, which is a list of the form
1986 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
1987 If PROP is already a property on the list, its value is set to VAL,
1988 otherwise the new PROP VAL pair is added. The new plist is returned;
1989 use `(setq x (plist-put x prop val))' to be sure to use the new value.
1990 The PLIST is modified by side effects. */)
1991 (Lisp_Object plist
, Lisp_Object prop
, Lisp_Object val
)
1993 Lisp_Object prev
= Qnil
, tail
= plist
;
1994 FOR_EACH_TAIL (tail
)
1996 if (! CONSP (XCDR (tail
)))
1999 if (EQ (prop
, XCAR (tail
)))
2001 Fsetcar (XCDR (tail
), val
);
2007 if (EQ (tail
, li
.tortoise
))
2008 circular_list (plist
);
2010 CHECK_LIST_END (tail
, plist
);
2012 = Fcons (prop
, Fcons (val
, NILP (prev
) ? plist
: XCDR (XCDR (prev
))));
2015 Fsetcdr (XCDR (prev
), newcell
);
2019 DEFUN ("put", Fput
, Sput
, 3, 3, 0,
2020 doc
: /* Store SYMBOL's PROPNAME property with value VALUE.
2021 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
2022 (Lisp_Object symbol
, Lisp_Object propname
, Lisp_Object value
)
2024 CHECK_SYMBOL (symbol
);
2026 (symbol
, Fplist_put (XSYMBOL (symbol
)->plist
, propname
, value
));
2030 DEFUN ("lax-plist-get", Flax_plist_get
, Slax_plist_get
, 2, 2, 0,
2031 doc
: /* Extract a value from a property list, comparing with `equal'.
2032 PLIST is a property list, which is a list of the form
2033 \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2034 corresponding to the given PROP, or nil if PROP is not
2035 one of the properties on the list. */)
2036 (Lisp_Object plist
, Lisp_Object prop
)
2038 Lisp_Object tail
= plist
;
2039 FOR_EACH_TAIL (tail
)
2041 if (! CONSP (XCDR (tail
)))
2043 if (! NILP (Fequal (prop
, XCAR (tail
))))
2044 return XCAR (XCDR (tail
));
2046 if (EQ (tail
, li
.tortoise
))
2047 circular_list (plist
);
2050 CHECK_LIST_END (tail
, plist
);
2055 DEFUN ("lax-plist-put", Flax_plist_put
, Slax_plist_put
, 3, 3, 0,
2056 doc
: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
2057 PLIST is a property list, which is a list of the form
2058 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
2059 If PROP is already a property on the list, its value is set to VAL,
2060 otherwise the new PROP VAL pair is added. The new plist is returned;
2061 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
2062 The PLIST is modified by side effects. */)
2063 (Lisp_Object plist
, Lisp_Object prop
, Lisp_Object val
)
2065 Lisp_Object prev
= Qnil
, tail
= plist
;
2066 FOR_EACH_TAIL (tail
)
2068 if (! CONSP (XCDR (tail
)))
2071 if (! NILP (Fequal (prop
, XCAR (tail
))))
2073 Fsetcar (XCDR (tail
), val
);
2079 if (EQ (tail
, li
.tortoise
))
2080 circular_list (plist
);
2082 CHECK_LIST_END (tail
, plist
);
2083 Lisp_Object newcell
= list2 (prop
, val
);
2086 Fsetcdr (XCDR (prev
), newcell
);
2090 DEFUN ("eql", Feql
, Seql
, 2, 2, 0,
2091 doc
: /* Return t if the two args are the same Lisp object.
2092 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
2093 (Lisp_Object obj1
, Lisp_Object obj2
)
2096 return equal_no_quit (obj1
, obj2
) ? Qt
: Qnil
;
2098 return EQ (obj1
, obj2
) ? Qt
: Qnil
;
2101 DEFUN ("equal", Fequal
, Sequal
, 2, 2, 0,
2102 doc
: /* Return t if two Lisp objects have similar structure and contents.
2103 They must have the same data type.
2104 Conses are compared by comparing the cars and the cdrs.
2105 Vectors and strings are compared element by element.
2106 Numbers are compared by value, but integers cannot equal floats.
2107 (Use `=' if you want integers and floats to be able to be equal.)
2108 Symbols must match exactly. */)
2109 (Lisp_Object o1
, Lisp_Object o2
)
2111 return internal_equal (o1
, o2
, EQUAL_PLAIN
, 0, Qnil
) ? Qt
: Qnil
;
2114 DEFUN ("equal-including-properties", Fequal_including_properties
, Sequal_including_properties
, 2, 2, 0,
2115 doc
: /* Return t if two Lisp objects have similar structure and contents.
2116 This is like `equal' except that it compares the text properties
2117 of strings. (`equal' ignores text properties.) */)
2118 (Lisp_Object o1
, Lisp_Object o2
)
2120 return (internal_equal (o1
, o2
, EQUAL_INCLUDING_PROPERTIES
, 0, Qnil
)
2124 /* Return true if O1 and O2 are equal. Do not quit or check for cycles.
2125 Use this only on arguments that are cycle-free and not too large and
2126 are not window configurations. */
2129 equal_no_quit (Lisp_Object o1
, Lisp_Object o2
)
2131 return internal_equal (o1
, o2
, EQUAL_NO_QUIT
, 0, Qnil
);
2134 /* Return true if O1 and O2 are equal. EQUAL_KIND specifies what kind
2135 of equality test to use: if it is EQUAL_NO_QUIT, do not check for
2136 cycles or large arguments or quits; if EQUAL_PLAIN, do ordinary
2137 Lisp equality; and if EQUAL_INCLUDING_PROPERTIES, do
2138 equal-including-properties.
2140 If DEPTH is the current depth of recursion; signal an error if it
2141 gets too deep. HT is a hash table used to detect cycles; if nil,
2142 it has not been allocated yet. But ignore the last two arguments
2143 if EQUAL_KIND == EQUAL_NO_QUIT. */
2146 internal_equal (Lisp_Object o1
, Lisp_Object o2
, enum equal_kind equal_kind
,
2147 int depth
, Lisp_Object ht
)
2152 eassert (equal_kind
!= EQUAL_NO_QUIT
);
2154 error ("Stack overflow in equal");
2156 ht
= CALLN (Fmake_hash_table
, QCtest
, Qeq
);
2159 case Lisp_Cons
: case Lisp_Misc
: case Lisp_Vectorlike
:
2161 struct Lisp_Hash_Table
*h
= XHASH_TABLE (ht
);
2163 ptrdiff_t i
= hash_lookup (h
, o1
, &hash
);
2165 { /* `o1' was seen already. */
2166 Lisp_Object o2s
= HASH_VALUE (h
, i
);
2167 if (!NILP (Fmemq (o2
, o2s
)))
2170 set_hash_value_slot (h
, i
, Fcons (o2
, o2s
));
2173 hash_put (h
, o1
, Fcons (o2
, Qnil
), hash
);
2181 if (XTYPE (o1
) != XTYPE (o2
))
2188 double d1
= XFLOAT_DATA (o1
);
2189 double d2
= XFLOAT_DATA (o2
);
2190 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2191 though they are not =. */
2192 return d1
== d2
|| (d1
!= d1
&& d2
!= d2
);
2196 if (equal_kind
== EQUAL_NO_QUIT
)
2197 for (; CONSP (o1
); o1
= XCDR (o1
))
2201 if (! equal_no_quit (XCAR (o1
), XCAR (o2
)))
2204 if (EQ (XCDR (o1
), o2
))
2212 if (! internal_equal (XCAR (o1
), XCAR (o2
),
2213 equal_kind
, depth
+ 1, ht
))
2216 if (EQ (XCDR (o1
), o2
))
2223 if (XMISCTYPE (o1
) != XMISCTYPE (o2
))
2227 if (!internal_equal (OVERLAY_START (o1
), OVERLAY_START (o2
),
2228 equal_kind
, depth
+ 1, ht
)
2229 || !internal_equal (OVERLAY_END (o1
), OVERLAY_END (o2
),
2230 equal_kind
, depth
+ 1, ht
))
2232 o1
= XOVERLAY (o1
)->plist
;
2233 o2
= XOVERLAY (o2
)->plist
;
2239 return (XMARKER (o1
)->buffer
== XMARKER (o2
)->buffer
2240 && (XMARKER (o1
)->buffer
== 0
2241 || XMARKER (o1
)->bytepos
== XMARKER (o2
)->bytepos
));
2245 case Lisp_Vectorlike
:
2248 ptrdiff_t size
= ASIZE (o1
);
2249 /* Pseudovectors have the type encoded in the size field, so this test
2250 actually checks that the objects have the same type as well as the
2252 if (ASIZE (o2
) != size
)
2254 /* Boolvectors are compared much like strings. */
2255 if (BOOL_VECTOR_P (o1
))
2257 EMACS_INT size
= bool_vector_size (o1
);
2258 if (size
!= bool_vector_size (o2
))
2260 if (memcmp (bool_vector_data (o1
), bool_vector_data (o2
),
2261 bool_vector_bytes (size
)))
2265 if (WINDOW_CONFIGURATIONP (o1
))
2267 eassert (equal_kind
!= EQUAL_NO_QUIT
);
2268 return compare_window_configurations (o1
, o2
, false);
2271 /* Aside from them, only true vectors, char-tables, compiled
2272 functions, and fonts (font-spec, font-entity, font-object)
2273 are sensible to compare, so eliminate the others now. */
2274 if (size
& PSEUDOVECTOR_FLAG
)
2276 if (((size
& PVEC_TYPE_MASK
) >> PSEUDOVECTOR_AREA_BITS
)
2279 size
&= PSEUDOVECTOR_SIZE_MASK
;
2281 for (i
= 0; i
< size
; i
++)
2286 if (!internal_equal (v1
, v2
, equal_kind
, depth
+ 1, ht
))
2294 if (SCHARS (o1
) != SCHARS (o2
))
2296 if (SBYTES (o1
) != SBYTES (o2
))
2298 if (memcmp (SDATA (o1
), SDATA (o2
), SBYTES (o1
)))
2300 if (equal_kind
== EQUAL_INCLUDING_PROPERTIES
2301 && !compare_string_intervals (o1
, o2
))
2313 DEFUN ("fillarray", Ffillarray
, Sfillarray
, 2, 2, 0,
2314 doc
: /* Store each element of ARRAY with ITEM.
2315 ARRAY is a vector, string, char-table, or bool-vector. */)
2316 (Lisp_Object array
, Lisp_Object item
)
2318 register ptrdiff_t size
, idx
;
2320 if (VECTORP (array
))
2321 for (idx
= 0, size
= ASIZE (array
); idx
< size
; idx
++)
2322 ASET (array
, idx
, item
);
2323 else if (CHAR_TABLE_P (array
))
2327 for (i
= 0; i
< (1 << CHARTAB_SIZE_BITS_0
); i
++)
2328 set_char_table_contents (array
, i
, item
);
2329 set_char_table_defalt (array
, item
);
2331 else if (STRINGP (array
))
2333 register unsigned char *p
= SDATA (array
);
2335 CHECK_CHARACTER (item
);
2336 charval
= XFASTINT (item
);
2337 size
= SCHARS (array
);
2338 if (STRING_MULTIBYTE (array
))
2340 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
2341 int len
= CHAR_STRING (charval
, str
);
2342 ptrdiff_t size_byte
= SBYTES (array
);
2345 if (INT_MULTIPLY_WRAPV (size
, len
, &product
) || product
!= size_byte
)
2346 error ("Attempt to change byte length of a string");
2347 for (idx
= 0; idx
< size_byte
; idx
++)
2348 *p
++ = str
[idx
% len
];
2351 for (idx
= 0; idx
< size
; idx
++)
2354 else if (BOOL_VECTOR_P (array
))
2355 return bool_vector_fill (array
, item
);
2357 wrong_type_argument (Qarrayp
, array
);
2361 DEFUN ("clear-string", Fclear_string
, Sclear_string
,
2363 doc
: /* Clear the contents of STRING.
2364 This makes STRING unibyte and may change its length. */)
2365 (Lisp_Object string
)
2368 CHECK_STRING (string
);
2369 len
= SBYTES (string
);
2370 memset (SDATA (string
), 0, len
);
2371 STRING_SET_CHARS (string
, len
);
2372 STRING_SET_UNIBYTE (string
);
2378 nconc2 (Lisp_Object s1
, Lisp_Object s2
)
2380 return CALLN (Fnconc
, s1
, s2
);
2383 DEFUN ("nconc", Fnconc
, Snconc
, 0, MANY
, 0,
2384 doc
: /* Concatenate any number of lists by altering them.
2385 Only the last argument is not altered, and need not be a list.
2386 usage: (nconc &rest LISTS) */)
2387 (ptrdiff_t nargs
, Lisp_Object
*args
)
2389 Lisp_Object val
= Qnil
;
2391 for (ptrdiff_t argnum
= 0; argnum
< nargs
; argnum
++)
2393 Lisp_Object tem
= args
[argnum
];
2394 if (NILP (tem
)) continue;
2399 if (argnum
+ 1 == nargs
) break;
2407 tem
= args
[argnum
+ 1];
2408 Fsetcdr (tail
, tem
);
2410 args
[argnum
+ 1] = tail
;
2416 /* This is the guts of all mapping functions.
2417 Apply FN to each element of SEQ, one by one, storing the results
2418 into elements of VALS, a C vector of Lisp_Objects. LENI is the
2419 length of VALS, which should also be the length of SEQ. Return the
2420 number of results; although this is normally LENI, it can be less
2421 if SEQ is made shorter as a side effect of FN. */
2424 mapcar1 (EMACS_INT leni
, Lisp_Object
*vals
, Lisp_Object fn
, Lisp_Object seq
)
2426 Lisp_Object tail
, dummy
;
2429 if (VECTORP (seq
) || COMPILEDP (seq
))
2431 for (i
= 0; i
< leni
; i
++)
2433 dummy
= call1 (fn
, AREF (seq
, i
));
2438 else if (BOOL_VECTOR_P (seq
))
2440 for (i
= 0; i
< leni
; i
++)
2442 dummy
= call1 (fn
, bool_vector_ref (seq
, i
));
2447 else if (STRINGP (seq
))
2451 for (i
= 0, i_byte
= 0; i
< leni
;)
2454 ptrdiff_t i_before
= i
;
2456 FETCH_STRING_CHAR_ADVANCE (c
, seq
, i
, i_byte
);
2457 XSETFASTINT (dummy
, c
);
2458 dummy
= call1 (fn
, dummy
);
2460 vals
[i_before
] = dummy
;
2463 else /* Must be a list, since Flength did not get an error */
2466 for (i
= 0; i
< leni
; i
++)
2470 dummy
= call1 (fn
, XCAR (tail
));
2480 DEFUN ("mapconcat", Fmapconcat
, Smapconcat
, 3, 3, 0,
2481 doc
: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2482 In between each pair of results, stick in SEPARATOR. Thus, " " as
2483 SEPARATOR results in spaces between the values returned by FUNCTION.
2484 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2485 (Lisp_Object function
, Lisp_Object sequence
, Lisp_Object separator
)
2488 EMACS_INT leni
= XFASTINT (Flength (sequence
));
2489 if (CHAR_TABLE_P (sequence
))
2490 wrong_type_argument (Qlistp
, sequence
);
2491 EMACS_INT args_alloc
= 2 * leni
- 1;
2493 return empty_unibyte_string
;
2495 SAFE_ALLOCA_LISP (args
, args_alloc
);
2496 ptrdiff_t nmapped
= mapcar1 (leni
, args
, function
, sequence
);
2497 ptrdiff_t nargs
= 2 * nmapped
- 1;
2499 for (ptrdiff_t i
= nmapped
- 1; i
> 0; i
--)
2500 args
[i
+ i
] = args
[i
];
2502 for (ptrdiff_t i
= 1; i
< nargs
; i
+= 2)
2503 args
[i
] = separator
;
2505 Lisp_Object ret
= Fconcat (nargs
, args
);
2510 DEFUN ("mapcar", Fmapcar
, Smapcar
, 2, 2, 0,
2511 doc
: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2512 The result is a list just as long as SEQUENCE.
2513 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2514 (Lisp_Object function
, Lisp_Object sequence
)
2517 EMACS_INT leni
= XFASTINT (Flength (sequence
));
2518 if (CHAR_TABLE_P (sequence
))
2519 wrong_type_argument (Qlistp
, sequence
);
2521 SAFE_ALLOCA_LISP (args
, leni
);
2522 ptrdiff_t nmapped
= mapcar1 (leni
, args
, function
, sequence
);
2523 Lisp_Object ret
= Flist (nmapped
, args
);
2528 DEFUN ("mapc", Fmapc
, Smapc
, 2, 2, 0,
2529 doc
: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2530 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2531 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2532 (Lisp_Object function
, Lisp_Object sequence
)
2534 register EMACS_INT leni
;
2536 leni
= XFASTINT (Flength (sequence
));
2537 if (CHAR_TABLE_P (sequence
))
2538 wrong_type_argument (Qlistp
, sequence
);
2539 mapcar1 (leni
, 0, function
, sequence
);
2544 DEFUN ("mapcan", Fmapcan
, Smapcan
, 2, 2, 0,
2545 doc
: /* Apply FUNCTION to each element of SEQUENCE, and concatenate
2546 the results by altering them (using `nconc').
2547 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2548 (Lisp_Object function
, Lisp_Object sequence
)
2551 EMACS_INT leni
= XFASTINT (Flength (sequence
));
2552 if (CHAR_TABLE_P (sequence
))
2553 wrong_type_argument (Qlistp
, sequence
);
2555 SAFE_ALLOCA_LISP (args
, leni
);
2556 ptrdiff_t nmapped
= mapcar1 (leni
, args
, function
, sequence
);
2557 Lisp_Object ret
= Fnconc (nmapped
, args
);
2562 /* This is how C code calls `yes-or-no-p' and allows the user
2566 do_yes_or_no_p (Lisp_Object prompt
)
2568 return call1 (intern ("yes-or-no-p"), prompt
);
2571 DEFUN ("yes-or-no-p", Fyes_or_no_p
, Syes_or_no_p
, 1, 1, 0,
2572 doc
: /* Ask user a yes-or-no question.
2573 Return t if answer is yes, and nil if the answer is no.
2574 PROMPT is the string to display to ask the question. It should end in
2575 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2577 The user must confirm the answer with RET, and can edit it until it
2580 If dialog boxes are supported, a dialog box will be used
2581 if `last-nonmenu-event' is nil, and `use-dialog-box' is non-nil. */)
2582 (Lisp_Object prompt
)
2586 CHECK_STRING (prompt
);
2588 if ((NILP (last_nonmenu_event
) || CONSP (last_nonmenu_event
))
2589 && use_dialog_box
&& ! NILP (last_input_event
))
2591 Lisp_Object pane
, menu
, obj
;
2592 redisplay_preserve_echo_area (4);
2593 pane
= list2 (Fcons (build_string ("Yes"), Qt
),
2594 Fcons (build_string ("No"), Qnil
));
2595 menu
= Fcons (prompt
, pane
);
2596 obj
= Fx_popup_dialog (Qt
, menu
, Qnil
);
2600 AUTO_STRING (yes_or_no
, "(yes or no) ");
2601 prompt
= CALLN (Fconcat
, prompt
, yes_or_no
);
2605 ans
= Fdowncase (Fread_from_minibuffer (prompt
, Qnil
, Qnil
, Qnil
,
2606 Qyes_or_no_p_history
, Qnil
,
2608 if (SCHARS (ans
) == 3 && !strcmp (SSDATA (ans
), "yes"))
2610 if (SCHARS (ans
) == 2 && !strcmp (SSDATA (ans
), "no"))
2615 message1 ("Please answer yes or no.");
2616 Fsleep_for (make_number (2), Qnil
);
2620 DEFUN ("load-average", Fload_average
, Sload_average
, 0, 1, 0,
2621 doc
: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2623 Each of the three load averages is multiplied by 100, then converted
2626 When USE-FLOATS is non-nil, floats will be used instead of integers.
2627 These floats are not multiplied by 100.
2629 If the 5-minute or 15-minute load averages are not available, return a
2630 shortened list, containing only those averages which are available.
2632 An error is thrown if the load average can't be obtained. In some
2633 cases making it work would require Emacs being installed setuid or
2634 setgid so that it can read kernel information, and that usually isn't
2636 (Lisp_Object use_floats
)
2639 int loads
= getloadavg (load_ave
, 3);
2640 Lisp_Object ret
= Qnil
;
2643 error ("load-average not implemented for this operating system");
2647 Lisp_Object load
= (NILP (use_floats
)
2648 ? make_number (100.0 * load_ave
[loads
])
2649 : make_float (load_ave
[loads
]));
2650 ret
= Fcons (load
, ret
);
2656 DEFUN ("featurep", Ffeaturep
, Sfeaturep
, 1, 2, 0,
2657 doc
: /* Return t if FEATURE is present in this Emacs.
2659 Use this to conditionalize execution of lisp code based on the
2660 presence or absence of Emacs or environment extensions.
2661 Use `provide' to declare that a feature is available. This function
2662 looks at the value of the variable `features'. The optional argument
2663 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2664 (Lisp_Object feature
, Lisp_Object subfeature
)
2666 register Lisp_Object tem
;
2667 CHECK_SYMBOL (feature
);
2668 tem
= Fmemq (feature
, Vfeatures
);
2669 if (!NILP (tem
) && !NILP (subfeature
))
2670 tem
= Fmember (subfeature
, Fget (feature
, Qsubfeatures
));
2671 return (NILP (tem
)) ? Qnil
: Qt
;
2674 DEFUN ("provide", Fprovide
, Sprovide
, 1, 2, 0,
2675 doc
: /* Announce that FEATURE is a feature of the current Emacs.
2676 The optional argument SUBFEATURES should be a list of symbols listing
2677 particular subfeatures supported in this version of FEATURE. */)
2678 (Lisp_Object feature
, Lisp_Object subfeatures
)
2680 register Lisp_Object tem
;
2681 CHECK_SYMBOL (feature
);
2682 CHECK_LIST (subfeatures
);
2683 if (!NILP (Vautoload_queue
))
2684 Vautoload_queue
= Fcons (Fcons (make_number (0), Vfeatures
),
2686 tem
= Fmemq (feature
, Vfeatures
);
2688 Vfeatures
= Fcons (feature
, Vfeatures
);
2689 if (!NILP (subfeatures
))
2690 Fput (feature
, Qsubfeatures
, subfeatures
);
2691 LOADHIST_ATTACH (Fcons (Qprovide
, feature
));
2693 /* Run any load-hooks for this file. */
2694 tem
= Fassq (feature
, Vafter_load_alist
);
2696 Fmapc (Qfuncall
, XCDR (tem
));
2701 /* `require' and its subroutines. */
2703 /* List of features currently being require'd, innermost first. */
2705 static Lisp_Object require_nesting_list
;
2708 require_unwind (Lisp_Object old_value
)
2710 require_nesting_list
= old_value
;
2713 DEFUN ("require", Frequire
, Srequire
, 1, 3, 0,
2714 doc
: /* If feature FEATURE is not loaded, load it from FILENAME.
2715 If FEATURE is not a member of the list `features', then the feature is
2716 not loaded; so load the file FILENAME.
2718 If FILENAME is omitted, the printname of FEATURE is used as the file
2719 name, and `load' will try to load this name appended with the suffix
2720 `.elc', `.el', or the system-dependent suffix for dynamic module
2721 files, in that order. The name without appended suffix will not be
2722 used. See `get-load-suffixes' for the complete list of suffixes.
2724 The directories in `load-path' are searched when trying to find the
2727 If the optional third argument NOERROR is non-nil, then return nil if
2728 the file is not found instead of signaling an error. Normally the
2729 return value is FEATURE.
2731 The normal messages at start and end of loading FILENAME are
2733 (Lisp_Object feature
, Lisp_Object filename
, Lisp_Object noerror
)
2736 bool from_file
= load_in_progress
;
2738 CHECK_SYMBOL (feature
);
2740 /* Record the presence of `require' in this file
2741 even if the feature specified is already loaded.
2742 But not more than once in any file,
2743 and not when we aren't loading or reading from a file. */
2745 for (tem
= Vcurrent_load_list
; CONSP (tem
); tem
= XCDR (tem
))
2746 if (NILP (XCDR (tem
)) && STRINGP (XCAR (tem
)))
2751 tem
= Fcons (Qrequire
, feature
);
2752 if (NILP (Fmember (tem
, Vcurrent_load_list
)))
2753 LOADHIST_ATTACH (tem
);
2755 tem
= Fmemq (feature
, Vfeatures
);
2759 ptrdiff_t count
= SPECPDL_INDEX ();
2762 /* This is to make sure that loadup.el gives a clear picture
2763 of what files are preloaded and when. */
2764 if (! NILP (Vpurify_flag
))
2765 error ("(require %s) while preparing to dump",
2766 SDATA (SYMBOL_NAME (feature
)));
2768 /* A certain amount of recursive `require' is legitimate,
2769 but if we require the same feature recursively 3 times,
2771 tem
= require_nesting_list
;
2772 while (! NILP (tem
))
2774 if (! NILP (Fequal (feature
, XCAR (tem
))))
2779 error ("Recursive `require' for feature `%s'",
2780 SDATA (SYMBOL_NAME (feature
)));
2782 /* Update the list for any nested `require's that occur. */
2783 record_unwind_protect (require_unwind
, require_nesting_list
);
2784 require_nesting_list
= Fcons (feature
, require_nesting_list
);
2786 /* Value saved here is to be restored into Vautoload_queue */
2787 record_unwind_protect (un_autoload
, Vautoload_queue
);
2788 Vautoload_queue
= Qt
;
2790 /* Load the file. */
2791 tem
= Fload (NILP (filename
) ? Fsymbol_name (feature
) : filename
,
2792 noerror
, Qt
, Qnil
, (NILP (filename
) ? Qt
: Qnil
));
2794 /* If load failed entirely, return nil. */
2796 return unbind_to (count
, Qnil
);
2798 tem
= Fmemq (feature
, Vfeatures
);
2800 error ("Required feature `%s' was not provided",
2801 SDATA (SYMBOL_NAME (feature
)));
2803 /* Once loading finishes, don't undo it. */
2804 Vautoload_queue
= Qt
;
2805 feature
= unbind_to (count
, feature
);
2811 /* Primitives for work of the "widget" library.
2812 In an ideal world, this section would not have been necessary.
2813 However, lisp function calls being as slow as they are, it turns
2814 out that some functions in the widget library (wid-edit.el) are the
2815 bottleneck of Widget operation. Here is their translation to C,
2816 for the sole reason of efficiency. */
2818 DEFUN ("plist-member", Fplist_member
, Splist_member
, 2, 2, 0,
2819 doc
: /* Return non-nil if PLIST has the property PROP.
2820 PLIST is a property list, which is a list of the form
2821 \(PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol.
2822 Unlike `plist-get', this allows you to distinguish between a missing
2823 property and a property with the value nil.
2824 The value is actually the tail of PLIST whose car is PROP. */)
2825 (Lisp_Object plist
, Lisp_Object prop
)
2827 Lisp_Object tail
= plist
;
2828 FOR_EACH_TAIL (tail
)
2830 if (EQ (XCAR (tail
), prop
))
2835 if (EQ (tail
, li
.tortoise
))
2836 circular_list (tail
);
2838 CHECK_LIST_END (tail
, plist
);
2842 DEFUN ("widget-put", Fwidget_put
, Swidget_put
, 3, 3, 0,
2843 doc
: /* In WIDGET, set PROPERTY to VALUE.
2844 The value can later be retrieved with `widget-get'. */)
2845 (Lisp_Object widget
, Lisp_Object property
, Lisp_Object value
)
2847 CHECK_CONS (widget
);
2848 XSETCDR (widget
, Fplist_put (XCDR (widget
), property
, value
));
2852 DEFUN ("widget-get", Fwidget_get
, Swidget_get
, 2, 2, 0,
2853 doc
: /* In WIDGET, get the value of PROPERTY.
2854 The value could either be specified when the widget was created, or
2855 later with `widget-put'. */)
2856 (Lisp_Object widget
, Lisp_Object property
)
2864 CHECK_CONS (widget
);
2865 tmp
= Fplist_member (XCDR (widget
), property
);
2871 tmp
= XCAR (widget
);
2874 widget
= Fget (tmp
, Qwidget_type
);
2878 DEFUN ("widget-apply", Fwidget_apply
, Swidget_apply
, 2, MANY
, 0,
2879 doc
: /* Apply the value of WIDGET's PROPERTY to the widget itself.
2880 ARGS are passed as extra arguments to the function.
2881 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
2882 (ptrdiff_t nargs
, Lisp_Object
*args
)
2884 Lisp_Object widget
= args
[0];
2885 Lisp_Object property
= args
[1];
2886 Lisp_Object propval
= Fwidget_get (widget
, property
);
2887 Lisp_Object trailing_args
= Flist (nargs
- 2, args
+ 2);
2888 Lisp_Object result
= CALLN (Fapply
, propval
, widget
, trailing_args
);
2892 #ifdef HAVE_LANGINFO_CODESET
2893 #include <langinfo.h>
2896 DEFUN ("locale-info", Flocale_info
, Slocale_info
, 1, 1, 0,
2897 doc
: /* Access locale data ITEM for the current C locale, if available.
2898 ITEM should be one of the following:
2900 `codeset', returning the character set as a string (locale item CODESET);
2902 `days', returning a 7-element vector of day names (locale items DAY_n);
2904 `months', returning a 12-element vector of month names (locale items MON_n);
2906 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
2907 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
2909 If the system can't provide such information through a call to
2910 `nl_langinfo', or if ITEM isn't from the list above, return nil.
2912 See also Info node `(libc)Locales'.
2914 The data read from the system are decoded using `locale-coding-system'. */)
2918 #ifdef HAVE_LANGINFO_CODESET
2919 if (EQ (item
, Qcodeset
))
2921 str
= nl_langinfo (CODESET
);
2922 return build_string (str
);
2925 else if (EQ (item
, Qdays
)) /* e.g. for calendar-day-name-array */
2927 Lisp_Object v
= Fmake_vector (make_number (7), Qnil
);
2928 const int days
[7] = {DAY_1
, DAY_2
, DAY_3
, DAY_4
, DAY_5
, DAY_6
, DAY_7
};
2930 synchronize_system_time_locale ();
2931 for (i
= 0; i
< 7; i
++)
2933 str
= nl_langinfo (days
[i
]);
2934 AUTO_STRING (val
, str
);
2935 /* Fixme: Is this coding system necessarily right, even if
2936 it is consistent with CODESET? If not, what to do? */
2937 ASET (v
, i
, code_convert_string_norecord (val
, Vlocale_coding_system
,
2944 else if (EQ (item
, Qmonths
)) /* e.g. for calendar-month-name-array */
2946 Lisp_Object v
= Fmake_vector (make_number (12), Qnil
);
2947 const int months
[12] = {MON_1
, MON_2
, MON_3
, MON_4
, MON_5
, MON_6
, MON_7
,
2948 MON_8
, MON_9
, MON_10
, MON_11
, MON_12
};
2950 synchronize_system_time_locale ();
2951 for (i
= 0; i
< 12; i
++)
2953 str
= nl_langinfo (months
[i
]);
2954 AUTO_STRING (val
, str
);
2955 ASET (v
, i
, code_convert_string_norecord (val
, Vlocale_coding_system
,
2961 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
2962 but is in the locale files. This could be used by ps-print. */
2964 else if (EQ (item
, Qpaper
))
2965 return list2i (nl_langinfo (PAPER_WIDTH
), nl_langinfo (PAPER_HEIGHT
));
2966 #endif /* PAPER_WIDTH */
2967 #endif /* HAVE_LANGINFO_CODESET*/
2971 /* base64 encode/decode functions (RFC 2045).
2972 Based on code from GNU recode. */
2974 #define MIME_LINE_LENGTH 76
2976 #define IS_ASCII(Character) \
2978 #define IS_BASE64(Character) \
2979 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
2980 #define IS_BASE64_IGNORABLE(Character) \
2981 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
2982 || (Character) == '\f' || (Character) == '\r')
2984 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
2985 character or return retval if there are no characters left to
2987 #define READ_QUADRUPLET_BYTE(retval) \
2992 if (nchars_return) \
2993 *nchars_return = nchars; \
2998 while (IS_BASE64_IGNORABLE (c))
3000 /* Table of characters coding the 64 values. */
3001 static const char base64_value_to_char
[64] =
3003 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
3004 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
3005 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
3006 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
3007 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
3008 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
3009 '8', '9', '+', '/' /* 60-63 */
3012 /* Table of base64 values for first 128 characters. */
3013 static const short base64_char_to_value
[128] =
3015 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
3016 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
3017 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
3018 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
3019 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
3020 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
3021 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
3022 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
3023 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
3024 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
3025 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
3026 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
3027 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
3030 /* The following diagram shows the logical steps by which three octets
3031 get transformed into four base64 characters.
3033 .--------. .--------. .--------.
3034 |aaaaaabb| |bbbbcccc| |ccdddddd|
3035 `--------' `--------' `--------'
3037 .--------+--------+--------+--------.
3038 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
3039 `--------+--------+--------+--------'
3041 .--------+--------+--------+--------.
3042 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
3043 `--------+--------+--------+--------'
3045 The octets are divided into 6 bit chunks, which are then encoded into
3046 base64 characters. */
3049 static ptrdiff_t base64_encode_1 (const char *, char *, ptrdiff_t, bool, bool);
3050 static ptrdiff_t base64_decode_1 (const char *, char *, ptrdiff_t, bool,
3053 DEFUN ("base64-encode-region", Fbase64_encode_region
, Sbase64_encode_region
,
3055 doc
: /* Base64-encode the region between BEG and END.
3056 Return the length of the encoded text.
3057 Optional third argument NO-LINE-BREAK means do not break long lines
3058 into shorter lines. */)
3059 (Lisp_Object beg
, Lisp_Object end
, Lisp_Object no_line_break
)
3062 ptrdiff_t allength
, length
;
3063 ptrdiff_t ibeg
, iend
, encoded_length
;
3064 ptrdiff_t old_pos
= PT
;
3067 validate_region (&beg
, &end
);
3069 ibeg
= CHAR_TO_BYTE (XFASTINT (beg
));
3070 iend
= CHAR_TO_BYTE (XFASTINT (end
));
3071 move_gap_both (XFASTINT (beg
), ibeg
);
3073 /* We need to allocate enough room for encoding the text.
3074 We need 33 1/3% more space, plus a newline every 76
3075 characters, and then we round up. */
3076 length
= iend
- ibeg
;
3077 allength
= length
+ length
/3 + 1;
3078 allength
+= allength
/ MIME_LINE_LENGTH
+ 1 + 6;
3080 encoded
= SAFE_ALLOCA (allength
);
3081 encoded_length
= base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg
),
3082 encoded
, length
, NILP (no_line_break
),
3083 !NILP (BVAR (current_buffer
, enable_multibyte_characters
)));
3084 if (encoded_length
> allength
)
3087 if (encoded_length
< 0)
3089 /* The encoding wasn't possible. */
3091 error ("Multibyte character in data for base64 encoding");
3094 /* Now we have encoded the region, so we insert the new contents
3095 and delete the old. (Insert first in order to preserve markers.) */
3096 SET_PT_BOTH (XFASTINT (beg
), ibeg
);
3097 insert (encoded
, encoded_length
);
3099 del_range_byte (ibeg
+ encoded_length
, iend
+ encoded_length
);
3101 /* If point was outside of the region, restore it exactly; else just
3102 move to the beginning of the region. */
3103 if (old_pos
>= XFASTINT (end
))
3104 old_pos
+= encoded_length
- (XFASTINT (end
) - XFASTINT (beg
));
3105 else if (old_pos
> XFASTINT (beg
))
3106 old_pos
= XFASTINT (beg
);
3109 /* We return the length of the encoded text. */
3110 return make_number (encoded_length
);
3113 DEFUN ("base64-encode-string", Fbase64_encode_string
, Sbase64_encode_string
,
3115 doc
: /* Base64-encode STRING and return the result.
3116 Optional second argument NO-LINE-BREAK means do not break long lines
3117 into shorter lines. */)
3118 (Lisp_Object string
, Lisp_Object no_line_break
)
3120 ptrdiff_t allength
, length
, encoded_length
;
3122 Lisp_Object encoded_string
;
3125 CHECK_STRING (string
);
3127 /* We need to allocate enough room for encoding the text.
3128 We need 33 1/3% more space, plus a newline every 76
3129 characters, and then we round up. */
3130 length
= SBYTES (string
);
3131 allength
= length
+ length
/3 + 1;
3132 allength
+= allength
/ MIME_LINE_LENGTH
+ 1 + 6;
3134 /* We need to allocate enough room for decoding the text. */
3135 encoded
= SAFE_ALLOCA (allength
);
3137 encoded_length
= base64_encode_1 (SSDATA (string
),
3138 encoded
, length
, NILP (no_line_break
),
3139 STRING_MULTIBYTE (string
));
3140 if (encoded_length
> allength
)
3143 if (encoded_length
< 0)
3145 /* The encoding wasn't possible. */
3146 error ("Multibyte character in data for base64 encoding");
3149 encoded_string
= make_unibyte_string (encoded
, encoded_length
);
3152 return encoded_string
;
3156 base64_encode_1 (const char *from
, char *to
, ptrdiff_t length
,
3157 bool line_break
, bool multibyte
)
3170 c
= STRING_CHAR_AND_LENGTH ((unsigned char *) from
+ i
, bytes
);
3171 if (CHAR_BYTE8_P (c
))
3172 c
= CHAR_TO_BYTE8 (c
);
3180 /* Wrap line every 76 characters. */
3184 if (counter
< MIME_LINE_LENGTH
/ 4)
3193 /* Process first byte of a triplet. */
3195 *e
++ = base64_value_to_char
[0x3f & c
>> 2];
3196 value
= (0x03 & c
) << 4;
3198 /* Process second byte of a triplet. */
3202 *e
++ = base64_value_to_char
[value
];
3210 c
= STRING_CHAR_AND_LENGTH ((unsigned char *) from
+ i
, bytes
);
3211 if (CHAR_BYTE8_P (c
))
3212 c
= CHAR_TO_BYTE8 (c
);
3220 *e
++ = base64_value_to_char
[value
| (0x0f & c
>> 4)];
3221 value
= (0x0f & c
) << 2;
3223 /* Process third byte of a triplet. */
3227 *e
++ = base64_value_to_char
[value
];
3234 c
= STRING_CHAR_AND_LENGTH ((unsigned char *) from
+ i
, bytes
);
3235 if (CHAR_BYTE8_P (c
))
3236 c
= CHAR_TO_BYTE8 (c
);
3244 *e
++ = base64_value_to_char
[value
| (0x03 & c
>> 6)];
3245 *e
++ = base64_value_to_char
[0x3f & c
];
3252 DEFUN ("base64-decode-region", Fbase64_decode_region
, Sbase64_decode_region
,
3254 doc
: /* Base64-decode the region between BEG and END.
3255 Return the length of the decoded text.
3256 If the region can't be decoded, signal an error and don't modify the buffer. */)
3257 (Lisp_Object beg
, Lisp_Object end
)
3259 ptrdiff_t ibeg
, iend
, length
, allength
;
3261 ptrdiff_t old_pos
= PT
;
3262 ptrdiff_t decoded_length
;
3263 ptrdiff_t inserted_chars
;
3264 bool multibyte
= !NILP (BVAR (current_buffer
, enable_multibyte_characters
));
3267 validate_region (&beg
, &end
);
3269 ibeg
= CHAR_TO_BYTE (XFASTINT (beg
));
3270 iend
= CHAR_TO_BYTE (XFASTINT (end
));
3272 length
= iend
- ibeg
;
3274 /* We need to allocate enough room for decoding the text. If we are
3275 working on a multibyte buffer, each decoded code may occupy at
3277 allength
= multibyte
? length
* 2 : length
;
3278 decoded
= SAFE_ALLOCA (allength
);
3280 move_gap_both (XFASTINT (beg
), ibeg
);
3281 decoded_length
= base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg
),
3283 multibyte
, &inserted_chars
);
3284 if (decoded_length
> allength
)
3287 if (decoded_length
< 0)
3289 /* The decoding wasn't possible. */
3290 error ("Invalid base64 data");
3293 /* Now we have decoded the region, so we insert the new contents
3294 and delete the old. (Insert first in order to preserve markers.) */
3295 TEMP_SET_PT_BOTH (XFASTINT (beg
), ibeg
);
3296 insert_1_both (decoded
, inserted_chars
, decoded_length
, 0, 1, 0);
3299 /* Delete the original text. */
3300 del_range_both (PT
, PT_BYTE
, XFASTINT (end
) + inserted_chars
,
3301 iend
+ decoded_length
, 1);
3303 /* If point was outside of the region, restore it exactly; else just
3304 move to the beginning of the region. */
3305 if (old_pos
>= XFASTINT (end
))
3306 old_pos
+= inserted_chars
- (XFASTINT (end
) - XFASTINT (beg
));
3307 else if (old_pos
> XFASTINT (beg
))
3308 old_pos
= XFASTINT (beg
);
3309 SET_PT (old_pos
> ZV
? ZV
: old_pos
);
3311 return make_number (inserted_chars
);
3314 DEFUN ("base64-decode-string", Fbase64_decode_string
, Sbase64_decode_string
,
3316 doc
: /* Base64-decode STRING and return the result. */)
3317 (Lisp_Object string
)
3320 ptrdiff_t length
, decoded_length
;
3321 Lisp_Object decoded_string
;
3324 CHECK_STRING (string
);
3326 length
= SBYTES (string
);
3327 /* We need to allocate enough room for decoding the text. */
3328 decoded
= SAFE_ALLOCA (length
);
3330 /* The decoded result should be unibyte. */
3331 decoded_length
= base64_decode_1 (SSDATA (string
), decoded
, length
,
3333 if (decoded_length
> length
)
3335 else if (decoded_length
>= 0)
3336 decoded_string
= make_unibyte_string (decoded
, decoded_length
);
3338 decoded_string
= Qnil
;
3341 if (!STRINGP (decoded_string
))
3342 error ("Invalid base64 data");
3344 return decoded_string
;
3347 /* Base64-decode the data at FROM of LENGTH bytes into TO. If
3348 MULTIBYTE, the decoded result should be in multibyte
3349 form. If NCHARS_RETURN is not NULL, store the number of produced
3350 characters in *NCHARS_RETURN. */
3353 base64_decode_1 (const char *from
, char *to
, ptrdiff_t length
,
3354 bool multibyte
, ptrdiff_t *nchars_return
)
3356 ptrdiff_t i
= 0; /* Used inside READ_QUADRUPLET_BYTE */
3359 unsigned long value
;
3360 ptrdiff_t nchars
= 0;
3364 /* Process first byte of a quadruplet. */
3366 READ_QUADRUPLET_BYTE (e
-to
);
3370 value
= base64_char_to_value
[c
] << 18;
3372 /* Process second byte of a quadruplet. */
3374 READ_QUADRUPLET_BYTE (-1);
3378 value
|= base64_char_to_value
[c
] << 12;
3380 c
= (unsigned char) (value
>> 16);
3381 if (multibyte
&& c
>= 128)
3382 e
+= BYTE8_STRING (c
, e
);
3387 /* Process third byte of a quadruplet. */
3389 READ_QUADRUPLET_BYTE (-1);
3393 READ_QUADRUPLET_BYTE (-1);
3402 value
|= base64_char_to_value
[c
] << 6;
3404 c
= (unsigned char) (0xff & value
>> 8);
3405 if (multibyte
&& c
>= 128)
3406 e
+= BYTE8_STRING (c
, e
);
3411 /* Process fourth byte of a quadruplet. */
3413 READ_QUADRUPLET_BYTE (-1);
3420 value
|= base64_char_to_value
[c
];
3422 c
= (unsigned char) (0xff & value
);
3423 if (multibyte
&& c
>= 128)
3424 e
+= BYTE8_STRING (c
, e
);
3433 /***********************************************************************
3435 ***** Hash Tables *****
3437 ***********************************************************************/
3439 /* Implemented by gerd@gnu.org. This hash table implementation was
3440 inspired by CMUCL hash tables. */
3444 1. For small tables, association lists are probably faster than
3445 hash tables because they have lower overhead.
3447 For uses of hash tables where the O(1) behavior of table
3448 operations is not a requirement, it might therefore be a good idea
3449 not to hash. Instead, we could just do a linear search in the
3450 key_and_value vector of the hash table. This could be done
3451 if a `:linear-search t' argument is given to make-hash-table. */
3454 /* The list of all weak hash tables. Don't staticpro this one. */
3456 static struct Lisp_Hash_Table
*weak_hash_tables
;
3459 /***********************************************************************
3461 ***********************************************************************/
3464 CHECK_HASH_TABLE (Lisp_Object x
)
3466 CHECK_TYPE (HASH_TABLE_P (x
), Qhash_table_p
, x
);
3470 set_hash_key_and_value (struct Lisp_Hash_Table
*h
, Lisp_Object key_and_value
)
3472 h
->key_and_value
= key_and_value
;
3475 set_hash_next (struct Lisp_Hash_Table
*h
, Lisp_Object next
)
3480 set_hash_next_slot (struct Lisp_Hash_Table
*h
, ptrdiff_t idx
, ptrdiff_t val
)
3482 gc_aset (h
->next
, idx
, make_number (val
));
3485 set_hash_hash (struct Lisp_Hash_Table
*h
, Lisp_Object hash
)
3490 set_hash_hash_slot (struct Lisp_Hash_Table
*h
, ptrdiff_t idx
, Lisp_Object val
)
3492 gc_aset (h
->hash
, idx
, val
);
3495 set_hash_index (struct Lisp_Hash_Table
*h
, Lisp_Object index
)
3500 set_hash_index_slot (struct Lisp_Hash_Table
*h
, ptrdiff_t idx
, ptrdiff_t val
)
3502 gc_aset (h
->index
, idx
, make_number (val
));
3505 /* If OBJ is a Lisp hash table, return a pointer to its struct
3506 Lisp_Hash_Table. Otherwise, signal an error. */
3508 static struct Lisp_Hash_Table
*
3509 check_hash_table (Lisp_Object obj
)
3511 CHECK_HASH_TABLE (obj
);
3512 return XHASH_TABLE (obj
);
3516 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3517 number. A number is "almost" a prime number if it is not divisible
3518 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3521 next_almost_prime (EMACS_INT n
)
3523 verify (NEXT_ALMOST_PRIME_LIMIT
== 11);
3524 for (n
|= 1; ; n
+= 2)
3525 if (n
% 3 != 0 && n
% 5 != 0 && n
% 7 != 0)
3530 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3531 which USED[I] is non-zero. If found at index I in ARGS, set
3532 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3533 0. This function is used to extract a keyword/argument pair from
3534 a DEFUN parameter list. */
3537 get_key_arg (Lisp_Object key
, ptrdiff_t nargs
, Lisp_Object
*args
, char *used
)
3541 for (i
= 1; i
< nargs
; i
++)
3542 if (!used
[i
- 1] && EQ (args
[i
- 1], key
))
3553 /* Return a Lisp vector which has the same contents as VEC but has
3554 at least INCR_MIN more entries, where INCR_MIN is positive.
3555 If NITEMS_MAX is not -1, do not grow the vector to be any larger
3556 than NITEMS_MAX. New entries in the resulting vector are
3560 larger_vecalloc (Lisp_Object vec
, ptrdiff_t incr_min
, ptrdiff_t nitems_max
)
3562 struct Lisp_Vector
*v
;
3563 ptrdiff_t incr
, incr_max
, old_size
, new_size
;
3564 ptrdiff_t C_language_max
= min (PTRDIFF_MAX
, SIZE_MAX
) / sizeof *v
->contents
;
3565 ptrdiff_t n_max
= (0 <= nitems_max
&& nitems_max
< C_language_max
3566 ? nitems_max
: C_language_max
);
3567 eassert (VECTORP (vec
));
3568 eassert (0 < incr_min
&& -1 <= nitems_max
);
3569 old_size
= ASIZE (vec
);
3570 incr_max
= n_max
- old_size
;
3571 incr
= max (incr_min
, min (old_size
>> 1, incr_max
));
3572 if (incr_max
< incr
)
3573 memory_full (SIZE_MAX
);
3574 new_size
= old_size
+ incr
;
3575 v
= allocate_vector (new_size
);
3576 memcpy (v
->contents
, XVECTOR (vec
)->contents
, old_size
* sizeof *v
->contents
);
3577 XSETVECTOR (vec
, v
);
3581 /* Likewise, except set new entries in the resulting vector to nil. */
3584 larger_vector (Lisp_Object vec
, ptrdiff_t incr_min
, ptrdiff_t nitems_max
)
3586 ptrdiff_t old_size
= ASIZE (vec
);
3587 Lisp_Object v
= larger_vecalloc (vec
, incr_min
, nitems_max
);
3588 ptrdiff_t new_size
= ASIZE (v
);
3589 memclear (XVECTOR (v
)->contents
+ old_size
,
3590 (new_size
- old_size
) * word_size
);
3595 /***********************************************************************
3597 ***********************************************************************/
3599 /* Return the index of the next entry in H following the one at IDX,
3603 HASH_NEXT (struct Lisp_Hash_Table
*h
, ptrdiff_t idx
)
3605 return XINT (AREF (h
->next
, idx
));
3608 /* Return the index of the element in hash table H that is the start
3609 of the collision list at index IDX, or -1 if the list is empty. */
3612 HASH_INDEX (struct Lisp_Hash_Table
*h
, ptrdiff_t idx
)
3614 return XINT (AREF (h
->index
, idx
));
3617 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3618 HASH2 in hash table H using `eql'. Value is true if KEY1 and
3619 KEY2 are the same. */
3622 cmpfn_eql (struct hash_table_test
*ht
,
3626 return (FLOATP (key1
)
3628 && XFLOAT_DATA (key1
) == XFLOAT_DATA (key2
));
3632 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3633 HASH2 in hash table H using `equal'. Value is true if KEY1 and
3634 KEY2 are the same. */
3637 cmpfn_equal (struct hash_table_test
*ht
,
3641 return !NILP (Fequal (key1
, key2
));
3645 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3646 HASH2 in hash table H using H->user_cmp_function. Value is true
3647 if KEY1 and KEY2 are the same. */
3650 cmpfn_user_defined (struct hash_table_test
*ht
,
3654 return !NILP (call2 (ht
->user_cmp_function
, key1
, key2
));
3657 /* Value is a hash code for KEY for use in hash table H which uses
3658 `eq' to compare keys. The hash code returned is guaranteed to fit
3659 in a Lisp integer. */
3662 hashfn_eq (struct hash_table_test
*ht
, Lisp_Object key
)
3664 return XHASH (key
) ^ XTYPE (key
);
3667 /* Value is a hash code for KEY for use in hash table H which uses
3668 `equal' to compare keys. The hash code returned is guaranteed to fit
3669 in a Lisp integer. */
3672 hashfn_equal (struct hash_table_test
*ht
, Lisp_Object key
)
3674 return sxhash (key
, 0);
3677 /* Value is a hash code for KEY for use in hash table H which uses
3678 `eql' to compare keys. The hash code returned is guaranteed to fit
3679 in a Lisp integer. */
3682 hashfn_eql (struct hash_table_test
*ht
, Lisp_Object key
)
3684 return FLOATP (key
) ? hashfn_equal (ht
, key
) : hashfn_eq (ht
, key
);
3687 /* Value is a hash code for KEY for use in hash table H which uses as
3688 user-defined function to compare keys. The hash code returned is
3689 guaranteed to fit in a Lisp integer. */
3692 hashfn_user_defined (struct hash_table_test
*ht
, Lisp_Object key
)
3694 Lisp_Object hash
= call1 (ht
->user_hash_function
, key
);
3695 return hashfn_eq (ht
, hash
);
3698 struct hash_table_test
const
3699 hashtest_eq
= { LISPSYM_INITIALLY (Qeq
), LISPSYM_INITIALLY (Qnil
),
3700 LISPSYM_INITIALLY (Qnil
), 0, hashfn_eq
},
3701 hashtest_eql
= { LISPSYM_INITIALLY (Qeql
), LISPSYM_INITIALLY (Qnil
),
3702 LISPSYM_INITIALLY (Qnil
), cmpfn_eql
, hashfn_eql
},
3703 hashtest_equal
= { LISPSYM_INITIALLY (Qequal
), LISPSYM_INITIALLY (Qnil
),
3704 LISPSYM_INITIALLY (Qnil
), cmpfn_equal
, hashfn_equal
};
3706 /* Allocate basically initialized hash table. */
3708 static struct Lisp_Hash_Table
*
3709 allocate_hash_table (void)
3711 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table
,
3712 count
, PVEC_HASH_TABLE
);
3715 /* An upper bound on the size of a hash table index. It must fit in
3716 ptrdiff_t and be a valid Emacs fixnum. */
3717 #define INDEX_SIZE_BOUND \
3718 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, PTRDIFF_MAX / word_size))
3720 /* Create and initialize a new hash table.
3722 TEST specifies the test the hash table will use to compare keys.
3723 It must be either one of the predefined tests `eq', `eql' or
3724 `equal' or a symbol denoting a user-defined test named TEST with
3725 test and hash functions USER_TEST and USER_HASH.
3727 Give the table initial capacity SIZE, 0 <= SIZE <= MOST_POSITIVE_FIXNUM.
3729 If REHASH_SIZE is equal to a negative integer, this hash table's
3730 new size when it becomes full is computed by subtracting
3731 REHASH_SIZE from its old size. Otherwise it must be positive, and
3732 the table's new size is computed by multiplying its old size by
3735 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3736 be resized when the approximate ratio of table entries to table
3737 size exceeds REHASH_THRESHOLD.
3739 WEAK specifies the weakness of the table. If non-nil, it must be
3740 one of the symbols `key', `value', `key-or-value', or `key-and-value'.
3742 If PURECOPY is non-nil, the table can be copied to pure storage via
3743 `purecopy' when Emacs is being dumped. Such tables can no longer be
3744 changed after purecopy. */
3747 make_hash_table (struct hash_table_test test
, EMACS_INT size
,
3748 float rehash_size
, float rehash_threshold
,
3749 Lisp_Object weak
, bool pure
)
3751 struct Lisp_Hash_Table
*h
;
3753 EMACS_INT index_size
;
3757 /* Preconditions. */
3758 eassert (SYMBOLP (test
.name
));
3759 eassert (0 <= size
&& size
<= MOST_POSITIVE_FIXNUM
);
3760 eassert (rehash_size
<= -1 || 0 < rehash_size
);
3761 eassert (0 < rehash_threshold
&& rehash_threshold
<= 1);
3766 double threshold
= rehash_threshold
;
3767 index_float
= size
/ threshold
;
3768 index_size
= (index_float
< INDEX_SIZE_BOUND
+ 1
3769 ? next_almost_prime (index_float
)
3770 : INDEX_SIZE_BOUND
+ 1);
3771 if (INDEX_SIZE_BOUND
< max (index_size
, 2 * size
))
3772 error ("Hash table too large");
3774 /* Allocate a table and initialize it. */
3775 h
= allocate_hash_table ();
3777 /* Initialize hash table slots. */
3780 h
->rehash_threshold
= rehash_threshold
;
3781 h
->rehash_size
= rehash_size
;
3783 h
->key_and_value
= Fmake_vector (make_number (2 * size
), Qnil
);
3784 h
->hash
= Fmake_vector (make_number (size
), Qnil
);
3785 h
->next
= Fmake_vector (make_number (size
), make_number (-1));
3786 h
->index
= Fmake_vector (make_number (index_size
), make_number (-1));
3789 /* Set up the free list. */
3790 for (i
= 0; i
< size
- 1; ++i
)
3791 set_hash_next_slot (h
, i
, i
+ 1);
3794 XSET_HASH_TABLE (table
, h
);
3795 eassert (HASH_TABLE_P (table
));
3796 eassert (XHASH_TABLE (table
) == h
);
3798 /* Maybe add this hash table to the list of all weak hash tables. */
3801 h
->next_weak
= weak_hash_tables
;
3802 weak_hash_tables
= h
;
3809 /* Return a copy of hash table H1. Keys and values are not copied,
3810 only the table itself is. */
3813 copy_hash_table (struct Lisp_Hash_Table
*h1
)
3816 struct Lisp_Hash_Table
*h2
;
3818 h2
= allocate_hash_table ();
3820 h2
->key_and_value
= Fcopy_sequence (h1
->key_and_value
);
3821 h2
->hash
= Fcopy_sequence (h1
->hash
);
3822 h2
->next
= Fcopy_sequence (h1
->next
);
3823 h2
->index
= Fcopy_sequence (h1
->index
);
3824 XSET_HASH_TABLE (table
, h2
);
3826 /* Maybe add this hash table to the list of all weak hash tables. */
3827 if (!NILP (h2
->weak
))
3829 h2
->next_weak
= h1
->next_weak
;
3837 /* Resize hash table H if it's too full. If H cannot be resized
3838 because it's already too large, throw an error. */
3841 maybe_resize_hash_table (struct Lisp_Hash_Table
*h
)
3843 if (h
->next_free
< 0)
3845 ptrdiff_t old_size
= HASH_TABLE_SIZE (h
);
3846 EMACS_INT new_size
, index_size
, nsize
;
3848 double rehash_size
= h
->rehash_size
;
3851 if (rehash_size
< 0)
3852 new_size
= old_size
- rehash_size
;
3855 double float_new_size
= old_size
* (rehash_size
+ 1);
3856 if (float_new_size
< INDEX_SIZE_BOUND
+ 1)
3857 new_size
= float_new_size
;
3859 new_size
= INDEX_SIZE_BOUND
+ 1;
3861 if (new_size
<= old_size
)
3862 new_size
= old_size
+ 1;
3863 double threshold
= h
->rehash_threshold
;
3864 index_float
= new_size
/ threshold
;
3865 index_size
= (index_float
< INDEX_SIZE_BOUND
+ 1
3866 ? next_almost_prime (index_float
)
3867 : INDEX_SIZE_BOUND
+ 1);
3868 nsize
= max (index_size
, 2 * new_size
);
3869 if (INDEX_SIZE_BOUND
< nsize
)
3870 error ("Hash table too large to resize");
3872 #ifdef ENABLE_CHECKING
3873 if (HASH_TABLE_P (Vpurify_flag
)
3874 && XHASH_TABLE (Vpurify_flag
) == h
)
3875 message ("Growing hash table to: %"pI
"d", new_size
);
3878 set_hash_key_and_value (h
, larger_vector (h
->key_and_value
,
3879 2 * (new_size
- old_size
), -1));
3880 set_hash_hash (h
, larger_vector (h
->hash
, new_size
- old_size
, -1));
3881 set_hash_index (h
, Fmake_vector (make_number (index_size
),
3883 set_hash_next (h
, larger_vecalloc (h
->next
, new_size
- old_size
, -1));
3885 /* Update the free list. Do it so that new entries are added at
3886 the end of the free list. This makes some operations like
3888 for (i
= old_size
; i
< new_size
- 1; ++i
)
3889 set_hash_next_slot (h
, i
, i
+ 1);
3890 set_hash_next_slot (h
, i
, -1);
3892 if (h
->next_free
< 0)
3893 h
->next_free
= old_size
;
3896 ptrdiff_t last
= h
->next_free
;
3899 ptrdiff_t next
= HASH_NEXT (h
, last
);
3904 set_hash_next_slot (h
, last
, old_size
);
3908 for (i
= 0; i
< old_size
; ++i
)
3909 if (!NILP (HASH_HASH (h
, i
)))
3911 EMACS_UINT hash_code
= XUINT (HASH_HASH (h
, i
));
3912 ptrdiff_t start_of_bucket
= hash_code
% ASIZE (h
->index
);
3913 set_hash_next_slot (h
, i
, HASH_INDEX (h
, start_of_bucket
));
3914 set_hash_index_slot (h
, start_of_bucket
, i
);
3920 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
3921 the hash code of KEY. Value is the index of the entry in H
3922 matching KEY, or -1 if not found. */
3925 hash_lookup (struct Lisp_Hash_Table
*h
, Lisp_Object key
, EMACS_UINT
*hash
)
3927 EMACS_UINT hash_code
;
3928 ptrdiff_t start_of_bucket
, i
;
3930 hash_code
= h
->test
.hashfn (&h
->test
, key
);
3931 eassert ((hash_code
& ~INTMASK
) == 0);
3935 start_of_bucket
= hash_code
% ASIZE (h
->index
);
3937 for (i
= HASH_INDEX (h
, start_of_bucket
); 0 <= i
; i
= HASH_NEXT (h
, i
))
3938 if (EQ (key
, HASH_KEY (h
, i
))
3940 && hash_code
== XUINT (HASH_HASH (h
, i
))
3941 && h
->test
.cmpfn (&h
->test
, key
, HASH_KEY (h
, i
))))
3948 /* Put an entry into hash table H that associates KEY with VALUE.
3949 HASH is a previously computed hash code of KEY.
3950 Value is the index of the entry in H matching KEY. */
3953 hash_put (struct Lisp_Hash_Table
*h
, Lisp_Object key
, Lisp_Object value
,
3956 ptrdiff_t start_of_bucket
, i
;
3958 eassert ((hash
& ~INTMASK
) == 0);
3960 /* Increment count after resizing because resizing may fail. */
3961 maybe_resize_hash_table (h
);
3964 /* Store key/value in the key_and_value vector. */
3966 h
->next_free
= HASH_NEXT (h
, i
);
3967 set_hash_key_slot (h
, i
, key
);
3968 set_hash_value_slot (h
, i
, value
);
3970 /* Remember its hash code. */
3971 set_hash_hash_slot (h
, i
, make_number (hash
));
3973 /* Add new entry to its collision chain. */
3974 start_of_bucket
= hash
% ASIZE (h
->index
);
3975 set_hash_next_slot (h
, i
, HASH_INDEX (h
, start_of_bucket
));
3976 set_hash_index_slot (h
, start_of_bucket
, i
);
3981 /* Remove the entry matching KEY from hash table H, if there is one. */
3984 hash_remove_from_table (struct Lisp_Hash_Table
*h
, Lisp_Object key
)
3986 EMACS_UINT hash_code
= h
->test
.hashfn (&h
->test
, key
);
3987 eassert ((hash_code
& ~INTMASK
) == 0);
3988 ptrdiff_t start_of_bucket
= hash_code
% ASIZE (h
->index
);
3989 ptrdiff_t prev
= -1;
3991 for (ptrdiff_t i
= HASH_INDEX (h
, start_of_bucket
);
3993 i
= HASH_NEXT (h
, i
))
3995 if (EQ (key
, HASH_KEY (h
, i
))
3997 && hash_code
== XUINT (HASH_HASH (h
, i
))
3998 && h
->test
.cmpfn (&h
->test
, key
, HASH_KEY (h
, i
))))
4000 /* Take entry out of collision chain. */
4002 set_hash_index_slot (h
, start_of_bucket
, HASH_NEXT (h
, i
));
4004 set_hash_next_slot (h
, prev
, HASH_NEXT (h
, i
));
4006 /* Clear slots in key_and_value and add the slots to
4008 set_hash_key_slot (h
, i
, Qnil
);
4009 set_hash_value_slot (h
, i
, Qnil
);
4010 set_hash_hash_slot (h
, i
, Qnil
);
4011 set_hash_next_slot (h
, i
, h
->next_free
);
4014 eassert (h
->count
>= 0);
4023 /* Clear hash table H. */
4026 hash_clear (struct Lisp_Hash_Table
*h
)
4030 ptrdiff_t i
, size
= HASH_TABLE_SIZE (h
);
4032 for (i
= 0; i
< size
; ++i
)
4034 set_hash_next_slot (h
, i
, i
< size
- 1 ? i
+ 1 : -1);
4035 set_hash_key_slot (h
, i
, Qnil
);
4036 set_hash_value_slot (h
, i
, Qnil
);
4037 set_hash_hash_slot (h
, i
, Qnil
);
4040 for (i
= 0; i
< ASIZE (h
->index
); ++i
)
4041 ASET (h
->index
, i
, make_number (-1));
4050 /************************************************************************
4052 ************************************************************************/
4054 /* Sweep weak hash table H. REMOVE_ENTRIES_P means remove
4055 entries from the table that don't survive the current GC.
4056 !REMOVE_ENTRIES_P means mark entries that are in use. Value is
4057 true if anything was marked. */
4060 sweep_weak_table (struct Lisp_Hash_Table
*h
, bool remove_entries_p
)
4062 ptrdiff_t n
= gc_asize (h
->index
);
4063 bool marked
= false;
4065 for (ptrdiff_t bucket
= 0; bucket
< n
; ++bucket
)
4067 /* Follow collision chain, removing entries that
4068 don't survive this garbage collection. */
4069 ptrdiff_t prev
= -1;
4071 for (ptrdiff_t i
= HASH_INDEX (h
, bucket
); 0 <= i
; i
= next
)
4073 bool key_known_to_survive_p
= survives_gc_p (HASH_KEY (h
, i
));
4074 bool value_known_to_survive_p
= survives_gc_p (HASH_VALUE (h
, i
));
4077 if (EQ (h
->weak
, Qkey
))
4078 remove_p
= !key_known_to_survive_p
;
4079 else if (EQ (h
->weak
, Qvalue
))
4080 remove_p
= !value_known_to_survive_p
;
4081 else if (EQ (h
->weak
, Qkey_or_value
))
4082 remove_p
= !(key_known_to_survive_p
|| value_known_to_survive_p
);
4083 else if (EQ (h
->weak
, Qkey_and_value
))
4084 remove_p
= !(key_known_to_survive_p
&& value_known_to_survive_p
);
4088 next
= HASH_NEXT (h
, i
);
4090 if (remove_entries_p
)
4094 /* Take out of collision chain. */
4096 set_hash_index_slot (h
, bucket
, next
);
4098 set_hash_next_slot (h
, prev
, next
);
4100 /* Add to free list. */
4101 set_hash_next_slot (h
, i
, h
->next_free
);
4104 /* Clear key, value, and hash. */
4105 set_hash_key_slot (h
, i
, Qnil
);
4106 set_hash_value_slot (h
, i
, Qnil
);
4107 set_hash_hash_slot (h
, i
, Qnil
);
4120 /* Make sure key and value survive. */
4121 if (!key_known_to_survive_p
)
4123 mark_object (HASH_KEY (h
, i
));
4127 if (!value_known_to_survive_p
)
4129 mark_object (HASH_VALUE (h
, i
));
4140 /* Remove elements from weak hash tables that don't survive the
4141 current garbage collection. Remove weak tables that don't survive
4142 from Vweak_hash_tables. Called from gc_sweep. */
4144 NO_INLINE
/* For better stack traces */
4146 sweep_weak_hash_tables (void)
4148 struct Lisp_Hash_Table
*h
, *used
, *next
;
4151 /* Mark all keys and values that are in use. Keep on marking until
4152 there is no more change. This is necessary for cases like
4153 value-weak table A containing an entry X -> Y, where Y is used in a
4154 key-weak table B, Z -> Y. If B comes after A in the list of weak
4155 tables, X -> Y might be removed from A, although when looking at B
4156 one finds that it shouldn't. */
4160 for (h
= weak_hash_tables
; h
; h
= h
->next_weak
)
4162 if (h
->header
.size
& ARRAY_MARK_FLAG
)
4163 marked
|= sweep_weak_table (h
, 0);
4168 /* Remove tables and entries that aren't used. */
4169 for (h
= weak_hash_tables
, used
= NULL
; h
; h
= next
)
4171 next
= h
->next_weak
;
4173 if (h
->header
.size
& ARRAY_MARK_FLAG
)
4175 /* TABLE is marked as used. Sweep its contents. */
4177 sweep_weak_table (h
, 1);
4179 /* Add table to the list of used weak hash tables. */
4180 h
->next_weak
= used
;
4185 weak_hash_tables
= used
;
4190 /***********************************************************************
4191 Hash Code Computation
4192 ***********************************************************************/
4194 /* Maximum depth up to which to dive into Lisp structures. */
4196 #define SXHASH_MAX_DEPTH 3
4198 /* Maximum length up to which to take list and vector elements into
4201 #define SXHASH_MAX_LEN 7
4203 /* Return a hash for string PTR which has length LEN. The hash value
4204 can be any EMACS_UINT value. */
4207 hash_string (char const *ptr
, ptrdiff_t len
)
4209 char const *p
= ptr
;
4210 char const *end
= p
+ len
;
4212 EMACS_UINT hash
= 0;
4217 hash
= sxhash_combine (hash
, c
);
4223 /* Return a hash for string PTR which has length LEN. The hash
4224 code returned is guaranteed to fit in a Lisp integer. */
4227 sxhash_string (char const *ptr
, ptrdiff_t len
)
4229 EMACS_UINT hash
= hash_string (ptr
, len
);
4230 return SXHASH_REDUCE (hash
);
4233 /* Return a hash for the floating point value VAL. */
4236 sxhash_float (double val
)
4238 EMACS_UINT hash
= 0;
4240 WORDS_PER_DOUBLE
= (sizeof val
/ sizeof hash
4241 + (sizeof val
% sizeof hash
!= 0))
4245 EMACS_UINT word
[WORDS_PER_DOUBLE
];
4249 memset (&u
.val
+ 1, 0, sizeof u
- sizeof u
.val
);
4250 for (i
= 0; i
< WORDS_PER_DOUBLE
; i
++)
4251 hash
= sxhash_combine (hash
, u
.word
[i
]);
4252 return SXHASH_REDUCE (hash
);
4255 /* Return a hash for list LIST. DEPTH is the current depth in the
4256 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4259 sxhash_list (Lisp_Object list
, int depth
)
4261 EMACS_UINT hash
= 0;
4264 if (depth
< SXHASH_MAX_DEPTH
)
4266 CONSP (list
) && i
< SXHASH_MAX_LEN
;
4267 list
= XCDR (list
), ++i
)
4269 EMACS_UINT hash2
= sxhash (XCAR (list
), depth
+ 1);
4270 hash
= sxhash_combine (hash
, hash2
);
4275 EMACS_UINT hash2
= sxhash (list
, depth
+ 1);
4276 hash
= sxhash_combine (hash
, hash2
);
4279 return SXHASH_REDUCE (hash
);
4283 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4284 the Lisp structure. */
4287 sxhash_vector (Lisp_Object vec
, int depth
)
4289 EMACS_UINT hash
= ASIZE (vec
);
4292 n
= min (SXHASH_MAX_LEN
, ASIZE (vec
));
4293 for (i
= 0; i
< n
; ++i
)
4295 EMACS_UINT hash2
= sxhash (AREF (vec
, i
), depth
+ 1);
4296 hash
= sxhash_combine (hash
, hash2
);
4299 return SXHASH_REDUCE (hash
);
4302 /* Return a hash for bool-vector VECTOR. */
4305 sxhash_bool_vector (Lisp_Object vec
)
4307 EMACS_INT size
= bool_vector_size (vec
);
4308 EMACS_UINT hash
= size
;
4311 n
= min (SXHASH_MAX_LEN
, bool_vector_words (size
));
4312 for (i
= 0; i
< n
; ++i
)
4313 hash
= sxhash_combine (hash
, bool_vector_data (vec
)[i
]);
4315 return SXHASH_REDUCE (hash
);
4319 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4320 structure. Value is an unsigned integer clipped to INTMASK. */
4323 sxhash (Lisp_Object obj
, int depth
)
4327 if (depth
> SXHASH_MAX_DEPTH
)
4330 switch (XTYPE (obj
))
4342 hash
= sxhash_string (SSDATA (obj
), SBYTES (obj
));
4345 /* This can be everything from a vector to an overlay. */
4346 case Lisp_Vectorlike
:
4348 /* According to the CL HyperSpec, two arrays are equal only if
4349 they are `eq', except for strings and bit-vectors. In
4350 Emacs, this works differently. We have to compare element
4352 hash
= sxhash_vector (obj
, depth
);
4353 else if (BOOL_VECTOR_P (obj
))
4354 hash
= sxhash_bool_vector (obj
);
4356 /* Others are `equal' if they are `eq', so let's take their
4362 hash
= sxhash_list (obj
, depth
);
4366 hash
= sxhash_float (XFLOAT_DATA (obj
));
4378 /***********************************************************************
4380 ***********************************************************************/
4382 DEFUN ("sxhash-eq", Fsxhash_eq
, Ssxhash_eq
, 1, 1, 0,
4383 doc
: /* Return an integer hash code for OBJ suitable for `eq'.
4384 If (eq A B), then (= (sxhash-eq A) (sxhash-eq B)). */)
4387 return make_number (hashfn_eq (NULL
, obj
));
4390 DEFUN ("sxhash-eql", Fsxhash_eql
, Ssxhash_eql
, 1, 1, 0,
4391 doc
: /* Return an integer hash code for OBJ suitable for `eql'.
4392 If (eql A B), then (= (sxhash-eql A) (sxhash-eql B)). */)
4395 return make_number (hashfn_eql (NULL
, obj
));
4398 DEFUN ("sxhash-equal", Fsxhash_equal
, Ssxhash_equal
, 1, 1, 0,
4399 doc
: /* Return an integer hash code for OBJ suitable for `equal'.
4400 If (equal A B), then (= (sxhash-equal A) (sxhash-equal B)). */)
4403 return make_number (hashfn_equal (NULL
, obj
));
4406 DEFUN ("make-hash-table", Fmake_hash_table
, Smake_hash_table
, 0, MANY
, 0,
4407 doc
: /* Create and return a new hash table.
4409 Arguments are specified as keyword/argument pairs. The following
4410 arguments are defined:
4412 :test TEST -- TEST must be a symbol that specifies how to compare
4413 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4414 `equal'. User-supplied test and hash functions can be specified via
4415 `define-hash-table-test'.
4417 :size SIZE -- A hint as to how many elements will be put in the table.
4420 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4421 fills up. If REHASH-SIZE is an integer, increase the size by that
4422 amount. If it is a float, it must be > 1.0, and the new size is the
4423 old size multiplied by that factor. Default is 1.5.
4425 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4426 Resize the hash table when the ratio (table entries / table size)
4427 exceeds an approximation to THRESHOLD. Default is 0.8125.
4429 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4430 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4431 returned is a weak table. Key/value pairs are removed from a weak
4432 hash table when there are no non-weak references pointing to their
4433 key, value, one of key or value, or both key and value, depending on
4434 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4437 :purecopy PURECOPY -- If PURECOPY is non-nil, the table can be copied
4438 to pure storage when Emacs is being dumped, making the contents of the
4439 table read only. Any further changes to purified tables will result
4442 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4443 (ptrdiff_t nargs
, Lisp_Object
*args
)
4445 Lisp_Object test
, weak
;
4447 struct hash_table_test testdesc
;
4451 /* The vector `used' is used to keep track of arguments that
4452 have been consumed. */
4453 char *used
= SAFE_ALLOCA (nargs
* sizeof *used
);
4454 memset (used
, 0, nargs
* sizeof *used
);
4456 /* See if there's a `:test TEST' among the arguments. */
4457 i
= get_key_arg (QCtest
, nargs
, args
, used
);
4458 test
= i
? args
[i
] : Qeql
;
4460 testdesc
= hashtest_eq
;
4461 else if (EQ (test
, Qeql
))
4462 testdesc
= hashtest_eql
;
4463 else if (EQ (test
, Qequal
))
4464 testdesc
= hashtest_equal
;
4467 /* See if it is a user-defined test. */
4470 prop
= Fget (test
, Qhash_table_test
);
4471 if (!CONSP (prop
) || !CONSP (XCDR (prop
)))
4472 signal_error ("Invalid hash table test", test
);
4473 testdesc
.name
= test
;
4474 testdesc
.user_cmp_function
= XCAR (prop
);
4475 testdesc
.user_hash_function
= XCAR (XCDR (prop
));
4476 testdesc
.hashfn
= hashfn_user_defined
;
4477 testdesc
.cmpfn
= cmpfn_user_defined
;
4480 /* See if there's a `:purecopy PURECOPY' argument. */
4481 i
= get_key_arg (QCpurecopy
, nargs
, args
, used
);
4482 pure
= i
&& !NILP (args
[i
]);
4483 /* See if there's a `:size SIZE' argument. */
4484 i
= get_key_arg (QCsize
, nargs
, args
, used
);
4485 Lisp_Object size_arg
= i
? args
[i
] : Qnil
;
4487 if (NILP (size_arg
))
4488 size
= DEFAULT_HASH_SIZE
;
4489 else if (NATNUMP (size_arg
))
4490 size
= XFASTINT (size_arg
);
4492 signal_error ("Invalid hash table size", size_arg
);
4494 /* Look for `:rehash-size SIZE'. */
4496 i
= get_key_arg (QCrehash_size
, nargs
, args
, used
);
4498 rehash_size
= DEFAULT_REHASH_SIZE
;
4499 else if (INTEGERP (args
[i
]) && 0 < XINT (args
[i
]))
4500 rehash_size
= - XINT (args
[i
]);
4501 else if (FLOATP (args
[i
]) && 0 < (float) (XFLOAT_DATA (args
[i
]) - 1))
4502 rehash_size
= (float) (XFLOAT_DATA (args
[i
]) - 1);
4504 signal_error ("Invalid hash table rehash size", args
[i
]);
4506 /* Look for `:rehash-threshold THRESHOLD'. */
4507 i
= get_key_arg (QCrehash_threshold
, nargs
, args
, used
);
4508 float rehash_threshold
= (!i
? DEFAULT_REHASH_THRESHOLD
4509 : !FLOATP (args
[i
]) ? 0
4510 : (float) XFLOAT_DATA (args
[i
]));
4511 if (! (0 < rehash_threshold
&& rehash_threshold
<= 1))
4512 signal_error ("Invalid hash table rehash threshold", args
[i
]);
4514 /* Look for `:weakness WEAK'. */
4515 i
= get_key_arg (QCweakness
, nargs
, args
, used
);
4516 weak
= i
? args
[i
] : Qnil
;
4518 weak
= Qkey_and_value
;
4521 && !EQ (weak
, Qvalue
)
4522 && !EQ (weak
, Qkey_or_value
)
4523 && !EQ (weak
, Qkey_and_value
))
4524 signal_error ("Invalid hash table weakness", weak
);
4526 /* Now, all args should have been used up, or there's a problem. */
4527 for (i
= 0; i
< nargs
; ++i
)
4529 signal_error ("Invalid argument list", args
[i
]);
4532 return make_hash_table (testdesc
, size
, rehash_size
, rehash_threshold
, weak
,
4537 DEFUN ("copy-hash-table", Fcopy_hash_table
, Scopy_hash_table
, 1, 1, 0,
4538 doc
: /* Return a copy of hash table TABLE. */)
4541 return copy_hash_table (check_hash_table (table
));
4545 DEFUN ("hash-table-count", Fhash_table_count
, Shash_table_count
, 1, 1, 0,
4546 doc
: /* Return the number of elements in TABLE. */)
4549 return make_number (check_hash_table (table
)->count
);
4553 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size
,
4554 Shash_table_rehash_size
, 1, 1, 0,
4555 doc
: /* Return the current rehash size of TABLE. */)
4558 double rehash_size
= check_hash_table (table
)->rehash_size
;
4559 if (rehash_size
< 0)
4561 EMACS_INT s
= -rehash_size
;
4562 return make_number (min (s
, MOST_POSITIVE_FIXNUM
));
4565 return make_float (rehash_size
+ 1);
4569 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold
,
4570 Shash_table_rehash_threshold
, 1, 1, 0,
4571 doc
: /* Return the current rehash threshold of TABLE. */)
4574 return make_float (check_hash_table (table
)->rehash_threshold
);
4578 DEFUN ("hash-table-size", Fhash_table_size
, Shash_table_size
, 1, 1, 0,
4579 doc
: /* Return the size of TABLE.
4580 The size can be used as an argument to `make-hash-table' to create
4581 a hash table than can hold as many elements as TABLE holds
4582 without need for resizing. */)
4585 struct Lisp_Hash_Table
*h
= check_hash_table (table
);
4586 return make_number (HASH_TABLE_SIZE (h
));
4590 DEFUN ("hash-table-test", Fhash_table_test
, Shash_table_test
, 1, 1, 0,
4591 doc
: /* Return the test TABLE uses. */)
4594 return check_hash_table (table
)->test
.name
;
4598 DEFUN ("hash-table-weakness", Fhash_table_weakness
, Shash_table_weakness
,
4600 doc
: /* Return the weakness of TABLE. */)
4603 return check_hash_table (table
)->weak
;
4607 DEFUN ("hash-table-p", Fhash_table_p
, Shash_table_p
, 1, 1, 0,
4608 doc
: /* Return t if OBJ is a Lisp hash table object. */)
4611 return HASH_TABLE_P (obj
) ? Qt
: Qnil
;
4615 DEFUN ("clrhash", Fclrhash
, Sclrhash
, 1, 1, 0,
4616 doc
: /* Clear hash table TABLE and return it. */)
4619 struct Lisp_Hash_Table
*h
= check_hash_table (table
);
4620 CHECK_IMPURE (table
, h
);
4622 /* Be compatible with XEmacs. */
4627 DEFUN ("gethash", Fgethash
, Sgethash
, 2, 3, 0,
4628 doc
: /* Look up KEY in TABLE and return its associated value.
4629 If KEY is not found, return DFLT which defaults to nil. */)
4630 (Lisp_Object key
, Lisp_Object table
, Lisp_Object dflt
)
4632 struct Lisp_Hash_Table
*h
= check_hash_table (table
);
4633 ptrdiff_t i
= hash_lookup (h
, key
, NULL
);
4634 return i
>= 0 ? HASH_VALUE (h
, i
) : dflt
;
4638 DEFUN ("puthash", Fputhash
, Sputhash
, 3, 3, 0,
4639 doc
: /* Associate KEY with VALUE in hash table TABLE.
4640 If KEY is already present in table, replace its current value with
4641 VALUE. In any case, return VALUE. */)
4642 (Lisp_Object key
, Lisp_Object value
, Lisp_Object table
)
4644 struct Lisp_Hash_Table
*h
= check_hash_table (table
);
4645 CHECK_IMPURE (table
, h
);
4649 i
= hash_lookup (h
, key
, &hash
);
4651 set_hash_value_slot (h
, i
, value
);
4653 hash_put (h
, key
, value
, hash
);
4659 DEFUN ("remhash", Fremhash
, Sremhash
, 2, 2, 0,
4660 doc
: /* Remove KEY from TABLE. */)
4661 (Lisp_Object key
, Lisp_Object table
)
4663 struct Lisp_Hash_Table
*h
= check_hash_table (table
);
4664 CHECK_IMPURE (table
, h
);
4665 hash_remove_from_table (h
, key
);
4670 DEFUN ("maphash", Fmaphash
, Smaphash
, 2, 2, 0,
4671 doc
: /* Call FUNCTION for all entries in hash table TABLE.
4672 FUNCTION is called with two arguments, KEY and VALUE.
4673 `maphash' always returns nil. */)
4674 (Lisp_Object function
, Lisp_Object table
)
4676 struct Lisp_Hash_Table
*h
= check_hash_table (table
);
4678 for (ptrdiff_t i
= 0; i
< HASH_TABLE_SIZE (h
); ++i
)
4679 if (!NILP (HASH_HASH (h
, i
)))
4680 call2 (function
, HASH_KEY (h
, i
), HASH_VALUE (h
, i
));
4686 DEFUN ("define-hash-table-test", Fdefine_hash_table_test
,
4687 Sdefine_hash_table_test
, 3, 3, 0,
4688 doc
: /* Define a new hash table test with name NAME, a symbol.
4690 In hash tables created with NAME specified as test, use TEST to
4691 compare keys, and HASH for computing hash codes of keys.
4693 TEST must be a function taking two arguments and returning non-nil if
4694 both arguments are the same. HASH must be a function taking one
4695 argument and returning an object that is the hash code of the argument.
4696 It should be the case that if (eq (funcall HASH x1) (funcall HASH x2))
4697 returns nil, then (funcall TEST x1 x2) also returns nil. */)
4698 (Lisp_Object name
, Lisp_Object test
, Lisp_Object hash
)
4700 return Fput (name
, Qhash_table_test
, list2 (test
, hash
));
4705 /************************************************************************
4706 MD5, SHA-1, and SHA-2
4707 ************************************************************************/
4715 make_digest_string (Lisp_Object digest
, int digest_size
)
4717 unsigned char *p
= SDATA (digest
);
4719 for (int i
= digest_size
- 1; i
>= 0; i
--)
4721 static char const hexdigit
[16] = "0123456789abcdef";
4723 p
[2 * i
] = hexdigit
[p_i
>> 4];
4724 p
[2 * i
+ 1] = hexdigit
[p_i
& 0xf];
4729 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4732 secure_hash (Lisp_Object algorithm
, Lisp_Object object
, Lisp_Object start
,
4733 Lisp_Object end
, Lisp_Object coding_system
, Lisp_Object noerror
,
4736 ptrdiff_t size
, start_char
= 0, start_byte
, end_char
= 0, end_byte
;
4737 register EMACS_INT b
, e
;
4738 register struct buffer
*bp
;
4741 void *(*hash_func
) (const char *, size_t, void *);
4744 CHECK_SYMBOL (algorithm
);
4746 if (STRINGP (object
))
4748 if (NILP (coding_system
))
4750 /* Decide the coding-system to encode the data with. */
4752 if (STRING_MULTIBYTE (object
))
4753 /* use default, we can't guess correct value */
4754 coding_system
= preferred_coding_system ();
4756 coding_system
= Qraw_text
;
4759 if (NILP (Fcoding_system_p (coding_system
)))
4761 /* Invalid coding system. */
4763 if (!NILP (noerror
))
4764 coding_system
= Qraw_text
;
4766 xsignal1 (Qcoding_system_error
, coding_system
);
4769 if (STRING_MULTIBYTE (object
))
4770 object
= code_convert_string (object
, coding_system
, Qnil
, 1, 0, 1);
4772 size
= SCHARS (object
);
4773 validate_subarray (object
, start
, end
, size
, &start_char
, &end_char
);
4775 start_byte
= !start_char
? 0 : string_char_to_byte (object
, start_char
);
4776 end_byte
= (end_char
== size
4778 : string_char_to_byte (object
, end_char
));
4782 struct buffer
*prev
= current_buffer
;
4784 record_unwind_current_buffer ();
4786 CHECK_BUFFER (object
);
4788 bp
= XBUFFER (object
);
4789 set_buffer_internal (bp
);
4795 CHECK_NUMBER_COERCE_MARKER (start
);
4803 CHECK_NUMBER_COERCE_MARKER (end
);
4808 temp
= b
, b
= e
, e
= temp
;
4810 if (!(BEGV
<= b
&& e
<= ZV
))
4811 args_out_of_range (start
, end
);
4813 if (NILP (coding_system
))
4815 /* Decide the coding-system to encode the data with.
4816 See fileio.c:Fwrite-region */
4818 if (!NILP (Vcoding_system_for_write
))
4819 coding_system
= Vcoding_system_for_write
;
4822 bool force_raw_text
= 0;
4824 coding_system
= BVAR (XBUFFER (object
), buffer_file_coding_system
);
4825 if (NILP (coding_system
)
4826 || NILP (Flocal_variable_p (Qbuffer_file_coding_system
, Qnil
)))
4828 coding_system
= Qnil
;
4829 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
4833 if (NILP (coding_system
) && !NILP (Fbuffer_file_name (object
)))
4835 /* Check file-coding-system-alist. */
4836 Lisp_Object val
= CALLN (Ffind_operation_coding_system
,
4837 Qwrite_region
, start
, end
,
4838 Fbuffer_file_name (object
));
4839 if (CONSP (val
) && !NILP (XCDR (val
)))
4840 coding_system
= XCDR (val
);
4843 if (NILP (coding_system
)
4844 && !NILP (BVAR (XBUFFER (object
), buffer_file_coding_system
)))
4846 /* If we still have not decided a coding system, use the
4847 default value of buffer-file-coding-system. */
4848 coding_system
= BVAR (XBUFFER (object
), buffer_file_coding_system
);
4852 && !NILP (Ffboundp (Vselect_safe_coding_system_function
)))
4853 /* Confirm that VAL can surely encode the current region. */
4854 coding_system
= call4 (Vselect_safe_coding_system_function
,
4855 make_number (b
), make_number (e
),
4856 coding_system
, Qnil
);
4859 coding_system
= Qraw_text
;
4862 if (NILP (Fcoding_system_p (coding_system
)))
4864 /* Invalid coding system. */
4866 if (!NILP (noerror
))
4867 coding_system
= Qraw_text
;
4869 xsignal1 (Qcoding_system_error
, coding_system
);
4873 object
= make_buffer_string (b
, e
, 0);
4874 set_buffer_internal (prev
);
4875 /* Discard the unwind protect for recovering the current
4879 if (STRING_MULTIBYTE (object
))
4880 object
= code_convert_string (object
, coding_system
, Qnil
, 1, 0, 0);
4882 end_byte
= SBYTES (object
);
4885 if (EQ (algorithm
, Qmd5
))
4887 digest_size
= MD5_DIGEST_SIZE
;
4888 hash_func
= md5_buffer
;
4890 else if (EQ (algorithm
, Qsha1
))
4892 digest_size
= SHA1_DIGEST_SIZE
;
4893 hash_func
= sha1_buffer
;
4895 else if (EQ (algorithm
, Qsha224
))
4897 digest_size
= SHA224_DIGEST_SIZE
;
4898 hash_func
= sha224_buffer
;
4900 else if (EQ (algorithm
, Qsha256
))
4902 digest_size
= SHA256_DIGEST_SIZE
;
4903 hash_func
= sha256_buffer
;
4905 else if (EQ (algorithm
, Qsha384
))
4907 digest_size
= SHA384_DIGEST_SIZE
;
4908 hash_func
= sha384_buffer
;
4910 else if (EQ (algorithm
, Qsha512
))
4912 digest_size
= SHA512_DIGEST_SIZE
;
4913 hash_func
= sha512_buffer
;
4916 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm
)));
4918 /* allocate 2 x digest_size so that it can be re-used to hold the
4920 digest
= make_uninit_string (digest_size
* 2);
4922 hash_func (SSDATA (object
) + start_byte
,
4923 end_byte
- start_byte
,
4927 return make_digest_string (digest
, digest_size
);
4929 return make_unibyte_string (SSDATA (digest
), digest_size
);
4932 DEFUN ("md5", Fmd5
, Smd5
, 1, 5, 0,
4933 doc
: /* Return MD5 message digest of OBJECT, a buffer or string.
4935 A message digest is a cryptographic checksum of a document, and the
4936 algorithm to calculate it is defined in RFC 1321.
4938 The two optional arguments START and END are character positions
4939 specifying for which part of OBJECT the message digest should be
4940 computed. If nil or omitted, the digest is computed for the whole
4943 The MD5 message digest is computed from the result of encoding the
4944 text in a coding system, not directly from the internal Emacs form of
4945 the text. The optional fourth argument CODING-SYSTEM specifies which
4946 coding system to encode the text with. It should be the same coding
4947 system that you used or will use when actually writing the text into a
4950 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
4951 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
4952 system would be chosen by default for writing this text into a file.
4954 If OBJECT is a string, the most preferred coding system (see the
4955 command `prefer-coding-system') is used.
4957 If NOERROR is non-nil, silently assume the `raw-text' coding if the
4958 guesswork fails. Normally, an error is signaled in such case. */)
4959 (Lisp_Object object
, Lisp_Object start
, Lisp_Object end
, Lisp_Object coding_system
, Lisp_Object noerror
)
4961 return secure_hash (Qmd5
, object
, start
, end
, coding_system
, noerror
, Qnil
);
4964 DEFUN ("secure-hash", Fsecure_hash
, Ssecure_hash
, 2, 5, 0,
4965 doc
: /* Return the secure hash of OBJECT, a buffer or string.
4966 ALGORITHM is a symbol specifying the hash to use:
4967 md5, sha1, sha224, sha256, sha384 or sha512.
4969 The two optional arguments START and END are positions specifying for
4970 which part of OBJECT to compute the hash. If nil or omitted, uses the
4973 If BINARY is non-nil, returns a string in binary form. */)
4974 (Lisp_Object algorithm
, Lisp_Object object
, Lisp_Object start
, Lisp_Object end
, Lisp_Object binary
)
4976 return secure_hash (algorithm
, object
, start
, end
, Qnil
, Qnil
, binary
);
4979 DEFUN ("buffer-hash", Fbuffer_hash
, Sbuffer_hash
, 0, 1, 0,
4980 doc
: /* Return a hash of the contents of BUFFER-OR-NAME.
4981 This hash is performed on the raw internal format of the buffer,
4982 disregarding any coding systems. If nil, use the current buffer. */ )
4983 (Lisp_Object buffer_or_name
)
4987 struct sha1_ctx ctx
;
4989 if (NILP (buffer_or_name
))
4990 buffer
= Fcurrent_buffer ();
4992 buffer
= Fget_buffer (buffer_or_name
);
4994 nsberror (buffer_or_name
);
4996 b
= XBUFFER (buffer
);
4997 sha1_init_ctx (&ctx
);
4999 /* Process the first part of the buffer. */
5000 sha1_process_bytes (BUF_BEG_ADDR (b
),
5001 BUF_GPT_BYTE (b
) - BUF_BEG_BYTE (b
),
5004 /* If the gap is before the end of the buffer, process the last half
5006 if (BUF_GPT_BYTE (b
) < BUF_Z_BYTE (b
))
5007 sha1_process_bytes (BUF_GAP_END_ADDR (b
),
5008 BUF_Z_ADDR (b
) - BUF_GAP_END_ADDR (b
),
5011 Lisp_Object digest
= make_uninit_string (SHA1_DIGEST_SIZE
* 2);
5012 sha1_finish_ctx (&ctx
, SSDATA (digest
));
5013 return make_digest_string (digest
, SHA1_DIGEST_SIZE
);
5020 DEFSYM (Qmd5
, "md5");
5021 DEFSYM (Qsha1
, "sha1");
5022 DEFSYM (Qsha224
, "sha224");
5023 DEFSYM (Qsha256
, "sha256");
5024 DEFSYM (Qsha384
, "sha384");
5025 DEFSYM (Qsha512
, "sha512");
5027 /* Hash table stuff. */
5028 DEFSYM (Qhash_table_p
, "hash-table-p");
5030 DEFSYM (Qeql
, "eql");
5031 DEFSYM (Qequal
, "equal");
5032 DEFSYM (QCtest
, ":test");
5033 DEFSYM (QCsize
, ":size");
5034 DEFSYM (QCpurecopy
, ":purecopy");
5035 DEFSYM (QCrehash_size
, ":rehash-size");
5036 DEFSYM (QCrehash_threshold
, ":rehash-threshold");
5037 DEFSYM (QCweakness
, ":weakness");
5038 DEFSYM (Qkey
, "key");
5039 DEFSYM (Qvalue
, "value");
5040 DEFSYM (Qhash_table_test
, "hash-table-test");
5041 DEFSYM (Qkey_or_value
, "key-or-value");
5042 DEFSYM (Qkey_and_value
, "key-and-value");
5044 defsubr (&Ssxhash_eq
);
5045 defsubr (&Ssxhash_eql
);
5046 defsubr (&Ssxhash_equal
);
5047 defsubr (&Smake_hash_table
);
5048 defsubr (&Scopy_hash_table
);
5049 defsubr (&Shash_table_count
);
5050 defsubr (&Shash_table_rehash_size
);
5051 defsubr (&Shash_table_rehash_threshold
);
5052 defsubr (&Shash_table_size
);
5053 defsubr (&Shash_table_test
);
5054 defsubr (&Shash_table_weakness
);
5055 defsubr (&Shash_table_p
);
5056 defsubr (&Sclrhash
);
5057 defsubr (&Sgethash
);
5058 defsubr (&Sputhash
);
5059 defsubr (&Sremhash
);
5060 defsubr (&Smaphash
);
5061 defsubr (&Sdefine_hash_table_test
);
5063 DEFSYM (Qstring_lessp
, "string-lessp");
5064 DEFSYM (Qprovide
, "provide");
5065 DEFSYM (Qrequire
, "require");
5066 DEFSYM (Qyes_or_no_p_history
, "yes-or-no-p-history");
5067 DEFSYM (Qcursor_in_echo_area
, "cursor-in-echo-area");
5068 DEFSYM (Qwidget_type
, "widget-type");
5070 staticpro (&string_char_byte_cache_string
);
5071 string_char_byte_cache_string
= Qnil
;
5073 require_nesting_list
= Qnil
;
5074 staticpro (&require_nesting_list
);
5076 Fset (Qyes_or_no_p_history
, Qnil
);
5078 DEFVAR_LISP ("features", Vfeatures
,
5079 doc
: /* A list of symbols which are the features of the executing Emacs.
5080 Used by `featurep' and `require', and altered by `provide'. */);
5081 Vfeatures
= list1 (Qemacs
);
5082 DEFSYM (Qfeatures
, "features");
5083 /* Let people use lexically scoped vars named `features'. */
5084 Fmake_var_non_special (Qfeatures
);
5085 DEFSYM (Qsubfeatures
, "subfeatures");
5086 DEFSYM (Qfuncall
, "funcall");
5088 #ifdef HAVE_LANGINFO_CODESET
5089 DEFSYM (Qcodeset
, "codeset");
5090 DEFSYM (Qdays
, "days");
5091 DEFSYM (Qmonths
, "months");
5092 DEFSYM (Qpaper
, "paper");
5093 #endif /* HAVE_LANGINFO_CODESET */
5095 DEFVAR_BOOL ("use-dialog-box", use_dialog_box
,
5096 doc
: /* Non-nil means mouse commands use dialog boxes to ask questions.
5097 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
5098 invoked by mouse clicks and mouse menu items.
5100 On some platforms, file selection dialogs are also enabled if this is
5104 DEFVAR_BOOL ("use-file-dialog", use_file_dialog
,
5105 doc
: /* Non-nil means mouse commands use a file dialog to ask for files.
5106 This applies to commands from menus and tool bar buttons even when
5107 they are initiated from the keyboard. If `use-dialog-box' is nil,
5108 that disables the use of a file dialog, regardless of the value of
5110 use_file_dialog
= 1;
5112 defsubr (&Sidentity
);
5115 defsubr (&Ssafe_length
);
5116 defsubr (&Sstring_bytes
);
5117 defsubr (&Sstring_equal
);
5118 defsubr (&Scompare_strings
);
5119 defsubr (&Sstring_lessp
);
5120 defsubr (&Sstring_version_lessp
);
5121 defsubr (&Sstring_collate_lessp
);
5122 defsubr (&Sstring_collate_equalp
);
5125 defsubr (&Svconcat
);
5126 defsubr (&Scopy_sequence
);
5127 defsubr (&Sstring_make_multibyte
);
5128 defsubr (&Sstring_make_unibyte
);
5129 defsubr (&Sstring_as_multibyte
);
5130 defsubr (&Sstring_as_unibyte
);
5131 defsubr (&Sstring_to_multibyte
);
5132 defsubr (&Sstring_to_unibyte
);
5133 defsubr (&Scopy_alist
);
5134 defsubr (&Ssubstring
);
5135 defsubr (&Ssubstring_no_properties
);
5148 defsubr (&Snreverse
);
5149 defsubr (&Sreverse
);
5151 defsubr (&Splist_get
);
5153 defsubr (&Splist_put
);
5155 defsubr (&Slax_plist_get
);
5156 defsubr (&Slax_plist_put
);
5159 defsubr (&Sequal_including_properties
);
5160 defsubr (&Sfillarray
);
5161 defsubr (&Sclear_string
);
5166 defsubr (&Smapconcat
);
5167 defsubr (&Syes_or_no_p
);
5168 defsubr (&Sload_average
);
5169 defsubr (&Sfeaturep
);
5170 defsubr (&Srequire
);
5171 defsubr (&Sprovide
);
5172 defsubr (&Splist_member
);
5173 defsubr (&Swidget_put
);
5174 defsubr (&Swidget_get
);
5175 defsubr (&Swidget_apply
);
5176 defsubr (&Sbase64_encode_region
);
5177 defsubr (&Sbase64_decode_region
);
5178 defsubr (&Sbase64_encode_string
);
5179 defsubr (&Sbase64_decode_string
);
5181 defsubr (&Ssecure_hash
);
5182 defsubr (&Sbuffer_hash
);
5183 defsubr (&Slocale_info
);