(font_prop_validate): Make nil a valid value.
[emacs.git] / src / editfns.c
blob95ad2f1aaafbaf0d6b2d675db35aa7bca6864973
1 /* Lisp functions pertaining to editing.
2 Copyright (C) 1985, 1986, 1987, 1989, 1993, 1994, 1995, 1996,
3 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <sys/types.h>
24 #include <stdio.h>
26 #ifdef HAVE_PWD_H
27 #include <pwd.h>
28 #endif
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
34 #ifdef HAVE_SYS_UTSNAME_H
35 #include <sys/utsname.h>
36 #endif
38 #include "lisp.h"
40 /* systime.h includes <sys/time.h> which, on some systems, is required
41 for <sys/resource.h>; thus systime.h must be included before
42 <sys/resource.h> */
43 #include "systime.h"
45 #if defined HAVE_SYS_RESOURCE_H
46 #include <sys/resource.h>
47 #endif
49 #include <ctype.h>
51 #include "intervals.h"
52 #include "buffer.h"
53 #include "character.h"
54 #include "coding.h"
55 #include "frame.h"
56 #include "window.h"
57 #include "blockinput.h"
59 #ifdef STDC_HEADERS
60 #include <float.h>
61 #define MAX_10_EXP DBL_MAX_10_EXP
62 #else
63 #define MAX_10_EXP 310
64 #endif
66 #ifndef NULL
67 #define NULL 0
68 #endif
70 #ifndef USE_CRT_DLL
71 extern char **environ;
72 #endif
74 #define TM_YEAR_BASE 1900
76 /* Nonzero if TM_YEAR is a struct tm's tm_year value that causes
77 asctime to have well-defined behavior. */
78 #ifndef TM_YEAR_IN_ASCTIME_RANGE
79 # define TM_YEAR_IN_ASCTIME_RANGE(tm_year) \
80 (1000 - TM_YEAR_BASE <= (tm_year) && (tm_year) <= 9999 - TM_YEAR_BASE)
81 #endif
83 extern size_t emacs_strftimeu P_ ((char *, size_t, const char *,
84 const struct tm *, int));
86 #ifdef WINDOWSNT
87 extern Lisp_Object w32_get_internal_run_time ();
88 #endif
90 static int tm_diff P_ ((struct tm *, struct tm *));
91 static void find_field P_ ((Lisp_Object, Lisp_Object, Lisp_Object, int *, Lisp_Object, int *));
92 static void update_buffer_properties P_ ((int, int));
93 static Lisp_Object region_limit P_ ((int));
94 int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
95 static size_t emacs_memftimeu P_ ((char *, size_t, const char *,
96 size_t, const struct tm *, int));
97 static void general_insert_function P_ ((void (*) (const unsigned char *, int),
98 void (*) (Lisp_Object, int, int, int,
99 int, int),
100 int, int, Lisp_Object *));
101 static Lisp_Object subst_char_in_region_unwind P_ ((Lisp_Object));
102 static Lisp_Object subst_char_in_region_unwind_1 P_ ((Lisp_Object));
103 static void transpose_markers P_ ((int, int, int, int, int, int, int, int));
105 #ifdef HAVE_INDEX
106 extern char *index P_ ((const char *, int));
107 #endif
109 Lisp_Object Vbuffer_access_fontify_functions;
110 Lisp_Object Qbuffer_access_fontify_functions;
111 Lisp_Object Vbuffer_access_fontified_property;
113 Lisp_Object Fuser_full_name P_ ((Lisp_Object));
115 /* Non-nil means don't stop at field boundary in text motion commands. */
117 Lisp_Object Vinhibit_field_text_motion;
119 /* Some static data, and a function to initialize it for each run */
121 Lisp_Object Vsystem_name;
122 Lisp_Object Vuser_real_login_name; /* login name of current user ID */
123 Lisp_Object Vuser_full_name; /* full name of current user */
124 Lisp_Object Vuser_login_name; /* user name from LOGNAME or USER */
125 Lisp_Object Voperating_system_release; /* Operating System Release */
127 /* Symbol for the text property used to mark fields. */
129 Lisp_Object Qfield;
131 /* A special value for Qfield properties. */
133 Lisp_Object Qboundary;
136 void
137 init_editfns ()
139 char *user_name;
140 register unsigned char *p;
141 struct passwd *pw; /* password entry for the current user */
142 Lisp_Object tem;
144 /* Set up system_name even when dumping. */
145 init_system_name ();
147 #ifndef CANNOT_DUMP
148 /* Don't bother with this on initial start when just dumping out */
149 if (!initialized)
150 return;
151 #endif /* not CANNOT_DUMP */
153 pw = (struct passwd *) getpwuid (getuid ());
154 #ifdef MSDOS
155 /* We let the real user name default to "root" because that's quite
156 accurate on MSDOG and because it lets Emacs find the init file.
157 (The DVX libraries override the Djgpp libraries here.) */
158 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
159 #else
160 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
161 #endif
163 /* Get the effective user name, by consulting environment variables,
164 or the effective uid if those are unset. */
165 user_name = (char *) getenv ("LOGNAME");
166 if (!user_name)
167 #ifdef WINDOWSNT
168 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
169 #else /* WINDOWSNT */
170 user_name = (char *) getenv ("USER");
171 #endif /* WINDOWSNT */
172 if (!user_name)
174 pw = (struct passwd *) getpwuid (geteuid ());
175 user_name = (char *) (pw ? pw->pw_name : "unknown");
177 Vuser_login_name = build_string (user_name);
179 /* If the user name claimed in the environment vars differs from
180 the real uid, use the claimed name to find the full name. */
181 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
182 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
183 : Vuser_login_name);
185 p = (unsigned char *) getenv ("NAME");
186 if (p)
187 Vuser_full_name = build_string (p);
188 else if (NILP (Vuser_full_name))
189 Vuser_full_name = build_string ("unknown");
191 #ifdef HAVE_SYS_UTSNAME_H
193 struct utsname uts;
194 uname (&uts);
195 Voperating_system_release = build_string (uts.release);
197 #else
198 Voperating_system_release = Qnil;
199 #endif
202 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
203 doc: /* Convert arg CHAR to a string containing that character.
204 usage: (char-to-string CHAR) */)
205 (character)
206 Lisp_Object character;
208 int len;
209 unsigned char str[MAX_MULTIBYTE_LENGTH];
211 CHECK_CHARACTER (character);
213 len = CHAR_STRING (XFASTINT (character), str);
214 return make_string_from_bytes (str, 1, len);
217 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
218 doc: /* Convert arg STRING to a character, the first character of that string.
219 A multibyte character is handled correctly. */)
220 (string)
221 register Lisp_Object string;
223 register Lisp_Object val;
224 CHECK_STRING (string);
225 if (SCHARS (string))
227 if (STRING_MULTIBYTE (string))
228 XSETFASTINT (val, STRING_CHAR (SDATA (string), SBYTES (string)));
229 else
230 XSETFASTINT (val, SREF (string, 0));
232 else
233 XSETFASTINT (val, 0);
234 return val;
237 static Lisp_Object
238 buildmark (charpos, bytepos)
239 int charpos, bytepos;
241 register Lisp_Object mark;
242 mark = Fmake_marker ();
243 set_marker_both (mark, Qnil, charpos, bytepos);
244 return mark;
247 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
248 doc: /* Return value of point, as an integer.
249 Beginning of buffer is position (point-min). */)
252 Lisp_Object temp;
253 XSETFASTINT (temp, PT);
254 return temp;
257 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
258 doc: /* Return value of point, as a marker object. */)
261 return buildmark (PT, PT_BYTE);
265 clip_to_bounds (lower, num, upper)
266 int lower, num, upper;
268 if (num < lower)
269 return lower;
270 else if (num > upper)
271 return upper;
272 else
273 return num;
276 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
277 doc: /* Set point to POSITION, a number or marker.
278 Beginning of buffer is position (point-min), end is (point-max).
280 The return value is POSITION. */)
281 (position)
282 register Lisp_Object position;
284 int pos;
286 if (MARKERP (position)
287 && current_buffer == XMARKER (position)->buffer)
289 pos = marker_position (position);
290 if (pos < BEGV)
291 SET_PT_BOTH (BEGV, BEGV_BYTE);
292 else if (pos > ZV)
293 SET_PT_BOTH (ZV, ZV_BYTE);
294 else
295 SET_PT_BOTH (pos, marker_byte_position (position));
297 return position;
300 CHECK_NUMBER_COERCE_MARKER (position);
302 pos = clip_to_bounds (BEGV, XINT (position), ZV);
303 SET_PT (pos);
304 return position;
308 /* Return the start or end position of the region.
309 BEGINNINGP non-zero means return the start.
310 If there is no region active, signal an error. */
312 static Lisp_Object
313 region_limit (beginningp)
314 int beginningp;
316 extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
317 Lisp_Object m;
319 if (!NILP (Vtransient_mark_mode)
320 && NILP (Vmark_even_if_inactive)
321 && NILP (current_buffer->mark_active))
322 xsignal0 (Qmark_inactive);
324 m = Fmarker_position (current_buffer->mark);
325 if (NILP (m))
326 error ("The mark is not set now, so there is no region");
328 if ((PT < XFASTINT (m)) == (beginningp != 0))
329 m = make_number (PT);
330 return m;
333 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
334 doc: /* Return position of beginning of region, as an integer. */)
337 return region_limit (1);
340 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
341 doc: /* Return position of end of region, as an integer. */)
344 return region_limit (0);
347 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
348 doc: /* Return this buffer's mark, as a marker object.
349 Watch out! Moving this marker changes the mark position.
350 If you set the marker not to point anywhere, the buffer will have no mark. */)
353 return current_buffer->mark;
357 /* Find all the overlays in the current buffer that touch position POS.
358 Return the number found, and store them in a vector in VEC
359 of length LEN. */
361 static int
362 overlays_around (pos, vec, len)
363 int pos;
364 Lisp_Object *vec;
365 int len;
367 Lisp_Object overlay, start, end;
368 struct Lisp_Overlay *tail;
369 int startpos, endpos;
370 int idx = 0;
372 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
374 XSETMISC (overlay, tail);
376 end = OVERLAY_END (overlay);
377 endpos = OVERLAY_POSITION (end);
378 if (endpos < pos)
379 break;
380 start = OVERLAY_START (overlay);
381 startpos = OVERLAY_POSITION (start);
382 if (startpos <= pos)
384 if (idx < len)
385 vec[idx] = overlay;
386 /* Keep counting overlays even if we can't return them all. */
387 idx++;
391 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
393 XSETMISC (overlay, tail);
395 start = OVERLAY_START (overlay);
396 startpos = OVERLAY_POSITION (start);
397 if (pos < startpos)
398 break;
399 end = OVERLAY_END (overlay);
400 endpos = OVERLAY_POSITION (end);
401 if (pos <= endpos)
403 if (idx < len)
404 vec[idx] = overlay;
405 idx++;
409 return idx;
412 /* Return the value of property PROP, in OBJECT at POSITION.
413 It's the value of PROP that a char inserted at POSITION would get.
414 OBJECT is optional and defaults to the current buffer.
415 If OBJECT is a buffer, then overlay properties are considered as well as
416 text properties.
417 If OBJECT is a window, then that window's buffer is used, but
418 window-specific overlays are considered only if they are associated
419 with OBJECT. */
420 Lisp_Object
421 get_pos_property (position, prop, object)
422 Lisp_Object position, object;
423 register Lisp_Object prop;
425 CHECK_NUMBER_COERCE_MARKER (position);
427 if (NILP (object))
428 XSETBUFFER (object, current_buffer);
429 else if (WINDOWP (object))
430 object = XWINDOW (object)->buffer;
432 if (!BUFFERP (object))
433 /* pos-property only makes sense in buffers right now, since strings
434 have no overlays and no notion of insertion for which stickiness
435 could be obeyed. */
436 return Fget_text_property (position, prop, object);
437 else
439 int posn = XINT (position);
440 int noverlays;
441 Lisp_Object *overlay_vec, tem;
442 struct buffer *obuf = current_buffer;
444 set_buffer_temp (XBUFFER (object));
446 /* First try with room for 40 overlays. */
447 noverlays = 40;
448 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
449 noverlays = overlays_around (posn, overlay_vec, noverlays);
451 /* If there are more than 40,
452 make enough space for all, and try again. */
453 if (noverlays > 40)
455 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
456 noverlays = overlays_around (posn, overlay_vec, noverlays);
458 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
460 set_buffer_temp (obuf);
462 /* Now check the overlays in order of decreasing priority. */
463 while (--noverlays >= 0)
465 Lisp_Object ol = overlay_vec[noverlays];
466 tem = Foverlay_get (ol, prop);
467 if (!NILP (tem))
469 /* Check the overlay is indeed active at point. */
470 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
471 if ((OVERLAY_POSITION (start) == posn
472 && XMARKER (start)->insertion_type == 1)
473 || (OVERLAY_POSITION (finish) == posn
474 && XMARKER (finish)->insertion_type == 0))
475 ; /* The overlay will not cover a char inserted at point. */
476 else
478 return tem;
483 { /* Now check the text properties. */
484 int stickiness = text_property_stickiness (prop, position, object);
485 if (stickiness > 0)
486 return Fget_text_property (position, prop, object);
487 else if (stickiness < 0
488 && XINT (position) > BUF_BEGV (XBUFFER (object)))
489 return Fget_text_property (make_number (XINT (position) - 1),
490 prop, object);
491 else
492 return Qnil;
497 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
498 the value of point is used instead. If BEG or END is null,
499 means don't store the beginning or end of the field.
501 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
502 results; they do not effect boundary behavior.
504 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
505 position of a field, then the beginning of the previous field is
506 returned instead of the beginning of POS's field (since the end of a
507 field is actually also the beginning of the next input field, this
508 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
509 true case, if two fields are separated by a field with the special
510 value `boundary', and POS lies within it, then the two separated
511 fields are considered to be adjacent, and POS between them, when
512 finding the beginning and ending of the "merged" field.
514 Either BEG or END may be 0, in which case the corresponding value
515 is not stored. */
517 static void
518 find_field (pos, merge_at_boundary, beg_limit, beg, end_limit, end)
519 Lisp_Object pos;
520 Lisp_Object merge_at_boundary;
521 Lisp_Object beg_limit, end_limit;
522 int *beg, *end;
524 /* Fields right before and after the point. */
525 Lisp_Object before_field, after_field;
526 /* 1 if POS counts as the start of a field. */
527 int at_field_start = 0;
528 /* 1 if POS counts as the end of a field. */
529 int at_field_end = 0;
531 if (NILP (pos))
532 XSETFASTINT (pos, PT);
533 else
534 CHECK_NUMBER_COERCE_MARKER (pos);
536 after_field
537 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
538 before_field
539 = (XFASTINT (pos) > BEGV
540 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
541 Qfield, Qnil, NULL)
542 /* Using nil here would be a more obvious choice, but it would
543 fail when the buffer starts with a non-sticky field. */
544 : after_field);
546 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
547 and POS is at beginning of a field, which can also be interpreted
548 as the end of the previous field. Note that the case where if
549 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
550 more natural one; then we avoid treating the beginning of a field
551 specially. */
552 if (NILP (merge_at_boundary))
554 Lisp_Object field = get_pos_property (pos, Qfield, Qnil);
555 if (!EQ (field, after_field))
556 at_field_end = 1;
557 if (!EQ (field, before_field))
558 at_field_start = 1;
559 if (NILP (field) && at_field_start && at_field_end)
560 /* If an inserted char would have a nil field while the surrounding
561 text is non-nil, we're probably not looking at a
562 zero-length field, but instead at a non-nil field that's
563 not intended for editing (such as comint's prompts). */
564 at_field_end = at_field_start = 0;
567 /* Note about special `boundary' fields:
569 Consider the case where the point (`.') is between the fields `x' and `y':
571 xxxx.yyyy
573 In this situation, if merge_at_boundary is true, we consider the
574 `x' and `y' fields as forming one big merged field, and so the end
575 of the field is the end of `y'.
577 However, if `x' and `y' are separated by a special `boundary' field
578 (a field with a `field' char-property of 'boundary), then we ignore
579 this special field when merging adjacent fields. Here's the same
580 situation, but with a `boundary' field between the `x' and `y' fields:
582 xxx.BBBByyyy
584 Here, if point is at the end of `x', the beginning of `y', or
585 anywhere in-between (within the `boundary' field), we merge all
586 three fields and consider the beginning as being the beginning of
587 the `x' field, and the end as being the end of the `y' field. */
589 if (beg)
591 if (at_field_start)
592 /* POS is at the edge of a field, and we should consider it as
593 the beginning of the following field. */
594 *beg = XFASTINT (pos);
595 else
596 /* Find the previous field boundary. */
598 Lisp_Object p = pos;
599 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
600 /* Skip a `boundary' field. */
601 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
602 beg_limit);
604 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
605 beg_limit);
606 *beg = NILP (p) ? BEGV : XFASTINT (p);
610 if (end)
612 if (at_field_end)
613 /* POS is at the edge of a field, and we should consider it as
614 the end of the previous field. */
615 *end = XFASTINT (pos);
616 else
617 /* Find the next field boundary. */
619 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
620 /* Skip a `boundary' field. */
621 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
622 end_limit);
624 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
625 end_limit);
626 *end = NILP (pos) ? ZV : XFASTINT (pos);
632 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
633 doc: /* Delete the field surrounding POS.
634 A field is a region of text with the same `field' property.
635 If POS is nil, the value of point is used for POS. */)
636 (pos)
637 Lisp_Object pos;
639 int beg, end;
640 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
641 if (beg != end)
642 del_range (beg, end);
643 return Qnil;
646 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
647 doc: /* Return the contents of the field surrounding POS as a string.
648 A field is a region of text with the same `field' property.
649 If POS is nil, the value of point is used for POS. */)
650 (pos)
651 Lisp_Object pos;
653 int beg, end;
654 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
655 return make_buffer_string (beg, end, 1);
658 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
659 doc: /* Return the contents of the field around POS, without text properties.
660 A field is a region of text with the same `field' property.
661 If POS is nil, the value of point is used for POS. */)
662 (pos)
663 Lisp_Object pos;
665 int beg, end;
666 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
667 return make_buffer_string (beg, end, 0);
670 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
671 doc: /* Return the beginning of the field surrounding POS.
672 A field is a region of text with the same `field' property.
673 If POS is nil, the value of point is used for POS.
674 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
675 field, then the beginning of the *previous* field is returned.
676 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
677 is before LIMIT, then LIMIT will be returned instead. */)
678 (pos, escape_from_edge, limit)
679 Lisp_Object pos, escape_from_edge, limit;
681 int beg;
682 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
683 return make_number (beg);
686 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
687 doc: /* Return the end of the field surrounding POS.
688 A field is a region of text with the same `field' property.
689 If POS is nil, the value of point is used for POS.
690 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
691 then the end of the *following* field is returned.
692 If LIMIT is non-nil, it is a buffer position; if the end of the field
693 is after LIMIT, then LIMIT will be returned instead. */)
694 (pos, escape_from_edge, limit)
695 Lisp_Object pos, escape_from_edge, limit;
697 int end;
698 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
699 return make_number (end);
702 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
703 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
705 A field is a region of text with the same `field' property.
706 If NEW-POS is nil, then the current point is used instead, and set to the
707 constrained position if that is different.
709 If OLD-POS is at the boundary of two fields, then the allowable
710 positions for NEW-POS depends on the value of the optional argument
711 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
712 constrained to the field that has the same `field' char-property
713 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
714 is non-nil, NEW-POS is constrained to the union of the two adjacent
715 fields. Additionally, if two fields are separated by another field with
716 the special value `boundary', then any point within this special field is
717 also considered to be `on the boundary'.
719 If the optional argument ONLY-IN-LINE is non-nil and constraining
720 NEW-POS would move it to a different line, NEW-POS is returned
721 unconstrained. This useful for commands that move by line, like
722 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
723 only in the case where they can still move to the right line.
725 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
726 a non-nil property of that name, then any field boundaries are ignored.
728 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
729 (new_pos, old_pos, escape_from_edge, only_in_line, inhibit_capture_property)
730 Lisp_Object new_pos, old_pos;
731 Lisp_Object escape_from_edge, only_in_line, inhibit_capture_property;
733 /* If non-zero, then the original point, before re-positioning. */
734 int orig_point = 0;
735 int fwd;
736 Lisp_Object prev_old, prev_new;
738 if (NILP (new_pos))
739 /* Use the current point, and afterwards, set it. */
741 orig_point = PT;
742 XSETFASTINT (new_pos, PT);
745 CHECK_NUMBER_COERCE_MARKER (new_pos);
746 CHECK_NUMBER_COERCE_MARKER (old_pos);
748 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
750 prev_old = make_number (XFASTINT (old_pos) - 1);
751 prev_new = make_number (XFASTINT (new_pos) - 1);
753 if (NILP (Vinhibit_field_text_motion)
754 && !EQ (new_pos, old_pos)
755 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
756 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
757 /* To recognize field boundaries, we must also look at the
758 previous positions; we could use `get_pos_property'
759 instead, but in itself that would fail inside non-sticky
760 fields (like comint prompts). */
761 || (XFASTINT (new_pos) > BEGV
762 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
763 || (XFASTINT (old_pos) > BEGV
764 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
765 && (NILP (inhibit_capture_property)
766 /* Field boundaries are again a problem; but now we must
767 decide the case exactly, so we need to call
768 `get_pos_property' as well. */
769 || (NILP (get_pos_property (old_pos, inhibit_capture_property, Qnil))
770 && (XFASTINT (old_pos) <= BEGV
771 || NILP (Fget_char_property (old_pos, inhibit_capture_property, Qnil))
772 || NILP (Fget_char_property (prev_old, inhibit_capture_property, Qnil))))))
773 /* It is possible that NEW_POS is not within the same field as
774 OLD_POS; try to move NEW_POS so that it is. */
776 int shortage;
777 Lisp_Object field_bound;
779 if (fwd)
780 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
781 else
782 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
784 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
785 other side of NEW_POS, which would mean that NEW_POS is
786 already acceptable, and it's not necessary to constrain it
787 to FIELD_BOUND. */
788 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
789 /* NEW_POS should be constrained, but only if either
790 ONLY_IN_LINE is nil (in which case any constraint is OK),
791 or NEW_POS and FIELD_BOUND are on the same line (in which
792 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
793 && (NILP (only_in_line)
794 /* This is the ONLY_IN_LINE case, check that NEW_POS and
795 FIELD_BOUND are on the same line by seeing whether
796 there's an intervening newline or not. */
797 || (scan_buffer ('\n',
798 XFASTINT (new_pos), XFASTINT (field_bound),
799 fwd ? -1 : 1, &shortage, 1),
800 shortage != 0)))
801 /* Constrain NEW_POS to FIELD_BOUND. */
802 new_pos = field_bound;
804 if (orig_point && XFASTINT (new_pos) != orig_point)
805 /* The NEW_POS argument was originally nil, so automatically set PT. */
806 SET_PT (XFASTINT (new_pos));
809 return new_pos;
813 DEFUN ("line-beginning-position",
814 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
815 doc: /* Return the character position of the first character on the current line.
816 With argument N not nil or 1, move forward N - 1 lines first.
817 If scan reaches end of buffer, return that position.
819 This function constrains the returned position to the current field
820 unless that would be on a different line than the original,
821 unconstrained result. If N is nil or 1, and a front-sticky field
822 starts at point, the scan stops as soon as it starts. To ignore field
823 boundaries bind `inhibit-field-text-motion' to t.
825 This function does not move point. */)
827 Lisp_Object n;
829 int orig, orig_byte, end;
830 int count = SPECPDL_INDEX ();
831 specbind (Qinhibit_point_motion_hooks, Qt);
833 if (NILP (n))
834 XSETFASTINT (n, 1);
835 else
836 CHECK_NUMBER (n);
838 orig = PT;
839 orig_byte = PT_BYTE;
840 Fforward_line (make_number (XINT (n) - 1));
841 end = PT;
843 SET_PT_BOTH (orig, orig_byte);
845 unbind_to (count, Qnil);
847 /* Return END constrained to the current input field. */
848 return Fconstrain_to_field (make_number (end), make_number (orig),
849 XINT (n) != 1 ? Qt : Qnil,
850 Qt, Qnil);
853 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
854 doc: /* Return the character position of the last character on the current line.
855 With argument N not nil or 1, move forward N - 1 lines first.
856 If scan reaches end of buffer, return that position.
858 This function constrains the returned position to the current field
859 unless that would be on a different line than the original,
860 unconstrained result. If N is nil or 1, and a rear-sticky field ends
861 at point, the scan stops as soon as it starts. To ignore field
862 boundaries bind `inhibit-field-text-motion' to t.
864 This function does not move point. */)
866 Lisp_Object n;
868 int end_pos;
869 int orig = PT;
871 if (NILP (n))
872 XSETFASTINT (n, 1);
873 else
874 CHECK_NUMBER (n);
876 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
878 /* Return END_POS constrained to the current input field. */
879 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
880 Qnil, Qt, Qnil);
884 Lisp_Object
885 save_excursion_save ()
887 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
888 == current_buffer);
890 return Fcons (Fpoint_marker (),
891 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
892 Fcons (visible ? Qt : Qnil,
893 Fcons (current_buffer->mark_active,
894 selected_window))));
897 Lisp_Object
898 save_excursion_restore (info)
899 Lisp_Object info;
901 Lisp_Object tem, tem1, omark, nmark;
902 struct gcpro gcpro1, gcpro2, gcpro3;
903 int visible_p;
905 tem = Fmarker_buffer (XCAR (info));
906 /* If buffer being returned to is now deleted, avoid error */
907 /* Otherwise could get error here while unwinding to top level
908 and crash */
909 /* In that case, Fmarker_buffer returns nil now. */
910 if (NILP (tem))
911 return Qnil;
913 omark = nmark = Qnil;
914 GCPRO3 (info, omark, nmark);
916 Fset_buffer (tem);
918 /* Point marker. */
919 tem = XCAR (info);
920 Fgoto_char (tem);
921 unchain_marker (XMARKER (tem));
923 /* Mark marker. */
924 info = XCDR (info);
925 tem = XCAR (info);
926 omark = Fmarker_position (current_buffer->mark);
927 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
928 nmark = Fmarker_position (tem);
929 unchain_marker (XMARKER (tem));
931 /* visible */
932 info = XCDR (info);
933 visible_p = !NILP (XCAR (info));
935 #if 0 /* We used to make the current buffer visible in the selected window
936 if that was true previously. That avoids some anomalies.
937 But it creates others, and it wasn't documented, and it is simpler
938 and cleaner never to alter the window/buffer connections. */
939 tem1 = Fcar (tem);
940 if (!NILP (tem1)
941 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
942 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
943 #endif /* 0 */
945 /* Mark active */
946 info = XCDR (info);
947 tem = XCAR (info);
948 tem1 = current_buffer->mark_active;
949 current_buffer->mark_active = tem;
951 if (!NILP (Vrun_hooks))
953 /* If mark is active now, and either was not active
954 or was at a different place, run the activate hook. */
955 if (! NILP (current_buffer->mark_active))
957 if (! EQ (omark, nmark))
958 call1 (Vrun_hooks, intern ("activate-mark-hook"));
960 /* If mark has ceased to be active, run deactivate hook. */
961 else if (! NILP (tem1))
962 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
965 /* If buffer was visible in a window, and a different window was
966 selected, and the old selected window is still showing this
967 buffer, restore point in that window. */
968 tem = XCDR (info);
969 if (visible_p
970 && !EQ (tem, selected_window)
971 && (tem1 = XWINDOW (tem)->buffer,
972 (/* Window is live... */
973 BUFFERP (tem1)
974 /* ...and it shows the current buffer. */
975 && XBUFFER (tem1) == current_buffer)))
976 Fset_window_point (tem, make_number (PT));
978 UNGCPRO;
979 return Qnil;
982 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
983 doc: /* Save point, mark, and current buffer; execute BODY; restore those things.
984 Executes BODY just like `progn'.
985 The values of point, mark and the current buffer are restored
986 even in case of abnormal exit (throw or error).
987 The state of activation of the mark is also restored.
989 This construct does not save `deactivate-mark', and therefore
990 functions that change the buffer will still cause deactivation
991 of the mark at the end of the command. To prevent that, bind
992 `deactivate-mark' with `let'.
994 usage: (save-excursion &rest BODY) */)
995 (args)
996 Lisp_Object args;
998 register Lisp_Object val;
999 int count = SPECPDL_INDEX ();
1001 record_unwind_protect (save_excursion_restore, save_excursion_save ());
1003 val = Fprogn (args);
1004 return unbind_to (count, val);
1007 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
1008 doc: /* Save the current buffer; execute BODY; restore the current buffer.
1009 Executes BODY just like `progn'.
1010 usage: (save-current-buffer &rest BODY) */)
1011 (args)
1012 Lisp_Object args;
1014 Lisp_Object val;
1015 int count = SPECPDL_INDEX ();
1017 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
1019 val = Fprogn (args);
1020 return unbind_to (count, val);
1023 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
1024 doc: /* Return the number of characters in the current buffer.
1025 If BUFFER, return the number of characters in that buffer instead. */)
1026 (buffer)
1027 Lisp_Object buffer;
1029 if (NILP (buffer))
1030 return make_number (Z - BEG);
1031 else
1033 CHECK_BUFFER (buffer);
1034 return make_number (BUF_Z (XBUFFER (buffer))
1035 - BUF_BEG (XBUFFER (buffer)));
1039 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
1040 doc: /* Return the minimum permissible value of point in the current buffer.
1041 This is 1, unless narrowing (a buffer restriction) is in effect. */)
1044 Lisp_Object temp;
1045 XSETFASTINT (temp, BEGV);
1046 return temp;
1049 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
1050 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1051 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1054 return buildmark (BEGV, BEGV_BYTE);
1057 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1058 doc: /* Return the maximum permissible value of point in the current buffer.
1059 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1060 is in effect, in which case it is less. */)
1063 Lisp_Object temp;
1064 XSETFASTINT (temp, ZV);
1065 return temp;
1068 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1069 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1070 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1071 is in effect, in which case it is less. */)
1074 return buildmark (ZV, ZV_BYTE);
1077 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1078 doc: /* Return the position of the gap, in the current buffer.
1079 See also `gap-size'. */)
1082 Lisp_Object temp;
1083 XSETFASTINT (temp, GPT);
1084 return temp;
1087 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1088 doc: /* Return the size of the current buffer's gap.
1089 See also `gap-position'. */)
1092 Lisp_Object temp;
1093 XSETFASTINT (temp, GAP_SIZE);
1094 return temp;
1097 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1098 doc: /* Return the byte position for character position POSITION.
1099 If POSITION is out of range, the value is nil. */)
1100 (position)
1101 Lisp_Object position;
1103 CHECK_NUMBER_COERCE_MARKER (position);
1104 if (XINT (position) < BEG || XINT (position) > Z)
1105 return Qnil;
1106 return make_number (CHAR_TO_BYTE (XINT (position)));
1109 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1110 doc: /* Return the character position for byte position BYTEPOS.
1111 If BYTEPOS is out of range, the value is nil. */)
1112 (bytepos)
1113 Lisp_Object bytepos;
1115 CHECK_NUMBER (bytepos);
1116 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
1117 return Qnil;
1118 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1121 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1122 doc: /* Return the character following point, as a number.
1123 At the end of the buffer or accessible region, return 0. */)
1126 Lisp_Object temp;
1127 if (PT >= ZV)
1128 XSETFASTINT (temp, 0);
1129 else
1130 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1131 return temp;
1134 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1135 doc: /* Return the character preceding point, as a number.
1136 At the beginning of the buffer or accessible region, return 0. */)
1139 Lisp_Object temp;
1140 if (PT <= BEGV)
1141 XSETFASTINT (temp, 0);
1142 else if (!NILP (current_buffer->enable_multibyte_characters))
1144 int pos = PT_BYTE;
1145 DEC_POS (pos);
1146 XSETFASTINT (temp, FETCH_CHAR (pos));
1148 else
1149 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1150 return temp;
1153 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1154 doc: /* Return t if point is at the beginning of the buffer.
1155 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1158 if (PT == BEGV)
1159 return Qt;
1160 return Qnil;
1163 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1164 doc: /* Return t if point is at the end of the buffer.
1165 If the buffer is narrowed, this means the end of the narrowed part. */)
1168 if (PT == ZV)
1169 return Qt;
1170 return Qnil;
1173 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1174 doc: /* Return t if point is at the beginning of a line. */)
1177 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1178 return Qt;
1179 return Qnil;
1182 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1183 doc: /* Return t if point is at the end of a line.
1184 `End of a line' includes point being at the end of the buffer. */)
1187 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1188 return Qt;
1189 return Qnil;
1192 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1193 doc: /* Return character in current buffer at position POS.
1194 POS is an integer or a marker and defaults to point.
1195 If POS is out of range, the value is nil. */)
1196 (pos)
1197 Lisp_Object pos;
1199 register int pos_byte;
1201 if (NILP (pos))
1203 pos_byte = PT_BYTE;
1204 XSETFASTINT (pos, PT);
1207 if (MARKERP (pos))
1209 pos_byte = marker_byte_position (pos);
1210 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1211 return Qnil;
1213 else
1215 CHECK_NUMBER_COERCE_MARKER (pos);
1216 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1217 return Qnil;
1219 pos_byte = CHAR_TO_BYTE (XINT (pos));
1222 return make_number (FETCH_CHAR (pos_byte));
1225 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1226 doc: /* Return character in current buffer preceding position POS.
1227 POS is an integer or a marker and defaults to point.
1228 If POS is out of range, the value is nil. */)
1229 (pos)
1230 Lisp_Object pos;
1232 register Lisp_Object val;
1233 register int pos_byte;
1235 if (NILP (pos))
1237 pos_byte = PT_BYTE;
1238 XSETFASTINT (pos, PT);
1241 if (MARKERP (pos))
1243 pos_byte = marker_byte_position (pos);
1245 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1246 return Qnil;
1248 else
1250 CHECK_NUMBER_COERCE_MARKER (pos);
1252 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1253 return Qnil;
1255 pos_byte = CHAR_TO_BYTE (XINT (pos));
1258 if (!NILP (current_buffer->enable_multibyte_characters))
1260 DEC_POS (pos_byte);
1261 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1263 else
1265 pos_byte--;
1266 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1268 return val;
1271 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1272 doc: /* Return the name under which the user logged in, as a string.
1273 This is based on the effective uid, not the real uid.
1274 Also, if the environment variables LOGNAME or USER are set,
1275 that determines the value of this function.
1277 If optional argument UID is an integer, return the login name of the user
1278 with that uid, or nil if there is no such user. */)
1279 (uid)
1280 Lisp_Object uid;
1282 struct passwd *pw;
1284 /* Set up the user name info if we didn't do it before.
1285 (That can happen if Emacs is dumpable
1286 but you decide to run `temacs -l loadup' and not dump. */
1287 if (INTEGERP (Vuser_login_name))
1288 init_editfns ();
1290 if (NILP (uid))
1291 return Vuser_login_name;
1293 CHECK_NUMBER (uid);
1294 BLOCK_INPUT;
1295 pw = (struct passwd *) getpwuid (XINT (uid));
1296 UNBLOCK_INPUT;
1297 return (pw ? build_string (pw->pw_name) : Qnil);
1300 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1301 0, 0, 0,
1302 doc: /* Return the name of the user's real uid, as a string.
1303 This ignores the environment variables LOGNAME and USER, so it differs from
1304 `user-login-name' when running under `su'. */)
1307 /* Set up the user name info if we didn't do it before.
1308 (That can happen if Emacs is dumpable
1309 but you decide to run `temacs -l loadup' and not dump. */
1310 if (INTEGERP (Vuser_login_name))
1311 init_editfns ();
1312 return Vuser_real_login_name;
1315 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1316 doc: /* Return the effective uid of Emacs.
1317 Value is an integer or float, depending on the value. */)
1320 /* Assignment to EMACS_INT stops GCC whining about limited range of
1321 data type. */
1322 EMACS_INT euid = geteuid ();
1323 return make_fixnum_or_float (euid);
1326 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1327 doc: /* Return the real uid of Emacs.
1328 Value is an integer or float, depending on the value. */)
1331 /* Assignment to EMACS_INT stops GCC whining about limited range of
1332 data type. */
1333 EMACS_INT uid = getuid ();
1334 return make_fixnum_or_float (uid);
1337 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1338 doc: /* Return the full name of the user logged in, as a string.
1339 If the full name corresponding to Emacs's userid is not known,
1340 return "unknown".
1342 If optional argument UID is an integer or float, return the full name
1343 of the user with that uid, or nil if there is no such user.
1344 If UID is a string, return the full name of the user with that login
1345 name, or nil if there is no such user. */)
1346 (uid)
1347 Lisp_Object uid;
1349 struct passwd *pw;
1350 register unsigned char *p, *q;
1351 Lisp_Object full;
1353 if (NILP (uid))
1354 return Vuser_full_name;
1355 else if (NUMBERP (uid))
1357 BLOCK_INPUT;
1358 pw = (struct passwd *) getpwuid ((uid_t) XFLOATINT (uid));
1359 UNBLOCK_INPUT;
1361 else if (STRINGP (uid))
1363 BLOCK_INPUT;
1364 pw = (struct passwd *) getpwnam (SDATA (uid));
1365 UNBLOCK_INPUT;
1367 else
1368 error ("Invalid UID specification");
1370 if (!pw)
1371 return Qnil;
1373 p = (unsigned char *) USER_FULL_NAME;
1374 /* Chop off everything after the first comma. */
1375 q = (unsigned char *) index (p, ',');
1376 full = make_string (p, q ? q - p : strlen (p));
1378 #ifdef AMPERSAND_FULL_NAME
1379 p = SDATA (full);
1380 q = (unsigned char *) index (p, '&');
1381 /* Substitute the login name for the &, upcasing the first character. */
1382 if (q)
1384 register unsigned char *r;
1385 Lisp_Object login;
1387 login = Fuser_login_name (make_number (pw->pw_uid));
1388 r = (unsigned char *) alloca (strlen (p) + SCHARS (login) + 1);
1389 bcopy (p, r, q - p);
1390 r[q - p] = 0;
1391 strcat (r, SDATA (login));
1392 r[q - p] = UPCASE (r[q - p]);
1393 strcat (r, q + 1);
1394 full = build_string (r);
1396 #endif /* AMPERSAND_FULL_NAME */
1398 return full;
1401 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1402 doc: /* Return the host name of the machine you are running on, as a string. */)
1405 return Vsystem_name;
1408 /* For the benefit of callers who don't want to include lisp.h */
1410 char *
1411 get_system_name ()
1413 if (STRINGP (Vsystem_name))
1414 return (char *) SDATA (Vsystem_name);
1415 else
1416 return "";
1419 char *
1420 get_operating_system_release()
1422 if (STRINGP (Voperating_system_release))
1423 return (char *) SDATA (Voperating_system_release);
1424 else
1425 return "";
1428 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1429 doc: /* Return the process ID of Emacs, as an integer. */)
1432 return make_number (getpid ());
1435 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1436 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1437 The time is returned as a list of three integers. The first has the
1438 most significant 16 bits of the seconds, while the second has the
1439 least significant 16 bits. The third integer gives the microsecond
1440 count.
1442 The microsecond count is zero on systems that do not provide
1443 resolution finer than a second. */)
1446 EMACS_TIME t;
1448 EMACS_GET_TIME (t);
1449 return list3 (make_number ((EMACS_SECS (t) >> 16) & 0xffff),
1450 make_number ((EMACS_SECS (t) >> 0) & 0xffff),
1451 make_number (EMACS_USECS (t)));
1454 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1455 0, 0, 0,
1456 doc: /* Return the current run time used by Emacs.
1457 The time is returned as a list of three integers. The first has the
1458 most significant 16 bits of the seconds, while the second has the
1459 least significant 16 bits. The third integer gives the microsecond
1460 count.
1462 On systems that can't determine the run time, `get-internal-run-time'
1463 does the same thing as `current-time'. The microsecond count is zero
1464 on systems that do not provide resolution finer than a second. */)
1467 #ifdef HAVE_GETRUSAGE
1468 struct rusage usage;
1469 int secs, usecs;
1471 if (getrusage (RUSAGE_SELF, &usage) < 0)
1472 /* This shouldn't happen. What action is appropriate? */
1473 xsignal0 (Qerror);
1475 /* Sum up user time and system time. */
1476 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1477 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1478 if (usecs >= 1000000)
1480 usecs -= 1000000;
1481 secs++;
1484 return list3 (make_number ((secs >> 16) & 0xffff),
1485 make_number ((secs >> 0) & 0xffff),
1486 make_number (usecs));
1487 #else /* ! HAVE_GETRUSAGE */
1488 #if WINDOWSNT
1489 return w32_get_internal_run_time ();
1490 #else /* ! WINDOWSNT */
1491 return Fcurrent_time ();
1492 #endif /* WINDOWSNT */
1493 #endif /* HAVE_GETRUSAGE */
1498 lisp_time_argument (specified_time, result, usec)
1499 Lisp_Object specified_time;
1500 time_t *result;
1501 int *usec;
1503 if (NILP (specified_time))
1505 if (usec)
1507 EMACS_TIME t;
1509 EMACS_GET_TIME (t);
1510 *usec = EMACS_USECS (t);
1511 *result = EMACS_SECS (t);
1512 return 1;
1514 else
1515 return time (result) != -1;
1517 else
1519 Lisp_Object high, low;
1520 high = Fcar (specified_time);
1521 CHECK_NUMBER (high);
1522 low = Fcdr (specified_time);
1523 if (CONSP (low))
1525 if (usec)
1527 Lisp_Object usec_l = Fcdr (low);
1528 if (CONSP (usec_l))
1529 usec_l = Fcar (usec_l);
1530 if (NILP (usec_l))
1531 *usec = 0;
1532 else
1534 CHECK_NUMBER (usec_l);
1535 *usec = XINT (usec_l);
1538 low = Fcar (low);
1540 else if (usec)
1541 *usec = 0;
1542 CHECK_NUMBER (low);
1543 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
1544 return *result >> 16 == XINT (high);
1548 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1549 doc: /* Return the current time, as a float number of seconds since the epoch.
1550 If SPECIFIED-TIME is given, it is the time to convert to float
1551 instead of the current time. The argument should have the form
1552 (HIGH LOW . IGNORED). Thus, you can use times obtained from
1553 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
1554 have the form (HIGH . LOW), but this is considered obsolete.
1556 WARNING: Since the result is floating point, it may not be exact.
1557 Do not use this function if precise time stamps are required. */)
1558 (specified_time)
1559 Lisp_Object specified_time;
1561 time_t sec;
1562 int usec;
1564 if (! lisp_time_argument (specified_time, &sec, &usec))
1565 error ("Invalid time specification");
1567 return make_float ((sec * 1e6 + usec) / 1e6);
1570 /* Write information into buffer S of size MAXSIZE, according to the
1571 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1572 Default to Universal Time if UT is nonzero, local time otherwise.
1573 Return the number of bytes written, not including the terminating
1574 '\0'. If S is NULL, nothing will be written anywhere; so to
1575 determine how many bytes would be written, use NULL for S and
1576 ((size_t) -1) for MAXSIZE.
1578 This function behaves like emacs_strftimeu, except it allows null
1579 bytes in FORMAT. */
1580 static size_t
1581 emacs_memftimeu (s, maxsize, format, format_len, tp, ut)
1582 char *s;
1583 size_t maxsize;
1584 const char *format;
1585 size_t format_len;
1586 const struct tm *tp;
1587 int ut;
1589 size_t total = 0;
1591 /* Loop through all the null-terminated strings in the format
1592 argument. Normally there's just one null-terminated string, but
1593 there can be arbitrarily many, concatenated together, if the
1594 format contains '\0' bytes. emacs_strftimeu stops at the first
1595 '\0' byte so we must invoke it separately for each such string. */
1596 for (;;)
1598 size_t len;
1599 size_t result;
1601 if (s)
1602 s[0] = '\1';
1604 result = emacs_strftimeu (s, maxsize, format, tp, ut);
1606 if (s)
1608 if (result == 0 && s[0] != '\0')
1609 return 0;
1610 s += result + 1;
1613 maxsize -= result + 1;
1614 total += result;
1615 len = strlen (format);
1616 if (len == format_len)
1617 return total;
1618 total++;
1619 format += len + 1;
1620 format_len -= len + 1;
1624 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1625 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
1626 TIME is specified as (HIGH LOW . IGNORED), as returned by
1627 `current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
1628 is also still accepted.
1629 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1630 as Universal Time; nil means describe TIME in the local time zone.
1631 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1632 by text that describes the specified date and time in TIME:
1634 %Y is the year, %y within the century, %C the century.
1635 %G is the year corresponding to the ISO week, %g within the century.
1636 %m is the numeric month.
1637 %b and %h are the locale's abbreviated month name, %B the full name.
1638 %d is the day of the month, zero-padded, %e is blank-padded.
1639 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1640 %a is the locale's abbreviated name of the day of week, %A the full name.
1641 %U is the week number starting on Sunday, %W starting on Monday,
1642 %V according to ISO 8601.
1643 %j is the day of the year.
1645 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1646 only blank-padded, %l is like %I blank-padded.
1647 %p is the locale's equivalent of either AM or PM.
1648 %M is the minute.
1649 %S is the second.
1650 %Z is the time zone name, %z is the numeric form.
1651 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1653 %c is the locale's date and time format.
1654 %x is the locale's "preferred" date format.
1655 %D is like "%m/%d/%y".
1657 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1658 %X is the locale's "preferred" time format.
1660 Finally, %n is a newline, %t is a tab, %% is a literal %.
1662 Certain flags and modifiers are available with some format controls.
1663 The flags are `_', `-', `^' and `#'. For certain characters X,
1664 %_X is like %X, but padded with blanks; %-X is like %X,
1665 but without padding. %^X is like %X, but with all textual
1666 characters up-cased; %#X is like %X, but with letter-case of
1667 all textual characters reversed.
1668 %NX (where N stands for an integer) is like %X,
1669 but takes up at least N (a number) positions.
1670 The modifiers are `E' and `O'. For certain characters X,
1671 %EX is a locale's alternative version of %X;
1672 %OX is like %X, but uses the locale's number symbols.
1674 For example, to produce full ISO 8601 format, use "%Y-%m-%dT%T%z". */)
1675 (format_string, time, universal)
1676 Lisp_Object format_string, time, universal;
1678 time_t value;
1679 int size;
1680 struct tm *tm;
1681 int ut = ! NILP (universal);
1683 CHECK_STRING (format_string);
1685 if (! lisp_time_argument (time, &value, NULL))
1686 error ("Invalid time specification");
1688 format_string = code_convert_string_norecord (format_string,
1689 Vlocale_coding_system, 1);
1691 /* This is probably enough. */
1692 size = SBYTES (format_string) * 6 + 50;
1694 BLOCK_INPUT;
1695 tm = ut ? gmtime (&value) : localtime (&value);
1696 UNBLOCK_INPUT;
1697 if (! tm)
1698 error ("Specified time is not representable");
1700 synchronize_system_time_locale ();
1702 while (1)
1704 char *buf = (char *) alloca (size + 1);
1705 int result;
1707 buf[0] = '\1';
1708 BLOCK_INPUT;
1709 result = emacs_memftimeu (buf, size, SDATA (format_string),
1710 SBYTES (format_string),
1711 tm, ut);
1712 UNBLOCK_INPUT;
1713 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1714 return code_convert_string_norecord (make_unibyte_string (buf, result),
1715 Vlocale_coding_system, 0);
1717 /* If buffer was too small, make it bigger and try again. */
1718 BLOCK_INPUT;
1719 result = emacs_memftimeu (NULL, (size_t) -1,
1720 SDATA (format_string),
1721 SBYTES (format_string),
1722 tm, ut);
1723 UNBLOCK_INPUT;
1724 size = result + 1;
1728 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1729 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
1730 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
1731 as from `current-time' and `file-attributes', or nil to use the
1732 current time. The obsolete form (HIGH . LOW) is also still accepted.
1733 The list has the following nine members: SEC is an integer between 0
1734 and 60; SEC is 60 for a leap second, which only some operating systems
1735 support. MINUTE is an integer between 0 and 59. HOUR is an integer
1736 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
1737 integer between 1 and 12. YEAR is an integer indicating the
1738 four-digit year. DOW is the day of week, an integer between 0 and 6,
1739 where 0 is Sunday. DST is t if daylight saving time is in effect,
1740 otherwise nil. ZONE is an integer indicating the number of seconds
1741 east of Greenwich. (Note that Common Lisp has different meanings for
1742 DOW and ZONE.) */)
1743 (specified_time)
1744 Lisp_Object specified_time;
1746 time_t time_spec;
1747 struct tm save_tm;
1748 struct tm *decoded_time;
1749 Lisp_Object list_args[9];
1751 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1752 error ("Invalid time specification");
1754 BLOCK_INPUT;
1755 decoded_time = localtime (&time_spec);
1756 UNBLOCK_INPUT;
1757 if (! decoded_time)
1758 error ("Specified time is not representable");
1759 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1760 XSETFASTINT (list_args[1], decoded_time->tm_min);
1761 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1762 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1763 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1764 /* On 64-bit machines an int is narrower than EMACS_INT, thus the
1765 cast below avoids overflow in int arithmetics. */
1766 XSETINT (list_args[5], TM_YEAR_BASE + (EMACS_INT) decoded_time->tm_year);
1767 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1768 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1770 /* Make a copy, in case gmtime modifies the struct. */
1771 save_tm = *decoded_time;
1772 BLOCK_INPUT;
1773 decoded_time = gmtime (&time_spec);
1774 UNBLOCK_INPUT;
1775 if (decoded_time == 0)
1776 list_args[8] = Qnil;
1777 else
1778 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1779 return Flist (9, list_args);
1782 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1783 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
1784 This is the reverse operation of `decode-time', which see.
1785 ZONE defaults to the current time zone rule. This can
1786 be a string or t (as from `set-time-zone-rule'), or it can be a list
1787 \(as from `current-time-zone') or an integer (as from `decode-time')
1788 applied without consideration for daylight saving time.
1790 You can pass more than 7 arguments; then the first six arguments
1791 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
1792 The intervening arguments are ignored.
1793 This feature lets (apply 'encode-time (decode-time ...)) work.
1795 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
1796 for example, a DAY of 0 means the day preceding the given month.
1797 Year numbers less than 100 are treated just like other year numbers.
1798 If you want them to stand for years in this century, you must do that yourself.
1800 Years before 1970 are not guaranteed to work. On some systems,
1801 year values as low as 1901 do work.
1803 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
1804 (nargs, args)
1805 int nargs;
1806 register Lisp_Object *args;
1808 time_t time;
1809 struct tm tm;
1810 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1812 CHECK_NUMBER (args[0]); /* second */
1813 CHECK_NUMBER (args[1]); /* minute */
1814 CHECK_NUMBER (args[2]); /* hour */
1815 CHECK_NUMBER (args[3]); /* day */
1816 CHECK_NUMBER (args[4]); /* month */
1817 CHECK_NUMBER (args[5]); /* year */
1819 tm.tm_sec = XINT (args[0]);
1820 tm.tm_min = XINT (args[1]);
1821 tm.tm_hour = XINT (args[2]);
1822 tm.tm_mday = XINT (args[3]);
1823 tm.tm_mon = XINT (args[4]) - 1;
1824 tm.tm_year = XINT (args[5]) - TM_YEAR_BASE;
1825 tm.tm_isdst = -1;
1827 if (CONSP (zone))
1828 zone = Fcar (zone);
1829 if (NILP (zone))
1831 BLOCK_INPUT;
1832 time = mktime (&tm);
1833 UNBLOCK_INPUT;
1835 else
1837 char tzbuf[100];
1838 char *tzstring;
1839 char **oldenv = environ, **newenv;
1841 if (EQ (zone, Qt))
1842 tzstring = "UTC0";
1843 else if (STRINGP (zone))
1844 tzstring = (char *) SDATA (zone);
1845 else if (INTEGERP (zone))
1847 int abszone = eabs (XINT (zone));
1848 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1849 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1850 tzstring = tzbuf;
1852 else
1853 error ("Invalid time zone specification");
1855 /* Set TZ before calling mktime; merely adjusting mktime's returned
1856 value doesn't suffice, since that would mishandle leap seconds. */
1857 set_time_zone_rule (tzstring);
1859 BLOCK_INPUT;
1860 time = mktime (&tm);
1861 UNBLOCK_INPUT;
1863 /* Restore TZ to previous value. */
1864 newenv = environ;
1865 environ = oldenv;
1866 xfree (newenv);
1867 #ifdef LOCALTIME_CACHE
1868 tzset ();
1869 #endif
1872 if (time == (time_t) -1)
1873 error ("Specified time is not representable");
1875 return make_time (time);
1878 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1879 doc: /* Return the current time, as a human-readable string.
1880 Programs can use this function to decode a time,
1881 since the number of columns in each field is fixed
1882 if the year is in the range 1000-9999.
1883 The format is `Sun Sep 16 01:03:52 1973'.
1884 However, see also the functions `decode-time' and `format-time-string'
1885 which provide a much more powerful and general facility.
1887 If SPECIFIED-TIME is given, it is a time to format instead of the
1888 current time. The argument should have the form (HIGH LOW . IGNORED).
1889 Thus, you can use times obtained from `current-time' and from
1890 `file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
1891 but this is considered obsolete. */)
1892 (specified_time)
1893 Lisp_Object specified_time;
1895 time_t value;
1896 struct tm *tm;
1897 register char *tem;
1899 if (! lisp_time_argument (specified_time, &value, NULL))
1900 error ("Invalid time specification");
1902 /* Convert to a string, checking for out-of-range time stamps.
1903 Don't use 'ctime', as that might dump core if VALUE is out of
1904 range. */
1905 BLOCK_INPUT;
1906 tm = localtime (&value);
1907 UNBLOCK_INPUT;
1908 if (! (tm && TM_YEAR_IN_ASCTIME_RANGE (tm->tm_year) && (tem = asctime (tm))))
1909 error ("Specified time is not representable");
1911 /* Remove the trailing newline. */
1912 tem[strlen (tem) - 1] = '\0';
1914 return build_string (tem);
1917 /* Yield A - B, measured in seconds.
1918 This function is copied from the GNU C Library. */
1919 static int
1920 tm_diff (a, b)
1921 struct tm *a, *b;
1923 /* Compute intervening leap days correctly even if year is negative.
1924 Take care to avoid int overflow in leap day calculations,
1925 but it's OK to assume that A and B are close to each other. */
1926 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1927 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1928 int a100 = a4 / 25 - (a4 % 25 < 0);
1929 int b100 = b4 / 25 - (b4 % 25 < 0);
1930 int a400 = a100 >> 2;
1931 int b400 = b100 >> 2;
1932 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1933 int years = a->tm_year - b->tm_year;
1934 int days = (365 * years + intervening_leap_days
1935 + (a->tm_yday - b->tm_yday));
1936 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1937 + (a->tm_min - b->tm_min))
1938 + (a->tm_sec - b->tm_sec));
1941 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1942 doc: /* Return the offset and name for the local time zone.
1943 This returns a list of the form (OFFSET NAME).
1944 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
1945 A negative value means west of Greenwich.
1946 NAME is a string giving the name of the time zone.
1947 If SPECIFIED-TIME is given, the time zone offset is determined from it
1948 instead of using the current time. The argument should have the form
1949 (HIGH LOW . IGNORED). Thus, you can use times obtained from
1950 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
1951 have the form (HIGH . LOW), but this is considered obsolete.
1953 Some operating systems cannot provide all this information to Emacs;
1954 in this case, `current-time-zone' returns a list containing nil for
1955 the data it can't find. */)
1956 (specified_time)
1957 Lisp_Object specified_time;
1959 time_t value;
1960 struct tm *t;
1961 struct tm gmt;
1963 if (!lisp_time_argument (specified_time, &value, NULL))
1964 t = NULL;
1965 else
1967 BLOCK_INPUT;
1968 t = gmtime (&value);
1969 if (t)
1971 gmt = *t;
1972 t = localtime (&value);
1974 UNBLOCK_INPUT;
1977 if (t)
1979 int offset = tm_diff (t, &gmt);
1980 char *s = 0;
1981 char buf[6];
1983 #ifdef HAVE_TM_ZONE
1984 if (t->tm_zone)
1985 s = (char *)t->tm_zone;
1986 #else /* not HAVE_TM_ZONE */
1987 #ifdef HAVE_TZNAME
1988 if (t->tm_isdst == 0 || t->tm_isdst == 1)
1989 s = tzname[t->tm_isdst];
1990 #endif
1991 #endif /* not HAVE_TM_ZONE */
1993 if (!s)
1995 /* No local time zone name is available; use "+-NNNN" instead. */
1996 int am = (offset < 0 ? -offset : offset) / 60;
1997 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
1998 s = buf;
2001 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
2003 else
2004 return Fmake_list (make_number (2), Qnil);
2007 /* This holds the value of `environ' produced by the previous
2008 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
2009 has never been called. */
2010 static char **environbuf;
2012 /* This holds the startup value of the TZ environment variable so it
2013 can be restored if the user calls set-time-zone-rule with a nil
2014 argument. */
2015 static char *initial_tz;
2017 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2018 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
2019 If TZ is nil, use implementation-defined default time zone information.
2020 If TZ is t, use Universal Time. */)
2021 (tz)
2022 Lisp_Object tz;
2024 char *tzstring;
2026 /* When called for the first time, save the original TZ. */
2027 if (!environbuf)
2028 initial_tz = (char *) getenv ("TZ");
2030 if (NILP (tz))
2031 tzstring = initial_tz;
2032 else if (EQ (tz, Qt))
2033 tzstring = "UTC0";
2034 else
2036 CHECK_STRING (tz);
2037 tzstring = (char *) SDATA (tz);
2040 set_time_zone_rule (tzstring);
2041 if (environbuf)
2042 free (environbuf);
2043 environbuf = environ;
2045 return Qnil;
2048 #ifdef LOCALTIME_CACHE
2050 /* These two values are known to load tz files in buggy implementations,
2051 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
2052 Their values shouldn't matter in non-buggy implementations.
2053 We don't use string literals for these strings,
2054 since if a string in the environment is in readonly
2055 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
2056 See Sun bugs 1113095 and 1114114, ``Timezone routines
2057 improperly modify environment''. */
2059 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
2060 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
2062 #endif
2064 /* Set the local time zone rule to TZSTRING.
2065 This allocates memory into `environ', which it is the caller's
2066 responsibility to free. */
2068 void
2069 set_time_zone_rule (tzstring)
2070 char *tzstring;
2072 int envptrs;
2073 char **from, **to, **newenv;
2075 /* Make the ENVIRON vector longer with room for TZSTRING. */
2076 for (from = environ; *from; from++)
2077 continue;
2078 envptrs = from - environ + 2;
2079 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
2080 + (tzstring ? strlen (tzstring) + 4 : 0));
2082 /* Add TZSTRING to the end of environ, as a value for TZ. */
2083 if (tzstring)
2085 char *t = (char *) (to + envptrs);
2086 strcpy (t, "TZ=");
2087 strcat (t, tzstring);
2088 *to++ = t;
2091 /* Copy the old environ vector elements into NEWENV,
2092 but don't copy the TZ variable.
2093 So we have only one definition of TZ, which came from TZSTRING. */
2094 for (from = environ; *from; from++)
2095 if (strncmp (*from, "TZ=", 3) != 0)
2096 *to++ = *from;
2097 *to = 0;
2099 environ = newenv;
2101 /* If we do have a TZSTRING, NEWENV points to the vector slot where
2102 the TZ variable is stored. If we do not have a TZSTRING,
2103 TO points to the vector slot which has the terminating null. */
2105 #ifdef LOCALTIME_CACHE
2107 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
2108 "US/Pacific" that loads a tz file, then changes to a value like
2109 "XXX0" that does not load a tz file, and then changes back to
2110 its original value, the last change is (incorrectly) ignored.
2111 Also, if TZ changes twice in succession to values that do
2112 not load a tz file, tzset can dump core (see Sun bug#1225179).
2113 The following code works around these bugs. */
2115 if (tzstring)
2117 /* Temporarily set TZ to a value that loads a tz file
2118 and that differs from tzstring. */
2119 char *tz = *newenv;
2120 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
2121 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
2122 tzset ();
2123 *newenv = tz;
2125 else
2127 /* The implied tzstring is unknown, so temporarily set TZ to
2128 two different values that each load a tz file. */
2129 *to = set_time_zone_rule_tz1;
2130 to[1] = 0;
2131 tzset ();
2132 *to = set_time_zone_rule_tz2;
2133 tzset ();
2134 *to = 0;
2137 /* Now TZ has the desired value, and tzset can be invoked safely. */
2140 tzset ();
2141 #endif
2144 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2145 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2146 type of object is Lisp_String). INHERIT is passed to
2147 INSERT_FROM_STRING_FUNC as the last argument. */
2149 static void
2150 general_insert_function (insert_func, insert_from_string_func,
2151 inherit, nargs, args)
2152 void (*insert_func) P_ ((const unsigned char *, int));
2153 void (*insert_from_string_func) P_ ((Lisp_Object, int, int, int, int, int));
2154 int inherit, nargs;
2155 register Lisp_Object *args;
2157 register int argnum;
2158 register Lisp_Object val;
2160 for (argnum = 0; argnum < nargs; argnum++)
2162 val = args[argnum];
2163 if (CHARACTERP (val))
2165 unsigned char str[MAX_MULTIBYTE_LENGTH];
2166 int len;
2168 if (!NILP (current_buffer->enable_multibyte_characters))
2169 len = CHAR_STRING (XFASTINT (val), str);
2170 else
2172 str[0] = (ASCII_CHAR_P (XINT (val))
2173 ? XINT (val)
2174 : multibyte_char_to_unibyte (XINT (val), Qnil));
2175 len = 1;
2177 (*insert_func) (str, len);
2179 else if (STRINGP (val))
2181 (*insert_from_string_func) (val, 0, 0,
2182 SCHARS (val),
2183 SBYTES (val),
2184 inherit);
2186 else
2187 wrong_type_argument (Qchar_or_string_p, val);
2191 void
2192 insert1 (arg)
2193 Lisp_Object arg;
2195 Finsert (1, &arg);
2199 /* Callers passing one argument to Finsert need not gcpro the
2200 argument "array", since the only element of the array will
2201 not be used after calling insert or insert_from_string, so
2202 we don't care if it gets trashed. */
2204 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2205 doc: /* Insert the arguments, either strings or characters, at point.
2206 Point and before-insertion markers move forward to end up
2207 after the inserted text.
2208 Any other markers at the point of insertion remain before the text.
2210 If the current buffer is multibyte, unibyte strings are converted
2211 to multibyte for insertion (see `string-make-multibyte').
2212 If the current buffer is unibyte, multibyte strings are converted
2213 to unibyte for insertion (see `string-make-unibyte').
2215 When operating on binary data, it may be necessary to preserve the
2216 original bytes of a unibyte string when inserting it into a multibyte
2217 buffer; to accomplish this, apply `string-as-multibyte' to the string
2218 and insert the result.
2220 usage: (insert &rest ARGS) */)
2221 (nargs, args)
2222 int nargs;
2223 register Lisp_Object *args;
2225 general_insert_function (insert, insert_from_string, 0, nargs, args);
2226 return Qnil;
2229 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2230 0, MANY, 0,
2231 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2232 Point and before-insertion markers move forward to end up
2233 after the inserted text.
2234 Any other markers at the point of insertion remain before the text.
2236 If the current buffer is multibyte, unibyte strings are converted
2237 to multibyte for insertion (see `unibyte-char-to-multibyte').
2238 If the current buffer is unibyte, multibyte strings are converted
2239 to unibyte for insertion.
2241 usage: (insert-and-inherit &rest ARGS) */)
2242 (nargs, args)
2243 int nargs;
2244 register Lisp_Object *args;
2246 general_insert_function (insert_and_inherit, insert_from_string, 1,
2247 nargs, args);
2248 return Qnil;
2251 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2252 doc: /* Insert strings or characters at point, relocating markers after the text.
2253 Point and markers move forward to end up after the inserted text.
2255 If the current buffer is multibyte, unibyte strings are converted
2256 to multibyte for insertion (see `unibyte-char-to-multibyte').
2257 If the current buffer is unibyte, multibyte strings are converted
2258 to unibyte for insertion.
2260 usage: (insert-before-markers &rest ARGS) */)
2261 (nargs, args)
2262 int nargs;
2263 register Lisp_Object *args;
2265 general_insert_function (insert_before_markers,
2266 insert_from_string_before_markers, 0,
2267 nargs, args);
2268 return Qnil;
2271 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2272 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2273 doc: /* Insert text at point, relocating markers and inheriting properties.
2274 Point and markers move forward to end up after the inserted text.
2276 If the current buffer is multibyte, unibyte strings are converted
2277 to multibyte for insertion (see `unibyte-char-to-multibyte').
2278 If the current buffer is unibyte, multibyte strings are converted
2279 to unibyte for insertion.
2281 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2282 (nargs, args)
2283 int nargs;
2284 register Lisp_Object *args;
2286 general_insert_function (insert_before_markers_and_inherit,
2287 insert_from_string_before_markers, 1,
2288 nargs, args);
2289 return Qnil;
2292 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
2293 doc: /* Insert COUNT copies of CHARACTER.
2294 Point, and before-insertion markers, are relocated as in the function `insert'.
2295 The optional third arg INHERIT, if non-nil, says to inherit text properties
2296 from adjoining text, if those properties are sticky. */)
2297 (character, count, inherit)
2298 Lisp_Object character, count, inherit;
2300 register unsigned char *string;
2301 register int strlen;
2302 register int i, n;
2303 int len;
2304 unsigned char str[MAX_MULTIBYTE_LENGTH];
2306 CHECK_NUMBER (character);
2307 CHECK_NUMBER (count);
2309 if (!NILP (current_buffer->enable_multibyte_characters))
2310 len = CHAR_STRING (XFASTINT (character), str);
2311 else
2312 str[0] = XFASTINT (character), len = 1;
2313 n = XINT (count) * len;
2314 if (n <= 0)
2315 return Qnil;
2316 strlen = min (n, 256 * len);
2317 string = (unsigned char *) alloca (strlen);
2318 for (i = 0; i < strlen; i++)
2319 string[i] = str[i % len];
2320 while (n >= strlen)
2322 QUIT;
2323 if (!NILP (inherit))
2324 insert_and_inherit (string, strlen);
2325 else
2326 insert (string, strlen);
2327 n -= strlen;
2329 if (n > 0)
2331 if (!NILP (inherit))
2332 insert_and_inherit (string, n);
2333 else
2334 insert (string, n);
2336 return Qnil;
2339 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2340 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2341 Both arguments are required.
2342 BYTE is a number of the range 0..255.
2344 If BYTE is 128..255 and the current buffer is multibyte, the
2345 corresponding eight-bit character is inserted.
2347 Point, and before-insertion markers, are relocated as in the function `insert'.
2348 The optional third arg INHERIT, if non-nil, says to inherit text properties
2349 from adjoining text, if those properties are sticky. */)
2350 (byte, count, inherit)
2351 Lisp_Object byte, count, inherit;
2353 CHECK_NUMBER (byte);
2354 if (XINT (byte) < 0 || XINT (byte) > 255)
2355 args_out_of_range_3 (byte, make_number (0), make_number (255));
2356 if (XINT (byte) >= 128
2357 && ! NILP (current_buffer->enable_multibyte_characters))
2358 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2359 return Finsert_char (byte, count, inherit);
2363 /* Making strings from buffer contents. */
2365 /* Return a Lisp_String containing the text of the current buffer from
2366 START to END. If text properties are in use and the current buffer
2367 has properties in the range specified, the resulting string will also
2368 have them, if PROPS is nonzero.
2370 We don't want to use plain old make_string here, because it calls
2371 make_uninit_string, which can cause the buffer arena to be
2372 compacted. make_string has no way of knowing that the data has
2373 been moved, and thus copies the wrong data into the string. This
2374 doesn't effect most of the other users of make_string, so it should
2375 be left as is. But we should use this function when conjuring
2376 buffer substrings. */
2378 Lisp_Object
2379 make_buffer_string (start, end, props)
2380 int start, end;
2381 int props;
2383 int start_byte = CHAR_TO_BYTE (start);
2384 int end_byte = CHAR_TO_BYTE (end);
2386 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2389 /* Return a Lisp_String containing the text of the current buffer from
2390 START / START_BYTE to END / END_BYTE.
2392 If text properties are in use and the current buffer
2393 has properties in the range specified, the resulting string will also
2394 have them, if PROPS is nonzero.
2396 We don't want to use plain old make_string here, because it calls
2397 make_uninit_string, which can cause the buffer arena to be
2398 compacted. make_string has no way of knowing that the data has
2399 been moved, and thus copies the wrong data into the string. This
2400 doesn't effect most of the other users of make_string, so it should
2401 be left as is. But we should use this function when conjuring
2402 buffer substrings. */
2404 Lisp_Object
2405 make_buffer_string_both (start, start_byte, end, end_byte, props)
2406 int start, start_byte, end, end_byte;
2407 int props;
2409 Lisp_Object result, tem, tem1;
2411 if (start < GPT && GPT < end)
2412 move_gap (start);
2414 if (! NILP (current_buffer->enable_multibyte_characters))
2415 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2416 else
2417 result = make_uninit_string (end - start);
2418 bcopy (BYTE_POS_ADDR (start_byte), SDATA (result),
2419 end_byte - start_byte);
2421 /* If desired, update and copy the text properties. */
2422 if (props)
2424 update_buffer_properties (start, end);
2426 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2427 tem1 = Ftext_properties_at (make_number (start), Qnil);
2429 if (XINT (tem) != end || !NILP (tem1))
2430 copy_intervals_to_string (result, current_buffer, start,
2431 end - start);
2434 return result;
2437 /* Call Vbuffer_access_fontify_functions for the range START ... END
2438 in the current buffer, if necessary. */
2440 static void
2441 update_buffer_properties (start, end)
2442 int start, end;
2444 /* If this buffer has some access functions,
2445 call them, specifying the range of the buffer being accessed. */
2446 if (!NILP (Vbuffer_access_fontify_functions))
2448 Lisp_Object args[3];
2449 Lisp_Object tem;
2451 args[0] = Qbuffer_access_fontify_functions;
2452 XSETINT (args[1], start);
2453 XSETINT (args[2], end);
2455 /* But don't call them if we can tell that the work
2456 has already been done. */
2457 if (!NILP (Vbuffer_access_fontified_property))
2459 tem = Ftext_property_any (args[1], args[2],
2460 Vbuffer_access_fontified_property,
2461 Qnil, Qnil);
2462 if (! NILP (tem))
2463 Frun_hook_with_args (3, args);
2465 else
2466 Frun_hook_with_args (3, args);
2470 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2471 doc: /* Return the contents of part of the current buffer as a string.
2472 The two arguments START and END are character positions;
2473 they can be in either order.
2474 The string returned is multibyte if the buffer is multibyte.
2476 This function copies the text properties of that part of the buffer
2477 into the result string; if you don't want the text properties,
2478 use `buffer-substring-no-properties' instead. */)
2479 (start, end)
2480 Lisp_Object start, end;
2482 register int b, e;
2484 validate_region (&start, &end);
2485 b = XINT (start);
2486 e = XINT (end);
2488 return make_buffer_string (b, e, 1);
2491 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2492 Sbuffer_substring_no_properties, 2, 2, 0,
2493 doc: /* Return the characters of part of the buffer, without the text properties.
2494 The two arguments START and END are character positions;
2495 they can be in either order. */)
2496 (start, end)
2497 Lisp_Object start, end;
2499 register int b, e;
2501 validate_region (&start, &end);
2502 b = XINT (start);
2503 e = XINT (end);
2505 return make_buffer_string (b, e, 0);
2508 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2509 doc: /* Return the contents of the current buffer as a string.
2510 If narrowing is in effect, this function returns only the visible part
2511 of the buffer. */)
2514 return make_buffer_string (BEGV, ZV, 1);
2517 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2518 1, 3, 0,
2519 doc: /* Insert before point a substring of the contents of BUFFER.
2520 BUFFER may be a buffer or a buffer name.
2521 Arguments START and END are character positions specifying the substring.
2522 They default to the values of (point-min) and (point-max) in BUFFER. */)
2523 (buffer, start, end)
2524 Lisp_Object buffer, start, end;
2526 register int b, e, temp;
2527 register struct buffer *bp, *obuf;
2528 Lisp_Object buf;
2530 buf = Fget_buffer (buffer);
2531 if (NILP (buf))
2532 nsberror (buffer);
2533 bp = XBUFFER (buf);
2534 if (NILP (bp->name))
2535 error ("Selecting deleted buffer");
2537 if (NILP (start))
2538 b = BUF_BEGV (bp);
2539 else
2541 CHECK_NUMBER_COERCE_MARKER (start);
2542 b = XINT (start);
2544 if (NILP (end))
2545 e = BUF_ZV (bp);
2546 else
2548 CHECK_NUMBER_COERCE_MARKER (end);
2549 e = XINT (end);
2552 if (b > e)
2553 temp = b, b = e, e = temp;
2555 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2556 args_out_of_range (start, end);
2558 obuf = current_buffer;
2559 set_buffer_internal_1 (bp);
2560 update_buffer_properties (b, e);
2561 set_buffer_internal_1 (obuf);
2563 insert_from_buffer (bp, b, e - b, 0);
2564 return Qnil;
2567 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2568 6, 6, 0,
2569 doc: /* Compare two substrings of two buffers; return result as number.
2570 the value is -N if first string is less after N-1 chars,
2571 +N if first string is greater after N-1 chars, or 0 if strings match.
2572 Each substring is represented as three arguments: BUFFER, START and END.
2573 That makes six args in all, three for each substring.
2575 The value of `case-fold-search' in the current buffer
2576 determines whether case is significant or ignored. */)
2577 (buffer1, start1, end1, buffer2, start2, end2)
2578 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
2580 register int begp1, endp1, begp2, endp2, temp;
2581 register struct buffer *bp1, *bp2;
2582 register Lisp_Object trt
2583 = (!NILP (current_buffer->case_fold_search)
2584 ? current_buffer->case_canon_table : Qnil);
2585 int chars = 0;
2586 int i1, i2, i1_byte, i2_byte;
2588 /* Find the first buffer and its substring. */
2590 if (NILP (buffer1))
2591 bp1 = current_buffer;
2592 else
2594 Lisp_Object buf1;
2595 buf1 = Fget_buffer (buffer1);
2596 if (NILP (buf1))
2597 nsberror (buffer1);
2598 bp1 = XBUFFER (buf1);
2599 if (NILP (bp1->name))
2600 error ("Selecting deleted buffer");
2603 if (NILP (start1))
2604 begp1 = BUF_BEGV (bp1);
2605 else
2607 CHECK_NUMBER_COERCE_MARKER (start1);
2608 begp1 = XINT (start1);
2610 if (NILP (end1))
2611 endp1 = BUF_ZV (bp1);
2612 else
2614 CHECK_NUMBER_COERCE_MARKER (end1);
2615 endp1 = XINT (end1);
2618 if (begp1 > endp1)
2619 temp = begp1, begp1 = endp1, endp1 = temp;
2621 if (!(BUF_BEGV (bp1) <= begp1
2622 && begp1 <= endp1
2623 && endp1 <= BUF_ZV (bp1)))
2624 args_out_of_range (start1, end1);
2626 /* Likewise for second substring. */
2628 if (NILP (buffer2))
2629 bp2 = current_buffer;
2630 else
2632 Lisp_Object buf2;
2633 buf2 = Fget_buffer (buffer2);
2634 if (NILP (buf2))
2635 nsberror (buffer2);
2636 bp2 = XBUFFER (buf2);
2637 if (NILP (bp2->name))
2638 error ("Selecting deleted buffer");
2641 if (NILP (start2))
2642 begp2 = BUF_BEGV (bp2);
2643 else
2645 CHECK_NUMBER_COERCE_MARKER (start2);
2646 begp2 = XINT (start2);
2648 if (NILP (end2))
2649 endp2 = BUF_ZV (bp2);
2650 else
2652 CHECK_NUMBER_COERCE_MARKER (end2);
2653 endp2 = XINT (end2);
2656 if (begp2 > endp2)
2657 temp = begp2, begp2 = endp2, endp2 = temp;
2659 if (!(BUF_BEGV (bp2) <= begp2
2660 && begp2 <= endp2
2661 && endp2 <= BUF_ZV (bp2)))
2662 args_out_of_range (start2, end2);
2664 i1 = begp1;
2665 i2 = begp2;
2666 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2667 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2669 while (i1 < endp1 && i2 < endp2)
2671 /* When we find a mismatch, we must compare the
2672 characters, not just the bytes. */
2673 int c1, c2;
2675 QUIT;
2677 if (! NILP (bp1->enable_multibyte_characters))
2679 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2680 BUF_INC_POS (bp1, i1_byte);
2681 i1++;
2683 else
2685 c1 = BUF_FETCH_BYTE (bp1, i1);
2686 c1 = unibyte_char_to_multibyte (c1);
2687 i1++;
2690 if (! NILP (bp2->enable_multibyte_characters))
2692 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2693 BUF_INC_POS (bp2, i2_byte);
2694 i2++;
2696 else
2698 c2 = BUF_FETCH_BYTE (bp2, i2);
2699 c2 = unibyte_char_to_multibyte (c2);
2700 i2++;
2703 if (!NILP (trt))
2705 c1 = CHAR_TABLE_TRANSLATE (trt, c1);
2706 c2 = CHAR_TABLE_TRANSLATE (trt, c2);
2708 if (c1 < c2)
2709 return make_number (- 1 - chars);
2710 if (c1 > c2)
2711 return make_number (chars + 1);
2713 chars++;
2716 /* The strings match as far as they go.
2717 If one is shorter, that one is less. */
2718 if (chars < endp1 - begp1)
2719 return make_number (chars + 1);
2720 else if (chars < endp2 - begp2)
2721 return make_number (- chars - 1);
2723 /* Same length too => they are equal. */
2724 return make_number (0);
2727 static Lisp_Object
2728 subst_char_in_region_unwind (arg)
2729 Lisp_Object arg;
2731 return current_buffer->undo_list = arg;
2734 static Lisp_Object
2735 subst_char_in_region_unwind_1 (arg)
2736 Lisp_Object arg;
2738 return current_buffer->filename = arg;
2741 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2742 Ssubst_char_in_region, 4, 5, 0,
2743 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
2744 If optional arg NOUNDO is non-nil, don't record this change for undo
2745 and don't mark the buffer as really changed.
2746 Both characters must have the same length of multi-byte form. */)
2747 (start, end, fromchar, tochar, noundo)
2748 Lisp_Object start, end, fromchar, tochar, noundo;
2750 register int pos, pos_byte, stop, i, len, end_byte;
2751 /* Keep track of the first change in the buffer:
2752 if 0 we haven't found it yet.
2753 if < 0 we've found it and we've run the before-change-function.
2754 if > 0 we've actually performed it and the value is its position. */
2755 int changed = 0;
2756 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2757 unsigned char *p;
2758 int count = SPECPDL_INDEX ();
2759 #define COMBINING_NO 0
2760 #define COMBINING_BEFORE 1
2761 #define COMBINING_AFTER 2
2762 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2763 int maybe_byte_combining = COMBINING_NO;
2764 int last_changed = 0;
2765 int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
2767 restart:
2769 validate_region (&start, &end);
2770 CHECK_NUMBER (fromchar);
2771 CHECK_NUMBER (tochar);
2773 if (multibyte_p)
2775 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2776 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
2777 error ("Characters in `subst-char-in-region' have different byte-lengths");
2778 if (!ASCII_BYTE_P (*tostr))
2780 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2781 complete multibyte character, it may be combined with the
2782 after bytes. If it is in the range 0xA0..0xFF, it may be
2783 combined with the before and after bytes. */
2784 if (!CHAR_HEAD_P (*tostr))
2785 maybe_byte_combining = COMBINING_BOTH;
2786 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2787 maybe_byte_combining = COMBINING_AFTER;
2790 else
2792 len = 1;
2793 fromstr[0] = XFASTINT (fromchar);
2794 tostr[0] = XFASTINT (tochar);
2797 pos = XINT (start);
2798 pos_byte = CHAR_TO_BYTE (pos);
2799 stop = CHAR_TO_BYTE (XINT (end));
2800 end_byte = stop;
2802 /* If we don't want undo, turn off putting stuff on the list.
2803 That's faster than getting rid of things,
2804 and it prevents even the entry for a first change.
2805 Also inhibit locking the file. */
2806 if (!changed && !NILP (noundo))
2808 record_unwind_protect (subst_char_in_region_unwind,
2809 current_buffer->undo_list);
2810 current_buffer->undo_list = Qt;
2811 /* Don't do file-locking. */
2812 record_unwind_protect (subst_char_in_region_unwind_1,
2813 current_buffer->filename);
2814 current_buffer->filename = Qnil;
2817 if (pos_byte < GPT_BYTE)
2818 stop = min (stop, GPT_BYTE);
2819 while (1)
2821 int pos_byte_next = pos_byte;
2823 if (pos_byte >= stop)
2825 if (pos_byte >= end_byte) break;
2826 stop = end_byte;
2828 p = BYTE_POS_ADDR (pos_byte);
2829 if (multibyte_p)
2830 INC_POS (pos_byte_next);
2831 else
2832 ++pos_byte_next;
2833 if (pos_byte_next - pos_byte == len
2834 && p[0] == fromstr[0]
2835 && (len == 1
2836 || (p[1] == fromstr[1]
2837 && (len == 2 || (p[2] == fromstr[2]
2838 && (len == 3 || p[3] == fromstr[3]))))))
2840 if (changed < 0)
2841 /* We've already seen this and run the before-change-function;
2842 this time we only need to record the actual position. */
2843 changed = pos;
2844 else if (!changed)
2846 changed = -1;
2847 modify_region (current_buffer, pos, XINT (end), 0);
2849 if (! NILP (noundo))
2851 if (MODIFF - 1 == SAVE_MODIFF)
2852 SAVE_MODIFF++;
2853 if (MODIFF - 1 == current_buffer->auto_save_modified)
2854 current_buffer->auto_save_modified++;
2857 /* The before-change-function may have moved the gap
2858 or even modified the buffer so we should start over. */
2859 goto restart;
2862 /* Take care of the case where the new character
2863 combines with neighboring bytes. */
2864 if (maybe_byte_combining
2865 && (maybe_byte_combining == COMBINING_AFTER
2866 ? (pos_byte_next < Z_BYTE
2867 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2868 : ((pos_byte_next < Z_BYTE
2869 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2870 || (pos_byte > BEG_BYTE
2871 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2873 Lisp_Object tem, string;
2875 struct gcpro gcpro1;
2877 tem = current_buffer->undo_list;
2878 GCPRO1 (tem);
2880 /* Make a multibyte string containing this single character. */
2881 string = make_multibyte_string (tostr, 1, len);
2882 /* replace_range is less efficient, because it moves the gap,
2883 but it handles combining correctly. */
2884 replace_range (pos, pos + 1, string,
2885 0, 0, 1);
2886 pos_byte_next = CHAR_TO_BYTE (pos);
2887 if (pos_byte_next > pos_byte)
2888 /* Before combining happened. We should not increment
2889 POS. So, to cancel the later increment of POS,
2890 decrease it now. */
2891 pos--;
2892 else
2893 INC_POS (pos_byte_next);
2895 if (! NILP (noundo))
2896 current_buffer->undo_list = tem;
2898 UNGCPRO;
2900 else
2902 if (NILP (noundo))
2903 record_change (pos, 1);
2904 for (i = 0; i < len; i++) *p++ = tostr[i];
2906 last_changed = pos + 1;
2908 pos_byte = pos_byte_next;
2909 pos++;
2912 if (changed > 0)
2914 signal_after_change (changed,
2915 last_changed - changed, last_changed - changed);
2916 update_compositions (changed, last_changed, CHECK_ALL);
2919 unbind_to (count, Qnil);
2920 return Qnil;
2924 static Lisp_Object check_translation P_ ((int, int, int, Lisp_Object));
2926 /* Helper function for Ftranslate_region_internal.
2928 Check if a character sequence at POS (POS_BYTE) matches an element
2929 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
2930 element is found, return it. Otherwise return Qnil. */
2932 static Lisp_Object
2933 check_translation (pos, pos_byte, end, val)
2934 int pos, pos_byte, end;
2935 Lisp_Object val;
2937 int buf_size = 16, buf_used = 0;
2938 int *buf = alloca (sizeof (int) * buf_size);
2940 for (; CONSP (val); val = XCDR (val))
2942 Lisp_Object elt;
2943 int len, i;
2945 elt = XCAR (val);
2946 if (! CONSP (elt))
2947 continue;
2948 elt = XCAR (elt);
2949 if (! VECTORP (elt))
2950 continue;
2951 len = ASIZE (elt);
2952 if (len <= end - pos)
2954 for (i = 0; i < len; i++)
2956 if (buf_used <= i)
2958 unsigned char *p = BYTE_POS_ADDR (pos_byte);
2959 int len;
2961 if (buf_used == buf_size)
2963 int *newbuf;
2965 buf_size += 16;
2966 newbuf = alloca (sizeof (int) * buf_size);
2967 memcpy (newbuf, buf, sizeof (int) * buf_used);
2968 buf = newbuf;
2970 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, 0, len);
2971 pos_byte += len;
2973 if (XINT (AREF (elt, i)) != buf[i])
2974 break;
2976 if (i == len)
2977 return XCAR (val);
2980 return Qnil;
2984 DEFUN ("translate-region-internal", Ftranslate_region_internal,
2985 Stranslate_region_internal, 3, 3, 0,
2986 doc: /* Internal use only.
2987 From START to END, translate characters according to TABLE.
2988 TABLE is a string or a char-table; the Nth character in it is the
2989 mapping for the character with code N.
2990 It returns the number of characters changed. */)
2991 (start, end, table)
2992 Lisp_Object start;
2993 Lisp_Object end;
2994 register Lisp_Object table;
2996 register unsigned char *tt; /* Trans table. */
2997 register int nc; /* New character. */
2998 int cnt; /* Number of changes made. */
2999 int size; /* Size of translate table. */
3000 int pos, pos_byte, end_pos;
3001 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
3002 int string_multibyte;
3003 Lisp_Object val;
3005 validate_region (&start, &end);
3006 if (CHAR_TABLE_P (table))
3008 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3009 error ("Not a translation table");
3010 size = MAX_CHAR;
3011 tt = NULL;
3013 else
3015 CHECK_STRING (table);
3017 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3018 table = string_make_unibyte (table);
3019 string_multibyte = SCHARS (table) < SBYTES (table);
3020 size = SBYTES (table);
3021 tt = SDATA (table);
3024 pos = XINT (start);
3025 pos_byte = CHAR_TO_BYTE (pos);
3026 end_pos = XINT (end);
3027 modify_region (current_buffer, pos, end_pos, 0);
3029 cnt = 0;
3030 for (; pos < end_pos; )
3032 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
3033 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3034 int len, str_len;
3035 int oc;
3036 Lisp_Object val;
3038 if (multibyte)
3039 oc = STRING_CHAR_AND_LENGTH (p, MAX_MULTIBYTE_LENGTH, len);
3040 else
3041 oc = *p, len = 1;
3042 if (oc < size)
3044 if (tt)
3046 /* Reload as signal_after_change in last iteration may GC. */
3047 tt = SDATA (table);
3048 if (string_multibyte)
3050 str = tt + string_char_to_byte (table, oc);
3051 nc = STRING_CHAR_AND_LENGTH (str, MAX_MULTIBYTE_LENGTH,
3052 str_len);
3054 else
3056 nc = tt[oc];
3057 if (! ASCII_BYTE_P (nc) && multibyte)
3059 str_len = BYTE8_STRING (nc, buf);
3060 str = buf;
3062 else
3064 str_len = 1;
3065 str = tt + oc;
3069 else
3071 int c;
3073 nc = oc;
3074 val = CHAR_TABLE_REF (table, oc);
3075 if (CHARACTERP (val)
3076 && (c = XINT (val), CHAR_VALID_P (c, 0)))
3078 nc = c;
3079 str_len = CHAR_STRING (nc, buf);
3080 str = buf;
3082 else if (VECTORP (val) || (CONSP (val)))
3084 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3085 where TO is TO-CHAR or [TO-CHAR ...]. */
3086 nc = -1;
3090 if (nc != oc && nc >= 0)
3092 /* Simple one char to one char translation. */
3093 if (len != str_len)
3095 Lisp_Object string;
3097 /* This is less efficient, because it moves the gap,
3098 but it should handle multibyte characters correctly. */
3099 string = make_multibyte_string (str, 1, str_len);
3100 replace_range (pos, pos + 1, string, 1, 0, 1);
3101 len = str_len;
3103 else
3105 record_change (pos, 1);
3106 while (str_len-- > 0)
3107 *p++ = *str++;
3108 signal_after_change (pos, 1, 1);
3109 update_compositions (pos, pos + 1, CHECK_BORDER);
3111 ++cnt;
3113 else if (nc < 0)
3115 Lisp_Object string;
3117 if (CONSP (val))
3119 val = check_translation (pos, pos_byte, end_pos, val);
3120 if (NILP (val))
3122 pos_byte += len;
3123 pos++;
3124 continue;
3126 /* VAL is ([FROM-CHAR ...] . TO). */
3127 len = ASIZE (XCAR (val));
3128 val = XCDR (val);
3130 else
3131 len = 1;
3133 if (VECTORP (val))
3135 int i;
3137 string = Fmake_string (make_number (ASIZE (val)),
3138 AREF (val, 0));
3139 for (i = 1; i < ASIZE (val); i++)
3140 Faset (string, make_number (i), AREF (val, i));
3142 else
3144 string = Fmake_string (make_number (1), val);
3146 replace_range (pos, pos + len, string, 1, 0, 1);
3147 pos_byte += SBYTES (string);
3148 pos += SCHARS (string);
3149 cnt += SCHARS (string);
3150 end_pos += SCHARS (string) - len;
3151 continue;
3154 pos_byte += len;
3155 pos++;
3158 return make_number (cnt);
3161 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3162 doc: /* Delete the text between point and mark.
3164 When called from a program, expects two arguments,
3165 positions (integers or markers) specifying the stretch to be deleted. */)
3166 (start, end)
3167 Lisp_Object start, end;
3169 validate_region (&start, &end);
3170 del_range (XINT (start), XINT (end));
3171 return Qnil;
3174 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3175 Sdelete_and_extract_region, 2, 2, 0,
3176 doc: /* Delete the text between START and END and return it. */)
3177 (start, end)
3178 Lisp_Object start, end;
3180 validate_region (&start, &end);
3181 if (XINT (start) == XINT (end))
3182 return empty_unibyte_string;
3183 return del_range_1 (XINT (start), XINT (end), 1, 1);
3186 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3187 doc: /* Remove restrictions (narrowing) from current buffer.
3188 This allows the buffer's full text to be seen and edited. */)
3191 if (BEG != BEGV || Z != ZV)
3192 current_buffer->clip_changed = 1;
3193 BEGV = BEG;
3194 BEGV_BYTE = BEG_BYTE;
3195 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3196 /* Changing the buffer bounds invalidates any recorded current column. */
3197 invalidate_current_column ();
3198 return Qnil;
3201 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3202 doc: /* Restrict editing in this buffer to the current region.
3203 The rest of the text becomes temporarily invisible and untouchable
3204 but is not deleted; if you save the buffer in a file, the invisible
3205 text is included in the file. \\[widen] makes all visible again.
3206 See also `save-restriction'.
3208 When calling from a program, pass two arguments; positions (integers
3209 or markers) bounding the text that should remain visible. */)
3210 (start, end)
3211 register Lisp_Object start, end;
3213 CHECK_NUMBER_COERCE_MARKER (start);
3214 CHECK_NUMBER_COERCE_MARKER (end);
3216 if (XINT (start) > XINT (end))
3218 Lisp_Object tem;
3219 tem = start; start = end; end = tem;
3222 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3223 args_out_of_range (start, end);
3225 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3226 current_buffer->clip_changed = 1;
3228 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3229 SET_BUF_ZV (current_buffer, XFASTINT (end));
3230 if (PT < XFASTINT (start))
3231 SET_PT (XFASTINT (start));
3232 if (PT > XFASTINT (end))
3233 SET_PT (XFASTINT (end));
3234 /* Changing the buffer bounds invalidates any recorded current column. */
3235 invalidate_current_column ();
3236 return Qnil;
3239 Lisp_Object
3240 save_restriction_save ()
3242 if (BEGV == BEG && ZV == Z)
3243 /* The common case that the buffer isn't narrowed.
3244 We return just the buffer object, which save_restriction_restore
3245 recognizes as meaning `no restriction'. */
3246 return Fcurrent_buffer ();
3247 else
3248 /* We have to save a restriction, so return a pair of markers, one
3249 for the beginning and one for the end. */
3251 Lisp_Object beg, end;
3253 beg = buildmark (BEGV, BEGV_BYTE);
3254 end = buildmark (ZV, ZV_BYTE);
3256 /* END must move forward if text is inserted at its exact location. */
3257 XMARKER(end)->insertion_type = 1;
3259 return Fcons (beg, end);
3263 Lisp_Object
3264 save_restriction_restore (data)
3265 Lisp_Object data;
3267 if (CONSP (data))
3268 /* A pair of marks bounding a saved restriction. */
3270 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3271 struct Lisp_Marker *end = XMARKER (XCDR (data));
3272 struct buffer *buf = beg->buffer; /* END should have the same buffer. */
3274 if (buf /* Verify marker still points to a buffer. */
3275 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3276 /* The restriction has changed from the saved one, so restore
3277 the saved restriction. */
3279 int pt = BUF_PT (buf);
3281 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3282 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3284 if (pt < beg->charpos || pt > end->charpos)
3285 /* The point is outside the new visible range, move it inside. */
3286 SET_BUF_PT_BOTH (buf,
3287 clip_to_bounds (beg->charpos, pt, end->charpos),
3288 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3289 end->bytepos));
3291 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3294 else
3295 /* A buffer, which means that there was no old restriction. */
3297 struct buffer *buf = XBUFFER (data);
3299 if (buf /* Verify marker still points to a buffer. */
3300 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3301 /* The buffer has been narrowed, get rid of the narrowing. */
3303 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3304 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3306 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3310 return Qnil;
3313 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3314 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3315 The buffer's restrictions make parts of the beginning and end invisible.
3316 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3317 This special form, `save-restriction', saves the current buffer's restrictions
3318 when it is entered, and restores them when it is exited.
3319 So any `narrow-to-region' within BODY lasts only until the end of the form.
3320 The old restrictions settings are restored
3321 even in case of abnormal exit (throw or error).
3323 The value returned is the value of the last form in BODY.
3325 Note: if you are using both `save-excursion' and `save-restriction',
3326 use `save-excursion' outermost:
3327 (save-excursion (save-restriction ...))
3329 usage: (save-restriction &rest BODY) */)
3330 (body)
3331 Lisp_Object body;
3333 register Lisp_Object val;
3334 int count = SPECPDL_INDEX ();
3336 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3337 val = Fprogn (body);
3338 return unbind_to (count, val);
3341 /* Buffer for the most recent text displayed by Fmessage_box. */
3342 static char *message_text;
3344 /* Allocated length of that buffer. */
3345 static int message_length;
3347 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3348 doc: /* Display a message at the bottom of the screen.
3349 The message also goes into the `*Messages*' buffer.
3350 \(In keyboard macros, that's all it does.)
3351 Return the message.
3353 The first argument is a format control string, and the rest are data
3354 to be formatted under control of the string. See `format' for details.
3356 Note: Use (message "%s" VALUE) to print the value of expressions and
3357 variables to avoid accidentally interpreting `%' as format specifiers.
3359 If the first argument is nil or the empty string, the function clears
3360 any existing message; this lets the minibuffer contents show. See
3361 also `current-message'.
3363 usage: (message FORMAT-STRING &rest ARGS) */)
3364 (nargs, args)
3365 int nargs;
3366 Lisp_Object *args;
3368 if (NILP (args[0])
3369 || (STRINGP (args[0])
3370 && SBYTES (args[0]) == 0))
3372 message (0);
3373 return args[0];
3375 else
3377 register Lisp_Object val;
3378 val = Fformat (nargs, args);
3379 message3 (val, SBYTES (val), STRING_MULTIBYTE (val));
3380 return val;
3384 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3385 doc: /* Display a message, in a dialog box if possible.
3386 If a dialog box is not available, use the echo area.
3387 The first argument is a format control string, and the rest are data
3388 to be formatted under control of the string. See `format' for details.
3390 If the first argument is nil or the empty string, clear any existing
3391 message; let the minibuffer contents show.
3393 usage: (message-box FORMAT-STRING &rest ARGS) */)
3394 (nargs, args)
3395 int nargs;
3396 Lisp_Object *args;
3398 if (NILP (args[0]))
3400 message (0);
3401 return Qnil;
3403 else
3405 register Lisp_Object val;
3406 val = Fformat (nargs, args);
3407 #ifdef HAVE_MENUS
3408 /* The MS-DOS frames support popup menus even though they are
3409 not FRAME_WINDOW_P. */
3410 if (FRAME_WINDOW_P (XFRAME (selected_frame))
3411 || FRAME_MSDOS_P (XFRAME (selected_frame)))
3413 Lisp_Object pane, menu, obj;
3414 struct gcpro gcpro1;
3415 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
3416 GCPRO1 (pane);
3417 menu = Fcons (val, pane);
3418 obj = Fx_popup_dialog (Qt, menu, Qt);
3419 UNGCPRO;
3420 return val;
3422 #endif /* HAVE_MENUS */
3423 /* Copy the data so that it won't move when we GC. */
3424 if (! message_text)
3426 message_text = (char *)xmalloc (80);
3427 message_length = 80;
3429 if (SBYTES (val) > message_length)
3431 message_length = SBYTES (val);
3432 message_text = (char *)xrealloc (message_text, message_length);
3434 bcopy (SDATA (val), message_text, SBYTES (val));
3435 message2 (message_text, SBYTES (val),
3436 STRING_MULTIBYTE (val));
3437 return val;
3440 #ifdef HAVE_MENUS
3441 extern Lisp_Object last_nonmenu_event;
3442 #endif
3444 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3445 doc: /* Display a message in a dialog box or in the echo area.
3446 If this command was invoked with the mouse, use a dialog box if
3447 `use-dialog-box' is non-nil.
3448 Otherwise, use the echo area.
3449 The first argument is a format control string, and the rest are data
3450 to be formatted under control of the string. See `format' for details.
3452 If the first argument is nil or the empty string, clear any existing
3453 message; let the minibuffer contents show.
3455 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3456 (nargs, args)
3457 int nargs;
3458 Lisp_Object *args;
3460 #ifdef HAVE_MENUS
3461 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3462 && use_dialog_box)
3463 return Fmessage_box (nargs, args);
3464 #endif
3465 return Fmessage (nargs, args);
3468 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3469 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3472 return current_message ();
3476 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3477 doc: /* Return a copy of STRING with text properties added.
3478 First argument is the string to copy.
3479 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3480 properties to add to the result.
3481 usage: (propertize STRING &rest PROPERTIES) */)
3482 (nargs, args)
3483 int nargs;
3484 Lisp_Object *args;
3486 Lisp_Object properties, string;
3487 struct gcpro gcpro1, gcpro2;
3488 int i;
3490 /* Number of args must be odd. */
3491 if ((nargs & 1) == 0 || nargs < 1)
3492 error ("Wrong number of arguments");
3494 properties = string = Qnil;
3495 GCPRO2 (properties, string);
3497 /* First argument must be a string. */
3498 CHECK_STRING (args[0]);
3499 string = Fcopy_sequence (args[0]);
3501 for (i = 1; i < nargs; i += 2)
3502 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3504 Fadd_text_properties (make_number (0),
3505 make_number (SCHARS (string)),
3506 properties, string);
3507 RETURN_UNGCPRO (string);
3511 /* Number of bytes that STRING will occupy when put into the result.
3512 MULTIBYTE is nonzero if the result should be multibyte. */
3514 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3515 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
3516 ? count_size_as_multibyte (SDATA (STRING), SBYTES (STRING)) \
3517 : SBYTES (STRING))
3519 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3520 doc: /* Format a string out of a format-string and arguments.
3521 The first argument is a format control string.
3522 The other arguments are substituted into it to make the result, a string.
3524 The format control string may contain %-sequences meaning to substitute
3525 the next available argument:
3527 %s means print a string argument. Actually, prints any object, with `princ'.
3528 %d means print as number in decimal (%o octal, %x hex).
3529 %X is like %x, but uses upper case.
3530 %e means print a number in exponential notation.
3531 %f means print a number in decimal-point notation.
3532 %g means print a number in exponential notation
3533 or decimal-point notation, whichever uses fewer characters.
3534 %c means print a number as a single character.
3535 %S means print any object as an s-expression (using `prin1').
3537 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3538 Use %% to put a single % into the output.
3540 A %-sequence may contain optional flag, width, and precision
3541 specifiers, as follows:
3543 %<flags><width><precision>character
3545 where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3547 The + flag character inserts a + before any positive number, while a
3548 space inserts a space before any positive number; these flags only
3549 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3550 The # flag means to use an alternate display form for %o, %x, %X, %e,
3551 %f, and %g sequences. The - and 0 flags affect the width specifier,
3552 as described below.
3554 The width specifier supplies a lower limit for the length of the
3555 printed representation. The padding, if any, normally goes on the
3556 left, but it goes on the right if the - flag is present. The padding
3557 character is normally a space, but it is 0 if the 0 flag is present.
3558 The - flag takes precedence over the 0 flag.
3560 For %e, %f, and %g sequences, the number after the "." in the
3561 precision specifier says how many decimal places to show; if zero, the
3562 decimal point itself is omitted. For %s and %S, the precision
3563 specifier truncates the string to the given width.
3565 usage: (format STRING &rest OBJECTS) */)
3566 (nargs, args)
3567 int nargs;
3568 register Lisp_Object *args;
3570 register int n; /* The number of the next arg to substitute */
3571 register int total; /* An estimate of the final length */
3572 char *buf, *p;
3573 register unsigned char *format, *end, *format_start;
3574 int nchars;
3575 /* Nonzero if the output should be a multibyte string,
3576 which is true if any of the inputs is one. */
3577 int multibyte = 0;
3578 /* When we make a multibyte string, we must pay attention to the
3579 byte combining problem, i.e., a byte may be combined with a
3580 multibyte charcter of the previous string. This flag tells if we
3581 must consider such a situation or not. */
3582 int maybe_combine_byte;
3583 unsigned char *this_format;
3584 /* Precision for each spec, or -1, a flag value meaning no precision
3585 was given in that spec. Element 0, corresonding to the format
3586 string itself, will not be used. Element NARGS, corresponding to
3587 no argument, *will* be assigned to in the case that a `%' and `.'
3588 occur after the final format specifier. */
3589 int *precision = (int *) (alloca((nargs + 1) * sizeof (int)));
3590 int longest_format;
3591 Lisp_Object val;
3592 int arg_intervals = 0;
3593 USE_SAFE_ALLOCA;
3595 /* discarded[I] is 1 if byte I of the format
3596 string was not copied into the output.
3597 It is 2 if byte I was not the first byte of its character. */
3598 char *discarded = 0;
3600 /* Each element records, for one argument,
3601 the start and end bytepos in the output string,
3602 and whether the argument is a string with intervals.
3603 info[0] is unused. Unused elements have -1 for start. */
3604 struct info
3606 int start, end, intervals;
3607 } *info = 0;
3609 /* It should not be necessary to GCPRO ARGS, because
3610 the caller in the interpreter should take care of that. */
3612 /* Try to determine whether the result should be multibyte.
3613 This is not always right; sometimes the result needs to be multibyte
3614 because of an object that we will pass through prin1,
3615 and in that case, we won't know it here. */
3616 for (n = 0; n < nargs; n++)
3618 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3619 multibyte = 1;
3620 /* Piggyback on this loop to initialize precision[N]. */
3621 precision[n] = -1;
3623 precision[nargs] = -1;
3625 CHECK_STRING (args[0]);
3626 /* We may have to change "%S" to "%s". */
3627 args[0] = Fcopy_sequence (args[0]);
3629 /* GC should never happen here, so abort if it does. */
3630 abort_on_gc++;
3632 /* If we start out planning a unibyte result,
3633 then discover it has to be multibyte, we jump back to retry.
3634 That can only happen from the first large while loop below. */
3635 retry:
3637 format = SDATA (args[0]);
3638 format_start = format;
3639 end = format + SBYTES (args[0]);
3640 longest_format = 0;
3642 /* Make room in result for all the non-%-codes in the control string. */
3643 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]) + 1;
3645 /* Allocate the info and discarded tables. */
3647 int nbytes = (nargs+1) * sizeof *info;
3648 int i;
3649 if (!info)
3650 info = (struct info *) alloca (nbytes);
3651 bzero (info, nbytes);
3652 for (i = 0; i <= nargs; i++)
3653 info[i].start = -1;
3654 if (!discarded)
3655 SAFE_ALLOCA (discarded, char *, SBYTES (args[0]));
3656 bzero (discarded, SBYTES (args[0]));
3659 /* Add to TOTAL enough space to hold the converted arguments. */
3661 n = 0;
3662 while (format != end)
3663 if (*format++ == '%')
3665 int thissize = 0;
3666 int actual_width = 0;
3667 unsigned char *this_format_start = format - 1;
3668 int field_width = 0;
3670 /* General format specifications look like
3672 '%' [flags] [field-width] [precision] format
3674 where
3676 flags ::= [-+ #0]+
3677 field-width ::= [0-9]+
3678 precision ::= '.' [0-9]*
3680 If a field-width is specified, it specifies to which width
3681 the output should be padded with blanks, if the output
3682 string is shorter than field-width.
3684 If precision is specified, it specifies the number of
3685 digits to print after the '.' for floats, or the max.
3686 number of chars to print from a string. */
3688 while (format != end
3689 && (*format == '-' || *format == '0' || *format == '#'
3690 || * format == ' ' || *format == '+'))
3691 ++format;
3693 if (*format >= '0' && *format <= '9')
3695 for (field_width = 0; *format >= '0' && *format <= '9'; ++format)
3696 field_width = 10 * field_width + *format - '0';
3699 /* N is not incremented for another few lines below, so refer to
3700 element N+1 (which might be precision[NARGS]). */
3701 if (*format == '.')
3703 ++format;
3704 for (precision[n+1] = 0; *format >= '0' && *format <= '9'; ++format)
3705 precision[n+1] = 10 * precision[n+1] + *format - '0';
3708 /* Extra +1 for 'l' that we may need to insert into the
3709 format. */
3710 if (format - this_format_start + 2 > longest_format)
3711 longest_format = format - this_format_start + 2;
3713 if (format == end)
3714 error ("Format string ends in middle of format specifier");
3715 if (*format == '%')
3716 format++;
3717 else if (++n >= nargs)
3718 error ("Not enough arguments for format string");
3719 else if (*format == 'S')
3721 /* For `S', prin1 the argument and then treat like a string. */
3722 register Lisp_Object tem;
3723 tem = Fprin1_to_string (args[n], Qnil);
3724 if (STRING_MULTIBYTE (tem) && ! multibyte)
3726 multibyte = 1;
3727 goto retry;
3729 args[n] = tem;
3730 /* If we restart the loop, we should not come here again
3731 because args[n] is now a string and calling
3732 Fprin1_to_string on it produces superflous double
3733 quotes. So, change "%S" to "%s" now. */
3734 *format = 's';
3735 goto string;
3737 else if (SYMBOLP (args[n]))
3739 args[n] = SYMBOL_NAME (args[n]);
3740 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3742 multibyte = 1;
3743 goto retry;
3745 goto string;
3747 else if (STRINGP (args[n]))
3749 string:
3750 if (*format != 's' && *format != 'S')
3751 error ("Format specifier doesn't match argument type");
3752 /* In the case (PRECISION[N] > 0), THISSIZE may not need
3753 to be as large as is calculated here. Easy check for
3754 the case PRECISION = 0. */
3755 thissize = precision[n] ? CONVERTED_BYTE_SIZE (multibyte, args[n]) : 0;
3756 actual_width = lisp_string_width (args[n], -1, NULL, NULL);
3758 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3759 else if (INTEGERP (args[n]) && *format != 's')
3761 /* The following loop assumes the Lisp type indicates
3762 the proper way to pass the argument.
3763 So make sure we have a flonum if the argument should
3764 be a double. */
3765 if (*format == 'e' || *format == 'f' || *format == 'g')
3766 args[n] = Ffloat (args[n]);
3767 else
3768 if (*format != 'd' && *format != 'o' && *format != 'x'
3769 && *format != 'i' && *format != 'X' && *format != 'c')
3770 error ("Invalid format operation %%%c", *format);
3772 thissize = 30 + (precision[n] > 0 ? precision[n] : 0);
3773 if (*format == 'c')
3775 if (! ASCII_CHAR_P (XINT (args[n]))
3776 /* Note: No one can remeber why we have to treat
3777 the character 0 as a multibyte character here.
3778 But, until it causes a real problem, let's
3779 don't change it. */
3780 || XINT (args[n]) == 0)
3782 if (! multibyte)
3784 multibyte = 1;
3785 goto retry;
3787 args[n] = Fchar_to_string (args[n]);
3788 thissize = SBYTES (args[n]);
3790 else if (! ASCII_BYTE_P (XINT (args[n])) && multibyte)
3792 args[n]
3793 = Fchar_to_string (Funibyte_char_to_multibyte (args[n]));
3794 thissize = SBYTES (args[n]);
3798 else if (FLOATP (args[n]) && *format != 's')
3800 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3802 if (*format != 'd' && *format != 'o' && *format != 'x'
3803 && *format != 'i' && *format != 'X' && *format != 'c')
3804 error ("Invalid format operation %%%c", *format);
3805 /* This fails unnecessarily if args[n] is bigger than
3806 most-positive-fixnum but smaller than MAXINT.
3807 These cases are important because we sometimes use floats
3808 to represent such integer values (typically such values
3809 come from UIDs or PIDs). */
3810 /* args[n] = Ftruncate (args[n], Qnil); */
3813 /* Note that we're using sprintf to print floats,
3814 so we have to take into account what that function
3815 prints. */
3816 /* Filter out flag value of -1. */
3817 thissize = (MAX_10_EXP + 100
3818 + (precision[n] > 0 ? precision[n] : 0));
3820 else
3822 /* Anything but a string, convert to a string using princ. */
3823 register Lisp_Object tem;
3824 tem = Fprin1_to_string (args[n], Qt);
3825 if (STRING_MULTIBYTE (tem) && ! multibyte)
3827 multibyte = 1;
3828 goto retry;
3830 args[n] = tem;
3831 goto string;
3834 thissize += max (0, field_width - actual_width);
3835 total += thissize + 4;
3838 abort_on_gc--;
3840 /* Now we can no longer jump to retry.
3841 TOTAL and LONGEST_FORMAT are known for certain. */
3843 this_format = (unsigned char *) alloca (longest_format + 1);
3845 /* Allocate the space for the result.
3846 Note that TOTAL is an overestimate. */
3847 SAFE_ALLOCA (buf, char *, total);
3849 p = buf;
3850 nchars = 0;
3851 n = 0;
3853 /* Scan the format and store result in BUF. */
3854 format = SDATA (args[0]);
3855 format_start = format;
3856 end = format + SBYTES (args[0]);
3857 maybe_combine_byte = 0;
3858 while (format != end)
3860 if (*format == '%')
3862 int minlen;
3863 int negative = 0;
3864 unsigned char *this_format_start = format;
3866 discarded[format - format_start] = 1;
3867 format++;
3869 while (index("-+0# ", *format))
3871 if (*format == '-')
3873 negative = 1;
3875 discarded[format - format_start] = 1;
3876 ++format;
3879 minlen = atoi (format);
3881 while ((*format >= '0' && *format <= '9') || *format == '.')
3883 discarded[format - format_start] = 1;
3884 format++;
3887 if (*format++ == '%')
3889 *p++ = '%';
3890 nchars++;
3891 continue;
3894 ++n;
3896 discarded[format - format_start - 1] = 1;
3897 info[n].start = nchars;
3899 if (STRINGP (args[n]))
3901 /* handle case (precision[n] >= 0) */
3903 int width, padding;
3904 int nbytes, start, end;
3905 int nchars_string;
3907 /* lisp_string_width ignores a precision of 0, but GNU
3908 libc functions print 0 characters when the precision
3909 is 0. Imitate libc behavior here. Changing
3910 lisp_string_width is the right thing, and will be
3911 done, but meanwhile we work with it. */
3913 if (precision[n] == 0)
3914 width = nchars_string = nbytes = 0;
3915 else if (precision[n] > 0)
3916 width = lisp_string_width (args[n], precision[n], &nchars_string, &nbytes);
3917 else
3918 { /* no precision spec given for this argument */
3919 width = lisp_string_width (args[n], -1, NULL, NULL);
3920 nbytes = SBYTES (args[n]);
3921 nchars_string = SCHARS (args[n]);
3924 /* If spec requires it, pad on right with spaces. */
3925 padding = minlen - width;
3926 if (! negative)
3927 while (padding-- > 0)
3929 *p++ = ' ';
3930 ++nchars;
3933 info[n].start = start = nchars;
3934 nchars += nchars_string;
3935 end = nchars;
3937 if (p > buf
3938 && multibyte
3939 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3940 && STRING_MULTIBYTE (args[n])
3941 && !CHAR_HEAD_P (SREF (args[n], 0)))
3942 maybe_combine_byte = 1;
3944 p += copy_text (SDATA (args[n]), p,
3945 nbytes,
3946 STRING_MULTIBYTE (args[n]), multibyte);
3948 info[n].end = nchars;
3950 if (negative)
3951 while (padding-- > 0)
3953 *p++ = ' ';
3954 nchars++;
3957 /* If this argument has text properties, record where
3958 in the result string it appears. */
3959 if (STRING_INTERVALS (args[n]))
3960 info[n].intervals = arg_intervals = 1;
3962 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3964 int this_nchars;
3966 bcopy (this_format_start, this_format,
3967 format - this_format_start);
3968 this_format[format - this_format_start] = 0;
3970 if (format[-1] == 'e' || format[-1] == 'f' || format[-1] == 'g')
3971 sprintf (p, this_format, XFLOAT_DATA (args[n]));
3972 else
3974 if (sizeof (EMACS_INT) > sizeof (int)
3975 && format[-1] != 'c')
3977 /* Insert 'l' before format spec. */
3978 this_format[format - this_format_start]
3979 = this_format[format - this_format_start - 1];
3980 this_format[format - this_format_start - 1] = 'l';
3981 this_format[format - this_format_start + 1] = 0;
3984 if (INTEGERP (args[n]))
3986 if (format[-1] == 'c')
3987 sprintf (p, this_format, (int) XINT (args[n]));
3988 else if (format[-1] == 'd')
3989 sprintf (p, this_format, XINT (args[n]));
3990 /* Don't sign-extend for octal or hex printing. */
3991 else
3992 sprintf (p, this_format, XUINT (args[n]));
3994 else if (format[-1] == 'c')
3995 sprintf (p, this_format, (int) XFLOAT_DATA (args[n]));
3996 else if (format[-1] == 'd')
3997 /* Maybe we should use "%1.0f" instead so it also works
3998 for values larger than MAXINT. */
3999 sprintf (p, this_format, (EMACS_INT) XFLOAT_DATA (args[n]));
4000 else
4001 /* Don't sign-extend for octal or hex printing. */
4002 sprintf (p, this_format, (EMACS_UINT) XFLOAT_DATA (args[n]));
4005 if (p > buf
4006 && multibyte
4007 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4008 && !CHAR_HEAD_P (*((unsigned char *) p)))
4009 maybe_combine_byte = 1;
4010 this_nchars = strlen (p);
4011 if (multibyte)
4012 p += str_to_multibyte (p, buf + total - 1 - p, this_nchars);
4013 else
4014 p += this_nchars;
4015 nchars += this_nchars;
4016 info[n].end = nchars;
4020 else if (STRING_MULTIBYTE (args[0]))
4022 /* Copy a whole multibyte character. */
4023 if (p > buf
4024 && multibyte
4025 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4026 && !CHAR_HEAD_P (*format))
4027 maybe_combine_byte = 1;
4028 *p++ = *format++;
4029 while (! CHAR_HEAD_P (*format))
4031 discarded[format - format_start] = 2;
4032 *p++ = *format++;
4034 nchars++;
4036 else if (multibyte)
4038 /* Convert a single-byte character to multibyte. */
4039 int len = copy_text (format, p, 1, 0, 1);
4041 p += len;
4042 format++;
4043 nchars++;
4045 else
4046 *p++ = *format++, nchars++;
4049 if (p > buf + total)
4050 abort ();
4052 if (maybe_combine_byte)
4053 nchars = multibyte_chars_in_text (buf, p - buf);
4054 val = make_specified_string (buf, nchars, p - buf, multibyte);
4056 /* If we allocated BUF with malloc, free it too. */
4057 SAFE_FREE ();
4059 /* If the format string has text properties, or any of the string
4060 arguments has text properties, set up text properties of the
4061 result string. */
4063 if (STRING_INTERVALS (args[0]) || arg_intervals)
4065 Lisp_Object len, new_len, props;
4066 struct gcpro gcpro1;
4068 /* Add text properties from the format string. */
4069 len = make_number (SCHARS (args[0]));
4070 props = text_property_list (args[0], make_number (0), len, Qnil);
4071 GCPRO1 (props);
4073 if (CONSP (props))
4075 int bytepos = 0, position = 0, translated = 0, argn = 1;
4076 Lisp_Object list;
4078 /* Adjust the bounds of each text property
4079 to the proper start and end in the output string. */
4081 /* Put the positions in PROPS in increasing order, so that
4082 we can do (effectively) one scan through the position
4083 space of the format string. */
4084 props = Fnreverse (props);
4086 /* BYTEPOS is the byte position in the format string,
4087 POSITION is the untranslated char position in it,
4088 TRANSLATED is the translated char position in BUF,
4089 and ARGN is the number of the next arg we will come to. */
4090 for (list = props; CONSP (list); list = XCDR (list))
4092 Lisp_Object item;
4093 int pos;
4095 item = XCAR (list);
4097 /* First adjust the property start position. */
4098 pos = XINT (XCAR (item));
4100 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4101 up to this position. */
4102 for (; position < pos; bytepos++)
4104 if (! discarded[bytepos])
4105 position++, translated++;
4106 else if (discarded[bytepos] == 1)
4108 position++;
4109 if (translated == info[argn].start)
4111 translated += info[argn].end - info[argn].start;
4112 argn++;
4117 XSETCAR (item, make_number (translated));
4119 /* Likewise adjust the property end position. */
4120 pos = XINT (XCAR (XCDR (item)));
4122 for (; position < pos; bytepos++)
4124 if (! discarded[bytepos])
4125 position++, translated++;
4126 else if (discarded[bytepos] == 1)
4128 position++;
4129 if (translated == info[argn].start)
4131 translated += info[argn].end - info[argn].start;
4132 argn++;
4137 XSETCAR (XCDR (item), make_number (translated));
4140 add_text_properties_from_list (val, props, make_number (0));
4143 /* Add text properties from arguments. */
4144 if (arg_intervals)
4145 for (n = 1; n < nargs; ++n)
4146 if (info[n].intervals)
4148 len = make_number (SCHARS (args[n]));
4149 new_len = make_number (info[n].end - info[n].start);
4150 props = text_property_list (args[n], make_number (0), len, Qnil);
4151 extend_property_ranges (props, len, new_len);
4152 /* If successive arguments have properites, be sure that
4153 the value of `composition' property be the copy. */
4154 if (n > 1 && info[n - 1].end)
4155 make_composition_value_copy (props);
4156 add_text_properties_from_list (val, props,
4157 make_number (info[n].start));
4160 UNGCPRO;
4163 return val;
4166 Lisp_Object
4167 format2 (string1, arg0, arg1)
4168 char *string1;
4169 Lisp_Object arg0, arg1;
4171 Lisp_Object args[3];
4172 args[0] = build_string (string1);
4173 args[1] = arg0;
4174 args[2] = arg1;
4175 return Fformat (3, args);
4178 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4179 doc: /* Return t if two characters match, optionally ignoring case.
4180 Both arguments must be characters (i.e. integers).
4181 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4182 (c1, c2)
4183 register Lisp_Object c1, c2;
4185 int i1, i2;
4186 /* Check they're chars, not just integers, otherwise we could get array
4187 bounds violations in DOWNCASE. */
4188 CHECK_CHARACTER (c1);
4189 CHECK_CHARACTER (c2);
4191 if (XINT (c1) == XINT (c2))
4192 return Qt;
4193 if (NILP (current_buffer->case_fold_search))
4194 return Qnil;
4196 /* Do these in separate statements,
4197 then compare the variables.
4198 because of the way DOWNCASE uses temp variables. */
4199 i1 = XFASTINT (c1);
4200 if (NILP (current_buffer->enable_multibyte_characters)
4201 && ! ASCII_CHAR_P (i1))
4203 MAKE_CHAR_MULTIBYTE (i1);
4205 i2 = XFASTINT (c2);
4206 if (NILP (current_buffer->enable_multibyte_characters)
4207 && ! ASCII_CHAR_P (i2))
4209 MAKE_CHAR_MULTIBYTE (i2);
4211 i1 = DOWNCASE (i1);
4212 i2 = DOWNCASE (i2);
4213 return (i1 == i2 ? Qt : Qnil);
4216 /* Transpose the markers in two regions of the current buffer, and
4217 adjust the ones between them if necessary (i.e.: if the regions
4218 differ in size).
4220 START1, END1 are the character positions of the first region.
4221 START1_BYTE, END1_BYTE are the byte positions.
4222 START2, END2 are the character positions of the second region.
4223 START2_BYTE, END2_BYTE are the byte positions.
4225 Traverses the entire marker list of the buffer to do so, adding an
4226 appropriate amount to some, subtracting from some, and leaving the
4227 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4229 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4231 static void
4232 transpose_markers (start1, end1, start2, end2,
4233 start1_byte, end1_byte, start2_byte, end2_byte)
4234 register int start1, end1, start2, end2;
4235 register int start1_byte, end1_byte, start2_byte, end2_byte;
4237 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4238 register struct Lisp_Marker *marker;
4240 /* Update point as if it were a marker. */
4241 if (PT < start1)
4243 else if (PT < end1)
4244 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4245 PT_BYTE + (end2_byte - end1_byte));
4246 else if (PT < start2)
4247 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4248 (PT_BYTE + (end2_byte - start2_byte)
4249 - (end1_byte - start1_byte)));
4250 else if (PT < end2)
4251 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4252 PT_BYTE - (start2_byte - start1_byte));
4254 /* We used to adjust the endpoints here to account for the gap, but that
4255 isn't good enough. Even if we assume the caller has tried to move the
4256 gap out of our way, it might still be at start1 exactly, for example;
4257 and that places it `inside' the interval, for our purposes. The amount
4258 of adjustment is nontrivial if there's a `denormalized' marker whose
4259 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4260 the dirty work to Fmarker_position, below. */
4262 /* The difference between the region's lengths */
4263 diff = (end2 - start2) - (end1 - start1);
4264 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4266 /* For shifting each marker in a region by the length of the other
4267 region plus the distance between the regions. */
4268 amt1 = (end2 - start2) + (start2 - end1);
4269 amt2 = (end1 - start1) + (start2 - end1);
4270 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4271 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4273 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4275 mpos = marker->bytepos;
4276 if (mpos >= start1_byte && mpos < end2_byte)
4278 if (mpos < end1_byte)
4279 mpos += amt1_byte;
4280 else if (mpos < start2_byte)
4281 mpos += diff_byte;
4282 else
4283 mpos -= amt2_byte;
4284 marker->bytepos = mpos;
4286 mpos = marker->charpos;
4287 if (mpos >= start1 && mpos < end2)
4289 if (mpos < end1)
4290 mpos += amt1;
4291 else if (mpos < start2)
4292 mpos += diff;
4293 else
4294 mpos -= amt2;
4296 marker->charpos = mpos;
4300 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4301 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4302 The regions may not be overlapping, because the size of the buffer is
4303 never changed in a transposition.
4305 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4306 any markers that happen to be located in the regions.
4308 Transposing beyond buffer boundaries is an error. */)
4309 (startr1, endr1, startr2, endr2, leave_markers)
4310 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
4312 register EMACS_INT start1, end1, start2, end2;
4313 EMACS_INT start1_byte, start2_byte, len1_byte, len2_byte;
4314 EMACS_INT gap, len1, len_mid, len2;
4315 unsigned char *start1_addr, *start2_addr, *temp;
4317 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4318 Lisp_Object buf;
4320 XSETBUFFER (buf, current_buffer);
4321 cur_intv = BUF_INTERVALS (current_buffer);
4323 validate_region (&startr1, &endr1);
4324 validate_region (&startr2, &endr2);
4326 start1 = XFASTINT (startr1);
4327 end1 = XFASTINT (endr1);
4328 start2 = XFASTINT (startr2);
4329 end2 = XFASTINT (endr2);
4330 gap = GPT;
4332 /* Swap the regions if they're reversed. */
4333 if (start2 < end1)
4335 register int glumph = start1;
4336 start1 = start2;
4337 start2 = glumph;
4338 glumph = end1;
4339 end1 = end2;
4340 end2 = glumph;
4343 len1 = end1 - start1;
4344 len2 = end2 - start2;
4346 if (start2 < end1)
4347 error ("Transposed regions overlap");
4348 else if (start1 == end1 || start2 == end2)
4349 error ("Transposed region has length 0");
4351 /* The possibilities are:
4352 1. Adjacent (contiguous) regions, or separate but equal regions
4353 (no, really equal, in this case!), or
4354 2. Separate regions of unequal size.
4356 The worst case is usually No. 2. It means that (aside from
4357 potential need for getting the gap out of the way), there also
4358 needs to be a shifting of the text between the two regions. So
4359 if they are spread far apart, we are that much slower... sigh. */
4361 /* It must be pointed out that the really studly thing to do would
4362 be not to move the gap at all, but to leave it in place and work
4363 around it if necessary. This would be extremely efficient,
4364 especially considering that people are likely to do
4365 transpositions near where they are working interactively, which
4366 is exactly where the gap would be found. However, such code
4367 would be much harder to write and to read. So, if you are
4368 reading this comment and are feeling squirrely, by all means have
4369 a go! I just didn't feel like doing it, so I will simply move
4370 the gap the minimum distance to get it out of the way, and then
4371 deal with an unbroken array. */
4373 /* Make sure the gap won't interfere, by moving it out of the text
4374 we will operate on. */
4375 if (start1 < gap && gap < end2)
4377 if (gap - start1 < end2 - gap)
4378 move_gap (start1);
4379 else
4380 move_gap (end2);
4383 start1_byte = CHAR_TO_BYTE (start1);
4384 start2_byte = CHAR_TO_BYTE (start2);
4385 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4386 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
4388 #ifdef BYTE_COMBINING_DEBUG
4389 if (end1 == start2)
4391 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4392 len2_byte, start1, start1_byte)
4393 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4394 len1_byte, end2, start2_byte + len2_byte)
4395 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4396 len1_byte, end2, start2_byte + len2_byte))
4397 abort ();
4399 else
4401 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4402 len2_byte, start1, start1_byte)
4403 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4404 len1_byte, start2, start2_byte)
4405 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4406 len2_byte, end1, start1_byte + len1_byte)
4407 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4408 len1_byte, end2, start2_byte + len2_byte))
4409 abort ();
4411 #endif
4413 /* Hmmm... how about checking to see if the gap is large
4414 enough to use as the temporary storage? That would avoid an
4415 allocation... interesting. Later, don't fool with it now. */
4417 /* Working without memmove, for portability (sigh), so must be
4418 careful of overlapping subsections of the array... */
4420 if (end1 == start2) /* adjacent regions */
4422 modify_region (current_buffer, start1, end2, 0);
4423 record_change (start1, len1 + len2);
4425 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4426 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4427 /* Don't use Fset_text_properties: that can cause GC, which can
4428 clobber objects stored in the tmp_intervals. */
4429 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4430 if (!NULL_INTERVAL_P (tmp_interval3))
4431 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4433 /* First region smaller than second. */
4434 if (len1_byte < len2_byte)
4436 USE_SAFE_ALLOCA;
4438 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4440 /* Don't precompute these addresses. We have to compute them
4441 at the last minute, because the relocating allocator might
4442 have moved the buffer around during the xmalloc. */
4443 start1_addr = BYTE_POS_ADDR (start1_byte);
4444 start2_addr = BYTE_POS_ADDR (start2_byte);
4446 bcopy (start2_addr, temp, len2_byte);
4447 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
4448 bcopy (temp, start1_addr, len2_byte);
4449 SAFE_FREE ();
4451 else
4452 /* First region not smaller than second. */
4454 USE_SAFE_ALLOCA;
4456 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4457 start1_addr = BYTE_POS_ADDR (start1_byte);
4458 start2_addr = BYTE_POS_ADDR (start2_byte);
4459 bcopy (start1_addr, temp, len1_byte);
4460 bcopy (start2_addr, start1_addr, len2_byte);
4461 bcopy (temp, start1_addr + len2_byte, len1_byte);
4462 SAFE_FREE ();
4464 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4465 len1, current_buffer, 0);
4466 graft_intervals_into_buffer (tmp_interval2, start1,
4467 len2, current_buffer, 0);
4468 update_compositions (start1, start1 + len2, CHECK_BORDER);
4469 update_compositions (start1 + len2, end2, CHECK_TAIL);
4471 /* Non-adjacent regions, because end1 != start2, bleagh... */
4472 else
4474 len_mid = start2_byte - (start1_byte + len1_byte);
4476 if (len1_byte == len2_byte)
4477 /* Regions are same size, though, how nice. */
4479 USE_SAFE_ALLOCA;
4481 modify_region (current_buffer, start1, end1, 0);
4482 modify_region (current_buffer, start2, end2, 0);
4483 record_change (start1, len1);
4484 record_change (start2, len2);
4485 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4486 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4488 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4489 if (!NULL_INTERVAL_P (tmp_interval3))
4490 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4492 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4493 if (!NULL_INTERVAL_P (tmp_interval3))
4494 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
4496 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4497 start1_addr = BYTE_POS_ADDR (start1_byte);
4498 start2_addr = BYTE_POS_ADDR (start2_byte);
4499 bcopy (start1_addr, temp, len1_byte);
4500 bcopy (start2_addr, start1_addr, len2_byte);
4501 bcopy (temp, start2_addr, len1_byte);
4502 SAFE_FREE ();
4504 graft_intervals_into_buffer (tmp_interval1, start2,
4505 len1, current_buffer, 0);
4506 graft_intervals_into_buffer (tmp_interval2, start1,
4507 len2, current_buffer, 0);
4510 else if (len1_byte < len2_byte) /* Second region larger than first */
4511 /* Non-adjacent & unequal size, area between must also be shifted. */
4513 USE_SAFE_ALLOCA;
4515 modify_region (current_buffer, start1, end2, 0);
4516 record_change (start1, (end2 - start1));
4517 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4518 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4519 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4521 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4522 if (!NULL_INTERVAL_P (tmp_interval3))
4523 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4525 /* holds region 2 */
4526 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4527 start1_addr = BYTE_POS_ADDR (start1_byte);
4528 start2_addr = BYTE_POS_ADDR (start2_byte);
4529 bcopy (start2_addr, temp, len2_byte);
4530 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
4531 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
4532 bcopy (temp, start1_addr, len2_byte);
4533 SAFE_FREE ();
4535 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4536 len1, current_buffer, 0);
4537 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4538 len_mid, current_buffer, 0);
4539 graft_intervals_into_buffer (tmp_interval2, start1,
4540 len2, current_buffer, 0);
4542 else
4543 /* Second region smaller than first. */
4545 USE_SAFE_ALLOCA;
4547 record_change (start1, (end2 - start1));
4548 modify_region (current_buffer, start1, end2, 0);
4550 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4551 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4552 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4554 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4555 if (!NULL_INTERVAL_P (tmp_interval3))
4556 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4558 /* holds region 1 */
4559 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4560 start1_addr = BYTE_POS_ADDR (start1_byte);
4561 start2_addr = BYTE_POS_ADDR (start2_byte);
4562 bcopy (start1_addr, temp, len1_byte);
4563 bcopy (start2_addr, start1_addr, len2_byte);
4564 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
4565 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
4566 SAFE_FREE ();
4568 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4569 len1, current_buffer, 0);
4570 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4571 len_mid, current_buffer, 0);
4572 graft_intervals_into_buffer (tmp_interval2, start1,
4573 len2, current_buffer, 0);
4576 update_compositions (start1, start1 + len2, CHECK_BORDER);
4577 update_compositions (end2 - len1, end2, CHECK_BORDER);
4580 /* When doing multiple transpositions, it might be nice
4581 to optimize this. Perhaps the markers in any one buffer
4582 should be organized in some sorted data tree. */
4583 if (NILP (leave_markers))
4585 transpose_markers (start1, end1, start2, end2,
4586 start1_byte, start1_byte + len1_byte,
4587 start2_byte, start2_byte + len2_byte);
4588 fix_start_end_in_overlays (start1, end2);
4591 signal_after_change (start1, end2 - start1, end2 - start1);
4592 return Qnil;
4596 void
4597 syms_of_editfns ()
4599 environbuf = 0;
4600 initial_tz = 0;
4602 Qbuffer_access_fontify_functions
4603 = intern ("buffer-access-fontify-functions");
4604 staticpro (&Qbuffer_access_fontify_functions);
4606 DEFVAR_LISP ("inhibit-field-text-motion", &Vinhibit_field_text_motion,
4607 doc: /* Non-nil means text motion commands don't notice fields. */);
4608 Vinhibit_field_text_motion = Qnil;
4610 DEFVAR_LISP ("buffer-access-fontify-functions",
4611 &Vbuffer_access_fontify_functions,
4612 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4613 Each function is called with two arguments which specify the range
4614 of the buffer being accessed. */);
4615 Vbuffer_access_fontify_functions = Qnil;
4618 Lisp_Object obuf;
4619 extern Lisp_Object Vprin1_to_string_buffer;
4620 obuf = Fcurrent_buffer ();
4621 /* Do this here, because init_buffer_once is too early--it won't work. */
4622 Fset_buffer (Vprin1_to_string_buffer);
4623 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4624 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
4625 Qnil);
4626 Fset_buffer (obuf);
4629 DEFVAR_LISP ("buffer-access-fontified-property",
4630 &Vbuffer_access_fontified_property,
4631 doc: /* Property which (if non-nil) indicates text has been fontified.
4632 `buffer-substring' need not call the `buffer-access-fontify-functions'
4633 functions if all the text being accessed has this property. */);
4634 Vbuffer_access_fontified_property = Qnil;
4636 DEFVAR_LISP ("system-name", &Vsystem_name,
4637 doc: /* The host name of the machine Emacs is running on. */);
4639 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
4640 doc: /* The full name of the user logged in. */);
4642 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
4643 doc: /* The user's name, taken from environment variables if possible. */);
4645 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
4646 doc: /* The user's name, based upon the real uid only. */);
4648 DEFVAR_LISP ("operating-system-release", &Voperating_system_release,
4649 doc: /* The release of the operating system Emacs is running on. */);
4651 defsubr (&Spropertize);
4652 defsubr (&Schar_equal);
4653 defsubr (&Sgoto_char);
4654 defsubr (&Sstring_to_char);
4655 defsubr (&Schar_to_string);
4656 defsubr (&Sbuffer_substring);
4657 defsubr (&Sbuffer_substring_no_properties);
4658 defsubr (&Sbuffer_string);
4660 defsubr (&Spoint_marker);
4661 defsubr (&Smark_marker);
4662 defsubr (&Spoint);
4663 defsubr (&Sregion_beginning);
4664 defsubr (&Sregion_end);
4666 staticpro (&Qfield);
4667 Qfield = intern ("field");
4668 staticpro (&Qboundary);
4669 Qboundary = intern ("boundary");
4670 defsubr (&Sfield_beginning);
4671 defsubr (&Sfield_end);
4672 defsubr (&Sfield_string);
4673 defsubr (&Sfield_string_no_properties);
4674 defsubr (&Sdelete_field);
4675 defsubr (&Sconstrain_to_field);
4677 defsubr (&Sline_beginning_position);
4678 defsubr (&Sline_end_position);
4680 /* defsubr (&Smark); */
4681 /* defsubr (&Sset_mark); */
4682 defsubr (&Ssave_excursion);
4683 defsubr (&Ssave_current_buffer);
4685 defsubr (&Sbufsize);
4686 defsubr (&Spoint_max);
4687 defsubr (&Spoint_min);
4688 defsubr (&Spoint_min_marker);
4689 defsubr (&Spoint_max_marker);
4690 defsubr (&Sgap_position);
4691 defsubr (&Sgap_size);
4692 defsubr (&Sposition_bytes);
4693 defsubr (&Sbyte_to_position);
4695 defsubr (&Sbobp);
4696 defsubr (&Seobp);
4697 defsubr (&Sbolp);
4698 defsubr (&Seolp);
4699 defsubr (&Sfollowing_char);
4700 defsubr (&Sprevious_char);
4701 defsubr (&Schar_after);
4702 defsubr (&Schar_before);
4703 defsubr (&Sinsert);
4704 defsubr (&Sinsert_before_markers);
4705 defsubr (&Sinsert_and_inherit);
4706 defsubr (&Sinsert_and_inherit_before_markers);
4707 defsubr (&Sinsert_char);
4708 defsubr (&Sinsert_byte);
4710 defsubr (&Suser_login_name);
4711 defsubr (&Suser_real_login_name);
4712 defsubr (&Suser_uid);
4713 defsubr (&Suser_real_uid);
4714 defsubr (&Suser_full_name);
4715 defsubr (&Semacs_pid);
4716 defsubr (&Scurrent_time);
4717 defsubr (&Sget_internal_run_time);
4718 defsubr (&Sformat_time_string);
4719 defsubr (&Sfloat_time);
4720 defsubr (&Sdecode_time);
4721 defsubr (&Sencode_time);
4722 defsubr (&Scurrent_time_string);
4723 defsubr (&Scurrent_time_zone);
4724 defsubr (&Sset_time_zone_rule);
4725 defsubr (&Ssystem_name);
4726 defsubr (&Smessage);
4727 defsubr (&Smessage_box);
4728 defsubr (&Smessage_or_box);
4729 defsubr (&Scurrent_message);
4730 defsubr (&Sformat);
4732 defsubr (&Sinsert_buffer_substring);
4733 defsubr (&Scompare_buffer_substrings);
4734 defsubr (&Ssubst_char_in_region);
4735 defsubr (&Stranslate_region_internal);
4736 defsubr (&Sdelete_region);
4737 defsubr (&Sdelete_and_extract_region);
4738 defsubr (&Swiden);
4739 defsubr (&Snarrow_to_region);
4740 defsubr (&Ssave_restriction);
4741 defsubr (&Stranspose_regions);
4744 /* arch-tag: fc3827d8-6f60-4067-b11e-c3218031b018
4745 (do not change this comment) */