* src/xdisp.c (safe_eval_handler): Distinguish symbols and strings.
[emacs.git] / src / editfns.c
blob5407cd772a72a1a0887f47fed9c8b7c253aef783
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>
49 #include "intervals.h"
50 #include "buffer.h"
51 #include "character.h"
52 #include "coding.h"
53 #include "frame.h"
54 #include "window.h"
55 #include "blockinput.h"
57 #ifdef STDC_HEADERS
58 #include <float.h>
59 #define MAX_10_EXP DBL_MAX_10_EXP
60 #else
61 #define MAX_10_EXP 310
62 #endif
64 #ifndef NULL
65 #define NULL 0
66 #endif
68 #ifndef USER_FULL_NAME
69 #define USER_FULL_NAME pw->pw_gecos
70 #endif
72 #ifndef USE_CRT_DLL
73 extern char **environ;
74 #endif
76 #define TM_YEAR_BASE 1900
78 /* Nonzero if TM_YEAR is a struct tm's tm_year value that causes
79 asctime to have well-defined behavior. */
80 #ifndef TM_YEAR_IN_ASCTIME_RANGE
81 # define TM_YEAR_IN_ASCTIME_RANGE(tm_year) \
82 (1000 - TM_YEAR_BASE <= (tm_year) && (tm_year) <= 9999 - TM_YEAR_BASE)
83 #endif
85 extern size_t emacs_strftimeu (char *, size_t, const char *,
86 const struct tm *, int);
88 #ifdef WINDOWSNT
89 extern Lisp_Object w32_get_internal_run_time (void);
90 #endif
92 static int tm_diff (struct tm *, struct tm *);
93 static void find_field (Lisp_Object, Lisp_Object, Lisp_Object,
94 EMACS_INT *, Lisp_Object, EMACS_INT *);
95 static void update_buffer_properties (EMACS_INT, EMACS_INT);
96 static Lisp_Object region_limit (int);
97 static size_t emacs_memftimeu (char *, size_t, const char *,
98 size_t, const struct tm *, int);
99 static void general_insert_function (void (*) (const unsigned char *, EMACS_INT),
100 void (*) (Lisp_Object, EMACS_INT,
101 EMACS_INT, EMACS_INT,
102 EMACS_INT, int),
103 int, int, Lisp_Object *);
104 static Lisp_Object subst_char_in_region_unwind (Lisp_Object);
105 static Lisp_Object subst_char_in_region_unwind_1 (Lisp_Object);
106 static void transpose_markers (EMACS_INT, EMACS_INT, EMACS_INT, EMACS_INT,
107 EMACS_INT, EMACS_INT, EMACS_INT, EMACS_INT);
109 Lisp_Object Qbuffer_access_fontify_functions;
110 Lisp_Object Fuser_full_name (Lisp_Object);
112 /* Symbol for the text property used to mark fields. */
114 Lisp_Object Qfield;
116 /* A special value for Qfield properties. */
118 Lisp_Object Qboundary;
121 void
122 init_editfns (void)
124 char *user_name;
125 register unsigned char *p;
126 struct passwd *pw; /* password entry for the current user */
127 Lisp_Object tem;
129 /* Set up system_name even when dumping. */
130 init_system_name ();
132 #ifndef CANNOT_DUMP
133 /* Don't bother with this on initial start when just dumping out */
134 if (!initialized)
135 return;
136 #endif /* not CANNOT_DUMP */
138 pw = (struct passwd *) getpwuid (getuid ());
139 #ifdef MSDOS
140 /* We let the real user name default to "root" because that's quite
141 accurate on MSDOG and because it lets Emacs find the init file.
142 (The DVX libraries override the Djgpp libraries here.) */
143 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
144 #else
145 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
146 #endif
148 /* Get the effective user name, by consulting environment variables,
149 or the effective uid if those are unset. */
150 user_name = (char *) getenv ("LOGNAME");
151 if (!user_name)
152 #ifdef WINDOWSNT
153 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
154 #else /* WINDOWSNT */
155 user_name = (char *) getenv ("USER");
156 #endif /* WINDOWSNT */
157 if (!user_name)
159 pw = (struct passwd *) getpwuid (geteuid ());
160 user_name = (char *) (pw ? pw->pw_name : "unknown");
162 Vuser_login_name = build_string (user_name);
164 /* If the user name claimed in the environment vars differs from
165 the real uid, use the claimed name to find the full name. */
166 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
167 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
168 : Vuser_login_name);
170 p = (unsigned char *) getenv ("NAME");
171 if (p)
172 Vuser_full_name = build_string (p);
173 else if (NILP (Vuser_full_name))
174 Vuser_full_name = build_string ("unknown");
176 #ifdef HAVE_SYS_UTSNAME_H
178 struct utsname uts;
179 uname (&uts);
180 Voperating_system_release = build_string (uts.release);
182 #else
183 Voperating_system_release = Qnil;
184 #endif
187 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
188 doc: /* Convert arg CHAR to a string containing that character.
189 usage: (char-to-string CHAR) */)
190 (Lisp_Object character)
192 int len;
193 unsigned char str[MAX_MULTIBYTE_LENGTH];
195 CHECK_CHARACTER (character);
197 len = CHAR_STRING (XFASTINT (character), str);
198 return make_string_from_bytes (str, 1, len);
201 DEFUN ("byte-to-string", Fbyte_to_string, Sbyte_to_string, 1, 1, 0,
202 doc: /* Convert arg BYTE to a unibyte string containing that byte. */)
203 (Lisp_Object byte)
205 unsigned char b;
206 CHECK_NUMBER (byte);
207 if (XINT (byte) < 0 || XINT (byte) > 255)
208 error ("Invalid byte");
209 b = XINT (byte);
210 return make_string_from_bytes (&b, 1, 1);
213 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
214 doc: /* Convert arg STRING to a character, the first character of that string.
215 A multibyte character is handled correctly. */)
216 (register Lisp_Object string)
218 register Lisp_Object val;
219 CHECK_STRING (string);
220 if (SCHARS (string))
222 if (STRING_MULTIBYTE (string))
223 XSETFASTINT (val, STRING_CHAR (SDATA (string)));
224 else
225 XSETFASTINT (val, SREF (string, 0));
227 else
228 XSETFASTINT (val, 0);
229 return val;
232 static Lisp_Object
233 buildmark (EMACS_INT charpos, EMACS_INT bytepos)
235 register Lisp_Object mark;
236 mark = Fmake_marker ();
237 set_marker_both (mark, Qnil, charpos, bytepos);
238 return mark;
241 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
242 doc: /* Return value of point, as an integer.
243 Beginning of buffer is position (point-min). */)
244 (void)
246 Lisp_Object temp;
247 XSETFASTINT (temp, PT);
248 return temp;
251 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
252 doc: /* Return value of point, as a marker object. */)
253 (void)
255 return buildmark (PT, PT_BYTE);
258 EMACS_INT
259 clip_to_bounds (EMACS_INT lower, EMACS_INT num, EMACS_INT upper)
261 if (num < lower)
262 return lower;
263 else if (num > upper)
264 return upper;
265 else
266 return num;
269 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
270 doc: /* Set point to POSITION, a number or marker.
271 Beginning of buffer is position (point-min), end is (point-max).
273 The return value is POSITION. */)
274 (register Lisp_Object position)
276 EMACS_INT pos;
278 if (MARKERP (position)
279 && current_buffer == XMARKER (position)->buffer)
281 pos = marker_position (position);
282 if (pos < BEGV)
283 SET_PT_BOTH (BEGV, BEGV_BYTE);
284 else if (pos > ZV)
285 SET_PT_BOTH (ZV, ZV_BYTE);
286 else
287 SET_PT_BOTH (pos, marker_byte_position (position));
289 return position;
292 CHECK_NUMBER_COERCE_MARKER (position);
294 pos = clip_to_bounds (BEGV, XINT (position), ZV);
295 SET_PT (pos);
296 return position;
300 /* Return the start or end position of the region.
301 BEGINNINGP non-zero means return the start.
302 If there is no region active, signal an error. */
304 static Lisp_Object
305 region_limit (int beginningp)
307 Lisp_Object m;
309 if (!NILP (Vtransient_mark_mode)
310 && NILP (Vmark_even_if_inactive)
311 && NILP (current_buffer->mark_active))
312 xsignal0 (Qmark_inactive);
314 m = Fmarker_position (current_buffer->mark);
315 if (NILP (m))
316 error ("The mark is not set now, so there is no region");
318 if ((PT < XFASTINT (m)) == (beginningp != 0))
319 m = make_number (PT);
320 return m;
323 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
324 doc: /* Return the integer value of point or mark, whichever is smaller. */)
325 (void)
327 return region_limit (1);
330 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
331 doc: /* Return the integer value of point or mark, whichever is larger. */)
332 (void)
334 return region_limit (0);
337 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
338 doc: /* Return this buffer's mark, as a marker object.
339 Watch out! Moving this marker changes the mark position.
340 If you set the marker not to point anywhere, the buffer will have no mark. */)
341 (void)
343 return current_buffer->mark;
347 /* Find all the overlays in the current buffer that touch position POS.
348 Return the number found, and store them in a vector in VEC
349 of length LEN. */
351 static int
352 overlays_around (EMACS_INT pos, Lisp_Object *vec, int len)
354 Lisp_Object overlay, start, end;
355 struct Lisp_Overlay *tail;
356 EMACS_INT startpos, endpos;
357 int idx = 0;
359 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
361 XSETMISC (overlay, tail);
363 end = OVERLAY_END (overlay);
364 endpos = OVERLAY_POSITION (end);
365 if (endpos < pos)
366 break;
367 start = OVERLAY_START (overlay);
368 startpos = OVERLAY_POSITION (start);
369 if (startpos <= pos)
371 if (idx < len)
372 vec[idx] = overlay;
373 /* Keep counting overlays even if we can't return them all. */
374 idx++;
378 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
380 XSETMISC (overlay, tail);
382 start = OVERLAY_START (overlay);
383 startpos = OVERLAY_POSITION (start);
384 if (pos < startpos)
385 break;
386 end = OVERLAY_END (overlay);
387 endpos = OVERLAY_POSITION (end);
388 if (pos <= endpos)
390 if (idx < len)
391 vec[idx] = overlay;
392 idx++;
396 return idx;
399 /* Return the value of property PROP, in OBJECT at POSITION.
400 It's the value of PROP that a char inserted at POSITION would get.
401 OBJECT is optional and defaults to the current buffer.
402 If OBJECT is a buffer, then overlay properties are considered as well as
403 text properties.
404 If OBJECT is a window, then that window's buffer is used, but
405 window-specific overlays are considered only if they are associated
406 with OBJECT. */
407 Lisp_Object
408 get_pos_property (Lisp_Object position, register Lisp_Object prop, Lisp_Object object)
410 CHECK_NUMBER_COERCE_MARKER (position);
412 if (NILP (object))
413 XSETBUFFER (object, current_buffer);
414 else if (WINDOWP (object))
415 object = XWINDOW (object)->buffer;
417 if (!BUFFERP (object))
418 /* pos-property only makes sense in buffers right now, since strings
419 have no overlays and no notion of insertion for which stickiness
420 could be obeyed. */
421 return Fget_text_property (position, prop, object);
422 else
424 EMACS_INT posn = XINT (position);
425 int noverlays;
426 Lisp_Object *overlay_vec, tem;
427 struct buffer *obuf = current_buffer;
429 set_buffer_temp (XBUFFER (object));
431 /* First try with room for 40 overlays. */
432 noverlays = 40;
433 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
434 noverlays = overlays_around (posn, overlay_vec, noverlays);
436 /* If there are more than 40,
437 make enough space for all, and try again. */
438 if (noverlays > 40)
440 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
441 noverlays = overlays_around (posn, overlay_vec, noverlays);
443 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
445 set_buffer_temp (obuf);
447 /* Now check the overlays in order of decreasing priority. */
448 while (--noverlays >= 0)
450 Lisp_Object ol = overlay_vec[noverlays];
451 tem = Foverlay_get (ol, prop);
452 if (!NILP (tem))
454 /* Check the overlay is indeed active at point. */
455 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
456 if ((OVERLAY_POSITION (start) == posn
457 && XMARKER (start)->insertion_type == 1)
458 || (OVERLAY_POSITION (finish) == posn
459 && XMARKER (finish)->insertion_type == 0))
460 ; /* The overlay will not cover a char inserted at point. */
461 else
463 return tem;
468 { /* Now check the text properties. */
469 int stickiness = text_property_stickiness (prop, position, object);
470 if (stickiness > 0)
471 return Fget_text_property (position, prop, object);
472 else if (stickiness < 0
473 && XINT (position) > BUF_BEGV (XBUFFER (object)))
474 return Fget_text_property (make_number (XINT (position) - 1),
475 prop, object);
476 else
477 return Qnil;
482 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
483 the value of point is used instead. If BEG or END is null,
484 means don't store the beginning or end of the field.
486 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
487 results; they do not effect boundary behavior.
489 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
490 position of a field, then the beginning of the previous field is
491 returned instead of the beginning of POS's field (since the end of a
492 field is actually also the beginning of the next input field, this
493 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
494 true case, if two fields are separated by a field with the special
495 value `boundary', and POS lies within it, then the two separated
496 fields are considered to be adjacent, and POS between them, when
497 finding the beginning and ending of the "merged" field.
499 Either BEG or END may be 0, in which case the corresponding value
500 is not stored. */
502 static void
503 find_field (Lisp_Object pos, Lisp_Object merge_at_boundary,
504 Lisp_Object beg_limit,
505 EMACS_INT *beg, Lisp_Object end_limit, EMACS_INT *end)
507 /* Fields right before and after the point. */
508 Lisp_Object before_field, after_field;
509 /* 1 if POS counts as the start of a field. */
510 int at_field_start = 0;
511 /* 1 if POS counts as the end of a field. */
512 int at_field_end = 0;
514 if (NILP (pos))
515 XSETFASTINT (pos, PT);
516 else
517 CHECK_NUMBER_COERCE_MARKER (pos);
519 after_field
520 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
521 before_field
522 = (XFASTINT (pos) > BEGV
523 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
524 Qfield, Qnil, NULL)
525 /* Using nil here would be a more obvious choice, but it would
526 fail when the buffer starts with a non-sticky field. */
527 : after_field);
529 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
530 and POS is at beginning of a field, which can also be interpreted
531 as the end of the previous field. Note that the case where if
532 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
533 more natural one; then we avoid treating the beginning of a field
534 specially. */
535 if (NILP (merge_at_boundary))
537 Lisp_Object field = get_pos_property (pos, Qfield, Qnil);
538 if (!EQ (field, after_field))
539 at_field_end = 1;
540 if (!EQ (field, before_field))
541 at_field_start = 1;
542 if (NILP (field) && at_field_start && at_field_end)
543 /* If an inserted char would have a nil field while the surrounding
544 text is non-nil, we're probably not looking at a
545 zero-length field, but instead at a non-nil field that's
546 not intended for editing (such as comint's prompts). */
547 at_field_end = at_field_start = 0;
550 /* Note about special `boundary' fields:
552 Consider the case where the point (`.') is between the fields `x' and `y':
554 xxxx.yyyy
556 In this situation, if merge_at_boundary is true, we consider the
557 `x' and `y' fields as forming one big merged field, and so the end
558 of the field is the end of `y'.
560 However, if `x' and `y' are separated by a special `boundary' field
561 (a field with a `field' char-property of 'boundary), then we ignore
562 this special field when merging adjacent fields. Here's the same
563 situation, but with a `boundary' field between the `x' and `y' fields:
565 xxx.BBBByyyy
567 Here, if point is at the end of `x', the beginning of `y', or
568 anywhere in-between (within the `boundary' field), we merge all
569 three fields and consider the beginning as being the beginning of
570 the `x' field, and the end as being the end of the `y' field. */
572 if (beg)
574 if (at_field_start)
575 /* POS is at the edge of a field, and we should consider it as
576 the beginning of the following field. */
577 *beg = XFASTINT (pos);
578 else
579 /* Find the previous field boundary. */
581 Lisp_Object p = pos;
582 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
583 /* Skip a `boundary' field. */
584 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
585 beg_limit);
587 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
588 beg_limit);
589 *beg = NILP (p) ? BEGV : XFASTINT (p);
593 if (end)
595 if (at_field_end)
596 /* POS is at the edge of a field, and we should consider it as
597 the end of the previous field. */
598 *end = XFASTINT (pos);
599 else
600 /* Find the next field boundary. */
602 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
603 /* Skip a `boundary' field. */
604 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
605 end_limit);
607 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
608 end_limit);
609 *end = NILP (pos) ? ZV : XFASTINT (pos);
615 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
616 doc: /* Delete the field surrounding POS.
617 A field is a region of text with the same `field' property.
618 If POS is nil, the value of point is used for POS. */)
619 (Lisp_Object pos)
621 EMACS_INT beg, end;
622 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
623 if (beg != end)
624 del_range (beg, end);
625 return Qnil;
628 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
629 doc: /* Return the contents of the field surrounding POS as a string.
630 A field is a region of text with the same `field' property.
631 If POS is nil, the value of point is used for POS. */)
632 (Lisp_Object pos)
634 EMACS_INT beg, end;
635 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
636 return make_buffer_string (beg, end, 1);
639 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
640 doc: /* Return the contents of the field around POS, without text properties.
641 A field is a region of text with the same `field' property.
642 If POS is nil, the value of point is used for POS. */)
643 (Lisp_Object pos)
645 EMACS_INT beg, end;
646 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
647 return make_buffer_string (beg, end, 0);
650 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
651 doc: /* Return the beginning of the field surrounding POS.
652 A field is a region of text with the same `field' property.
653 If POS is nil, the value of point is used for POS.
654 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
655 field, then the beginning of the *previous* field is returned.
656 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
657 is before LIMIT, then LIMIT will be returned instead. */)
658 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
660 EMACS_INT beg;
661 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
662 return make_number (beg);
665 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
666 doc: /* Return the end of the field surrounding POS.
667 A field is a region of text with the same `field' property.
668 If POS is nil, the value of point is used for POS.
669 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
670 then the end of the *following* field is returned.
671 If LIMIT is non-nil, it is a buffer position; if the end of the field
672 is after LIMIT, then LIMIT will be returned instead. */)
673 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
675 EMACS_INT end;
676 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
677 return make_number (end);
680 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
681 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
683 A field is a region of text with the same `field' property.
684 If NEW-POS is nil, then the current point is used instead, and set to the
685 constrained position if that is different.
687 If OLD-POS is at the boundary of two fields, then the allowable
688 positions for NEW-POS depends on the value of the optional argument
689 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
690 constrained to the field that has the same `field' char-property
691 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
692 is non-nil, NEW-POS is constrained to the union of the two adjacent
693 fields. Additionally, if two fields are separated by another field with
694 the special value `boundary', then any point within this special field is
695 also considered to be `on the boundary'.
697 If the optional argument ONLY-IN-LINE is non-nil and constraining
698 NEW-POS would move it to a different line, NEW-POS is returned
699 unconstrained. This useful for commands that move by line, like
700 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
701 only in the case where they can still move to the right line.
703 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
704 a non-nil property of that name, then any field boundaries are ignored.
706 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
707 (Lisp_Object new_pos, Lisp_Object old_pos, Lisp_Object escape_from_edge, Lisp_Object only_in_line, Lisp_Object inhibit_capture_property)
709 /* If non-zero, then the original point, before re-positioning. */
710 EMACS_INT orig_point = 0;
711 int fwd;
712 Lisp_Object prev_old, prev_new;
714 if (NILP (new_pos))
715 /* Use the current point, and afterwards, set it. */
717 orig_point = PT;
718 XSETFASTINT (new_pos, PT);
721 CHECK_NUMBER_COERCE_MARKER (new_pos);
722 CHECK_NUMBER_COERCE_MARKER (old_pos);
724 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
726 prev_old = make_number (XFASTINT (old_pos) - 1);
727 prev_new = make_number (XFASTINT (new_pos) - 1);
729 if (NILP (Vinhibit_field_text_motion)
730 && !EQ (new_pos, old_pos)
731 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
732 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
733 /* To recognize field boundaries, we must also look at the
734 previous positions; we could use `get_pos_property'
735 instead, but in itself that would fail inside non-sticky
736 fields (like comint prompts). */
737 || (XFASTINT (new_pos) > BEGV
738 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
739 || (XFASTINT (old_pos) > BEGV
740 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
741 && (NILP (inhibit_capture_property)
742 /* Field boundaries are again a problem; but now we must
743 decide the case exactly, so we need to call
744 `get_pos_property' as well. */
745 || (NILP (get_pos_property (old_pos, inhibit_capture_property, Qnil))
746 && (XFASTINT (old_pos) <= BEGV
747 || NILP (Fget_char_property (old_pos, inhibit_capture_property, Qnil))
748 || NILP (Fget_char_property (prev_old, inhibit_capture_property, Qnil))))))
749 /* It is possible that NEW_POS is not within the same field as
750 OLD_POS; try to move NEW_POS so that it is. */
752 int shortage;
753 Lisp_Object field_bound;
755 if (fwd)
756 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
757 else
758 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
760 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
761 other side of NEW_POS, which would mean that NEW_POS is
762 already acceptable, and it's not necessary to constrain it
763 to FIELD_BOUND. */
764 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
765 /* NEW_POS should be constrained, but only if either
766 ONLY_IN_LINE is nil (in which case any constraint is OK),
767 or NEW_POS and FIELD_BOUND are on the same line (in which
768 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
769 && (NILP (only_in_line)
770 /* This is the ONLY_IN_LINE case, check that NEW_POS and
771 FIELD_BOUND are on the same line by seeing whether
772 there's an intervening newline or not. */
773 || (scan_buffer ('\n',
774 XFASTINT (new_pos), XFASTINT (field_bound),
775 fwd ? -1 : 1, &shortage, 1),
776 shortage != 0)))
777 /* Constrain NEW_POS to FIELD_BOUND. */
778 new_pos = field_bound;
780 if (orig_point && XFASTINT (new_pos) != orig_point)
781 /* The NEW_POS argument was originally nil, so automatically set PT. */
782 SET_PT (XFASTINT (new_pos));
785 return new_pos;
789 DEFUN ("line-beginning-position",
790 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
791 doc: /* Return the character position of the first character on the current line.
792 With argument N not nil or 1, move forward N - 1 lines first.
793 If scan reaches end of buffer, return that position.
795 The returned position is of the first character in the logical order,
796 i.e. the one that has the smallest character position.
798 This function constrains the returned position to the current field
799 unless that would be on a different line than the original,
800 unconstrained result. If N is nil or 1, and a front-sticky field
801 starts at point, the scan stops as soon as it starts. To ignore field
802 boundaries bind `inhibit-field-text-motion' to t.
804 This function does not move point. */)
805 (Lisp_Object n)
807 EMACS_INT orig, orig_byte, end;
808 int count = SPECPDL_INDEX ();
809 specbind (Qinhibit_point_motion_hooks, Qt);
811 if (NILP (n))
812 XSETFASTINT (n, 1);
813 else
814 CHECK_NUMBER (n);
816 orig = PT;
817 orig_byte = PT_BYTE;
818 Fforward_line (make_number (XINT (n) - 1));
819 end = PT;
821 SET_PT_BOTH (orig, orig_byte);
823 unbind_to (count, Qnil);
825 /* Return END constrained to the current input field. */
826 return Fconstrain_to_field (make_number (end), make_number (orig),
827 XINT (n) != 1 ? Qt : Qnil,
828 Qt, Qnil);
831 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
832 doc: /* Return the character position of the last character on the current line.
833 With argument N not nil or 1, move forward N - 1 lines first.
834 If scan reaches end of buffer, return that position.
836 The returned position is of the last character in the logical order,
837 i.e. the character whose buffer position is the largest one.
839 This function constrains the returned position to the current field
840 unless that would be on a different line than the original,
841 unconstrained result. If N is nil or 1, and a rear-sticky field ends
842 at point, the scan stops as soon as it starts. To ignore field
843 boundaries bind `inhibit-field-text-motion' to t.
845 This function does not move point. */)
846 (Lisp_Object n)
848 EMACS_INT end_pos;
849 EMACS_INT orig = PT;
851 if (NILP (n))
852 XSETFASTINT (n, 1);
853 else
854 CHECK_NUMBER (n);
856 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
858 /* Return END_POS constrained to the current input field. */
859 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
860 Qnil, Qt, Qnil);
864 Lisp_Object
865 save_excursion_save (void)
867 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
868 == current_buffer);
870 return Fcons (Fpoint_marker (),
871 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
872 Fcons (visible ? Qt : Qnil,
873 Fcons (current_buffer->mark_active,
874 selected_window))));
877 Lisp_Object
878 save_excursion_restore (Lisp_Object info)
880 Lisp_Object tem, tem1, omark, nmark;
881 struct gcpro gcpro1, gcpro2, gcpro3;
882 int visible_p;
884 tem = Fmarker_buffer (XCAR (info));
885 /* If buffer being returned to is now deleted, avoid error */
886 /* Otherwise could get error here while unwinding to top level
887 and crash */
888 /* In that case, Fmarker_buffer returns nil now. */
889 if (NILP (tem))
890 return Qnil;
892 omark = nmark = Qnil;
893 GCPRO3 (info, omark, nmark);
895 Fset_buffer (tem);
897 /* Point marker. */
898 tem = XCAR (info);
899 Fgoto_char (tem);
900 unchain_marker (XMARKER (tem));
902 /* Mark marker. */
903 info = XCDR (info);
904 tem = XCAR (info);
905 omark = Fmarker_position (current_buffer->mark);
906 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
907 nmark = Fmarker_position (tem);
908 unchain_marker (XMARKER (tem));
910 /* visible */
911 info = XCDR (info);
912 visible_p = !NILP (XCAR (info));
914 #if 0 /* We used to make the current buffer visible in the selected window
915 if that was true previously. That avoids some anomalies.
916 But it creates others, and it wasn't documented, and it is simpler
917 and cleaner never to alter the window/buffer connections. */
918 tem1 = Fcar (tem);
919 if (!NILP (tem1)
920 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
921 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
922 #endif /* 0 */
924 /* Mark active */
925 info = XCDR (info);
926 tem = XCAR (info);
927 tem1 = current_buffer->mark_active;
928 current_buffer->mark_active = tem;
930 if (!NILP (Vrun_hooks))
932 /* If mark is active now, and either was not active
933 or was at a different place, run the activate hook. */
934 if (! NILP (current_buffer->mark_active))
936 if (! EQ (omark, nmark))
937 call1 (Vrun_hooks, intern ("activate-mark-hook"));
939 /* If mark has ceased to be active, run deactivate hook. */
940 else if (! NILP (tem1))
941 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
944 /* If buffer was visible in a window, and a different window was
945 selected, and the old selected window is still showing this
946 buffer, restore point in that window. */
947 tem = XCDR (info);
948 if (visible_p
949 && !EQ (tem, selected_window)
950 && (tem1 = XWINDOW (tem)->buffer,
951 (/* Window is live... */
952 BUFFERP (tem1)
953 /* ...and it shows the current buffer. */
954 && XBUFFER (tem1) == current_buffer)))
955 Fset_window_point (tem, make_number (PT));
957 UNGCPRO;
958 return Qnil;
961 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
962 doc: /* Save point, mark, and current buffer; execute BODY; restore those things.
963 Executes BODY just like `progn'.
964 The values of point, mark and the current buffer are restored
965 even in case of abnormal exit (throw or error).
966 The state of activation of the mark is also restored.
968 This construct does not save `deactivate-mark', and therefore
969 functions that change the buffer will still cause deactivation
970 of the mark at the end of the command. To prevent that, bind
971 `deactivate-mark' with `let'.
973 If you only want to save the current buffer but not point nor mark,
974 then just use `save-current-buffer', or even `with-current-buffer'.
976 usage: (save-excursion &rest BODY) */)
977 (Lisp_Object args)
979 register Lisp_Object val;
980 int count = SPECPDL_INDEX ();
982 record_unwind_protect (save_excursion_restore, save_excursion_save ());
984 val = Fprogn (args);
985 return unbind_to (count, val);
988 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
989 doc: /* Save the current buffer; execute BODY; restore the current buffer.
990 Executes BODY just like `progn'.
991 usage: (save-current-buffer &rest BODY) */)
992 (Lisp_Object args)
994 Lisp_Object val;
995 int count = SPECPDL_INDEX ();
997 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
999 val = Fprogn (args);
1000 return unbind_to (count, val);
1003 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
1004 doc: /* Return the number of characters in the current buffer.
1005 If BUFFER, return the number of characters in that buffer instead. */)
1006 (Lisp_Object buffer)
1008 if (NILP (buffer))
1009 return make_number (Z - BEG);
1010 else
1012 CHECK_BUFFER (buffer);
1013 return make_number (BUF_Z (XBUFFER (buffer))
1014 - BUF_BEG (XBUFFER (buffer)));
1018 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
1019 doc: /* Return the minimum permissible value of point in the current buffer.
1020 This is 1, unless narrowing (a buffer restriction) is in effect. */)
1021 (void)
1023 Lisp_Object temp;
1024 XSETFASTINT (temp, BEGV);
1025 return temp;
1028 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
1029 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1030 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1031 (void)
1033 return buildmark (BEGV, BEGV_BYTE);
1036 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1037 doc: /* Return the maximum permissible value of point in the current buffer.
1038 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1039 is in effect, in which case it is less. */)
1040 (void)
1042 Lisp_Object temp;
1043 XSETFASTINT (temp, ZV);
1044 return temp;
1047 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1048 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1049 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1050 is in effect, in which case it is less. */)
1051 (void)
1053 return buildmark (ZV, ZV_BYTE);
1056 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1057 doc: /* Return the position of the gap, in the current buffer.
1058 See also `gap-size'. */)
1059 (void)
1061 Lisp_Object temp;
1062 XSETFASTINT (temp, GPT);
1063 return temp;
1066 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1067 doc: /* Return the size of the current buffer's gap.
1068 See also `gap-position'. */)
1069 (void)
1071 Lisp_Object temp;
1072 XSETFASTINT (temp, GAP_SIZE);
1073 return temp;
1076 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1077 doc: /* Return the byte position for character position POSITION.
1078 If POSITION is out of range, the value is nil. */)
1079 (Lisp_Object position)
1081 CHECK_NUMBER_COERCE_MARKER (position);
1082 if (XINT (position) < BEG || XINT (position) > Z)
1083 return Qnil;
1084 return make_number (CHAR_TO_BYTE (XINT (position)));
1087 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1088 doc: /* Return the character position for byte position BYTEPOS.
1089 If BYTEPOS is out of range, the value is nil. */)
1090 (Lisp_Object bytepos)
1092 CHECK_NUMBER (bytepos);
1093 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
1094 return Qnil;
1095 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1098 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1099 doc: /* Return the character following point, as a number.
1100 At the end of the buffer or accessible region, return 0. */)
1101 (void)
1103 Lisp_Object temp;
1104 if (PT >= ZV)
1105 XSETFASTINT (temp, 0);
1106 else
1107 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1108 return temp;
1111 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1112 doc: /* Return the character preceding point, as a number.
1113 At the beginning of the buffer or accessible region, return 0. */)
1114 (void)
1116 Lisp_Object temp;
1117 if (PT <= BEGV)
1118 XSETFASTINT (temp, 0);
1119 else if (!NILP (current_buffer->enable_multibyte_characters))
1121 EMACS_INT pos = PT_BYTE;
1122 DEC_POS (pos);
1123 XSETFASTINT (temp, FETCH_CHAR (pos));
1125 else
1126 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1127 return temp;
1130 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1131 doc: /* Return t if point is at the beginning of the buffer.
1132 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1133 (void)
1135 if (PT == BEGV)
1136 return Qt;
1137 return Qnil;
1140 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1141 doc: /* Return t if point is at the end of the buffer.
1142 If the buffer is narrowed, this means the end of the narrowed part. */)
1143 (void)
1145 if (PT == ZV)
1146 return Qt;
1147 return Qnil;
1150 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1151 doc: /* Return t if point is at the beginning of a line. */)
1152 (void)
1154 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1155 return Qt;
1156 return Qnil;
1159 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1160 doc: /* Return t if point is at the end of a line.
1161 `End of a line' includes point being at the end of the buffer. */)
1162 (void)
1164 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1165 return Qt;
1166 return Qnil;
1169 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1170 doc: /* Return character in current buffer at position POS.
1171 POS is an integer or a marker and defaults to point.
1172 If POS is out of range, the value is nil. */)
1173 (Lisp_Object pos)
1175 register EMACS_INT pos_byte;
1177 if (NILP (pos))
1179 pos_byte = PT_BYTE;
1180 XSETFASTINT (pos, PT);
1183 if (MARKERP (pos))
1185 pos_byte = marker_byte_position (pos);
1186 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1187 return Qnil;
1189 else
1191 CHECK_NUMBER_COERCE_MARKER (pos);
1192 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1193 return Qnil;
1195 pos_byte = CHAR_TO_BYTE (XINT (pos));
1198 return make_number (FETCH_CHAR (pos_byte));
1201 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1202 doc: /* Return character in current buffer preceding position POS.
1203 POS is an integer or a marker and defaults to point.
1204 If POS is out of range, the value is nil. */)
1205 (Lisp_Object pos)
1207 register Lisp_Object val;
1208 register EMACS_INT pos_byte;
1210 if (NILP (pos))
1212 pos_byte = PT_BYTE;
1213 XSETFASTINT (pos, PT);
1216 if (MARKERP (pos))
1218 pos_byte = marker_byte_position (pos);
1220 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1221 return Qnil;
1223 else
1225 CHECK_NUMBER_COERCE_MARKER (pos);
1227 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1228 return Qnil;
1230 pos_byte = CHAR_TO_BYTE (XINT (pos));
1233 if (!NILP (current_buffer->enable_multibyte_characters))
1235 DEC_POS (pos_byte);
1236 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1238 else
1240 pos_byte--;
1241 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1243 return val;
1246 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1247 doc: /* Return the name under which the user logged in, as a string.
1248 This is based on the effective uid, not the real uid.
1249 Also, if the environment variables LOGNAME or USER are set,
1250 that determines the value of this function.
1252 If optional argument UID is an integer or a float, return the login name
1253 of the user with that uid, or nil if there is no such user. */)
1254 (Lisp_Object uid)
1256 struct passwd *pw;
1257 uid_t id;
1259 /* Set up the user name info if we didn't do it before.
1260 (That can happen if Emacs is dumpable
1261 but you decide to run `temacs -l loadup' and not dump. */
1262 if (INTEGERP (Vuser_login_name))
1263 init_editfns ();
1265 if (NILP (uid))
1266 return Vuser_login_name;
1268 id = (uid_t)XFLOATINT (uid);
1269 BLOCK_INPUT;
1270 pw = (struct passwd *) getpwuid (id);
1271 UNBLOCK_INPUT;
1272 return (pw ? build_string (pw->pw_name) : Qnil);
1275 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1276 0, 0, 0,
1277 doc: /* Return the name of the user's real uid, as a string.
1278 This ignores the environment variables LOGNAME and USER, so it differs from
1279 `user-login-name' when running under `su'. */)
1280 (void)
1282 /* Set up the user name info if we didn't do it before.
1283 (That can happen if Emacs is dumpable
1284 but you decide to run `temacs -l loadup' and not dump. */
1285 if (INTEGERP (Vuser_login_name))
1286 init_editfns ();
1287 return Vuser_real_login_name;
1290 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1291 doc: /* Return the effective uid of Emacs.
1292 Value is an integer or a float, depending on the value. */)
1293 (void)
1295 /* Assignment to EMACS_INT stops GCC whining about limited range of
1296 data type. */
1297 EMACS_INT euid = geteuid ();
1299 /* Make sure we don't produce a negative UID due to signed integer
1300 overflow. */
1301 if (euid < 0)
1302 return make_float ((double)geteuid ());
1303 return make_fixnum_or_float (euid);
1306 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1307 doc: /* Return the real uid of Emacs.
1308 Value is an integer or a float, depending on the value. */)
1309 (void)
1311 /* Assignment to EMACS_INT stops GCC whining about limited range of
1312 data type. */
1313 EMACS_INT uid = getuid ();
1315 /* Make sure we don't produce a negative UID due to signed integer
1316 overflow. */
1317 if (uid < 0)
1318 return make_float ((double)getuid ());
1319 return make_fixnum_or_float (uid);
1322 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1323 doc: /* Return the full name of the user logged in, as a string.
1324 If the full name corresponding to Emacs's userid is not known,
1325 return "unknown".
1327 If optional argument UID is an integer or float, return the full name
1328 of the user with that uid, or nil if there is no such user.
1329 If UID is a string, return the full name of the user with that login
1330 name, or nil if there is no such user. */)
1331 (Lisp_Object uid)
1333 struct passwd *pw;
1334 register unsigned char *p, *q;
1335 Lisp_Object full;
1337 if (NILP (uid))
1338 return Vuser_full_name;
1339 else if (NUMBERP (uid))
1341 BLOCK_INPUT;
1342 pw = (struct passwd *) getpwuid ((uid_t) XFLOATINT (uid));
1343 UNBLOCK_INPUT;
1345 else if (STRINGP (uid))
1347 BLOCK_INPUT;
1348 pw = (struct passwd *) getpwnam (SDATA (uid));
1349 UNBLOCK_INPUT;
1351 else
1352 error ("Invalid UID specification");
1354 if (!pw)
1355 return Qnil;
1357 p = (unsigned char *) USER_FULL_NAME;
1358 /* Chop off everything after the first comma. */
1359 q = (unsigned char *) strchr (p, ',');
1360 full = make_string (p, q ? q - p : strlen (p));
1362 #ifdef AMPERSAND_FULL_NAME
1363 p = SDATA (full);
1364 q = (unsigned char *) strchr (p, '&');
1365 /* Substitute the login name for the &, upcasing the first character. */
1366 if (q)
1368 register unsigned char *r;
1369 Lisp_Object login;
1371 login = Fuser_login_name (make_number (pw->pw_uid));
1372 r = (unsigned char *) alloca (strlen (p) + SCHARS (login) + 1);
1373 memcpy (r, p, q - p);
1374 r[q - p] = 0;
1375 strcat (r, SDATA (login));
1376 r[q - p] = UPCASE (r[q - p]);
1377 strcat (r, q + 1);
1378 full = build_string (r);
1380 #endif /* AMPERSAND_FULL_NAME */
1382 return full;
1385 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1386 doc: /* Return the host name of the machine you are running on, as a string. */)
1387 (void)
1389 return Vsystem_name;
1392 /* For the benefit of callers who don't want to include lisp.h */
1394 const char *
1395 get_system_name (void)
1397 if (STRINGP (Vsystem_name))
1398 return SSDATA (Vsystem_name);
1399 else
1400 return "";
1403 const char *
1404 get_operating_system_release (void)
1406 if (STRINGP (Voperating_system_release))
1407 return SSDATA (Voperating_system_release);
1408 else
1409 return "";
1412 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1413 doc: /* Return the process ID of Emacs, as an integer. */)
1414 (void)
1416 return make_number (getpid ());
1419 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1420 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1421 The time is returned as a list of three integers. The first has the
1422 most significant 16 bits of the seconds, while the second has the
1423 least significant 16 bits. The third integer gives the microsecond
1424 count.
1426 The microsecond count is zero on systems that do not provide
1427 resolution finer than a second. */)
1428 (void)
1430 EMACS_TIME t;
1432 EMACS_GET_TIME (t);
1433 return list3 (make_number ((EMACS_SECS (t) >> 16) & 0xffff),
1434 make_number ((EMACS_SECS (t) >> 0) & 0xffff),
1435 make_number (EMACS_USECS (t)));
1438 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1439 0, 0, 0,
1440 doc: /* Return the current run time used by Emacs.
1441 The time is returned as a list of three integers. The first has the
1442 most significant 16 bits of the seconds, while the second has the
1443 least significant 16 bits. The third integer gives the microsecond
1444 count.
1446 On systems that can't determine the run time, `get-internal-run-time'
1447 does the same thing as `current-time'. The microsecond count is zero
1448 on systems that do not provide resolution finer than a second. */)
1449 (void)
1451 #ifdef HAVE_GETRUSAGE
1452 struct rusage usage;
1453 int secs, usecs;
1455 if (getrusage (RUSAGE_SELF, &usage) < 0)
1456 /* This shouldn't happen. What action is appropriate? */
1457 xsignal0 (Qerror);
1459 /* Sum up user time and system time. */
1460 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1461 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1462 if (usecs >= 1000000)
1464 usecs -= 1000000;
1465 secs++;
1468 return list3 (make_number ((secs >> 16) & 0xffff),
1469 make_number ((secs >> 0) & 0xffff),
1470 make_number (usecs));
1471 #else /* ! HAVE_GETRUSAGE */
1472 #ifdef WINDOWSNT
1473 return w32_get_internal_run_time ();
1474 #else /* ! WINDOWSNT */
1475 return Fcurrent_time ();
1476 #endif /* WINDOWSNT */
1477 #endif /* HAVE_GETRUSAGE */
1482 lisp_time_argument (Lisp_Object specified_time, time_t *result, int *usec)
1484 if (NILP (specified_time))
1486 if (usec)
1488 EMACS_TIME t;
1490 EMACS_GET_TIME (t);
1491 *usec = EMACS_USECS (t);
1492 *result = EMACS_SECS (t);
1493 return 1;
1495 else
1496 return time (result) != -1;
1498 else
1500 Lisp_Object high, low;
1501 high = Fcar (specified_time);
1502 CHECK_NUMBER (high);
1503 low = Fcdr (specified_time);
1504 if (CONSP (low))
1506 if (usec)
1508 Lisp_Object usec_l = Fcdr (low);
1509 if (CONSP (usec_l))
1510 usec_l = Fcar (usec_l);
1511 if (NILP (usec_l))
1512 *usec = 0;
1513 else
1515 CHECK_NUMBER (usec_l);
1516 *usec = XINT (usec_l);
1519 low = Fcar (low);
1521 else if (usec)
1522 *usec = 0;
1523 CHECK_NUMBER (low);
1524 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
1525 return *result >> 16 == XINT (high);
1529 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1530 doc: /* Return the current time, as a float number of seconds since the epoch.
1531 If SPECIFIED-TIME is given, it is the time to convert to float
1532 instead of the current time. The argument should have the form
1533 (HIGH LOW) or (HIGH LOW USEC). Thus, you can use times obtained from
1534 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
1535 have the form (HIGH . LOW), but this is considered obsolete.
1537 WARNING: Since the result is floating point, it may not be exact.
1538 If precise time stamps are required, use either `current-time',
1539 or (if you need time as a string) `format-time-string'. */)
1540 (Lisp_Object specified_time)
1542 time_t sec;
1543 int usec;
1545 if (! lisp_time_argument (specified_time, &sec, &usec))
1546 error ("Invalid time specification");
1548 return make_float ((sec * 1e6 + usec) / 1e6);
1551 /* Write information into buffer S of size MAXSIZE, according to the
1552 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1553 Default to Universal Time if UT is nonzero, local time otherwise.
1554 Return the number of bytes written, not including the terminating
1555 '\0'. If S is NULL, nothing will be written anywhere; so to
1556 determine how many bytes would be written, use NULL for S and
1557 ((size_t) -1) for MAXSIZE.
1559 This function behaves like emacs_strftimeu, except it allows null
1560 bytes in FORMAT. */
1561 static size_t
1562 emacs_memftimeu (char *s, size_t maxsize, const char *format, size_t format_len, const struct tm *tp, int ut)
1564 size_t total = 0;
1566 /* Loop through all the null-terminated strings in the format
1567 argument. Normally there's just one null-terminated string, but
1568 there can be arbitrarily many, concatenated together, if the
1569 format contains '\0' bytes. emacs_strftimeu stops at the first
1570 '\0' byte so we must invoke it separately for each such string. */
1571 for (;;)
1573 size_t len;
1574 size_t result;
1576 if (s)
1577 s[0] = '\1';
1579 result = emacs_strftimeu (s, maxsize, format, tp, ut);
1581 if (s)
1583 if (result == 0 && s[0] != '\0')
1584 return 0;
1585 s += result + 1;
1588 maxsize -= result + 1;
1589 total += result;
1590 len = strlen (format);
1591 if (len == format_len)
1592 return total;
1593 total++;
1594 format += len + 1;
1595 format_len -= len + 1;
1599 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1600 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
1601 TIME is specified as (HIGH LOW . IGNORED), as returned by
1602 `current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
1603 is also still accepted.
1604 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1605 as Universal Time; nil means describe TIME in the local time zone.
1606 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1607 by text that describes the specified date and time in TIME:
1609 %Y is the year, %y within the century, %C the century.
1610 %G is the year corresponding to the ISO week, %g within the century.
1611 %m is the numeric month.
1612 %b and %h are the locale's abbreviated month name, %B the full name.
1613 %d is the day of the month, zero-padded, %e is blank-padded.
1614 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1615 %a is the locale's abbreviated name of the day of week, %A the full name.
1616 %U is the week number starting on Sunday, %W starting on Monday,
1617 %V according to ISO 8601.
1618 %j is the day of the year.
1620 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1621 only blank-padded, %l is like %I blank-padded.
1622 %p is the locale's equivalent of either AM or PM.
1623 %M is the minute.
1624 %S is the second.
1625 %Z is the time zone name, %z is the numeric form.
1626 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1628 %c is the locale's date and time format.
1629 %x is the locale's "preferred" date format.
1630 %D is like "%m/%d/%y".
1632 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1633 %X is the locale's "preferred" time format.
1635 Finally, %n is a newline, %t is a tab, %% is a literal %.
1637 Certain flags and modifiers are available with some format controls.
1638 The flags are `_', `-', `^' and `#'. For certain characters X,
1639 %_X is like %X, but padded with blanks; %-X is like %X,
1640 but without padding. %^X is like %X, but with all textual
1641 characters up-cased; %#X is like %X, but with letter-case of
1642 all textual characters reversed.
1643 %NX (where N stands for an integer) is like %X,
1644 but takes up at least N (a number) positions.
1645 The modifiers are `E' and `O'. For certain characters X,
1646 %EX is a locale's alternative version of %X;
1647 %OX is like %X, but uses the locale's number symbols.
1649 For example, to produce full ISO 8601 format, use "%Y-%m-%dT%T%z". */)
1650 (Lisp_Object format_string, Lisp_Object time, Lisp_Object universal)
1652 time_t value;
1653 int size;
1654 struct tm *tm;
1655 int ut = ! NILP (universal);
1657 CHECK_STRING (format_string);
1659 if (! lisp_time_argument (time, &value, NULL))
1660 error ("Invalid time specification");
1662 format_string = code_convert_string_norecord (format_string,
1663 Vlocale_coding_system, 1);
1665 /* This is probably enough. */
1666 size = SBYTES (format_string) * 6 + 50;
1668 BLOCK_INPUT;
1669 tm = ut ? gmtime (&value) : localtime (&value);
1670 UNBLOCK_INPUT;
1671 if (! tm)
1672 error ("Specified time is not representable");
1674 synchronize_system_time_locale ();
1676 while (1)
1678 char *buf = (char *) alloca (size + 1);
1679 int result;
1681 buf[0] = '\1';
1682 BLOCK_INPUT;
1683 result = emacs_memftimeu (buf, size, SDATA (format_string),
1684 SBYTES (format_string),
1685 tm, ut);
1686 UNBLOCK_INPUT;
1687 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1688 return code_convert_string_norecord (make_unibyte_string (buf, result),
1689 Vlocale_coding_system, 0);
1691 /* If buffer was too small, make it bigger and try again. */
1692 BLOCK_INPUT;
1693 result = emacs_memftimeu (NULL, (size_t) -1,
1694 SDATA (format_string),
1695 SBYTES (format_string),
1696 tm, ut);
1697 UNBLOCK_INPUT;
1698 size = result + 1;
1702 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1703 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
1704 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
1705 as from `current-time' and `file-attributes', or nil to use the
1706 current time. The obsolete form (HIGH . LOW) is also still accepted.
1707 The list has the following nine members: SEC is an integer between 0
1708 and 60; SEC is 60 for a leap second, which only some operating systems
1709 support. MINUTE is an integer between 0 and 59. HOUR is an integer
1710 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
1711 integer between 1 and 12. YEAR is an integer indicating the
1712 four-digit year. DOW is the day of week, an integer between 0 and 6,
1713 where 0 is Sunday. DST is t if daylight saving time is in effect,
1714 otherwise nil. ZONE is an integer indicating the number of seconds
1715 east of Greenwich. (Note that Common Lisp has different meanings for
1716 DOW and ZONE.) */)
1717 (Lisp_Object specified_time)
1719 time_t time_spec;
1720 struct tm save_tm;
1721 struct tm *decoded_time;
1722 Lisp_Object list_args[9];
1724 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1725 error ("Invalid time specification");
1727 BLOCK_INPUT;
1728 decoded_time = localtime (&time_spec);
1729 UNBLOCK_INPUT;
1730 if (! decoded_time)
1731 error ("Specified time is not representable");
1732 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1733 XSETFASTINT (list_args[1], decoded_time->tm_min);
1734 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1735 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1736 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1737 /* On 64-bit machines an int is narrower than EMACS_INT, thus the
1738 cast below avoids overflow in int arithmetics. */
1739 XSETINT (list_args[5], TM_YEAR_BASE + (EMACS_INT) decoded_time->tm_year);
1740 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1741 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1743 /* Make a copy, in case gmtime modifies the struct. */
1744 save_tm = *decoded_time;
1745 BLOCK_INPUT;
1746 decoded_time = gmtime (&time_spec);
1747 UNBLOCK_INPUT;
1748 if (decoded_time == 0)
1749 list_args[8] = Qnil;
1750 else
1751 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1752 return Flist (9, list_args);
1755 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1756 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
1757 This is the reverse operation of `decode-time', which see.
1758 ZONE defaults to the current time zone rule. This can
1759 be a string or t (as from `set-time-zone-rule'), or it can be a list
1760 \(as from `current-time-zone') or an integer (as from `decode-time')
1761 applied without consideration for daylight saving time.
1763 You can pass more than 7 arguments; then the first six arguments
1764 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
1765 The intervening arguments are ignored.
1766 This feature lets (apply 'encode-time (decode-time ...)) work.
1768 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
1769 for example, a DAY of 0 means the day preceding the given month.
1770 Year numbers less than 100 are treated just like other year numbers.
1771 If you want them to stand for years in this century, you must do that yourself.
1773 Years before 1970 are not guaranteed to work. On some systems,
1774 year values as low as 1901 do work.
1776 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
1777 (int nargs, register Lisp_Object *args)
1779 time_t time;
1780 struct tm tm;
1781 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1783 CHECK_NUMBER (args[0]); /* second */
1784 CHECK_NUMBER (args[1]); /* minute */
1785 CHECK_NUMBER (args[2]); /* hour */
1786 CHECK_NUMBER (args[3]); /* day */
1787 CHECK_NUMBER (args[4]); /* month */
1788 CHECK_NUMBER (args[5]); /* year */
1790 tm.tm_sec = XINT (args[0]);
1791 tm.tm_min = XINT (args[1]);
1792 tm.tm_hour = XINT (args[2]);
1793 tm.tm_mday = XINT (args[3]);
1794 tm.tm_mon = XINT (args[4]) - 1;
1795 tm.tm_year = XINT (args[5]) - TM_YEAR_BASE;
1796 tm.tm_isdst = -1;
1798 if (CONSP (zone))
1799 zone = Fcar (zone);
1800 if (NILP (zone))
1802 BLOCK_INPUT;
1803 time = mktime (&tm);
1804 UNBLOCK_INPUT;
1806 else
1808 char tzbuf[100];
1809 const char *tzstring;
1810 char **oldenv = environ, **newenv;
1812 if (EQ (zone, Qt))
1813 tzstring = "UTC0";
1814 else if (STRINGP (zone))
1815 tzstring = SSDATA (zone);
1816 else if (INTEGERP (zone))
1818 int abszone = eabs (XINT (zone));
1819 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1820 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1821 tzstring = tzbuf;
1823 else
1824 error ("Invalid time zone specification");
1826 /* Set TZ before calling mktime; merely adjusting mktime's returned
1827 value doesn't suffice, since that would mishandle leap seconds. */
1828 set_time_zone_rule (tzstring);
1830 BLOCK_INPUT;
1831 time = mktime (&tm);
1832 UNBLOCK_INPUT;
1834 /* Restore TZ to previous value. */
1835 newenv = environ;
1836 environ = oldenv;
1837 xfree (newenv);
1838 #ifdef LOCALTIME_CACHE
1839 tzset ();
1840 #endif
1843 if (time == (time_t) -1)
1844 error ("Specified time is not representable");
1846 return make_time (time);
1849 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1850 doc: /* Return the current local time, as a human-readable string.
1851 Programs can use this function to decode a time,
1852 since the number of columns in each field is fixed
1853 if the year is in the range 1000-9999.
1854 The format is `Sun Sep 16 01:03:52 1973'.
1855 However, see also the functions `decode-time' and `format-time-string'
1856 which provide a much more powerful and general facility.
1858 If SPECIFIED-TIME is given, it is a time to format instead of the
1859 current time. The argument should have the form (HIGH LOW . IGNORED).
1860 Thus, you can use times obtained from `current-time' and from
1861 `file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
1862 but this is considered obsolete. */)
1863 (Lisp_Object specified_time)
1865 time_t value;
1866 struct tm *tm;
1867 register char *tem;
1869 if (! lisp_time_argument (specified_time, &value, NULL))
1870 error ("Invalid time specification");
1872 /* Convert to a string, checking for out-of-range time stamps.
1873 Don't use 'ctime', as that might dump core if VALUE is out of
1874 range. */
1875 BLOCK_INPUT;
1876 tm = localtime (&value);
1877 UNBLOCK_INPUT;
1878 if (! (tm && TM_YEAR_IN_ASCTIME_RANGE (tm->tm_year) && (tem = asctime (tm))))
1879 error ("Specified time is not representable");
1881 /* Remove the trailing newline. */
1882 tem[strlen (tem) - 1] = '\0';
1884 return build_string (tem);
1887 /* Yield A - B, measured in seconds.
1888 This function is copied from the GNU C Library. */
1889 static int
1890 tm_diff (struct tm *a, struct tm *b)
1892 /* Compute intervening leap days correctly even if year is negative.
1893 Take care to avoid int overflow in leap day calculations,
1894 but it's OK to assume that A and B are close to each other. */
1895 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1896 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1897 int a100 = a4 / 25 - (a4 % 25 < 0);
1898 int b100 = b4 / 25 - (b4 % 25 < 0);
1899 int a400 = a100 >> 2;
1900 int b400 = b100 >> 2;
1901 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1902 int years = a->tm_year - b->tm_year;
1903 int days = (365 * years + intervening_leap_days
1904 + (a->tm_yday - b->tm_yday));
1905 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1906 + (a->tm_min - b->tm_min))
1907 + (a->tm_sec - b->tm_sec));
1910 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1911 doc: /* Return the offset and name for the local time zone.
1912 This returns a list of the form (OFFSET NAME).
1913 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
1914 A negative value means west of Greenwich.
1915 NAME is a string giving the name of the time zone.
1916 If SPECIFIED-TIME is given, the time zone offset is determined from it
1917 instead of using the current time. The argument should have the form
1918 (HIGH LOW . IGNORED). Thus, you can use times obtained from
1919 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
1920 have the form (HIGH . LOW), but this is considered obsolete.
1922 Some operating systems cannot provide all this information to Emacs;
1923 in this case, `current-time-zone' returns a list containing nil for
1924 the data it can't find. */)
1925 (Lisp_Object specified_time)
1927 time_t value;
1928 struct tm *t;
1929 struct tm gmt;
1931 if (!lisp_time_argument (specified_time, &value, NULL))
1932 t = NULL;
1933 else
1935 BLOCK_INPUT;
1936 t = gmtime (&value);
1937 if (t)
1939 gmt = *t;
1940 t = localtime (&value);
1942 UNBLOCK_INPUT;
1945 if (t)
1947 int offset = tm_diff (t, &gmt);
1948 char *s = 0;
1949 char buf[6];
1951 #ifdef HAVE_TM_ZONE
1952 if (t->tm_zone)
1953 s = (char *)t->tm_zone;
1954 #else /* not HAVE_TM_ZONE */
1955 #ifdef HAVE_TZNAME
1956 if (t->tm_isdst == 0 || t->tm_isdst == 1)
1957 s = tzname[t->tm_isdst];
1958 #endif
1959 #endif /* not HAVE_TM_ZONE */
1961 if (!s)
1963 /* No local time zone name is available; use "+-NNNN" instead. */
1964 int am = (offset < 0 ? -offset : offset) / 60;
1965 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
1966 s = buf;
1969 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
1971 else
1972 return Fmake_list (make_number (2), Qnil);
1975 /* This holds the value of `environ' produced by the previous
1976 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
1977 has never been called. */
1978 static char **environbuf;
1980 /* This holds the startup value of the TZ environment variable so it
1981 can be restored if the user calls set-time-zone-rule with a nil
1982 argument. */
1983 static char *initial_tz;
1985 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
1986 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
1987 If TZ is nil, use implementation-defined default time zone information.
1988 If TZ is t, use Universal Time. */)
1989 (Lisp_Object tz)
1991 const char *tzstring;
1993 /* When called for the first time, save the original TZ. */
1994 if (!environbuf)
1995 initial_tz = (char *) getenv ("TZ");
1997 if (NILP (tz))
1998 tzstring = initial_tz;
1999 else if (EQ (tz, Qt))
2000 tzstring = "UTC0";
2001 else
2003 CHECK_STRING (tz);
2004 tzstring = SSDATA (tz);
2007 set_time_zone_rule (tzstring);
2008 free (environbuf);
2009 environbuf = environ;
2011 return Qnil;
2014 #ifdef LOCALTIME_CACHE
2016 /* These two values are known to load tz files in buggy implementations,
2017 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
2018 Their values shouldn't matter in non-buggy implementations.
2019 We don't use string literals for these strings,
2020 since if a string in the environment is in readonly
2021 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
2022 See Sun bugs 1113095 and 1114114, ``Timezone routines
2023 improperly modify environment''. */
2025 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
2026 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
2028 #endif
2030 /* Set the local time zone rule to TZSTRING.
2031 This allocates memory into `environ', which it is the caller's
2032 responsibility to free. */
2034 void
2035 set_time_zone_rule (const char *tzstring)
2037 int envptrs;
2038 char **from, **to, **newenv;
2040 /* Make the ENVIRON vector longer with room for TZSTRING. */
2041 for (from = environ; *from; from++)
2042 continue;
2043 envptrs = from - environ + 2;
2044 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
2045 + (tzstring ? strlen (tzstring) + 4 : 0));
2047 /* Add TZSTRING to the end of environ, as a value for TZ. */
2048 if (tzstring)
2050 char *t = (char *) (to + envptrs);
2051 strcpy (t, "TZ=");
2052 strcat (t, tzstring);
2053 *to++ = t;
2056 /* Copy the old environ vector elements into NEWENV,
2057 but don't copy the TZ variable.
2058 So we have only one definition of TZ, which came from TZSTRING. */
2059 for (from = environ; *from; from++)
2060 if (strncmp (*from, "TZ=", 3) != 0)
2061 *to++ = *from;
2062 *to = 0;
2064 environ = newenv;
2066 /* If we do have a TZSTRING, NEWENV points to the vector slot where
2067 the TZ variable is stored. If we do not have a TZSTRING,
2068 TO points to the vector slot which has the terminating null. */
2070 #ifdef LOCALTIME_CACHE
2072 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
2073 "US/Pacific" that loads a tz file, then changes to a value like
2074 "XXX0" that does not load a tz file, and then changes back to
2075 its original value, the last change is (incorrectly) ignored.
2076 Also, if TZ changes twice in succession to values that do
2077 not load a tz file, tzset can dump core (see Sun bug#1225179).
2078 The following code works around these bugs. */
2080 if (tzstring)
2082 /* Temporarily set TZ to a value that loads a tz file
2083 and that differs from tzstring. */
2084 char *tz = *newenv;
2085 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
2086 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
2087 tzset ();
2088 *newenv = tz;
2090 else
2092 /* The implied tzstring is unknown, so temporarily set TZ to
2093 two different values that each load a tz file. */
2094 *to = set_time_zone_rule_tz1;
2095 to[1] = 0;
2096 tzset ();
2097 *to = set_time_zone_rule_tz2;
2098 tzset ();
2099 *to = 0;
2102 /* Now TZ has the desired value, and tzset can be invoked safely. */
2105 tzset ();
2106 #endif
2109 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2110 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2111 type of object is Lisp_String). INHERIT is passed to
2112 INSERT_FROM_STRING_FUNC as the last argument. */
2114 static void
2115 general_insert_function (void (*insert_func)
2116 (const unsigned char *, EMACS_INT),
2117 void (*insert_from_string_func)
2118 (Lisp_Object, EMACS_INT, EMACS_INT,
2119 EMACS_INT, EMACS_INT, int),
2120 int inherit, int nargs, Lisp_Object *args)
2122 register int argnum;
2123 register Lisp_Object val;
2125 for (argnum = 0; argnum < nargs; argnum++)
2127 val = args[argnum];
2128 if (CHARACTERP (val))
2130 unsigned char str[MAX_MULTIBYTE_LENGTH];
2131 int len;
2133 if (!NILP (current_buffer->enable_multibyte_characters))
2134 len = CHAR_STRING (XFASTINT (val), str);
2135 else
2137 str[0] = (ASCII_CHAR_P (XINT (val))
2138 ? XINT (val)
2139 : multibyte_char_to_unibyte (XINT (val), Qnil));
2140 len = 1;
2142 (*insert_func) (str, len);
2144 else if (STRINGP (val))
2146 (*insert_from_string_func) (val, 0, 0,
2147 SCHARS (val),
2148 SBYTES (val),
2149 inherit);
2151 else
2152 wrong_type_argument (Qchar_or_string_p, val);
2156 void
2157 insert1 (Lisp_Object arg)
2159 Finsert (1, &arg);
2163 /* Callers passing one argument to Finsert need not gcpro the
2164 argument "array", since the only element of the array will
2165 not be used after calling insert or insert_from_string, so
2166 we don't care if it gets trashed. */
2168 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2169 doc: /* Insert the arguments, either strings or characters, at point.
2170 Point and before-insertion markers move forward to end up
2171 after the inserted text.
2172 Any other markers at the point of insertion remain before the text.
2174 If the current buffer is multibyte, unibyte strings are converted
2175 to multibyte for insertion (see `string-make-multibyte').
2176 If the current buffer is unibyte, multibyte strings are converted
2177 to unibyte for insertion (see `string-make-unibyte').
2179 When operating on binary data, it may be necessary to preserve the
2180 original bytes of a unibyte string when inserting it into a multibyte
2181 buffer; to accomplish this, apply `string-as-multibyte' to the string
2182 and insert the result.
2184 usage: (insert &rest ARGS) */)
2185 (int nargs, register Lisp_Object *args)
2187 general_insert_function (insert, insert_from_string, 0, nargs, args);
2188 return Qnil;
2191 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2192 0, MANY, 0,
2193 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2194 Point and before-insertion markers move forward to end up
2195 after the inserted text.
2196 Any other markers at the point of insertion remain before the text.
2198 If the current buffer is multibyte, unibyte strings are converted
2199 to multibyte for insertion (see `unibyte-char-to-multibyte').
2200 If the current buffer is unibyte, multibyte strings are converted
2201 to unibyte for insertion.
2203 usage: (insert-and-inherit &rest ARGS) */)
2204 (int nargs, register Lisp_Object *args)
2206 general_insert_function (insert_and_inherit, insert_from_string, 1,
2207 nargs, args);
2208 return Qnil;
2211 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2212 doc: /* Insert strings or characters at point, relocating markers after the text.
2213 Point and markers move forward to end up after the inserted text.
2215 If the current buffer is multibyte, unibyte strings are converted
2216 to multibyte for insertion (see `unibyte-char-to-multibyte').
2217 If the current buffer is unibyte, multibyte strings are converted
2218 to unibyte for insertion.
2220 usage: (insert-before-markers &rest ARGS) */)
2221 (int nargs, register Lisp_Object *args)
2223 general_insert_function (insert_before_markers,
2224 insert_from_string_before_markers, 0,
2225 nargs, args);
2226 return Qnil;
2229 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2230 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2231 doc: /* Insert text at point, relocating markers and inheriting properties.
2232 Point and markers move forward to end up after the inserted text.
2234 If the current buffer is multibyte, unibyte strings are converted
2235 to multibyte for insertion (see `unibyte-char-to-multibyte').
2236 If the current buffer is unibyte, multibyte strings are converted
2237 to unibyte for insertion.
2239 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2240 (int nargs, register Lisp_Object *args)
2242 general_insert_function (insert_before_markers_and_inherit,
2243 insert_from_string_before_markers, 1,
2244 nargs, args);
2245 return Qnil;
2248 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
2249 doc: /* Insert COUNT copies of CHARACTER.
2250 Point, and before-insertion markers, are relocated as in the function `insert'.
2251 The optional third arg INHERIT, if non-nil, says to inherit text properties
2252 from adjoining text, if those properties are sticky. */)
2253 (Lisp_Object character, Lisp_Object count, Lisp_Object inherit)
2255 register unsigned char *string;
2256 register EMACS_INT strlen;
2257 register int i;
2258 register EMACS_INT n;
2259 int len;
2260 unsigned char str[MAX_MULTIBYTE_LENGTH];
2262 CHECK_NUMBER (character);
2263 CHECK_NUMBER (count);
2265 if (!NILP (current_buffer->enable_multibyte_characters))
2266 len = CHAR_STRING (XFASTINT (character), str);
2267 else
2268 str[0] = XFASTINT (character), len = 1;
2269 if (MOST_POSITIVE_FIXNUM / len < XINT (count))
2270 error ("Maximum buffer size would be exceeded");
2271 n = XINT (count) * len;
2272 if (n <= 0)
2273 return Qnil;
2274 strlen = min (n, 256 * len);
2275 string = (unsigned char *) alloca (strlen);
2276 for (i = 0; i < strlen; i++)
2277 string[i] = str[i % len];
2278 while (n >= strlen)
2280 QUIT;
2281 if (!NILP (inherit))
2282 insert_and_inherit (string, strlen);
2283 else
2284 insert (string, strlen);
2285 n -= strlen;
2287 if (n > 0)
2289 if (!NILP (inherit))
2290 insert_and_inherit (string, n);
2291 else
2292 insert (string, n);
2294 return Qnil;
2297 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2298 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2299 Both arguments are required.
2300 BYTE is a number of the range 0..255.
2302 If BYTE is 128..255 and the current buffer is multibyte, the
2303 corresponding eight-bit character is inserted.
2305 Point, and before-insertion markers, are relocated as in the function `insert'.
2306 The optional third arg INHERIT, if non-nil, says to inherit text properties
2307 from adjoining text, if those properties are sticky. */)
2308 (Lisp_Object byte, Lisp_Object count, Lisp_Object inherit)
2310 CHECK_NUMBER (byte);
2311 if (XINT (byte) < 0 || XINT (byte) > 255)
2312 args_out_of_range_3 (byte, make_number (0), make_number (255));
2313 if (XINT (byte) >= 128
2314 && ! NILP (current_buffer->enable_multibyte_characters))
2315 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2316 return Finsert_char (byte, count, inherit);
2320 /* Making strings from buffer contents. */
2322 /* Return a Lisp_String containing the text of the current buffer from
2323 START to END. If text properties are in use and the current buffer
2324 has properties in the range specified, the resulting string will also
2325 have them, if PROPS is nonzero.
2327 We don't want to use plain old make_string here, because it calls
2328 make_uninit_string, which can cause the buffer arena to be
2329 compacted. make_string has no way of knowing that the data has
2330 been moved, and thus copies the wrong data into the string. This
2331 doesn't effect most of the other users of make_string, so it should
2332 be left as is. But we should use this function when conjuring
2333 buffer substrings. */
2335 Lisp_Object
2336 make_buffer_string (EMACS_INT start, EMACS_INT end, int props)
2338 EMACS_INT start_byte = CHAR_TO_BYTE (start);
2339 EMACS_INT end_byte = CHAR_TO_BYTE (end);
2341 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2344 /* Return a Lisp_String containing the text of the current buffer from
2345 START / START_BYTE to END / END_BYTE.
2347 If text properties are in use and the current buffer
2348 has properties in the range specified, the resulting string will also
2349 have them, if PROPS is nonzero.
2351 We don't want to use plain old make_string here, because it calls
2352 make_uninit_string, which can cause the buffer arena to be
2353 compacted. make_string has no way of knowing that the data has
2354 been moved, and thus copies the wrong data into the string. This
2355 doesn't effect most of the other users of make_string, so it should
2356 be left as is. But we should use this function when conjuring
2357 buffer substrings. */
2359 Lisp_Object
2360 make_buffer_string_both (EMACS_INT start, EMACS_INT start_byte,
2361 EMACS_INT end, EMACS_INT end_byte, int props)
2363 Lisp_Object result, tem, tem1;
2365 if (start < GPT && GPT < end)
2366 move_gap (start);
2368 if (! NILP (current_buffer->enable_multibyte_characters))
2369 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2370 else
2371 result = make_uninit_string (end - start);
2372 memcpy (SDATA (result), BYTE_POS_ADDR (start_byte), end_byte - start_byte);
2374 /* If desired, update and copy the text properties. */
2375 if (props)
2377 update_buffer_properties (start, end);
2379 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2380 tem1 = Ftext_properties_at (make_number (start), Qnil);
2382 if (XINT (tem) != end || !NILP (tem1))
2383 copy_intervals_to_string (result, current_buffer, start,
2384 end - start);
2387 return result;
2390 /* Call Vbuffer_access_fontify_functions for the range START ... END
2391 in the current buffer, if necessary. */
2393 static void
2394 update_buffer_properties (EMACS_INT start, EMACS_INT end)
2396 /* If this buffer has some access functions,
2397 call them, specifying the range of the buffer being accessed. */
2398 if (!NILP (Vbuffer_access_fontify_functions))
2400 Lisp_Object args[3];
2401 Lisp_Object tem;
2403 args[0] = Qbuffer_access_fontify_functions;
2404 XSETINT (args[1], start);
2405 XSETINT (args[2], end);
2407 /* But don't call them if we can tell that the work
2408 has already been done. */
2409 if (!NILP (Vbuffer_access_fontified_property))
2411 tem = Ftext_property_any (args[1], args[2],
2412 Vbuffer_access_fontified_property,
2413 Qnil, Qnil);
2414 if (! NILP (tem))
2415 Frun_hook_with_args (3, args);
2417 else
2418 Frun_hook_with_args (3, args);
2422 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2423 doc: /* Return the contents of part of the current buffer as a string.
2424 The two arguments START and END are character positions;
2425 they can be in either order.
2426 The string returned is multibyte if the buffer is multibyte.
2428 This function copies the text properties of that part of the buffer
2429 into the result string; if you don't want the text properties,
2430 use `buffer-substring-no-properties' instead. */)
2431 (Lisp_Object start, Lisp_Object end)
2433 register EMACS_INT b, e;
2435 validate_region (&start, &end);
2436 b = XINT (start);
2437 e = XINT (end);
2439 return make_buffer_string (b, e, 1);
2442 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2443 Sbuffer_substring_no_properties, 2, 2, 0,
2444 doc: /* Return the characters of part of the buffer, without the text properties.
2445 The two arguments START and END are character positions;
2446 they can be in either order. */)
2447 (Lisp_Object start, Lisp_Object end)
2449 register EMACS_INT b, e;
2451 validate_region (&start, &end);
2452 b = XINT (start);
2453 e = XINT (end);
2455 return make_buffer_string (b, e, 0);
2458 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2459 doc: /* Return the contents of the current buffer as a string.
2460 If narrowing is in effect, this function returns only the visible part
2461 of the buffer. */)
2462 (void)
2464 return make_buffer_string (BEGV, ZV, 1);
2467 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2468 1, 3, 0,
2469 doc: /* Insert before point a substring of the contents of BUFFER.
2470 BUFFER may be a buffer or a buffer name.
2471 Arguments START and END are character positions specifying the substring.
2472 They default to the values of (point-min) and (point-max) in BUFFER. */)
2473 (Lisp_Object buffer, Lisp_Object start, Lisp_Object end)
2475 register EMACS_INT b, e, temp;
2476 register struct buffer *bp, *obuf;
2477 Lisp_Object buf;
2479 buf = Fget_buffer (buffer);
2480 if (NILP (buf))
2481 nsberror (buffer);
2482 bp = XBUFFER (buf);
2483 if (NILP (bp->name))
2484 error ("Selecting deleted buffer");
2486 if (NILP (start))
2487 b = BUF_BEGV (bp);
2488 else
2490 CHECK_NUMBER_COERCE_MARKER (start);
2491 b = XINT (start);
2493 if (NILP (end))
2494 e = BUF_ZV (bp);
2495 else
2497 CHECK_NUMBER_COERCE_MARKER (end);
2498 e = XINT (end);
2501 if (b > e)
2502 temp = b, b = e, e = temp;
2504 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2505 args_out_of_range (start, end);
2507 obuf = current_buffer;
2508 set_buffer_internal_1 (bp);
2509 update_buffer_properties (b, e);
2510 set_buffer_internal_1 (obuf);
2512 insert_from_buffer (bp, b, e - b, 0);
2513 return Qnil;
2516 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2517 6, 6, 0,
2518 doc: /* Compare two substrings of two buffers; return result as number.
2519 the value is -N if first string is less after N-1 chars,
2520 +N if first string is greater after N-1 chars, or 0 if strings match.
2521 Each substring is represented as three arguments: BUFFER, START and END.
2522 That makes six args in all, three for each substring.
2524 The value of `case-fold-search' in the current buffer
2525 determines whether case is significant or ignored. */)
2526 (Lisp_Object buffer1, Lisp_Object start1, Lisp_Object end1, Lisp_Object buffer2, Lisp_Object start2, Lisp_Object end2)
2528 register EMACS_INT begp1, endp1, begp2, endp2, temp;
2529 register struct buffer *bp1, *bp2;
2530 register Lisp_Object trt
2531 = (!NILP (current_buffer->case_fold_search)
2532 ? current_buffer->case_canon_table : Qnil);
2533 EMACS_INT chars = 0;
2534 EMACS_INT i1, i2, i1_byte, i2_byte;
2536 /* Find the first buffer and its substring. */
2538 if (NILP (buffer1))
2539 bp1 = current_buffer;
2540 else
2542 Lisp_Object buf1;
2543 buf1 = Fget_buffer (buffer1);
2544 if (NILP (buf1))
2545 nsberror (buffer1);
2546 bp1 = XBUFFER (buf1);
2547 if (NILP (bp1->name))
2548 error ("Selecting deleted buffer");
2551 if (NILP (start1))
2552 begp1 = BUF_BEGV (bp1);
2553 else
2555 CHECK_NUMBER_COERCE_MARKER (start1);
2556 begp1 = XINT (start1);
2558 if (NILP (end1))
2559 endp1 = BUF_ZV (bp1);
2560 else
2562 CHECK_NUMBER_COERCE_MARKER (end1);
2563 endp1 = XINT (end1);
2566 if (begp1 > endp1)
2567 temp = begp1, begp1 = endp1, endp1 = temp;
2569 if (!(BUF_BEGV (bp1) <= begp1
2570 && begp1 <= endp1
2571 && endp1 <= BUF_ZV (bp1)))
2572 args_out_of_range (start1, end1);
2574 /* Likewise for second substring. */
2576 if (NILP (buffer2))
2577 bp2 = current_buffer;
2578 else
2580 Lisp_Object buf2;
2581 buf2 = Fget_buffer (buffer2);
2582 if (NILP (buf2))
2583 nsberror (buffer2);
2584 bp2 = XBUFFER (buf2);
2585 if (NILP (bp2->name))
2586 error ("Selecting deleted buffer");
2589 if (NILP (start2))
2590 begp2 = BUF_BEGV (bp2);
2591 else
2593 CHECK_NUMBER_COERCE_MARKER (start2);
2594 begp2 = XINT (start2);
2596 if (NILP (end2))
2597 endp2 = BUF_ZV (bp2);
2598 else
2600 CHECK_NUMBER_COERCE_MARKER (end2);
2601 endp2 = XINT (end2);
2604 if (begp2 > endp2)
2605 temp = begp2, begp2 = endp2, endp2 = temp;
2607 if (!(BUF_BEGV (bp2) <= begp2
2608 && begp2 <= endp2
2609 && endp2 <= BUF_ZV (bp2)))
2610 args_out_of_range (start2, end2);
2612 i1 = begp1;
2613 i2 = begp2;
2614 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2615 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2617 while (i1 < endp1 && i2 < endp2)
2619 /* When we find a mismatch, we must compare the
2620 characters, not just the bytes. */
2621 int c1, c2;
2623 QUIT;
2625 if (! NILP (bp1->enable_multibyte_characters))
2627 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2628 BUF_INC_POS (bp1, i1_byte);
2629 i1++;
2631 else
2633 c1 = BUF_FETCH_BYTE (bp1, i1);
2634 MAKE_CHAR_MULTIBYTE (c1);
2635 i1++;
2638 if (! NILP (bp2->enable_multibyte_characters))
2640 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2641 BUF_INC_POS (bp2, i2_byte);
2642 i2++;
2644 else
2646 c2 = BUF_FETCH_BYTE (bp2, i2);
2647 MAKE_CHAR_MULTIBYTE (c2);
2648 i2++;
2651 if (!NILP (trt))
2653 c1 = CHAR_TABLE_TRANSLATE (trt, c1);
2654 c2 = CHAR_TABLE_TRANSLATE (trt, c2);
2656 if (c1 < c2)
2657 return make_number (- 1 - chars);
2658 if (c1 > c2)
2659 return make_number (chars + 1);
2661 chars++;
2664 /* The strings match as far as they go.
2665 If one is shorter, that one is less. */
2666 if (chars < endp1 - begp1)
2667 return make_number (chars + 1);
2668 else if (chars < endp2 - begp2)
2669 return make_number (- chars - 1);
2671 /* Same length too => they are equal. */
2672 return make_number (0);
2675 static Lisp_Object
2676 subst_char_in_region_unwind (Lisp_Object arg)
2678 return current_buffer->undo_list = arg;
2681 static Lisp_Object
2682 subst_char_in_region_unwind_1 (Lisp_Object arg)
2684 return current_buffer->filename = arg;
2687 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2688 Ssubst_char_in_region, 4, 5, 0,
2689 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
2690 If optional arg NOUNDO is non-nil, don't record this change for undo
2691 and don't mark the buffer as really changed.
2692 Both characters must have the same length of multi-byte form. */)
2693 (Lisp_Object start, Lisp_Object end, Lisp_Object fromchar, Lisp_Object tochar, Lisp_Object noundo)
2695 register EMACS_INT pos, pos_byte, stop, i, len, end_byte;
2696 /* Keep track of the first change in the buffer:
2697 if 0 we haven't found it yet.
2698 if < 0 we've found it and we've run the before-change-function.
2699 if > 0 we've actually performed it and the value is its position. */
2700 EMACS_INT changed = 0;
2701 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2702 unsigned char *p;
2703 int count = SPECPDL_INDEX ();
2704 #define COMBINING_NO 0
2705 #define COMBINING_BEFORE 1
2706 #define COMBINING_AFTER 2
2707 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2708 int maybe_byte_combining = COMBINING_NO;
2709 EMACS_INT last_changed = 0;
2710 int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
2712 restart:
2714 validate_region (&start, &end);
2715 CHECK_NUMBER (fromchar);
2716 CHECK_NUMBER (tochar);
2718 if (multibyte_p)
2720 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2721 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
2722 error ("Characters in `subst-char-in-region' have different byte-lengths");
2723 if (!ASCII_BYTE_P (*tostr))
2725 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2726 complete multibyte character, it may be combined with the
2727 after bytes. If it is in the range 0xA0..0xFF, it may be
2728 combined with the before and after bytes. */
2729 if (!CHAR_HEAD_P (*tostr))
2730 maybe_byte_combining = COMBINING_BOTH;
2731 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2732 maybe_byte_combining = COMBINING_AFTER;
2735 else
2737 len = 1;
2738 fromstr[0] = XFASTINT (fromchar);
2739 tostr[0] = XFASTINT (tochar);
2742 pos = XINT (start);
2743 pos_byte = CHAR_TO_BYTE (pos);
2744 stop = CHAR_TO_BYTE (XINT (end));
2745 end_byte = stop;
2747 /* If we don't want undo, turn off putting stuff on the list.
2748 That's faster than getting rid of things,
2749 and it prevents even the entry for a first change.
2750 Also inhibit locking the file. */
2751 if (!changed && !NILP (noundo))
2753 record_unwind_protect (subst_char_in_region_unwind,
2754 current_buffer->undo_list);
2755 current_buffer->undo_list = Qt;
2756 /* Don't do file-locking. */
2757 record_unwind_protect (subst_char_in_region_unwind_1,
2758 current_buffer->filename);
2759 current_buffer->filename = Qnil;
2762 if (pos_byte < GPT_BYTE)
2763 stop = min (stop, GPT_BYTE);
2764 while (1)
2766 EMACS_INT pos_byte_next = pos_byte;
2768 if (pos_byte >= stop)
2770 if (pos_byte >= end_byte) break;
2771 stop = end_byte;
2773 p = BYTE_POS_ADDR (pos_byte);
2774 if (multibyte_p)
2775 INC_POS (pos_byte_next);
2776 else
2777 ++pos_byte_next;
2778 if (pos_byte_next - pos_byte == len
2779 && p[0] == fromstr[0]
2780 && (len == 1
2781 || (p[1] == fromstr[1]
2782 && (len == 2 || (p[2] == fromstr[2]
2783 && (len == 3 || p[3] == fromstr[3]))))))
2785 if (changed < 0)
2786 /* We've already seen this and run the before-change-function;
2787 this time we only need to record the actual position. */
2788 changed = pos;
2789 else if (!changed)
2791 changed = -1;
2792 modify_region (current_buffer, pos, XINT (end), 0);
2794 if (! NILP (noundo))
2796 if (MODIFF - 1 == SAVE_MODIFF)
2797 SAVE_MODIFF++;
2798 if (MODIFF - 1 == BUF_AUTOSAVE_MODIFF (current_buffer))
2799 BUF_AUTOSAVE_MODIFF (current_buffer)++;
2802 /* The before-change-function may have moved the gap
2803 or even modified the buffer so we should start over. */
2804 goto restart;
2807 /* Take care of the case where the new character
2808 combines with neighboring bytes. */
2809 if (maybe_byte_combining
2810 && (maybe_byte_combining == COMBINING_AFTER
2811 ? (pos_byte_next < Z_BYTE
2812 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2813 : ((pos_byte_next < Z_BYTE
2814 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2815 || (pos_byte > BEG_BYTE
2816 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2818 Lisp_Object tem, string;
2820 struct gcpro gcpro1;
2822 tem = current_buffer->undo_list;
2823 GCPRO1 (tem);
2825 /* Make a multibyte string containing this single character. */
2826 string = make_multibyte_string (tostr, 1, len);
2827 /* replace_range is less efficient, because it moves the gap,
2828 but it handles combining correctly. */
2829 replace_range (pos, pos + 1, string,
2830 0, 0, 1);
2831 pos_byte_next = CHAR_TO_BYTE (pos);
2832 if (pos_byte_next > pos_byte)
2833 /* Before combining happened. We should not increment
2834 POS. So, to cancel the later increment of POS,
2835 decrease it now. */
2836 pos--;
2837 else
2838 INC_POS (pos_byte_next);
2840 if (! NILP (noundo))
2841 current_buffer->undo_list = tem;
2843 UNGCPRO;
2845 else
2847 if (NILP (noundo))
2848 record_change (pos, 1);
2849 for (i = 0; i < len; i++) *p++ = tostr[i];
2851 last_changed = pos + 1;
2853 pos_byte = pos_byte_next;
2854 pos++;
2857 if (changed > 0)
2859 signal_after_change (changed,
2860 last_changed - changed, last_changed - changed);
2861 update_compositions (changed, last_changed, CHECK_ALL);
2864 unbind_to (count, Qnil);
2865 return Qnil;
2869 static Lisp_Object check_translation (EMACS_INT, EMACS_INT, EMACS_INT,
2870 Lisp_Object);
2872 /* Helper function for Ftranslate_region_internal.
2874 Check if a character sequence at POS (POS_BYTE) matches an element
2875 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
2876 element is found, return it. Otherwise return Qnil. */
2878 static Lisp_Object
2879 check_translation (EMACS_INT pos, EMACS_INT pos_byte, EMACS_INT end,
2880 Lisp_Object val)
2882 int buf_size = 16, buf_used = 0;
2883 int *buf = alloca (sizeof (int) * buf_size);
2885 for (; CONSP (val); val = XCDR (val))
2887 Lisp_Object elt;
2888 EMACS_INT len, i;
2890 elt = XCAR (val);
2891 if (! CONSP (elt))
2892 continue;
2893 elt = XCAR (elt);
2894 if (! VECTORP (elt))
2895 continue;
2896 len = ASIZE (elt);
2897 if (len <= end - pos)
2899 for (i = 0; i < len; i++)
2901 if (buf_used <= i)
2903 unsigned char *p = BYTE_POS_ADDR (pos_byte);
2904 int len1;
2906 if (buf_used == buf_size)
2908 int *newbuf;
2910 buf_size += 16;
2911 newbuf = alloca (sizeof (int) * buf_size);
2912 memcpy (newbuf, buf, sizeof (int) * buf_used);
2913 buf = newbuf;
2915 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len1);
2916 pos_byte += len1;
2918 if (XINT (AREF (elt, i)) != buf[i])
2919 break;
2921 if (i == len)
2922 return XCAR (val);
2925 return Qnil;
2929 DEFUN ("translate-region-internal", Ftranslate_region_internal,
2930 Stranslate_region_internal, 3, 3, 0,
2931 doc: /* Internal use only.
2932 From START to END, translate characters according to TABLE.
2933 TABLE is a string or a char-table; the Nth character in it is the
2934 mapping for the character with code N.
2935 It returns the number of characters changed. */)
2936 (Lisp_Object start, Lisp_Object end, register Lisp_Object table)
2938 register unsigned char *tt; /* Trans table. */
2939 register int nc; /* New character. */
2940 int cnt; /* Number of changes made. */
2941 EMACS_INT size; /* Size of translate table. */
2942 EMACS_INT pos, pos_byte, end_pos;
2943 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
2944 int string_multibyte;
2945 Lisp_Object val;
2947 validate_region (&start, &end);
2948 if (CHAR_TABLE_P (table))
2950 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
2951 error ("Not a translation table");
2952 size = MAX_CHAR;
2953 tt = NULL;
2955 else
2957 CHECK_STRING (table);
2959 if (! multibyte && (SCHARS (table) < SBYTES (table)))
2960 table = string_make_unibyte (table);
2961 string_multibyte = SCHARS (table) < SBYTES (table);
2962 size = SBYTES (table);
2963 tt = SDATA (table);
2966 pos = XINT (start);
2967 pos_byte = CHAR_TO_BYTE (pos);
2968 end_pos = XINT (end);
2969 modify_region (current_buffer, pos, end_pos, 0);
2971 cnt = 0;
2972 for (; pos < end_pos; )
2974 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
2975 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
2976 int len, str_len;
2977 int oc;
2978 Lisp_Object val;
2980 if (multibyte)
2981 oc = STRING_CHAR_AND_LENGTH (p, len);
2982 else
2983 oc = *p, len = 1;
2984 if (oc < size)
2986 if (tt)
2988 /* Reload as signal_after_change in last iteration may GC. */
2989 tt = SDATA (table);
2990 if (string_multibyte)
2992 str = tt + string_char_to_byte (table, oc);
2993 nc = STRING_CHAR_AND_LENGTH (str, str_len);
2995 else
2997 nc = tt[oc];
2998 if (! ASCII_BYTE_P (nc) && multibyte)
3000 str_len = BYTE8_STRING (nc, buf);
3001 str = buf;
3003 else
3005 str_len = 1;
3006 str = tt + oc;
3010 else
3012 EMACS_INT c;
3014 nc = oc;
3015 val = CHAR_TABLE_REF (table, oc);
3016 if (CHARACTERP (val)
3017 && (c = XINT (val), CHAR_VALID_P (c, 0)))
3019 nc = c;
3020 str_len = CHAR_STRING (nc, buf);
3021 str = buf;
3023 else if (VECTORP (val) || (CONSP (val)))
3025 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3026 where TO is TO-CHAR or [TO-CHAR ...]. */
3027 nc = -1;
3031 if (nc != oc && nc >= 0)
3033 /* Simple one char to one char translation. */
3034 if (len != str_len)
3036 Lisp_Object string;
3038 /* This is less efficient, because it moves the gap,
3039 but it should handle multibyte characters correctly. */
3040 string = make_multibyte_string (str, 1, str_len);
3041 replace_range (pos, pos + 1, string, 1, 0, 1);
3042 len = str_len;
3044 else
3046 record_change (pos, 1);
3047 while (str_len-- > 0)
3048 *p++ = *str++;
3049 signal_after_change (pos, 1, 1);
3050 update_compositions (pos, pos + 1, CHECK_BORDER);
3052 ++cnt;
3054 else if (nc < 0)
3056 Lisp_Object string;
3058 if (CONSP (val))
3060 val = check_translation (pos, pos_byte, end_pos, val);
3061 if (NILP (val))
3063 pos_byte += len;
3064 pos++;
3065 continue;
3067 /* VAL is ([FROM-CHAR ...] . TO). */
3068 len = ASIZE (XCAR (val));
3069 val = XCDR (val);
3071 else
3072 len = 1;
3074 if (VECTORP (val))
3076 string = Fconcat (1, &val);
3078 else
3080 string = Fmake_string (make_number (1), val);
3082 replace_range (pos, pos + len, string, 1, 0, 1);
3083 pos_byte += SBYTES (string);
3084 pos += SCHARS (string);
3085 cnt += SCHARS (string);
3086 end_pos += SCHARS (string) - len;
3087 continue;
3090 pos_byte += len;
3091 pos++;
3094 return make_number (cnt);
3097 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3098 doc: /* Delete the text between point and mark.
3100 When called from a program, expects two arguments,
3101 positions (integers or markers) specifying the stretch to be deleted. */)
3102 (Lisp_Object start, Lisp_Object end)
3104 validate_region (&start, &end);
3105 del_range (XINT (start), XINT (end));
3106 return Qnil;
3109 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3110 Sdelete_and_extract_region, 2, 2, 0,
3111 doc: /* Delete the text between START and END and return it. */)
3112 (Lisp_Object start, Lisp_Object end)
3114 validate_region (&start, &end);
3115 if (XINT (start) == XINT (end))
3116 return empty_unibyte_string;
3117 return del_range_1 (XINT (start), XINT (end), 1, 1);
3120 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3121 doc: /* Remove restrictions (narrowing) from current buffer.
3122 This allows the buffer's full text to be seen and edited. */)
3123 (void)
3125 if (BEG != BEGV || Z != ZV)
3126 current_buffer->clip_changed = 1;
3127 BEGV = BEG;
3128 BEGV_BYTE = BEG_BYTE;
3129 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3130 /* Changing the buffer bounds invalidates any recorded current column. */
3131 invalidate_current_column ();
3132 return Qnil;
3135 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3136 doc: /* Restrict editing in this buffer to the current region.
3137 The rest of the text becomes temporarily invisible and untouchable
3138 but is not deleted; if you save the buffer in a file, the invisible
3139 text is included in the file. \\[widen] makes all visible again.
3140 See also `save-restriction'.
3142 When calling from a program, pass two arguments; positions (integers
3143 or markers) bounding the text that should remain visible. */)
3144 (register Lisp_Object start, Lisp_Object end)
3146 CHECK_NUMBER_COERCE_MARKER (start);
3147 CHECK_NUMBER_COERCE_MARKER (end);
3149 if (XINT (start) > XINT (end))
3151 Lisp_Object tem;
3152 tem = start; start = end; end = tem;
3155 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3156 args_out_of_range (start, end);
3158 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3159 current_buffer->clip_changed = 1;
3161 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3162 SET_BUF_ZV (current_buffer, XFASTINT (end));
3163 if (PT < XFASTINT (start))
3164 SET_PT (XFASTINT (start));
3165 if (PT > XFASTINT (end))
3166 SET_PT (XFASTINT (end));
3167 /* Changing the buffer bounds invalidates any recorded current column. */
3168 invalidate_current_column ();
3169 return Qnil;
3172 Lisp_Object
3173 save_restriction_save (void)
3175 if (BEGV == BEG && ZV == Z)
3176 /* The common case that the buffer isn't narrowed.
3177 We return just the buffer object, which save_restriction_restore
3178 recognizes as meaning `no restriction'. */
3179 return Fcurrent_buffer ();
3180 else
3181 /* We have to save a restriction, so return a pair of markers, one
3182 for the beginning and one for the end. */
3184 Lisp_Object beg, end;
3186 beg = buildmark (BEGV, BEGV_BYTE);
3187 end = buildmark (ZV, ZV_BYTE);
3189 /* END must move forward if text is inserted at its exact location. */
3190 XMARKER(end)->insertion_type = 1;
3192 return Fcons (beg, end);
3196 Lisp_Object
3197 save_restriction_restore (Lisp_Object data)
3199 struct buffer *cur = NULL;
3200 struct buffer *buf = (CONSP (data)
3201 ? XMARKER (XCAR (data))->buffer
3202 : XBUFFER (data));
3204 if (buf && buf != current_buffer && !NILP (buf->pt_marker))
3205 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3206 is the case if it is or has an indirect buffer), then make
3207 sure it is current before we update BEGV, so
3208 set_buffer_internal takes care of managing those markers. */
3209 cur = current_buffer;
3210 set_buffer_internal (buf);
3213 if (CONSP (data))
3214 /* A pair of marks bounding a saved restriction. */
3216 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3217 struct Lisp_Marker *end = XMARKER (XCDR (data));
3218 eassert (buf == end->buffer);
3220 if (buf /* Verify marker still points to a buffer. */
3221 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3222 /* The restriction has changed from the saved one, so restore
3223 the saved restriction. */
3225 EMACS_INT pt = BUF_PT (buf);
3227 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3228 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3230 if (pt < beg->charpos || pt > end->charpos)
3231 /* The point is outside the new visible range, move it inside. */
3232 SET_BUF_PT_BOTH (buf,
3233 clip_to_bounds (beg->charpos, pt, end->charpos),
3234 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3235 end->bytepos));
3237 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3240 else
3241 /* A buffer, which means that there was no old restriction. */
3243 if (buf /* Verify marker still points to a buffer. */
3244 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3245 /* The buffer has been narrowed, get rid of the narrowing. */
3247 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3248 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3250 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3254 if (cur)
3255 set_buffer_internal (cur);
3257 return Qnil;
3260 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3261 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3262 The buffer's restrictions make parts of the beginning and end invisible.
3263 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3264 This special form, `save-restriction', saves the current buffer's restrictions
3265 when it is entered, and restores them when it is exited.
3266 So any `narrow-to-region' within BODY lasts only until the end of the form.
3267 The old restrictions settings are restored
3268 even in case of abnormal exit (throw or error).
3270 The value returned is the value of the last form in BODY.
3272 Note: if you are using both `save-excursion' and `save-restriction',
3273 use `save-excursion' outermost:
3274 (save-excursion (save-restriction ...))
3276 usage: (save-restriction &rest BODY) */)
3277 (Lisp_Object body)
3279 register Lisp_Object val;
3280 int count = SPECPDL_INDEX ();
3282 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3283 val = Fprogn (body);
3284 return unbind_to (count, val);
3287 /* Buffer for the most recent text displayed by Fmessage_box. */
3288 static char *message_text;
3290 /* Allocated length of that buffer. */
3291 static int message_length;
3293 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3294 doc: /* Display a message at the bottom of the screen.
3295 The message also goes into the `*Messages*' buffer.
3296 \(In keyboard macros, that's all it does.)
3297 Return the message.
3299 The first argument is a format control string, and the rest are data
3300 to be formatted under control of the string. See `format' for details.
3302 Note: Use (message "%s" VALUE) to print the value of expressions and
3303 variables to avoid accidentally interpreting `%' as format specifiers.
3305 If the first argument is nil or the empty string, the function clears
3306 any existing message; this lets the minibuffer contents show. See
3307 also `current-message'.
3309 usage: (message FORMAT-STRING &rest ARGS) */)
3310 (int nargs, Lisp_Object *args)
3312 if (NILP (args[0])
3313 || (STRINGP (args[0])
3314 && SBYTES (args[0]) == 0))
3316 message (0);
3317 return args[0];
3319 else
3321 register Lisp_Object val;
3322 val = Fformat (nargs, args);
3323 message3 (val, SBYTES (val), STRING_MULTIBYTE (val));
3324 return val;
3328 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3329 doc: /* Display a message, in a dialog box if possible.
3330 If a dialog box is not available, use the echo area.
3331 The first argument is a format control string, and the rest are data
3332 to be formatted under control of the string. See `format' for details.
3334 If the first argument is nil or the empty string, clear any existing
3335 message; let the minibuffer contents show.
3337 usage: (message-box FORMAT-STRING &rest ARGS) */)
3338 (int nargs, Lisp_Object *args)
3340 if (NILP (args[0]))
3342 message (0);
3343 return Qnil;
3345 else
3347 register Lisp_Object val;
3348 val = Fformat (nargs, args);
3349 #ifdef HAVE_MENUS
3350 /* The MS-DOS frames support popup menus even though they are
3351 not FRAME_WINDOW_P. */
3352 if (FRAME_WINDOW_P (XFRAME (selected_frame))
3353 || FRAME_MSDOS_P (XFRAME (selected_frame)))
3355 Lisp_Object pane, menu, obj;
3356 struct gcpro gcpro1;
3357 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
3358 GCPRO1 (pane);
3359 menu = Fcons (val, pane);
3360 obj = Fx_popup_dialog (Qt, menu, Qt);
3361 UNGCPRO;
3362 return val;
3364 #endif /* HAVE_MENUS */
3365 /* Copy the data so that it won't move when we GC. */
3366 if (! message_text)
3368 message_text = (char *)xmalloc (80);
3369 message_length = 80;
3371 if (SBYTES (val) > message_length)
3373 message_length = SBYTES (val);
3374 message_text = (char *)xrealloc (message_text, message_length);
3376 memcpy (message_text, SDATA (val), SBYTES (val));
3377 message2 (message_text, SBYTES (val),
3378 STRING_MULTIBYTE (val));
3379 return val;
3383 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3384 doc: /* Display a message in a dialog box or in the echo area.
3385 If this command was invoked with the mouse, use a dialog box if
3386 `use-dialog-box' is non-nil.
3387 Otherwise, use the echo area.
3388 The first argument is a format control string, and the rest are data
3389 to be formatted under control of the string. See `format' for details.
3391 If the first argument is nil or the empty string, clear any existing
3392 message; let the minibuffer contents show.
3394 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3395 (int nargs, Lisp_Object *args)
3397 #ifdef HAVE_MENUS
3398 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3399 && use_dialog_box)
3400 return Fmessage_box (nargs, args);
3401 #endif
3402 return Fmessage (nargs, args);
3405 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3406 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3407 (void)
3409 return current_message ();
3413 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3414 doc: /* Return a copy of STRING with text properties added.
3415 First argument is the string to copy.
3416 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3417 properties to add to the result.
3418 usage: (propertize STRING &rest PROPERTIES) */)
3419 (int nargs, Lisp_Object *args)
3421 Lisp_Object properties, string;
3422 struct gcpro gcpro1, gcpro2;
3423 int i;
3425 /* Number of args must be odd. */
3426 if ((nargs & 1) == 0 || nargs < 1)
3427 error ("Wrong number of arguments");
3429 properties = string = Qnil;
3430 GCPRO2 (properties, string);
3432 /* First argument must be a string. */
3433 CHECK_STRING (args[0]);
3434 string = Fcopy_sequence (args[0]);
3436 for (i = 1; i < nargs; i += 2)
3437 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3439 Fadd_text_properties (make_number (0),
3440 make_number (SCHARS (string)),
3441 properties, string);
3442 RETURN_UNGCPRO (string);
3446 /* Number of bytes that STRING will occupy when put into the result.
3447 MULTIBYTE is nonzero if the result should be multibyte. */
3449 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3450 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
3451 ? count_size_as_multibyte (SDATA (STRING), SBYTES (STRING)) \
3452 : SBYTES (STRING))
3454 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3455 doc: /* Format a string out of a format-string and arguments.
3456 The first argument is a format control string.
3457 The other arguments are substituted into it to make the result, a string.
3459 The format control string may contain %-sequences meaning to substitute
3460 the next available argument:
3462 %s means print a string argument. Actually, prints any object, with `princ'.
3463 %d means print as number in decimal (%o octal, %x hex).
3464 %X is like %x, but uses upper case.
3465 %e means print a number in exponential notation.
3466 %f means print a number in decimal-point notation.
3467 %g means print a number in exponential notation
3468 or decimal-point notation, whichever uses fewer characters.
3469 %c means print a number as a single character.
3470 %S means print any object as an s-expression (using `prin1').
3472 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3473 Use %% to put a single % into the output.
3475 A %-sequence may contain optional flag, width, and precision
3476 specifiers, as follows:
3478 %<flags><width><precision>character
3480 where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3482 The + flag character inserts a + before any positive number, while a
3483 space inserts a space before any positive number; these flags only
3484 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3485 The # flag means to use an alternate display form for %o, %x, %X, %e,
3486 %f, and %g sequences. The - and 0 flags affect the width specifier,
3487 as described below.
3489 The width specifier supplies a lower limit for the length of the
3490 printed representation. The padding, if any, normally goes on the
3491 left, but it goes on the right if the - flag is present. The padding
3492 character is normally a space, but it is 0 if the 0 flag is present.
3493 The - flag takes precedence over the 0 flag.
3495 For %e, %f, and %g sequences, the number after the "." in the
3496 precision specifier says how many decimal places to show; if zero, the
3497 decimal point itself is omitted. For %s and %S, the precision
3498 specifier truncates the string to the given width.
3500 usage: (format STRING &rest OBJECTS) */)
3501 (int nargs, register Lisp_Object *args)
3503 register int n; /* The number of the next arg to substitute */
3504 register EMACS_INT total; /* An estimate of the final length */
3505 char *buf, *p;
3506 register unsigned char *format, *end, *format_start;
3507 int nchars;
3508 /* Nonzero if the output should be a multibyte string,
3509 which is true if any of the inputs is one. */
3510 int multibyte = 0;
3511 /* When we make a multibyte string, we must pay attention to the
3512 byte combining problem, i.e., a byte may be combined with a
3513 multibyte character of the previous string. This flag tells if we
3514 must consider such a situation or not. */
3515 int maybe_combine_byte;
3516 unsigned char *this_format;
3517 /* Precision for each spec, or -1, a flag value meaning no precision
3518 was given in that spec. Element 0, corresonding to the format
3519 string itself, will not be used. Element NARGS, corresponding to
3520 no argument, *will* be assigned to in the case that a `%' and `.'
3521 occur after the final format specifier. */
3522 int *precision = (int *) (alloca ((nargs + 1) * sizeof (int)));
3523 int longest_format;
3524 Lisp_Object val;
3525 int arg_intervals = 0;
3526 USE_SAFE_ALLOCA;
3528 /* discarded[I] is 1 if byte I of the format
3529 string was not copied into the output.
3530 It is 2 if byte I was not the first byte of its character. */
3531 char *discarded = 0;
3533 /* Each element records, for one argument,
3534 the start and end bytepos in the output string,
3535 and whether the argument is a string with intervals.
3536 info[0] is unused. Unused elements have -1 for start. */
3537 struct info
3539 int start, end, intervals;
3540 } *info = 0;
3542 /* It should not be necessary to GCPRO ARGS, because
3543 the caller in the interpreter should take care of that. */
3545 /* Try to determine whether the result should be multibyte.
3546 This is not always right; sometimes the result needs to be multibyte
3547 because of an object that we will pass through prin1,
3548 and in that case, we won't know it here. */
3549 for (n = 0; n < nargs; n++)
3551 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3552 multibyte = 1;
3553 /* Piggyback on this loop to initialize precision[N]. */
3554 precision[n] = -1;
3556 precision[nargs] = -1;
3558 CHECK_STRING (args[0]);
3559 /* We may have to change "%S" to "%s". */
3560 args[0] = Fcopy_sequence (args[0]);
3562 /* GC should never happen here, so abort if it does. */
3563 abort_on_gc++;
3565 /* If we start out planning a unibyte result,
3566 then discover it has to be multibyte, we jump back to retry.
3567 That can only happen from the first large while loop below. */
3568 retry:
3570 format = SDATA (args[0]);
3571 format_start = format;
3572 end = format + SBYTES (args[0]);
3573 longest_format = 0;
3575 /* Make room in result for all the non-%-codes in the control string. */
3576 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]) + 1;
3578 /* Allocate the info and discarded tables. */
3580 int nbytes = (nargs+1) * sizeof *info;
3581 int i;
3582 if (!info)
3583 info = (struct info *) alloca (nbytes);
3584 memset (info, 0, nbytes);
3585 for (i = 0; i <= nargs; i++)
3586 info[i].start = -1;
3587 if (!discarded)
3588 SAFE_ALLOCA (discarded, char *, SBYTES (args[0]));
3589 memset (discarded, 0, SBYTES (args[0]));
3592 /* Add to TOTAL enough space to hold the converted arguments. */
3594 n = 0;
3595 while (format != end)
3596 if (*format++ == '%')
3598 EMACS_INT thissize = 0;
3599 EMACS_INT actual_width = 0;
3600 unsigned char *this_format_start = format - 1;
3601 int field_width = 0;
3603 /* General format specifications look like
3605 '%' [flags] [field-width] [precision] format
3607 where
3609 flags ::= [-+ #0]+
3610 field-width ::= [0-9]+
3611 precision ::= '.' [0-9]*
3613 If a field-width is specified, it specifies to which width
3614 the output should be padded with blanks, if the output
3615 string is shorter than field-width.
3617 If precision is specified, it specifies the number of
3618 digits to print after the '.' for floats, or the max.
3619 number of chars to print from a string. */
3621 while (format != end
3622 && (*format == '-' || *format == '0' || *format == '#'
3623 || * format == ' ' || *format == '+'))
3624 ++format;
3626 if (*format >= '0' && *format <= '9')
3628 for (field_width = 0; *format >= '0' && *format <= '9'; ++format)
3629 field_width = 10 * field_width + *format - '0';
3632 /* N is not incremented for another few lines below, so refer to
3633 element N+1 (which might be precision[NARGS]). */
3634 if (*format == '.')
3636 ++format;
3637 for (precision[n+1] = 0; *format >= '0' && *format <= '9'; ++format)
3638 precision[n+1] = 10 * precision[n+1] + *format - '0';
3641 /* Extra +1 for 'l' that we may need to insert into the
3642 format. */
3643 if (format - this_format_start + 2 > longest_format)
3644 longest_format = format - this_format_start + 2;
3646 if (format == end)
3647 error ("Format string ends in middle of format specifier");
3648 if (*format == '%')
3649 format++;
3650 else if (++n >= nargs)
3651 error ("Not enough arguments for format string");
3652 else if (*format == 'S')
3654 /* For `S', prin1 the argument and then treat like a string. */
3655 register Lisp_Object tem;
3656 tem = Fprin1_to_string (args[n], Qnil);
3657 if (STRING_MULTIBYTE (tem) && ! multibyte)
3659 multibyte = 1;
3660 goto retry;
3662 args[n] = tem;
3663 /* If we restart the loop, we should not come here again
3664 because args[n] is now a string and calling
3665 Fprin1_to_string on it produces superflous double
3666 quotes. So, change "%S" to "%s" now. */
3667 *format = 's';
3668 goto string;
3670 else if (SYMBOLP (args[n]))
3672 args[n] = SYMBOL_NAME (args[n]);
3673 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3675 multibyte = 1;
3676 goto retry;
3678 goto string;
3680 else if (STRINGP (args[n]))
3682 string:
3683 if (*format != 's' && *format != 'S')
3684 error ("Format specifier doesn't match argument type");
3685 /* In the case (PRECISION[N] > 0), THISSIZE may not need
3686 to be as large as is calculated here. Easy check for
3687 the case PRECISION = 0. */
3688 thissize = precision[n] ? CONVERTED_BYTE_SIZE (multibyte, args[n]) : 0;
3689 /* The precision also constrains how much of the argument
3690 string will finally appear (Bug#5710). */
3691 actual_width = lisp_string_width (args[n], -1, NULL, NULL);
3692 if (precision[n] != -1)
3693 actual_width = min (actual_width, precision[n]);
3695 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3696 else if (INTEGERP (args[n]) && *format != 's')
3698 /* The following loop assumes the Lisp type indicates
3699 the proper way to pass the argument.
3700 So make sure we have a flonum if the argument should
3701 be a double. */
3702 if (*format == 'e' || *format == 'f' || *format == 'g')
3703 args[n] = Ffloat (args[n]);
3704 else
3705 if (*format != 'd' && *format != 'o' && *format != 'x'
3706 && *format != 'i' && *format != 'X' && *format != 'c')
3707 error ("Invalid format operation %%%c", *format);
3709 thissize = 30 + (precision[n] > 0 ? precision[n] : 0);
3710 if (*format == 'c')
3712 if (! ASCII_CHAR_P (XINT (args[n]))
3713 /* Note: No one can remeber why we have to treat
3714 the character 0 as a multibyte character here.
3715 But, until it causes a real problem, let's
3716 don't change it. */
3717 || XINT (args[n]) == 0)
3719 if (! multibyte)
3721 multibyte = 1;
3722 goto retry;
3724 args[n] = Fchar_to_string (args[n]);
3725 thissize = SBYTES (args[n]);
3727 else if (! ASCII_BYTE_P (XINT (args[n])) && multibyte)
3729 args[n]
3730 = Fchar_to_string (Funibyte_char_to_multibyte (args[n]));
3731 thissize = SBYTES (args[n]);
3735 else if (FLOATP (args[n]) && *format != 's')
3737 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3739 if (*format != 'd' && *format != 'o' && *format != 'x'
3740 && *format != 'i' && *format != 'X' && *format != 'c')
3741 error ("Invalid format operation %%%c", *format);
3742 /* This fails unnecessarily if args[n] is bigger than
3743 most-positive-fixnum but smaller than MAXINT.
3744 These cases are important because we sometimes use floats
3745 to represent such integer values (typically such values
3746 come from UIDs or PIDs). */
3747 /* args[n] = Ftruncate (args[n], Qnil); */
3750 /* Note that we're using sprintf to print floats,
3751 so we have to take into account what that function
3752 prints. */
3753 /* Filter out flag value of -1. */
3754 thissize = (MAX_10_EXP + 100
3755 + (precision[n] > 0 ? precision[n] : 0));
3757 else
3759 /* Anything but a string, convert to a string using princ. */
3760 register Lisp_Object tem;
3761 tem = Fprin1_to_string (args[n], Qt);
3762 if (STRING_MULTIBYTE (tem) && ! multibyte)
3764 multibyte = 1;
3765 goto retry;
3767 args[n] = tem;
3768 goto string;
3771 thissize += max (0, field_width - actual_width);
3772 total += thissize + 4;
3775 abort_on_gc--;
3777 /* Now we can no longer jump to retry.
3778 TOTAL and LONGEST_FORMAT are known for certain. */
3780 this_format = (unsigned char *) alloca (longest_format + 1);
3782 /* Allocate the space for the result.
3783 Note that TOTAL is an overestimate. */
3784 SAFE_ALLOCA (buf, char *, total);
3786 p = buf;
3787 nchars = 0;
3788 n = 0;
3790 /* Scan the format and store result in BUF. */
3791 format = SDATA (args[0]);
3792 format_start = format;
3793 end = format + SBYTES (args[0]);
3794 maybe_combine_byte = 0;
3795 while (format != end)
3797 if (*format == '%')
3799 int minlen;
3800 int negative = 0;
3801 unsigned char *this_format_start = format;
3803 discarded[format - format_start] = 1;
3804 format++;
3806 while (strchr ("-+0# ", *format))
3808 if (*format == '-')
3810 negative = 1;
3812 discarded[format - format_start] = 1;
3813 ++format;
3816 minlen = atoi (format);
3818 while ((*format >= '0' && *format <= '9') || *format == '.')
3820 discarded[format - format_start] = 1;
3821 format++;
3824 if (*format++ == '%')
3826 *p++ = '%';
3827 nchars++;
3828 continue;
3831 ++n;
3833 discarded[format - format_start - 1] = 1;
3834 info[n].start = nchars;
3836 if (STRINGP (args[n]))
3838 /* handle case (precision[n] >= 0) */
3840 int width, padding;
3841 EMACS_INT nbytes, start, end;
3842 EMACS_INT nchars_string;
3844 /* lisp_string_width ignores a precision of 0, but GNU
3845 libc functions print 0 characters when the precision
3846 is 0. Imitate libc behavior here. Changing
3847 lisp_string_width is the right thing, and will be
3848 done, but meanwhile we work with it. */
3850 if (precision[n] == 0)
3851 width = nchars_string = nbytes = 0;
3852 else if (precision[n] > 0)
3853 width = lisp_string_width (args[n], precision[n],
3854 &nchars_string, &nbytes);
3855 else
3856 { /* no precision spec given for this argument */
3857 width = lisp_string_width (args[n], -1, NULL, NULL);
3858 nbytes = SBYTES (args[n]);
3859 nchars_string = SCHARS (args[n]);
3862 /* If spec requires it, pad on right with spaces. */
3863 padding = minlen - width;
3864 if (! negative)
3865 while (padding-- > 0)
3867 *p++ = ' ';
3868 ++nchars;
3871 info[n].start = start = nchars;
3872 nchars += nchars_string;
3873 end = nchars;
3875 if (p > buf
3876 && multibyte
3877 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3878 && STRING_MULTIBYTE (args[n])
3879 && !CHAR_HEAD_P (SREF (args[n], 0)))
3880 maybe_combine_byte = 1;
3882 p += copy_text (SDATA (args[n]), p,
3883 nbytes,
3884 STRING_MULTIBYTE (args[n]), multibyte);
3886 info[n].end = nchars;
3888 if (negative)
3889 while (padding-- > 0)
3891 *p++ = ' ';
3892 nchars++;
3895 /* If this argument has text properties, record where
3896 in the result string it appears. */
3897 if (STRING_INTERVALS (args[n]))
3898 info[n].intervals = arg_intervals = 1;
3900 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3902 int this_nchars;
3904 memcpy (this_format, this_format_start,
3905 format - this_format_start);
3906 this_format[format - this_format_start] = 0;
3908 if (format[-1] == 'e' || format[-1] == 'f' || format[-1] == 'g')
3909 sprintf (p, this_format, XFLOAT_DATA (args[n]));
3910 else
3912 if (sizeof (EMACS_INT) > sizeof (int)
3913 && format[-1] != 'c')
3915 /* Insert 'l' before format spec. */
3916 this_format[format - this_format_start]
3917 = this_format[format - this_format_start - 1];
3918 this_format[format - this_format_start - 1] = 'l';
3919 this_format[format - this_format_start + 1] = 0;
3922 if (INTEGERP (args[n]))
3924 if (format[-1] == 'c')
3925 sprintf (p, this_format, (int) XINT (args[n]));
3926 else if (format[-1] == 'd')
3927 sprintf (p, this_format, XINT (args[n]));
3928 /* Don't sign-extend for octal or hex printing. */
3929 else
3930 sprintf (p, this_format, XUINT (args[n]));
3932 else if (format[-1] == 'c')
3933 sprintf (p, this_format, (int) XFLOAT_DATA (args[n]));
3934 else if (format[-1] == 'd')
3935 /* Maybe we should use "%1.0f" instead so it also works
3936 for values larger than MAXINT. */
3937 sprintf (p, this_format, (EMACS_INT) XFLOAT_DATA (args[n]));
3938 else
3939 /* Don't sign-extend for octal or hex printing. */
3940 sprintf (p, this_format, (EMACS_UINT) XFLOAT_DATA (args[n]));
3943 if (p > buf
3944 && multibyte
3945 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3946 && !CHAR_HEAD_P (*((unsigned char *) p)))
3947 maybe_combine_byte = 1;
3948 this_nchars = strlen (p);
3949 if (multibyte)
3950 p += str_to_multibyte (p, buf + total - 1 - p, this_nchars);
3951 else
3952 p += this_nchars;
3953 nchars += this_nchars;
3954 info[n].end = nchars;
3958 else if (STRING_MULTIBYTE (args[0]))
3960 /* Copy a whole multibyte character. */
3961 if (p > buf
3962 && multibyte
3963 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3964 && !CHAR_HEAD_P (*format))
3965 maybe_combine_byte = 1;
3966 *p++ = *format++;
3967 while (! CHAR_HEAD_P (*format))
3969 discarded[format - format_start] = 2;
3970 *p++ = *format++;
3972 nchars++;
3974 else if (multibyte)
3976 /* Convert a single-byte character to multibyte. */
3977 int len = copy_text (format, p, 1, 0, 1);
3979 p += len;
3980 format++;
3981 nchars++;
3983 else
3984 *p++ = *format++, nchars++;
3987 if (p > buf + total)
3988 abort ();
3990 if (maybe_combine_byte)
3991 nchars = multibyte_chars_in_text (buf, p - buf);
3992 val = make_specified_string (buf, nchars, p - buf, multibyte);
3994 /* If we allocated BUF with malloc, free it too. */
3995 SAFE_FREE ();
3997 /* If the format string has text properties, or any of the string
3998 arguments has text properties, set up text properties of the
3999 result string. */
4001 if (STRING_INTERVALS (args[0]) || arg_intervals)
4003 Lisp_Object len, new_len, props;
4004 struct gcpro gcpro1;
4006 /* Add text properties from the format string. */
4007 len = make_number (SCHARS (args[0]));
4008 props = text_property_list (args[0], make_number (0), len, Qnil);
4009 GCPRO1 (props);
4011 if (CONSP (props))
4013 EMACS_INT bytepos = 0, position = 0, translated = 0;
4014 int argn = 1;
4015 Lisp_Object list;
4017 /* Adjust the bounds of each text property
4018 to the proper start and end in the output string. */
4020 /* Put the positions in PROPS in increasing order, so that
4021 we can do (effectively) one scan through the position
4022 space of the format string. */
4023 props = Fnreverse (props);
4025 /* BYTEPOS is the byte position in the format string,
4026 POSITION is the untranslated char position in it,
4027 TRANSLATED is the translated char position in BUF,
4028 and ARGN is the number of the next arg we will come to. */
4029 for (list = props; CONSP (list); list = XCDR (list))
4031 Lisp_Object item;
4032 EMACS_INT pos;
4034 item = XCAR (list);
4036 /* First adjust the property start position. */
4037 pos = XINT (XCAR (item));
4039 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4040 up to this position. */
4041 for (; position < pos; bytepos++)
4043 if (! discarded[bytepos])
4044 position++, translated++;
4045 else if (discarded[bytepos] == 1)
4047 position++;
4048 if (translated == info[argn].start)
4050 translated += info[argn].end - info[argn].start;
4051 argn++;
4056 XSETCAR (item, make_number (translated));
4058 /* Likewise adjust the property end position. */
4059 pos = XINT (XCAR (XCDR (item)));
4061 for (; position < pos; bytepos++)
4063 if (! discarded[bytepos])
4064 position++, translated++;
4065 else if (discarded[bytepos] == 1)
4067 position++;
4068 if (translated == info[argn].start)
4070 translated += info[argn].end - info[argn].start;
4071 argn++;
4076 XSETCAR (XCDR (item), make_number (translated));
4079 add_text_properties_from_list (val, props, make_number (0));
4082 /* Add text properties from arguments. */
4083 if (arg_intervals)
4084 for (n = 1; n < nargs; ++n)
4085 if (info[n].intervals)
4087 len = make_number (SCHARS (args[n]));
4088 new_len = make_number (info[n].end - info[n].start);
4089 props = text_property_list (args[n], make_number (0), len, Qnil);
4090 props = extend_property_ranges (props, new_len);
4091 /* If successive arguments have properties, be sure that
4092 the value of `composition' property be the copy. */
4093 if (n > 1 && info[n - 1].end)
4094 make_composition_value_copy (props);
4095 add_text_properties_from_list (val, props,
4096 make_number (info[n].start));
4099 UNGCPRO;
4102 return val;
4105 Lisp_Object
4106 format2 (const char *string1, Lisp_Object arg0, Lisp_Object arg1)
4108 Lisp_Object args[3];
4109 args[0] = build_string (string1);
4110 args[1] = arg0;
4111 args[2] = arg1;
4112 return Fformat (3, args);
4115 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4116 doc: /* Return t if two characters match, optionally ignoring case.
4117 Both arguments must be characters (i.e. integers).
4118 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4119 (register Lisp_Object c1, Lisp_Object c2)
4121 int i1, i2;
4122 /* Check they're chars, not just integers, otherwise we could get array
4123 bounds violations in DOWNCASE. */
4124 CHECK_CHARACTER (c1);
4125 CHECK_CHARACTER (c2);
4127 if (XINT (c1) == XINT (c2))
4128 return Qt;
4129 if (NILP (current_buffer->case_fold_search))
4130 return Qnil;
4132 /* Do these in separate statements,
4133 then compare the variables.
4134 because of the way DOWNCASE uses temp variables. */
4135 i1 = XFASTINT (c1);
4136 if (NILP (current_buffer->enable_multibyte_characters)
4137 && ! ASCII_CHAR_P (i1))
4139 MAKE_CHAR_MULTIBYTE (i1);
4141 i2 = XFASTINT (c2);
4142 if (NILP (current_buffer->enable_multibyte_characters)
4143 && ! ASCII_CHAR_P (i2))
4145 MAKE_CHAR_MULTIBYTE (i2);
4147 i1 = DOWNCASE (i1);
4148 i2 = DOWNCASE (i2);
4149 return (i1 == i2 ? Qt : Qnil);
4152 /* Transpose the markers in two regions of the current buffer, and
4153 adjust the ones between them if necessary (i.e.: if the regions
4154 differ in size).
4156 START1, END1 are the character positions of the first region.
4157 START1_BYTE, END1_BYTE are the byte positions.
4158 START2, END2 are the character positions of the second region.
4159 START2_BYTE, END2_BYTE are the byte positions.
4161 Traverses the entire marker list of the buffer to do so, adding an
4162 appropriate amount to some, subtracting from some, and leaving the
4163 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4165 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4167 static void
4168 transpose_markers (EMACS_INT start1, EMACS_INT end1,
4169 EMACS_INT start2, EMACS_INT end2,
4170 EMACS_INT start1_byte, EMACS_INT end1_byte,
4171 EMACS_INT start2_byte, EMACS_INT end2_byte)
4173 register EMACS_INT amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4174 register struct Lisp_Marker *marker;
4176 /* Update point as if it were a marker. */
4177 if (PT < start1)
4179 else if (PT < end1)
4180 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4181 PT_BYTE + (end2_byte - end1_byte));
4182 else if (PT < start2)
4183 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4184 (PT_BYTE + (end2_byte - start2_byte)
4185 - (end1_byte - start1_byte)));
4186 else if (PT < end2)
4187 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4188 PT_BYTE - (start2_byte - start1_byte));
4190 /* We used to adjust the endpoints here to account for the gap, but that
4191 isn't good enough. Even if we assume the caller has tried to move the
4192 gap out of our way, it might still be at start1 exactly, for example;
4193 and that places it `inside' the interval, for our purposes. The amount
4194 of adjustment is nontrivial if there's a `denormalized' marker whose
4195 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4196 the dirty work to Fmarker_position, below. */
4198 /* The difference between the region's lengths */
4199 diff = (end2 - start2) - (end1 - start1);
4200 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4202 /* For shifting each marker in a region by the length of the other
4203 region plus the distance between the regions. */
4204 amt1 = (end2 - start2) + (start2 - end1);
4205 amt2 = (end1 - start1) + (start2 - end1);
4206 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4207 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4209 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4211 mpos = marker->bytepos;
4212 if (mpos >= start1_byte && mpos < end2_byte)
4214 if (mpos < end1_byte)
4215 mpos += amt1_byte;
4216 else if (mpos < start2_byte)
4217 mpos += diff_byte;
4218 else
4219 mpos -= amt2_byte;
4220 marker->bytepos = mpos;
4222 mpos = marker->charpos;
4223 if (mpos >= start1 && mpos < end2)
4225 if (mpos < end1)
4226 mpos += amt1;
4227 else if (mpos < start2)
4228 mpos += diff;
4229 else
4230 mpos -= amt2;
4232 marker->charpos = mpos;
4236 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4237 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4238 The regions should not be overlapping, because the size of the buffer is
4239 never changed in a transposition.
4241 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4242 any markers that happen to be located in the regions.
4244 Transposing beyond buffer boundaries is an error. */)
4245 (Lisp_Object startr1, Lisp_Object endr1, Lisp_Object startr2, Lisp_Object endr2, Lisp_Object leave_markers)
4247 register EMACS_INT start1, end1, start2, end2;
4248 EMACS_INT start1_byte, start2_byte, len1_byte, len2_byte;
4249 EMACS_INT gap, len1, len_mid, len2;
4250 unsigned char *start1_addr, *start2_addr, *temp;
4252 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4253 Lisp_Object buf;
4255 XSETBUFFER (buf, current_buffer);
4256 cur_intv = BUF_INTERVALS (current_buffer);
4258 validate_region (&startr1, &endr1);
4259 validate_region (&startr2, &endr2);
4261 start1 = XFASTINT (startr1);
4262 end1 = XFASTINT (endr1);
4263 start2 = XFASTINT (startr2);
4264 end2 = XFASTINT (endr2);
4265 gap = GPT;
4267 /* Swap the regions if they're reversed. */
4268 if (start2 < end1)
4270 register EMACS_INT glumph = start1;
4271 start1 = start2;
4272 start2 = glumph;
4273 glumph = end1;
4274 end1 = end2;
4275 end2 = glumph;
4278 len1 = end1 - start1;
4279 len2 = end2 - start2;
4281 if (start2 < end1)
4282 error ("Transposed regions overlap");
4283 else if (start1 == end1 || start2 == end2)
4284 error ("Transposed region has length 0");
4286 /* The possibilities are:
4287 1. Adjacent (contiguous) regions, or separate but equal regions
4288 (no, really equal, in this case!), or
4289 2. Separate regions of unequal size.
4291 The worst case is usually No. 2. It means that (aside from
4292 potential need for getting the gap out of the way), there also
4293 needs to be a shifting of the text between the two regions. So
4294 if they are spread far apart, we are that much slower... sigh. */
4296 /* It must be pointed out that the really studly thing to do would
4297 be not to move the gap at all, but to leave it in place and work
4298 around it if necessary. This would be extremely efficient,
4299 especially considering that people are likely to do
4300 transpositions near where they are working interactively, which
4301 is exactly where the gap would be found. However, such code
4302 would be much harder to write and to read. So, if you are
4303 reading this comment and are feeling squirrely, by all means have
4304 a go! I just didn't feel like doing it, so I will simply move
4305 the gap the minimum distance to get it out of the way, and then
4306 deal with an unbroken array. */
4308 /* Make sure the gap won't interfere, by moving it out of the text
4309 we will operate on. */
4310 if (start1 < gap && gap < end2)
4312 if (gap - start1 < end2 - gap)
4313 move_gap (start1);
4314 else
4315 move_gap (end2);
4318 start1_byte = CHAR_TO_BYTE (start1);
4319 start2_byte = CHAR_TO_BYTE (start2);
4320 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4321 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
4323 #ifdef BYTE_COMBINING_DEBUG
4324 if (end1 == start2)
4326 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4327 len2_byte, start1, start1_byte)
4328 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4329 len1_byte, end2, start2_byte + len2_byte)
4330 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4331 len1_byte, end2, start2_byte + len2_byte))
4332 abort ();
4334 else
4336 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4337 len2_byte, start1, start1_byte)
4338 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4339 len1_byte, start2, start2_byte)
4340 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4341 len2_byte, end1, start1_byte + len1_byte)
4342 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4343 len1_byte, end2, start2_byte + len2_byte))
4344 abort ();
4346 #endif
4348 /* Hmmm... how about checking to see if the gap is large
4349 enough to use as the temporary storage? That would avoid an
4350 allocation... interesting. Later, don't fool with it now. */
4352 /* Working without memmove, for portability (sigh), so must be
4353 careful of overlapping subsections of the array... */
4355 if (end1 == start2) /* adjacent regions */
4357 modify_region (current_buffer, start1, end2, 0);
4358 record_change (start1, len1 + len2);
4360 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4361 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4362 /* Don't use Fset_text_properties: that can cause GC, which can
4363 clobber objects stored in the tmp_intervals. */
4364 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4365 if (!NULL_INTERVAL_P (tmp_interval3))
4366 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4368 /* First region smaller than second. */
4369 if (len1_byte < len2_byte)
4371 USE_SAFE_ALLOCA;
4373 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4375 /* Don't precompute these addresses. We have to compute them
4376 at the last minute, because the relocating allocator might
4377 have moved the buffer around during the xmalloc. */
4378 start1_addr = BYTE_POS_ADDR (start1_byte);
4379 start2_addr = BYTE_POS_ADDR (start2_byte);
4381 memcpy (temp, start2_addr, len2_byte);
4382 memcpy (start1_addr + len2_byte, start1_addr, len1_byte);
4383 memcpy (start1_addr, temp, len2_byte);
4384 SAFE_FREE ();
4386 else
4387 /* First region not smaller than second. */
4389 USE_SAFE_ALLOCA;
4391 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4392 start1_addr = BYTE_POS_ADDR (start1_byte);
4393 start2_addr = BYTE_POS_ADDR (start2_byte);
4394 memcpy (temp, start1_addr, len1_byte);
4395 memcpy (start1_addr, start2_addr, len2_byte);
4396 memcpy (start1_addr + len2_byte, temp, len1_byte);
4397 SAFE_FREE ();
4399 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4400 len1, current_buffer, 0);
4401 graft_intervals_into_buffer (tmp_interval2, start1,
4402 len2, current_buffer, 0);
4403 update_compositions (start1, start1 + len2, CHECK_BORDER);
4404 update_compositions (start1 + len2, end2, CHECK_TAIL);
4406 /* Non-adjacent regions, because end1 != start2, bleagh... */
4407 else
4409 len_mid = start2_byte - (start1_byte + len1_byte);
4411 if (len1_byte == len2_byte)
4412 /* Regions are same size, though, how nice. */
4414 USE_SAFE_ALLOCA;
4416 modify_region (current_buffer, start1, end1, 0);
4417 modify_region (current_buffer, start2, end2, 0);
4418 record_change (start1, len1);
4419 record_change (start2, len2);
4420 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4421 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4423 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4424 if (!NULL_INTERVAL_P (tmp_interval3))
4425 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4427 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4428 if (!NULL_INTERVAL_P (tmp_interval3))
4429 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
4431 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4432 start1_addr = BYTE_POS_ADDR (start1_byte);
4433 start2_addr = BYTE_POS_ADDR (start2_byte);
4434 memcpy (temp, start1_addr, len1_byte);
4435 memcpy (start1_addr, start2_addr, len2_byte);
4436 memcpy (start2_addr, temp, len1_byte);
4437 SAFE_FREE ();
4439 graft_intervals_into_buffer (tmp_interval1, start2,
4440 len1, current_buffer, 0);
4441 graft_intervals_into_buffer (tmp_interval2, start1,
4442 len2, current_buffer, 0);
4445 else if (len1_byte < len2_byte) /* Second region larger than first */
4446 /* Non-adjacent & unequal size, area between must also be shifted. */
4448 USE_SAFE_ALLOCA;
4450 modify_region (current_buffer, start1, end2, 0);
4451 record_change (start1, (end2 - start1));
4452 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4453 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4454 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4456 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4457 if (!NULL_INTERVAL_P (tmp_interval3))
4458 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4460 /* holds region 2 */
4461 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4462 start1_addr = BYTE_POS_ADDR (start1_byte);
4463 start2_addr = BYTE_POS_ADDR (start2_byte);
4464 memcpy (temp, start2_addr, len2_byte);
4465 memcpy (start1_addr + len_mid + len2_byte, start1_addr, len1_byte);
4466 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4467 memcpy (start1_addr, temp, len2_byte);
4468 SAFE_FREE ();
4470 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4471 len1, current_buffer, 0);
4472 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4473 len_mid, current_buffer, 0);
4474 graft_intervals_into_buffer (tmp_interval2, start1,
4475 len2, current_buffer, 0);
4477 else
4478 /* Second region smaller than first. */
4480 USE_SAFE_ALLOCA;
4482 record_change (start1, (end2 - start1));
4483 modify_region (current_buffer, start1, end2, 0);
4485 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4486 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4487 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4489 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4490 if (!NULL_INTERVAL_P (tmp_interval3))
4491 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4493 /* holds region 1 */
4494 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4495 start1_addr = BYTE_POS_ADDR (start1_byte);
4496 start2_addr = BYTE_POS_ADDR (start2_byte);
4497 memcpy (temp, start1_addr, len1_byte);
4498 memcpy (start1_addr, start2_addr, len2_byte);
4499 memcpy (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4500 memcpy (start1_addr + len2_byte + len_mid, temp, len1_byte);
4501 SAFE_FREE ();
4503 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4504 len1, current_buffer, 0);
4505 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4506 len_mid, current_buffer, 0);
4507 graft_intervals_into_buffer (tmp_interval2, start1,
4508 len2, current_buffer, 0);
4511 update_compositions (start1, start1 + len2, CHECK_BORDER);
4512 update_compositions (end2 - len1, end2, CHECK_BORDER);
4515 /* When doing multiple transpositions, it might be nice
4516 to optimize this. Perhaps the markers in any one buffer
4517 should be organized in some sorted data tree. */
4518 if (NILP (leave_markers))
4520 transpose_markers (start1, end1, start2, end2,
4521 start1_byte, start1_byte + len1_byte,
4522 start2_byte, start2_byte + len2_byte);
4523 fix_start_end_in_overlays (start1, end2);
4526 signal_after_change (start1, end2 - start1, end2 - start1);
4527 return Qnil;
4531 void
4532 syms_of_editfns (void)
4534 environbuf = 0;
4535 initial_tz = 0;
4537 Qbuffer_access_fontify_functions
4538 = intern_c_string ("buffer-access-fontify-functions");
4539 staticpro (&Qbuffer_access_fontify_functions);
4541 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion,
4542 doc: /* Non-nil means text motion commands don't notice fields. */);
4543 Vinhibit_field_text_motion = Qnil;
4545 DEFVAR_LISP ("buffer-access-fontify-functions",
4546 Vbuffer_access_fontify_functions,
4547 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4548 Each function is called with two arguments which specify the range
4549 of the buffer being accessed. */);
4550 Vbuffer_access_fontify_functions = Qnil;
4553 Lisp_Object obuf;
4554 obuf = Fcurrent_buffer ();
4555 /* Do this here, because init_buffer_once is too early--it won't work. */
4556 Fset_buffer (Vprin1_to_string_buffer);
4557 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4558 Fset (Fmake_local_variable (intern_c_string ("buffer-access-fontify-functions")),
4559 Qnil);
4560 Fset_buffer (obuf);
4563 DEFVAR_LISP ("buffer-access-fontified-property",
4564 Vbuffer_access_fontified_property,
4565 doc: /* Property which (if non-nil) indicates text has been fontified.
4566 `buffer-substring' need not call the `buffer-access-fontify-functions'
4567 functions if all the text being accessed has this property. */);
4568 Vbuffer_access_fontified_property = Qnil;
4570 DEFVAR_LISP ("system-name", Vsystem_name,
4571 doc: /* The host name of the machine Emacs is running on. */);
4573 DEFVAR_LISP ("user-full-name", Vuser_full_name,
4574 doc: /* The full name of the user logged in. */);
4576 DEFVAR_LISP ("user-login-name", Vuser_login_name,
4577 doc: /* The user's name, taken from environment variables if possible. */);
4579 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name,
4580 doc: /* The user's name, based upon the real uid only. */);
4582 DEFVAR_LISP ("operating-system-release", Voperating_system_release,
4583 doc: /* The release of the operating system Emacs is running on. */);
4585 defsubr (&Spropertize);
4586 defsubr (&Schar_equal);
4587 defsubr (&Sgoto_char);
4588 defsubr (&Sstring_to_char);
4589 defsubr (&Schar_to_string);
4590 defsubr (&Sbyte_to_string);
4591 defsubr (&Sbuffer_substring);
4592 defsubr (&Sbuffer_substring_no_properties);
4593 defsubr (&Sbuffer_string);
4595 defsubr (&Spoint_marker);
4596 defsubr (&Smark_marker);
4597 defsubr (&Spoint);
4598 defsubr (&Sregion_beginning);
4599 defsubr (&Sregion_end);
4601 staticpro (&Qfield);
4602 Qfield = intern_c_string ("field");
4603 staticpro (&Qboundary);
4604 Qboundary = intern_c_string ("boundary");
4605 defsubr (&Sfield_beginning);
4606 defsubr (&Sfield_end);
4607 defsubr (&Sfield_string);
4608 defsubr (&Sfield_string_no_properties);
4609 defsubr (&Sdelete_field);
4610 defsubr (&Sconstrain_to_field);
4612 defsubr (&Sline_beginning_position);
4613 defsubr (&Sline_end_position);
4615 /* defsubr (&Smark); */
4616 /* defsubr (&Sset_mark); */
4617 defsubr (&Ssave_excursion);
4618 defsubr (&Ssave_current_buffer);
4620 defsubr (&Sbufsize);
4621 defsubr (&Spoint_max);
4622 defsubr (&Spoint_min);
4623 defsubr (&Spoint_min_marker);
4624 defsubr (&Spoint_max_marker);
4625 defsubr (&Sgap_position);
4626 defsubr (&Sgap_size);
4627 defsubr (&Sposition_bytes);
4628 defsubr (&Sbyte_to_position);
4630 defsubr (&Sbobp);
4631 defsubr (&Seobp);
4632 defsubr (&Sbolp);
4633 defsubr (&Seolp);
4634 defsubr (&Sfollowing_char);
4635 defsubr (&Sprevious_char);
4636 defsubr (&Schar_after);
4637 defsubr (&Schar_before);
4638 defsubr (&Sinsert);
4639 defsubr (&Sinsert_before_markers);
4640 defsubr (&Sinsert_and_inherit);
4641 defsubr (&Sinsert_and_inherit_before_markers);
4642 defsubr (&Sinsert_char);
4643 defsubr (&Sinsert_byte);
4645 defsubr (&Suser_login_name);
4646 defsubr (&Suser_real_login_name);
4647 defsubr (&Suser_uid);
4648 defsubr (&Suser_real_uid);
4649 defsubr (&Suser_full_name);
4650 defsubr (&Semacs_pid);
4651 defsubr (&Scurrent_time);
4652 defsubr (&Sget_internal_run_time);
4653 defsubr (&Sformat_time_string);
4654 defsubr (&Sfloat_time);
4655 defsubr (&Sdecode_time);
4656 defsubr (&Sencode_time);
4657 defsubr (&Scurrent_time_string);
4658 defsubr (&Scurrent_time_zone);
4659 defsubr (&Sset_time_zone_rule);
4660 defsubr (&Ssystem_name);
4661 defsubr (&Smessage);
4662 defsubr (&Smessage_box);
4663 defsubr (&Smessage_or_box);
4664 defsubr (&Scurrent_message);
4665 defsubr (&Sformat);
4667 defsubr (&Sinsert_buffer_substring);
4668 defsubr (&Scompare_buffer_substrings);
4669 defsubr (&Ssubst_char_in_region);
4670 defsubr (&Stranslate_region_internal);
4671 defsubr (&Sdelete_region);
4672 defsubr (&Sdelete_and_extract_region);
4673 defsubr (&Swiden);
4674 defsubr (&Snarrow_to_region);
4675 defsubr (&Ssave_restriction);
4676 defsubr (&Stranspose_regions);