1 /* Lisp functions pertaining to editing. -*- coding: utf-8 -*-
3 Copyright (C) 1985-1987, 1989, 1993-2017 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 <https://www.gnu.org/licenses/>. */
22 #include <sys/types.h>
32 #ifdef HAVE_SYS_UTSNAME_H
33 #include <sys/utsname.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
43 #if defined HAVE_SYS_RESOURCE_H
44 #include <sys/resource.h>
57 #include "composite.h"
58 #include "intervals.h"
59 #include "character.h"
63 #include "blockinput.h"
65 #define TM_YEAR_BASE 1900
68 extern Lisp_Object
w32_get_internal_run_time (void);
71 static struct lisp_time
lisp_time_struct (Lisp_Object
, int *);
72 static Lisp_Object
format_time_string (char const *, ptrdiff_t, struct timespec
,
73 Lisp_Object
, struct tm
*);
74 static long int tm_gmtoff (struct tm
*);
75 static int tm_diff (struct tm
*, struct tm
*);
76 static void update_buffer_properties (ptrdiff_t, ptrdiff_t);
78 #ifndef HAVE_TM_GMTOFF
79 # define HAVE_TM_GMTOFF false
82 enum { tzeqlen
= sizeof "TZ=" - 1 };
84 /* Time zones equivalent to current local time and to UTC, respectively. */
85 static timezone_t local_tz
;
86 static timezone_t
const utc_tz
= 0;
88 /* The cached value of Vsystem_name. This is used only to compare it
89 to Vsystem_name, so it need not be visible to the GC. */
90 static Lisp_Object cached_system_name
;
93 init_and_cache_system_name (void)
96 cached_system_name
= Vsystem_name
;
100 emacs_localtime_rz (timezone_t tz
, time_t const *t
, struct tm
*tm
)
102 tm
= localtime_rz (tz
, t
, tm
);
103 if (!tm
&& errno
== ENOMEM
)
104 memory_full (SIZE_MAX
);
109 emacs_mktime_z (timezone_t tz
, struct tm
*tm
)
112 time_t t
= mktime_z (tz
, tm
);
113 if (t
== (time_t) -1 && errno
== ENOMEM
)
114 memory_full (SIZE_MAX
);
118 /* Allocate a timezone, signaling on failure. */
120 xtzalloc (char const *name
)
122 timezone_t tz
= tzalloc (name
);
124 memory_full (SIZE_MAX
);
128 /* Free a timezone, except do not free the time zone for local time.
129 Freeing utc_tz is also a no-op. */
131 xtzfree (timezone_t tz
)
137 /* Convert the Lisp time zone rule ZONE to a timezone_t object.
138 The returned value either is 0, or is LOCAL_TZ, or is newly allocated.
139 If SETTZ, set Emacs local time to the time zone rule; otherwise,
140 the caller should eventually pass the returned value to xtzfree. */
142 tzlookup (Lisp_Object zone
, bool settz
)
144 static char const tzbuf_format
[] = "<%+.*"pI
"d>%s%"pI
"d:%02d:%02d";
145 char const *trailing_tzbuf_format
= tzbuf_format
+ sizeof "<%+.*"pI
"d" - 1;
146 char tzbuf
[sizeof tzbuf_format
+ 2 * INT_STRLEN_BOUND (EMACS_INT
)];
147 char const *zone_string
;
152 else if (EQ (zone
, Qt
))
154 zone_string
= "UTC0";
159 bool plain_integer
= INTEGERP (zone
);
161 if (EQ (zone
, Qwall
))
163 else if (STRINGP (zone
))
164 zone_string
= SSDATA (ENCODE_SYSTEM (zone
));
165 else if (plain_integer
|| (CONSP (zone
) && INTEGERP (XCAR (zone
))
166 && CONSP (XCDR (zone
))))
171 abbr
= XCAR (XCDR (zone
));
175 EMACS_INT abszone
= eabs (XINT (zone
)), hour
= abszone
/ (60 * 60);
176 int hour_remainder
= abszone
% (60 * 60);
177 int min
= hour_remainder
/ 60, sec
= hour_remainder
% 60;
182 EMACS_INT numzone
= hour
;
183 if (hour_remainder
!= 0)
185 prec
+= 2, numzone
= 100 * numzone
+ min
;
187 prec
+= 2, numzone
= 100 * numzone
+ sec
;
189 sprintf (tzbuf
, tzbuf_format
, prec
,
190 XINT (zone
) < 0 ? -numzone
: numzone
,
191 &"-"[XINT (zone
) < 0], hour
, min
, sec
);
196 AUTO_STRING (leading
, "<");
197 AUTO_STRING_WITH_LEN (trailing
, tzbuf
,
198 sprintf (tzbuf
, trailing_tzbuf_format
,
199 &"-"[XINT (zone
) < 0],
201 zone_string
= SSDATA (concat3 (leading
, ENCODE_SYSTEM (abbr
),
206 xsignal2 (Qerror
, build_string ("Invalid time zone specification"),
208 new_tz
= xtzalloc (zone_string
);
214 emacs_setenv_TZ (zone_string
);
216 timezone_t old_tz
= local_tz
;
226 init_editfns (bool dumping
)
228 #if !defined CANNOT_DUMP
229 /* A valid but unlikely setting for the TZ environment variable.
230 It is OK (though a bit slower) if the user chooses this value. */
231 static char dump_tz_string
[] = "TZ=UtC0";
234 const char *user_name
;
236 struct passwd
*pw
; /* password entry for the current user */
239 /* Set up system_name even when dumping. */
240 init_and_cache_system_name ();
243 /* When just dumping out, set the time zone to a known unlikely value
244 and skip the rest of this function. */
247 xputenv (dump_tz_string
);
253 char *tz
= getenv ("TZ");
255 #if !defined CANNOT_DUMP
256 /* If the execution TZ happens to be the same as the dump TZ,
257 change it to some other value and then change it back,
258 to force the underlying implementation to reload the TZ info.
259 This is needed on implementations that load TZ info from files,
260 since the TZ file contents may differ between dump and execution. */
261 if (tz
&& strcmp (tz
, &dump_tz_string
[tzeqlen
]) == 0)
269 /* Set the time zone rule now, so that the call to putenv is done
270 before multiple threads are active. */
271 tzlookup (tz
? build_string (tz
) : Qwall
, true);
273 pw
= getpwuid (getuid ());
275 /* We let the real user name default to "root" because that's quite
276 accurate on MS-DOS and because it lets Emacs find the init file.
277 (The DVX libraries override the Djgpp libraries here.) */
278 Vuser_real_login_name
= build_string (pw
? pw
->pw_name
: "root");
280 Vuser_real_login_name
= build_string (pw
? pw
->pw_name
: "unknown");
283 /* Get the effective user name, by consulting environment variables,
284 or the effective uid if those are unset. */
285 user_name
= getenv ("LOGNAME");
288 user_name
= getenv ("USERNAME"); /* it's USERNAME on NT */
289 #else /* WINDOWSNT */
290 user_name
= getenv ("USER");
291 #endif /* WINDOWSNT */
294 pw
= getpwuid (geteuid ());
295 user_name
= pw
? pw
->pw_name
: "unknown";
297 Vuser_login_name
= build_string (user_name
);
299 /* If the user name claimed in the environment vars differs from
300 the real uid, use the claimed name to find the full name. */
301 tem
= Fstring_equal (Vuser_login_name
, Vuser_real_login_name
);
303 tem
= Vuser_login_name
;
306 uid_t euid
= geteuid ();
307 tem
= make_fixnum_or_float (euid
);
309 Vuser_full_name
= Fuser_full_name (tem
);
313 Vuser_full_name
= build_string (p
);
314 else if (NILP (Vuser_full_name
))
315 Vuser_full_name
= build_string ("unknown");
317 #ifdef HAVE_SYS_UTSNAME_H
321 Voperating_system_release
= build_string (uts
.release
);
324 Voperating_system_release
= Qnil
;
328 DEFUN ("char-to-string", Fchar_to_string
, Schar_to_string
, 1, 1, 0,
329 doc
: /* Convert arg CHAR to a string containing that character.
330 usage: (char-to-string CHAR) */)
331 (Lisp_Object character
)
334 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
336 CHECK_CHARACTER (character
);
337 c
= XFASTINT (character
);
339 len
= CHAR_STRING (c
, str
);
340 return make_string_from_bytes ((char *) str
, 1, len
);
343 DEFUN ("byte-to-string", Fbyte_to_string
, Sbyte_to_string
, 1, 1, 0,
344 doc
: /* Convert arg BYTE to a unibyte string containing that byte. */)
349 if (XINT (byte
) < 0 || XINT (byte
) > 255)
350 error ("Invalid byte");
352 return make_string_from_bytes ((char *) &b
, 1, 1);
355 DEFUN ("string-to-char", Fstring_to_char
, Sstring_to_char
, 1, 1, 0,
356 doc
: /* Return the first character in STRING. */)
357 (register Lisp_Object string
)
359 register Lisp_Object val
;
360 CHECK_STRING (string
);
363 if (STRING_MULTIBYTE (string
))
364 XSETFASTINT (val
, STRING_CHAR (SDATA (string
)));
366 XSETFASTINT (val
, SREF (string
, 0));
369 XSETFASTINT (val
, 0);
373 DEFUN ("point", Fpoint
, Spoint
, 0, 0, 0,
374 doc
: /* Return value of point, as an integer.
375 Beginning of buffer is position (point-min). */)
379 XSETFASTINT (temp
, PT
);
383 DEFUN ("point-marker", Fpoint_marker
, Spoint_marker
, 0, 0, 0,
384 doc
: /* Return value of point, as a marker object. */)
387 return build_marker (current_buffer
, PT
, PT_BYTE
);
390 DEFUN ("goto-char", Fgoto_char
, Sgoto_char
, 1, 1, "NGoto char: ",
391 doc
: /* Set point to POSITION, a number or marker.
392 Beginning of buffer is position (point-min), end is (point-max).
394 The return value is POSITION. */)
395 (register Lisp_Object position
)
397 if (MARKERP (position
))
398 set_point_from_marker (position
);
399 else if (INTEGERP (position
))
400 SET_PT (clip_to_bounds (BEGV
, XINT (position
), ZV
));
402 wrong_type_argument (Qinteger_or_marker_p
, position
);
407 /* Return the start or end position of the region.
408 BEGINNINGP means return the start.
409 If there is no region active, signal an error. */
412 region_limit (bool beginningp
)
416 if (!NILP (Vtransient_mark_mode
)
417 && NILP (Vmark_even_if_inactive
)
418 && NILP (BVAR (current_buffer
, mark_active
)))
419 xsignal0 (Qmark_inactive
);
421 m
= Fmarker_position (BVAR (current_buffer
, mark
));
423 error ("The mark is not set now, so there is no region");
425 /* Clip to the current narrowing (bug#11770). */
426 return make_number ((PT
< XFASTINT (m
)) == beginningp
428 : clip_to_bounds (BEGV
, XFASTINT (m
), ZV
));
431 DEFUN ("region-beginning", Fregion_beginning
, Sregion_beginning
, 0, 0, 0,
432 doc
: /* Return the integer value of point or mark, whichever is smaller. */)
435 return region_limit (1);
438 DEFUN ("region-end", Fregion_end
, Sregion_end
, 0, 0, 0,
439 doc
: /* Return the integer value of point or mark, whichever is larger. */)
442 return region_limit (0);
445 DEFUN ("mark-marker", Fmark_marker
, Smark_marker
, 0, 0, 0,
446 doc
: /* Return this buffer's mark, as a marker object.
447 Watch out! Moving this marker changes the mark position.
448 If you set the marker not to point anywhere, the buffer will have no mark. */)
451 return BVAR (current_buffer
, mark
);
455 /* Find all the overlays in the current buffer that touch position POS.
456 Return the number found, and store them in a vector in VEC
460 overlays_around (EMACS_INT pos
, Lisp_Object
*vec
, ptrdiff_t len
)
462 Lisp_Object overlay
, start
, end
;
463 struct Lisp_Overlay
*tail
;
464 ptrdiff_t startpos
, endpos
;
467 for (tail
= current_buffer
->overlays_before
; tail
; tail
= tail
->next
)
469 XSETMISC (overlay
, tail
);
471 end
= OVERLAY_END (overlay
);
472 endpos
= OVERLAY_POSITION (end
);
475 start
= OVERLAY_START (overlay
);
476 startpos
= OVERLAY_POSITION (start
);
481 /* Keep counting overlays even if we can't return them all. */
486 for (tail
= current_buffer
->overlays_after
; tail
; tail
= tail
->next
)
488 XSETMISC (overlay
, tail
);
490 start
= OVERLAY_START (overlay
);
491 startpos
= OVERLAY_POSITION (start
);
494 end
= OVERLAY_END (overlay
);
495 endpos
= OVERLAY_POSITION (end
);
507 DEFUN ("get-pos-property", Fget_pos_property
, Sget_pos_property
, 2, 3, 0,
508 doc
: /* Return the value of POSITION's property PROP, in OBJECT.
509 Almost identical to `get-char-property' except for the following difference:
510 Whereas `get-char-property' returns the property of the char at (i.e. right
511 after) POSITION, this pays attention to properties's stickiness and overlays's
512 advancement settings, in order to find the property of POSITION itself,
513 i.e. the property that a char would inherit if it were inserted
515 (Lisp_Object position
, register Lisp_Object prop
, Lisp_Object object
)
517 CHECK_NUMBER_COERCE_MARKER (position
);
520 XSETBUFFER (object
, current_buffer
);
521 else if (WINDOWP (object
))
522 object
= XWINDOW (object
)->contents
;
524 if (!BUFFERP (object
))
525 /* pos-property only makes sense in buffers right now, since strings
526 have no overlays and no notion of insertion for which stickiness
528 return Fget_text_property (position
, prop
, object
);
531 EMACS_INT posn
= XINT (position
);
533 Lisp_Object
*overlay_vec
, tem
;
534 struct buffer
*obuf
= current_buffer
;
537 set_buffer_temp (XBUFFER (object
));
539 /* First try with room for 40 overlays. */
540 Lisp_Object overlay_vecbuf
[40];
541 noverlays
= ARRAYELTS (overlay_vecbuf
);
542 overlay_vec
= overlay_vecbuf
;
543 noverlays
= overlays_around (posn
, overlay_vec
, noverlays
);
545 /* If there are more than 40,
546 make enough space for all, and try again. */
547 if (ARRAYELTS (overlay_vecbuf
) < noverlays
)
549 SAFE_ALLOCA_LISP (overlay_vec
, noverlays
);
550 noverlays
= overlays_around (posn
, overlay_vec
, noverlays
);
552 noverlays
= sort_overlays (overlay_vec
, noverlays
, NULL
);
554 set_buffer_temp (obuf
);
556 /* Now check the overlays in order of decreasing priority. */
557 while (--noverlays
>= 0)
559 Lisp_Object ol
= overlay_vec
[noverlays
];
560 tem
= Foverlay_get (ol
, prop
);
563 /* Check the overlay is indeed active at point. */
564 Lisp_Object start
= OVERLAY_START (ol
), finish
= OVERLAY_END (ol
);
565 if ((OVERLAY_POSITION (start
) == posn
566 && XMARKER (start
)->insertion_type
== 1)
567 || (OVERLAY_POSITION (finish
) == posn
568 && XMARKER (finish
)->insertion_type
== 0))
569 ; /* The overlay will not cover a char inserted at point. */
579 { /* Now check the text properties. */
580 int stickiness
= text_property_stickiness (prop
, position
, object
);
582 return Fget_text_property (position
, prop
, object
);
583 else if (stickiness
< 0
584 && XINT (position
) > BUF_BEGV (XBUFFER (object
)))
585 return Fget_text_property (make_number (XINT (position
) - 1),
593 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
594 the value of point is used instead. If BEG or END is null,
595 means don't store the beginning or end of the field.
597 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
598 results; they do not effect boundary behavior.
600 If MERGE_AT_BOUNDARY is non-nil, then if POS is at the very first
601 position of a field, then the beginning of the previous field is
602 returned instead of the beginning of POS's field (since the end of a
603 field is actually also the beginning of the next input field, this
604 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
605 non-nil case, if two fields are separated by a field with the special
606 value `boundary', and POS lies within it, then the two separated
607 fields are considered to be adjacent, and POS between them, when
608 finding the beginning and ending of the "merged" field.
610 Either BEG or END may be 0, in which case the corresponding value
614 find_field (Lisp_Object pos
, Lisp_Object merge_at_boundary
,
615 Lisp_Object beg_limit
,
616 ptrdiff_t *beg
, Lisp_Object end_limit
, ptrdiff_t *end
)
618 /* Fields right before and after the point. */
619 Lisp_Object before_field
, after_field
;
620 /* True if POS counts as the start of a field. */
621 bool at_field_start
= 0;
622 /* True if POS counts as the end of a field. */
623 bool at_field_end
= 0;
626 XSETFASTINT (pos
, PT
);
628 CHECK_NUMBER_COERCE_MARKER (pos
);
631 = get_char_property_and_overlay (pos
, Qfield
, Qnil
, NULL
);
633 = (XFASTINT (pos
) > BEGV
634 ? get_char_property_and_overlay (make_number (XINT (pos
) - 1),
636 /* Using nil here would be a more obvious choice, but it would
637 fail when the buffer starts with a non-sticky field. */
640 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
641 and POS is at beginning of a field, which can also be interpreted
642 as the end of the previous field. Note that the case where if
643 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
644 more natural one; then we avoid treating the beginning of a field
646 if (NILP (merge_at_boundary
))
648 Lisp_Object field
= Fget_pos_property (pos
, Qfield
, Qnil
);
649 if (!EQ (field
, after_field
))
651 if (!EQ (field
, before_field
))
653 if (NILP (field
) && at_field_start
&& at_field_end
)
654 /* If an inserted char would have a nil field while the surrounding
655 text is non-nil, we're probably not looking at a
656 zero-length field, but instead at a non-nil field that's
657 not intended for editing (such as comint's prompts). */
658 at_field_end
= at_field_start
= 0;
661 /* Note about special `boundary' fields:
663 Consider the case where the point (`.') is between the fields `x' and `y':
667 In this situation, if merge_at_boundary is non-nil, consider the
668 `x' and `y' fields as forming one big merged field, and so the end
669 of the field is the end of `y'.
671 However, if `x' and `y' are separated by a special `boundary' field
672 (a field with a `field' char-property of 'boundary), then ignore
673 this special field when merging adjacent fields. Here's the same
674 situation, but with a `boundary' field between the `x' and `y' fields:
678 Here, if point is at the end of `x', the beginning of `y', or
679 anywhere in-between (within the `boundary' field), merge all
680 three fields and consider the beginning as being the beginning of
681 the `x' field, and the end as being the end of the `y' field. */
686 /* POS is at the edge of a field, and we should consider it as
687 the beginning of the following field. */
688 *beg
= XFASTINT (pos
);
690 /* Find the previous field boundary. */
693 if (!NILP (merge_at_boundary
) && EQ (before_field
, Qboundary
))
694 /* Skip a `boundary' field. */
695 p
= Fprevious_single_char_property_change (p
, Qfield
, Qnil
,
698 p
= Fprevious_single_char_property_change (p
, Qfield
, Qnil
,
700 *beg
= NILP (p
) ? BEGV
: XFASTINT (p
);
707 /* POS is at the edge of a field, and we should consider it as
708 the end of the previous field. */
709 *end
= XFASTINT (pos
);
711 /* Find the next field boundary. */
713 if (!NILP (merge_at_boundary
) && EQ (after_field
, Qboundary
))
714 /* Skip a `boundary' field. */
715 pos
= Fnext_single_char_property_change (pos
, Qfield
, Qnil
,
718 pos
= Fnext_single_char_property_change (pos
, Qfield
, Qnil
,
720 *end
= NILP (pos
) ? ZV
: XFASTINT (pos
);
726 DEFUN ("delete-field", Fdelete_field
, Sdelete_field
, 0, 1, 0,
727 doc
: /* Delete the field surrounding POS.
728 A field is a region of text with the same `field' property.
729 If POS is nil, the value of point is used for POS. */)
733 find_field (pos
, Qnil
, Qnil
, &beg
, Qnil
, &end
);
735 del_range (beg
, end
);
739 DEFUN ("field-string", Ffield_string
, Sfield_string
, 0, 1, 0,
740 doc
: /* Return the contents of the field surrounding POS as a string.
741 A field is a region of text with the same `field' property.
742 If POS is nil, the value of point is used for POS. */)
746 find_field (pos
, Qnil
, Qnil
, &beg
, Qnil
, &end
);
747 return make_buffer_string (beg
, end
, 1);
750 DEFUN ("field-string-no-properties", Ffield_string_no_properties
, Sfield_string_no_properties
, 0, 1, 0,
751 doc
: /* Return the contents of the field around POS, without text properties.
752 A field is a region of text with the same `field' property.
753 If POS is nil, the value of point is used for POS. */)
757 find_field (pos
, Qnil
, Qnil
, &beg
, Qnil
, &end
);
758 return make_buffer_string (beg
, end
, 0);
761 DEFUN ("field-beginning", Ffield_beginning
, Sfield_beginning
, 0, 3, 0,
762 doc
: /* Return the beginning of the field surrounding POS.
763 A field is a region of text with the same `field' property.
764 If POS is nil, the value of point is used for POS.
765 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
766 field, then the beginning of the *previous* field is returned.
767 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
768 is before LIMIT, then LIMIT will be returned instead. */)
769 (Lisp_Object pos
, Lisp_Object escape_from_edge
, Lisp_Object limit
)
772 find_field (pos
, escape_from_edge
, limit
, &beg
, Qnil
, 0);
773 return make_number (beg
);
776 DEFUN ("field-end", Ffield_end
, Sfield_end
, 0, 3, 0,
777 doc
: /* Return the end of the field surrounding POS.
778 A field is a region of text with the same `field' property.
779 If POS is nil, the value of point is used for POS.
780 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
781 then the end of the *following* field is returned.
782 If LIMIT is non-nil, it is a buffer position; if the end of the field
783 is after LIMIT, then LIMIT will be returned instead. */)
784 (Lisp_Object pos
, Lisp_Object escape_from_edge
, Lisp_Object limit
)
787 find_field (pos
, escape_from_edge
, Qnil
, 0, limit
, &end
);
788 return make_number (end
);
791 DEFUN ("constrain-to-field", Fconstrain_to_field
, Sconstrain_to_field
, 2, 5, 0,
792 doc
: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
793 A field is a region of text with the same `field' property.
795 If NEW-POS is nil, then use the current point instead, and move point
796 to the resulting constrained position, in addition to returning that
799 If OLD-POS is at the boundary of two fields, then the allowable
800 positions for NEW-POS depends on the value of the optional argument
801 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
802 constrained to the field that has the same `field' char-property
803 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
804 is non-nil, NEW-POS is constrained to the union of the two adjacent
805 fields. Additionally, if two fields are separated by another field with
806 the special value `boundary', then any point within this special field is
807 also considered to be `on the boundary'.
809 If the optional argument ONLY-IN-LINE is non-nil and constraining
810 NEW-POS would move it to a different line, NEW-POS is returned
811 unconstrained. This is useful for commands that move by line, like
812 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
813 only in the case where they can still move to the right line.
815 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
816 a non-nil property of that name, then any field boundaries are ignored.
818 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
819 (Lisp_Object new_pos
, Lisp_Object old_pos
, Lisp_Object escape_from_edge
,
820 Lisp_Object only_in_line
, Lisp_Object inhibit_capture_property
)
822 /* If non-zero, then the original point, before re-positioning. */
823 ptrdiff_t orig_point
= 0;
825 Lisp_Object prev_old
, prev_new
;
828 /* Use the current point, and afterwards, set it. */
831 XSETFASTINT (new_pos
, PT
);
834 CHECK_NUMBER_COERCE_MARKER (new_pos
);
835 CHECK_NUMBER_COERCE_MARKER (old_pos
);
837 fwd
= (XINT (new_pos
) > XINT (old_pos
));
839 prev_old
= make_number (XINT (old_pos
) - 1);
840 prev_new
= make_number (XINT (new_pos
) - 1);
842 if (NILP (Vinhibit_field_text_motion
)
843 && !EQ (new_pos
, old_pos
)
844 && (!NILP (Fget_char_property (new_pos
, Qfield
, Qnil
))
845 || !NILP (Fget_char_property (old_pos
, Qfield
, Qnil
))
846 /* To recognize field boundaries, we must also look at the
847 previous positions; we could use `Fget_pos_property'
848 instead, but in itself that would fail inside non-sticky
849 fields (like comint prompts). */
850 || (XFASTINT (new_pos
) > BEGV
851 && !NILP (Fget_char_property (prev_new
, Qfield
, Qnil
)))
852 || (XFASTINT (old_pos
) > BEGV
853 && !NILP (Fget_char_property (prev_old
, Qfield
, Qnil
))))
854 && (NILP (inhibit_capture_property
)
855 /* Field boundaries are again a problem; but now we must
856 decide the case exactly, so we need to call
857 `get_pos_property' as well. */
858 || (NILP (Fget_pos_property (old_pos
, inhibit_capture_property
, Qnil
))
859 && (XFASTINT (old_pos
) <= BEGV
860 || NILP (Fget_char_property
861 (old_pos
, inhibit_capture_property
, Qnil
))
862 || NILP (Fget_char_property
863 (prev_old
, inhibit_capture_property
, Qnil
))))))
864 /* It is possible that NEW_POS is not within the same field as
865 OLD_POS; try to move NEW_POS so that it is. */
868 Lisp_Object field_bound
;
871 field_bound
= Ffield_end (old_pos
, escape_from_edge
, new_pos
);
873 field_bound
= Ffield_beginning (old_pos
, escape_from_edge
, new_pos
);
875 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
876 other side of NEW_POS, which would mean that NEW_POS is
877 already acceptable, and it's not necessary to constrain it
879 ((XFASTINT (field_bound
) < XFASTINT (new_pos
)) ? fwd
: !fwd
)
880 /* NEW_POS should be constrained, but only if either
881 ONLY_IN_LINE is nil (in which case any constraint is OK),
882 or NEW_POS and FIELD_BOUND are on the same line (in which
883 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
884 && (NILP (only_in_line
)
885 /* This is the ONLY_IN_LINE case, check that NEW_POS and
886 FIELD_BOUND are on the same line by seeing whether
887 there's an intervening newline or not. */
888 || (find_newline (XFASTINT (new_pos
), -1,
889 XFASTINT (field_bound
), -1,
890 fwd
? -1 : 1, &shortage
, NULL
, 1),
892 /* Constrain NEW_POS to FIELD_BOUND. */
893 new_pos
= field_bound
;
895 if (orig_point
&& XFASTINT (new_pos
) != orig_point
)
896 /* The NEW_POS argument was originally nil, so automatically set PT. */
897 SET_PT (XFASTINT (new_pos
));
904 DEFUN ("line-beginning-position",
905 Fline_beginning_position
, Sline_beginning_position
, 0, 1, 0,
906 doc
: /* Return the character position of the first character on the current line.
907 With optional argument N, scan forward N - 1 lines first.
908 If the scan reaches the end of the buffer, return that position.
910 This function ignores text display directionality; it returns the
911 position of the first character in logical order, i.e. the smallest
912 character position on the line.
914 This function constrains the returned position to the current field
915 unless that position would be on a different line than the original,
916 unconstrained result. If N is nil or 1, and a front-sticky field
917 starts at point, the scan stops as soon as it starts. To ignore field
918 boundaries, bind `inhibit-field-text-motion' to t.
920 This function does not move point. */)
923 ptrdiff_t charpos
, bytepos
;
930 scan_newline_from_point (XINT (n
) - 1, &charpos
, &bytepos
);
932 /* Return END constrained to the current input field. */
933 return Fconstrain_to_field (make_number (charpos
), make_number (PT
),
934 XINT (n
) != 1 ? Qt
: Qnil
,
938 DEFUN ("line-end-position", Fline_end_position
, Sline_end_position
, 0, 1, 0,
939 doc
: /* Return the character position of the last character on the current line.
940 With argument N not nil or 1, move forward N - 1 lines first.
941 If scan reaches end of buffer, return that position.
943 This function ignores text display directionality; it returns the
944 position of the last character in logical order, i.e. the largest
945 character position on the line.
947 This function constrains the returned position to the current field
948 unless that would be on a different line than the original,
949 unconstrained result. If N is nil or 1, and a rear-sticky field ends
950 at point, the scan stops as soon as it starts. To ignore field
951 boundaries bind `inhibit-field-text-motion' to t.
953 This function does not move point. */)
965 clipped_n
= clip_to_bounds (PTRDIFF_MIN
+ 1, XINT (n
), PTRDIFF_MAX
);
966 end_pos
= find_before_next_newline (orig
, 0, clipped_n
- (clipped_n
<= 0),
969 /* Return END_POS constrained to the current input field. */
970 return Fconstrain_to_field (make_number (end_pos
), make_number (orig
),
974 /* Save current buffer state for `save-excursion' special form.
975 We (ab)use Lisp_Misc_Save_Value to allow explicit free and so
976 offload some work from GC. */
979 save_excursion_save (void)
981 return make_save_obj_obj_obj_obj
984 /* Selected window if current buffer is shown in it, nil otherwise. */
985 (EQ (XWINDOW (selected_window
)->contents
, Fcurrent_buffer ())
986 ? selected_window
: Qnil
),
990 /* Restore saved buffer before leaving `save-excursion' special form. */
993 save_excursion_restore (Lisp_Object info
)
995 Lisp_Object tem
, tem1
;
997 tem
= Fmarker_buffer (XSAVE_OBJECT (info
, 0));
998 /* If we're unwinding to top level, saved buffer may be deleted. This
999 means that all of its markers are unchained and so tem is nil. */
1006 tem
= XSAVE_OBJECT (info
, 0);
1008 unchain_marker (XMARKER (tem
));
1010 /* If buffer was visible in a window, and a different window was
1011 selected, and the old selected window is still showing this
1012 buffer, restore point in that window. */
1013 tem
= XSAVE_OBJECT (info
, 2);
1015 && !EQ (tem
, selected_window
)
1016 && (tem1
= XWINDOW (tem
)->contents
,
1017 (/* Window is live... */
1019 /* ...and it shows the current buffer. */
1020 && XBUFFER (tem1
) == current_buffer
)))
1021 Fset_window_point (tem
, make_number (PT
));
1028 DEFUN ("save-excursion", Fsave_excursion
, Ssave_excursion
, 0, UNEVALLED
, 0,
1029 doc
: /* Save point, and current buffer; execute BODY; restore those things.
1030 Executes BODY just like `progn'.
1031 The values of point and the current buffer are restored
1032 even in case of abnormal exit (throw or error).
1034 If you only want to save the current buffer but not point,
1035 then just use `save-current-buffer', or even `with-current-buffer'.
1037 Before Emacs 25.1, `save-excursion' used to save the mark state.
1038 To save the marker state as well as the point and buffer, use
1039 `save-mark-and-excursion'.
1041 usage: (save-excursion &rest BODY) */)
1044 register Lisp_Object val
;
1045 ptrdiff_t count
= SPECPDL_INDEX ();
1047 record_unwind_protect (save_excursion_restore
, save_excursion_save ());
1049 val
= Fprogn (args
);
1050 return unbind_to (count
, val
);
1053 DEFUN ("save-current-buffer", Fsave_current_buffer
, Ssave_current_buffer
, 0, UNEVALLED
, 0,
1054 doc
: /* Record which buffer is current; execute BODY; make that buffer current.
1055 BODY is executed just like `progn'.
1056 usage: (save-current-buffer &rest BODY) */)
1059 ptrdiff_t count
= SPECPDL_INDEX ();
1061 record_unwind_current_buffer ();
1062 return unbind_to (count
, Fprogn (args
));
1065 DEFUN ("buffer-size", Fbuffer_size
, Sbuffer_size
, 0, 1, 0,
1066 doc
: /* Return the number of characters in the current buffer.
1067 If BUFFER is not nil, return the number of characters in that buffer
1070 This does not take narrowing into account; to count the number of
1071 characters in the accessible portion of the current buffer, use
1072 `(- (point-max) (point-min))', and to count the number of characters
1073 in some other BUFFER, use
1074 `(with-current-buffer BUFFER (- (point-max) (point-min)))'. */)
1075 (Lisp_Object buffer
)
1078 return make_number (Z
- BEG
);
1081 CHECK_BUFFER (buffer
);
1082 return make_number (BUF_Z (XBUFFER (buffer
))
1083 - BUF_BEG (XBUFFER (buffer
)));
1087 DEFUN ("point-min", Fpoint_min
, Spoint_min
, 0, 0, 0,
1088 doc
: /* Return the minimum permissible value of point in the current buffer.
1089 This is 1, unless narrowing (a buffer restriction) is in effect. */)
1093 XSETFASTINT (temp
, BEGV
);
1097 DEFUN ("point-min-marker", Fpoint_min_marker
, Spoint_min_marker
, 0, 0, 0,
1098 doc
: /* Return a marker to the minimum permissible value of point in this buffer.
1099 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1102 return build_marker (current_buffer
, BEGV
, BEGV_BYTE
);
1105 DEFUN ("point-max", Fpoint_max
, Spoint_max
, 0, 0, 0,
1106 doc
: /* Return the maximum permissible value of point in the current buffer.
1107 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1108 is in effect, in which case it is less. */)
1112 XSETFASTINT (temp
, ZV
);
1116 DEFUN ("point-max-marker", Fpoint_max_marker
, Spoint_max_marker
, 0, 0, 0,
1117 doc
: /* Return a marker to the maximum permissible value of point in this buffer.
1118 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1119 is in effect, in which case it is less. */)
1122 return build_marker (current_buffer
, ZV
, ZV_BYTE
);
1125 DEFUN ("gap-position", Fgap_position
, Sgap_position
, 0, 0, 0,
1126 doc
: /* Return the position of the gap, in the current buffer.
1127 See also `gap-size'. */)
1131 XSETFASTINT (temp
, GPT
);
1135 DEFUN ("gap-size", Fgap_size
, Sgap_size
, 0, 0, 0,
1136 doc
: /* Return the size of the current buffer's gap.
1137 See also `gap-position'. */)
1141 XSETFASTINT (temp
, GAP_SIZE
);
1145 DEFUN ("position-bytes", Fposition_bytes
, Sposition_bytes
, 1, 1, 0,
1146 doc
: /* Return the byte position for character position POSITION.
1147 If POSITION is out of range, the value is nil. */)
1148 (Lisp_Object position
)
1150 CHECK_NUMBER_COERCE_MARKER (position
);
1151 if (XINT (position
) < BEG
|| XINT (position
) > Z
)
1153 return make_number (CHAR_TO_BYTE (XINT (position
)));
1156 DEFUN ("byte-to-position", Fbyte_to_position
, Sbyte_to_position
, 1, 1, 0,
1157 doc
: /* Return the character position for byte position BYTEPOS.
1158 If BYTEPOS is out of range, the value is nil. */)
1159 (Lisp_Object bytepos
)
1163 CHECK_NUMBER (bytepos
);
1164 pos_byte
= XINT (bytepos
);
1165 if (pos_byte
< BEG_BYTE
|| pos_byte
> Z_BYTE
)
1168 /* There are multibyte characters in the buffer.
1169 The argument of BYTE_TO_CHAR must be a byte position at
1170 a character boundary, so search for the start of the current
1172 while (!CHAR_HEAD_P (FETCH_BYTE (pos_byte
)))
1174 return make_number (BYTE_TO_CHAR (pos_byte
));
1177 DEFUN ("following-char", Ffollowing_char
, Sfollowing_char
, 0, 0, 0,
1178 doc
: /* Return the character following point, as a number.
1179 At the end of the buffer or accessible region, return 0. */)
1184 XSETFASTINT (temp
, 0);
1186 XSETFASTINT (temp
, FETCH_CHAR (PT_BYTE
));
1190 DEFUN ("preceding-char", Fprevious_char
, Sprevious_char
, 0, 0, 0,
1191 doc
: /* Return the character preceding point, as a number.
1192 At the beginning of the buffer or accessible region, return 0. */)
1197 XSETFASTINT (temp
, 0);
1198 else if (!NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
1200 ptrdiff_t pos
= PT_BYTE
;
1202 XSETFASTINT (temp
, FETCH_CHAR (pos
));
1205 XSETFASTINT (temp
, FETCH_BYTE (PT_BYTE
- 1));
1209 DEFUN ("bobp", Fbobp
, Sbobp
, 0, 0, 0,
1210 doc
: /* Return t if point is at the beginning of the buffer.
1211 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1219 DEFUN ("eobp", Feobp
, Seobp
, 0, 0, 0,
1220 doc
: /* Return t if point is at the end of the buffer.
1221 If the buffer is narrowed, this means the end of the narrowed part. */)
1229 DEFUN ("bolp", Fbolp
, Sbolp
, 0, 0, 0,
1230 doc
: /* Return t if point is at the beginning of a line. */)
1233 if (PT
== BEGV
|| FETCH_BYTE (PT_BYTE
- 1) == '\n')
1238 DEFUN ("eolp", Feolp
, Seolp
, 0, 0, 0,
1239 doc
: /* Return t if point is at the end of a line.
1240 `End of a line' includes point being at the end of the buffer. */)
1243 if (PT
== ZV
|| FETCH_BYTE (PT_BYTE
) == '\n')
1248 DEFUN ("char-after", Fchar_after
, Schar_after
, 0, 1, 0,
1249 doc
: /* Return character in current buffer at position POS.
1250 POS is an integer or a marker and defaults to point.
1251 If POS is out of range, the value is nil. */)
1254 register ptrdiff_t pos_byte
;
1259 XSETFASTINT (pos
, PT
);
1264 pos_byte
= marker_byte_position (pos
);
1265 if (pos_byte
< BEGV_BYTE
|| pos_byte
>= ZV_BYTE
)
1270 CHECK_NUMBER_COERCE_MARKER (pos
);
1271 if (XINT (pos
) < BEGV
|| XINT (pos
) >= ZV
)
1274 pos_byte
= CHAR_TO_BYTE (XINT (pos
));
1277 return make_number (FETCH_CHAR (pos_byte
));
1280 DEFUN ("char-before", Fchar_before
, Schar_before
, 0, 1, 0,
1281 doc
: /* Return character in current buffer preceding position POS.
1282 POS is an integer or a marker and defaults to point.
1283 If POS is out of range, the value is nil. */)
1286 register Lisp_Object val
;
1287 register ptrdiff_t pos_byte
;
1292 XSETFASTINT (pos
, PT
);
1297 pos_byte
= marker_byte_position (pos
);
1299 if (pos_byte
<= BEGV_BYTE
|| pos_byte
> ZV_BYTE
)
1304 CHECK_NUMBER_COERCE_MARKER (pos
);
1306 if (XINT (pos
) <= BEGV
|| XINT (pos
) > ZV
)
1309 pos_byte
= CHAR_TO_BYTE (XINT (pos
));
1312 if (!NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
1315 XSETFASTINT (val
, FETCH_CHAR (pos_byte
));
1320 XSETFASTINT (val
, FETCH_BYTE (pos_byte
));
1325 DEFUN ("user-login-name", Fuser_login_name
, Suser_login_name
, 0, 1, 0,
1326 doc
: /* Return the name under which the user logged in, as a string.
1327 This is based on the effective uid, not the real uid.
1328 Also, if the environment variables LOGNAME or USER are set,
1329 that determines the value of this function.
1331 If optional argument UID is an integer or a float, return the login name
1332 of the user with that uid, or nil if there is no such user. */)
1338 /* Set up the user name info if we didn't do it before.
1339 (That can happen if Emacs is dumpable
1340 but you decide to run `temacs -l loadup' and not dump. */
1341 if (NILP (Vuser_login_name
))
1342 init_editfns (false);
1345 return Vuser_login_name
;
1347 CONS_TO_INTEGER (uid
, uid_t
, id
);
1351 return (pw
? build_string (pw
->pw_name
) : Qnil
);
1354 DEFUN ("user-real-login-name", Fuser_real_login_name
, Suser_real_login_name
,
1356 doc
: /* Return the name of the user's real uid, as a string.
1357 This ignores the environment variables LOGNAME and USER, so it differs from
1358 `user-login-name' when running under `su'. */)
1361 /* Set up the user name info if we didn't do it before.
1362 (That can happen if Emacs is dumpable
1363 but you decide to run `temacs -l loadup' and not dump. */
1364 if (NILP (Vuser_login_name
))
1365 init_editfns (false);
1366 return Vuser_real_login_name
;
1369 DEFUN ("user-uid", Fuser_uid
, Suser_uid
, 0, 0, 0,
1370 doc
: /* Return the effective uid of Emacs.
1371 Value is an integer or a float, depending on the value. */)
1374 uid_t euid
= geteuid ();
1375 return make_fixnum_or_float (euid
);
1378 DEFUN ("user-real-uid", Fuser_real_uid
, Suser_real_uid
, 0, 0, 0,
1379 doc
: /* Return the real uid of Emacs.
1380 Value is an integer or a float, depending on the value. */)
1383 uid_t uid
= getuid ();
1384 return make_fixnum_or_float (uid
);
1387 DEFUN ("group-gid", Fgroup_gid
, Sgroup_gid
, 0, 0, 0,
1388 doc
: /* Return the effective gid of Emacs.
1389 Value is an integer or a float, depending on the value. */)
1392 gid_t egid
= getegid ();
1393 return make_fixnum_or_float (egid
);
1396 DEFUN ("group-real-gid", Fgroup_real_gid
, Sgroup_real_gid
, 0, 0, 0,
1397 doc
: /* Return the real gid of Emacs.
1398 Value is an integer or a float, depending on the value. */)
1401 gid_t gid
= getgid ();
1402 return make_fixnum_or_float (gid
);
1405 DEFUN ("user-full-name", Fuser_full_name
, Suser_full_name
, 0, 1, 0,
1406 doc
: /* Return the full name of the user logged in, as a string.
1407 If the full name corresponding to Emacs's userid is not known,
1410 If optional argument UID is an integer or float, return the full name
1411 of the user with that uid, or nil if there is no such user.
1412 If UID is a string, return the full name of the user with that login
1413 name, or nil if there is no such user. */)
1417 register char *p
, *q
;
1421 return Vuser_full_name
;
1422 else if (NUMBERP (uid
))
1425 CONS_TO_INTEGER (uid
, uid_t
, u
);
1430 else if (STRINGP (uid
))
1433 pw
= getpwnam (SSDATA (uid
));
1437 error ("Invalid UID specification");
1443 /* Chop off everything after the first comma. */
1444 q
= strchr (p
, ',');
1445 full
= make_string (p
, q
? q
- p
: strlen (p
));
1447 #ifdef AMPERSAND_FULL_NAME
1449 q
= strchr (p
, '&');
1450 /* Substitute the login name for the &, upcasing the first character. */
1453 Lisp_Object login
= Fuser_login_name (make_number (pw
->pw_uid
));
1455 char *r
= SAFE_ALLOCA (strlen (p
) + SBYTES (login
) + 1);
1456 memcpy (r
, p
, q
- p
);
1457 char *s
= lispstpcpy (&r
[q
- p
], login
);
1458 r
[q
- p
] = upcase ((unsigned char) r
[q
- p
]);
1460 full
= build_string (r
);
1463 #endif /* AMPERSAND_FULL_NAME */
1468 DEFUN ("system-name", Fsystem_name
, Ssystem_name
, 0, 0, 0,
1469 doc
: /* Return the host name of the machine you are running on, as a string. */)
1472 if (EQ (Vsystem_name
, cached_system_name
))
1473 init_and_cache_system_name ();
1474 return Vsystem_name
;
1477 DEFUN ("emacs-pid", Femacs_pid
, Semacs_pid
, 0, 0, 0,
1478 doc
: /* Return the process ID of Emacs, as a number. */)
1481 pid_t pid
= getpid ();
1482 return make_fixnum_or_float (pid
);
1488 # define TIME_T_MIN TYPE_MINIMUM (time_t)
1491 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
1494 /* Report that a time value is out of range for Emacs. */
1496 time_overflow (void)
1498 error ("Specified time is not representable");
1501 static _Noreturn
void
1504 error ("Invalid time specification");
1507 /* Check a return value compatible with that of decode_time_components. */
1509 check_time_validity (int validity
)
1520 /* Return the upper part of the time T (everything but the bottom 16 bits). */
1524 time_t hi
= t
>> LO_TIME_BITS
;
1525 if (FIXNUM_OVERFLOW_P (hi
))
1530 /* Return the bottom bits of the time T. */
1534 return t
& ((1 << LO_TIME_BITS
) - 1);
1537 DEFUN ("current-time", Fcurrent_time
, Scurrent_time
, 0, 0, 0,
1538 doc
: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1539 The time is returned as a list of integers (HIGH LOW USEC PSEC).
1540 HIGH has the most significant bits of the seconds, while LOW has the
1541 least significant 16 bits. USEC and PSEC are the microsecond and
1542 picosecond counts. */)
1545 return make_lisp_time (current_timespec ());
1548 static struct lisp_time
1549 time_add (struct lisp_time ta
, struct lisp_time tb
)
1551 EMACS_INT hi
= ta
.hi
+ tb
.hi
;
1552 int lo
= ta
.lo
+ tb
.lo
;
1553 int us
= ta
.us
+ tb
.us
;
1554 int ps
= ta
.ps
+ tb
.ps
;
1555 us
+= (1000000 <= ps
);
1556 ps
-= (1000000 <= ps
) * 1000000;
1557 lo
+= (1000000 <= us
);
1558 us
-= (1000000 <= us
) * 1000000;
1559 hi
+= (1 << LO_TIME_BITS
<= lo
);
1560 lo
-= (1 << LO_TIME_BITS
<= lo
) << LO_TIME_BITS
;
1561 return (struct lisp_time
) { hi
, lo
, us
, ps
};
1564 static struct lisp_time
1565 time_subtract (struct lisp_time ta
, struct lisp_time tb
)
1567 EMACS_INT hi
= ta
.hi
- tb
.hi
;
1568 int lo
= ta
.lo
- tb
.lo
;
1569 int us
= ta
.us
- tb
.us
;
1570 int ps
= ta
.ps
- tb
.ps
;
1572 ps
+= (ps
< 0) * 1000000;
1574 us
+= (us
< 0) * 1000000;
1576 lo
+= (lo
< 0) << LO_TIME_BITS
;
1577 return (struct lisp_time
) { hi
, lo
, us
, ps
};
1581 time_arith (Lisp_Object a
, Lisp_Object b
,
1582 struct lisp_time (*op
) (struct lisp_time
, struct lisp_time
))
1585 struct lisp_time ta
= lisp_time_struct (a
, &alen
);
1586 struct lisp_time tb
= lisp_time_struct (b
, &blen
);
1587 struct lisp_time t
= op (ta
, tb
);
1588 if (FIXNUM_OVERFLOW_P (t
.hi
))
1590 Lisp_Object val
= Qnil
;
1592 switch (max (alen
, blen
))
1595 val
= Fcons (make_number (t
.ps
), val
);
1598 val
= Fcons (make_number (t
.us
), val
);
1601 val
= Fcons (make_number (t
.lo
), val
);
1602 val
= Fcons (make_number (t
.hi
), val
);
1609 DEFUN ("time-add", Ftime_add
, Stime_add
, 2, 2, 0,
1610 doc
: /* Return the sum of two time values A and B, as a time value.
1611 A nil value for either argument stands for the current time.
1612 See `current-time-string' for the various forms of a time value. */)
1613 (Lisp_Object a
, Lisp_Object b
)
1615 return time_arith (a
, b
, time_add
);
1618 DEFUN ("time-subtract", Ftime_subtract
, Stime_subtract
, 2, 2, 0,
1619 doc
: /* Return the difference between two time values A and B, as a time value.
1620 Use `float-time' to convert the difference into elapsed seconds.
1621 A nil value for either argument stands for the current time.
1622 See `current-time-string' for the various forms of a time value. */)
1623 (Lisp_Object a
, Lisp_Object b
)
1625 return time_arith (a
, b
, time_subtract
);
1628 DEFUN ("time-less-p", Ftime_less_p
, Stime_less_p
, 2, 2, 0,
1629 doc
: /* Return non-nil if time value T1 is earlier than time value T2.
1630 A nil value for either argument stands for the current time.
1631 See `current-time-string' for the various forms of a time value. */)
1632 (Lisp_Object t1
, Lisp_Object t2
)
1635 struct lisp_time a
= lisp_time_struct (t1
, &t1len
);
1636 struct lisp_time b
= lisp_time_struct (t2
, &t2len
);
1637 return ((a
.hi
!= b
.hi
? a
.hi
< b
.hi
1638 : a
.lo
!= b
.lo
? a
.lo
< b
.lo
1639 : a
.us
!= b
.us
? a
.us
< b
.us
1645 DEFUN ("get-internal-run-time", Fget_internal_run_time
, Sget_internal_run_time
,
1647 doc
: /* Return the current run time used by Emacs.
1648 The time is returned as a list (HIGH LOW USEC PSEC), using the same
1649 style as (current-time).
1651 On systems that can't determine the run time, `get-internal-run-time'
1652 does the same thing as `current-time'. */)
1655 #ifdef HAVE_GETRUSAGE
1656 struct rusage usage
;
1660 if (getrusage (RUSAGE_SELF
, &usage
) < 0)
1661 /* This shouldn't happen. What action is appropriate? */
1664 /* Sum up user time and system time. */
1665 secs
= usage
.ru_utime
.tv_sec
+ usage
.ru_stime
.tv_sec
;
1666 usecs
= usage
.ru_utime
.tv_usec
+ usage
.ru_stime
.tv_usec
;
1667 if (usecs
>= 1000000)
1672 return make_lisp_time (make_timespec (secs
, usecs
* 1000));
1673 #else /* ! HAVE_GETRUSAGE */
1675 return w32_get_internal_run_time ();
1676 #else /* ! WINDOWSNT */
1677 return Fcurrent_time ();
1678 #endif /* WINDOWSNT */
1679 #endif /* HAVE_GETRUSAGE */
1683 /* Make a Lisp list that represents the Emacs time T. T may be an
1684 invalid time, with a slightly negative tv_nsec value such as
1685 UNKNOWN_MODTIME_NSECS; in that case, the Lisp list contains a
1686 correspondingly negative picosecond count. */
1688 make_lisp_time (struct timespec t
)
1690 time_t s
= t
.tv_sec
;
1692 return list4i (hi_time (s
), lo_time (s
), ns
/ 1000, ns
% 1000 * 1000);
1695 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1696 Set *PHIGH, *PLOW, *PUSEC, *PPSEC to its parts; do not check their values.
1697 Return 2, 3, or 4 to indicate the effective length of SPECIFIED_TIME
1698 if successful, 0 if unsuccessful. */
1700 disassemble_lisp_time (Lisp_Object specified_time
, Lisp_Object
*phigh
,
1701 Lisp_Object
*plow
, Lisp_Object
*pusec
,
1704 Lisp_Object high
= make_number (0);
1705 Lisp_Object low
= specified_time
;
1706 Lisp_Object usec
= make_number (0);
1707 Lisp_Object psec
= make_number (0);
1710 if (CONSP (specified_time
))
1712 high
= XCAR (specified_time
);
1713 low
= XCDR (specified_time
);
1716 Lisp_Object low_tail
= XCDR (low
);
1718 if (CONSP (low_tail
))
1720 usec
= XCAR (low_tail
);
1721 low_tail
= XCDR (low_tail
);
1722 if (CONSP (low_tail
))
1723 psec
= XCAR (low_tail
);
1727 else if (!NILP (low_tail
))
1738 /* When combining components, require LOW to be an integer,
1739 as otherwise it would be a pain to add up times. */
1740 if (! INTEGERP (low
))
1743 else if (INTEGERP (specified_time
))
1753 /* Convert T into an Emacs time *RESULT, truncating toward minus infinity.
1754 Return true if T is in range, false otherwise. */
1756 decode_float_time (double t
, struct lisp_time
*result
)
1758 double lo_multiplier
= 1 << LO_TIME_BITS
;
1759 double emacs_time_min
= MOST_NEGATIVE_FIXNUM
* lo_multiplier
;
1760 if (! (emacs_time_min
<= t
&& t
< -emacs_time_min
))
1763 double small_t
= t
/ lo_multiplier
;
1764 EMACS_INT hi
= small_t
;
1765 double t_sans_hi
= t
- hi
* lo_multiplier
;
1767 long double fracps
= (t_sans_hi
- lo
) * 1e12L
;
1768 #ifdef INT_FAST64_MAX
1769 int_fast64_t ifracps
= fracps
;
1770 int us
= ifracps
/ 1000000;
1771 int ps
= ifracps
% 1000000;
1773 int us
= fracps
/ 1e6L
;
1774 int ps
= fracps
- us
* 1e6L
;
1777 ps
+= (ps
< 0) * 1000000;
1779 us
+= (us
< 0) * 1000000;
1781 lo
+= (lo
< 0) << LO_TIME_BITS
;
1789 /* From the time components HIGH, LOW, USEC and PSEC taken from a Lisp
1790 list, generate the corresponding time value.
1791 If LOW is floating point, the other components should be zero.
1793 If RESULT is not null, store into *RESULT the converted time.
1794 If *DRESULT is not null, store into *DRESULT the number of
1795 seconds since the start of the POSIX Epoch.
1797 Return 1 if successful, 0 if the components are of the
1798 wrong type, and -1 if the time is out of range. */
1800 decode_time_components (Lisp_Object high
, Lisp_Object low
, Lisp_Object usec
,
1802 struct lisp_time
*result
, double *dresult
)
1804 EMACS_INT hi
, lo
, us
, ps
;
1805 if (! (INTEGERP (high
)
1806 && INTEGERP (usec
) && INTEGERP (psec
)))
1808 if (! INTEGERP (low
))
1812 double t
= XFLOAT_DATA (low
);
1813 if (result
&& ! decode_float_time (t
, result
))
1819 else if (NILP (low
))
1821 struct timespec now
= current_timespec ();
1824 result
->hi
= hi_time (now
.tv_sec
);
1825 result
->lo
= lo_time (now
.tv_sec
);
1826 result
->us
= now
.tv_nsec
/ 1000;
1827 result
->ps
= now
.tv_nsec
% 1000 * 1000;
1830 *dresult
= now
.tv_sec
+ now
.tv_nsec
/ 1e9
;
1842 /* Normalize out-of-range lower-order components by carrying
1843 each overflow into the next higher-order component. */
1844 us
+= ps
/ 1000000 - (ps
% 1000000 < 0);
1845 lo
+= us
/ 1000000 - (us
% 1000000 < 0);
1846 hi
+= lo
>> LO_TIME_BITS
;
1847 ps
= ps
% 1000000 + 1000000 * (ps
% 1000000 < 0);
1848 us
= us
% 1000000 + 1000000 * (us
% 1000000 < 0);
1849 lo
&= (1 << LO_TIME_BITS
) - 1;
1853 if (FIXNUM_OVERFLOW_P (hi
))
1864 *dresult
= (us
* 1e6
+ ps
) / 1e12
+ lo
+ dhi
* (1 << LO_TIME_BITS
);
1871 lisp_to_timespec (struct lisp_time t
)
1873 if (! ((TYPE_SIGNED (time_t) ? TIME_T_MIN
>> LO_TIME_BITS
<= t
.hi
: 0 <= t
.hi
)
1874 && t
.hi
<= TIME_T_MAX
>> LO_TIME_BITS
))
1875 return invalid_timespec ();
1876 time_t s
= (t
.hi
<< LO_TIME_BITS
) + t
.lo
;
1877 int ns
= t
.us
* 1000 + t
.ps
/ 1000;
1878 return make_timespec (s
, ns
);
1881 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1882 Store its effective length into *PLEN.
1883 If SPECIFIED_TIME is nil, use the current time.
1884 Signal an error if SPECIFIED_TIME does not represent a time. */
1885 static struct lisp_time
1886 lisp_time_struct (Lisp_Object specified_time
, int *plen
)
1888 Lisp_Object high
, low
, usec
, psec
;
1890 int len
= disassemble_lisp_time (specified_time
, &high
, &low
, &usec
, &psec
);
1893 int val
= decode_time_components (high
, low
, usec
, psec
, &t
, 0);
1894 check_time_validity (val
);
1899 /* Like lisp_time_struct, except return a struct timespec.
1900 Discard any low-order digits. */
1902 lisp_time_argument (Lisp_Object specified_time
)
1905 struct lisp_time lt
= lisp_time_struct (specified_time
, &len
);
1906 struct timespec t
= lisp_to_timespec (lt
);
1907 if (! timespec_valid_p (t
))
1912 /* Like lisp_time_argument, except decode only the seconds part,
1913 and do not check the subseconds part. */
1915 lisp_seconds_argument (Lisp_Object specified_time
)
1917 Lisp_Object high
, low
, usec
, psec
;
1920 int val
= disassemble_lisp_time (specified_time
, &high
, &low
, &usec
, &psec
);
1923 val
= decode_time_components (high
, low
, make_number (0),
1924 make_number (0), &t
, 0);
1926 && ! ((TYPE_SIGNED (time_t)
1927 ? TIME_T_MIN
>> LO_TIME_BITS
<= t
.hi
1929 && t
.hi
<= TIME_T_MAX
>> LO_TIME_BITS
))
1932 check_time_validity (val
);
1933 return (t
.hi
<< LO_TIME_BITS
) + t
.lo
;
1936 DEFUN ("float-time", Ffloat_time
, Sfloat_time
, 0, 1, 0,
1937 doc
: /* Return the current time, as a float number of seconds since the epoch.
1938 If SPECIFIED-TIME is given, it is the time to convert to float
1939 instead of the current time. The argument should have the form
1940 \(HIGH LOW) or (HIGH LOW USEC) or (HIGH LOW USEC PSEC). Thus,
1941 you can use times from `current-time' and from `file-attributes'.
1942 SPECIFIED-TIME can also have the form (HIGH . LOW), but this is
1943 considered obsolete.
1945 WARNING: Since the result is floating point, it may not be exact.
1946 If precise time stamps are required, use either `current-time',
1947 or (if you need time as a string) `format-time-string'. */)
1948 (Lisp_Object specified_time
)
1951 Lisp_Object high
, low
, usec
, psec
;
1952 if (! (disassemble_lisp_time (specified_time
, &high
, &low
, &usec
, &psec
)
1953 && decode_time_components (high
, low
, usec
, psec
, 0, &t
)))
1955 return make_float (t
);
1958 /* Write information into buffer S of size MAXSIZE, according to the
1959 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1960 Use the time zone specified by TZ.
1961 Use NS as the number of nanoseconds in the %N directive.
1962 Return the number of bytes written, not including the terminating
1963 '\0'. If S is NULL, nothing will be written anywhere; so to
1964 determine how many bytes would be written, use NULL for S and
1965 ((size_t) -1) for MAXSIZE.
1967 This function behaves like nstrftime, except it allows null
1968 bytes in FORMAT and it does not support nanoseconds. */
1970 emacs_nmemftime (char *s
, size_t maxsize
, const char *format
,
1971 size_t format_len
, const struct tm
*tp
, timezone_t tz
, int ns
)
1975 /* Loop through all the null-terminated strings in the format
1976 argument. Normally there's just one null-terminated string, but
1977 there can be arbitrarily many, concatenated together, if the
1978 format contains '\0' bytes. nstrftime stops at the first
1979 '\0' byte so we must invoke it separately for each such string. */
1988 result
= nstrftime (s
, maxsize
, format
, tp
, tz
, ns
);
1992 if (result
== 0 && s
[0] != '\0')
1997 maxsize
-= result
+ 1;
1999 len
= strlen (format
);
2000 if (len
== format_len
)
2004 format_len
-= len
+ 1;
2008 DEFUN ("format-time-string", Fformat_time_string
, Sformat_time_string
, 1, 3, 0,
2009 doc
: /* Use FORMAT-STRING to format the time TIME, or now if omitted or nil.
2010 TIME is specified as (HIGH LOW USEC PSEC), as returned by
2011 `current-time' or `file-attributes'. It can also be a single integer
2012 number of seconds since the epoch. The obsolete form (HIGH . LOW) is
2013 also still accepted.
2015 The optional ZONE is omitted or nil for Emacs local time, t for
2016 Universal Time, `wall' for system wall clock time, or a string as in
2017 the TZ environment variable. It can also be a list (as from
2018 `current-time-zone') or an integer (as from `decode-time') applied
2019 without consideration for daylight saving time.
2021 The value is a copy of FORMAT-STRING, but with certain constructs replaced
2022 by text that describes the specified date and time in TIME:
2024 %Y is the year, %y within the century, %C the century.
2025 %G is the year corresponding to the ISO week, %g within the century.
2026 %m is the numeric month.
2027 %b and %h are the locale's abbreviated month name, %B the full name.
2028 (%h is not supported on MS-Windows.)
2029 %d is the day of the month, zero-padded, %e is blank-padded.
2030 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
2031 %a is the locale's abbreviated name of the day of week, %A the full name.
2032 %U is the week number starting on Sunday, %W starting on Monday,
2033 %V according to ISO 8601.
2034 %j is the day of the year.
2036 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
2037 only blank-padded, %l is like %I blank-padded.
2038 %p is the locale's equivalent of either AM or PM.
2039 %q is the calendar quarter (1–4).
2042 %N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
2043 %Z is the time zone name, %z is the numeric form.
2044 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
2046 %c is the locale's date and time format.
2047 %x is the locale's "preferred" date format.
2048 %D is like "%m/%d/%y".
2049 %F is the ISO 8601 date format (like "%Y-%m-%d").
2051 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
2052 %X is the locale's "preferred" time format.
2054 Finally, %n is a newline, %t is a tab, %% is a literal %.
2056 Certain flags and modifiers are available with some format controls.
2057 The flags are `_', `-', `^' and `#'. For certain characters X,
2058 %_X is like %X, but padded with blanks; %-X is like %X,
2059 but without padding. %^X is like %X, but with all textual
2060 characters up-cased; %#X is like %X, but with letter-case of
2061 all textual characters reversed.
2062 %NX (where N stands for an integer) is like %X,
2063 but takes up at least N (a number) positions.
2064 The modifiers are `E' and `O'. For certain characters X,
2065 %EX is a locale's alternative version of %X;
2066 %OX is like %X, but uses the locale's number symbols.
2068 For example, to produce full ISO 8601 format, use "%FT%T%z".
2070 usage: (format-time-string FORMAT-STRING &optional TIME ZONE) */)
2071 (Lisp_Object format_string
, Lisp_Object timeval
, Lisp_Object zone
)
2073 struct timespec t
= lisp_time_argument (timeval
);
2076 CHECK_STRING (format_string
);
2077 format_string
= code_convert_string_norecord (format_string
,
2078 Vlocale_coding_system
, 1);
2079 return format_time_string (SSDATA (format_string
), SBYTES (format_string
),
2084 format_time_string (char const *format
, ptrdiff_t formatlen
,
2085 struct timespec t
, Lisp_Object zone
, struct tm
*tmp
)
2089 ptrdiff_t size
= sizeof buffer
;
2094 timezone_t tz
= tzlookup (zone
, false);
2095 /* On some systems, like 32-bit MinGW, tv_sec of struct timespec is
2096 a 64-bit type, but time_t is a 32-bit type. emacs_localtime_rz
2097 expects a pointer to time_t value. */
2098 time_t tsec
= t
.tv_sec
;
2099 tmp
= emacs_localtime_rz (tz
, &tsec
, tmp
);
2105 synchronize_system_time_locale ();
2110 len
= emacs_nmemftime (buf
, size
, format
, formatlen
, tmp
, tz
, ns
);
2111 if ((0 < len
&& len
< size
) || (len
== 0 && buf
[0] == '\0'))
2114 /* Buffer was too small, so make it bigger and try again. */
2115 len
= emacs_nmemftime (NULL
, SIZE_MAX
, format
, formatlen
, tmp
, tz
, ns
);
2116 if (STRING_BYTES_BOUND
<= len
)
2122 buf
= SAFE_ALLOCA (size
);
2126 AUTO_STRING_WITH_LEN (bufstring
, buf
, len
);
2127 Lisp_Object result
= code_convert_string_norecord (bufstring
,
2128 Vlocale_coding_system
, 0);
2133 DEFUN ("decode-time", Fdecode_time
, Sdecode_time
, 0, 2, 0,
2134 doc
: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST UTCOFF).
2135 The optional TIME should be a list of (HIGH LOW . IGNORED),
2136 as from `current-time' and `file-attributes', or nil to use the
2137 current time. It can also be a single integer number of seconds since
2138 the epoch. The obsolete form (HIGH . LOW) is also still accepted.
2140 The optional ZONE is omitted or nil for Emacs local time, t for
2141 Universal Time, `wall' for system wall clock time, or a string as in
2142 the TZ environment variable. It can also be a list (as from
2143 `current-time-zone') or an integer (the UTC offset in seconds) applied
2144 without consideration for daylight saving time.
2146 The list has the following nine members: SEC is an integer between 0
2147 and 60; SEC is 60 for a leap second, which only some operating systems
2148 support. MINUTE is an integer between 0 and 59. HOUR is an integer
2149 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
2150 integer between 1 and 12. YEAR is an integer indicating the
2151 four-digit year. DOW is the day of week, an integer between 0 and 6,
2152 where 0 is Sunday. DST is t if daylight saving time is in effect,
2153 otherwise nil. UTCOFF is an integer indicating the UTC offset in
2154 seconds, i.e., the number of seconds east of Greenwich. (Note that
2155 Common Lisp has different meanings for DOW and UTCOFF.)
2157 usage: (decode-time &optional TIME ZONE) */)
2158 (Lisp_Object specified_time
, Lisp_Object zone
)
2160 time_t time_spec
= lisp_seconds_argument (specified_time
);
2161 struct tm local_tm
, gmt_tm
;
2162 timezone_t tz
= tzlookup (zone
, false);
2163 struct tm
*tm
= emacs_localtime_rz (tz
, &time_spec
, &local_tm
);
2167 && MOST_NEGATIVE_FIXNUM
- TM_YEAR_BASE
<= local_tm
.tm_year
2168 && local_tm
.tm_year
<= MOST_POSITIVE_FIXNUM
- TM_YEAR_BASE
))
2171 /* Avoid overflow when INT_MAX < EMACS_INT_MAX. */
2172 EMACS_INT tm_year_base
= TM_YEAR_BASE
;
2174 return CALLN (Flist
,
2175 make_number (local_tm
.tm_sec
),
2176 make_number (local_tm
.tm_min
),
2177 make_number (local_tm
.tm_hour
),
2178 make_number (local_tm
.tm_mday
),
2179 make_number (local_tm
.tm_mon
+ 1),
2180 make_number (local_tm
.tm_year
+ tm_year_base
),
2181 make_number (local_tm
.tm_wday
),
2182 local_tm
.tm_isdst
? Qt
: Qnil
,
2184 ? make_number (tm_gmtoff (&local_tm
))
2185 : gmtime_r (&time_spec
, &gmt_tm
)
2186 ? make_number (tm_diff (&local_tm
, &gmt_tm
))
2190 /* Return OBJ - OFFSET, checking that OBJ is a valid fixnum and that
2191 the result is representable as an int. */
2193 check_tm_member (Lisp_Object obj
, int offset
)
2196 EMACS_INT n
= XINT (obj
);
2198 if (INT_SUBTRACT_WRAPV (n
, offset
, &result
))
2203 DEFUN ("encode-time", Fencode_time
, Sencode_time
, 6, MANY
, 0,
2204 doc
: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
2205 This is the reverse operation of `decode-time', which see.
2207 The optional ZONE is omitted or nil for Emacs local time, t for
2208 Universal Time, `wall' for system wall clock time, or a string as in
2209 the TZ environment variable. It can also be a list (as from
2210 `current-time-zone') or an integer (as from `decode-time') applied
2211 without consideration for daylight saving time.
2213 You can pass more than 7 arguments; then the first six arguments
2214 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
2215 The intervening arguments are ignored.
2216 This feature lets (apply \\='encode-time (decode-time ...)) work.
2218 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
2219 for example, a DAY of 0 means the day preceding the given month.
2220 Year numbers less than 100 are treated just like other year numbers.
2221 If you want them to stand for years in this century, you must do that yourself.
2223 Years before 1970 are not guaranteed to work. On some systems,
2224 year values as low as 1901 do work.
2226 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
2227 (ptrdiff_t nargs
, Lisp_Object
*args
)
2231 Lisp_Object zone
= (nargs
> 6 ? args
[nargs
- 1] : Qnil
);
2233 tm
.tm_sec
= check_tm_member (args
[0], 0);
2234 tm
.tm_min
= check_tm_member (args
[1], 0);
2235 tm
.tm_hour
= check_tm_member (args
[2], 0);
2236 tm
.tm_mday
= check_tm_member (args
[3], 0);
2237 tm
.tm_mon
= check_tm_member (args
[4], 1);
2238 tm
.tm_year
= check_tm_member (args
[5], TM_YEAR_BASE
);
2241 timezone_t tz
= tzlookup (zone
, false);
2242 value
= emacs_mktime_z (tz
, &tm
);
2245 if (value
== (time_t) -1)
2248 return list2i (hi_time (value
), lo_time (value
));
2251 DEFUN ("current-time-string", Fcurrent_time_string
, Scurrent_time_string
,
2253 doc
: /* Return the current local time, as a human-readable string.
2254 Programs can use this function to decode a time,
2255 since the number of columns in each field is fixed
2256 if the year is in the range 1000-9999.
2257 The format is `Sun Sep 16 01:03:52 1973'.
2258 However, see also the functions `decode-time' and `format-time-string'
2259 which provide a much more powerful and general facility.
2261 If SPECIFIED-TIME is given, it is a time to format instead of the
2262 current time. The argument should have the form (HIGH LOW . IGNORED).
2263 Thus, you can use times obtained from `current-time' and from
2264 `file-attributes'. SPECIFIED-TIME can also be a single integer number
2265 of seconds since the epoch. The obsolete form (HIGH . LOW) is also
2268 The optional ZONE is omitted or nil for Emacs local time, t for
2269 Universal Time, `wall' for system wall clock time, or a string as in
2270 the TZ environment variable. It can also be a list (as from
2271 `current-time-zone') or an integer (as from `decode-time') applied
2272 without consideration for daylight saving time. */)
2273 (Lisp_Object specified_time
, Lisp_Object zone
)
2275 time_t value
= lisp_seconds_argument (specified_time
);
2276 timezone_t tz
= tzlookup (zone
, false);
2278 /* Convert to a string in ctime format, except without the trailing
2279 newline, and without the 4-digit year limit. Don't use asctime
2280 or ctime, as they might dump core if the year is outside the
2281 range -999 .. 9999. */
2283 struct tm
*tmp
= emacs_localtime_rz (tz
, &value
, &tm
);
2288 static char const wday_name
[][4] =
2289 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
2290 static char const mon_name
[][4] =
2291 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2292 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
2293 printmax_t year_base
= TM_YEAR_BASE
;
2294 char buf
[sizeof "Mon Apr 30 12:49:17 " + INT_STRLEN_BOUND (int) + 1];
2295 int len
= sprintf (buf
, "%s %s%3d %02d:%02d:%02d %"pMd
,
2296 wday_name
[tm
.tm_wday
], mon_name
[tm
.tm_mon
], tm
.tm_mday
,
2297 tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
,
2298 tm
.tm_year
+ year_base
);
2300 return make_unibyte_string (buf
, len
);
2303 /* Yield A - B, measured in seconds.
2304 This function is copied from the GNU C Library. */
2306 tm_diff (struct tm
*a
, struct tm
*b
)
2308 /* Compute intervening leap days correctly even if year is negative.
2309 Take care to avoid int overflow in leap day calculations,
2310 but it's OK to assume that A and B are close to each other. */
2311 int a4
= (a
->tm_year
>> 2) + (TM_YEAR_BASE
>> 2) - ! (a
->tm_year
& 3);
2312 int b4
= (b
->tm_year
>> 2) + (TM_YEAR_BASE
>> 2) - ! (b
->tm_year
& 3);
2313 int a100
= a4
/ 25 - (a4
% 25 < 0);
2314 int b100
= b4
/ 25 - (b4
% 25 < 0);
2315 int a400
= a100
>> 2;
2316 int b400
= b100
>> 2;
2317 int intervening_leap_days
= (a4
- b4
) - (a100
- b100
) + (a400
- b400
);
2318 int years
= a
->tm_year
- b
->tm_year
;
2319 int days
= (365 * years
+ intervening_leap_days
2320 + (a
->tm_yday
- b
->tm_yday
));
2321 return (60 * (60 * (24 * days
+ (a
->tm_hour
- b
->tm_hour
))
2322 + (a
->tm_min
- b
->tm_min
))
2323 + (a
->tm_sec
- b
->tm_sec
));
2326 /* Yield A's UTC offset, or an unspecified value if unknown. */
2328 tm_gmtoff (struct tm
*a
)
2331 return a
->tm_gmtoff
;
2337 DEFUN ("current-time-zone", Fcurrent_time_zone
, Scurrent_time_zone
, 0, 2, 0,
2338 doc
: /* Return the offset and name for the local time zone.
2339 This returns a list of the form (OFFSET NAME).
2340 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
2341 A negative value means west of Greenwich.
2342 NAME is a string giving the name of the time zone.
2343 If SPECIFIED-TIME is given, the time zone offset is determined from it
2344 instead of using the current time. The argument should have the form
2345 \(HIGH LOW . IGNORED). Thus, you can use times obtained from
2346 `current-time' and from `file-attributes'. SPECIFIED-TIME can also be
2347 a single integer number of seconds since the epoch. The obsolete form
2348 (HIGH . LOW) is also still accepted.
2350 The optional ZONE is omitted or nil for Emacs local time, t for
2351 Universal Time, `wall' for system wall clock time, or a string as in
2352 the TZ environment variable. It can also be a list (as from
2353 `current-time-zone') or an integer (as from `decode-time') applied
2354 without consideration for daylight saving time.
2356 Some operating systems cannot provide all this information to Emacs;
2357 in this case, `current-time-zone' returns a list containing nil for
2358 the data it can't find. */)
2359 (Lisp_Object specified_time
, Lisp_Object zone
)
2361 struct timespec value
;
2362 struct tm local_tm
, gmt_tm
;
2363 Lisp_Object zone_offset
, zone_name
;
2366 value
= make_timespec (lisp_seconds_argument (specified_time
), 0);
2367 zone_name
= format_time_string ("%Z", sizeof "%Z" - 1, value
,
2370 /* gmtime_r expects a pointer to time_t, but tv_sec of struct
2371 timespec on some systems (MinGW) is a 64-bit field. */
2372 time_t tsec
= value
.tv_sec
;
2373 if (HAVE_TM_GMTOFF
|| gmtime_r (&tsec
, &gmt_tm
))
2375 long int offset
= (HAVE_TM_GMTOFF
2376 ? tm_gmtoff (&local_tm
)
2377 : tm_diff (&local_tm
, &gmt_tm
));
2378 zone_offset
= make_number (offset
);
2379 if (SCHARS (zone_name
) == 0)
2381 /* No local time zone name is available; use numeric zone instead. */
2382 long int hour
= offset
/ 3600;
2383 int min_sec
= offset
% 3600;
2384 int amin_sec
= min_sec
< 0 ? - min_sec
: min_sec
;
2385 int min
= amin_sec
/ 60;
2386 int sec
= amin_sec
% 60;
2387 int min_prec
= min_sec
? 2 : 0;
2388 int sec_prec
= sec
? 2 : 0;
2389 char buf
[sizeof "+0000" + INT_STRLEN_BOUND (long int)];
2390 zone_name
= make_formatted_string (buf
, "%c%.2ld%.*d%.*d",
2391 (offset
< 0 ? '-' : '+'),
2392 hour
, min_prec
, min
, sec_prec
, sec
);
2396 return list2 (zone_offset
, zone_name
);
2399 DEFUN ("set-time-zone-rule", Fset_time_zone_rule
, Sset_time_zone_rule
, 1, 1, 0,
2400 doc
: /* Set the Emacs local time zone using TZ, a string specifying a time zone rule.
2401 If TZ is nil or `wall', use system wall clock time; this differs from
2402 the usual Emacs convention where nil means current local time. If TZ
2403 is t, use Universal Time. If TZ is a list (as from
2404 `current-time-zone') or an integer (as from `decode-time'), use the
2405 specified time zone without consideration for daylight saving time.
2407 Instead of calling this function, you typically want something else.
2408 To temporarily use a different time zone rule for just one invocation
2409 of `decode-time', `encode-time', or `format-time-string', pass the
2410 function a ZONE argument. To change local time consistently
2411 throughout Emacs, call (setenv "TZ" TZ): this changes both the
2412 environment of the Emacs process and the variable
2413 `process-environment', whereas `set-time-zone-rule' affects only the
2417 tzlookup (NILP (tz
) ? Qwall
: tz
, true);
2421 /* A buffer holding a string of the form "TZ=value", intended
2422 to be part of the environment. If TZ is supposed to be unset,
2423 the buffer string is "tZ=". */
2424 static char *tzvalbuf
;
2426 /* Get the local time zone rule. */
2428 emacs_getenv_TZ (void)
2430 return tzvalbuf
[0] == 'T' ? tzvalbuf
+ tzeqlen
: 0;
2433 /* Set the local time zone rule to TZSTRING, which can be null to
2434 denote wall clock time. Do not record the setting in LOCAL_TZ.
2436 This function is not thread-safe, in theory because putenv is not,
2437 but mostly because of the static storage it updates. Other threads
2438 that invoke localtime etc. may be adversely affected while this
2439 function is executing. */
2442 emacs_setenv_TZ (const char *tzstring
)
2444 static ptrdiff_t tzvalbufsize
;
2445 ptrdiff_t tzstringlen
= tzstring
? strlen (tzstring
) : 0;
2446 char *tzval
= tzvalbuf
;
2447 bool new_tzvalbuf
= tzvalbufsize
<= tzeqlen
+ tzstringlen
;
2451 /* Do not attempt to free the old tzvalbuf, since another thread
2452 may be using it. In practice, the first allocation is large
2453 enough and memory does not leak. */
2454 tzval
= xpalloc (NULL
, &tzvalbufsize
,
2455 tzeqlen
+ tzstringlen
- tzvalbufsize
+ 1, -1, 1);
2463 /* Modify TZVAL in place. Although this is dicey in a
2464 multithreaded environment, we know of no portable alternative.
2465 Calling putenv or setenv could crash some other thread. */
2467 strcpy (tzval
+ tzeqlen
, tzstring
);
2471 /* Turn 'TZ=whatever' into an empty environment variable 'tZ='.
2472 Although this is also dicey, calling unsetenv here can crash Emacs.
2480 /* Modifying *TZVAL merely requires calling tzset (which is the
2481 caller's responsibility). However, modifying TZVAL requires
2482 calling putenv; although this is not thread-safe, in practice this
2483 runs only on startup when there is only one thread. */
2484 bool need_putenv
= new_tzvalbuf
;
2486 /* MS-Windows 'putenv' copies the argument string into a block it
2487 allocates, so modifying *TZVAL will not change the environment.
2488 However, the other threads run by Emacs on MS-Windows never call
2489 'xputenv' or 'putenv' or 'unsetenv', so the original cause for the
2490 dicey in-place modification technique doesn't exist there in the
2492 bool need_putenv
= true;
2500 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2501 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2502 type of object is Lisp_String). INHERIT is passed to
2503 INSERT_FROM_STRING_FUNC as the last argument. */
2506 general_insert_function (void (*insert_func
)
2507 (const char *, ptrdiff_t),
2508 void (*insert_from_string_func
)
2509 (Lisp_Object
, ptrdiff_t, ptrdiff_t,
2510 ptrdiff_t, ptrdiff_t, bool),
2511 bool inherit
, ptrdiff_t nargs
, Lisp_Object
*args
)
2516 for (argnum
= 0; argnum
< nargs
; argnum
++)
2519 if (CHARACTERP (val
))
2521 int c
= XFASTINT (val
);
2522 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
2525 if (!NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2526 len
= CHAR_STRING (c
, str
);
2529 str
[0] = CHAR_TO_BYTE8 (c
);
2532 (*insert_func
) ((char *) str
, len
);
2534 else if (STRINGP (val
))
2536 (*insert_from_string_func
) (val
, 0, 0,
2542 wrong_type_argument (Qchar_or_string_p
, val
);
2547 insert1 (Lisp_Object arg
)
2553 DEFUN ("insert", Finsert
, Sinsert
, 0, MANY
, 0,
2554 doc
: /* Insert the arguments, either strings or characters, at point.
2555 Point and after-insertion markers move forward to end up
2556 after the inserted text.
2557 Any other markers at the point of insertion remain before the text.
2559 If the current buffer is multibyte, unibyte strings are converted
2560 to multibyte for insertion (see `string-make-multibyte').
2561 If the current buffer is unibyte, multibyte strings are converted
2562 to unibyte for insertion (see `string-make-unibyte').
2564 When operating on binary data, it may be necessary to preserve the
2565 original bytes of a unibyte string when inserting it into a multibyte
2566 buffer; to accomplish this, apply `string-as-multibyte' to the string
2567 and insert the result.
2569 usage: (insert &rest ARGS) */)
2570 (ptrdiff_t nargs
, Lisp_Object
*args
)
2572 general_insert_function (insert
, insert_from_string
, 0, nargs
, args
);
2576 DEFUN ("insert-and-inherit", Finsert_and_inherit
, Sinsert_and_inherit
,
2578 doc
: /* Insert the arguments at point, inheriting properties from adjoining text.
2579 Point and after-insertion markers move forward to end up
2580 after the inserted text.
2581 Any other markers at the point of insertion remain before the 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-and-inherit &rest ARGS) */)
2589 (ptrdiff_t nargs
, Lisp_Object
*args
)
2591 general_insert_function (insert_and_inherit
, insert_from_string
, 1,
2596 DEFUN ("insert-before-markers", Finsert_before_markers
, Sinsert_before_markers
, 0, MANY
, 0,
2597 doc
: /* Insert strings or characters at point, relocating markers after the text.
2598 Point and markers move forward to end up after the inserted text.
2600 If the current buffer is multibyte, unibyte strings are converted
2601 to multibyte for insertion (see `unibyte-char-to-multibyte').
2602 If the current buffer is unibyte, multibyte strings are converted
2603 to unibyte for insertion.
2605 If an overlay begins at the insertion point, the inserted text falls
2606 outside the overlay; if a nonempty overlay ends at the insertion
2607 point, the inserted text falls inside that overlay.
2609 usage: (insert-before-markers &rest ARGS) */)
2610 (ptrdiff_t nargs
, Lisp_Object
*args
)
2612 general_insert_function (insert_before_markers
,
2613 insert_from_string_before_markers
, 0,
2618 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers
,
2619 Sinsert_and_inherit_before_markers
, 0, MANY
, 0,
2620 doc
: /* Insert text at point, relocating markers and inheriting properties.
2621 Point and markers move forward to end up after the inserted text.
2623 If the current buffer is multibyte, unibyte strings are converted
2624 to multibyte for insertion (see `unibyte-char-to-multibyte').
2625 If the current buffer is unibyte, multibyte strings are converted
2626 to unibyte for insertion.
2628 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2629 (ptrdiff_t nargs
, Lisp_Object
*args
)
2631 general_insert_function (insert_before_markers_and_inherit
,
2632 insert_from_string_before_markers
, 1,
2637 DEFUN ("insert-char", Finsert_char
, Sinsert_char
, 1, 3,
2638 "(list (read-char-by-name \"Insert character (Unicode name or hex): \")\
2639 (prefix-numeric-value current-prefix-arg)\
2641 doc
: /* Insert COUNT copies of CHARACTER.
2642 Interactively, prompt for CHARACTER. You can specify CHARACTER in one
2645 - As its Unicode character name, e.g. \"LATIN SMALL LETTER A\".
2646 Completion is available; if you type a substring of the name
2647 preceded by an asterisk `*', Emacs shows all names which include
2648 that substring, not necessarily at the beginning of the name.
2650 - As a hexadecimal code point, e.g. 263A. Note that code points in
2651 Emacs are equivalent to Unicode up to 10FFFF (which is the limit of
2652 the Unicode code space).
2654 - As a code point with a radix specified with #, e.g. #o21430
2655 (octal), #x2318 (hex), or #10r8984 (decimal).
2657 If called interactively, COUNT is given by the prefix argument. If
2658 omitted or nil, it defaults to 1.
2660 Inserting the character(s) relocates point and before-insertion
2661 markers in the same ways as the function `insert'.
2663 The optional third argument INHERIT, if non-nil, says to inherit text
2664 properties from adjoining text, if those properties are sticky. If
2665 called interactively, INHERIT is t. */)
2666 (Lisp_Object character
, Lisp_Object count
, Lisp_Object inherit
)
2669 register ptrdiff_t n
;
2671 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
2674 CHECK_CHARACTER (character
);
2676 XSETFASTINT (count
, 1);
2677 CHECK_NUMBER (count
);
2678 c
= XFASTINT (character
);
2680 if (!NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2681 len
= CHAR_STRING (c
, str
);
2683 str
[0] = c
, len
= 1;
2684 if (XINT (count
) <= 0)
2686 if (BUF_BYTES_MAX
/ len
< XINT (count
))
2688 n
= XINT (count
) * len
;
2689 stringlen
= min (n
, sizeof string
- sizeof string
% len
);
2690 for (i
= 0; i
< stringlen
; i
++)
2691 string
[i
] = str
[i
% len
];
2692 while (n
> stringlen
)
2695 if (!NILP (inherit
))
2696 insert_and_inherit (string
, stringlen
);
2698 insert (string
, stringlen
);
2701 if (!NILP (inherit
))
2702 insert_and_inherit (string
, n
);
2708 DEFUN ("insert-byte", Finsert_byte
, Sinsert_byte
, 2, 3, 0,
2709 doc
: /* Insert COUNT (second arg) copies of BYTE (first arg).
2710 Both arguments are required.
2711 BYTE is a number of the range 0..255.
2713 If BYTE is 128..255 and the current buffer is multibyte, the
2714 corresponding eight-bit character is inserted.
2716 Point, and before-insertion markers, are relocated as in the function `insert'.
2717 The optional third arg INHERIT, if non-nil, says to inherit text properties
2718 from adjoining text, if those properties are sticky. */)
2719 (Lisp_Object byte
, Lisp_Object count
, Lisp_Object inherit
)
2721 CHECK_NUMBER (byte
);
2722 if (XINT (byte
) < 0 || XINT (byte
) > 255)
2723 args_out_of_range_3 (byte
, make_number (0), make_number (255));
2724 if (XINT (byte
) >= 128
2725 && ! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2726 XSETFASTINT (byte
, BYTE8_TO_CHAR (XINT (byte
)));
2727 return Finsert_char (byte
, count
, inherit
);
2731 /* Making strings from buffer contents. */
2733 /* Return a Lisp_String containing the text of the current buffer from
2734 START to END. If text properties are in use and the current buffer
2735 has properties in the range specified, the resulting string will also
2736 have them, if PROPS is true.
2738 We don't want to use plain old make_string here, because it calls
2739 make_uninit_string, which can cause the buffer arena to be
2740 compacted. make_string has no way of knowing that the data has
2741 been moved, and thus copies the wrong data into the string. This
2742 doesn't effect most of the other users of make_string, so it should
2743 be left as is. But we should use this function when conjuring
2744 buffer substrings. */
2747 make_buffer_string (ptrdiff_t start
, ptrdiff_t end
, bool props
)
2749 ptrdiff_t start_byte
= CHAR_TO_BYTE (start
);
2750 ptrdiff_t end_byte
= CHAR_TO_BYTE (end
);
2752 return make_buffer_string_both (start
, start_byte
, end
, end_byte
, props
);
2755 /* Return a Lisp_String containing the text of the current buffer from
2756 START / START_BYTE to END / END_BYTE.
2758 If text properties are in use and the current buffer
2759 has properties in the range specified, the resulting string will also
2760 have them, if PROPS is true.
2762 We don't want to use plain old make_string here, because it calls
2763 make_uninit_string, which can cause the buffer arena to be
2764 compacted. make_string has no way of knowing that the data has
2765 been moved, and thus copies the wrong data into the string. This
2766 doesn't effect most of the other users of make_string, so it should
2767 be left as is. But we should use this function when conjuring
2768 buffer substrings. */
2771 make_buffer_string_both (ptrdiff_t start
, ptrdiff_t start_byte
,
2772 ptrdiff_t end
, ptrdiff_t end_byte
, bool props
)
2774 Lisp_Object result
, tem
, tem1
;
2775 ptrdiff_t beg0
, end0
, beg1
, end1
, size
;
2777 if (start_byte
< GPT_BYTE
&& GPT_BYTE
< end_byte
)
2779 /* Two regions, before and after the gap. */
2782 beg1
= GPT_BYTE
+ GAP_SIZE
- BEG_BYTE
;
2783 end1
= end_byte
+ GAP_SIZE
- BEG_BYTE
;
2787 /* The only region. */
2794 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2795 result
= make_uninit_multibyte_string (end
- start
, end_byte
- start_byte
);
2797 result
= make_uninit_string (end
- start
);
2800 memcpy (SDATA (result
), BYTE_POS_ADDR (beg0
), size
);
2802 memcpy (SDATA (result
) + size
, BEG_ADDR
+ beg1
, end1
- beg1
);
2804 /* If desired, update and copy the text properties. */
2807 update_buffer_properties (start
, end
);
2809 tem
= Fnext_property_change (make_number (start
), Qnil
, make_number (end
));
2810 tem1
= Ftext_properties_at (make_number (start
), Qnil
);
2812 if (XINT (tem
) != end
|| !NILP (tem1
))
2813 copy_intervals_to_string (result
, current_buffer
, start
,
2820 /* Call Vbuffer_access_fontify_functions for the range START ... END
2821 in the current buffer, if necessary. */
2824 update_buffer_properties (ptrdiff_t start
, ptrdiff_t end
)
2826 /* If this buffer has some access functions,
2827 call them, specifying the range of the buffer being accessed. */
2828 if (!NILP (Vbuffer_access_fontify_functions
))
2830 /* But don't call them if we can tell that the work
2831 has already been done. */
2832 if (!NILP (Vbuffer_access_fontified_property
))
2835 = Ftext_property_any (make_number (start
), make_number (end
),
2836 Vbuffer_access_fontified_property
,
2842 CALLN (Frun_hook_with_args
, Qbuffer_access_fontify_functions
,
2843 make_number (start
), make_number (end
));
2847 DEFUN ("buffer-substring", Fbuffer_substring
, Sbuffer_substring
, 2, 2, 0,
2848 doc
: /* Return the contents of part of the current buffer as a string.
2849 The two arguments START and END are character positions;
2850 they can be in either order.
2851 The string returned is multibyte if the buffer is multibyte.
2853 This function copies the text properties of that part of the buffer
2854 into the result string; if you don't want the text properties,
2855 use `buffer-substring-no-properties' instead. */)
2856 (Lisp_Object start
, Lisp_Object end
)
2858 register ptrdiff_t b
, e
;
2860 validate_region (&start
, &end
);
2864 return make_buffer_string (b
, e
, 1);
2867 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties
,
2868 Sbuffer_substring_no_properties
, 2, 2, 0,
2869 doc
: /* Return the characters of part of the buffer, without the text properties.
2870 The two arguments START and END are character positions;
2871 they can be in either order. */)
2872 (Lisp_Object start
, Lisp_Object end
)
2874 register ptrdiff_t b
, e
;
2876 validate_region (&start
, &end
);
2880 return make_buffer_string (b
, e
, 0);
2883 DEFUN ("buffer-string", Fbuffer_string
, Sbuffer_string
, 0, 0, 0,
2884 doc
: /* Return the contents of the current buffer as a string.
2885 If narrowing is in effect, this function returns only the visible part
2889 return make_buffer_string_both (BEGV
, BEGV_BYTE
, ZV
, ZV_BYTE
, 1);
2892 DEFUN ("insert-buffer-substring", Finsert_buffer_substring
, Sinsert_buffer_substring
,
2894 doc
: /* Insert before point a substring of the contents of BUFFER.
2895 BUFFER may be a buffer or a buffer name.
2896 Arguments START and END are character positions specifying the substring.
2897 They default to the values of (point-min) and (point-max) in BUFFER.
2899 Point and before-insertion markers move forward to end up after the
2901 Any other markers at the point of insertion remain before the text.
2903 If the current buffer is multibyte and BUFFER is unibyte, or vice
2904 versa, strings are converted from unibyte to multibyte or vice versa
2905 using `string-make-multibyte' or `string-make-unibyte', which see. */)
2906 (Lisp_Object buffer
, Lisp_Object start
, Lisp_Object end
)
2908 register EMACS_INT b
, e
, temp
;
2909 register struct buffer
*bp
, *obuf
;
2912 buf
= Fget_buffer (buffer
);
2916 if (!BUFFER_LIVE_P (bp
))
2917 error ("Selecting deleted buffer");
2923 CHECK_NUMBER_COERCE_MARKER (start
);
2930 CHECK_NUMBER_COERCE_MARKER (end
);
2935 temp
= b
, b
= e
, e
= temp
;
2937 if (!(BUF_BEGV (bp
) <= b
&& e
<= BUF_ZV (bp
)))
2938 args_out_of_range (start
, end
);
2940 obuf
= current_buffer
;
2941 set_buffer_internal_1 (bp
);
2942 update_buffer_properties (b
, e
);
2943 set_buffer_internal_1 (obuf
);
2945 insert_from_buffer (bp
, b
, e
- b
, 0);
2949 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings
, Scompare_buffer_substrings
,
2951 doc
: /* Compare two substrings of two buffers; return result as number.
2952 Return -N if first string is less after N-1 chars, +N if first string is
2953 greater after N-1 chars, or 0 if strings match.
2954 The first substring is in BUFFER1 from START1 to END1 and the second
2955 is in BUFFER2 from START2 to END2.
2956 All arguments may be nil. If BUFFER1 or BUFFER2 is nil, the current
2957 buffer is used. If START1 or START2 is nil, the value of `point-min'
2958 in the respective buffers is used. If END1 or END2 is nil, the value
2959 of `point-max' in the respective buffers is used.
2960 The value of `case-fold-search' in the current buffer
2961 determines whether case is significant or ignored. */)
2962 (Lisp_Object buffer1
, Lisp_Object start1
, Lisp_Object end1
, Lisp_Object buffer2
, Lisp_Object start2
, Lisp_Object end2
)
2964 register EMACS_INT begp1
, endp1
, begp2
, endp2
, temp
;
2965 register struct buffer
*bp1
, *bp2
;
2966 register Lisp_Object trt
2967 = (!NILP (BVAR (current_buffer
, case_fold_search
))
2968 ? BVAR (current_buffer
, case_canon_table
) : Qnil
);
2969 ptrdiff_t chars
= 0;
2970 ptrdiff_t i1
, i2
, i1_byte
, i2_byte
;
2972 /* Find the first buffer and its substring. */
2975 bp1
= current_buffer
;
2979 buf1
= Fget_buffer (buffer1
);
2982 bp1
= XBUFFER (buf1
);
2983 if (!BUFFER_LIVE_P (bp1
))
2984 error ("Selecting deleted buffer");
2988 begp1
= BUF_BEGV (bp1
);
2991 CHECK_NUMBER_COERCE_MARKER (start1
);
2992 begp1
= XINT (start1
);
2995 endp1
= BUF_ZV (bp1
);
2998 CHECK_NUMBER_COERCE_MARKER (end1
);
2999 endp1
= XINT (end1
);
3003 temp
= begp1
, begp1
= endp1
, endp1
= temp
;
3005 if (!(BUF_BEGV (bp1
) <= begp1
3007 && endp1
<= BUF_ZV (bp1
)))
3008 args_out_of_range (start1
, end1
);
3010 /* Likewise for second substring. */
3013 bp2
= current_buffer
;
3017 buf2
= Fget_buffer (buffer2
);
3020 bp2
= XBUFFER (buf2
);
3021 if (!BUFFER_LIVE_P (bp2
))
3022 error ("Selecting deleted buffer");
3026 begp2
= BUF_BEGV (bp2
);
3029 CHECK_NUMBER_COERCE_MARKER (start2
);
3030 begp2
= XINT (start2
);
3033 endp2
= BUF_ZV (bp2
);
3036 CHECK_NUMBER_COERCE_MARKER (end2
);
3037 endp2
= XINT (end2
);
3041 temp
= begp2
, begp2
= endp2
, endp2
= temp
;
3043 if (!(BUF_BEGV (bp2
) <= begp2
3045 && endp2
<= BUF_ZV (bp2
)))
3046 args_out_of_range (start2
, end2
);
3050 i1_byte
= buf_charpos_to_bytepos (bp1
, i1
);
3051 i2_byte
= buf_charpos_to_bytepos (bp2
, i2
);
3053 while (i1
< endp1
&& i2
< endp2
)
3055 /* When we find a mismatch, we must compare the
3056 characters, not just the bytes. */
3059 if (! NILP (BVAR (bp1
, enable_multibyte_characters
)))
3061 c1
= BUF_FETCH_MULTIBYTE_CHAR (bp1
, i1_byte
);
3062 BUF_INC_POS (bp1
, i1_byte
);
3067 c1
= BUF_FETCH_BYTE (bp1
, i1
);
3068 MAKE_CHAR_MULTIBYTE (c1
);
3072 if (! NILP (BVAR (bp2
, enable_multibyte_characters
)))
3074 c2
= BUF_FETCH_MULTIBYTE_CHAR (bp2
, i2_byte
);
3075 BUF_INC_POS (bp2
, i2_byte
);
3080 c2
= BUF_FETCH_BYTE (bp2
, i2
);
3081 MAKE_CHAR_MULTIBYTE (c2
);
3087 c1
= char_table_translate (trt
, c1
);
3088 c2
= char_table_translate (trt
, c2
);
3092 return make_number (c1
< c2
? -1 - chars
: chars
+ 1);
3095 rarely_quit (chars
);
3098 /* The strings match as far as they go.
3099 If one is shorter, that one is less. */
3100 if (chars
< endp1
- begp1
)
3101 return make_number (chars
+ 1);
3102 else if (chars
< endp2
- begp2
)
3103 return make_number (- chars
- 1);
3105 /* Same length too => they are equal. */
3106 return make_number (0);
3110 /* Set up necessary definitions for diffseq.h; see comments in
3111 diffseq.h for explanation. */
3116 #define XVECREF_YVECREF_EQUAL(ctx, xoff, yoff) \
3117 buffer_chars_equal ((ctx), (xoff), (yoff))
3119 #define OFFSET ptrdiff_t
3121 #define EXTRA_CONTEXT_FIELDS \
3122 /* Buffers to compare. */ \
3123 struct buffer *buffer_a; \
3124 struct buffer *buffer_b; \
3125 /* Bit vectors recording for each character whether it was deleted
3127 unsigned char *deletions; \
3128 unsigned char *insertions;
3130 #define NOTE_DELETE(ctx, xoff) set_bit ((ctx)->deletions, (xoff))
3131 #define NOTE_INSERT(ctx, yoff) set_bit ((ctx)->insertions, (yoff))
3134 static void set_bit (unsigned char *, OFFSET
);
3135 static bool bit_is_set (const unsigned char *, OFFSET
);
3136 static bool buffer_chars_equal (struct context
*, OFFSET
, OFFSET
);
3139 #include "diffseq.h"
3141 DEFUN ("replace-buffer-contents", Freplace_buffer_contents
,
3142 Sreplace_buffer_contents
, 1, 1, "bSource buffer: ",
3143 doc
: /* Replace accessible portion of current buffer with that of SOURCE.
3144 SOURCE can be a buffer or a string that names a buffer.
3145 Interactively, prompt for SOURCE.
3146 As far as possible the replacement is non-destructive, i.e. existing
3147 buffer contents, markers, properties, and overlays in the current
3148 buffer stay intact. */)
3149 (Lisp_Object source
)
3151 struct buffer
*a
= current_buffer
;
3152 Lisp_Object source_buffer
= Fget_buffer (source
);
3153 if (NILP (source_buffer
))
3155 struct buffer
*b
= XBUFFER (source_buffer
);
3156 if (! BUFFER_LIVE_P (b
))
3157 error ("Selecting deleted buffer");
3159 error ("Cannot replace a buffer with itself");
3161 ptrdiff_t min_a
= BEGV
;
3162 ptrdiff_t min_b
= BUF_BEGV (b
);
3163 ptrdiff_t size_a
= ZV
- min_a
;
3164 ptrdiff_t size_b
= BUF_ZV (b
) - min_b
;
3165 eassume (size_a
>= 0);
3166 eassume (size_b
>= 0);
3167 bool a_empty
= size_a
== 0;
3168 bool b_empty
= size_b
== 0;
3170 /* Handle trivial cases where at least one accessible portion is
3173 if (a_empty
&& b_empty
)
3177 return Finsert_buffer_substring (source
, Qnil
, Qnil
);
3181 del_range_both (BEGV
, BEGV_BYTE
, ZV
, ZV_BYTE
, true);
3185 /* FIXME: It is not documented how to initialize the contents of the
3186 context structure. This code cargo-cults from the existing
3187 caller in src/analyze.c of GNU Diffutils, which appears to
3190 ptrdiff_t diags
= size_a
+ size_b
+ 3;
3193 SAFE_NALLOCA (buffer
, 2, diags
);
3194 /* Micro-optimization: Casting to size_t generates much better
3196 ptrdiff_t del_bytes
= (size_t) size_a
/ CHAR_BIT
+ 1;
3197 ptrdiff_t ins_bytes
= (size_t) size_b
/ CHAR_BIT
+ 1;
3198 struct context ctx
= {
3201 .deletions
= SAFE_ALLOCA (del_bytes
),
3202 .insertions
= SAFE_ALLOCA (ins_bytes
),
3203 .fdiag
= buffer
+ size_b
+ 1,
3204 .bdiag
= buffer
+ diags
+ size_b
+ 1,
3205 /* FIXME: Find a good number for .too_expensive. */
3206 .too_expensive
= 1000000,
3208 memclear (ctx
.deletions
, del_bytes
);
3209 memclear (ctx
.insertions
, ins_bytes
);
3210 /* compareseq requires indices to be zero-based. We add BEGV back
3212 bool early_abort
= compareseq (0, size_a
, 0, size_b
, false, &ctx
);
3213 /* Since we didn’t define EARLY_ABORT, we should never abort
3215 eassert (! early_abort
);
3219 ptrdiff_t count
= SPECPDL_INDEX ();
3220 record_unwind_protect (save_excursion_restore
, save_excursion_save ());
3222 ptrdiff_t i
= size_a
;
3223 ptrdiff_t j
= size_b
;
3224 /* Walk backwards through the lists of changes. This was also
3225 cargo-culted from src/analyze.c in GNU Diffutils. Because we
3226 walk backwards, we don’t have to keep the positions in sync. */
3227 while (i
>= 0 || j
>= 0)
3229 /* Check whether there is a change (insertion or deletion)
3230 before the current position. */
3231 if ((i
> 0 && bit_is_set (ctx
.deletions
, i
- 1)) ||
3232 (j
> 0 && bit_is_set (ctx
.insertions
, j
- 1)))
3234 ptrdiff_t end_a
= min_a
+ i
;
3235 ptrdiff_t end_b
= min_b
+ j
;
3236 /* Find the beginning of the current change run. */
3237 while (i
> 0 && bit_is_set (ctx
.deletions
, i
- 1))
3239 while (j
> 0 && bit_is_set (ctx
.insertions
, j
- 1))
3241 ptrdiff_t beg_a
= min_a
+ i
;
3242 ptrdiff_t beg_b
= min_b
+ j
;
3243 eassert (beg_a
>= BEGV
);
3244 eassert (beg_b
>= BUF_BEGV (b
));
3245 eassert (beg_a
<= end_a
);
3246 eassert (beg_b
<= end_b
);
3247 eassert (end_a
<= ZV
);
3248 eassert (end_b
<= BUF_ZV (b
));
3249 eassert (beg_a
< end_a
|| beg_b
< end_b
);
3251 del_range (beg_a
, end_a
);
3255 Finsert_buffer_substring (source
, make_natnum (beg_b
),
3256 make_natnum (end_b
));
3263 return unbind_to (count
, Qnil
);
3267 set_bit (unsigned char *a
, ptrdiff_t i
)
3270 /* Micro-optimization: Casting to size_t generates much better
3273 a
[j
/ CHAR_BIT
] |= (1 << (j
% CHAR_BIT
));
3277 bit_is_set (const unsigned char *a
, ptrdiff_t i
)
3280 /* Micro-optimization: Casting to size_t generates much better
3283 return a
[j
/ CHAR_BIT
] & (1 << (j
% CHAR_BIT
));
3286 /* Return true if the characters at position POS_A of buffer
3287 CTX->buffer_a and at position POS_B of buffer CTX->buffer_b are
3288 equal. POS_A and POS_B are zero-based. Text properties are
3292 buffer_chars_equal (struct context
*ctx
,
3293 ptrdiff_t pos_a
, ptrdiff_t pos_b
)
3295 eassert (pos_a
>= 0);
3296 pos_a
+= BUF_BEGV (ctx
->buffer_a
);
3297 eassert (pos_a
>= BUF_BEGV (ctx
->buffer_a
));
3298 eassert (pos_a
< BUF_ZV (ctx
->buffer_a
));
3300 eassert (pos_b
>= 0);
3301 pos_b
+= BUF_BEGV (ctx
->buffer_b
);
3302 eassert (pos_b
>= BUF_BEGV (ctx
->buffer_b
));
3303 eassert (pos_b
< BUF_ZV (ctx
->buffer_b
));
3305 return BUF_FETCH_CHAR_AS_MULTIBYTE (ctx
->buffer_a
, pos_a
)
3306 == BUF_FETCH_CHAR_AS_MULTIBYTE (ctx
->buffer_b
, pos_b
);
3311 subst_char_in_region_unwind (Lisp_Object arg
)
3313 bset_undo_list (current_buffer
, arg
);
3317 subst_char_in_region_unwind_1 (Lisp_Object arg
)
3319 bset_filename (current_buffer
, arg
);
3322 DEFUN ("subst-char-in-region", Fsubst_char_in_region
,
3323 Ssubst_char_in_region
, 4, 5, 0,
3324 doc
: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
3325 If optional arg NOUNDO is non-nil, don't record this change for undo
3326 and don't mark the buffer as really changed.
3327 Both characters must have the same length of multi-byte form. */)
3328 (Lisp_Object start
, Lisp_Object end
, Lisp_Object fromchar
, Lisp_Object tochar
, Lisp_Object noundo
)
3330 register ptrdiff_t pos
, pos_byte
, stop
, i
, len
, end_byte
;
3331 /* Keep track of the first change in the buffer:
3332 if 0 we haven't found it yet.
3333 if < 0 we've found it and we've run the before-change-function.
3334 if > 0 we've actually performed it and the value is its position. */
3335 ptrdiff_t changed
= 0;
3336 unsigned char fromstr
[MAX_MULTIBYTE_LENGTH
], tostr
[MAX_MULTIBYTE_LENGTH
];
3338 ptrdiff_t count
= SPECPDL_INDEX ();
3339 #define COMBINING_NO 0
3340 #define COMBINING_BEFORE 1
3341 #define COMBINING_AFTER 2
3342 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
3343 int maybe_byte_combining
= COMBINING_NO
;
3344 ptrdiff_t last_changed
= 0;
3346 = !NILP (BVAR (current_buffer
, enable_multibyte_characters
));
3351 validate_region (&start
, &end
);
3352 CHECK_CHARACTER (fromchar
);
3353 CHECK_CHARACTER (tochar
);
3354 fromc
= XFASTINT (fromchar
);
3355 toc
= XFASTINT (tochar
);
3359 len
= CHAR_STRING (fromc
, fromstr
);
3360 if (CHAR_STRING (toc
, tostr
) != len
)
3361 error ("Characters in `subst-char-in-region' have different byte-lengths");
3362 if (!ASCII_CHAR_P (*tostr
))
3364 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
3365 complete multibyte character, it may be combined with the
3366 after bytes. If it is in the range 0xA0..0xFF, it may be
3367 combined with the before and after bytes. */
3368 if (!CHAR_HEAD_P (*tostr
))
3369 maybe_byte_combining
= COMBINING_BOTH
;
3370 else if (BYTES_BY_CHAR_HEAD (*tostr
) > len
)
3371 maybe_byte_combining
= COMBINING_AFTER
;
3382 pos_byte
= CHAR_TO_BYTE (pos
);
3383 stop
= CHAR_TO_BYTE (XINT (end
));
3386 /* If we don't want undo, turn off putting stuff on the list.
3387 That's faster than getting rid of things,
3388 and it prevents even the entry for a first change.
3389 Also inhibit locking the file. */
3390 if (!changed
&& !NILP (noundo
))
3392 record_unwind_protect (subst_char_in_region_unwind
,
3393 BVAR (current_buffer
, undo_list
));
3394 bset_undo_list (current_buffer
, Qt
);
3395 /* Don't do file-locking. */
3396 record_unwind_protect (subst_char_in_region_unwind_1
,
3397 BVAR (current_buffer
, filename
));
3398 bset_filename (current_buffer
, Qnil
);
3401 if (pos_byte
< GPT_BYTE
)
3402 stop
= min (stop
, GPT_BYTE
);
3405 ptrdiff_t pos_byte_next
= pos_byte
;
3407 if (pos_byte
>= stop
)
3409 if (pos_byte
>= end_byte
) break;
3412 p
= BYTE_POS_ADDR (pos_byte
);
3414 INC_POS (pos_byte_next
);
3417 if (pos_byte_next
- pos_byte
== len
3418 && p
[0] == fromstr
[0]
3420 || (p
[1] == fromstr
[1]
3421 && (len
== 2 || (p
[2] == fromstr
[2]
3422 && (len
== 3 || p
[3] == fromstr
[3]))))))
3425 /* We've already seen this and run the before-change-function;
3426 this time we only need to record the actual position. */
3431 modify_text (pos
, XINT (end
));
3433 if (! NILP (noundo
))
3435 if (MODIFF
- 1 == SAVE_MODIFF
)
3437 if (MODIFF
- 1 == BUF_AUTOSAVE_MODIFF (current_buffer
))
3438 BUF_AUTOSAVE_MODIFF (current_buffer
)++;
3441 /* The before-change-function may have moved the gap
3442 or even modified the buffer so we should start over. */
3446 /* Take care of the case where the new character
3447 combines with neighboring bytes. */
3448 if (maybe_byte_combining
3449 && (maybe_byte_combining
== COMBINING_AFTER
3450 ? (pos_byte_next
< Z_BYTE
3451 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next
)))
3452 : ((pos_byte_next
< Z_BYTE
3453 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next
)))
3454 || (pos_byte
> BEG_BYTE
3455 && ! ASCII_CHAR_P (FETCH_BYTE (pos_byte
- 1))))))
3457 Lisp_Object tem
, string
;
3459 tem
= BVAR (current_buffer
, undo_list
);
3461 /* Make a multibyte string containing this single character. */
3462 string
= make_multibyte_string ((char *) tostr
, 1, len
);
3463 /* replace_range is less efficient, because it moves the gap,
3464 but it handles combining correctly. */
3465 replace_range (pos
, pos
+ 1, string
,
3467 pos_byte_next
= CHAR_TO_BYTE (pos
);
3468 if (pos_byte_next
> pos_byte
)
3469 /* Before combining happened. We should not increment
3470 POS. So, to cancel the later increment of POS,
3474 INC_POS (pos_byte_next
);
3476 if (! NILP (noundo
))
3477 bset_undo_list (current_buffer
, tem
);
3482 record_change (pos
, 1);
3483 for (i
= 0; i
< len
; i
++) *p
++ = tostr
[i
];
3485 last_changed
= pos
+ 1;
3487 pos_byte
= pos_byte_next
;
3493 signal_after_change (changed
,
3494 last_changed
- changed
, last_changed
- changed
);
3495 update_compositions (changed
, last_changed
, CHECK_ALL
);
3498 unbind_to (count
, Qnil
);
3503 static Lisp_Object
check_translation (ptrdiff_t, ptrdiff_t, ptrdiff_t,
3506 /* Helper function for Ftranslate_region_internal.
3508 Check if a character sequence at POS (POS_BYTE) matches an element
3509 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
3510 element is found, return it. Otherwise return Qnil. */
3513 check_translation (ptrdiff_t pos
, ptrdiff_t pos_byte
, ptrdiff_t end
,
3516 int initial_buf
[16];
3517 int *buf
= initial_buf
;
3518 ptrdiff_t buf_size
= ARRAYELTS (initial_buf
);
3520 ptrdiff_t buf_used
= 0;
3521 Lisp_Object result
= Qnil
;
3523 for (; CONSP (val
); val
= XCDR (val
))
3532 if (! VECTORP (elt
))
3535 if (len
<= end
- pos
)
3537 for (i
= 0; i
< len
; i
++)
3541 unsigned char *p
= BYTE_POS_ADDR (pos_byte
);
3544 if (buf_used
== buf_size
)
3546 bufalloc
= xpalloc (bufalloc
, &buf_size
, 1, -1,
3548 if (buf
== initial_buf
)
3549 memcpy (bufalloc
, buf
, sizeof initial_buf
);
3552 buf
[buf_used
++] = STRING_CHAR_AND_LENGTH (p
, len1
);
3555 if (XINT (AREF (elt
, i
)) != buf
[i
])
3560 result
= XCAR (val
);
3571 DEFUN ("translate-region-internal", Ftranslate_region_internal
,
3572 Stranslate_region_internal
, 3, 3, 0,
3573 doc
: /* Internal use only.
3574 From START to END, translate characters according to TABLE.
3575 TABLE is a string or a char-table; the Nth character in it is the
3576 mapping for the character with code N.
3577 It returns the number of characters changed. */)
3578 (Lisp_Object start
, Lisp_Object end
, register Lisp_Object table
)
3580 register unsigned char *tt
; /* Trans table. */
3581 register int nc
; /* New character. */
3582 int cnt
; /* Number of changes made. */
3583 ptrdiff_t size
; /* Size of translate table. */
3584 ptrdiff_t pos
, pos_byte
, end_pos
;
3585 bool multibyte
= !NILP (BVAR (current_buffer
, enable_multibyte_characters
));
3586 bool string_multibyte UNINIT
;
3588 validate_region (&start
, &end
);
3589 if (CHAR_TABLE_P (table
))
3591 if (! EQ (XCHAR_TABLE (table
)->purpose
, Qtranslation_table
))
3592 error ("Not a translation table");
3598 CHECK_STRING (table
);
3600 if (! multibyte
&& (SCHARS (table
) < SBYTES (table
)))
3601 table
= string_make_unibyte (table
);
3602 string_multibyte
= SCHARS (table
) < SBYTES (table
);
3603 size
= SBYTES (table
);
3608 pos_byte
= CHAR_TO_BYTE (pos
);
3609 end_pos
= XINT (end
);
3610 modify_text (pos
, end_pos
);
3613 for (; pos
< end_pos
; )
3615 unsigned char *p
= BYTE_POS_ADDR (pos_byte
);
3616 unsigned char *str UNINIT
;
3617 unsigned char buf
[MAX_MULTIBYTE_LENGTH
];
3623 oc
= STRING_CHAR_AND_LENGTH (p
, len
);
3630 /* Reload as signal_after_change in last iteration may GC. */
3632 if (string_multibyte
)
3634 str
= tt
+ string_char_to_byte (table
, oc
);
3635 nc
= STRING_CHAR_AND_LENGTH (str
, str_len
);
3640 if (! ASCII_CHAR_P (nc
) && multibyte
)
3642 str_len
= BYTE8_STRING (nc
, buf
);
3655 val
= CHAR_TABLE_REF (table
, oc
);
3656 if (CHARACTERP (val
))
3658 nc
= XFASTINT (val
);
3659 str_len
= CHAR_STRING (nc
, buf
);
3662 else if (VECTORP (val
) || (CONSP (val
)))
3664 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3665 where TO is TO-CHAR or [TO-CHAR ...]. */
3670 if (nc
!= oc
&& nc
>= 0)
3672 /* Simple one char to one char translation. */
3677 /* This is less efficient, because it moves the gap,
3678 but it should handle multibyte characters correctly. */
3679 string
= make_multibyte_string ((char *) str
, 1, str_len
);
3680 replace_range (pos
, pos
+ 1, string
, 1, 0, 1, 0);
3685 record_change (pos
, 1);
3686 while (str_len
-- > 0)
3688 signal_after_change (pos
, 1, 1);
3689 update_compositions (pos
, pos
+ 1, CHECK_BORDER
);
3699 val
= check_translation (pos
, pos_byte
, end_pos
, val
);
3706 /* VAL is ([FROM-CHAR ...] . TO). */
3707 len
= ASIZE (XCAR (val
));
3715 string
= Fconcat (1, &val
);
3719 string
= Fmake_string (make_number (1), val
);
3721 replace_range (pos
, pos
+ len
, string
, 1, 0, 1, 0);
3722 pos_byte
+= SBYTES (string
);
3723 pos
+= SCHARS (string
);
3724 cnt
+= SCHARS (string
);
3725 end_pos
+= SCHARS (string
) - len
;
3733 return make_number (cnt
);
3736 DEFUN ("delete-region", Fdelete_region
, Sdelete_region
, 2, 2, "r",
3737 doc
: /* Delete the text between START and END.
3738 If called interactively, delete the region between point and mark.
3739 This command deletes buffer text without modifying the kill ring. */)
3740 (Lisp_Object start
, Lisp_Object end
)
3742 validate_region (&start
, &end
);
3743 del_range (XINT (start
), XINT (end
));
3747 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region
,
3748 Sdelete_and_extract_region
, 2, 2, 0,
3749 doc
: /* Delete the text between START and END and return it. */)
3750 (Lisp_Object start
, Lisp_Object end
)
3752 validate_region (&start
, &end
);
3753 if (XINT (start
) == XINT (end
))
3754 return empty_unibyte_string
;
3755 return del_range_1 (XINT (start
), XINT (end
), 1, 1);
3758 DEFUN ("widen", Fwiden
, Swiden
, 0, 0, "",
3759 doc
: /* Remove restrictions (narrowing) from current buffer.
3760 This allows the buffer's full text to be seen and edited. */)
3763 if (BEG
!= BEGV
|| Z
!= ZV
)
3764 current_buffer
->clip_changed
= 1;
3766 BEGV_BYTE
= BEG_BYTE
;
3767 SET_BUF_ZV_BOTH (current_buffer
, Z
, Z_BYTE
);
3768 /* Changing the buffer bounds invalidates any recorded current column. */
3769 invalidate_current_column ();
3773 DEFUN ("narrow-to-region", Fnarrow_to_region
, Snarrow_to_region
, 2, 2, "r",
3774 doc
: /* Restrict editing in this buffer to the current region.
3775 The rest of the text becomes temporarily invisible and untouchable
3776 but is not deleted; if you save the buffer in a file, the invisible
3777 text is included in the file. \\[widen] makes all visible again.
3778 See also `save-restriction'.
3780 When calling from a program, pass two arguments; positions (integers
3781 or markers) bounding the text that should remain visible. */)
3782 (register Lisp_Object start
, Lisp_Object end
)
3784 CHECK_NUMBER_COERCE_MARKER (start
);
3785 CHECK_NUMBER_COERCE_MARKER (end
);
3787 if (XINT (start
) > XINT (end
))
3790 tem
= start
; start
= end
; end
= tem
;
3793 if (!(BEG
<= XINT (start
) && XINT (start
) <= XINT (end
) && XINT (end
) <= Z
))
3794 args_out_of_range (start
, end
);
3796 if (BEGV
!= XFASTINT (start
) || ZV
!= XFASTINT (end
))
3797 current_buffer
->clip_changed
= 1;
3799 SET_BUF_BEGV (current_buffer
, XFASTINT (start
));
3800 SET_BUF_ZV (current_buffer
, XFASTINT (end
));
3801 if (PT
< XFASTINT (start
))
3802 SET_PT (XFASTINT (start
));
3803 if (PT
> XFASTINT (end
))
3804 SET_PT (XFASTINT (end
));
3805 /* Changing the buffer bounds invalidates any recorded current column. */
3806 invalidate_current_column ();
3811 save_restriction_save (void)
3813 if (BEGV
== BEG
&& ZV
== Z
)
3814 /* The common case that the buffer isn't narrowed.
3815 We return just the buffer object, which save_restriction_restore
3816 recognizes as meaning `no restriction'. */
3817 return Fcurrent_buffer ();
3819 /* We have to save a restriction, so return a pair of markers, one
3820 for the beginning and one for the end. */
3822 Lisp_Object beg
, end
;
3824 beg
= build_marker (current_buffer
, BEGV
, BEGV_BYTE
);
3825 end
= build_marker (current_buffer
, ZV
, ZV_BYTE
);
3827 /* END must move forward if text is inserted at its exact location. */
3828 XMARKER (end
)->insertion_type
= 1;
3830 return Fcons (beg
, end
);
3835 save_restriction_restore (Lisp_Object data
)
3837 struct buffer
*cur
= NULL
;
3838 struct buffer
*buf
= (CONSP (data
)
3839 ? XMARKER (XCAR (data
))->buffer
3842 if (buf
&& buf
!= current_buffer
&& !NILP (BVAR (buf
, pt_marker
)))
3843 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3844 is the case if it is or has an indirect buffer), then make
3845 sure it is current before we update BEGV, so
3846 set_buffer_internal takes care of managing those markers. */
3847 cur
= current_buffer
;
3848 set_buffer_internal (buf
);
3852 /* A pair of marks bounding a saved restriction. */
3854 struct Lisp_Marker
*beg
= XMARKER (XCAR (data
));
3855 struct Lisp_Marker
*end
= XMARKER (XCDR (data
));
3856 eassert (buf
== end
->buffer
);
3858 if (buf
/* Verify marker still points to a buffer. */
3859 && (beg
->charpos
!= BUF_BEGV (buf
) || end
->charpos
!= BUF_ZV (buf
)))
3860 /* The restriction has changed from the saved one, so restore
3861 the saved restriction. */
3863 ptrdiff_t pt
= BUF_PT (buf
);
3865 SET_BUF_BEGV_BOTH (buf
, beg
->charpos
, beg
->bytepos
);
3866 SET_BUF_ZV_BOTH (buf
, end
->charpos
, end
->bytepos
);
3868 if (pt
< beg
->charpos
|| pt
> end
->charpos
)
3869 /* The point is outside the new visible range, move it inside. */
3870 SET_BUF_PT_BOTH (buf
,
3871 clip_to_bounds (beg
->charpos
, pt
, end
->charpos
),
3872 clip_to_bounds (beg
->bytepos
, BUF_PT_BYTE (buf
),
3875 buf
->clip_changed
= 1; /* Remember that the narrowing changed. */
3877 /* These aren't needed anymore, so don't wait for GC. */
3878 free_marker (XCAR (data
));
3879 free_marker (XCDR (data
));
3880 free_cons (XCONS (data
));
3883 /* A buffer, which means that there was no old restriction. */
3885 if (buf
/* Verify marker still points to a buffer. */
3886 && (BUF_BEGV (buf
) != BUF_BEG (buf
) || BUF_ZV (buf
) != BUF_Z (buf
)))
3887 /* The buffer has been narrowed, get rid of the narrowing. */
3889 SET_BUF_BEGV_BOTH (buf
, BUF_BEG (buf
), BUF_BEG_BYTE (buf
));
3890 SET_BUF_ZV_BOTH (buf
, BUF_Z (buf
), BUF_Z_BYTE (buf
));
3892 buf
->clip_changed
= 1; /* Remember that the narrowing changed. */
3896 /* Changing the buffer bounds invalidates any recorded current column. */
3897 invalidate_current_column ();
3900 set_buffer_internal (cur
);
3903 DEFUN ("save-restriction", Fsave_restriction
, Ssave_restriction
, 0, UNEVALLED
, 0,
3904 doc
: /* Execute BODY, saving and restoring current buffer's restrictions.
3905 The buffer's restrictions make parts of the beginning and end invisible.
3906 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3907 This special form, `save-restriction', saves the current buffer's restrictions
3908 when it is entered, and restores them when it is exited.
3909 So any `narrow-to-region' within BODY lasts only until the end of the form.
3910 The old restrictions settings are restored
3911 even in case of abnormal exit (throw or error).
3913 The value returned is the value of the last form in BODY.
3915 Note: if you are using both `save-excursion' and `save-restriction',
3916 use `save-excursion' outermost:
3917 (save-excursion (save-restriction ...))
3919 usage: (save-restriction &rest BODY) */)
3922 register Lisp_Object val
;
3923 ptrdiff_t count
= SPECPDL_INDEX ();
3925 record_unwind_protect (save_restriction_restore
, save_restriction_save ());
3926 val
= Fprogn (body
);
3927 return unbind_to (count
, val
);
3930 DEFUN ("message", Fmessage
, Smessage
, 1, MANY
, 0,
3931 doc
: /* Display a message at the bottom of the screen.
3932 The message also goes into the `*Messages*' buffer, if `message-log-max'
3933 is non-nil. (In keyboard macros, that's all it does.)
3936 In batch mode, the message is printed to the standard error stream,
3937 followed by a newline.
3939 The first argument is a format control string, and the rest are data
3940 to be formatted under control of the string. Percent sign (%), grave
3941 accent (\\=`) and apostrophe (\\=') are special in the format; see
3942 `format-message' for details. To display STRING without special
3943 treatment, use (message "%s" STRING).
3945 If the first argument is nil or the empty string, the function clears
3946 any existing message; this lets the minibuffer contents show. See
3947 also `current-message'.
3949 usage: (message FORMAT-STRING &rest ARGS) */)
3950 (ptrdiff_t nargs
, Lisp_Object
*args
)
3953 || (STRINGP (args
[0])
3954 && SBYTES (args
[0]) == 0))
3961 Lisp_Object val
= styled_format (nargs
, args
, true, false);
3967 DEFUN ("message-box", Fmessage_box
, Smessage_box
, 1, MANY
, 0,
3968 doc
: /* Display a message, in a dialog box if possible.
3969 If a dialog box is not available, use the echo area.
3970 The first argument is a format control string, and the rest are data
3971 to be formatted under control of the string. See `format-message' for
3974 If the first argument is nil or the empty string, clear any existing
3975 message; let the minibuffer contents show.
3977 usage: (message-box FORMAT-STRING &rest ARGS) */)
3978 (ptrdiff_t nargs
, Lisp_Object
*args
)
3987 Lisp_Object val
= styled_format (nargs
, args
, true, false);
3988 Lisp_Object pane
, menu
;
3990 pane
= list1 (Fcons (build_string ("OK"), Qt
));
3991 menu
= Fcons (val
, pane
);
3992 Fx_popup_dialog (Qt
, menu
, Qt
);
3997 DEFUN ("message-or-box", Fmessage_or_box
, Smessage_or_box
, 1, MANY
, 0,
3998 doc
: /* Display a message in a dialog box or in the echo area.
3999 If this command was invoked with the mouse, use a dialog box if
4000 `use-dialog-box' is non-nil.
4001 Otherwise, use the echo area.
4002 The first argument is a format control string, and the rest are data
4003 to be formatted under control of the string. See `format-message' for
4006 If the first argument is nil or the empty string, clear any existing
4007 message; let the minibuffer contents show.
4009 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
4010 (ptrdiff_t nargs
, Lisp_Object
*args
)
4012 if ((NILP (last_nonmenu_event
) || CONSP (last_nonmenu_event
))
4014 return Fmessage_box (nargs
, args
);
4015 return Fmessage (nargs
, args
);
4018 DEFUN ("current-message", Fcurrent_message
, Scurrent_message
, 0, 0, 0,
4019 doc
: /* Return the string currently displayed in the echo area, or nil if none. */)
4022 return current_message ();
4026 DEFUN ("propertize", Fpropertize
, Spropertize
, 1, MANY
, 0,
4027 doc
: /* Return a copy of STRING with text properties added.
4028 First argument is the string to copy.
4029 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
4030 properties to add to the result.
4031 usage: (propertize STRING &rest PROPERTIES) */)
4032 (ptrdiff_t nargs
, Lisp_Object
*args
)
4034 Lisp_Object properties
, string
;
4037 /* Number of args must be odd. */
4038 if ((nargs
& 1) == 0)
4039 error ("Wrong number of arguments");
4041 properties
= string
= Qnil
;
4043 /* First argument must be a string. */
4044 CHECK_STRING (args
[0]);
4045 string
= Fcopy_sequence (args
[0]);
4047 for (i
= 1; i
< nargs
; i
+= 2)
4048 properties
= Fcons (args
[i
], Fcons (args
[i
+ 1], properties
));
4050 Fadd_text_properties (make_number (0),
4051 make_number (SCHARS (string
)),
4052 properties
, string
);
4056 /* Convert the prefix of STR from ASCII decimal digits to a number.
4057 Set *STR_END to the address of the first non-digit. Return the
4058 number, or PTRDIFF_MAX on overflow. Return 0 if there is no number.
4059 This is like strtol for ptrdiff_t and base 10 and C locale,
4060 except without negative numbers or errno. */
4063 str2num (char *str
, char **str_end
)
4066 for (; c_isdigit (*str
); str
++)
4067 if (INT_MULTIPLY_WRAPV (n
, 10, &n
) || INT_ADD_WRAPV (n
, *str
- '0', &n
))
4073 DEFUN ("format", Fformat
, Sformat
, 1, MANY
, 0,
4074 doc
: /* Format a string out of a format-string and arguments.
4075 The first argument is a format control string.
4076 The other arguments are substituted into it to make the result, a string.
4078 The format control string may contain %-sequences meaning to substitute
4079 the next available argument, or the argument explicitly specified:
4081 %s means print a string argument. Actually, prints any object, with `princ'.
4082 %d means print as signed number in decimal.
4083 %o means print as unsigned number in octal, %x as unsigned number in hex.
4084 %X is like %x, but uses upper case.
4085 %e means print a number in exponential notation.
4086 %f means print a number in decimal-point notation.
4087 %g means print a number in exponential notation if the exponent would be
4088 less than -4 or greater than or equal to the precision (default: 6);
4089 otherwise it prints in decimal-point notation.
4090 %c means print a number as a single character.
4091 %S means print any object as an s-expression (using `prin1').
4093 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
4094 Use %% to put a single % into the output.
4096 A %-sequence other than %% may contain optional field number, flag,
4097 width, and precision specifiers, as follows:
4099 %<field><flags><width><precision>character
4101 where field is [0-9]+ followed by a literal dollar "$", flags is
4102 [+ #-0]+, width is [0-9]+, and precision is a literal period "."
4105 If a %-sequence is numbered with a field with positive value N, the
4106 Nth argument is substituted instead of the next one. A format can
4107 contain either numbered or unnumbered %-sequences but not both, except
4108 that %% can be mixed with numbered %-sequences.
4110 The + flag character inserts a + before any positive number, while a
4111 space inserts a space before any positive number; these flags only
4112 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
4113 The - and 0 flags affect the width specifier, as described below.
4115 The # flag means to use an alternate display form for %o, %x, %X, %e,
4116 %f, and %g sequences: for %o, it ensures that the result begins with
4117 \"0\"; for %x and %X, it prefixes the result with \"0x\" or \"0X\";
4118 for %e and %f, it causes a decimal point to be included even if the
4119 the precision is zero; for %g, it causes a decimal point to be
4120 included even if the the precision is zero, and also forces trailing
4121 zeros after the decimal point to be left in place.
4123 The width specifier supplies a lower limit for the length of the
4124 printed representation. The padding, if any, normally goes on the
4125 left, but it goes on the right if the - flag is present. The padding
4126 character is normally a space, but it is 0 if the 0 flag is present.
4127 The 0 flag is ignored if the - flag is present, or the format sequence
4128 is something other than %d, %e, %f, and %g.
4130 For %e and %f sequences, the number after the "." in the precision
4131 specifier says how many decimal places to show; if zero, the decimal
4132 point itself is omitted. For %g, the precision specifies how many
4133 significant digits to print; zero or omitted are treated as 1.
4134 For %s and %S, the precision specifier truncates the string to the
4137 Text properties, if any, are copied from the format-string to the
4140 usage: (format STRING &rest OBJECTS) */)
4141 (ptrdiff_t nargs
, Lisp_Object
*args
)
4143 return styled_format (nargs
, args
, false, true);
4146 DEFUN ("format-message", Fformat_message
, Sformat_message
, 1, MANY
, 0,
4147 doc
: /* Format a string out of a format-string and arguments.
4148 The first argument is a format control string.
4149 The other arguments are substituted into it to make the result, a string.
4151 This acts like `format', except it also replaces each grave accent (\\=`)
4152 by a left quote, and each apostrophe (\\=') by a right quote. The left
4153 and right quote replacement characters are specified by
4154 `text-quoting-style'.
4156 usage: (format-message STRING &rest OBJECTS) */)
4157 (ptrdiff_t nargs
, Lisp_Object
*args
)
4159 return styled_format (nargs
, args
, true, true);
4162 /* Implement ‘format-message’ if MESSAGE is true, ‘format’ otherwise.
4163 If NEW_RESULT, the result is a new string; otherwise, the result
4164 may be one of the arguments. */
4167 styled_format (ptrdiff_t nargs
, Lisp_Object
*args
, bool message
,
4170 ptrdiff_t n
; /* The number of the next arg to substitute. */
4171 char initial_buffer
[4000];
4172 char *buf
= initial_buffer
;
4173 ptrdiff_t bufsize
= sizeof initial_buffer
;
4174 ptrdiff_t max_bufsize
= STRING_BYTES_BOUND
+ 1;
4176 ptrdiff_t buf_save_value_index UNINIT
;
4179 /* When we make a multibyte string, we must pay attention to the
4180 byte combining problem, i.e., a byte may be combined with a
4181 multibyte character of the previous string. This flag tells if we
4182 must consider such a situation or not. */
4183 bool maybe_combine_byte
;
4184 bool arg_intervals
= false;
4186 sa_avail
-= sizeof initial_buffer
;
4188 /* Information recorded for each format spec. */
4191 /* The corresponding argument, converted to string if conversion
4193 Lisp_Object argument
;
4195 /* The start and end bytepos in the output string. */
4196 ptrdiff_t start
, end
;
4198 /* Whether the argument is a newly created string. */
4199 bool_bf new_string
: 1;
4201 /* Whether the argument is a string with intervals. */
4202 bool_bf intervals
: 1;
4205 CHECK_STRING (args
[0]);
4206 char *format_start
= SSDATA (args
[0]);
4207 bool multibyte_format
= STRING_MULTIBYTE (args
[0]);
4208 ptrdiff_t formatlen
= SBYTES (args
[0]);
4210 /* Upper bound on number of format specs. Each uses at least 2 chars. */
4211 ptrdiff_t nspec_bound
= SCHARS (args
[0]) >> 1;
4213 /* Allocate the info and discarded tables. */
4214 ptrdiff_t alloca_size
;
4215 if (INT_MULTIPLY_WRAPV (nspec_bound
, sizeof *info
, &alloca_size
)
4216 || INT_ADD_WRAPV (formatlen
, alloca_size
, &alloca_size
)
4217 || SIZE_MAX
< alloca_size
)
4218 memory_full (SIZE_MAX
);
4219 info
= SAFE_ALLOCA (alloca_size
);
4220 /* discarded[I] is 1 if byte I of the format
4221 string was not copied into the output.
4222 It is 2 if byte I was not the first byte of its character. */
4223 char *discarded
= (char *) &info
[nspec_bound
];
4224 memset (discarded
, 0, formatlen
);
4226 /* Try to determine whether the result should be multibyte.
4227 This is not always right; sometimes the result needs to be multibyte
4228 because of an object that we will pass through prin1.
4229 or because a grave accent or apostrophe is requoted,
4230 and in that case, we won't know it here. */
4232 /* True if the output should be a multibyte string,
4233 which is true if any of the inputs is one. */
4234 bool multibyte
= multibyte_format
;
4235 for (ptrdiff_t i
= 1; !multibyte
&& i
< nargs
; i
++)
4236 if (STRINGP (args
[i
]) && STRING_MULTIBYTE (args
[i
]))
4239 int quoting_style
= message
? text_quoting_style () : -1;
4242 ptrdiff_t nspec
= 0;
4244 /* If we start out planning a unibyte result,
4245 then discover it has to be multibyte, we jump back to retry. */
4251 /* N is the argument index, ISPEC is the specification index. */
4255 /* Scan the format and store result in BUF. */
4256 format
= format_start
;
4257 end
= format
+ formatlen
;
4258 maybe_combine_byte
= false;
4260 while (format
!= end
)
4262 /* The values of N, ISPEC, and FORMAT when the loop body is
4265 ptrdiff_t ispec0
= ispec
;
4266 char *format0
= format
;
4267 char const *convsrc
= format
;
4268 unsigned char format_char
= *format
++;
4270 /* Bytes needed to represent the output of this conversion. */
4271 ptrdiff_t convbytes
= 1;
4273 if (format_char
== '%')
4275 /* General format specifications look like
4277 '%' [field-number] [flags] [field-width] [precision] format
4281 field-number ::= [0-9]+ '$'
4283 field-width ::= [0-9]+
4284 precision ::= '.' [0-9]*
4286 If present, a field-number specifies the argument number
4287 to substitute. Otherwise, the next argument is taken.
4289 If a field-width is specified, it specifies to which width
4290 the output should be padded with blanks, if the output
4291 string is shorter than field-width.
4293 If precision is specified, it specifies the number of
4294 digits to print after the '.' for floats, or the max.
4295 number of chars to print from a string. */
4299 if (c_isdigit (*format
))
4301 num
= str2num (format
, &num_end
);
4302 if (*num_end
== '$')
4305 format
= num_end
+ 1;
4309 bool minus_flag
= false;
4310 bool plus_flag
= false;
4311 bool space_flag
= false;
4312 bool sharp_flag
= false;
4313 bool zero_flag
= false;
4319 case '-': minus_flag
= true; continue;
4320 case '+': plus_flag
= true; continue;
4321 case ' ': space_flag
= true; continue;
4322 case '#': sharp_flag
= true; continue;
4323 case '0': zero_flag
= true; continue;
4328 /* Ignore flags when sprintf ignores them. */
4329 space_flag
&= ! plus_flag
;
4330 zero_flag
&= ! minus_flag
;
4332 num
= str2num (format
, &num_end
);
4333 if (max_bufsize
<= num
)
4335 ptrdiff_t field_width
= num
;
4337 bool precision_given
= *num_end
== '.';
4338 ptrdiff_t precision
= (precision_given
4339 ? str2num (num_end
+ 1, &num_end
)
4344 error ("Format string ends in middle of format specifier");
4346 char conversion
= *format
++;
4347 memset (&discarded
[format0
- format_start
], 1,
4348 format
- format0
- (conversion
== '%'));
4349 if (conversion
== '%')
4357 error ("Not enough arguments for format string");
4359 struct info
*spec
= &info
[ispec
++];
4362 spec
->argument
= args
[n
];
4363 spec
->new_string
= false;
4364 spec
->intervals
= false;
4367 Lisp_Object arg
= spec
->argument
;
4369 /* For 'S', prin1 the argument, and then treat like 's'.
4370 For 's', princ any argument that is not a string or
4371 symbol. But don't do this conversion twice, which might
4372 happen after retrying. */
4373 if ((conversion
== 'S'
4374 || (conversion
== 's'
4375 && ! STRINGP (arg
) && ! SYMBOLP (arg
))))
4377 if (EQ (arg
, args
[n
]))
4379 Lisp_Object noescape
= conversion
== 'S' ? Qnil
: Qt
;
4380 spec
->argument
= arg
= Fprin1_to_string (arg
, noescape
);
4381 spec
->new_string
= true;
4382 if (STRING_MULTIBYTE (arg
) && ! multibyte
)
4391 else if (conversion
== 'c')
4393 if (INTEGERP (arg
) && ! ASCII_CHAR_P (XINT (arg
)))
4400 spec
->argument
= arg
= Fchar_to_string (arg
);
4401 spec
->new_string
= true;
4404 if (!EQ (arg
, args
[n
]))
4411 spec
->argument
= arg
= SYMBOL_NAME (arg
);
4412 if (STRING_MULTIBYTE (arg
) && ! multibyte
)
4419 bool float_conversion
4420 = conversion
== 'e' || conversion
== 'f' || conversion
== 'g';
4422 if (conversion
== 's')
4424 if (format
== end
&& format
- format_start
== 2
4425 && (!new_result
|| spec
->new_string
)
4426 && ! string_intervals (args
[0]))
4429 /* handle case (precision[n] >= 0) */
4431 ptrdiff_t prec
= -1;
4432 if (precision_given
)
4435 /* lisp_string_width ignores a precision of 0, but GNU
4436 libc functions print 0 characters when the precision
4437 is 0. Imitate libc behavior here. Changing
4438 lisp_string_width is the right thing, and will be
4439 done, but meanwhile we work with it. */
4441 ptrdiff_t width
, nbytes
;
4442 ptrdiff_t nchars_string
;
4444 width
= nchars_string
= nbytes
= 0;
4448 width
= lisp_string_width (arg
, prec
, &nch
, &nby
);
4451 nchars_string
= SCHARS (arg
);
4452 nbytes
= SBYTES (arg
);
4456 nchars_string
= nch
;
4462 if (convbytes
&& multibyte
&& ! STRING_MULTIBYTE (arg
))
4463 convbytes
= count_size_as_multibyte (SDATA (arg
), nbytes
);
4466 = width
< field_width
? field_width
- width
: 0;
4468 if (max_bufsize
- padding
<= convbytes
)
4470 convbytes
+= padding
;
4471 if (convbytes
<= buf
+ bufsize
- p
)
4475 memset (p
, ' ', padding
);
4479 spec
->start
= nchars
;
4483 && !ASCII_CHAR_P (*((unsigned char *) p
- 1))
4484 && STRING_MULTIBYTE (arg
)
4485 && !CHAR_HEAD_P (SREF (arg
, 0)))
4486 maybe_combine_byte
= true;
4488 p
+= copy_text (SDATA (arg
), (unsigned char *) p
,
4490 STRING_MULTIBYTE (arg
), multibyte
);
4492 nchars
+= nchars_string
;
4496 memset (p
, ' ', padding
);
4502 /* If this argument has text properties, record where
4503 in the result string it appears. */
4504 if (string_intervals (arg
))
4505 spec
->intervals
= arg_intervals
= true;
4511 else if (! (conversion
== 'c' || conversion
== 'd'
4512 || float_conversion
|| conversion
== 'i'
4513 || conversion
== 'o' || conversion
== 'x'
4514 || conversion
== 'X'))
4515 error ("Invalid format operation %%%c",
4516 STRING_CHAR ((unsigned char *) format
- 1));
4517 else if (! (INTEGERP (arg
) || (FLOATP (arg
) && conversion
!= 'c')))
4518 error ("Format specifier doesn't match argument type");
4523 /* Lower bound on the number of bits per
4524 base-FLT_RADIX digit. */
4525 DIG_BITS_LBOUND
= FLT_RADIX
< 16 ? 1 : 4,
4527 /* 1 if integers should be formatted as long doubles,
4528 because they may be so large that there is a rounding
4529 error when converting them to double, and long doubles
4530 are wider than doubles. */
4531 INT_AS_LDBL
= (DIG_BITS_LBOUND
* DBL_MANT_DIG
< FIXNUM_BITS
- 1
4532 && DBL_MANT_DIG
< LDBL_MANT_DIG
),
4534 /* Maximum precision for a %f conversion such that the
4535 trailing output digit might be nonzero. Any precision
4536 larger than this will not yield useful information. */
4537 USEFUL_PRECISION_MAX
=
4539 * (FLT_RADIX
== 2 || FLT_RADIX
== 10 ? 1
4540 : FLT_RADIX
== 16 ? 4
4543 /* Maximum number of bytes generated by any format, if
4544 precision is no more than USEFUL_PRECISION_MAX.
4545 On all practical hosts, %f is the worst case. */
4547 sizeof "-." + (LDBL_MAX_10_EXP
+ 1) + USEFUL_PRECISION_MAX
,
4549 /* Length of pM (that is, of pMd without the
4551 pMlen
= sizeof pMd
- 2
4553 verify (USEFUL_PRECISION_MAX
> 0);
4555 /* Avoid undefined behavior in underlying sprintf. */
4556 if (conversion
== 'd' || conversion
== 'i')
4559 /* Create the copy of the conversion specification, with
4560 any width and precision removed, with ".*" inserted,
4561 with "L" possibly inserted for floating-point formats,
4562 and with pM inserted for integer formats.
4563 At most two flags F can be specified at once. */
4564 char convspec
[sizeof "%FF.*d" + max (INT_AS_LDBL
, pMlen
)];
4568 /* MINUS_FLAG and ZERO_FLAG are dealt with later. */
4569 *f
= '+'; f
+= plus_flag
;
4570 *f
= ' '; f
+= space_flag
;
4571 *f
= '#'; f
+= sharp_flag
;
4574 if (float_conversion
)
4579 f
+= INTEGERP (arg
);
4582 else if (conversion
!= 'c')
4584 memcpy (f
, pMd
, pMlen
);
4586 zero_flag
&= ! precision_given
;
4593 if (precision_given
)
4594 prec
= min (precision
, USEFUL_PRECISION_MAX
);
4596 /* Use sprintf to format this number into sprintf_buf. Omit
4597 padding and excess precision, though, because sprintf limits
4598 output length to INT_MAX.
4600 There are four types of conversion: double, unsigned
4601 char (passed as int), wide signed int, and wide
4602 unsigned int. Treat them separately because the
4603 sprintf ABI is sensitive to which type is passed. Be
4604 careful about integer overflow, NaNs, infinities, and
4605 conversions; for example, the min and max macros are
4606 not suitable here. */
4607 char sprintf_buf
[SPRINTF_BUFSIZE
];
4608 ptrdiff_t sprintf_bytes
;
4609 if (float_conversion
)
4611 if (INT_AS_LDBL
&& INTEGERP (arg
))
4613 /* Although long double may have a rounding error if
4614 DIG_BITS_LBOUND * LDBL_MANT_DIG < FIXNUM_BITS - 1,
4615 it is more accurate than plain 'double'. */
4616 long double x
= XINT (arg
);
4617 sprintf_bytes
= sprintf (sprintf_buf
, convspec
, prec
, x
);
4620 sprintf_bytes
= sprintf (sprintf_buf
, convspec
, prec
,
4623 else if (conversion
== 'c')
4625 /* Don't use sprintf here, as it might mishandle prec. */
4626 sprintf_buf
[0] = XINT (arg
);
4627 sprintf_bytes
= prec
!= 0;
4629 else if (conversion
== 'd' || conversion
== 'i')
4631 /* For float, maybe we should use "%1.0f"
4632 instead so it also works for values outside
4633 the integer range. */
4639 double d
= XFLOAT_DATA (arg
);
4642 x
= TYPE_MINIMUM (printmax_t
);
4648 x
= TYPE_MAXIMUM (printmax_t
);
4653 sprintf_bytes
= sprintf (sprintf_buf
, convspec
, prec
, x
);
4657 /* Don't sign-extend for octal or hex printing. */
4663 double d
= XFLOAT_DATA (arg
);
4668 x
= TYPE_MAXIMUM (uprintmax_t
);
4673 sprintf_bytes
= sprintf (sprintf_buf
, convspec
, prec
, x
);
4676 /* Now the length of the formatted item is known, except it omits
4677 padding and excess precision. Deal with excess precision
4678 first. This happens only when the format specifies
4679 ridiculously large precision. */
4680 ptrdiff_t excess_precision
4681 = precision_given
? precision
- prec
: 0;
4682 ptrdiff_t leading_zeros
= 0, trailing_zeros
= 0;
4683 if (excess_precision
)
4685 if (float_conversion
)
4687 if ((conversion
== 'g' && ! sharp_flag
)
4688 || ! ('0' <= sprintf_buf
[sprintf_bytes
- 1]
4689 && sprintf_buf
[sprintf_bytes
- 1] <= '9'))
4690 excess_precision
= 0;
4693 if (conversion
== 'g')
4695 char *dot
= strchr (sprintf_buf
, '.');
4697 excess_precision
= 0;
4700 trailing_zeros
= excess_precision
;
4703 leading_zeros
= excess_precision
;
4706 /* Compute the total bytes needed for this item, including
4707 excess precision and padding. */
4709 if (INT_ADD_WRAPV (sprintf_bytes
, excess_precision
, &numwidth
))
4710 numwidth
= PTRDIFF_MAX
;
4712 = numwidth
< field_width
? field_width
- numwidth
: 0;
4713 if (max_bufsize
- sprintf_bytes
<= excess_precision
4714 || max_bufsize
- padding
<= numwidth
)
4716 convbytes
= numwidth
+ padding
;
4718 if (convbytes
<= buf
+ bufsize
- p
)
4720 /* Copy the formatted item from sprintf_buf into buf,
4721 inserting padding and excess-precision zeros. */
4723 char *src
= sprintf_buf
;
4725 int exponent_bytes
= 0;
4726 bool signedp
= src0
== '-' || src0
== '+' || src0
== ' ';
4727 unsigned char after_sign
= src
[signedp
];
4728 if (zero_flag
&& 0 <= char_hexdigit (after_sign
))
4730 leading_zeros
+= padding
;
4734 if (excess_precision
4735 && (conversion
== 'e' || conversion
== 'g'))
4737 char *e
= strchr (src
, 'e');
4739 exponent_bytes
= src
+ sprintf_bytes
- e
;
4742 spec
->start
= nchars
;
4745 memset (p
, ' ', padding
);
4753 memset (p
, '0', leading_zeros
);
4755 int significand_bytes
4756 = sprintf_bytes
- signedp
- exponent_bytes
;
4757 memcpy (p
, src
, significand_bytes
);
4758 p
+= significand_bytes
;
4759 src
+= significand_bytes
;
4760 memset (p
, '0', trailing_zeros
);
4761 p
+= trailing_zeros
;
4762 memcpy (p
, src
, exponent_bytes
);
4763 p
+= exponent_bytes
;
4765 nchars
+= leading_zeros
+ sprintf_bytes
+ trailing_zeros
;
4769 memset (p
, ' ', padding
);
4782 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
4784 if ((format_char
== '`' || format_char
== '\'')
4785 && quoting_style
== CURVE_QUOTING_STYLE
)
4792 convsrc
= format_char
== '`' ? uLSQM
: uRSQM
;
4796 else if (format_char
== '`' && quoting_style
== STRAIGHT_QUOTING_STYLE
)
4803 /* Copy a single character from format to buf. */
4804 if (multibyte_format
)
4806 /* Copy a whole multibyte character. */
4808 && !ASCII_CHAR_P (*((unsigned char *) p
- 1))
4809 && !CHAR_HEAD_P (format_char
))
4810 maybe_combine_byte
= true;
4812 while (! CHAR_HEAD_P (*format
))
4815 convbytes
= format
- format0
;
4816 memset (&discarded
[format0
+ 1 - format_start
], 2,
4819 else if (multibyte
&& !ASCII_CHAR_P (format_char
))
4821 int c
= BYTE8_TO_CHAR (format_char
);
4822 convbytes
= CHAR_STRING (c
, str
);
4823 convsrc
= (char *) str
;
4829 if (convbytes
<= buf
+ bufsize
- p
)
4831 memcpy (p
, convsrc
, convbytes
);
4838 /* There wasn't enough room to store this conversion or single
4839 character. CONVBYTES says how much room is needed. Allocate
4840 enough room (and then some) and do it again. */
4842 ptrdiff_t used
= p
- buf
;
4843 if (max_bufsize
- used
< convbytes
)
4845 bufsize
= used
+ convbytes
;
4846 bufsize
= bufsize
< max_bufsize
/ 2 ? bufsize
* 2 : max_bufsize
;
4848 if (buf
== initial_buffer
)
4850 buf
= xmalloc (bufsize
);
4851 sa_must_free
= true;
4852 buf_save_value_index
= SPECPDL_INDEX ();
4853 record_unwind_protect_ptr (xfree
, buf
);
4854 memcpy (buf
, initial_buffer
, used
);
4858 buf
= xrealloc (buf
, bufsize
);
4859 set_unwind_protect_ptr (buf_save_value_index
, xfree
, buf
);
4868 if (bufsize
< p
- buf
)
4874 if (maybe_combine_byte
)
4875 nchars
= multibyte_chars_in_text ((unsigned char *) buf
, p
- buf
);
4876 Lisp_Object val
= make_specified_string (buf
, nchars
, p
- buf
, multibyte
);
4878 /* If the format string has text properties, or any of the string
4879 arguments has text properties, set up text properties of the
4882 if (string_intervals (args
[0]) || arg_intervals
)
4884 /* Add text properties from the format string. */
4885 Lisp_Object len
= make_number (SCHARS (args
[0]));
4886 Lisp_Object props
= text_property_list (args
[0], make_number (0),
4890 ptrdiff_t bytepos
= 0, position
= 0, translated
= 0;
4891 ptrdiff_t fieldn
= 0;
4893 /* Adjust the bounds of each text property
4894 to the proper start and end in the output string. */
4896 /* Put the positions in PROPS in increasing order, so that
4897 we can do (effectively) one scan through the position
4898 space of the format string. */
4899 props
= Fnreverse (props
);
4901 /* BYTEPOS is the byte position in the format string,
4902 POSITION is the untranslated char position in it,
4903 TRANSLATED is the translated char position in BUF,
4904 and ARGN is the number of the next arg we will come to. */
4905 for (Lisp_Object list
= props
; CONSP (list
); list
= XCDR (list
))
4907 Lisp_Object item
= XCAR (list
);
4909 /* First adjust the property start position. */
4910 ptrdiff_t pos
= XINT (XCAR (item
));
4912 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4913 up to this position. */
4914 for (; position
< pos
; bytepos
++)
4916 if (! discarded
[bytepos
])
4917 position
++, translated
++;
4918 else if (discarded
[bytepos
] == 1)
4921 if (translated
== info
[fieldn
].start
)
4923 translated
+= info
[fieldn
].end
- info
[fieldn
].start
;
4929 XSETCAR (item
, make_number (translated
));
4931 /* Likewise adjust the property end position. */
4932 pos
= XINT (XCAR (XCDR (item
)));
4934 for (; position
< pos
; bytepos
++)
4936 if (! discarded
[bytepos
])
4937 position
++, translated
++;
4938 else if (discarded
[bytepos
] == 1)
4941 if (translated
== info
[fieldn
].start
)
4943 translated
+= info
[fieldn
].end
- info
[fieldn
].start
;
4949 XSETCAR (XCDR (item
), make_number (translated
));
4952 add_text_properties_from_list (val
, props
, make_number (0));
4955 /* Add text properties from arguments. */
4957 for (ptrdiff_t i
= 0; i
< nspec
; i
++)
4958 if (info
[i
].intervals
)
4960 len
= make_number (SCHARS (info
[i
].argument
));
4961 Lisp_Object new_len
= make_number (info
[i
].end
- info
[i
].start
);
4962 props
= text_property_list (info
[i
].argument
,
4963 make_number (0), len
, Qnil
);
4964 props
= extend_property_ranges (props
, len
, new_len
);
4965 /* If successive arguments have properties, be sure that
4966 the value of `composition' property be the copy. */
4967 if (1 < i
&& info
[i
- 1].end
)
4968 make_composition_value_copy (props
);
4969 add_text_properties_from_list (val
, props
,
4970 make_number (info
[i
].start
));
4974 /* If we allocated BUF or INFO with malloc, free it too. */
4980 DEFUN ("char-equal", Fchar_equal
, Schar_equal
, 2, 2, 0,
4981 doc
: /* Return t if two characters match, optionally ignoring case.
4982 Both arguments must be characters (i.e. integers).
4983 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4984 (register Lisp_Object c1
, Lisp_Object c2
)
4987 /* Check they're chars, not just integers, otherwise we could get array
4988 bounds violations in downcase. */
4989 CHECK_CHARACTER (c1
);
4990 CHECK_CHARACTER (c2
);
4992 if (XINT (c1
) == XINT (c2
))
4994 if (NILP (BVAR (current_buffer
, case_fold_search
)))
5000 /* FIXME: It is possible to compare multibyte characters even when
5001 the current buffer is unibyte. Unfortunately this is ambiguous
5002 for characters between 128 and 255, as they could be either
5003 eight-bit raw bytes or Latin-1 characters. Assume the former for
5004 now. See Bug#17011, and also see casefiddle.c's casify_object,
5005 which has a similar problem. */
5006 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
5008 if (SINGLE_BYTE_CHAR_P (i1
))
5009 i1
= UNIBYTE_TO_CHAR (i1
);
5010 if (SINGLE_BYTE_CHAR_P (i2
))
5011 i2
= UNIBYTE_TO_CHAR (i2
);
5014 return (downcase (i1
) == downcase (i2
) ? Qt
: Qnil
);
5017 /* Transpose the markers in two regions of the current buffer, and
5018 adjust the ones between them if necessary (i.e.: if the regions
5021 START1, END1 are the character positions of the first region.
5022 START1_BYTE, END1_BYTE are the byte positions.
5023 START2, END2 are the character positions of the second region.
5024 START2_BYTE, END2_BYTE are the byte positions.
5026 Traverses the entire marker list of the buffer to do so, adding an
5027 appropriate amount to some, subtracting from some, and leaving the
5028 rest untouched. Most of this is copied from adjust_markers in insdel.c.
5030 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
5033 transpose_markers (ptrdiff_t start1
, ptrdiff_t end1
,
5034 ptrdiff_t start2
, ptrdiff_t end2
,
5035 ptrdiff_t start1_byte
, ptrdiff_t end1_byte
,
5036 ptrdiff_t start2_byte
, ptrdiff_t end2_byte
)
5038 register ptrdiff_t amt1
, amt1_byte
, amt2
, amt2_byte
, diff
, diff_byte
, mpos
;
5039 register struct Lisp_Marker
*marker
;
5041 /* Update point as if it were a marker. */
5045 TEMP_SET_PT_BOTH (PT
+ (end2
- end1
),
5046 PT_BYTE
+ (end2_byte
- end1_byte
));
5047 else if (PT
< start2
)
5048 TEMP_SET_PT_BOTH (PT
+ (end2
- start2
) - (end1
- start1
),
5049 (PT_BYTE
+ (end2_byte
- start2_byte
)
5050 - (end1_byte
- start1_byte
)));
5052 TEMP_SET_PT_BOTH (PT
- (start2
- start1
),
5053 PT_BYTE
- (start2_byte
- start1_byte
));
5055 /* We used to adjust the endpoints here to account for the gap, but that
5056 isn't good enough. Even if we assume the caller has tried to move the
5057 gap out of our way, it might still be at start1 exactly, for example;
5058 and that places it `inside' the interval, for our purposes. The amount
5059 of adjustment is nontrivial if there's a `denormalized' marker whose
5060 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
5061 the dirty work to Fmarker_position, below. */
5063 /* The difference between the region's lengths */
5064 diff
= (end2
- start2
) - (end1
- start1
);
5065 diff_byte
= (end2_byte
- start2_byte
) - (end1_byte
- start1_byte
);
5067 /* For shifting each marker in a region by the length of the other
5068 region plus the distance between the regions. */
5069 amt1
= (end2
- start2
) + (start2
- end1
);
5070 amt2
= (end1
- start1
) + (start2
- end1
);
5071 amt1_byte
= (end2_byte
- start2_byte
) + (start2_byte
- end1_byte
);
5072 amt2_byte
= (end1_byte
- start1_byte
) + (start2_byte
- end1_byte
);
5074 for (marker
= BUF_MARKERS (current_buffer
); marker
; marker
= marker
->next
)
5076 mpos
= marker
->bytepos
;
5077 if (mpos
>= start1_byte
&& mpos
< end2_byte
)
5079 if (mpos
< end1_byte
)
5081 else if (mpos
< start2_byte
)
5085 marker
->bytepos
= mpos
;
5087 mpos
= marker
->charpos
;
5088 if (mpos
>= start1
&& mpos
< end2
)
5092 else if (mpos
< start2
)
5097 marker
->charpos
= mpos
;
5101 DEFUN ("transpose-regions", Ftranspose_regions
, Stranspose_regions
, 4, 5, 0,
5102 doc
: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
5103 The regions should not be overlapping, because the size of the buffer is
5104 never changed in a transposition.
5106 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
5107 any markers that happen to be located in the regions.
5109 Transposing beyond buffer boundaries is an error. */)
5110 (Lisp_Object startr1
, Lisp_Object endr1
, Lisp_Object startr2
, Lisp_Object endr2
, Lisp_Object leave_markers
)
5112 register ptrdiff_t start1
, end1
, start2
, end2
;
5113 ptrdiff_t start1_byte
, start2_byte
, len1_byte
, len2_byte
, end2_byte
;
5114 ptrdiff_t gap
, len1
, len_mid
, len2
;
5115 unsigned char *start1_addr
, *start2_addr
, *temp
;
5117 INTERVAL cur_intv
, tmp_interval1
, tmp_interval_mid
, tmp_interval2
, tmp_interval3
;
5120 XSETBUFFER (buf
, current_buffer
);
5121 cur_intv
= buffer_intervals (current_buffer
);
5123 validate_region (&startr1
, &endr1
);
5124 validate_region (&startr2
, &endr2
);
5126 start1
= XFASTINT (startr1
);
5127 end1
= XFASTINT (endr1
);
5128 start2
= XFASTINT (startr2
);
5129 end2
= XFASTINT (endr2
);
5132 /* Swap the regions if they're reversed. */
5135 register ptrdiff_t glumph
= start1
;
5143 len1
= end1
- start1
;
5144 len2
= end2
- start2
;
5147 error ("Transposed regions overlap");
5148 /* Nothing to change for adjacent regions with one being empty */
5149 else if ((start1
== end1
|| start2
== end2
) && end1
== start2
)
5152 /* The possibilities are:
5153 1. Adjacent (contiguous) regions, or separate but equal regions
5154 (no, really equal, in this case!), or
5155 2. Separate regions of unequal size.
5157 The worst case is usually No. 2. It means that (aside from
5158 potential need for getting the gap out of the way), there also
5159 needs to be a shifting of the text between the two regions. So
5160 if they are spread far apart, we are that much slower... sigh. */
5162 /* It must be pointed out that the really studly thing to do would
5163 be not to move the gap at all, but to leave it in place and work
5164 around it if necessary. This would be extremely efficient,
5165 especially considering that people are likely to do
5166 transpositions near where they are working interactively, which
5167 is exactly where the gap would be found. However, such code
5168 would be much harder to write and to read. So, if you are
5169 reading this comment and are feeling squirrely, by all means have
5170 a go! I just didn't feel like doing it, so I will simply move
5171 the gap the minimum distance to get it out of the way, and then
5172 deal with an unbroken array. */
5174 start1_byte
= CHAR_TO_BYTE (start1
);
5175 end2_byte
= CHAR_TO_BYTE (end2
);
5177 /* Make sure the gap won't interfere, by moving it out of the text
5178 we will operate on. */
5179 if (start1
< gap
&& gap
< end2
)
5181 if (gap
- start1
< end2
- gap
)
5182 move_gap_both (start1
, start1_byte
);
5184 move_gap_both (end2
, end2_byte
);
5187 start2_byte
= CHAR_TO_BYTE (start2
);
5188 len1_byte
= CHAR_TO_BYTE (end1
) - start1_byte
;
5189 len2_byte
= end2_byte
- start2_byte
;
5191 #ifdef BYTE_COMBINING_DEBUG
5194 if (count_combining_before (BYTE_POS_ADDR (start2_byte
),
5195 len2_byte
, start1
, start1_byte
)
5196 || count_combining_before (BYTE_POS_ADDR (start1_byte
),
5197 len1_byte
, end2
, start2_byte
+ len2_byte
)
5198 || count_combining_after (BYTE_POS_ADDR (start1_byte
),
5199 len1_byte
, end2
, start2_byte
+ len2_byte
))
5204 if (count_combining_before (BYTE_POS_ADDR (start2_byte
),
5205 len2_byte
, start1
, start1_byte
)
5206 || count_combining_before (BYTE_POS_ADDR (start1_byte
),
5207 len1_byte
, start2
, start2_byte
)
5208 || count_combining_after (BYTE_POS_ADDR (start2_byte
),
5209 len2_byte
, end1
, start1_byte
+ len1_byte
)
5210 || count_combining_after (BYTE_POS_ADDR (start1_byte
),
5211 len1_byte
, end2
, start2_byte
+ len2_byte
))
5216 /* Hmmm... how about checking to see if the gap is large
5217 enough to use as the temporary storage? That would avoid an
5218 allocation... interesting. Later, don't fool with it now. */
5220 /* Working without memmove, for portability (sigh), so must be
5221 careful of overlapping subsections of the array... */
5223 if (end1
== start2
) /* adjacent regions */
5225 modify_text (start1
, end2
);
5226 record_change (start1
, len1
+ len2
);
5228 tmp_interval1
= copy_intervals (cur_intv
, start1
, len1
);
5229 tmp_interval2
= copy_intervals (cur_intv
, start2
, len2
);
5230 /* Don't use Fset_text_properties: that can cause GC, which can
5231 clobber objects stored in the tmp_intervals. */
5232 tmp_interval3
= validate_interval_range (buf
, &startr1
, &endr2
, 0);
5234 set_text_properties_1 (startr1
, endr2
, Qnil
, buf
, tmp_interval3
);
5238 /* First region smaller than second. */
5239 if (len1_byte
< len2_byte
)
5241 temp
= SAFE_ALLOCA (len2_byte
);
5243 /* Don't precompute these addresses. We have to compute them
5244 at the last minute, because the relocating allocator might
5245 have moved the buffer around during the xmalloc. */
5246 start1_addr
= BYTE_POS_ADDR (start1_byte
);
5247 start2_addr
= BYTE_POS_ADDR (start2_byte
);
5249 memcpy (temp
, start2_addr
, len2_byte
);
5250 memcpy (start1_addr
+ len2_byte
, start1_addr
, len1_byte
);
5251 memcpy (start1_addr
, temp
, len2_byte
);
5254 /* First region not smaller than second. */
5256 temp
= SAFE_ALLOCA (len1_byte
);
5257 start1_addr
= BYTE_POS_ADDR (start1_byte
);
5258 start2_addr
= BYTE_POS_ADDR (start2_byte
);
5259 memcpy (temp
, start1_addr
, len1_byte
);
5260 memcpy (start1_addr
, start2_addr
, len2_byte
);
5261 memcpy (start1_addr
+ len2_byte
, temp
, len1_byte
);
5265 graft_intervals_into_buffer (tmp_interval1
, start1
+ len2
,
5266 len1
, current_buffer
, 0);
5267 graft_intervals_into_buffer (tmp_interval2
, start1
,
5268 len2
, current_buffer
, 0);
5269 update_compositions (start1
, start1
+ len2
, CHECK_BORDER
);
5270 update_compositions (start1
+ len2
, end2
, CHECK_TAIL
);
5272 /* Non-adjacent regions, because end1 != start2, bleagh... */
5275 len_mid
= start2_byte
- (start1_byte
+ len1_byte
);
5277 if (len1_byte
== len2_byte
)
5278 /* Regions are same size, though, how nice. */
5282 modify_text (start1
, end1
);
5283 modify_text (start2
, end2
);
5284 record_change (start1
, len1
);
5285 record_change (start2
, len2
);
5286 tmp_interval1
= copy_intervals (cur_intv
, start1
, len1
);
5287 tmp_interval2
= copy_intervals (cur_intv
, start2
, len2
);
5289 tmp_interval3
= validate_interval_range (buf
, &startr1
, &endr1
, 0);
5291 set_text_properties_1 (startr1
, endr1
, Qnil
, buf
, tmp_interval3
);
5293 tmp_interval3
= validate_interval_range (buf
, &startr2
, &endr2
, 0);
5295 set_text_properties_1 (startr2
, endr2
, Qnil
, buf
, tmp_interval3
);
5297 temp
= SAFE_ALLOCA (len1_byte
);
5298 start1_addr
= BYTE_POS_ADDR (start1_byte
);
5299 start2_addr
= BYTE_POS_ADDR (start2_byte
);
5300 memcpy (temp
, start1_addr
, len1_byte
);
5301 memcpy (start1_addr
, start2_addr
, len2_byte
);
5302 memcpy (start2_addr
, temp
, len1_byte
);
5305 graft_intervals_into_buffer (tmp_interval1
, start2
,
5306 len1
, current_buffer
, 0);
5307 graft_intervals_into_buffer (tmp_interval2
, start1
,
5308 len2
, current_buffer
, 0);
5311 else if (len1_byte
< len2_byte
) /* Second region larger than first */
5312 /* Non-adjacent & unequal size, area between must also be shifted. */
5316 modify_text (start1
, end2
);
5317 record_change (start1
, (end2
- start1
));
5318 tmp_interval1
= copy_intervals (cur_intv
, start1
, len1
);
5319 tmp_interval_mid
= copy_intervals (cur_intv
, end1
, len_mid
);
5320 tmp_interval2
= copy_intervals (cur_intv
, start2
, len2
);
5322 tmp_interval3
= validate_interval_range (buf
, &startr1
, &endr2
, 0);
5324 set_text_properties_1 (startr1
, endr2
, Qnil
, buf
, tmp_interval3
);
5326 /* holds region 2 */
5327 temp
= SAFE_ALLOCA (len2_byte
);
5328 start1_addr
= BYTE_POS_ADDR (start1_byte
);
5329 start2_addr
= BYTE_POS_ADDR (start2_byte
);
5330 memcpy (temp
, start2_addr
, len2_byte
);
5331 memcpy (start1_addr
+ len_mid
+ len2_byte
, start1_addr
, len1_byte
);
5332 memmove (start1_addr
+ len2_byte
, start1_addr
+ len1_byte
, len_mid
);
5333 memcpy (start1_addr
, temp
, len2_byte
);
5336 graft_intervals_into_buffer (tmp_interval1
, end2
- len1
,
5337 len1
, current_buffer
, 0);
5338 graft_intervals_into_buffer (tmp_interval_mid
, start1
+ len2
,
5339 len_mid
, current_buffer
, 0);
5340 graft_intervals_into_buffer (tmp_interval2
, start1
,
5341 len2
, current_buffer
, 0);
5344 /* Second region smaller than first. */
5348 record_change (start1
, (end2
- start1
));
5349 modify_text (start1
, end2
);
5351 tmp_interval1
= copy_intervals (cur_intv
, start1
, len1
);
5352 tmp_interval_mid
= copy_intervals (cur_intv
, end1
, len_mid
);
5353 tmp_interval2
= copy_intervals (cur_intv
, start2
, len2
);
5355 tmp_interval3
= validate_interval_range (buf
, &startr1
, &endr2
, 0);
5357 set_text_properties_1 (startr1
, endr2
, Qnil
, buf
, tmp_interval3
);
5359 /* holds region 1 */
5360 temp
= SAFE_ALLOCA (len1_byte
);
5361 start1_addr
= BYTE_POS_ADDR (start1_byte
);
5362 start2_addr
= BYTE_POS_ADDR (start2_byte
);
5363 memcpy (temp
, start1_addr
, len1_byte
);
5364 memcpy (start1_addr
, start2_addr
, len2_byte
);
5365 memmove (start1_addr
+ len2_byte
, start1_addr
+ len1_byte
, len_mid
);
5366 memcpy (start1_addr
+ len2_byte
+ len_mid
, temp
, len1_byte
);
5369 graft_intervals_into_buffer (tmp_interval1
, end2
- len1
,
5370 len1
, current_buffer
, 0);
5371 graft_intervals_into_buffer (tmp_interval_mid
, start1
+ len2
,
5372 len_mid
, current_buffer
, 0);
5373 graft_intervals_into_buffer (tmp_interval2
, start1
,
5374 len2
, current_buffer
, 0);
5377 update_compositions (start1
, start1
+ len2
, CHECK_BORDER
);
5378 update_compositions (end2
- len1
, end2
, CHECK_BORDER
);
5381 /* When doing multiple transpositions, it might be nice
5382 to optimize this. Perhaps the markers in any one buffer
5383 should be organized in some sorted data tree. */
5384 if (NILP (leave_markers
))
5386 transpose_markers (start1
, end1
, start2
, end2
,
5387 start1_byte
, start1_byte
+ len1_byte
,
5388 start2_byte
, start2_byte
+ len2_byte
);
5389 fix_start_end_in_overlays (start1
, end2
);
5393 /* The character positions of the markers remain intact, but we
5394 still need to update their byte positions, because the
5395 transposed regions might include multibyte sequences which
5396 make some original byte positions of the markers invalid. */
5397 adjust_markers_bytepos (start1
, start1_byte
, end2
, end2_byte
, 0);
5400 signal_after_change (start1
, end2
- start1
, end2
- start1
);
5406 syms_of_editfns (void)
5408 DEFSYM (Qbuffer_access_fontify_functions
, "buffer-access-fontify-functions");
5409 DEFSYM (Qwall
, "wall");
5411 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion
,
5412 doc
: /* Non-nil means text motion commands don't notice fields. */);
5413 Vinhibit_field_text_motion
= Qnil
;
5415 DEFVAR_LISP ("buffer-access-fontify-functions",
5416 Vbuffer_access_fontify_functions
,
5417 doc
: /* List of functions called by `buffer-substring' to fontify if necessary.
5418 Each function is called with two arguments which specify the range
5419 of the buffer being accessed. */);
5420 Vbuffer_access_fontify_functions
= Qnil
;
5424 obuf
= Fcurrent_buffer ();
5425 /* Do this here, because init_buffer_once is too early--it won't work. */
5426 Fset_buffer (Vprin1_to_string_buffer
);
5427 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
5428 Fset (Fmake_local_variable (Qbuffer_access_fontify_functions
), Qnil
);
5432 DEFVAR_LISP ("buffer-access-fontified-property",
5433 Vbuffer_access_fontified_property
,
5434 doc
: /* Property which (if non-nil) indicates text has been fontified.
5435 `buffer-substring' need not call the `buffer-access-fontify-functions'
5436 functions if all the text being accessed has this property. */);
5437 Vbuffer_access_fontified_property
= Qnil
;
5439 DEFVAR_LISP ("system-name", Vsystem_name
,
5440 doc
: /* The host name of the machine Emacs is running on. */);
5441 Vsystem_name
= cached_system_name
= Qnil
;
5443 DEFVAR_LISP ("user-full-name", Vuser_full_name
,
5444 doc
: /* The full name of the user logged in. */);
5446 DEFVAR_LISP ("user-login-name", Vuser_login_name
,
5447 doc
: /* The user's name, taken from environment variables if possible. */);
5448 Vuser_login_name
= Qnil
;
5450 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name
,
5451 doc
: /* The user's name, based upon the real uid only. */);
5453 DEFVAR_LISP ("operating-system-release", Voperating_system_release
,
5454 doc
: /* The release of the operating system Emacs is running on. */);
5456 defsubr (&Spropertize
);
5457 defsubr (&Schar_equal
);
5458 defsubr (&Sgoto_char
);
5459 defsubr (&Sstring_to_char
);
5460 defsubr (&Schar_to_string
);
5461 defsubr (&Sbyte_to_string
);
5462 defsubr (&Sbuffer_substring
);
5463 defsubr (&Sbuffer_substring_no_properties
);
5464 defsubr (&Sbuffer_string
);
5465 defsubr (&Sget_pos_property
);
5467 defsubr (&Spoint_marker
);
5468 defsubr (&Smark_marker
);
5470 defsubr (&Sregion_beginning
);
5471 defsubr (&Sregion_end
);
5473 /* Symbol for the text property used to mark fields. */
5474 DEFSYM (Qfield
, "field");
5476 /* A special value for Qfield properties. */
5477 DEFSYM (Qboundary
, "boundary");
5479 defsubr (&Sfield_beginning
);
5480 defsubr (&Sfield_end
);
5481 defsubr (&Sfield_string
);
5482 defsubr (&Sfield_string_no_properties
);
5483 defsubr (&Sdelete_field
);
5484 defsubr (&Sconstrain_to_field
);
5486 defsubr (&Sline_beginning_position
);
5487 defsubr (&Sline_end_position
);
5489 defsubr (&Ssave_excursion
);
5490 defsubr (&Ssave_current_buffer
);
5492 defsubr (&Sbuffer_size
);
5493 defsubr (&Spoint_max
);
5494 defsubr (&Spoint_min
);
5495 defsubr (&Spoint_min_marker
);
5496 defsubr (&Spoint_max_marker
);
5497 defsubr (&Sgap_position
);
5498 defsubr (&Sgap_size
);
5499 defsubr (&Sposition_bytes
);
5500 defsubr (&Sbyte_to_position
);
5506 defsubr (&Sfollowing_char
);
5507 defsubr (&Sprevious_char
);
5508 defsubr (&Schar_after
);
5509 defsubr (&Schar_before
);
5511 defsubr (&Sinsert_before_markers
);
5512 defsubr (&Sinsert_and_inherit
);
5513 defsubr (&Sinsert_and_inherit_before_markers
);
5514 defsubr (&Sinsert_char
);
5515 defsubr (&Sinsert_byte
);
5517 defsubr (&Suser_login_name
);
5518 defsubr (&Suser_real_login_name
);
5519 defsubr (&Suser_uid
);
5520 defsubr (&Suser_real_uid
);
5521 defsubr (&Sgroup_gid
);
5522 defsubr (&Sgroup_real_gid
);
5523 defsubr (&Suser_full_name
);
5524 defsubr (&Semacs_pid
);
5525 defsubr (&Scurrent_time
);
5526 defsubr (&Stime_add
);
5527 defsubr (&Stime_subtract
);
5528 defsubr (&Stime_less_p
);
5529 defsubr (&Sget_internal_run_time
);
5530 defsubr (&Sformat_time_string
);
5531 defsubr (&Sfloat_time
);
5532 defsubr (&Sdecode_time
);
5533 defsubr (&Sencode_time
);
5534 defsubr (&Scurrent_time_string
);
5535 defsubr (&Scurrent_time_zone
);
5536 defsubr (&Sset_time_zone_rule
);
5537 defsubr (&Ssystem_name
);
5538 defsubr (&Smessage
);
5539 defsubr (&Smessage_box
);
5540 defsubr (&Smessage_or_box
);
5541 defsubr (&Scurrent_message
);
5543 defsubr (&Sformat_message
);
5545 defsubr (&Sinsert_buffer_substring
);
5546 defsubr (&Scompare_buffer_substrings
);
5547 defsubr (&Sreplace_buffer_contents
);
5548 defsubr (&Ssubst_char_in_region
);
5549 defsubr (&Stranslate_region_internal
);
5550 defsubr (&Sdelete_region
);
5551 defsubr (&Sdelete_and_extract_region
);
5553 defsubr (&Snarrow_to_region
);
5554 defsubr (&Ssave_restriction
);
5555 defsubr (&Stranspose_regions
);