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