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