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