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