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