]> code.delx.au - gnu-emacs/blob - src/editfns.c
* editfns.c (Fformat): Fix several integer overflow problems.
[gnu-emacs] / 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 static Lisp_Object Qbuffer_access_fontify_functions;
111 static Lisp_Object Fuser_full_name (Lisp_Object);
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 static 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 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
189 doc: /* Convert arg CHAR to a string containing that character.
190 usage: (char-to-string CHAR) */)
191 (Lisp_Object character)
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 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
243 doc: /* Return value of point, as an integer.
244 Beginning of buffer is position (point-min). */)
245 (void)
246 {
247 Lisp_Object temp;
248 XSETFASTINT (temp, PT);
249 return temp;
250 }
251
252 DEFUN ("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 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
271 doc: /* Set point to POSITION, a number or marker.
272 Beginning of buffer is position (point-min), end is (point-max).
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 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
667 doc: /* Return the end of the field surrounding POS.
668 A field is a region of text with the same `field' property.
669 If POS is nil, the value of point is used for POS.
670 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
671 then the end of the *following* field is returned.
672 If LIMIT is non-nil, it is a buffer position; if the end of the field
673 is after LIMIT, then LIMIT will be returned instead. */)
674 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
675 {
676 EMACS_INT end;
677 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
678 return make_number (end);
679 }
680
681 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
682 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
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 DEFUN ("line-beginning-position",
791 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
792 doc: /* Return the character position of the first character on the current line.
793 With argument N not nil or 1, move forward N - 1 lines first.
794 If scan reaches end of buffer, return that position.
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 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
833 doc: /* Return the character position of the last character on the current line.
834 With argument N not nil or 1, move forward N - 1 lines first.
835 If scan reaches end of buffer, return that position.
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 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1052 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1053 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1054 is in effect, in which case it is less. */)
1055 (void)
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 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1103 doc: /* Return the character following point, as a number.
1104 At the end of the buffer or accessible region, return 0. */)
1105 (void)
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 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1116 doc: /* Return the character preceding point, as a number.
1117 At the beginning of the buffer or accessible region, return 0. */)
1118 (void)
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 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1135 doc: /* Return t if point is at the beginning of the buffer.
1136 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1137 (void)
1138 {
1139 if (PT == BEGV)
1140 return Qt;
1141 return Qnil;
1142 }
1143
1144 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1145 doc: /* Return t if point is at the end of the buffer.
1146 If the buffer is narrowed, this means the end of the narrowed part. */)
1147 (void)
1148 {
1149 if (PT == ZV)
1150 return Qt;
1151 return Qnil;
1152 }
1153
1154 DEFUN ("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 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1164 doc: /* Return t if point is at the end of a line.
1165 `End of a line' includes point being at the end of the buffer. */)
1166 (void)
1167 {
1168 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1169 return Qt;
1170 return Qnil;
1171 }
1172
1173 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1174 doc: /* Return character in current buffer at position POS.
1175 POS is an integer or a marker and defaults to point.
1176 If POS is out of range, the value is nil. */)
1177 (Lisp_Object pos)
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 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1251 doc: /* Return the name under which the user logged in, as a string.
1252 This is based on the effective uid, not the real uid.
1253 Also, if the environment variables LOGNAME or USER are set,
1254 that determines the value of this function.
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 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1391 doc: /* Return the host name of the machine you are running on, as a string. */)
1392 (void)
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 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1407 doc: /* Return the process ID of Emacs, as an integer. */)
1408 (void)
1409 {
1410 return make_number (getpid ());
1411 }
1412
1413 \f
1414
1415 #ifndef TIME_T_MIN
1416 # define TIME_T_MIN TYPE_MINIMUM (time_t)
1417 #endif
1418 #ifndef TIME_T_MAX
1419 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
1420 #endif
1421
1422 /* Report that a time value is out of range for Emacs. */
1423 static void
1424 time_overflow (void)
1425 {
1426 error ("Specified time is not representable");
1427 }
1428
1429 /* Return the upper part of the time T (everything but the bottom 16 bits),
1430 making sure that it is representable. */
1431 static EMACS_INT
1432 hi_time (time_t t)
1433 {
1434 time_t hi = t >> 16;
1435
1436 /* Check for overflow, helping the compiler for common cases where
1437 no runtime check is needed, and taking care not to convert
1438 negative numbers to unsigned before comparing them. */
1439 if (! ((! TYPE_SIGNED (time_t)
1440 || MOST_NEGATIVE_FIXNUM <= TIME_T_MIN >> 16
1441 || MOST_NEGATIVE_FIXNUM <= hi)
1442 && (TIME_T_MAX >> 16 <= MOST_POSITIVE_FIXNUM
1443 || hi <= MOST_POSITIVE_FIXNUM)))
1444 time_overflow ();
1445
1446 return hi;
1447 }
1448
1449 /* Return the bottom 16 bits of the time T. */
1450 static EMACS_INT
1451 lo_time (time_t t)
1452 {
1453 return t & ((1 << 16) - 1);
1454 }
1455
1456 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1457 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1458 The time is returned as a list of three integers. The first has the
1459 most significant 16 bits of the seconds, while the second has the
1460 least significant 16 bits. The third integer gives the microsecond
1461 count.
1462
1463 The microsecond count is zero on systems that do not provide
1464 resolution finer than a second. */)
1465 (void)
1466 {
1467 EMACS_TIME t;
1468
1469 EMACS_GET_TIME (t);
1470 return list3 (make_number (hi_time (EMACS_SECS (t))),
1471 make_number (lo_time (EMACS_SECS (t))),
1472 make_number (EMACS_USECS (t)));
1473 }
1474
1475 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1476 0, 0, 0,
1477 doc: /* Return the current run time used by Emacs.
1478 The time is returned as a list of three integers. The first has the
1479 most significant 16 bits of the seconds, while the second has the
1480 least significant 16 bits. The third integer gives the microsecond
1481 count.
1482
1483 On systems that can't determine the run time, `get-internal-run-time'
1484 does the same thing as `current-time'. The microsecond count is zero
1485 on systems that do not provide resolution finer than a second. */)
1486 (void)
1487 {
1488 #ifdef HAVE_GETRUSAGE
1489 struct rusage usage;
1490 time_t secs;
1491 int usecs;
1492
1493 if (getrusage (RUSAGE_SELF, &usage) < 0)
1494 /* This shouldn't happen. What action is appropriate? */
1495 xsignal0 (Qerror);
1496
1497 /* Sum up user time and system time. */
1498 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1499 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1500 if (usecs >= 1000000)
1501 {
1502 usecs -= 1000000;
1503 secs++;
1504 }
1505
1506 return list3 (make_number (hi_time (secs)),
1507 make_number (lo_time (secs)),
1508 make_number (usecs));
1509 #else /* ! HAVE_GETRUSAGE */
1510 #ifdef WINDOWSNT
1511 return w32_get_internal_run_time ();
1512 #else /* ! WINDOWSNT */
1513 return Fcurrent_time ();
1514 #endif /* WINDOWSNT */
1515 #endif /* HAVE_GETRUSAGE */
1516 }
1517 \f
1518
1519 /* Make a Lisp list that represents the time T. */
1520 Lisp_Object
1521 make_time (time_t t)
1522 {
1523 return list2 (make_number (hi_time (t)),
1524 make_number (lo_time (t)));
1525 }
1526
1527 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1528 If SPECIFIED_TIME is nil, use the current time.
1529 Set *RESULT to seconds since the Epoch.
1530 If USEC is not null, set *USEC to the microseconds component.
1531 Return nonzero if successful. */
1532 int
1533 lisp_time_argument (Lisp_Object specified_time, time_t *result, int *usec)
1534 {
1535 if (NILP (specified_time))
1536 {
1537 if (usec)
1538 {
1539 EMACS_TIME t;
1540
1541 EMACS_GET_TIME (t);
1542 *usec = EMACS_USECS (t);
1543 *result = EMACS_SECS (t);
1544 return 1;
1545 }
1546 else
1547 return time (result) != -1;
1548 }
1549 else
1550 {
1551 Lisp_Object high, low;
1552 EMACS_INT hi;
1553 high = Fcar (specified_time);
1554 CHECK_NUMBER (high);
1555 low = Fcdr (specified_time);
1556 if (CONSP (low))
1557 {
1558 if (usec)
1559 {
1560 Lisp_Object usec_l = Fcdr (low);
1561 if (CONSP (usec_l))
1562 usec_l = Fcar (usec_l);
1563 if (NILP (usec_l))
1564 *usec = 0;
1565 else
1566 {
1567 CHECK_NUMBER (usec_l);
1568 *usec = XINT (usec_l);
1569 }
1570 }
1571 low = Fcar (low);
1572 }
1573 else if (usec)
1574 *usec = 0;
1575 CHECK_NUMBER (low);
1576 hi = XINT (high);
1577
1578 /* Check for overflow, helping the compiler for common cases
1579 where no runtime check is needed, and taking care not to
1580 convert negative numbers to unsigned before comparing them. */
1581 if (! ((TYPE_SIGNED (time_t)
1582 ? (TIME_T_MIN >> 16 <= MOST_NEGATIVE_FIXNUM
1583 || TIME_T_MIN >> 16 <= hi)
1584 : 0 <= hi)
1585 && (MOST_POSITIVE_FIXNUM <= TIME_T_MAX >> 16
1586 || hi <= TIME_T_MAX >> 16)))
1587 return 0;
1588
1589 *result = (hi << 16) + (XINT (low) & 0xffff);
1590 return 1;
1591 }
1592 }
1593
1594 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1595 doc: /* Return the current time, as a float number of seconds since the epoch.
1596 If SPECIFIED-TIME is given, it is the time to convert to float
1597 instead of the current time. The argument should have the form
1598 (HIGH LOW) or (HIGH LOW USEC). Thus, you can use times obtained from
1599 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
1600 have the form (HIGH . LOW), but this is considered obsolete.
1601
1602 WARNING: Since the result is floating point, it may not be exact.
1603 If precise time stamps are required, use either `current-time',
1604 or (if you need time as a string) `format-time-string'. */)
1605 (Lisp_Object specified_time)
1606 {
1607 time_t sec;
1608 int usec;
1609
1610 if (! lisp_time_argument (specified_time, &sec, &usec))
1611 error ("Invalid time specification");
1612
1613 return make_float ((sec * 1e6 + usec) / 1e6);
1614 }
1615
1616 /* Write information into buffer S of size MAXSIZE, according to the
1617 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1618 Default to Universal Time if UT is nonzero, local time otherwise.
1619 Use NS as the number of nanoseconds in the %N directive.
1620 Return the number of bytes written, not including the terminating
1621 '\0'. If S is NULL, nothing will be written anywhere; so to
1622 determine how many bytes would be written, use NULL for S and
1623 ((size_t) -1) for MAXSIZE.
1624
1625 This function behaves like nstrftime, except it allows null
1626 bytes in FORMAT and it does not support nanoseconds. */
1627 static size_t
1628 emacs_nmemftime (char *s, size_t maxsize, const char *format,
1629 size_t format_len, const struct tm *tp, int ut, int ns)
1630 {
1631 size_t total = 0;
1632
1633 /* Loop through all the null-terminated strings in the format
1634 argument. Normally there's just one null-terminated string, but
1635 there can be arbitrarily many, concatenated together, if the
1636 format contains '\0' bytes. nstrftime stops at the first
1637 '\0' byte so we must invoke it separately for each such string. */
1638 for (;;)
1639 {
1640 size_t len;
1641 size_t result;
1642
1643 if (s)
1644 s[0] = '\1';
1645
1646 result = nstrftime (s, maxsize, format, tp, ut, ns);
1647
1648 if (s)
1649 {
1650 if (result == 0 && s[0] != '\0')
1651 return 0;
1652 s += result + 1;
1653 }
1654
1655 maxsize -= result + 1;
1656 total += result;
1657 len = strlen (format);
1658 if (len == format_len)
1659 return total;
1660 total++;
1661 format += len + 1;
1662 format_len -= len + 1;
1663 }
1664 }
1665
1666 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1667 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
1668 TIME is specified as (HIGH LOW . IGNORED), as returned by
1669 `current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
1670 is also still accepted.
1671 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1672 as Universal Time; nil means describe TIME in the local time zone.
1673 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1674 by text that describes the specified date and time in TIME:
1675
1676 %Y is the year, %y within the century, %C the century.
1677 %G is the year corresponding to the ISO week, %g within the century.
1678 %m is the numeric month.
1679 %b and %h are the locale's abbreviated month name, %B the full name.
1680 %d is the day of the month, zero-padded, %e is blank-padded.
1681 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1682 %a is the locale's abbreviated name of the day of week, %A the full name.
1683 %U is the week number starting on Sunday, %W starting on Monday,
1684 %V according to ISO 8601.
1685 %j is the day of the year.
1686
1687 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1688 only blank-padded, %l is like %I blank-padded.
1689 %p is the locale's equivalent of either AM or PM.
1690 %M is the minute.
1691 %S is the second.
1692 %N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
1693 %Z is the time zone name, %z is the numeric form.
1694 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1695
1696 %c is the locale's date and time format.
1697 %x is the locale's "preferred" date format.
1698 %D is like "%m/%d/%y".
1699
1700 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1701 %X is the locale's "preferred" time format.
1702
1703 Finally, %n is a newline, %t is a tab, %% is a literal %.
1704
1705 Certain flags and modifiers are available with some format controls.
1706 The flags are `_', `-', `^' and `#'. For certain characters X,
1707 %_X is like %X, but padded with blanks; %-X is like %X,
1708 but without padding. %^X is like %X, but with all textual
1709 characters up-cased; %#X is like %X, but with letter-case of
1710 all textual characters reversed.
1711 %NX (where N stands for an integer) is like %X,
1712 but takes up at least N (a number) positions.
1713 The modifiers are `E' and `O'. For certain characters X,
1714 %EX is a locale's alternative version of %X;
1715 %OX is like %X, but uses the locale's number symbols.
1716
1717 For example, to produce full ISO 8601 format, use "%Y-%m-%dT%T%z". */)
1718 (Lisp_Object format_string, Lisp_Object timeval, Lisp_Object universal)
1719 {
1720 time_t value;
1721 int size;
1722 int usec;
1723 int ns;
1724 struct tm *tm;
1725 int ut = ! NILP (universal);
1726
1727 CHECK_STRING (format_string);
1728
1729 if (! (lisp_time_argument (timeval, &value, &usec)
1730 && 0 <= usec && usec < 1000000))
1731 error ("Invalid time specification");
1732 ns = usec * 1000;
1733
1734 format_string = code_convert_string_norecord (format_string,
1735 Vlocale_coding_system, 1);
1736
1737 /* This is probably enough. */
1738 size = SBYTES (format_string) * 6 + 50;
1739
1740 BLOCK_INPUT;
1741 tm = ut ? gmtime (&value) : localtime (&value);
1742 UNBLOCK_INPUT;
1743 if (! tm)
1744 time_overflow ();
1745
1746 synchronize_system_time_locale ();
1747
1748 while (1)
1749 {
1750 char *buf = (char *) alloca (size + 1);
1751 int result;
1752
1753 buf[0] = '\1';
1754 BLOCK_INPUT;
1755 result = emacs_nmemftime (buf, size, SSDATA (format_string),
1756 SBYTES (format_string),
1757 tm, ut, ns);
1758 UNBLOCK_INPUT;
1759 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1760 return code_convert_string_norecord (make_unibyte_string (buf, result),
1761 Vlocale_coding_system, 0);
1762
1763 /* If buffer was too small, make it bigger and try again. */
1764 BLOCK_INPUT;
1765 result = emacs_nmemftime (NULL, (size_t) -1,
1766 SSDATA (format_string),
1767 SBYTES (format_string),
1768 tm, ut, ns);
1769 UNBLOCK_INPUT;
1770 size = result + 1;
1771 }
1772 }
1773
1774 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1775 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
1776 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
1777 as from `current-time' and `file-attributes', or nil to use the
1778 current time. The obsolete form (HIGH . LOW) is also still accepted.
1779 The list has the following nine members: SEC is an integer between 0
1780 and 60; SEC is 60 for a leap second, which only some operating systems
1781 support. MINUTE is an integer between 0 and 59. HOUR is an integer
1782 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
1783 integer between 1 and 12. YEAR is an integer indicating the
1784 four-digit year. DOW is the day of week, an integer between 0 and 6,
1785 where 0 is Sunday. DST is t if daylight saving time is in effect,
1786 otherwise nil. ZONE is an integer indicating the number of seconds
1787 east of Greenwich. (Note that Common Lisp has different meanings for
1788 DOW and ZONE.) */)
1789 (Lisp_Object specified_time)
1790 {
1791 time_t time_spec;
1792 struct tm save_tm;
1793 struct tm *decoded_time;
1794 Lisp_Object list_args[9];
1795
1796 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1797 error ("Invalid time specification");
1798
1799 BLOCK_INPUT;
1800 decoded_time = localtime (&time_spec);
1801 UNBLOCK_INPUT;
1802 if (! (decoded_time
1803 && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= decoded_time->tm_year
1804 && decoded_time->tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE))
1805 time_overflow ();
1806 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1807 XSETFASTINT (list_args[1], decoded_time->tm_min);
1808 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1809 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1810 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1811 /* On 64-bit machines an int is narrower than EMACS_INT, thus the
1812 cast below avoids overflow in int arithmetics. */
1813 XSETINT (list_args[5], TM_YEAR_BASE + (EMACS_INT) decoded_time->tm_year);
1814 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1815 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1816
1817 /* Make a copy, in case gmtime modifies the struct. */
1818 save_tm = *decoded_time;
1819 BLOCK_INPUT;
1820 decoded_time = gmtime (&time_spec);
1821 UNBLOCK_INPUT;
1822 if (decoded_time == 0)
1823 list_args[8] = Qnil;
1824 else
1825 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1826 return Flist (9, list_args);
1827 }
1828
1829 /* Return OBJ - OFFSET, checking that OBJ is a valid fixnum and that
1830 the result is representable as an int. Assume OFFSET is small and
1831 nonnegative. */
1832 static int
1833 check_tm_member (Lisp_Object obj, int offset)
1834 {
1835 EMACS_INT n;
1836 CHECK_NUMBER (obj);
1837 n = XINT (obj);
1838 if (! (INT_MIN + offset <= n && n - offset <= INT_MAX))
1839 time_overflow ();
1840 return n - offset;
1841 }
1842
1843 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1844 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
1845 This is the reverse operation of `decode-time', which see.
1846 ZONE defaults to the current time zone rule. This can
1847 be a string or t (as from `set-time-zone-rule'), or it can be a list
1848 \(as from `current-time-zone') or an integer (as from `decode-time')
1849 applied without consideration for daylight saving time.
1850
1851 You can pass more than 7 arguments; then the first six arguments
1852 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
1853 The intervening arguments are ignored.
1854 This feature lets (apply 'encode-time (decode-time ...)) work.
1855
1856 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
1857 for example, a DAY of 0 means the day preceding the given month.
1858 Year numbers less than 100 are treated just like other year numbers.
1859 If you want them to stand for years in this century, you must do that yourself.
1860
1861 Years before 1970 are not guaranteed to work. On some systems,
1862 year values as low as 1901 do work.
1863
1864 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
1865 (size_t nargs, register Lisp_Object *args)
1866 {
1867 time_t value;
1868 struct tm tm;
1869 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1870
1871 tm.tm_sec = check_tm_member (args[0], 0);
1872 tm.tm_min = check_tm_member (args[1], 0);
1873 tm.tm_hour = check_tm_member (args[2], 0);
1874 tm.tm_mday = check_tm_member (args[3], 0);
1875 tm.tm_mon = check_tm_member (args[4], 1);
1876 tm.tm_year = check_tm_member (args[5], TM_YEAR_BASE);
1877 tm.tm_isdst = -1;
1878
1879 if (CONSP (zone))
1880 zone = Fcar (zone);
1881 if (NILP (zone))
1882 {
1883 BLOCK_INPUT;
1884 value = mktime (&tm);
1885 UNBLOCK_INPUT;
1886 }
1887 else
1888 {
1889 char tzbuf[100];
1890 const char *tzstring;
1891 char **oldenv = environ, **newenv;
1892
1893 if (EQ (zone, Qt))
1894 tzstring = "UTC0";
1895 else if (STRINGP (zone))
1896 tzstring = SSDATA (zone);
1897 else if (INTEGERP (zone))
1898 {
1899 int abszone = eabs (XINT (zone));
1900 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1901 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1902 tzstring = tzbuf;
1903 }
1904 else
1905 error ("Invalid time zone specification");
1906
1907 /* Set TZ before calling mktime; merely adjusting mktime's returned
1908 value doesn't suffice, since that would mishandle leap seconds. */
1909 set_time_zone_rule (tzstring);
1910
1911 BLOCK_INPUT;
1912 value = mktime (&tm);
1913 UNBLOCK_INPUT;
1914
1915 /* Restore TZ to previous value. */
1916 newenv = environ;
1917 environ = oldenv;
1918 xfree (newenv);
1919 #ifdef LOCALTIME_CACHE
1920 tzset ();
1921 #endif
1922 }
1923
1924 if (value == (time_t) -1)
1925 time_overflow ();
1926
1927 return make_time (value);
1928 }
1929
1930 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1931 doc: /* Return the current local time, as a human-readable string.
1932 Programs can use this function to decode a time,
1933 since the number of columns in each field is fixed
1934 if the year is in the range 1000-9999.
1935 The format is `Sun Sep 16 01:03:52 1973'.
1936 However, see also the functions `decode-time' and `format-time-string'
1937 which provide a much more powerful and general facility.
1938
1939 If SPECIFIED-TIME is given, it is a time to format instead of the
1940 current time. The argument should have the form (HIGH LOW . IGNORED).
1941 Thus, you can use times obtained from `current-time' and from
1942 `file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
1943 but this is considered obsolete. */)
1944 (Lisp_Object specified_time)
1945 {
1946 time_t value;
1947 struct tm *tm;
1948 register char *tem;
1949
1950 if (! lisp_time_argument (specified_time, &value, NULL))
1951 error ("Invalid time specification");
1952
1953 /* Convert to a string, checking for out-of-range time stamps.
1954 Don't use 'ctime', as that might dump core if VALUE is out of
1955 range. */
1956 BLOCK_INPUT;
1957 tm = localtime (&value);
1958 UNBLOCK_INPUT;
1959 if (! (tm && TM_YEAR_IN_ASCTIME_RANGE (tm->tm_year) && (tem = asctime (tm))))
1960 time_overflow ();
1961
1962 /* Remove the trailing newline. */
1963 tem[strlen (tem) - 1] = '\0';
1964
1965 return build_string (tem);
1966 }
1967
1968 /* Yield A - B, measured in seconds.
1969 This function is copied from the GNU C Library. */
1970 static int
1971 tm_diff (struct tm *a, struct tm *b)
1972 {
1973 /* Compute intervening leap days correctly even if year is negative.
1974 Take care to avoid int overflow in leap day calculations,
1975 but it's OK to assume that A and B are close to each other. */
1976 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1977 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1978 int a100 = a4 / 25 - (a4 % 25 < 0);
1979 int b100 = b4 / 25 - (b4 % 25 < 0);
1980 int a400 = a100 >> 2;
1981 int b400 = b100 >> 2;
1982 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1983 int years = a->tm_year - b->tm_year;
1984 int days = (365 * years + intervening_leap_days
1985 + (a->tm_yday - b->tm_yday));
1986 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1987 + (a->tm_min - b->tm_min))
1988 + (a->tm_sec - b->tm_sec));
1989 }
1990
1991 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1992 doc: /* Return the offset and name for the local time zone.
1993 This returns a list of the form (OFFSET NAME).
1994 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
1995 A negative value means west of Greenwich.
1996 NAME is a string giving the name of the time zone.
1997 If SPECIFIED-TIME is given, the time zone offset is determined from it
1998 instead of using the current time. The argument should have the form
1999 (HIGH LOW . IGNORED). Thus, you can use times obtained from
2000 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
2001 have the form (HIGH . LOW), but this is considered obsolete.
2002
2003 Some operating systems cannot provide all this information to Emacs;
2004 in this case, `current-time-zone' returns a list containing nil for
2005 the data it can't find. */)
2006 (Lisp_Object specified_time)
2007 {
2008 time_t value;
2009 struct tm *t;
2010 struct tm gmt;
2011
2012 if (!lisp_time_argument (specified_time, &value, NULL))
2013 t = NULL;
2014 else
2015 {
2016 BLOCK_INPUT;
2017 t = gmtime (&value);
2018 if (t)
2019 {
2020 gmt = *t;
2021 t = localtime (&value);
2022 }
2023 UNBLOCK_INPUT;
2024 }
2025
2026 if (t)
2027 {
2028 int offset = tm_diff (t, &gmt);
2029 char *s = 0;
2030 char buf[6];
2031
2032 #ifdef HAVE_TM_ZONE
2033 if (t->tm_zone)
2034 s = (char *)t->tm_zone;
2035 #else /* not HAVE_TM_ZONE */
2036 #ifdef HAVE_TZNAME
2037 if (t->tm_isdst == 0 || t->tm_isdst == 1)
2038 s = tzname[t->tm_isdst];
2039 #endif
2040 #endif /* not HAVE_TM_ZONE */
2041
2042 if (!s)
2043 {
2044 /* No local time zone name is available; use "+-NNNN" instead. */
2045 int am = (offset < 0 ? -offset : offset) / 60;
2046 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
2047 s = buf;
2048 }
2049
2050 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
2051 }
2052 else
2053 return Fmake_list (make_number (2), Qnil);
2054 }
2055
2056 /* This holds the value of `environ' produced by the previous
2057 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
2058 has never been called. */
2059 static char **environbuf;
2060
2061 /* This holds the startup value of the TZ environment variable so it
2062 can be restored if the user calls set-time-zone-rule with a nil
2063 argument. */
2064 static char *initial_tz;
2065
2066 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2067 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
2068 If TZ is nil, use implementation-defined default time zone information.
2069 If TZ is t, use Universal Time. */)
2070 (Lisp_Object tz)
2071 {
2072 const char *tzstring;
2073
2074 /* When called for the first time, save the original TZ. */
2075 if (!environbuf)
2076 initial_tz = (char *) getenv ("TZ");
2077
2078 if (NILP (tz))
2079 tzstring = initial_tz;
2080 else if (EQ (tz, Qt))
2081 tzstring = "UTC0";
2082 else
2083 {
2084 CHECK_STRING (tz);
2085 tzstring = SSDATA (tz);
2086 }
2087
2088 set_time_zone_rule (tzstring);
2089 free (environbuf);
2090 environbuf = environ;
2091
2092 return Qnil;
2093 }
2094
2095 #ifdef LOCALTIME_CACHE
2096
2097 /* These two values are known to load tz files in buggy implementations,
2098 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
2099 Their values shouldn't matter in non-buggy implementations.
2100 We don't use string literals for these strings,
2101 since if a string in the environment is in readonly
2102 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
2103 See Sun bugs 1113095 and 1114114, ``Timezone routines
2104 improperly modify environment''. */
2105
2106 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
2107 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
2108
2109 #endif
2110
2111 /* Set the local time zone rule to TZSTRING.
2112 This allocates memory into `environ', which it is the caller's
2113 responsibility to free. */
2114
2115 void
2116 set_time_zone_rule (const char *tzstring)
2117 {
2118 int envptrs;
2119 char **from, **to, **newenv;
2120
2121 /* Make the ENVIRON vector longer with room for TZSTRING. */
2122 for (from = environ; *from; from++)
2123 continue;
2124 envptrs = from - environ + 2;
2125 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
2126 + (tzstring ? strlen (tzstring) + 4 : 0));
2127
2128 /* Add TZSTRING to the end of environ, as a value for TZ. */
2129 if (tzstring)
2130 {
2131 char *t = (char *) (to + envptrs);
2132 strcpy (t, "TZ=");
2133 strcat (t, tzstring);
2134 *to++ = t;
2135 }
2136
2137 /* Copy the old environ vector elements into NEWENV,
2138 but don't copy the TZ variable.
2139 So we have only one definition of TZ, which came from TZSTRING. */
2140 for (from = environ; *from; from++)
2141 if (strncmp (*from, "TZ=", 3) != 0)
2142 *to++ = *from;
2143 *to = 0;
2144
2145 environ = newenv;
2146
2147 /* If we do have a TZSTRING, NEWENV points to the vector slot where
2148 the TZ variable is stored. If we do not have a TZSTRING,
2149 TO points to the vector slot which has the terminating null. */
2150
2151 #ifdef LOCALTIME_CACHE
2152 {
2153 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
2154 "US/Pacific" that loads a tz file, then changes to a value like
2155 "XXX0" that does not load a tz file, and then changes back to
2156 its original value, the last change is (incorrectly) ignored.
2157 Also, if TZ changes twice in succession to values that do
2158 not load a tz file, tzset can dump core (see Sun bug#1225179).
2159 The following code works around these bugs. */
2160
2161 if (tzstring)
2162 {
2163 /* Temporarily set TZ to a value that loads a tz file
2164 and that differs from tzstring. */
2165 char *tz = *newenv;
2166 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
2167 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
2168 tzset ();
2169 *newenv = tz;
2170 }
2171 else
2172 {
2173 /* The implied tzstring is unknown, so temporarily set TZ to
2174 two different values that each load a tz file. */
2175 *to = set_time_zone_rule_tz1;
2176 to[1] = 0;
2177 tzset ();
2178 *to = set_time_zone_rule_tz2;
2179 tzset ();
2180 *to = 0;
2181 }
2182
2183 /* Now TZ has the desired value, and tzset can be invoked safely. */
2184 }
2185
2186 tzset ();
2187 #endif
2188 }
2189 \f
2190 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2191 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2192 type of object is Lisp_String). INHERIT is passed to
2193 INSERT_FROM_STRING_FUNC as the last argument. */
2194
2195 static void
2196 general_insert_function (void (*insert_func)
2197 (const char *, EMACS_INT),
2198 void (*insert_from_string_func)
2199 (Lisp_Object, EMACS_INT, EMACS_INT,
2200 EMACS_INT, EMACS_INT, int),
2201 int inherit, size_t nargs, Lisp_Object *args)
2202 {
2203 register size_t argnum;
2204 register Lisp_Object val;
2205
2206 for (argnum = 0; argnum < nargs; argnum++)
2207 {
2208 val = args[argnum];
2209 if (CHARACTERP (val))
2210 {
2211 unsigned char str[MAX_MULTIBYTE_LENGTH];
2212 int len;
2213
2214 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2215 len = CHAR_STRING (XFASTINT (val), str);
2216 else
2217 {
2218 str[0] = (ASCII_CHAR_P (XINT (val))
2219 ? XINT (val)
2220 : multibyte_char_to_unibyte (XINT (val)));
2221 len = 1;
2222 }
2223 (*insert_func) ((char *) str, len);
2224 }
2225 else if (STRINGP (val))
2226 {
2227 (*insert_from_string_func) (val, 0, 0,
2228 SCHARS (val),
2229 SBYTES (val),
2230 inherit);
2231 }
2232 else
2233 wrong_type_argument (Qchar_or_string_p, val);
2234 }
2235 }
2236
2237 void
2238 insert1 (Lisp_Object arg)
2239 {
2240 Finsert (1, &arg);
2241 }
2242
2243
2244 /* Callers passing one argument to Finsert need not gcpro the
2245 argument "array", since the only element of the array will
2246 not be used after calling insert or insert_from_string, so
2247 we don't care if it gets trashed. */
2248
2249 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2250 doc: /* Insert the arguments, either strings or characters, at point.
2251 Point and before-insertion markers move forward to end up
2252 after the inserted text.
2253 Any other markers at the point of insertion remain before the text.
2254
2255 If the current buffer is multibyte, unibyte strings are converted
2256 to multibyte for insertion (see `string-make-multibyte').
2257 If the current buffer is unibyte, multibyte strings are converted
2258 to unibyte for insertion (see `string-make-unibyte').
2259
2260 When operating on binary data, it may be necessary to preserve the
2261 original bytes of a unibyte string when inserting it into a multibyte
2262 buffer; to accomplish this, apply `string-as-multibyte' to the string
2263 and insert the result.
2264
2265 usage: (insert &rest ARGS) */)
2266 (size_t nargs, register Lisp_Object *args)
2267 {
2268 general_insert_function (insert, insert_from_string, 0, nargs, args);
2269 return Qnil;
2270 }
2271
2272 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2273 0, MANY, 0,
2274 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2275 Point and before-insertion markers move forward to end up
2276 after the inserted text.
2277 Any other markers at the point of insertion remain before the text.
2278
2279 If the current buffer is multibyte, unibyte strings are converted
2280 to multibyte for insertion (see `unibyte-char-to-multibyte').
2281 If the current buffer is unibyte, multibyte strings are converted
2282 to unibyte for insertion.
2283
2284 usage: (insert-and-inherit &rest ARGS) */)
2285 (size_t nargs, register Lisp_Object *args)
2286 {
2287 general_insert_function (insert_and_inherit, insert_from_string, 1,
2288 nargs, args);
2289 return Qnil;
2290 }
2291
2292 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2293 doc: /* Insert strings or characters at point, relocating markers after the text.
2294 Point and markers move forward to end up after the inserted text.
2295
2296 If the current buffer is multibyte, unibyte strings are converted
2297 to multibyte for insertion (see `unibyte-char-to-multibyte').
2298 If the current buffer is unibyte, multibyte strings are converted
2299 to unibyte for insertion.
2300
2301 usage: (insert-before-markers &rest ARGS) */)
2302 (size_t nargs, register Lisp_Object *args)
2303 {
2304 general_insert_function (insert_before_markers,
2305 insert_from_string_before_markers, 0,
2306 nargs, args);
2307 return Qnil;
2308 }
2309
2310 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2311 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2312 doc: /* Insert text at point, relocating markers and inheriting properties.
2313 Point and markers move forward to end up after the inserted text.
2314
2315 If the current buffer is multibyte, unibyte strings are converted
2316 to multibyte for insertion (see `unibyte-char-to-multibyte').
2317 If the current buffer is unibyte, multibyte strings are converted
2318 to unibyte for insertion.
2319
2320 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2321 (size_t nargs, register Lisp_Object *args)
2322 {
2323 general_insert_function (insert_before_markers_and_inherit,
2324 insert_from_string_before_markers, 1,
2325 nargs, args);
2326 return Qnil;
2327 }
2328 \f
2329 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
2330 doc: /* Insert COUNT copies of CHARACTER.
2331 Point, and before-insertion markers, are relocated as in the function `insert'.
2332 The optional third arg INHERIT, if non-nil, says to inherit text properties
2333 from adjoining text, if those properties are sticky. */)
2334 (Lisp_Object character, Lisp_Object count, Lisp_Object inherit)
2335 {
2336 register char *string;
2337 register EMACS_INT stringlen;
2338 register int i;
2339 register EMACS_INT n;
2340 int len;
2341 unsigned char str[MAX_MULTIBYTE_LENGTH];
2342
2343 CHECK_NUMBER (character);
2344 CHECK_NUMBER (count);
2345
2346 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2347 len = CHAR_STRING (XFASTINT (character), str);
2348 else
2349 str[0] = XFASTINT (character), len = 1;
2350 if (MOST_POSITIVE_FIXNUM / len < XINT (count))
2351 error ("Maximum buffer size would be exceeded");
2352 n = XINT (count) * len;
2353 if (n <= 0)
2354 return Qnil;
2355 stringlen = min (n, 256 * len);
2356 string = (char *) alloca (stringlen);
2357 for (i = 0; i < stringlen; i++)
2358 string[i] = str[i % len];
2359 while (n >= stringlen)
2360 {
2361 QUIT;
2362 if (!NILP (inherit))
2363 insert_and_inherit (string, stringlen);
2364 else
2365 insert (string, stringlen);
2366 n -= stringlen;
2367 }
2368 if (n > 0)
2369 {
2370 if (!NILP (inherit))
2371 insert_and_inherit (string, n);
2372 else
2373 insert (string, n);
2374 }
2375 return Qnil;
2376 }
2377
2378 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2379 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2380 Both arguments are required.
2381 BYTE is a number of the range 0..255.
2382
2383 If BYTE is 128..255 and the current buffer is multibyte, the
2384 corresponding eight-bit character is inserted.
2385
2386 Point, and before-insertion markers, are relocated as in the function `insert'.
2387 The optional third arg INHERIT, if non-nil, says to inherit text properties
2388 from adjoining text, if those properties are sticky. */)
2389 (Lisp_Object byte, Lisp_Object count, Lisp_Object inherit)
2390 {
2391 CHECK_NUMBER (byte);
2392 if (XINT (byte) < 0 || XINT (byte) > 255)
2393 args_out_of_range_3 (byte, make_number (0), make_number (255));
2394 if (XINT (byte) >= 128
2395 && ! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2396 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2397 return Finsert_char (byte, count, inherit);
2398 }
2399
2400 \f
2401 /* Making strings from buffer contents. */
2402
2403 /* Return a Lisp_String containing the text of the current buffer from
2404 START to END. If text properties are in use and the current buffer
2405 has properties in the range specified, the resulting string will also
2406 have them, if PROPS is nonzero.
2407
2408 We don't want to use plain old make_string here, because it calls
2409 make_uninit_string, which can cause the buffer arena to be
2410 compacted. make_string has no way of knowing that the data has
2411 been moved, and thus copies the wrong data into the string. This
2412 doesn't effect most of the other users of make_string, so it should
2413 be left as is. But we should use this function when conjuring
2414 buffer substrings. */
2415
2416 Lisp_Object
2417 make_buffer_string (EMACS_INT start, EMACS_INT end, int props)
2418 {
2419 EMACS_INT start_byte = CHAR_TO_BYTE (start);
2420 EMACS_INT end_byte = CHAR_TO_BYTE (end);
2421
2422 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2423 }
2424
2425 /* Return a Lisp_String containing the text of the current buffer from
2426 START / START_BYTE to END / END_BYTE.
2427
2428 If text properties are in use and the current buffer
2429 has properties in the range specified, the resulting string will also
2430 have them, if PROPS is nonzero.
2431
2432 We don't want to use plain old make_string here, because it calls
2433 make_uninit_string, which can cause the buffer arena to be
2434 compacted. make_string has no way of knowing that the data has
2435 been moved, and thus copies the wrong data into the string. This
2436 doesn't effect most of the other users of make_string, so it should
2437 be left as is. But we should use this function when conjuring
2438 buffer substrings. */
2439
2440 Lisp_Object
2441 make_buffer_string_both (EMACS_INT start, EMACS_INT start_byte,
2442 EMACS_INT end, EMACS_INT end_byte, int props)
2443 {
2444 Lisp_Object result, tem, tem1;
2445
2446 if (start < GPT && GPT < end)
2447 move_gap (start);
2448
2449 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2450 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2451 else
2452 result = make_uninit_string (end - start);
2453 memcpy (SDATA (result), BYTE_POS_ADDR (start_byte), end_byte - start_byte);
2454
2455 /* If desired, update and copy the text properties. */
2456 if (props)
2457 {
2458 update_buffer_properties (start, end);
2459
2460 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2461 tem1 = Ftext_properties_at (make_number (start), Qnil);
2462
2463 if (XINT (tem) != end || !NILP (tem1))
2464 copy_intervals_to_string (result, current_buffer, start,
2465 end - start);
2466 }
2467
2468 return result;
2469 }
2470
2471 /* Call Vbuffer_access_fontify_functions for the range START ... END
2472 in the current buffer, if necessary. */
2473
2474 static void
2475 update_buffer_properties (EMACS_INT start, EMACS_INT end)
2476 {
2477 /* If this buffer has some access functions,
2478 call them, specifying the range of the buffer being accessed. */
2479 if (!NILP (Vbuffer_access_fontify_functions))
2480 {
2481 Lisp_Object args[3];
2482 Lisp_Object tem;
2483
2484 args[0] = Qbuffer_access_fontify_functions;
2485 XSETINT (args[1], start);
2486 XSETINT (args[2], end);
2487
2488 /* But don't call them if we can tell that the work
2489 has already been done. */
2490 if (!NILP (Vbuffer_access_fontified_property))
2491 {
2492 tem = Ftext_property_any (args[1], args[2],
2493 Vbuffer_access_fontified_property,
2494 Qnil, Qnil);
2495 if (! NILP (tem))
2496 Frun_hook_with_args (3, args);
2497 }
2498 else
2499 Frun_hook_with_args (3, args);
2500 }
2501 }
2502
2503 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2504 doc: /* Return the contents of part of the current buffer as a string.
2505 The two arguments START and END are character positions;
2506 they can be in either order.
2507 The string returned is multibyte if the buffer is multibyte.
2508
2509 This function copies the text properties of that part of the buffer
2510 into the result string; if you don't want the text properties,
2511 use `buffer-substring-no-properties' instead. */)
2512 (Lisp_Object start, Lisp_Object end)
2513 {
2514 register EMACS_INT b, e;
2515
2516 validate_region (&start, &end);
2517 b = XINT (start);
2518 e = XINT (end);
2519
2520 return make_buffer_string (b, e, 1);
2521 }
2522
2523 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2524 Sbuffer_substring_no_properties, 2, 2, 0,
2525 doc: /* Return the characters of part of the buffer, without the text properties.
2526 The two arguments START and END are character positions;
2527 they can be in either order. */)
2528 (Lisp_Object start, Lisp_Object end)
2529 {
2530 register EMACS_INT b, e;
2531
2532 validate_region (&start, &end);
2533 b = XINT (start);
2534 e = XINT (end);
2535
2536 return make_buffer_string (b, e, 0);
2537 }
2538
2539 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2540 doc: /* Return the contents of the current buffer as a string.
2541 If narrowing is in effect, this function returns only the visible part
2542 of the buffer. */)
2543 (void)
2544 {
2545 return make_buffer_string (BEGV, ZV, 1);
2546 }
2547
2548 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2549 1, 3, 0,
2550 doc: /* Insert before point a substring of the contents of BUFFER.
2551 BUFFER may be a buffer or a buffer name.
2552 Arguments START and END are character positions specifying the substring.
2553 They default to the values of (point-min) and (point-max) in BUFFER. */)
2554 (Lisp_Object buffer, Lisp_Object start, Lisp_Object end)
2555 {
2556 register EMACS_INT b, e, temp;
2557 register struct buffer *bp, *obuf;
2558 Lisp_Object buf;
2559
2560 buf = Fget_buffer (buffer);
2561 if (NILP (buf))
2562 nsberror (buffer);
2563 bp = XBUFFER (buf);
2564 if (NILP (BVAR (bp, name)))
2565 error ("Selecting deleted buffer");
2566
2567 if (NILP (start))
2568 b = BUF_BEGV (bp);
2569 else
2570 {
2571 CHECK_NUMBER_COERCE_MARKER (start);
2572 b = XINT (start);
2573 }
2574 if (NILP (end))
2575 e = BUF_ZV (bp);
2576 else
2577 {
2578 CHECK_NUMBER_COERCE_MARKER (end);
2579 e = XINT (end);
2580 }
2581
2582 if (b > e)
2583 temp = b, b = e, e = temp;
2584
2585 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2586 args_out_of_range (start, end);
2587
2588 obuf = current_buffer;
2589 set_buffer_internal_1 (bp);
2590 update_buffer_properties (b, e);
2591 set_buffer_internal_1 (obuf);
2592
2593 insert_from_buffer (bp, b, e - b, 0);
2594 return Qnil;
2595 }
2596
2597 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2598 6, 6, 0,
2599 doc: /* Compare two substrings of two buffers; return result as number.
2600 the value is -N if first string is less after N-1 chars,
2601 +N if first string is greater after N-1 chars, or 0 if strings match.
2602 Each substring is represented as three arguments: BUFFER, START and END.
2603 That makes six args in all, three for each substring.
2604
2605 The value of `case-fold-search' in the current buffer
2606 determines whether case is significant or ignored. */)
2607 (Lisp_Object buffer1, Lisp_Object start1, Lisp_Object end1, Lisp_Object buffer2, Lisp_Object start2, Lisp_Object end2)
2608 {
2609 register EMACS_INT begp1, endp1, begp2, endp2, temp;
2610 register struct buffer *bp1, *bp2;
2611 register Lisp_Object trt
2612 = (!NILP (BVAR (current_buffer, case_fold_search))
2613 ? BVAR (current_buffer, case_canon_table) : Qnil);
2614 EMACS_INT chars = 0;
2615 EMACS_INT i1, i2, i1_byte, i2_byte;
2616
2617 /* Find the first buffer and its substring. */
2618
2619 if (NILP (buffer1))
2620 bp1 = current_buffer;
2621 else
2622 {
2623 Lisp_Object buf1;
2624 buf1 = Fget_buffer (buffer1);
2625 if (NILP (buf1))
2626 nsberror (buffer1);
2627 bp1 = XBUFFER (buf1);
2628 if (NILP (BVAR (bp1, name)))
2629 error ("Selecting deleted buffer");
2630 }
2631
2632 if (NILP (start1))
2633 begp1 = BUF_BEGV (bp1);
2634 else
2635 {
2636 CHECK_NUMBER_COERCE_MARKER (start1);
2637 begp1 = XINT (start1);
2638 }
2639 if (NILP (end1))
2640 endp1 = BUF_ZV (bp1);
2641 else
2642 {
2643 CHECK_NUMBER_COERCE_MARKER (end1);
2644 endp1 = XINT (end1);
2645 }
2646
2647 if (begp1 > endp1)
2648 temp = begp1, begp1 = endp1, endp1 = temp;
2649
2650 if (!(BUF_BEGV (bp1) <= begp1
2651 && begp1 <= endp1
2652 && endp1 <= BUF_ZV (bp1)))
2653 args_out_of_range (start1, end1);
2654
2655 /* Likewise for second substring. */
2656
2657 if (NILP (buffer2))
2658 bp2 = current_buffer;
2659 else
2660 {
2661 Lisp_Object buf2;
2662 buf2 = Fget_buffer (buffer2);
2663 if (NILP (buf2))
2664 nsberror (buffer2);
2665 bp2 = XBUFFER (buf2);
2666 if (NILP (BVAR (bp2, name)))
2667 error ("Selecting deleted buffer");
2668 }
2669
2670 if (NILP (start2))
2671 begp2 = BUF_BEGV (bp2);
2672 else
2673 {
2674 CHECK_NUMBER_COERCE_MARKER (start2);
2675 begp2 = XINT (start2);
2676 }
2677 if (NILP (end2))
2678 endp2 = BUF_ZV (bp2);
2679 else
2680 {
2681 CHECK_NUMBER_COERCE_MARKER (end2);
2682 endp2 = XINT (end2);
2683 }
2684
2685 if (begp2 > endp2)
2686 temp = begp2, begp2 = endp2, endp2 = temp;
2687
2688 if (!(BUF_BEGV (bp2) <= begp2
2689 && begp2 <= endp2
2690 && endp2 <= BUF_ZV (bp2)))
2691 args_out_of_range (start2, end2);
2692
2693 i1 = begp1;
2694 i2 = begp2;
2695 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2696 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2697
2698 while (i1 < endp1 && i2 < endp2)
2699 {
2700 /* When we find a mismatch, we must compare the
2701 characters, not just the bytes. */
2702 int c1, c2;
2703
2704 QUIT;
2705
2706 if (! NILP (BVAR (bp1, enable_multibyte_characters)))
2707 {
2708 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2709 BUF_INC_POS (bp1, i1_byte);
2710 i1++;
2711 }
2712 else
2713 {
2714 c1 = BUF_FETCH_BYTE (bp1, i1);
2715 MAKE_CHAR_MULTIBYTE (c1);
2716 i1++;
2717 }
2718
2719 if (! NILP (BVAR (bp2, enable_multibyte_characters)))
2720 {
2721 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2722 BUF_INC_POS (bp2, i2_byte);
2723 i2++;
2724 }
2725 else
2726 {
2727 c2 = BUF_FETCH_BYTE (bp2, i2);
2728 MAKE_CHAR_MULTIBYTE (c2);
2729 i2++;
2730 }
2731
2732 if (!NILP (trt))
2733 {
2734 c1 = CHAR_TABLE_TRANSLATE (trt, c1);
2735 c2 = CHAR_TABLE_TRANSLATE (trt, c2);
2736 }
2737 if (c1 < c2)
2738 return make_number (- 1 - chars);
2739 if (c1 > c2)
2740 return make_number (chars + 1);
2741
2742 chars++;
2743 }
2744
2745 /* The strings match as far as they go.
2746 If one is shorter, that one is less. */
2747 if (chars < endp1 - begp1)
2748 return make_number (chars + 1);
2749 else if (chars < endp2 - begp2)
2750 return make_number (- chars - 1);
2751
2752 /* Same length too => they are equal. */
2753 return make_number (0);
2754 }
2755 \f
2756 static Lisp_Object
2757 subst_char_in_region_unwind (Lisp_Object arg)
2758 {
2759 return BVAR (current_buffer, undo_list) = arg;
2760 }
2761
2762 static Lisp_Object
2763 subst_char_in_region_unwind_1 (Lisp_Object arg)
2764 {
2765 return BVAR (current_buffer, filename) = arg;
2766 }
2767
2768 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2769 Ssubst_char_in_region, 4, 5, 0,
2770 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
2771 If optional arg NOUNDO is non-nil, don't record this change for undo
2772 and don't mark the buffer as really changed.
2773 Both characters must have the same length of multi-byte form. */)
2774 (Lisp_Object start, Lisp_Object end, Lisp_Object fromchar, Lisp_Object tochar, Lisp_Object noundo)
2775 {
2776 register EMACS_INT pos, pos_byte, stop, i, len, end_byte;
2777 /* Keep track of the first change in the buffer:
2778 if 0 we haven't found it yet.
2779 if < 0 we've found it and we've run the before-change-function.
2780 if > 0 we've actually performed it and the value is its position. */
2781 EMACS_INT changed = 0;
2782 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2783 unsigned char *p;
2784 int count = SPECPDL_INDEX ();
2785 #define COMBINING_NO 0
2786 #define COMBINING_BEFORE 1
2787 #define COMBINING_AFTER 2
2788 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2789 int maybe_byte_combining = COMBINING_NO;
2790 EMACS_INT last_changed = 0;
2791 int multibyte_p = !NILP (BVAR (current_buffer, enable_multibyte_characters));
2792
2793 restart:
2794
2795 validate_region (&start, &end);
2796 CHECK_NUMBER (fromchar);
2797 CHECK_NUMBER (tochar);
2798
2799 if (multibyte_p)
2800 {
2801 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2802 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
2803 error ("Characters in `subst-char-in-region' have different byte-lengths");
2804 if (!ASCII_BYTE_P (*tostr))
2805 {
2806 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2807 complete multibyte character, it may be combined with the
2808 after bytes. If it is in the range 0xA0..0xFF, it may be
2809 combined with the before and after bytes. */
2810 if (!CHAR_HEAD_P (*tostr))
2811 maybe_byte_combining = COMBINING_BOTH;
2812 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2813 maybe_byte_combining = COMBINING_AFTER;
2814 }
2815 }
2816 else
2817 {
2818 len = 1;
2819 fromstr[0] = XFASTINT (fromchar);
2820 tostr[0] = XFASTINT (tochar);
2821 }
2822
2823 pos = XINT (start);
2824 pos_byte = CHAR_TO_BYTE (pos);
2825 stop = CHAR_TO_BYTE (XINT (end));
2826 end_byte = stop;
2827
2828 /* If we don't want undo, turn off putting stuff on the list.
2829 That's faster than getting rid of things,
2830 and it prevents even the entry for a first change.
2831 Also inhibit locking the file. */
2832 if (!changed && !NILP (noundo))
2833 {
2834 record_unwind_protect (subst_char_in_region_unwind,
2835 BVAR (current_buffer, undo_list));
2836 BVAR (current_buffer, undo_list) = Qt;
2837 /* Don't do file-locking. */
2838 record_unwind_protect (subst_char_in_region_unwind_1,
2839 BVAR (current_buffer, filename));
2840 BVAR (current_buffer, filename) = Qnil;
2841 }
2842
2843 if (pos_byte < GPT_BYTE)
2844 stop = min (stop, GPT_BYTE);
2845 while (1)
2846 {
2847 EMACS_INT pos_byte_next = pos_byte;
2848
2849 if (pos_byte >= stop)
2850 {
2851 if (pos_byte >= end_byte) break;
2852 stop = end_byte;
2853 }
2854 p = BYTE_POS_ADDR (pos_byte);
2855 if (multibyte_p)
2856 INC_POS (pos_byte_next);
2857 else
2858 ++pos_byte_next;
2859 if (pos_byte_next - pos_byte == len
2860 && p[0] == fromstr[0]
2861 && (len == 1
2862 || (p[1] == fromstr[1]
2863 && (len == 2 || (p[2] == fromstr[2]
2864 && (len == 3 || p[3] == fromstr[3]))))))
2865 {
2866 if (changed < 0)
2867 /* We've already seen this and run the before-change-function;
2868 this time we only need to record the actual position. */
2869 changed = pos;
2870 else if (!changed)
2871 {
2872 changed = -1;
2873 modify_region (current_buffer, pos, XINT (end), 0);
2874
2875 if (! NILP (noundo))
2876 {
2877 if (MODIFF - 1 == SAVE_MODIFF)
2878 SAVE_MODIFF++;
2879 if (MODIFF - 1 == BUF_AUTOSAVE_MODIFF (current_buffer))
2880 BUF_AUTOSAVE_MODIFF (current_buffer)++;
2881 }
2882
2883 /* The before-change-function may have moved the gap
2884 or even modified the buffer so we should start over. */
2885 goto restart;
2886 }
2887
2888 /* Take care of the case where the new character
2889 combines with neighboring bytes. */
2890 if (maybe_byte_combining
2891 && (maybe_byte_combining == COMBINING_AFTER
2892 ? (pos_byte_next < Z_BYTE
2893 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2894 : ((pos_byte_next < Z_BYTE
2895 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2896 || (pos_byte > BEG_BYTE
2897 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2898 {
2899 Lisp_Object tem, string;
2900
2901 struct gcpro gcpro1;
2902
2903 tem = BVAR (current_buffer, undo_list);
2904 GCPRO1 (tem);
2905
2906 /* Make a multibyte string containing this single character. */
2907 string = make_multibyte_string ((char *) tostr, 1, len);
2908 /* replace_range is less efficient, because it moves the gap,
2909 but it handles combining correctly. */
2910 replace_range (pos, pos + 1, string,
2911 0, 0, 1);
2912 pos_byte_next = CHAR_TO_BYTE (pos);
2913 if (pos_byte_next > pos_byte)
2914 /* Before combining happened. We should not increment
2915 POS. So, to cancel the later increment of POS,
2916 decrease it now. */
2917 pos--;
2918 else
2919 INC_POS (pos_byte_next);
2920
2921 if (! NILP (noundo))
2922 BVAR (current_buffer, undo_list) = tem;
2923
2924 UNGCPRO;
2925 }
2926 else
2927 {
2928 if (NILP (noundo))
2929 record_change (pos, 1);
2930 for (i = 0; i < len; i++) *p++ = tostr[i];
2931 }
2932 last_changed = pos + 1;
2933 }
2934 pos_byte = pos_byte_next;
2935 pos++;
2936 }
2937
2938 if (changed > 0)
2939 {
2940 signal_after_change (changed,
2941 last_changed - changed, last_changed - changed);
2942 update_compositions (changed, last_changed, CHECK_ALL);
2943 }
2944
2945 unbind_to (count, Qnil);
2946 return Qnil;
2947 }
2948
2949
2950 static Lisp_Object check_translation (EMACS_INT, EMACS_INT, EMACS_INT,
2951 Lisp_Object);
2952
2953 /* Helper function for Ftranslate_region_internal.
2954
2955 Check if a character sequence at POS (POS_BYTE) matches an element
2956 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
2957 element is found, return it. Otherwise return Qnil. */
2958
2959 static Lisp_Object
2960 check_translation (EMACS_INT pos, EMACS_INT pos_byte, EMACS_INT end,
2961 Lisp_Object val)
2962 {
2963 int buf_size = 16, buf_used = 0;
2964 int *buf = alloca (sizeof (int) * buf_size);
2965
2966 for (; CONSP (val); val = XCDR (val))
2967 {
2968 Lisp_Object elt;
2969 EMACS_INT len, i;
2970
2971 elt = XCAR (val);
2972 if (! CONSP (elt))
2973 continue;
2974 elt = XCAR (elt);
2975 if (! VECTORP (elt))
2976 continue;
2977 len = ASIZE (elt);
2978 if (len <= end - pos)
2979 {
2980 for (i = 0; i < len; i++)
2981 {
2982 if (buf_used <= i)
2983 {
2984 unsigned char *p = BYTE_POS_ADDR (pos_byte);
2985 int len1;
2986
2987 if (buf_used == buf_size)
2988 {
2989 int *newbuf;
2990
2991 buf_size += 16;
2992 newbuf = alloca (sizeof (int) * buf_size);
2993 memcpy (newbuf, buf, sizeof (int) * buf_used);
2994 buf = newbuf;
2995 }
2996 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len1);
2997 pos_byte += len1;
2998 }
2999 if (XINT (AREF (elt, i)) != buf[i])
3000 break;
3001 }
3002 if (i == len)
3003 return XCAR (val);
3004 }
3005 }
3006 return Qnil;
3007 }
3008
3009
3010 DEFUN ("translate-region-internal", Ftranslate_region_internal,
3011 Stranslate_region_internal, 3, 3, 0,
3012 doc: /* Internal use only.
3013 From START to END, translate characters according to TABLE.
3014 TABLE is a string or a char-table; the Nth character in it is the
3015 mapping for the character with code N.
3016 It returns the number of characters changed. */)
3017 (Lisp_Object start, Lisp_Object end, register Lisp_Object table)
3018 {
3019 register unsigned char *tt; /* Trans table. */
3020 register int nc; /* New character. */
3021 int cnt; /* Number of changes made. */
3022 EMACS_INT size; /* Size of translate table. */
3023 EMACS_INT pos, pos_byte, end_pos;
3024 int multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3025 int string_multibyte IF_LINT (= 0);
3026
3027 validate_region (&start, &end);
3028 if (CHAR_TABLE_P (table))
3029 {
3030 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3031 error ("Not a translation table");
3032 size = MAX_CHAR;
3033 tt = NULL;
3034 }
3035 else
3036 {
3037 CHECK_STRING (table);
3038
3039 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3040 table = string_make_unibyte (table);
3041 string_multibyte = SCHARS (table) < SBYTES (table);
3042 size = SBYTES (table);
3043 tt = SDATA (table);
3044 }
3045
3046 pos = XINT (start);
3047 pos_byte = CHAR_TO_BYTE (pos);
3048 end_pos = XINT (end);
3049 modify_region (current_buffer, pos, end_pos, 0);
3050
3051 cnt = 0;
3052 for (; pos < end_pos; )
3053 {
3054 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
3055 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3056 int len, str_len;
3057 int oc;
3058 Lisp_Object val;
3059
3060 if (multibyte)
3061 oc = STRING_CHAR_AND_LENGTH (p, len);
3062 else
3063 oc = *p, len = 1;
3064 if (oc < size)
3065 {
3066 if (tt)
3067 {
3068 /* Reload as signal_after_change in last iteration may GC. */
3069 tt = SDATA (table);
3070 if (string_multibyte)
3071 {
3072 str = tt + string_char_to_byte (table, oc);
3073 nc = STRING_CHAR_AND_LENGTH (str, str_len);
3074 }
3075 else
3076 {
3077 nc = tt[oc];
3078 if (! ASCII_BYTE_P (nc) && multibyte)
3079 {
3080 str_len = BYTE8_STRING (nc, buf);
3081 str = buf;
3082 }
3083 else
3084 {
3085 str_len = 1;
3086 str = tt + oc;
3087 }
3088 }
3089 }
3090 else
3091 {
3092 EMACS_INT c;
3093
3094 nc = oc;
3095 val = CHAR_TABLE_REF (table, oc);
3096 if (CHARACTERP (val)
3097 && (c = XINT (val), CHAR_VALID_P (c, 0)))
3098 {
3099 nc = c;
3100 str_len = CHAR_STRING (nc, buf);
3101 str = buf;
3102 }
3103 else if (VECTORP (val) || (CONSP (val)))
3104 {
3105 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3106 where TO is TO-CHAR or [TO-CHAR ...]. */
3107 nc = -1;
3108 }
3109 }
3110
3111 if (nc != oc && nc >= 0)
3112 {
3113 /* Simple one char to one char translation. */
3114 if (len != str_len)
3115 {
3116 Lisp_Object string;
3117
3118 /* This is less efficient, because it moves the gap,
3119 but it should handle multibyte characters correctly. */
3120 string = make_multibyte_string ((char *) str, 1, str_len);
3121 replace_range (pos, pos + 1, string, 1, 0, 1);
3122 len = str_len;
3123 }
3124 else
3125 {
3126 record_change (pos, 1);
3127 while (str_len-- > 0)
3128 *p++ = *str++;
3129 signal_after_change (pos, 1, 1);
3130 update_compositions (pos, pos + 1, CHECK_BORDER);
3131 }
3132 ++cnt;
3133 }
3134 else if (nc < 0)
3135 {
3136 Lisp_Object string;
3137
3138 if (CONSP (val))
3139 {
3140 val = check_translation (pos, pos_byte, end_pos, val);
3141 if (NILP (val))
3142 {
3143 pos_byte += len;
3144 pos++;
3145 continue;
3146 }
3147 /* VAL is ([FROM-CHAR ...] . TO). */
3148 len = ASIZE (XCAR (val));
3149 val = XCDR (val);
3150 }
3151 else
3152 len = 1;
3153
3154 if (VECTORP (val))
3155 {
3156 string = Fconcat (1, &val);
3157 }
3158 else
3159 {
3160 string = Fmake_string (make_number (1), val);
3161 }
3162 replace_range (pos, pos + len, string, 1, 0, 1);
3163 pos_byte += SBYTES (string);
3164 pos += SCHARS (string);
3165 cnt += SCHARS (string);
3166 end_pos += SCHARS (string) - len;
3167 continue;
3168 }
3169 }
3170 pos_byte += len;
3171 pos++;
3172 }
3173
3174 return make_number (cnt);
3175 }
3176
3177 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3178 doc: /* Delete the text between point and mark.
3179
3180 When called from a program, expects two arguments,
3181 positions (integers or markers) specifying the stretch to be deleted. */)
3182 (Lisp_Object start, Lisp_Object end)
3183 {
3184 validate_region (&start, &end);
3185 del_range (XINT (start), XINT (end));
3186 return Qnil;
3187 }
3188
3189 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3190 Sdelete_and_extract_region, 2, 2, 0,
3191 doc: /* Delete the text between START and END and return it. */)
3192 (Lisp_Object start, Lisp_Object end)
3193 {
3194 validate_region (&start, &end);
3195 if (XINT (start) == XINT (end))
3196 return empty_unibyte_string;
3197 return del_range_1 (XINT (start), XINT (end), 1, 1);
3198 }
3199 \f
3200 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3201 doc: /* Remove restrictions (narrowing) from current buffer.
3202 This allows the buffer's full text to be seen and edited. */)
3203 (void)
3204 {
3205 if (BEG != BEGV || Z != ZV)
3206 current_buffer->clip_changed = 1;
3207 BEGV = BEG;
3208 BEGV_BYTE = BEG_BYTE;
3209 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3210 /* Changing the buffer bounds invalidates any recorded current column. */
3211 invalidate_current_column ();
3212 return Qnil;
3213 }
3214
3215 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3216 doc: /* Restrict editing in this buffer to the current region.
3217 The rest of the text becomes temporarily invisible and untouchable
3218 but is not deleted; if you save the buffer in a file, the invisible
3219 text is included in the file. \\[widen] makes all visible again.
3220 See also `save-restriction'.
3221
3222 When calling from a program, pass two arguments; positions (integers
3223 or markers) bounding the text that should remain visible. */)
3224 (register Lisp_Object start, Lisp_Object end)
3225 {
3226 CHECK_NUMBER_COERCE_MARKER (start);
3227 CHECK_NUMBER_COERCE_MARKER (end);
3228
3229 if (XINT (start) > XINT (end))
3230 {
3231 Lisp_Object tem;
3232 tem = start; start = end; end = tem;
3233 }
3234
3235 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3236 args_out_of_range (start, end);
3237
3238 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3239 current_buffer->clip_changed = 1;
3240
3241 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3242 SET_BUF_ZV (current_buffer, XFASTINT (end));
3243 if (PT < XFASTINT (start))
3244 SET_PT (XFASTINT (start));
3245 if (PT > XFASTINT (end))
3246 SET_PT (XFASTINT (end));
3247 /* Changing the buffer bounds invalidates any recorded current column. */
3248 invalidate_current_column ();
3249 return Qnil;
3250 }
3251
3252 Lisp_Object
3253 save_restriction_save (void)
3254 {
3255 if (BEGV == BEG && ZV == Z)
3256 /* The common case that the buffer isn't narrowed.
3257 We return just the buffer object, which save_restriction_restore
3258 recognizes as meaning `no restriction'. */
3259 return Fcurrent_buffer ();
3260 else
3261 /* We have to save a restriction, so return a pair of markers, one
3262 for the beginning and one for the end. */
3263 {
3264 Lisp_Object beg, end;
3265
3266 beg = buildmark (BEGV, BEGV_BYTE);
3267 end = buildmark (ZV, ZV_BYTE);
3268
3269 /* END must move forward if text is inserted at its exact location. */
3270 XMARKER(end)->insertion_type = 1;
3271
3272 return Fcons (beg, end);
3273 }
3274 }
3275
3276 Lisp_Object
3277 save_restriction_restore (Lisp_Object data)
3278 {
3279 struct buffer *cur = NULL;
3280 struct buffer *buf = (CONSP (data)
3281 ? XMARKER (XCAR (data))->buffer
3282 : XBUFFER (data));
3283
3284 if (buf && buf != current_buffer && !NILP (BVAR (buf, pt_marker)))
3285 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3286 is the case if it is or has an indirect buffer), then make
3287 sure it is current before we update BEGV, so
3288 set_buffer_internal takes care of managing those markers. */
3289 cur = current_buffer;
3290 set_buffer_internal (buf);
3291 }
3292
3293 if (CONSP (data))
3294 /* A pair of marks bounding a saved restriction. */
3295 {
3296 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3297 struct Lisp_Marker *end = XMARKER (XCDR (data));
3298 eassert (buf == end->buffer);
3299
3300 if (buf /* Verify marker still points to a buffer. */
3301 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3302 /* The restriction has changed from the saved one, so restore
3303 the saved restriction. */
3304 {
3305 EMACS_INT pt = BUF_PT (buf);
3306
3307 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3308 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3309
3310 if (pt < beg->charpos || pt > end->charpos)
3311 /* The point is outside the new visible range, move it inside. */
3312 SET_BUF_PT_BOTH (buf,
3313 clip_to_bounds (beg->charpos, pt, end->charpos),
3314 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3315 end->bytepos));
3316
3317 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3318 }
3319 }
3320 else
3321 /* A buffer, which means that there was no old restriction. */
3322 {
3323 if (buf /* Verify marker still points to a buffer. */
3324 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3325 /* The buffer has been narrowed, get rid of the narrowing. */
3326 {
3327 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3328 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3329
3330 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3331 }
3332 }
3333
3334 /* Changing the buffer bounds invalidates any recorded current column. */
3335 invalidate_current_column ();
3336
3337 if (cur)
3338 set_buffer_internal (cur);
3339
3340 return Qnil;
3341 }
3342
3343 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3344 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3345 The buffer's restrictions make parts of the beginning and end invisible.
3346 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3347 This special form, `save-restriction', saves the current buffer's restrictions
3348 when it is entered, and restores them when it is exited.
3349 So any `narrow-to-region' within BODY lasts only until the end of the form.
3350 The old restrictions settings are restored
3351 even in case of abnormal exit (throw or error).
3352
3353 The value returned is the value of the last form in BODY.
3354
3355 Note: if you are using both `save-excursion' and `save-restriction',
3356 use `save-excursion' outermost:
3357 (save-excursion (save-restriction ...))
3358
3359 usage: (save-restriction &rest BODY) */)
3360 (Lisp_Object body)
3361 {
3362 register Lisp_Object val;
3363 int count = SPECPDL_INDEX ();
3364
3365 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3366 val = Fprogn (body);
3367 return unbind_to (count, val);
3368 }
3369 \f
3370 /* Buffer for the most recent text displayed by Fmessage_box. */
3371 static char *message_text;
3372
3373 /* Allocated length of that buffer. */
3374 static int message_length;
3375
3376 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3377 doc: /* Display a message at the bottom of the screen.
3378 The message also goes into the `*Messages*' buffer.
3379 \(In keyboard macros, that's all it does.)
3380 Return the message.
3381
3382 The first argument is a format control string, and the rest are data
3383 to be formatted under control of the string. See `format' for details.
3384
3385 Note: Use (message "%s" VALUE) to print the value of expressions and
3386 variables to avoid accidentally interpreting `%' as format specifiers.
3387
3388 If the first argument is nil or the empty string, the function clears
3389 any existing message; this lets the minibuffer contents show. See
3390 also `current-message'.
3391
3392 usage: (message FORMAT-STRING &rest ARGS) */)
3393 (size_t nargs, Lisp_Object *args)
3394 {
3395 if (NILP (args[0])
3396 || (STRINGP (args[0])
3397 && SBYTES (args[0]) == 0))
3398 {
3399 message (0);
3400 return args[0];
3401 }
3402 else
3403 {
3404 register Lisp_Object val;
3405 val = Fformat (nargs, args);
3406 message3 (val, SBYTES (val), STRING_MULTIBYTE (val));
3407 return val;
3408 }
3409 }
3410
3411 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3412 doc: /* Display a message, in a dialog box if possible.
3413 If a dialog box is not available, use the echo area.
3414 The first argument is a format control string, and the rest are data
3415 to be formatted under control of the string. See `format' for details.
3416
3417 If the first argument is nil or the empty string, clear any existing
3418 message; let the minibuffer contents show.
3419
3420 usage: (message-box FORMAT-STRING &rest ARGS) */)
3421 (size_t nargs, Lisp_Object *args)
3422 {
3423 if (NILP (args[0]))
3424 {
3425 message (0);
3426 return Qnil;
3427 }
3428 else
3429 {
3430 register Lisp_Object val;
3431 val = Fformat (nargs, args);
3432 #ifdef HAVE_MENUS
3433 /* The MS-DOS frames support popup menus even though they are
3434 not FRAME_WINDOW_P. */
3435 if (FRAME_WINDOW_P (XFRAME (selected_frame))
3436 || FRAME_MSDOS_P (XFRAME (selected_frame)))
3437 {
3438 Lisp_Object pane, menu;
3439 struct gcpro gcpro1;
3440 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
3441 GCPRO1 (pane);
3442 menu = Fcons (val, pane);
3443 Fx_popup_dialog (Qt, menu, Qt);
3444 UNGCPRO;
3445 return val;
3446 }
3447 #endif /* HAVE_MENUS */
3448 /* Copy the data so that it won't move when we GC. */
3449 if (! message_text)
3450 {
3451 message_text = (char *)xmalloc (80);
3452 message_length = 80;
3453 }
3454 if (SBYTES (val) > message_length)
3455 {
3456 message_length = SBYTES (val);
3457 message_text = (char *)xrealloc (message_text, message_length);
3458 }
3459 memcpy (message_text, SDATA (val), SBYTES (val));
3460 message2 (message_text, SBYTES (val),
3461 STRING_MULTIBYTE (val));
3462 return val;
3463 }
3464 }
3465
3466 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3467 doc: /* Display a message in a dialog box or in the echo area.
3468 If this command was invoked with the mouse, use a dialog box if
3469 `use-dialog-box' is non-nil.
3470 Otherwise, use the echo area.
3471 The first argument is a format control string, and the rest are data
3472 to be formatted under control of the string. See `format' for details.
3473
3474 If the first argument is nil or the empty string, clear any existing
3475 message; let the minibuffer contents show.
3476
3477 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3478 (size_t nargs, Lisp_Object *args)
3479 {
3480 #ifdef HAVE_MENUS
3481 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3482 && use_dialog_box)
3483 return Fmessage_box (nargs, args);
3484 #endif
3485 return Fmessage (nargs, args);
3486 }
3487
3488 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3489 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3490 (void)
3491 {
3492 return current_message ();
3493 }
3494
3495
3496 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3497 doc: /* Return a copy of STRING with text properties added.
3498 First argument is the string to copy.
3499 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3500 properties to add to the result.
3501 usage: (propertize STRING &rest PROPERTIES) */)
3502 (size_t nargs, Lisp_Object *args)
3503 {
3504 Lisp_Object properties, string;
3505 struct gcpro gcpro1, gcpro2;
3506 size_t i;
3507
3508 /* Number of args must be odd. */
3509 if ((nargs & 1) == 0)
3510 error ("Wrong number of arguments");
3511
3512 properties = string = Qnil;
3513 GCPRO2 (properties, string);
3514
3515 /* First argument must be a string. */
3516 CHECK_STRING (args[0]);
3517 string = Fcopy_sequence (args[0]);
3518
3519 for (i = 1; i < nargs; i += 2)
3520 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3521
3522 Fadd_text_properties (make_number (0),
3523 make_number (SCHARS (string)),
3524 properties, string);
3525 RETURN_UNGCPRO (string);
3526 }
3527
3528
3529 /* Number of bytes that STRING will occupy when put into the result.
3530 MULTIBYTE is nonzero if the result should be multibyte. */
3531
3532 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3533 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
3534 ? count_size_as_multibyte (SDATA (STRING), SBYTES (STRING)) \
3535 : SBYTES (STRING))
3536
3537 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3538 doc: /* Format a string out of a format-string and arguments.
3539 The first argument is a format control string.
3540 The other arguments are substituted into it to make the result, a string.
3541
3542 The format control string may contain %-sequences meaning to substitute
3543 the next available argument:
3544
3545 %s means print a string argument. Actually, prints any object, with `princ'.
3546 %d means print as number in decimal (%o octal, %x hex).
3547 %X is like %x, but uses upper case.
3548 %e means print a number in exponential notation.
3549 %f means print a number in decimal-point notation.
3550 %g means print a number in exponential notation
3551 or decimal-point notation, whichever uses fewer characters.
3552 %c means print a number as a single character.
3553 %S means print any object as an s-expression (using `prin1').
3554
3555 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3556 Use %% to put a single % into the output.
3557
3558 A %-sequence may contain optional flag, width, and precision
3559 specifiers, as follows:
3560
3561 %<flags><width><precision>character
3562
3563 where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3564
3565 The + flag character inserts a + before any positive number, while a
3566 space inserts a space before any positive number; these flags only
3567 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3568 The # flag means to use an alternate display form for %o, %x, %X, %e,
3569 %f, and %g sequences. The - and 0 flags affect the width specifier,
3570 as described below.
3571
3572 The width specifier supplies a lower limit for the length of the
3573 printed representation. The padding, if any, normally goes on the
3574 left, but it goes on the right if the - flag is present. The padding
3575 character is normally a space, but it is 0 if the 0 flag is present.
3576 The - flag takes precedence over the 0 flag.
3577
3578 For %e, %f, and %g sequences, the number after the "." in the
3579 precision specifier says how many decimal places to show; if zero, the
3580 decimal point itself is omitted. For %s and %S, the precision
3581 specifier truncates the string to the given width.
3582
3583 usage: (format STRING &rest OBJECTS) */)
3584 (size_t nargs, register Lisp_Object *args)
3585 {
3586 register EMACS_INT n; /* The number of the next arg to substitute */
3587 register EMACS_INT total; /* An estimate of the final length */
3588 int pIlen = sizeof pI - 1;
3589 char *buf, *p;
3590 register char *format, *end, *format_start;
3591 EMACS_INT nchars;
3592 /* Nonzero if the output should be a multibyte string,
3593 which is true if any of the inputs is one. */
3594 int multibyte = 0;
3595 /* When we make a multibyte string, we must pay attention to the
3596 byte combining problem, i.e., a byte may be combined with a
3597 multibyte character of the previous string. This flag tells if we
3598 must consider such a situation or not. */
3599 int maybe_combine_byte;
3600 char *this_format;
3601 /* Precision for each spec, or -1, a flag value meaning no precision
3602 was given in that spec. Element 0, corresponding to the format
3603 string itself, will not be used. Element NARGS, corresponding to
3604 no argument, *will* be assigned to in the case that a `%' and `.'
3605 occur after the final format specifier. */
3606 int *precision = (int *) (alloca ((nargs + 1) * sizeof (int)));
3607 EMACS_INT longest_format;
3608 Lisp_Object val;
3609 int arg_intervals = 0;
3610 USE_SAFE_ALLOCA;
3611
3612 /* discarded[I] is 1 if byte I of the format
3613 string was not copied into the output.
3614 It is 2 if byte I was not the first byte of its character. */
3615 char *discarded = 0;
3616
3617 /* Each element records, for one argument,
3618 the start and end bytepos in the output string,
3619 and whether the argument is a string with intervals.
3620 info[0] is unused. Unused elements have -1 for start. */
3621 struct info
3622 {
3623 EMACS_INT start, end;
3624 int intervals;
3625 } *info = 0;
3626
3627 /* It should not be necessary to GCPRO ARGS, because
3628 the caller in the interpreter should take care of that. */
3629
3630 /* Try to determine whether the result should be multibyte.
3631 This is not always right; sometimes the result needs to be multibyte
3632 because of an object that we will pass through prin1,
3633 and in that case, we won't know it here. */
3634 for (n = 0; n < nargs; n++)
3635 {
3636 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3637 multibyte = 1;
3638 /* Piggyback on this loop to initialize precision[N]. */
3639 precision[n] = -1;
3640 }
3641 precision[nargs] = -1;
3642
3643 CHECK_STRING (args[0]);
3644 /* We may have to change "%S" to "%s". */
3645 args[0] = Fcopy_sequence (args[0]);
3646
3647 /* GC should never happen here, so abort if it does. */
3648 abort_on_gc++;
3649
3650 /* If we start out planning a unibyte result,
3651 then discover it has to be multibyte, we jump back to retry.
3652 That can only happen from the first large while loop below. */
3653 retry:
3654
3655 format = SSDATA (args[0]);
3656 format_start = format;
3657 end = format + SBYTES (args[0]);
3658 longest_format = 0;
3659
3660 /* Make room in result for all the non-%-codes in the control string. */
3661 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]) + 1;
3662
3663 /* Allocate the info and discarded tables. */
3664 {
3665 EMACS_INT nbytes = (nargs + 1) * sizeof *info;
3666 EMACS_INT i;
3667 if (!info)
3668 info = (struct info *) alloca (nbytes);
3669 memset (info, 0, nbytes);
3670 for (i = 0; i < nargs + 1; i++)
3671 info[i].start = -1;
3672 if (!discarded)
3673 SAFE_ALLOCA (discarded, char *, SBYTES (args[0]));
3674 memset (discarded, 0, SBYTES (args[0]));
3675 }
3676
3677 /* Add to TOTAL enough space to hold the converted arguments. */
3678
3679 n = 0;
3680 while (format != end)
3681 if (*format++ == '%')
3682 {
3683 EMACS_INT thissize = 0;
3684 EMACS_INT actual_width = 0;
3685 char *this_format_start = format - 1;
3686 int field_width = 0;
3687
3688 /* General format specifications look like
3689
3690 '%' [flags] [field-width] [precision] format
3691
3692 where
3693
3694 flags ::= [-+ #0]+
3695 field-width ::= [0-9]+
3696 precision ::= '.' [0-9]*
3697
3698 If a field-width is specified, it specifies to which width
3699 the output should be padded with blanks, if the output
3700 string is shorter than field-width.
3701
3702 If precision is specified, it specifies the number of
3703 digits to print after the '.' for floats, or the max.
3704 number of chars to print from a string. */
3705
3706 while (format != end
3707 && (*format == '-' || *format == '0' || *format == '#'
3708 || * format == ' ' || *format == '+'))
3709 ++format;
3710
3711 /* Parse width and precision, limiting them to the range of 'int'
3712 because otherwise the underyling sprintf may go kaflooey. */
3713
3714 if (*format >= '0' && *format <= '9')
3715 {
3716 char *width_end;
3717 unsigned long width = strtoul (format, &width_end, 10);
3718 if (INT_MAX < width)
3719 error ("Format string field width too large");
3720 field_width = width;
3721 format = width_end;
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 char *prec_end;
3729 unsigned long prec = strtoul (format + 1, &prec_end, 10);
3730 if (INT_MAX < prec)
3731 error ("Format string precision too large");
3732 precision[n + 1] = prec;
3733 format = prec_end;
3734 }
3735
3736 if (longest_format < format - this_format_start + pIlen + 1)
3737 longest_format = format - this_format_start + pIlen + 1;
3738
3739 if (format == end)
3740 error ("Format string ends in middle of format specifier");
3741 if (*format == '%')
3742 format++;
3743 else if (++n >= nargs)
3744 error ("Not enough arguments for format string");
3745 else if (*format == 'S')
3746 {
3747 /* For `S', prin1 the argument and then treat like a string. */
3748 register Lisp_Object tem;
3749 tem = Fprin1_to_string (args[n], Qnil);
3750 if (STRING_MULTIBYTE (tem) && ! multibyte)
3751 {
3752 multibyte = 1;
3753 goto retry;
3754 }
3755 args[n] = tem;
3756 /* If we restart the loop, we should not come here again
3757 because args[n] is now a string and calling
3758 Fprin1_to_string on it produces superflous double
3759 quotes. So, change "%S" to "%s" now. */
3760 *format = 's';
3761 goto string;
3762 }
3763 else if (SYMBOLP (args[n]))
3764 {
3765 args[n] = SYMBOL_NAME (args[n]);
3766 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3767 {
3768 multibyte = 1;
3769 goto retry;
3770 }
3771 goto string;
3772 }
3773 else if (STRINGP (args[n]))
3774 {
3775 string:
3776 if (*format != 's' && *format != 'S')
3777 error ("Format specifier doesn't match argument type");
3778 /* In the case (PRECISION[N] > 0), THISSIZE may not need
3779 to be as large as is calculated here. Easy check for
3780 the case PRECISION = 0. */
3781 thissize = precision[n] ? CONVERTED_BYTE_SIZE (multibyte, args[n]) : 0;
3782 /* The precision also constrains how much of the argument
3783 string will finally appear (Bug#5710). */
3784 actual_width = lisp_string_width (args[n], -1, NULL, NULL);
3785 if (precision[n] != -1)
3786 actual_width = min (actual_width, precision[n]);
3787 }
3788 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3789 else if (INTEGERP (args[n]) && *format != 's')
3790 {
3791 /* The following loop assumes the Lisp type indicates
3792 the proper way to pass the argument.
3793 So make sure we have a flonum if the argument should
3794 be a double. */
3795 if (*format == 'e' || *format == 'f' || *format == 'g')
3796 args[n] = Ffloat (args[n]);
3797 else
3798 if (*format != 'd' && *format != 'o' && *format != 'x'
3799 && *format != 'i' && *format != 'X' && *format != 'c')
3800 error ("Invalid format operation %%%c", *format);
3801
3802 thissize = 30 + (precision[n] > 0 ? precision[n] : 0);
3803 if (*format == 'c')
3804 {
3805 if (! ASCII_CHAR_P (XINT (args[n]))
3806 /* Note: No one can remember why we have to treat
3807 the character 0 as a multibyte character here.
3808 But, until it causes a real problem, let's
3809 don't change it. */
3810 || XINT (args[n]) == 0)
3811 {
3812 if (! multibyte)
3813 {
3814 multibyte = 1;
3815 goto retry;
3816 }
3817 args[n] = Fchar_to_string (args[n]);
3818 thissize = SBYTES (args[n]);
3819 }
3820 }
3821 }
3822 else if (FLOATP (args[n]) && *format != 's')
3823 {
3824 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3825 {
3826 if (*format != 'd' && *format != 'o' && *format != 'x'
3827 && *format != 'i' && *format != 'X' && *format != 'c')
3828 error ("Invalid format operation %%%c", *format);
3829 /* This fails unnecessarily if args[n] is bigger than
3830 most-positive-fixnum but smaller than MAXINT.
3831 These cases are important because we sometimes use floats
3832 to represent such integer values (typically such values
3833 come from UIDs or PIDs). */
3834 /* args[n] = Ftruncate (args[n], Qnil); */
3835 }
3836
3837 /* Note that we're using sprintf to print floats,
3838 so we have to take into account what that function
3839 prints. */
3840 /* Filter out flag value of -1. */
3841 thissize = (MAX_10_EXP + 100
3842 + (precision[n] > 0 ? precision[n] : 0));
3843 }
3844 else
3845 {
3846 /* Anything but a string, convert to a string using princ. */
3847 register Lisp_Object tem;
3848 tem = Fprin1_to_string (args[n], Qt);
3849 if (STRING_MULTIBYTE (tem) && ! multibyte)
3850 {
3851 multibyte = 1;
3852 goto retry;
3853 }
3854 args[n] = tem;
3855 goto string;
3856 }
3857
3858 thissize += max (0, field_width - actual_width);
3859 total += thissize + 4;
3860 }
3861
3862 abort_on_gc--;
3863
3864 /* Now we can no longer jump to retry.
3865 TOTAL and LONGEST_FORMAT are known for certain. */
3866
3867 this_format = (char *) alloca (longest_format + 1);
3868
3869 /* Allocate the space for the result.
3870 Note that TOTAL is an overestimate. */
3871 SAFE_ALLOCA (buf, char *, total);
3872
3873 p = buf;
3874 nchars = 0;
3875 n = 0;
3876
3877 /* Scan the format and store result in BUF. */
3878 format = SSDATA (args[0]);
3879 format_start = format;
3880 end = format + SBYTES (args[0]);
3881 maybe_combine_byte = 0;
3882 while (format != end)
3883 {
3884 if (*format == '%')
3885 {
3886 int minlen;
3887 int negative = 0;
3888 char *this_format_start = format;
3889
3890 discarded[format - format_start] = 1;
3891 format++;
3892
3893 while (strchr ("-+0# ", *format))
3894 {
3895 if (*format == '-')
3896 {
3897 negative = 1;
3898 }
3899 discarded[format - format_start] = 1;
3900 ++format;
3901 }
3902
3903 minlen = atoi (format);
3904
3905 while ((*format >= '0' && *format <= '9') || *format == '.')
3906 {
3907 discarded[format - format_start] = 1;
3908 format++;
3909 }
3910
3911 if (*format++ == '%')
3912 {
3913 *p++ = '%';
3914 nchars++;
3915 continue;
3916 }
3917
3918 ++n;
3919
3920 discarded[format - format_start - 1] = 1;
3921 info[n].start = nchars;
3922
3923 if (STRINGP (args[n]))
3924 {
3925 /* handle case (precision[n] >= 0) */
3926
3927 int width, padding;
3928 EMACS_INT nbytes, start;
3929 EMACS_INT nchars_string;
3930
3931 /* lisp_string_width ignores a precision of 0, but GNU
3932 libc functions print 0 characters when the precision
3933 is 0. Imitate libc behavior here. Changing
3934 lisp_string_width is the right thing, and will be
3935 done, but meanwhile we work with it. */
3936
3937 if (precision[n] == 0)
3938 width = nchars_string = nbytes = 0;
3939 else if (precision[n] > 0)
3940 width = lisp_string_width (args[n], precision[n],
3941 &nchars_string, &nbytes);
3942 else
3943 { /* no precision spec given for this argument */
3944 width = lisp_string_width (args[n], -1, NULL, NULL);
3945 nbytes = SBYTES (args[n]);
3946 nchars_string = SCHARS (args[n]);
3947 }
3948
3949 /* If spec requires it, pad on right with spaces. */
3950 padding = minlen - width;
3951 if (! negative)
3952 while (padding-- > 0)
3953 {
3954 *p++ = ' ';
3955 ++nchars;
3956 }
3957
3958 info[n].start = start = nchars;
3959 nchars += nchars_string;
3960
3961 if (p > buf
3962 && multibyte
3963 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3964 && STRING_MULTIBYTE (args[n])
3965 && !CHAR_HEAD_P (SREF (args[n], 0)))
3966 maybe_combine_byte = 1;
3967
3968 p += copy_text (SDATA (args[n]), (unsigned char *) p,
3969 nbytes,
3970 STRING_MULTIBYTE (args[n]), multibyte);
3971
3972 info[n].end = nchars;
3973
3974 if (negative)
3975 while (padding-- > 0)
3976 {
3977 *p++ = ' ';
3978 nchars++;
3979 }
3980
3981 /* If this argument has text properties, record where
3982 in the result string it appears. */
3983 if (STRING_INTERVALS (args[n]))
3984 info[n].intervals = arg_intervals = 1;
3985 }
3986 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3987 {
3988 EMACS_INT this_nchars;
3989 EMACS_INT this_format_len = format - this_format_start;
3990
3991 memcpy (this_format, this_format_start, this_format_len);
3992 this_format[this_format_len] = 0;
3993
3994 if (format[-1] == 'e' || format[-1] == 'f' || format[-1] == 'g')
3995 sprintf (p, this_format, XFLOAT_DATA (args[n]));
3996 else
3997 {
3998 if (pIlen && format[-1] != 'c')
3999 {
4000 /* Insert pI before format spec. */
4001 memcpy (&this_format[this_format_len - 1], pI, pIlen);
4002 this_format[this_format_len + pIlen - 1] = format[-1];
4003 this_format[this_format_len + pIlen] = 0;
4004 }
4005
4006 if (INTEGERP (args[n]))
4007 {
4008 if (format[-1] == 'c')
4009 sprintf (p, this_format, (int) XINT (args[n]));
4010 else if (format[-1] == 'd')
4011 sprintf (p, this_format, XINT (args[n]));
4012 /* Don't sign-extend for octal or hex printing. */
4013 else
4014 sprintf (p, this_format, XUINT (args[n]));
4015 }
4016 else if (format[-1] == 'c')
4017 sprintf (p, this_format, (int) XFLOAT_DATA (args[n]));
4018 else if (format[-1] == 'd')
4019 /* Maybe we should use "%1.0f" instead so it also works
4020 for values larger than MAXINT. */
4021 sprintf (p, this_format, (EMACS_INT) XFLOAT_DATA (args[n]));
4022 else
4023 /* Don't sign-extend for octal or hex printing. */
4024 sprintf (p, this_format, (EMACS_UINT) XFLOAT_DATA (args[n]));
4025 }
4026
4027 if (p > buf
4028 && multibyte
4029 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4030 && !CHAR_HEAD_P (*((unsigned char *) p)))
4031 maybe_combine_byte = 1;
4032 this_nchars = strlen (p);
4033 if (multibyte)
4034 p += str_to_multibyte ((unsigned char *) p,
4035 buf + total - 1 - p, this_nchars);
4036 else
4037 p += this_nchars;
4038 nchars += this_nchars;
4039 info[n].end = nchars;
4040 }
4041
4042 }
4043 else if (STRING_MULTIBYTE (args[0]))
4044 {
4045 /* Copy a whole multibyte character. */
4046 if (p > buf
4047 && multibyte
4048 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4049 && !CHAR_HEAD_P (*format))
4050 maybe_combine_byte = 1;
4051 *p++ = *format++;
4052 while (! CHAR_HEAD_P (*format))
4053 {
4054 discarded[format - format_start] = 2;
4055 *p++ = *format++;
4056 }
4057 nchars++;
4058 }
4059 else if (multibyte)
4060 {
4061 /* Convert a single-byte character to multibyte. */
4062 int len = copy_text ((unsigned char *) format, (unsigned char *) p,
4063 1, 0, 1);
4064
4065 p += len;
4066 format++;
4067 nchars++;
4068 }
4069 else
4070 *p++ = *format++, nchars++;
4071 }
4072
4073 if (p > buf + total)
4074 abort ();
4075
4076 if (maybe_combine_byte)
4077 nchars = multibyte_chars_in_text ((unsigned char *) buf, p - buf);
4078 val = make_specified_string (buf, nchars, p - buf, multibyte);
4079
4080 /* If we allocated BUF with malloc, free it too. */
4081 SAFE_FREE ();
4082
4083 /* If the format string has text properties, or any of the string
4084 arguments has text properties, set up text properties of the
4085 result string. */
4086
4087 if (STRING_INTERVALS (args[0]) || arg_intervals)
4088 {
4089 Lisp_Object len, new_len, props;
4090 struct gcpro gcpro1;
4091
4092 /* Add text properties from the format string. */
4093 len = make_number (SCHARS (args[0]));
4094 props = text_property_list (args[0], make_number (0), len, Qnil);
4095 GCPRO1 (props);
4096
4097 if (CONSP (props))
4098 {
4099 EMACS_INT bytepos = 0, position = 0, translated = 0;
4100 EMACS_INT argn = 1;
4101 Lisp_Object list;
4102
4103 /* Adjust the bounds of each text property
4104 to the proper start and end in the output string. */
4105
4106 /* Put the positions in PROPS in increasing order, so that
4107 we can do (effectively) one scan through the position
4108 space of the format string. */
4109 props = Fnreverse (props);
4110
4111 /* BYTEPOS is the byte position in the format string,
4112 POSITION is the untranslated char position in it,
4113 TRANSLATED is the translated char position in BUF,
4114 and ARGN is the number of the next arg we will come to. */
4115 for (list = props; CONSP (list); list = XCDR (list))
4116 {
4117 Lisp_Object item;
4118 EMACS_INT pos;
4119
4120 item = XCAR (list);
4121
4122 /* First adjust the property start position. */
4123 pos = XINT (XCAR (item));
4124
4125 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4126 up to this position. */
4127 for (; position < pos; bytepos++)
4128 {
4129 if (! discarded[bytepos])
4130 position++, translated++;
4131 else if (discarded[bytepos] == 1)
4132 {
4133 position++;
4134 if (translated == info[argn].start)
4135 {
4136 translated += info[argn].end - info[argn].start;
4137 argn++;
4138 }
4139 }
4140 }
4141
4142 XSETCAR (item, make_number (translated));
4143
4144 /* Likewise adjust the property end position. */
4145 pos = XINT (XCAR (XCDR (item)));
4146
4147 for (; position < pos; bytepos++)
4148 {
4149 if (! discarded[bytepos])
4150 position++, translated++;
4151 else if (discarded[bytepos] == 1)
4152 {
4153 position++;
4154 if (translated == info[argn].start)
4155 {
4156 translated += info[argn].end - info[argn].start;
4157 argn++;
4158 }
4159 }
4160 }
4161
4162 XSETCAR (XCDR (item), make_number (translated));
4163 }
4164
4165 add_text_properties_from_list (val, props, make_number (0));
4166 }
4167
4168 /* Add text properties from arguments. */
4169 if (arg_intervals)
4170 for (n = 1; n < nargs; ++n)
4171 if (info[n].intervals)
4172 {
4173 len = make_number (SCHARS (args[n]));
4174 new_len = make_number (info[n].end - info[n].start);
4175 props = text_property_list (args[n], make_number (0), len, Qnil);
4176 props = extend_property_ranges (props, new_len);
4177 /* If successive arguments have properties, be sure that
4178 the value of `composition' property be the copy. */
4179 if (n > 1 && info[n - 1].end)
4180 make_composition_value_copy (props);
4181 add_text_properties_from_list (val, props,
4182 make_number (info[n].start));
4183 }
4184
4185 UNGCPRO;
4186 }
4187
4188 return val;
4189 }
4190
4191 Lisp_Object
4192 format2 (const char *string1, Lisp_Object arg0, Lisp_Object arg1)
4193 {
4194 Lisp_Object args[3];
4195 args[0] = build_string (string1);
4196 args[1] = arg0;
4197 args[2] = arg1;
4198 return Fformat (3, args);
4199 }
4200 \f
4201 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4202 doc: /* Return t if two characters match, optionally ignoring case.
4203 Both arguments must be characters (i.e. integers).
4204 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4205 (register Lisp_Object c1, Lisp_Object c2)
4206 {
4207 int i1, i2;
4208 /* Check they're chars, not just integers, otherwise we could get array
4209 bounds violations in downcase. */
4210 CHECK_CHARACTER (c1);
4211 CHECK_CHARACTER (c2);
4212
4213 if (XINT (c1) == XINT (c2))
4214 return Qt;
4215 if (NILP (BVAR (current_buffer, case_fold_search)))
4216 return Qnil;
4217
4218 i1 = XFASTINT (c1);
4219 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
4220 && ! ASCII_CHAR_P (i1))
4221 {
4222 MAKE_CHAR_MULTIBYTE (i1);
4223 }
4224 i2 = XFASTINT (c2);
4225 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
4226 && ! ASCII_CHAR_P (i2))
4227 {
4228 MAKE_CHAR_MULTIBYTE (i2);
4229 }
4230 return (downcase (i1) == downcase (i2) ? Qt : Qnil);
4231 }
4232 \f
4233 /* Transpose the markers in two regions of the current buffer, and
4234 adjust the ones between them if necessary (i.e.: if the regions
4235 differ in size).
4236
4237 START1, END1 are the character positions of the first region.
4238 START1_BYTE, END1_BYTE are the byte positions.
4239 START2, END2 are the character positions of the second region.
4240 START2_BYTE, END2_BYTE are the byte positions.
4241
4242 Traverses the entire marker list of the buffer to do so, adding an
4243 appropriate amount to some, subtracting from some, and leaving the
4244 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4245
4246 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4247
4248 static void
4249 transpose_markers (EMACS_INT start1, EMACS_INT end1,
4250 EMACS_INT start2, EMACS_INT end2,
4251 EMACS_INT start1_byte, EMACS_INT end1_byte,
4252 EMACS_INT start2_byte, EMACS_INT end2_byte)
4253 {
4254 register EMACS_INT amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4255 register struct Lisp_Marker *marker;
4256
4257 /* Update point as if it were a marker. */
4258 if (PT < start1)
4259 ;
4260 else if (PT < end1)
4261 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4262 PT_BYTE + (end2_byte - end1_byte));
4263 else if (PT < start2)
4264 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4265 (PT_BYTE + (end2_byte - start2_byte)
4266 - (end1_byte - start1_byte)));
4267 else if (PT < end2)
4268 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4269 PT_BYTE - (start2_byte - start1_byte));
4270
4271 /* We used to adjust the endpoints here to account for the gap, but that
4272 isn't good enough. Even if we assume the caller has tried to move the
4273 gap out of our way, it might still be at start1 exactly, for example;
4274 and that places it `inside' the interval, for our purposes. The amount
4275 of adjustment is nontrivial if there's a `denormalized' marker whose
4276 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4277 the dirty work to Fmarker_position, below. */
4278
4279 /* The difference between the region's lengths */
4280 diff = (end2 - start2) - (end1 - start1);
4281 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4282
4283 /* For shifting each marker in a region by the length of the other
4284 region plus the distance between the regions. */
4285 amt1 = (end2 - start2) + (start2 - end1);
4286 amt2 = (end1 - start1) + (start2 - end1);
4287 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4288 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4289
4290 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4291 {
4292 mpos = marker->bytepos;
4293 if (mpos >= start1_byte && mpos < end2_byte)
4294 {
4295 if (mpos < end1_byte)
4296 mpos += amt1_byte;
4297 else if (mpos < start2_byte)
4298 mpos += diff_byte;
4299 else
4300 mpos -= amt2_byte;
4301 marker->bytepos = mpos;
4302 }
4303 mpos = marker->charpos;
4304 if (mpos >= start1 && mpos < end2)
4305 {
4306 if (mpos < end1)
4307 mpos += amt1;
4308 else if (mpos < start2)
4309 mpos += diff;
4310 else
4311 mpos -= amt2;
4312 }
4313 marker->charpos = mpos;
4314 }
4315 }
4316
4317 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4318 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4319 The regions should not be overlapping, because the size of the buffer is
4320 never changed in a transposition.
4321
4322 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4323 any markers that happen to be located in the regions.
4324
4325 Transposing beyond buffer boundaries is an error. */)
4326 (Lisp_Object startr1, Lisp_Object endr1, Lisp_Object startr2, Lisp_Object endr2, Lisp_Object leave_markers)
4327 {
4328 register EMACS_INT start1, end1, start2, end2;
4329 EMACS_INT start1_byte, start2_byte, len1_byte, len2_byte;
4330 EMACS_INT gap, len1, len_mid, len2;
4331 unsigned char *start1_addr, *start2_addr, *temp;
4332
4333 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4334 Lisp_Object buf;
4335
4336 XSETBUFFER (buf, current_buffer);
4337 cur_intv = BUF_INTERVALS (current_buffer);
4338
4339 validate_region (&startr1, &endr1);
4340 validate_region (&startr2, &endr2);
4341
4342 start1 = XFASTINT (startr1);
4343 end1 = XFASTINT (endr1);
4344 start2 = XFASTINT (startr2);
4345 end2 = XFASTINT (endr2);
4346 gap = GPT;
4347
4348 /* Swap the regions if they're reversed. */
4349 if (start2 < end1)
4350 {
4351 register EMACS_INT glumph = start1;
4352 start1 = start2;
4353 start2 = glumph;
4354 glumph = end1;
4355 end1 = end2;
4356 end2 = glumph;
4357 }
4358
4359 len1 = end1 - start1;
4360 len2 = end2 - start2;
4361
4362 if (start2 < end1)
4363 error ("Transposed regions overlap");
4364 else if (start1 == end1 || start2 == end2)
4365 error ("Transposed region has length 0");
4366
4367 /* The possibilities are:
4368 1. Adjacent (contiguous) regions, or separate but equal regions
4369 (no, really equal, in this case!), or
4370 2. Separate regions of unequal size.
4371
4372 The worst case is usually No. 2. It means that (aside from
4373 potential need for getting the gap out of the way), there also
4374 needs to be a shifting of the text between the two regions. So
4375 if they are spread far apart, we are that much slower... sigh. */
4376
4377 /* It must be pointed out that the really studly thing to do would
4378 be not to move the gap at all, but to leave it in place and work
4379 around it if necessary. This would be extremely efficient,
4380 especially considering that people are likely to do
4381 transpositions near where they are working interactively, which
4382 is exactly where the gap would be found. However, such code
4383 would be much harder to write and to read. So, if you are
4384 reading this comment and are feeling squirrely, by all means have
4385 a go! I just didn't feel like doing it, so I will simply move
4386 the gap the minimum distance to get it out of the way, and then
4387 deal with an unbroken array. */
4388
4389 /* Make sure the gap won't interfere, by moving it out of the text
4390 we will operate on. */
4391 if (start1 < gap && gap < end2)
4392 {
4393 if (gap - start1 < end2 - gap)
4394 move_gap (start1);
4395 else
4396 move_gap (end2);
4397 }
4398
4399 start1_byte = CHAR_TO_BYTE (start1);
4400 start2_byte = CHAR_TO_BYTE (start2);
4401 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4402 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
4403
4404 #ifdef BYTE_COMBINING_DEBUG
4405 if (end1 == start2)
4406 {
4407 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4408 len2_byte, start1, start1_byte)
4409 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4410 len1_byte, end2, start2_byte + len2_byte)
4411 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4412 len1_byte, end2, start2_byte + len2_byte))
4413 abort ();
4414 }
4415 else
4416 {
4417 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4418 len2_byte, start1, start1_byte)
4419 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4420 len1_byte, start2, start2_byte)
4421 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4422 len2_byte, end1, start1_byte + len1_byte)
4423 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4424 len1_byte, end2, start2_byte + len2_byte))
4425 abort ();
4426 }
4427 #endif
4428
4429 /* Hmmm... how about checking to see if the gap is large
4430 enough to use as the temporary storage? That would avoid an
4431 allocation... interesting. Later, don't fool with it now. */
4432
4433 /* Working without memmove, for portability (sigh), so must be
4434 careful of overlapping subsections of the array... */
4435
4436 if (end1 == start2) /* adjacent regions */
4437 {
4438 modify_region (current_buffer, start1, end2, 0);
4439 record_change (start1, len1 + len2);
4440
4441 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4442 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4443 /* Don't use Fset_text_properties: that can cause GC, which can
4444 clobber objects stored in the tmp_intervals. */
4445 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4446 if (!NULL_INTERVAL_P (tmp_interval3))
4447 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4448
4449 /* First region smaller than second. */
4450 if (len1_byte < len2_byte)
4451 {
4452 USE_SAFE_ALLOCA;
4453
4454 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4455
4456 /* Don't precompute these addresses. We have to compute them
4457 at the last minute, because the relocating allocator might
4458 have moved the buffer around during the xmalloc. */
4459 start1_addr = BYTE_POS_ADDR (start1_byte);
4460 start2_addr = BYTE_POS_ADDR (start2_byte);
4461
4462 memcpy (temp, start2_addr, len2_byte);
4463 memcpy (start1_addr + len2_byte, start1_addr, len1_byte);
4464 memcpy (start1_addr, temp, len2_byte);
4465 SAFE_FREE ();
4466 }
4467 else
4468 /* First region not smaller than second. */
4469 {
4470 USE_SAFE_ALLOCA;
4471
4472 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4473 start1_addr = BYTE_POS_ADDR (start1_byte);
4474 start2_addr = BYTE_POS_ADDR (start2_byte);
4475 memcpy (temp, start1_addr, len1_byte);
4476 memcpy (start1_addr, start2_addr, len2_byte);
4477 memcpy (start1_addr + len2_byte, temp, len1_byte);
4478 SAFE_FREE ();
4479 }
4480 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4481 len1, current_buffer, 0);
4482 graft_intervals_into_buffer (tmp_interval2, start1,
4483 len2, current_buffer, 0);
4484 update_compositions (start1, start1 + len2, CHECK_BORDER);
4485 update_compositions (start1 + len2, end2, CHECK_TAIL);
4486 }
4487 /* Non-adjacent regions, because end1 != start2, bleagh... */
4488 else
4489 {
4490 len_mid = start2_byte - (start1_byte + len1_byte);
4491
4492 if (len1_byte == len2_byte)
4493 /* Regions are same size, though, how nice. */
4494 {
4495 USE_SAFE_ALLOCA;
4496
4497 modify_region (current_buffer, start1, end1, 0);
4498 modify_region (current_buffer, start2, end2, 0);
4499 record_change (start1, len1);
4500 record_change (start2, len2);
4501 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4502 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4503
4504 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4505 if (!NULL_INTERVAL_P (tmp_interval3))
4506 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4507
4508 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4509 if (!NULL_INTERVAL_P (tmp_interval3))
4510 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
4511
4512 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4513 start1_addr = BYTE_POS_ADDR (start1_byte);
4514 start2_addr = BYTE_POS_ADDR (start2_byte);
4515 memcpy (temp, start1_addr, len1_byte);
4516 memcpy (start1_addr, start2_addr, len2_byte);
4517 memcpy (start2_addr, temp, len1_byte);
4518 SAFE_FREE ();
4519
4520 graft_intervals_into_buffer (tmp_interval1, start2,
4521 len1, current_buffer, 0);
4522 graft_intervals_into_buffer (tmp_interval2, start1,
4523 len2, current_buffer, 0);
4524 }
4525
4526 else if (len1_byte < len2_byte) /* Second region larger than first */
4527 /* Non-adjacent & unequal size, area between must also be shifted. */
4528 {
4529 USE_SAFE_ALLOCA;
4530
4531 modify_region (current_buffer, start1, end2, 0);
4532 record_change (start1, (end2 - start1));
4533 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4534 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4535 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4536
4537 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4538 if (!NULL_INTERVAL_P (tmp_interval3))
4539 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4540
4541 /* holds region 2 */
4542 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4543 start1_addr = BYTE_POS_ADDR (start1_byte);
4544 start2_addr = BYTE_POS_ADDR (start2_byte);
4545 memcpy (temp, start2_addr, len2_byte);
4546 memcpy (start1_addr + len_mid + len2_byte, start1_addr, len1_byte);
4547 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4548 memcpy (start1_addr, temp, len2_byte);
4549 SAFE_FREE ();
4550
4551 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4552 len1, current_buffer, 0);
4553 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4554 len_mid, current_buffer, 0);
4555 graft_intervals_into_buffer (tmp_interval2, start1,
4556 len2, current_buffer, 0);
4557 }
4558 else
4559 /* Second region smaller than first. */
4560 {
4561 USE_SAFE_ALLOCA;
4562
4563 record_change (start1, (end2 - start1));
4564 modify_region (current_buffer, start1, end2, 0);
4565
4566 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4567 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4568 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4569
4570 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4571 if (!NULL_INTERVAL_P (tmp_interval3))
4572 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4573
4574 /* holds region 1 */
4575 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4576 start1_addr = BYTE_POS_ADDR (start1_byte);
4577 start2_addr = BYTE_POS_ADDR (start2_byte);
4578 memcpy (temp, start1_addr, len1_byte);
4579 memcpy (start1_addr, start2_addr, len2_byte);
4580 memcpy (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4581 memcpy (start1_addr + len2_byte + len_mid, temp, len1_byte);
4582 SAFE_FREE ();
4583
4584 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4585 len1, current_buffer, 0);
4586 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4587 len_mid, current_buffer, 0);
4588 graft_intervals_into_buffer (tmp_interval2, start1,
4589 len2, current_buffer, 0);
4590 }
4591
4592 update_compositions (start1, start1 + len2, CHECK_BORDER);
4593 update_compositions (end2 - len1, end2, CHECK_BORDER);
4594 }
4595
4596 /* When doing multiple transpositions, it might be nice
4597 to optimize this. Perhaps the markers in any one buffer
4598 should be organized in some sorted data tree. */
4599 if (NILP (leave_markers))
4600 {
4601 transpose_markers (start1, end1, start2, end2,
4602 start1_byte, start1_byte + len1_byte,
4603 start2_byte, start2_byte + len2_byte);
4604 fix_start_end_in_overlays (start1, end2);
4605 }
4606
4607 signal_after_change (start1, end2 - start1, end2 - start1);
4608 return Qnil;
4609 }
4610
4611 \f
4612 void
4613 syms_of_editfns (void)
4614 {
4615 environbuf = 0;
4616 initial_tz = 0;
4617
4618 Qbuffer_access_fontify_functions
4619 = intern_c_string ("buffer-access-fontify-functions");
4620 staticpro (&Qbuffer_access_fontify_functions);
4621
4622 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion,
4623 doc: /* Non-nil means text motion commands don't notice fields. */);
4624 Vinhibit_field_text_motion = Qnil;
4625
4626 DEFVAR_LISP ("buffer-access-fontify-functions",
4627 Vbuffer_access_fontify_functions,
4628 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4629 Each function is called with two arguments which specify the range
4630 of the buffer being accessed. */);
4631 Vbuffer_access_fontify_functions = Qnil;
4632
4633 {
4634 Lisp_Object obuf;
4635 obuf = Fcurrent_buffer ();
4636 /* Do this here, because init_buffer_once is too early--it won't work. */
4637 Fset_buffer (Vprin1_to_string_buffer);
4638 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4639 Fset (Fmake_local_variable (intern_c_string ("buffer-access-fontify-functions")),
4640 Qnil);
4641 Fset_buffer (obuf);
4642 }
4643
4644 DEFVAR_LISP ("buffer-access-fontified-property",
4645 Vbuffer_access_fontified_property,
4646 doc: /* Property which (if non-nil) indicates text has been fontified.
4647 `buffer-substring' need not call the `buffer-access-fontify-functions'
4648 functions if all the text being accessed has this property. */);
4649 Vbuffer_access_fontified_property = Qnil;
4650
4651 DEFVAR_LISP ("system-name", Vsystem_name,
4652 doc: /* The host name of the machine Emacs is running on. */);
4653
4654 DEFVAR_LISP ("user-full-name", Vuser_full_name,
4655 doc: /* The full name of the user logged in. */);
4656
4657 DEFVAR_LISP ("user-login-name", Vuser_login_name,
4658 doc: /* The user's name, taken from environment variables if possible. */);
4659
4660 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name,
4661 doc: /* The user's name, based upon the real uid only. */);
4662
4663 DEFVAR_LISP ("operating-system-release", Voperating_system_release,
4664 doc: /* The release of the operating system Emacs is running on. */);
4665
4666 defsubr (&Spropertize);
4667 defsubr (&Schar_equal);
4668 defsubr (&Sgoto_char);
4669 defsubr (&Sstring_to_char);
4670 defsubr (&Schar_to_string);
4671 defsubr (&Sbyte_to_string);
4672 defsubr (&Sbuffer_substring);
4673 defsubr (&Sbuffer_substring_no_properties);
4674 defsubr (&Sbuffer_string);
4675
4676 defsubr (&Spoint_marker);
4677 defsubr (&Smark_marker);
4678 defsubr (&Spoint);
4679 defsubr (&Sregion_beginning);
4680 defsubr (&Sregion_end);
4681
4682 staticpro (&Qfield);
4683 Qfield = intern_c_string ("field");
4684 staticpro (&Qboundary);
4685 Qboundary = intern_c_string ("boundary");
4686 defsubr (&Sfield_beginning);
4687 defsubr (&Sfield_end);
4688 defsubr (&Sfield_string);
4689 defsubr (&Sfield_string_no_properties);
4690 defsubr (&Sdelete_field);
4691 defsubr (&Sconstrain_to_field);
4692
4693 defsubr (&Sline_beginning_position);
4694 defsubr (&Sline_end_position);
4695
4696 /* defsubr (&Smark); */
4697 /* defsubr (&Sset_mark); */
4698 defsubr (&Ssave_excursion);
4699 defsubr (&Ssave_current_buffer);
4700
4701 defsubr (&Sbufsize);
4702 defsubr (&Spoint_max);
4703 defsubr (&Spoint_min);
4704 defsubr (&Spoint_min_marker);
4705 defsubr (&Spoint_max_marker);
4706 defsubr (&Sgap_position);
4707 defsubr (&Sgap_size);
4708 defsubr (&Sposition_bytes);
4709 defsubr (&Sbyte_to_position);
4710
4711 defsubr (&Sbobp);
4712 defsubr (&Seobp);
4713 defsubr (&Sbolp);
4714 defsubr (&Seolp);
4715 defsubr (&Sfollowing_char);
4716 defsubr (&Sprevious_char);
4717 defsubr (&Schar_after);
4718 defsubr (&Schar_before);
4719 defsubr (&Sinsert);
4720 defsubr (&Sinsert_before_markers);
4721 defsubr (&Sinsert_and_inherit);
4722 defsubr (&Sinsert_and_inherit_before_markers);
4723 defsubr (&Sinsert_char);
4724 defsubr (&Sinsert_byte);
4725
4726 defsubr (&Suser_login_name);
4727 defsubr (&Suser_real_login_name);
4728 defsubr (&Suser_uid);
4729 defsubr (&Suser_real_uid);
4730 defsubr (&Suser_full_name);
4731 defsubr (&Semacs_pid);
4732 defsubr (&Scurrent_time);
4733 defsubr (&Sget_internal_run_time);
4734 defsubr (&Sformat_time_string);
4735 defsubr (&Sfloat_time);
4736 defsubr (&Sdecode_time);
4737 defsubr (&Sencode_time);
4738 defsubr (&Scurrent_time_string);
4739 defsubr (&Scurrent_time_zone);
4740 defsubr (&Sset_time_zone_rule);
4741 defsubr (&Ssystem_name);
4742 defsubr (&Smessage);
4743 defsubr (&Smessage_box);
4744 defsubr (&Smessage_or_box);
4745 defsubr (&Scurrent_message);
4746 defsubr (&Sformat);
4747
4748 defsubr (&Sinsert_buffer_substring);
4749 defsubr (&Scompare_buffer_substrings);
4750 defsubr (&Ssubst_char_in_region);
4751 defsubr (&Stranslate_region_internal);
4752 defsubr (&Sdelete_region);
4753 defsubr (&Sdelete_and_extract_region);
4754 defsubr (&Swiden);
4755 defsubr (&Snarrow_to_region);
4756 defsubr (&Ssave_restriction);
4757 defsubr (&Stranspose_regions);
4758 }