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