More xmalloc and related cleanup.
[emacs/old-mirror.git] / src / editfns.c
blobd4146cefb92d998248412a80d4da43263fd0526c
1 /* Lisp functions pertaining to editing.
3 Copyright (C) 1985-1987, 1989, 1993-2012 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
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
22 #include <sys/types.h>
23 #include <stdio.h>
24 #include <setjmp.h>
26 #ifdef HAVE_PWD_H
27 #include <pwd.h>
28 #endif
30 #include <unistd.h>
32 #ifdef HAVE_SYS_UTSNAME_H
33 #include <sys/utsname.h>
34 #endif
36 #include "lisp.h"
38 /* systime.h includes <sys/time.h> which, on some systems, is required
39 for <sys/resource.h>; thus systime.h must be included before
40 <sys/resource.h> */
41 #include "systime.h"
43 #if defined HAVE_SYS_RESOURCE_H
44 #include <sys/resource.h>
45 #endif
47 #include <ctype.h>
48 #include <float.h>
49 #include <limits.h>
50 #include <intprops.h>
51 #include <strftime.h>
52 #include <verify.h>
54 #include "intervals.h"
55 #include "character.h"
56 #include "buffer.h"
57 #include "coding.h"
58 #include "frame.h"
59 #include "window.h"
60 #include "blockinput.h"
62 #ifndef USER_FULL_NAME
63 #define USER_FULL_NAME pw->pw_gecos
64 #endif
66 #ifndef USE_CRT_DLL
67 extern char **environ;
68 #endif
70 #define TM_YEAR_BASE 1900
72 #ifdef WINDOWSNT
73 extern Lisp_Object w32_get_internal_run_time (void);
74 #endif
76 static Lisp_Object format_time_string (char const *, ptrdiff_t, EMACS_TIME,
77 int, struct tm *);
78 static int tm_diff (struct tm *, struct tm *);
79 static void update_buffer_properties (ptrdiff_t, ptrdiff_t);
81 static Lisp_Object Qbuffer_access_fontify_functions;
83 /* Symbol for the text property used to mark fields. */
85 Lisp_Object Qfield;
87 /* A special value for Qfield properties. */
89 static Lisp_Object Qboundary;
92 void
93 init_editfns (void)
95 const char *user_name;
96 register char *p;
97 struct passwd *pw; /* password entry for the current user */
98 Lisp_Object tem;
100 /* Set up system_name even when dumping. */
101 init_system_name ();
103 #ifndef CANNOT_DUMP
104 /* Don't bother with this on initial start when just dumping out */
105 if (!initialized)
106 return;
107 #endif /* not CANNOT_DUMP */
109 pw = getpwuid (getuid ());
110 #ifdef MSDOS
111 /* We let the real user name default to "root" because that's quite
112 accurate on MSDOG and because it lets Emacs find the init file.
113 (The DVX libraries override the Djgpp libraries here.) */
114 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
115 #else
116 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
117 #endif
119 /* Get the effective user name, by consulting environment variables,
120 or the effective uid if those are unset. */
121 user_name = getenv ("LOGNAME");
122 if (!user_name)
123 #ifdef WINDOWSNT
124 user_name = getenv ("USERNAME"); /* it's USERNAME on NT */
125 #else /* WINDOWSNT */
126 user_name = getenv ("USER");
127 #endif /* WINDOWSNT */
128 if (!user_name)
130 pw = getpwuid (geteuid ());
131 user_name = pw ? pw->pw_name : "unknown";
133 Vuser_login_name = build_string (user_name);
135 /* If the user name claimed in the environment vars differs from
136 the real uid, use the claimed name to find the full name. */
137 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
138 if (! NILP (tem))
139 tem = Vuser_login_name;
140 else
142 uid_t euid = geteuid ();
143 tem = make_fixnum_or_float (euid);
145 Vuser_full_name = Fuser_full_name (tem);
147 p = getenv ("NAME");
148 if (p)
149 Vuser_full_name = build_string (p);
150 else if (NILP (Vuser_full_name))
151 Vuser_full_name = build_string ("unknown");
153 #ifdef HAVE_SYS_UTSNAME_H
155 struct utsname uts;
156 uname (&uts);
157 Voperating_system_release = build_string (uts.release);
159 #else
160 Voperating_system_release = Qnil;
161 #endif
164 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
165 doc: /* Convert arg CHAR to a string containing that character.
166 usage: (char-to-string CHAR) */)
167 (Lisp_Object character)
169 int c, len;
170 unsigned char str[MAX_MULTIBYTE_LENGTH];
172 CHECK_CHARACTER (character);
173 c = XFASTINT (character);
175 len = CHAR_STRING (c, str);
176 return make_string_from_bytes ((char *) str, 1, len);
179 DEFUN ("byte-to-string", Fbyte_to_string, Sbyte_to_string, 1, 1, 0,
180 doc: /* Convert arg BYTE to a unibyte string containing that byte. */)
181 (Lisp_Object byte)
183 unsigned char b;
184 CHECK_NUMBER (byte);
185 if (XINT (byte) < 0 || XINT (byte) > 255)
186 error ("Invalid byte");
187 b = XINT (byte);
188 return make_string_from_bytes ((char *) &b, 1, 1);
191 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
192 doc: /* Return the first character in STRING. */)
193 (register Lisp_Object string)
195 register Lisp_Object val;
196 CHECK_STRING (string);
197 if (SCHARS (string))
199 if (STRING_MULTIBYTE (string))
200 XSETFASTINT (val, STRING_CHAR (SDATA (string)));
201 else
202 XSETFASTINT (val, SREF (string, 0));
204 else
205 XSETFASTINT (val, 0);
206 return val;
209 static Lisp_Object
210 buildmark (ptrdiff_t charpos, ptrdiff_t bytepos)
212 register Lisp_Object mark;
213 mark = Fmake_marker ();
214 set_marker_both (mark, Qnil, charpos, bytepos);
215 return mark;
218 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
219 doc: /* Return value of point, as an integer.
220 Beginning of buffer is position (point-min). */)
221 (void)
223 Lisp_Object temp;
224 XSETFASTINT (temp, PT);
225 return temp;
228 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
229 doc: /* Return value of point, as a marker object. */)
230 (void)
232 return buildmark (PT, PT_BYTE);
235 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
236 doc: /* Set point to POSITION, a number or marker.
237 Beginning of buffer is position (point-min), end is (point-max).
239 The return value is POSITION. */)
240 (register Lisp_Object position)
242 ptrdiff_t pos;
244 if (MARKERP (position)
245 && current_buffer == XMARKER (position)->buffer)
247 pos = marker_position (position);
248 if (pos < BEGV)
249 SET_PT_BOTH (BEGV, BEGV_BYTE);
250 else if (pos > ZV)
251 SET_PT_BOTH (ZV, ZV_BYTE);
252 else
253 SET_PT_BOTH (pos, marker_byte_position (position));
255 return position;
258 CHECK_NUMBER_COERCE_MARKER (position);
260 pos = clip_to_bounds (BEGV, XINT (position), ZV);
261 SET_PT (pos);
262 return position;
266 /* Return the start or end position of the region.
267 BEGINNINGP non-zero means return the start.
268 If there is no region active, signal an error. */
270 static Lisp_Object
271 region_limit (int beginningp)
273 Lisp_Object m;
275 if (!NILP (Vtransient_mark_mode)
276 && NILP (Vmark_even_if_inactive)
277 && NILP (BVAR (current_buffer, mark_active)))
278 xsignal0 (Qmark_inactive);
280 m = Fmarker_position (BVAR (current_buffer, mark));
281 if (NILP (m))
282 error ("The mark is not set now, so there is no region");
284 /* Clip to the current narrowing (bug#11770). */
285 return make_number ((PT < XFASTINT (m)) == (beginningp != 0)
286 ? PT
287 : clip_to_bounds (BEGV, XFASTINT (m), ZV));
290 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
291 doc: /* Return the integer value of point or mark, whichever is smaller. */)
292 (void)
294 return region_limit (1);
297 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
298 doc: /* Return the integer value of point or mark, whichever is larger. */)
299 (void)
301 return region_limit (0);
304 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
305 doc: /* Return this buffer's mark, as a marker object.
306 Watch out! Moving this marker changes the mark position.
307 If you set the marker not to point anywhere, the buffer will have no mark. */)
308 (void)
310 return BVAR (current_buffer, mark);
314 /* Find all the overlays in the current buffer that touch position POS.
315 Return the number found, and store them in a vector in VEC
316 of length LEN. */
318 static ptrdiff_t
319 overlays_around (EMACS_INT pos, Lisp_Object *vec, ptrdiff_t len)
321 Lisp_Object overlay, start, end;
322 struct Lisp_Overlay *tail;
323 ptrdiff_t startpos, endpos;
324 ptrdiff_t idx = 0;
326 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
328 XSETMISC (overlay, tail);
330 end = OVERLAY_END (overlay);
331 endpos = OVERLAY_POSITION (end);
332 if (endpos < pos)
333 break;
334 start = OVERLAY_START (overlay);
335 startpos = OVERLAY_POSITION (start);
336 if (startpos <= pos)
338 if (idx < len)
339 vec[idx] = overlay;
340 /* Keep counting overlays even if we can't return them all. */
341 idx++;
345 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
347 XSETMISC (overlay, tail);
349 start = OVERLAY_START (overlay);
350 startpos = OVERLAY_POSITION (start);
351 if (pos < startpos)
352 break;
353 end = OVERLAY_END (overlay);
354 endpos = OVERLAY_POSITION (end);
355 if (pos <= endpos)
357 if (idx < len)
358 vec[idx] = overlay;
359 idx++;
363 return idx;
366 /* Return the value of property PROP, in OBJECT at POSITION.
367 It's the value of PROP that a char inserted at POSITION would get.
368 OBJECT is optional and defaults to the current buffer.
369 If OBJECT is a buffer, then overlay properties are considered as well as
370 text properties.
371 If OBJECT is a window, then that window's buffer is used, but
372 window-specific overlays are considered only if they are associated
373 with OBJECT. */
374 Lisp_Object
375 get_pos_property (Lisp_Object position, register Lisp_Object prop, Lisp_Object object)
377 CHECK_NUMBER_COERCE_MARKER (position);
379 if (NILP (object))
380 XSETBUFFER (object, current_buffer);
381 else if (WINDOWP (object))
382 object = XWINDOW (object)->buffer;
384 if (!BUFFERP (object))
385 /* pos-property only makes sense in buffers right now, since strings
386 have no overlays and no notion of insertion for which stickiness
387 could be obeyed. */
388 return Fget_text_property (position, prop, object);
389 else
391 EMACS_INT posn = XINT (position);
392 ptrdiff_t noverlays;
393 Lisp_Object *overlay_vec, tem;
394 struct buffer *obuf = current_buffer;
396 set_buffer_temp (XBUFFER (object));
398 /* First try with room for 40 overlays. */
399 noverlays = 40;
400 overlay_vec = alloca (noverlays * sizeof *overlay_vec);
401 noverlays = overlays_around (posn, overlay_vec, noverlays);
403 /* If there are more than 40,
404 make enough space for all, and try again. */
405 if (noverlays > 40)
407 overlay_vec = alloca (noverlays * sizeof *overlay_vec);
408 noverlays = overlays_around (posn, overlay_vec, noverlays);
410 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
412 set_buffer_temp (obuf);
414 /* Now check the overlays in order of decreasing priority. */
415 while (--noverlays >= 0)
417 Lisp_Object ol = overlay_vec[noverlays];
418 tem = Foverlay_get (ol, prop);
419 if (!NILP (tem))
421 /* Check the overlay is indeed active at point. */
422 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
423 if ((OVERLAY_POSITION (start) == posn
424 && XMARKER (start)->insertion_type == 1)
425 || (OVERLAY_POSITION (finish) == posn
426 && XMARKER (finish)->insertion_type == 0))
427 ; /* The overlay will not cover a char inserted at point. */
428 else
430 return tem;
435 { /* Now check the text properties. */
436 int stickiness = text_property_stickiness (prop, position, object);
437 if (stickiness > 0)
438 return Fget_text_property (position, prop, object);
439 else if (stickiness < 0
440 && XINT (position) > BUF_BEGV (XBUFFER (object)))
441 return Fget_text_property (make_number (XINT (position) - 1),
442 prop, object);
443 else
444 return Qnil;
449 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
450 the value of point is used instead. If BEG or END is null,
451 means don't store the beginning or end of the field.
453 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
454 results; they do not effect boundary behavior.
456 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
457 position of a field, then the beginning of the previous field is
458 returned instead of the beginning of POS's field (since the end of a
459 field is actually also the beginning of the next input field, this
460 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
461 true case, if two fields are separated by a field with the special
462 value `boundary', and POS lies within it, then the two separated
463 fields are considered to be adjacent, and POS between them, when
464 finding the beginning and ending of the "merged" field.
466 Either BEG or END may be 0, in which case the corresponding value
467 is not stored. */
469 static void
470 find_field (Lisp_Object pos, Lisp_Object merge_at_boundary,
471 Lisp_Object beg_limit,
472 ptrdiff_t *beg, Lisp_Object end_limit, ptrdiff_t *end)
474 /* Fields right before and after the point. */
475 Lisp_Object before_field, after_field;
476 /* 1 if POS counts as the start of a field. */
477 int at_field_start = 0;
478 /* 1 if POS counts as the end of a field. */
479 int at_field_end = 0;
481 if (NILP (pos))
482 XSETFASTINT (pos, PT);
483 else
484 CHECK_NUMBER_COERCE_MARKER (pos);
486 after_field
487 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
488 before_field
489 = (XFASTINT (pos) > BEGV
490 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
491 Qfield, Qnil, NULL)
492 /* Using nil here would be a more obvious choice, but it would
493 fail when the buffer starts with a non-sticky field. */
494 : after_field);
496 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
497 and POS is at beginning of a field, which can also be interpreted
498 as the end of the previous field. Note that the case where if
499 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
500 more natural one; then we avoid treating the beginning of a field
501 specially. */
502 if (NILP (merge_at_boundary))
504 Lisp_Object field = get_pos_property (pos, Qfield, Qnil);
505 if (!EQ (field, after_field))
506 at_field_end = 1;
507 if (!EQ (field, before_field))
508 at_field_start = 1;
509 if (NILP (field) && at_field_start && at_field_end)
510 /* If an inserted char would have a nil field while the surrounding
511 text is non-nil, we're probably not looking at a
512 zero-length field, but instead at a non-nil field that's
513 not intended for editing (such as comint's prompts). */
514 at_field_end = at_field_start = 0;
517 /* Note about special `boundary' fields:
519 Consider the case where the point (`.') is between the fields `x' and `y':
521 xxxx.yyyy
523 In this situation, if merge_at_boundary is true, we consider the
524 `x' and `y' fields as forming one big merged field, and so the end
525 of the field is the end of `y'.
527 However, if `x' and `y' are separated by a special `boundary' field
528 (a field with a `field' char-property of 'boundary), then we ignore
529 this special field when merging adjacent fields. Here's the same
530 situation, but with a `boundary' field between the `x' and `y' fields:
532 xxx.BBBByyyy
534 Here, if point is at the end of `x', the beginning of `y', or
535 anywhere in-between (within the `boundary' field), we merge all
536 three fields and consider the beginning as being the beginning of
537 the `x' field, and the end as being the end of the `y' field. */
539 if (beg)
541 if (at_field_start)
542 /* POS is at the edge of a field, and we should consider it as
543 the beginning of the following field. */
544 *beg = XFASTINT (pos);
545 else
546 /* Find the previous field boundary. */
548 Lisp_Object p = pos;
549 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
550 /* Skip a `boundary' field. */
551 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
552 beg_limit);
554 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
555 beg_limit);
556 *beg = NILP (p) ? BEGV : XFASTINT (p);
560 if (end)
562 if (at_field_end)
563 /* POS is at the edge of a field, and we should consider it as
564 the end of the previous field. */
565 *end = XFASTINT (pos);
566 else
567 /* Find the next field boundary. */
569 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
570 /* Skip a `boundary' field. */
571 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
572 end_limit);
574 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
575 end_limit);
576 *end = NILP (pos) ? ZV : XFASTINT (pos);
582 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
583 doc: /* Delete the field surrounding POS.
584 A field is a region of text with the same `field' property.
585 If POS is nil, the value of point is used for POS. */)
586 (Lisp_Object pos)
588 ptrdiff_t beg, end;
589 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
590 if (beg != end)
591 del_range (beg, end);
592 return Qnil;
595 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
596 doc: /* Return the contents of the field surrounding POS as a string.
597 A field is a region of text with the same `field' property.
598 If POS is nil, the value of point is used for POS. */)
599 (Lisp_Object pos)
601 ptrdiff_t beg, end;
602 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
603 return make_buffer_string (beg, end, 1);
606 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
607 doc: /* Return the contents of the field around POS, without text properties.
608 A field is a region of text with the same `field' property.
609 If POS is nil, the value of point is used for POS. */)
610 (Lisp_Object pos)
612 ptrdiff_t beg, end;
613 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
614 return make_buffer_string (beg, end, 0);
617 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
618 doc: /* Return the beginning of the field surrounding POS.
619 A field is a region of text with the same `field' property.
620 If POS is nil, the value of point is used for POS.
621 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
622 field, then the beginning of the *previous* field is returned.
623 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
624 is before LIMIT, then LIMIT will be returned instead. */)
625 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
627 ptrdiff_t beg;
628 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
629 return make_number (beg);
632 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
633 doc: /* Return the end of the field surrounding POS.
634 A field is a region of text with the same `field' property.
635 If POS is nil, the value of point is used for POS.
636 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
637 then the end of the *following* field is returned.
638 If LIMIT is non-nil, it is a buffer position; if the end of the field
639 is after LIMIT, then LIMIT will be returned instead. */)
640 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
642 ptrdiff_t end;
643 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
644 return make_number (end);
647 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
648 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
649 A field is a region of text with the same `field' property.
651 If NEW-POS is nil, then use the current point instead, and move point
652 to the resulting constrained position, in addition to returning that
653 position.
655 If OLD-POS is at the boundary of two fields, then the allowable
656 positions for NEW-POS depends on the value of the optional argument
657 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
658 constrained to the field that has the same `field' char-property
659 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
660 is non-nil, NEW-POS is constrained to the union of the two adjacent
661 fields. Additionally, if two fields are separated by another field with
662 the special value `boundary', then any point within this special field is
663 also considered to be `on the boundary'.
665 If the optional argument ONLY-IN-LINE is non-nil and constraining
666 NEW-POS would move it to a different line, NEW-POS is returned
667 unconstrained. This useful for commands that move by line, like
668 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
669 only in the case where they can still move to the right line.
671 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
672 a non-nil property of that name, then any field boundaries are ignored.
674 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
675 (Lisp_Object new_pos, Lisp_Object old_pos, Lisp_Object escape_from_edge, Lisp_Object only_in_line, Lisp_Object inhibit_capture_property)
677 /* If non-zero, then the original point, before re-positioning. */
678 ptrdiff_t orig_point = 0;
679 int fwd;
680 Lisp_Object prev_old, prev_new;
682 if (NILP (new_pos))
683 /* Use the current point, and afterwards, set it. */
685 orig_point = PT;
686 XSETFASTINT (new_pos, PT);
689 CHECK_NUMBER_COERCE_MARKER (new_pos);
690 CHECK_NUMBER_COERCE_MARKER (old_pos);
692 fwd = (XINT (new_pos) > XINT (old_pos));
694 prev_old = make_number (XINT (old_pos) - 1);
695 prev_new = make_number (XINT (new_pos) - 1);
697 if (NILP (Vinhibit_field_text_motion)
698 && !EQ (new_pos, old_pos)
699 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
700 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
701 /* To recognize field boundaries, we must also look at the
702 previous positions; we could use `get_pos_property'
703 instead, but in itself that would fail inside non-sticky
704 fields (like comint prompts). */
705 || (XFASTINT (new_pos) > BEGV
706 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
707 || (XFASTINT (old_pos) > BEGV
708 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
709 && (NILP (inhibit_capture_property)
710 /* Field boundaries are again a problem; but now we must
711 decide the case exactly, so we need to call
712 `get_pos_property' as well. */
713 || (NILP (get_pos_property (old_pos, inhibit_capture_property, Qnil))
714 && (XFASTINT (old_pos) <= BEGV
715 || NILP (Fget_char_property (old_pos, inhibit_capture_property, Qnil))
716 || NILP (Fget_char_property (prev_old, inhibit_capture_property, Qnil))))))
717 /* It is possible that NEW_POS is not within the same field as
718 OLD_POS; try to move NEW_POS so that it is. */
720 ptrdiff_t shortage;
721 Lisp_Object field_bound;
723 if (fwd)
724 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
725 else
726 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
728 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
729 other side of NEW_POS, which would mean that NEW_POS is
730 already acceptable, and it's not necessary to constrain it
731 to FIELD_BOUND. */
732 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
733 /* NEW_POS should be constrained, but only if either
734 ONLY_IN_LINE is nil (in which case any constraint is OK),
735 or NEW_POS and FIELD_BOUND are on the same line (in which
736 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
737 && (NILP (only_in_line)
738 /* This is the ONLY_IN_LINE case, check that NEW_POS and
739 FIELD_BOUND are on the same line by seeing whether
740 there's an intervening newline or not. */
741 || (scan_buffer ('\n',
742 XFASTINT (new_pos), XFASTINT (field_bound),
743 fwd ? -1 : 1, &shortage, 1),
744 shortage != 0)))
745 /* Constrain NEW_POS to FIELD_BOUND. */
746 new_pos = field_bound;
748 if (orig_point && XFASTINT (new_pos) != orig_point)
749 /* The NEW_POS argument was originally nil, so automatically set PT. */
750 SET_PT (XFASTINT (new_pos));
753 return new_pos;
757 DEFUN ("line-beginning-position",
758 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
759 doc: /* Return the character position of the first character on the current line.
760 With argument N not nil or 1, move forward N - 1 lines first.
761 If scan reaches end of buffer, return that position.
763 The returned position is of the first character in the logical order,
764 i.e. the one that has the smallest character position.
766 This function constrains the returned position to the current field
767 unless that would be on a different line than the original,
768 unconstrained result. If N is nil or 1, and a front-sticky field
769 starts at point, the scan stops as soon as it starts. To ignore field
770 boundaries bind `inhibit-field-text-motion' to t.
772 This function does not move point. */)
773 (Lisp_Object n)
775 ptrdiff_t orig, orig_byte, end;
776 ptrdiff_t count = SPECPDL_INDEX ();
777 specbind (Qinhibit_point_motion_hooks, Qt);
779 if (NILP (n))
780 XSETFASTINT (n, 1);
781 else
782 CHECK_NUMBER (n);
784 orig = PT;
785 orig_byte = PT_BYTE;
786 Fforward_line (make_number (XINT (n) - 1));
787 end = PT;
789 SET_PT_BOTH (orig, orig_byte);
791 unbind_to (count, Qnil);
793 /* Return END constrained to the current input field. */
794 return Fconstrain_to_field (make_number (end), make_number (orig),
795 XINT (n) != 1 ? Qt : Qnil,
796 Qt, Qnil);
799 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
800 doc: /* Return the character position of the last character on the current line.
801 With argument N not nil or 1, move forward N - 1 lines first.
802 If scan reaches end of buffer, return that position.
804 The returned position is of the last character in the logical order,
805 i.e. the character whose buffer position is the largest one.
807 This function constrains the returned position to the current field
808 unless that would be on a different line than the original,
809 unconstrained result. If N is nil or 1, and a rear-sticky field ends
810 at point, the scan stops as soon as it starts. To ignore field
811 boundaries bind `inhibit-field-text-motion' to t.
813 This function does not move point. */)
814 (Lisp_Object n)
816 ptrdiff_t clipped_n;
817 ptrdiff_t end_pos;
818 ptrdiff_t orig = PT;
820 if (NILP (n))
821 XSETFASTINT (n, 1);
822 else
823 CHECK_NUMBER (n);
825 clipped_n = clip_to_bounds (PTRDIFF_MIN + 1, XINT (n), PTRDIFF_MAX);
826 end_pos = find_before_next_newline (orig, 0, clipped_n - (clipped_n <= 0));
828 /* Return END_POS constrained to the current input field. */
829 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
830 Qnil, Qt, Qnil);
834 Lisp_Object
835 save_excursion_save (void)
837 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
838 == current_buffer);
840 return Fcons (Fpoint_marker (),
841 Fcons (Fcopy_marker (BVAR (current_buffer, mark), Qnil),
842 Fcons (visible ? Qt : Qnil,
843 Fcons (BVAR (current_buffer, mark_active),
844 selected_window))));
847 Lisp_Object
848 save_excursion_restore (Lisp_Object info)
850 Lisp_Object tem, tem1, omark, nmark;
851 struct gcpro gcpro1, gcpro2, gcpro3;
852 int visible_p;
854 tem = Fmarker_buffer (XCAR (info));
855 /* If buffer being returned to is now deleted, avoid error */
856 /* Otherwise could get error here while unwinding to top level
857 and crash */
858 /* In that case, Fmarker_buffer returns nil now. */
859 if (NILP (tem))
860 return Qnil;
862 omark = nmark = Qnil;
863 GCPRO3 (info, omark, nmark);
865 Fset_buffer (tem);
867 /* Point marker. */
868 tem = XCAR (info);
869 Fgoto_char (tem);
870 unchain_marker (XMARKER (tem));
872 /* Mark marker. */
873 info = XCDR (info);
874 tem = XCAR (info);
875 omark = Fmarker_position (BVAR (current_buffer, mark));
876 Fset_marker (BVAR (current_buffer, mark), tem, Fcurrent_buffer ());
877 nmark = Fmarker_position (tem);
878 unchain_marker (XMARKER (tem));
880 /* visible */
881 info = XCDR (info);
882 visible_p = !NILP (XCAR (info));
884 #if 0 /* We used to make the current buffer visible in the selected window
885 if that was true previously. That avoids some anomalies.
886 But it creates others, and it wasn't documented, and it is simpler
887 and cleaner never to alter the window/buffer connections. */
888 tem1 = Fcar (tem);
889 if (!NILP (tem1)
890 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
891 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
892 #endif /* 0 */
894 /* Mark active */
895 info = XCDR (info);
896 tem = XCAR (info);
897 tem1 = BVAR (current_buffer, mark_active);
898 BVAR (current_buffer, mark_active) = tem;
900 /* If mark is active now, and either was not active
901 or was at a different place, run the activate hook. */
902 if (! NILP (tem))
904 if (! EQ (omark, nmark))
906 tem = intern ("activate-mark-hook");
907 Frun_hooks (1, &tem);
910 /* If mark has ceased to be active, run deactivate hook. */
911 else if (! NILP (tem1))
913 tem = intern ("deactivate-mark-hook");
914 Frun_hooks (1, &tem);
917 /* If buffer was visible in a window, and a different window was
918 selected, and the old selected window is still showing this
919 buffer, restore point in that window. */
920 tem = XCDR (info);
921 if (visible_p
922 && !EQ (tem, selected_window)
923 && (tem1 = XWINDOW (tem)->buffer,
924 (/* Window is live... */
925 BUFFERP (tem1)
926 /* ...and it shows the current buffer. */
927 && XBUFFER (tem1) == current_buffer)))
928 Fset_window_point (tem, make_number (PT));
930 UNGCPRO;
931 return Qnil;
934 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
935 doc: /* Save point, mark, and current buffer; execute BODY; restore those things.
936 Executes BODY just like `progn'.
937 The values of point, mark and the current buffer are restored
938 even in case of abnormal exit (throw or error).
939 The state of activation of the mark is also restored.
941 This construct does not save `deactivate-mark', and therefore
942 functions that change the buffer will still cause deactivation
943 of the mark at the end of the command. To prevent that, bind
944 `deactivate-mark' with `let'.
946 If you only want to save the current buffer but not point nor mark,
947 then just use `save-current-buffer', or even `with-current-buffer'.
949 usage: (save-excursion &rest BODY) */)
950 (Lisp_Object args)
952 register Lisp_Object val;
953 ptrdiff_t count = SPECPDL_INDEX ();
955 record_unwind_protect (save_excursion_restore, save_excursion_save ());
957 val = Fprogn (args);
958 return unbind_to (count, val);
961 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
962 doc: /* Save the current buffer; execute BODY; restore the current buffer.
963 Executes BODY just like `progn'.
964 usage: (save-current-buffer &rest BODY) */)
965 (Lisp_Object args)
967 Lisp_Object val;
968 ptrdiff_t count = SPECPDL_INDEX ();
970 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
972 val = Fprogn (args);
973 return unbind_to (count, val);
976 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
977 doc: /* Return the number of characters in the current buffer.
978 If BUFFER, return the number of characters in that buffer instead. */)
979 (Lisp_Object buffer)
981 if (NILP (buffer))
982 return make_number (Z - BEG);
983 else
985 CHECK_BUFFER (buffer);
986 return make_number (BUF_Z (XBUFFER (buffer))
987 - BUF_BEG (XBUFFER (buffer)));
991 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
992 doc: /* Return the minimum permissible value of point in the current buffer.
993 This is 1, unless narrowing (a buffer restriction) is in effect. */)
994 (void)
996 Lisp_Object temp;
997 XSETFASTINT (temp, BEGV);
998 return temp;
1001 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
1002 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1003 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1004 (void)
1006 return buildmark (BEGV, BEGV_BYTE);
1009 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1010 doc: /* Return the maximum permissible value of point in the current buffer.
1011 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1012 is in effect, in which case it is less. */)
1013 (void)
1015 Lisp_Object temp;
1016 XSETFASTINT (temp, ZV);
1017 return temp;
1020 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1021 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1022 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1023 is in effect, in which case it is less. */)
1024 (void)
1026 return buildmark (ZV, ZV_BYTE);
1029 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1030 doc: /* Return the position of the gap, in the current buffer.
1031 See also `gap-size'. */)
1032 (void)
1034 Lisp_Object temp;
1035 XSETFASTINT (temp, GPT);
1036 return temp;
1039 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1040 doc: /* Return the size of the current buffer's gap.
1041 See also `gap-position'. */)
1042 (void)
1044 Lisp_Object temp;
1045 XSETFASTINT (temp, GAP_SIZE);
1046 return temp;
1049 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1050 doc: /* Return the byte position for character position POSITION.
1051 If POSITION is out of range, the value is nil. */)
1052 (Lisp_Object position)
1054 CHECK_NUMBER_COERCE_MARKER (position);
1055 if (XINT (position) < BEG || XINT (position) > Z)
1056 return Qnil;
1057 return make_number (CHAR_TO_BYTE (XINT (position)));
1060 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1061 doc: /* Return the character position for byte position BYTEPOS.
1062 If BYTEPOS is out of range, the value is nil. */)
1063 (Lisp_Object bytepos)
1065 CHECK_NUMBER (bytepos);
1066 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
1067 return Qnil;
1068 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1071 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1072 doc: /* Return the character following point, as a number.
1073 At the end of the buffer or accessible region, return 0. */)
1074 (void)
1076 Lisp_Object temp;
1077 if (PT >= ZV)
1078 XSETFASTINT (temp, 0);
1079 else
1080 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1081 return temp;
1084 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1085 doc: /* Return the character preceding point, as a number.
1086 At the beginning of the buffer or accessible region, return 0. */)
1087 (void)
1089 Lisp_Object temp;
1090 if (PT <= BEGV)
1091 XSETFASTINT (temp, 0);
1092 else if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1094 ptrdiff_t pos = PT_BYTE;
1095 DEC_POS (pos);
1096 XSETFASTINT (temp, FETCH_CHAR (pos));
1098 else
1099 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1100 return temp;
1103 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1104 doc: /* Return t if point is at the beginning of the buffer.
1105 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1106 (void)
1108 if (PT == BEGV)
1109 return Qt;
1110 return Qnil;
1113 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1114 doc: /* Return t if point is at the end of the buffer.
1115 If the buffer is narrowed, this means the end of the narrowed part. */)
1116 (void)
1118 if (PT == ZV)
1119 return Qt;
1120 return Qnil;
1123 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1124 doc: /* Return t if point is at the beginning of a line. */)
1125 (void)
1127 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1128 return Qt;
1129 return Qnil;
1132 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1133 doc: /* Return t if point is at the end of a line.
1134 `End of a line' includes point being at the end of the buffer. */)
1135 (void)
1137 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1138 return Qt;
1139 return Qnil;
1142 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1143 doc: /* Return character in current buffer at position POS.
1144 POS is an integer or a marker and defaults to point.
1145 If POS is out of range, the value is nil. */)
1146 (Lisp_Object pos)
1148 register ptrdiff_t pos_byte;
1150 if (NILP (pos))
1152 pos_byte = PT_BYTE;
1153 XSETFASTINT (pos, PT);
1156 if (MARKERP (pos))
1158 pos_byte = marker_byte_position (pos);
1159 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1160 return Qnil;
1162 else
1164 CHECK_NUMBER_COERCE_MARKER (pos);
1165 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1166 return Qnil;
1168 pos_byte = CHAR_TO_BYTE (XINT (pos));
1171 return make_number (FETCH_CHAR (pos_byte));
1174 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1175 doc: /* Return character in current buffer preceding position POS.
1176 POS is an integer or a marker and defaults to point.
1177 If POS is out of range, the value is nil. */)
1178 (Lisp_Object pos)
1180 register Lisp_Object val;
1181 register ptrdiff_t pos_byte;
1183 if (NILP (pos))
1185 pos_byte = PT_BYTE;
1186 XSETFASTINT (pos, PT);
1189 if (MARKERP (pos))
1191 pos_byte = marker_byte_position (pos);
1193 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1194 return Qnil;
1196 else
1198 CHECK_NUMBER_COERCE_MARKER (pos);
1200 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1201 return Qnil;
1203 pos_byte = CHAR_TO_BYTE (XINT (pos));
1206 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1208 DEC_POS (pos_byte);
1209 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1211 else
1213 pos_byte--;
1214 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1216 return val;
1219 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1220 doc: /* Return the name under which the user logged in, as a string.
1221 This is based on the effective uid, not the real uid.
1222 Also, if the environment variables LOGNAME or USER are set,
1223 that determines the value of this function.
1225 If optional argument UID is an integer or a float, return the login name
1226 of the user with that uid, or nil if there is no such user. */)
1227 (Lisp_Object uid)
1229 struct passwd *pw;
1230 uid_t id;
1232 /* Set up the user name info if we didn't do it before.
1233 (That can happen if Emacs is dumpable
1234 but you decide to run `temacs -l loadup' and not dump. */
1235 if (INTEGERP (Vuser_login_name))
1236 init_editfns ();
1238 if (NILP (uid))
1239 return Vuser_login_name;
1241 CONS_TO_INTEGER (uid, uid_t, id);
1242 BLOCK_INPUT;
1243 pw = getpwuid (id);
1244 UNBLOCK_INPUT;
1245 return (pw ? build_string (pw->pw_name) : Qnil);
1248 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1249 0, 0, 0,
1250 doc: /* Return the name of the user's real uid, as a string.
1251 This ignores the environment variables LOGNAME and USER, so it differs from
1252 `user-login-name' when running under `su'. */)
1253 (void)
1255 /* Set up the user name info if we didn't do it before.
1256 (That can happen if Emacs is dumpable
1257 but you decide to run `temacs -l loadup' and not dump. */
1258 if (INTEGERP (Vuser_login_name))
1259 init_editfns ();
1260 return Vuser_real_login_name;
1263 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1264 doc: /* Return the effective uid of Emacs.
1265 Value is an integer or a float, depending on the value. */)
1266 (void)
1268 uid_t euid = geteuid ();
1269 return make_fixnum_or_float (euid);
1272 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1273 doc: /* Return the real uid of Emacs.
1274 Value is an integer or a float, depending on the value. */)
1275 (void)
1277 uid_t uid = getuid ();
1278 return make_fixnum_or_float (uid);
1281 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1282 doc: /* Return the full name of the user logged in, as a string.
1283 If the full name corresponding to Emacs's userid is not known,
1284 return "unknown".
1286 If optional argument UID is an integer or float, return the full name
1287 of the user with that uid, or nil if there is no such user.
1288 If UID is a string, return the full name of the user with that login
1289 name, or nil if there is no such user. */)
1290 (Lisp_Object uid)
1292 struct passwd *pw;
1293 register char *p, *q;
1294 Lisp_Object full;
1296 if (NILP (uid))
1297 return Vuser_full_name;
1298 else if (NUMBERP (uid))
1300 uid_t u;
1301 CONS_TO_INTEGER (uid, uid_t, u);
1302 BLOCK_INPUT;
1303 pw = getpwuid (u);
1304 UNBLOCK_INPUT;
1306 else if (STRINGP (uid))
1308 BLOCK_INPUT;
1309 pw = getpwnam (SSDATA (uid));
1310 UNBLOCK_INPUT;
1312 else
1313 error ("Invalid UID specification");
1315 if (!pw)
1316 return Qnil;
1318 p = USER_FULL_NAME;
1319 /* Chop off everything after the first comma. */
1320 q = strchr (p, ',');
1321 full = make_string (p, q ? q - p : strlen (p));
1323 #ifdef AMPERSAND_FULL_NAME
1324 p = SSDATA (full);
1325 q = strchr (p, '&');
1326 /* Substitute the login name for the &, upcasing the first character. */
1327 if (q)
1329 register char *r;
1330 Lisp_Object login;
1332 login = Fuser_login_name (make_number (pw->pw_uid));
1333 r = alloca (strlen (p) + SCHARS (login) + 1);
1334 memcpy (r, p, q - p);
1335 r[q - p] = 0;
1336 strcat (r, SSDATA (login));
1337 r[q - p] = upcase ((unsigned char) r[q - p]);
1338 strcat (r, q + 1);
1339 full = build_string (r);
1341 #endif /* AMPERSAND_FULL_NAME */
1343 return full;
1346 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1347 doc: /* Return the host name of the machine you are running on, as a string. */)
1348 (void)
1350 return Vsystem_name;
1353 const char *
1354 get_system_name (void)
1356 if (STRINGP (Vsystem_name))
1357 return SSDATA (Vsystem_name);
1358 else
1359 return "";
1362 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1363 doc: /* Return the process ID of Emacs, as a number. */)
1364 (void)
1366 pid_t pid = getpid ();
1367 return make_fixnum_or_float (pid);
1372 #ifndef TIME_T_MIN
1373 # define TIME_T_MIN TYPE_MINIMUM (time_t)
1374 #endif
1375 #ifndef TIME_T_MAX
1376 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
1377 #endif
1379 /* Report that a time value is out of range for Emacs. */
1380 void
1381 time_overflow (void)
1383 error ("Specified time is not representable");
1386 /* Return the upper part of the time T (everything but the bottom 16 bits). */
1387 static EMACS_INT
1388 hi_time (time_t t)
1390 time_t hi = t >> 16;
1392 /* Check for overflow, helping the compiler for common cases where
1393 no runtime check is needed, and taking care not to convert
1394 negative numbers to unsigned before comparing them. */
1395 if (! ((! TYPE_SIGNED (time_t)
1396 || MOST_NEGATIVE_FIXNUM <= TIME_T_MIN >> 16
1397 || MOST_NEGATIVE_FIXNUM <= hi)
1398 && (TIME_T_MAX >> 16 <= MOST_POSITIVE_FIXNUM
1399 || hi <= MOST_POSITIVE_FIXNUM)))
1400 time_overflow ();
1402 return hi;
1405 /* Return the bottom 16 bits of the time T. */
1406 static int
1407 lo_time (time_t t)
1409 return t & ((1 << 16) - 1);
1412 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1413 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1414 The time is returned as a list of integers (HIGH LOW USEC PSEC).
1415 HIGH has the most significant bits of the seconds, while LOW has the
1416 least significant 16 bits. USEC and PSEC are the microsecond and
1417 picosecond counts. */)
1418 (void)
1420 EMACS_TIME t;
1422 EMACS_GET_TIME (t);
1423 return make_lisp_time (t);
1426 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1427 0, 0, 0,
1428 doc: /* Return the current run time used by Emacs.
1429 The time is returned as a list (HIGH LOW USEC PSEC), using the same
1430 style as (current-time).
1432 On systems that can't determine the run time, `get-internal-run-time'
1433 does the same thing as `current-time'. */)
1434 (void)
1436 #ifdef HAVE_GETRUSAGE
1437 struct rusage usage;
1438 time_t secs;
1439 int usecs;
1440 EMACS_TIME t;
1442 if (getrusage (RUSAGE_SELF, &usage) < 0)
1443 /* This shouldn't happen. What action is appropriate? */
1444 xsignal0 (Qerror);
1446 /* Sum up user time and system time. */
1447 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1448 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1449 if (usecs >= 1000000)
1451 usecs -= 1000000;
1452 secs++;
1454 EMACS_SET_SECS_USECS (t, secs, usecs);
1455 return make_lisp_time (t);
1456 #else /* ! HAVE_GETRUSAGE */
1457 #ifdef WINDOWSNT
1458 return w32_get_internal_run_time ();
1459 #else /* ! WINDOWSNT */
1460 return Fcurrent_time ();
1461 #endif /* WINDOWSNT */
1462 #endif /* HAVE_GETRUSAGE */
1466 /* Make a Lisp list that represents the time T with fraction TAIL. */
1467 static Lisp_Object
1468 make_time_tail (time_t t, Lisp_Object tail)
1470 return Fcons (make_number (hi_time (t)),
1471 Fcons (make_number (lo_time (t)), tail));
1474 /* Make a Lisp list that represents the system time T. */
1475 static Lisp_Object
1476 make_time (time_t t)
1478 return make_time_tail (t, Qnil);
1481 /* Make a Lisp list that represents the Emacs time T. T may be an
1482 invalid time, with a slightly negative tv_nsec value such as
1483 UNKNOWN_MODTIME_NSECS; in that case, the Lisp list contains a
1484 correspondingly negative picosecond count. */
1485 Lisp_Object
1486 make_lisp_time (EMACS_TIME t)
1488 int ns = EMACS_NSECS (t);
1489 return make_time_tail (EMACS_SECS (t),
1490 list2 (make_number (ns / 1000),
1491 make_number (ns % 1000 * 1000)));
1494 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1495 Set *PHIGH, *PLOW, *PUSEC, *PPSEC to its parts; do not check their values.
1496 Return nonzero if successful. */
1497 static int
1498 disassemble_lisp_time (Lisp_Object specified_time, Lisp_Object *phigh,
1499 Lisp_Object *plow, Lisp_Object *pusec,
1500 Lisp_Object *ppsec)
1502 if (CONSP (specified_time))
1504 Lisp_Object low = XCDR (specified_time);
1505 Lisp_Object usec = make_number (0);
1506 Lisp_Object psec = make_number (0);
1507 if (CONSP (low))
1509 Lisp_Object low_tail = XCDR (low);
1510 low = XCAR (low);
1511 if (CONSP (low_tail))
1513 usec = XCAR (low_tail);
1514 low_tail = XCDR (low_tail);
1515 if (CONSP (low_tail))
1516 psec = XCAR (low_tail);
1518 else if (!NILP (low_tail))
1519 usec = low_tail;
1522 *phigh = XCAR (specified_time);
1523 *plow = low;
1524 *pusec = usec;
1525 *ppsec = psec;
1526 return 1;
1529 return 0;
1532 /* From the time components HIGH, LOW, USEC and PSEC taken from a Lisp
1533 list, generate the corresponding EMACS_TIME value *RESULT, and
1534 if RESULT_PSEC is not null store into *RESULT_PSEC the
1535 (nonnegative) difference in picoseconds between the input time and
1536 the returned time. Return nonzero if successful. */
1538 decode_time_components (Lisp_Object high, Lisp_Object low, Lisp_Object usec,
1539 Lisp_Object psec, EMACS_TIME *result, int *result_psec)
1541 EMACS_INT hi, lo, us, ps;
1542 time_t sec;
1543 if (! (INTEGERP (high) && INTEGERP (low)
1544 && INTEGERP (usec) && INTEGERP (psec)))
1545 return 0;
1546 hi = XINT (high);
1547 lo = XINT (low);
1548 us = XINT (usec);
1549 ps = XINT (psec);
1551 /* Normalize out-of-range lower-order components by carrying
1552 each overflow into the next higher-order component. */
1553 us += ps / 1000000 - (ps % 1000000 < 0);
1554 lo += us / 1000000 - (us % 1000000 < 0);
1555 hi += lo >> 16;
1556 ps = ps % 1000000 + 1000000 * (ps % 1000000 < 0);
1557 us = us % 1000000 + 1000000 * (us % 1000000 < 0);
1558 lo &= (1 << 16) - 1;
1560 /* Check for overflow in the highest-order component. */
1561 if (! ((TYPE_SIGNED (time_t) ? TIME_T_MIN >> 16 <= hi : 0 <= hi)
1562 && hi <= TIME_T_MAX >> 16))
1563 return 0;
1565 sec = hi;
1566 EMACS_SET_SECS_NSECS (*result, (sec << 16) + lo, us * 1000 + ps / 1000);
1567 if (result_psec)
1568 *result_psec = ps % 1000;
1569 return 1;
1572 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1573 If SPECIFIED_TIME is nil, use the current time.
1574 Round the time down to the nearest EMACS_TIME value, and
1575 if PPSEC is not null store into *PPSEC the (nonnegative) difference in
1576 picoseconds between the input time and the returned time.
1577 Return seconds since the Epoch.
1578 Signal an error if unsuccessful. */
1579 EMACS_TIME
1580 lisp_time_argument (Lisp_Object specified_time, int *ppsec)
1582 EMACS_TIME t;
1583 if (NILP (specified_time))
1584 EMACS_GET_TIME (t);
1585 else
1587 Lisp_Object high, low, usec, psec;
1588 if (! (disassemble_lisp_time (specified_time, &high, &low, &usec, &psec)
1589 && decode_time_components (high, low, usec, psec, &t, ppsec)))
1590 error ("Invalid time specification");
1592 return t;
1595 /* Like lisp_time_argument, except decode only the seconds part,
1596 and do not check the subseconds part, and always round down. */
1597 static time_t
1598 lisp_seconds_argument (Lisp_Object specified_time)
1600 if (NILP (specified_time))
1601 return time (NULL);
1602 else
1604 Lisp_Object high, low, usec, psec;
1605 EMACS_TIME t;
1606 if (! (disassemble_lisp_time (specified_time, &high, &low, &usec, &psec)
1607 && decode_time_components (high, low, make_number (0),
1608 make_number (0), &t, 0)))
1609 error ("Invalid time specification");
1610 return EMACS_SECS (t);
1614 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1615 doc: /* Return the current time, as a float number of seconds since the epoch.
1616 If SPECIFIED-TIME is given, it is the time to convert to float
1617 instead of the current time. The argument should have the form
1618 (HIGH LOW) or (HIGH LOW USEC) or (HIGH LOW USEC PSEC). Thus,
1619 you can use times from `current-time' and from `file-attributes'.
1620 SPECIFIED-TIME can also have the form (HIGH . LOW), but this is
1621 considered obsolete.
1623 WARNING: Since the result is floating point, it may not be exact.
1624 If precise time stamps are required, use either `current-time',
1625 or (if you need time as a string) `format-time-string'. */)
1626 (Lisp_Object specified_time)
1628 int psec;
1629 EMACS_TIME t = lisp_time_argument (specified_time, &psec);
1630 double ps = (1000 * 1000 * 1000 <= INTMAX_MAX / 1000
1631 ? EMACS_NSECS (t) * (intmax_t) 1000 + psec
1632 : EMACS_NSECS (t) * 1e3 + psec);
1633 return make_float (EMACS_SECS (t) + ps / 1e12);
1636 /* Write information into buffer S of size MAXSIZE, according to the
1637 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1638 Default to Universal Time if UT is nonzero, local time otherwise.
1639 Use NS as the number of nanoseconds in the %N directive.
1640 Return the number of bytes written, not including the terminating
1641 '\0'. If S is NULL, nothing will be written anywhere; so to
1642 determine how many bytes would be written, use NULL for S and
1643 ((size_t) -1) for MAXSIZE.
1645 This function behaves like nstrftime, except it allows null
1646 bytes in FORMAT and it does not support nanoseconds. */
1647 static size_t
1648 emacs_nmemftime (char *s, size_t maxsize, const char *format,
1649 size_t format_len, const struct tm *tp, int ut, int ns)
1651 size_t total = 0;
1653 /* Loop through all the null-terminated strings in the format
1654 argument. Normally there's just one null-terminated string, but
1655 there can be arbitrarily many, concatenated together, if the
1656 format contains '\0' bytes. nstrftime stops at the first
1657 '\0' byte so we must invoke it separately for each such string. */
1658 for (;;)
1660 size_t len;
1661 size_t result;
1663 if (s)
1664 s[0] = '\1';
1666 result = nstrftime (s, maxsize, format, tp, ut, ns);
1668 if (s)
1670 if (result == 0 && s[0] != '\0')
1671 return 0;
1672 s += result + 1;
1675 maxsize -= result + 1;
1676 total += result;
1677 len = strlen (format);
1678 if (len == format_len)
1679 return total;
1680 total++;
1681 format += len + 1;
1682 format_len -= len + 1;
1686 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1687 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
1688 TIME is specified as (HIGH LOW USEC PSEC), as returned by
1689 `current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
1690 is also still accepted.
1691 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1692 as Universal Time; nil means describe TIME in the local time zone.
1693 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1694 by text that describes the specified date and time in TIME:
1696 %Y is the year, %y within the century, %C the century.
1697 %G is the year corresponding to the ISO week, %g within the century.
1698 %m is the numeric month.
1699 %b and %h are the locale's abbreviated month name, %B the full name.
1700 %d is the day of the month, zero-padded, %e is blank-padded.
1701 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1702 %a is the locale's abbreviated name of the day of week, %A the full name.
1703 %U is the week number starting on Sunday, %W starting on Monday,
1704 %V according to ISO 8601.
1705 %j is the day of the year.
1707 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1708 only blank-padded, %l is like %I blank-padded.
1709 %p is the locale's equivalent of either AM or PM.
1710 %M is the minute.
1711 %S is the second.
1712 %N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
1713 %Z is the time zone name, %z is the numeric form.
1714 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1716 %c is the locale's date and time format.
1717 %x is the locale's "preferred" date format.
1718 %D is like "%m/%d/%y".
1720 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1721 %X is the locale's "preferred" time format.
1723 Finally, %n is a newline, %t is a tab, %% is a literal %.
1725 Certain flags and modifiers are available with some format controls.
1726 The flags are `_', `-', `^' and `#'. For certain characters X,
1727 %_X is like %X, but padded with blanks; %-X is like %X,
1728 but without padding. %^X is like %X, but with all textual
1729 characters up-cased; %#X is like %X, but with letter-case of
1730 all textual characters reversed.
1731 %NX (where N stands for an integer) is like %X,
1732 but takes up at least N (a number) positions.
1733 The modifiers are `E' and `O'. For certain characters X,
1734 %EX is a locale's alternative version of %X;
1735 %OX is like %X, but uses the locale's number symbols.
1737 For example, to produce full ISO 8601 format, use "%Y-%m-%dT%T%z".
1739 usage: (format-time-string FORMAT-STRING &optional TIME UNIVERSAL) */)
1740 (Lisp_Object format_string, Lisp_Object timeval, Lisp_Object universal)
1742 EMACS_TIME t = lisp_time_argument (timeval, 0);
1743 struct tm tm;
1745 CHECK_STRING (format_string);
1746 format_string = code_convert_string_norecord (format_string,
1747 Vlocale_coding_system, 1);
1748 return format_time_string (SSDATA (format_string), SBYTES (format_string),
1749 t, ! NILP (universal), &tm);
1752 static Lisp_Object
1753 format_time_string (char const *format, ptrdiff_t formatlen,
1754 EMACS_TIME t, int ut, struct tm *tmp)
1756 char buffer[4000];
1757 char *buf = buffer;
1758 ptrdiff_t size = sizeof buffer;
1759 size_t len;
1760 Lisp_Object bufstring;
1761 int ns = EMACS_NSECS (t);
1762 struct tm *tm;
1763 USE_SAFE_ALLOCA;
1765 while (1)
1767 BLOCK_INPUT;
1769 synchronize_system_time_locale ();
1771 tm = ut ? gmtime (EMACS_SECS_ADDR (t)) : localtime (EMACS_SECS_ADDR (t));
1772 if (! tm)
1774 UNBLOCK_INPUT;
1775 time_overflow ();
1777 *tmp = *tm;
1779 buf[0] = '\1';
1780 len = emacs_nmemftime (buf, size, format, formatlen, tm, ut, ns);
1781 if ((0 < len && len < size) || (len == 0 && buf[0] == '\0'))
1782 break;
1784 /* Buffer was too small, so make it bigger and try again. */
1785 len = emacs_nmemftime (NULL, SIZE_MAX, format, formatlen, tm, ut, ns);
1786 UNBLOCK_INPUT;
1787 if (STRING_BYTES_BOUND <= len)
1788 string_overflow ();
1789 size = len + 1;
1790 SAFE_ALLOCA (buf, char *, size);
1793 UNBLOCK_INPUT;
1794 bufstring = make_unibyte_string (buf, len);
1795 SAFE_FREE ();
1796 return code_convert_string_norecord (bufstring, Vlocale_coding_system, 0);
1799 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1800 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
1801 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
1802 as from `current-time' and `file-attributes', or nil to use the
1803 current time. The obsolete form (HIGH . LOW) is also still accepted.
1804 The list has the following nine members: SEC is an integer between 0
1805 and 60; SEC is 60 for a leap second, which only some operating systems
1806 support. MINUTE is an integer between 0 and 59. HOUR is an integer
1807 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
1808 integer between 1 and 12. YEAR is an integer indicating the
1809 four-digit year. DOW is the day of week, an integer between 0 and 6,
1810 where 0 is Sunday. DST is t if daylight saving time is in effect,
1811 otherwise nil. ZONE is an integer indicating the number of seconds
1812 east of Greenwich. (Note that Common Lisp has different meanings for
1813 DOW and ZONE.) */)
1814 (Lisp_Object specified_time)
1816 time_t time_spec = lisp_seconds_argument (specified_time);
1817 struct tm save_tm;
1818 struct tm *decoded_time;
1819 Lisp_Object list_args[9];
1821 BLOCK_INPUT;
1822 decoded_time = localtime (&time_spec);
1823 if (decoded_time)
1824 save_tm = *decoded_time;
1825 UNBLOCK_INPUT;
1826 if (! (decoded_time
1827 && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= save_tm.tm_year
1828 && save_tm.tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE))
1829 time_overflow ();
1830 XSETFASTINT (list_args[0], save_tm.tm_sec);
1831 XSETFASTINT (list_args[1], save_tm.tm_min);
1832 XSETFASTINT (list_args[2], save_tm.tm_hour);
1833 XSETFASTINT (list_args[3], save_tm.tm_mday);
1834 XSETFASTINT (list_args[4], save_tm.tm_mon + 1);
1835 /* On 64-bit machines an int is narrower than EMACS_INT, thus the
1836 cast below avoids overflow in int arithmetics. */
1837 XSETINT (list_args[5], TM_YEAR_BASE + (EMACS_INT) save_tm.tm_year);
1838 XSETFASTINT (list_args[6], save_tm.tm_wday);
1839 list_args[7] = save_tm.tm_isdst ? Qt : Qnil;
1841 BLOCK_INPUT;
1842 decoded_time = gmtime (&time_spec);
1843 if (decoded_time == 0)
1844 list_args[8] = Qnil;
1845 else
1846 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1847 UNBLOCK_INPUT;
1848 return Flist (9, list_args);
1851 /* Return OBJ - OFFSET, checking that OBJ is a valid fixnum and that
1852 the result is representable as an int. Assume OFFSET is small and
1853 nonnegative. */
1854 static int
1855 check_tm_member (Lisp_Object obj, int offset)
1857 EMACS_INT n;
1858 CHECK_NUMBER (obj);
1859 n = XINT (obj);
1860 if (! (INT_MIN + offset <= n && n - offset <= INT_MAX))
1861 time_overflow ();
1862 return n - offset;
1865 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1866 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
1867 This is the reverse operation of `decode-time', which see.
1868 ZONE defaults to the current time zone rule. This can
1869 be a string or t (as from `set-time-zone-rule'), or it can be a list
1870 \(as from `current-time-zone') or an integer (as from `decode-time')
1871 applied without consideration for daylight saving time.
1873 You can pass more than 7 arguments; then the first six arguments
1874 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
1875 The intervening arguments are ignored.
1876 This feature lets (apply 'encode-time (decode-time ...)) work.
1878 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
1879 for example, a DAY of 0 means the day preceding the given month.
1880 Year numbers less than 100 are treated just like other year numbers.
1881 If you want them to stand for years in this century, you must do that yourself.
1883 Years before 1970 are not guaranteed to work. On some systems,
1884 year values as low as 1901 do work.
1886 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
1887 (ptrdiff_t nargs, Lisp_Object *args)
1889 time_t value;
1890 struct tm tm;
1891 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1893 tm.tm_sec = check_tm_member (args[0], 0);
1894 tm.tm_min = check_tm_member (args[1], 0);
1895 tm.tm_hour = check_tm_member (args[2], 0);
1896 tm.tm_mday = check_tm_member (args[3], 0);
1897 tm.tm_mon = check_tm_member (args[4], 1);
1898 tm.tm_year = check_tm_member (args[5], TM_YEAR_BASE);
1899 tm.tm_isdst = -1;
1901 if (CONSP (zone))
1902 zone = Fcar (zone);
1903 if (NILP (zone))
1905 BLOCK_INPUT;
1906 value = mktime (&tm);
1907 UNBLOCK_INPUT;
1909 else
1911 char tzbuf[100];
1912 const char *tzstring;
1913 char **oldenv = environ, **newenv;
1915 if (EQ (zone, Qt))
1916 tzstring = "UTC0";
1917 else if (STRINGP (zone))
1918 tzstring = SSDATA (zone);
1919 else if (INTEGERP (zone))
1921 EMACS_INT abszone = eabs (XINT (zone));
1922 EMACS_INT zone_hr = abszone / (60*60);
1923 int zone_min = (abszone/60) % 60;
1924 int zone_sec = abszone % 60;
1925 sprintf (tzbuf, "XXX%s%"pI"d:%02d:%02d", "-" + (XINT (zone) < 0),
1926 zone_hr, zone_min, zone_sec);
1927 tzstring = tzbuf;
1929 else
1930 error ("Invalid time zone specification");
1932 BLOCK_INPUT;
1934 /* Set TZ before calling mktime; merely adjusting mktime's returned
1935 value doesn't suffice, since that would mishandle leap seconds. */
1936 set_time_zone_rule (tzstring);
1938 value = mktime (&tm);
1940 /* Restore TZ to previous value. */
1941 newenv = environ;
1942 environ = oldenv;
1943 #ifdef LOCALTIME_CACHE
1944 tzset ();
1945 #endif
1946 UNBLOCK_INPUT;
1948 xfree (newenv);
1951 if (value == (time_t) -1)
1952 time_overflow ();
1954 return make_time (value);
1957 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1958 doc: /* Return the current local time, as a human-readable string.
1959 Programs can use this function to decode a time,
1960 since the number of columns in each field is fixed
1961 if the year is in the range 1000-9999.
1962 The format is `Sun Sep 16 01:03:52 1973'.
1963 However, see also the functions `decode-time' and `format-time-string'
1964 which provide a much more powerful and general facility.
1966 If SPECIFIED-TIME is given, it is a time to format instead of the
1967 current time. The argument should have the form (HIGH LOW . IGNORED).
1968 Thus, you can use times obtained from `current-time' and from
1969 `file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
1970 but this is considered obsolete. */)
1971 (Lisp_Object specified_time)
1973 time_t value = lisp_seconds_argument (specified_time);
1974 struct tm *tm;
1975 char buf[sizeof "Mon Apr 30 12:49:17 " + INT_STRLEN_BOUND (int) + 1];
1976 int len IF_LINT (= 0);
1978 /* Convert to a string in ctime format, except without the trailing
1979 newline, and without the 4-digit year limit. Don't use asctime
1980 or ctime, as they might dump core if the year is outside the
1981 range -999 .. 9999. */
1982 BLOCK_INPUT;
1983 tm = localtime (&value);
1984 if (tm)
1986 static char const wday_name[][4] =
1987 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1988 static char const mon_name[][4] =
1989 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1990 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1991 printmax_t year_base = TM_YEAR_BASE;
1993 len = sprintf (buf, "%s %s%3d %02d:%02d:%02d %"pMd,
1994 wday_name[tm->tm_wday], mon_name[tm->tm_mon], tm->tm_mday,
1995 tm->tm_hour, tm->tm_min, tm->tm_sec,
1996 tm->tm_year + year_base);
1998 UNBLOCK_INPUT;
1999 if (! tm)
2000 time_overflow ();
2002 return make_unibyte_string (buf, len);
2005 /* Yield A - B, measured in seconds.
2006 This function is copied from the GNU C Library. */
2007 static int
2008 tm_diff (struct tm *a, struct tm *b)
2010 /* Compute intervening leap days correctly even if year is negative.
2011 Take care to avoid int overflow in leap day calculations,
2012 but it's OK to assume that A and B are close to each other. */
2013 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2014 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2015 int a100 = a4 / 25 - (a4 % 25 < 0);
2016 int b100 = b4 / 25 - (b4 % 25 < 0);
2017 int a400 = a100 >> 2;
2018 int b400 = b100 >> 2;
2019 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2020 int years = a->tm_year - b->tm_year;
2021 int days = (365 * years + intervening_leap_days
2022 + (a->tm_yday - b->tm_yday));
2023 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2024 + (a->tm_min - b->tm_min))
2025 + (a->tm_sec - b->tm_sec));
2028 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
2029 doc: /* Return the offset and name for the local time zone.
2030 This returns a list of the form (OFFSET NAME).
2031 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
2032 A negative value means west of Greenwich.
2033 NAME is a string giving the name of the time zone.
2034 If SPECIFIED-TIME is given, the time zone offset is determined from it
2035 instead of using the current time. The argument should have the form
2036 (HIGH LOW . IGNORED). Thus, you can use times obtained from
2037 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
2038 have the form (HIGH . LOW), but this is considered obsolete.
2040 Some operating systems cannot provide all this information to Emacs;
2041 in this case, `current-time-zone' returns a list containing nil for
2042 the data it can't find. */)
2043 (Lisp_Object specified_time)
2045 EMACS_TIME value;
2046 int offset;
2047 struct tm *t;
2048 struct tm localtm;
2049 Lisp_Object zone_offset, zone_name;
2051 zone_offset = Qnil;
2052 EMACS_SET_SECS_NSECS (value, lisp_seconds_argument (specified_time), 0);
2053 zone_name = format_time_string ("%Z", sizeof "%Z" - 1, value, 0, &localtm);
2054 BLOCK_INPUT;
2055 t = gmtime (EMACS_SECS_ADDR (value));
2056 if (t)
2057 offset = tm_diff (&localtm, t);
2058 UNBLOCK_INPUT;
2060 if (t)
2062 zone_offset = make_number (offset);
2063 if (SCHARS (zone_name) == 0)
2065 /* No local time zone name is available; use "+-NNNN" instead. */
2066 int m = offset / 60;
2067 int am = offset < 0 ? - m : m;
2068 char buf[sizeof "+00" + INT_STRLEN_BOUND (int)];
2069 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
2070 zone_name = build_string (buf);
2074 return list2 (zone_offset, zone_name);
2077 /* This holds the value of `environ' produced by the previous
2078 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
2079 has never been called. */
2080 static char **environbuf;
2082 /* This holds the startup value of the TZ environment variable so it
2083 can be restored if the user calls set-time-zone-rule with a nil
2084 argument. */
2085 static char *initial_tz;
2087 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2088 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
2089 If TZ is nil, use implementation-defined default time zone information.
2090 If TZ is t, use Universal Time.
2092 Instead of calling this function, you typically want (setenv "TZ" TZ).
2093 That changes both the environment of the Emacs process and the
2094 variable `process-environment', whereas `set-time-zone-rule' affects
2095 only the former. */)
2096 (Lisp_Object tz)
2098 const char *tzstring;
2099 char **old_environbuf;
2101 if (! (NILP (tz) || EQ (tz, Qt)))
2102 CHECK_STRING (tz);
2104 BLOCK_INPUT;
2106 /* When called for the first time, save the original TZ. */
2107 old_environbuf = environbuf;
2108 if (!old_environbuf)
2109 initial_tz = (char *) getenv ("TZ");
2111 if (NILP (tz))
2112 tzstring = initial_tz;
2113 else if (EQ (tz, Qt))
2114 tzstring = "UTC0";
2115 else
2116 tzstring = SSDATA (tz);
2118 set_time_zone_rule (tzstring);
2119 environbuf = environ;
2121 UNBLOCK_INPUT;
2123 xfree (old_environbuf);
2124 return Qnil;
2127 #ifdef LOCALTIME_CACHE
2129 /* These two values are known to load tz files in buggy implementations,
2130 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
2131 Their values shouldn't matter in non-buggy implementations.
2132 We don't use string literals for these strings,
2133 since if a string in the environment is in readonly
2134 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
2135 See Sun bugs 1113095 and 1114114, ``Timezone routines
2136 improperly modify environment''. */
2138 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
2139 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
2141 #endif
2143 /* Set the local time zone rule to TZSTRING.
2144 This allocates memory into `environ', which it is the caller's
2145 responsibility to free. */
2147 void
2148 set_time_zone_rule (const char *tzstring)
2150 ptrdiff_t envptrs;
2151 char **from, **to, **newenv;
2153 /* Make the ENVIRON vector longer with room for TZSTRING. */
2154 for (from = environ; *from; from++)
2155 continue;
2156 envptrs = from - environ + 2;
2157 newenv = to = xmalloc (envptrs * sizeof *newenv
2158 + (tzstring ? strlen (tzstring) + 4 : 0));
2160 /* Add TZSTRING to the end of environ, as a value for TZ. */
2161 if (tzstring)
2163 char *t = (char *) (to + envptrs);
2164 strcpy (t, "TZ=");
2165 strcat (t, tzstring);
2166 *to++ = t;
2169 /* Copy the old environ vector elements into NEWENV,
2170 but don't copy the TZ variable.
2171 So we have only one definition of TZ, which came from TZSTRING. */
2172 for (from = environ; *from; from++)
2173 if (strncmp (*from, "TZ=", 3) != 0)
2174 *to++ = *from;
2175 *to = 0;
2177 environ = newenv;
2179 /* If we do have a TZSTRING, NEWENV points to the vector slot where
2180 the TZ variable is stored. If we do not have a TZSTRING,
2181 TO points to the vector slot which has the terminating null. */
2183 #ifdef LOCALTIME_CACHE
2185 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
2186 "US/Pacific" that loads a tz file, then changes to a value like
2187 "XXX0" that does not load a tz file, and then changes back to
2188 its original value, the last change is (incorrectly) ignored.
2189 Also, if TZ changes twice in succession to values that do
2190 not load a tz file, tzset can dump core (see Sun bug#1225179).
2191 The following code works around these bugs. */
2193 if (tzstring)
2195 /* Temporarily set TZ to a value that loads a tz file
2196 and that differs from tzstring. */
2197 char *tz = *newenv;
2198 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
2199 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
2200 tzset ();
2201 *newenv = tz;
2203 else
2205 /* The implied tzstring is unknown, so temporarily set TZ to
2206 two different values that each load a tz file. */
2207 *to = set_time_zone_rule_tz1;
2208 to[1] = 0;
2209 tzset ();
2210 *to = set_time_zone_rule_tz2;
2211 tzset ();
2212 *to = 0;
2215 /* Now TZ has the desired value, and tzset can be invoked safely. */
2218 tzset ();
2219 #endif
2222 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2223 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2224 type of object is Lisp_String). INHERIT is passed to
2225 INSERT_FROM_STRING_FUNC as the last argument. */
2227 static void
2228 general_insert_function (void (*insert_func)
2229 (const char *, ptrdiff_t),
2230 void (*insert_from_string_func)
2231 (Lisp_Object, ptrdiff_t, ptrdiff_t,
2232 ptrdiff_t, ptrdiff_t, int),
2233 int inherit, ptrdiff_t nargs, Lisp_Object *args)
2235 ptrdiff_t argnum;
2236 register Lisp_Object val;
2238 for (argnum = 0; argnum < nargs; argnum++)
2240 val = args[argnum];
2241 if (CHARACTERP (val))
2243 int c = XFASTINT (val);
2244 unsigned char str[MAX_MULTIBYTE_LENGTH];
2245 int len;
2247 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2248 len = CHAR_STRING (c, str);
2249 else
2251 str[0] = ASCII_CHAR_P (c) ? c : multibyte_char_to_unibyte (c);
2252 len = 1;
2254 (*insert_func) ((char *) str, len);
2256 else if (STRINGP (val))
2258 (*insert_from_string_func) (val, 0, 0,
2259 SCHARS (val),
2260 SBYTES (val),
2261 inherit);
2263 else
2264 wrong_type_argument (Qchar_or_string_p, val);
2268 void
2269 insert1 (Lisp_Object arg)
2271 Finsert (1, &arg);
2275 /* Callers passing one argument to Finsert need not gcpro the
2276 argument "array", since the only element of the array will
2277 not be used after calling insert or insert_from_string, so
2278 we don't care if it gets trashed. */
2280 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2281 doc: /* Insert the arguments, either strings or characters, at point.
2282 Point and before-insertion markers move forward to end up
2283 after the inserted text.
2284 Any other markers at the point of insertion remain before the text.
2286 If the current buffer is multibyte, unibyte strings are converted
2287 to multibyte for insertion (see `string-make-multibyte').
2288 If the current buffer is unibyte, multibyte strings are converted
2289 to unibyte for insertion (see `string-make-unibyte').
2291 When operating on binary data, it may be necessary to preserve the
2292 original bytes of a unibyte string when inserting it into a multibyte
2293 buffer; to accomplish this, apply `string-as-multibyte' to the string
2294 and insert the result.
2296 usage: (insert &rest ARGS) */)
2297 (ptrdiff_t nargs, Lisp_Object *args)
2299 general_insert_function (insert, insert_from_string, 0, nargs, args);
2300 return Qnil;
2303 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2304 0, MANY, 0,
2305 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2306 Point and before-insertion markers move forward to end up
2307 after the inserted text.
2308 Any other markers at the point of insertion remain before the text.
2310 If the current buffer is multibyte, unibyte strings are converted
2311 to multibyte for insertion (see `unibyte-char-to-multibyte').
2312 If the current buffer is unibyte, multibyte strings are converted
2313 to unibyte for insertion.
2315 usage: (insert-and-inherit &rest ARGS) */)
2316 (ptrdiff_t nargs, Lisp_Object *args)
2318 general_insert_function (insert_and_inherit, insert_from_string, 1,
2319 nargs, args);
2320 return Qnil;
2323 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2324 doc: /* Insert strings or characters at point, relocating markers after the text.
2325 Point and markers move forward to end up after the inserted text.
2327 If the current buffer is multibyte, unibyte strings are converted
2328 to multibyte for insertion (see `unibyte-char-to-multibyte').
2329 If the current buffer is unibyte, multibyte strings are converted
2330 to unibyte for insertion.
2332 usage: (insert-before-markers &rest ARGS) */)
2333 (ptrdiff_t nargs, Lisp_Object *args)
2335 general_insert_function (insert_before_markers,
2336 insert_from_string_before_markers, 0,
2337 nargs, args);
2338 return Qnil;
2341 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2342 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2343 doc: /* Insert text at point, relocating markers and inheriting properties.
2344 Point and markers move forward to end up after the inserted text.
2346 If the current buffer is multibyte, unibyte strings are converted
2347 to multibyte for insertion (see `unibyte-char-to-multibyte').
2348 If the current buffer is unibyte, multibyte strings are converted
2349 to unibyte for insertion.
2351 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2352 (ptrdiff_t nargs, Lisp_Object *args)
2354 general_insert_function (insert_before_markers_and_inherit,
2355 insert_from_string_before_markers, 1,
2356 nargs, args);
2357 return Qnil;
2360 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
2361 doc: /* Insert COUNT copies of CHARACTER.
2362 Point, and before-insertion markers, are relocated as in the function `insert'.
2363 The optional third arg INHERIT, if non-nil, says to inherit text properties
2364 from adjoining text, if those properties are sticky. */)
2365 (Lisp_Object character, Lisp_Object count, Lisp_Object inherit)
2367 int i, stringlen;
2368 register ptrdiff_t n;
2369 int c, len;
2370 unsigned char str[MAX_MULTIBYTE_LENGTH];
2371 char string[4000];
2373 CHECK_CHARACTER (character);
2374 CHECK_NUMBER (count);
2375 c = XFASTINT (character);
2377 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2378 len = CHAR_STRING (c, str);
2379 else
2380 str[0] = c, len = 1;
2381 if (XINT (count) <= 0)
2382 return Qnil;
2383 if (BUF_BYTES_MAX / len < XINT (count))
2384 buffer_overflow ();
2385 n = XINT (count) * len;
2386 stringlen = min (n, sizeof string - sizeof string % len);
2387 for (i = 0; i < stringlen; i++)
2388 string[i] = str[i % len];
2389 while (n > stringlen)
2391 QUIT;
2392 if (!NILP (inherit))
2393 insert_and_inherit (string, stringlen);
2394 else
2395 insert (string, stringlen);
2396 n -= stringlen;
2398 if (!NILP (inherit))
2399 insert_and_inherit (string, n);
2400 else
2401 insert (string, n);
2402 return Qnil;
2405 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2406 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2407 Both arguments are required.
2408 BYTE is a number of the range 0..255.
2410 If BYTE is 128..255 and the current buffer is multibyte, the
2411 corresponding eight-bit character is inserted.
2413 Point, and before-insertion markers, are relocated as in the function `insert'.
2414 The optional third arg INHERIT, if non-nil, says to inherit text properties
2415 from adjoining text, if those properties are sticky. */)
2416 (Lisp_Object byte, Lisp_Object count, Lisp_Object inherit)
2418 CHECK_NUMBER (byte);
2419 if (XINT (byte) < 0 || XINT (byte) > 255)
2420 args_out_of_range_3 (byte, make_number (0), make_number (255));
2421 if (XINT (byte) >= 128
2422 && ! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2423 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2424 return Finsert_char (byte, count, inherit);
2428 /* Making strings from buffer contents. */
2430 /* Return a Lisp_String containing the text of the current buffer from
2431 START to END. If text properties are in use and the current buffer
2432 has properties in the range specified, the resulting string will also
2433 have them, if PROPS is nonzero.
2435 We don't want to use plain old make_string here, because it calls
2436 make_uninit_string, which can cause the buffer arena to be
2437 compacted. make_string has no way of knowing that the data has
2438 been moved, and thus copies the wrong data into the string. This
2439 doesn't effect most of the other users of make_string, so it should
2440 be left as is. But we should use this function when conjuring
2441 buffer substrings. */
2443 Lisp_Object
2444 make_buffer_string (ptrdiff_t start, ptrdiff_t end, int props)
2446 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
2447 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
2449 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2452 /* Return a Lisp_String containing the text of the current buffer from
2453 START / START_BYTE to END / END_BYTE.
2455 If text properties are in use and the current buffer
2456 has properties in the range specified, the resulting string will also
2457 have them, if PROPS is nonzero.
2459 We don't want to use plain old make_string here, because it calls
2460 make_uninit_string, which can cause the buffer arena to be
2461 compacted. make_string has no way of knowing that the data has
2462 been moved, and thus copies the wrong data into the string. This
2463 doesn't effect most of the other users of make_string, so it should
2464 be left as is. But we should use this function when conjuring
2465 buffer substrings. */
2467 Lisp_Object
2468 make_buffer_string_both (ptrdiff_t start, ptrdiff_t start_byte,
2469 ptrdiff_t end, ptrdiff_t end_byte, int props)
2471 Lisp_Object result, tem, tem1;
2473 if (start < GPT && GPT < end)
2474 move_gap (start);
2476 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2477 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2478 else
2479 result = make_uninit_string (end - start);
2480 memcpy (SDATA (result), BYTE_POS_ADDR (start_byte), end_byte - start_byte);
2482 /* If desired, update and copy the text properties. */
2483 if (props)
2485 update_buffer_properties (start, end);
2487 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2488 tem1 = Ftext_properties_at (make_number (start), Qnil);
2490 if (XINT (tem) != end || !NILP (tem1))
2491 copy_intervals_to_string (result, current_buffer, start,
2492 end - start);
2495 return result;
2498 /* Call Vbuffer_access_fontify_functions for the range START ... END
2499 in the current buffer, if necessary. */
2501 static void
2502 update_buffer_properties (ptrdiff_t start, ptrdiff_t end)
2504 /* If this buffer has some access functions,
2505 call them, specifying the range of the buffer being accessed. */
2506 if (!NILP (Vbuffer_access_fontify_functions))
2508 Lisp_Object args[3];
2509 Lisp_Object tem;
2511 args[0] = Qbuffer_access_fontify_functions;
2512 XSETINT (args[1], start);
2513 XSETINT (args[2], end);
2515 /* But don't call them if we can tell that the work
2516 has already been done. */
2517 if (!NILP (Vbuffer_access_fontified_property))
2519 tem = Ftext_property_any (args[1], args[2],
2520 Vbuffer_access_fontified_property,
2521 Qnil, Qnil);
2522 if (! NILP (tem))
2523 Frun_hook_with_args (3, args);
2525 else
2526 Frun_hook_with_args (3, args);
2530 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2531 doc: /* Return the contents of part of the current buffer as a string.
2532 The two arguments START and END are character positions;
2533 they can be in either order.
2534 The string returned is multibyte if the buffer is multibyte.
2536 This function copies the text properties of that part of the buffer
2537 into the result string; if you don't want the text properties,
2538 use `buffer-substring-no-properties' instead. */)
2539 (Lisp_Object start, Lisp_Object end)
2541 register ptrdiff_t b, e;
2543 validate_region (&start, &end);
2544 b = XINT (start);
2545 e = XINT (end);
2547 return make_buffer_string (b, e, 1);
2550 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2551 Sbuffer_substring_no_properties, 2, 2, 0,
2552 doc: /* Return the characters of part of the buffer, without the text properties.
2553 The two arguments START and END are character positions;
2554 they can be in either order. */)
2555 (Lisp_Object start, Lisp_Object end)
2557 register ptrdiff_t b, e;
2559 validate_region (&start, &end);
2560 b = XINT (start);
2561 e = XINT (end);
2563 return make_buffer_string (b, e, 0);
2566 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2567 doc: /* Return the contents of the current buffer as a string.
2568 If narrowing is in effect, this function returns only the visible part
2569 of the buffer. */)
2570 (void)
2572 return make_buffer_string (BEGV, ZV, 1);
2575 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2576 1, 3, 0,
2577 doc: /* Insert before point a substring of the contents of BUFFER.
2578 BUFFER may be a buffer or a buffer name.
2579 Arguments START and END are character positions specifying the substring.
2580 They default to the values of (point-min) and (point-max) in BUFFER. */)
2581 (Lisp_Object buffer, Lisp_Object start, Lisp_Object end)
2583 register EMACS_INT b, e, temp;
2584 register struct buffer *bp, *obuf;
2585 Lisp_Object buf;
2587 buf = Fget_buffer (buffer);
2588 if (NILP (buf))
2589 nsberror (buffer);
2590 bp = XBUFFER (buf);
2591 if (NILP (BVAR (bp, name)))
2592 error ("Selecting deleted buffer");
2594 if (NILP (start))
2595 b = BUF_BEGV (bp);
2596 else
2598 CHECK_NUMBER_COERCE_MARKER (start);
2599 b = XINT (start);
2601 if (NILP (end))
2602 e = BUF_ZV (bp);
2603 else
2605 CHECK_NUMBER_COERCE_MARKER (end);
2606 e = XINT (end);
2609 if (b > e)
2610 temp = b, b = e, e = temp;
2612 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2613 args_out_of_range (start, end);
2615 obuf = current_buffer;
2616 set_buffer_internal_1 (bp);
2617 update_buffer_properties (b, e);
2618 set_buffer_internal_1 (obuf);
2620 insert_from_buffer (bp, b, e - b, 0);
2621 return Qnil;
2624 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2625 6, 6, 0,
2626 doc: /* Compare two substrings of two buffers; return result as number.
2627 the value is -N if first string is less after N-1 chars,
2628 +N if first string is greater after N-1 chars, or 0 if strings match.
2629 Each substring is represented as three arguments: BUFFER, START and END.
2630 That makes six args in all, three for each substring.
2632 The value of `case-fold-search' in the current buffer
2633 determines whether case is significant or ignored. */)
2634 (Lisp_Object buffer1, Lisp_Object start1, Lisp_Object end1, Lisp_Object buffer2, Lisp_Object start2, Lisp_Object end2)
2636 register EMACS_INT begp1, endp1, begp2, endp2, temp;
2637 register struct buffer *bp1, *bp2;
2638 register Lisp_Object trt
2639 = (!NILP (BVAR (current_buffer, case_fold_search))
2640 ? BVAR (current_buffer, case_canon_table) : Qnil);
2641 ptrdiff_t chars = 0;
2642 ptrdiff_t i1, i2, i1_byte, i2_byte;
2644 /* Find the first buffer and its substring. */
2646 if (NILP (buffer1))
2647 bp1 = current_buffer;
2648 else
2650 Lisp_Object buf1;
2651 buf1 = Fget_buffer (buffer1);
2652 if (NILP (buf1))
2653 nsberror (buffer1);
2654 bp1 = XBUFFER (buf1);
2655 if (NILP (BVAR (bp1, name)))
2656 error ("Selecting deleted buffer");
2659 if (NILP (start1))
2660 begp1 = BUF_BEGV (bp1);
2661 else
2663 CHECK_NUMBER_COERCE_MARKER (start1);
2664 begp1 = XINT (start1);
2666 if (NILP (end1))
2667 endp1 = BUF_ZV (bp1);
2668 else
2670 CHECK_NUMBER_COERCE_MARKER (end1);
2671 endp1 = XINT (end1);
2674 if (begp1 > endp1)
2675 temp = begp1, begp1 = endp1, endp1 = temp;
2677 if (!(BUF_BEGV (bp1) <= begp1
2678 && begp1 <= endp1
2679 && endp1 <= BUF_ZV (bp1)))
2680 args_out_of_range (start1, end1);
2682 /* Likewise for second substring. */
2684 if (NILP (buffer2))
2685 bp2 = current_buffer;
2686 else
2688 Lisp_Object buf2;
2689 buf2 = Fget_buffer (buffer2);
2690 if (NILP (buf2))
2691 nsberror (buffer2);
2692 bp2 = XBUFFER (buf2);
2693 if (NILP (BVAR (bp2, name)))
2694 error ("Selecting deleted buffer");
2697 if (NILP (start2))
2698 begp2 = BUF_BEGV (bp2);
2699 else
2701 CHECK_NUMBER_COERCE_MARKER (start2);
2702 begp2 = XINT (start2);
2704 if (NILP (end2))
2705 endp2 = BUF_ZV (bp2);
2706 else
2708 CHECK_NUMBER_COERCE_MARKER (end2);
2709 endp2 = XINT (end2);
2712 if (begp2 > endp2)
2713 temp = begp2, begp2 = endp2, endp2 = temp;
2715 if (!(BUF_BEGV (bp2) <= begp2
2716 && begp2 <= endp2
2717 && endp2 <= BUF_ZV (bp2)))
2718 args_out_of_range (start2, end2);
2720 i1 = begp1;
2721 i2 = begp2;
2722 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2723 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2725 while (i1 < endp1 && i2 < endp2)
2727 /* When we find a mismatch, we must compare the
2728 characters, not just the bytes. */
2729 int c1, c2;
2731 QUIT;
2733 if (! NILP (BVAR (bp1, enable_multibyte_characters)))
2735 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2736 BUF_INC_POS (bp1, i1_byte);
2737 i1++;
2739 else
2741 c1 = BUF_FETCH_BYTE (bp1, i1);
2742 MAKE_CHAR_MULTIBYTE (c1);
2743 i1++;
2746 if (! NILP (BVAR (bp2, enable_multibyte_characters)))
2748 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2749 BUF_INC_POS (bp2, i2_byte);
2750 i2++;
2752 else
2754 c2 = BUF_FETCH_BYTE (bp2, i2);
2755 MAKE_CHAR_MULTIBYTE (c2);
2756 i2++;
2759 if (!NILP (trt))
2761 c1 = CHAR_TABLE_TRANSLATE (trt, c1);
2762 c2 = CHAR_TABLE_TRANSLATE (trt, c2);
2764 if (c1 < c2)
2765 return make_number (- 1 - chars);
2766 if (c1 > c2)
2767 return make_number (chars + 1);
2769 chars++;
2772 /* The strings match as far as they go.
2773 If one is shorter, that one is less. */
2774 if (chars < endp1 - begp1)
2775 return make_number (chars + 1);
2776 else if (chars < endp2 - begp2)
2777 return make_number (- chars - 1);
2779 /* Same length too => they are equal. */
2780 return make_number (0);
2783 static Lisp_Object
2784 subst_char_in_region_unwind (Lisp_Object arg)
2786 return BVAR (current_buffer, undo_list) = arg;
2789 static Lisp_Object
2790 subst_char_in_region_unwind_1 (Lisp_Object arg)
2792 return BVAR (current_buffer, filename) = arg;
2795 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2796 Ssubst_char_in_region, 4, 5, 0,
2797 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
2798 If optional arg NOUNDO is non-nil, don't record this change for undo
2799 and don't mark the buffer as really changed.
2800 Both characters must have the same length of multi-byte form. */)
2801 (Lisp_Object start, Lisp_Object end, Lisp_Object fromchar, Lisp_Object tochar, Lisp_Object noundo)
2803 register ptrdiff_t pos, pos_byte, stop, i, len, end_byte;
2804 /* Keep track of the first change in the buffer:
2805 if 0 we haven't found it yet.
2806 if < 0 we've found it and we've run the before-change-function.
2807 if > 0 we've actually performed it and the value is its position. */
2808 ptrdiff_t changed = 0;
2809 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2810 unsigned char *p;
2811 ptrdiff_t count = SPECPDL_INDEX ();
2812 #define COMBINING_NO 0
2813 #define COMBINING_BEFORE 1
2814 #define COMBINING_AFTER 2
2815 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2816 int maybe_byte_combining = COMBINING_NO;
2817 ptrdiff_t last_changed = 0;
2818 int multibyte_p = !NILP (BVAR (current_buffer, enable_multibyte_characters));
2819 int fromc, toc;
2821 restart:
2823 validate_region (&start, &end);
2824 CHECK_CHARACTER (fromchar);
2825 CHECK_CHARACTER (tochar);
2826 fromc = XFASTINT (fromchar);
2827 toc = XFASTINT (tochar);
2829 if (multibyte_p)
2831 len = CHAR_STRING (fromc, fromstr);
2832 if (CHAR_STRING (toc, tostr) != len)
2833 error ("Characters in `subst-char-in-region' have different byte-lengths");
2834 if (!ASCII_BYTE_P (*tostr))
2836 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2837 complete multibyte character, it may be combined with the
2838 after bytes. If it is in the range 0xA0..0xFF, it may be
2839 combined with the before and after bytes. */
2840 if (!CHAR_HEAD_P (*tostr))
2841 maybe_byte_combining = COMBINING_BOTH;
2842 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2843 maybe_byte_combining = COMBINING_AFTER;
2846 else
2848 len = 1;
2849 fromstr[0] = fromc;
2850 tostr[0] = toc;
2853 pos = XINT (start);
2854 pos_byte = CHAR_TO_BYTE (pos);
2855 stop = CHAR_TO_BYTE (XINT (end));
2856 end_byte = stop;
2858 /* If we don't want undo, turn off putting stuff on the list.
2859 That's faster than getting rid of things,
2860 and it prevents even the entry for a first change.
2861 Also inhibit locking the file. */
2862 if (!changed && !NILP (noundo))
2864 record_unwind_protect (subst_char_in_region_unwind,
2865 BVAR (current_buffer, undo_list));
2866 BVAR (current_buffer, undo_list) = Qt;
2867 /* Don't do file-locking. */
2868 record_unwind_protect (subst_char_in_region_unwind_1,
2869 BVAR (current_buffer, filename));
2870 BVAR (current_buffer, filename) = Qnil;
2873 if (pos_byte < GPT_BYTE)
2874 stop = min (stop, GPT_BYTE);
2875 while (1)
2877 ptrdiff_t pos_byte_next = pos_byte;
2879 if (pos_byte >= stop)
2881 if (pos_byte >= end_byte) break;
2882 stop = end_byte;
2884 p = BYTE_POS_ADDR (pos_byte);
2885 if (multibyte_p)
2886 INC_POS (pos_byte_next);
2887 else
2888 ++pos_byte_next;
2889 if (pos_byte_next - pos_byte == len
2890 && p[0] == fromstr[0]
2891 && (len == 1
2892 || (p[1] == fromstr[1]
2893 && (len == 2 || (p[2] == fromstr[2]
2894 && (len == 3 || p[3] == fromstr[3]))))))
2896 if (changed < 0)
2897 /* We've already seen this and run the before-change-function;
2898 this time we only need to record the actual position. */
2899 changed = pos;
2900 else if (!changed)
2902 changed = -1;
2903 modify_region (current_buffer, pos, XINT (end), 0);
2905 if (! NILP (noundo))
2907 if (MODIFF - 1 == SAVE_MODIFF)
2908 SAVE_MODIFF++;
2909 if (MODIFF - 1 == BUF_AUTOSAVE_MODIFF (current_buffer))
2910 BUF_AUTOSAVE_MODIFF (current_buffer)++;
2913 /* The before-change-function may have moved the gap
2914 or even modified the buffer so we should start over. */
2915 goto restart;
2918 /* Take care of the case where the new character
2919 combines with neighboring bytes. */
2920 if (maybe_byte_combining
2921 && (maybe_byte_combining == COMBINING_AFTER
2922 ? (pos_byte_next < Z_BYTE
2923 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2924 : ((pos_byte_next < Z_BYTE
2925 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2926 || (pos_byte > BEG_BYTE
2927 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2929 Lisp_Object tem, string;
2931 struct gcpro gcpro1;
2933 tem = BVAR (current_buffer, undo_list);
2934 GCPRO1 (tem);
2936 /* Make a multibyte string containing this single character. */
2937 string = make_multibyte_string ((char *) tostr, 1, len);
2938 /* replace_range is less efficient, because it moves the gap,
2939 but it handles combining correctly. */
2940 replace_range (pos, pos + 1, string,
2941 0, 0, 1);
2942 pos_byte_next = CHAR_TO_BYTE (pos);
2943 if (pos_byte_next > pos_byte)
2944 /* Before combining happened. We should not increment
2945 POS. So, to cancel the later increment of POS,
2946 decrease it now. */
2947 pos--;
2948 else
2949 INC_POS (pos_byte_next);
2951 if (! NILP (noundo))
2952 BVAR (current_buffer, undo_list) = tem;
2954 UNGCPRO;
2956 else
2958 if (NILP (noundo))
2959 record_change (pos, 1);
2960 for (i = 0; i < len; i++) *p++ = tostr[i];
2962 last_changed = pos + 1;
2964 pos_byte = pos_byte_next;
2965 pos++;
2968 if (changed > 0)
2970 signal_after_change (changed,
2971 last_changed - changed, last_changed - changed);
2972 update_compositions (changed, last_changed, CHECK_ALL);
2975 unbind_to (count, Qnil);
2976 return Qnil;
2980 static Lisp_Object check_translation (ptrdiff_t, ptrdiff_t, ptrdiff_t,
2981 Lisp_Object);
2983 /* Helper function for Ftranslate_region_internal.
2985 Check if a character sequence at POS (POS_BYTE) matches an element
2986 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
2987 element is found, return it. Otherwise return Qnil. */
2989 static Lisp_Object
2990 check_translation (ptrdiff_t pos, ptrdiff_t pos_byte, ptrdiff_t end,
2991 Lisp_Object val)
2993 int buf_size = 16, buf_used = 0;
2994 int *buf = alloca (sizeof (int) * buf_size);
2996 for (; CONSP (val); val = XCDR (val))
2998 Lisp_Object elt;
2999 ptrdiff_t len, i;
3001 elt = XCAR (val);
3002 if (! CONSP (elt))
3003 continue;
3004 elt = XCAR (elt);
3005 if (! VECTORP (elt))
3006 continue;
3007 len = ASIZE (elt);
3008 if (len <= end - pos)
3010 for (i = 0; i < len; i++)
3012 if (buf_used <= i)
3014 unsigned char *p = BYTE_POS_ADDR (pos_byte);
3015 int len1;
3017 if (buf_used == buf_size)
3019 int *newbuf;
3021 buf_size += 16;
3022 newbuf = alloca (sizeof (int) * buf_size);
3023 memcpy (newbuf, buf, sizeof (int) * buf_used);
3024 buf = newbuf;
3026 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len1);
3027 pos_byte += len1;
3029 if (XINT (AREF (elt, i)) != buf[i])
3030 break;
3032 if (i == len)
3033 return XCAR (val);
3036 return Qnil;
3040 DEFUN ("translate-region-internal", Ftranslate_region_internal,
3041 Stranslate_region_internal, 3, 3, 0,
3042 doc: /* Internal use only.
3043 From START to END, translate characters according to TABLE.
3044 TABLE is a string or a char-table; the Nth character in it is the
3045 mapping for the character with code N.
3046 It returns the number of characters changed. */)
3047 (Lisp_Object start, Lisp_Object end, register Lisp_Object table)
3049 register unsigned char *tt; /* Trans table. */
3050 register int nc; /* New character. */
3051 int cnt; /* Number of changes made. */
3052 ptrdiff_t size; /* Size of translate table. */
3053 ptrdiff_t pos, pos_byte, end_pos;
3054 int multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3055 int string_multibyte IF_LINT (= 0);
3057 validate_region (&start, &end);
3058 if (CHAR_TABLE_P (table))
3060 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3061 error ("Not a translation table");
3062 size = MAX_CHAR;
3063 tt = NULL;
3065 else
3067 CHECK_STRING (table);
3069 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3070 table = string_make_unibyte (table);
3071 string_multibyte = SCHARS (table) < SBYTES (table);
3072 size = SBYTES (table);
3073 tt = SDATA (table);
3076 pos = XINT (start);
3077 pos_byte = CHAR_TO_BYTE (pos);
3078 end_pos = XINT (end);
3079 modify_region (current_buffer, pos, end_pos, 0);
3081 cnt = 0;
3082 for (; pos < end_pos; )
3084 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
3085 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3086 int len, str_len;
3087 int oc;
3088 Lisp_Object val;
3090 if (multibyte)
3091 oc = STRING_CHAR_AND_LENGTH (p, len);
3092 else
3093 oc = *p, len = 1;
3094 if (oc < size)
3096 if (tt)
3098 /* Reload as signal_after_change in last iteration may GC. */
3099 tt = SDATA (table);
3100 if (string_multibyte)
3102 str = tt + string_char_to_byte (table, oc);
3103 nc = STRING_CHAR_AND_LENGTH (str, str_len);
3105 else
3107 nc = tt[oc];
3108 if (! ASCII_BYTE_P (nc) && multibyte)
3110 str_len = BYTE8_STRING (nc, buf);
3111 str = buf;
3113 else
3115 str_len = 1;
3116 str = tt + oc;
3120 else
3122 nc = oc;
3123 val = CHAR_TABLE_REF (table, oc);
3124 if (CHARACTERP (val))
3126 nc = XFASTINT (val);
3127 str_len = CHAR_STRING (nc, buf);
3128 str = buf;
3130 else if (VECTORP (val) || (CONSP (val)))
3132 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3133 where TO is TO-CHAR or [TO-CHAR ...]. */
3134 nc = -1;
3138 if (nc != oc && nc >= 0)
3140 /* Simple one char to one char translation. */
3141 if (len != str_len)
3143 Lisp_Object string;
3145 /* This is less efficient, because it moves the gap,
3146 but it should handle multibyte characters correctly. */
3147 string = make_multibyte_string ((char *) str, 1, str_len);
3148 replace_range (pos, pos + 1, string, 1, 0, 1);
3149 len = str_len;
3151 else
3153 record_change (pos, 1);
3154 while (str_len-- > 0)
3155 *p++ = *str++;
3156 signal_after_change (pos, 1, 1);
3157 update_compositions (pos, pos + 1, CHECK_BORDER);
3159 ++cnt;
3161 else if (nc < 0)
3163 Lisp_Object string;
3165 if (CONSP (val))
3167 val = check_translation (pos, pos_byte, end_pos, val);
3168 if (NILP (val))
3170 pos_byte += len;
3171 pos++;
3172 continue;
3174 /* VAL is ([FROM-CHAR ...] . TO). */
3175 len = ASIZE (XCAR (val));
3176 val = XCDR (val);
3178 else
3179 len = 1;
3181 if (VECTORP (val))
3183 string = Fconcat (1, &val);
3185 else
3187 string = Fmake_string (make_number (1), val);
3189 replace_range (pos, pos + len, string, 1, 0, 1);
3190 pos_byte += SBYTES (string);
3191 pos += SCHARS (string);
3192 cnt += SCHARS (string);
3193 end_pos += SCHARS (string) - len;
3194 continue;
3197 pos_byte += len;
3198 pos++;
3201 return make_number (cnt);
3204 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3205 doc: /* Delete the text between START and END.
3206 If called interactively, delete the region between point and mark.
3207 This command deletes buffer text without modifying the kill ring. */)
3208 (Lisp_Object start, Lisp_Object end)
3210 validate_region (&start, &end);
3211 del_range (XINT (start), XINT (end));
3212 return Qnil;
3215 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3216 Sdelete_and_extract_region, 2, 2, 0,
3217 doc: /* Delete the text between START and END and return it. */)
3218 (Lisp_Object start, Lisp_Object end)
3220 validate_region (&start, &end);
3221 if (XINT (start) == XINT (end))
3222 return empty_unibyte_string;
3223 return del_range_1 (XINT (start), XINT (end), 1, 1);
3226 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3227 doc: /* Remove restrictions (narrowing) from current buffer.
3228 This allows the buffer's full text to be seen and edited. */)
3229 (void)
3231 if (BEG != BEGV || Z != ZV)
3232 current_buffer->clip_changed = 1;
3233 BEGV = BEG;
3234 BEGV_BYTE = BEG_BYTE;
3235 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3236 /* Changing the buffer bounds invalidates any recorded current column. */
3237 invalidate_current_column ();
3238 return Qnil;
3241 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3242 doc: /* Restrict editing in this buffer to the current region.
3243 The rest of the text becomes temporarily invisible and untouchable
3244 but is not deleted; if you save the buffer in a file, the invisible
3245 text is included in the file. \\[widen] makes all visible again.
3246 See also `save-restriction'.
3248 When calling from a program, pass two arguments; positions (integers
3249 or markers) bounding the text that should remain visible. */)
3250 (register Lisp_Object start, Lisp_Object end)
3252 CHECK_NUMBER_COERCE_MARKER (start);
3253 CHECK_NUMBER_COERCE_MARKER (end);
3255 if (XINT (start) > XINT (end))
3257 Lisp_Object tem;
3258 tem = start; start = end; end = tem;
3261 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3262 args_out_of_range (start, end);
3264 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3265 current_buffer->clip_changed = 1;
3267 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3268 SET_BUF_ZV (current_buffer, XFASTINT (end));
3269 if (PT < XFASTINT (start))
3270 SET_PT (XFASTINT (start));
3271 if (PT > XFASTINT (end))
3272 SET_PT (XFASTINT (end));
3273 /* Changing the buffer bounds invalidates any recorded current column. */
3274 invalidate_current_column ();
3275 return Qnil;
3278 Lisp_Object
3279 save_restriction_save (void)
3281 if (BEGV == BEG && ZV == Z)
3282 /* The common case that the buffer isn't narrowed.
3283 We return just the buffer object, which save_restriction_restore
3284 recognizes as meaning `no restriction'. */
3285 return Fcurrent_buffer ();
3286 else
3287 /* We have to save a restriction, so return a pair of markers, one
3288 for the beginning and one for the end. */
3290 Lisp_Object beg, end;
3292 beg = buildmark (BEGV, BEGV_BYTE);
3293 end = buildmark (ZV, ZV_BYTE);
3295 /* END must move forward if text is inserted at its exact location. */
3296 XMARKER (end)->insertion_type = 1;
3298 return Fcons (beg, end);
3302 Lisp_Object
3303 save_restriction_restore (Lisp_Object data)
3305 struct buffer *cur = NULL;
3306 struct buffer *buf = (CONSP (data)
3307 ? XMARKER (XCAR (data))->buffer
3308 : XBUFFER (data));
3310 if (buf && buf != current_buffer && !NILP (BVAR (buf, pt_marker)))
3311 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3312 is the case if it is or has an indirect buffer), then make
3313 sure it is current before we update BEGV, so
3314 set_buffer_internal takes care of managing those markers. */
3315 cur = current_buffer;
3316 set_buffer_internal (buf);
3319 if (CONSP (data))
3320 /* A pair of marks bounding a saved restriction. */
3322 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3323 struct Lisp_Marker *end = XMARKER (XCDR (data));
3324 eassert (buf == end->buffer);
3326 if (buf /* Verify marker still points to a buffer. */
3327 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3328 /* The restriction has changed from the saved one, so restore
3329 the saved restriction. */
3331 ptrdiff_t pt = BUF_PT (buf);
3333 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3334 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3336 if (pt < beg->charpos || pt > end->charpos)
3337 /* The point is outside the new visible range, move it inside. */
3338 SET_BUF_PT_BOTH (buf,
3339 clip_to_bounds (beg->charpos, pt, end->charpos),
3340 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3341 end->bytepos));
3343 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3346 else
3347 /* A buffer, which means that there was no old restriction. */
3349 if (buf /* Verify marker still points to a buffer. */
3350 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3351 /* The buffer has been narrowed, get rid of the narrowing. */
3353 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3354 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3356 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3360 /* Changing the buffer bounds invalidates any recorded current column. */
3361 invalidate_current_column ();
3363 if (cur)
3364 set_buffer_internal (cur);
3366 return Qnil;
3369 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3370 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3371 The buffer's restrictions make parts of the beginning and end invisible.
3372 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3373 This special form, `save-restriction', saves the current buffer's restrictions
3374 when it is entered, and restores them when it is exited.
3375 So any `narrow-to-region' within BODY lasts only until the end of the form.
3376 The old restrictions settings are restored
3377 even in case of abnormal exit (throw or error).
3379 The value returned is the value of the last form in BODY.
3381 Note: if you are using both `save-excursion' and `save-restriction',
3382 use `save-excursion' outermost:
3383 (save-excursion (save-restriction ...))
3385 usage: (save-restriction &rest BODY) */)
3386 (Lisp_Object body)
3388 register Lisp_Object val;
3389 ptrdiff_t count = SPECPDL_INDEX ();
3391 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3392 val = Fprogn (body);
3393 return unbind_to (count, val);
3396 /* Buffer for the most recent text displayed by Fmessage_box. */
3397 static char *message_text;
3399 /* Allocated length of that buffer. */
3400 static ptrdiff_t message_length;
3402 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3403 doc: /* Display a message at the bottom of the screen.
3404 The message also goes into the `*Messages*' buffer.
3405 \(In keyboard macros, that's all it does.)
3406 Return the message.
3408 The first argument is a format control string, and the rest are data
3409 to be formatted under control of the string. See `format' for details.
3411 Note: Use (message "%s" VALUE) to print the value of expressions and
3412 variables to avoid accidentally interpreting `%' as format specifiers.
3414 If the first argument is nil or the empty string, the function clears
3415 any existing message; this lets the minibuffer contents show. See
3416 also `current-message'.
3418 usage: (message FORMAT-STRING &rest ARGS) */)
3419 (ptrdiff_t nargs, Lisp_Object *args)
3421 if (NILP (args[0])
3422 || (STRINGP (args[0])
3423 && SBYTES (args[0]) == 0))
3425 message (0);
3426 return args[0];
3428 else
3430 register Lisp_Object val;
3431 val = Fformat (nargs, args);
3432 message3 (val, SBYTES (val), STRING_MULTIBYTE (val));
3433 return val;
3437 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3438 doc: /* Display a message, in a dialog box if possible.
3439 If a dialog box is not available, use the echo area.
3440 The first argument is a format control string, and the rest are data
3441 to be formatted under control of the string. See `format' for details.
3443 If the first argument is nil or the empty string, clear any existing
3444 message; let the minibuffer contents show.
3446 usage: (message-box FORMAT-STRING &rest ARGS) */)
3447 (ptrdiff_t nargs, Lisp_Object *args)
3449 if (NILP (args[0]))
3451 message (0);
3452 return Qnil;
3454 else
3456 register Lisp_Object val;
3457 val = Fformat (nargs, args);
3458 #ifdef HAVE_MENUS
3459 /* The MS-DOS frames support popup menus even though they are
3460 not FRAME_WINDOW_P. */
3461 if (FRAME_WINDOW_P (XFRAME (selected_frame))
3462 || FRAME_MSDOS_P (XFRAME (selected_frame)))
3464 Lisp_Object pane, menu;
3465 struct gcpro gcpro1;
3466 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
3467 GCPRO1 (pane);
3468 menu = Fcons (val, pane);
3469 Fx_popup_dialog (Qt, menu, Qt);
3470 UNGCPRO;
3471 return val;
3473 #endif /* HAVE_MENUS */
3474 /* Copy the data so that it won't move when we GC. */
3475 if (SBYTES (val) > message_length)
3477 ptrdiff_t new_length = SBYTES (val) + 80;
3478 message_text = xrealloc (message_text, new_length);
3479 message_length = new_length;
3481 memcpy (message_text, SDATA (val), SBYTES (val));
3482 message2 (message_text, SBYTES (val),
3483 STRING_MULTIBYTE (val));
3484 return val;
3488 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3489 doc: /* Display a message in a dialog box or in the echo area.
3490 If this command was invoked with the mouse, use a dialog box if
3491 `use-dialog-box' is non-nil.
3492 Otherwise, use the echo area.
3493 The first argument is a format control string, and the rest are data
3494 to be formatted under control of the string. See `format' for details.
3496 If the first argument is nil or the empty string, clear any existing
3497 message; let the minibuffer contents show.
3499 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3500 (ptrdiff_t nargs, Lisp_Object *args)
3502 #ifdef HAVE_MENUS
3503 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3504 && use_dialog_box)
3505 return Fmessage_box (nargs, args);
3506 #endif
3507 return Fmessage (nargs, args);
3510 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3511 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3512 (void)
3514 return current_message ();
3518 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3519 doc: /* Return a copy of STRING with text properties added.
3520 First argument is the string to copy.
3521 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3522 properties to add to the result.
3523 usage: (propertize STRING &rest PROPERTIES) */)
3524 (ptrdiff_t nargs, Lisp_Object *args)
3526 Lisp_Object properties, string;
3527 struct gcpro gcpro1, gcpro2;
3528 ptrdiff_t i;
3530 /* Number of args must be odd. */
3531 if ((nargs & 1) == 0)
3532 error ("Wrong number of arguments");
3534 properties = string = Qnil;
3535 GCPRO2 (properties, string);
3537 /* First argument must be a string. */
3538 CHECK_STRING (args[0]);
3539 string = Fcopy_sequence (args[0]);
3541 for (i = 1; i < nargs; i += 2)
3542 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3544 Fadd_text_properties (make_number (0),
3545 make_number (SCHARS (string)),
3546 properties, string);
3547 RETURN_UNGCPRO (string);
3550 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3551 doc: /* Format a string out of a format-string and arguments.
3552 The first argument is a format control string.
3553 The other arguments are substituted into it to make the result, a string.
3555 The format control string may contain %-sequences meaning to substitute
3556 the next available argument:
3558 %s means print a string argument. Actually, prints any object, with `princ'.
3559 %d means print as number in decimal (%o octal, %x hex).
3560 %X is like %x, but uses upper case.
3561 %e means print a number in exponential notation.
3562 %f means print a number in decimal-point notation.
3563 %g means print a number in exponential notation
3564 or decimal-point notation, whichever uses fewer characters.
3565 %c means print a number as a single character.
3566 %S means print any object as an s-expression (using `prin1').
3568 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3569 Use %% to put a single % into the output.
3571 A %-sequence may contain optional flag, width, and precision
3572 specifiers, as follows:
3574 %<flags><width><precision>character
3576 where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3578 The + flag character inserts a + before any positive number, while a
3579 space inserts a space before any positive number; these flags only
3580 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3581 The # flag means to use an alternate display form for %o, %x, %X, %e,
3582 %f, and %g sequences. The - and 0 flags affect the width specifier,
3583 as described below.
3585 The width specifier supplies a lower limit for the length of the
3586 printed representation. The padding, if any, normally goes on the
3587 left, but it goes on the right if the - flag is present. The padding
3588 character is normally a space, but it is 0 if the 0 flag is present.
3589 The 0 flag is ignored if the - flag is present, or the format sequence
3590 is something other than %d, %e, %f, and %g.
3592 For %e, %f, and %g sequences, the number after the "." in the
3593 precision specifier says how many decimal places to show; if zero, the
3594 decimal point itself is omitted. For %s and %S, the precision
3595 specifier truncates the string to the given width.
3597 usage: (format STRING &rest OBJECTS) */)
3598 (ptrdiff_t nargs, Lisp_Object *args)
3600 ptrdiff_t n; /* The number of the next arg to substitute */
3601 char initial_buffer[4000];
3602 char *buf = initial_buffer;
3603 ptrdiff_t bufsize = sizeof initial_buffer;
3604 ptrdiff_t max_bufsize = STRING_BYTES_BOUND + 1;
3605 char *p;
3606 Lisp_Object buf_save_value IF_LINT (= {0});
3607 register char *format, *end, *format_start;
3608 ptrdiff_t formatlen, nchars;
3609 /* Nonzero if the format is multibyte. */
3610 int multibyte_format = 0;
3611 /* Nonzero if the output should be a multibyte string,
3612 which is true if any of the inputs is one. */
3613 int multibyte = 0;
3614 /* When we make a multibyte string, we must pay attention to the
3615 byte combining problem, i.e., a byte may be combined with a
3616 multibyte character of the previous string. This flag tells if we
3617 must consider such a situation or not. */
3618 int maybe_combine_byte;
3619 Lisp_Object val;
3620 int arg_intervals = 0;
3621 USE_SAFE_ALLOCA;
3623 /* discarded[I] is 1 if byte I of the format
3624 string was not copied into the output.
3625 It is 2 if byte I was not the first byte of its character. */
3626 char *discarded;
3628 /* Each element records, for one argument,
3629 the start and end bytepos in the output string,
3630 whether the argument has been converted to string (e.g., due to "%S"),
3631 and whether the argument is a string with intervals.
3632 info[0] is unused. Unused elements have -1 for start. */
3633 struct info
3635 ptrdiff_t start, end;
3636 int converted_to_string;
3637 int intervals;
3638 } *info = 0;
3640 /* It should not be necessary to GCPRO ARGS, because
3641 the caller in the interpreter should take care of that. */
3643 CHECK_STRING (args[0]);
3644 format_start = SSDATA (args[0]);
3645 formatlen = SBYTES (args[0]);
3647 /* Allocate the info and discarded tables. */
3649 ptrdiff_t i;
3650 if ((SIZE_MAX - formatlen) / sizeof (struct info) <= nargs)
3651 memory_full (SIZE_MAX);
3652 SAFE_ALLOCA (info, struct info *, (nargs + 1) * sizeof *info + formatlen);
3653 discarded = (char *) &info[nargs + 1];
3654 for (i = 0; i < nargs + 1; i++)
3656 info[i].start = -1;
3657 info[i].intervals = info[i].converted_to_string = 0;
3659 memset (discarded, 0, formatlen);
3662 /* Try to determine whether the result should be multibyte.
3663 This is not always right; sometimes the result needs to be multibyte
3664 because of an object that we will pass through prin1,
3665 and in that case, we won't know it here. */
3666 multibyte_format = STRING_MULTIBYTE (args[0]);
3667 multibyte = multibyte_format;
3668 for (n = 1; !multibyte && n < nargs; n++)
3669 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3670 multibyte = 1;
3672 /* If we start out planning a unibyte result,
3673 then discover it has to be multibyte, we jump back to retry. */
3674 retry:
3676 p = buf;
3677 nchars = 0;
3678 n = 0;
3680 /* Scan the format and store result in BUF. */
3681 format = format_start;
3682 end = format + formatlen;
3683 maybe_combine_byte = 0;
3685 while (format != end)
3687 /* The values of N and FORMAT when the loop body is entered. */
3688 ptrdiff_t n0 = n;
3689 char *format0 = format;
3691 /* Bytes needed to represent the output of this conversion. */
3692 ptrdiff_t convbytes;
3694 if (*format == '%')
3696 /* General format specifications look like
3698 '%' [flags] [field-width] [precision] format
3700 where
3702 flags ::= [-+0# ]+
3703 field-width ::= [0-9]+
3704 precision ::= '.' [0-9]*
3706 If a field-width is specified, it specifies to which width
3707 the output should be padded with blanks, if the output
3708 string is shorter than field-width.
3710 If precision is specified, it specifies the number of
3711 digits to print after the '.' for floats, or the max.
3712 number of chars to print from a string. */
3714 int minus_flag = 0;
3715 int plus_flag = 0;
3716 int space_flag = 0;
3717 int sharp_flag = 0;
3718 int zero_flag = 0;
3719 ptrdiff_t field_width;
3720 int precision_given;
3721 uintmax_t precision = UINTMAX_MAX;
3722 char *num_end;
3723 char conversion;
3725 while (1)
3727 switch (*++format)
3729 case '-': minus_flag = 1; continue;
3730 case '+': plus_flag = 1; continue;
3731 case ' ': space_flag = 1; continue;
3732 case '#': sharp_flag = 1; continue;
3733 case '0': zero_flag = 1; continue;
3735 break;
3738 /* Ignore flags when sprintf ignores them. */
3739 space_flag &= ~ plus_flag;
3740 zero_flag &= ~ minus_flag;
3743 uintmax_t w = strtoumax (format, &num_end, 10);
3744 if (max_bufsize <= w)
3745 string_overflow ();
3746 field_width = w;
3748 precision_given = *num_end == '.';
3749 if (precision_given)
3750 precision = strtoumax (num_end + 1, &num_end, 10);
3751 format = num_end;
3753 if (format == end)
3754 error ("Format string ends in middle of format specifier");
3756 memset (&discarded[format0 - format_start], 1, format - format0);
3757 conversion = *format;
3758 if (conversion == '%')
3759 goto copy_char;
3760 discarded[format - format_start] = 1;
3761 format++;
3763 ++n;
3764 if (! (n < nargs))
3765 error ("Not enough arguments for format string");
3767 /* For 'S', prin1 the argument, and then treat like 's'.
3768 For 's', princ any argument that is not a string or
3769 symbol. But don't do this conversion twice, which might
3770 happen after retrying. */
3771 if ((conversion == 'S'
3772 || (conversion == 's'
3773 && ! STRINGP (args[n]) && ! SYMBOLP (args[n]))))
3775 if (! info[n].converted_to_string)
3777 Lisp_Object noescape = conversion == 'S' ? Qnil : Qt;
3778 args[n] = Fprin1_to_string (args[n], noescape);
3779 info[n].converted_to_string = 1;
3780 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3782 multibyte = 1;
3783 goto retry;
3786 conversion = 's';
3788 else if (conversion == 'c')
3790 if (FLOATP (args[n]))
3792 double d = XFLOAT_DATA (args[n]);
3793 args[n] = make_number (FIXNUM_OVERFLOW_P (d) ? -1 : d);
3796 if (INTEGERP (args[n]) && ! ASCII_CHAR_P (XINT (args[n])))
3798 if (!multibyte)
3800 multibyte = 1;
3801 goto retry;
3803 args[n] = Fchar_to_string (args[n]);
3804 info[n].converted_to_string = 1;
3807 if (info[n].converted_to_string)
3808 conversion = 's';
3809 zero_flag = 0;
3812 if (SYMBOLP (args[n]))
3814 args[n] = SYMBOL_NAME (args[n]);
3815 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3817 multibyte = 1;
3818 goto retry;
3822 if (conversion == 's')
3824 /* handle case (precision[n] >= 0) */
3826 ptrdiff_t width, padding, nbytes;
3827 ptrdiff_t nchars_string;
3829 ptrdiff_t prec = -1;
3830 if (precision_given && precision <= TYPE_MAXIMUM (ptrdiff_t))
3831 prec = precision;
3833 /* lisp_string_width ignores a precision of 0, but GNU
3834 libc functions print 0 characters when the precision
3835 is 0. Imitate libc behavior here. Changing
3836 lisp_string_width is the right thing, and will be
3837 done, but meanwhile we work with it. */
3839 if (prec == 0)
3840 width = nchars_string = nbytes = 0;
3841 else
3843 ptrdiff_t nch, nby;
3844 width = lisp_string_width (args[n], prec, &nch, &nby);
3845 if (prec < 0)
3847 nchars_string = SCHARS (args[n]);
3848 nbytes = SBYTES (args[n]);
3850 else
3852 nchars_string = nch;
3853 nbytes = nby;
3857 convbytes = nbytes;
3858 if (convbytes && multibyte && ! STRING_MULTIBYTE (args[n]))
3859 convbytes = count_size_as_multibyte (SDATA (args[n]), nbytes);
3861 padding = width < field_width ? field_width - width : 0;
3863 if (max_bufsize - padding <= convbytes)
3864 string_overflow ();
3865 convbytes += padding;
3866 if (convbytes <= buf + bufsize - p)
3868 if (! minus_flag)
3870 memset (p, ' ', padding);
3871 p += padding;
3872 nchars += padding;
3875 if (p > buf
3876 && multibyte
3877 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3878 && STRING_MULTIBYTE (args[n])
3879 && !CHAR_HEAD_P (SREF (args[n], 0)))
3880 maybe_combine_byte = 1;
3882 p += copy_text (SDATA (args[n]), (unsigned char *) p,
3883 nbytes,
3884 STRING_MULTIBYTE (args[n]), multibyte);
3886 info[n].start = nchars;
3887 nchars += nchars_string;
3888 info[n].end = nchars;
3890 if (minus_flag)
3892 memset (p, ' ', padding);
3893 p += padding;
3894 nchars += padding;
3897 /* If this argument has text properties, record where
3898 in the result string it appears. */
3899 if (STRING_INTERVALS (args[n]))
3900 info[n].intervals = arg_intervals = 1;
3902 continue;
3905 else if (! (conversion == 'c' || conversion == 'd'
3906 || conversion == 'e' || conversion == 'f'
3907 || conversion == 'g' || conversion == 'i'
3908 || conversion == 'o' || conversion == 'x'
3909 || conversion == 'X'))
3910 error ("Invalid format operation %%%c",
3911 STRING_CHAR ((unsigned char *) format - 1));
3912 else if (! (INTEGERP (args[n]) || FLOATP (args[n])))
3913 error ("Format specifier doesn't match argument type");
3914 else
3916 enum
3918 /* Maximum precision for a %f conversion such that the
3919 trailing output digit might be nonzero. Any precision
3920 larger than this will not yield useful information. */
3921 USEFUL_PRECISION_MAX =
3922 ((1 - DBL_MIN_EXP)
3923 * (FLT_RADIX == 2 || FLT_RADIX == 10 ? 1
3924 : FLT_RADIX == 16 ? 4
3925 : -1)),
3927 /* Maximum number of bytes generated by any format, if
3928 precision is no more than USEFUL_PRECISION_MAX.
3929 On all practical hosts, %f is the worst case. */
3930 SPRINTF_BUFSIZE =
3931 sizeof "-." + (DBL_MAX_10_EXP + 1) + USEFUL_PRECISION_MAX,
3933 /* Length of pM (that is, of pMd without the
3934 trailing "d"). */
3935 pMlen = sizeof pMd - 2
3937 verify (0 < USEFUL_PRECISION_MAX);
3939 int prec;
3940 ptrdiff_t padding, sprintf_bytes;
3941 uintmax_t excess_precision, numwidth;
3942 uintmax_t leading_zeros = 0, trailing_zeros = 0;
3944 char sprintf_buf[SPRINTF_BUFSIZE];
3946 /* Copy of conversion specification, modified somewhat.
3947 At most three flags F can be specified at once. */
3948 char convspec[sizeof "%FFF.*d" + pMlen];
3950 /* Avoid undefined behavior in underlying sprintf. */
3951 if (conversion == 'd' || conversion == 'i')
3952 sharp_flag = 0;
3954 /* Create the copy of the conversion specification, with
3955 any width and precision removed, with ".*" inserted,
3956 and with pM inserted for integer formats. */
3958 char *f = convspec;
3959 *f++ = '%';
3960 *f = '-'; f += minus_flag;
3961 *f = '+'; f += plus_flag;
3962 *f = ' '; f += space_flag;
3963 *f = '#'; f += sharp_flag;
3964 *f = '0'; f += zero_flag;
3965 *f++ = '.';
3966 *f++ = '*';
3967 if (conversion == 'd' || conversion == 'i'
3968 || conversion == 'o' || conversion == 'x'
3969 || conversion == 'X')
3971 memcpy (f, pMd, pMlen);
3972 f += pMlen;
3973 zero_flag &= ~ precision_given;
3975 *f++ = conversion;
3976 *f = '\0';
3979 prec = -1;
3980 if (precision_given)
3981 prec = min (precision, USEFUL_PRECISION_MAX);
3983 /* Use sprintf to format this number into sprintf_buf. Omit
3984 padding and excess precision, though, because sprintf limits
3985 output length to INT_MAX.
3987 There are four types of conversion: double, unsigned
3988 char (passed as int), wide signed int, and wide
3989 unsigned int. Treat them separately because the
3990 sprintf ABI is sensitive to which type is passed. Be
3991 careful about integer overflow, NaNs, infinities, and
3992 conversions; for example, the min and max macros are
3993 not suitable here. */
3994 if (conversion == 'e' || conversion == 'f' || conversion == 'g')
3996 double x = (INTEGERP (args[n])
3997 ? XINT (args[n])
3998 : XFLOAT_DATA (args[n]));
3999 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4001 else if (conversion == 'c')
4003 /* Don't use sprintf here, as it might mishandle prec. */
4004 sprintf_buf[0] = XINT (args[n]);
4005 sprintf_bytes = prec != 0;
4007 else if (conversion == 'd')
4009 /* For float, maybe we should use "%1.0f"
4010 instead so it also works for values outside
4011 the integer range. */
4012 printmax_t x;
4013 if (INTEGERP (args[n]))
4014 x = XINT (args[n]);
4015 else
4017 double d = XFLOAT_DATA (args[n]);
4018 if (d < 0)
4020 x = TYPE_MINIMUM (printmax_t);
4021 if (x < d)
4022 x = d;
4024 else
4026 x = TYPE_MAXIMUM (printmax_t);
4027 if (d < x)
4028 x = d;
4031 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4033 else
4035 /* Don't sign-extend for octal or hex printing. */
4036 uprintmax_t x;
4037 if (INTEGERP (args[n]))
4038 x = XUINT (args[n]);
4039 else
4041 double d = XFLOAT_DATA (args[n]);
4042 if (d < 0)
4043 x = 0;
4044 else
4046 x = TYPE_MAXIMUM (uprintmax_t);
4047 if (d < x)
4048 x = d;
4051 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4054 /* Now the length of the formatted item is known, except it omits
4055 padding and excess precision. Deal with excess precision
4056 first. This happens only when the format specifies
4057 ridiculously large precision. */
4058 excess_precision = precision - prec;
4059 if (excess_precision)
4061 if (conversion == 'e' || conversion == 'f'
4062 || conversion == 'g')
4064 if ((conversion == 'g' && ! sharp_flag)
4065 || ! ('0' <= sprintf_buf[sprintf_bytes - 1]
4066 && sprintf_buf[sprintf_bytes - 1] <= '9'))
4067 excess_precision = 0;
4068 else
4070 if (conversion == 'g')
4072 char *dot = strchr (sprintf_buf, '.');
4073 if (!dot)
4074 excess_precision = 0;
4077 trailing_zeros = excess_precision;
4079 else
4080 leading_zeros = excess_precision;
4083 /* Compute the total bytes needed for this item, including
4084 excess precision and padding. */
4085 numwidth = sprintf_bytes + excess_precision;
4086 padding = numwidth < field_width ? field_width - numwidth : 0;
4087 if (max_bufsize - sprintf_bytes <= excess_precision
4088 || max_bufsize - padding <= numwidth)
4089 string_overflow ();
4090 convbytes = numwidth + padding;
4092 if (convbytes <= buf + bufsize - p)
4094 /* Copy the formatted item from sprintf_buf into buf,
4095 inserting padding and excess-precision zeros. */
4097 char *src = sprintf_buf;
4098 char src0 = src[0];
4099 int exponent_bytes = 0;
4100 int signedp = src0 == '-' || src0 == '+' || src0 == ' ';
4101 int significand_bytes;
4102 if (zero_flag
4103 && ((src[signedp] >= '0' && src[signedp] <= '9')
4104 || (src[signedp] >= 'a' && src[signedp] <= 'f')
4105 || (src[signedp] >= 'A' && src[signedp] <= 'F')))
4107 leading_zeros += padding;
4108 padding = 0;
4111 if (excess_precision
4112 && (conversion == 'e' || conversion == 'g'))
4114 char *e = strchr (src, 'e');
4115 if (e)
4116 exponent_bytes = src + sprintf_bytes - e;
4119 if (! minus_flag)
4121 memset (p, ' ', padding);
4122 p += padding;
4123 nchars += padding;
4126 *p = src0;
4127 src += signedp;
4128 p += signedp;
4129 memset (p, '0', leading_zeros);
4130 p += leading_zeros;
4131 significand_bytes = sprintf_bytes - signedp - exponent_bytes;
4132 memcpy (p, src, significand_bytes);
4133 p += significand_bytes;
4134 src += significand_bytes;
4135 memset (p, '0', trailing_zeros);
4136 p += trailing_zeros;
4137 memcpy (p, src, exponent_bytes);
4138 p += exponent_bytes;
4140 info[n].start = nchars;
4141 nchars += leading_zeros + sprintf_bytes + trailing_zeros;
4142 info[n].end = nchars;
4144 if (minus_flag)
4146 memset (p, ' ', padding);
4147 p += padding;
4148 nchars += padding;
4151 continue;
4155 else
4156 copy_char:
4158 /* Copy a single character from format to buf. */
4160 char *src = format;
4161 unsigned char str[MAX_MULTIBYTE_LENGTH];
4163 if (multibyte_format)
4165 /* Copy a whole multibyte character. */
4166 if (p > buf
4167 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4168 && !CHAR_HEAD_P (*format))
4169 maybe_combine_byte = 1;
4172 format++;
4173 while (! CHAR_HEAD_P (*format));
4175 convbytes = format - src;
4176 memset (&discarded[src + 1 - format_start], 2, convbytes - 1);
4178 else
4180 unsigned char uc = *format++;
4181 if (! multibyte || ASCII_BYTE_P (uc))
4182 convbytes = 1;
4183 else
4185 int c = BYTE8_TO_CHAR (uc);
4186 convbytes = CHAR_STRING (c, str);
4187 src = (char *) str;
4191 if (convbytes <= buf + bufsize - p)
4193 memcpy (p, src, convbytes);
4194 p += convbytes;
4195 nchars++;
4196 continue;
4200 /* There wasn't enough room to store this conversion or single
4201 character. CONVBYTES says how much room is needed. Allocate
4202 enough room (and then some) and do it again. */
4204 ptrdiff_t used = p - buf;
4206 if (max_bufsize - used < convbytes)
4207 string_overflow ();
4208 bufsize = used + convbytes;
4209 bufsize = bufsize < max_bufsize / 2 ? bufsize * 2 : max_bufsize;
4211 if (buf == initial_buffer)
4213 buf = xmalloc (bufsize);
4214 sa_must_free = 1;
4215 buf_save_value = make_save_value (buf, 0);
4216 record_unwind_protect (safe_alloca_unwind, buf_save_value);
4217 memcpy (buf, initial_buffer, used);
4219 else
4220 XSAVE_VALUE (buf_save_value)->pointer = buf = xrealloc (buf, bufsize);
4222 p = buf + used;
4225 format = format0;
4226 n = n0;
4229 if (bufsize < p - buf)
4230 abort ();
4232 if (maybe_combine_byte)
4233 nchars = multibyte_chars_in_text ((unsigned char *) buf, p - buf);
4234 val = make_specified_string (buf, nchars, p - buf, multibyte);
4236 /* If we allocated BUF with malloc, free it too. */
4237 SAFE_FREE ();
4239 /* If the format string has text properties, or any of the string
4240 arguments has text properties, set up text properties of the
4241 result string. */
4243 if (STRING_INTERVALS (args[0]) || arg_intervals)
4245 Lisp_Object len, new_len, props;
4246 struct gcpro gcpro1;
4248 /* Add text properties from the format string. */
4249 len = make_number (SCHARS (args[0]));
4250 props = text_property_list (args[0], make_number (0), len, Qnil);
4251 GCPRO1 (props);
4253 if (CONSP (props))
4255 ptrdiff_t bytepos = 0, position = 0, translated = 0;
4256 ptrdiff_t argn = 1;
4257 Lisp_Object list;
4259 /* Adjust the bounds of each text property
4260 to the proper start and end in the output string. */
4262 /* Put the positions in PROPS in increasing order, so that
4263 we can do (effectively) one scan through the position
4264 space of the format string. */
4265 props = Fnreverse (props);
4267 /* BYTEPOS is the byte position in the format string,
4268 POSITION is the untranslated char position in it,
4269 TRANSLATED is the translated char position in BUF,
4270 and ARGN is the number of the next arg we will come to. */
4271 for (list = props; CONSP (list); list = XCDR (list))
4273 Lisp_Object item;
4274 ptrdiff_t pos;
4276 item = XCAR (list);
4278 /* First adjust the property start position. */
4279 pos = XINT (XCAR (item));
4281 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4282 up to this position. */
4283 for (; position < pos; bytepos++)
4285 if (! discarded[bytepos])
4286 position++, translated++;
4287 else if (discarded[bytepos] == 1)
4289 position++;
4290 if (translated == info[argn].start)
4292 translated += info[argn].end - info[argn].start;
4293 argn++;
4298 XSETCAR (item, make_number (translated));
4300 /* Likewise adjust the property end position. */
4301 pos = XINT (XCAR (XCDR (item)));
4303 for (; position < pos; bytepos++)
4305 if (! discarded[bytepos])
4306 position++, translated++;
4307 else if (discarded[bytepos] == 1)
4309 position++;
4310 if (translated == info[argn].start)
4312 translated += info[argn].end - info[argn].start;
4313 argn++;
4318 XSETCAR (XCDR (item), make_number (translated));
4321 add_text_properties_from_list (val, props, make_number (0));
4324 /* Add text properties from arguments. */
4325 if (arg_intervals)
4326 for (n = 1; n < nargs; ++n)
4327 if (info[n].intervals)
4329 len = make_number (SCHARS (args[n]));
4330 new_len = make_number (info[n].end - info[n].start);
4331 props = text_property_list (args[n], make_number (0), len, Qnil);
4332 props = extend_property_ranges (props, new_len);
4333 /* If successive arguments have properties, be sure that
4334 the value of `composition' property be the copy. */
4335 if (n > 1 && info[n - 1].end)
4336 make_composition_value_copy (props);
4337 add_text_properties_from_list (val, props,
4338 make_number (info[n].start));
4341 UNGCPRO;
4344 return val;
4347 Lisp_Object
4348 format2 (const char *string1, Lisp_Object arg0, Lisp_Object arg1)
4350 Lisp_Object args[3];
4351 args[0] = build_string (string1);
4352 args[1] = arg0;
4353 args[2] = arg1;
4354 return Fformat (3, args);
4357 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4358 doc: /* Return t if two characters match, optionally ignoring case.
4359 Both arguments must be characters (i.e. integers).
4360 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4361 (register Lisp_Object c1, Lisp_Object c2)
4363 int i1, i2;
4364 /* Check they're chars, not just integers, otherwise we could get array
4365 bounds violations in downcase. */
4366 CHECK_CHARACTER (c1);
4367 CHECK_CHARACTER (c2);
4369 if (XINT (c1) == XINT (c2))
4370 return Qt;
4371 if (NILP (BVAR (current_buffer, case_fold_search)))
4372 return Qnil;
4374 i1 = XFASTINT (c1);
4375 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
4376 && ! ASCII_CHAR_P (i1))
4378 MAKE_CHAR_MULTIBYTE (i1);
4380 i2 = XFASTINT (c2);
4381 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
4382 && ! ASCII_CHAR_P (i2))
4384 MAKE_CHAR_MULTIBYTE (i2);
4386 return (downcase (i1) == downcase (i2) ? Qt : Qnil);
4389 /* Transpose the markers in two regions of the current buffer, and
4390 adjust the ones between them if necessary (i.e.: if the regions
4391 differ in size).
4393 START1, END1 are the character positions of the first region.
4394 START1_BYTE, END1_BYTE are the byte positions.
4395 START2, END2 are the character positions of the second region.
4396 START2_BYTE, END2_BYTE are the byte positions.
4398 Traverses the entire marker list of the buffer to do so, adding an
4399 appropriate amount to some, subtracting from some, and leaving the
4400 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4402 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4404 static void
4405 transpose_markers (ptrdiff_t start1, ptrdiff_t end1,
4406 ptrdiff_t start2, ptrdiff_t end2,
4407 ptrdiff_t start1_byte, ptrdiff_t end1_byte,
4408 ptrdiff_t start2_byte, ptrdiff_t end2_byte)
4410 register ptrdiff_t amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4411 register struct Lisp_Marker *marker;
4413 /* Update point as if it were a marker. */
4414 if (PT < start1)
4416 else if (PT < end1)
4417 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4418 PT_BYTE + (end2_byte - end1_byte));
4419 else if (PT < start2)
4420 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4421 (PT_BYTE + (end2_byte - start2_byte)
4422 - (end1_byte - start1_byte)));
4423 else if (PT < end2)
4424 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4425 PT_BYTE - (start2_byte - start1_byte));
4427 /* We used to adjust the endpoints here to account for the gap, but that
4428 isn't good enough. Even if we assume the caller has tried to move the
4429 gap out of our way, it might still be at start1 exactly, for example;
4430 and that places it `inside' the interval, for our purposes. The amount
4431 of adjustment is nontrivial if there's a `denormalized' marker whose
4432 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4433 the dirty work to Fmarker_position, below. */
4435 /* The difference between the region's lengths */
4436 diff = (end2 - start2) - (end1 - start1);
4437 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4439 /* For shifting each marker in a region by the length of the other
4440 region plus the distance between the regions. */
4441 amt1 = (end2 - start2) + (start2 - end1);
4442 amt2 = (end1 - start1) + (start2 - end1);
4443 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4444 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4446 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4448 mpos = marker->bytepos;
4449 if (mpos >= start1_byte && mpos < end2_byte)
4451 if (mpos < end1_byte)
4452 mpos += amt1_byte;
4453 else if (mpos < start2_byte)
4454 mpos += diff_byte;
4455 else
4456 mpos -= amt2_byte;
4457 marker->bytepos = mpos;
4459 mpos = marker->charpos;
4460 if (mpos >= start1 && mpos < end2)
4462 if (mpos < end1)
4463 mpos += amt1;
4464 else if (mpos < start2)
4465 mpos += diff;
4466 else
4467 mpos -= amt2;
4469 marker->charpos = mpos;
4473 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4474 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4475 The regions should not be overlapping, because the size of the buffer is
4476 never changed in a transposition.
4478 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4479 any markers that happen to be located in the regions.
4481 Transposing beyond buffer boundaries is an error. */)
4482 (Lisp_Object startr1, Lisp_Object endr1, Lisp_Object startr2, Lisp_Object endr2, Lisp_Object leave_markers)
4484 register ptrdiff_t start1, end1, start2, end2;
4485 ptrdiff_t start1_byte, start2_byte, len1_byte, len2_byte;
4486 ptrdiff_t gap, len1, len_mid, len2;
4487 unsigned char *start1_addr, *start2_addr, *temp;
4489 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4490 Lisp_Object buf;
4492 XSETBUFFER (buf, current_buffer);
4493 cur_intv = BUF_INTERVALS (current_buffer);
4495 validate_region (&startr1, &endr1);
4496 validate_region (&startr2, &endr2);
4498 start1 = XFASTINT (startr1);
4499 end1 = XFASTINT (endr1);
4500 start2 = XFASTINT (startr2);
4501 end2 = XFASTINT (endr2);
4502 gap = GPT;
4504 /* Swap the regions if they're reversed. */
4505 if (start2 < end1)
4507 register ptrdiff_t glumph = start1;
4508 start1 = start2;
4509 start2 = glumph;
4510 glumph = end1;
4511 end1 = end2;
4512 end2 = glumph;
4515 len1 = end1 - start1;
4516 len2 = end2 - start2;
4518 if (start2 < end1)
4519 error ("Transposed regions overlap");
4520 /* Nothing to change for adjacent regions with one being empty */
4521 else if ((start1 == end1 || start2 == end2) && end1 == start2)
4522 return Qnil;
4524 /* The possibilities are:
4525 1. Adjacent (contiguous) regions, or separate but equal regions
4526 (no, really equal, in this case!), or
4527 2. Separate regions of unequal size.
4529 The worst case is usually No. 2. It means that (aside from
4530 potential need for getting the gap out of the way), there also
4531 needs to be a shifting of the text between the two regions. So
4532 if they are spread far apart, we are that much slower... sigh. */
4534 /* It must be pointed out that the really studly thing to do would
4535 be not to move the gap at all, but to leave it in place and work
4536 around it if necessary. This would be extremely efficient,
4537 especially considering that people are likely to do
4538 transpositions near where they are working interactively, which
4539 is exactly where the gap would be found. However, such code
4540 would be much harder to write and to read. So, if you are
4541 reading this comment and are feeling squirrely, by all means have
4542 a go! I just didn't feel like doing it, so I will simply move
4543 the gap the minimum distance to get it out of the way, and then
4544 deal with an unbroken array. */
4546 /* Make sure the gap won't interfere, by moving it out of the text
4547 we will operate on. */
4548 if (start1 < gap && gap < end2)
4550 if (gap - start1 < end2 - gap)
4551 move_gap (start1);
4552 else
4553 move_gap (end2);
4556 start1_byte = CHAR_TO_BYTE (start1);
4557 start2_byte = CHAR_TO_BYTE (start2);
4558 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4559 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
4561 #ifdef BYTE_COMBINING_DEBUG
4562 if (end1 == start2)
4564 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4565 len2_byte, start1, start1_byte)
4566 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4567 len1_byte, end2, start2_byte + len2_byte)
4568 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4569 len1_byte, end2, start2_byte + len2_byte))
4570 abort ();
4572 else
4574 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4575 len2_byte, start1, start1_byte)
4576 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4577 len1_byte, start2, start2_byte)
4578 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4579 len2_byte, end1, start1_byte + len1_byte)
4580 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4581 len1_byte, end2, start2_byte + len2_byte))
4582 abort ();
4584 #endif
4586 /* Hmmm... how about checking to see if the gap is large
4587 enough to use as the temporary storage? That would avoid an
4588 allocation... interesting. Later, don't fool with it now. */
4590 /* Working without memmove, for portability (sigh), so must be
4591 careful of overlapping subsections of the array... */
4593 if (end1 == start2) /* adjacent regions */
4595 modify_region (current_buffer, start1, end2, 0);
4596 record_change (start1, len1 + len2);
4598 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4599 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4600 /* Don't use Fset_text_properties: that can cause GC, which can
4601 clobber objects stored in the tmp_intervals. */
4602 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4603 if (!NULL_INTERVAL_P (tmp_interval3))
4604 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4606 /* First region smaller than second. */
4607 if (len1_byte < len2_byte)
4609 USE_SAFE_ALLOCA;
4611 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4613 /* Don't precompute these addresses. We have to compute them
4614 at the last minute, because the relocating allocator might
4615 have moved the buffer around during the xmalloc. */
4616 start1_addr = BYTE_POS_ADDR (start1_byte);
4617 start2_addr = BYTE_POS_ADDR (start2_byte);
4619 memcpy (temp, start2_addr, len2_byte);
4620 memcpy (start1_addr + len2_byte, start1_addr, len1_byte);
4621 memcpy (start1_addr, temp, len2_byte);
4622 SAFE_FREE ();
4624 else
4625 /* First region not smaller than second. */
4627 USE_SAFE_ALLOCA;
4629 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4630 start1_addr = BYTE_POS_ADDR (start1_byte);
4631 start2_addr = BYTE_POS_ADDR (start2_byte);
4632 memcpy (temp, start1_addr, len1_byte);
4633 memcpy (start1_addr, start2_addr, len2_byte);
4634 memcpy (start1_addr + len2_byte, temp, len1_byte);
4635 SAFE_FREE ();
4637 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4638 len1, current_buffer, 0);
4639 graft_intervals_into_buffer (tmp_interval2, start1,
4640 len2, current_buffer, 0);
4641 update_compositions (start1, start1 + len2, CHECK_BORDER);
4642 update_compositions (start1 + len2, end2, CHECK_TAIL);
4644 /* Non-adjacent regions, because end1 != start2, bleagh... */
4645 else
4647 len_mid = start2_byte - (start1_byte + len1_byte);
4649 if (len1_byte == len2_byte)
4650 /* Regions are same size, though, how nice. */
4652 USE_SAFE_ALLOCA;
4654 modify_region (current_buffer, start1, end1, 0);
4655 modify_region (current_buffer, start2, end2, 0);
4656 record_change (start1, len1);
4657 record_change (start2, len2);
4658 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4659 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4661 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4662 if (!NULL_INTERVAL_P (tmp_interval3))
4663 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4665 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4666 if (!NULL_INTERVAL_P (tmp_interval3))
4667 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
4669 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4670 start1_addr = BYTE_POS_ADDR (start1_byte);
4671 start2_addr = BYTE_POS_ADDR (start2_byte);
4672 memcpy (temp, start1_addr, len1_byte);
4673 memcpy (start1_addr, start2_addr, len2_byte);
4674 memcpy (start2_addr, temp, len1_byte);
4675 SAFE_FREE ();
4677 graft_intervals_into_buffer (tmp_interval1, start2,
4678 len1, current_buffer, 0);
4679 graft_intervals_into_buffer (tmp_interval2, start1,
4680 len2, current_buffer, 0);
4683 else if (len1_byte < len2_byte) /* Second region larger than first */
4684 /* Non-adjacent & unequal size, area between must also be shifted. */
4686 USE_SAFE_ALLOCA;
4688 modify_region (current_buffer, start1, end2, 0);
4689 record_change (start1, (end2 - start1));
4690 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4691 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4692 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4694 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4695 if (!NULL_INTERVAL_P (tmp_interval3))
4696 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4698 /* holds region 2 */
4699 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4700 start1_addr = BYTE_POS_ADDR (start1_byte);
4701 start2_addr = BYTE_POS_ADDR (start2_byte);
4702 memcpy (temp, start2_addr, len2_byte);
4703 memcpy (start1_addr + len_mid + len2_byte, start1_addr, len1_byte);
4704 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4705 memcpy (start1_addr, temp, len2_byte);
4706 SAFE_FREE ();
4708 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4709 len1, current_buffer, 0);
4710 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4711 len_mid, current_buffer, 0);
4712 graft_intervals_into_buffer (tmp_interval2, start1,
4713 len2, current_buffer, 0);
4715 else
4716 /* Second region smaller than first. */
4718 USE_SAFE_ALLOCA;
4720 record_change (start1, (end2 - start1));
4721 modify_region (current_buffer, start1, end2, 0);
4723 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4724 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4725 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4727 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4728 if (!NULL_INTERVAL_P (tmp_interval3))
4729 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4731 /* holds region 1 */
4732 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4733 start1_addr = BYTE_POS_ADDR (start1_byte);
4734 start2_addr = BYTE_POS_ADDR (start2_byte);
4735 memcpy (temp, start1_addr, len1_byte);
4736 memcpy (start1_addr, start2_addr, len2_byte);
4737 memcpy (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4738 memcpy (start1_addr + len2_byte + len_mid, temp, len1_byte);
4739 SAFE_FREE ();
4741 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4742 len1, current_buffer, 0);
4743 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4744 len_mid, current_buffer, 0);
4745 graft_intervals_into_buffer (tmp_interval2, start1,
4746 len2, current_buffer, 0);
4749 update_compositions (start1, start1 + len2, CHECK_BORDER);
4750 update_compositions (end2 - len1, end2, CHECK_BORDER);
4753 /* When doing multiple transpositions, it might be nice
4754 to optimize this. Perhaps the markers in any one buffer
4755 should be organized in some sorted data tree. */
4756 if (NILP (leave_markers))
4758 transpose_markers (start1, end1, start2, end2,
4759 start1_byte, start1_byte + len1_byte,
4760 start2_byte, start2_byte + len2_byte);
4761 fix_start_end_in_overlays (start1, end2);
4764 signal_after_change (start1, end2 - start1, end2 - start1);
4765 return Qnil;
4769 void
4770 syms_of_editfns (void)
4772 environbuf = 0;
4773 initial_tz = 0;
4775 DEFSYM (Qbuffer_access_fontify_functions, "buffer-access-fontify-functions");
4777 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion,
4778 doc: /* Non-nil means text motion commands don't notice fields. */);
4779 Vinhibit_field_text_motion = Qnil;
4781 DEFVAR_LISP ("buffer-access-fontify-functions",
4782 Vbuffer_access_fontify_functions,
4783 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4784 Each function is called with two arguments which specify the range
4785 of the buffer being accessed. */);
4786 Vbuffer_access_fontify_functions = Qnil;
4789 Lisp_Object obuf;
4790 obuf = Fcurrent_buffer ();
4791 /* Do this here, because init_buffer_once is too early--it won't work. */
4792 Fset_buffer (Vprin1_to_string_buffer);
4793 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4794 Fset (Fmake_local_variable (intern_c_string ("buffer-access-fontify-functions")),
4795 Qnil);
4796 Fset_buffer (obuf);
4799 DEFVAR_LISP ("buffer-access-fontified-property",
4800 Vbuffer_access_fontified_property,
4801 doc: /* Property which (if non-nil) indicates text has been fontified.
4802 `buffer-substring' need not call the `buffer-access-fontify-functions'
4803 functions if all the text being accessed has this property. */);
4804 Vbuffer_access_fontified_property = Qnil;
4806 DEFVAR_LISP ("system-name", Vsystem_name,
4807 doc: /* The host name of the machine Emacs is running on. */);
4809 DEFVAR_LISP ("user-full-name", Vuser_full_name,
4810 doc: /* The full name of the user logged in. */);
4812 DEFVAR_LISP ("user-login-name", Vuser_login_name,
4813 doc: /* The user's name, taken from environment variables if possible. */);
4815 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name,
4816 doc: /* The user's name, based upon the real uid only. */);
4818 DEFVAR_LISP ("operating-system-release", Voperating_system_release,
4819 doc: /* The release of the operating system Emacs is running on. */);
4821 defsubr (&Spropertize);
4822 defsubr (&Schar_equal);
4823 defsubr (&Sgoto_char);
4824 defsubr (&Sstring_to_char);
4825 defsubr (&Schar_to_string);
4826 defsubr (&Sbyte_to_string);
4827 defsubr (&Sbuffer_substring);
4828 defsubr (&Sbuffer_substring_no_properties);
4829 defsubr (&Sbuffer_string);
4831 defsubr (&Spoint_marker);
4832 defsubr (&Smark_marker);
4833 defsubr (&Spoint);
4834 defsubr (&Sregion_beginning);
4835 defsubr (&Sregion_end);
4837 DEFSYM (Qfield, "field");
4838 DEFSYM (Qboundary, "boundary");
4839 defsubr (&Sfield_beginning);
4840 defsubr (&Sfield_end);
4841 defsubr (&Sfield_string);
4842 defsubr (&Sfield_string_no_properties);
4843 defsubr (&Sdelete_field);
4844 defsubr (&Sconstrain_to_field);
4846 defsubr (&Sline_beginning_position);
4847 defsubr (&Sline_end_position);
4849 /* defsubr (&Smark); */
4850 /* defsubr (&Sset_mark); */
4851 defsubr (&Ssave_excursion);
4852 defsubr (&Ssave_current_buffer);
4854 defsubr (&Sbufsize);
4855 defsubr (&Spoint_max);
4856 defsubr (&Spoint_min);
4857 defsubr (&Spoint_min_marker);
4858 defsubr (&Spoint_max_marker);
4859 defsubr (&Sgap_position);
4860 defsubr (&Sgap_size);
4861 defsubr (&Sposition_bytes);
4862 defsubr (&Sbyte_to_position);
4864 defsubr (&Sbobp);
4865 defsubr (&Seobp);
4866 defsubr (&Sbolp);
4867 defsubr (&Seolp);
4868 defsubr (&Sfollowing_char);
4869 defsubr (&Sprevious_char);
4870 defsubr (&Schar_after);
4871 defsubr (&Schar_before);
4872 defsubr (&Sinsert);
4873 defsubr (&Sinsert_before_markers);
4874 defsubr (&Sinsert_and_inherit);
4875 defsubr (&Sinsert_and_inherit_before_markers);
4876 defsubr (&Sinsert_char);
4877 defsubr (&Sinsert_byte);
4879 defsubr (&Suser_login_name);
4880 defsubr (&Suser_real_login_name);
4881 defsubr (&Suser_uid);
4882 defsubr (&Suser_real_uid);
4883 defsubr (&Suser_full_name);
4884 defsubr (&Semacs_pid);
4885 defsubr (&Scurrent_time);
4886 defsubr (&Sget_internal_run_time);
4887 defsubr (&Sformat_time_string);
4888 defsubr (&Sfloat_time);
4889 defsubr (&Sdecode_time);
4890 defsubr (&Sencode_time);
4891 defsubr (&Scurrent_time_string);
4892 defsubr (&Scurrent_time_zone);
4893 defsubr (&Sset_time_zone_rule);
4894 defsubr (&Ssystem_name);
4895 defsubr (&Smessage);
4896 defsubr (&Smessage_box);
4897 defsubr (&Smessage_or_box);
4898 defsubr (&Scurrent_message);
4899 defsubr (&Sformat);
4901 defsubr (&Sinsert_buffer_substring);
4902 defsubr (&Scompare_buffer_substrings);
4903 defsubr (&Ssubst_char_in_region);
4904 defsubr (&Stranslate_region_internal);
4905 defsubr (&Sdelete_region);
4906 defsubr (&Sdelete_and_extract_region);
4907 defsubr (&Swiden);
4908 defsubr (&Snarrow_to_region);
4909 defsubr (&Ssave_restriction);
4910 defsubr (&Stranspose_regions);