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