Merge from emacs-23; up to 2010-06-08T03:06:47Z!dann@ics.uci.edu.
[emacs.git] / src / editfns.c
blobcd424f277bf167fa31bce41d2974338c63a3acfe
1 /* Lisp functions pertaining to editing.
3 Copyright (C) 1985-1987, 1989, 1993-2011 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 <limits.h>
49 #include <intprops.h>
50 #include <strftime.h>
52 #include "intervals.h"
53 #include "buffer.h"
54 #include "character.h"
55 #include "coding.h"
56 #include "frame.h"
57 #include "window.h"
58 #include "blockinput.h"
60 #ifdef STDC_HEADERS
61 #include <float.h>
62 #define MAX_10_EXP DBL_MAX_10_EXP
63 #else
64 #define MAX_10_EXP 310
65 #endif
67 #ifndef NULL
68 #define NULL 0
69 #endif
71 #ifndef USER_FULL_NAME
72 #define USER_FULL_NAME pw->pw_gecos
73 #endif
75 #ifndef USE_CRT_DLL
76 extern char **environ;
77 #endif
79 #define TM_YEAR_BASE 1900
81 /* Nonzero if TM_YEAR is a struct tm's tm_year value that causes
82 asctime to have well-defined behavior. */
83 #ifndef TM_YEAR_IN_ASCTIME_RANGE
84 # define TM_YEAR_IN_ASCTIME_RANGE(tm_year) \
85 (1000 - TM_YEAR_BASE <= (tm_year) && (tm_year) <= 9999 - TM_YEAR_BASE)
86 #endif
88 #ifdef WINDOWSNT
89 extern Lisp_Object w32_get_internal_run_time (void);
90 #endif
92 static void time_overflow (void) NO_RETURN;
93 static int tm_diff (struct tm *, struct tm *);
94 static void find_field (Lisp_Object, Lisp_Object, Lisp_Object,
95 EMACS_INT *, Lisp_Object, EMACS_INT *);
96 static void update_buffer_properties (EMACS_INT, EMACS_INT);
97 static Lisp_Object region_limit (int);
98 static size_t emacs_nmemftime (char *, size_t, const char *,
99 size_t, const struct tm *, int, int);
100 static void general_insert_function (void (*) (const char *, EMACS_INT),
101 void (*) (Lisp_Object, EMACS_INT,
102 EMACS_INT, EMACS_INT,
103 EMACS_INT, int),
104 int, size_t, Lisp_Object *);
105 static Lisp_Object subst_char_in_region_unwind (Lisp_Object);
106 static Lisp_Object subst_char_in_region_unwind_1 (Lisp_Object);
107 static void transpose_markers (EMACS_INT, EMACS_INT, EMACS_INT, EMACS_INT,
108 EMACS_INT, EMACS_INT, EMACS_INT, EMACS_INT);
110 Lisp_Object Qbuffer_access_fontify_functions;
111 Lisp_Object Fuser_full_name (Lisp_Object);
113 /* Symbol for the text property used to mark fields. */
115 Lisp_Object Qfield;
117 /* A special value for Qfield properties. */
119 Lisp_Object Qboundary;
122 void
123 init_editfns (void)
125 const char *user_name;
126 register char *p;
127 struct passwd *pw; /* password entry for the current user */
128 Lisp_Object tem;
130 /* Set up system_name even when dumping. */
131 init_system_name ();
133 #ifndef CANNOT_DUMP
134 /* Don't bother with this on initial start when just dumping out */
135 if (!initialized)
136 return;
137 #endif /* not CANNOT_DUMP */
139 pw = getpwuid (getuid ());
140 #ifdef MSDOS
141 /* We let the real user name default to "root" because that's quite
142 accurate on MSDOG and because it lets Emacs find the init file.
143 (The DVX libraries override the Djgpp libraries here.) */
144 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
145 #else
146 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
147 #endif
149 /* Get the effective user name, by consulting environment variables,
150 or the effective uid if those are unset. */
151 user_name = getenv ("LOGNAME");
152 if (!user_name)
153 #ifdef WINDOWSNT
154 user_name = getenv ("USERNAME"); /* it's USERNAME on NT */
155 #else /* WINDOWSNT */
156 user_name = getenv ("USER");
157 #endif /* WINDOWSNT */
158 if (!user_name)
160 pw = getpwuid (geteuid ());
161 user_name = pw ? pw->pw_name : "unknown";
163 Vuser_login_name = build_string (user_name);
165 /* If the user name claimed in the environment vars differs from
166 the real uid, use the claimed name to find the full name. */
167 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
168 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
169 : Vuser_login_name);
171 p = getenv ("NAME");
172 if (p)
173 Vuser_full_name = build_string (p);
174 else if (NILP (Vuser_full_name))
175 Vuser_full_name = build_string ("unknown");
177 #ifdef HAVE_SYS_UTSNAME_H
179 struct utsname uts;
180 uname (&uts);
181 Voperating_system_release = build_string (uts.release);
183 #else
184 Voperating_system_release = Qnil;
185 #endif
188 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
189 doc: /* Convert arg CHAR to a string containing that character.
190 usage: (char-to-string CHAR) */)
191 (Lisp_Object character)
193 int len;
194 unsigned char str[MAX_MULTIBYTE_LENGTH];
196 CHECK_CHARACTER (character);
198 len = CHAR_STRING (XFASTINT (character), str);
199 return make_string_from_bytes ((char *) str, 1, len);
202 DEFUN ("byte-to-string", Fbyte_to_string, Sbyte_to_string, 1, 1, 0,
203 doc: /* Convert arg BYTE to a unibyte string containing that byte. */)
204 (Lisp_Object byte)
206 unsigned char b;
207 CHECK_NUMBER (byte);
208 if (XINT (byte) < 0 || XINT (byte) > 255)
209 error ("Invalid byte");
210 b = XINT (byte);
211 return make_string_from_bytes ((char *) &b, 1, 1);
214 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
215 doc: /* Convert arg STRING to a character, the first character of that string.
216 A multibyte character is handled correctly. */)
217 (register Lisp_Object string)
219 register Lisp_Object val;
220 CHECK_STRING (string);
221 if (SCHARS (string))
223 if (STRING_MULTIBYTE (string))
224 XSETFASTINT (val, STRING_CHAR (SDATA (string)));
225 else
226 XSETFASTINT (val, SREF (string, 0));
228 else
229 XSETFASTINT (val, 0);
230 return val;
233 static Lisp_Object
234 buildmark (EMACS_INT charpos, EMACS_INT bytepos)
236 register Lisp_Object mark;
237 mark = Fmake_marker ();
238 set_marker_both (mark, Qnil, charpos, bytepos);
239 return mark;
242 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
243 doc: /* Return value of point, as an integer.
244 Beginning of buffer is position (point-min). */)
245 (void)
247 Lisp_Object temp;
248 XSETFASTINT (temp, PT);
249 return temp;
252 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
253 doc: /* Return value of point, as a marker object. */)
254 (void)
256 return buildmark (PT, PT_BYTE);
259 EMACS_INT
260 clip_to_bounds (EMACS_INT lower, EMACS_INT num, EMACS_INT upper)
262 if (num < lower)
263 return lower;
264 else if (num > upper)
265 return upper;
266 else
267 return num;
270 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
271 doc: /* Set point to POSITION, a number or marker.
272 Beginning of buffer is position (point-min), end is (point-max).
274 The return value is POSITION. */)
275 (register Lisp_Object position)
277 EMACS_INT pos;
279 if (MARKERP (position)
280 && current_buffer == XMARKER (position)->buffer)
282 pos = marker_position (position);
283 if (pos < BEGV)
284 SET_PT_BOTH (BEGV, BEGV_BYTE);
285 else if (pos > ZV)
286 SET_PT_BOTH (ZV, ZV_BYTE);
287 else
288 SET_PT_BOTH (pos, marker_byte_position (position));
290 return position;
293 CHECK_NUMBER_COERCE_MARKER (position);
295 pos = clip_to_bounds (BEGV, XINT (position), ZV);
296 SET_PT (pos);
297 return position;
301 /* Return the start or end position of the region.
302 BEGINNINGP non-zero means return the start.
303 If there is no region active, signal an error. */
305 static Lisp_Object
306 region_limit (int beginningp)
308 Lisp_Object m;
310 if (!NILP (Vtransient_mark_mode)
311 && NILP (Vmark_even_if_inactive)
312 && NILP (BVAR (current_buffer, mark_active)))
313 xsignal0 (Qmark_inactive);
315 m = Fmarker_position (BVAR (current_buffer, mark));
316 if (NILP (m))
317 error ("The mark is not set now, so there is no region");
319 if ((PT < XFASTINT (m)) == (beginningp != 0))
320 m = make_number (PT);
321 return m;
324 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
325 doc: /* Return the integer value of point or mark, whichever is smaller. */)
326 (void)
328 return region_limit (1);
331 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
332 doc: /* Return the integer value of point or mark, whichever is larger. */)
333 (void)
335 return region_limit (0);
338 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
339 doc: /* Return this buffer's mark, as a marker object.
340 Watch out! Moving this marker changes the mark position.
341 If you set the marker not to point anywhere, the buffer will have no mark. */)
342 (void)
344 return BVAR (current_buffer, mark);
348 /* Find all the overlays in the current buffer that touch position POS.
349 Return the number found, and store them in a vector in VEC
350 of length LEN. */
352 static int
353 overlays_around (EMACS_INT pos, Lisp_Object *vec, int len)
355 Lisp_Object overlay, start, end;
356 struct Lisp_Overlay *tail;
357 EMACS_INT startpos, endpos;
358 int idx = 0;
360 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
362 XSETMISC (overlay, tail);
364 end = OVERLAY_END (overlay);
365 endpos = OVERLAY_POSITION (end);
366 if (endpos < pos)
367 break;
368 start = OVERLAY_START (overlay);
369 startpos = OVERLAY_POSITION (start);
370 if (startpos <= pos)
372 if (idx < len)
373 vec[idx] = overlay;
374 /* Keep counting overlays even if we can't return them all. */
375 idx++;
379 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
381 XSETMISC (overlay, tail);
383 start = OVERLAY_START (overlay);
384 startpos = OVERLAY_POSITION (start);
385 if (pos < startpos)
386 break;
387 end = OVERLAY_END (overlay);
388 endpos = OVERLAY_POSITION (end);
389 if (pos <= endpos)
391 if (idx < len)
392 vec[idx] = overlay;
393 idx++;
397 return idx;
400 /* Return the value of property PROP, in OBJECT at POSITION.
401 It's the value of PROP that a char inserted at POSITION would get.
402 OBJECT is optional and defaults to the current buffer.
403 If OBJECT is a buffer, then overlay properties are considered as well as
404 text properties.
405 If OBJECT is a window, then that window's buffer is used, but
406 window-specific overlays are considered only if they are associated
407 with OBJECT. */
408 Lisp_Object
409 get_pos_property (Lisp_Object position, register Lisp_Object prop, Lisp_Object object)
411 CHECK_NUMBER_COERCE_MARKER (position);
413 if (NILP (object))
414 XSETBUFFER (object, current_buffer);
415 else if (WINDOWP (object))
416 object = XWINDOW (object)->buffer;
418 if (!BUFFERP (object))
419 /* pos-property only makes sense in buffers right now, since strings
420 have no overlays and no notion of insertion for which stickiness
421 could be obeyed. */
422 return Fget_text_property (position, prop, object);
423 else
425 EMACS_INT posn = XINT (position);
426 int noverlays;
427 Lisp_Object *overlay_vec, tem;
428 struct buffer *obuf = current_buffer;
430 set_buffer_temp (XBUFFER (object));
432 /* First try with room for 40 overlays. */
433 noverlays = 40;
434 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
435 noverlays = overlays_around (posn, overlay_vec, noverlays);
437 /* If there are more than 40,
438 make enough space for all, and try again. */
439 if (noverlays > 40)
441 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
442 noverlays = overlays_around (posn, overlay_vec, noverlays);
444 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
446 set_buffer_temp (obuf);
448 /* Now check the overlays in order of decreasing priority. */
449 while (--noverlays >= 0)
451 Lisp_Object ol = overlay_vec[noverlays];
452 tem = Foverlay_get (ol, prop);
453 if (!NILP (tem))
455 /* Check the overlay is indeed active at point. */
456 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
457 if ((OVERLAY_POSITION (start) == posn
458 && XMARKER (start)->insertion_type == 1)
459 || (OVERLAY_POSITION (finish) == posn
460 && XMARKER (finish)->insertion_type == 0))
461 ; /* The overlay will not cover a char inserted at point. */
462 else
464 return tem;
469 { /* Now check the text properties. */
470 int stickiness = text_property_stickiness (prop, position, object);
471 if (stickiness > 0)
472 return Fget_text_property (position, prop, object);
473 else if (stickiness < 0
474 && XINT (position) > BUF_BEGV (XBUFFER (object)))
475 return Fget_text_property (make_number (XINT (position) - 1),
476 prop, object);
477 else
478 return Qnil;
483 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
484 the value of point is used instead. If BEG or END is null,
485 means don't store the beginning or end of the field.
487 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
488 results; they do not effect boundary behavior.
490 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
491 position of a field, then the beginning of the previous field is
492 returned instead of the beginning of POS's field (since the end of a
493 field is actually also the beginning of the next input field, this
494 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
495 true case, if two fields are separated by a field with the special
496 value `boundary', and POS lies within it, then the two separated
497 fields are considered to be adjacent, and POS between them, when
498 finding the beginning and ending of the "merged" field.
500 Either BEG or END may be 0, in which case the corresponding value
501 is not stored. */
503 static void
504 find_field (Lisp_Object pos, Lisp_Object merge_at_boundary,
505 Lisp_Object beg_limit,
506 EMACS_INT *beg, Lisp_Object end_limit, EMACS_INT *end)
508 /* Fields right before and after the point. */
509 Lisp_Object before_field, after_field;
510 /* 1 if POS counts as the start of a field. */
511 int at_field_start = 0;
512 /* 1 if POS counts as the end of a field. */
513 int at_field_end = 0;
515 if (NILP (pos))
516 XSETFASTINT (pos, PT);
517 else
518 CHECK_NUMBER_COERCE_MARKER (pos);
520 after_field
521 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
522 before_field
523 = (XFASTINT (pos) > BEGV
524 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
525 Qfield, Qnil, NULL)
526 /* Using nil here would be a more obvious choice, but it would
527 fail when the buffer starts with a non-sticky field. */
528 : after_field);
530 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
531 and POS is at beginning of a field, which can also be interpreted
532 as the end of the previous field. Note that the case where if
533 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
534 more natural one; then we avoid treating the beginning of a field
535 specially. */
536 if (NILP (merge_at_boundary))
538 Lisp_Object field = get_pos_property (pos, Qfield, Qnil);
539 if (!EQ (field, after_field))
540 at_field_end = 1;
541 if (!EQ (field, before_field))
542 at_field_start = 1;
543 if (NILP (field) && at_field_start && at_field_end)
544 /* If an inserted char would have a nil field while the surrounding
545 text is non-nil, we're probably not looking at a
546 zero-length field, but instead at a non-nil field that's
547 not intended for editing (such as comint's prompts). */
548 at_field_end = at_field_start = 0;
551 /* Note about special `boundary' fields:
553 Consider the case where the point (`.') is between the fields `x' and `y':
555 xxxx.yyyy
557 In this situation, if merge_at_boundary is true, we consider the
558 `x' and `y' fields as forming one big merged field, and so the end
559 of the field is the end of `y'.
561 However, if `x' and `y' are separated by a special `boundary' field
562 (a field with a `field' char-property of 'boundary), then we ignore
563 this special field when merging adjacent fields. Here's the same
564 situation, but with a `boundary' field between the `x' and `y' fields:
566 xxx.BBBByyyy
568 Here, if point is at the end of `x', the beginning of `y', or
569 anywhere in-between (within the `boundary' field), we merge all
570 three fields and consider the beginning as being the beginning of
571 the `x' field, and the end as being the end of the `y' field. */
573 if (beg)
575 if (at_field_start)
576 /* POS is at the edge of a field, and we should consider it as
577 the beginning of the following field. */
578 *beg = XFASTINT (pos);
579 else
580 /* Find the previous field boundary. */
582 Lisp_Object p = pos;
583 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
584 /* Skip a `boundary' field. */
585 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
586 beg_limit);
588 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
589 beg_limit);
590 *beg = NILP (p) ? BEGV : XFASTINT (p);
594 if (end)
596 if (at_field_end)
597 /* POS is at the edge of a field, and we should consider it as
598 the end of the previous field. */
599 *end = XFASTINT (pos);
600 else
601 /* Find the next field boundary. */
603 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
604 /* Skip a `boundary' field. */
605 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
606 end_limit);
608 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
609 end_limit);
610 *end = NILP (pos) ? ZV : XFASTINT (pos);
616 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
617 doc: /* Delete the field surrounding POS.
618 A field is a region of text with the same `field' property.
619 If POS is nil, the value of point is used for POS. */)
620 (Lisp_Object pos)
622 EMACS_INT beg, end;
623 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
624 if (beg != end)
625 del_range (beg, end);
626 return Qnil;
629 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
630 doc: /* Return the contents of the field surrounding POS as a string.
631 A field is a region of text with the same `field' property.
632 If POS is nil, the value of point is used for POS. */)
633 (Lisp_Object pos)
635 EMACS_INT beg, end;
636 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
637 return make_buffer_string (beg, end, 1);
640 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
641 doc: /* Return the contents of the field around POS, without text properties.
642 A field is a region of text with the same `field' property.
643 If POS is nil, the value of point is used for POS. */)
644 (Lisp_Object pos)
646 EMACS_INT beg, end;
647 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
648 return make_buffer_string (beg, end, 0);
651 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
652 doc: /* Return the beginning of the field surrounding POS.
653 A field is a region of text with the same `field' property.
654 If POS is nil, the value of point is used for POS.
655 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
656 field, then the beginning of the *previous* field is returned.
657 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
658 is before LIMIT, then LIMIT will be returned instead. */)
659 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
661 EMACS_INT beg;
662 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
663 return make_number (beg);
666 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
667 doc: /* Return the end of the field surrounding POS.
668 A field is a region of text with the same `field' property.
669 If POS is nil, the value of point is used for POS.
670 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
671 then the end of the *following* field is returned.
672 If LIMIT is non-nil, it is a buffer position; if the end of the field
673 is after LIMIT, then LIMIT will be returned instead. */)
674 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
676 EMACS_INT end;
677 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
678 return make_number (end);
681 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
682 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
684 A field is a region of text with the same `field' property.
685 If NEW-POS is nil, then the current point is used instead, and set to the
686 constrained position if that is different.
688 If OLD-POS is at the boundary of two fields, then the allowable
689 positions for NEW-POS depends on the value of the optional argument
690 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
691 constrained to the field that has the same `field' char-property
692 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
693 is non-nil, NEW-POS is constrained to the union of the two adjacent
694 fields. Additionally, if two fields are separated by another field with
695 the special value `boundary', then any point within this special field is
696 also considered to be `on the boundary'.
698 If the optional argument ONLY-IN-LINE is non-nil and constraining
699 NEW-POS would move it to a different line, NEW-POS is returned
700 unconstrained. This useful for commands that move by line, like
701 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
702 only in the case where they can still move to the right line.
704 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
705 a non-nil property of that name, then any field boundaries are ignored.
707 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
708 (Lisp_Object new_pos, Lisp_Object old_pos, Lisp_Object escape_from_edge, Lisp_Object only_in_line, Lisp_Object inhibit_capture_property)
710 /* If non-zero, then the original point, before re-positioning. */
711 EMACS_INT orig_point = 0;
712 int fwd;
713 Lisp_Object prev_old, prev_new;
715 if (NILP (new_pos))
716 /* Use the current point, and afterwards, set it. */
718 orig_point = PT;
719 XSETFASTINT (new_pos, PT);
722 CHECK_NUMBER_COERCE_MARKER (new_pos);
723 CHECK_NUMBER_COERCE_MARKER (old_pos);
725 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
727 prev_old = make_number (XFASTINT (old_pos) - 1);
728 prev_new = make_number (XFASTINT (new_pos) - 1);
730 if (NILP (Vinhibit_field_text_motion)
731 && !EQ (new_pos, old_pos)
732 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
733 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
734 /* To recognize field boundaries, we must also look at the
735 previous positions; we could use `get_pos_property'
736 instead, but in itself that would fail inside non-sticky
737 fields (like comint prompts). */
738 || (XFASTINT (new_pos) > BEGV
739 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
740 || (XFASTINT (old_pos) > BEGV
741 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
742 && (NILP (inhibit_capture_property)
743 /* Field boundaries are again a problem; but now we must
744 decide the case exactly, so we need to call
745 `get_pos_property' as well. */
746 || (NILP (get_pos_property (old_pos, inhibit_capture_property, Qnil))
747 && (XFASTINT (old_pos) <= BEGV
748 || NILP (Fget_char_property (old_pos, inhibit_capture_property, Qnil))
749 || NILP (Fget_char_property (prev_old, inhibit_capture_property, Qnil))))))
750 /* It is possible that NEW_POS is not within the same field as
751 OLD_POS; try to move NEW_POS so that it is. */
753 EMACS_INT shortage;
754 Lisp_Object field_bound;
756 if (fwd)
757 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
758 else
759 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
761 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
762 other side of NEW_POS, which would mean that NEW_POS is
763 already acceptable, and it's not necessary to constrain it
764 to FIELD_BOUND. */
765 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
766 /* NEW_POS should be constrained, but only if either
767 ONLY_IN_LINE is nil (in which case any constraint is OK),
768 or NEW_POS and FIELD_BOUND are on the same line (in which
769 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
770 && (NILP (only_in_line)
771 /* This is the ONLY_IN_LINE case, check that NEW_POS and
772 FIELD_BOUND are on the same line by seeing whether
773 there's an intervening newline or not. */
774 || (scan_buffer ('\n',
775 XFASTINT (new_pos), XFASTINT (field_bound),
776 fwd ? -1 : 1, &shortage, 1),
777 shortage != 0)))
778 /* Constrain NEW_POS to FIELD_BOUND. */
779 new_pos = field_bound;
781 if (orig_point && XFASTINT (new_pos) != orig_point)
782 /* The NEW_POS argument was originally nil, so automatically set PT. */
783 SET_PT (XFASTINT (new_pos));
786 return new_pos;
790 DEFUN ("line-beginning-position",
791 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
792 doc: /* Return the character position of the first character on the current line.
793 With argument N not nil or 1, move forward N - 1 lines first.
794 If scan reaches end of buffer, return that position.
796 The returned position is of the first character in the logical order,
797 i.e. the one that has the smallest character position.
799 This function constrains the returned position to the current field
800 unless that would be on a different line than the original,
801 unconstrained result. If N is nil or 1, and a front-sticky field
802 starts at point, the scan stops as soon as it starts. To ignore field
803 boundaries bind `inhibit-field-text-motion' to t.
805 This function does not move point. */)
806 (Lisp_Object n)
808 EMACS_INT orig, orig_byte, end;
809 int count = SPECPDL_INDEX ();
810 specbind (Qinhibit_point_motion_hooks, Qt);
812 if (NILP (n))
813 XSETFASTINT (n, 1);
814 else
815 CHECK_NUMBER (n);
817 orig = PT;
818 orig_byte = PT_BYTE;
819 Fforward_line (make_number (XINT (n) - 1));
820 end = PT;
822 SET_PT_BOTH (orig, orig_byte);
824 unbind_to (count, Qnil);
826 /* Return END constrained to the current input field. */
827 return Fconstrain_to_field (make_number (end), make_number (orig),
828 XINT (n) != 1 ? Qt : Qnil,
829 Qt, Qnil);
832 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
833 doc: /* Return the character position of the last character on the current line.
834 With argument N not nil or 1, move forward N - 1 lines first.
835 If scan reaches end of buffer, return that position.
837 The returned position is of the last character in the logical order,
838 i.e. the character whose buffer position is the largest one.
840 This function constrains the returned position to the current field
841 unless that would be on a different line than the original,
842 unconstrained result. If N is nil or 1, and a rear-sticky field ends
843 at point, the scan stops as soon as it starts. To ignore field
844 boundaries bind `inhibit-field-text-motion' to t.
846 This function does not move point. */)
847 (Lisp_Object n)
849 EMACS_INT end_pos;
850 EMACS_INT orig = PT;
852 if (NILP (n))
853 XSETFASTINT (n, 1);
854 else
855 CHECK_NUMBER (n);
857 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
859 /* Return END_POS constrained to the current input field. */
860 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
861 Qnil, Qt, Qnil);
865 Lisp_Object
866 save_excursion_save (void)
868 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
869 == current_buffer);
871 return Fcons (Fpoint_marker (),
872 Fcons (Fcopy_marker (BVAR (current_buffer, mark), Qnil),
873 Fcons (visible ? Qt : Qnil,
874 Fcons (BVAR (current_buffer, mark_active),
875 selected_window))));
878 Lisp_Object
879 save_excursion_restore (Lisp_Object info)
881 Lisp_Object tem, tem1, omark, nmark;
882 struct gcpro gcpro1, gcpro2, gcpro3;
883 int visible_p;
885 tem = Fmarker_buffer (XCAR (info));
886 /* If buffer being returned to is now deleted, avoid error */
887 /* Otherwise could get error here while unwinding to top level
888 and crash */
889 /* In that case, Fmarker_buffer returns nil now. */
890 if (NILP (tem))
891 return Qnil;
893 omark = nmark = Qnil;
894 GCPRO3 (info, omark, nmark);
896 Fset_buffer (tem);
898 /* Point marker. */
899 tem = XCAR (info);
900 Fgoto_char (tem);
901 unchain_marker (XMARKER (tem));
903 /* Mark marker. */
904 info = XCDR (info);
905 tem = XCAR (info);
906 omark = Fmarker_position (BVAR (current_buffer, mark));
907 Fset_marker (BVAR (current_buffer, mark), tem, Fcurrent_buffer ());
908 nmark = Fmarker_position (tem);
909 unchain_marker (XMARKER (tem));
911 /* visible */
912 info = XCDR (info);
913 visible_p = !NILP (XCAR (info));
915 #if 0 /* We used to make the current buffer visible in the selected window
916 if that was true previously. That avoids some anomalies.
917 But it creates others, and it wasn't documented, and it is simpler
918 and cleaner never to alter the window/buffer connections. */
919 tem1 = Fcar (tem);
920 if (!NILP (tem1)
921 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
922 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
923 #endif /* 0 */
925 /* Mark active */
926 info = XCDR (info);
927 tem = XCAR (info);
928 tem1 = BVAR (current_buffer, mark_active);
929 BVAR (current_buffer, mark_active) = tem;
931 /* If mark is active now, and either was not active
932 or was at a different place, run the activate hook. */
933 if (! NILP (tem))
935 if (! EQ (omark, nmark))
937 tem = intern ("activate-mark-hook");
938 Frun_hooks (1, &tem);
941 /* If mark has ceased to be active, run deactivate hook. */
942 else if (! NILP (tem1))
944 tem = intern ("deactivate-mark-hook");
945 Frun_hooks (1, &tem);
948 /* If buffer was visible in a window, and a different window was
949 selected, and the old selected window is still showing this
950 buffer, restore point in that window. */
951 tem = XCDR (info);
952 if (visible_p
953 && !EQ (tem, selected_window)
954 && (tem1 = XWINDOW (tem)->buffer,
955 (/* Window is live... */
956 BUFFERP (tem1)
957 /* ...and it shows the current buffer. */
958 && XBUFFER (tem1) == current_buffer)))
959 Fset_window_point (tem, make_number (PT));
961 UNGCPRO;
962 return Qnil;
965 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
966 doc: /* Save point, mark, and current buffer; execute BODY; restore those things.
967 Executes BODY just like `progn'.
968 The values of point, mark and the current buffer are restored
969 even in case of abnormal exit (throw or error).
970 The state of activation of the mark is also restored.
972 This construct does not save `deactivate-mark', and therefore
973 functions that change the buffer will still cause deactivation
974 of the mark at the end of the command. To prevent that, bind
975 `deactivate-mark' with `let'.
977 If you only want to save the current buffer but not point nor mark,
978 then just use `save-current-buffer', or even `with-current-buffer'.
980 usage: (save-excursion &rest BODY) */)
981 (Lisp_Object args)
983 register Lisp_Object val;
984 int count = SPECPDL_INDEX ();
986 record_unwind_protect (save_excursion_restore, save_excursion_save ());
988 val = Fprogn (args);
989 return unbind_to (count, val);
992 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
993 doc: /* Save the current buffer; execute BODY; restore the current buffer.
994 Executes BODY just like `progn'.
995 usage: (save-current-buffer &rest BODY) */)
996 (Lisp_Object args)
998 Lisp_Object val;
999 int count = SPECPDL_INDEX ();
1001 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
1003 val = Fprogn (args);
1004 return unbind_to (count, val);
1007 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
1008 doc: /* Return the number of characters in the current buffer.
1009 If BUFFER, return the number of characters in that buffer instead. */)
1010 (Lisp_Object buffer)
1012 if (NILP (buffer))
1013 return make_number (Z - BEG);
1014 else
1016 CHECK_BUFFER (buffer);
1017 return make_number (BUF_Z (XBUFFER (buffer))
1018 - BUF_BEG (XBUFFER (buffer)));
1022 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
1023 doc: /* Return the minimum permissible value of point in the current buffer.
1024 This is 1, unless narrowing (a buffer restriction) is in effect. */)
1025 (void)
1027 Lisp_Object temp;
1028 XSETFASTINT (temp, BEGV);
1029 return temp;
1032 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
1033 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1034 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1035 (void)
1037 return buildmark (BEGV, BEGV_BYTE);
1040 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1041 doc: /* Return the maximum permissible value of point in the current buffer.
1042 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1043 is in effect, in which case it is less. */)
1044 (void)
1046 Lisp_Object temp;
1047 XSETFASTINT (temp, ZV);
1048 return temp;
1051 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1052 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1053 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1054 is in effect, in which case it is less. */)
1055 (void)
1057 return buildmark (ZV, ZV_BYTE);
1060 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1061 doc: /* Return the position of the gap, in the current buffer.
1062 See also `gap-size'. */)
1063 (void)
1065 Lisp_Object temp;
1066 XSETFASTINT (temp, GPT);
1067 return temp;
1070 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1071 doc: /* Return the size of the current buffer's gap.
1072 See also `gap-position'. */)
1073 (void)
1075 Lisp_Object temp;
1076 XSETFASTINT (temp, GAP_SIZE);
1077 return temp;
1080 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1081 doc: /* Return the byte position for character position POSITION.
1082 If POSITION is out of range, the value is nil. */)
1083 (Lisp_Object position)
1085 CHECK_NUMBER_COERCE_MARKER (position);
1086 if (XINT (position) < BEG || XINT (position) > Z)
1087 return Qnil;
1088 return make_number (CHAR_TO_BYTE (XINT (position)));
1091 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1092 doc: /* Return the character position for byte position BYTEPOS.
1093 If BYTEPOS is out of range, the value is nil. */)
1094 (Lisp_Object bytepos)
1096 CHECK_NUMBER (bytepos);
1097 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
1098 return Qnil;
1099 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1102 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1103 doc: /* Return the character following point, as a number.
1104 At the end of the buffer or accessible region, return 0. */)
1105 (void)
1107 Lisp_Object temp;
1108 if (PT >= ZV)
1109 XSETFASTINT (temp, 0);
1110 else
1111 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1112 return temp;
1115 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1116 doc: /* Return the character preceding point, as a number.
1117 At the beginning of the buffer or accessible region, return 0. */)
1118 (void)
1120 Lisp_Object temp;
1121 if (PT <= BEGV)
1122 XSETFASTINT (temp, 0);
1123 else if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1125 EMACS_INT pos = PT_BYTE;
1126 DEC_POS (pos);
1127 XSETFASTINT (temp, FETCH_CHAR (pos));
1129 else
1130 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1131 return temp;
1134 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1135 doc: /* Return t if point is at the beginning of the buffer.
1136 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1137 (void)
1139 if (PT == BEGV)
1140 return Qt;
1141 return Qnil;
1144 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1145 doc: /* Return t if point is at the end of the buffer.
1146 If the buffer is narrowed, this means the end of the narrowed part. */)
1147 (void)
1149 if (PT == ZV)
1150 return Qt;
1151 return Qnil;
1154 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1155 doc: /* Return t if point is at the beginning of a line. */)
1156 (void)
1158 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1159 return Qt;
1160 return Qnil;
1163 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1164 doc: /* Return t if point is at the end of a line.
1165 `End of a line' includes point being at the end of the buffer. */)
1166 (void)
1168 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1169 return Qt;
1170 return Qnil;
1173 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1174 doc: /* Return character in current buffer at position POS.
1175 POS is an integer or a marker and defaults to point.
1176 If POS is out of range, the value is nil. */)
1177 (Lisp_Object pos)
1179 register EMACS_INT pos_byte;
1181 if (NILP (pos))
1183 pos_byte = PT_BYTE;
1184 XSETFASTINT (pos, PT);
1187 if (MARKERP (pos))
1189 pos_byte = marker_byte_position (pos);
1190 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1191 return Qnil;
1193 else
1195 CHECK_NUMBER_COERCE_MARKER (pos);
1196 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1197 return Qnil;
1199 pos_byte = CHAR_TO_BYTE (XINT (pos));
1202 return make_number (FETCH_CHAR (pos_byte));
1205 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1206 doc: /* Return character in current buffer preceding position POS.
1207 POS is an integer or a marker and defaults to point.
1208 If POS is out of range, the value is nil. */)
1209 (Lisp_Object pos)
1211 register Lisp_Object val;
1212 register EMACS_INT pos_byte;
1214 if (NILP (pos))
1216 pos_byte = PT_BYTE;
1217 XSETFASTINT (pos, PT);
1220 if (MARKERP (pos))
1222 pos_byte = marker_byte_position (pos);
1224 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1225 return Qnil;
1227 else
1229 CHECK_NUMBER_COERCE_MARKER (pos);
1231 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1232 return Qnil;
1234 pos_byte = CHAR_TO_BYTE (XINT (pos));
1237 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1239 DEC_POS (pos_byte);
1240 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1242 else
1244 pos_byte--;
1245 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1247 return val;
1250 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1251 doc: /* Return the name under which the user logged in, as a string.
1252 This is based on the effective uid, not the real uid.
1253 Also, if the environment variables LOGNAME or USER are set,
1254 that determines the value of this function.
1256 If optional argument UID is an integer or a float, return the login name
1257 of the user with that uid, or nil if there is no such user. */)
1258 (Lisp_Object uid)
1260 struct passwd *pw;
1261 uid_t id;
1263 /* Set up the user name info if we didn't do it before.
1264 (That can happen if Emacs is dumpable
1265 but you decide to run `temacs -l loadup' and not dump. */
1266 if (INTEGERP (Vuser_login_name))
1267 init_editfns ();
1269 if (NILP (uid))
1270 return Vuser_login_name;
1272 id = XFLOATINT (uid);
1273 BLOCK_INPUT;
1274 pw = getpwuid (id);
1275 UNBLOCK_INPUT;
1276 return (pw ? build_string (pw->pw_name) : Qnil);
1279 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1280 0, 0, 0,
1281 doc: /* Return the name of the user's real uid, as a string.
1282 This ignores the environment variables LOGNAME and USER, so it differs from
1283 `user-login-name' when running under `su'. */)
1284 (void)
1286 /* Set up the user name info if we didn't do it before.
1287 (That can happen if Emacs is dumpable
1288 but you decide to run `temacs -l loadup' and not dump. */
1289 if (INTEGERP (Vuser_login_name))
1290 init_editfns ();
1291 return Vuser_real_login_name;
1294 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1295 doc: /* Return the effective uid of Emacs.
1296 Value is an integer or a float, depending on the value. */)
1297 (void)
1299 /* Assignment to EMACS_INT stops GCC whining about limited range of
1300 data type. */
1301 EMACS_INT euid = geteuid ();
1303 /* Make sure we don't produce a negative UID due to signed integer
1304 overflow. */
1305 if (euid < 0)
1306 return make_float (geteuid ());
1307 return make_fixnum_or_float (euid);
1310 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1311 doc: /* Return the real uid of Emacs.
1312 Value is an integer or a float, depending on the value. */)
1313 (void)
1315 /* Assignment to EMACS_INT stops GCC whining about limited range of
1316 data type. */
1317 EMACS_INT uid = getuid ();
1319 /* Make sure we don't produce a negative UID due to signed integer
1320 overflow. */
1321 if (uid < 0)
1322 return make_float (getuid ());
1323 return make_fixnum_or_float (uid);
1326 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1327 doc: /* Return the full name of the user logged in, as a string.
1328 If the full name corresponding to Emacs's userid is not known,
1329 return "unknown".
1331 If optional argument UID is an integer or float, return the full name
1332 of the user with that uid, or nil if there is no such user.
1333 If UID is a string, return the full name of the user with that login
1334 name, or nil if there is no such user. */)
1335 (Lisp_Object uid)
1337 struct passwd *pw;
1338 register char *p, *q;
1339 Lisp_Object full;
1341 if (NILP (uid))
1342 return Vuser_full_name;
1343 else if (NUMBERP (uid))
1345 uid_t u = XFLOATINT (uid);
1346 BLOCK_INPUT;
1347 pw = getpwuid (u);
1348 UNBLOCK_INPUT;
1350 else if (STRINGP (uid))
1352 BLOCK_INPUT;
1353 pw = getpwnam (SSDATA (uid));
1354 UNBLOCK_INPUT;
1356 else
1357 error ("Invalid UID specification");
1359 if (!pw)
1360 return Qnil;
1362 p = USER_FULL_NAME;
1363 /* Chop off everything after the first comma. */
1364 q = strchr (p, ',');
1365 full = make_string (p, q ? q - p : strlen (p));
1367 #ifdef AMPERSAND_FULL_NAME
1368 p = SSDATA (full);
1369 q = strchr (p, '&');
1370 /* Substitute the login name for the &, upcasing the first character. */
1371 if (q)
1373 register char *r;
1374 Lisp_Object login;
1376 login = Fuser_login_name (make_number (pw->pw_uid));
1377 r = (char *) alloca (strlen (p) + SCHARS (login) + 1);
1378 memcpy (r, p, q - p);
1379 r[q - p] = 0;
1380 strcat (r, SSDATA (login));
1381 r[q - p] = upcase ((unsigned char) r[q - p]);
1382 strcat (r, q + 1);
1383 full = build_string (r);
1385 #endif /* AMPERSAND_FULL_NAME */
1387 return full;
1390 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1391 doc: /* Return the host name of the machine you are running on, as a string. */)
1392 (void)
1394 return Vsystem_name;
1397 const char *
1398 get_system_name (void)
1400 if (STRINGP (Vsystem_name))
1401 return SSDATA (Vsystem_name);
1402 else
1403 return "";
1406 const char *
1407 get_operating_system_release (void)
1409 if (STRINGP (Voperating_system_release))
1410 return SSDATA (Voperating_system_release);
1411 else
1412 return "";
1415 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1416 doc: /* Return the process ID of Emacs, as an integer. */)
1417 (void)
1419 return make_number (getpid ());
1424 #ifndef TIME_T_MIN
1425 # define TIME_T_MIN TYPE_MINIMUM (time_t)
1426 #endif
1427 #ifndef TIME_T_MAX
1428 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
1429 #endif
1431 /* Report that a time value is out of range for Emacs. */
1432 static void
1433 time_overflow (void)
1435 error ("Specified time is not representable");
1438 /* Return the upper part of the time T (everything but the bottom 16 bits),
1439 making sure that it is representable. */
1440 static EMACS_INT
1441 hi_time (time_t t)
1443 time_t hi = t >> 16;
1445 /* Check for overflow, helping the compiler for common cases where
1446 no runtime check is needed, and taking care not to convert
1447 negative numbers to unsigned before comparing them. */
1448 if (! ((! TYPE_SIGNED (time_t)
1449 || MOST_NEGATIVE_FIXNUM <= TIME_T_MIN >> 16
1450 || MOST_NEGATIVE_FIXNUM <= hi)
1451 && (TIME_T_MAX >> 16 <= MOST_POSITIVE_FIXNUM
1452 || hi <= MOST_POSITIVE_FIXNUM)))
1453 time_overflow ();
1455 return hi;
1458 /* Return the bottom 16 bits of the time T. */
1459 static EMACS_INT
1460 lo_time (time_t t)
1462 return t & ((1 << 16) - 1);
1465 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1466 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1467 The time is returned as a list of three integers. The first has the
1468 most significant 16 bits of the seconds, while the second has the
1469 least significant 16 bits. The third integer gives the microsecond
1470 count.
1472 The microsecond count is zero on systems that do not provide
1473 resolution finer than a second. */)
1474 (void)
1476 EMACS_TIME t;
1478 EMACS_GET_TIME (t);
1479 return list3 (make_number (hi_time (EMACS_SECS (t))),
1480 make_number (lo_time (EMACS_SECS (t))),
1481 make_number (EMACS_USECS (t)));
1484 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1485 0, 0, 0,
1486 doc: /* Return the current run time used by Emacs.
1487 The time is returned as a list of three integers. The first has the
1488 most significant 16 bits of the seconds, while the second has the
1489 least significant 16 bits. The third integer gives the microsecond
1490 count.
1492 On systems that can't determine the run time, `get-internal-run-time'
1493 does the same thing as `current-time'. The microsecond count is zero
1494 on systems that do not provide resolution finer than a second. */)
1495 (void)
1497 #ifdef HAVE_GETRUSAGE
1498 struct rusage usage;
1499 time_t secs;
1500 int usecs;
1502 if (getrusage (RUSAGE_SELF, &usage) < 0)
1503 /* This shouldn't happen. What action is appropriate? */
1504 xsignal0 (Qerror);
1506 /* Sum up user time and system time. */
1507 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1508 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1509 if (usecs >= 1000000)
1511 usecs -= 1000000;
1512 secs++;
1515 return list3 (make_number (hi_time (secs)),
1516 make_number (lo_time (secs)),
1517 make_number (usecs));
1518 #else /* ! HAVE_GETRUSAGE */
1519 #ifdef WINDOWSNT
1520 return w32_get_internal_run_time ();
1521 #else /* ! WINDOWSNT */
1522 return Fcurrent_time ();
1523 #endif /* WINDOWSNT */
1524 #endif /* HAVE_GETRUSAGE */
1528 /* Make a Lisp list that represents the time T. */
1529 Lisp_Object
1530 make_time (time_t t)
1532 return list2 (make_number (hi_time (t)),
1533 make_number (lo_time (t)));
1536 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1537 If SPECIFIED_TIME is nil, use the current time.
1538 Set *RESULT to seconds since the Epoch.
1539 If USEC is not null, set *USEC to the microseconds component.
1540 Return nonzero if successful. */
1542 lisp_time_argument (Lisp_Object specified_time, time_t *result, int *usec)
1544 if (NILP (specified_time))
1546 if (usec)
1548 EMACS_TIME t;
1550 EMACS_GET_TIME (t);
1551 *usec = EMACS_USECS (t);
1552 *result = EMACS_SECS (t);
1553 return 1;
1555 else
1556 return time (result) != -1;
1558 else
1560 Lisp_Object high, low;
1561 EMACS_INT hi;
1562 high = Fcar (specified_time);
1563 CHECK_NUMBER (high);
1564 low = Fcdr (specified_time);
1565 if (CONSP (low))
1567 if (usec)
1569 Lisp_Object usec_l = Fcdr (low);
1570 if (CONSP (usec_l))
1571 usec_l = Fcar (usec_l);
1572 if (NILP (usec_l))
1573 *usec = 0;
1574 else
1576 CHECK_NUMBER (usec_l);
1577 *usec = XINT (usec_l);
1580 low = Fcar (low);
1582 else if (usec)
1583 *usec = 0;
1584 CHECK_NUMBER (low);
1585 hi = XINT (high);
1587 /* Check for overflow, helping the compiler for common cases
1588 where no runtime check is needed, and taking care not to
1589 convert negative numbers to unsigned before comparing them. */
1590 if (! ((TYPE_SIGNED (time_t)
1591 ? (TIME_T_MIN >> 16 <= MOST_NEGATIVE_FIXNUM
1592 || TIME_T_MIN >> 16 <= hi)
1593 : 0 <= hi)
1594 && (MOST_POSITIVE_FIXNUM <= TIME_T_MAX >> 16
1595 || hi <= TIME_T_MAX >> 16)))
1596 return 0;
1598 *result = (hi << 16) + (XINT (low) & 0xffff);
1599 return 1;
1603 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1604 doc: /* Return the current time, as a float number of seconds since the epoch.
1605 If SPECIFIED-TIME is given, it is the time to convert to float
1606 instead of the current time. The argument should have the form
1607 (HIGH LOW) or (HIGH LOW USEC). Thus, you can use times obtained from
1608 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
1609 have the form (HIGH . LOW), but this is considered obsolete.
1611 WARNING: Since the result is floating point, it may not be exact.
1612 If precise time stamps are required, use either `current-time',
1613 or (if you need time as a string) `format-time-string'. */)
1614 (Lisp_Object specified_time)
1616 time_t sec;
1617 int usec;
1619 if (! lisp_time_argument (specified_time, &sec, &usec))
1620 error ("Invalid time specification");
1622 return make_float ((sec * 1e6 + usec) / 1e6);
1625 /* Write information into buffer S of size MAXSIZE, according to the
1626 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1627 Default to Universal Time if UT is nonzero, local time otherwise.
1628 Use NS as the number of nanoseconds in the %N directive.
1629 Return the number of bytes written, not including the terminating
1630 '\0'. If S is NULL, nothing will be written anywhere; so to
1631 determine how many bytes would be written, use NULL for S and
1632 ((size_t) -1) for MAXSIZE.
1634 This function behaves like nstrftime, except it allows null
1635 bytes in FORMAT and it does not support nanoseconds. */
1636 static size_t
1637 emacs_nmemftime (char *s, size_t maxsize, const char *format,
1638 size_t format_len, const struct tm *tp, int ut, int ns)
1640 size_t total = 0;
1642 /* Loop through all the null-terminated strings in the format
1643 argument. Normally there's just one null-terminated string, but
1644 there can be arbitrarily many, concatenated together, if the
1645 format contains '\0' bytes. nstrftime stops at the first
1646 '\0' byte so we must invoke it separately for each such string. */
1647 for (;;)
1649 size_t len;
1650 size_t result;
1652 if (s)
1653 s[0] = '\1';
1655 result = nstrftime (s, maxsize, format, tp, ut, ns);
1657 if (s)
1659 if (result == 0 && s[0] != '\0')
1660 return 0;
1661 s += result + 1;
1664 maxsize -= result + 1;
1665 total += result;
1666 len = strlen (format);
1667 if (len == format_len)
1668 return total;
1669 total++;
1670 format += len + 1;
1671 format_len -= len + 1;
1675 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1676 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
1677 TIME is specified as (HIGH LOW . IGNORED), as returned by
1678 `current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
1679 is also still accepted.
1680 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1681 as Universal Time; nil means describe TIME in the local time zone.
1682 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1683 by text that describes the specified date and time in TIME:
1685 %Y is the year, %y within the century, %C the century.
1686 %G is the year corresponding to the ISO week, %g within the century.
1687 %m is the numeric month.
1688 %b and %h are the locale's abbreviated month name, %B the full name.
1689 %d is the day of the month, zero-padded, %e is blank-padded.
1690 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1691 %a is the locale's abbreviated name of the day of week, %A the full name.
1692 %U is the week number starting on Sunday, %W starting on Monday,
1693 %V according to ISO 8601.
1694 %j is the day of the year.
1696 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1697 only blank-padded, %l is like %I blank-padded.
1698 %p is the locale's equivalent of either AM or PM.
1699 %M is the minute.
1700 %S is the second.
1701 %N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
1702 %Z is the time zone name, %z is the numeric form.
1703 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1705 %c is the locale's date and time format.
1706 %x is the locale's "preferred" date format.
1707 %D is like "%m/%d/%y".
1709 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1710 %X is the locale's "preferred" time format.
1712 Finally, %n is a newline, %t is a tab, %% is a literal %.
1714 Certain flags and modifiers are available with some format controls.
1715 The flags are `_', `-', `^' and `#'. For certain characters X,
1716 %_X is like %X, but padded with blanks; %-X is like %X,
1717 but without padding. %^X is like %X, but with all textual
1718 characters up-cased; %#X is like %X, but with letter-case of
1719 all textual characters reversed.
1720 %NX (where N stands for an integer) is like %X,
1721 but takes up at least N (a number) positions.
1722 The modifiers are `E' and `O'. For certain characters X,
1723 %EX is a locale's alternative version of %X;
1724 %OX is like %X, but uses the locale's number symbols.
1726 For example, to produce full ISO 8601 format, use "%Y-%m-%dT%T%z". */)
1727 (Lisp_Object format_string, Lisp_Object timeval, Lisp_Object universal)
1729 time_t value;
1730 int size;
1731 int usec;
1732 int ns;
1733 struct tm *tm;
1734 int ut = ! NILP (universal);
1736 CHECK_STRING (format_string);
1738 if (! (lisp_time_argument (timeval, &value, &usec)
1739 && 0 <= usec && usec < 1000000))
1740 error ("Invalid time specification");
1741 ns = usec * 1000;
1743 format_string = code_convert_string_norecord (format_string,
1744 Vlocale_coding_system, 1);
1746 /* This is probably enough. */
1747 size = SBYTES (format_string) * 6 + 50;
1749 BLOCK_INPUT;
1750 tm = ut ? gmtime (&value) : localtime (&value);
1751 UNBLOCK_INPUT;
1752 if (! tm)
1753 time_overflow ();
1755 synchronize_system_time_locale ();
1757 while (1)
1759 char *buf = (char *) alloca (size + 1);
1760 int result;
1762 buf[0] = '\1';
1763 BLOCK_INPUT;
1764 result = emacs_nmemftime (buf, size, SSDATA (format_string),
1765 SBYTES (format_string),
1766 tm, ut, ns);
1767 UNBLOCK_INPUT;
1768 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1769 return code_convert_string_norecord (make_unibyte_string (buf, result),
1770 Vlocale_coding_system, 0);
1772 /* If buffer was too small, make it bigger and try again. */
1773 BLOCK_INPUT;
1774 result = emacs_nmemftime (NULL, (size_t) -1,
1775 SSDATA (format_string),
1776 SBYTES (format_string),
1777 tm, ut, ns);
1778 UNBLOCK_INPUT;
1779 size = result + 1;
1783 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1784 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
1785 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
1786 as from `current-time' and `file-attributes', or nil to use the
1787 current time. The obsolete form (HIGH . LOW) is also still accepted.
1788 The list has the following nine members: SEC is an integer between 0
1789 and 60; SEC is 60 for a leap second, which only some operating systems
1790 support. MINUTE is an integer between 0 and 59. HOUR is an integer
1791 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
1792 integer between 1 and 12. YEAR is an integer indicating the
1793 four-digit year. DOW is the day of week, an integer between 0 and 6,
1794 where 0 is Sunday. DST is t if daylight saving time is in effect,
1795 otherwise nil. ZONE is an integer indicating the number of seconds
1796 east of Greenwich. (Note that Common Lisp has different meanings for
1797 DOW and ZONE.) */)
1798 (Lisp_Object specified_time)
1800 time_t time_spec;
1801 struct tm save_tm;
1802 struct tm *decoded_time;
1803 Lisp_Object list_args[9];
1805 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1806 error ("Invalid time specification");
1808 BLOCK_INPUT;
1809 decoded_time = localtime (&time_spec);
1810 UNBLOCK_INPUT;
1811 if (! (decoded_time
1812 && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= decoded_time->tm_year
1813 && decoded_time->tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE))
1814 time_overflow ();
1815 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1816 XSETFASTINT (list_args[1], decoded_time->tm_min);
1817 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1818 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1819 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1820 /* On 64-bit machines an int is narrower than EMACS_INT, thus the
1821 cast below avoids overflow in int arithmetics. */
1822 XSETINT (list_args[5], TM_YEAR_BASE + (EMACS_INT) decoded_time->tm_year);
1823 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1824 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1826 /* Make a copy, in case gmtime modifies the struct. */
1827 save_tm = *decoded_time;
1828 BLOCK_INPUT;
1829 decoded_time = gmtime (&time_spec);
1830 UNBLOCK_INPUT;
1831 if (decoded_time == 0)
1832 list_args[8] = Qnil;
1833 else
1834 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1835 return Flist (9, list_args);
1838 /* Return OBJ - OFFSET, checking that OBJ is a valid fixnum and that
1839 the result is representable as an int. Assume OFFSET is small and
1840 nonnegative. */
1841 static int
1842 check_tm_member (Lisp_Object obj, int offset)
1844 EMACS_INT n;
1845 CHECK_NUMBER (obj);
1846 n = XINT (obj);
1847 if (! (INT_MIN + offset <= n && n - offset <= INT_MAX))
1848 time_overflow ();
1849 return n - offset;
1852 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1853 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
1854 This is the reverse operation of `decode-time', which see.
1855 ZONE defaults to the current time zone rule. This can
1856 be a string or t (as from `set-time-zone-rule'), or it can be a list
1857 \(as from `current-time-zone') or an integer (as from `decode-time')
1858 applied without consideration for daylight saving time.
1860 You can pass more than 7 arguments; then the first six arguments
1861 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
1862 The intervening arguments are ignored.
1863 This feature lets (apply 'encode-time (decode-time ...)) work.
1865 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
1866 for example, a DAY of 0 means the day preceding the given month.
1867 Year numbers less than 100 are treated just like other year numbers.
1868 If you want them to stand for years in this century, you must do that yourself.
1870 Years before 1970 are not guaranteed to work. On some systems,
1871 year values as low as 1901 do work.
1873 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
1874 (size_t nargs, register Lisp_Object *args)
1876 time_t value;
1877 struct tm tm;
1878 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1880 tm.tm_sec = check_tm_member (args[0], 0);
1881 tm.tm_min = check_tm_member (args[1], 0);
1882 tm.tm_hour = check_tm_member (args[2], 0);
1883 tm.tm_mday = check_tm_member (args[3], 0);
1884 tm.tm_mon = check_tm_member (args[4], 1);
1885 tm.tm_year = check_tm_member (args[5], TM_YEAR_BASE);
1886 tm.tm_isdst = -1;
1888 if (CONSP (zone))
1889 zone = Fcar (zone);
1890 if (NILP (zone))
1892 BLOCK_INPUT;
1893 value = mktime (&tm);
1894 UNBLOCK_INPUT;
1896 else
1898 char tzbuf[100];
1899 const char *tzstring;
1900 char **oldenv = environ, **newenv;
1902 if (EQ (zone, Qt))
1903 tzstring = "UTC0";
1904 else if (STRINGP (zone))
1905 tzstring = SSDATA (zone);
1906 else if (INTEGERP (zone))
1908 int abszone = eabs (XINT (zone));
1909 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1910 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1911 tzstring = tzbuf;
1913 else
1914 error ("Invalid time zone specification");
1916 /* Set TZ before calling mktime; merely adjusting mktime's returned
1917 value doesn't suffice, since that would mishandle leap seconds. */
1918 set_time_zone_rule (tzstring);
1920 BLOCK_INPUT;
1921 value = mktime (&tm);
1922 UNBLOCK_INPUT;
1924 /* Restore TZ to previous value. */
1925 newenv = environ;
1926 environ = oldenv;
1927 xfree (newenv);
1928 #ifdef LOCALTIME_CACHE
1929 tzset ();
1930 #endif
1933 if (value == (time_t) -1)
1934 time_overflow ();
1936 return make_time (value);
1939 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1940 doc: /* Return the current local time, as a human-readable string.
1941 Programs can use this function to decode a time,
1942 since the number of columns in each field is fixed
1943 if the year is in the range 1000-9999.
1944 The format is `Sun Sep 16 01:03:52 1973'.
1945 However, see also the functions `decode-time' and `format-time-string'
1946 which provide a much more powerful and general facility.
1948 If SPECIFIED-TIME is given, it is a time to format instead of the
1949 current time. The argument should have the form (HIGH LOW . IGNORED).
1950 Thus, you can use times obtained from `current-time' and from
1951 `file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
1952 but this is considered obsolete. */)
1953 (Lisp_Object specified_time)
1955 time_t value;
1956 struct tm *tm;
1957 register char *tem;
1959 if (! lisp_time_argument (specified_time, &value, NULL))
1960 error ("Invalid time specification");
1962 /* Convert to a string, checking for out-of-range time stamps.
1963 Don't use 'ctime', as that might dump core if VALUE is out of
1964 range. */
1965 BLOCK_INPUT;
1966 tm = localtime (&value);
1967 UNBLOCK_INPUT;
1968 if (! (tm && TM_YEAR_IN_ASCTIME_RANGE (tm->tm_year) && (tem = asctime (tm))))
1969 time_overflow ();
1971 /* Remove the trailing newline. */
1972 tem[strlen (tem) - 1] = '\0';
1974 return build_string (tem);
1977 /* Yield A - B, measured in seconds.
1978 This function is copied from the GNU C Library. */
1979 static int
1980 tm_diff (struct tm *a, struct tm *b)
1982 /* Compute intervening leap days correctly even if year is negative.
1983 Take care to avoid int overflow in leap day calculations,
1984 but it's OK to assume that A and B are close to each other. */
1985 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1986 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1987 int a100 = a4 / 25 - (a4 % 25 < 0);
1988 int b100 = b4 / 25 - (b4 % 25 < 0);
1989 int a400 = a100 >> 2;
1990 int b400 = b100 >> 2;
1991 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1992 int years = a->tm_year - b->tm_year;
1993 int days = (365 * years + intervening_leap_days
1994 + (a->tm_yday - b->tm_yday));
1995 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1996 + (a->tm_min - b->tm_min))
1997 + (a->tm_sec - b->tm_sec));
2000 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
2001 doc: /* Return the offset and name for the local time zone.
2002 This returns a list of the form (OFFSET NAME).
2003 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
2004 A negative value means west of Greenwich.
2005 NAME is a string giving the name of the time zone.
2006 If SPECIFIED-TIME is given, the time zone offset is determined from it
2007 instead of using the current time. The argument should have the form
2008 (HIGH LOW . IGNORED). Thus, you can use times obtained from
2009 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
2010 have the form (HIGH . LOW), but this is considered obsolete.
2012 Some operating systems cannot provide all this information to Emacs;
2013 in this case, `current-time-zone' returns a list containing nil for
2014 the data it can't find. */)
2015 (Lisp_Object specified_time)
2017 time_t value;
2018 struct tm *t;
2019 struct tm gmt;
2021 if (!lisp_time_argument (specified_time, &value, NULL))
2022 t = NULL;
2023 else
2025 BLOCK_INPUT;
2026 t = gmtime (&value);
2027 if (t)
2029 gmt = *t;
2030 t = localtime (&value);
2032 UNBLOCK_INPUT;
2035 if (t)
2037 int offset = tm_diff (t, &gmt);
2038 char *s = 0;
2039 char buf[6];
2041 #ifdef HAVE_TM_ZONE
2042 if (t->tm_zone)
2043 s = (char *)t->tm_zone;
2044 #else /* not HAVE_TM_ZONE */
2045 #ifdef HAVE_TZNAME
2046 if (t->tm_isdst == 0 || t->tm_isdst == 1)
2047 s = tzname[t->tm_isdst];
2048 #endif
2049 #endif /* not HAVE_TM_ZONE */
2051 if (!s)
2053 /* No local time zone name is available; use "+-NNNN" instead. */
2054 int am = (offset < 0 ? -offset : offset) / 60;
2055 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
2056 s = buf;
2059 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
2061 else
2062 return Fmake_list (make_number (2), Qnil);
2065 /* This holds the value of `environ' produced by the previous
2066 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
2067 has never been called. */
2068 static char **environbuf;
2070 /* This holds the startup value of the TZ environment variable so it
2071 can be restored if the user calls set-time-zone-rule with a nil
2072 argument. */
2073 static char *initial_tz;
2075 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2076 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
2077 If TZ is nil, use implementation-defined default time zone information.
2078 If TZ is t, use Universal Time. */)
2079 (Lisp_Object tz)
2081 const char *tzstring;
2083 /* When called for the first time, save the original TZ. */
2084 if (!environbuf)
2085 initial_tz = (char *) getenv ("TZ");
2087 if (NILP (tz))
2088 tzstring = initial_tz;
2089 else if (EQ (tz, Qt))
2090 tzstring = "UTC0";
2091 else
2093 CHECK_STRING (tz);
2094 tzstring = SSDATA (tz);
2097 set_time_zone_rule (tzstring);
2098 free (environbuf);
2099 environbuf = environ;
2101 return Qnil;
2104 #ifdef LOCALTIME_CACHE
2106 /* These two values are known to load tz files in buggy implementations,
2107 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
2108 Their values shouldn't matter in non-buggy implementations.
2109 We don't use string literals for these strings,
2110 since if a string in the environment is in readonly
2111 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
2112 See Sun bugs 1113095 and 1114114, ``Timezone routines
2113 improperly modify environment''. */
2115 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
2116 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
2118 #endif
2120 /* Set the local time zone rule to TZSTRING.
2121 This allocates memory into `environ', which it is the caller's
2122 responsibility to free. */
2124 void
2125 set_time_zone_rule (const char *tzstring)
2127 int envptrs;
2128 char **from, **to, **newenv;
2130 /* Make the ENVIRON vector longer with room for TZSTRING. */
2131 for (from = environ; *from; from++)
2132 continue;
2133 envptrs = from - environ + 2;
2134 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
2135 + (tzstring ? strlen (tzstring) + 4 : 0));
2137 /* Add TZSTRING to the end of environ, as a value for TZ. */
2138 if (tzstring)
2140 char *t = (char *) (to + envptrs);
2141 strcpy (t, "TZ=");
2142 strcat (t, tzstring);
2143 *to++ = t;
2146 /* Copy the old environ vector elements into NEWENV,
2147 but don't copy the TZ variable.
2148 So we have only one definition of TZ, which came from TZSTRING. */
2149 for (from = environ; *from; from++)
2150 if (strncmp (*from, "TZ=", 3) != 0)
2151 *to++ = *from;
2152 *to = 0;
2154 environ = newenv;
2156 /* If we do have a TZSTRING, NEWENV points to the vector slot where
2157 the TZ variable is stored. If we do not have a TZSTRING,
2158 TO points to the vector slot which has the terminating null. */
2160 #ifdef LOCALTIME_CACHE
2162 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
2163 "US/Pacific" that loads a tz file, then changes to a value like
2164 "XXX0" that does not load a tz file, and then changes back to
2165 its original value, the last change is (incorrectly) ignored.
2166 Also, if TZ changes twice in succession to values that do
2167 not load a tz file, tzset can dump core (see Sun bug#1225179).
2168 The following code works around these bugs. */
2170 if (tzstring)
2172 /* Temporarily set TZ to a value that loads a tz file
2173 and that differs from tzstring. */
2174 char *tz = *newenv;
2175 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
2176 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
2177 tzset ();
2178 *newenv = tz;
2180 else
2182 /* The implied tzstring is unknown, so temporarily set TZ to
2183 two different values that each load a tz file. */
2184 *to = set_time_zone_rule_tz1;
2185 to[1] = 0;
2186 tzset ();
2187 *to = set_time_zone_rule_tz2;
2188 tzset ();
2189 *to = 0;
2192 /* Now TZ has the desired value, and tzset can be invoked safely. */
2195 tzset ();
2196 #endif
2199 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2200 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2201 type of object is Lisp_String). INHERIT is passed to
2202 INSERT_FROM_STRING_FUNC as the last argument. */
2204 static void
2205 general_insert_function (void (*insert_func)
2206 (const char *, EMACS_INT),
2207 void (*insert_from_string_func)
2208 (Lisp_Object, EMACS_INT, EMACS_INT,
2209 EMACS_INT, EMACS_INT, int),
2210 int inherit, size_t nargs, Lisp_Object *args)
2212 register size_t argnum;
2213 register Lisp_Object val;
2215 for (argnum = 0; argnum < nargs; argnum++)
2217 val = args[argnum];
2218 if (CHARACTERP (val))
2220 unsigned char str[MAX_MULTIBYTE_LENGTH];
2221 int len;
2223 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2224 len = CHAR_STRING (XFASTINT (val), str);
2225 else
2227 str[0] = (ASCII_CHAR_P (XINT (val))
2228 ? XINT (val)
2229 : multibyte_char_to_unibyte (XINT (val)));
2230 len = 1;
2232 (*insert_func) ((char *) str, len);
2234 else if (STRINGP (val))
2236 (*insert_from_string_func) (val, 0, 0,
2237 SCHARS (val),
2238 SBYTES (val),
2239 inherit);
2241 else
2242 wrong_type_argument (Qchar_or_string_p, val);
2246 void
2247 insert1 (Lisp_Object arg)
2249 Finsert (1, &arg);
2253 /* Callers passing one argument to Finsert need not gcpro the
2254 argument "array", since the only element of the array will
2255 not be used after calling insert or insert_from_string, so
2256 we don't care if it gets trashed. */
2258 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2259 doc: /* Insert the arguments, either strings or characters, at point.
2260 Point and before-insertion markers move forward to end up
2261 after the inserted text.
2262 Any other markers at the point of insertion remain before the text.
2264 If the current buffer is multibyte, unibyte strings are converted
2265 to multibyte for insertion (see `string-make-multibyte').
2266 If the current buffer is unibyte, multibyte strings are converted
2267 to unibyte for insertion (see `string-make-unibyte').
2269 When operating on binary data, it may be necessary to preserve the
2270 original bytes of a unibyte string when inserting it into a multibyte
2271 buffer; to accomplish this, apply `string-as-multibyte' to the string
2272 and insert the result.
2274 usage: (insert &rest ARGS) */)
2275 (size_t nargs, register Lisp_Object *args)
2277 general_insert_function (insert, insert_from_string, 0, nargs, args);
2278 return Qnil;
2281 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2282 0, MANY, 0,
2283 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2284 Point and before-insertion markers move forward to end up
2285 after the inserted text.
2286 Any other markers at the point of insertion remain before the text.
2288 If the current buffer is multibyte, unibyte strings are converted
2289 to multibyte for insertion (see `unibyte-char-to-multibyte').
2290 If the current buffer is unibyte, multibyte strings are converted
2291 to unibyte for insertion.
2293 usage: (insert-and-inherit &rest ARGS) */)
2294 (size_t nargs, register Lisp_Object *args)
2296 general_insert_function (insert_and_inherit, insert_from_string, 1,
2297 nargs, args);
2298 return Qnil;
2301 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2302 doc: /* Insert strings or characters at point, relocating markers after the text.
2303 Point and markers move forward to end up after the inserted text.
2305 If the current buffer is multibyte, unibyte strings are converted
2306 to multibyte for insertion (see `unibyte-char-to-multibyte').
2307 If the current buffer is unibyte, multibyte strings are converted
2308 to unibyte for insertion.
2310 usage: (insert-before-markers &rest ARGS) */)
2311 (size_t nargs, register Lisp_Object *args)
2313 general_insert_function (insert_before_markers,
2314 insert_from_string_before_markers, 0,
2315 nargs, args);
2316 return Qnil;
2319 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2320 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2321 doc: /* Insert text at point, relocating markers and inheriting properties.
2322 Point and markers move forward to end up after the inserted text.
2324 If the current buffer is multibyte, unibyte strings are converted
2325 to multibyte for insertion (see `unibyte-char-to-multibyte').
2326 If the current buffer is unibyte, multibyte strings are converted
2327 to unibyte for insertion.
2329 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2330 (size_t nargs, register Lisp_Object *args)
2332 general_insert_function (insert_before_markers_and_inherit,
2333 insert_from_string_before_markers, 1,
2334 nargs, args);
2335 return Qnil;
2338 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
2339 doc: /* Insert COUNT copies of CHARACTER.
2340 Point, and before-insertion markers, are relocated as in the function `insert'.
2341 The optional third arg INHERIT, if non-nil, says to inherit text properties
2342 from adjoining text, if those properties are sticky. */)
2343 (Lisp_Object character, Lisp_Object count, Lisp_Object inherit)
2345 register char *string;
2346 register EMACS_INT stringlen;
2347 register int i;
2348 register EMACS_INT n;
2349 int len;
2350 unsigned char str[MAX_MULTIBYTE_LENGTH];
2352 CHECK_NUMBER (character);
2353 CHECK_NUMBER (count);
2355 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2356 len = CHAR_STRING (XFASTINT (character), str);
2357 else
2358 str[0] = XFASTINT (character), len = 1;
2359 if (MOST_POSITIVE_FIXNUM / len < XINT (count))
2360 error ("Maximum buffer size would be exceeded");
2361 n = XINT (count) * len;
2362 if (n <= 0)
2363 return Qnil;
2364 stringlen = min (n, 256 * len);
2365 string = (char *) alloca (stringlen);
2366 for (i = 0; i < stringlen; i++)
2367 string[i] = str[i % len];
2368 while (n >= stringlen)
2370 QUIT;
2371 if (!NILP (inherit))
2372 insert_and_inherit (string, stringlen);
2373 else
2374 insert (string, stringlen);
2375 n -= stringlen;
2377 if (n > 0)
2379 if (!NILP (inherit))
2380 insert_and_inherit (string, n);
2381 else
2382 insert (string, n);
2384 return Qnil;
2387 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2388 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2389 Both arguments are required.
2390 BYTE is a number of the range 0..255.
2392 If BYTE is 128..255 and the current buffer is multibyte, the
2393 corresponding eight-bit character is inserted.
2395 Point, and before-insertion markers, are relocated as in the function `insert'.
2396 The optional third arg INHERIT, if non-nil, says to inherit text properties
2397 from adjoining text, if those properties are sticky. */)
2398 (Lisp_Object byte, Lisp_Object count, Lisp_Object inherit)
2400 CHECK_NUMBER (byte);
2401 if (XINT (byte) < 0 || XINT (byte) > 255)
2402 args_out_of_range_3 (byte, make_number (0), make_number (255));
2403 if (XINT (byte) >= 128
2404 && ! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2405 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2406 return Finsert_char (byte, count, inherit);
2410 /* Making strings from buffer contents. */
2412 /* Return a Lisp_String containing the text of the current buffer from
2413 START to END. If text properties are in use and the current buffer
2414 has properties in the range specified, the resulting string will also
2415 have them, if PROPS is nonzero.
2417 We don't want to use plain old make_string here, because it calls
2418 make_uninit_string, which can cause the buffer arena to be
2419 compacted. make_string has no way of knowing that the data has
2420 been moved, and thus copies the wrong data into the string. This
2421 doesn't effect most of the other users of make_string, so it should
2422 be left as is. But we should use this function when conjuring
2423 buffer substrings. */
2425 Lisp_Object
2426 make_buffer_string (EMACS_INT start, EMACS_INT end, int props)
2428 EMACS_INT start_byte = CHAR_TO_BYTE (start);
2429 EMACS_INT end_byte = CHAR_TO_BYTE (end);
2431 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2434 /* Return a Lisp_String containing the text of the current buffer from
2435 START / START_BYTE to END / END_BYTE.
2437 If text properties are in use and the current buffer
2438 has properties in the range specified, the resulting string will also
2439 have them, if PROPS is nonzero.
2441 We don't want to use plain old make_string here, because it calls
2442 make_uninit_string, which can cause the buffer arena to be
2443 compacted. make_string has no way of knowing that the data has
2444 been moved, and thus copies the wrong data into the string. This
2445 doesn't effect most of the other users of make_string, so it should
2446 be left as is. But we should use this function when conjuring
2447 buffer substrings. */
2449 Lisp_Object
2450 make_buffer_string_both (EMACS_INT start, EMACS_INT start_byte,
2451 EMACS_INT end, EMACS_INT end_byte, int props)
2453 Lisp_Object result, tem, tem1;
2455 if (start < GPT && GPT < end)
2456 move_gap (start);
2458 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2459 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2460 else
2461 result = make_uninit_string (end - start);
2462 memcpy (SDATA (result), BYTE_POS_ADDR (start_byte), end_byte - start_byte);
2464 /* If desired, update and copy the text properties. */
2465 if (props)
2467 update_buffer_properties (start, end);
2469 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2470 tem1 = Ftext_properties_at (make_number (start), Qnil);
2472 if (XINT (tem) != end || !NILP (tem1))
2473 copy_intervals_to_string (result, current_buffer, start,
2474 end - start);
2477 return result;
2480 /* Call Vbuffer_access_fontify_functions for the range START ... END
2481 in the current buffer, if necessary. */
2483 static void
2484 update_buffer_properties (EMACS_INT start, EMACS_INT end)
2486 /* If this buffer has some access functions,
2487 call them, specifying the range of the buffer being accessed. */
2488 if (!NILP (Vbuffer_access_fontify_functions))
2490 Lisp_Object args[3];
2491 Lisp_Object tem;
2493 args[0] = Qbuffer_access_fontify_functions;
2494 XSETINT (args[1], start);
2495 XSETINT (args[2], end);
2497 /* But don't call them if we can tell that the work
2498 has already been done. */
2499 if (!NILP (Vbuffer_access_fontified_property))
2501 tem = Ftext_property_any (args[1], args[2],
2502 Vbuffer_access_fontified_property,
2503 Qnil, Qnil);
2504 if (! NILP (tem))
2505 Frun_hook_with_args (3, args);
2507 else
2508 Frun_hook_with_args (3, args);
2512 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2513 doc: /* Return the contents of part of the current buffer as a string.
2514 The two arguments START and END are character positions;
2515 they can be in either order.
2516 The string returned is multibyte if the buffer is multibyte.
2518 This function copies the text properties of that part of the buffer
2519 into the result string; if you don't want the text properties,
2520 use `buffer-substring-no-properties' instead. */)
2521 (Lisp_Object start, Lisp_Object end)
2523 register EMACS_INT b, e;
2525 validate_region (&start, &end);
2526 b = XINT (start);
2527 e = XINT (end);
2529 return make_buffer_string (b, e, 1);
2532 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2533 Sbuffer_substring_no_properties, 2, 2, 0,
2534 doc: /* Return the characters of part of the buffer, without the text properties.
2535 The two arguments START and END are character positions;
2536 they can be in either order. */)
2537 (Lisp_Object start, Lisp_Object end)
2539 register EMACS_INT b, e;
2541 validate_region (&start, &end);
2542 b = XINT (start);
2543 e = XINT (end);
2545 return make_buffer_string (b, e, 0);
2548 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2549 doc: /* Return the contents of the current buffer as a string.
2550 If narrowing is in effect, this function returns only the visible part
2551 of the buffer. */)
2552 (void)
2554 return make_buffer_string (BEGV, ZV, 1);
2557 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2558 1, 3, 0,
2559 doc: /* Insert before point a substring of the contents of BUFFER.
2560 BUFFER may be a buffer or a buffer name.
2561 Arguments START and END are character positions specifying the substring.
2562 They default to the values of (point-min) and (point-max) in BUFFER. */)
2563 (Lisp_Object buffer, Lisp_Object start, Lisp_Object end)
2565 register EMACS_INT b, e, temp;
2566 register struct buffer *bp, *obuf;
2567 Lisp_Object buf;
2569 buf = Fget_buffer (buffer);
2570 if (NILP (buf))
2571 nsberror (buffer);
2572 bp = XBUFFER (buf);
2573 if (NILP (BVAR (bp, name)))
2574 error ("Selecting deleted buffer");
2576 if (NILP (start))
2577 b = BUF_BEGV (bp);
2578 else
2580 CHECK_NUMBER_COERCE_MARKER (start);
2581 b = XINT (start);
2583 if (NILP (end))
2584 e = BUF_ZV (bp);
2585 else
2587 CHECK_NUMBER_COERCE_MARKER (end);
2588 e = XINT (end);
2591 if (b > e)
2592 temp = b, b = e, e = temp;
2594 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2595 args_out_of_range (start, end);
2597 obuf = current_buffer;
2598 set_buffer_internal_1 (bp);
2599 update_buffer_properties (b, e);
2600 set_buffer_internal_1 (obuf);
2602 insert_from_buffer (bp, b, e - b, 0);
2603 return Qnil;
2606 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2607 6, 6, 0,
2608 doc: /* Compare two substrings of two buffers; return result as number.
2609 the value is -N if first string is less after N-1 chars,
2610 +N if first string is greater after N-1 chars, or 0 if strings match.
2611 Each substring is represented as three arguments: BUFFER, START and END.
2612 That makes six args in all, three for each substring.
2614 The value of `case-fold-search' in the current buffer
2615 determines whether case is significant or ignored. */)
2616 (Lisp_Object buffer1, Lisp_Object start1, Lisp_Object end1, Lisp_Object buffer2, Lisp_Object start2, Lisp_Object end2)
2618 register EMACS_INT begp1, endp1, begp2, endp2, temp;
2619 register struct buffer *bp1, *bp2;
2620 register Lisp_Object trt
2621 = (!NILP (BVAR (current_buffer, case_fold_search))
2622 ? BVAR (current_buffer, case_canon_table) : Qnil);
2623 EMACS_INT chars = 0;
2624 EMACS_INT i1, i2, i1_byte, i2_byte;
2626 /* Find the first buffer and its substring. */
2628 if (NILP (buffer1))
2629 bp1 = current_buffer;
2630 else
2632 Lisp_Object buf1;
2633 buf1 = Fget_buffer (buffer1);
2634 if (NILP (buf1))
2635 nsberror (buffer1);
2636 bp1 = XBUFFER (buf1);
2637 if (NILP (BVAR (bp1, name)))
2638 error ("Selecting deleted buffer");
2641 if (NILP (start1))
2642 begp1 = BUF_BEGV (bp1);
2643 else
2645 CHECK_NUMBER_COERCE_MARKER (start1);
2646 begp1 = XINT (start1);
2648 if (NILP (end1))
2649 endp1 = BUF_ZV (bp1);
2650 else
2652 CHECK_NUMBER_COERCE_MARKER (end1);
2653 endp1 = XINT (end1);
2656 if (begp1 > endp1)
2657 temp = begp1, begp1 = endp1, endp1 = temp;
2659 if (!(BUF_BEGV (bp1) <= begp1
2660 && begp1 <= endp1
2661 && endp1 <= BUF_ZV (bp1)))
2662 args_out_of_range (start1, end1);
2664 /* Likewise for second substring. */
2666 if (NILP (buffer2))
2667 bp2 = current_buffer;
2668 else
2670 Lisp_Object buf2;
2671 buf2 = Fget_buffer (buffer2);
2672 if (NILP (buf2))
2673 nsberror (buffer2);
2674 bp2 = XBUFFER (buf2);
2675 if (NILP (BVAR (bp2, name)))
2676 error ("Selecting deleted buffer");
2679 if (NILP (start2))
2680 begp2 = BUF_BEGV (bp2);
2681 else
2683 CHECK_NUMBER_COERCE_MARKER (start2);
2684 begp2 = XINT (start2);
2686 if (NILP (end2))
2687 endp2 = BUF_ZV (bp2);
2688 else
2690 CHECK_NUMBER_COERCE_MARKER (end2);
2691 endp2 = XINT (end2);
2694 if (begp2 > endp2)
2695 temp = begp2, begp2 = endp2, endp2 = temp;
2697 if (!(BUF_BEGV (bp2) <= begp2
2698 && begp2 <= endp2
2699 && endp2 <= BUF_ZV (bp2)))
2700 args_out_of_range (start2, end2);
2702 i1 = begp1;
2703 i2 = begp2;
2704 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2705 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2707 while (i1 < endp1 && i2 < endp2)
2709 /* When we find a mismatch, we must compare the
2710 characters, not just the bytes. */
2711 int c1, c2;
2713 QUIT;
2715 if (! NILP (BVAR (bp1, enable_multibyte_characters)))
2717 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2718 BUF_INC_POS (bp1, i1_byte);
2719 i1++;
2721 else
2723 c1 = BUF_FETCH_BYTE (bp1, i1);
2724 MAKE_CHAR_MULTIBYTE (c1);
2725 i1++;
2728 if (! NILP (BVAR (bp2, enable_multibyte_characters)))
2730 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2731 BUF_INC_POS (bp2, i2_byte);
2732 i2++;
2734 else
2736 c2 = BUF_FETCH_BYTE (bp2, i2);
2737 MAKE_CHAR_MULTIBYTE (c2);
2738 i2++;
2741 if (!NILP (trt))
2743 c1 = CHAR_TABLE_TRANSLATE (trt, c1);
2744 c2 = CHAR_TABLE_TRANSLATE (trt, c2);
2746 if (c1 < c2)
2747 return make_number (- 1 - chars);
2748 if (c1 > c2)
2749 return make_number (chars + 1);
2751 chars++;
2754 /* The strings match as far as they go.
2755 If one is shorter, that one is less. */
2756 if (chars < endp1 - begp1)
2757 return make_number (chars + 1);
2758 else if (chars < endp2 - begp2)
2759 return make_number (- chars - 1);
2761 /* Same length too => they are equal. */
2762 return make_number (0);
2765 static Lisp_Object
2766 subst_char_in_region_unwind (Lisp_Object arg)
2768 return BVAR (current_buffer, undo_list) = arg;
2771 static Lisp_Object
2772 subst_char_in_region_unwind_1 (Lisp_Object arg)
2774 return BVAR (current_buffer, filename) = arg;
2777 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2778 Ssubst_char_in_region, 4, 5, 0,
2779 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
2780 If optional arg NOUNDO is non-nil, don't record this change for undo
2781 and don't mark the buffer as really changed.
2782 Both characters must have the same length of multi-byte form. */)
2783 (Lisp_Object start, Lisp_Object end, Lisp_Object fromchar, Lisp_Object tochar, Lisp_Object noundo)
2785 register EMACS_INT pos, pos_byte, stop, i, len, end_byte;
2786 /* Keep track of the first change in the buffer:
2787 if 0 we haven't found it yet.
2788 if < 0 we've found it and we've run the before-change-function.
2789 if > 0 we've actually performed it and the value is its position. */
2790 EMACS_INT changed = 0;
2791 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2792 unsigned char *p;
2793 int count = SPECPDL_INDEX ();
2794 #define COMBINING_NO 0
2795 #define COMBINING_BEFORE 1
2796 #define COMBINING_AFTER 2
2797 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2798 int maybe_byte_combining = COMBINING_NO;
2799 EMACS_INT last_changed = 0;
2800 int multibyte_p = !NILP (BVAR (current_buffer, enable_multibyte_characters));
2802 restart:
2804 validate_region (&start, &end);
2805 CHECK_NUMBER (fromchar);
2806 CHECK_NUMBER (tochar);
2808 if (multibyte_p)
2810 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2811 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
2812 error ("Characters in `subst-char-in-region' have different byte-lengths");
2813 if (!ASCII_BYTE_P (*tostr))
2815 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2816 complete multibyte character, it may be combined with the
2817 after bytes. If it is in the range 0xA0..0xFF, it may be
2818 combined with the before and after bytes. */
2819 if (!CHAR_HEAD_P (*tostr))
2820 maybe_byte_combining = COMBINING_BOTH;
2821 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2822 maybe_byte_combining = COMBINING_AFTER;
2825 else
2827 len = 1;
2828 fromstr[0] = XFASTINT (fromchar);
2829 tostr[0] = XFASTINT (tochar);
2832 pos = XINT (start);
2833 pos_byte = CHAR_TO_BYTE (pos);
2834 stop = CHAR_TO_BYTE (XINT (end));
2835 end_byte = stop;
2837 /* If we don't want undo, turn off putting stuff on the list.
2838 That's faster than getting rid of things,
2839 and it prevents even the entry for a first change.
2840 Also inhibit locking the file. */
2841 if (!changed && !NILP (noundo))
2843 record_unwind_protect (subst_char_in_region_unwind,
2844 BVAR (current_buffer, undo_list));
2845 BVAR (current_buffer, undo_list) = Qt;
2846 /* Don't do file-locking. */
2847 record_unwind_protect (subst_char_in_region_unwind_1,
2848 BVAR (current_buffer, filename));
2849 BVAR (current_buffer, filename) = Qnil;
2852 if (pos_byte < GPT_BYTE)
2853 stop = min (stop, GPT_BYTE);
2854 while (1)
2856 EMACS_INT pos_byte_next = pos_byte;
2858 if (pos_byte >= stop)
2860 if (pos_byte >= end_byte) break;
2861 stop = end_byte;
2863 p = BYTE_POS_ADDR (pos_byte);
2864 if (multibyte_p)
2865 INC_POS (pos_byte_next);
2866 else
2867 ++pos_byte_next;
2868 if (pos_byte_next - pos_byte == len
2869 && p[0] == fromstr[0]
2870 && (len == 1
2871 || (p[1] == fromstr[1]
2872 && (len == 2 || (p[2] == fromstr[2]
2873 && (len == 3 || p[3] == fromstr[3]))))))
2875 if (changed < 0)
2876 /* We've already seen this and run the before-change-function;
2877 this time we only need to record the actual position. */
2878 changed = pos;
2879 else if (!changed)
2881 changed = -1;
2882 modify_region (current_buffer, pos, XINT (end), 0);
2884 if (! NILP (noundo))
2886 if (MODIFF - 1 == SAVE_MODIFF)
2887 SAVE_MODIFF++;
2888 if (MODIFF - 1 == BUF_AUTOSAVE_MODIFF (current_buffer))
2889 BUF_AUTOSAVE_MODIFF (current_buffer)++;
2892 /* The before-change-function may have moved the gap
2893 or even modified the buffer so we should start over. */
2894 goto restart;
2897 /* Take care of the case where the new character
2898 combines with neighboring bytes. */
2899 if (maybe_byte_combining
2900 && (maybe_byte_combining == COMBINING_AFTER
2901 ? (pos_byte_next < Z_BYTE
2902 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2903 : ((pos_byte_next < Z_BYTE
2904 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2905 || (pos_byte > BEG_BYTE
2906 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2908 Lisp_Object tem, string;
2910 struct gcpro gcpro1;
2912 tem = BVAR (current_buffer, undo_list);
2913 GCPRO1 (tem);
2915 /* Make a multibyte string containing this single character. */
2916 string = make_multibyte_string ((char *) tostr, 1, len);
2917 /* replace_range is less efficient, because it moves the gap,
2918 but it handles combining correctly. */
2919 replace_range (pos, pos + 1, string,
2920 0, 0, 1);
2921 pos_byte_next = CHAR_TO_BYTE (pos);
2922 if (pos_byte_next > pos_byte)
2923 /* Before combining happened. We should not increment
2924 POS. So, to cancel the later increment of POS,
2925 decrease it now. */
2926 pos--;
2927 else
2928 INC_POS (pos_byte_next);
2930 if (! NILP (noundo))
2931 BVAR (current_buffer, undo_list) = tem;
2933 UNGCPRO;
2935 else
2937 if (NILP (noundo))
2938 record_change (pos, 1);
2939 for (i = 0; i < len; i++) *p++ = tostr[i];
2941 last_changed = pos + 1;
2943 pos_byte = pos_byte_next;
2944 pos++;
2947 if (changed > 0)
2949 signal_after_change (changed,
2950 last_changed - changed, last_changed - changed);
2951 update_compositions (changed, last_changed, CHECK_ALL);
2954 unbind_to (count, Qnil);
2955 return Qnil;
2959 static Lisp_Object check_translation (EMACS_INT, EMACS_INT, EMACS_INT,
2960 Lisp_Object);
2962 /* Helper function for Ftranslate_region_internal.
2964 Check if a character sequence at POS (POS_BYTE) matches an element
2965 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
2966 element is found, return it. Otherwise return Qnil. */
2968 static Lisp_Object
2969 check_translation (EMACS_INT pos, EMACS_INT pos_byte, EMACS_INT end,
2970 Lisp_Object val)
2972 int buf_size = 16, buf_used = 0;
2973 int *buf = alloca (sizeof (int) * buf_size);
2975 for (; CONSP (val); val = XCDR (val))
2977 Lisp_Object elt;
2978 EMACS_INT len, i;
2980 elt = XCAR (val);
2981 if (! CONSP (elt))
2982 continue;
2983 elt = XCAR (elt);
2984 if (! VECTORP (elt))
2985 continue;
2986 len = ASIZE (elt);
2987 if (len <= end - pos)
2989 for (i = 0; i < len; i++)
2991 if (buf_used <= i)
2993 unsigned char *p = BYTE_POS_ADDR (pos_byte);
2994 int len1;
2996 if (buf_used == buf_size)
2998 int *newbuf;
3000 buf_size += 16;
3001 newbuf = alloca (sizeof (int) * buf_size);
3002 memcpy (newbuf, buf, sizeof (int) * buf_used);
3003 buf = newbuf;
3005 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len1);
3006 pos_byte += len1;
3008 if (XINT (AREF (elt, i)) != buf[i])
3009 break;
3011 if (i == len)
3012 return XCAR (val);
3015 return Qnil;
3019 DEFUN ("translate-region-internal", Ftranslate_region_internal,
3020 Stranslate_region_internal, 3, 3, 0,
3021 doc: /* Internal use only.
3022 From START to END, translate characters according to TABLE.
3023 TABLE is a string or a char-table; the Nth character in it is the
3024 mapping for the character with code N.
3025 It returns the number of characters changed. */)
3026 (Lisp_Object start, Lisp_Object end, register Lisp_Object table)
3028 register unsigned char *tt; /* Trans table. */
3029 register int nc; /* New character. */
3030 int cnt; /* Number of changes made. */
3031 EMACS_INT size; /* Size of translate table. */
3032 EMACS_INT pos, pos_byte, end_pos;
3033 int multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3034 int string_multibyte IF_LINT (= 0);
3036 validate_region (&start, &end);
3037 if (CHAR_TABLE_P (table))
3039 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3040 error ("Not a translation table");
3041 size = MAX_CHAR;
3042 tt = NULL;
3044 else
3046 CHECK_STRING (table);
3048 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3049 table = string_make_unibyte (table);
3050 string_multibyte = SCHARS (table) < SBYTES (table);
3051 size = SBYTES (table);
3052 tt = SDATA (table);
3055 pos = XINT (start);
3056 pos_byte = CHAR_TO_BYTE (pos);
3057 end_pos = XINT (end);
3058 modify_region (current_buffer, pos, end_pos, 0);
3060 cnt = 0;
3061 for (; pos < end_pos; )
3063 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
3064 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3065 int len, str_len;
3066 int oc;
3067 Lisp_Object val;
3069 if (multibyte)
3070 oc = STRING_CHAR_AND_LENGTH (p, len);
3071 else
3072 oc = *p, len = 1;
3073 if (oc < size)
3075 if (tt)
3077 /* Reload as signal_after_change in last iteration may GC. */
3078 tt = SDATA (table);
3079 if (string_multibyte)
3081 str = tt + string_char_to_byte (table, oc);
3082 nc = STRING_CHAR_AND_LENGTH (str, str_len);
3084 else
3086 nc = tt[oc];
3087 if (! ASCII_BYTE_P (nc) && multibyte)
3089 str_len = BYTE8_STRING (nc, buf);
3090 str = buf;
3092 else
3094 str_len = 1;
3095 str = tt + oc;
3099 else
3101 EMACS_INT c;
3103 nc = oc;
3104 val = CHAR_TABLE_REF (table, oc);
3105 if (CHARACTERP (val)
3106 && (c = XINT (val), CHAR_VALID_P (c, 0)))
3108 nc = c;
3109 str_len = CHAR_STRING (nc, buf);
3110 str = buf;
3112 else if (VECTORP (val) || (CONSP (val)))
3114 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3115 where TO is TO-CHAR or [TO-CHAR ...]. */
3116 nc = -1;
3120 if (nc != oc && nc >= 0)
3122 /* Simple one char to one char translation. */
3123 if (len != str_len)
3125 Lisp_Object string;
3127 /* This is less efficient, because it moves the gap,
3128 but it should handle multibyte characters correctly. */
3129 string = make_multibyte_string ((char *) str, 1, str_len);
3130 replace_range (pos, pos + 1, string, 1, 0, 1);
3131 len = str_len;
3133 else
3135 record_change (pos, 1);
3136 while (str_len-- > 0)
3137 *p++ = *str++;
3138 signal_after_change (pos, 1, 1);
3139 update_compositions (pos, pos + 1, CHECK_BORDER);
3141 ++cnt;
3143 else if (nc < 0)
3145 Lisp_Object string;
3147 if (CONSP (val))
3149 val = check_translation (pos, pos_byte, end_pos, val);
3150 if (NILP (val))
3152 pos_byte += len;
3153 pos++;
3154 continue;
3156 /* VAL is ([FROM-CHAR ...] . TO). */
3157 len = ASIZE (XCAR (val));
3158 val = XCDR (val);
3160 else
3161 len = 1;
3163 if (VECTORP (val))
3165 string = Fconcat (1, &val);
3167 else
3169 string = Fmake_string (make_number (1), val);
3171 replace_range (pos, pos + len, string, 1, 0, 1);
3172 pos_byte += SBYTES (string);
3173 pos += SCHARS (string);
3174 cnt += SCHARS (string);
3175 end_pos += SCHARS (string) - len;
3176 continue;
3179 pos_byte += len;
3180 pos++;
3183 return make_number (cnt);
3186 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3187 doc: /* Delete the text between point and mark.
3189 When called from a program, expects two arguments,
3190 positions (integers or markers) specifying the stretch to be deleted. */)
3191 (Lisp_Object start, Lisp_Object end)
3193 validate_region (&start, &end);
3194 del_range (XINT (start), XINT (end));
3195 return Qnil;
3198 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3199 Sdelete_and_extract_region, 2, 2, 0,
3200 doc: /* Delete the text between START and END and return it. */)
3201 (Lisp_Object start, Lisp_Object end)
3203 validate_region (&start, &end);
3204 if (XINT (start) == XINT (end))
3205 return empty_unibyte_string;
3206 return del_range_1 (XINT (start), XINT (end), 1, 1);
3209 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3210 doc: /* Remove restrictions (narrowing) from current buffer.
3211 This allows the buffer's full text to be seen and edited. */)
3212 (void)
3214 if (BEG != BEGV || Z != ZV)
3215 current_buffer->clip_changed = 1;
3216 BEGV = BEG;
3217 BEGV_BYTE = BEG_BYTE;
3218 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3219 /* Changing the buffer bounds invalidates any recorded current column. */
3220 invalidate_current_column ();
3221 return Qnil;
3224 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3225 doc: /* Restrict editing in this buffer to the current region.
3226 The rest of the text becomes temporarily invisible and untouchable
3227 but is not deleted; if you save the buffer in a file, the invisible
3228 text is included in the file. \\[widen] makes all visible again.
3229 See also `save-restriction'.
3231 When calling from a program, pass two arguments; positions (integers
3232 or markers) bounding the text that should remain visible. */)
3233 (register Lisp_Object start, Lisp_Object end)
3235 CHECK_NUMBER_COERCE_MARKER (start);
3236 CHECK_NUMBER_COERCE_MARKER (end);
3238 if (XINT (start) > XINT (end))
3240 Lisp_Object tem;
3241 tem = start; start = end; end = tem;
3244 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3245 args_out_of_range (start, end);
3247 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3248 current_buffer->clip_changed = 1;
3250 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3251 SET_BUF_ZV (current_buffer, XFASTINT (end));
3252 if (PT < XFASTINT (start))
3253 SET_PT (XFASTINT (start));
3254 if (PT > XFASTINT (end))
3255 SET_PT (XFASTINT (end));
3256 /* Changing the buffer bounds invalidates any recorded current column. */
3257 invalidate_current_column ();
3258 return Qnil;
3261 Lisp_Object
3262 save_restriction_save (void)
3264 if (BEGV == BEG && ZV == Z)
3265 /* The common case that the buffer isn't narrowed.
3266 We return just the buffer object, which save_restriction_restore
3267 recognizes as meaning `no restriction'. */
3268 return Fcurrent_buffer ();
3269 else
3270 /* We have to save a restriction, so return a pair of markers, one
3271 for the beginning and one for the end. */
3273 Lisp_Object beg, end;
3275 beg = buildmark (BEGV, BEGV_BYTE);
3276 end = buildmark (ZV, ZV_BYTE);
3278 /* END must move forward if text is inserted at its exact location. */
3279 XMARKER(end)->insertion_type = 1;
3281 return Fcons (beg, end);
3285 Lisp_Object
3286 save_restriction_restore (Lisp_Object data)
3288 struct buffer *cur = NULL;
3289 struct buffer *buf = (CONSP (data)
3290 ? XMARKER (XCAR (data))->buffer
3291 : XBUFFER (data));
3293 if (buf && buf != current_buffer && !NILP (BVAR (buf, pt_marker)))
3294 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3295 is the case if it is or has an indirect buffer), then make
3296 sure it is current before we update BEGV, so
3297 set_buffer_internal takes care of managing those markers. */
3298 cur = current_buffer;
3299 set_buffer_internal (buf);
3302 if (CONSP (data))
3303 /* A pair of marks bounding a saved restriction. */
3305 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3306 struct Lisp_Marker *end = XMARKER (XCDR (data));
3307 eassert (buf == end->buffer);
3309 if (buf /* Verify marker still points to a buffer. */
3310 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3311 /* The restriction has changed from the saved one, so restore
3312 the saved restriction. */
3314 EMACS_INT pt = BUF_PT (buf);
3316 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3317 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3319 if (pt < beg->charpos || pt > end->charpos)
3320 /* The point is outside the new visible range, move it inside. */
3321 SET_BUF_PT_BOTH (buf,
3322 clip_to_bounds (beg->charpos, pt, end->charpos),
3323 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3324 end->bytepos));
3326 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3329 else
3330 /* A buffer, which means that there was no old restriction. */
3332 if (buf /* Verify marker still points to a buffer. */
3333 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3334 /* The buffer has been narrowed, get rid of the narrowing. */
3336 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3337 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3339 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3343 /* Changing the buffer bounds invalidates any recorded current column. */
3344 invalidate_current_column ();
3346 if (cur)
3347 set_buffer_internal (cur);
3349 return Qnil;
3352 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3353 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3354 The buffer's restrictions make parts of the beginning and end invisible.
3355 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3356 This special form, `save-restriction', saves the current buffer's restrictions
3357 when it is entered, and restores them when it is exited.
3358 So any `narrow-to-region' within BODY lasts only until the end of the form.
3359 The old restrictions settings are restored
3360 even in case of abnormal exit (throw or error).
3362 The value returned is the value of the last form in BODY.
3364 Note: if you are using both `save-excursion' and `save-restriction',
3365 use `save-excursion' outermost:
3366 (save-excursion (save-restriction ...))
3368 usage: (save-restriction &rest BODY) */)
3369 (Lisp_Object body)
3371 register Lisp_Object val;
3372 int count = SPECPDL_INDEX ();
3374 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3375 val = Fprogn (body);
3376 return unbind_to (count, val);
3379 /* Buffer for the most recent text displayed by Fmessage_box. */
3380 static char *message_text;
3382 /* Allocated length of that buffer. */
3383 static int message_length;
3385 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3386 doc: /* Display a message at the bottom of the screen.
3387 The message also goes into the `*Messages*' buffer.
3388 \(In keyboard macros, that's all it does.)
3389 Return the message.
3391 The first argument is a format control string, and the rest are data
3392 to be formatted under control of the string. See `format' for details.
3394 Note: Use (message "%s" VALUE) to print the value of expressions and
3395 variables to avoid accidentally interpreting `%' as format specifiers.
3397 If the first argument is nil or the empty string, the function clears
3398 any existing message; this lets the minibuffer contents show. See
3399 also `current-message'.
3401 usage: (message FORMAT-STRING &rest ARGS) */)
3402 (size_t nargs, Lisp_Object *args)
3404 if (NILP (args[0])
3405 || (STRINGP (args[0])
3406 && SBYTES (args[0]) == 0))
3408 message (0);
3409 return args[0];
3411 else
3413 register Lisp_Object val;
3414 val = Fformat (nargs, args);
3415 message3 (val, SBYTES (val), STRING_MULTIBYTE (val));
3416 return val;
3420 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3421 doc: /* Display a message, in a dialog box if possible.
3422 If a dialog box is not available, use the echo area.
3423 The first argument is a format control string, and the rest are data
3424 to be formatted under control of the string. See `format' for details.
3426 If the first argument is nil or the empty string, clear any existing
3427 message; let the minibuffer contents show.
3429 usage: (message-box FORMAT-STRING &rest ARGS) */)
3430 (size_t nargs, Lisp_Object *args)
3432 if (NILP (args[0]))
3434 message (0);
3435 return Qnil;
3437 else
3439 register Lisp_Object val;
3440 val = Fformat (nargs, args);
3441 #ifdef HAVE_MENUS
3442 /* The MS-DOS frames support popup menus even though they are
3443 not FRAME_WINDOW_P. */
3444 if (FRAME_WINDOW_P (XFRAME (selected_frame))
3445 || FRAME_MSDOS_P (XFRAME (selected_frame)))
3447 Lisp_Object pane, menu;
3448 struct gcpro gcpro1;
3449 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
3450 GCPRO1 (pane);
3451 menu = Fcons (val, pane);
3452 Fx_popup_dialog (Qt, menu, Qt);
3453 UNGCPRO;
3454 return val;
3456 #endif /* HAVE_MENUS */
3457 /* Copy the data so that it won't move when we GC. */
3458 if (! message_text)
3460 message_text = (char *)xmalloc (80);
3461 message_length = 80;
3463 if (SBYTES (val) > message_length)
3465 message_length = SBYTES (val);
3466 message_text = (char *)xrealloc (message_text, message_length);
3468 memcpy (message_text, SDATA (val), SBYTES (val));
3469 message2 (message_text, SBYTES (val),
3470 STRING_MULTIBYTE (val));
3471 return val;
3475 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3476 doc: /* Display a message in a dialog box or in the echo area.
3477 If this command was invoked with the mouse, use a dialog box if
3478 `use-dialog-box' is non-nil.
3479 Otherwise, use the echo area.
3480 The first argument is a format control string, and the rest are data
3481 to be formatted under control of the string. See `format' for details.
3483 If the first argument is nil or the empty string, clear any existing
3484 message; let the minibuffer contents show.
3486 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3487 (size_t nargs, Lisp_Object *args)
3489 #ifdef HAVE_MENUS
3490 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3491 && use_dialog_box)
3492 return Fmessage_box (nargs, args);
3493 #endif
3494 return Fmessage (nargs, args);
3497 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3498 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3499 (void)
3501 return current_message ();
3505 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3506 doc: /* Return a copy of STRING with text properties added.
3507 First argument is the string to copy.
3508 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3509 properties to add to the result.
3510 usage: (propertize STRING &rest PROPERTIES) */)
3511 (size_t nargs, Lisp_Object *args)
3513 Lisp_Object properties, string;
3514 struct gcpro gcpro1, gcpro2;
3515 size_t i;
3517 /* Number of args must be odd. */
3518 if ((nargs & 1) == 0)
3519 error ("Wrong number of arguments");
3521 properties = string = Qnil;
3522 GCPRO2 (properties, string);
3524 /* First argument must be a string. */
3525 CHECK_STRING (args[0]);
3526 string = Fcopy_sequence (args[0]);
3528 for (i = 1; i < nargs; i += 2)
3529 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3531 Fadd_text_properties (make_number (0),
3532 make_number (SCHARS (string)),
3533 properties, string);
3534 RETURN_UNGCPRO (string);
3538 /* Number of bytes that STRING will occupy when put into the result.
3539 MULTIBYTE is nonzero if the result should be multibyte. */
3541 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3542 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
3543 ? count_size_as_multibyte (SDATA (STRING), SBYTES (STRING)) \
3544 : SBYTES (STRING))
3546 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3547 doc: /* Format a string out of a format-string and arguments.
3548 The first argument is a format control string.
3549 The other arguments are substituted into it to make the result, a string.
3551 The format control string may contain %-sequences meaning to substitute
3552 the next available argument:
3554 %s means print a string argument. Actually, prints any object, with `princ'.
3555 %d means print as number in decimal (%o octal, %x hex).
3556 %X is like %x, but uses upper case.
3557 %e means print a number in exponential notation.
3558 %f means print a number in decimal-point notation.
3559 %g means print a number in exponential notation
3560 or decimal-point notation, whichever uses fewer characters.
3561 %c means print a number as a single character.
3562 %S means print any object as an s-expression (using `prin1').
3564 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3565 Use %% to put a single % into the output.
3567 A %-sequence may contain optional flag, width, and precision
3568 specifiers, as follows:
3570 %<flags><width><precision>character
3572 where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3574 The + flag character inserts a + before any positive number, while a
3575 space inserts a space before any positive number; these flags only
3576 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3577 The # flag means to use an alternate display form for %o, %x, %X, %e,
3578 %f, and %g sequences. The - and 0 flags affect the width specifier,
3579 as described below.
3581 The width specifier supplies a lower limit for the length of the
3582 printed representation. The padding, if any, normally goes on the
3583 left, but it goes on the right if the - flag is present. The padding
3584 character is normally a space, but it is 0 if the 0 flag is present.
3585 The - flag takes precedence over the 0 flag.
3587 For %e, %f, and %g sequences, the number after the "." in the
3588 precision specifier says how many decimal places to show; if zero, the
3589 decimal point itself is omitted. For %s and %S, the precision
3590 specifier truncates the string to the given width.
3592 usage: (format STRING &rest OBJECTS) */)
3593 (size_t nargs, register Lisp_Object *args)
3595 register size_t n; /* The number of the next arg to substitute */
3596 register size_t total; /* An estimate of the final length */
3597 char *buf, *p;
3598 register char *format, *end, *format_start;
3599 int nchars;
3600 /* Nonzero if the output should be a multibyte string,
3601 which is true if any of the inputs is one. */
3602 int multibyte = 0;
3603 /* When we make a multibyte string, we must pay attention to the
3604 byte combining problem, i.e., a byte may be combined with a
3605 multibyte character of the previous string. This flag tells if we
3606 must consider such a situation or not. */
3607 int maybe_combine_byte;
3608 char *this_format;
3609 /* Precision for each spec, or -1, a flag value meaning no precision
3610 was given in that spec. Element 0, corresponding to the format
3611 string itself, will not be used. Element NARGS, corresponding to
3612 no argument, *will* be assigned to in the case that a `%' and `.'
3613 occur after the final format specifier. */
3614 int *precision = (int *) (alloca ((nargs + 1) * sizeof (int)));
3615 int longest_format;
3616 Lisp_Object val;
3617 int arg_intervals = 0;
3618 USE_SAFE_ALLOCA;
3620 /* discarded[I] is 1 if byte I of the format
3621 string was not copied into the output.
3622 It is 2 if byte I was not the first byte of its character. */
3623 char *discarded = 0;
3625 /* Each element records, for one argument,
3626 the start and end bytepos in the output string,
3627 and whether the argument is a string with intervals.
3628 info[0] is unused. Unused elements have -1 for start. */
3629 struct info
3631 int start, end, intervals;
3632 } *info = 0;
3634 /* It should not be necessary to GCPRO ARGS, because
3635 the caller in the interpreter should take care of that. */
3637 /* Try to determine whether the result should be multibyte.
3638 This is not always right; sometimes the result needs to be multibyte
3639 because of an object that we will pass through prin1,
3640 and in that case, we won't know it here. */
3641 for (n = 0; n < nargs; n++)
3643 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3644 multibyte = 1;
3645 /* Piggyback on this loop to initialize precision[N]. */
3646 precision[n] = -1;
3648 precision[nargs] = -1;
3650 CHECK_STRING (args[0]);
3651 /* We may have to change "%S" to "%s". */
3652 args[0] = Fcopy_sequence (args[0]);
3654 /* GC should never happen here, so abort if it does. */
3655 abort_on_gc++;
3657 /* If we start out planning a unibyte result,
3658 then discover it has to be multibyte, we jump back to retry.
3659 That can only happen from the first large while loop below. */
3660 retry:
3662 format = SSDATA (args[0]);
3663 format_start = format;
3664 end = format + SBYTES (args[0]);
3665 longest_format = 0;
3667 /* Make room in result for all the non-%-codes in the control string. */
3668 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]) + 1;
3670 /* Allocate the info and discarded tables. */
3672 size_t nbytes = (nargs+1) * sizeof *info;
3673 size_t i;
3674 if (!info)
3675 info = (struct info *) alloca (nbytes);
3676 memset (info, 0, nbytes);
3677 for (i = 0; i <= nargs; i++)
3678 info[i].start = -1;
3679 if (!discarded)
3680 SAFE_ALLOCA (discarded, char *, SBYTES (args[0]));
3681 memset (discarded, 0, SBYTES (args[0]));
3684 /* Add to TOTAL enough space to hold the converted arguments. */
3686 n = 0;
3687 while (format != end)
3688 if (*format++ == '%')
3690 EMACS_INT thissize = 0;
3691 EMACS_INT actual_width = 0;
3692 char *this_format_start = format - 1;
3693 int field_width = 0;
3695 /* General format specifications look like
3697 '%' [flags] [field-width] [precision] format
3699 where
3701 flags ::= [-+ #0]+
3702 field-width ::= [0-9]+
3703 precision ::= '.' [0-9]*
3705 If a field-width is specified, it specifies to which width
3706 the output should be padded with blanks, if the output
3707 string is shorter than field-width.
3709 If precision is specified, it specifies the number of
3710 digits to print after the '.' for floats, or the max.
3711 number of chars to print from a string. */
3713 while (format != end
3714 && (*format == '-' || *format == '0' || *format == '#'
3715 || * format == ' ' || *format == '+'))
3716 ++format;
3718 if (*format >= '0' && *format <= '9')
3720 for (field_width = 0; *format >= '0' && *format <= '9'; ++format)
3721 field_width = 10 * field_width + *format - '0';
3724 /* N is not incremented for another few lines below, so refer to
3725 element N+1 (which might be precision[NARGS]). */
3726 if (*format == '.')
3728 ++format;
3729 for (precision[n+1] = 0; *format >= '0' && *format <= '9'; ++format)
3730 precision[n+1] = 10 * precision[n+1] + *format - '0';
3733 /* Extra +1 for 'l' that we may need to insert into the
3734 format. */
3735 if (format - this_format_start + 2 > longest_format)
3736 longest_format = format - this_format_start + 2;
3738 if (format == end)
3739 error ("Format string ends in middle of format specifier");
3740 if (*format == '%')
3741 format++;
3742 else if (++n >= nargs)
3743 error ("Not enough arguments for format string");
3744 else if (*format == 'S')
3746 /* For `S', prin1 the argument and then treat like a string. */
3747 register Lisp_Object tem;
3748 tem = Fprin1_to_string (args[n], Qnil);
3749 if (STRING_MULTIBYTE (tem) && ! multibyte)
3751 multibyte = 1;
3752 goto retry;
3754 args[n] = tem;
3755 /* If we restart the loop, we should not come here again
3756 because args[n] is now a string and calling
3757 Fprin1_to_string on it produces superflous double
3758 quotes. So, change "%S" to "%s" now. */
3759 *format = 's';
3760 goto string;
3762 else if (SYMBOLP (args[n]))
3764 args[n] = SYMBOL_NAME (args[n]);
3765 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3767 multibyte = 1;
3768 goto retry;
3770 goto string;
3772 else if (STRINGP (args[n]))
3774 string:
3775 if (*format != 's' && *format != 'S')
3776 error ("Format specifier doesn't match argument type");
3777 /* In the case (PRECISION[N] > 0), THISSIZE may not need
3778 to be as large as is calculated here. Easy check for
3779 the case PRECISION = 0. */
3780 thissize = precision[n] ? CONVERTED_BYTE_SIZE (multibyte, args[n]) : 0;
3781 /* The precision also constrains how much of the argument
3782 string will finally appear (Bug#5710). */
3783 actual_width = lisp_string_width (args[n], -1, NULL, NULL);
3784 if (precision[n] != -1)
3785 actual_width = min (actual_width, precision[n]);
3787 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3788 else if (INTEGERP (args[n]) && *format != 's')
3790 /* The following loop assumes the Lisp type indicates
3791 the proper way to pass the argument.
3792 So make sure we have a flonum if the argument should
3793 be a double. */
3794 if (*format == 'e' || *format == 'f' || *format == 'g')
3795 args[n] = Ffloat (args[n]);
3796 else
3797 if (*format != 'd' && *format != 'o' && *format != 'x'
3798 && *format != 'i' && *format != 'X' && *format != 'c')
3799 error ("Invalid format operation %%%c", *format);
3801 thissize = 30 + (precision[n] > 0 ? precision[n] : 0);
3802 if (*format == 'c')
3804 if (! ASCII_CHAR_P (XINT (args[n]))
3805 /* Note: No one can remeber why we have to treat
3806 the character 0 as a multibyte character here.
3807 But, until it causes a real problem, let's
3808 don't change it. */
3809 || XINT (args[n]) == 0)
3811 if (! multibyte)
3813 multibyte = 1;
3814 goto retry;
3816 args[n] = Fchar_to_string (args[n]);
3817 thissize = SBYTES (args[n]);
3819 else if (! ASCII_BYTE_P (XINT (args[n])) && multibyte)
3821 args[n]
3822 = Fchar_to_string (Funibyte_char_to_multibyte (args[n]));
3823 thissize = SBYTES (args[n]);
3827 else if (FLOATP (args[n]) && *format != 's')
3829 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3831 if (*format != 'd' && *format != 'o' && *format != 'x'
3832 && *format != 'i' && *format != 'X' && *format != 'c')
3833 error ("Invalid format operation %%%c", *format);
3834 /* This fails unnecessarily if args[n] is bigger than
3835 most-positive-fixnum but smaller than MAXINT.
3836 These cases are important because we sometimes use floats
3837 to represent such integer values (typically such values
3838 come from UIDs or PIDs). */
3839 /* args[n] = Ftruncate (args[n], Qnil); */
3842 /* Note that we're using sprintf to print floats,
3843 so we have to take into account what that function
3844 prints. */
3845 /* Filter out flag value of -1. */
3846 thissize = (MAX_10_EXP + 100
3847 + (precision[n] > 0 ? precision[n] : 0));
3849 else
3851 /* Anything but a string, convert to a string using princ. */
3852 register Lisp_Object tem;
3853 tem = Fprin1_to_string (args[n], Qt);
3854 if (STRING_MULTIBYTE (tem) && ! multibyte)
3856 multibyte = 1;
3857 goto retry;
3859 args[n] = tem;
3860 goto string;
3863 thissize += max (0, field_width - actual_width);
3864 total += thissize + 4;
3867 abort_on_gc--;
3869 /* Now we can no longer jump to retry.
3870 TOTAL and LONGEST_FORMAT are known for certain. */
3872 this_format = (char *) alloca (longest_format + 1);
3874 /* Allocate the space for the result.
3875 Note that TOTAL is an overestimate. */
3876 SAFE_ALLOCA (buf, char *, total);
3878 p = buf;
3879 nchars = 0;
3880 n = 0;
3882 /* Scan the format and store result in BUF. */
3883 format = SSDATA (args[0]);
3884 format_start = format;
3885 end = format + SBYTES (args[0]);
3886 maybe_combine_byte = 0;
3887 while (format != end)
3889 if (*format == '%')
3891 int minlen;
3892 int negative = 0;
3893 char *this_format_start = format;
3895 discarded[format - format_start] = 1;
3896 format++;
3898 while (strchr ("-+0# ", *format))
3900 if (*format == '-')
3902 negative = 1;
3904 discarded[format - format_start] = 1;
3905 ++format;
3908 minlen = atoi (format);
3910 while ((*format >= '0' && *format <= '9') || *format == '.')
3912 discarded[format - format_start] = 1;
3913 format++;
3916 if (*format++ == '%')
3918 *p++ = '%';
3919 nchars++;
3920 continue;
3923 ++n;
3925 discarded[format - format_start - 1] = 1;
3926 info[n].start = nchars;
3928 if (STRINGP (args[n]))
3930 /* handle case (precision[n] >= 0) */
3932 int width, padding;
3933 EMACS_INT nbytes, start;
3934 EMACS_INT nchars_string;
3936 /* lisp_string_width ignores a precision of 0, but GNU
3937 libc functions print 0 characters when the precision
3938 is 0. Imitate libc behavior here. Changing
3939 lisp_string_width is the right thing, and will be
3940 done, but meanwhile we work with it. */
3942 if (precision[n] == 0)
3943 width = nchars_string = nbytes = 0;
3944 else if (precision[n] > 0)
3945 width = lisp_string_width (args[n], precision[n],
3946 &nchars_string, &nbytes);
3947 else
3948 { /* no precision spec given for this argument */
3949 width = lisp_string_width (args[n], -1, NULL, NULL);
3950 nbytes = SBYTES (args[n]);
3951 nchars_string = SCHARS (args[n]);
3954 /* If spec requires it, pad on right with spaces. */
3955 padding = minlen - width;
3956 if (! negative)
3957 while (padding-- > 0)
3959 *p++ = ' ';
3960 ++nchars;
3963 info[n].start = start = nchars;
3964 nchars += nchars_string;
3966 if (p > buf
3967 && multibyte
3968 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3969 && STRING_MULTIBYTE (args[n])
3970 && !CHAR_HEAD_P (SREF (args[n], 0)))
3971 maybe_combine_byte = 1;
3973 p += copy_text (SDATA (args[n]), (unsigned char *) p,
3974 nbytes,
3975 STRING_MULTIBYTE (args[n]), multibyte);
3977 info[n].end = nchars;
3979 if (negative)
3980 while (padding-- > 0)
3982 *p++ = ' ';
3983 nchars++;
3986 /* If this argument has text properties, record where
3987 in the result string it appears. */
3988 if (STRING_INTERVALS (args[n]))
3989 info[n].intervals = arg_intervals = 1;
3991 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3993 int this_nchars;
3995 memcpy (this_format, this_format_start,
3996 format - this_format_start);
3997 this_format[format - this_format_start] = 0;
3999 if (format[-1] == 'e' || format[-1] == 'f' || format[-1] == 'g')
4000 sprintf (p, this_format, XFLOAT_DATA (args[n]));
4001 else
4003 if (sizeof (EMACS_INT) > sizeof (int)
4004 && format[-1] != 'c')
4006 /* Insert 'l' before format spec. */
4007 this_format[format - this_format_start]
4008 = this_format[format - this_format_start - 1];
4009 this_format[format - this_format_start - 1] = 'l';
4010 this_format[format - this_format_start + 1] = 0;
4013 if (INTEGERP (args[n]))
4015 if (format[-1] == 'c')
4016 sprintf (p, this_format, (int) XINT (args[n]));
4017 else if (format[-1] == 'd')
4018 sprintf (p, this_format, XINT (args[n]));
4019 /* Don't sign-extend for octal or hex printing. */
4020 else
4021 sprintf (p, this_format, XUINT (args[n]));
4023 else if (format[-1] == 'c')
4024 sprintf (p, this_format, (int) XFLOAT_DATA (args[n]));
4025 else if (format[-1] == 'd')
4026 /* Maybe we should use "%1.0f" instead so it also works
4027 for values larger than MAXINT. */
4028 sprintf (p, this_format, (EMACS_INT) XFLOAT_DATA (args[n]));
4029 else
4030 /* Don't sign-extend for octal or hex printing. */
4031 sprintf (p, this_format, (EMACS_UINT) XFLOAT_DATA (args[n]));
4034 if (p > buf
4035 && multibyte
4036 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4037 && !CHAR_HEAD_P (*((unsigned char *) p)))
4038 maybe_combine_byte = 1;
4039 this_nchars = strlen (p);
4040 if (multibyte)
4041 p += str_to_multibyte ((unsigned char *) p,
4042 buf + total - 1 - p, this_nchars);
4043 else
4044 p += this_nchars;
4045 nchars += this_nchars;
4046 info[n].end = nchars;
4050 else if (STRING_MULTIBYTE (args[0]))
4052 /* Copy a whole multibyte character. */
4053 if (p > buf
4054 && multibyte
4055 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4056 && !CHAR_HEAD_P (*format))
4057 maybe_combine_byte = 1;
4058 *p++ = *format++;
4059 while (! CHAR_HEAD_P (*format))
4061 discarded[format - format_start] = 2;
4062 *p++ = *format++;
4064 nchars++;
4066 else if (multibyte)
4068 /* Convert a single-byte character to multibyte. */
4069 int len = copy_text ((unsigned char *) format, (unsigned char *) p,
4070 1, 0, 1);
4072 p += len;
4073 format++;
4074 nchars++;
4076 else
4077 *p++ = *format++, nchars++;
4080 if (p > buf + total)
4081 abort ();
4083 if (maybe_combine_byte)
4084 nchars = multibyte_chars_in_text ((unsigned char *) buf, p - buf);
4085 val = make_specified_string (buf, nchars, p - buf, multibyte);
4087 /* If we allocated BUF with malloc, free it too. */
4088 SAFE_FREE ();
4090 /* If the format string has text properties, or any of the string
4091 arguments has text properties, set up text properties of the
4092 result string. */
4094 if (STRING_INTERVALS (args[0]) || arg_intervals)
4096 Lisp_Object len, new_len, props;
4097 struct gcpro gcpro1;
4099 /* Add text properties from the format string. */
4100 len = make_number (SCHARS (args[0]));
4101 props = text_property_list (args[0], make_number (0), len, Qnil);
4102 GCPRO1 (props);
4104 if (CONSP (props))
4106 EMACS_INT bytepos = 0, position = 0, translated = 0;
4107 int argn = 1;
4108 Lisp_Object list;
4110 /* Adjust the bounds of each text property
4111 to the proper start and end in the output string. */
4113 /* Put the positions in PROPS in increasing order, so that
4114 we can do (effectively) one scan through the position
4115 space of the format string. */
4116 props = Fnreverse (props);
4118 /* BYTEPOS is the byte position in the format string,
4119 POSITION is the untranslated char position in it,
4120 TRANSLATED is the translated char position in BUF,
4121 and ARGN is the number of the next arg we will come to. */
4122 for (list = props; CONSP (list); list = XCDR (list))
4124 Lisp_Object item;
4125 EMACS_INT pos;
4127 item = XCAR (list);
4129 /* First adjust the property start position. */
4130 pos = XINT (XCAR (item));
4132 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4133 up to this position. */
4134 for (; position < pos; bytepos++)
4136 if (! discarded[bytepos])
4137 position++, translated++;
4138 else if (discarded[bytepos] == 1)
4140 position++;
4141 if (translated == info[argn].start)
4143 translated += info[argn].end - info[argn].start;
4144 argn++;
4149 XSETCAR (item, make_number (translated));
4151 /* Likewise adjust the property end position. */
4152 pos = XINT (XCAR (XCDR (item)));
4154 for (; position < pos; bytepos++)
4156 if (! discarded[bytepos])
4157 position++, translated++;
4158 else if (discarded[bytepos] == 1)
4160 position++;
4161 if (translated == info[argn].start)
4163 translated += info[argn].end - info[argn].start;
4164 argn++;
4169 XSETCAR (XCDR (item), make_number (translated));
4172 add_text_properties_from_list (val, props, make_number (0));
4175 /* Add text properties from arguments. */
4176 if (arg_intervals)
4177 for (n = 1; n < nargs; ++n)
4178 if (info[n].intervals)
4180 len = make_number (SCHARS (args[n]));
4181 new_len = make_number (info[n].end - info[n].start);
4182 props = text_property_list (args[n], make_number (0), len, Qnil);
4183 props = extend_property_ranges (props, new_len);
4184 /* If successive arguments have properties, be sure that
4185 the value of `composition' property be the copy. */
4186 if (n > 1 && info[n - 1].end)
4187 make_composition_value_copy (props);
4188 add_text_properties_from_list (val, props,
4189 make_number (info[n].start));
4192 UNGCPRO;
4195 return val;
4198 Lisp_Object
4199 format2 (const char *string1, Lisp_Object arg0, Lisp_Object arg1)
4201 Lisp_Object args[3];
4202 args[0] = build_string (string1);
4203 args[1] = arg0;
4204 args[2] = arg1;
4205 return Fformat (3, args);
4208 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4209 doc: /* Return t if two characters match, optionally ignoring case.
4210 Both arguments must be characters (i.e. integers).
4211 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4212 (register Lisp_Object c1, Lisp_Object c2)
4214 int i1, i2;
4215 /* Check they're chars, not just integers, otherwise we could get array
4216 bounds violations in downcase. */
4217 CHECK_CHARACTER (c1);
4218 CHECK_CHARACTER (c2);
4220 if (XINT (c1) == XINT (c2))
4221 return Qt;
4222 if (NILP (BVAR (current_buffer, case_fold_search)))
4223 return Qnil;
4225 i1 = XFASTINT (c1);
4226 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
4227 && ! ASCII_CHAR_P (i1))
4229 MAKE_CHAR_MULTIBYTE (i1);
4231 i2 = XFASTINT (c2);
4232 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
4233 && ! ASCII_CHAR_P (i2))
4235 MAKE_CHAR_MULTIBYTE (i2);
4237 return (downcase (i1) == downcase (i2) ? Qt : Qnil);
4240 /* Transpose the markers in two regions of the current buffer, and
4241 adjust the ones between them if necessary (i.e.: if the regions
4242 differ in size).
4244 START1, END1 are the character positions of the first region.
4245 START1_BYTE, END1_BYTE are the byte positions.
4246 START2, END2 are the character positions of the second region.
4247 START2_BYTE, END2_BYTE are the byte positions.
4249 Traverses the entire marker list of the buffer to do so, adding an
4250 appropriate amount to some, subtracting from some, and leaving the
4251 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4253 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4255 static void
4256 transpose_markers (EMACS_INT start1, EMACS_INT end1,
4257 EMACS_INT start2, EMACS_INT end2,
4258 EMACS_INT start1_byte, EMACS_INT end1_byte,
4259 EMACS_INT start2_byte, EMACS_INT end2_byte)
4261 register EMACS_INT amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4262 register struct Lisp_Marker *marker;
4264 /* Update point as if it were a marker. */
4265 if (PT < start1)
4267 else if (PT < end1)
4268 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4269 PT_BYTE + (end2_byte - end1_byte));
4270 else if (PT < start2)
4271 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4272 (PT_BYTE + (end2_byte - start2_byte)
4273 - (end1_byte - start1_byte)));
4274 else if (PT < end2)
4275 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4276 PT_BYTE - (start2_byte - start1_byte));
4278 /* We used to adjust the endpoints here to account for the gap, but that
4279 isn't good enough. Even if we assume the caller has tried to move the
4280 gap out of our way, it might still be at start1 exactly, for example;
4281 and that places it `inside' the interval, for our purposes. The amount
4282 of adjustment is nontrivial if there's a `denormalized' marker whose
4283 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4284 the dirty work to Fmarker_position, below. */
4286 /* The difference between the region's lengths */
4287 diff = (end2 - start2) - (end1 - start1);
4288 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4290 /* For shifting each marker in a region by the length of the other
4291 region plus the distance between the regions. */
4292 amt1 = (end2 - start2) + (start2 - end1);
4293 amt2 = (end1 - start1) + (start2 - end1);
4294 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4295 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4297 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4299 mpos = marker->bytepos;
4300 if (mpos >= start1_byte && mpos < end2_byte)
4302 if (mpos < end1_byte)
4303 mpos += amt1_byte;
4304 else if (mpos < start2_byte)
4305 mpos += diff_byte;
4306 else
4307 mpos -= amt2_byte;
4308 marker->bytepos = mpos;
4310 mpos = marker->charpos;
4311 if (mpos >= start1 && mpos < end2)
4313 if (mpos < end1)
4314 mpos += amt1;
4315 else if (mpos < start2)
4316 mpos += diff;
4317 else
4318 mpos -= amt2;
4320 marker->charpos = mpos;
4324 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4325 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4326 The regions should not be overlapping, because the size of the buffer is
4327 never changed in a transposition.
4329 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4330 any markers that happen to be located in the regions.
4332 Transposing beyond buffer boundaries is an error. */)
4333 (Lisp_Object startr1, Lisp_Object endr1, Lisp_Object startr2, Lisp_Object endr2, Lisp_Object leave_markers)
4335 register EMACS_INT start1, end1, start2, end2;
4336 EMACS_INT start1_byte, start2_byte, len1_byte, len2_byte;
4337 EMACS_INT gap, len1, len_mid, len2;
4338 unsigned char *start1_addr, *start2_addr, *temp;
4340 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4341 Lisp_Object buf;
4343 XSETBUFFER (buf, current_buffer);
4344 cur_intv = BUF_INTERVALS (current_buffer);
4346 validate_region (&startr1, &endr1);
4347 validate_region (&startr2, &endr2);
4349 start1 = XFASTINT (startr1);
4350 end1 = XFASTINT (endr1);
4351 start2 = XFASTINT (startr2);
4352 end2 = XFASTINT (endr2);
4353 gap = GPT;
4355 /* Swap the regions if they're reversed. */
4356 if (start2 < end1)
4358 register EMACS_INT glumph = start1;
4359 start1 = start2;
4360 start2 = glumph;
4361 glumph = end1;
4362 end1 = end2;
4363 end2 = glumph;
4366 len1 = end1 - start1;
4367 len2 = end2 - start2;
4369 if (start2 < end1)
4370 error ("Transposed regions overlap");
4371 else if (start1 == end1 || start2 == end2)
4372 error ("Transposed region has length 0");
4374 /* The possibilities are:
4375 1. Adjacent (contiguous) regions, or separate but equal regions
4376 (no, really equal, in this case!), or
4377 2. Separate regions of unequal size.
4379 The worst case is usually No. 2. It means that (aside from
4380 potential need for getting the gap out of the way), there also
4381 needs to be a shifting of the text between the two regions. So
4382 if they are spread far apart, we are that much slower... sigh. */
4384 /* It must be pointed out that the really studly thing to do would
4385 be not to move the gap at all, but to leave it in place and work
4386 around it if necessary. This would be extremely efficient,
4387 especially considering that people are likely to do
4388 transpositions near where they are working interactively, which
4389 is exactly where the gap would be found. However, such code
4390 would be much harder to write and to read. So, if you are
4391 reading this comment and are feeling squirrely, by all means have
4392 a go! I just didn't feel like doing it, so I will simply move
4393 the gap the minimum distance to get it out of the way, and then
4394 deal with an unbroken array. */
4396 /* Make sure the gap won't interfere, by moving it out of the text
4397 we will operate on. */
4398 if (start1 < gap && gap < end2)
4400 if (gap - start1 < end2 - gap)
4401 move_gap (start1);
4402 else
4403 move_gap (end2);
4406 start1_byte = CHAR_TO_BYTE (start1);
4407 start2_byte = CHAR_TO_BYTE (start2);
4408 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4409 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
4411 #ifdef BYTE_COMBINING_DEBUG
4412 if (end1 == start2)
4414 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4415 len2_byte, start1, start1_byte)
4416 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4417 len1_byte, end2, start2_byte + len2_byte)
4418 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4419 len1_byte, end2, start2_byte + len2_byte))
4420 abort ();
4422 else
4424 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4425 len2_byte, start1, start1_byte)
4426 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4427 len1_byte, start2, start2_byte)
4428 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4429 len2_byte, end1, start1_byte + len1_byte)
4430 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4431 len1_byte, end2, start2_byte + len2_byte))
4432 abort ();
4434 #endif
4436 /* Hmmm... how about checking to see if the gap is large
4437 enough to use as the temporary storage? That would avoid an
4438 allocation... interesting. Later, don't fool with it now. */
4440 /* Working without memmove, for portability (sigh), so must be
4441 careful of overlapping subsections of the array... */
4443 if (end1 == start2) /* adjacent regions */
4445 modify_region (current_buffer, start1, end2, 0);
4446 record_change (start1, len1 + len2);
4448 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4449 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4450 /* Don't use Fset_text_properties: that can cause GC, which can
4451 clobber objects stored in the tmp_intervals. */
4452 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4453 if (!NULL_INTERVAL_P (tmp_interval3))
4454 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4456 /* First region smaller than second. */
4457 if (len1_byte < len2_byte)
4459 USE_SAFE_ALLOCA;
4461 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4463 /* Don't precompute these addresses. We have to compute them
4464 at the last minute, because the relocating allocator might
4465 have moved the buffer around during the xmalloc. */
4466 start1_addr = BYTE_POS_ADDR (start1_byte);
4467 start2_addr = BYTE_POS_ADDR (start2_byte);
4469 memcpy (temp, start2_addr, len2_byte);
4470 memcpy (start1_addr + len2_byte, start1_addr, len1_byte);
4471 memcpy (start1_addr, temp, len2_byte);
4472 SAFE_FREE ();
4474 else
4475 /* First region not smaller than second. */
4477 USE_SAFE_ALLOCA;
4479 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4480 start1_addr = BYTE_POS_ADDR (start1_byte);
4481 start2_addr = BYTE_POS_ADDR (start2_byte);
4482 memcpy (temp, start1_addr, len1_byte);
4483 memcpy (start1_addr, start2_addr, len2_byte);
4484 memcpy (start1_addr + len2_byte, temp, len1_byte);
4485 SAFE_FREE ();
4487 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4488 len1, current_buffer, 0);
4489 graft_intervals_into_buffer (tmp_interval2, start1,
4490 len2, current_buffer, 0);
4491 update_compositions (start1, start1 + len2, CHECK_BORDER);
4492 update_compositions (start1 + len2, end2, CHECK_TAIL);
4494 /* Non-adjacent regions, because end1 != start2, bleagh... */
4495 else
4497 len_mid = start2_byte - (start1_byte + len1_byte);
4499 if (len1_byte == len2_byte)
4500 /* Regions are same size, though, how nice. */
4502 USE_SAFE_ALLOCA;
4504 modify_region (current_buffer, start1, end1, 0);
4505 modify_region (current_buffer, start2, end2, 0);
4506 record_change (start1, len1);
4507 record_change (start2, len2);
4508 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4509 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4511 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4512 if (!NULL_INTERVAL_P (tmp_interval3))
4513 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4515 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4516 if (!NULL_INTERVAL_P (tmp_interval3))
4517 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
4519 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4520 start1_addr = BYTE_POS_ADDR (start1_byte);
4521 start2_addr = BYTE_POS_ADDR (start2_byte);
4522 memcpy (temp, start1_addr, len1_byte);
4523 memcpy (start1_addr, start2_addr, len2_byte);
4524 memcpy (start2_addr, temp, len1_byte);
4525 SAFE_FREE ();
4527 graft_intervals_into_buffer (tmp_interval1, start2,
4528 len1, current_buffer, 0);
4529 graft_intervals_into_buffer (tmp_interval2, start1,
4530 len2, current_buffer, 0);
4533 else if (len1_byte < len2_byte) /* Second region larger than first */
4534 /* Non-adjacent & unequal size, area between must also be shifted. */
4536 USE_SAFE_ALLOCA;
4538 modify_region (current_buffer, start1, end2, 0);
4539 record_change (start1, (end2 - start1));
4540 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4541 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4542 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4544 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4545 if (!NULL_INTERVAL_P (tmp_interval3))
4546 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4548 /* holds region 2 */
4549 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4550 start1_addr = BYTE_POS_ADDR (start1_byte);
4551 start2_addr = BYTE_POS_ADDR (start2_byte);
4552 memcpy (temp, start2_addr, len2_byte);
4553 memcpy (start1_addr + len_mid + len2_byte, start1_addr, len1_byte);
4554 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4555 memcpy (start1_addr, temp, len2_byte);
4556 SAFE_FREE ();
4558 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4559 len1, current_buffer, 0);
4560 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4561 len_mid, current_buffer, 0);
4562 graft_intervals_into_buffer (tmp_interval2, start1,
4563 len2, current_buffer, 0);
4565 else
4566 /* Second region smaller than first. */
4568 USE_SAFE_ALLOCA;
4570 record_change (start1, (end2 - start1));
4571 modify_region (current_buffer, start1, end2, 0);
4573 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4574 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4575 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4577 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4578 if (!NULL_INTERVAL_P (tmp_interval3))
4579 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4581 /* holds region 1 */
4582 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4583 start1_addr = BYTE_POS_ADDR (start1_byte);
4584 start2_addr = BYTE_POS_ADDR (start2_byte);
4585 memcpy (temp, start1_addr, len1_byte);
4586 memcpy (start1_addr, start2_addr, len2_byte);
4587 memcpy (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4588 memcpy (start1_addr + len2_byte + len_mid, temp, len1_byte);
4589 SAFE_FREE ();
4591 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4592 len1, current_buffer, 0);
4593 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4594 len_mid, current_buffer, 0);
4595 graft_intervals_into_buffer (tmp_interval2, start1,
4596 len2, current_buffer, 0);
4599 update_compositions (start1, start1 + len2, CHECK_BORDER);
4600 update_compositions (end2 - len1, end2, CHECK_BORDER);
4603 /* When doing multiple transpositions, it might be nice
4604 to optimize this. Perhaps the markers in any one buffer
4605 should be organized in some sorted data tree. */
4606 if (NILP (leave_markers))
4608 transpose_markers (start1, end1, start2, end2,
4609 start1_byte, start1_byte + len1_byte,
4610 start2_byte, start2_byte + len2_byte);
4611 fix_start_end_in_overlays (start1, end2);
4614 signal_after_change (start1, end2 - start1, end2 - start1);
4615 return Qnil;
4619 void
4620 syms_of_editfns (void)
4622 environbuf = 0;
4623 initial_tz = 0;
4625 Qbuffer_access_fontify_functions
4626 = intern_c_string ("buffer-access-fontify-functions");
4627 staticpro (&Qbuffer_access_fontify_functions);
4629 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion,
4630 doc: /* Non-nil means text motion commands don't notice fields. */);
4631 Vinhibit_field_text_motion = Qnil;
4633 DEFVAR_LISP ("buffer-access-fontify-functions",
4634 Vbuffer_access_fontify_functions,
4635 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4636 Each function is called with two arguments which specify the range
4637 of the buffer being accessed. */);
4638 Vbuffer_access_fontify_functions = Qnil;
4641 Lisp_Object obuf;
4642 obuf = Fcurrent_buffer ();
4643 /* Do this here, because init_buffer_once is too early--it won't work. */
4644 Fset_buffer (Vprin1_to_string_buffer);
4645 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4646 Fset (Fmake_local_variable (intern_c_string ("buffer-access-fontify-functions")),
4647 Qnil);
4648 Fset_buffer (obuf);
4651 DEFVAR_LISP ("buffer-access-fontified-property",
4652 Vbuffer_access_fontified_property,
4653 doc: /* Property which (if non-nil) indicates text has been fontified.
4654 `buffer-substring' need not call the `buffer-access-fontify-functions'
4655 functions if all the text being accessed has this property. */);
4656 Vbuffer_access_fontified_property = Qnil;
4658 DEFVAR_LISP ("system-name", Vsystem_name,
4659 doc: /* The host name of the machine Emacs is running on. */);
4661 DEFVAR_LISP ("user-full-name", Vuser_full_name,
4662 doc: /* The full name of the user logged in. */);
4664 DEFVAR_LISP ("user-login-name", Vuser_login_name,
4665 doc: /* The user's name, taken from environment variables if possible. */);
4667 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name,
4668 doc: /* The user's name, based upon the real uid only. */);
4670 DEFVAR_LISP ("operating-system-release", Voperating_system_release,
4671 doc: /* The release of the operating system Emacs is running on. */);
4673 defsubr (&Spropertize);
4674 defsubr (&Schar_equal);
4675 defsubr (&Sgoto_char);
4676 defsubr (&Sstring_to_char);
4677 defsubr (&Schar_to_string);
4678 defsubr (&Sbyte_to_string);
4679 defsubr (&Sbuffer_substring);
4680 defsubr (&Sbuffer_substring_no_properties);
4681 defsubr (&Sbuffer_string);
4683 defsubr (&Spoint_marker);
4684 defsubr (&Smark_marker);
4685 defsubr (&Spoint);
4686 defsubr (&Sregion_beginning);
4687 defsubr (&Sregion_end);
4689 staticpro (&Qfield);
4690 Qfield = intern_c_string ("field");
4691 staticpro (&Qboundary);
4692 Qboundary = intern_c_string ("boundary");
4693 defsubr (&Sfield_beginning);
4694 defsubr (&Sfield_end);
4695 defsubr (&Sfield_string);
4696 defsubr (&Sfield_string_no_properties);
4697 defsubr (&Sdelete_field);
4698 defsubr (&Sconstrain_to_field);
4700 defsubr (&Sline_beginning_position);
4701 defsubr (&Sline_end_position);
4703 /* defsubr (&Smark); */
4704 /* defsubr (&Sset_mark); */
4705 defsubr (&Ssave_excursion);
4706 defsubr (&Ssave_current_buffer);
4708 defsubr (&Sbufsize);
4709 defsubr (&Spoint_max);
4710 defsubr (&Spoint_min);
4711 defsubr (&Spoint_min_marker);
4712 defsubr (&Spoint_max_marker);
4713 defsubr (&Sgap_position);
4714 defsubr (&Sgap_size);
4715 defsubr (&Sposition_bytes);
4716 defsubr (&Sbyte_to_position);
4718 defsubr (&Sbobp);
4719 defsubr (&Seobp);
4720 defsubr (&Sbolp);
4721 defsubr (&Seolp);
4722 defsubr (&Sfollowing_char);
4723 defsubr (&Sprevious_char);
4724 defsubr (&Schar_after);
4725 defsubr (&Schar_before);
4726 defsubr (&Sinsert);
4727 defsubr (&Sinsert_before_markers);
4728 defsubr (&Sinsert_and_inherit);
4729 defsubr (&Sinsert_and_inherit_before_markers);
4730 defsubr (&Sinsert_char);
4731 defsubr (&Sinsert_byte);
4733 defsubr (&Suser_login_name);
4734 defsubr (&Suser_real_login_name);
4735 defsubr (&Suser_uid);
4736 defsubr (&Suser_real_uid);
4737 defsubr (&Suser_full_name);
4738 defsubr (&Semacs_pid);
4739 defsubr (&Scurrent_time);
4740 defsubr (&Sget_internal_run_time);
4741 defsubr (&Sformat_time_string);
4742 defsubr (&Sfloat_time);
4743 defsubr (&Sdecode_time);
4744 defsubr (&Sencode_time);
4745 defsubr (&Scurrent_time_string);
4746 defsubr (&Scurrent_time_zone);
4747 defsubr (&Sset_time_zone_rule);
4748 defsubr (&Ssystem_name);
4749 defsubr (&Smessage);
4750 defsubr (&Smessage_box);
4751 defsubr (&Smessage_or_box);
4752 defsubr (&Scurrent_message);
4753 defsubr (&Sformat);
4755 defsubr (&Sinsert_buffer_substring);
4756 defsubr (&Scompare_buffer_substrings);
4757 defsubr (&Ssubst_char_in_region);
4758 defsubr (&Stranslate_region_internal);
4759 defsubr (&Sdelete_region);
4760 defsubr (&Sdelete_and_extract_region);
4761 defsubr (&Swiden);
4762 defsubr (&Snarrow_to_region);
4763 defsubr (&Ssave_restriction);
4764 defsubr (&Stranspose_regions);