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