(Fformat_network_address): Fix int/Lisp_Object mixup.
[emacs.git] / src / editfns.c
blobbf4976273aad22b39df48dc6eefa7bcb22930fb6
1 /* Lisp functions pertaining to editing.
2 Copyright (C) 1985,86,87,89,93,94,95,96,97,98, 1999, 2000, 2001, 2002
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
23 #include <config.h>
24 #include <sys/types.h>
26 #ifdef VMS
27 #include "vms-pwd.h"
28 #else
29 #include <pwd.h>
30 #endif
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
36 /* Without this, sprintf on Mac OS Classic will produce wrong
37 result. */
38 #ifdef MAC_OS8
39 #include <stdio.h>
40 #endif
42 #include <ctype.h>
44 #include "lisp.h"
45 #include "intervals.h"
46 #include "buffer.h"
47 #include "charset.h"
48 #include "coding.h"
49 #include "frame.h"
50 #include "window.h"
52 #include "systime.h"
54 #ifdef STDC_HEADERS
55 #include <float.h>
56 #define MAX_10_EXP DBL_MAX_10_EXP
57 #else
58 #define MAX_10_EXP 310
59 #endif
61 #ifndef NULL
62 #define NULL 0
63 #endif
65 #ifndef USE_CRT_DLL
66 extern char **environ;
67 #endif
69 extern Lisp_Object make_time P_ ((time_t));
70 extern size_t emacs_strftimeu P_ ((char *, size_t, const char *,
71 const struct tm *, int));
72 static int tm_diff P_ ((struct tm *, struct tm *));
73 static void find_field P_ ((Lisp_Object, Lisp_Object, Lisp_Object, int *, Lisp_Object, int *));
74 static void update_buffer_properties P_ ((int, int));
75 static Lisp_Object region_limit P_ ((int));
76 static int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
77 static size_t emacs_memftimeu P_ ((char *, size_t, const char *,
78 size_t, const struct tm *, int));
79 static void general_insert_function P_ ((void (*) (const unsigned char *, int),
80 void (*) (Lisp_Object, int, int, int,
81 int, int),
82 int, int, Lisp_Object *));
83 static Lisp_Object subst_char_in_region_unwind P_ ((Lisp_Object));
84 static Lisp_Object subst_char_in_region_unwind_1 P_ ((Lisp_Object));
85 static void transpose_markers P_ ((int, int, int, int, int, int, int, int));
87 #ifdef HAVE_INDEX
88 extern char *index P_ ((const char *, int));
89 #endif
91 Lisp_Object Vbuffer_access_fontify_functions;
92 Lisp_Object Qbuffer_access_fontify_functions;
93 Lisp_Object Vbuffer_access_fontified_property;
95 Lisp_Object Fuser_full_name P_ ((Lisp_Object));
97 /* Non-nil means don't stop at field boundary in text motion commands. */
99 Lisp_Object Vinhibit_field_text_motion;
101 /* Some static data, and a function to initialize it for each run */
103 Lisp_Object Vsystem_name;
104 Lisp_Object Vuser_real_login_name; /* login name of current user ID */
105 Lisp_Object Vuser_full_name; /* full name of current user */
106 Lisp_Object Vuser_login_name; /* user name from LOGNAME or USER */
108 /* Symbol for the text property used to mark fields. */
110 Lisp_Object Qfield;
112 /* A special value for Qfield properties. */
114 Lisp_Object Qboundary;
117 void
118 init_editfns ()
120 char *user_name;
121 register unsigned char *p;
122 struct passwd *pw; /* password entry for the current user */
123 Lisp_Object tem;
125 /* Set up system_name even when dumping. */
126 init_system_name ();
128 #ifndef CANNOT_DUMP
129 /* Don't bother with this on initial start when just dumping out */
130 if (!initialized)
131 return;
132 #endif /* not CANNOT_DUMP */
134 pw = (struct passwd *) getpwuid (getuid ());
135 #ifdef MSDOS
136 /* We let the real user name default to "root" because that's quite
137 accurate on MSDOG and because it lets Emacs find the init file.
138 (The DVX libraries override the Djgpp libraries here.) */
139 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
140 #else
141 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
142 #endif
144 /* Get the effective user name, by consulting environment variables,
145 or the effective uid if those are unset. */
146 user_name = (char *) getenv ("LOGNAME");
147 if (!user_name)
148 #ifdef WINDOWSNT
149 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
150 #else /* WINDOWSNT */
151 user_name = (char *) getenv ("USER");
152 #endif /* WINDOWSNT */
153 if (!user_name)
155 pw = (struct passwd *) getpwuid (geteuid ());
156 user_name = (char *) (pw ? pw->pw_name : "unknown");
158 Vuser_login_name = build_string (user_name);
160 /* If the user name claimed in the environment vars differs from
161 the real uid, use the claimed name to find the full name. */
162 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
163 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
164 : Vuser_login_name);
166 p = (unsigned char *) getenv ("NAME");
167 if (p)
168 Vuser_full_name = build_string (p);
169 else if (NILP (Vuser_full_name))
170 Vuser_full_name = build_string ("unknown");
173 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
174 doc: /* Convert arg CHAR to a string containing that character.
175 usage: (char-to-string CHAR) */)
176 (character)
177 Lisp_Object character;
179 int len;
180 unsigned char str[MAX_MULTIBYTE_LENGTH];
182 CHECK_NUMBER (character);
184 len = (SINGLE_BYTE_CHAR_P (XFASTINT (character))
185 ? (*str = (unsigned char)(XFASTINT (character)), 1)
186 : char_to_string (XFASTINT (character), str));
187 return make_string_from_bytes (str, 1, len);
190 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
191 doc: /* Convert arg STRING to a character, the first character of that string.
192 A multibyte character is handled correctly. */)
193 (string)
194 register Lisp_Object string;
196 register Lisp_Object val;
197 CHECK_STRING (string);
198 if (SCHARS (string))
200 if (STRING_MULTIBYTE (string))
201 XSETFASTINT (val, STRING_CHAR (SDATA (string), SBYTES (string)));
202 else
203 XSETFASTINT (val, SREF (string, 0));
205 else
206 XSETFASTINT (val, 0);
207 return val;
210 static Lisp_Object
211 buildmark (charpos, bytepos)
212 int charpos, bytepos;
214 register Lisp_Object mark;
215 mark = Fmake_marker ();
216 set_marker_both (mark, Qnil, charpos, bytepos);
217 return mark;
220 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
221 doc: /* Return value of point, as an integer.
222 Beginning of buffer is position (point-min). */)
225 Lisp_Object temp;
226 XSETFASTINT (temp, PT);
227 return temp;
230 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
231 doc: /* Return value of point, as a marker object. */)
234 return buildmark (PT, PT_BYTE);
238 clip_to_bounds (lower, num, upper)
239 int lower, num, upper;
241 if (num < lower)
242 return lower;
243 else if (num > upper)
244 return upper;
245 else
246 return num;
249 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
250 doc: /* Set point to POSITION, a number or marker.
251 Beginning of buffer is position (point-min), end is (point-max).
252 If the position is in the middle of a multibyte form,
253 the actual point is set at the head of the multibyte form
254 except in the case that `enable-multibyte-characters' is nil. */)
255 (position)
256 register Lisp_Object position;
258 int pos;
260 if (MARKERP (position)
261 && current_buffer == XMARKER (position)->buffer)
263 pos = marker_position (position);
264 if (pos < BEGV)
265 SET_PT_BOTH (BEGV, BEGV_BYTE);
266 else if (pos > ZV)
267 SET_PT_BOTH (ZV, ZV_BYTE);
268 else
269 SET_PT_BOTH (pos, marker_byte_position (position));
271 return position;
274 CHECK_NUMBER_COERCE_MARKER (position);
276 pos = clip_to_bounds (BEGV, XINT (position), ZV);
277 SET_PT (pos);
278 return position;
282 /* Return the start or end position of the region.
283 BEGINNINGP non-zero means return the start.
284 If there is no region active, signal an error. */
286 static Lisp_Object
287 region_limit (beginningp)
288 int beginningp;
290 extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
291 Lisp_Object m;
293 if (!NILP (Vtransient_mark_mode)
294 && NILP (Vmark_even_if_inactive)
295 && NILP (current_buffer->mark_active))
296 Fsignal (Qmark_inactive, Qnil);
298 m = Fmarker_position (current_buffer->mark);
299 if (NILP (m))
300 error ("The mark is not set now, so there is no region");
302 if ((PT < XFASTINT (m)) == beginningp)
303 m = make_number (PT);
304 return m;
307 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
308 doc: /* Return position of beginning of region, as an integer. */)
311 return region_limit (1);
314 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
315 doc: /* Return position of end of region, as an integer. */)
318 return region_limit (0);
321 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
322 doc: /* Return this buffer's mark, as a marker object.
323 Watch out! Moving this marker changes the mark position.
324 If you set the marker not to point anywhere, the buffer will have no mark. */)
327 return current_buffer->mark;
331 /* Find all the overlays in the current buffer that touch position POS.
332 Return the number found, and store them in a vector in VEC
333 of length LEN. */
335 static int
336 overlays_around (pos, vec, len)
337 int pos;
338 Lisp_Object *vec;
339 int len;
341 Lisp_Object tail, overlay, start, end;
342 int startpos, endpos;
343 int idx = 0;
345 for (tail = current_buffer->overlays_before;
346 GC_CONSP (tail);
347 tail = XCDR (tail))
349 overlay = XCAR (tail);
351 end = OVERLAY_END (overlay);
352 endpos = OVERLAY_POSITION (end);
353 if (endpos < pos)
354 break;
355 start = OVERLAY_START (overlay);
356 startpos = OVERLAY_POSITION (start);
357 if (startpos <= pos)
359 if (idx < len)
360 vec[idx] = overlay;
361 /* Keep counting overlays even if we can't return them all. */
362 idx++;
366 for (tail = current_buffer->overlays_after;
367 GC_CONSP (tail);
368 tail = XCDR (tail))
370 overlay = XCAR (tail);
372 start = OVERLAY_START (overlay);
373 startpos = OVERLAY_POSITION (start);
374 if (pos < startpos)
375 break;
376 end = OVERLAY_END (overlay);
377 endpos = OVERLAY_POSITION (end);
378 if (pos <= endpos)
380 if (idx < len)
381 vec[idx] = overlay;
382 idx++;
386 return idx;
389 /* Return the value of property PROP, in OBJECT at POSITION.
390 It's the value of PROP that a char inserted at POSITION would get.
391 OBJECT is optional and defaults to the current buffer.
392 If OBJECT is a buffer, then overlay properties are considered as well as
393 text properties.
394 If OBJECT is a window, then that window's buffer is used, but
395 window-specific overlays are considered only if they are associated
396 with OBJECT. */
397 static Lisp_Object
398 get_pos_property (position, prop, object)
399 Lisp_Object position, object;
400 register Lisp_Object prop;
402 struct window *w = 0;
404 CHECK_NUMBER_COERCE_MARKER (position);
406 if (NILP (object))
407 XSETBUFFER (object, current_buffer);
409 if (WINDOWP (object))
411 w = XWINDOW (object);
412 object = w->buffer;
414 if (BUFFERP (object))
416 int posn = XINT (position);
417 int noverlays;
418 Lisp_Object *overlay_vec, tem;
419 struct buffer *obuf = current_buffer;
421 set_buffer_temp (XBUFFER (object));
423 /* First try with room for 40 overlays. */
424 noverlays = 40;
425 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
426 noverlays = overlays_around (posn, overlay_vec, noverlays);
428 /* If there are more than 40,
429 make enough space for all, and try again. */
430 if (noverlays > 40)
432 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
433 noverlays = overlays_around (posn, overlay_vec, noverlays);
435 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
437 set_buffer_temp (obuf);
439 /* Now check the overlays in order of decreasing priority. */
440 while (--noverlays >= 0)
442 Lisp_Object ol = overlay_vec[noverlays];
443 tem = Foverlay_get (ol, prop);
444 if (!NILP (tem))
446 /* Check the overlay is indeed active at point. */
447 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
448 if ((OVERLAY_POSITION (start) == posn
449 && XMARKER (start)->insertion_type == 1)
450 || (OVERLAY_POSITION (finish) == posn
451 && XMARKER (finish)->insertion_type == 0))
452 ; /* The overlay will not cover a char inserted at point. */
453 else
455 return tem;
462 { /* Now check the text-properties. */
463 int stickiness = text_property_stickiness (Qfield, position);
464 if (stickiness > 0)
465 return Fget_text_property (position, Qfield, Qnil);
466 else if (stickiness < 0 && XINT (position) > BEGV)
467 return Fget_text_property (make_number (XINT (position) - 1),
468 Qfield, Qnil);
469 else
470 return Qnil;
474 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
475 the value of point is used instead. If BEG or END null,
476 means don't store the beginning or end of the field.
478 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
479 results; they do not effect boundary behavior.
481 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
482 position of a field, then the beginning of the previous field is
483 returned instead of the beginning of POS's field (since the end of a
484 field is actually also the beginning of the next input field, this
485 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
486 true case, if two fields are separated by a field with the special
487 value `boundary', and POS lies within it, then the two separated
488 fields are considered to be adjacent, and POS between them, when
489 finding the beginning and ending of the "merged" field.
491 Either BEG or END may be 0, in which case the corresponding value
492 is not stored. */
494 static void
495 find_field (pos, merge_at_boundary, beg_limit, beg, end_limit, end)
496 Lisp_Object pos;
497 Lisp_Object merge_at_boundary;
498 Lisp_Object beg_limit, end_limit;
499 int *beg, *end;
501 /* Fields right before and after the point. */
502 Lisp_Object before_field, after_field;
503 /* 1 if POS counts as the start of a field. */
504 int at_field_start = 0;
505 /* 1 if POS counts as the end of a field. */
506 int at_field_end = 0;
508 if (NILP (pos))
509 XSETFASTINT (pos, PT);
510 else
511 CHECK_NUMBER_COERCE_MARKER (pos);
513 after_field
514 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
515 before_field
516 = (XFASTINT (pos) > BEGV
517 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
518 Qfield, Qnil, NULL)
519 : Qnil);
521 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
522 and POS is at beginning of a field, which can also be interpreted
523 as the end of the previous field. Note that the case where if
524 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
525 more natural one; then we avoid treating the beginning of a field
526 specially. */
527 if (NILP (merge_at_boundary))
529 Lisp_Object field = get_pos_property (pos, Qfield, Qnil);
530 if (!EQ (field, after_field))
531 at_field_end = 1;
532 if (!EQ (field, before_field))
533 at_field_start = 1;
536 /* Note about special `boundary' fields:
538 Consider the case where the point (`.') is between the fields `x' and `y':
540 xxxx.yyyy
542 In this situation, if merge_at_boundary is true, we consider the
543 `x' and `y' fields as forming one big merged field, and so the end
544 of the field is the end of `y'.
546 However, if `x' and `y' are separated by a special `boundary' field
547 (a field with a `field' char-property of 'boundary), then we ignore
548 this special field when merging adjacent fields. Here's the same
549 situation, but with a `boundary' field between the `x' and `y' fields:
551 xxx.BBBByyyy
553 Here, if point is at the end of `x', the beginning of `y', or
554 anywhere in-between (within the `boundary' field), we merge all
555 three fields and consider the beginning as being the beginning of
556 the `x' field, and the end as being the end of the `y' field. */
558 if (beg)
560 if (at_field_start)
561 /* POS is at the edge of a field, and we should consider it as
562 the beginning of the following field. */
563 *beg = XFASTINT (pos);
564 else
565 /* Find the previous field boundary. */
567 Lisp_Object p = pos;
568 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
569 /* Skip a `boundary' field. */
570 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
571 beg_limit);
573 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
574 beg_limit);
575 *beg = NILP (p) ? BEGV : XFASTINT (p);
579 if (end)
581 if (at_field_end)
582 /* POS is at the edge of a field, and we should consider it as
583 the end of the previous field. */
584 *end = XFASTINT (pos);
585 else
586 /* Find the next field boundary. */
588 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
589 /* Skip a `boundary' field. */
590 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
591 end_limit);
593 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
594 end_limit);
595 *end = NILP (pos) ? ZV : XFASTINT (pos);
601 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
602 doc: /* Delete the field surrounding POS.
603 A field is a region of text with the same `field' property.
604 If POS is nil, the value of point is used for POS. */)
605 (pos)
606 Lisp_Object pos;
608 int beg, end;
609 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
610 if (beg != end)
611 del_range (beg, end);
612 return Qnil;
615 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
616 doc: /* Return the contents of the field surrounding POS as a string.
617 A field is a region of text with the same `field' property.
618 If POS is nil, the value of point is used for POS. */)
619 (pos)
620 Lisp_Object pos;
622 int beg, end;
623 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
624 return make_buffer_string (beg, end, 1);
627 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
628 doc: /* Return the contents of the field around POS, without text-properties.
629 A field is a region of text with the same `field' property.
630 If POS is nil, the value of point is used for POS. */)
631 (pos)
632 Lisp_Object pos;
634 int beg, end;
635 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
636 return make_buffer_string (beg, end, 0);
639 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
640 doc: /* Return the beginning of the field surrounding POS.
641 A field is a region of text with the same `field' property.
642 If POS is nil, the value of point is used for POS.
643 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
644 field, then the beginning of the *previous* field is returned.
645 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
646 is before LIMIT, then LIMIT will be returned instead. */)
647 (pos, escape_from_edge, limit)
648 Lisp_Object pos, escape_from_edge, limit;
650 int beg;
651 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
652 return make_number (beg);
655 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
656 doc: /* Return the end of the field surrounding POS.
657 A field is a region of text with the same `field' property.
658 If POS is nil, the value of point is used for POS.
659 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
660 then the end of the *following* field is returned.
661 If LIMIT is non-nil, it is a buffer position; if the end of the field
662 is after LIMIT, then LIMIT will be returned instead. */)
663 (pos, escape_from_edge, limit)
664 Lisp_Object pos, escape_from_edge, limit;
666 int end;
667 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
668 return make_number (end);
671 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
672 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
674 A field is a region of text with the same `field' property.
675 If NEW-POS is nil, then the current point is used instead, and set to the
676 constrained position if that is different.
678 If OLD-POS is at the boundary of two fields, then the allowable
679 positions for NEW-POS depends on the value of the optional argument
680 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
681 constrained to the field that has the same `field' char-property
682 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
683 is non-nil, NEW-POS is constrained to the union of the two adjacent
684 fields. Additionally, if two fields are separated by another field with
685 the special value `boundary', then any point within this special field is
686 also considered to be `on the boundary'.
688 If the optional argument ONLY-IN-LINE is non-nil and constraining
689 NEW-POS would move it to a different line, NEW-POS is returned
690 unconstrained. This useful for commands that move by line, like
691 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
692 only in the case where they can still move to the right line.
694 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
695 a non-nil property of that name, then any field boundaries are ignored.
697 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
698 (new_pos, old_pos, escape_from_edge, only_in_line, inhibit_capture_property)
699 Lisp_Object new_pos, old_pos;
700 Lisp_Object escape_from_edge, only_in_line, inhibit_capture_property;
702 /* If non-zero, then the original point, before re-positioning. */
703 int orig_point = 0;
705 if (NILP (new_pos))
706 /* Use the current point, and afterwards, set it. */
708 orig_point = PT;
709 XSETFASTINT (new_pos, PT);
712 if (NILP (Vinhibit_field_text_motion)
713 && !EQ (new_pos, old_pos)
714 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
715 || !NILP (Fget_char_property (old_pos, Qfield, Qnil)))
716 && (NILP (inhibit_capture_property)
717 || NILP (Fget_char_property(old_pos, inhibit_capture_property, Qnil))))
718 /* NEW_POS is not within the same field as OLD_POS; try to
719 move NEW_POS so that it is. */
721 int fwd, shortage;
722 Lisp_Object field_bound;
724 CHECK_NUMBER_COERCE_MARKER (new_pos);
725 CHECK_NUMBER_COERCE_MARKER (old_pos);
727 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
729 if (fwd)
730 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
731 else
732 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
734 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
735 other side of NEW_POS, which would mean that NEW_POS is
736 already acceptable, and it's not necessary to constrain it
737 to FIELD_BOUND. */
738 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
739 /* NEW_POS should be constrained, but only if either
740 ONLY_IN_LINE is nil (in which case any constraint is OK),
741 or NEW_POS and FIELD_BOUND are on the same line (in which
742 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
743 && (NILP (only_in_line)
744 /* This is the ONLY_IN_LINE case, check that NEW_POS and
745 FIELD_BOUND are on the same line by seeing whether
746 there's an intervening newline or not. */
747 || (scan_buffer ('\n',
748 XFASTINT (new_pos), XFASTINT (field_bound),
749 fwd ? -1 : 1, &shortage, 1),
750 shortage != 0)))
751 /* Constrain NEW_POS to FIELD_BOUND. */
752 new_pos = field_bound;
754 if (orig_point && XFASTINT (new_pos) != orig_point)
755 /* The NEW_POS argument was originally nil, so automatically set PT. */
756 SET_PT (XFASTINT (new_pos));
759 return new_pos;
763 DEFUN ("line-beginning-position",
764 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
765 doc: /* Return the character position of the first character on the current line.
766 With argument N not nil or 1, move forward N - 1 lines first.
767 If scan reaches end of buffer, return that position.
769 The scan does not cross a field boundary unless doing so would move
770 beyond there to a different line; if N is nil or 1, and scan starts at a
771 field boundary, the scan stops as soon as it starts. To ignore field
772 boundaries bind `inhibit-field-text-motion' to t.
774 This function does not move point. */)
776 Lisp_Object n;
778 int orig, orig_byte, end;
780 if (NILP (n))
781 XSETFASTINT (n, 1);
782 else
783 CHECK_NUMBER (n);
785 orig = PT;
786 orig_byte = PT_BYTE;
787 Fforward_line (make_number (XINT (n) - 1));
788 end = PT;
790 SET_PT_BOTH (orig, orig_byte);
792 /* Return END constrained to the current input field. */
793 return Fconstrain_to_field (make_number (end), make_number (orig),
794 XINT (n) != 1 ? Qt : Qnil,
795 Qt, Qnil);
798 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
799 doc: /* Return the character position of the last character on the current line.
800 With argument N not nil or 1, move forward N - 1 lines first.
801 If scan reaches end of buffer, return that position.
803 The scan does not cross a field boundary unless doing so would move
804 beyond there to a different line; if N is nil or 1, and scan starts at a
805 field boundary, the scan stops as soon as it starts. To ignore field
806 boundaries bind `inhibit-field-text-motion' to t.
808 This function does not move point. */)
810 Lisp_Object n;
812 int end_pos;
813 int orig = PT;
815 if (NILP (n))
816 XSETFASTINT (n, 1);
817 else
818 CHECK_NUMBER (n);
820 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
822 /* Return END_POS constrained to the current input field. */
823 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
824 Qnil, Qt, Qnil);
828 Lisp_Object
829 save_excursion_save ()
831 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
832 == current_buffer);
834 return Fcons (Fpoint_marker (),
835 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
836 Fcons (visible ? Qt : Qnil,
837 Fcons (current_buffer->mark_active,
838 selected_window))));
841 Lisp_Object
842 save_excursion_restore (info)
843 Lisp_Object info;
845 Lisp_Object tem, tem1, omark, nmark;
846 struct gcpro gcpro1, gcpro2, gcpro3;
847 int visible_p;
849 tem = Fmarker_buffer (XCAR (info));
850 /* If buffer being returned to is now deleted, avoid error */
851 /* Otherwise could get error here while unwinding to top level
852 and crash */
853 /* In that case, Fmarker_buffer returns nil now. */
854 if (NILP (tem))
855 return Qnil;
857 omark = nmark = Qnil;
858 GCPRO3 (info, omark, nmark);
860 Fset_buffer (tem);
862 /* Point marker. */
863 tem = XCAR (info);
864 Fgoto_char (tem);
865 unchain_marker (tem);
867 /* Mark marker. */
868 info = XCDR (info);
869 tem = XCAR (info);
870 omark = Fmarker_position (current_buffer->mark);
871 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
872 nmark = Fmarker_position (tem);
873 unchain_marker (tem);
875 /* visible */
876 info = XCDR (info);
877 visible_p = !NILP (XCAR (info));
879 #if 0 /* We used to make the current buffer visible in the selected window
880 if that was true previously. That avoids some anomalies.
881 But it creates others, and it wasn't documented, and it is simpler
882 and cleaner never to alter the window/buffer connections. */
883 tem1 = Fcar (tem);
884 if (!NILP (tem1)
885 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
886 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
887 #endif /* 0 */
889 /* Mark active */
890 info = XCDR (info);
891 tem = XCAR (info);
892 tem1 = current_buffer->mark_active;
893 current_buffer->mark_active = tem;
895 if (!NILP (Vrun_hooks))
897 /* If mark is active now, and either was not active
898 or was at a different place, run the activate hook. */
899 if (! NILP (current_buffer->mark_active))
901 if (! EQ (omark, nmark))
902 call1 (Vrun_hooks, intern ("activate-mark-hook"));
904 /* If mark has ceased to be active, run deactivate hook. */
905 else if (! NILP (tem1))
906 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
909 /* If buffer was visible in a window, and a different window was
910 selected, and the old selected window is still showing this
911 buffer, restore point in that window. */
912 tem = XCDR (info);
913 if (visible_p
914 && !EQ (tem, selected_window)
915 && (tem1 = XWINDOW (tem)->buffer,
916 (/* Window is live... */
917 BUFFERP (tem1)
918 /* ...and it shows the current buffer. */
919 && XBUFFER (tem1) == current_buffer)))
920 Fset_window_point (tem, make_number (PT));
922 UNGCPRO;
923 return Qnil;
926 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
927 doc: /* Save point, mark, and current buffer; execute BODY; restore those things.
928 Executes BODY just like `progn'.
929 The values of point, mark and the current buffer are restored
930 even in case of abnormal exit (throw or error).
931 The state of activation of the mark is also restored.
933 This construct does not save `deactivate-mark', and therefore
934 functions that change the buffer will still cause deactivation
935 of the mark at the end of the command. To prevent that, bind
936 `deactivate-mark' with `let'.
938 usage: (save-excursion &rest BODY) */)
939 (args)
940 Lisp_Object args;
942 register Lisp_Object val;
943 int count = SPECPDL_INDEX ();
945 record_unwind_protect (save_excursion_restore, save_excursion_save ());
947 val = Fprogn (args);
948 return unbind_to (count, val);
951 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
952 doc: /* Save the current buffer; execute BODY; restore the current buffer.
953 Executes BODY just like `progn'.
954 usage: (save-current-buffer &rest BODY) */)
955 (args)
956 Lisp_Object args;
958 Lisp_Object val;
959 int count = SPECPDL_INDEX ();
961 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
963 val = Fprogn (args);
964 return unbind_to (count, val);
967 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
968 doc: /* Return the number of characters in the current buffer.
969 If BUFFER, return the number of characters in that buffer instead. */)
970 (buffer)
971 Lisp_Object buffer;
973 if (NILP (buffer))
974 return make_number (Z - BEG);
975 else
977 CHECK_BUFFER (buffer);
978 return make_number (BUF_Z (XBUFFER (buffer))
979 - BUF_BEG (XBUFFER (buffer)));
983 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
984 doc: /* Return the minimum permissible value of point in the current buffer.
985 This is 1, unless narrowing (a buffer restriction) is in effect. */)
988 Lisp_Object temp;
989 XSETFASTINT (temp, BEGV);
990 return temp;
993 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
994 doc: /* Return a marker to the minimum permissible value of point in this buffer.
995 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
998 return buildmark (BEGV, BEGV_BYTE);
1001 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1002 doc: /* Return the maximum permissible value of point in the current buffer.
1003 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1004 is in effect, in which case it is less. */)
1007 Lisp_Object temp;
1008 XSETFASTINT (temp, ZV);
1009 return temp;
1012 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1013 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1014 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1015 is in effect, in which case it is less. */)
1018 return buildmark (ZV, ZV_BYTE);
1021 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1022 doc: /* Return the position of the gap, in the current buffer.
1023 See also `gap-size'. */)
1026 Lisp_Object temp;
1027 XSETFASTINT (temp, GPT);
1028 return temp;
1031 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1032 doc: /* Return the size of the current buffer's gap.
1033 See also `gap-position'. */)
1036 Lisp_Object temp;
1037 XSETFASTINT (temp, GAP_SIZE);
1038 return temp;
1041 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1042 doc: /* Return the byte position for character position POSITION.
1043 If POSITION is out of range, the value is nil. */)
1044 (position)
1045 Lisp_Object position;
1047 CHECK_NUMBER_COERCE_MARKER (position);
1048 if (XINT (position) < BEG || XINT (position) > Z)
1049 return Qnil;
1050 return make_number (CHAR_TO_BYTE (XINT (position)));
1053 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1054 doc: /* Return the character position for byte position BYTEPOS.
1055 If BYTEPOS is out of range, the value is nil. */)
1056 (bytepos)
1057 Lisp_Object bytepos;
1059 CHECK_NUMBER (bytepos);
1060 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
1061 return Qnil;
1062 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1065 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1066 doc: /* Return the character following point, as a number.
1067 At the end of the buffer or accessible region, return 0. */)
1070 Lisp_Object temp;
1071 if (PT >= ZV)
1072 XSETFASTINT (temp, 0);
1073 else
1074 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1075 return temp;
1078 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1079 doc: /* Return the character preceding point, as a number.
1080 At the beginning of the buffer or accessible region, return 0. */)
1083 Lisp_Object temp;
1084 if (PT <= BEGV)
1085 XSETFASTINT (temp, 0);
1086 else if (!NILP (current_buffer->enable_multibyte_characters))
1088 int pos = PT_BYTE;
1089 DEC_POS (pos);
1090 XSETFASTINT (temp, FETCH_CHAR (pos));
1092 else
1093 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1094 return temp;
1097 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1098 doc: /* Return t if point is at the beginning of the buffer.
1099 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1102 if (PT == BEGV)
1103 return Qt;
1104 return Qnil;
1107 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1108 doc: /* Return t if point is at the end of the buffer.
1109 If the buffer is narrowed, this means the end of the narrowed part. */)
1112 if (PT == ZV)
1113 return Qt;
1114 return Qnil;
1117 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1118 doc: /* Return t if point is at the beginning of a line. */)
1121 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1122 return Qt;
1123 return Qnil;
1126 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1127 doc: /* Return t if point is at the end of a line.
1128 `End of a line' includes point being at the end of the buffer. */)
1131 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1132 return Qt;
1133 return Qnil;
1136 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1137 doc: /* Return character in current buffer at position POS.
1138 POS is an integer or a marker.
1139 If POS is out of range, the value is nil. */)
1140 (pos)
1141 Lisp_Object pos;
1143 register int pos_byte;
1145 if (NILP (pos))
1147 pos_byte = PT_BYTE;
1148 XSETFASTINT (pos, PT);
1151 if (MARKERP (pos))
1153 pos_byte = marker_byte_position (pos);
1154 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1155 return Qnil;
1157 else
1159 CHECK_NUMBER_COERCE_MARKER (pos);
1160 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1161 return Qnil;
1163 pos_byte = CHAR_TO_BYTE (XINT (pos));
1166 return make_number (FETCH_CHAR (pos_byte));
1169 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1170 doc: /* Return character in current buffer preceding position POS.
1171 POS is an integer or a marker.
1172 If POS is out of range, the value is nil. */)
1173 (pos)
1174 Lisp_Object pos;
1176 register Lisp_Object val;
1177 register int pos_byte;
1179 if (NILP (pos))
1181 pos_byte = PT_BYTE;
1182 XSETFASTINT (pos, PT);
1185 if (MARKERP (pos))
1187 pos_byte = marker_byte_position (pos);
1189 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1190 return Qnil;
1192 else
1194 CHECK_NUMBER_COERCE_MARKER (pos);
1196 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1197 return Qnil;
1199 pos_byte = CHAR_TO_BYTE (XINT (pos));
1202 if (!NILP (current_buffer->enable_multibyte_characters))
1204 DEC_POS (pos_byte);
1205 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1207 else
1209 pos_byte--;
1210 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1212 return val;
1215 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1216 doc: /* Return the name under which the user logged in, as a string.
1217 This is based on the effective uid, not the real uid.
1218 Also, if the environment variable LOGNAME or USER is set,
1219 that determines the value of this function.
1221 If optional argument UID is an integer, return the login name of the user
1222 with that uid, or nil if there is no such user. */)
1223 (uid)
1224 Lisp_Object uid;
1226 struct passwd *pw;
1228 /* Set up the user name info if we didn't do it before.
1229 (That can happen if Emacs is dumpable
1230 but you decide to run `temacs -l loadup' and not dump. */
1231 if (INTEGERP (Vuser_login_name))
1232 init_editfns ();
1234 if (NILP (uid))
1235 return Vuser_login_name;
1237 CHECK_NUMBER (uid);
1238 pw = (struct passwd *) getpwuid (XINT (uid));
1239 return (pw ? build_string (pw->pw_name) : Qnil);
1242 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1243 0, 0, 0,
1244 doc: /* Return the name of the user's real uid, as a string.
1245 This ignores the environment variables LOGNAME and USER, so it differs from
1246 `user-login-name' when running under `su'. */)
1249 /* Set up the user name info if we didn't do it before.
1250 (That can happen if Emacs is dumpable
1251 but you decide to run `temacs -l loadup' and not dump. */
1252 if (INTEGERP (Vuser_login_name))
1253 init_editfns ();
1254 return Vuser_real_login_name;
1257 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1258 doc: /* Return the effective uid of Emacs.
1259 Value is an integer or float, depending on the value. */)
1262 return make_fixnum_or_float (geteuid ());
1265 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1266 doc: /* Return the real uid of Emacs.
1267 Value is an integer or float, depending on the value. */)
1270 return make_fixnum_or_float (getuid ());
1273 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1274 doc: /* Return the full name of the user logged in, as a string.
1275 If the full name corresponding to Emacs's userid is not known,
1276 return "unknown".
1278 If optional argument UID is an integer or float, return the full name
1279 of the user with that uid, or nil if there is no such user.
1280 If UID is a string, return the full name of the user with that login
1281 name, or nil if there is no such user. */)
1282 (uid)
1283 Lisp_Object uid;
1285 struct passwd *pw;
1286 register unsigned char *p, *q;
1287 Lisp_Object full;
1289 if (NILP (uid))
1290 return Vuser_full_name;
1291 else if (NUMBERP (uid))
1292 pw = (struct passwd *) getpwuid ((uid_t) XFLOATINT (uid));
1293 else if (STRINGP (uid))
1294 pw = (struct passwd *) getpwnam (SDATA (uid));
1295 else
1296 error ("Invalid UID specification");
1298 if (!pw)
1299 return Qnil;
1301 p = (unsigned char *) USER_FULL_NAME;
1302 /* Chop off everything after the first comma. */
1303 q = (unsigned char *) index (p, ',');
1304 full = make_string (p, q ? q - p : strlen (p));
1306 #ifdef AMPERSAND_FULL_NAME
1307 p = SDATA (full);
1308 q = (unsigned char *) index (p, '&');
1309 /* Substitute the login name for the &, upcasing the first character. */
1310 if (q)
1312 register unsigned char *r;
1313 Lisp_Object login;
1315 login = Fuser_login_name (make_number (pw->pw_uid));
1316 r = (unsigned char *) alloca (strlen (p) + SCHARS (login) + 1);
1317 bcopy (p, r, q - p);
1318 r[q - p] = 0;
1319 strcat (r, SDATA (login));
1320 r[q - p] = UPCASE (r[q - p]);
1321 strcat (r, q + 1);
1322 full = build_string (r);
1324 #endif /* AMPERSAND_FULL_NAME */
1326 return full;
1329 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1330 doc: /* Return the name of the machine you are running on, as a string. */)
1333 return Vsystem_name;
1336 /* For the benefit of callers who don't want to include lisp.h */
1338 char *
1339 get_system_name ()
1341 if (STRINGP (Vsystem_name))
1342 return (char *) SDATA (Vsystem_name);
1343 else
1344 return "";
1347 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1348 doc: /* Return the process ID of Emacs, as an integer. */)
1351 return make_number (getpid ());
1354 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1355 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1356 The time is returned as a list of three integers. The first has the
1357 most significant 16 bits of the seconds, while the second has the
1358 least significant 16 bits. The third integer gives the microsecond
1359 count.
1361 The microsecond count is zero on systems that do not provide
1362 resolution finer than a second. */)
1365 EMACS_TIME t;
1366 Lisp_Object result[3];
1368 EMACS_GET_TIME (t);
1369 XSETINT (result[0], (EMACS_SECS (t) >> 16) & 0xffff);
1370 XSETINT (result[1], (EMACS_SECS (t) >> 0) & 0xffff);
1371 XSETINT (result[2], EMACS_USECS (t));
1373 return Flist (3, result);
1377 static int
1378 lisp_time_argument (specified_time, result, usec)
1379 Lisp_Object specified_time;
1380 time_t *result;
1381 int *usec;
1383 if (NILP (specified_time))
1385 if (usec)
1387 EMACS_TIME t;
1389 EMACS_GET_TIME (t);
1390 *usec = EMACS_USECS (t);
1391 *result = EMACS_SECS (t);
1392 return 1;
1394 else
1395 return time (result) != -1;
1397 else
1399 Lisp_Object high, low;
1400 high = Fcar (specified_time);
1401 CHECK_NUMBER (high);
1402 low = Fcdr (specified_time);
1403 if (CONSP (low))
1405 if (usec)
1407 Lisp_Object usec_l = Fcdr (low);
1408 if (CONSP (usec_l))
1409 usec_l = Fcar (usec_l);
1410 if (NILP (usec_l))
1411 *usec = 0;
1412 else
1414 CHECK_NUMBER (usec_l);
1415 *usec = XINT (usec_l);
1418 low = Fcar (low);
1420 else if (usec)
1421 *usec = 0;
1422 CHECK_NUMBER (low);
1423 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
1424 return *result >> 16 == XINT (high);
1428 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1429 doc: /* Return the current time, as a float number of seconds since the epoch.
1430 If an argument is given, it specifies a time to convert to float
1431 instead of the current time. The argument should have the forms:
1432 (HIGH . LOW) or (HIGH LOW USEC) or (HIGH LOW . USEC).
1433 Thus, you can use times obtained from `current-time'
1434 and from `file-attributes'.
1436 WARNING: Since the result is floating point, it may not be exact.
1437 Do not use this function if precise time stamps are required. */)
1438 (specified_time)
1439 Lisp_Object specified_time;
1441 time_t sec;
1442 int usec;
1444 if (! lisp_time_argument (specified_time, &sec, &usec))
1445 error ("Invalid time specification");
1447 return make_float ((sec * 1e6 + usec) / 1e6);
1450 /* Write information into buffer S of size MAXSIZE, according to the
1451 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1452 Default to Universal Time if UT is nonzero, local time otherwise.
1453 Return the number of bytes written, not including the terminating
1454 '\0'. If S is NULL, nothing will be written anywhere; so to
1455 determine how many bytes would be written, use NULL for S and
1456 ((size_t) -1) for MAXSIZE.
1458 This function behaves like emacs_strftimeu, except it allows null
1459 bytes in FORMAT. */
1460 static size_t
1461 emacs_memftimeu (s, maxsize, format, format_len, tp, ut)
1462 char *s;
1463 size_t maxsize;
1464 const char *format;
1465 size_t format_len;
1466 const struct tm *tp;
1467 int ut;
1469 size_t total = 0;
1471 /* Loop through all the null-terminated strings in the format
1472 argument. Normally there's just one null-terminated string, but
1473 there can be arbitrarily many, concatenated together, if the
1474 format contains '\0' bytes. emacs_strftimeu stops at the first
1475 '\0' byte so we must invoke it separately for each such string. */
1476 for (;;)
1478 size_t len;
1479 size_t result;
1481 if (s)
1482 s[0] = '\1';
1484 result = emacs_strftimeu (s, maxsize, format, tp, ut);
1486 if (s)
1488 if (result == 0 && s[0] != '\0')
1489 return 0;
1490 s += result + 1;
1493 maxsize -= result + 1;
1494 total += result;
1495 len = strlen (format);
1496 if (len == format_len)
1497 return total;
1498 total++;
1499 format += len + 1;
1500 format_len -= len + 1;
1504 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1505 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
1506 TIME is specified as (HIGH LOW . IGNORED) or (HIGH . LOW), as returned by
1507 `current-time' or `file-attributes'.
1508 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1509 as Universal Time; nil means describe TIME in the local time zone.
1510 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1511 by text that describes the specified date and time in TIME:
1513 %Y is the year, %y within the century, %C the century.
1514 %G is the year corresponding to the ISO week, %g within the century.
1515 %m is the numeric month.
1516 %b and %h are the locale's abbreviated month name, %B the full name.
1517 %d is the day of the month, zero-padded, %e is blank-padded.
1518 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1519 %a is the locale's abbreviated name of the day of week, %A the full name.
1520 %U is the week number starting on Sunday, %W starting on Monday,
1521 %V according to ISO 8601.
1522 %j is the day of the year.
1524 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1525 only blank-padded, %l is like %I blank-padded.
1526 %p is the locale's equivalent of either AM or PM.
1527 %M is the minute.
1528 %S is the second.
1529 %Z is the time zone name, %z is the numeric form.
1530 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1532 %c is the locale's date and time format.
1533 %x is the locale's "preferred" date format.
1534 %D is like "%m/%d/%y".
1536 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1537 %X is the locale's "preferred" time format.
1539 Finally, %n is a newline, %t is a tab, %% is a literal %.
1541 Certain flags and modifiers are available with some format controls.
1542 The flags are `_', `-', `^' and `#'. For certain characters X,
1543 %_X is like %X, but padded with blanks; %-X is like %X,
1544 but without padding. %^X is like %X, but with all textual
1545 characters up-cased; %#X is like %X, but with letter-case of
1546 all textual characters reversed.
1547 %NX (where N stands for an integer) is like %X,
1548 but takes up at least N (a number) positions.
1549 The modifiers are `E' and `O'. For certain characters X,
1550 %EX is a locale's alternative version of %X;
1551 %OX is like %X, but uses the locale's number symbols.
1553 For example, to produce full ISO 8601 format, use "%Y-%m-%dT%T%z". */)
1554 (format_string, time, universal)
1555 Lisp_Object format_string, time, universal;
1557 time_t value;
1558 int size;
1559 struct tm *tm;
1560 int ut = ! NILP (universal);
1562 CHECK_STRING (format_string);
1564 if (! lisp_time_argument (time, &value, NULL))
1565 error ("Invalid time specification");
1567 format_string = code_convert_string_norecord (format_string,
1568 Vlocale_coding_system, 1);
1570 /* This is probably enough. */
1571 size = SBYTES (format_string) * 6 + 50;
1573 tm = ut ? gmtime (&value) : localtime (&value);
1574 if (! tm)
1575 error ("Specified time is not representable");
1577 synchronize_system_time_locale ();
1579 while (1)
1581 char *buf = (char *) alloca (size + 1);
1582 int result;
1584 buf[0] = '\1';
1585 result = emacs_memftimeu (buf, size, SDATA (format_string),
1586 SBYTES (format_string),
1587 tm, ut);
1588 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1589 return code_convert_string_norecord (make_string (buf, result),
1590 Vlocale_coding_system, 0);
1592 /* If buffer was too small, make it bigger and try again. */
1593 result = emacs_memftimeu (NULL, (size_t) -1,
1594 SDATA (format_string),
1595 SBYTES (format_string),
1596 tm, ut);
1597 size = result + 1;
1601 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1602 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
1603 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED)
1604 or (HIGH . LOW), as from `current-time' and `file-attributes', or `nil'
1605 to use the current time. The list has the following nine members:
1606 SEC is an integer between 0 and 60; SEC is 60 for a leap second, which
1607 only some operating systems support. MINUTE is an integer between 0 and 59.
1608 HOUR is an integer between 0 and 23. DAY is an integer between 1 and 31.
1609 MONTH is an integer between 1 and 12. YEAR is an integer indicating the
1610 four-digit year. DOW is the day of week, an integer between 0 and 6, where
1611 0 is Sunday. DST is t if daylight savings time is effect, otherwise nil.
1612 ZONE is an integer indicating the number of seconds east of Greenwich.
1613 (Note that Common Lisp has different meanings for DOW and ZONE.) */)
1614 (specified_time)
1615 Lisp_Object specified_time;
1617 time_t time_spec;
1618 struct tm save_tm;
1619 struct tm *decoded_time;
1620 Lisp_Object list_args[9];
1622 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1623 error ("Invalid time specification");
1625 decoded_time = localtime (&time_spec);
1626 if (! decoded_time)
1627 error ("Specified time is not representable");
1628 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1629 XSETFASTINT (list_args[1], decoded_time->tm_min);
1630 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1631 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1632 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1633 XSETINT (list_args[5], decoded_time->tm_year + 1900);
1634 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1635 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1637 /* Make a copy, in case gmtime modifies the struct. */
1638 save_tm = *decoded_time;
1639 decoded_time = gmtime (&time_spec);
1640 if (decoded_time == 0)
1641 list_args[8] = Qnil;
1642 else
1643 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1644 return Flist (9, list_args);
1647 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1648 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
1649 This is the reverse operation of `decode-time', which see.
1650 ZONE defaults to the current time zone rule. This can
1651 be a string or t (as from `set-time-zone-rule'), or it can be a list
1652 \(as from `current-time-zone') or an integer (as from `decode-time')
1653 applied without consideration for daylight savings time.
1655 You can pass more than 7 arguments; then the first six arguments
1656 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
1657 The intervening arguments are ignored.
1658 This feature lets (apply 'encode-time (decode-time ...)) work.
1660 Out-of-range values for SEC, MINUTE, HOUR, DAY, or MONTH are allowed;
1661 for example, a DAY of 0 means the day preceding the given month.
1662 Year numbers less than 100 are treated just like other year numbers.
1663 If you want them to stand for years in this century, you must do that yourself.
1665 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
1666 (nargs, args)
1667 int nargs;
1668 register Lisp_Object *args;
1670 time_t time;
1671 struct tm tm;
1672 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1674 CHECK_NUMBER (args[0]); /* second */
1675 CHECK_NUMBER (args[1]); /* minute */
1676 CHECK_NUMBER (args[2]); /* hour */
1677 CHECK_NUMBER (args[3]); /* day */
1678 CHECK_NUMBER (args[4]); /* month */
1679 CHECK_NUMBER (args[5]); /* year */
1681 tm.tm_sec = XINT (args[0]);
1682 tm.tm_min = XINT (args[1]);
1683 tm.tm_hour = XINT (args[2]);
1684 tm.tm_mday = XINT (args[3]);
1685 tm.tm_mon = XINT (args[4]) - 1;
1686 tm.tm_year = XINT (args[5]) - 1900;
1687 tm.tm_isdst = -1;
1689 if (CONSP (zone))
1690 zone = Fcar (zone);
1691 if (NILP (zone))
1692 time = mktime (&tm);
1693 else
1695 char tzbuf[100];
1696 char *tzstring;
1697 char **oldenv = environ, **newenv;
1699 if (EQ (zone, Qt))
1700 tzstring = "UTC0";
1701 else if (STRINGP (zone))
1702 tzstring = (char *) SDATA (zone);
1703 else if (INTEGERP (zone))
1705 int abszone = abs (XINT (zone));
1706 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1707 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1708 tzstring = tzbuf;
1710 else
1711 error ("Invalid time zone specification");
1713 /* Set TZ before calling mktime; merely adjusting mktime's returned
1714 value doesn't suffice, since that would mishandle leap seconds. */
1715 set_time_zone_rule (tzstring);
1717 time = mktime (&tm);
1719 /* Restore TZ to previous value. */
1720 newenv = environ;
1721 environ = oldenv;
1722 xfree (newenv);
1723 #ifdef LOCALTIME_CACHE
1724 tzset ();
1725 #endif
1728 if (time == (time_t) -1)
1729 error ("Specified time is not representable");
1731 return make_time (time);
1734 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1735 doc: /* Return the current time, as a human-readable string.
1736 Programs can use this function to decode a time,
1737 since the number of columns in each field is fixed.
1738 The format is `Sun Sep 16 01:03:52 1973'.
1739 However, see also the functions `decode-time' and `format-time-string'
1740 which provide a much more powerful and general facility.
1742 If an argument is given, it specifies a time to format
1743 instead of the current time. The argument should have the form:
1744 (HIGH . LOW)
1745 or the form:
1746 (HIGH LOW . IGNORED).
1747 Thus, you can use times obtained from `current-time'
1748 and from `file-attributes'. */)
1749 (specified_time)
1750 Lisp_Object specified_time;
1752 time_t value;
1753 char buf[30];
1754 register char *tem;
1756 if (! lisp_time_argument (specified_time, &value, NULL))
1757 value = -1;
1758 tem = (char *) ctime (&value);
1760 strncpy (buf, tem, 24);
1761 buf[24] = 0;
1763 return build_string (buf);
1766 #define TM_YEAR_BASE 1900
1768 /* Yield A - B, measured in seconds.
1769 This function is copied from the GNU C Library. */
1770 static int
1771 tm_diff (a, b)
1772 struct tm *a, *b;
1774 /* Compute intervening leap days correctly even if year is negative.
1775 Take care to avoid int overflow in leap day calculations,
1776 but it's OK to assume that A and B are close to each other. */
1777 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1778 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1779 int a100 = a4 / 25 - (a4 % 25 < 0);
1780 int b100 = b4 / 25 - (b4 % 25 < 0);
1781 int a400 = a100 >> 2;
1782 int b400 = b100 >> 2;
1783 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1784 int years = a->tm_year - b->tm_year;
1785 int days = (365 * years + intervening_leap_days
1786 + (a->tm_yday - b->tm_yday));
1787 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1788 + (a->tm_min - b->tm_min))
1789 + (a->tm_sec - b->tm_sec));
1792 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1793 doc: /* Return the offset and name for the local time zone.
1794 This returns a list of the form (OFFSET NAME).
1795 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
1796 A negative value means west of Greenwich.
1797 NAME is a string giving the name of the time zone.
1798 If an argument is given, it specifies when the time zone offset is determined
1799 instead of using the current time. The argument should have the form:
1800 (HIGH . LOW)
1801 or the form:
1802 (HIGH LOW . IGNORED).
1803 Thus, you can use times obtained from `current-time'
1804 and from `file-attributes'.
1806 Some operating systems cannot provide all this information to Emacs;
1807 in this case, `current-time-zone' returns a list containing nil for
1808 the data it can't find. */)
1809 (specified_time)
1810 Lisp_Object specified_time;
1812 time_t value;
1813 struct tm *t;
1814 struct tm gmt;
1816 if (lisp_time_argument (specified_time, &value, NULL)
1817 && (t = gmtime (&value)) != 0
1818 && (gmt = *t, t = localtime (&value)) != 0)
1820 int offset = tm_diff (t, &gmt);
1821 char *s = 0;
1822 char buf[6];
1823 #ifdef HAVE_TM_ZONE
1824 if (t->tm_zone)
1825 s = (char *)t->tm_zone;
1826 #else /* not HAVE_TM_ZONE */
1827 #ifdef HAVE_TZNAME
1828 if (t->tm_isdst == 0 || t->tm_isdst == 1)
1829 s = tzname[t->tm_isdst];
1830 #endif
1831 #endif /* not HAVE_TM_ZONE */
1833 #if defined HAVE_TM_ZONE || defined HAVE_TZNAME
1834 if (s)
1836 /* On Japanese w32, we can get a Japanese string as time
1837 zone name. Don't accept that. */
1838 char *p;
1839 for (p = s; *p && (isalnum ((unsigned char)*p) || *p == ' '); ++p)
1841 if (p == s || *p)
1842 s = NULL;
1844 #endif
1846 if (!s)
1848 /* No local time zone name is available; use "+-NNNN" instead. */
1849 int am = (offset < 0 ? -offset : offset) / 60;
1850 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
1851 s = buf;
1853 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
1855 else
1856 return Fmake_list (make_number (2), Qnil);
1859 /* This holds the value of `environ' produced by the previous
1860 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
1861 has never been called. */
1862 static char **environbuf;
1864 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
1865 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
1866 If TZ is nil, use implementation-defined default time zone information.
1867 If TZ is t, use Universal Time. */)
1868 (tz)
1869 Lisp_Object tz;
1871 char *tzstring;
1873 if (NILP (tz))
1874 tzstring = 0;
1875 else if (EQ (tz, Qt))
1876 tzstring = "UTC0";
1877 else
1879 CHECK_STRING (tz);
1880 tzstring = (char *) SDATA (tz);
1883 set_time_zone_rule (tzstring);
1884 if (environbuf)
1885 free (environbuf);
1886 environbuf = environ;
1888 return Qnil;
1891 #ifdef LOCALTIME_CACHE
1893 /* These two values are known to load tz files in buggy implementations,
1894 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
1895 Their values shouldn't matter in non-buggy implementations.
1896 We don't use string literals for these strings,
1897 since if a string in the environment is in readonly
1898 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
1899 See Sun bugs 1113095 and 1114114, ``Timezone routines
1900 improperly modify environment''. */
1902 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
1903 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
1905 #endif
1907 /* Set the local time zone rule to TZSTRING.
1908 This allocates memory into `environ', which it is the caller's
1909 responsibility to free. */
1911 void
1912 set_time_zone_rule (tzstring)
1913 char *tzstring;
1915 int envptrs;
1916 char **from, **to, **newenv;
1918 /* Make the ENVIRON vector longer with room for TZSTRING. */
1919 for (from = environ; *from; from++)
1920 continue;
1921 envptrs = from - environ + 2;
1922 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
1923 + (tzstring ? strlen (tzstring) + 4 : 0));
1925 /* Add TZSTRING to the end of environ, as a value for TZ. */
1926 if (tzstring)
1928 char *t = (char *) (to + envptrs);
1929 strcpy (t, "TZ=");
1930 strcat (t, tzstring);
1931 *to++ = t;
1934 /* Copy the old environ vector elements into NEWENV,
1935 but don't copy the TZ variable.
1936 So we have only one definition of TZ, which came from TZSTRING. */
1937 for (from = environ; *from; from++)
1938 if (strncmp (*from, "TZ=", 3) != 0)
1939 *to++ = *from;
1940 *to = 0;
1942 environ = newenv;
1944 /* If we do have a TZSTRING, NEWENV points to the vector slot where
1945 the TZ variable is stored. If we do not have a TZSTRING,
1946 TO points to the vector slot which has the terminating null. */
1948 #ifdef LOCALTIME_CACHE
1950 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
1951 "US/Pacific" that loads a tz file, then changes to a value like
1952 "XXX0" that does not load a tz file, and then changes back to
1953 its original value, the last change is (incorrectly) ignored.
1954 Also, if TZ changes twice in succession to values that do
1955 not load a tz file, tzset can dump core (see Sun bug#1225179).
1956 The following code works around these bugs. */
1958 if (tzstring)
1960 /* Temporarily set TZ to a value that loads a tz file
1961 and that differs from tzstring. */
1962 char *tz = *newenv;
1963 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
1964 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
1965 tzset ();
1966 *newenv = tz;
1968 else
1970 /* The implied tzstring is unknown, so temporarily set TZ to
1971 two different values that each load a tz file. */
1972 *to = set_time_zone_rule_tz1;
1973 to[1] = 0;
1974 tzset ();
1975 *to = set_time_zone_rule_tz2;
1976 tzset ();
1977 *to = 0;
1980 /* Now TZ has the desired value, and tzset can be invoked safely. */
1983 tzset ();
1984 #endif
1987 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
1988 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
1989 type of object is Lisp_String). INHERIT is passed to
1990 INSERT_FROM_STRING_FUNC as the last argument. */
1992 static void
1993 general_insert_function (insert_func, insert_from_string_func,
1994 inherit, nargs, args)
1995 void (*insert_func) P_ ((const unsigned char *, int));
1996 void (*insert_from_string_func) P_ ((Lisp_Object, int, int, int, int, int));
1997 int inherit, nargs;
1998 register Lisp_Object *args;
2000 register int argnum;
2001 register Lisp_Object val;
2003 for (argnum = 0; argnum < nargs; argnum++)
2005 val = args[argnum];
2006 retry:
2007 if (INTEGERP (val))
2009 unsigned char str[MAX_MULTIBYTE_LENGTH];
2010 int len;
2012 if (!NILP (current_buffer->enable_multibyte_characters))
2013 len = CHAR_STRING (XFASTINT (val), str);
2014 else
2016 str[0] = (SINGLE_BYTE_CHAR_P (XINT (val))
2017 ? XINT (val)
2018 : multibyte_char_to_unibyte (XINT (val), Qnil));
2019 len = 1;
2021 (*insert_func) (str, len);
2023 else if (STRINGP (val))
2025 (*insert_from_string_func) (val, 0, 0,
2026 SCHARS (val),
2027 SBYTES (val),
2028 inherit);
2030 else
2032 val = wrong_type_argument (Qchar_or_string_p, val);
2033 goto retry;
2038 void
2039 insert1 (arg)
2040 Lisp_Object arg;
2042 Finsert (1, &arg);
2046 /* Callers passing one argument to Finsert need not gcpro the
2047 argument "array", since the only element of the array will
2048 not be used after calling insert or insert_from_string, so
2049 we don't care if it gets trashed. */
2051 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2052 doc: /* Insert the arguments, either strings or characters, at point.
2053 Point and before-insertion markers move forward to end up
2054 after the inserted text.
2055 Any other markers at the point of insertion remain before the text.
2057 If the current buffer is multibyte, unibyte strings are converted
2058 to multibyte for insertion (see `unibyte-char-to-multibyte').
2059 If the current buffer is unibyte, multibyte strings are converted
2060 to unibyte for insertion.
2062 usage: (insert &rest ARGS) */)
2063 (nargs, args)
2064 int nargs;
2065 register Lisp_Object *args;
2067 general_insert_function (insert, insert_from_string, 0, nargs, args);
2068 return Qnil;
2071 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2072 0, MANY, 0,
2073 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2074 Point and before-insertion markers move forward to end up
2075 after the inserted text.
2076 Any other markers at the point of insertion remain before the text.
2078 If the current buffer is multibyte, unibyte strings are converted
2079 to multibyte for insertion (see `unibyte-char-to-multibyte').
2080 If the current buffer is unibyte, multibyte strings are converted
2081 to unibyte for insertion.
2083 usage: (insert-and-inherit &rest ARGS) */)
2084 (nargs, args)
2085 int nargs;
2086 register Lisp_Object *args;
2088 general_insert_function (insert_and_inherit, insert_from_string, 1,
2089 nargs, args);
2090 return Qnil;
2093 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2094 doc: /* Insert strings or characters at point, relocating markers after the text.
2095 Point and markers move forward to end up after the inserted text.
2097 If the current buffer is multibyte, unibyte strings are converted
2098 to multibyte for insertion (see `unibyte-char-to-multibyte').
2099 If the current buffer is unibyte, multibyte strings are converted
2100 to unibyte for insertion.
2102 usage: (insert-before-markers &rest ARGS) */)
2103 (nargs, args)
2104 int nargs;
2105 register Lisp_Object *args;
2107 general_insert_function (insert_before_markers,
2108 insert_from_string_before_markers, 0,
2109 nargs, args);
2110 return Qnil;
2113 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2114 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2115 doc: /* Insert text at point, relocating markers and inheriting properties.
2116 Point and markers move forward to end up after the inserted text.
2118 If the current buffer is multibyte, unibyte strings are converted
2119 to multibyte for insertion (see `unibyte-char-to-multibyte').
2120 If the current buffer is unibyte, multibyte strings are converted
2121 to unibyte for insertion.
2123 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2124 (nargs, args)
2125 int nargs;
2126 register Lisp_Object *args;
2128 general_insert_function (insert_before_markers_and_inherit,
2129 insert_from_string_before_markers, 1,
2130 nargs, args);
2131 return Qnil;
2134 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
2135 doc: /* Insert COUNT (second arg) copies of CHARACTER (first arg).
2136 Both arguments are required.
2137 Point, and before-insertion markers, are relocated as in the function `insert'.
2138 The optional third arg INHERIT, if non-nil, says to inherit text properties
2139 from adjoining text, if those properties are sticky. */)
2140 (character, count, inherit)
2141 Lisp_Object character, count, inherit;
2143 register unsigned char *string;
2144 register int strlen;
2145 register int i, n;
2146 int len;
2147 unsigned char str[MAX_MULTIBYTE_LENGTH];
2149 CHECK_NUMBER (character);
2150 CHECK_NUMBER (count);
2152 if (!NILP (current_buffer->enable_multibyte_characters))
2153 len = CHAR_STRING (XFASTINT (character), str);
2154 else
2155 str[0] = XFASTINT (character), len = 1;
2156 n = XINT (count) * len;
2157 if (n <= 0)
2158 return Qnil;
2159 strlen = min (n, 256 * len);
2160 string = (unsigned char *) alloca (strlen);
2161 for (i = 0; i < strlen; i++)
2162 string[i] = str[i % len];
2163 while (n >= strlen)
2165 QUIT;
2166 if (!NILP (inherit))
2167 insert_and_inherit (string, strlen);
2168 else
2169 insert (string, strlen);
2170 n -= strlen;
2172 if (n > 0)
2174 if (!NILP (inherit))
2175 insert_and_inherit (string, n);
2176 else
2177 insert (string, n);
2179 return Qnil;
2183 /* Making strings from buffer contents. */
2185 /* Return a Lisp_String containing the text of the current buffer from
2186 START to END. If text properties are in use and the current buffer
2187 has properties in the range specified, the resulting string will also
2188 have them, if PROPS is nonzero.
2190 We don't want to use plain old make_string here, because it calls
2191 make_uninit_string, which can cause the buffer arena to be
2192 compacted. make_string has no way of knowing that the data has
2193 been moved, and thus copies the wrong data into the string. This
2194 doesn't effect most of the other users of make_string, so it should
2195 be left as is. But we should use this function when conjuring
2196 buffer substrings. */
2198 Lisp_Object
2199 make_buffer_string (start, end, props)
2200 int start, end;
2201 int props;
2203 int start_byte = CHAR_TO_BYTE (start);
2204 int end_byte = CHAR_TO_BYTE (end);
2206 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2209 /* Return a Lisp_String containing the text of the current buffer from
2210 START / START_BYTE to END / END_BYTE.
2212 If text properties are in use and the current buffer
2213 has properties in the range specified, the resulting string will also
2214 have them, if PROPS is nonzero.
2216 We don't want to use plain old make_string here, because it calls
2217 make_uninit_string, which can cause the buffer arena to be
2218 compacted. make_string has no way of knowing that the data has
2219 been moved, and thus copies the wrong data into the string. This
2220 doesn't effect most of the other users of make_string, so it should
2221 be left as is. But we should use this function when conjuring
2222 buffer substrings. */
2224 Lisp_Object
2225 make_buffer_string_both (start, start_byte, end, end_byte, props)
2226 int start, start_byte, end, end_byte;
2227 int props;
2229 Lisp_Object result, tem, tem1;
2231 if (start < GPT && GPT < end)
2232 move_gap (start);
2234 if (! NILP (current_buffer->enable_multibyte_characters))
2235 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2236 else
2237 result = make_uninit_string (end - start);
2238 bcopy (BYTE_POS_ADDR (start_byte), SDATA (result),
2239 end_byte - start_byte);
2241 /* If desired, update and copy the text properties. */
2242 if (props)
2244 update_buffer_properties (start, end);
2246 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2247 tem1 = Ftext_properties_at (make_number (start), Qnil);
2249 if (XINT (tem) != end || !NILP (tem1))
2250 copy_intervals_to_string (result, current_buffer, start,
2251 end - start);
2254 return result;
2257 /* Call Vbuffer_access_fontify_functions for the range START ... END
2258 in the current buffer, if necessary. */
2260 static void
2261 update_buffer_properties (start, end)
2262 int start, end;
2264 /* If this buffer has some access functions,
2265 call them, specifying the range of the buffer being accessed. */
2266 if (!NILP (Vbuffer_access_fontify_functions))
2268 Lisp_Object args[3];
2269 Lisp_Object tem;
2271 args[0] = Qbuffer_access_fontify_functions;
2272 XSETINT (args[1], start);
2273 XSETINT (args[2], end);
2275 /* But don't call them if we can tell that the work
2276 has already been done. */
2277 if (!NILP (Vbuffer_access_fontified_property))
2279 tem = Ftext_property_any (args[1], args[2],
2280 Vbuffer_access_fontified_property,
2281 Qnil, Qnil);
2282 if (! NILP (tem))
2283 Frun_hook_with_args (3, args);
2285 else
2286 Frun_hook_with_args (3, args);
2290 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2291 doc: /* Return the contents of part of the current buffer as a string.
2292 The two arguments START and END are character positions;
2293 they can be in either order.
2294 The string returned is multibyte if the buffer is multibyte.
2296 This function copies the text properties of that part of the buffer
2297 into the result string; if you don't want the text properties,
2298 use `buffer-substring-no-properties' instead. */)
2299 (start, end)
2300 Lisp_Object start, end;
2302 register int b, e;
2304 validate_region (&start, &end);
2305 b = XINT (start);
2306 e = XINT (end);
2308 return make_buffer_string (b, e, 1);
2311 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2312 Sbuffer_substring_no_properties, 2, 2, 0,
2313 doc: /* Return the characters of part of the buffer, without the text properties.
2314 The two arguments START and END are character positions;
2315 they can be in either order. */)
2316 (start, end)
2317 Lisp_Object start, end;
2319 register int b, e;
2321 validate_region (&start, &end);
2322 b = XINT (start);
2323 e = XINT (end);
2325 return make_buffer_string (b, e, 0);
2328 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2329 doc: /* Return the contents of the current buffer as a string.
2330 If narrowing is in effect, this function returns only the visible part
2331 of the buffer. */)
2334 return make_buffer_string (BEGV, ZV, 1);
2337 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2338 1, 3, 0,
2339 doc: /* Insert before point a substring of the contents of buffer BUFFER.
2340 BUFFER may be a buffer or a buffer name.
2341 Arguments START and END are character numbers specifying the substring.
2342 They default to the beginning and the end of BUFFER. */)
2343 (buf, start, end)
2344 Lisp_Object buf, start, end;
2346 register int b, e, temp;
2347 register struct buffer *bp, *obuf;
2348 Lisp_Object buffer;
2350 buffer = Fget_buffer (buf);
2351 if (NILP (buffer))
2352 nsberror (buf);
2353 bp = XBUFFER (buffer);
2354 if (NILP (bp->name))
2355 error ("Selecting deleted buffer");
2357 if (NILP (start))
2358 b = BUF_BEGV (bp);
2359 else
2361 CHECK_NUMBER_COERCE_MARKER (start);
2362 b = XINT (start);
2364 if (NILP (end))
2365 e = BUF_ZV (bp);
2366 else
2368 CHECK_NUMBER_COERCE_MARKER (end);
2369 e = XINT (end);
2372 if (b > e)
2373 temp = b, b = e, e = temp;
2375 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2376 args_out_of_range (start, end);
2378 obuf = current_buffer;
2379 set_buffer_internal_1 (bp);
2380 update_buffer_properties (b, e);
2381 set_buffer_internal_1 (obuf);
2383 insert_from_buffer (bp, b, e - b, 0);
2384 return Qnil;
2387 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2388 6, 6, 0,
2389 doc: /* Compare two substrings of two buffers; return result as number.
2390 the value is -N if first string is less after N-1 chars,
2391 +N if first string is greater after N-1 chars, or 0 if strings match.
2392 Each substring is represented as three arguments: BUFFER, START and END.
2393 That makes six args in all, three for each substring.
2395 The value of `case-fold-search' in the current buffer
2396 determines whether case is significant or ignored. */)
2397 (buffer1, start1, end1, buffer2, start2, end2)
2398 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
2400 register int begp1, endp1, begp2, endp2, temp;
2401 register struct buffer *bp1, *bp2;
2402 register Lisp_Object *trt
2403 = (!NILP (current_buffer->case_fold_search)
2404 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents : 0);
2405 int chars = 0;
2406 int i1, i2, i1_byte, i2_byte;
2408 /* Find the first buffer and its substring. */
2410 if (NILP (buffer1))
2411 bp1 = current_buffer;
2412 else
2414 Lisp_Object buf1;
2415 buf1 = Fget_buffer (buffer1);
2416 if (NILP (buf1))
2417 nsberror (buffer1);
2418 bp1 = XBUFFER (buf1);
2419 if (NILP (bp1->name))
2420 error ("Selecting deleted buffer");
2423 if (NILP (start1))
2424 begp1 = BUF_BEGV (bp1);
2425 else
2427 CHECK_NUMBER_COERCE_MARKER (start1);
2428 begp1 = XINT (start1);
2430 if (NILP (end1))
2431 endp1 = BUF_ZV (bp1);
2432 else
2434 CHECK_NUMBER_COERCE_MARKER (end1);
2435 endp1 = XINT (end1);
2438 if (begp1 > endp1)
2439 temp = begp1, begp1 = endp1, endp1 = temp;
2441 if (!(BUF_BEGV (bp1) <= begp1
2442 && begp1 <= endp1
2443 && endp1 <= BUF_ZV (bp1)))
2444 args_out_of_range (start1, end1);
2446 /* Likewise for second substring. */
2448 if (NILP (buffer2))
2449 bp2 = current_buffer;
2450 else
2452 Lisp_Object buf2;
2453 buf2 = Fget_buffer (buffer2);
2454 if (NILP (buf2))
2455 nsberror (buffer2);
2456 bp2 = XBUFFER (buf2);
2457 if (NILP (bp2->name))
2458 error ("Selecting deleted buffer");
2461 if (NILP (start2))
2462 begp2 = BUF_BEGV (bp2);
2463 else
2465 CHECK_NUMBER_COERCE_MARKER (start2);
2466 begp2 = XINT (start2);
2468 if (NILP (end2))
2469 endp2 = BUF_ZV (bp2);
2470 else
2472 CHECK_NUMBER_COERCE_MARKER (end2);
2473 endp2 = XINT (end2);
2476 if (begp2 > endp2)
2477 temp = begp2, begp2 = endp2, endp2 = temp;
2479 if (!(BUF_BEGV (bp2) <= begp2
2480 && begp2 <= endp2
2481 && endp2 <= BUF_ZV (bp2)))
2482 args_out_of_range (start2, end2);
2484 i1 = begp1;
2485 i2 = begp2;
2486 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2487 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2489 while (i1 < endp1 && i2 < endp2)
2491 /* When we find a mismatch, we must compare the
2492 characters, not just the bytes. */
2493 int c1, c2;
2495 QUIT;
2497 if (! NILP (bp1->enable_multibyte_characters))
2499 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2500 BUF_INC_POS (bp1, i1_byte);
2501 i1++;
2503 else
2505 c1 = BUF_FETCH_BYTE (bp1, i1);
2506 c1 = unibyte_char_to_multibyte (c1);
2507 i1++;
2510 if (! NILP (bp2->enable_multibyte_characters))
2512 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2513 BUF_INC_POS (bp2, i2_byte);
2514 i2++;
2516 else
2518 c2 = BUF_FETCH_BYTE (bp2, i2);
2519 c2 = unibyte_char_to_multibyte (c2);
2520 i2++;
2523 if (trt)
2525 c1 = XINT (trt[c1]);
2526 c2 = XINT (trt[c2]);
2528 if (c1 < c2)
2529 return make_number (- 1 - chars);
2530 if (c1 > c2)
2531 return make_number (chars + 1);
2533 chars++;
2536 /* The strings match as far as they go.
2537 If one is shorter, that one is less. */
2538 if (chars < endp1 - begp1)
2539 return make_number (chars + 1);
2540 else if (chars < endp2 - begp2)
2541 return make_number (- chars - 1);
2543 /* Same length too => they are equal. */
2544 return make_number (0);
2547 static Lisp_Object
2548 subst_char_in_region_unwind (arg)
2549 Lisp_Object arg;
2551 return current_buffer->undo_list = arg;
2554 static Lisp_Object
2555 subst_char_in_region_unwind_1 (arg)
2556 Lisp_Object arg;
2558 return current_buffer->filename = arg;
2561 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2562 Ssubst_char_in_region, 4, 5, 0,
2563 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
2564 If optional arg NOUNDO is non-nil, don't record this change for undo
2565 and don't mark the buffer as really changed.
2566 Both characters must have the same length of multi-byte form. */)
2567 (start, end, fromchar, tochar, noundo)
2568 Lisp_Object start, end, fromchar, tochar, noundo;
2570 register int pos, pos_byte, stop, i, len, end_byte;
2571 int changed = 0;
2572 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2573 unsigned char *p;
2574 int count = SPECPDL_INDEX ();
2575 #define COMBINING_NO 0
2576 #define COMBINING_BEFORE 1
2577 #define COMBINING_AFTER 2
2578 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2579 int maybe_byte_combining = COMBINING_NO;
2580 int last_changed = 0;
2581 int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
2583 validate_region (&start, &end);
2584 CHECK_NUMBER (fromchar);
2585 CHECK_NUMBER (tochar);
2587 if (multibyte_p)
2589 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2590 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
2591 error ("Characters in subst-char-in-region have different byte-lengths");
2592 if (!ASCII_BYTE_P (*tostr))
2594 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2595 complete multibyte character, it may be combined with the
2596 after bytes. If it is in the range 0xA0..0xFF, it may be
2597 combined with the before and after bytes. */
2598 if (!CHAR_HEAD_P (*tostr))
2599 maybe_byte_combining = COMBINING_BOTH;
2600 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2601 maybe_byte_combining = COMBINING_AFTER;
2604 else
2606 len = 1;
2607 fromstr[0] = XFASTINT (fromchar);
2608 tostr[0] = XFASTINT (tochar);
2611 pos = XINT (start);
2612 pos_byte = CHAR_TO_BYTE (pos);
2613 stop = CHAR_TO_BYTE (XINT (end));
2614 end_byte = stop;
2616 /* If we don't want undo, turn off putting stuff on the list.
2617 That's faster than getting rid of things,
2618 and it prevents even the entry for a first change.
2619 Also inhibit locking the file. */
2620 if (!NILP (noundo))
2622 record_unwind_protect (subst_char_in_region_unwind,
2623 current_buffer->undo_list);
2624 current_buffer->undo_list = Qt;
2625 /* Don't do file-locking. */
2626 record_unwind_protect (subst_char_in_region_unwind_1,
2627 current_buffer->filename);
2628 current_buffer->filename = Qnil;
2631 if (pos_byte < GPT_BYTE)
2632 stop = min (stop, GPT_BYTE);
2633 while (1)
2635 int pos_byte_next = pos_byte;
2637 if (pos_byte >= stop)
2639 if (pos_byte >= end_byte) break;
2640 stop = end_byte;
2642 p = BYTE_POS_ADDR (pos_byte);
2643 if (multibyte_p)
2644 INC_POS (pos_byte_next);
2645 else
2646 ++pos_byte_next;
2647 if (pos_byte_next - pos_byte == len
2648 && p[0] == fromstr[0]
2649 && (len == 1
2650 || (p[1] == fromstr[1]
2651 && (len == 2 || (p[2] == fromstr[2]
2652 && (len == 3 || p[3] == fromstr[3]))))))
2654 if (! changed)
2656 changed = pos;
2657 modify_region (current_buffer, changed, XINT (end));
2659 if (! NILP (noundo))
2661 if (MODIFF - 1 == SAVE_MODIFF)
2662 SAVE_MODIFF++;
2663 if (MODIFF - 1 == current_buffer->auto_save_modified)
2664 current_buffer->auto_save_modified++;
2668 /* Take care of the case where the new character
2669 combines with neighboring bytes. */
2670 if (maybe_byte_combining
2671 && (maybe_byte_combining == COMBINING_AFTER
2672 ? (pos_byte_next < Z_BYTE
2673 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2674 : ((pos_byte_next < Z_BYTE
2675 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2676 || (pos_byte > BEG_BYTE
2677 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2679 Lisp_Object tem, string;
2681 struct gcpro gcpro1;
2683 tem = current_buffer->undo_list;
2684 GCPRO1 (tem);
2686 /* Make a multibyte string containing this single character. */
2687 string = make_multibyte_string (tostr, 1, len);
2688 /* replace_range is less efficient, because it moves the gap,
2689 but it handles combining correctly. */
2690 replace_range (pos, pos + 1, string,
2691 0, 0, 1);
2692 pos_byte_next = CHAR_TO_BYTE (pos);
2693 if (pos_byte_next > pos_byte)
2694 /* Before combining happened. We should not increment
2695 POS. So, to cancel the later increment of POS,
2696 decrease it now. */
2697 pos--;
2698 else
2699 INC_POS (pos_byte_next);
2701 if (! NILP (noundo))
2702 current_buffer->undo_list = tem;
2704 UNGCPRO;
2706 else
2708 if (NILP (noundo))
2709 record_change (pos, 1);
2710 for (i = 0; i < len; i++) *p++ = tostr[i];
2712 last_changed = pos + 1;
2714 pos_byte = pos_byte_next;
2715 pos++;
2718 if (changed)
2720 signal_after_change (changed,
2721 last_changed - changed, last_changed - changed);
2722 update_compositions (changed, last_changed, CHECK_ALL);
2725 unbind_to (count, Qnil);
2726 return Qnil;
2729 DEFUN ("translate-region", Ftranslate_region, Stranslate_region, 3, 3, 0,
2730 doc: /* From START to END, translate characters according to TABLE.
2731 TABLE is a string; the Nth character in it is the mapping
2732 for the character with code N.
2733 This function does not alter multibyte characters.
2734 It returns the number of characters changed. */)
2735 (start, end, table)
2736 Lisp_Object start;
2737 Lisp_Object end;
2738 register Lisp_Object table;
2740 register int pos_byte, stop; /* Limits of the region. */
2741 register unsigned char *tt; /* Trans table. */
2742 register int nc; /* New character. */
2743 int cnt; /* Number of changes made. */
2744 int size; /* Size of translate table. */
2745 int pos;
2746 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
2748 validate_region (&start, &end);
2749 CHECK_STRING (table);
2751 size = SBYTES (table);
2752 tt = SDATA (table);
2754 pos_byte = CHAR_TO_BYTE (XINT (start));
2755 stop = CHAR_TO_BYTE (XINT (end));
2756 modify_region (current_buffer, XINT (start), XINT (end));
2757 pos = XINT (start);
2759 cnt = 0;
2760 for (; pos_byte < stop; )
2762 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
2763 int len;
2764 int oc;
2765 int pos_byte_next;
2767 if (multibyte)
2768 oc = STRING_CHAR_AND_LENGTH (p, stop - pos_byte, len);
2769 else
2770 oc = *p, len = 1;
2771 pos_byte_next = pos_byte + len;
2772 if (oc < size && len == 1)
2774 nc = tt[oc];
2775 if (nc != oc)
2777 /* Take care of the case where the new character
2778 combines with neighboring bytes. */
2779 if (!ASCII_BYTE_P (nc)
2780 && (CHAR_HEAD_P (nc)
2781 ? ! CHAR_HEAD_P (FETCH_BYTE (pos_byte + 1))
2782 : (pos_byte > BEG_BYTE
2783 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1)))))
2785 Lisp_Object string;
2787 string = make_multibyte_string (tt + oc, 1, 1);
2788 /* This is less efficient, because it moves the gap,
2789 but it handles combining correctly. */
2790 replace_range (pos, pos + 1, string,
2791 1, 0, 1);
2792 pos_byte_next = CHAR_TO_BYTE (pos);
2793 if (pos_byte_next > pos_byte)
2794 /* Before combining happened. We should not
2795 increment POS. So, to cancel the later
2796 increment of POS, we decrease it now. */
2797 pos--;
2798 else
2799 INC_POS (pos_byte_next);
2801 else
2803 record_change (pos, 1);
2804 *p = nc;
2805 signal_after_change (pos, 1, 1);
2806 update_compositions (pos, pos + 1, CHECK_BORDER);
2808 ++cnt;
2811 pos_byte = pos_byte_next;
2812 pos++;
2815 return make_number (cnt);
2818 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
2819 doc: /* Delete the text between point and mark.
2820 When called from a program, expects two arguments,
2821 positions (integers or markers) specifying the stretch to be deleted. */)
2822 (start, end)
2823 Lisp_Object start, end;
2825 validate_region (&start, &end);
2826 del_range (XINT (start), XINT (end));
2827 return Qnil;
2830 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
2831 Sdelete_and_extract_region, 2, 2, 0,
2832 doc: /* Delete the text between START and END and return it. */)
2833 (start, end)
2834 Lisp_Object start, end;
2836 validate_region (&start, &end);
2837 return del_range_1 (XINT (start), XINT (end), 1, 1);
2840 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
2841 doc: /* Remove restrictions (narrowing) from current buffer.
2842 This allows the buffer's full text to be seen and edited. */)
2845 if (BEG != BEGV || Z != ZV)
2846 current_buffer->clip_changed = 1;
2847 BEGV = BEG;
2848 BEGV_BYTE = BEG_BYTE;
2849 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
2850 /* Changing the buffer bounds invalidates any recorded current column. */
2851 invalidate_current_column ();
2852 return Qnil;
2855 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
2856 doc: /* Restrict editing in this buffer to the current region.
2857 The rest of the text becomes temporarily invisible and untouchable
2858 but is not deleted; if you save the buffer in a file, the invisible
2859 text is included in the file. \\[widen] makes all visible again.
2860 See also `save-restriction'.
2862 When calling from a program, pass two arguments; positions (integers
2863 or markers) bounding the text that should remain visible. */)
2864 (start, end)
2865 register Lisp_Object start, end;
2867 CHECK_NUMBER_COERCE_MARKER (start);
2868 CHECK_NUMBER_COERCE_MARKER (end);
2870 if (XINT (start) > XINT (end))
2872 Lisp_Object tem;
2873 tem = start; start = end; end = tem;
2876 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
2877 args_out_of_range (start, end);
2879 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
2880 current_buffer->clip_changed = 1;
2882 SET_BUF_BEGV (current_buffer, XFASTINT (start));
2883 SET_BUF_ZV (current_buffer, XFASTINT (end));
2884 if (PT < XFASTINT (start))
2885 SET_PT (XFASTINT (start));
2886 if (PT > XFASTINT (end))
2887 SET_PT (XFASTINT (end));
2888 /* Changing the buffer bounds invalidates any recorded current column. */
2889 invalidate_current_column ();
2890 return Qnil;
2893 Lisp_Object
2894 save_restriction_save ()
2896 if (BEGV == BEG && ZV == Z)
2897 /* The common case that the buffer isn't narrowed.
2898 We return just the buffer object, which save_restriction_restore
2899 recognizes as meaning `no restriction'. */
2900 return Fcurrent_buffer ();
2901 else
2902 /* We have to save a restriction, so return a pair of markers, one
2903 for the beginning and one for the end. */
2905 Lisp_Object beg, end;
2907 beg = buildmark (BEGV, BEGV_BYTE);
2908 end = buildmark (ZV, ZV_BYTE);
2910 /* END must move forward if text is inserted at its exact location. */
2911 XMARKER(end)->insertion_type = 1;
2913 return Fcons (beg, end);
2917 Lisp_Object
2918 save_restriction_restore (data)
2919 Lisp_Object data;
2921 if (CONSP (data))
2922 /* A pair of marks bounding a saved restriction. */
2924 struct Lisp_Marker *beg = XMARKER (XCAR (data));
2925 struct Lisp_Marker *end = XMARKER (XCDR (data));
2926 struct buffer *buf = beg->buffer; /* END should have the same buffer. */
2928 if (buf /* Verify marker still points to a buffer. */
2929 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
2930 /* The restriction has changed from the saved one, so restore
2931 the saved restriction. */
2933 int pt = BUF_PT (buf);
2935 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
2936 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
2938 if (pt < beg->charpos || pt > end->charpos)
2939 /* The point is outside the new visible range, move it inside. */
2940 SET_BUF_PT_BOTH (buf,
2941 clip_to_bounds (beg->charpos, pt, end->charpos),
2942 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
2943 end->bytepos));
2945 buf->clip_changed = 1; /* Remember that the narrowing changed. */
2948 else
2949 /* A buffer, which means that there was no old restriction. */
2951 struct buffer *buf = XBUFFER (data);
2953 if (buf /* Verify marker still points to a buffer. */
2954 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
2955 /* The buffer has been narrowed, get rid of the narrowing. */
2957 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
2958 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
2960 buf->clip_changed = 1; /* Remember that the narrowing changed. */
2964 return Qnil;
2967 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
2968 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
2969 The buffer's restrictions make parts of the beginning and end invisible.
2970 (They are set up with `narrow-to-region' and eliminated with `widen'.)
2971 This special form, `save-restriction', saves the current buffer's restrictions
2972 when it is entered, and restores them when it is exited.
2973 So any `narrow-to-region' within BODY lasts only until the end of the form.
2974 The old restrictions settings are restored
2975 even in case of abnormal exit (throw or error).
2977 The value returned is the value of the last form in BODY.
2979 Note: if you are using both `save-excursion' and `save-restriction',
2980 use `save-excursion' outermost:
2981 (save-excursion (save-restriction ...))
2983 usage: (save-restriction &rest BODY) */)
2984 (body)
2985 Lisp_Object body;
2987 register Lisp_Object val;
2988 int count = SPECPDL_INDEX ();
2990 record_unwind_protect (save_restriction_restore, save_restriction_save ());
2991 val = Fprogn (body);
2992 return unbind_to (count, val);
2995 /* Buffer for the most recent text displayed by Fmessage_box. */
2996 static char *message_text;
2998 /* Allocated length of that buffer. */
2999 static int message_length;
3001 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3002 doc: /* Print a one-line message at the bottom of the screen.
3003 The first argument is a format control string, and the rest are data
3004 to be formatted under control of the string. See `format' for details.
3006 If the first argument is nil, clear any existing message; let the
3007 minibuffer contents show.
3009 usage: (message STRING &rest ARGS) */)
3010 (nargs, args)
3011 int nargs;
3012 Lisp_Object *args;
3014 if (NILP (args[0])
3015 || (STRINGP (args[0])
3016 && SBYTES (args[0]) == 0))
3018 message (0);
3019 return Qnil;
3021 else
3023 register Lisp_Object val;
3024 val = nargs < 2 && STRINGP (args[0]) ? args[0] : Fformat (nargs, args);
3025 message3 (val, SBYTES (val), STRING_MULTIBYTE (val));
3026 return val;
3030 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3031 doc: /* Display a message, in a dialog box if possible.
3032 If a dialog box is not available, use the echo area.
3033 The first argument is a format control string, and the rest are data
3034 to be formatted under control of the string. See `format' for details.
3036 If the first argument is nil, clear any existing message; let the
3037 minibuffer contents show.
3039 usage: (message-box STRING &rest ARGS) */)
3040 (nargs, args)
3041 int nargs;
3042 Lisp_Object *args;
3044 if (NILP (args[0]))
3046 message (0);
3047 return Qnil;
3049 else
3051 register Lisp_Object val;
3052 val = Fformat (nargs, args);
3053 #ifdef HAVE_MENUS
3054 /* The MS-DOS frames support popup menus even though they are
3055 not FRAME_WINDOW_P. */
3056 if (FRAME_WINDOW_P (XFRAME (selected_frame))
3057 || FRAME_MSDOS_P (XFRAME (selected_frame)))
3059 Lisp_Object pane, menu, obj;
3060 struct gcpro gcpro1;
3061 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
3062 GCPRO1 (pane);
3063 menu = Fcons (val, pane);
3064 obj = Fx_popup_dialog (Qt, menu);
3065 UNGCPRO;
3066 return val;
3068 #endif /* HAVE_MENUS */
3069 /* Copy the data so that it won't move when we GC. */
3070 if (! message_text)
3072 message_text = (char *)xmalloc (80);
3073 message_length = 80;
3075 if (SBYTES (val) > message_length)
3077 message_length = SBYTES (val);
3078 message_text = (char *)xrealloc (message_text, message_length);
3080 bcopy (SDATA (val), message_text, SBYTES (val));
3081 message2 (message_text, SBYTES (val),
3082 STRING_MULTIBYTE (val));
3083 return val;
3086 #ifdef HAVE_MENUS
3087 extern Lisp_Object last_nonmenu_event;
3088 #endif
3090 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3091 doc: /* Display a message in a dialog box or in the echo area.
3092 If this command was invoked with the mouse, use a dialog box if
3093 `use-dialog-box' is non-nil.
3094 Otherwise, use the echo area.
3095 The first argument is a format control string, and the rest are data
3096 to be formatted under control of the string. See `format' for details.
3098 If the first argument is nil, clear any existing message; let the
3099 minibuffer contents show.
3101 usage: (message-or-box STRING &rest ARGS) */)
3102 (nargs, args)
3103 int nargs;
3104 Lisp_Object *args;
3106 #ifdef HAVE_MENUS
3107 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3108 && use_dialog_box)
3109 return Fmessage_box (nargs, args);
3110 #endif
3111 return Fmessage (nargs, args);
3114 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3115 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3118 return current_message ();
3122 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3123 doc: /* Return a copy of STRING with text properties added.
3124 First argument is the string to copy.
3125 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3126 properties to add to the result.
3127 usage: (propertize STRING &rest PROPERTIES) */)
3128 (nargs, args)
3129 int nargs;
3130 Lisp_Object *args;
3132 Lisp_Object properties, string;
3133 struct gcpro gcpro1, gcpro2;
3134 int i;
3136 /* Number of args must be odd. */
3137 if ((nargs & 1) == 0 || nargs < 1)
3138 error ("Wrong number of arguments");
3140 properties = string = Qnil;
3141 GCPRO2 (properties, string);
3143 /* First argument must be a string. */
3144 CHECK_STRING (args[0]);
3145 string = Fcopy_sequence (args[0]);
3147 for (i = 1; i < nargs; i += 2)
3149 CHECK_SYMBOL (args[i]);
3150 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3153 Fadd_text_properties (make_number (0),
3154 make_number (SCHARS (string)),
3155 properties, string);
3156 RETURN_UNGCPRO (string);
3160 /* Number of bytes that STRING will occupy when put into the result.
3161 MULTIBYTE is nonzero if the result should be multibyte. */
3163 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3164 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
3165 ? count_size_as_multibyte (SDATA (STRING), SBYTES (STRING)) \
3166 : SBYTES (STRING))
3168 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3169 doc: /* Format a string out of a control-string and arguments.
3170 The first argument is a control string.
3171 The other arguments are substituted into it to make the result, a string.
3172 It may contain %-sequences meaning to substitute the next argument.
3173 %s means print a string argument. Actually, prints any object, with `princ'.
3174 %d means print as number in decimal (%o octal, %x hex).
3175 %X is like %x, but uses upper case.
3176 %e means print a number in exponential notation.
3177 %f means print a number in decimal-point notation.
3178 %g means print a number in exponential notation
3179 or decimal-point notation, whichever uses fewer characters.
3180 %c means print a number as a single character.
3181 %S means print any object as an s-expression (using `prin1').
3182 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3183 Use %% to put a single % into the output.
3185 usage: (format STRING &rest OBJECTS) */)
3186 (nargs, args)
3187 int nargs;
3188 register Lisp_Object *args;
3190 register int n; /* The number of the next arg to substitute */
3191 register int total; /* An estimate of the final length */
3192 char *buf, *p;
3193 register unsigned char *format, *end;
3194 int nchars;
3195 /* Nonzero if the output should be a multibyte string,
3196 which is true if any of the inputs is one. */
3197 int multibyte = 0;
3198 /* When we make a multibyte string, we must pay attention to the
3199 byte combining problem, i.e., a byte may be combined with a
3200 multibyte charcter of the previous string. This flag tells if we
3201 must consider such a situation or not. */
3202 int maybe_combine_byte;
3203 unsigned char *this_format;
3204 int longest_format;
3205 Lisp_Object val;
3206 struct info
3208 int start, end;
3209 } *info = 0;
3211 /* It should not be necessary to GCPRO ARGS, because
3212 the caller in the interpreter should take care of that. */
3214 /* Try to determine whether the result should be multibyte.
3215 This is not always right; sometimes the result needs to be multibyte
3216 because of an object that we will pass through prin1,
3217 and in that case, we won't know it here. */
3218 for (n = 0; n < nargs; n++)
3219 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3220 multibyte = 1;
3222 CHECK_STRING (args[0]);
3224 /* If we start out planning a unibyte result,
3225 and later find it has to be multibyte, we jump back to retry. */
3226 retry:
3228 format = SDATA (args[0]);
3229 end = format + SBYTES (args[0]);
3230 longest_format = 0;
3232 /* Make room in result for all the non-%-codes in the control string. */
3233 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]);
3235 /* Add to TOTAL enough space to hold the converted arguments. */
3237 n = 0;
3238 while (format != end)
3239 if (*format++ == '%')
3241 int thissize = 0;
3242 int actual_width = 0;
3243 unsigned char *this_format_start = format - 1;
3244 int field_width, precision;
3246 /* General format specifications look like
3248 '%' [flags] [field-width] [precision] format
3250 where
3252 flags ::= [#-* 0]+
3253 field-width ::= [0-9]+
3254 precision ::= '.' [0-9]*
3256 If a field-width is specified, it specifies to which width
3257 the output should be padded with blanks, iff the output
3258 string is shorter than field-width.
3260 if precision is specified, it specifies the number of
3261 digits to print after the '.' for floats, or the max.
3262 number of chars to print from a string. */
3264 precision = field_width = 0;
3266 while (index ("-*# 0", *format))
3267 ++format;
3269 if (*format >= '0' && *format <= '9')
3271 for (field_width = 0; *format >= '0' && *format <= '9'; ++format)
3272 field_width = 10 * field_width + *format - '0';
3275 if (*format == '.')
3277 ++format;
3278 for (precision = 0; *format >= '0' && *format <= '9'; ++format)
3279 precision = 10 * precision + *format - '0';
3282 if (format - this_format_start + 1 > longest_format)
3283 longest_format = format - this_format_start + 1;
3285 if (format == end)
3286 error ("Format string ends in middle of format specifier");
3287 if (*format == '%')
3288 format++;
3289 else if (++n >= nargs)
3290 error ("Not enough arguments for format string");
3291 else if (*format == 'S')
3293 /* For `S', prin1 the argument and then treat like a string. */
3294 register Lisp_Object tem;
3295 tem = Fprin1_to_string (args[n], Qnil);
3296 if (STRING_MULTIBYTE (tem) && ! multibyte)
3298 multibyte = 1;
3299 goto retry;
3301 args[n] = tem;
3302 goto string;
3304 else if (SYMBOLP (args[n]))
3306 args[n] = SYMBOL_NAME (args[n]);
3307 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3309 multibyte = 1;
3310 goto retry;
3312 goto string;
3314 else if (STRINGP (args[n]))
3316 string:
3317 if (*format != 's' && *format != 'S')
3318 error ("Format specifier doesn't match argument type");
3319 thissize = CONVERTED_BYTE_SIZE (multibyte, args[n]);
3320 actual_width = lisp_string_width (args[n], -1, NULL, NULL);
3322 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3323 else if (INTEGERP (args[n]) && *format != 's')
3325 /* The following loop assumes the Lisp type indicates
3326 the proper way to pass the argument.
3327 So make sure we have a flonum if the argument should
3328 be a double. */
3329 if (*format == 'e' || *format == 'f' || *format == 'g')
3330 args[n] = Ffloat (args[n]);
3331 else
3332 if (*format != 'd' && *format != 'o' && *format != 'x'
3333 && *format != 'i' && *format != 'X' && *format != 'c')
3334 error ("Invalid format operation %%%c", *format);
3336 thissize = 30;
3337 if (*format == 'c'
3338 && (! SINGLE_BYTE_CHAR_P (XINT (args[n]))
3339 || XINT (args[n]) == 0))
3341 if (! multibyte)
3343 multibyte = 1;
3344 goto retry;
3346 args[n] = Fchar_to_string (args[n]);
3347 thissize = SBYTES (args[n]);
3350 else if (FLOATP (args[n]) && *format != 's')
3352 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3354 if (*format != 'd' && *format != 'o' && *format != 'x'
3355 && *format != 'i' && *format != 'X' && *format != 'c')
3356 error ("Invalid format operation %%%c", *format);
3357 args[n] = Ftruncate (args[n], Qnil);
3360 /* Note that we're using sprintf to print floats,
3361 so we have to take into account what that function
3362 prints. */
3363 thissize = MAX_10_EXP + 100 + precision;
3365 else
3367 /* Anything but a string, convert to a string using princ. */
3368 register Lisp_Object tem;
3369 tem = Fprin1_to_string (args[n], Qt);
3370 if (STRING_MULTIBYTE (tem) & ! multibyte)
3372 multibyte = 1;
3373 goto retry;
3375 args[n] = tem;
3376 goto string;
3379 thissize += max (0, field_width - actual_width);
3380 total += thissize + 4;
3383 /* Now we can no longer jump to retry.
3384 TOTAL and LONGEST_FORMAT are known for certain. */
3386 this_format = (unsigned char *) alloca (longest_format + 1);
3388 /* Allocate the space for the result.
3389 Note that TOTAL is an overestimate. */
3390 if (total < 1000)
3391 buf = (char *) alloca (total + 1);
3392 else
3393 buf = (char *) xmalloc (total + 1);
3395 p = buf;
3396 nchars = 0;
3397 n = 0;
3399 /* Scan the format and store result in BUF. */
3400 format = SDATA (args[0]);
3401 maybe_combine_byte = 0;
3402 while (format != end)
3404 if (*format == '%')
3406 int minlen;
3407 int negative = 0;
3408 unsigned char *this_format_start = format;
3410 format++;
3412 /* Process a numeric arg and skip it. */
3413 minlen = atoi (format);
3414 if (minlen < 0)
3415 minlen = - minlen, negative = 1;
3417 while ((*format >= '0' && *format <= '9')
3418 || *format == '-' || *format == ' ' || *format == '.')
3419 format++;
3421 if (*format++ == '%')
3423 *p++ = '%';
3424 nchars++;
3425 continue;
3428 ++n;
3430 if (STRINGP (args[n]))
3432 int padding, nbytes, start, end;
3433 int width = lisp_string_width (args[n], -1, NULL, NULL);
3435 /* If spec requires it, pad on right with spaces. */
3436 padding = minlen - width;
3437 if (! negative)
3438 while (padding-- > 0)
3440 *p++ = ' ';
3441 ++nchars;
3444 start = nchars;
3446 if (p > buf
3447 && multibyte
3448 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3449 && STRING_MULTIBYTE (args[n])
3450 && !CHAR_HEAD_P (SREF (args[n], 0)))
3451 maybe_combine_byte = 1;
3452 nbytes = copy_text (SDATA (args[n]), p,
3453 SBYTES (args[n]),
3454 STRING_MULTIBYTE (args[n]), multibyte);
3455 p += nbytes;
3456 nchars += SCHARS (args[n]);
3457 end = nchars;
3459 if (negative)
3460 while (padding-- > 0)
3462 *p++ = ' ';
3463 nchars++;
3466 /* If this argument has text properties, record where
3467 in the result string it appears. */
3468 if (STRING_INTERVALS (args[n]))
3470 if (!info)
3472 int nbytes = nargs * sizeof *info;
3473 info = (struct info *) alloca (nbytes);
3474 bzero (info, nbytes);
3477 info[n].start = start;
3478 info[n].end = end;
3481 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3483 int this_nchars;
3485 bcopy (this_format_start, this_format,
3486 format - this_format_start);
3487 this_format[format - this_format_start] = 0;
3489 if (INTEGERP (args[n]))
3490 sprintf (p, this_format, XINT (args[n]));
3491 else
3492 sprintf (p, this_format, XFLOAT_DATA (args[n]));
3494 if (p > buf
3495 && multibyte
3496 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3497 && !CHAR_HEAD_P (*((unsigned char *) p)))
3498 maybe_combine_byte = 1;
3499 this_nchars = strlen (p);
3500 if (multibyte)
3501 p += str_to_multibyte (p, buf + total - p, this_nchars);
3502 else
3503 p += this_nchars;
3504 nchars += this_nchars;
3507 else if (STRING_MULTIBYTE (args[0]))
3509 /* Copy a whole multibyte character. */
3510 if (p > buf
3511 && multibyte
3512 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3513 && !CHAR_HEAD_P (*format))
3514 maybe_combine_byte = 1;
3515 *p++ = *format++;
3516 while (! CHAR_HEAD_P (*format)) *p++ = *format++;
3517 nchars++;
3519 else if (multibyte)
3521 /* Convert a single-byte character to multibyte. */
3522 int len = copy_text (format, p, 1, 0, 1);
3524 p += len;
3525 format++;
3526 nchars++;
3528 else
3529 *p++ = *format++, nchars++;
3532 if (p > buf + total + 1)
3533 abort ();
3535 if (maybe_combine_byte)
3536 nchars = multibyte_chars_in_text (buf, p - buf);
3537 val = make_specified_string (buf, nchars, p - buf, multibyte);
3539 /* If we allocated BUF with malloc, free it too. */
3540 if (total >= 1000)
3541 xfree (buf);
3543 /* If the format string has text properties, or any of the string
3544 arguments has text properties, set up text properties of the
3545 result string. */
3547 if (STRING_INTERVALS (args[0]) || info)
3549 Lisp_Object len, new_len, props;
3550 struct gcpro gcpro1;
3552 /* Add text properties from the format string. */
3553 len = make_number (SCHARS (args[0]));
3554 props = text_property_list (args[0], make_number (0), len, Qnil);
3555 GCPRO1 (props);
3557 if (CONSP (props))
3559 new_len = make_number (SCHARS (val));
3560 extend_property_ranges (props, len, new_len);
3561 add_text_properties_from_list (val, props, make_number (0));
3564 /* Add text properties from arguments. */
3565 if (info)
3566 for (n = 1; n < nargs; ++n)
3567 if (info[n].end)
3569 len = make_number (SCHARS (args[n]));
3570 new_len = make_number (info[n].end - info[n].start);
3571 props = text_property_list (args[n], make_number (0), len, Qnil);
3572 extend_property_ranges (props, len, new_len);
3573 /* If successive arguments have properites, be sure that
3574 the value of `composition' property be the copy. */
3575 if (n > 1 && info[n - 1].end)
3576 make_composition_value_copy (props);
3577 add_text_properties_from_list (val, props,
3578 make_number (info[n].start));
3581 UNGCPRO;
3584 return val;
3588 /* VARARGS 1 */
3589 Lisp_Object
3590 #ifdef NO_ARG_ARRAY
3591 format1 (string1, arg0, arg1, arg2, arg3, arg4)
3592 EMACS_INT arg0, arg1, arg2, arg3, arg4;
3593 #else
3594 format1 (string1)
3595 #endif
3596 char *string1;
3598 char buf[100];
3599 #ifdef NO_ARG_ARRAY
3600 EMACS_INT args[5];
3601 args[0] = arg0;
3602 args[1] = arg1;
3603 args[2] = arg2;
3604 args[3] = arg3;
3605 args[4] = arg4;
3606 doprnt (buf, sizeof buf, string1, (char *)0, 5, (char **) args);
3607 #else
3608 doprnt (buf, sizeof buf, string1, (char *)0, 5, &string1 + 1);
3609 #endif
3610 return build_string (buf);
3613 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
3614 doc: /* Return t if two characters match, optionally ignoring case.
3615 Both arguments must be characters (i.e. integers).
3616 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
3617 (c1, c2)
3618 register Lisp_Object c1, c2;
3620 int i1, i2;
3621 CHECK_NUMBER (c1);
3622 CHECK_NUMBER (c2);
3624 if (XINT (c1) == XINT (c2))
3625 return Qt;
3626 if (NILP (current_buffer->case_fold_search))
3627 return Qnil;
3629 /* Do these in separate statements,
3630 then compare the variables.
3631 because of the way DOWNCASE uses temp variables. */
3632 i1 = DOWNCASE (XFASTINT (c1));
3633 i2 = DOWNCASE (XFASTINT (c2));
3634 return (i1 == i2 ? Qt : Qnil);
3637 /* Transpose the markers in two regions of the current buffer, and
3638 adjust the ones between them if necessary (i.e.: if the regions
3639 differ in size).
3641 START1, END1 are the character positions of the first region.
3642 START1_BYTE, END1_BYTE are the byte positions.
3643 START2, END2 are the character positions of the second region.
3644 START2_BYTE, END2_BYTE are the byte positions.
3646 Traverses the entire marker list of the buffer to do so, adding an
3647 appropriate amount to some, subtracting from some, and leaving the
3648 rest untouched. Most of this is copied from adjust_markers in insdel.c.
3650 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
3652 static void
3653 transpose_markers (start1, end1, start2, end2,
3654 start1_byte, end1_byte, start2_byte, end2_byte)
3655 register int start1, end1, start2, end2;
3656 register int start1_byte, end1_byte, start2_byte, end2_byte;
3658 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
3659 register Lisp_Object marker;
3661 /* Update point as if it were a marker. */
3662 if (PT < start1)
3664 else if (PT < end1)
3665 TEMP_SET_PT_BOTH (PT + (end2 - end1),
3666 PT_BYTE + (end2_byte - end1_byte));
3667 else if (PT < start2)
3668 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
3669 (PT_BYTE + (end2_byte - start2_byte)
3670 - (end1_byte - start1_byte)));
3671 else if (PT < end2)
3672 TEMP_SET_PT_BOTH (PT - (start2 - start1),
3673 PT_BYTE - (start2_byte - start1_byte));
3675 /* We used to adjust the endpoints here to account for the gap, but that
3676 isn't good enough. Even if we assume the caller has tried to move the
3677 gap out of our way, it might still be at start1 exactly, for example;
3678 and that places it `inside' the interval, for our purposes. The amount
3679 of adjustment is nontrivial if there's a `denormalized' marker whose
3680 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
3681 the dirty work to Fmarker_position, below. */
3683 /* The difference between the region's lengths */
3684 diff = (end2 - start2) - (end1 - start1);
3685 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
3687 /* For shifting each marker in a region by the length of the other
3688 region plus the distance between the regions. */
3689 amt1 = (end2 - start2) + (start2 - end1);
3690 amt2 = (end1 - start1) + (start2 - end1);
3691 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
3692 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
3694 for (marker = BUF_MARKERS (current_buffer); !NILP (marker);
3695 marker = XMARKER (marker)->chain)
3697 mpos = marker_byte_position (marker);
3698 if (mpos >= start1_byte && mpos < end2_byte)
3700 if (mpos < end1_byte)
3701 mpos += amt1_byte;
3702 else if (mpos < start2_byte)
3703 mpos += diff_byte;
3704 else
3705 mpos -= amt2_byte;
3706 XMARKER (marker)->bytepos = mpos;
3708 mpos = XMARKER (marker)->charpos;
3709 if (mpos >= start1 && mpos < end2)
3711 if (mpos < end1)
3712 mpos += amt1;
3713 else if (mpos < start2)
3714 mpos += diff;
3715 else
3716 mpos -= amt2;
3718 XMARKER (marker)->charpos = mpos;
3722 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
3723 doc: /* Transpose region START1 to END1 with START2 to END2.
3724 The regions may not be overlapping, because the size of the buffer is
3725 never changed in a transposition.
3727 Optional fifth arg LEAVE_MARKERS, if non-nil, means don't update
3728 any markers that happen to be located in the regions.
3730 Transposing beyond buffer boundaries is an error. */)
3731 (startr1, endr1, startr2, endr2, leave_markers)
3732 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
3734 register int start1, end1, start2, end2;
3735 int start1_byte, start2_byte, len1_byte, len2_byte;
3736 int gap, len1, len_mid, len2;
3737 unsigned char *start1_addr, *start2_addr, *temp;
3739 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2;
3740 cur_intv = BUF_INTERVALS (current_buffer);
3742 validate_region (&startr1, &endr1);
3743 validate_region (&startr2, &endr2);
3745 start1 = XFASTINT (startr1);
3746 end1 = XFASTINT (endr1);
3747 start2 = XFASTINT (startr2);
3748 end2 = XFASTINT (endr2);
3749 gap = GPT;
3751 /* Swap the regions if they're reversed. */
3752 if (start2 < end1)
3754 register int glumph = start1;
3755 start1 = start2;
3756 start2 = glumph;
3757 glumph = end1;
3758 end1 = end2;
3759 end2 = glumph;
3762 len1 = end1 - start1;
3763 len2 = end2 - start2;
3765 if (start2 < end1)
3766 error ("Transposed regions overlap");
3767 else if (start1 == end1 || start2 == end2)
3768 error ("Transposed region has length 0");
3770 /* The possibilities are:
3771 1. Adjacent (contiguous) regions, or separate but equal regions
3772 (no, really equal, in this case!), or
3773 2. Separate regions of unequal size.
3775 The worst case is usually No. 2. It means that (aside from
3776 potential need for getting the gap out of the way), there also
3777 needs to be a shifting of the text between the two regions. So
3778 if they are spread far apart, we are that much slower... sigh. */
3780 /* It must be pointed out that the really studly thing to do would
3781 be not to move the gap at all, but to leave it in place and work
3782 around it if necessary. This would be extremely efficient,
3783 especially considering that people are likely to do
3784 transpositions near where they are working interactively, which
3785 is exactly where the gap would be found. However, such code
3786 would be much harder to write and to read. So, if you are
3787 reading this comment and are feeling squirrely, by all means have
3788 a go! I just didn't feel like doing it, so I will simply move
3789 the gap the minimum distance to get it out of the way, and then
3790 deal with an unbroken array. */
3792 /* Make sure the gap won't interfere, by moving it out of the text
3793 we will operate on. */
3794 if (start1 < gap && gap < end2)
3796 if (gap - start1 < end2 - gap)
3797 move_gap (start1);
3798 else
3799 move_gap (end2);
3802 start1_byte = CHAR_TO_BYTE (start1);
3803 start2_byte = CHAR_TO_BYTE (start2);
3804 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
3805 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
3807 #ifdef BYTE_COMBINING_DEBUG
3808 if (end1 == start2)
3810 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
3811 len2_byte, start1, start1_byte)
3812 || count_combining_before (BYTE_POS_ADDR (start1_byte),
3813 len1_byte, end2, start2_byte + len2_byte)
3814 || count_combining_after (BYTE_POS_ADDR (start1_byte),
3815 len1_byte, end2, start2_byte + len2_byte))
3816 abort ();
3818 else
3820 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
3821 len2_byte, start1, start1_byte)
3822 || count_combining_before (BYTE_POS_ADDR (start1_byte),
3823 len1_byte, start2, start2_byte)
3824 || count_combining_after (BYTE_POS_ADDR (start2_byte),
3825 len2_byte, end1, start1_byte + len1_byte)
3826 || count_combining_after (BYTE_POS_ADDR (start1_byte),
3827 len1_byte, end2, start2_byte + len2_byte))
3828 abort ();
3830 #endif
3832 /* Hmmm... how about checking to see if the gap is large
3833 enough to use as the temporary storage? That would avoid an
3834 allocation... interesting. Later, don't fool with it now. */
3836 /* Working without memmove, for portability (sigh), so must be
3837 careful of overlapping subsections of the array... */
3839 if (end1 == start2) /* adjacent regions */
3841 modify_region (current_buffer, start1, end2);
3842 record_change (start1, len1 + len2);
3844 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3845 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3846 Fset_text_properties (make_number (start1), make_number (end2),
3847 Qnil, Qnil);
3849 /* First region smaller than second. */
3850 if (len1_byte < len2_byte)
3852 /* We use alloca only if it is small,
3853 because we want to avoid stack overflow. */
3854 if (len2_byte > 20000)
3855 temp = (unsigned char *) xmalloc (len2_byte);
3856 else
3857 temp = (unsigned char *) alloca (len2_byte);
3859 /* Don't precompute these addresses. We have to compute them
3860 at the last minute, because the relocating allocator might
3861 have moved the buffer around during the xmalloc. */
3862 start1_addr = BYTE_POS_ADDR (start1_byte);
3863 start2_addr = BYTE_POS_ADDR (start2_byte);
3865 bcopy (start2_addr, temp, len2_byte);
3866 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
3867 bcopy (temp, start1_addr, len2_byte);
3868 if (len2_byte > 20000)
3869 xfree (temp);
3871 else
3872 /* First region not smaller than second. */
3874 if (len1_byte > 20000)
3875 temp = (unsigned char *) xmalloc (len1_byte);
3876 else
3877 temp = (unsigned char *) alloca (len1_byte);
3878 start1_addr = BYTE_POS_ADDR (start1_byte);
3879 start2_addr = BYTE_POS_ADDR (start2_byte);
3880 bcopy (start1_addr, temp, len1_byte);
3881 bcopy (start2_addr, start1_addr, len2_byte);
3882 bcopy (temp, start1_addr + len2_byte, len1_byte);
3883 if (len1_byte > 20000)
3884 xfree (temp);
3886 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
3887 len1, current_buffer, 0);
3888 graft_intervals_into_buffer (tmp_interval2, start1,
3889 len2, current_buffer, 0);
3890 update_compositions (start1, start1 + len2, CHECK_BORDER);
3891 update_compositions (start1 + len2, end2, CHECK_TAIL);
3893 /* Non-adjacent regions, because end1 != start2, bleagh... */
3894 else
3896 len_mid = start2_byte - (start1_byte + len1_byte);
3898 if (len1_byte == len2_byte)
3899 /* Regions are same size, though, how nice. */
3901 modify_region (current_buffer, start1, end1);
3902 modify_region (current_buffer, start2, end2);
3903 record_change (start1, len1);
3904 record_change (start2, len2);
3905 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3906 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3907 Fset_text_properties (make_number (start1), make_number (end1),
3908 Qnil, Qnil);
3909 Fset_text_properties (make_number (start2), make_number (end2),
3910 Qnil, Qnil);
3912 if (len1_byte > 20000)
3913 temp = (unsigned char *) xmalloc (len1_byte);
3914 else
3915 temp = (unsigned char *) alloca (len1_byte);
3916 start1_addr = BYTE_POS_ADDR (start1_byte);
3917 start2_addr = BYTE_POS_ADDR (start2_byte);
3918 bcopy (start1_addr, temp, len1_byte);
3919 bcopy (start2_addr, start1_addr, len2_byte);
3920 bcopy (temp, start2_addr, len1_byte);
3921 if (len1_byte > 20000)
3922 xfree (temp);
3923 graft_intervals_into_buffer (tmp_interval1, start2,
3924 len1, current_buffer, 0);
3925 graft_intervals_into_buffer (tmp_interval2, start1,
3926 len2, current_buffer, 0);
3929 else if (len1_byte < len2_byte) /* Second region larger than first */
3930 /* Non-adjacent & unequal size, area between must also be shifted. */
3932 modify_region (current_buffer, start1, end2);
3933 record_change (start1, (end2 - start1));
3934 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3935 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3936 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3937 Fset_text_properties (make_number (start1), make_number (end2),
3938 Qnil, Qnil);
3940 /* holds region 2 */
3941 if (len2_byte > 20000)
3942 temp = (unsigned char *) xmalloc (len2_byte);
3943 else
3944 temp = (unsigned char *) alloca (len2_byte);
3945 start1_addr = BYTE_POS_ADDR (start1_byte);
3946 start2_addr = BYTE_POS_ADDR (start2_byte);
3947 bcopy (start2_addr, temp, len2_byte);
3948 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
3949 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3950 bcopy (temp, start1_addr, len2_byte);
3951 if (len2_byte > 20000)
3952 xfree (temp);
3953 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3954 len1, current_buffer, 0);
3955 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3956 len_mid, current_buffer, 0);
3957 graft_intervals_into_buffer (tmp_interval2, start1,
3958 len2, current_buffer, 0);
3960 else
3961 /* Second region smaller than first. */
3963 record_change (start1, (end2 - start1));
3964 modify_region (current_buffer, start1, end2);
3966 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3967 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3968 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3969 Fset_text_properties (make_number (start1), make_number (end2),
3970 Qnil, Qnil);
3972 /* holds region 1 */
3973 if (len1_byte > 20000)
3974 temp = (unsigned char *) xmalloc (len1_byte);
3975 else
3976 temp = (unsigned char *) alloca (len1_byte);
3977 start1_addr = BYTE_POS_ADDR (start1_byte);
3978 start2_addr = BYTE_POS_ADDR (start2_byte);
3979 bcopy (start1_addr, temp, len1_byte);
3980 bcopy (start2_addr, start1_addr, len2_byte);
3981 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3982 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
3983 if (len1_byte > 20000)
3984 xfree (temp);
3985 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3986 len1, current_buffer, 0);
3987 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3988 len_mid, current_buffer, 0);
3989 graft_intervals_into_buffer (tmp_interval2, start1,
3990 len2, current_buffer, 0);
3993 update_compositions (start1, start1 + len2, CHECK_BORDER);
3994 update_compositions (end2 - len1, end2, CHECK_BORDER);
3997 /* When doing multiple transpositions, it might be nice
3998 to optimize this. Perhaps the markers in any one buffer
3999 should be organized in some sorted data tree. */
4000 if (NILP (leave_markers))
4002 transpose_markers (start1, end1, start2, end2,
4003 start1_byte, start1_byte + len1_byte,
4004 start2_byte, start2_byte + len2_byte);
4005 fix_overlays_in_range (start1, end2);
4008 return Qnil;
4012 void
4013 syms_of_editfns ()
4015 environbuf = 0;
4017 Qbuffer_access_fontify_functions
4018 = intern ("buffer-access-fontify-functions");
4019 staticpro (&Qbuffer_access_fontify_functions);
4021 DEFVAR_LISP ("inhibit-field-text-motion", &Vinhibit_field_text_motion,
4022 doc: /* Non-nil means text motion commands don't notice fields. */);
4023 Vinhibit_field_text_motion = Qnil;
4025 DEFVAR_LISP ("buffer-access-fontify-functions",
4026 &Vbuffer_access_fontify_functions,
4027 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4028 Each function is called with two arguments which specify the range
4029 of the buffer being accessed. */);
4030 Vbuffer_access_fontify_functions = Qnil;
4033 Lisp_Object obuf;
4034 extern Lisp_Object Vprin1_to_string_buffer;
4035 obuf = Fcurrent_buffer ();
4036 /* Do this here, because init_buffer_once is too early--it won't work. */
4037 Fset_buffer (Vprin1_to_string_buffer);
4038 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4039 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
4040 Qnil);
4041 Fset_buffer (obuf);
4044 DEFVAR_LISP ("buffer-access-fontified-property",
4045 &Vbuffer_access_fontified_property,
4046 doc: /* Property which (if non-nil) indicates text has been fontified.
4047 `buffer-substring' need not call the `buffer-access-fontify-functions'
4048 functions if all the text being accessed has this property. */);
4049 Vbuffer_access_fontified_property = Qnil;
4051 DEFVAR_LISP ("system-name", &Vsystem_name,
4052 doc: /* The name of the machine Emacs is running on. */);
4054 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
4055 doc: /* The full name of the user logged in. */);
4057 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
4058 doc: /* The user's name, taken from environment variables if possible. */);
4060 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
4061 doc: /* The user's name, based upon the real uid only. */);
4063 defsubr (&Spropertize);
4064 defsubr (&Schar_equal);
4065 defsubr (&Sgoto_char);
4066 defsubr (&Sstring_to_char);
4067 defsubr (&Schar_to_string);
4068 defsubr (&Sbuffer_substring);
4069 defsubr (&Sbuffer_substring_no_properties);
4070 defsubr (&Sbuffer_string);
4072 defsubr (&Spoint_marker);
4073 defsubr (&Smark_marker);
4074 defsubr (&Spoint);
4075 defsubr (&Sregion_beginning);
4076 defsubr (&Sregion_end);
4078 staticpro (&Qfield);
4079 Qfield = intern ("field");
4080 staticpro (&Qboundary);
4081 Qboundary = intern ("boundary");
4082 defsubr (&Sfield_beginning);
4083 defsubr (&Sfield_end);
4084 defsubr (&Sfield_string);
4085 defsubr (&Sfield_string_no_properties);
4086 defsubr (&Sdelete_field);
4087 defsubr (&Sconstrain_to_field);
4089 defsubr (&Sline_beginning_position);
4090 defsubr (&Sline_end_position);
4092 /* defsubr (&Smark); */
4093 /* defsubr (&Sset_mark); */
4094 defsubr (&Ssave_excursion);
4095 defsubr (&Ssave_current_buffer);
4097 defsubr (&Sbufsize);
4098 defsubr (&Spoint_max);
4099 defsubr (&Spoint_min);
4100 defsubr (&Spoint_min_marker);
4101 defsubr (&Spoint_max_marker);
4102 defsubr (&Sgap_position);
4103 defsubr (&Sgap_size);
4104 defsubr (&Sposition_bytes);
4105 defsubr (&Sbyte_to_position);
4107 defsubr (&Sbobp);
4108 defsubr (&Seobp);
4109 defsubr (&Sbolp);
4110 defsubr (&Seolp);
4111 defsubr (&Sfollowing_char);
4112 defsubr (&Sprevious_char);
4113 defsubr (&Schar_after);
4114 defsubr (&Schar_before);
4115 defsubr (&Sinsert);
4116 defsubr (&Sinsert_before_markers);
4117 defsubr (&Sinsert_and_inherit);
4118 defsubr (&Sinsert_and_inherit_before_markers);
4119 defsubr (&Sinsert_char);
4121 defsubr (&Suser_login_name);
4122 defsubr (&Suser_real_login_name);
4123 defsubr (&Suser_uid);
4124 defsubr (&Suser_real_uid);
4125 defsubr (&Suser_full_name);
4126 defsubr (&Semacs_pid);
4127 defsubr (&Scurrent_time);
4128 defsubr (&Sformat_time_string);
4129 defsubr (&Sfloat_time);
4130 defsubr (&Sdecode_time);
4131 defsubr (&Sencode_time);
4132 defsubr (&Scurrent_time_string);
4133 defsubr (&Scurrent_time_zone);
4134 defsubr (&Sset_time_zone_rule);
4135 defsubr (&Ssystem_name);
4136 defsubr (&Smessage);
4137 defsubr (&Smessage_box);
4138 defsubr (&Smessage_or_box);
4139 defsubr (&Scurrent_message);
4140 defsubr (&Sformat);
4142 defsubr (&Sinsert_buffer_substring);
4143 defsubr (&Scompare_buffer_substrings);
4144 defsubr (&Ssubst_char_in_region);
4145 defsubr (&Stranslate_region);
4146 defsubr (&Sdelete_region);
4147 defsubr (&Sdelete_and_extract_region);
4148 defsubr (&Swiden);
4149 defsubr (&Snarrow_to_region);
4150 defsubr (&Ssave_restriction);
4151 defsubr (&Stranspose_regions);