]> code.delx.au - gnu-emacs/blob - src/editfns.c
Prefer stpcpy to strcat
[gnu-emacs] / src / editfns.c
1 /* Lisp functions pertaining to editing.
2
3 Copyright (C) 1985-1987, 1989, 1993-2014 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
19
20
21 #include <config.h>
22 #include <sys/types.h>
23 #include <stdio.h>
24
25 #ifdef HAVE_PWD_H
26 #include <pwd.h>
27 #include <grp.h>
28 #endif
29
30 #include <unistd.h>
31
32 #ifdef HAVE_SYS_UTSNAME_H
33 #include <sys/utsname.h>
34 #endif
35
36 #include "lisp.h"
37
38 /* systime.h includes <sys/time.h> which, on some systems, is required
39 for <sys/resource.h>; thus systime.h must be included before
40 <sys/resource.h> */
41 #include "systime.h"
42
43 #if defined HAVE_SYS_RESOURCE_H
44 #include <sys/resource.h>
45 #endif
46
47 #include <float.h>
48 #include <limits.h>
49 #include <intprops.h>
50 #include <strftime.h>
51 #include <verify.h>
52
53 #include "intervals.h"
54 #include "character.h"
55 #include "buffer.h"
56 #include "coding.h"
57 #include "frame.h"
58 #include "window.h"
59 #include "blockinput.h"
60
61 #define TM_YEAR_BASE 1900
62
63 #ifdef WINDOWSNT
64 extern Lisp_Object w32_get_internal_run_time (void);
65 #endif
66
67 static struct lisp_time lisp_time_struct (Lisp_Object, int *);
68 static void set_time_zone_rule (char const *);
69 static Lisp_Object format_time_string (char const *, ptrdiff_t, struct timespec,
70 bool, struct tm *);
71 static long int tm_gmtoff (struct tm *);
72 static int tm_diff (struct tm *, struct tm *);
73 static void update_buffer_properties (ptrdiff_t, ptrdiff_t);
74
75 #ifndef HAVE_TM_GMTOFF
76 # define HAVE_TM_GMTOFF false
77 #endif
78
79 static Lisp_Object Qbuffer_access_fontify_functions;
80
81 /* Symbol for the text property used to mark fields. */
82
83 Lisp_Object Qfield;
84
85 /* A special value for Qfield properties. */
86
87 static Lisp_Object Qboundary;
88
89 /* The startup value of the TZ environment variable; null if unset. */
90 static char const *initial_tz;
91
92 /* A valid but unlikely setting for the TZ environment variable.
93 It is OK (though a bit slower) if the user chooses this value. */
94 static char dump_tz_string[] = "TZ=UtC0";
95
96 void
97 init_editfns (void)
98 {
99 const char *user_name;
100 register char *p;
101 struct passwd *pw; /* password entry for the current user */
102 Lisp_Object tem;
103
104 /* Set up system_name even when dumping. */
105 init_system_name ();
106
107 #ifndef CANNOT_DUMP
108 /* When just dumping out, set the time zone to a known unlikely value
109 and skip the rest of this function. */
110 if (!initialized)
111 {
112 # ifdef HAVE_TZSET
113 xputenv (dump_tz_string);
114 tzset ();
115 # endif
116 return;
117 }
118 #endif
119
120 char *tz = getenv ("TZ");
121 initial_tz = tz;
122
123 #if !defined CANNOT_DUMP && defined HAVE_TZSET
124 /* If the execution TZ happens to be the same as the dump TZ,
125 change it to some other value and then change it back,
126 to force the underlying implementation to reload the TZ info.
127 This is needed on implementations that load TZ info from files,
128 since the TZ file contents may differ between dump and execution. */
129 if (tz && strcmp (tz, &dump_tz_string[sizeof "TZ=" - 1]) == 0)
130 {
131 ++*tz;
132 tzset ();
133 --*tz;
134 }
135 #endif
136
137 /* Call set_time_zone_rule now, so that its call to putenv is done
138 before multiple threads are active. */
139 set_time_zone_rule (tz);
140
141 pw = getpwuid (getuid ());
142 #ifdef MSDOS
143 /* We let the real user name default to "root" because that's quite
144 accurate on MS-DOS and because it lets Emacs find the init file.
145 (The DVX libraries override the Djgpp libraries here.) */
146 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
147 #else
148 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
149 #endif
150
151 /* Get the effective user name, by consulting environment variables,
152 or the effective uid if those are unset. */
153 user_name = getenv ("LOGNAME");
154 if (!user_name)
155 #ifdef WINDOWSNT
156 user_name = getenv ("USERNAME"); /* it's USERNAME on NT */
157 #else /* WINDOWSNT */
158 user_name = getenv ("USER");
159 #endif /* WINDOWSNT */
160 if (!user_name)
161 {
162 pw = getpwuid (geteuid ());
163 user_name = pw ? pw->pw_name : "unknown";
164 }
165 Vuser_login_name = build_string (user_name);
166
167 /* If the user name claimed in the environment vars differs from
168 the real uid, use the claimed name to find the full name. */
169 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
170 if (! NILP (tem))
171 tem = Vuser_login_name;
172 else
173 {
174 uid_t euid = geteuid ();
175 tem = make_fixnum_or_float (euid);
176 }
177 Vuser_full_name = Fuser_full_name (tem);
178
179 p = getenv ("NAME");
180 if (p)
181 Vuser_full_name = build_string (p);
182 else if (NILP (Vuser_full_name))
183 Vuser_full_name = build_string ("unknown");
184
185 #ifdef HAVE_SYS_UTSNAME_H
186 {
187 struct utsname uts;
188 uname (&uts);
189 Voperating_system_release = build_string (uts.release);
190 }
191 #else
192 Voperating_system_release = Qnil;
193 #endif
194 }
195 \f
196 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
197 doc: /* Convert arg CHAR to a string containing that character.
198 usage: (char-to-string CHAR) */)
199 (Lisp_Object character)
200 {
201 int c, len;
202 unsigned char str[MAX_MULTIBYTE_LENGTH];
203
204 CHECK_CHARACTER (character);
205 c = XFASTINT (character);
206
207 len = CHAR_STRING (c, str);
208 return make_string_from_bytes ((char *) str, 1, len);
209 }
210
211 DEFUN ("byte-to-string", Fbyte_to_string, Sbyte_to_string, 1, 1, 0,
212 doc: /* Convert arg BYTE to a unibyte string containing that byte. */)
213 (Lisp_Object byte)
214 {
215 unsigned char b;
216 CHECK_NUMBER (byte);
217 if (XINT (byte) < 0 || XINT (byte) > 255)
218 error ("Invalid byte");
219 b = XINT (byte);
220 return make_string_from_bytes ((char *) &b, 1, 1);
221 }
222
223 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
224 doc: /* Return the first character in STRING. */)
225 (register Lisp_Object string)
226 {
227 register Lisp_Object val;
228 CHECK_STRING (string);
229 if (SCHARS (string))
230 {
231 if (STRING_MULTIBYTE (string))
232 XSETFASTINT (val, STRING_CHAR (SDATA (string)));
233 else
234 XSETFASTINT (val, SREF (string, 0));
235 }
236 else
237 XSETFASTINT (val, 0);
238 return val;
239 }
240
241 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
242 doc: /* Return value of point, as an integer.
243 Beginning of buffer is position (point-min). */)
244 (void)
245 {
246 Lisp_Object temp;
247 XSETFASTINT (temp, PT);
248 return temp;
249 }
250
251 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
252 doc: /* Return value of point, as a marker object. */)
253 (void)
254 {
255 return build_marker (current_buffer, PT, PT_BYTE);
256 }
257
258 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
259 doc: /* Set point to POSITION, a number or marker.
260 Beginning of buffer is position (point-min), end is (point-max).
261
262 The return value is POSITION. */)
263 (register Lisp_Object position)
264 {
265 if (MARKERP (position))
266 set_point_from_marker (position);
267 else if (INTEGERP (position))
268 SET_PT (clip_to_bounds (BEGV, XINT (position), ZV));
269 else
270 wrong_type_argument (Qinteger_or_marker_p, position);
271 return position;
272 }
273
274
275 /* Return the start or end position of the region.
276 BEGINNINGP means return the start.
277 If there is no region active, signal an error. */
278
279 static Lisp_Object
280 region_limit (bool beginningp)
281 {
282 Lisp_Object m;
283
284 if (!NILP (Vtransient_mark_mode)
285 && NILP (Vmark_even_if_inactive)
286 && NILP (BVAR (current_buffer, mark_active)))
287 xsignal0 (Qmark_inactive);
288
289 m = Fmarker_position (BVAR (current_buffer, mark));
290 if (NILP (m))
291 error ("The mark is not set now, so there is no region");
292
293 /* Clip to the current narrowing (bug#11770). */
294 return make_number ((PT < XFASTINT (m)) == beginningp
295 ? PT
296 : clip_to_bounds (BEGV, XFASTINT (m), ZV));
297 }
298
299 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
300 doc: /* Return the integer value of point or mark, whichever is smaller. */)
301 (void)
302 {
303 return region_limit (1);
304 }
305
306 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
307 doc: /* Return the integer value of point or mark, whichever is larger. */)
308 (void)
309 {
310 return region_limit (0);
311 }
312
313 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
314 doc: /* Return this buffer's mark, as a marker object.
315 Watch out! Moving this marker changes the mark position.
316 If you set the marker not to point anywhere, the buffer will have no mark. */)
317 (void)
318 {
319 return BVAR (current_buffer, mark);
320 }
321
322 \f
323 /* Find all the overlays in the current buffer that touch position POS.
324 Return the number found, and store them in a vector in VEC
325 of length LEN. */
326
327 static ptrdiff_t
328 overlays_around (EMACS_INT pos, Lisp_Object *vec, ptrdiff_t len)
329 {
330 Lisp_Object overlay, start, end;
331 struct Lisp_Overlay *tail;
332 ptrdiff_t startpos, endpos;
333 ptrdiff_t idx = 0;
334
335 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
336 {
337 XSETMISC (overlay, tail);
338
339 end = OVERLAY_END (overlay);
340 endpos = OVERLAY_POSITION (end);
341 if (endpos < pos)
342 break;
343 start = OVERLAY_START (overlay);
344 startpos = OVERLAY_POSITION (start);
345 if (startpos <= pos)
346 {
347 if (idx < len)
348 vec[idx] = overlay;
349 /* Keep counting overlays even if we can't return them all. */
350 idx++;
351 }
352 }
353
354 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
355 {
356 XSETMISC (overlay, tail);
357
358 start = OVERLAY_START (overlay);
359 startpos = OVERLAY_POSITION (start);
360 if (pos < startpos)
361 break;
362 end = OVERLAY_END (overlay);
363 endpos = OVERLAY_POSITION (end);
364 if (pos <= endpos)
365 {
366 if (idx < len)
367 vec[idx] = overlay;
368 idx++;
369 }
370 }
371
372 return idx;
373 }
374
375 DEFUN ("get-pos-property", Fget_pos_property, Sget_pos_property, 2, 3, 0,
376 doc: /* Return the value of POSITION's property PROP, in OBJECT.
377 Almost identical to `get-char-property' except for the following difference:
378 Whereas `get-char-property' returns the property of the char at (i.e. right
379 after) POSITION, this pays attention to properties's stickiness and overlays's
380 advancement settings, in order to find the property of POSITION itself,
381 i.e. the property that a char would inherit if it were inserted
382 at POSITION. */)
383 (Lisp_Object position, register Lisp_Object prop, Lisp_Object object)
384 {
385 CHECK_NUMBER_COERCE_MARKER (position);
386
387 if (NILP (object))
388 XSETBUFFER (object, current_buffer);
389 else if (WINDOWP (object))
390 object = XWINDOW (object)->contents;
391
392 if (!BUFFERP (object))
393 /* pos-property only makes sense in buffers right now, since strings
394 have no overlays and no notion of insertion for which stickiness
395 could be obeyed. */
396 return Fget_text_property (position, prop, object);
397 else
398 {
399 EMACS_INT posn = XINT (position);
400 ptrdiff_t noverlays;
401 Lisp_Object *overlay_vec, tem;
402 struct buffer *obuf = current_buffer;
403 USE_SAFE_ALLOCA;
404
405 set_buffer_temp (XBUFFER (object));
406
407 /* First try with room for 40 overlays. */
408 Lisp_Object overlay_vecbuf[40];
409 noverlays = ARRAYELTS (overlay_vecbuf);
410 overlay_vec = overlay_vecbuf;
411 noverlays = overlays_around (posn, overlay_vec, noverlays);
412
413 /* If there are more than 40,
414 make enough space for all, and try again. */
415 if (ARRAYELTS (overlay_vecbuf) < noverlays)
416 {
417 SAFE_ALLOCA_LISP (overlay_vec, noverlays);
418 noverlays = overlays_around (posn, overlay_vec, noverlays);
419 }
420 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
421
422 set_buffer_temp (obuf);
423
424 /* Now check the overlays in order of decreasing priority. */
425 while (--noverlays >= 0)
426 {
427 Lisp_Object ol = overlay_vec[noverlays];
428 tem = Foverlay_get (ol, prop);
429 if (!NILP (tem))
430 {
431 /* Check the overlay is indeed active at point. */
432 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
433 if ((OVERLAY_POSITION (start) == posn
434 && XMARKER (start)->insertion_type == 1)
435 || (OVERLAY_POSITION (finish) == posn
436 && XMARKER (finish)->insertion_type == 0))
437 ; /* The overlay will not cover a char inserted at point. */
438 else
439 {
440 SAFE_FREE ();
441 return tem;
442 }
443 }
444 }
445 SAFE_FREE ();
446
447 { /* Now check the text properties. */
448 int stickiness = text_property_stickiness (prop, position, object);
449 if (stickiness > 0)
450 return Fget_text_property (position, prop, object);
451 else if (stickiness < 0
452 && XINT (position) > BUF_BEGV (XBUFFER (object)))
453 return Fget_text_property (make_number (XINT (position) - 1),
454 prop, object);
455 else
456 return Qnil;
457 }
458 }
459 }
460
461 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
462 the value of point is used instead. If BEG or END is null,
463 means don't store the beginning or end of the field.
464
465 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
466 results; they do not effect boundary behavior.
467
468 If MERGE_AT_BOUNDARY is non-nil, then if POS is at the very first
469 position of a field, then the beginning of the previous field is
470 returned instead of the beginning of POS's field (since the end of a
471 field is actually also the beginning of the next input field, this
472 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
473 non-nil case, if two fields are separated by a field with the special
474 value `boundary', and POS lies within it, then the two separated
475 fields are considered to be adjacent, and POS between them, when
476 finding the beginning and ending of the "merged" field.
477
478 Either BEG or END may be 0, in which case the corresponding value
479 is not stored. */
480
481 static void
482 find_field (Lisp_Object pos, Lisp_Object merge_at_boundary,
483 Lisp_Object beg_limit,
484 ptrdiff_t *beg, Lisp_Object end_limit, ptrdiff_t *end)
485 {
486 /* Fields right before and after the point. */
487 Lisp_Object before_field, after_field;
488 /* True if POS counts as the start of a field. */
489 bool at_field_start = 0;
490 /* True if POS counts as the end of a field. */
491 bool at_field_end = 0;
492
493 if (NILP (pos))
494 XSETFASTINT (pos, PT);
495 else
496 CHECK_NUMBER_COERCE_MARKER (pos);
497
498 after_field
499 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
500 before_field
501 = (XFASTINT (pos) > BEGV
502 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
503 Qfield, Qnil, NULL)
504 /* Using nil here would be a more obvious choice, but it would
505 fail when the buffer starts with a non-sticky field. */
506 : after_field);
507
508 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
509 and POS is at beginning of a field, which can also be interpreted
510 as the end of the previous field. Note that the case where if
511 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
512 more natural one; then we avoid treating the beginning of a field
513 specially. */
514 if (NILP (merge_at_boundary))
515 {
516 Lisp_Object field = Fget_pos_property (pos, Qfield, Qnil);
517 if (!EQ (field, after_field))
518 at_field_end = 1;
519 if (!EQ (field, before_field))
520 at_field_start = 1;
521 if (NILP (field) && at_field_start && at_field_end)
522 /* If an inserted char would have a nil field while the surrounding
523 text is non-nil, we're probably not looking at a
524 zero-length field, but instead at a non-nil field that's
525 not intended for editing (such as comint's prompts). */
526 at_field_end = at_field_start = 0;
527 }
528
529 /* Note about special `boundary' fields:
530
531 Consider the case where the point (`.') is between the fields `x' and `y':
532
533 xxxx.yyyy
534
535 In this situation, if merge_at_boundary is non-nil, consider the
536 `x' and `y' fields as forming one big merged field, and so the end
537 of the field is the end of `y'.
538
539 However, if `x' and `y' are separated by a special `boundary' field
540 (a field with a `field' char-property of 'boundary), then ignore
541 this special field when merging adjacent fields. Here's the same
542 situation, but with a `boundary' field between the `x' and `y' fields:
543
544 xxx.BBBByyyy
545
546 Here, if point is at the end of `x', the beginning of `y', or
547 anywhere in-between (within the `boundary' field), merge all
548 three fields and consider the beginning as being the beginning of
549 the `x' field, and the end as being the end of the `y' field. */
550
551 if (beg)
552 {
553 if (at_field_start)
554 /* POS is at the edge of a field, and we should consider it as
555 the beginning of the following field. */
556 *beg = XFASTINT (pos);
557 else
558 /* Find the previous field boundary. */
559 {
560 Lisp_Object p = pos;
561 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
562 /* Skip a `boundary' field. */
563 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
564 beg_limit);
565
566 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
567 beg_limit);
568 *beg = NILP (p) ? BEGV : XFASTINT (p);
569 }
570 }
571
572 if (end)
573 {
574 if (at_field_end)
575 /* POS is at the edge of a field, and we should consider it as
576 the end of the previous field. */
577 *end = XFASTINT (pos);
578 else
579 /* Find the next field boundary. */
580 {
581 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
582 /* Skip a `boundary' field. */
583 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
584 end_limit);
585
586 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
587 end_limit);
588 *end = NILP (pos) ? ZV : XFASTINT (pos);
589 }
590 }
591 }
592
593 \f
594 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
595 doc: /* Delete the field surrounding POS.
596 A field is a region of text with the same `field' property.
597 If POS is nil, the value of point is used for POS. */)
598 (Lisp_Object pos)
599 {
600 ptrdiff_t beg, end;
601 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
602 if (beg != end)
603 del_range (beg, end);
604 return Qnil;
605 }
606
607 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
608 doc: /* Return the contents of the field surrounding POS as a string.
609 A field is a region of text with the same `field' property.
610 If POS is nil, the value of point is used for POS. */)
611 (Lisp_Object pos)
612 {
613 ptrdiff_t beg, end;
614 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
615 return make_buffer_string (beg, end, 1);
616 }
617
618 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
619 doc: /* Return the contents of the field around POS, without text properties.
620 A field is a region of text with the same `field' property.
621 If POS is nil, the value of point is used for POS. */)
622 (Lisp_Object pos)
623 {
624 ptrdiff_t beg, end;
625 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
626 return make_buffer_string (beg, end, 0);
627 }
628
629 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
630 doc: /* Return the beginning of the field surrounding POS.
631 A field is a region of text with the same `field' property.
632 If POS is nil, the value of point is used for POS.
633 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
634 field, then the beginning of the *previous* field is returned.
635 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
636 is before LIMIT, then LIMIT will be returned instead. */)
637 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
638 {
639 ptrdiff_t beg;
640 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
641 return make_number (beg);
642 }
643
644 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
645 doc: /* Return the end of the field surrounding POS.
646 A field is a region of text with the same `field' property.
647 If POS is nil, the value of point is used for POS.
648 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
649 then the end of the *following* field is returned.
650 If LIMIT is non-nil, it is a buffer position; if the end of the field
651 is after LIMIT, then LIMIT will be returned instead. */)
652 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
653 {
654 ptrdiff_t end;
655 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
656 return make_number (end);
657 }
658
659 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
660 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
661 A field is a region of text with the same `field' property.
662
663 If NEW-POS is nil, then use the current point instead, and move point
664 to the resulting constrained position, in addition to returning that
665 position.
666
667 If OLD-POS is at the boundary of two fields, then the allowable
668 positions for NEW-POS depends on the value of the optional argument
669 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
670 constrained to the field that has the same `field' char-property
671 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
672 is non-nil, NEW-POS is constrained to the union of the two adjacent
673 fields. Additionally, if two fields are separated by another field with
674 the special value `boundary', then any point within this special field is
675 also considered to be `on the boundary'.
676
677 If the optional argument ONLY-IN-LINE is non-nil and constraining
678 NEW-POS would move it to a different line, NEW-POS is returned
679 unconstrained. This is useful for commands that move by line, like
680 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
681 only in the case where they can still move to the right line.
682
683 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
684 a non-nil property of that name, then any field boundaries are ignored.
685
686 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
687 (Lisp_Object new_pos, Lisp_Object old_pos, Lisp_Object escape_from_edge,
688 Lisp_Object only_in_line, Lisp_Object inhibit_capture_property)
689 {
690 /* If non-zero, then the original point, before re-positioning. */
691 ptrdiff_t orig_point = 0;
692 bool fwd;
693 Lisp_Object prev_old, prev_new;
694
695 if (NILP (new_pos))
696 /* Use the current point, and afterwards, set it. */
697 {
698 orig_point = PT;
699 XSETFASTINT (new_pos, PT);
700 }
701
702 CHECK_NUMBER_COERCE_MARKER (new_pos);
703 CHECK_NUMBER_COERCE_MARKER (old_pos);
704
705 fwd = (XINT (new_pos) > XINT (old_pos));
706
707 prev_old = make_number (XINT (old_pos) - 1);
708 prev_new = make_number (XINT (new_pos) - 1);
709
710 if (NILP (Vinhibit_field_text_motion)
711 && !EQ (new_pos, old_pos)
712 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
713 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
714 /* To recognize field boundaries, we must also look at the
715 previous positions; we could use `Fget_pos_property'
716 instead, but in itself that would fail inside non-sticky
717 fields (like comint prompts). */
718 || (XFASTINT (new_pos) > BEGV
719 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
720 || (XFASTINT (old_pos) > BEGV
721 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
722 && (NILP (inhibit_capture_property)
723 /* Field boundaries are again a problem; but now we must
724 decide the case exactly, so we need to call
725 `get_pos_property' as well. */
726 || (NILP (Fget_pos_property (old_pos, inhibit_capture_property, Qnil))
727 && (XFASTINT (old_pos) <= BEGV
728 || NILP (Fget_char_property
729 (old_pos, inhibit_capture_property, Qnil))
730 || NILP (Fget_char_property
731 (prev_old, inhibit_capture_property, Qnil))))))
732 /* It is possible that NEW_POS is not within the same field as
733 OLD_POS; try to move NEW_POS so that it is. */
734 {
735 ptrdiff_t shortage;
736 Lisp_Object field_bound;
737
738 if (fwd)
739 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
740 else
741 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
742
743 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
744 other side of NEW_POS, which would mean that NEW_POS is
745 already acceptable, and it's not necessary to constrain it
746 to FIELD_BOUND. */
747 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
748 /* NEW_POS should be constrained, but only if either
749 ONLY_IN_LINE is nil (in which case any constraint is OK),
750 or NEW_POS and FIELD_BOUND are on the same line (in which
751 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
752 && (NILP (only_in_line)
753 /* This is the ONLY_IN_LINE case, check that NEW_POS and
754 FIELD_BOUND are on the same line by seeing whether
755 there's an intervening newline or not. */
756 || (find_newline (XFASTINT (new_pos), -1,
757 XFASTINT (field_bound), -1,
758 fwd ? -1 : 1, &shortage, NULL, 1),
759 shortage != 0)))
760 /* Constrain NEW_POS to FIELD_BOUND. */
761 new_pos = field_bound;
762
763 if (orig_point && XFASTINT (new_pos) != orig_point)
764 /* The NEW_POS argument was originally nil, so automatically set PT. */
765 SET_PT (XFASTINT (new_pos));
766 }
767
768 return new_pos;
769 }
770
771 \f
772 DEFUN ("line-beginning-position",
773 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
774 doc: /* Return the character position of the first character on the current line.
775 With optional argument N, scan forward N - 1 lines first.
776 If the scan reaches the end of the buffer, return that position.
777
778 This function ignores text display directionality; it returns the
779 position of the first character in logical order, i.e. the smallest
780 character position on the line.
781
782 This function constrains the returned position to the current field
783 unless that position would be on a different line than the original,
784 unconstrained result. If N is nil or 1, and a front-sticky field
785 starts at point, the scan stops as soon as it starts. To ignore field
786 boundaries, bind `inhibit-field-text-motion' to t.
787
788 This function does not move point. */)
789 (Lisp_Object n)
790 {
791 ptrdiff_t charpos, bytepos;
792
793 if (NILP (n))
794 XSETFASTINT (n, 1);
795 else
796 CHECK_NUMBER (n);
797
798 scan_newline_from_point (XINT (n) - 1, &charpos, &bytepos);
799
800 /* Return END constrained to the current input field. */
801 return Fconstrain_to_field (make_number (charpos), make_number (PT),
802 XINT (n) != 1 ? Qt : Qnil,
803 Qt, Qnil);
804 }
805
806 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
807 doc: /* Return the character position of the last character on the current line.
808 With argument N not nil or 1, move forward N - 1 lines first.
809 If scan reaches end of buffer, return that position.
810
811 This function ignores text display directionality; it returns the
812 position of the last character in logical order, i.e. the largest
813 character position on the line.
814
815 This function constrains the returned position to the current field
816 unless that would be on a different line than the original,
817 unconstrained result. If N is nil or 1, and a rear-sticky field ends
818 at point, the scan stops as soon as it starts. To ignore field
819 boundaries bind `inhibit-field-text-motion' to t.
820
821 This function does not move point. */)
822 (Lisp_Object n)
823 {
824 ptrdiff_t clipped_n;
825 ptrdiff_t end_pos;
826 ptrdiff_t orig = PT;
827
828 if (NILP (n))
829 XSETFASTINT (n, 1);
830 else
831 CHECK_NUMBER (n);
832
833 clipped_n = clip_to_bounds (PTRDIFF_MIN + 1, XINT (n), PTRDIFF_MAX);
834 end_pos = find_before_next_newline (orig, 0, clipped_n - (clipped_n <= 0),
835 NULL);
836
837 /* Return END_POS constrained to the current input field. */
838 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
839 Qnil, Qt, Qnil);
840 }
841
842 /* Save current buffer state for `save-excursion' special form.
843 We (ab)use Lisp_Misc_Save_Value to allow explicit free and so
844 offload some work from GC. */
845
846 Lisp_Object
847 save_excursion_save (void)
848 {
849 return make_save_obj_obj_obj_obj
850 (Fpoint_marker (),
851 /* Do not copy the mark if it points to nowhere. */
852 (XMARKER (BVAR (current_buffer, mark))->buffer
853 ? Fcopy_marker (BVAR (current_buffer, mark), Qnil)
854 : Qnil),
855 /* Selected window if current buffer is shown in it, nil otherwise. */
856 (EQ (XWINDOW (selected_window)->contents, Fcurrent_buffer ())
857 ? selected_window : Qnil),
858 BVAR (current_buffer, mark_active));
859 }
860
861 /* Restore saved buffer before leaving `save-excursion' special form. */
862
863 void
864 save_excursion_restore (Lisp_Object info)
865 {
866 Lisp_Object tem, tem1, omark, nmark;
867 struct gcpro gcpro1, gcpro2, gcpro3;
868
869 tem = Fmarker_buffer (XSAVE_OBJECT (info, 0));
870 /* If we're unwinding to top level, saved buffer may be deleted. This
871 means that all of its markers are unchained and so tem is nil. */
872 if (NILP (tem))
873 goto out;
874
875 omark = nmark = Qnil;
876 GCPRO3 (info, omark, nmark);
877
878 Fset_buffer (tem);
879
880 /* Point marker. */
881 tem = XSAVE_OBJECT (info, 0);
882 Fgoto_char (tem);
883 unchain_marker (XMARKER (tem));
884
885 /* Mark marker. */
886 tem = XSAVE_OBJECT (info, 1);
887 omark = Fmarker_position (BVAR (current_buffer, mark));
888 if (NILP (tem))
889 unchain_marker (XMARKER (BVAR (current_buffer, mark)));
890 else
891 {
892 Fset_marker (BVAR (current_buffer, mark), tem, Fcurrent_buffer ());
893 nmark = Fmarker_position (tem);
894 unchain_marker (XMARKER (tem));
895 }
896
897 /* Mark active. */
898 tem = XSAVE_OBJECT (info, 3);
899 tem1 = BVAR (current_buffer, mark_active);
900 bset_mark_active (current_buffer, tem);
901
902 /* If mark is active now, and either was not active
903 or was at a different place, run the activate hook. */
904 if (! NILP (tem))
905 {
906 if (! EQ (omark, nmark))
907 {
908 tem = intern ("activate-mark-hook");
909 Frun_hooks (1, &tem);
910 }
911 }
912 /* If mark has ceased to be active, run deactivate hook. */
913 else if (! NILP (tem1))
914 {
915 tem = intern ("deactivate-mark-hook");
916 Frun_hooks (1, &tem);
917 }
918
919 /* If buffer was visible in a window, and a different window was
920 selected, and the old selected window is still showing this
921 buffer, restore point in that window. */
922 tem = XSAVE_OBJECT (info, 2);
923 if (WINDOWP (tem)
924 && !EQ (tem, selected_window)
925 && (tem1 = XWINDOW (tem)->contents,
926 (/* Window is live... */
927 BUFFERP (tem1)
928 /* ...and it shows the current buffer. */
929 && XBUFFER (tem1) == current_buffer)))
930 Fset_window_point (tem, make_number (PT));
931
932 UNGCPRO;
933
934 out:
935
936 free_misc (info);
937 }
938
939 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
940 doc: /* Save point, mark, and current buffer; execute BODY; restore those things.
941 Executes BODY just like `progn'.
942 The values of point, mark and the current buffer are restored
943 even in case of abnormal exit (throw or error).
944 The state of activation of the mark is also restored.
945
946 This construct does not save `deactivate-mark', and therefore
947 functions that change the buffer will still cause deactivation
948 of the mark at the end of the command. To prevent that, bind
949 `deactivate-mark' with `let'.
950
951 If you only want to save the current buffer but not point nor mark,
952 then just use `save-current-buffer', or even `with-current-buffer'.
953
954 usage: (save-excursion &rest BODY) */)
955 (Lisp_Object args)
956 {
957 register Lisp_Object val;
958 ptrdiff_t count = SPECPDL_INDEX ();
959
960 record_unwind_protect (save_excursion_restore, save_excursion_save ());
961
962 val = Fprogn (args);
963 return unbind_to (count, val);
964 }
965
966 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
967 doc: /* Record which buffer is current; execute BODY; make that buffer current.
968 BODY is executed just like `progn'.
969 usage: (save-current-buffer &rest BODY) */)
970 (Lisp_Object args)
971 {
972 ptrdiff_t count = SPECPDL_INDEX ();
973
974 record_unwind_current_buffer ();
975 return unbind_to (count, Fprogn (args));
976 }
977 \f
978 DEFUN ("buffer-size", Fbuffer_size, Sbuffer_size, 0, 1, 0,
979 doc: /* Return the number of characters in the current buffer.
980 If BUFFER, return the number of characters in that buffer instead. */)
981 (Lisp_Object buffer)
982 {
983 if (NILP (buffer))
984 return make_number (Z - BEG);
985 else
986 {
987 CHECK_BUFFER (buffer);
988 return make_number (BUF_Z (XBUFFER (buffer))
989 - BUF_BEG (XBUFFER (buffer)));
990 }
991 }
992
993 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
994 doc: /* Return the minimum permissible value of point in the current buffer.
995 This is 1, unless narrowing (a buffer restriction) is in effect. */)
996 (void)
997 {
998 Lisp_Object temp;
999 XSETFASTINT (temp, BEGV);
1000 return temp;
1001 }
1002
1003 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
1004 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1005 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1006 (void)
1007 {
1008 return build_marker (current_buffer, BEGV, BEGV_BYTE);
1009 }
1010
1011 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1012 doc: /* Return the maximum permissible value of point in the current buffer.
1013 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1014 is in effect, in which case it is less. */)
1015 (void)
1016 {
1017 Lisp_Object temp;
1018 XSETFASTINT (temp, ZV);
1019 return temp;
1020 }
1021
1022 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1023 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1024 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1025 is in effect, in which case it is less. */)
1026 (void)
1027 {
1028 return build_marker (current_buffer, ZV, ZV_BYTE);
1029 }
1030
1031 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1032 doc: /* Return the position of the gap, in the current buffer.
1033 See also `gap-size'. */)
1034 (void)
1035 {
1036 Lisp_Object temp;
1037 XSETFASTINT (temp, GPT);
1038 return temp;
1039 }
1040
1041 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1042 doc: /* Return the size of the current buffer's gap.
1043 See also `gap-position'. */)
1044 (void)
1045 {
1046 Lisp_Object temp;
1047 XSETFASTINT (temp, GAP_SIZE);
1048 return temp;
1049 }
1050
1051 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1052 doc: /* Return the byte position for character position POSITION.
1053 If POSITION is out of range, the value is nil. */)
1054 (Lisp_Object position)
1055 {
1056 CHECK_NUMBER_COERCE_MARKER (position);
1057 if (XINT (position) < BEG || XINT (position) > Z)
1058 return Qnil;
1059 return make_number (CHAR_TO_BYTE (XINT (position)));
1060 }
1061
1062 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1063 doc: /* Return the character position for byte position BYTEPOS.
1064 If BYTEPOS is out of range, the value is nil. */)
1065 (Lisp_Object bytepos)
1066 {
1067 CHECK_NUMBER (bytepos);
1068 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
1069 return Qnil;
1070 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1071 }
1072 \f
1073 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1074 doc: /* Return the character following point, as a number.
1075 At the end of the buffer or accessible region, return 0. */)
1076 (void)
1077 {
1078 Lisp_Object temp;
1079 if (PT >= ZV)
1080 XSETFASTINT (temp, 0);
1081 else
1082 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1083 return temp;
1084 }
1085
1086 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1087 doc: /* Return the character preceding point, as a number.
1088 At the beginning of the buffer or accessible region, return 0. */)
1089 (void)
1090 {
1091 Lisp_Object temp;
1092 if (PT <= BEGV)
1093 XSETFASTINT (temp, 0);
1094 else if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1095 {
1096 ptrdiff_t pos = PT_BYTE;
1097 DEC_POS (pos);
1098 XSETFASTINT (temp, FETCH_CHAR (pos));
1099 }
1100 else
1101 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1102 return temp;
1103 }
1104
1105 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1106 doc: /* Return t if point is at the beginning of the buffer.
1107 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1108 (void)
1109 {
1110 if (PT == BEGV)
1111 return Qt;
1112 return Qnil;
1113 }
1114
1115 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1116 doc: /* Return t if point is at the end of the buffer.
1117 If the buffer is narrowed, this means the end of the narrowed part. */)
1118 (void)
1119 {
1120 if (PT == ZV)
1121 return Qt;
1122 return Qnil;
1123 }
1124
1125 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1126 doc: /* Return t if point is at the beginning of a line. */)
1127 (void)
1128 {
1129 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1130 return Qt;
1131 return Qnil;
1132 }
1133
1134 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1135 doc: /* Return t if point is at the end of a line.
1136 `End of a line' includes point being at the end of the buffer. */)
1137 (void)
1138 {
1139 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1140 return Qt;
1141 return Qnil;
1142 }
1143
1144 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1145 doc: /* Return character in current buffer at position POS.
1146 POS is an integer or a marker and defaults to point.
1147 If POS is out of range, the value is nil. */)
1148 (Lisp_Object pos)
1149 {
1150 register ptrdiff_t pos_byte;
1151
1152 if (NILP (pos))
1153 {
1154 pos_byte = PT_BYTE;
1155 XSETFASTINT (pos, PT);
1156 }
1157
1158 if (MARKERP (pos))
1159 {
1160 pos_byte = marker_byte_position (pos);
1161 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1162 return Qnil;
1163 }
1164 else
1165 {
1166 CHECK_NUMBER_COERCE_MARKER (pos);
1167 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1168 return Qnil;
1169
1170 pos_byte = CHAR_TO_BYTE (XINT (pos));
1171 }
1172
1173 return make_number (FETCH_CHAR (pos_byte));
1174 }
1175
1176 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1177 doc: /* Return character in current buffer preceding position POS.
1178 POS is an integer or a marker and defaults to point.
1179 If POS is out of range, the value is nil. */)
1180 (Lisp_Object pos)
1181 {
1182 register Lisp_Object val;
1183 register ptrdiff_t pos_byte;
1184
1185 if (NILP (pos))
1186 {
1187 pos_byte = PT_BYTE;
1188 XSETFASTINT (pos, PT);
1189 }
1190
1191 if (MARKERP (pos))
1192 {
1193 pos_byte = marker_byte_position (pos);
1194
1195 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1196 return Qnil;
1197 }
1198 else
1199 {
1200 CHECK_NUMBER_COERCE_MARKER (pos);
1201
1202 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1203 return Qnil;
1204
1205 pos_byte = CHAR_TO_BYTE (XINT (pos));
1206 }
1207
1208 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1209 {
1210 DEC_POS (pos_byte);
1211 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1212 }
1213 else
1214 {
1215 pos_byte--;
1216 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1217 }
1218 return val;
1219 }
1220 \f
1221 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1222 doc: /* Return the name under which the user logged in, as a string.
1223 This is based on the effective uid, not the real uid.
1224 Also, if the environment variables LOGNAME or USER are set,
1225 that determines the value of this function.
1226
1227 If optional argument UID is an integer or a float, return the login name
1228 of the user with that uid, or nil if there is no such user. */)
1229 (Lisp_Object uid)
1230 {
1231 struct passwd *pw;
1232 uid_t id;
1233
1234 /* Set up the user name info if we didn't do it before.
1235 (That can happen if Emacs is dumpable
1236 but you decide to run `temacs -l loadup' and not dump. */
1237 if (INTEGERP (Vuser_login_name))
1238 init_editfns ();
1239
1240 if (NILP (uid))
1241 return Vuser_login_name;
1242
1243 CONS_TO_INTEGER (uid, uid_t, id);
1244 block_input ();
1245 pw = getpwuid (id);
1246 unblock_input ();
1247 return (pw ? build_string (pw->pw_name) : Qnil);
1248 }
1249
1250 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1251 0, 0, 0,
1252 doc: /* Return the name of the user's real uid, as a string.
1253 This ignores the environment variables LOGNAME and USER, so it differs from
1254 `user-login-name' when running under `su'. */)
1255 (void)
1256 {
1257 /* Set up the user name info if we didn't do it before.
1258 (That can happen if Emacs is dumpable
1259 but you decide to run `temacs -l loadup' and not dump. */
1260 if (INTEGERP (Vuser_login_name))
1261 init_editfns ();
1262 return Vuser_real_login_name;
1263 }
1264
1265 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1266 doc: /* Return the effective uid of Emacs.
1267 Value is an integer or a float, depending on the value. */)
1268 (void)
1269 {
1270 uid_t euid = geteuid ();
1271 return make_fixnum_or_float (euid);
1272 }
1273
1274 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1275 doc: /* Return the real uid of Emacs.
1276 Value is an integer or a float, depending on the value. */)
1277 (void)
1278 {
1279 uid_t uid = getuid ();
1280 return make_fixnum_or_float (uid);
1281 }
1282
1283 DEFUN ("group-gid", Fgroup_gid, Sgroup_gid, 0, 0, 0,
1284 doc: /* Return the effective gid of Emacs.
1285 Value is an integer or a float, depending on the value. */)
1286 (void)
1287 {
1288 gid_t egid = getegid ();
1289 return make_fixnum_or_float (egid);
1290 }
1291
1292 DEFUN ("group-real-gid", Fgroup_real_gid, Sgroup_real_gid, 0, 0, 0,
1293 doc: /* Return the real gid of Emacs.
1294 Value is an integer or a float, depending on the value. */)
1295 (void)
1296 {
1297 gid_t gid = getgid ();
1298 return make_fixnum_or_float (gid);
1299 }
1300
1301 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1302 doc: /* Return the full name of the user logged in, as a string.
1303 If the full name corresponding to Emacs's userid is not known,
1304 return "unknown".
1305
1306 If optional argument UID is an integer or float, return the full name
1307 of the user with that uid, or nil if there is no such user.
1308 If UID is a string, return the full name of the user with that login
1309 name, or nil if there is no such user. */)
1310 (Lisp_Object uid)
1311 {
1312 struct passwd *pw;
1313 register char *p, *q;
1314 Lisp_Object full;
1315
1316 if (NILP (uid))
1317 return Vuser_full_name;
1318 else if (NUMBERP (uid))
1319 {
1320 uid_t u;
1321 CONS_TO_INTEGER (uid, uid_t, u);
1322 block_input ();
1323 pw = getpwuid (u);
1324 unblock_input ();
1325 }
1326 else if (STRINGP (uid))
1327 {
1328 block_input ();
1329 pw = getpwnam (SSDATA (uid));
1330 unblock_input ();
1331 }
1332 else
1333 error ("Invalid UID specification");
1334
1335 if (!pw)
1336 return Qnil;
1337
1338 p = USER_FULL_NAME;
1339 /* Chop off everything after the first comma. */
1340 q = strchr (p, ',');
1341 full = make_string (p, q ? q - p : strlen (p));
1342
1343 #ifdef AMPERSAND_FULL_NAME
1344 p = SSDATA (full);
1345 q = strchr (p, '&');
1346 /* Substitute the login name for the &, upcasing the first character. */
1347 if (q)
1348 {
1349 Lisp_Object login = Fuser_login_name (make_number (pw->pw_uid));
1350 USE_SAFE_ALLOCA;
1351 char *r = SAFE_ALLOCA (strlen (p) + SBYTES (login) + 1);
1352 memcpy (r, p, q - p);
1353 char *s = lispstpcpy (&r[q - p], login);
1354 r[q - p] = upcase ((unsigned char) r[q - p]);
1355 strcpy (s, q + 1);
1356 full = build_string (r);
1357 SAFE_FREE ();
1358 }
1359 #endif /* AMPERSAND_FULL_NAME */
1360
1361 return full;
1362 }
1363
1364 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1365 doc: /* Return the host name of the machine you are running on, as a string. */)
1366 (void)
1367 {
1368 return Vsystem_name;
1369 }
1370
1371 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1372 doc: /* Return the process ID of Emacs, as a number. */)
1373 (void)
1374 {
1375 pid_t pid = getpid ();
1376 return make_fixnum_or_float (pid);
1377 }
1378
1379 \f
1380
1381 #ifndef TIME_T_MIN
1382 # define TIME_T_MIN TYPE_MINIMUM (time_t)
1383 #endif
1384 #ifndef TIME_T_MAX
1385 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
1386 #endif
1387
1388 /* Report that a time value is out of range for Emacs. */
1389 void
1390 time_overflow (void)
1391 {
1392 error ("Specified time is not representable");
1393 }
1394
1395 static void
1396 invalid_time (void)
1397 {
1398 error ("Invalid time specification");
1399 }
1400
1401 /* A substitute for mktime_z on platforms that lack it. It's not
1402 thread-safe, but should be good enough for Emacs in typical use. */
1403 #ifndef HAVE_TZALLOC
1404 time_t
1405 mktime_z (timezone_t tz, struct tm *tm)
1406 {
1407 char *oldtz = getenv ("TZ");
1408 USE_SAFE_ALLOCA;
1409 if (oldtz)
1410 {
1411 size_t oldtzsize = strlen (oldtz) + 1;
1412 char *oldtzcopy = SAFE_ALLOCA (oldtzsize);
1413 oldtz = strcpy (oldtzcopy, oldtz);
1414 }
1415 block_input ();
1416 set_time_zone_rule (tz);
1417 time_t t = mktime (tm);
1418 set_time_zone_rule (oldtz);
1419 unblock_input ();
1420 SAFE_FREE ();
1421 return t;
1422 }
1423 #endif
1424
1425 /* Return the upper part of the time T (everything but the bottom 16 bits). */
1426 static EMACS_INT
1427 hi_time (time_t t)
1428 {
1429 time_t hi = t >> LO_TIME_BITS;
1430
1431 /* Check for overflow, helping the compiler for common cases where
1432 no runtime check is needed, and taking care not to convert
1433 negative numbers to unsigned before comparing them. */
1434 if (! ((! TYPE_SIGNED (time_t)
1435 || MOST_NEGATIVE_FIXNUM <= TIME_T_MIN >> LO_TIME_BITS
1436 || MOST_NEGATIVE_FIXNUM <= hi)
1437 && (TIME_T_MAX >> LO_TIME_BITS <= MOST_POSITIVE_FIXNUM
1438 || hi <= MOST_POSITIVE_FIXNUM)))
1439 time_overflow ();
1440
1441 return hi;
1442 }
1443
1444 /* Return the bottom bits of the time T. */
1445 static int
1446 lo_time (time_t t)
1447 {
1448 return t & ((1 << LO_TIME_BITS) - 1);
1449 }
1450
1451 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1452 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1453 The time is returned as a list of integers (HIGH LOW USEC PSEC).
1454 HIGH has the most significant bits of the seconds, while LOW has the
1455 least significant 16 bits. USEC and PSEC are the microsecond and
1456 picosecond counts. */)
1457 (void)
1458 {
1459 return make_lisp_time (current_timespec ());
1460 }
1461
1462 static struct lisp_time
1463 time_add (struct lisp_time ta, struct lisp_time tb)
1464 {
1465 EMACS_INT hi = ta.hi + tb.hi;
1466 int lo = ta.lo + tb.lo;
1467 int us = ta.us + tb.us;
1468 int ps = ta.ps + tb.ps;
1469 us += (1000000 <= ps);
1470 ps -= (1000000 <= ps) * 1000000;
1471 lo += (1000000 <= us);
1472 us -= (1000000 <= us) * 1000000;
1473 hi += (1 << LO_TIME_BITS <= lo);
1474 lo -= (1 << LO_TIME_BITS <= lo) << LO_TIME_BITS;
1475 return (struct lisp_time) { hi, lo, us, ps };
1476 }
1477
1478 static struct lisp_time
1479 time_subtract (struct lisp_time ta, struct lisp_time tb)
1480 {
1481 EMACS_INT hi = ta.hi - tb.hi;
1482 int lo = ta.lo - tb.lo;
1483 int us = ta.us - tb.us;
1484 int ps = ta.ps - tb.ps;
1485 us -= (ps < 0);
1486 ps += (ps < 0) * 1000000;
1487 lo -= (us < 0);
1488 us += (us < 0) * 1000000;
1489 hi -= (lo < 0);
1490 lo += (lo < 0) << LO_TIME_BITS;
1491 return (struct lisp_time) { hi, lo, us, ps };
1492 }
1493
1494 static Lisp_Object
1495 time_arith (Lisp_Object a, Lisp_Object b,
1496 struct lisp_time (*op) (struct lisp_time, struct lisp_time))
1497 {
1498 int alen, blen;
1499 struct lisp_time ta = lisp_time_struct (a, &alen);
1500 struct lisp_time tb = lisp_time_struct (b, &blen);
1501 struct lisp_time t = op (ta, tb);
1502 if (! (MOST_NEGATIVE_FIXNUM <= t.hi && t.hi <= MOST_POSITIVE_FIXNUM))
1503 time_overflow ();
1504 Lisp_Object val = Qnil;
1505
1506 switch (max (alen, blen))
1507 {
1508 default:
1509 val = Fcons (make_number (t.ps), val);
1510 /* Fall through. */
1511 case 3:
1512 val = Fcons (make_number (t.us), val);
1513 /* Fall through. */
1514 case 2:
1515 val = Fcons (make_number (t.lo), val);
1516 val = Fcons (make_number (t.hi), val);
1517 break;
1518 }
1519
1520 return val;
1521 }
1522
1523 DEFUN ("time-add", Ftime_add, Stime_add, 2, 2, 0,
1524 doc: /* Return the sum of two time values A and B, as a time value. */)
1525 (Lisp_Object a, Lisp_Object b)
1526 {
1527 return time_arith (a, b, time_add);
1528 }
1529
1530 DEFUN ("time-subtract", Ftime_subtract, Stime_subtract, 2, 2, 0,
1531 doc: /* Return the difference between two time values A and B, as a time value. */)
1532 (Lisp_Object a, Lisp_Object b)
1533 {
1534 return time_arith (a, b, time_subtract);
1535 }
1536
1537 DEFUN ("time-less-p", Ftime_less_p, Stime_less_p, 2, 2, 0,
1538 doc: /* Return non-nil if time value T1 is earlier than time value T2. */)
1539 (Lisp_Object t1, Lisp_Object t2)
1540 {
1541 int t1len, t2len;
1542 struct lisp_time a = lisp_time_struct (t1, &t1len);
1543 struct lisp_time b = lisp_time_struct (t2, &t2len);
1544 return ((a.hi != b.hi ? a.hi < b.hi
1545 : a.lo != b.lo ? a.lo < b.lo
1546 : a.us != b.us ? a.us < b.us
1547 : a.ps < b.ps)
1548 ? Qt : Qnil);
1549 }
1550
1551
1552 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1553 0, 0, 0,
1554 doc: /* Return the current run time used by Emacs.
1555 The time is returned as a list (HIGH LOW USEC PSEC), using the same
1556 style as (current-time).
1557
1558 On systems that can't determine the run time, `get-internal-run-time'
1559 does the same thing as `current-time'. */)
1560 (void)
1561 {
1562 #ifdef HAVE_GETRUSAGE
1563 struct rusage usage;
1564 time_t secs;
1565 int usecs;
1566
1567 if (getrusage (RUSAGE_SELF, &usage) < 0)
1568 /* This shouldn't happen. What action is appropriate? */
1569 xsignal0 (Qerror);
1570
1571 /* Sum up user time and system time. */
1572 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1573 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1574 if (usecs >= 1000000)
1575 {
1576 usecs -= 1000000;
1577 secs++;
1578 }
1579 return make_lisp_time (make_timespec (secs, usecs * 1000));
1580 #else /* ! HAVE_GETRUSAGE */
1581 #ifdef WINDOWSNT
1582 return w32_get_internal_run_time ();
1583 #else /* ! WINDOWSNT */
1584 return Fcurrent_time ();
1585 #endif /* WINDOWSNT */
1586 #endif /* HAVE_GETRUSAGE */
1587 }
1588 \f
1589
1590 /* Make a Lisp list that represents the Emacs time T. T may be an
1591 invalid time, with a slightly negative tv_nsec value such as
1592 UNKNOWN_MODTIME_NSECS; in that case, the Lisp list contains a
1593 correspondingly negative picosecond count. */
1594 Lisp_Object
1595 make_lisp_time (struct timespec t)
1596 {
1597 time_t s = t.tv_sec;
1598 int ns = t.tv_nsec;
1599 return list4i (hi_time (s), lo_time (s), ns / 1000, ns % 1000 * 1000);
1600 }
1601
1602 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1603 Set *PHIGH, *PLOW, *PUSEC, *PPSEC to its parts; do not check their values.
1604 Return 2, 3, or 4 to indicate the effective length of SPECIFIED_TIME
1605 if successful, 0 if unsuccessful. */
1606 static int
1607 disassemble_lisp_time (Lisp_Object specified_time, Lisp_Object *phigh,
1608 Lisp_Object *plow, Lisp_Object *pusec,
1609 Lisp_Object *ppsec)
1610 {
1611 Lisp_Object high = make_number (0);
1612 Lisp_Object low = specified_time;
1613 Lisp_Object usec = make_number (0);
1614 Lisp_Object psec = make_number (0);
1615 int len = 4;
1616
1617 if (CONSP (specified_time))
1618 {
1619 high = XCAR (specified_time);
1620 low = XCDR (specified_time);
1621 if (CONSP (low))
1622 {
1623 Lisp_Object low_tail = XCDR (low);
1624 low = XCAR (low);
1625 if (CONSP (low_tail))
1626 {
1627 usec = XCAR (low_tail);
1628 low_tail = XCDR (low_tail);
1629 if (CONSP (low_tail))
1630 psec = XCAR (low_tail);
1631 else
1632 len = 3;
1633 }
1634 else if (!NILP (low_tail))
1635 {
1636 usec = low_tail;
1637 len = 3;
1638 }
1639 else
1640 len = 2;
1641 }
1642 else
1643 len = 2;
1644
1645 /* When combining components, require LOW to be an integer,
1646 as otherwise it would be a pain to add up times. */
1647 if (! INTEGERP (low))
1648 return 0;
1649 }
1650 else if (INTEGERP (specified_time))
1651 len = 2;
1652
1653 *phigh = high;
1654 *plow = low;
1655 *pusec = usec;
1656 *ppsec = psec;
1657 return len;
1658 }
1659
1660 /* Convert T into an Emacs time *RESULT, truncating toward minus infinity.
1661 Return true if T is in range, false otherwise. */
1662 static bool
1663 decode_float_time (double t, struct lisp_time *result)
1664 {
1665 double lo_multiplier = 1 << LO_TIME_BITS;
1666 double emacs_time_min = MOST_NEGATIVE_FIXNUM * lo_multiplier;
1667 if (! (emacs_time_min <= t && t < -emacs_time_min))
1668 return false;
1669
1670 double small_t = t / lo_multiplier;
1671 EMACS_INT hi = small_t;
1672 double t_sans_hi = t - hi * lo_multiplier;
1673 int lo = t_sans_hi;
1674 long double fracps = (t_sans_hi - lo) * 1e12L;
1675 #ifdef INT_FAST64_MAX
1676 int_fast64_t ifracps = fracps;
1677 int us = ifracps / 1000000;
1678 int ps = ifracps % 1000000;
1679 #else
1680 int us = fracps / 1e6L;
1681 int ps = fracps - us * 1e6L;
1682 #endif
1683 us -= (ps < 0);
1684 ps += (ps < 0) * 1000000;
1685 lo -= (us < 0);
1686 us += (us < 0) * 1000000;
1687 hi -= (lo < 0);
1688 lo += (lo < 0) << LO_TIME_BITS;
1689 result->hi = hi;
1690 result->lo = lo;
1691 result->us = us;
1692 result->ps = ps;
1693 return true;
1694 }
1695
1696 /* From the time components HIGH, LOW, USEC and PSEC taken from a Lisp
1697 list, generate the corresponding time value.
1698 If LOW is floating point, the other components should be zero.
1699
1700 If RESULT is not null, store into *RESULT the converted time.
1701 If *DRESULT is not null, store into *DRESULT the number of
1702 seconds since the start of the POSIX Epoch.
1703
1704 Return true if successful, false if the components are of the
1705 wrong type or represent a time out of range. */
1706 bool
1707 decode_time_components (Lisp_Object high, Lisp_Object low, Lisp_Object usec,
1708 Lisp_Object psec,
1709 struct lisp_time *result, double *dresult)
1710 {
1711 EMACS_INT hi, lo, us, ps;
1712 if (! (INTEGERP (high)
1713 && INTEGERP (usec) && INTEGERP (psec)))
1714 return false;
1715 if (! INTEGERP (low))
1716 {
1717 if (FLOATP (low))
1718 {
1719 double t = XFLOAT_DATA (low);
1720 if (result && ! decode_float_time (t, result))
1721 return false;
1722 if (dresult)
1723 *dresult = t;
1724 return true;
1725 }
1726 else if (NILP (low))
1727 {
1728 struct timespec now = current_timespec ();
1729 if (result)
1730 {
1731 result->hi = hi_time (now.tv_sec);
1732 result->lo = lo_time (now.tv_sec);
1733 result->us = now.tv_nsec / 1000;
1734 result->ps = now.tv_nsec % 1000 * 1000;
1735 }
1736 if (dresult)
1737 *dresult = now.tv_sec + now.tv_nsec / 1e9;
1738 return true;
1739 }
1740 else
1741 return false;
1742 }
1743
1744 hi = XINT (high);
1745 lo = XINT (low);
1746 us = XINT (usec);
1747 ps = XINT (psec);
1748
1749 /* Normalize out-of-range lower-order components by carrying
1750 each overflow into the next higher-order component. */
1751 us += ps / 1000000 - (ps % 1000000 < 0);
1752 lo += us / 1000000 - (us % 1000000 < 0);
1753 hi += lo >> LO_TIME_BITS;
1754 ps = ps % 1000000 + 1000000 * (ps % 1000000 < 0);
1755 us = us % 1000000 + 1000000 * (us % 1000000 < 0);
1756 lo &= (1 << LO_TIME_BITS) - 1;
1757
1758 if (result)
1759 {
1760 if (! (MOST_NEGATIVE_FIXNUM <= hi && hi <= MOST_POSITIVE_FIXNUM))
1761 return false;
1762 result->hi = hi;
1763 result->lo = lo;
1764 result->us = us;
1765 result->ps = ps;
1766 }
1767
1768 if (dresult)
1769 {
1770 double dhi = hi;
1771 *dresult = (us * 1e6 + ps) / 1e12 + lo + dhi * (1 << LO_TIME_BITS);
1772 }
1773
1774 return true;
1775 }
1776
1777 struct timespec
1778 lisp_to_timespec (struct lisp_time t)
1779 {
1780 if (! ((TYPE_SIGNED (time_t) ? TIME_T_MIN >> LO_TIME_BITS <= t.hi : 0 <= t.hi)
1781 && t.hi <= TIME_T_MAX >> LO_TIME_BITS))
1782 return invalid_timespec ();
1783 time_t s = (t.hi << LO_TIME_BITS) + t.lo;
1784 int ns = t.us * 1000 + t.ps / 1000;
1785 return make_timespec (s, ns);
1786 }
1787
1788 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1789 Store its effective length into *PLEN.
1790 If SPECIFIED_TIME is nil, use the current time.
1791 Signal an error if SPECIFIED_TIME does not represent a time. */
1792 static struct lisp_time
1793 lisp_time_struct (Lisp_Object specified_time, int *plen)
1794 {
1795 Lisp_Object high, low, usec, psec;
1796 struct lisp_time t;
1797 int len = disassemble_lisp_time (specified_time, &high, &low, &usec, &psec);
1798 if (! (len && decode_time_components (high, low, usec, psec, &t, 0)))
1799 invalid_time ();
1800 *plen = len;
1801 return t;
1802 }
1803
1804 /* Like lisp_time_struct, except return a struct timespec.
1805 Discard any low-order digits. */
1806 struct timespec
1807 lisp_time_argument (Lisp_Object specified_time)
1808 {
1809 int len;
1810 struct lisp_time lt = lisp_time_struct (specified_time, &len);
1811 struct timespec t = lisp_to_timespec (lt);
1812 if (! timespec_valid_p (t))
1813 time_overflow ();
1814 return t;
1815 }
1816
1817 /* Like lisp_time_argument, except decode only the seconds part,
1818 and do not check the subseconds part. */
1819 static time_t
1820 lisp_seconds_argument (Lisp_Object specified_time)
1821 {
1822 Lisp_Object high, low, usec, psec;
1823 struct lisp_time t;
1824 if (! (disassemble_lisp_time (specified_time, &high, &low, &usec, &psec)
1825 && decode_time_components (high, low, make_number (0),
1826 make_number (0), &t, 0)))
1827 invalid_time ();
1828 if (! ((TYPE_SIGNED (time_t) ? TIME_T_MIN >> LO_TIME_BITS <= t.hi : 0 <= t.hi)
1829 && t.hi <= TIME_T_MAX >> LO_TIME_BITS))
1830 time_overflow ();
1831 return (t.hi << LO_TIME_BITS) + t.lo;
1832 }
1833
1834 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1835 doc: /* Return the current time, as a float number of seconds since the epoch.
1836 If SPECIFIED-TIME is given, it is the time to convert to float
1837 instead of the current time. The argument should have the form
1838 (HIGH LOW) or (HIGH LOW USEC) or (HIGH LOW USEC PSEC). Thus,
1839 you can use times from `current-time' and from `file-attributes'.
1840 SPECIFIED-TIME can also have the form (HIGH . LOW), but this is
1841 considered obsolete.
1842
1843 WARNING: Since the result is floating point, it may not be exact.
1844 If precise time stamps are required, use either `current-time',
1845 or (if you need time as a string) `format-time-string'. */)
1846 (Lisp_Object specified_time)
1847 {
1848 double t;
1849 Lisp_Object high, low, usec, psec;
1850 if (! (disassemble_lisp_time (specified_time, &high, &low, &usec, &psec)
1851 && decode_time_components (high, low, usec, psec, 0, &t)))
1852 invalid_time ();
1853 return make_float (t);
1854 }
1855
1856 /* Write information into buffer S of size MAXSIZE, according to the
1857 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1858 Default to Universal Time if UT, local time otherwise.
1859 Use NS as the number of nanoseconds in the %N directive.
1860 Return the number of bytes written, not including the terminating
1861 '\0'. If S is NULL, nothing will be written anywhere; so to
1862 determine how many bytes would be written, use NULL for S and
1863 ((size_t) -1) for MAXSIZE.
1864
1865 This function behaves like nstrftime, except it allows null
1866 bytes in FORMAT and it does not support nanoseconds. */
1867 static size_t
1868 emacs_nmemftime (char *s, size_t maxsize, const char *format,
1869 size_t format_len, const struct tm *tp, bool ut, int ns)
1870 {
1871 size_t total = 0;
1872
1873 /* Loop through all the null-terminated strings in the format
1874 argument. Normally there's just one null-terminated string, but
1875 there can be arbitrarily many, concatenated together, if the
1876 format contains '\0' bytes. nstrftime stops at the first
1877 '\0' byte so we must invoke it separately for each such string. */
1878 for (;;)
1879 {
1880 size_t len;
1881 size_t result;
1882
1883 if (s)
1884 s[0] = '\1';
1885
1886 result = nstrftime (s, maxsize, format, tp, ut, ns);
1887
1888 if (s)
1889 {
1890 if (result == 0 && s[0] != '\0')
1891 return 0;
1892 s += result + 1;
1893 }
1894
1895 maxsize -= result + 1;
1896 total += result;
1897 len = strlen (format);
1898 if (len == format_len)
1899 return total;
1900 total++;
1901 format += len + 1;
1902 format_len -= len + 1;
1903 }
1904 }
1905
1906 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1907 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
1908 TIME is specified as (HIGH LOW USEC PSEC), as returned by
1909 `current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
1910 is also still accepted.
1911 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1912 as Universal Time; nil means describe TIME in the local time zone.
1913 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1914 by text that describes the specified date and time in TIME:
1915
1916 %Y is the year, %y within the century, %C the century.
1917 %G is the year corresponding to the ISO week, %g within the century.
1918 %m is the numeric month.
1919 %b and %h are the locale's abbreviated month name, %B the full name.
1920 (%h is not supported on MS-Windows.)
1921 %d is the day of the month, zero-padded, %e is blank-padded.
1922 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1923 %a is the locale's abbreviated name of the day of week, %A the full name.
1924 %U is the week number starting on Sunday, %W starting on Monday,
1925 %V according to ISO 8601.
1926 %j is the day of the year.
1927
1928 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1929 only blank-padded, %l is like %I blank-padded.
1930 %p is the locale's equivalent of either AM or PM.
1931 %M is the minute.
1932 %S is the second.
1933 %N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
1934 %Z is the time zone name, %z is the numeric form.
1935 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1936
1937 %c is the locale's date and time format.
1938 %x is the locale's "preferred" date format.
1939 %D is like "%m/%d/%y".
1940 %F is the ISO 8601 date format (like "%Y-%m-%d").
1941
1942 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1943 %X is the locale's "preferred" time format.
1944
1945 Finally, %n is a newline, %t is a tab, %% is a literal %.
1946
1947 Certain flags and modifiers are available with some format controls.
1948 The flags are `_', `-', `^' and `#'. For certain characters X,
1949 %_X is like %X, but padded with blanks; %-X is like %X,
1950 but without padding. %^X is like %X, but with all textual
1951 characters up-cased; %#X is like %X, but with letter-case of
1952 all textual characters reversed.
1953 %NX (where N stands for an integer) is like %X,
1954 but takes up at least N (a number) positions.
1955 The modifiers are `E' and `O'. For certain characters X,
1956 %EX is a locale's alternative version of %X;
1957 %OX is like %X, but uses the locale's number symbols.
1958
1959 For example, to produce full ISO 8601 format, use "%FT%T%z".
1960
1961 usage: (format-time-string FORMAT-STRING &optional TIME UNIVERSAL) */)
1962 (Lisp_Object format_string, Lisp_Object timeval, Lisp_Object universal)
1963 {
1964 struct timespec t = lisp_time_argument (timeval);
1965 struct tm tm;
1966
1967 CHECK_STRING (format_string);
1968 format_string = code_convert_string_norecord (format_string,
1969 Vlocale_coding_system, 1);
1970 return format_time_string (SSDATA (format_string), SBYTES (format_string),
1971 t, ! NILP (universal), &tm);
1972 }
1973
1974 static Lisp_Object
1975 format_time_string (char const *format, ptrdiff_t formatlen,
1976 struct timespec t, bool ut, struct tm *tmp)
1977 {
1978 char buffer[4000];
1979 char *buf = buffer;
1980 ptrdiff_t size = sizeof buffer;
1981 size_t len;
1982 Lisp_Object bufstring;
1983 int ns = t.tv_nsec;
1984 USE_SAFE_ALLOCA;
1985
1986 tmp = ut ? gmtime_r (&t.tv_sec, tmp) : localtime_r (&t.tv_sec, tmp);
1987 if (! tmp)
1988 time_overflow ();
1989 synchronize_system_time_locale ();
1990
1991 while (true)
1992 {
1993 buf[0] = '\1';
1994 len = emacs_nmemftime (buf, size, format, formatlen, tmp, ut, ns);
1995 if ((0 < len && len < size) || (len == 0 && buf[0] == '\0'))
1996 break;
1997
1998 /* Buffer was too small, so make it bigger and try again. */
1999 len = emacs_nmemftime (NULL, SIZE_MAX, format, formatlen, tmp, ut, ns);
2000 if (STRING_BYTES_BOUND <= len)
2001 string_overflow ();
2002 size = len + 1;
2003 buf = SAFE_ALLOCA (size);
2004 }
2005
2006 bufstring = make_unibyte_string (buf, len);
2007 SAFE_FREE ();
2008 return code_convert_string_norecord (bufstring, Vlocale_coding_system, 0);
2009 }
2010
2011 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
2012 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
2013 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
2014 as from `current-time' and `file-attributes', or nil to use the
2015 current time. The obsolete form (HIGH . LOW) is also still accepted.
2016 The list has the following nine members: SEC is an integer between 0
2017 and 60; SEC is 60 for a leap second, which only some operating systems
2018 support. MINUTE is an integer between 0 and 59. HOUR is an integer
2019 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
2020 integer between 1 and 12. YEAR is an integer indicating the
2021 four-digit year. DOW is the day of week, an integer between 0 and 6,
2022 where 0 is Sunday. DST is t if daylight saving time is in effect,
2023 otherwise nil. ZONE is an integer indicating the number of seconds
2024 east of Greenwich. (Note that Common Lisp has different meanings for
2025 DOW and ZONE.) */)
2026 (Lisp_Object specified_time)
2027 {
2028 time_t time_spec = lisp_seconds_argument (specified_time);
2029 struct tm local_tm, gmt_tm;
2030
2031 if (! (localtime_r (&time_spec, &local_tm)
2032 && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= local_tm.tm_year
2033 && local_tm.tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE))
2034 time_overflow ();
2035
2036 /* Avoid overflow when INT_MAX < EMACS_INT_MAX. */
2037 EMACS_INT tm_year_base = TM_YEAR_BASE;
2038
2039 return Flist (9, ((Lisp_Object [])
2040 {make_number (local_tm.tm_sec),
2041 make_number (local_tm.tm_min),
2042 make_number (local_tm.tm_hour),
2043 make_number (local_tm.tm_mday),
2044 make_number (local_tm.tm_mon + 1),
2045 make_number (local_tm.tm_year + tm_year_base),
2046 make_number (local_tm.tm_wday),
2047 local_tm.tm_isdst ? Qt : Qnil,
2048 (HAVE_TM_GMTOFF
2049 ? make_number (tm_gmtoff (&local_tm))
2050 : gmtime_r (&time_spec, &gmt_tm)
2051 ? make_number (tm_diff (&local_tm, &gmt_tm))
2052 : Qnil)}));
2053 }
2054
2055 /* Return OBJ - OFFSET, checking that OBJ is a valid fixnum and that
2056 the result is representable as an int. Assume OFFSET is small and
2057 nonnegative. */
2058 static int
2059 check_tm_member (Lisp_Object obj, int offset)
2060 {
2061 EMACS_INT n;
2062 CHECK_NUMBER (obj);
2063 n = XINT (obj);
2064 if (! (INT_MIN + offset <= n && n - offset <= INT_MAX))
2065 time_overflow ();
2066 return n - offset;
2067 }
2068
2069 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
2070 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
2071 This is the reverse operation of `decode-time', which see.
2072 ZONE defaults to the current time zone rule. This can
2073 be a string or t (as from `set-time-zone-rule'), or it can be a list
2074 \(as from `current-time-zone') or an integer (as from `decode-time')
2075 applied without consideration for daylight saving time.
2076
2077 You can pass more than 7 arguments; then the first six arguments
2078 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
2079 The intervening arguments are ignored.
2080 This feature lets (apply 'encode-time (decode-time ...)) work.
2081
2082 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
2083 for example, a DAY of 0 means the day preceding the given month.
2084 Year numbers less than 100 are treated just like other year numbers.
2085 If you want them to stand for years in this century, you must do that yourself.
2086
2087 Years before 1970 are not guaranteed to work. On some systems,
2088 year values as low as 1901 do work.
2089
2090 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
2091 (ptrdiff_t nargs, Lisp_Object *args)
2092 {
2093 time_t value;
2094 struct tm tm;
2095 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
2096
2097 tm.tm_sec = check_tm_member (args[0], 0);
2098 tm.tm_min = check_tm_member (args[1], 0);
2099 tm.tm_hour = check_tm_member (args[2], 0);
2100 tm.tm_mday = check_tm_member (args[3], 0);
2101 tm.tm_mon = check_tm_member (args[4], 1);
2102 tm.tm_year = check_tm_member (args[5], TM_YEAR_BASE);
2103 tm.tm_isdst = -1;
2104
2105 if (CONSP (zone))
2106 zone = XCAR (zone);
2107 if (NILP (zone))
2108 value = mktime (&tm);
2109 else
2110 {
2111 static char const tzbuf_format[] = "XXX%s%"pI"d:%02d:%02d";
2112 char tzbuf[sizeof tzbuf_format + INT_STRLEN_BOUND (EMACS_INT)];
2113 const char *tzstring;
2114
2115 if (EQ (zone, Qt))
2116 tzstring = "UTC0";
2117 else if (STRINGP (zone))
2118 tzstring = SSDATA (zone);
2119 else if (INTEGERP (zone))
2120 {
2121 EMACS_INT abszone = eabs (XINT (zone));
2122 EMACS_INT zone_hr = abszone / (60*60);
2123 int zone_min = (abszone/60) % 60;
2124 int zone_sec = abszone % 60;
2125 sprintf (tzbuf, tzbuf_format, &"-"[XINT (zone) < 0],
2126 zone_hr, zone_min, zone_sec);
2127 tzstring = tzbuf;
2128 }
2129 else
2130 tzstring = 0;
2131
2132 timezone_t tz = tzstring ? tzalloc (tzstring) : 0;
2133 if (! tz)
2134 error ("Invalid time zone specification");
2135 value = mktime_z (tz, &tm);
2136 tzfree (tz);
2137 }
2138
2139 if (value == (time_t) -1)
2140 time_overflow ();
2141
2142 return list2i (hi_time (value), lo_time (value));
2143 }
2144
2145 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
2146 doc: /* Return the current local time, as a human-readable string.
2147 Programs can use this function to decode a time,
2148 since the number of columns in each field is fixed
2149 if the year is in the range 1000-9999.
2150 The format is `Sun Sep 16 01:03:52 1973'.
2151 However, see also the functions `decode-time' and `format-time-string'
2152 which provide a much more powerful and general facility.
2153
2154 If SPECIFIED-TIME is given, it is a time to format instead of the
2155 current time. The argument should have the form (HIGH LOW . IGNORED).
2156 Thus, you can use times obtained from `current-time' and from
2157 `file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
2158 but this is considered obsolete. */)
2159 (Lisp_Object specified_time)
2160 {
2161 time_t value = lisp_seconds_argument (specified_time);
2162
2163 /* Convert to a string in ctime format, except without the trailing
2164 newline, and without the 4-digit year limit. Don't use asctime
2165 or ctime, as they might dump core if the year is outside the
2166 range -999 .. 9999. */
2167 struct tm tm;
2168 if (! localtime_r (&value, &tm))
2169 time_overflow ();
2170
2171 static char const wday_name[][4] =
2172 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
2173 static char const mon_name[][4] =
2174 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2175 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
2176 printmax_t year_base = TM_YEAR_BASE;
2177 char buf[sizeof "Mon Apr 30 12:49:17 " + INT_STRLEN_BOUND (int) + 1];
2178 int len = sprintf (buf, "%s %s%3d %02d:%02d:%02d %"pMd,
2179 wday_name[tm.tm_wday], mon_name[tm.tm_mon], tm.tm_mday,
2180 tm.tm_hour, tm.tm_min, tm.tm_sec,
2181 tm.tm_year + year_base);
2182
2183 return make_unibyte_string (buf, len);
2184 }
2185
2186 /* Yield A - B, measured in seconds.
2187 This function is copied from the GNU C Library. */
2188 static int
2189 tm_diff (struct tm *a, struct tm *b)
2190 {
2191 /* Compute intervening leap days correctly even if year is negative.
2192 Take care to avoid int overflow in leap day calculations,
2193 but it's OK to assume that A and B are close to each other. */
2194 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2195 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2196 int a100 = a4 / 25 - (a4 % 25 < 0);
2197 int b100 = b4 / 25 - (b4 % 25 < 0);
2198 int a400 = a100 >> 2;
2199 int b400 = b100 >> 2;
2200 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2201 int years = a->tm_year - b->tm_year;
2202 int days = (365 * years + intervening_leap_days
2203 + (a->tm_yday - b->tm_yday));
2204 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2205 + (a->tm_min - b->tm_min))
2206 + (a->tm_sec - b->tm_sec));
2207 }
2208
2209 /* Yield A's UTC offset, or an unspecified value if unknown. */
2210 static long int
2211 tm_gmtoff (struct tm *a)
2212 {
2213 #if HAVE_TM_GMTOFF
2214 return a->tm_gmtoff;
2215 #else
2216 return 0;
2217 #endif
2218 }
2219
2220 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
2221 doc: /* Return the offset and name for the local time zone.
2222 This returns a list of the form (OFFSET NAME).
2223 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
2224 A negative value means west of Greenwich.
2225 NAME is a string giving the name of the time zone.
2226 If SPECIFIED-TIME is given, the time zone offset is determined from it
2227 instead of using the current time. The argument should have the form
2228 (HIGH LOW . IGNORED). Thus, you can use times obtained from
2229 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
2230 have the form (HIGH . LOW), but this is considered obsolete.
2231
2232 Some operating systems cannot provide all this information to Emacs;
2233 in this case, `current-time-zone' returns a list containing nil for
2234 the data it can't find. */)
2235 (Lisp_Object specified_time)
2236 {
2237 struct timespec value;
2238 struct tm local_tm, gmt_tm;
2239 Lisp_Object zone_offset, zone_name;
2240
2241 zone_offset = Qnil;
2242 value = make_timespec (lisp_seconds_argument (specified_time), 0);
2243 zone_name = format_time_string ("%Z", sizeof "%Z" - 1, value, 0, &local_tm);
2244
2245 if (HAVE_TM_GMTOFF || gmtime_r (&value.tv_sec, &gmt_tm))
2246 {
2247 long int offset = (HAVE_TM_GMTOFF
2248 ? tm_gmtoff (&local_tm)
2249 : tm_diff (&local_tm, &gmt_tm));
2250 zone_offset = make_number (offset);
2251 if (SCHARS (zone_name) == 0)
2252 {
2253 /* No local time zone name is available; use "+-NNNN" instead. */
2254 long int m = offset / 60;
2255 long int am = offset < 0 ? - m : m;
2256 long int hour = am / 60;
2257 int min = am % 60;
2258 char buf[sizeof "+00" + INT_STRLEN_BOUND (long int)];
2259 zone_name = make_formatted_string (buf, "%c%02ld%02d",
2260 (offset < 0 ? '-' : '+'),
2261 hour, min);
2262 }
2263 }
2264
2265 return list2 (zone_offset, zone_name);
2266 }
2267
2268 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2269 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
2270 If TZ is nil, use implementation-defined default time zone information.
2271 If TZ is t, use Universal Time.
2272
2273 Instead of calling this function, you typically want (setenv "TZ" TZ).
2274 That changes both the environment of the Emacs process and the
2275 variable `process-environment', whereas `set-time-zone-rule' affects
2276 only the former. */)
2277 (Lisp_Object tz)
2278 {
2279 const char *tzstring;
2280
2281 if (! (NILP (tz) || EQ (tz, Qt)))
2282 CHECK_STRING (tz);
2283
2284 if (NILP (tz))
2285 tzstring = initial_tz;
2286 else if (EQ (tz, Qt))
2287 tzstring = "UTC0";
2288 else
2289 tzstring = SSDATA (tz);
2290
2291 block_input ();
2292 set_time_zone_rule (tzstring);
2293 unblock_input ();
2294
2295 return Qnil;
2296 }
2297
2298 /* Set the local time zone rule to TZSTRING.
2299
2300 This function is not thread-safe, in theory because putenv is not,
2301 but mostly because of the static storage it updates. Other threads
2302 that invoke localtime etc. may be adversely affected while this
2303 function is executing. */
2304
2305 static void
2306 set_time_zone_rule (const char *tzstring)
2307 {
2308 /* A buffer holding a string of the form "TZ=value", intended
2309 to be part of the environment. */
2310 static char *tzvalbuf;
2311 static ptrdiff_t tzvalbufsize;
2312
2313 int tzeqlen = sizeof "TZ=" - 1;
2314 ptrdiff_t tzstringlen = tzstring ? strlen (tzstring) : 0;
2315 char *tzval = tzvalbuf;
2316 bool new_tzvalbuf = tzvalbufsize <= tzeqlen + tzstringlen;
2317
2318 if (new_tzvalbuf)
2319 {
2320 /* Do not attempt to free the old tzvalbuf, since another thread
2321 may be using it. In practice, the first allocation is large
2322 enough and memory does not leak. */
2323 tzval = xpalloc (NULL, &tzvalbufsize,
2324 tzeqlen + tzstringlen - tzvalbufsize + 1, -1, 1);
2325 tzvalbuf = tzval;
2326 tzval[1] = 'Z';
2327 tzval[2] = '=';
2328 }
2329
2330 if (tzstring)
2331 {
2332 /* Modify TZVAL in place. Although this is dicey in a
2333 multithreaded environment, we know of no portable alternative.
2334 Calling putenv or setenv could crash some other thread. */
2335 tzval[0] = 'T';
2336 strcpy (tzval + tzeqlen, tzstring);
2337 }
2338 else
2339 {
2340 /* Turn 'TZ=whatever' into an empty environment variable 'tZ='.
2341 Although this is also dicey, calling unsetenv here can crash Emacs.
2342 See Bug#8705. */
2343 tzval[0] = 't';
2344 tzval[tzeqlen] = 0;
2345 }
2346
2347 if (new_tzvalbuf)
2348 {
2349 /* Although this is not thread-safe, in practice this runs only
2350 on startup when there is only one thread. */
2351 xputenv (tzval);
2352 }
2353
2354 #ifdef HAVE_TZSET
2355 tzset ();
2356 #endif
2357 }
2358 \f
2359 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2360 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2361 type of object is Lisp_String). INHERIT is passed to
2362 INSERT_FROM_STRING_FUNC as the last argument. */
2363
2364 static void
2365 general_insert_function (void (*insert_func)
2366 (const char *, ptrdiff_t),
2367 void (*insert_from_string_func)
2368 (Lisp_Object, ptrdiff_t, ptrdiff_t,
2369 ptrdiff_t, ptrdiff_t, bool),
2370 bool inherit, ptrdiff_t nargs, Lisp_Object *args)
2371 {
2372 ptrdiff_t argnum;
2373 Lisp_Object val;
2374
2375 for (argnum = 0; argnum < nargs; argnum++)
2376 {
2377 val = args[argnum];
2378 if (CHARACTERP (val))
2379 {
2380 int c = XFASTINT (val);
2381 unsigned char str[MAX_MULTIBYTE_LENGTH];
2382 int len;
2383
2384 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2385 len = CHAR_STRING (c, str);
2386 else
2387 {
2388 str[0] = CHAR_TO_BYTE8 (c);
2389 len = 1;
2390 }
2391 (*insert_func) ((char *) str, len);
2392 }
2393 else if (STRINGP (val))
2394 {
2395 (*insert_from_string_func) (val, 0, 0,
2396 SCHARS (val),
2397 SBYTES (val),
2398 inherit);
2399 }
2400 else
2401 wrong_type_argument (Qchar_or_string_p, val);
2402 }
2403 }
2404
2405 void
2406 insert1 (Lisp_Object arg)
2407 {
2408 Finsert (1, &arg);
2409 }
2410
2411
2412 /* Callers passing one argument to Finsert need not gcpro the
2413 argument "array", since the only element of the array will
2414 not be used after calling insert or insert_from_string, so
2415 we don't care if it gets trashed. */
2416
2417 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2418 doc: /* Insert the arguments, either strings or characters, at point.
2419 Point and before-insertion markers move forward to end up
2420 after the inserted text.
2421 Any other markers at the point of insertion remain before the text.
2422
2423 If the current buffer is multibyte, unibyte strings are converted
2424 to multibyte for insertion (see `string-make-multibyte').
2425 If the current buffer is unibyte, multibyte strings are converted
2426 to unibyte for insertion (see `string-make-unibyte').
2427
2428 When operating on binary data, it may be necessary to preserve the
2429 original bytes of a unibyte string when inserting it into a multibyte
2430 buffer; to accomplish this, apply `string-as-multibyte' to the string
2431 and insert the result.
2432
2433 usage: (insert &rest ARGS) */)
2434 (ptrdiff_t nargs, Lisp_Object *args)
2435 {
2436 general_insert_function (insert, insert_from_string, 0, nargs, args);
2437 return Qnil;
2438 }
2439
2440 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2441 0, MANY, 0,
2442 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2443 Point and before-insertion markers move forward to end up
2444 after the inserted text.
2445 Any other markers at the point of insertion remain before the text.
2446
2447 If the current buffer is multibyte, unibyte strings are converted
2448 to multibyte for insertion (see `unibyte-char-to-multibyte').
2449 If the current buffer is unibyte, multibyte strings are converted
2450 to unibyte for insertion.
2451
2452 usage: (insert-and-inherit &rest ARGS) */)
2453 (ptrdiff_t nargs, Lisp_Object *args)
2454 {
2455 general_insert_function (insert_and_inherit, insert_from_string, 1,
2456 nargs, args);
2457 return Qnil;
2458 }
2459
2460 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2461 doc: /* Insert strings or characters at point, relocating markers after the text.
2462 Point and markers move forward to end up after the inserted text.
2463
2464 If the current buffer is multibyte, unibyte strings are converted
2465 to multibyte for insertion (see `unibyte-char-to-multibyte').
2466 If the current buffer is unibyte, multibyte strings are converted
2467 to unibyte for insertion.
2468
2469 If an overlay begins at the insertion point, the inserted text falls
2470 outside the overlay; if a nonempty overlay ends at the insertion
2471 point, the inserted text falls inside that overlay.
2472
2473 usage: (insert-before-markers &rest ARGS) */)
2474 (ptrdiff_t nargs, Lisp_Object *args)
2475 {
2476 general_insert_function (insert_before_markers,
2477 insert_from_string_before_markers, 0,
2478 nargs, args);
2479 return Qnil;
2480 }
2481
2482 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2483 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2484 doc: /* Insert text at point, relocating markers and inheriting properties.
2485 Point and markers move forward to end up after the inserted text.
2486
2487 If the current buffer is multibyte, unibyte strings are converted
2488 to multibyte for insertion (see `unibyte-char-to-multibyte').
2489 If the current buffer is unibyte, multibyte strings are converted
2490 to unibyte for insertion.
2491
2492 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2493 (ptrdiff_t nargs, Lisp_Object *args)
2494 {
2495 general_insert_function (insert_before_markers_and_inherit,
2496 insert_from_string_before_markers, 1,
2497 nargs, args);
2498 return Qnil;
2499 }
2500 \f
2501 DEFUN ("insert-char", Finsert_char, Sinsert_char, 1, 3,
2502 "(list (read-char-by-name \"Insert character (Unicode name or hex): \")\
2503 (prefix-numeric-value current-prefix-arg)\
2504 t))",
2505 doc: /* Insert COUNT copies of CHARACTER.
2506 Interactively, prompt for CHARACTER. You can specify CHARACTER in one
2507 of these ways:
2508
2509 - As its Unicode character name, e.g. \"LATIN SMALL LETTER A\".
2510 Completion is available; if you type a substring of the name
2511 preceded by an asterisk `*', Emacs shows all names which include
2512 that substring, not necessarily at the beginning of the name.
2513
2514 - As a hexadecimal code point, e.g. 263A. Note that code points in
2515 Emacs are equivalent to Unicode up to 10FFFF (which is the limit of
2516 the Unicode code space).
2517
2518 - As a code point with a radix specified with #, e.g. #o21430
2519 (octal), #x2318 (hex), or #10r8984 (decimal).
2520
2521 If called interactively, COUNT is given by the prefix argument. If
2522 omitted or nil, it defaults to 1.
2523
2524 Inserting the character(s) relocates point and before-insertion
2525 markers in the same ways as the function `insert'.
2526
2527 The optional third argument INHERIT, if non-nil, says to inherit text
2528 properties from adjoining text, if those properties are sticky. If
2529 called interactively, INHERIT is t. */)
2530 (Lisp_Object character, Lisp_Object count, Lisp_Object inherit)
2531 {
2532 int i, stringlen;
2533 register ptrdiff_t n;
2534 int c, len;
2535 unsigned char str[MAX_MULTIBYTE_LENGTH];
2536 char string[4000];
2537
2538 CHECK_CHARACTER (character);
2539 if (NILP (count))
2540 XSETFASTINT (count, 1);
2541 CHECK_NUMBER (count);
2542 c = XFASTINT (character);
2543
2544 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2545 len = CHAR_STRING (c, str);
2546 else
2547 str[0] = c, len = 1;
2548 if (XINT (count) <= 0)
2549 return Qnil;
2550 if (BUF_BYTES_MAX / len < XINT (count))
2551 buffer_overflow ();
2552 n = XINT (count) * len;
2553 stringlen = min (n, sizeof string - sizeof string % len);
2554 for (i = 0; i < stringlen; i++)
2555 string[i] = str[i % len];
2556 while (n > stringlen)
2557 {
2558 QUIT;
2559 if (!NILP (inherit))
2560 insert_and_inherit (string, stringlen);
2561 else
2562 insert (string, stringlen);
2563 n -= stringlen;
2564 }
2565 if (!NILP (inherit))
2566 insert_and_inherit (string, n);
2567 else
2568 insert (string, n);
2569 return Qnil;
2570 }
2571
2572 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2573 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2574 Both arguments are required.
2575 BYTE is a number of the range 0..255.
2576
2577 If BYTE is 128..255 and the current buffer is multibyte, the
2578 corresponding eight-bit character is inserted.
2579
2580 Point, and before-insertion markers, are relocated as in the function `insert'.
2581 The optional third arg INHERIT, if non-nil, says to inherit text properties
2582 from adjoining text, if those properties are sticky. */)
2583 (Lisp_Object byte, Lisp_Object count, Lisp_Object inherit)
2584 {
2585 CHECK_NUMBER (byte);
2586 if (XINT (byte) < 0 || XINT (byte) > 255)
2587 args_out_of_range_3 (byte, make_number (0), make_number (255));
2588 if (XINT (byte) >= 128
2589 && ! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2590 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2591 return Finsert_char (byte, count, inherit);
2592 }
2593
2594 \f
2595 /* Making strings from buffer contents. */
2596
2597 /* Return a Lisp_String containing the text of the current buffer from
2598 START to END. If text properties are in use and the current buffer
2599 has properties in the range specified, the resulting string will also
2600 have them, if PROPS is true.
2601
2602 We don't want to use plain old make_string here, because it calls
2603 make_uninit_string, which can cause the buffer arena to be
2604 compacted. make_string has no way of knowing that the data has
2605 been moved, and thus copies the wrong data into the string. This
2606 doesn't effect most of the other users of make_string, so it should
2607 be left as is. But we should use this function when conjuring
2608 buffer substrings. */
2609
2610 Lisp_Object
2611 make_buffer_string (ptrdiff_t start, ptrdiff_t end, bool props)
2612 {
2613 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
2614 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
2615
2616 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2617 }
2618
2619 /* Return a Lisp_String containing the text of the current buffer from
2620 START / START_BYTE to END / END_BYTE.
2621
2622 If text properties are in use and the current buffer
2623 has properties in the range specified, the resulting string will also
2624 have them, if PROPS is true.
2625
2626 We don't want to use plain old make_string here, because it calls
2627 make_uninit_string, which can cause the buffer arena to be
2628 compacted. make_string has no way of knowing that the data has
2629 been moved, and thus copies the wrong data into the string. This
2630 doesn't effect most of the other users of make_string, so it should
2631 be left as is. But we should use this function when conjuring
2632 buffer substrings. */
2633
2634 Lisp_Object
2635 make_buffer_string_both (ptrdiff_t start, ptrdiff_t start_byte,
2636 ptrdiff_t end, ptrdiff_t end_byte, bool props)
2637 {
2638 Lisp_Object result, tem, tem1;
2639
2640 if (start < GPT && GPT < end)
2641 move_gap_both (start, start_byte);
2642
2643 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2644 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2645 else
2646 result = make_uninit_string (end - start);
2647 memcpy (SDATA (result), BYTE_POS_ADDR (start_byte), end_byte - start_byte);
2648
2649 /* If desired, update and copy the text properties. */
2650 if (props)
2651 {
2652 update_buffer_properties (start, end);
2653
2654 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2655 tem1 = Ftext_properties_at (make_number (start), Qnil);
2656
2657 if (XINT (tem) != end || !NILP (tem1))
2658 copy_intervals_to_string (result, current_buffer, start,
2659 end - start);
2660 }
2661
2662 return result;
2663 }
2664
2665 /* Call Vbuffer_access_fontify_functions for the range START ... END
2666 in the current buffer, if necessary. */
2667
2668 static void
2669 update_buffer_properties (ptrdiff_t start, ptrdiff_t end)
2670 {
2671 /* If this buffer has some access functions,
2672 call them, specifying the range of the buffer being accessed. */
2673 if (!NILP (Vbuffer_access_fontify_functions))
2674 {
2675 Lisp_Object args[3];
2676 Lisp_Object tem;
2677
2678 args[0] = Qbuffer_access_fontify_functions;
2679 XSETINT (args[1], start);
2680 XSETINT (args[2], end);
2681
2682 /* But don't call them if we can tell that the work
2683 has already been done. */
2684 if (!NILP (Vbuffer_access_fontified_property))
2685 {
2686 tem = Ftext_property_any (args[1], args[2],
2687 Vbuffer_access_fontified_property,
2688 Qnil, Qnil);
2689 if (! NILP (tem))
2690 Frun_hook_with_args (3, args);
2691 }
2692 else
2693 Frun_hook_with_args (3, args);
2694 }
2695 }
2696
2697 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2698 doc: /* Return the contents of part of the current buffer as a string.
2699 The two arguments START and END are character positions;
2700 they can be in either order.
2701 The string returned is multibyte if the buffer is multibyte.
2702
2703 This function copies the text properties of that part of the buffer
2704 into the result string; if you don't want the text properties,
2705 use `buffer-substring-no-properties' instead. */)
2706 (Lisp_Object start, Lisp_Object end)
2707 {
2708 register ptrdiff_t b, e;
2709
2710 validate_region (&start, &end);
2711 b = XINT (start);
2712 e = XINT (end);
2713
2714 return make_buffer_string (b, e, 1);
2715 }
2716
2717 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2718 Sbuffer_substring_no_properties, 2, 2, 0,
2719 doc: /* Return the characters of part of the buffer, without the text properties.
2720 The two arguments START and END are character positions;
2721 they can be in either order. */)
2722 (Lisp_Object start, Lisp_Object end)
2723 {
2724 register ptrdiff_t b, e;
2725
2726 validate_region (&start, &end);
2727 b = XINT (start);
2728 e = XINT (end);
2729
2730 return make_buffer_string (b, e, 0);
2731 }
2732
2733 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2734 doc: /* Return the contents of the current buffer as a string.
2735 If narrowing is in effect, this function returns only the visible part
2736 of the buffer. */)
2737 (void)
2738 {
2739 return make_buffer_string_both (BEGV, BEGV_BYTE, ZV, ZV_BYTE, 1);
2740 }
2741
2742 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2743 1, 3, 0,
2744 doc: /* Insert before point a substring of the contents of BUFFER.
2745 BUFFER may be a buffer or a buffer name.
2746 Arguments START and END are character positions specifying the substring.
2747 They default to the values of (point-min) and (point-max) in BUFFER. */)
2748 (Lisp_Object buffer, Lisp_Object start, Lisp_Object end)
2749 {
2750 register EMACS_INT b, e, temp;
2751 register struct buffer *bp, *obuf;
2752 Lisp_Object buf;
2753
2754 buf = Fget_buffer (buffer);
2755 if (NILP (buf))
2756 nsberror (buffer);
2757 bp = XBUFFER (buf);
2758 if (!BUFFER_LIVE_P (bp))
2759 error ("Selecting deleted buffer");
2760
2761 if (NILP (start))
2762 b = BUF_BEGV (bp);
2763 else
2764 {
2765 CHECK_NUMBER_COERCE_MARKER (start);
2766 b = XINT (start);
2767 }
2768 if (NILP (end))
2769 e = BUF_ZV (bp);
2770 else
2771 {
2772 CHECK_NUMBER_COERCE_MARKER (end);
2773 e = XINT (end);
2774 }
2775
2776 if (b > e)
2777 temp = b, b = e, e = temp;
2778
2779 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2780 args_out_of_range (start, end);
2781
2782 obuf = current_buffer;
2783 set_buffer_internal_1 (bp);
2784 update_buffer_properties (b, e);
2785 set_buffer_internal_1 (obuf);
2786
2787 insert_from_buffer (bp, b, e - b, 0);
2788 return Qnil;
2789 }
2790
2791 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2792 6, 6, 0,
2793 doc: /* Compare two substrings of two buffers; return result as number.
2794 Return -N if first string is less after N-1 chars, +N if first string is
2795 greater after N-1 chars, or 0 if strings match. Each substring is
2796 represented as three arguments: BUFFER, START and END. That makes six
2797 args in all, three for each substring.
2798
2799 The value of `case-fold-search' in the current buffer
2800 determines whether case is significant or ignored. */)
2801 (Lisp_Object buffer1, Lisp_Object start1, Lisp_Object end1, Lisp_Object buffer2, Lisp_Object start2, Lisp_Object end2)
2802 {
2803 register EMACS_INT begp1, endp1, begp2, endp2, temp;
2804 register struct buffer *bp1, *bp2;
2805 register Lisp_Object trt
2806 = (!NILP (BVAR (current_buffer, case_fold_search))
2807 ? BVAR (current_buffer, case_canon_table) : Qnil);
2808 ptrdiff_t chars = 0;
2809 ptrdiff_t i1, i2, i1_byte, i2_byte;
2810
2811 /* Find the first buffer and its substring. */
2812
2813 if (NILP (buffer1))
2814 bp1 = current_buffer;
2815 else
2816 {
2817 Lisp_Object buf1;
2818 buf1 = Fget_buffer (buffer1);
2819 if (NILP (buf1))
2820 nsberror (buffer1);
2821 bp1 = XBUFFER (buf1);
2822 if (!BUFFER_LIVE_P (bp1))
2823 error ("Selecting deleted buffer");
2824 }
2825
2826 if (NILP (start1))
2827 begp1 = BUF_BEGV (bp1);
2828 else
2829 {
2830 CHECK_NUMBER_COERCE_MARKER (start1);
2831 begp1 = XINT (start1);
2832 }
2833 if (NILP (end1))
2834 endp1 = BUF_ZV (bp1);
2835 else
2836 {
2837 CHECK_NUMBER_COERCE_MARKER (end1);
2838 endp1 = XINT (end1);
2839 }
2840
2841 if (begp1 > endp1)
2842 temp = begp1, begp1 = endp1, endp1 = temp;
2843
2844 if (!(BUF_BEGV (bp1) <= begp1
2845 && begp1 <= endp1
2846 && endp1 <= BUF_ZV (bp1)))
2847 args_out_of_range (start1, end1);
2848
2849 /* Likewise for second substring. */
2850
2851 if (NILP (buffer2))
2852 bp2 = current_buffer;
2853 else
2854 {
2855 Lisp_Object buf2;
2856 buf2 = Fget_buffer (buffer2);
2857 if (NILP (buf2))
2858 nsberror (buffer2);
2859 bp2 = XBUFFER (buf2);
2860 if (!BUFFER_LIVE_P (bp2))
2861 error ("Selecting deleted buffer");
2862 }
2863
2864 if (NILP (start2))
2865 begp2 = BUF_BEGV (bp2);
2866 else
2867 {
2868 CHECK_NUMBER_COERCE_MARKER (start2);
2869 begp2 = XINT (start2);
2870 }
2871 if (NILP (end2))
2872 endp2 = BUF_ZV (bp2);
2873 else
2874 {
2875 CHECK_NUMBER_COERCE_MARKER (end2);
2876 endp2 = XINT (end2);
2877 }
2878
2879 if (begp2 > endp2)
2880 temp = begp2, begp2 = endp2, endp2 = temp;
2881
2882 if (!(BUF_BEGV (bp2) <= begp2
2883 && begp2 <= endp2
2884 && endp2 <= BUF_ZV (bp2)))
2885 args_out_of_range (start2, end2);
2886
2887 i1 = begp1;
2888 i2 = begp2;
2889 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2890 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2891
2892 while (i1 < endp1 && i2 < endp2)
2893 {
2894 /* When we find a mismatch, we must compare the
2895 characters, not just the bytes. */
2896 int c1, c2;
2897
2898 QUIT;
2899
2900 if (! NILP (BVAR (bp1, enable_multibyte_characters)))
2901 {
2902 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2903 BUF_INC_POS (bp1, i1_byte);
2904 i1++;
2905 }
2906 else
2907 {
2908 c1 = BUF_FETCH_BYTE (bp1, i1);
2909 MAKE_CHAR_MULTIBYTE (c1);
2910 i1++;
2911 }
2912
2913 if (! NILP (BVAR (bp2, enable_multibyte_characters)))
2914 {
2915 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2916 BUF_INC_POS (bp2, i2_byte);
2917 i2++;
2918 }
2919 else
2920 {
2921 c2 = BUF_FETCH_BYTE (bp2, i2);
2922 MAKE_CHAR_MULTIBYTE (c2);
2923 i2++;
2924 }
2925
2926 if (!NILP (trt))
2927 {
2928 c1 = char_table_translate (trt, c1);
2929 c2 = char_table_translate (trt, c2);
2930 }
2931 if (c1 < c2)
2932 return make_number (- 1 - chars);
2933 if (c1 > c2)
2934 return make_number (chars + 1);
2935
2936 chars++;
2937 }
2938
2939 /* The strings match as far as they go.
2940 If one is shorter, that one is less. */
2941 if (chars < endp1 - begp1)
2942 return make_number (chars + 1);
2943 else if (chars < endp2 - begp2)
2944 return make_number (- chars - 1);
2945
2946 /* Same length too => they are equal. */
2947 return make_number (0);
2948 }
2949 \f
2950 static void
2951 subst_char_in_region_unwind (Lisp_Object arg)
2952 {
2953 bset_undo_list (current_buffer, arg);
2954 }
2955
2956 static void
2957 subst_char_in_region_unwind_1 (Lisp_Object arg)
2958 {
2959 bset_filename (current_buffer, arg);
2960 }
2961
2962 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2963 Ssubst_char_in_region, 4, 5, 0,
2964 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
2965 If optional arg NOUNDO is non-nil, don't record this change for undo
2966 and don't mark the buffer as really changed.
2967 Both characters must have the same length of multi-byte form. */)
2968 (Lisp_Object start, Lisp_Object end, Lisp_Object fromchar, Lisp_Object tochar, Lisp_Object noundo)
2969 {
2970 register ptrdiff_t pos, pos_byte, stop, i, len, end_byte;
2971 /* Keep track of the first change in the buffer:
2972 if 0 we haven't found it yet.
2973 if < 0 we've found it and we've run the before-change-function.
2974 if > 0 we've actually performed it and the value is its position. */
2975 ptrdiff_t changed = 0;
2976 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2977 unsigned char *p;
2978 ptrdiff_t count = SPECPDL_INDEX ();
2979 #define COMBINING_NO 0
2980 #define COMBINING_BEFORE 1
2981 #define COMBINING_AFTER 2
2982 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2983 int maybe_byte_combining = COMBINING_NO;
2984 ptrdiff_t last_changed = 0;
2985 bool multibyte_p
2986 = !NILP (BVAR (current_buffer, enable_multibyte_characters));
2987 int fromc, toc;
2988
2989 restart:
2990
2991 validate_region (&start, &end);
2992 CHECK_CHARACTER (fromchar);
2993 CHECK_CHARACTER (tochar);
2994 fromc = XFASTINT (fromchar);
2995 toc = XFASTINT (tochar);
2996
2997 if (multibyte_p)
2998 {
2999 len = CHAR_STRING (fromc, fromstr);
3000 if (CHAR_STRING (toc, tostr) != len)
3001 error ("Characters in `subst-char-in-region' have different byte-lengths");
3002 if (!ASCII_CHAR_P (*tostr))
3003 {
3004 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
3005 complete multibyte character, it may be combined with the
3006 after bytes. If it is in the range 0xA0..0xFF, it may be
3007 combined with the before and after bytes. */
3008 if (!CHAR_HEAD_P (*tostr))
3009 maybe_byte_combining = COMBINING_BOTH;
3010 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
3011 maybe_byte_combining = COMBINING_AFTER;
3012 }
3013 }
3014 else
3015 {
3016 len = 1;
3017 fromstr[0] = fromc;
3018 tostr[0] = toc;
3019 }
3020
3021 pos = XINT (start);
3022 pos_byte = CHAR_TO_BYTE (pos);
3023 stop = CHAR_TO_BYTE (XINT (end));
3024 end_byte = stop;
3025
3026 /* If we don't want undo, turn off putting stuff on the list.
3027 That's faster than getting rid of things,
3028 and it prevents even the entry for a first change.
3029 Also inhibit locking the file. */
3030 if (!changed && !NILP (noundo))
3031 {
3032 record_unwind_protect (subst_char_in_region_unwind,
3033 BVAR (current_buffer, undo_list));
3034 bset_undo_list (current_buffer, Qt);
3035 /* Don't do file-locking. */
3036 record_unwind_protect (subst_char_in_region_unwind_1,
3037 BVAR (current_buffer, filename));
3038 bset_filename (current_buffer, Qnil);
3039 }
3040
3041 if (pos_byte < GPT_BYTE)
3042 stop = min (stop, GPT_BYTE);
3043 while (1)
3044 {
3045 ptrdiff_t pos_byte_next = pos_byte;
3046
3047 if (pos_byte >= stop)
3048 {
3049 if (pos_byte >= end_byte) break;
3050 stop = end_byte;
3051 }
3052 p = BYTE_POS_ADDR (pos_byte);
3053 if (multibyte_p)
3054 INC_POS (pos_byte_next);
3055 else
3056 ++pos_byte_next;
3057 if (pos_byte_next - pos_byte == len
3058 && p[0] == fromstr[0]
3059 && (len == 1
3060 || (p[1] == fromstr[1]
3061 && (len == 2 || (p[2] == fromstr[2]
3062 && (len == 3 || p[3] == fromstr[3]))))))
3063 {
3064 if (changed < 0)
3065 /* We've already seen this and run the before-change-function;
3066 this time we only need to record the actual position. */
3067 changed = pos;
3068 else if (!changed)
3069 {
3070 changed = -1;
3071 modify_text (pos, XINT (end));
3072
3073 if (! NILP (noundo))
3074 {
3075 if (MODIFF - 1 == SAVE_MODIFF)
3076 SAVE_MODIFF++;
3077 if (MODIFF - 1 == BUF_AUTOSAVE_MODIFF (current_buffer))
3078 BUF_AUTOSAVE_MODIFF (current_buffer)++;
3079 }
3080
3081 /* The before-change-function may have moved the gap
3082 or even modified the buffer so we should start over. */
3083 goto restart;
3084 }
3085
3086 /* Take care of the case where the new character
3087 combines with neighboring bytes. */
3088 if (maybe_byte_combining
3089 && (maybe_byte_combining == COMBINING_AFTER
3090 ? (pos_byte_next < Z_BYTE
3091 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
3092 : ((pos_byte_next < Z_BYTE
3093 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
3094 || (pos_byte > BEG_BYTE
3095 && ! ASCII_CHAR_P (FETCH_BYTE (pos_byte - 1))))))
3096 {
3097 Lisp_Object tem, string;
3098
3099 struct gcpro gcpro1;
3100
3101 tem = BVAR (current_buffer, undo_list);
3102 GCPRO1 (tem);
3103
3104 /* Make a multibyte string containing this single character. */
3105 string = make_multibyte_string ((char *) tostr, 1, len);
3106 /* replace_range is less efficient, because it moves the gap,
3107 but it handles combining correctly. */
3108 replace_range (pos, pos + 1, string,
3109 0, 0, 1);
3110 pos_byte_next = CHAR_TO_BYTE (pos);
3111 if (pos_byte_next > pos_byte)
3112 /* Before combining happened. We should not increment
3113 POS. So, to cancel the later increment of POS,
3114 decrease it now. */
3115 pos--;
3116 else
3117 INC_POS (pos_byte_next);
3118
3119 if (! NILP (noundo))
3120 bset_undo_list (current_buffer, tem);
3121
3122 UNGCPRO;
3123 }
3124 else
3125 {
3126 if (NILP (noundo))
3127 record_change (pos, 1);
3128 for (i = 0; i < len; i++) *p++ = tostr[i];
3129 }
3130 last_changed = pos + 1;
3131 }
3132 pos_byte = pos_byte_next;
3133 pos++;
3134 }
3135
3136 if (changed > 0)
3137 {
3138 signal_after_change (changed,
3139 last_changed - changed, last_changed - changed);
3140 update_compositions (changed, last_changed, CHECK_ALL);
3141 }
3142
3143 unbind_to (count, Qnil);
3144 return Qnil;
3145 }
3146
3147
3148 static Lisp_Object check_translation (ptrdiff_t, ptrdiff_t, ptrdiff_t,
3149 Lisp_Object);
3150
3151 /* Helper function for Ftranslate_region_internal.
3152
3153 Check if a character sequence at POS (POS_BYTE) matches an element
3154 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
3155 element is found, return it. Otherwise return Qnil. */
3156
3157 static Lisp_Object
3158 check_translation (ptrdiff_t pos, ptrdiff_t pos_byte, ptrdiff_t end,
3159 Lisp_Object val)
3160 {
3161 int initial_buf[16];
3162 int *buf = initial_buf;
3163 ptrdiff_t buf_size = ARRAYELTS (initial_buf);
3164 int *bufalloc = 0;
3165 ptrdiff_t buf_used = 0;
3166 Lisp_Object result = Qnil;
3167
3168 for (; CONSP (val); val = XCDR (val))
3169 {
3170 Lisp_Object elt;
3171 ptrdiff_t len, i;
3172
3173 elt = XCAR (val);
3174 if (! CONSP (elt))
3175 continue;
3176 elt = XCAR (elt);
3177 if (! VECTORP (elt))
3178 continue;
3179 len = ASIZE (elt);
3180 if (len <= end - pos)
3181 {
3182 for (i = 0; i < len; i++)
3183 {
3184 if (buf_used <= i)
3185 {
3186 unsigned char *p = BYTE_POS_ADDR (pos_byte);
3187 int len1;
3188
3189 if (buf_used == buf_size)
3190 {
3191 bufalloc = xpalloc (bufalloc, &buf_size, 1, -1,
3192 sizeof *bufalloc);
3193 if (buf == initial_buf)
3194 memcpy (bufalloc, buf, sizeof initial_buf);
3195 buf = bufalloc;
3196 }
3197 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len1);
3198 pos_byte += len1;
3199 }
3200 if (XINT (AREF (elt, i)) != buf[i])
3201 break;
3202 }
3203 if (i == len)
3204 {
3205 result = XCAR (val);
3206 break;
3207 }
3208 }
3209 }
3210
3211 xfree (bufalloc);
3212 return result;
3213 }
3214
3215
3216 DEFUN ("translate-region-internal", Ftranslate_region_internal,
3217 Stranslate_region_internal, 3, 3, 0,
3218 doc: /* Internal use only.
3219 From START to END, translate characters according to TABLE.
3220 TABLE is a string or a char-table; the Nth character in it is the
3221 mapping for the character with code N.
3222 It returns the number of characters changed. */)
3223 (Lisp_Object start, Lisp_Object end, register Lisp_Object table)
3224 {
3225 register unsigned char *tt; /* Trans table. */
3226 register int nc; /* New character. */
3227 int cnt; /* Number of changes made. */
3228 ptrdiff_t size; /* Size of translate table. */
3229 ptrdiff_t pos, pos_byte, end_pos;
3230 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3231 bool string_multibyte IF_LINT (= 0);
3232
3233 validate_region (&start, &end);
3234 if (CHAR_TABLE_P (table))
3235 {
3236 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3237 error ("Not a translation table");
3238 size = MAX_CHAR;
3239 tt = NULL;
3240 }
3241 else
3242 {
3243 CHECK_STRING (table);
3244
3245 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3246 table = string_make_unibyte (table);
3247 string_multibyte = SCHARS (table) < SBYTES (table);
3248 size = SBYTES (table);
3249 tt = SDATA (table);
3250 }
3251
3252 pos = XINT (start);
3253 pos_byte = CHAR_TO_BYTE (pos);
3254 end_pos = XINT (end);
3255 modify_text (pos, end_pos);
3256
3257 cnt = 0;
3258 for (; pos < end_pos; )
3259 {
3260 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
3261 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3262 int len, str_len;
3263 int oc;
3264 Lisp_Object val;
3265
3266 if (multibyte)
3267 oc = STRING_CHAR_AND_LENGTH (p, len);
3268 else
3269 oc = *p, len = 1;
3270 if (oc < size)
3271 {
3272 if (tt)
3273 {
3274 /* Reload as signal_after_change in last iteration may GC. */
3275 tt = SDATA (table);
3276 if (string_multibyte)
3277 {
3278 str = tt + string_char_to_byte (table, oc);
3279 nc = STRING_CHAR_AND_LENGTH (str, str_len);
3280 }
3281 else
3282 {
3283 nc = tt[oc];
3284 if (! ASCII_CHAR_P (nc) && multibyte)
3285 {
3286 str_len = BYTE8_STRING (nc, buf);
3287 str = buf;
3288 }
3289 else
3290 {
3291 str_len = 1;
3292 str = tt + oc;
3293 }
3294 }
3295 }
3296 else
3297 {
3298 nc = oc;
3299 val = CHAR_TABLE_REF (table, oc);
3300 if (CHARACTERP (val))
3301 {
3302 nc = XFASTINT (val);
3303 str_len = CHAR_STRING (nc, buf);
3304 str = buf;
3305 }
3306 else if (VECTORP (val) || (CONSP (val)))
3307 {
3308 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3309 where TO is TO-CHAR or [TO-CHAR ...]. */
3310 nc = -1;
3311 }
3312 }
3313
3314 if (nc != oc && nc >= 0)
3315 {
3316 /* Simple one char to one char translation. */
3317 if (len != str_len)
3318 {
3319 Lisp_Object string;
3320
3321 /* This is less efficient, because it moves the gap,
3322 but it should handle multibyte characters correctly. */
3323 string = make_multibyte_string ((char *) str, 1, str_len);
3324 replace_range (pos, pos + 1, string, 1, 0, 1);
3325 len = str_len;
3326 }
3327 else
3328 {
3329 record_change (pos, 1);
3330 while (str_len-- > 0)
3331 *p++ = *str++;
3332 signal_after_change (pos, 1, 1);
3333 update_compositions (pos, pos + 1, CHECK_BORDER);
3334 }
3335 ++cnt;
3336 }
3337 else if (nc < 0)
3338 {
3339 Lisp_Object string;
3340
3341 if (CONSP (val))
3342 {
3343 val = check_translation (pos, pos_byte, end_pos, val);
3344 if (NILP (val))
3345 {
3346 pos_byte += len;
3347 pos++;
3348 continue;
3349 }
3350 /* VAL is ([FROM-CHAR ...] . TO). */
3351 len = ASIZE (XCAR (val));
3352 val = XCDR (val);
3353 }
3354 else
3355 len = 1;
3356
3357 if (VECTORP (val))
3358 {
3359 string = Fconcat (1, &val);
3360 }
3361 else
3362 {
3363 string = Fmake_string (make_number (1), val);
3364 }
3365 replace_range (pos, pos + len, string, 1, 0, 1);
3366 pos_byte += SBYTES (string);
3367 pos += SCHARS (string);
3368 cnt += SCHARS (string);
3369 end_pos += SCHARS (string) - len;
3370 continue;
3371 }
3372 }
3373 pos_byte += len;
3374 pos++;
3375 }
3376
3377 return make_number (cnt);
3378 }
3379
3380 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3381 doc: /* Delete the text between START and END.
3382 If called interactively, delete the region between point and mark.
3383 This command deletes buffer text without modifying the kill ring. */)
3384 (Lisp_Object start, Lisp_Object end)
3385 {
3386 validate_region (&start, &end);
3387 del_range (XINT (start), XINT (end));
3388 return Qnil;
3389 }
3390
3391 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3392 Sdelete_and_extract_region, 2, 2, 0,
3393 doc: /* Delete the text between START and END and return it. */)
3394 (Lisp_Object start, Lisp_Object end)
3395 {
3396 validate_region (&start, &end);
3397 if (XINT (start) == XINT (end))
3398 return empty_unibyte_string;
3399 return del_range_1 (XINT (start), XINT (end), 1, 1);
3400 }
3401 \f
3402 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3403 doc: /* Remove restrictions (narrowing) from current buffer.
3404 This allows the buffer's full text to be seen and edited. */)
3405 (void)
3406 {
3407 if (BEG != BEGV || Z != ZV)
3408 current_buffer->clip_changed = 1;
3409 BEGV = BEG;
3410 BEGV_BYTE = BEG_BYTE;
3411 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3412 /* Changing the buffer bounds invalidates any recorded current column. */
3413 invalidate_current_column ();
3414 return Qnil;
3415 }
3416
3417 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3418 doc: /* Restrict editing in this buffer to the current region.
3419 The rest of the text becomes temporarily invisible and untouchable
3420 but is not deleted; if you save the buffer in a file, the invisible
3421 text is included in the file. \\[widen] makes all visible again.
3422 See also `save-restriction'.
3423
3424 When calling from a program, pass two arguments; positions (integers
3425 or markers) bounding the text that should remain visible. */)
3426 (register Lisp_Object start, Lisp_Object end)
3427 {
3428 CHECK_NUMBER_COERCE_MARKER (start);
3429 CHECK_NUMBER_COERCE_MARKER (end);
3430
3431 if (XINT (start) > XINT (end))
3432 {
3433 Lisp_Object tem;
3434 tem = start; start = end; end = tem;
3435 }
3436
3437 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3438 args_out_of_range (start, end);
3439
3440 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3441 current_buffer->clip_changed = 1;
3442
3443 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3444 SET_BUF_ZV (current_buffer, XFASTINT (end));
3445 if (PT < XFASTINT (start))
3446 SET_PT (XFASTINT (start));
3447 if (PT > XFASTINT (end))
3448 SET_PT (XFASTINT (end));
3449 /* Changing the buffer bounds invalidates any recorded current column. */
3450 invalidate_current_column ();
3451 return Qnil;
3452 }
3453
3454 Lisp_Object
3455 save_restriction_save (void)
3456 {
3457 if (BEGV == BEG && ZV == Z)
3458 /* The common case that the buffer isn't narrowed.
3459 We return just the buffer object, which save_restriction_restore
3460 recognizes as meaning `no restriction'. */
3461 return Fcurrent_buffer ();
3462 else
3463 /* We have to save a restriction, so return a pair of markers, one
3464 for the beginning and one for the end. */
3465 {
3466 Lisp_Object beg, end;
3467
3468 beg = build_marker (current_buffer, BEGV, BEGV_BYTE);
3469 end = build_marker (current_buffer, ZV, ZV_BYTE);
3470
3471 /* END must move forward if text is inserted at its exact location. */
3472 XMARKER (end)->insertion_type = 1;
3473
3474 return Fcons (beg, end);
3475 }
3476 }
3477
3478 void
3479 save_restriction_restore (Lisp_Object data)
3480 {
3481 struct buffer *cur = NULL;
3482 struct buffer *buf = (CONSP (data)
3483 ? XMARKER (XCAR (data))->buffer
3484 : XBUFFER (data));
3485
3486 if (buf && buf != current_buffer && !NILP (BVAR (buf, pt_marker)))
3487 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3488 is the case if it is or has an indirect buffer), then make
3489 sure it is current before we update BEGV, so
3490 set_buffer_internal takes care of managing those markers. */
3491 cur = current_buffer;
3492 set_buffer_internal (buf);
3493 }
3494
3495 if (CONSP (data))
3496 /* A pair of marks bounding a saved restriction. */
3497 {
3498 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3499 struct Lisp_Marker *end = XMARKER (XCDR (data));
3500 eassert (buf == end->buffer);
3501
3502 if (buf /* Verify marker still points to a buffer. */
3503 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3504 /* The restriction has changed from the saved one, so restore
3505 the saved restriction. */
3506 {
3507 ptrdiff_t pt = BUF_PT (buf);
3508
3509 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3510 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3511
3512 if (pt < beg->charpos || pt > end->charpos)
3513 /* The point is outside the new visible range, move it inside. */
3514 SET_BUF_PT_BOTH (buf,
3515 clip_to_bounds (beg->charpos, pt, end->charpos),
3516 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3517 end->bytepos));
3518
3519 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3520 }
3521 /* These aren't needed anymore, so don't wait for GC. */
3522 free_marker (XCAR (data));
3523 free_marker (XCDR (data));
3524 free_cons (XCONS (data));
3525 }
3526 else
3527 /* A buffer, which means that there was no old restriction. */
3528 {
3529 if (buf /* Verify marker still points to a buffer. */
3530 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3531 /* The buffer has been narrowed, get rid of the narrowing. */
3532 {
3533 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3534 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3535
3536 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3537 }
3538 }
3539
3540 /* Changing the buffer bounds invalidates any recorded current column. */
3541 invalidate_current_column ();
3542
3543 if (cur)
3544 set_buffer_internal (cur);
3545 }
3546
3547 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3548 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3549 The buffer's restrictions make parts of the beginning and end invisible.
3550 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3551 This special form, `save-restriction', saves the current buffer's restrictions
3552 when it is entered, and restores them when it is exited.
3553 So any `narrow-to-region' within BODY lasts only until the end of the form.
3554 The old restrictions settings are restored
3555 even in case of abnormal exit (throw or error).
3556
3557 The value returned is the value of the last form in BODY.
3558
3559 Note: if you are using both `save-excursion' and `save-restriction',
3560 use `save-excursion' outermost:
3561 (save-excursion (save-restriction ...))
3562
3563 usage: (save-restriction &rest BODY) */)
3564 (Lisp_Object body)
3565 {
3566 register Lisp_Object val;
3567 ptrdiff_t count = SPECPDL_INDEX ();
3568
3569 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3570 val = Fprogn (body);
3571 return unbind_to (count, val);
3572 }
3573 \f
3574 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3575 doc: /* Display a message at the bottom of the screen.
3576 The message also goes into the `*Messages*' buffer, if `message-log-max'
3577 is non-nil. (In keyboard macros, that's all it does.)
3578 Return the message.
3579
3580 In batch mode, the message is printed to the standard error stream,
3581 followed by a newline.
3582
3583 The first argument is a format control string, and the rest are data
3584 to be formatted under control of the string. See `format' for details.
3585
3586 Note: Use (message "%s" VALUE) to print the value of expressions and
3587 variables to avoid accidentally interpreting `%' as format specifiers.
3588
3589 If the first argument is nil or the empty string, the function clears
3590 any existing message; this lets the minibuffer contents show. See
3591 also `current-message'.
3592
3593 usage: (message FORMAT-STRING &rest ARGS) */)
3594 (ptrdiff_t nargs, Lisp_Object *args)
3595 {
3596 if (NILP (args[0])
3597 || (STRINGP (args[0])
3598 && SBYTES (args[0]) == 0))
3599 {
3600 message1 (0);
3601 return args[0];
3602 }
3603 else
3604 {
3605 register Lisp_Object val;
3606 val = Fformat (nargs, args);
3607 message3 (val);
3608 return val;
3609 }
3610 }
3611
3612 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3613 doc: /* Display a message, in a dialog box if possible.
3614 If a dialog box is not available, use the echo area.
3615 The first argument is a format control string, and the rest are data
3616 to be formatted under control of the string. See `format' for details.
3617
3618 If the first argument is nil or the empty string, clear any existing
3619 message; let the minibuffer contents show.
3620
3621 usage: (message-box FORMAT-STRING &rest ARGS) */)
3622 (ptrdiff_t nargs, Lisp_Object *args)
3623 {
3624 if (NILP (args[0]))
3625 {
3626 message1 (0);
3627 return Qnil;
3628 }
3629 else
3630 {
3631 Lisp_Object val = Fformat (nargs, args);
3632 Lisp_Object pane, menu;
3633 struct gcpro gcpro1;
3634
3635 pane = list1 (Fcons (build_string ("OK"), Qt));
3636 GCPRO1 (pane);
3637 menu = Fcons (val, pane);
3638 Fx_popup_dialog (Qt, menu, Qt);
3639 UNGCPRO;
3640 return val;
3641 }
3642 }
3643
3644 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3645 doc: /* Display a message in a dialog box or in the echo area.
3646 If this command was invoked with the mouse, use a dialog box if
3647 `use-dialog-box' is non-nil.
3648 Otherwise, use the echo area.
3649 The first argument is a format control string, and the rest are data
3650 to be formatted under control of the string. See `format' for details.
3651
3652 If the first argument is nil or the empty string, clear any existing
3653 message; let the minibuffer contents show.
3654
3655 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3656 (ptrdiff_t nargs, Lisp_Object *args)
3657 {
3658 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3659 && use_dialog_box)
3660 return Fmessage_box (nargs, args);
3661 return Fmessage (nargs, args);
3662 }
3663
3664 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3665 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3666 (void)
3667 {
3668 return current_message ();
3669 }
3670
3671
3672 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3673 doc: /* Return a copy of STRING with text properties added.
3674 First argument is the string to copy.
3675 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3676 properties to add to the result.
3677 usage: (propertize STRING &rest PROPERTIES) */)
3678 (ptrdiff_t nargs, Lisp_Object *args)
3679 {
3680 Lisp_Object properties, string;
3681 struct gcpro gcpro1, gcpro2;
3682 ptrdiff_t i;
3683
3684 /* Number of args must be odd. */
3685 if ((nargs & 1) == 0)
3686 error ("Wrong number of arguments");
3687
3688 properties = string = Qnil;
3689 GCPRO2 (properties, string);
3690
3691 /* First argument must be a string. */
3692 CHECK_STRING (args[0]);
3693 string = Fcopy_sequence (args[0]);
3694
3695 for (i = 1; i < nargs; i += 2)
3696 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3697
3698 Fadd_text_properties (make_number (0),
3699 make_number (SCHARS (string)),
3700 properties, string);
3701 RETURN_UNGCPRO (string);
3702 }
3703
3704 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3705 doc: /* Format a string out of a format-string and arguments.
3706 The first argument is a format control string.
3707 The other arguments are substituted into it to make the result, a string.
3708
3709 The format control string may contain %-sequences meaning to substitute
3710 the next available argument:
3711
3712 %s means print a string argument. Actually, prints any object, with `princ'.
3713 %d means print as number in decimal (%o octal, %x hex).
3714 %X is like %x, but uses upper case.
3715 %e means print a number in exponential notation.
3716 %f means print a number in decimal-point notation.
3717 %g means print a number in exponential notation
3718 or decimal-point notation, whichever uses fewer characters.
3719 %c means print a number as a single character.
3720 %S means print any object as an s-expression (using `prin1').
3721
3722 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3723 Use %% to put a single % into the output.
3724
3725 A %-sequence may contain optional flag, width, and precision
3726 specifiers, as follows:
3727
3728 %<flags><width><precision>character
3729
3730 where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3731
3732 The + flag character inserts a + before any positive number, while a
3733 space inserts a space before any positive number; these flags only
3734 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3735 The - and 0 flags affect the width specifier, as described below.
3736
3737 The # flag means to use an alternate display form for %o, %x, %X, %e,
3738 %f, and %g sequences: for %o, it ensures that the result begins with
3739 \"0\"; for %x and %X, it prefixes the result with \"0x\" or \"0X\";
3740 for %e, %f, and %g, it causes a decimal point to be included even if
3741 the precision is zero.
3742
3743 The width specifier supplies a lower limit for the length of the
3744 printed representation. The padding, if any, normally goes on the
3745 left, but it goes on the right if the - flag is present. The padding
3746 character is normally a space, but it is 0 if the 0 flag is present.
3747 The 0 flag is ignored if the - flag is present, or the format sequence
3748 is something other than %d, %e, %f, and %g.
3749
3750 For %e, %f, and %g sequences, the number after the "." in the
3751 precision specifier says how many decimal places to show; if zero, the
3752 decimal point itself is omitted. For %s and %S, the precision
3753 specifier truncates the string to the given width.
3754
3755 usage: (format STRING &rest OBJECTS) */)
3756 (ptrdiff_t nargs, Lisp_Object *args)
3757 {
3758 ptrdiff_t n; /* The number of the next arg to substitute. */
3759 char initial_buffer[4000];
3760 char *buf = initial_buffer;
3761 ptrdiff_t bufsize = sizeof initial_buffer;
3762 ptrdiff_t max_bufsize = STRING_BYTES_BOUND + 1;
3763 char *p;
3764 ptrdiff_t buf_save_value_index IF_LINT (= 0);
3765 char *format, *end, *format_start;
3766 ptrdiff_t formatlen, nchars;
3767 /* True if the format is multibyte. */
3768 bool multibyte_format = 0;
3769 /* True if the output should be a multibyte string,
3770 which is true if any of the inputs is one. */
3771 bool multibyte = 0;
3772 /* When we make a multibyte string, we must pay attention to the
3773 byte combining problem, i.e., a byte may be combined with a
3774 multibyte character of the previous string. This flag tells if we
3775 must consider such a situation or not. */
3776 bool maybe_combine_byte;
3777 Lisp_Object val;
3778 bool arg_intervals = 0;
3779 USE_SAFE_ALLOCA;
3780
3781 /* discarded[I] is 1 if byte I of the format
3782 string was not copied into the output.
3783 It is 2 if byte I was not the first byte of its character. */
3784 char *discarded;
3785
3786 /* Each element records, for one argument,
3787 the start and end bytepos in the output string,
3788 whether the argument has been converted to string (e.g., due to "%S"),
3789 and whether the argument is a string with intervals.
3790 info[0] is unused. Unused elements have -1 for start. */
3791 struct info
3792 {
3793 ptrdiff_t start, end;
3794 bool_bf converted_to_string : 1;
3795 bool_bf intervals : 1;
3796 } *info = 0;
3797
3798 /* It should not be necessary to GCPRO ARGS, because
3799 the caller in the interpreter should take care of that. */
3800
3801 CHECK_STRING (args[0]);
3802 format_start = SSDATA (args[0]);
3803 formatlen = SBYTES (args[0]);
3804
3805 /* Allocate the info and discarded tables. */
3806 {
3807 ptrdiff_t i;
3808 if ((SIZE_MAX - formatlen) / sizeof (struct info) <= nargs)
3809 memory_full (SIZE_MAX);
3810 info = SAFE_ALLOCA ((nargs + 1) * sizeof *info + formatlen);
3811 discarded = (char *) &info[nargs + 1];
3812 for (i = 0; i < nargs + 1; i++)
3813 {
3814 info[i].start = -1;
3815 info[i].intervals = info[i].converted_to_string = 0;
3816 }
3817 memset (discarded, 0, formatlen);
3818 }
3819
3820 /* Try to determine whether the result should be multibyte.
3821 This is not always right; sometimes the result needs to be multibyte
3822 because of an object that we will pass through prin1,
3823 and in that case, we won't know it here. */
3824 multibyte_format = STRING_MULTIBYTE (args[0]);
3825 multibyte = multibyte_format;
3826 for (n = 1; !multibyte && n < nargs; n++)
3827 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3828 multibyte = 1;
3829
3830 /* If we start out planning a unibyte result,
3831 then discover it has to be multibyte, we jump back to retry. */
3832 retry:
3833
3834 p = buf;
3835 nchars = 0;
3836 n = 0;
3837
3838 /* Scan the format and store result in BUF. */
3839 format = format_start;
3840 end = format + formatlen;
3841 maybe_combine_byte = 0;
3842
3843 while (format != end)
3844 {
3845 /* The values of N and FORMAT when the loop body is entered. */
3846 ptrdiff_t n0 = n;
3847 char *format0 = format;
3848
3849 /* Bytes needed to represent the output of this conversion. */
3850 ptrdiff_t convbytes;
3851
3852 if (*format == '%')
3853 {
3854 /* General format specifications look like
3855
3856 '%' [flags] [field-width] [precision] format
3857
3858 where
3859
3860 flags ::= [-+0# ]+
3861 field-width ::= [0-9]+
3862 precision ::= '.' [0-9]*
3863
3864 If a field-width is specified, it specifies to which width
3865 the output should be padded with blanks, if the output
3866 string is shorter than field-width.
3867
3868 If precision is specified, it specifies the number of
3869 digits to print after the '.' for floats, or the max.
3870 number of chars to print from a string. */
3871
3872 bool minus_flag = 0;
3873 bool plus_flag = 0;
3874 bool space_flag = 0;
3875 bool sharp_flag = 0;
3876 bool zero_flag = 0;
3877 ptrdiff_t field_width;
3878 bool precision_given;
3879 uintmax_t precision = UINTMAX_MAX;
3880 char *num_end;
3881 char conversion;
3882
3883 while (1)
3884 {
3885 switch (*++format)
3886 {
3887 case '-': minus_flag = 1; continue;
3888 case '+': plus_flag = 1; continue;
3889 case ' ': space_flag = 1; continue;
3890 case '#': sharp_flag = 1; continue;
3891 case '0': zero_flag = 1; continue;
3892 }
3893 break;
3894 }
3895
3896 /* Ignore flags when sprintf ignores them. */
3897 space_flag &= ~ plus_flag;
3898 zero_flag &= ~ minus_flag;
3899
3900 {
3901 uintmax_t w = strtoumax (format, &num_end, 10);
3902 if (max_bufsize <= w)
3903 string_overflow ();
3904 field_width = w;
3905 }
3906 precision_given = *num_end == '.';
3907 if (precision_given)
3908 precision = strtoumax (num_end + 1, &num_end, 10);
3909 format = num_end;
3910
3911 if (format == end)
3912 error ("Format string ends in middle of format specifier");
3913
3914 memset (&discarded[format0 - format_start], 1, format - format0);
3915 conversion = *format;
3916 if (conversion == '%')
3917 goto copy_char;
3918 discarded[format - format_start] = 1;
3919 format++;
3920
3921 ++n;
3922 if (! (n < nargs))
3923 error ("Not enough arguments for format string");
3924
3925 /* For 'S', prin1 the argument, and then treat like 's'.
3926 For 's', princ any argument that is not a string or
3927 symbol. But don't do this conversion twice, which might
3928 happen after retrying. */
3929 if ((conversion == 'S'
3930 || (conversion == 's'
3931 && ! STRINGP (args[n]) && ! SYMBOLP (args[n]))))
3932 {
3933 if (! info[n].converted_to_string)
3934 {
3935 Lisp_Object noescape = conversion == 'S' ? Qnil : Qt;
3936 args[n] = Fprin1_to_string (args[n], noescape);
3937 info[n].converted_to_string = 1;
3938 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3939 {
3940 multibyte = 1;
3941 goto retry;
3942 }
3943 }
3944 conversion = 's';
3945 }
3946 else if (conversion == 'c')
3947 {
3948 if (FLOATP (args[n]))
3949 {
3950 double d = XFLOAT_DATA (args[n]);
3951 args[n] = make_number (FIXNUM_OVERFLOW_P (d) ? -1 : d);
3952 }
3953
3954 if (INTEGERP (args[n]) && ! ASCII_CHAR_P (XINT (args[n])))
3955 {
3956 if (!multibyte)
3957 {
3958 multibyte = 1;
3959 goto retry;
3960 }
3961 args[n] = Fchar_to_string (args[n]);
3962 info[n].converted_to_string = 1;
3963 }
3964
3965 if (info[n].converted_to_string)
3966 conversion = 's';
3967 zero_flag = 0;
3968 }
3969
3970 if (SYMBOLP (args[n]))
3971 {
3972 args[n] = SYMBOL_NAME (args[n]);
3973 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3974 {
3975 multibyte = 1;
3976 goto retry;
3977 }
3978 }
3979
3980 if (conversion == 's')
3981 {
3982 /* handle case (precision[n] >= 0) */
3983
3984 ptrdiff_t width, padding, nbytes;
3985 ptrdiff_t nchars_string;
3986
3987 ptrdiff_t prec = -1;
3988 if (precision_given && precision <= TYPE_MAXIMUM (ptrdiff_t))
3989 prec = precision;
3990
3991 /* lisp_string_width ignores a precision of 0, but GNU
3992 libc functions print 0 characters when the precision
3993 is 0. Imitate libc behavior here. Changing
3994 lisp_string_width is the right thing, and will be
3995 done, but meanwhile we work with it. */
3996
3997 if (prec == 0)
3998 width = nchars_string = nbytes = 0;
3999 else
4000 {
4001 ptrdiff_t nch, nby;
4002 width = lisp_string_width (args[n], prec, &nch, &nby);
4003 if (prec < 0)
4004 {
4005 nchars_string = SCHARS (args[n]);
4006 nbytes = SBYTES (args[n]);
4007 }
4008 else
4009 {
4010 nchars_string = nch;
4011 nbytes = nby;
4012 }
4013 }
4014
4015 convbytes = nbytes;
4016 if (convbytes && multibyte && ! STRING_MULTIBYTE (args[n]))
4017 convbytes = count_size_as_multibyte (SDATA (args[n]), nbytes);
4018
4019 padding = width < field_width ? field_width - width : 0;
4020
4021 if (max_bufsize - padding <= convbytes)
4022 string_overflow ();
4023 convbytes += padding;
4024 if (convbytes <= buf + bufsize - p)
4025 {
4026 if (! minus_flag)
4027 {
4028 memset (p, ' ', padding);
4029 p += padding;
4030 nchars += padding;
4031 }
4032
4033 if (p > buf
4034 && multibyte
4035 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
4036 && STRING_MULTIBYTE (args[n])
4037 && !CHAR_HEAD_P (SREF (args[n], 0)))
4038 maybe_combine_byte = 1;
4039
4040 p += copy_text (SDATA (args[n]), (unsigned char *) p,
4041 nbytes,
4042 STRING_MULTIBYTE (args[n]), multibyte);
4043
4044 info[n].start = nchars;
4045 nchars += nchars_string;
4046 info[n].end = nchars;
4047
4048 if (minus_flag)
4049 {
4050 memset (p, ' ', padding);
4051 p += padding;
4052 nchars += padding;
4053 }
4054
4055 /* If this argument has text properties, record where
4056 in the result string it appears. */
4057 if (string_intervals (args[n]))
4058 info[n].intervals = arg_intervals = 1;
4059
4060 continue;
4061 }
4062 }
4063 else if (! (conversion == 'c' || conversion == 'd'
4064 || conversion == 'e' || conversion == 'f'
4065 || conversion == 'g' || conversion == 'i'
4066 || conversion == 'o' || conversion == 'x'
4067 || conversion == 'X'))
4068 error ("Invalid format operation %%%c",
4069 STRING_CHAR ((unsigned char *) format - 1));
4070 else if (! (INTEGERP (args[n]) || FLOATP (args[n])))
4071 error ("Format specifier doesn't match argument type");
4072 else
4073 {
4074 enum
4075 {
4076 /* Maximum precision for a %f conversion such that the
4077 trailing output digit might be nonzero. Any precision
4078 larger than this will not yield useful information. */
4079 USEFUL_PRECISION_MAX =
4080 ((1 - DBL_MIN_EXP)
4081 * (FLT_RADIX == 2 || FLT_RADIX == 10 ? 1
4082 : FLT_RADIX == 16 ? 4
4083 : -1)),
4084
4085 /* Maximum number of bytes generated by any format, if
4086 precision is no more than USEFUL_PRECISION_MAX.
4087 On all practical hosts, %f is the worst case. */
4088 SPRINTF_BUFSIZE =
4089 sizeof "-." + (DBL_MAX_10_EXP + 1) + USEFUL_PRECISION_MAX,
4090
4091 /* Length of pM (that is, of pMd without the
4092 trailing "d"). */
4093 pMlen = sizeof pMd - 2
4094 };
4095 verify (USEFUL_PRECISION_MAX > 0);
4096
4097 int prec;
4098 ptrdiff_t padding, sprintf_bytes;
4099 uintmax_t excess_precision, numwidth;
4100 uintmax_t leading_zeros = 0, trailing_zeros = 0;
4101
4102 char sprintf_buf[SPRINTF_BUFSIZE];
4103
4104 /* Copy of conversion specification, modified somewhat.
4105 At most three flags F can be specified at once. */
4106 char convspec[sizeof "%FFF.*d" + pMlen];
4107
4108 /* Avoid undefined behavior in underlying sprintf. */
4109 if (conversion == 'd' || conversion == 'i')
4110 sharp_flag = 0;
4111
4112 /* Create the copy of the conversion specification, with
4113 any width and precision removed, with ".*" inserted,
4114 and with pM inserted for integer formats. */
4115 {
4116 char *f = convspec;
4117 *f++ = '%';
4118 *f = '-'; f += minus_flag;
4119 *f = '+'; f += plus_flag;
4120 *f = ' '; f += space_flag;
4121 *f = '#'; f += sharp_flag;
4122 *f = '0'; f += zero_flag;
4123 *f++ = '.';
4124 *f++ = '*';
4125 if (conversion == 'd' || conversion == 'i'
4126 || conversion == 'o' || conversion == 'x'
4127 || conversion == 'X')
4128 {
4129 memcpy (f, pMd, pMlen);
4130 f += pMlen;
4131 zero_flag &= ~ precision_given;
4132 }
4133 *f++ = conversion;
4134 *f = '\0';
4135 }
4136
4137 prec = -1;
4138 if (precision_given)
4139 prec = min (precision, USEFUL_PRECISION_MAX);
4140
4141 /* Use sprintf to format this number into sprintf_buf. Omit
4142 padding and excess precision, though, because sprintf limits
4143 output length to INT_MAX.
4144
4145 There are four types of conversion: double, unsigned
4146 char (passed as int), wide signed int, and wide
4147 unsigned int. Treat them separately because the
4148 sprintf ABI is sensitive to which type is passed. Be
4149 careful about integer overflow, NaNs, infinities, and
4150 conversions; for example, the min and max macros are
4151 not suitable here. */
4152 if (conversion == 'e' || conversion == 'f' || conversion == 'g')
4153 {
4154 double x = (INTEGERP (args[n])
4155 ? XINT (args[n])
4156 : XFLOAT_DATA (args[n]));
4157 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4158 }
4159 else if (conversion == 'c')
4160 {
4161 /* Don't use sprintf here, as it might mishandle prec. */
4162 sprintf_buf[0] = XINT (args[n]);
4163 sprintf_bytes = prec != 0;
4164 }
4165 else if (conversion == 'd')
4166 {
4167 /* For float, maybe we should use "%1.0f"
4168 instead so it also works for values outside
4169 the integer range. */
4170 printmax_t x;
4171 if (INTEGERP (args[n]))
4172 x = XINT (args[n]);
4173 else
4174 {
4175 double d = XFLOAT_DATA (args[n]);
4176 if (d < 0)
4177 {
4178 x = TYPE_MINIMUM (printmax_t);
4179 if (x < d)
4180 x = d;
4181 }
4182 else
4183 {
4184 x = TYPE_MAXIMUM (printmax_t);
4185 if (d < x)
4186 x = d;
4187 }
4188 }
4189 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4190 }
4191 else
4192 {
4193 /* Don't sign-extend for octal or hex printing. */
4194 uprintmax_t x;
4195 if (INTEGERP (args[n]))
4196 x = XUINT (args[n]);
4197 else
4198 {
4199 double d = XFLOAT_DATA (args[n]);
4200 if (d < 0)
4201 x = 0;
4202 else
4203 {
4204 x = TYPE_MAXIMUM (uprintmax_t);
4205 if (d < x)
4206 x = d;
4207 }
4208 }
4209 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4210 }
4211
4212 /* Now the length of the formatted item is known, except it omits
4213 padding and excess precision. Deal with excess precision
4214 first. This happens only when the format specifies
4215 ridiculously large precision. */
4216 excess_precision = precision - prec;
4217 if (excess_precision)
4218 {
4219 if (conversion == 'e' || conversion == 'f'
4220 || conversion == 'g')
4221 {
4222 if ((conversion == 'g' && ! sharp_flag)
4223 || ! ('0' <= sprintf_buf[sprintf_bytes - 1]
4224 && sprintf_buf[sprintf_bytes - 1] <= '9'))
4225 excess_precision = 0;
4226 else
4227 {
4228 if (conversion == 'g')
4229 {
4230 char *dot = strchr (sprintf_buf, '.');
4231 if (!dot)
4232 excess_precision = 0;
4233 }
4234 }
4235 trailing_zeros = excess_precision;
4236 }
4237 else
4238 leading_zeros = excess_precision;
4239 }
4240
4241 /* Compute the total bytes needed for this item, including
4242 excess precision and padding. */
4243 numwidth = sprintf_bytes + excess_precision;
4244 padding = numwidth < field_width ? field_width - numwidth : 0;
4245 if (max_bufsize - sprintf_bytes <= excess_precision
4246 || max_bufsize - padding <= numwidth)
4247 string_overflow ();
4248 convbytes = numwidth + padding;
4249
4250 if (convbytes <= buf + bufsize - p)
4251 {
4252 /* Copy the formatted item from sprintf_buf into buf,
4253 inserting padding and excess-precision zeros. */
4254
4255 char *src = sprintf_buf;
4256 char src0 = src[0];
4257 int exponent_bytes = 0;
4258 bool signedp = src0 == '-' || src0 == '+' || src0 == ' ';
4259 int significand_bytes;
4260 if (zero_flag
4261 && ((src[signedp] >= '0' && src[signedp] <= '9')
4262 || (src[signedp] >= 'a' && src[signedp] <= 'f')
4263 || (src[signedp] >= 'A' && src[signedp] <= 'F')))
4264 {
4265 leading_zeros += padding;
4266 padding = 0;
4267 }
4268
4269 if (excess_precision
4270 && (conversion == 'e' || conversion == 'g'))
4271 {
4272 char *e = strchr (src, 'e');
4273 if (e)
4274 exponent_bytes = src + sprintf_bytes - e;
4275 }
4276
4277 if (! minus_flag)
4278 {
4279 memset (p, ' ', padding);
4280 p += padding;
4281 nchars += padding;
4282 }
4283
4284 *p = src0;
4285 src += signedp;
4286 p += signedp;
4287 memset (p, '0', leading_zeros);
4288 p += leading_zeros;
4289 significand_bytes = sprintf_bytes - signedp - exponent_bytes;
4290 memcpy (p, src, significand_bytes);
4291 p += significand_bytes;
4292 src += significand_bytes;
4293 memset (p, '0', trailing_zeros);
4294 p += trailing_zeros;
4295 memcpy (p, src, exponent_bytes);
4296 p += exponent_bytes;
4297
4298 info[n].start = nchars;
4299 nchars += leading_zeros + sprintf_bytes + trailing_zeros;
4300 info[n].end = nchars;
4301
4302 if (minus_flag)
4303 {
4304 memset (p, ' ', padding);
4305 p += padding;
4306 nchars += padding;
4307 }
4308
4309 continue;
4310 }
4311 }
4312 }
4313 else
4314 copy_char:
4315 {
4316 /* Copy a single character from format to buf. */
4317
4318 char *src = format;
4319 unsigned char str[MAX_MULTIBYTE_LENGTH];
4320
4321 if (multibyte_format)
4322 {
4323 /* Copy a whole multibyte character. */
4324 if (p > buf
4325 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
4326 && !CHAR_HEAD_P (*format))
4327 maybe_combine_byte = 1;
4328
4329 do
4330 format++;
4331 while (! CHAR_HEAD_P (*format));
4332
4333 convbytes = format - src;
4334 memset (&discarded[src + 1 - format_start], 2, convbytes - 1);
4335 }
4336 else
4337 {
4338 unsigned char uc = *format++;
4339 if (! multibyte || ASCII_CHAR_P (uc))
4340 convbytes = 1;
4341 else
4342 {
4343 int c = BYTE8_TO_CHAR (uc);
4344 convbytes = CHAR_STRING (c, str);
4345 src = (char *) str;
4346 }
4347 }
4348
4349 if (convbytes <= buf + bufsize - p)
4350 {
4351 memcpy (p, src, convbytes);
4352 p += convbytes;
4353 nchars++;
4354 continue;
4355 }
4356 }
4357
4358 /* There wasn't enough room to store this conversion or single
4359 character. CONVBYTES says how much room is needed. Allocate
4360 enough room (and then some) and do it again. */
4361 {
4362 ptrdiff_t used = p - buf;
4363
4364 if (max_bufsize - used < convbytes)
4365 string_overflow ();
4366 bufsize = used + convbytes;
4367 bufsize = bufsize < max_bufsize / 2 ? bufsize * 2 : max_bufsize;
4368
4369 if (buf == initial_buffer)
4370 {
4371 buf = xmalloc (bufsize);
4372 sa_must_free = true;
4373 buf_save_value_index = SPECPDL_INDEX ();
4374 record_unwind_protect_ptr (xfree, buf);
4375 memcpy (buf, initial_buffer, used);
4376 }
4377 else
4378 {
4379 buf = xrealloc (buf, bufsize);
4380 set_unwind_protect_ptr (buf_save_value_index, xfree, buf);
4381 }
4382
4383 p = buf + used;
4384 }
4385
4386 format = format0;
4387 n = n0;
4388 }
4389
4390 if (bufsize < p - buf)
4391 emacs_abort ();
4392
4393 if (maybe_combine_byte)
4394 nchars = multibyte_chars_in_text ((unsigned char *) buf, p - buf);
4395 val = make_specified_string (buf, nchars, p - buf, multibyte);
4396
4397 /* If we allocated BUF with malloc, free it too. */
4398 SAFE_FREE ();
4399
4400 /* If the format string has text properties, or any of the string
4401 arguments has text properties, set up text properties of the
4402 result string. */
4403
4404 if (string_intervals (args[0]) || arg_intervals)
4405 {
4406 Lisp_Object len, new_len, props;
4407 struct gcpro gcpro1;
4408
4409 /* Add text properties from the format string. */
4410 len = make_number (SCHARS (args[0]));
4411 props = text_property_list (args[0], make_number (0), len, Qnil);
4412 GCPRO1 (props);
4413
4414 if (CONSP (props))
4415 {
4416 ptrdiff_t bytepos = 0, position = 0, translated = 0;
4417 ptrdiff_t argn = 1;
4418 Lisp_Object list;
4419
4420 /* Adjust the bounds of each text property
4421 to the proper start and end in the output string. */
4422
4423 /* Put the positions in PROPS in increasing order, so that
4424 we can do (effectively) one scan through the position
4425 space of the format string. */
4426 props = Fnreverse (props);
4427
4428 /* BYTEPOS is the byte position in the format string,
4429 POSITION is the untranslated char position in it,
4430 TRANSLATED is the translated char position in BUF,
4431 and ARGN is the number of the next arg we will come to. */
4432 for (list = props; CONSP (list); list = XCDR (list))
4433 {
4434 Lisp_Object item;
4435 ptrdiff_t pos;
4436
4437 item = XCAR (list);
4438
4439 /* First adjust the property start position. */
4440 pos = XINT (XCAR (item));
4441
4442 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4443 up to this position. */
4444 for (; position < pos; bytepos++)
4445 {
4446 if (! discarded[bytepos])
4447 position++, translated++;
4448 else if (discarded[bytepos] == 1)
4449 {
4450 position++;
4451 if (translated == info[argn].start)
4452 {
4453 translated += info[argn].end - info[argn].start;
4454 argn++;
4455 }
4456 }
4457 }
4458
4459 XSETCAR (item, make_number (translated));
4460
4461 /* Likewise adjust the property end position. */
4462 pos = XINT (XCAR (XCDR (item)));
4463
4464 for (; position < pos; bytepos++)
4465 {
4466 if (! discarded[bytepos])
4467 position++, translated++;
4468 else if (discarded[bytepos] == 1)
4469 {
4470 position++;
4471 if (translated == info[argn].start)
4472 {
4473 translated += info[argn].end - info[argn].start;
4474 argn++;
4475 }
4476 }
4477 }
4478
4479 XSETCAR (XCDR (item), make_number (translated));
4480 }
4481
4482 add_text_properties_from_list (val, props, make_number (0));
4483 }
4484
4485 /* Add text properties from arguments. */
4486 if (arg_intervals)
4487 for (n = 1; n < nargs; ++n)
4488 if (info[n].intervals)
4489 {
4490 len = make_number (SCHARS (args[n]));
4491 new_len = make_number (info[n].end - info[n].start);
4492 props = text_property_list (args[n], make_number (0), len, Qnil);
4493 props = extend_property_ranges (props, new_len);
4494 /* If successive arguments have properties, be sure that
4495 the value of `composition' property be the copy. */
4496 if (n > 1 && info[n - 1].end)
4497 make_composition_value_copy (props);
4498 add_text_properties_from_list (val, props,
4499 make_number (info[n].start));
4500 }
4501
4502 UNGCPRO;
4503 }
4504
4505 return val;
4506 }
4507
4508 Lisp_Object
4509 format2 (const char *string1, Lisp_Object arg0, Lisp_Object arg1)
4510 {
4511 AUTO_STRING (format, string1);
4512 return Fformat (3, (Lisp_Object []) {format, arg0, arg1});
4513 }
4514 \f
4515 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4516 doc: /* Return t if two characters match, optionally ignoring case.
4517 Both arguments must be characters (i.e. integers).
4518 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4519 (register Lisp_Object c1, Lisp_Object c2)
4520 {
4521 int i1, i2;
4522 /* Check they're chars, not just integers, otherwise we could get array
4523 bounds violations in downcase. */
4524 CHECK_CHARACTER (c1);
4525 CHECK_CHARACTER (c2);
4526
4527 if (XINT (c1) == XINT (c2))
4528 return Qt;
4529 if (NILP (BVAR (current_buffer, case_fold_search)))
4530 return Qnil;
4531
4532 i1 = XFASTINT (c1);
4533 i2 = XFASTINT (c2);
4534
4535 /* FIXME: It is possible to compare multibyte characters even when
4536 the current buffer is unibyte. Unfortunately this is ambiguous
4537 for characters between 128 and 255, as they could be either
4538 eight-bit raw bytes or Latin-1 characters. Assume the former for
4539 now. See Bug#17011, and also see casefiddle.c's casify_object,
4540 which has a similar problem. */
4541 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4542 {
4543 if (SINGLE_BYTE_CHAR_P (i1))
4544 i1 = UNIBYTE_TO_CHAR (i1);
4545 if (SINGLE_BYTE_CHAR_P (i2))
4546 i2 = UNIBYTE_TO_CHAR (i2);
4547 }
4548
4549 return (downcase (i1) == downcase (i2) ? Qt : Qnil);
4550 }
4551 \f
4552 /* Transpose the markers in two regions of the current buffer, and
4553 adjust the ones between them if necessary (i.e.: if the regions
4554 differ in size).
4555
4556 START1, END1 are the character positions of the first region.
4557 START1_BYTE, END1_BYTE are the byte positions.
4558 START2, END2 are the character positions of the second region.
4559 START2_BYTE, END2_BYTE are the byte positions.
4560
4561 Traverses the entire marker list of the buffer to do so, adding an
4562 appropriate amount to some, subtracting from some, and leaving the
4563 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4564
4565 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4566
4567 static void
4568 transpose_markers (ptrdiff_t start1, ptrdiff_t end1,
4569 ptrdiff_t start2, ptrdiff_t end2,
4570 ptrdiff_t start1_byte, ptrdiff_t end1_byte,
4571 ptrdiff_t start2_byte, ptrdiff_t end2_byte)
4572 {
4573 register ptrdiff_t amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4574 register struct Lisp_Marker *marker;
4575
4576 /* Update point as if it were a marker. */
4577 if (PT < start1)
4578 ;
4579 else if (PT < end1)
4580 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4581 PT_BYTE + (end2_byte - end1_byte));
4582 else if (PT < start2)
4583 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4584 (PT_BYTE + (end2_byte - start2_byte)
4585 - (end1_byte - start1_byte)));
4586 else if (PT < end2)
4587 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4588 PT_BYTE - (start2_byte - start1_byte));
4589
4590 /* We used to adjust the endpoints here to account for the gap, but that
4591 isn't good enough. Even if we assume the caller has tried to move the
4592 gap out of our way, it might still be at start1 exactly, for example;
4593 and that places it `inside' the interval, for our purposes. The amount
4594 of adjustment is nontrivial if there's a `denormalized' marker whose
4595 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4596 the dirty work to Fmarker_position, below. */
4597
4598 /* The difference between the region's lengths */
4599 diff = (end2 - start2) - (end1 - start1);
4600 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4601
4602 /* For shifting each marker in a region by the length of the other
4603 region plus the distance between the regions. */
4604 amt1 = (end2 - start2) + (start2 - end1);
4605 amt2 = (end1 - start1) + (start2 - end1);
4606 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4607 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4608
4609 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4610 {
4611 mpos = marker->bytepos;
4612 if (mpos >= start1_byte && mpos < end2_byte)
4613 {
4614 if (mpos < end1_byte)
4615 mpos += amt1_byte;
4616 else if (mpos < start2_byte)
4617 mpos += diff_byte;
4618 else
4619 mpos -= amt2_byte;
4620 marker->bytepos = mpos;
4621 }
4622 mpos = marker->charpos;
4623 if (mpos >= start1 && mpos < end2)
4624 {
4625 if (mpos < end1)
4626 mpos += amt1;
4627 else if (mpos < start2)
4628 mpos += diff;
4629 else
4630 mpos -= amt2;
4631 }
4632 marker->charpos = mpos;
4633 }
4634 }
4635
4636 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4637 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4638 The regions should not be overlapping, because the size of the buffer is
4639 never changed in a transposition.
4640
4641 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4642 any markers that happen to be located in the regions.
4643
4644 Transposing beyond buffer boundaries is an error. */)
4645 (Lisp_Object startr1, Lisp_Object endr1, Lisp_Object startr2, Lisp_Object endr2, Lisp_Object leave_markers)
4646 {
4647 register ptrdiff_t start1, end1, start2, end2;
4648 ptrdiff_t start1_byte, start2_byte, len1_byte, len2_byte, end2_byte;
4649 ptrdiff_t gap, len1, len_mid, len2;
4650 unsigned char *start1_addr, *start2_addr, *temp;
4651
4652 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4653 Lisp_Object buf;
4654
4655 XSETBUFFER (buf, current_buffer);
4656 cur_intv = buffer_intervals (current_buffer);
4657
4658 validate_region (&startr1, &endr1);
4659 validate_region (&startr2, &endr2);
4660
4661 start1 = XFASTINT (startr1);
4662 end1 = XFASTINT (endr1);
4663 start2 = XFASTINT (startr2);
4664 end2 = XFASTINT (endr2);
4665 gap = GPT;
4666
4667 /* Swap the regions if they're reversed. */
4668 if (start2 < end1)
4669 {
4670 register ptrdiff_t glumph = start1;
4671 start1 = start2;
4672 start2 = glumph;
4673 glumph = end1;
4674 end1 = end2;
4675 end2 = glumph;
4676 }
4677
4678 len1 = end1 - start1;
4679 len2 = end2 - start2;
4680
4681 if (start2 < end1)
4682 error ("Transposed regions overlap");
4683 /* Nothing to change for adjacent regions with one being empty */
4684 else if ((start1 == end1 || start2 == end2) && end1 == start2)
4685 return Qnil;
4686
4687 /* The possibilities are:
4688 1. Adjacent (contiguous) regions, or separate but equal regions
4689 (no, really equal, in this case!), or
4690 2. Separate regions of unequal size.
4691
4692 The worst case is usually No. 2. It means that (aside from
4693 potential need for getting the gap out of the way), there also
4694 needs to be a shifting of the text between the two regions. So
4695 if they are spread far apart, we are that much slower... sigh. */
4696
4697 /* It must be pointed out that the really studly thing to do would
4698 be not to move the gap at all, but to leave it in place and work
4699 around it if necessary. This would be extremely efficient,
4700 especially considering that people are likely to do
4701 transpositions near where they are working interactively, which
4702 is exactly where the gap would be found. However, such code
4703 would be much harder to write and to read. So, if you are
4704 reading this comment and are feeling squirrely, by all means have
4705 a go! I just didn't feel like doing it, so I will simply move
4706 the gap the minimum distance to get it out of the way, and then
4707 deal with an unbroken array. */
4708
4709 start1_byte = CHAR_TO_BYTE (start1);
4710 end2_byte = CHAR_TO_BYTE (end2);
4711
4712 /* Make sure the gap won't interfere, by moving it out of the text
4713 we will operate on. */
4714 if (start1 < gap && gap < end2)
4715 {
4716 if (gap - start1 < end2 - gap)
4717 move_gap_both (start1, start1_byte);
4718 else
4719 move_gap_both (end2, end2_byte);
4720 }
4721
4722 start2_byte = CHAR_TO_BYTE (start2);
4723 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4724 len2_byte = end2_byte - start2_byte;
4725
4726 #ifdef BYTE_COMBINING_DEBUG
4727 if (end1 == start2)
4728 {
4729 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4730 len2_byte, start1, start1_byte)
4731 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4732 len1_byte, end2, start2_byte + len2_byte)
4733 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4734 len1_byte, end2, start2_byte + len2_byte))
4735 emacs_abort ();
4736 }
4737 else
4738 {
4739 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4740 len2_byte, start1, start1_byte)
4741 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4742 len1_byte, start2, start2_byte)
4743 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4744 len2_byte, end1, start1_byte + len1_byte)
4745 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4746 len1_byte, end2, start2_byte + len2_byte))
4747 emacs_abort ();
4748 }
4749 #endif
4750
4751 /* Hmmm... how about checking to see if the gap is large
4752 enough to use as the temporary storage? That would avoid an
4753 allocation... interesting. Later, don't fool with it now. */
4754
4755 /* Working without memmove, for portability (sigh), so must be
4756 careful of overlapping subsections of the array... */
4757
4758 if (end1 == start2) /* adjacent regions */
4759 {
4760 modify_text (start1, end2);
4761 record_change (start1, len1 + len2);
4762
4763 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4764 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4765 /* Don't use Fset_text_properties: that can cause GC, which can
4766 clobber objects stored in the tmp_intervals. */
4767 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4768 if (tmp_interval3)
4769 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4770
4771 USE_SAFE_ALLOCA;
4772
4773 /* First region smaller than second. */
4774 if (len1_byte < len2_byte)
4775 {
4776 temp = SAFE_ALLOCA (len2_byte);
4777
4778 /* Don't precompute these addresses. We have to compute them
4779 at the last minute, because the relocating allocator might
4780 have moved the buffer around during the xmalloc. */
4781 start1_addr = BYTE_POS_ADDR (start1_byte);
4782 start2_addr = BYTE_POS_ADDR (start2_byte);
4783
4784 memcpy (temp, start2_addr, len2_byte);
4785 memcpy (start1_addr + len2_byte, start1_addr, len1_byte);
4786 memcpy (start1_addr, temp, len2_byte);
4787 }
4788 else
4789 /* First region not smaller than second. */
4790 {
4791 temp = SAFE_ALLOCA (len1_byte);
4792 start1_addr = BYTE_POS_ADDR (start1_byte);
4793 start2_addr = BYTE_POS_ADDR (start2_byte);
4794 memcpy (temp, start1_addr, len1_byte);
4795 memcpy (start1_addr, start2_addr, len2_byte);
4796 memcpy (start1_addr + len2_byte, temp, len1_byte);
4797 }
4798
4799 SAFE_FREE ();
4800 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4801 len1, current_buffer, 0);
4802 graft_intervals_into_buffer (tmp_interval2, start1,
4803 len2, current_buffer, 0);
4804 update_compositions (start1, start1 + len2, CHECK_BORDER);
4805 update_compositions (start1 + len2, end2, CHECK_TAIL);
4806 }
4807 /* Non-adjacent regions, because end1 != start2, bleagh... */
4808 else
4809 {
4810 len_mid = start2_byte - (start1_byte + len1_byte);
4811
4812 if (len1_byte == len2_byte)
4813 /* Regions are same size, though, how nice. */
4814 {
4815 USE_SAFE_ALLOCA;
4816
4817 modify_text (start1, end1);
4818 modify_text (start2, end2);
4819 record_change (start1, len1);
4820 record_change (start2, len2);
4821 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4822 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4823
4824 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4825 if (tmp_interval3)
4826 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4827
4828 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4829 if (tmp_interval3)
4830 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
4831
4832 temp = SAFE_ALLOCA (len1_byte);
4833 start1_addr = BYTE_POS_ADDR (start1_byte);
4834 start2_addr = BYTE_POS_ADDR (start2_byte);
4835 memcpy (temp, start1_addr, len1_byte);
4836 memcpy (start1_addr, start2_addr, len2_byte);
4837 memcpy (start2_addr, temp, len1_byte);
4838 SAFE_FREE ();
4839
4840 graft_intervals_into_buffer (tmp_interval1, start2,
4841 len1, current_buffer, 0);
4842 graft_intervals_into_buffer (tmp_interval2, start1,
4843 len2, current_buffer, 0);
4844 }
4845
4846 else if (len1_byte < len2_byte) /* Second region larger than first */
4847 /* Non-adjacent & unequal size, area between must also be shifted. */
4848 {
4849 USE_SAFE_ALLOCA;
4850
4851 modify_text (start1, end2);
4852 record_change (start1, (end2 - start1));
4853 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4854 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4855 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4856
4857 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4858 if (tmp_interval3)
4859 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4860
4861 /* holds region 2 */
4862 temp = SAFE_ALLOCA (len2_byte);
4863 start1_addr = BYTE_POS_ADDR (start1_byte);
4864 start2_addr = BYTE_POS_ADDR (start2_byte);
4865 memcpy (temp, start2_addr, len2_byte);
4866 memcpy (start1_addr + len_mid + len2_byte, start1_addr, len1_byte);
4867 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4868 memcpy (start1_addr, temp, len2_byte);
4869 SAFE_FREE ();
4870
4871 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4872 len1, current_buffer, 0);
4873 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4874 len_mid, current_buffer, 0);
4875 graft_intervals_into_buffer (tmp_interval2, start1,
4876 len2, current_buffer, 0);
4877 }
4878 else
4879 /* Second region smaller than first. */
4880 {
4881 USE_SAFE_ALLOCA;
4882
4883 record_change (start1, (end2 - start1));
4884 modify_text (start1, end2);
4885
4886 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4887 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4888 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4889
4890 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4891 if (tmp_interval3)
4892 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4893
4894 /* holds region 1 */
4895 temp = SAFE_ALLOCA (len1_byte);
4896 start1_addr = BYTE_POS_ADDR (start1_byte);
4897 start2_addr = BYTE_POS_ADDR (start2_byte);
4898 memcpy (temp, start1_addr, len1_byte);
4899 memcpy (start1_addr, start2_addr, len2_byte);
4900 memcpy (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4901 memcpy (start1_addr + len2_byte + len_mid, temp, len1_byte);
4902 SAFE_FREE ();
4903
4904 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4905 len1, current_buffer, 0);
4906 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4907 len_mid, current_buffer, 0);
4908 graft_intervals_into_buffer (tmp_interval2, start1,
4909 len2, current_buffer, 0);
4910 }
4911
4912 update_compositions (start1, start1 + len2, CHECK_BORDER);
4913 update_compositions (end2 - len1, end2, CHECK_BORDER);
4914 }
4915
4916 /* When doing multiple transpositions, it might be nice
4917 to optimize this. Perhaps the markers in any one buffer
4918 should be organized in some sorted data tree. */
4919 if (NILP (leave_markers))
4920 {
4921 transpose_markers (start1, end1, start2, end2,
4922 start1_byte, start1_byte + len1_byte,
4923 start2_byte, start2_byte + len2_byte);
4924 fix_start_end_in_overlays (start1, end2);
4925 }
4926
4927 signal_after_change (start1, end2 - start1, end2 - start1);
4928 return Qnil;
4929 }
4930
4931 \f
4932 void
4933 syms_of_editfns (void)
4934 {
4935 DEFSYM (Qbuffer_access_fontify_functions, "buffer-access-fontify-functions");
4936
4937 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion,
4938 doc: /* Non-nil means text motion commands don't notice fields. */);
4939 Vinhibit_field_text_motion = Qnil;
4940
4941 DEFVAR_LISP ("buffer-access-fontify-functions",
4942 Vbuffer_access_fontify_functions,
4943 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4944 Each function is called with two arguments which specify the range
4945 of the buffer being accessed. */);
4946 Vbuffer_access_fontify_functions = Qnil;
4947
4948 {
4949 Lisp_Object obuf;
4950 obuf = Fcurrent_buffer ();
4951 /* Do this here, because init_buffer_once is too early--it won't work. */
4952 Fset_buffer (Vprin1_to_string_buffer);
4953 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4954 Fset (Fmake_local_variable (intern_c_string ("buffer-access-fontify-functions")),
4955 Qnil);
4956 Fset_buffer (obuf);
4957 }
4958
4959 DEFVAR_LISP ("buffer-access-fontified-property",
4960 Vbuffer_access_fontified_property,
4961 doc: /* Property which (if non-nil) indicates text has been fontified.
4962 `buffer-substring' need not call the `buffer-access-fontify-functions'
4963 functions if all the text being accessed has this property. */);
4964 Vbuffer_access_fontified_property = Qnil;
4965
4966 DEFVAR_LISP ("system-name", Vsystem_name,
4967 doc: /* The host name of the machine Emacs is running on. */);
4968
4969 DEFVAR_LISP ("user-full-name", Vuser_full_name,
4970 doc: /* The full name of the user logged in. */);
4971
4972 DEFVAR_LISP ("user-login-name", Vuser_login_name,
4973 doc: /* The user's name, taken from environment variables if possible. */);
4974
4975 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name,
4976 doc: /* The user's name, based upon the real uid only. */);
4977
4978 DEFVAR_LISP ("operating-system-release", Voperating_system_release,
4979 doc: /* The release of the operating system Emacs is running on. */);
4980
4981 defsubr (&Spropertize);
4982 defsubr (&Schar_equal);
4983 defsubr (&Sgoto_char);
4984 defsubr (&Sstring_to_char);
4985 defsubr (&Schar_to_string);
4986 defsubr (&Sbyte_to_string);
4987 defsubr (&Sbuffer_substring);
4988 defsubr (&Sbuffer_substring_no_properties);
4989 defsubr (&Sbuffer_string);
4990 defsubr (&Sget_pos_property);
4991
4992 defsubr (&Spoint_marker);
4993 defsubr (&Smark_marker);
4994 defsubr (&Spoint);
4995 defsubr (&Sregion_beginning);
4996 defsubr (&Sregion_end);
4997
4998 DEFSYM (Qfield, "field");
4999 DEFSYM (Qboundary, "boundary");
5000 defsubr (&Sfield_beginning);
5001 defsubr (&Sfield_end);
5002 defsubr (&Sfield_string);
5003 defsubr (&Sfield_string_no_properties);
5004 defsubr (&Sdelete_field);
5005 defsubr (&Sconstrain_to_field);
5006
5007 defsubr (&Sline_beginning_position);
5008 defsubr (&Sline_end_position);
5009
5010 defsubr (&Ssave_excursion);
5011 defsubr (&Ssave_current_buffer);
5012
5013 defsubr (&Sbuffer_size);
5014 defsubr (&Spoint_max);
5015 defsubr (&Spoint_min);
5016 defsubr (&Spoint_min_marker);
5017 defsubr (&Spoint_max_marker);
5018 defsubr (&Sgap_position);
5019 defsubr (&Sgap_size);
5020 defsubr (&Sposition_bytes);
5021 defsubr (&Sbyte_to_position);
5022
5023 defsubr (&Sbobp);
5024 defsubr (&Seobp);
5025 defsubr (&Sbolp);
5026 defsubr (&Seolp);
5027 defsubr (&Sfollowing_char);
5028 defsubr (&Sprevious_char);
5029 defsubr (&Schar_after);
5030 defsubr (&Schar_before);
5031 defsubr (&Sinsert);
5032 defsubr (&Sinsert_before_markers);
5033 defsubr (&Sinsert_and_inherit);
5034 defsubr (&Sinsert_and_inherit_before_markers);
5035 defsubr (&Sinsert_char);
5036 defsubr (&Sinsert_byte);
5037
5038 defsubr (&Suser_login_name);
5039 defsubr (&Suser_real_login_name);
5040 defsubr (&Suser_uid);
5041 defsubr (&Suser_real_uid);
5042 defsubr (&Sgroup_gid);
5043 defsubr (&Sgroup_real_gid);
5044 defsubr (&Suser_full_name);
5045 defsubr (&Semacs_pid);
5046 defsubr (&Scurrent_time);
5047 defsubr (&Stime_add);
5048 defsubr (&Stime_subtract);
5049 defsubr (&Stime_less_p);
5050 defsubr (&Sget_internal_run_time);
5051 defsubr (&Sformat_time_string);
5052 defsubr (&Sfloat_time);
5053 defsubr (&Sdecode_time);
5054 defsubr (&Sencode_time);
5055 defsubr (&Scurrent_time_string);
5056 defsubr (&Scurrent_time_zone);
5057 defsubr (&Sset_time_zone_rule);
5058 defsubr (&Ssystem_name);
5059 defsubr (&Smessage);
5060 defsubr (&Smessage_box);
5061 defsubr (&Smessage_or_box);
5062 defsubr (&Scurrent_message);
5063 defsubr (&Sformat);
5064
5065 defsubr (&Sinsert_buffer_substring);
5066 defsubr (&Scompare_buffer_substrings);
5067 defsubr (&Ssubst_char_in_region);
5068 defsubr (&Stranslate_region_internal);
5069 defsubr (&Sdelete_region);
5070 defsubr (&Sdelete_and_extract_region);
5071 defsubr (&Swiden);
5072 defsubr (&Snarrow_to_region);
5073 defsubr (&Ssave_restriction);
5074 defsubr (&Stranspose_regions);
5075 }