Add title parameters to frames.
[bpt/emacs.git] / src / editfns.c
CommitLineData
35692fe0 1/* Lisp functions pertaining to editing.
31c8f881 2 Copyright (C) 1985,86,87,89,93,94,95,96,97,98 Free Software Foundation, Inc.
35692fe0
JB
3
4This file is part of GNU Emacs.
5
6GNU Emacs is free software; you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
7c938215 8the Free Software Foundation; either version 2, or (at your option)
35692fe0
JB
9any later version.
10
11GNU Emacs is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with GNU Emacs; see the file COPYING. If not, write to
5a7670bf
RS
18the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19Boston, MA 02111-1307, USA. */
35692fe0
JB
20
21
738429d1
JB
22#include <sys/types.h>
23
18160b98 24#include <config.h>
bfb61299
JB
25
26#ifdef VMS
956ace37 27#include "vms-pwd.h"
bfb61299 28#else
35692fe0 29#include <pwd.h>
bfb61299
JB
30#endif
31
dfcf069d
AS
32#ifdef STDC_HEADERS
33#include <stdlib.h>
34#endif
35
36#ifdef HAVE_UNISTD_H
37#include <unistd.h>
38#endif
39
35692fe0 40#include "lisp.h"
74d6d8c5 41#include "intervals.h"
35692fe0 42#include "buffer.h"
fb8106e8 43#include "charset.h"
35692fe0
JB
44#include "window.h"
45
956ace37 46#include "systime.h"
35692fe0
JB
47
48#define min(a, b) ((a) < (b) ? (a) : (b))
49#define max(a, b) ((a) > (b) ? (a) : (b))
50
a03eaf1c
RS
51#ifndef NULL
52#define NULL 0
53#endif
54
c59b5089
PE
55extern char **environ;
56extern Lisp_Object make_time ();
b1b0ee5a 57extern void insert_from_buffer ();
94751666 58static int tm_diff ();
260e2e2a 59static void update_buffer_properties ();
b771d0da 60size_t emacs_strftime ();
a92ae0ce 61void set_time_zone_rule ();
260e2e2a
KH
62
63Lisp_Object Vbuffer_access_fontify_functions;
64Lisp_Object Qbuffer_access_fontify_functions;
65Lisp_Object Vbuffer_access_fontified_property;
b1b0ee5a 66
e3ed8469
KH
67Lisp_Object Fuser_full_name ();
68
35692fe0
JB
69/* Some static data, and a function to initialize it for each run */
70
71Lisp_Object Vsystem_name;
35b34f72
KH
72Lisp_Object Vuser_real_login_name; /* login name of current user ID */
73Lisp_Object Vuser_full_name; /* full name of current user */
74Lisp_Object Vuser_login_name; /* user name from LOGNAME or USER */
35692fe0
JB
75
76void
77init_editfns ()
78{
52b14ac0 79 char *user_name;
35692fe0
JB
80 register unsigned char *p, *q, *r;
81 struct passwd *pw; /* password entry for the current user */
35692fe0
JB
82 Lisp_Object tem;
83
84 /* Set up system_name even when dumping. */
ac988277 85 init_system_name ();
35692fe0
JB
86
87#ifndef CANNOT_DUMP
88 /* Don't bother with this on initial start when just dumping out */
89 if (!initialized)
90 return;
91#endif /* not CANNOT_DUMP */
92
93 pw = (struct passwd *) getpwuid (getuid ());
87485d6f
MW
94#ifdef MSDOS
95 /* We let the real user name default to "root" because that's quite
96 accurate on MSDOG and because it lets Emacs find the init file.
97 (The DVX libraries override the Djgpp libraries here.) */
35b34f72 98 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
87485d6f 99#else
35b34f72 100 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
87485d6f 101#endif
35692fe0 102
52b14ac0
JB
103 /* Get the effective user name, by consulting environment variables,
104 or the effective uid if those are unset. */
2c9ae24e 105 user_name = (char *) getenv ("LOGNAME");
35692fe0 106 if (!user_name)
4691c06d
RS
107#ifdef WINDOWSNT
108 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
109#else /* WINDOWSNT */
2c9ae24e 110 user_name = (char *) getenv ("USER");
4691c06d 111#endif /* WINDOWSNT */
52b14ac0
JB
112 if (!user_name)
113 {
114 pw = (struct passwd *) getpwuid (geteuid ());
115 user_name = (char *) (pw ? pw->pw_name : "unknown");
116 }
35b34f72 117 Vuser_login_name = build_string (user_name);
35692fe0 118
52b14ac0
JB
119 /* If the user name claimed in the environment vars differs from
120 the real uid, use the claimed name to find the full name. */
35b34f72 121 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
3415b0e9
RS
122 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
123 : Vuser_login_name);
35692fe0 124
8f1e2d16 125 p = (unsigned char *) getenv ("NAME");
9d36d071
RS
126 if (p)
127 Vuser_full_name = build_string (p);
3347526c
RS
128 else if (NILP (Vuser_full_name))
129 Vuser_full_name = build_string ("unknown");
35692fe0
JB
130}
131\f
132DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
5f75e666 133 "Convert arg CHAR to a string containing that character.")
2591ec64
EN
134 (character)
135 Lisp_Object character;
35692fe0 136{
fb8106e8 137 int len;
d11ba98c 138 unsigned char workbuf[4], *str;
fb8106e8 139
2591ec64 140 CHECK_NUMBER (character, 0);
35692fe0 141
fb8106e8 142 len = CHAR_STRING (XFASTINT (character), workbuf, str);
5f75e666 143 return make_string_from_bytes (str, 1, len);
35692fe0
JB
144}
145
146DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
fb8106e8
KH
147 "Convert arg STRING to a character, the first character of that string.\n\
148A multibyte character is handled correctly.")
2591ec64
EN
149 (string)
150 register Lisp_Object string;
35692fe0
JB
151{
152 register Lisp_Object val;
153 register struct Lisp_String *p;
2591ec64 154 CHECK_STRING (string, 0);
2591ec64 155 p = XSTRING (string);
35692fe0 156 if (p->size)
dc3620af 157 XSETFASTINT (val, STRING_CHAR (p->data, STRING_BYTES (p)));
35692fe0 158 else
55561c63 159 XSETFASTINT (val, 0);
35692fe0
JB
160 return val;
161}
162\f
163static Lisp_Object
ec1c14f6
RS
164buildmark (charpos, bytepos)
165 int charpos, bytepos;
35692fe0
JB
166{
167 register Lisp_Object mark;
168 mark = Fmake_marker ();
ec1c14f6 169 set_marker_both (mark, Qnil, charpos, bytepos);
35692fe0
JB
170 return mark;
171}
172
173DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
174 "Return value of point, as an integer.\n\
175Beginning of buffer is position (point-min)")
176 ()
177{
178 Lisp_Object temp;
6ec8bbd2 179 XSETFASTINT (temp, PT);
35692fe0
JB
180 return temp;
181}
182
183DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
184 "Return value of point, as a marker object.")
185 ()
186{
ec1c14f6 187 return buildmark (PT, PT_BYTE);
35692fe0
JB
188}
189
190int
191clip_to_bounds (lower, num, upper)
192 int lower, num, upper;
193{
194 if (num < lower)
195 return lower;
196 else if (num > upper)
197 return upper;
198 else
199 return num;
200}
201
202DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
203 "Set point to POSITION, a number or marker.\n\
fb8106e8
KH
204Beginning of buffer is position (point-min), end is (point-max).\n\
205If the position is in the middle of a multibyte form,\n\
206the actual point is set at the head of the multibyte form\n\
207except in the case that `enable-multibyte-characters' is nil.")
2591ec64
EN
208 (position)
209 register Lisp_Object position;
35692fe0 210{
fb8106e8
KH
211 int pos;
212 unsigned char *p;
213
72ef82ec
RS
214 if (MARKERP (position)
215 && current_buffer == XMARKER (position)->buffer)
ec1c14f6
RS
216 {
217 pos = marker_position (position);
218 if (pos < BEGV)
219 SET_PT_BOTH (BEGV, BEGV_BYTE);
220 else if (pos > ZV)
221 SET_PT_BOTH (ZV, ZV_BYTE);
222 else
223 SET_PT_BOTH (pos, marker_byte_position (position));
224
225 return position;
226 }
227
2591ec64 228 CHECK_NUMBER_COERCE_MARKER (position, 0);
35692fe0 229
fb8106e8 230 pos = clip_to_bounds (BEGV, XINT (position), ZV);
fb8106e8 231 SET_PT (pos);
2591ec64 232 return position;
35692fe0
JB
233}
234
235static Lisp_Object
236region_limit (beginningp)
237 int beginningp;
238{
646d9d18 239 extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
35692fe0 240 register Lisp_Object m;
c9dd14e1
RM
241 if (!NILP (Vtransient_mark_mode) && NILP (Vmark_even_if_inactive)
242 && NILP (current_buffer->mark_active))
243 Fsignal (Qmark_inactive, Qnil);
35692fe0 244 m = Fmarker_position (current_buffer->mark);
56a98455 245 if (NILP (m)) error ("There is no region now");
6ec8bbd2
KH
246 if ((PT < XFASTINT (m)) == beginningp)
247 return (make_number (PT));
35692fe0
JB
248 else
249 return (m);
250}
251
252DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
253 "Return position of beginning of region, as an integer.")
254 ()
255{
256 return (region_limit (1));
257}
258
259DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
260 "Return position of end of region, as an integer.")
261 ()
262{
263 return (region_limit (0));
264}
265
35692fe0
JB
266DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
267 "Return this buffer's mark, as a marker object.\n\
268Watch out! Moving this marker changes the mark position.\n\
269If you set the marker not to point anywhere, the buffer will have no mark.")
270 ()
271{
272 return current_buffer->mark;
273}
c9ed721d
RS
274\f
275DEFUN ("line-beginning-position", Fline_beginning_position, Sline_beginning_position,
276 0, 1, 0,
277 "Return the character position of the first character on the current line.\n\
278With argument N not nil or 1, move forward N - 1 lines first.\n\
279If scan reaches end of buffer, return that position.\n\
280This function does not move point.")
281 (n)
282 Lisp_Object n;
283{
ec1c14f6 284 register int orig, orig_byte, end;
c9ed721d
RS
285
286 if (NILP (n))
287 XSETFASTINT (n, 1);
288 else
289 CHECK_NUMBER (n, 0);
290
291 orig = PT;
ec1c14f6 292 orig_byte = PT_BYTE;
c9ed721d
RS
293 Fforward_line (make_number (XINT (n) - 1));
294 end = PT;
ec1c14f6 295 SET_PT_BOTH (orig, orig_byte);
35692fe0 296
c9ed721d
RS
297 return make_number (end);
298}
299
300DEFUN ("line-end-position", Fline_end_position, Sline_end_position,
301 0, 1, 0,
302 "Return the character position of the last character on the current line.\n\
303With argument N not nil or 1, move forward N - 1 lines first.\n\
304If scan reaches end of buffer, return that position.\n\
305This function does not move point.")
306 (n)
307 Lisp_Object n;
308{
309 if (NILP (n))
310 XSETFASTINT (n, 1);
311 else
312 CHECK_NUMBER (n, 0);
313
314 return make_number (find_before_next_newline
315 (PT, 0, XINT (n) - (XINT (n) <= 0)));
316}
317\f
35692fe0
JB
318Lisp_Object
319save_excursion_save ()
320{
0e2c9c70
JB
321 register int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
322 == current_buffer);
35692fe0
JB
323
324 return Fcons (Fpoint_marker (),
aea4a109 325 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
9772455e
RS
326 Fcons (visible ? Qt : Qnil,
327 current_buffer->mark_active)));
35692fe0
JB
328}
329
330Lisp_Object
331save_excursion_restore (info)
4ad8681a 332 Lisp_Object info;
35692fe0 333{
4ad8681a
RS
334 Lisp_Object tem, tem1, omark, nmark;
335 struct gcpro gcpro1, gcpro2, gcpro3;
35692fe0
JB
336
337 tem = Fmarker_buffer (Fcar (info));
338 /* If buffer being returned to is now deleted, avoid error */
339 /* Otherwise could get error here while unwinding to top level
340 and crash */
341 /* In that case, Fmarker_buffer returns nil now. */
56a98455 342 if (NILP (tem))
35692fe0 343 return Qnil;
4ad8681a
RS
344
345 omark = nmark = Qnil;
346 GCPRO3 (info, omark, nmark);
347
35692fe0
JB
348 Fset_buffer (tem);
349 tem = Fcar (info);
350 Fgoto_char (tem);
351 unchain_marker (tem);
352 tem = Fcar (Fcdr (info));
03d18690 353 omark = Fmarker_position (current_buffer->mark);
35692fe0 354 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
03d18690 355 nmark = Fmarker_position (tem);
35692fe0
JB
356 unchain_marker (tem);
357 tem = Fcdr (Fcdr (info));
ef580991
RS
358#if 0 /* We used to make the current buffer visible in the selected window
359 if that was true previously. That avoids some anomalies.
360 But it creates others, and it wasn't documented, and it is simpler
361 and cleaner never to alter the window/buffer connections. */
9772455e
RS
362 tem1 = Fcar (tem);
363 if (!NILP (tem1)
0e2c9c70 364 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
35692fe0 365 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
ef580991 366#endif /* 0 */
9772455e
RS
367
368 tem1 = current_buffer->mark_active;
369 current_buffer->mark_active = Fcdr (tem);
9fed2b18
RS
370 if (!NILP (Vrun_hooks))
371 {
03d18690
RS
372 /* If mark is active now, and either was not active
373 or was at a different place, run the activate hook. */
9fed2b18 374 if (! NILP (current_buffer->mark_active))
03d18690
RS
375 {
376 if (! EQ (omark, nmark))
377 call1 (Vrun_hooks, intern ("activate-mark-hook"));
378 }
379 /* If mark has ceased to be active, run deactivate hook. */
9fed2b18
RS
380 else if (! NILP (tem1))
381 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
382 }
4ad8681a 383 UNGCPRO;
35692fe0
JB
384 return Qnil;
385}
386
387DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
388 "Save point, mark, and current buffer; execute BODY; restore those things.\n\
389Executes BODY just like `progn'.\n\
390The values of point, mark and the current buffer are restored\n\
9772455e 391even in case of abnormal exit (throw or error).\n\
85cac557
RS
392The state of activation of the mark is also restored.\n\
393\n\
394This construct does not save `deactivate-mark', and therefore\n\
395functions that change the buffer will still cause deactivation\n\
396of the mark at the end of the command. To prevent that, bind\n\
397`deactivate-mark' with `let'.")
35692fe0
JB
398 (args)
399 Lisp_Object args;
400{
401 register Lisp_Object val;
402 int count = specpdl_ptr - specpdl;
403
404 record_unwind_protect (save_excursion_restore, save_excursion_save ());
4bc8c7d2
RS
405
406 val = Fprogn (args);
407 return unbind_to (count, val);
408}
409
410DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
411 "Save the current buffer; execute BODY; restore the current buffer.\n\
412Executes BODY just like `progn'.")
413 (args)
414 Lisp_Object args;
415{
416 register Lisp_Object val;
417 int count = specpdl_ptr - specpdl;
418
cb5e5f74 419 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
4bc8c7d2 420
35692fe0
JB
421 val = Fprogn (args);
422 return unbind_to (count, val);
423}
424\f
425DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 0, 0,
426 "Return the number of characters in the current buffer.")
427 ()
428{
429 Lisp_Object temp;
55561c63 430 XSETFASTINT (temp, Z - BEG);
35692fe0
JB
431 return temp;
432}
433
434DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
435 "Return the minimum permissible value of point in the current buffer.\n\
4c390850 436This is 1, unless narrowing (a buffer restriction) is in effect.")
35692fe0
JB
437 ()
438{
439 Lisp_Object temp;
55561c63 440 XSETFASTINT (temp, BEGV);
35692fe0
JB
441 return temp;
442}
443
444DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
445 "Return a marker to the minimum permissible value of point in this buffer.\n\
4c390850 446This is the beginning, unless narrowing (a buffer restriction) is in effect.")
35692fe0
JB
447 ()
448{
ec1c14f6 449 return buildmark (BEGV, BEGV_BYTE);
35692fe0
JB
450}
451
452DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
453 "Return the maximum permissible value of point in the current buffer.\n\
4c390850
RS
454This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
455is in effect, in which case it is less.")
35692fe0
JB
456 ()
457{
458 Lisp_Object temp;
55561c63 459 XSETFASTINT (temp, ZV);
35692fe0
JB
460 return temp;
461}
462
463DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
464 "Return a marker to the maximum permissible value of point in this buffer.\n\
4c390850
RS
465This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
466is in effect, in which case it is less.")
35692fe0
JB
467 ()
468{
ec1c14f6 469 return buildmark (ZV, ZV_BYTE);
35692fe0
JB
470}
471
c86212b9
RS
472DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
473 "Return the position of the gap, in the current buffer.\n\
474See also `gap-size'.")
475 ()
476{
477 Lisp_Object temp;
478 XSETFASTINT (temp, GPT);
479 return temp;
480}
481
482DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
483 "Return the size of the current buffer's gap.\n\
484See also `gap-position'.")
485 ()
486{
487 Lisp_Object temp;
488 XSETFASTINT (temp, GAP_SIZE);
489 return temp;
490}
491
7df74da6 492DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
fcf9683e
KH
493 "Return the byte position for character position POSITION.\n\
494If POSITION is out of range, the value is nil.")
7df74da6 495 (position)
80e01f8d 496 Lisp_Object position;
7df74da6 497{
fa8a5a15 498 CHECK_NUMBER_COERCE_MARKER (position, 1);
fcf9683e
KH
499 if (XINT (position) < BEG || XINT (position) > Z)
500 return Qnil;
fa8a5a15 501 return make_number (CHAR_TO_BYTE (XINT (position)));
7df74da6 502}
3ab0732d
RS
503
504DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
fcf9683e
KH
505 "Return the character position for byte position BYTEPOS.\n\
506If BYTEPOS is out of range, the value is nil.")
3ab0732d
RS
507 (bytepos)
508 Lisp_Object bytepos;
509{
510 CHECK_NUMBER (bytepos, 1);
fcf9683e
KH
511 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
512 return Qnil;
3ab0732d
RS
513 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
514}
7df74da6 515\f
850a8179
JB
516DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
517 "Return the character following point, as a number.\n\
fb8106e8
KH
518At the end of the buffer or accessible region, return 0.\n\
519If `enable-multibyte-characters' is nil or point is not\n\
520 at character boundary, multibyte form is ignored,\n\
521 and only one byte following point is returned as a character.")
35692fe0
JB
522 ()
523{
524 Lisp_Object temp;
6ec8bbd2 525 if (PT >= ZV)
55561c63 526 XSETFASTINT (temp, 0);
850a8179 527 else
ec1c14f6 528 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
35692fe0
JB
529 return temp;
530}
531
850a8179
JB
532DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
533 "Return the character preceding point, as a number.\n\
fb8106e8
KH
534At the beginning of the buffer or accessible region, return 0.\n\
535If `enable-multibyte-characters' is nil or point is not\n\
536 at character boundary, multi-byte form is ignored,\n\
537 and only one byte preceding point is returned as a character.")
35692fe0
JB
538 ()
539{
540 Lisp_Object temp;
6ec8bbd2 541 if (PT <= BEGV)
55561c63 542 XSETFASTINT (temp, 0);
fb8106e8
KH
543 else if (!NILP (current_buffer->enable_multibyte_characters))
544 {
ec1c14f6 545 int pos = PT_BYTE;
fb8106e8
KH
546 DEC_POS (pos);
547 XSETFASTINT (temp, FETCH_CHAR (pos));
548 }
35692fe0 549 else
ec1c14f6 550 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
35692fe0
JB
551 return temp;
552}
553
554DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
ec1c14f6 555 "Return t if point is at the beginning of the buffer.\n\
35692fe0
JB
556If the buffer is narrowed, this means the beginning of the narrowed part.")
557 ()
558{
6ec8bbd2 559 if (PT == BEGV)
35692fe0
JB
560 return Qt;
561 return Qnil;
562}
563
564DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
ec1c14f6 565 "Return t if point is at the end of the buffer.\n\
35692fe0
JB
566If the buffer is narrowed, this means the end of the narrowed part.")
567 ()
568{
6ec8bbd2 569 if (PT == ZV)
35692fe0
JB
570 return Qt;
571 return Qnil;
572}
573
574DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
ec1c14f6 575 "Return t if point is at the beginning of a line.")
35692fe0
JB
576 ()
577{
ec1c14f6 578 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
35692fe0
JB
579 return Qt;
580 return Qnil;
581}
582
583DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
ec1c14f6 584 "Return t if point is at the end of a line.\n\
35692fe0
JB
585`End of a line' includes point being at the end of the buffer.")
586 ()
587{
ec1c14f6 588 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
35692fe0
JB
589 return Qt;
590 return Qnil;
591}
592
fa1d3816 593DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
35692fe0
JB
594 "Return character in current buffer at position POS.\n\
595POS is an integer or a buffer pointer.\n\
39a4c932 596If POS is out of range, the value is nil.")
35692fe0
JB
597 (pos)
598 Lisp_Object pos;
599{
ec1c14f6 600 register int pos_byte;
35692fe0 601 register Lisp_Object val;
35692fe0 602
fa1d3816 603 if (NILP (pos))
39a4c932
RS
604 {
605 pos_byte = PT_BYTE;
606 pos = PT;
607 }
608
609 if (MARKERP (pos))
85cac557
RS
610 {
611 pos_byte = marker_byte_position (pos);
612 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
613 return Qnil;
614 }
fa1d3816
RS
615 else
616 {
617 CHECK_NUMBER_COERCE_MARKER (pos, 0);
b98ef0dc 618 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
85cac557 619 return Qnil;
ec1c14f6
RS
620
621 pos_byte = CHAR_TO_BYTE (XINT (pos));
fa1d3816 622 }
35692fe0 623
ec1c14f6 624 return make_number (FETCH_CHAR (pos_byte));
35692fe0 625}
fb8106e8 626
fa1d3816 627DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
fb8106e8
KH
628 "Return character in current buffer preceding position POS.\n\
629POS is an integer or a buffer pointer.\n\
39a4c932 630If POS is out of range, the value is nil.")
fb8106e8
KH
631 (pos)
632 Lisp_Object pos;
633{
634 register Lisp_Object val;
ec1c14f6 635 register int pos_byte;
fb8106e8 636
fa1d3816 637 if (NILP (pos))
39a4c932
RS
638 {
639 pos_byte = PT_BYTE;
640 pos = PT;
641 }
642
643 if (MARKERP (pos))
85cac557
RS
644 {
645 pos_byte = marker_byte_position (pos);
646
647 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
648 return Qnil;
649 }
fa1d3816
RS
650 else
651 {
652 CHECK_NUMBER_COERCE_MARKER (pos, 0);
fb8106e8 653
b98ef0dc 654 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
85cac557
RS
655 return Qnil;
656
ec1c14f6 657 pos_byte = CHAR_TO_BYTE (XINT (pos));
fa1d3816 658 }
fb8106e8
KH
659
660 if (!NILP (current_buffer->enable_multibyte_characters))
661 {
ec1c14f6
RS
662 DEC_POS (pos_byte);
663 XSETFASTINT (val, FETCH_CHAR (pos_byte));
fb8106e8
KH
664 }
665 else
666 {
ec1c14f6
RS
667 pos_byte--;
668 XSETFASTINT (val, FETCH_BYTE (pos_byte));
fb8106e8
KH
669 }
670 return val;
671}
35692fe0 672\f
87485d6f 673DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
35692fe0
JB
674 "Return the name under which the user logged in, as a string.\n\
675This is based on the effective uid, not the real uid.\n\
2c9ae24e 676Also, if the environment variable LOGNAME or USER is set,\n\
87485d6f
MW
677that determines the value of this function.\n\n\
678If optional argument UID is an integer, return the login name of the user\n\
679with that uid, or nil if there is no such user.")
680 (uid)
681 Lisp_Object uid;
35692fe0 682{
87485d6f
MW
683 struct passwd *pw;
684
f8a0e364
RS
685 /* Set up the user name info if we didn't do it before.
686 (That can happen if Emacs is dumpable
687 but you decide to run `temacs -l loadup' and not dump. */
35b34f72 688 if (INTEGERP (Vuser_login_name))
f8a0e364 689 init_editfns ();
87485d6f
MW
690
691 if (NILP (uid))
35b34f72 692 return Vuser_login_name;
87485d6f
MW
693
694 CHECK_NUMBER (uid, 0);
695 pw = (struct passwd *) getpwuid (XINT (uid));
696 return (pw ? build_string (pw->pw_name) : Qnil);
35692fe0
JB
697}
698
699DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
700 0, 0, 0,
701 "Return the name of the user's real uid, as a string.\n\
9658bdd0 702This ignores the environment variables LOGNAME and USER, so it differs from\n\
b1da234a 703`user-login-name' when running under `su'.")
35692fe0
JB
704 ()
705{
f8a0e364
RS
706 /* Set up the user name info if we didn't do it before.
707 (That can happen if Emacs is dumpable
708 but you decide to run `temacs -l loadup' and not dump. */
35b34f72 709 if (INTEGERP (Vuser_login_name))
f8a0e364 710 init_editfns ();
35b34f72 711 return Vuser_real_login_name;
35692fe0
JB
712}
713
714DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
715 "Return the effective uid of Emacs, as an integer.")
716 ()
717{
718 return make_number (geteuid ());
719}
720
721DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
722 "Return the real uid of Emacs, as an integer.")
723 ()
724{
725 return make_number (getuid ());
726}
727
c9ed721d
RS
728DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
729 "Return the full name of the user logged in, as a string.\n\
730If optional argument UID is an integer, return the full name of the user\n\
ca38bbb2 731with that uid, or \"unknown\" if there is no such user.\n\
3415b0e9
RS
732If UID is a string, return the full name of the user with that login\n\
733name, or \"unknown\" if no such user could be found.")
c9ed721d
RS
734 (uid)
735 Lisp_Object uid;
35692fe0 736{
c9ed721d 737 struct passwd *pw;
b0e92acd 738 register unsigned char *p, *q;
3415b0e9
RS
739 extern char *index ();
740 Lisp_Object full;
c9ed721d
RS
741
742 if (NILP (uid))
3415b0e9
RS
743 return Vuser_full_name;
744 else if (NUMBERP (uid))
745 pw = (struct passwd *) getpwuid (XINT (uid));
746 else if (STRINGP (uid))
747 pw = (struct passwd *) getpwnam (XSTRING (uid)->data);
748 else
749 error ("Invalid UID specification");
c9ed721d 750
3415b0e9 751 if (!pw)
3347526c 752 return Qnil;
3415b0e9
RS
753
754 p = (unsigned char *) USER_FULL_NAME;
755 /* Chop off everything after the first comma. */
756 q = (unsigned char *) index (p, ',');
757 full = make_string (p, q ? q - p : strlen (p));
758
759#ifdef AMPERSAND_FULL_NAME
760 p = XSTRING (full)->data;
761 q = (unsigned char *) index (p, '&');
762 /* Substitute the login name for the &, upcasing the first character. */
763 if (q)
764 {
b0e92acd 765 register unsigned char *r;
3415b0e9
RS
766 Lisp_Object login;
767
768 login = Fuser_login_name (make_number (pw->pw_uid));
769 r = (unsigned char *) alloca (strlen (p) + XSTRING (login)->size + 1);
770 bcopy (p, r, q - p);
771 r[q - p] = 0;
772 strcat (r, XSTRING (login)->data);
773 r[q - p] = UPCASE (r[q - p]);
774 strcat (r, q + 1);
775 full = build_string (r);
776 }
777#endif /* AMPERSAND_FULL_NAME */
778
779 return full;
35692fe0
JB
780}
781
782DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
783 "Return the name of the machine you are running on, as a string.")
784 ()
785{
786 return Vsystem_name;
787}
788
ac988277
KH
789/* For the benefit of callers who don't want to include lisp.h */
790char *
791get_system_name ()
792{
3d976a9a
RS
793 if (STRINGP (Vsystem_name))
794 return (char *) XSTRING (Vsystem_name)->data;
795 else
796 return "";
ac988277
KH
797}
798
7fd233b3
RS
799DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
800 "Return the process ID of Emacs, as an integer.")
801 ()
802{
803 return make_number (getpid ());
804}
805
d940e0e4 806DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
e983fdb2 807 "Return the current time, as the number of seconds since 1970-01-01 00:00:00.\n\
956ace37
JB
808The time is returned as a list of three integers. The first has the\n\
809most significant 16 bits of the seconds, while the second has the\n\
810least significant 16 bits. The third integer gives the microsecond\n\
811count.\n\
812\n\
813The microsecond count is zero on systems that do not provide\n\
814resolution finer than a second.")
d940e0e4
JB
815 ()
816{
956ace37
JB
817 EMACS_TIME t;
818 Lisp_Object result[3];
819
820 EMACS_GET_TIME (t);
d2fd0445
KH
821 XSETINT (result[0], (EMACS_SECS (t) >> 16) & 0xffff);
822 XSETINT (result[1], (EMACS_SECS (t) >> 0) & 0xffff);
823 XSETINT (result[2], EMACS_USECS (t));
956ace37
JB
824
825 return Flist (3, result);
d940e0e4
JB
826}
827\f
828
e3120ab5
JB
829static int
830lisp_time_argument (specified_time, result)
831 Lisp_Object specified_time;
832 time_t *result;
833{
834 if (NILP (specified_time))
835 return time (result) != -1;
836 else
837 {
838 Lisp_Object high, low;
839 high = Fcar (specified_time);
840 CHECK_NUMBER (high, 0);
841 low = Fcdr (specified_time);
ae683129 842 if (CONSP (low))
e3120ab5
JB
843 low = Fcar (low);
844 CHECK_NUMBER (low, 0);
845 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
846 return *result >> 16 == XINT (high);
847 }
848}
849
70ebbe5f
PE
850/* Write information into buffer S of size MAXSIZE, according to the
851 FORMAT of length FORMAT_LEN, using time information taken from *TP.
852 Return the number of bytes written, not including the terminating
853 '\0'. If S is NULL, nothing will be written anywhere; so to
854 determine how many bytes would be written, use NULL for S and
855 ((size_t) -1) for MAXSIZE.
856
857 This function behaves like emacs_strftime, except it allows null
858 bytes in FORMAT. */
859static size_t
860emacs_memftime (s, maxsize, format, format_len, tp)
861 char *s;
862 size_t maxsize;
863 const char *format;
864 size_t format_len;
865 const struct tm *tp;
866{
867 size_t total = 0;
868
be09e6e6
PE
869 /* Loop through all the null-terminated strings in the format
870 argument. Normally there's just one null-terminated string, but
871 there can be arbitrarily many, concatenated together, if the
872 format contains '\0' bytes. emacs_strftime stops at the first
873 '\0' byte so we must invoke it separately for each such string. */
70ebbe5f
PE
874 for (;;)
875 {
876 size_t len;
877 size_t result;
878
879 if (s)
880 s[0] = '\1';
881
882 result = emacs_strftime (s, maxsize, format, tp);
883
884 if (s)
885 {
886 if (result == 0 && s[0] != '\0')
887 return 0;
888 s += result + 1;
889 }
890
891 maxsize -= result + 1;
892 total += result;
893 len = strlen (format);
894 if (len == format_len)
895 return total;
896 total++;
897 format += len + 1;
898 format_len -= len + 1;
899 }
900}
901
3efcc98a 902/*
b48382a0
RS
903DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
904 "Use FORMAT-STRING to format the time TIME, or now if omitted.\n\
905TIME is specified as (HIGH LOW . IGNORED) or (HIGH . LOW), as returned by\n\
906`current-time' or `file-attributes'.\n\
907The third, optional, argument UNIVERSAL, if non-nil, means describe TIME\n\
908as Universal Time; nil means describe TIME in the local time zone.\n\
909The value is a copy of FORMAT-STRING, but with certain constructs replaced\n\
910by text that describes the specified date and time in TIME:\n\
a82d387c 911\n\
b48382a0
RS
912%Y is the year, %y within the century, %C the century.\n\
913%G is the year corresponding to the ISO week, %g within the century.\n\
b771d0da
PE
914%m is the numeric month.\n\
915%b and %h are the locale's abbreviated month name, %B the full name.\n\
b48382a0
RS
916%d is the day of the month, zero-padded, %e is blank-padded.\n\
917%u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.\n\
b771d0da 918%a is the locale's abbreviated name of the day of week, %A the full name.\n\
b48382a0
RS
919%U is the week number starting on Sunday, %W starting on Monday,\n\
920 %V according to ISO 8601.\n\
921%j is the day of the year.\n\
922\n\
923%H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H\n\
924 only blank-padded, %l is like %I blank-padded.\n\
b771d0da 925%p is the locale's equivalent of either AM or PM.\n\
b48382a0
RS
926%M is the minute.\n\
927%S is the second.\n\
928%Z is the time zone name, %z is the numeric form.\n\
929%s is the number of seconds since 1970-01-01 00:00:00 +0000.\n\
930\n\
931%c is the locale's date and time format.\n\
932%x is the locale's \"preferred\" date format.\n\
933%D is like \"%m/%d/%y\".\n\
934\n\
935%R is like \"%H:%M\", %T is like \"%H:%M:%S\", %r is like \"%I:%M:%S %p\".\n\
936%X is the locale's \"preferred\" time format.\n\
937\n\
b771d0da 938Finally, %n is a newline, %t is a tab, %% is a literal %.\n\
b48382a0 939\n\
3efcc98a 940Certain flags and modifiers are available with some format controls.\n\
b48382a0
RS
941The flags are `_' and `-'. For certain characters X, %_X is like %X,\n\
942but padded with blanks; %-X is like %X, but without padding.\n\
943%NX (where N stands for an integer) is like %X,\n\
944but takes up at least N (a number) positions.\n\
945The modifiers are `E' and `O'. For certain characters X,\n\
946%EX is a locale's alternative version of %X;\n\
947%OX is like %X, but uses the locale's number symbols.\n\
948\n\
949For example, to produce full ISO 8601 format, use \"%Y-%m-%dT%T%z\".")
726ed0da 950 (format_string, time, universal)
3efcc98a
RS
951*/
952
953DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
954 0 /* See immediately above */)
b48382a0
RS
955 (format_string, time, universal)
956 Lisp_Object format_string, time, universal;
a82d387c
RS
957{
958 time_t value;
959 int size;
177ea5f1 960 struct tm *tm;
a82d387c
RS
961
962 CHECK_STRING (format_string, 1);
963
964 if (! lisp_time_argument (time, &value))
965 error ("Invalid time specification");
966
967 /* This is probably enough. */
dc3620af 968 size = STRING_BYTES (XSTRING (format_string)) * 6 + 50;
a82d387c 969
177ea5f1
PE
970 tm = NILP (universal) ? localtime (&value) : gmtime (&value);
971 if (! tm)
972 error ("Specified time is not representable");
973
a82d387c
RS
974 while (1)
975 {
b48382a0
RS
976 char *buf = (char *) alloca (size + 1);
977 int result;
978
bfbcc5ee 979 buf[0] = '\1';
70ebbe5f
PE
980 result = emacs_memftime (buf, size, XSTRING (format_string)->data,
981 STRING_BYTES (XSTRING (format_string)),
177ea5f1 982 tm);
bfbcc5ee 983 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
70ebbe5f 984 return make_string (buf, result);
b48382a0
RS
985
986 /* If buffer was too small, make it bigger and try again. */
70ebbe5f
PE
987 result = emacs_memftime (NULL, (size_t) -1,
988 XSTRING (format_string)->data,
989 STRING_BYTES (XSTRING (format_string)),
177ea5f1 990 tm);
b48382a0 991 size = result + 1;
a82d387c
RS
992 }
993}
994
4691c06d
RS
995DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
996 "Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).\n\
997The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED)\n\
998or (HIGH . LOW), as from `current-time' and `file-attributes', or `nil'\n\
999to use the current time. The list has the following nine members:\n\
145b0681
RS
1000SEC is an integer between 0 and 60; SEC is 60 for a leap second, which\n\
1001only some operating systems support. MINUTE is an integer between 0 and 59.\n\
4691c06d
RS
1002HOUR is an integer between 0 and 23. DAY is an integer between 1 and 31.\n\
1003MONTH is an integer between 1 and 12. YEAR is an integer indicating the\n\
1004four-digit year. DOW is the day of week, an integer between 0 and 6, where\n\
10050 is Sunday. DST is t if daylight savings time is effect, otherwise nil.\n\
1006ZONE is an integer indicating the number of seconds east of Greenwich.\n\
2c6c7c72 1007\(Note that Common Lisp has different meanings for DOW and ZONE.)")
4691c06d
RS
1008 (specified_time)
1009 Lisp_Object specified_time;
1010{
1011 time_t time_spec;
3c887943 1012 struct tm save_tm;
4691c06d
RS
1013 struct tm *decoded_time;
1014 Lisp_Object list_args[9];
1015
1016 if (! lisp_time_argument (specified_time, &time_spec))
1017 error ("Invalid time specification");
1018
1019 decoded_time = localtime (&time_spec);
177ea5f1
PE
1020 if (! decoded_time)
1021 error ("Specified time is not representable");
3c887943
KH
1022 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1023 XSETFASTINT (list_args[1], decoded_time->tm_min);
1024 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1025 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1026 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
236ebf35 1027 XSETINT (list_args[5], decoded_time->tm_year + 1900);
3c887943 1028 XSETFASTINT (list_args[6], decoded_time->tm_wday);
4691c06d 1029 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
3c887943
KH
1030
1031 /* Make a copy, in case gmtime modifies the struct. */
1032 save_tm = *decoded_time;
1033 decoded_time = gmtime (&time_spec);
1034 if (decoded_time == 0)
1035 list_args[8] = Qnil;
1036 else
94751666 1037 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
4691c06d
RS
1038 return Flist (9, list_args);
1039}
1040
6ee9061c 1041DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
2591ec64 1042 "Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.\n\
6ee9061c
RS
1043This is the reverse operation of `decode-time', which see.\n\
1044ZONE defaults to the current time zone rule. This can\n\
085e9fcb 1045be a string or t (as from `set-time-zone-rule'), or it can be a list\n\
7459d65b 1046\(as from `current-time-zone') or an integer (as from `decode-time')\n\
c59b5089 1047applied without consideration for daylight savings time.\n\
6ee9061c
RS
1048\n\
1049You can pass more than 7 arguments; then the first six arguments\n\
1050are used as SECOND through YEAR, and the *last* argument is used as ZONE.\n\
1051The intervening arguments are ignored.\n\
1052This feature lets (apply 'encode-time (decode-time ...)) work.\n\
1053\n\
c59b5089
PE
1054Out-of-range values for SEC, MINUTE, HOUR, DAY, or MONTH are allowed;\n\
1055for example, a DAY of 0 means the day preceding the given month.\n\
01ba8cce 1056Year numbers less than 100 are treated just like other year numbers.\n\
c59b5089 1057If you want them to stand for years in this century, you must do that yourself.")
6ee9061c
RS
1058 (nargs, args)
1059 int nargs;
1060 register Lisp_Object *args;
cce7b8a0 1061{
1b8fa736 1062 time_t time;
c59b5089 1063 struct tm tm;
60653898 1064 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
6ee9061c
RS
1065
1066 CHECK_NUMBER (args[0], 0); /* second */
1067 CHECK_NUMBER (args[1], 1); /* minute */
1068 CHECK_NUMBER (args[2], 2); /* hour */
1069 CHECK_NUMBER (args[3], 3); /* day */
1070 CHECK_NUMBER (args[4], 4); /* month */
1071 CHECK_NUMBER (args[5], 5); /* year */
1072
1073 tm.tm_sec = XINT (args[0]);
1074 tm.tm_min = XINT (args[1]);
1075 tm.tm_hour = XINT (args[2]);
1076 tm.tm_mday = XINT (args[3]);
1077 tm.tm_mon = XINT (args[4]) - 1;
1078 tm.tm_year = XINT (args[5]) - 1900;
c59b5089
PE
1079 tm.tm_isdst = -1;
1080
1081 if (CONSP (zone))
1082 zone = Fcar (zone);
1b8fa736 1083 if (NILP (zone))
c59b5089
PE
1084 time = mktime (&tm);
1085 else
1b8fa736 1086 {
c59b5089
PE
1087 char tzbuf[100];
1088 char *tzstring;
1089 char **oldenv = environ, **newenv;
1090
2e34157c 1091 if (EQ (zone, Qt))
085e9fcb
EN
1092 tzstring = "UTC0";
1093 else if (STRINGP (zone))
4d4c1514 1094 tzstring = (char *) XSTRING (zone)->data;
c59b5089 1095 else if (INTEGERP (zone))
1b8fa736 1096 {
c59b5089
PE
1097 int abszone = abs (XINT (zone));
1098 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1099 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1100 tzstring = tzbuf;
1b8fa736 1101 }
c59b5089
PE
1102 else
1103 error ("Invalid time zone specification");
1104
1105 /* Set TZ before calling mktime; merely adjusting mktime's returned
1106 value doesn't suffice, since that would mishandle leap seconds. */
1107 set_time_zone_rule (tzstring);
1108
1109 time = mktime (&tm);
1110
1111 /* Restore TZ to previous value. */
1112 newenv = environ;
1113 environ = oldenv;
c0efcacf 1114 xfree (newenv);
c59b5089
PE
1115#ifdef LOCALTIME_CACHE
1116 tzset ();
1117#endif
1b8fa736 1118 }
1b8fa736 1119
c59b5089
PE
1120 if (time == (time_t) -1)
1121 error ("Specified time is not representable");
1122
1123 return make_time (time);
cce7b8a0
RS
1124}
1125
2148f2b4 1126DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
35692fe0 1127 "Return the current time, as a human-readable string.\n\
2148f2b4
RS
1128Programs can use this function to decode a time,\n\
1129since the number of columns in each field is fixed.\n\
1130The format is `Sun Sep 16 01:03:52 1973'.\n\
7a8630da
RS
1131However, see also the functions `decode-time' and `format-time-string'\n\
1132which provide a much more powerful and general facility.\n\
1133\n\
2148f2b4
RS
1134If an argument is given, it specifies a time to format\n\
1135instead of the current time. The argument should have the form:\n\
1136 (HIGH . LOW)\n\
1137or the form:\n\
1138 (HIGH LOW . IGNORED).\n\
1139Thus, you can use times obtained from `current-time'\n\
1140and from `file-attributes'.")
1141 (specified_time)
1142 Lisp_Object specified_time;
1143{
e3120ab5 1144 time_t value;
35692fe0 1145 char buf[30];
2148f2b4
RS
1146 register char *tem;
1147
e3120ab5
JB
1148 if (! lisp_time_argument (specified_time, &value))
1149 value = -1;
2148f2b4 1150 tem = (char *) ctime (&value);
35692fe0
JB
1151
1152 strncpy (buf, tem, 24);
1153 buf[24] = 0;
1154
1155 return build_string (buf);
1156}
c2662aea 1157
94751666 1158#define TM_YEAR_BASE 1900
e3120ab5 1159
94751666
PE
1160/* Yield A - B, measured in seconds.
1161 This function is copied from the GNU C Library. */
1162static int
1163tm_diff (a, b)
e3120ab5
JB
1164 struct tm *a, *b;
1165{
94751666
PE
1166 /* Compute intervening leap days correctly even if year is negative.
1167 Take care to avoid int overflow in leap day calculations,
1168 but it's OK to assume that A and B are close to each other. */
1169 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1170 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1171 int a100 = a4 / 25 - (a4 % 25 < 0);
1172 int b100 = b4 / 25 - (b4 % 25 < 0);
1173 int a400 = a100 >> 2;
1174 int b400 = b100 >> 2;
1175 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1176 int years = a->tm_year - b->tm_year;
1177 int days = (365 * years + intervening_leap_days
1178 + (a->tm_yday - b->tm_yday));
1179 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1180 + (a->tm_min - b->tm_min))
8e718b4e 1181 + (a->tm_sec - b->tm_sec));
e3120ab5
JB
1182}
1183
1184DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1185 "Return the offset and name for the local time zone.\n\
1186This returns a list of the form (OFFSET NAME).\n\
1187OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).\n\
1188 A negative value means west of Greenwich.\n\
1189NAME is a string giving the name of the time zone.\n\
1190If an argument is given, it specifies when the time zone offset is determined\n\
1191instead of using the current time. The argument should have the form:\n\
1192 (HIGH . LOW)\n\
1193or the form:\n\
1194 (HIGH LOW . IGNORED).\n\
1195Thus, you can use times obtained from `current-time'\n\
1196and from `file-attributes'.\n\
773c1fd3
JB
1197\n\
1198Some operating systems cannot provide all this information to Emacs;\n\
2d88f747 1199in this case, `current-time-zone' returns a list containing nil for\n\
773c1fd3 1200the data it can't find.")
e3120ab5
JB
1201 (specified_time)
1202 Lisp_Object specified_time;
c2662aea 1203{
e3120ab5
JB
1204 time_t value;
1205 struct tm *t;
177ea5f1 1206 struct tm gmt;
c2662aea 1207
e3120ab5 1208 if (lisp_time_argument (specified_time, &value)
177ea5f1
PE
1209 && (t = gmtime (&value)) != 0
1210 && (gmt = *t, t = localtime (&value)) != 0)
e3120ab5 1211 {
177ea5f1
PE
1212 int offset = tm_diff (t, &gmt);
1213 char *s = 0;
1214 char buf[6];
e3120ab5
JB
1215#ifdef HAVE_TM_ZONE
1216 if (t->tm_zone)
5fd4de15 1217 s = (char *)t->tm_zone;
a7971c39
RS
1218#else /* not HAVE_TM_ZONE */
1219#ifdef HAVE_TZNAME
1220 if (t->tm_isdst == 0 || t->tm_isdst == 1)
1221 s = tzname[t->tm_isdst];
c2662aea 1222#endif
a7971c39 1223#endif /* not HAVE_TM_ZONE */
e3120ab5
JB
1224 if (!s)
1225 {
1226 /* No local time zone name is available; use "+-NNNN" instead. */
00fc94d0 1227 int am = (offset < 0 ? -offset : offset) / 60;
e3120ab5
JB
1228 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
1229 s = buf;
1230 }
1231 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
1232 }
1233 else
09dbcf71 1234 return Fmake_list (make_number (2), Qnil);
c2662aea
JB
1235}
1236
260e2e2a
KH
1237/* This holds the value of `environ' produced by the previous
1238 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
1239 has never been called. */
1240static char **environbuf;
1241
143cb9a9
RS
1242DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
1243 "Set the local time zone using TZ, a string specifying a time zone rule.\n\
085e9fcb
EN
1244If TZ is nil, use implementation-defined default time zone information.\n\
1245If TZ is t, use Universal Time.")
143cb9a9
RS
1246 (tz)
1247 Lisp_Object tz;
1248{
143cb9a9
RS
1249 char *tzstring;
1250
1251 if (NILP (tz))
1252 tzstring = 0;
2e34157c 1253 else if (EQ (tz, Qt))
085e9fcb 1254 tzstring = "UTC0";
143cb9a9
RS
1255 else
1256 {
1257 CHECK_STRING (tz, 0);
4d4c1514 1258 tzstring = (char *) XSTRING (tz)->data;
143cb9a9
RS
1259 }
1260
c59b5089
PE
1261 set_time_zone_rule (tzstring);
1262 if (environbuf)
1263 free (environbuf);
1264 environbuf = environ;
1265
1266 return Qnil;
1267}
1268
e0bf9faf
PE
1269#ifdef LOCALTIME_CACHE
1270
1271/* These two values are known to load tz files in buggy implementations,
1272 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
1155c453
RS
1273 Their values shouldn't matter in non-buggy implementations.
1274 We don't use string literals for these strings,
1275 since if a string in the environment is in readonly
1276 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
1277 See Sun bugs 1113095 and 1114114, ``Timezone routines
1278 improperly modify environment''. */
1279
e0bf9faf
PE
1280static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
1281static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
1282
1283#endif
1155c453 1284
c59b5089
PE
1285/* Set the local time zone rule to TZSTRING.
1286 This allocates memory into `environ', which it is the caller's
1287 responsibility to free. */
a92ae0ce 1288void
c59b5089
PE
1289set_time_zone_rule (tzstring)
1290 char *tzstring;
1291{
1292 int envptrs;
1293 char **from, **to, **newenv;
1294
aafe5147 1295 /* Make the ENVIRON vector longer with room for TZSTRING. */
143cb9a9
RS
1296 for (from = environ; *from; from++)
1297 continue;
1298 envptrs = from - environ + 2;
1299 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
1300 + (tzstring ? strlen (tzstring) + 4 : 0));
aafe5147
RS
1301
1302 /* Add TZSTRING to the end of environ, as a value for TZ. */
143cb9a9
RS
1303 if (tzstring)
1304 {
1305 char *t = (char *) (to + envptrs);
1306 strcpy (t, "TZ=");
1307 strcat (t, tzstring);
1308 *to++ = t;
1309 }
1310
aafe5147
RS
1311 /* Copy the old environ vector elements into NEWENV,
1312 but don't copy the TZ variable.
1313 So we have only one definition of TZ, which came from TZSTRING. */
143cb9a9
RS
1314 for (from = environ; *from; from++)
1315 if (strncmp (*from, "TZ=", 3) != 0)
1316 *to++ = *from;
1317 *to = 0;
1318
1319 environ = newenv;
143cb9a9 1320
aafe5147
RS
1321 /* If we do have a TZSTRING, NEWENV points to the vector slot where
1322 the TZ variable is stored. If we do not have a TZSTRING,
1323 TO points to the vector slot which has the terminating null. */
1324
143cb9a9 1325#ifdef LOCALTIME_CACHE
aafe5147
RS
1326 {
1327 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
1328 "US/Pacific" that loads a tz file, then changes to a value like
1329 "XXX0" that does not load a tz file, and then changes back to
1330 its original value, the last change is (incorrectly) ignored.
1331 Also, if TZ changes twice in succession to values that do
1332 not load a tz file, tzset can dump core (see Sun bug#1225179).
1333 The following code works around these bugs. */
1334
aafe5147
RS
1335 if (tzstring)
1336 {
1337 /* Temporarily set TZ to a value that loads a tz file
1338 and that differs from tzstring. */
1339 char *tz = *newenv;
1155c453
RS
1340 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
1341 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
aafe5147
RS
1342 tzset ();
1343 *newenv = tz;
1344 }
1345 else
1346 {
1347 /* The implied tzstring is unknown, so temporarily set TZ to
1348 two different values that each load a tz file. */
1155c453 1349 *to = set_time_zone_rule_tz1;
aafe5147
RS
1350 to[1] = 0;
1351 tzset ();
1155c453 1352 *to = set_time_zone_rule_tz2;
aafe5147
RS
1353 tzset ();
1354 *to = 0;
1355 }
1356
1357 /* Now TZ has the desired value, and tzset can be invoked safely. */
1358 }
1359
143cb9a9
RS
1360 tzset ();
1361#endif
143cb9a9 1362}
35692fe0 1363\f
fb8106e8
KH
1364/* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
1365 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
1366 type of object is Lisp_String). INHERIT is passed to
1367 INSERT_FROM_STRING_FUNC as the last argument. */
1368
d11ba98c 1369void
fb8106e8
KH
1370general_insert_function (insert_func, insert_from_string_func,
1371 inherit, nargs, args)
d11ba98c 1372 void (*insert_func) P_ ((unsigned char *, int));
1f24f4fd 1373 void (*insert_from_string_func) P_ ((Lisp_Object, int, int, int, int, int));
fb8106e8
KH
1374 int inherit, nargs;
1375 register Lisp_Object *args;
1376{
1377 register int argnum;
1378 register Lisp_Object val;
1379
1380 for (argnum = 0; argnum < nargs; argnum++)
1381 {
1382 val = args[argnum];
1383 retry:
1384 if (INTEGERP (val))
1385 {
d11ba98c 1386 unsigned char workbuf[4], *str;
fb8106e8
KH
1387 int len;
1388
1389 if (!NILP (current_buffer->enable_multibyte_characters))
1390 len = CHAR_STRING (XFASTINT (val), workbuf, str);
1391 else
13c148b8
KH
1392 {
1393 workbuf[0] = (SINGLE_BYTE_CHAR_P (XINT (val))
1394 ? XINT (val)
1395 : multibyte_char_to_unibyte (XINT (val), Qnil));
1396 str = workbuf;
1397 len = 1;
1398 }
fb8106e8
KH
1399 (*insert_func) (str, len);
1400 }
1401 else if (STRINGP (val))
1402 {
1f24f4fd
RS
1403 (*insert_from_string_func) (val, 0, 0,
1404 XSTRING (val)->size,
dc3620af 1405 STRING_BYTES (XSTRING (val)),
1f24f4fd 1406 inherit);
fb8106e8
KH
1407 }
1408 else
1409 {
1410 val = wrong_type_argument (Qchar_or_string_p, val);
1411 goto retry;
1412 }
1413 }
1414}
1415
35692fe0
JB
1416void
1417insert1 (arg)
1418 Lisp_Object arg;
1419{
1420 Finsert (1, &arg);
1421}
1422
52b14ac0
JB
1423
1424/* Callers passing one argument to Finsert need not gcpro the
1425 argument "array", since the only element of the array will
1426 not be used after calling insert or insert_from_string, so
1427 we don't care if it gets trashed. */
1428
35692fe0
JB
1429DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
1430 "Insert the arguments, either strings or characters, at point.\n\
24d6bf26 1431Point and before-insertion markers move forward to end up\n\
fb8106e8 1432 after the inserted text.\n\
24d6bf26
RS
1433Any other markers at the point of insertion remain before the text.\n\
1434\n\
1435If the current buffer is multibyte, unibyte strings are converted\n\
1436to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
13903932 1437If the current buffer is unibyte, multibyte strings are converted\n\
24d6bf26 1438to unibyte for insertion.")
35692fe0
JB
1439 (nargs, args)
1440 int nargs;
1441 register Lisp_Object *args;
1442{
fb8106e8 1443 general_insert_function (insert, insert_from_string, 0, nargs, args);
be91036a
RS
1444 return Qnil;
1445}
1446
1447DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
1448 0, MANY, 0,
1449 "Insert the arguments at point, inheriting properties from adjoining text.\n\
24d6bf26 1450Point and before-insertion markers move forward to end up\n\
fb8106e8 1451 after the inserted text.\n\
24d6bf26
RS
1452Any other markers at the point of insertion remain before the text.\n\
1453\n\
1454If the current buffer is multibyte, unibyte strings are converted\n\
1455to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
13903932 1456If the current buffer is unibyte, multibyte strings are converted\n\
24d6bf26 1457to unibyte for insertion.")
be91036a
RS
1458 (nargs, args)
1459 int nargs;
1460 register Lisp_Object *args;
1461{
fb8106e8
KH
1462 general_insert_function (insert_and_inherit, insert_from_string, 1,
1463 nargs, args);
35692fe0
JB
1464 return Qnil;
1465}
1466
1467DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
1468 "Insert strings or characters at point, relocating markers after the text.\n\
24d6bf26
RS
1469Point and markers move forward to end up after the inserted text.\n\
1470\n\
1471If the current buffer is multibyte, unibyte strings are converted\n\
1472to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
13903932 1473If the current buffer is unibyte, multibyte strings are converted\n\
24d6bf26 1474to unibyte for insertion.")
35692fe0
JB
1475 (nargs, args)
1476 int nargs;
1477 register Lisp_Object *args;
1478{
fb8106e8
KH
1479 general_insert_function (insert_before_markers,
1480 insert_from_string_before_markers, 0,
1481 nargs, args);
be91036a
RS
1482 return Qnil;
1483}
1484
a0d76c27
EN
1485DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
1486 Sinsert_and_inherit_before_markers, 0, MANY, 0,
be91036a 1487 "Insert text at point, relocating markers and inheriting properties.\n\
24d6bf26
RS
1488Point and markers move forward to end up after the inserted text.\n\
1489\n\
1490If the current buffer is multibyte, unibyte strings are converted\n\
1491to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
13903932 1492If the current buffer is unibyte, multibyte strings are converted\n\
24d6bf26 1493to unibyte for insertion.")
be91036a
RS
1494 (nargs, args)
1495 int nargs;
1496 register Lisp_Object *args;
1497{
fb8106e8
KH
1498 general_insert_function (insert_before_markers_and_inherit,
1499 insert_from_string_before_markers, 1,
1500 nargs, args);
35692fe0
JB
1501 return Qnil;
1502}
1503\f
e2eeabbb 1504DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
2591ec64 1505 "Insert COUNT (second arg) copies of CHARACTER (first arg).\n\
e2eeabbb 1506Both arguments are required.\n\
ba88b322 1507Point, and before-insertion markers, are relocated as in the function `insert'.\n\
e2eeabbb
RS
1508The optional third arg INHERIT, if non-nil, says to inherit text properties\n\
1509from adjoining text, if those properties are sticky.")
2591ec64
EN
1510 (character, count, inherit)
1511 Lisp_Object character, count, inherit;
35692fe0
JB
1512{
1513 register unsigned char *string;
1514 register int strlen;
1515 register int i, n;
fb8106e8
KH
1516 int len;
1517 unsigned char workbuf[4], *str;
35692fe0 1518
2591ec64 1519 CHECK_NUMBER (character, 0);
35692fe0
JB
1520 CHECK_NUMBER (count, 1);
1521
fb8106e8
KH
1522 if (!NILP (current_buffer->enable_multibyte_characters))
1523 len = CHAR_STRING (XFASTINT (character), workbuf, str);
1524 else
1525 workbuf[0] = XFASTINT (character), str = workbuf, len = 1;
1526 n = XINT (count) * len;
35692fe0
JB
1527 if (n <= 0)
1528 return Qnil;
fb8106e8 1529 strlen = min (n, 256 * len);
35692fe0
JB
1530 string = (unsigned char *) alloca (strlen);
1531 for (i = 0; i < strlen; i++)
fb8106e8 1532 string[i] = str[i % len];
35692fe0
JB
1533 while (n >= strlen)
1534 {
54e42e2d 1535 QUIT;
e2eeabbb
RS
1536 if (!NILP (inherit))
1537 insert_and_inherit (string, strlen);
1538 else
1539 insert (string, strlen);
35692fe0
JB
1540 n -= strlen;
1541 }
1542 if (n > 0)
83951f1e
KH
1543 {
1544 if (!NILP (inherit))
1545 insert_and_inherit (string, n);
1546 else
1547 insert (string, n);
1548 }
35692fe0
JB
1549 return Qnil;
1550}
1551
1552\f
ffd56f97
JB
1553/* Making strings from buffer contents. */
1554
1555/* Return a Lisp_String containing the text of the current buffer from
74d6d8c5 1556 START to END. If text properties are in use and the current buffer
eb8c3be9 1557 has properties in the range specified, the resulting string will also
260e2e2a 1558 have them, if PROPS is nonzero.
ffd56f97
JB
1559
1560 We don't want to use plain old make_string here, because it calls
1561 make_uninit_string, which can cause the buffer arena to be
1562 compacted. make_string has no way of knowing that the data has
1563 been moved, and thus copies the wrong data into the string. This
1564 doesn't effect most of the other users of make_string, so it should
1565 be left as is. But we should use this function when conjuring
1566 buffer substrings. */
74d6d8c5 1567
ffd56f97 1568Lisp_Object
260e2e2a 1569make_buffer_string (start, end, props)
ffd56f97 1570 int start, end;
260e2e2a 1571 int props;
ffd56f97 1572{
ec1c14f6
RS
1573 int start_byte = CHAR_TO_BYTE (start);
1574 int end_byte = CHAR_TO_BYTE (end);
ffd56f97 1575
88441c8e
RS
1576 return make_buffer_string_both (start, start_byte, end, end_byte, props);
1577}
1578
1579/* Return a Lisp_String containing the text of the current buffer from
1580 START / START_BYTE to END / END_BYTE.
1581
1582 If text properties are in use and the current buffer
1583 has properties in the range specified, the resulting string will also
1584 have them, if PROPS is nonzero.
1585
1586 We don't want to use plain old make_string here, because it calls
1587 make_uninit_string, which can cause the buffer arena to be
1588 compacted. make_string has no way of knowing that the data has
1589 been moved, and thus copies the wrong data into the string. This
1590 doesn't effect most of the other users of make_string, so it should
1591 be left as is. But we should use this function when conjuring
1592 buffer substrings. */
1593
1594Lisp_Object
1595make_buffer_string_both (start, start_byte, end, end_byte, props)
1596 int start, start_byte, end, end_byte;
1597 int props;
1598{
1599 Lisp_Object result, tem, tem1;
1600
ffd56f97
JB
1601 if (start < GPT && GPT < end)
1602 move_gap (start);
1603
5f75e666
RS
1604 if (! NILP (current_buffer->enable_multibyte_characters))
1605 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
1606 else
1607 result = make_uninit_string (end - start);
ec1c14f6
RS
1608 bcopy (BYTE_POS_ADDR (start_byte), XSTRING (result)->data,
1609 end_byte - start_byte);
ffd56f97 1610
260e2e2a 1611 /* If desired, update and copy the text properties. */
60b96ee7 1612#ifdef USE_TEXT_PROPERTIES
260e2e2a
KH
1613 if (props)
1614 {
1615 update_buffer_properties (start, end);
1616
1617 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
1618 tem1 = Ftext_properties_at (make_number (start), Qnil);
1619
1620 if (XINT (tem) != end || !NILP (tem1))
ec1c14f6
RS
1621 copy_intervals_to_string (result, current_buffer, start,
1622 end - start);
260e2e2a 1623 }
60b96ee7 1624#endif
74d6d8c5 1625
ffd56f97
JB
1626 return result;
1627}
35692fe0 1628
260e2e2a
KH
1629/* Call Vbuffer_access_fontify_functions for the range START ... END
1630 in the current buffer, if necessary. */
1631
1632static void
1633update_buffer_properties (start, end)
1634 int start, end;
1635{
1636#ifdef USE_TEXT_PROPERTIES
1637 /* If this buffer has some access functions,
1638 call them, specifying the range of the buffer being accessed. */
1639 if (!NILP (Vbuffer_access_fontify_functions))
1640 {
1641 Lisp_Object args[3];
1642 Lisp_Object tem;
1643
1644 args[0] = Qbuffer_access_fontify_functions;
1645 XSETINT (args[1], start);
1646 XSETINT (args[2], end);
1647
1648 /* But don't call them if we can tell that the work
1649 has already been done. */
1650 if (!NILP (Vbuffer_access_fontified_property))
1651 {
1652 tem = Ftext_property_any (args[1], args[2],
1653 Vbuffer_access_fontified_property,
1654 Qnil, Qnil);
1655 if (! NILP (tem))
ced1d19a 1656 Frun_hook_with_args (3, args);
260e2e2a
KH
1657 }
1658 else
ced1d19a 1659 Frun_hook_with_args (3, args);
260e2e2a
KH
1660 }
1661#endif
1662}
1663
35692fe0
JB
1664DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
1665 "Return the contents of part of the current buffer as a string.\n\
1666The two arguments START and END are character positions;\n\
24d6bf26
RS
1667they can be in either order.\n\
1668The string returned is multibyte if the buffer is multibyte.")
2591ec64
EN
1669 (start, end)
1670 Lisp_Object start, end;
35692fe0 1671{
2591ec64 1672 register int b, e;
35692fe0 1673
2591ec64
EN
1674 validate_region (&start, &end);
1675 b = XINT (start);
1676 e = XINT (end);
35692fe0 1677
2591ec64 1678 return make_buffer_string (b, e, 1);
260e2e2a
KH
1679}
1680
1681DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
1682 Sbuffer_substring_no_properties, 2, 2, 0,
1683 "Return the characters of part of the buffer, without the text properties.\n\
1684The two arguments START and END are character positions;\n\
1685they can be in either order.")
2591ec64
EN
1686 (start, end)
1687 Lisp_Object start, end;
260e2e2a 1688{
2591ec64 1689 register int b, e;
260e2e2a 1690
2591ec64
EN
1691 validate_region (&start, &end);
1692 b = XINT (start);
1693 e = XINT (end);
260e2e2a 1694
2591ec64 1695 return make_buffer_string (b, e, 0);
35692fe0
JB
1696}
1697
1698DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
af7bd86c
KH
1699 "Return the contents of the current buffer as a string.\n\
1700If narrowing is in effect, this function returns only the visible part\n\
1701of the buffer.")
35692fe0
JB
1702 ()
1703{
260e2e2a 1704 return make_buffer_string (BEGV, ZV, 1);
35692fe0
JB
1705}
1706
1707DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
1708 1, 3, 0,
83ea6fc2 1709 "Insert before point a substring of the contents of buffer BUFFER.\n\
35692fe0
JB
1710BUFFER may be a buffer or a buffer name.\n\
1711Arguments START and END are character numbers specifying the substring.\n\
1712They default to the beginning and the end of BUFFER.")
2591ec64
EN
1713 (buf, start, end)
1714 Lisp_Object buf, start, end;
35692fe0 1715{
2591ec64 1716 register int b, e, temp;
260e2e2a 1717 register struct buffer *bp, *obuf;
3fff2dfa 1718 Lisp_Object buffer;
35692fe0 1719
3fff2dfa
RS
1720 buffer = Fget_buffer (buf);
1721 if (NILP (buffer))
1722 nsberror (buf);
1723 bp = XBUFFER (buffer);
93b62e82
KH
1724 if (NILP (bp->name))
1725 error ("Selecting deleted buffer");
35692fe0 1726
2591ec64
EN
1727 if (NILP (start))
1728 b = BUF_BEGV (bp);
35692fe0
JB
1729 else
1730 {
2591ec64
EN
1731 CHECK_NUMBER_COERCE_MARKER (start, 0);
1732 b = XINT (start);
35692fe0 1733 }
2591ec64
EN
1734 if (NILP (end))
1735 e = BUF_ZV (bp);
35692fe0
JB
1736 else
1737 {
2591ec64
EN
1738 CHECK_NUMBER_COERCE_MARKER (end, 1);
1739 e = XINT (end);
35692fe0
JB
1740 }
1741
2591ec64
EN
1742 if (b > e)
1743 temp = b, b = e, e = temp;
35692fe0 1744
2591ec64
EN
1745 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
1746 args_out_of_range (start, end);
35692fe0 1747
260e2e2a
KH
1748 obuf = current_buffer;
1749 set_buffer_internal_1 (bp);
2591ec64 1750 update_buffer_properties (b, e);
260e2e2a
KH
1751 set_buffer_internal_1 (obuf);
1752
2591ec64 1753 insert_from_buffer (bp, b, e - b, 0);
35692fe0
JB
1754 return Qnil;
1755}
e9cf2084
RS
1756
1757DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
1758 6, 6, 0,
1759 "Compare two substrings of two buffers; return result as number.\n\
1760the value is -N if first string is less after N-1 chars,\n\
1761+N if first string is greater after N-1 chars, or 0 if strings match.\n\
1762Each substring is represented as three arguments: BUFFER, START and END.\n\
1763That makes six args in all, three for each substring.\n\n\
1764The value of `case-fold-search' in the current buffer\n\
1765determines whether case is significant or ignored.")
1766 (buffer1, start1, end1, buffer2, start2, end2)
1767 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
1768{
07422a12 1769 register int begp1, endp1, begp2, endp2, temp;
e9cf2084 1770 register struct buffer *bp1, *bp2;
2a8b0ff0 1771 register Lisp_Object *trt
e9cf2084 1772 = (!NILP (current_buffer->case_fold_search)
2a8b0ff0 1773 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents : 0);
ec1c14f6 1774 int chars = 0;
07422a12 1775 int i1, i2, i1_byte, i2_byte;
e9cf2084
RS
1776
1777 /* Find the first buffer and its substring. */
1778
1779 if (NILP (buffer1))
1780 bp1 = current_buffer;
1781 else
1782 {
3fff2dfa
RS
1783 Lisp_Object buf1;
1784 buf1 = Fget_buffer (buffer1);
1785 if (NILP (buf1))
1786 nsberror (buffer1);
1787 bp1 = XBUFFER (buf1);
93b62e82
KH
1788 if (NILP (bp1->name))
1789 error ("Selecting deleted buffer");
e9cf2084
RS
1790 }
1791
1792 if (NILP (start1))
1793 begp1 = BUF_BEGV (bp1);
1794 else
1795 {
1796 CHECK_NUMBER_COERCE_MARKER (start1, 1);
1797 begp1 = XINT (start1);
1798 }
1799 if (NILP (end1))
1800 endp1 = BUF_ZV (bp1);
1801 else
1802 {
1803 CHECK_NUMBER_COERCE_MARKER (end1, 2);
1804 endp1 = XINT (end1);
1805 }
1806
1807 if (begp1 > endp1)
1808 temp = begp1, begp1 = endp1, endp1 = temp;
1809
1810 if (!(BUF_BEGV (bp1) <= begp1
1811 && begp1 <= endp1
1812 && endp1 <= BUF_ZV (bp1)))
1813 args_out_of_range (start1, end1);
1814
1815 /* Likewise for second substring. */
1816
1817 if (NILP (buffer2))
1818 bp2 = current_buffer;
1819 else
1820 {
3fff2dfa
RS
1821 Lisp_Object buf2;
1822 buf2 = Fget_buffer (buffer2);
1823 if (NILP (buf2))
1824 nsberror (buffer2);
3b1fdd85 1825 bp2 = XBUFFER (buf2);
93b62e82
KH
1826 if (NILP (bp2->name))
1827 error ("Selecting deleted buffer");
e9cf2084
RS
1828 }
1829
1830 if (NILP (start2))
1831 begp2 = BUF_BEGV (bp2);
1832 else
1833 {
1834 CHECK_NUMBER_COERCE_MARKER (start2, 4);
1835 begp2 = XINT (start2);
1836 }
1837 if (NILP (end2))
1838 endp2 = BUF_ZV (bp2);
1839 else
1840 {
1841 CHECK_NUMBER_COERCE_MARKER (end2, 5);
1842 endp2 = XINT (end2);
1843 }
1844
1845 if (begp2 > endp2)
1846 temp = begp2, begp2 = endp2, endp2 = temp;
1847
1848 if (!(BUF_BEGV (bp2) <= begp2
1849 && begp2 <= endp2
1850 && endp2 <= BUF_ZV (bp2)))
1851 args_out_of_range (start2, end2);
1852
07422a12
RS
1853 i1 = begp1;
1854 i2 = begp2;
1855 i1_byte = buf_charpos_to_bytepos (bp1, i1);
1856 i2_byte = buf_charpos_to_bytepos (bp2, i2);
e9cf2084 1857
07422a12 1858 while (i1 < endp1 && i2 < endp2)
e9cf2084 1859 {
07422a12
RS
1860 /* When we find a mismatch, we must compare the
1861 characters, not just the bytes. */
1862 int c1, c2;
ec1c14f6 1863
07422a12
RS
1864 if (! NILP (bp1->enable_multibyte_characters))
1865 {
1866 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
1867 BUF_INC_POS (bp1, i1_byte);
1868 i1++;
1869 }
1870 else
1871 {
1872 c1 = BUF_FETCH_BYTE (bp1, i1);
1873 c1 = unibyte_char_to_multibyte (c1);
1874 i1++;
1875 }
1876
1877 if (! NILP (bp2->enable_multibyte_characters))
1878 {
1879 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
1880 BUF_INC_POS (bp2, i2_byte);
1881 i2++;
1882 }
1883 else
1884 {
1885 c2 = BUF_FETCH_BYTE (bp2, i2);
1886 c2 = unibyte_char_to_multibyte (c2);
1887 i2++;
1888 }
ec1c14f6 1889
e9cf2084
RS
1890 if (trt)
1891 {
1b10fb77
RS
1892 c1 = XINT (trt[c1]);
1893 c2 = XINT (trt[c2]);
e9cf2084
RS
1894 }
1895 if (c1 < c2)
ec1c14f6 1896 return make_number (- 1 - chars);
e9cf2084 1897 if (c1 > c2)
ec1c14f6 1898 return make_number (chars + 1);
07422a12
RS
1899
1900 chars++;
e9cf2084
RS
1901 }
1902
1903 /* The strings match as far as they go.
1904 If one is shorter, that one is less. */
07422a12 1905 if (chars < endp1 - begp1)
ec1c14f6 1906 return make_number (chars + 1);
07422a12 1907 else if (chars < endp2 - begp2)
ec1c14f6 1908 return make_number (- chars - 1);
e9cf2084
RS
1909
1910 /* Same length too => they are equal. */
1911 return make_number (0);
1912}
35692fe0 1913\f
d5a539cd
RS
1914static Lisp_Object
1915subst_char_in_region_unwind (arg)
1916 Lisp_Object arg;
1917{
1918 return current_buffer->undo_list = arg;
1919}
1920
c8e76b47
RS
1921static Lisp_Object
1922subst_char_in_region_unwind_1 (arg)
1923 Lisp_Object arg;
1924{
1925 return current_buffer->filename = arg;
1926}
1927
35692fe0
JB
1928DEFUN ("subst-char-in-region", Fsubst_char_in_region,
1929 Ssubst_char_in_region, 4, 5, 0,
1930 "From START to END, replace FROMCHAR with TOCHAR each time it occurs.\n\
1931If optional arg NOUNDO is non-nil, don't record this change for undo\n\
fb8106e8
KH
1932and don't mark the buffer as really changed.\n\
1933Both characters must have the same length of multi-byte form.")
35692fe0
JB
1934 (start, end, fromchar, tochar, noundo)
1935 Lisp_Object start, end, fromchar, tochar, noundo;
1936{
84246b95 1937 register int pos, pos_byte, stop, i, len, end_byte;
60b96ee7 1938 int changed = 0;
fb8106e8 1939 unsigned char fromwork[4], *fromstr, towork[4], *tostr, *p;
d5a539cd 1940 int count = specpdl_ptr - specpdl;
35692fe0
JB
1941
1942 validate_region (&start, &end);
1943 CHECK_NUMBER (fromchar, 2);
1944 CHECK_NUMBER (tochar, 3);
1945
fb8106e8
KH
1946 if (! NILP (current_buffer->enable_multibyte_characters))
1947 {
1948 len = CHAR_STRING (XFASTINT (fromchar), fromwork, fromstr);
1949 if (CHAR_STRING (XFASTINT (tochar), towork, tostr) != len)
1950 error ("Characters in subst-char-in-region have different byte-lengths");
1951 }
1952 else
1953 {
1954 len = 1;
1955 fromwork[0] = XFASTINT (fromchar), fromstr = fromwork;
1956 towork[0] = XFASTINT (tochar), tostr = towork;
1957 }
1958
84246b95
KH
1959 pos = XINT (start);
1960 pos_byte = CHAR_TO_BYTE (pos);
ec1c14f6
RS
1961 stop = CHAR_TO_BYTE (XINT (end));
1962 end_byte = stop;
35692fe0 1963
d5a539cd
RS
1964 /* If we don't want undo, turn off putting stuff on the list.
1965 That's faster than getting rid of things,
c8e76b47
RS
1966 and it prevents even the entry for a first change.
1967 Also inhibit locking the file. */
d5a539cd
RS
1968 if (!NILP (noundo))
1969 {
1970 record_unwind_protect (subst_char_in_region_unwind,
1971 current_buffer->undo_list);
1972 current_buffer->undo_list = Qt;
c8e76b47
RS
1973 /* Don't do file-locking. */
1974 record_unwind_protect (subst_char_in_region_unwind_1,
1975 current_buffer->filename);
1976 current_buffer->filename = Qnil;
d5a539cd
RS
1977 }
1978
84246b95 1979 if (pos_byte < GPT_BYTE)
ec1c14f6 1980 stop = min (stop, GPT_BYTE);
fb8106e8 1981 while (1)
35692fe0 1982 {
84246b95 1983 if (pos_byte >= stop)
fb8106e8 1984 {
84246b95 1985 if (pos_byte >= end_byte) break;
ec1c14f6 1986 stop = end_byte;
fb8106e8 1987 }
84246b95 1988 p = BYTE_POS_ADDR (pos_byte);
fb8106e8
KH
1989 if (p[0] == fromstr[0]
1990 && (len == 1
1991 || (p[1] == fromstr[1]
1992 && (len == 2 || (p[2] == fromstr[2]
1993 && (len == 3 || p[3] == fromstr[3]))))))
35692fe0 1994 {
60b96ee7
RS
1995 if (! changed)
1996 {
fb8106e8 1997 modify_region (current_buffer, XINT (start), XINT (end));
7653d030
RS
1998
1999 if (! NILP (noundo))
2000 {
1e158d25
RS
2001 if (MODIFF - 1 == SAVE_MODIFF)
2002 SAVE_MODIFF++;
7653d030
RS
2003 if (MODIFF - 1 == current_buffer->auto_save_modified)
2004 current_buffer->auto_save_modified++;
2005 }
2006
fb8106e8 2007 changed = 1;
60b96ee7
RS
2008 }
2009
0c1e3b85
RS
2010 /* Take care of the case where the new character
2011 combines with neighboring bytes. */
2012 if (len == 1
2013 && ((! CHAR_HEAD_P (tostr[0])
2014 && pos_byte > BEGV_BYTE
2015 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1)))
2016 ||
2017 (! ASCII_BYTE_P (tostr[0])
2018 && pos_byte + 1 < ZV_BYTE
2019 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte + 1)))))
2020 {
2021 Lisp_Object tem, string;
2022
2023 struct gcpro gcpro1;
2024
2025 tem = current_buffer->undo_list;
2026 GCPRO1 (tem);
2027
2028 /* Make a multibyte string containing this
2029 single-byte character. */
2030 string = Fmake_string (make_number (1),
2031 make_number (tochar));
2032 SET_STRING_BYTES (XSTRING (string), 1);
2033 /* replace_range is less efficient, because it moves the gap,
2034 but it handles combining correctly. */
2035 replace_range (pos, pos + 1, string,
9869520f 2036 0, 0, 1);
0c1e3b85
RS
2037 if (! NILP (noundo))
2038 current_buffer->undo_list = tem;
2039
2040 UNGCPRO;
2041 }
2042 else
2043 {
2044 if (NILP (noundo))
2045 record_change (pos, 1);
2046 for (i = 0; i < len; i++) *p++ = tostr[i];
2047 }
35692fe0 2048 }
84246b95 2049 INC_BOTH (pos, pos_byte);
35692fe0
JB
2050 }
2051
60b96ee7
RS
2052 if (changed)
2053 signal_after_change (XINT (start),
84246b95 2054 XINT (end) - XINT (start), XINT (end) - XINT (start));
60b96ee7 2055
d5a539cd 2056 unbind_to (count, Qnil);
35692fe0
JB
2057 return Qnil;
2058}
2059
2060DEFUN ("translate-region", Ftranslate_region, Stranslate_region, 3, 3, 0,
2061 "From START to END, translate characters according to TABLE.\n\
2062TABLE is a string; the Nth character in it is the mapping\n\
1f24f4fd
RS
2063for the character with code N.\n\
2064This function does not alter multibyte characters.\n\
2065It returns the number of characters changed.")
35692fe0
JB
2066 (start, end, table)
2067 Lisp_Object start;
2068 Lisp_Object end;
2069 register Lisp_Object table;
2070{
ec1c14f6 2071 register int pos_byte, stop; /* Limits of the region. */
35692fe0 2072 register unsigned char *tt; /* Trans table. */
35692fe0
JB
2073 register int nc; /* New character. */
2074 int cnt; /* Number of changes made. */
35692fe0 2075 int size; /* Size of translate table. */
1f24f4fd 2076 int pos;
35692fe0
JB
2077
2078 validate_region (&start, &end);
2079 CHECK_STRING (table, 2);
2080
dc3620af 2081 size = STRING_BYTES (XSTRING (table));
35692fe0
JB
2082 tt = XSTRING (table)->data;
2083
ec1c14f6
RS
2084 pos_byte = CHAR_TO_BYTE (XINT (start));
2085 stop = CHAR_TO_BYTE (XINT (end));
2086 modify_region (current_buffer, XINT (start), XINT (end));
1f24f4fd 2087 pos = XINT (start);
35692fe0
JB
2088
2089 cnt = 0;
1f24f4fd 2090 for (; pos_byte < stop; )
35692fe0 2091 {
ec1c14f6 2092 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
1f24f4fd
RS
2093 int len;
2094 int oc;
ec1c14f6 2095
1f24f4fd
RS
2096 oc = STRING_CHAR_AND_LENGTH (p, stop - pos_byte, len);
2097 if (oc < size && len == 1)
35692fe0
JB
2098 {
2099 nc = tt[oc];
2100 if (nc != oc)
2101 {
0c1e3b85
RS
2102 /* Take care of the case where the new character
2103 combines with neighboring bytes. */
2104 if ((! CHAR_HEAD_P (nc)
2105 && pos_byte > BEGV_BYTE
2106 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1)))
2107 ||
2108 (! ASCII_BYTE_P (nc)
2109 && pos_byte + 1 < ZV_BYTE
2110 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte + 1))))
2111 {
2112 Lisp_Object string;
2113
2114 string = Fmake_string (make_number (1),
2115 make_number (nc));
2116 SET_STRING_BYTES (XSTRING (string), 1);
2117
2118 /* This is less efficient, because it moves the gap,
2119 but it handles combining correctly. */
2120 replace_range (pos, pos + 1, string,
2121 1, 0, 0);
2122 }
2123 else
2124 {
2125 record_change (pos, 1);
2126 *p = nc;
2127 signal_after_change (pos, 1, 1);
2128 }
35692fe0
JB
2129 ++cnt;
2130 }
2131 }
1f24f4fd
RS
2132 pos_byte += len;
2133 pos++;
35692fe0
JB
2134 }
2135
ec1c14f6 2136 return make_number (cnt);
35692fe0
JB
2137}
2138
2139DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
2140 "Delete the text between point and mark.\n\
2141When called from a program, expects two arguments,\n\
2142positions (integers or markers) specifying the stretch to be deleted.")
2591ec64
EN
2143 (start, end)
2144 Lisp_Object start, end;
35692fe0 2145{
2591ec64
EN
2146 validate_region (&start, &end);
2147 del_range (XINT (start), XINT (end));
35692fe0
JB
2148 return Qnil;
2149}
2150\f
2151DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
2152 "Remove restrictions (narrowing) from current buffer.\n\
2153This allows the buffer's full text to be seen and edited.")
2154 ()
2155{
2cad2e34
RS
2156 if (BEG != BEGV || Z != ZV)
2157 current_buffer->clip_changed = 1;
35692fe0 2158 BEGV = BEG;
ec1c14f6
RS
2159 BEGV_BYTE = BEG_BYTE;
2160 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
52b14ac0
JB
2161 /* Changing the buffer bounds invalidates any recorded current column. */
2162 invalidate_current_column ();
35692fe0
JB
2163 return Qnil;
2164}
2165
2166DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
2167 "Restrict editing in this buffer to the current region.\n\
2168The rest of the text becomes temporarily invisible and untouchable\n\
2169but is not deleted; if you save the buffer in a file, the invisible\n\
2170text is included in the file. \\[widen] makes all visible again.\n\
2171See also `save-restriction'.\n\
2172\n\
2173When calling from a program, pass two arguments; positions (integers\n\
2174or markers) bounding the text that should remain visible.")
2591ec64
EN
2175 (start, end)
2176 register Lisp_Object start, end;
35692fe0 2177{
2591ec64
EN
2178 CHECK_NUMBER_COERCE_MARKER (start, 0);
2179 CHECK_NUMBER_COERCE_MARKER (end, 1);
35692fe0 2180
2591ec64 2181 if (XINT (start) > XINT (end))
35692fe0 2182 {
b5a6948e 2183 Lisp_Object tem;
2591ec64 2184 tem = start; start = end; end = tem;
35692fe0
JB
2185 }
2186
2591ec64
EN
2187 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
2188 args_out_of_range (start, end);
35692fe0 2189
2cad2e34
RS
2190 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
2191 current_buffer->clip_changed = 1;
2192
ec1c14f6 2193 SET_BUF_BEGV (current_buffer, XFASTINT (start));
2591ec64 2194 SET_BUF_ZV (current_buffer, XFASTINT (end));
6ec8bbd2 2195 if (PT < XFASTINT (start))
2591ec64 2196 SET_PT (XFASTINT (start));
6ec8bbd2 2197 if (PT > XFASTINT (end))
2591ec64 2198 SET_PT (XFASTINT (end));
52b14ac0
JB
2199 /* Changing the buffer bounds invalidates any recorded current column. */
2200 invalidate_current_column ();
35692fe0
JB
2201 return Qnil;
2202}
2203
2204Lisp_Object
2205save_restriction_save ()
2206{
2207 register Lisp_Object bottom, top;
2208 /* Note: I tried using markers here, but it does not win
2209 because insertion at the end of the saved region
2210 does not advance mh and is considered "outside" the saved region. */
55561c63
KH
2211 XSETFASTINT (bottom, BEGV - BEG);
2212 XSETFASTINT (top, Z - ZV);
35692fe0
JB
2213
2214 return Fcons (Fcurrent_buffer (), Fcons (bottom, top));
2215}
2216
2217Lisp_Object
2218save_restriction_restore (data)
2219 Lisp_Object data;
2220{
2221 register struct buffer *buf;
2222 register int newhead, newtail;
2223 register Lisp_Object tem;
2cad2e34 2224 int obegv, ozv;
35692fe0
JB
2225
2226 buf = XBUFFER (XCONS (data)->car);
2227
2228 data = XCONS (data)->cdr;
2229
2230 tem = XCONS (data)->car;
2231 newhead = XINT (tem);
2232 tem = XCONS (data)->cdr;
2233 newtail = XINT (tem);
2234 if (newhead + newtail > BUF_Z (buf) - BUF_BEG (buf))
2235 {
2236 newhead = 0;
2237 newtail = 0;
2238 }
2cad2e34
RS
2239
2240 obegv = BUF_BEGV (buf);
2241 ozv = BUF_ZV (buf);
2242
ec1c14f6 2243 SET_BUF_BEGV (buf, BUF_BEG (buf) + newhead);
35692fe0 2244 SET_BUF_ZV (buf, BUF_Z (buf) - newtail);
2cad2e34
RS
2245
2246 if (obegv != BUF_BEGV (buf) || ozv != BUF_ZV (buf))
2247 current_buffer->clip_changed = 1;
35692fe0
JB
2248
2249 /* If point is outside the new visible range, move it inside. */
ec1c14f6
RS
2250 SET_BUF_PT_BOTH (buf,
2251 clip_to_bounds (BUF_BEGV (buf), BUF_PT (buf), BUF_ZV (buf)),
2252 clip_to_bounds (BUF_BEGV_BYTE (buf), BUF_PT_BYTE (buf),
2253 BUF_ZV_BYTE (buf)));
35692fe0
JB
2254
2255 return Qnil;
2256}
2257
2258DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
2259 "Execute BODY, saving and restoring current buffer's restrictions.\n\
2260The buffer's restrictions make parts of the beginning and end invisible.\n\
2261\(They are set up with `narrow-to-region' and eliminated with `widen'.)\n\
2262This special form, `save-restriction', saves the current buffer's restrictions\n\
2263when it is entered, and restores them when it is exited.\n\
2264So any `narrow-to-region' within BODY lasts only until the end of the form.\n\
2265The old restrictions settings are restored\n\
2266even in case of abnormal exit (throw or error).\n\
2267\n\
2268The value returned is the value of the last form in BODY.\n\
2269\n\
2270`save-restriction' can get confused if, within the BODY, you widen\n\
2271and then make changes outside the area within the saved restrictions.\n\
5b2a5316 2272See Info node `(elisp)Narrowing' for details and an appropriate technique.\n\
35692fe0
JB
2273\n\
2274Note: if you are using both `save-excursion' and `save-restriction',\n\
2275use `save-excursion' outermost:\n\
2276 (save-excursion (save-restriction ...))")
2277 (body)
2278 Lisp_Object body;
2279{
2280 register Lisp_Object val;
2281 int count = specpdl_ptr - specpdl;
2282
2283 record_unwind_protect (save_restriction_restore, save_restriction_save ());
2284 val = Fprogn (body);
2285 return unbind_to (count, val);
2286}
2287\f
671fbc4d
KH
2288/* Buffer for the most recent text displayed by Fmessage. */
2289static char *message_text;
2290
2291/* Allocated length of that buffer. */
2292static int message_length;
2293
35692fe0
JB
2294DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
2295 "Print a one-line message at the bottom of the screen.\n\
98fc5c3c
RS
2296The first argument is a format control string, and the rest are data\n\
2297to be formatted under control of the string. See `format' for details.\n\
2298\n\
ccdac5be
JB
2299If the first argument is nil, clear any existing message; let the\n\
2300minibuffer contents show.")
35692fe0
JB
2301 (nargs, args)
2302 int nargs;
2303 Lisp_Object *args;
2304{
ccdac5be 2305 if (NILP (args[0]))
f0250249
JB
2306 {
2307 message (0);
2308 return Qnil;
2309 }
ccdac5be
JB
2310 else
2311 {
2312 register Lisp_Object val;
2313 val = Fformat (nargs, args);
671fbc4d
KH
2314 /* Copy the data so that it won't move when we GC. */
2315 if (! message_text)
2316 {
2317 message_text = (char *)xmalloc (80);
2318 message_length = 80;
2319 }
dc3620af 2320 if (STRING_BYTES (XSTRING (val)) > message_length)
671fbc4d 2321 {
dc3620af 2322 message_length = STRING_BYTES (XSTRING (val));
671fbc4d
KH
2323 message_text = (char *)xrealloc (message_text, message_length);
2324 }
dc3620af
RS
2325 bcopy (XSTRING (val)->data, message_text, STRING_BYTES (XSTRING (val)));
2326 message2 (message_text, STRING_BYTES (XSTRING (val)),
1f24f4fd 2327 STRING_MULTIBYTE (val));
ccdac5be
JB
2328 return val;
2329 }
35692fe0
JB
2330}
2331
cacc3e2c
RS
2332DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
2333 "Display a message, in a dialog box if possible.\n\
2334If a dialog box is not available, use the echo area.\n\
f8250f01
RS
2335The first argument is a format control string, and the rest are data\n\
2336to be formatted under control of the string. See `format' for details.\n\
2337\n\
cacc3e2c
RS
2338If the first argument is nil, clear any existing message; let the\n\
2339minibuffer contents show.")
2340 (nargs, args)
2341 int nargs;
2342 Lisp_Object *args;
2343{
2344 if (NILP (args[0]))
2345 {
2346 message (0);
2347 return Qnil;
2348 }
2349 else
2350 {
2351 register Lisp_Object val;
2352 val = Fformat (nargs, args);
f8250f01 2353#ifdef HAVE_MENUS
cacc3e2c
RS
2354 {
2355 Lisp_Object pane, menu, obj;
2356 struct gcpro gcpro1;
2357 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
2358 GCPRO1 (pane);
2359 menu = Fcons (val, pane);
2360 obj = Fx_popup_dialog (Qt, menu);
2361 UNGCPRO;
2362 return val;
2363 }
f8250f01 2364#else /* not HAVE_MENUS */
cacc3e2c
RS
2365 /* Copy the data so that it won't move when we GC. */
2366 if (! message_text)
2367 {
2368 message_text = (char *)xmalloc (80);
2369 message_length = 80;
2370 }
dc3620af 2371 if (STRING_BYTES (XSTRING (val)) > message_length)
cacc3e2c 2372 {
dc3620af 2373 message_length = STRING_BYTES (XSTRING (val));
cacc3e2c
RS
2374 message_text = (char *)xrealloc (message_text, message_length);
2375 }
dc3620af 2376 bcopy (XSTRING (val)->data, message_text, STRING_BYTES (XSTRING (val)));
d13a8480
RS
2377 message2 (message_text, STRING_BYTES (XSTRING (val)),
2378 STRING_MULTIBYTE (val));
cacc3e2c 2379 return val;
f8250f01 2380#endif /* not HAVE_MENUS */
cacc3e2c
RS
2381 }
2382}
f8250f01 2383#ifdef HAVE_MENUS
cacc3e2c
RS
2384extern Lisp_Object last_nonmenu_event;
2385#endif
f8250f01 2386
cacc3e2c
RS
2387DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
2388 "Display a message in a dialog box or in the echo area.\n\
2389If this command was invoked with the mouse, use a dialog box.\n\
2390Otherwise, use the echo area.\n\
f8250f01
RS
2391The first argument is a format control string, and the rest are data\n\
2392to be formatted under control of the string. See `format' for details.\n\
cacc3e2c 2393\n\
cacc3e2c
RS
2394If the first argument is nil, clear any existing message; let the\n\
2395minibuffer contents show.")
2396 (nargs, args)
2397 int nargs;
2398 Lisp_Object *args;
2399{
f8250f01 2400#ifdef HAVE_MENUS
cacc3e2c 2401 if (NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
0a56ee6b 2402 return Fmessage_box (nargs, args);
cacc3e2c
RS
2403#endif
2404 return Fmessage (nargs, args);
2405}
2406
b14dda8a
RS
2407DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
2408 "Return the string currently displayed in the echo area, or nil if none.")
2409 ()
2410{
2411 return (echo_area_glyphs
2412 ? make_string (echo_area_glyphs, echo_area_glyphs_length)
2413 : Qnil);
2414}
2415
1f24f4fd
RS
2416/* Number of bytes that STRING will occupy when put into the result.
2417 MULTIBYTE is nonzero if the result should be multibyte. */
2418
2419#define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
2420 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
8d6179dc 2421 ? count_size_as_multibyte (XSTRING (STRING)->data, \
dc3620af
RS
2422 STRING_BYTES (XSTRING (STRING))) \
2423 : STRING_BYTES (XSTRING (STRING)))
1f24f4fd 2424
35692fe0
JB
2425DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
2426 "Format a string out of a control-string and arguments.\n\
2427The first argument is a control string.\n\
2428The other arguments are substituted into it to make the result, a string.\n\
2429It may contain %-sequences meaning to substitute the next argument.\n\
2430%s means print a string argument. Actually, prints any object, with `princ'.\n\
2431%d means print as number in decimal (%o octal, %x hex).\n\
9db1775a
RS
2432%e means print a number in exponential notation.\n\
2433%f means print a number in decimal-point notation.\n\
2434%g means print a number in exponential notation\n\
2435 or decimal-point notation, whichever uses fewer characters.\n\
35692fe0
JB
2436%c means print a number as a single character.\n\
2437%S means print any object as an s-expression (using prin1).\n\
9db1775a 2438 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.\n\
52b14ac0 2439Use %% to put a single % into the output.")
35692fe0
JB
2440 (nargs, args)
2441 int nargs;
2442 register Lisp_Object *args;
2443{
2444 register int n; /* The number of the next arg to substitute */
e781c49e 2445 register int total; /* An estimate of the final length */
1f24f4fd 2446 char *buf, *p;
35692fe0 2447 register unsigned char *format, *end;
1f24f4fd
RS
2448 int length, nchars;
2449 /* Nonzero if the output should be a multibyte string,
2450 which is true if any of the inputs is one. */
2451 int multibyte = 0;
8f2917e4
KH
2452 /* When we make a multibyte string, we must pay attention to the
2453 byte combining problem, i.e., a byte may be combined with a
2454 multibyte charcter of the previous string. This flag tells if we
2455 must consider such a situation or not. */
2456 int maybe_combine_byte;
1f24f4fd 2457 unsigned char *this_format;
e781c49e 2458 int longest_format;
8d6179dc 2459 Lisp_Object val;
1f24f4fd 2460
35692fe0 2461 extern char *index ();
1f24f4fd 2462
35692fe0
JB
2463 /* It should not be necessary to GCPRO ARGS, because
2464 the caller in the interpreter should take care of that. */
2465
e781c49e
RS
2466 /* Try to determine whether the result should be multibyte.
2467 This is not always right; sometimes the result needs to be multibyte
2468 because of an object that we will pass through prin1,
2469 and in that case, we won't know it here. */
1f24f4fd
RS
2470 for (n = 0; n < nargs; n++)
2471 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
2472 multibyte = 1;
2473
35692fe0 2474 CHECK_STRING (args[0], 0);
e781c49e
RS
2475
2476 /* If we start out planning a unibyte result,
2477 and later find it has to be multibyte, we jump back to retry. */
2478 retry:
2479
35692fe0 2480 format = XSTRING (args[0])->data;
dc3620af 2481 end = format + STRING_BYTES (XSTRING (args[0]));
e781c49e 2482 longest_format = 0;
1f24f4fd
RS
2483
2484 /* Make room in result for all the non-%-codes in the control string. */
e781c49e 2485 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]);
1f24f4fd
RS
2486
2487 /* Add to TOTAL enough space to hold the converted arguments. */
35692fe0
JB
2488
2489 n = 0;
2490 while (format != end)
2491 if (*format++ == '%')
2492 {
1f24f4fd
RS
2493 int minlen, thissize = 0;
2494 unsigned char *this_format_start = format - 1;
35692fe0
JB
2495
2496 /* Process a numeric arg and skip it. */
2497 minlen = atoi (format);
537dfb13
RS
2498 if (minlen < 0)
2499 minlen = - minlen;
2500
35692fe0
JB
2501 while ((*format >= '0' && *format <= '9')
2502 || *format == '-' || *format == ' ' || *format == '.')
2503 format++;
2504
1f24f4fd
RS
2505 if (format - this_format_start + 1 > longest_format)
2506 longest_format = format - this_format_start + 1;
2507
bf6ab66c
KH
2508 if (format == end)
2509 error ("Format string ends in middle of format specifier");
35692fe0
JB
2510 if (*format == '%')
2511 format++;
2512 else if (++n >= nargs)
537dfb13 2513 error ("Not enough arguments for format string");
35692fe0
JB
2514 else if (*format == 'S')
2515 {
2516 /* For `S', prin1 the argument and then treat like a string. */
2517 register Lisp_Object tem;
2518 tem = Fprin1_to_string (args[n], Qnil);
e781c49e
RS
2519 if (STRING_MULTIBYTE (tem) && ! multibyte)
2520 {
2521 multibyte = 1;
2522 goto retry;
2523 }
35692fe0
JB
2524 args[n] = tem;
2525 goto string;
2526 }
ae683129 2527 else if (SYMBOLP (args[n]))
35692fe0 2528 {
d2fd0445 2529 XSETSTRING (args[n], XSYMBOL (args[n])->name);
7df74da6
RS
2530 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
2531 {
2532 multibyte = 1;
2533 goto retry;
2534 }
35692fe0
JB
2535 goto string;
2536 }
ae683129 2537 else if (STRINGP (args[n]))
35692fe0
JB
2538 {
2539 string:
b22e7ecc 2540 if (*format != 's' && *format != 'S')
bf6ab66c 2541 error ("Format specifier doesn't match argument type");
1f24f4fd 2542 thissize = CONVERTED_BYTE_SIZE (multibyte, args[n]);
35692fe0
JB
2543 }
2544 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
ae683129 2545 else if (INTEGERP (args[n]) && *format != 's')
35692fe0 2546 {
4746118a 2547#ifdef LISP_FLOAT_TYPE
eb8c3be9 2548 /* The following loop assumes the Lisp type indicates
35692fe0
JB
2549 the proper way to pass the argument.
2550 So make sure we have a flonum if the argument should
2551 be a double. */
2552 if (*format == 'e' || *format == 'f' || *format == 'g')
2553 args[n] = Ffloat (args[n]);
4224cb62 2554 else
4746118a 2555#endif
4224cb62
KH
2556 if (*format != 'd' && *format != 'o' && *format != 'x'
2557 && *format != 'X' && *format != 'c')
2558 error ("Invalid format operation %%%c", *format);
2559
f49a2d74 2560 thissize = 30;
25c9e7fb
RS
2561 if (*format == 'c'
2562 && (! SINGLE_BYTE_CHAR_P (XINT (args[n]))
2563 || XINT (args[n]) == 0))
f49a2d74
KH
2564 {
2565 if (! multibyte)
2566 {
2567 multibyte = 1;
2568 goto retry;
2569 }
2570 args[n] = Fchar_to_string (args[n]);
dc3620af 2571 thissize = STRING_BYTES (XSTRING (args[n]));
f49a2d74 2572 }
35692fe0 2573 }
4746118a 2574#ifdef LISP_FLOAT_TYPE
ae683129 2575 else if (FLOATP (args[n]) && *format != 's')
35692fe0
JB
2576 {
2577 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
247422ce 2578 args[n] = Ftruncate (args[n], Qnil);
1f24f4fd 2579 thissize = 60;
35692fe0 2580 }
4746118a 2581#endif
35692fe0
JB
2582 else
2583 {
2584 /* Anything but a string, convert to a string using princ. */
2585 register Lisp_Object tem;
2586 tem = Fprin1_to_string (args[n], Qt);
a4e91443 2587 if (STRING_MULTIBYTE (tem) & ! multibyte)
e781c49e
RS
2588 {
2589 multibyte = 1;
2590 goto retry;
2591 }
35692fe0
JB
2592 args[n] = tem;
2593 goto string;
2594 }
1f24f4fd
RS
2595
2596 if (thissize < minlen)
2597 thissize = minlen;
2598
2599 total += thissize + 4;
35692fe0
JB
2600 }
2601
e781c49e
RS
2602 /* Now we can no longer jump to retry.
2603 TOTAL and LONGEST_FORMAT are known for certain. */
2604
1f24f4fd 2605 this_format = (unsigned char *) alloca (longest_format + 1);
50aa2f90 2606
1f24f4fd
RS
2607 /* Allocate the space for the result.
2608 Note that TOTAL is an overestimate. */
2609 if (total < 1000)
3c6db9d5 2610 buf = (char *) alloca (total + 1);
1f24f4fd 2611 else
3c6db9d5 2612 buf = (char *) xmalloc (total + 1);
35692fe0 2613
1f24f4fd
RS
2614 p = buf;
2615 nchars = 0;
2616 n = 0;
35692fe0 2617
1f24f4fd
RS
2618 /* Scan the format and store result in BUF. */
2619 format = XSTRING (args[0])->data;
8f2917e4 2620 maybe_combine_byte = 0;
1f24f4fd
RS
2621 while (format != end)
2622 {
2623 if (*format == '%')
2624 {
2625 int minlen;
25c9e7fb 2626 int negative = 0;
1f24f4fd 2627 unsigned char *this_format_start = format;
35692fe0 2628
1f24f4fd 2629 format++;
fb893977 2630
1f24f4fd
RS
2631 /* Process a numeric arg and skip it. */
2632 minlen = atoi (format);
2633 if (minlen < 0)
25c9e7fb 2634 minlen = - minlen, negative = 1;
35692fe0 2635
1f24f4fd
RS
2636 while ((*format >= '0' && *format <= '9')
2637 || *format == '-' || *format == ' ' || *format == '.')
2638 format++;
35692fe0 2639
1f24f4fd
RS
2640 if (*format++ == '%')
2641 {
2642 *p++ = '%';
2643 nchars++;
2644 continue;
2645 }
2646
2647 ++n;
2648
2649 if (STRINGP (args[n]))
2650 {
25c9e7fb
RS
2651 int padding, nbytes;
2652 int width = strwidth (XSTRING (args[n])->data,
dc3620af 2653 STRING_BYTES (XSTRING (args[n])));
25c9e7fb
RS
2654
2655 /* If spec requires it, pad on right with spaces. */
2656 padding = minlen - width;
2657 if (! negative)
2658 while (padding-- > 0)
2659 {
2660 *p++ = ' ';
2661 nchars++;
2662 }
1f24f4fd 2663
8f2917e4
KH
2664 if (p > buf
2665 && multibyte
25aa5d64 2666 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
8f2917e4 2667 && STRING_MULTIBYTE (args[n])
25aa5d64 2668 && !CHAR_HEAD_P (XSTRING (args[n])->data[0]))
8f2917e4 2669 maybe_combine_byte = 1;
1f24f4fd 2670 nbytes = copy_text (XSTRING (args[n])->data, p,
dc3620af 2671 STRING_BYTES (XSTRING (args[n])),
1f24f4fd
RS
2672 STRING_MULTIBYTE (args[n]), multibyte);
2673 p += nbytes;
2674 nchars += XSTRING (args[n])->size;
2675
25c9e7fb
RS
2676 if (negative)
2677 while (padding-- > 0)
2678 {
2679 *p++ = ' ';
2680 nchars++;
2681 }
1f24f4fd
RS
2682 }
2683 else if (INTEGERP (args[n]) || FLOATP (args[n]))
2684 {
2685 int this_nchars;
2686
2687 bcopy (this_format_start, this_format,
2688 format - this_format_start);
2689 this_format[format - this_format_start] = 0;
2690
d0183d38
RS
2691 if (INTEGERP (args[n]))
2692 sprintf (p, this_format, XINT (args[n]));
2693 else
2694 sprintf (p, this_format, XFLOAT (args[n])->data);
1f24f4fd 2695
8f2917e4
KH
2696 if (p > buf
2697 && multibyte
25aa5d64
KH
2698 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
2699 && !CHAR_HEAD_P (*((unsigned char *) p)))
8f2917e4 2700 maybe_combine_byte = 1;
1f24f4fd
RS
2701 this_nchars = strlen (p);
2702 p += this_nchars;
2703 nchars += this_nchars;
2704 }
2705 }
7df74da6
RS
2706 else if (STRING_MULTIBYTE (args[0]))
2707 {
2708 /* Copy a whole multibyte character. */
8f2917e4
KH
2709 if (p > buf
2710 && multibyte
25aa5d64
KH
2711 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
2712 && !CHAR_HEAD_P (*format))
8f2917e4 2713 maybe_combine_byte = 1;
7df74da6
RS
2714 *p++ = *format++;
2715 while (! CHAR_HEAD_P (*format)) *p++ = *format++;
2716 nchars++;
2717 }
2718 else if (multibyte)
1f24f4fd
RS
2719 {
2720 /* Convert a single-byte character to multibyte. */
2721 int len = copy_text (format, p, 1, 0, 1);
2722
2723 p += len;
2724 format++;
2725 nchars++;
2726 }
2727 else
2728 *p++ = *format++, nchars++;
2729 }
2730
8f2917e4
KH
2731 if (maybe_combine_byte)
2732 nchars = multibyte_chars_in_text (buf, p - buf);
5f75e666 2733 val = make_specified_string (buf, nchars, p - buf, multibyte);
8d6179dc 2734
1f24f4fd
RS
2735 /* If we allocated BUF with malloc, free it too. */
2736 if (total >= 1000)
2737 xfree (buf);
35692fe0 2738
8d6179dc 2739 return val;
35692fe0
JB
2740}
2741
2742/* VARARGS 1 */
2743Lisp_Object
2744#ifdef NO_ARG_ARRAY
2745format1 (string1, arg0, arg1, arg2, arg3, arg4)
679e18b1 2746 EMACS_INT arg0, arg1, arg2, arg3, arg4;
35692fe0
JB
2747#else
2748format1 (string1)
2749#endif
2750 char *string1;
2751{
2752 char buf[100];
2753#ifdef NO_ARG_ARRAY
679e18b1 2754 EMACS_INT args[5];
35692fe0
JB
2755 args[0] = arg0;
2756 args[1] = arg1;
2757 args[2] = arg2;
2758 args[3] = arg3;
2759 args[4] = arg4;
e3670faa 2760 doprnt (buf, sizeof buf, string1, (char *)0, 5, (char **) args);
35692fe0 2761#else
ea4d2909 2762 doprnt (buf, sizeof buf, string1, (char *)0, 5, &string1 + 1);
35692fe0
JB
2763#endif
2764 return build_string (buf);
2765}
2766\f
2767DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
2768 "Return t if two characters match, optionally ignoring case.\n\
2769Both arguments must be characters (i.e. integers).\n\
2770Case is ignored if `case-fold-search' is non-nil in the current buffer.")
2771 (c1, c2)
2772 register Lisp_Object c1, c2;
2773{
1b5d98bb 2774 int i1, i2;
35692fe0
JB
2775 CHECK_NUMBER (c1, 0);
2776 CHECK_NUMBER (c2, 1);
2777
1b5d98bb 2778 if (XINT (c1) == XINT (c2))
35692fe0 2779 return Qt;
1b5d98bb
RS
2780 if (NILP (current_buffer->case_fold_search))
2781 return Qnil;
2782
2783 /* Do these in separate statements,
2784 then compare the variables.
2785 because of the way DOWNCASE uses temp variables. */
2786 i1 = DOWNCASE (XFASTINT (c1));
2787 i2 = DOWNCASE (XFASTINT (c2));
2788 return (i1 == i2 ? Qt : Qnil);
35692fe0 2789}
b229b8d1
RS
2790\f
2791/* Transpose the markers in two regions of the current buffer, and
2792 adjust the ones between them if necessary (i.e.: if the regions
2793 differ in size).
2794
ec1c14f6
RS
2795 START1, END1 are the character positions of the first region.
2796 START1_BYTE, END1_BYTE are the byte positions.
2797 START2, END2 are the character positions of the second region.
2798 START2_BYTE, END2_BYTE are the byte positions.
2799
b229b8d1
RS
2800 Traverses the entire marker list of the buffer to do so, adding an
2801 appropriate amount to some, subtracting from some, and leaving the
2802 rest untouched. Most of this is copied from adjust_markers in insdel.c.
2803
ec1c14f6 2804 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
b229b8d1
RS
2805
2806void
ec1c14f6
RS
2807transpose_markers (start1, end1, start2, end2,
2808 start1_byte, end1_byte, start2_byte, end2_byte)
b229b8d1 2809 register int start1, end1, start2, end2;
ec1c14f6 2810 register int start1_byte, end1_byte, start2_byte, end2_byte;
b229b8d1 2811{
ec1c14f6 2812 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
b229b8d1 2813 register Lisp_Object marker;
b229b8d1 2814
03240d11 2815 /* Update point as if it were a marker. */
8de1d5f0
KH
2816 if (PT < start1)
2817 ;
2818 else if (PT < end1)
ec1c14f6
RS
2819 TEMP_SET_PT_BOTH (PT + (end2 - end1),
2820 PT_BYTE + (end2_byte - end1_byte));
8de1d5f0 2821 else if (PT < start2)
ec1c14f6
RS
2822 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
2823 (PT_BYTE + (end2_byte - start2_byte)
2824 - (end1_byte - start1_byte)));
8de1d5f0 2825 else if (PT < end2)
ec1c14f6
RS
2826 TEMP_SET_PT_BOTH (PT - (start2 - start1),
2827 PT_BYTE - (start2_byte - start1_byte));
8de1d5f0 2828
03240d11
KH
2829 /* We used to adjust the endpoints here to account for the gap, but that
2830 isn't good enough. Even if we assume the caller has tried to move the
2831 gap out of our way, it might still be at start1 exactly, for example;
2832 and that places it `inside' the interval, for our purposes. The amount
2833 of adjustment is nontrivial if there's a `denormalized' marker whose
2834 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
2835 the dirty work to Fmarker_position, below. */
b229b8d1
RS
2836
2837 /* The difference between the region's lengths */
2838 diff = (end2 - start2) - (end1 - start1);
ec1c14f6 2839 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
b229b8d1
RS
2840
2841 /* For shifting each marker in a region by the length of the other
ec1c14f6 2842 region plus the distance between the regions. */
b229b8d1
RS
2843 amt1 = (end2 - start2) + (start2 - end1);
2844 amt2 = (end1 - start1) + (start2 - end1);
ec1c14f6
RS
2845 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
2846 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
b229b8d1 2847
1e158d25 2848 for (marker = BUF_MARKERS (current_buffer); !NILP (marker);
03240d11 2849 marker = XMARKER (marker)->chain)
b229b8d1 2850 {
ec1c14f6
RS
2851 mpos = marker_byte_position (marker);
2852 if (mpos >= start1_byte && mpos < end2_byte)
2853 {
2854 if (mpos < end1_byte)
2855 mpos += amt1_byte;
2856 else if (mpos < start2_byte)
2857 mpos += diff_byte;
2858 else
2859 mpos -= amt2_byte;
f3e1f752 2860 XMARKER (marker)->bytepos = mpos;
ec1c14f6
RS
2861 }
2862 mpos = XMARKER (marker)->charpos;
03240d11
KH
2863 if (mpos >= start1 && mpos < end2)
2864 {
2865 if (mpos < end1)
2866 mpos += amt1;
2867 else if (mpos < start2)
2868 mpos += diff;
2869 else
2870 mpos -= amt2;
03240d11 2871 }
ec1c14f6 2872 XMARKER (marker)->charpos = mpos;
b229b8d1
RS
2873 }
2874}
2875
2876DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
2877 "Transpose region START1 to END1 with START2 to END2.\n\
2878The regions may not be overlapping, because the size of the buffer is\n\
2879never changed in a transposition.\n\
2880\n\
ec1c14f6 2881Optional fifth arg LEAVE_MARKERS, if non-nil, means don't update\n\
b229b8d1
RS
2882any markers that happen to be located in the regions.\n\
2883\n\
2884Transposing beyond buffer boundaries is an error.")
2885 (startr1, endr1, startr2, endr2, leave_markers)
2886 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
2887{
ec1c14f6
RS
2888 register int start1, end1, start2, end2;
2889 int start1_byte, start2_byte, len1_byte, len2_byte;
2890 int gap, len1, len_mid, len2;
3c6bc7d0 2891 unsigned char *start1_addr, *start2_addr, *temp;
dc3620af
RS
2892 int combined_before_bytes_1, combined_after_bytes_1;
2893 int combined_before_bytes_2, combined_after_bytes_2;
2894 struct gcpro gcpro1, gcpro2;
b229b8d1
RS
2895
2896#ifdef USE_TEXT_PROPERTIES
2897 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2;
1e158d25 2898 cur_intv = BUF_INTERVALS (current_buffer);
b229b8d1
RS
2899#endif /* USE_TEXT_PROPERTIES */
2900
2901 validate_region (&startr1, &endr1);
2902 validate_region (&startr2, &endr2);
2903
2904 start1 = XFASTINT (startr1);
2905 end1 = XFASTINT (endr1);
2906 start2 = XFASTINT (startr2);
2907 end2 = XFASTINT (endr2);
2908 gap = GPT;
2909
2910 /* Swap the regions if they're reversed. */
2911 if (start2 < end1)
2912 {
2913 register int glumph = start1;
2914 start1 = start2;
2915 start2 = glumph;
2916 glumph = end1;
2917 end1 = end2;
2918 end2 = glumph;
2919 }
2920
b229b8d1
RS
2921 len1 = end1 - start1;
2922 len2 = end2 - start2;
2923
2924 if (start2 < end1)
dc3620af 2925 error ("Transposed regions overlap");
b229b8d1 2926 else if (start1 == end1 || start2 == end2)
dc3620af 2927 error ("Transposed region has length 0");
b229b8d1
RS
2928
2929 /* The possibilities are:
2930 1. Adjacent (contiguous) regions, or separate but equal regions
2931 (no, really equal, in this case!), or
2932 2. Separate regions of unequal size.
2933
2934 The worst case is usually No. 2. It means that (aside from
2935 potential need for getting the gap out of the way), there also
2936 needs to be a shifting of the text between the two regions. So
2937 if they are spread far apart, we are that much slower... sigh. */
2938
2939 /* It must be pointed out that the really studly thing to do would
2940 be not to move the gap at all, but to leave it in place and work
2941 around it if necessary. This would be extremely efficient,
2942 especially considering that people are likely to do
2943 transpositions near where they are working interactively, which
2944 is exactly where the gap would be found. However, such code
2945 would be much harder to write and to read. So, if you are
2946 reading this comment and are feeling squirrely, by all means have
2947 a go! I just didn't feel like doing it, so I will simply move
2948 the gap the minimum distance to get it out of the way, and then
2949 deal with an unbroken array. */
3c6bc7d0
RS
2950
2951 /* Make sure the gap won't interfere, by moving it out of the text
2952 we will operate on. */
2953 if (start1 < gap && gap < end2)
2954 {
2955 if (gap - start1 < end2 - gap)
2956 move_gap (start1);
2957 else
2958 move_gap (end2);
2959 }
ec1c14f6
RS
2960
2961 start1_byte = CHAR_TO_BYTE (start1);
2962 start2_byte = CHAR_TO_BYTE (start2);
2963 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
2964 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
dc3620af
RS
2965
2966 if (end1 == start2)
2967 {
2968 combined_before_bytes_2
2969 = count_combining_before (BYTE_POS_ADDR (start2_byte),
2970 len2_byte, start1, start1_byte);
2971 combined_before_bytes_1
2972 = count_combining_before (BYTE_POS_ADDR (start1_byte),
2973 len1_byte, end2, start2_byte + len2_byte);
2974 combined_after_bytes_1
2975 = count_combining_after (BYTE_POS_ADDR (start1_byte),
2976 len1_byte, end2, start2_byte + len2_byte);
2977 combined_after_bytes_2 = 0;
2978 }
2979 else
2980 {
2981 combined_before_bytes_2
2982 = count_combining_before (BYTE_POS_ADDR (start2_byte),
2983 len2_byte, start1, start1_byte);
2984 combined_before_bytes_1
2985 = count_combining_before (BYTE_POS_ADDR (start1_byte),
2986 len1_byte, start2, start2_byte);
2987 combined_after_bytes_2
2988 = count_combining_after (BYTE_POS_ADDR (start2_byte),
2989 len2_byte, end1, start1_byte + len1_byte);
2990 combined_after_bytes_1
2991 = count_combining_after (BYTE_POS_ADDR (start1_byte),
2992 len1_byte, end2, start2_byte + len2_byte);
2993 }
2994
2995 /* If any combining is going to happen, do this the stupid way,
2996 because replace handles combining properly. */
2997 if (combined_before_bytes_1 || combined_before_bytes_2
2998 || combined_after_bytes_1 || combined_after_bytes_2)
2999 {
3000 Lisp_Object text1, text2;
3001
3002 text1 = text2 = Qnil;
3003 GCPRO2 (text1, text2);
3004
3005 text1 = make_buffer_string_both (start1, start1_byte,
3006 end1, start1_byte + len1_byte, 1);
3007 text2 = make_buffer_string_both (start2, start2_byte,
3008 end2, start2_byte + len2_byte, 1);
3009
3010 transpose_markers (start1, end1, start2, end2,
3011 start1_byte, start1_byte + len1_byte,
3012 start2_byte, start2_byte + len2_byte);
3013
c2b70590
RS
3014 replace_range (start2, end2, text1, 1, 0, 0);
3015 replace_range (start1, end1, text2, 1, 0, 0);
dc3620af
RS
3016
3017 UNGCPRO;
3018 return Qnil;
3019 }
b229b8d1
RS
3020
3021 /* Hmmm... how about checking to see if the gap is large
3022 enough to use as the temporary storage? That would avoid an
3023 allocation... interesting. Later, don't fool with it now. */
3024
3025 /* Working without memmove, for portability (sigh), so must be
3026 careful of overlapping subsections of the array... */
3027
3028 if (end1 == start2) /* adjacent regions */
3029 {
b229b8d1
RS
3030 modify_region (current_buffer, start1, end2);
3031 record_change (start1, len1 + len2);
3032
3033#ifdef USE_TEXT_PROPERTIES
3034 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3035 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
09dbcf71
RS
3036 Fset_text_properties (make_number (start1), make_number (end2),
3037 Qnil, Qnil);
b229b8d1
RS
3038#endif /* USE_TEXT_PROPERTIES */
3039
3040 /* First region smaller than second. */
ec1c14f6 3041 if (len1_byte < len2_byte)
b229b8d1 3042 {
3c6bc7d0
RS
3043 /* We use alloca only if it is small,
3044 because we want to avoid stack overflow. */
ec1c14f6
RS
3045 if (len2_byte > 20000)
3046 temp = (unsigned char *) xmalloc (len2_byte);
3c6bc7d0 3047 else
ec1c14f6 3048 temp = (unsigned char *) alloca (len2_byte);
03240d11
KH
3049
3050 /* Don't precompute these addresses. We have to compute them
3051 at the last minute, because the relocating allocator might
3052 have moved the buffer around during the xmalloc. */
23017390
KH
3053 start1_addr = BYTE_POS_ADDR (start1_byte);
3054 start2_addr = BYTE_POS_ADDR (start2_byte);
03240d11 3055
ec1c14f6
RS
3056 bcopy (start2_addr, temp, len2_byte);
3057 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
3058 bcopy (temp, start1_addr, len2_byte);
3059 if (len2_byte > 20000)
3c6bc7d0 3060 free (temp);
b229b8d1
RS
3061 }
3062 else
3063 /* First region not smaller than second. */
3064 {
ec1c14f6
RS
3065 if (len1_byte > 20000)
3066 temp = (unsigned char *) xmalloc (len1_byte);
3c6bc7d0 3067 else
ec1c14f6 3068 temp = (unsigned char *) alloca (len1_byte);
23017390
KH
3069 start1_addr = BYTE_POS_ADDR (start1_byte);
3070 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
3071 bcopy (start1_addr, temp, len1_byte);
3072 bcopy (start2_addr, start1_addr, len2_byte);
3073 bcopy (temp, start1_addr + len2_byte, len1_byte);
3074 if (len1_byte > 20000)
3c6bc7d0 3075 free (temp);
b229b8d1
RS
3076 }
3077#ifdef USE_TEXT_PROPERTIES
3078 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
3079 len1, current_buffer, 0);
3080 graft_intervals_into_buffer (tmp_interval2, start1,
3081 len2, current_buffer, 0);
3082#endif /* USE_TEXT_PROPERTIES */
3083 }
3084 /* Non-adjacent regions, because end1 != start2, bleagh... */
3085 else
3086 {
ec1c14f6
RS
3087 len_mid = start2_byte - (start1_byte + len1_byte);
3088
3089 if (len1_byte == len2_byte)
b229b8d1
RS
3090 /* Regions are same size, though, how nice. */
3091 {
3092 modify_region (current_buffer, start1, end1);
3093 modify_region (current_buffer, start2, end2);
3094 record_change (start1, len1);
3095 record_change (start2, len2);
3096#ifdef USE_TEXT_PROPERTIES
3097 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3098 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
09dbcf71
RS
3099 Fset_text_properties (make_number (start1), make_number (end1),
3100 Qnil, Qnil);
3101 Fset_text_properties (make_number (start2), make_number (end2),
3102 Qnil, Qnil);
b229b8d1
RS
3103#endif /* USE_TEXT_PROPERTIES */
3104
ec1c14f6
RS
3105 if (len1_byte > 20000)
3106 temp = (unsigned char *) xmalloc (len1_byte);
3c6bc7d0 3107 else
ec1c14f6 3108 temp = (unsigned char *) alloca (len1_byte);
23017390
KH
3109 start1_addr = BYTE_POS_ADDR (start1_byte);
3110 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
3111 bcopy (start1_addr, temp, len1_byte);
3112 bcopy (start2_addr, start1_addr, len2_byte);
3113 bcopy (temp, start2_addr, len1_byte);
3114 if (len1_byte > 20000)
3c6bc7d0 3115 free (temp);
b229b8d1
RS
3116#ifdef USE_TEXT_PROPERTIES
3117 graft_intervals_into_buffer (tmp_interval1, start2,
3118 len1, current_buffer, 0);
3119 graft_intervals_into_buffer (tmp_interval2, start1,
3120 len2, current_buffer, 0);
3121#endif /* USE_TEXT_PROPERTIES */
3122 }
3123
ec1c14f6 3124 else if (len1_byte < len2_byte) /* Second region larger than first */
b229b8d1
RS
3125 /* Non-adjacent & unequal size, area between must also be shifted. */
3126 {
b229b8d1
RS
3127 modify_region (current_buffer, start1, end2);
3128 record_change (start1, (end2 - start1));
3129#ifdef USE_TEXT_PROPERTIES
3130 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3131 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3132 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
09dbcf71
RS
3133 Fset_text_properties (make_number (start1), make_number (end2),
3134 Qnil, Qnil);
b229b8d1
RS
3135#endif /* USE_TEXT_PROPERTIES */
3136
3c6bc7d0 3137 /* holds region 2 */
ec1c14f6
RS
3138 if (len2_byte > 20000)
3139 temp = (unsigned char *) xmalloc (len2_byte);
3c6bc7d0 3140 else
ec1c14f6 3141 temp = (unsigned char *) alloca (len2_byte);
23017390
KH
3142 start1_addr = BYTE_POS_ADDR (start1_byte);
3143 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
3144 bcopy (start2_addr, temp, len2_byte);
3145 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
3146 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3147 bcopy (temp, start1_addr, len2_byte);
3148 if (len2_byte > 20000)
3c6bc7d0 3149 free (temp);
b229b8d1
RS
3150#ifdef USE_TEXT_PROPERTIES
3151 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3152 len1, current_buffer, 0);
3153 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3154 len_mid, current_buffer, 0);
3155 graft_intervals_into_buffer (tmp_interval2, start1,
3156 len2, current_buffer, 0);
3157#endif /* USE_TEXT_PROPERTIES */
3158 }
3159 else
3160 /* Second region smaller than first. */
3161 {
b229b8d1
RS
3162 record_change (start1, (end2 - start1));
3163 modify_region (current_buffer, start1, end2);
3164
3165#ifdef USE_TEXT_PROPERTIES
3166 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3167 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3168 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
09dbcf71
RS
3169 Fset_text_properties (make_number (start1), make_number (end2),
3170 Qnil, Qnil);
b229b8d1
RS
3171#endif /* USE_TEXT_PROPERTIES */
3172
3c6bc7d0 3173 /* holds region 1 */
ec1c14f6
RS
3174 if (len1_byte > 20000)
3175 temp = (unsigned char *) xmalloc (len1_byte);
3c6bc7d0 3176 else
ec1c14f6 3177 temp = (unsigned char *) alloca (len1_byte);
23017390
KH
3178 start1_addr = BYTE_POS_ADDR (start1_byte);
3179 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
3180 bcopy (start1_addr, temp, len1_byte);
3181 bcopy (start2_addr, start1_addr, len2_byte);
3182 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3183 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
3184 if (len1_byte > 20000)
3c6bc7d0 3185 free (temp);
b229b8d1
RS
3186#ifdef USE_TEXT_PROPERTIES
3187 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3188 len1, current_buffer, 0);
3189 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3190 len_mid, current_buffer, 0);
3191 graft_intervals_into_buffer (tmp_interval2, start1,
3192 len2, current_buffer, 0);
3193#endif /* USE_TEXT_PROPERTIES */
3194 }
3195 }
3196
ec1c14f6
RS
3197 /* When doing multiple transpositions, it might be nice
3198 to optimize this. Perhaps the markers in any one buffer
3199 should be organized in some sorted data tree. */
b229b8d1 3200 if (NILP (leave_markers))
8de1d5f0 3201 {
ec1c14f6
RS
3202 transpose_markers (start1, end1, start2, end2,
3203 start1_byte, start1_byte + len1_byte,
3204 start2_byte, start2_byte + len2_byte);
8de1d5f0
KH
3205 fix_overlays_in_range (start1, end2);
3206 }
b229b8d1
RS
3207
3208 return Qnil;
3209}
35692fe0 3210
35692fe0
JB
3211\f
3212void
3213syms_of_editfns ()
3214{
260e2e2a
KH
3215 environbuf = 0;
3216
3217 Qbuffer_access_fontify_functions
3218 = intern ("buffer-access-fontify-functions");
3219 staticpro (&Qbuffer_access_fontify_functions);
3220
3221 DEFVAR_LISP ("buffer-access-fontify-functions",
3222 &Vbuffer_access_fontify_functions,
3223 "List of functions called by `buffer-substring' to fontify if necessary.\n\
3224Each function is called with two arguments which specify the range\n\
3225of the buffer being accessed.");
3226 Vbuffer_access_fontify_functions = Qnil;
3227
af209db8
RS
3228 {
3229 Lisp_Object obuf;
3230 extern Lisp_Object Vprin1_to_string_buffer;
3231 obuf = Fcurrent_buffer ();
3232 /* Do this here, because init_buffer_once is too early--it won't work. */
3233 Fset_buffer (Vprin1_to_string_buffer);
3234 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
3235 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
3236 Qnil);
3237 Fset_buffer (obuf);
3238 }
3239
0b6fd023 3240 DEFVAR_LISP ("buffer-access-fontified-property",
260e2e2a
KH
3241 &Vbuffer_access_fontified_property,
3242 "Property which (if non-nil) indicates text has been fontified.\n\
3243`buffer-substring' need not call the `buffer-access-fontify-functions'\n\
3244functions if all the text being accessed has this property.");
3245 Vbuffer_access_fontified_property = Qnil;
3246
f43754f6
KH
3247 DEFVAR_LISP ("system-name", &Vsystem_name,
3248 "The name of the machine Emacs is running on.");
3249
3250 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
3251 "The full name of the user logged in.");
3252
35b34f72 3253 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
f43754f6
KH
3254 "The user's name, taken from environment variables if possible.");
3255
35b34f72 3256 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
f43754f6 3257 "The user's name, based upon the real uid only.");
35692fe0
JB
3258
3259 defsubr (&Schar_equal);
3260 defsubr (&Sgoto_char);
3261 defsubr (&Sstring_to_char);
3262 defsubr (&Schar_to_string);
3263 defsubr (&Sbuffer_substring);
260e2e2a 3264 defsubr (&Sbuffer_substring_no_properties);
35692fe0
JB
3265 defsubr (&Sbuffer_string);
3266
3267 defsubr (&Spoint_marker);
3268 defsubr (&Smark_marker);
3269 defsubr (&Spoint);
3270 defsubr (&Sregion_beginning);
3271 defsubr (&Sregion_end);
7df74da6
RS
3272
3273 defsubr (&Sline_beginning_position);
3274 defsubr (&Sline_end_position);
3275
35692fe0
JB
3276/* defsubr (&Smark); */
3277/* defsubr (&Sset_mark); */
3278 defsubr (&Ssave_excursion);
4bc8c7d2 3279 defsubr (&Ssave_current_buffer);
35692fe0
JB
3280
3281 defsubr (&Sbufsize);
3282 defsubr (&Spoint_max);
3283 defsubr (&Spoint_min);
3284 defsubr (&Spoint_min_marker);
3285 defsubr (&Spoint_max_marker);
c86212b9
RS
3286 defsubr (&Sgap_position);
3287 defsubr (&Sgap_size);
7df74da6 3288 defsubr (&Sposition_bytes);
3ab0732d 3289 defsubr (&Sbyte_to_position);
c9ed721d 3290
35692fe0
JB
3291 defsubr (&Sbobp);
3292 defsubr (&Seobp);
3293 defsubr (&Sbolp);
3294 defsubr (&Seolp);
850a8179
JB
3295 defsubr (&Sfollowing_char);
3296 defsubr (&Sprevious_char);
35692fe0 3297 defsubr (&Schar_after);
fb8106e8 3298 defsubr (&Schar_before);
35692fe0
JB
3299 defsubr (&Sinsert);
3300 defsubr (&Sinsert_before_markers);
be91036a
RS
3301 defsubr (&Sinsert_and_inherit);
3302 defsubr (&Sinsert_and_inherit_before_markers);
35692fe0
JB
3303 defsubr (&Sinsert_char);
3304
3305 defsubr (&Suser_login_name);
3306 defsubr (&Suser_real_login_name);
3307 defsubr (&Suser_uid);
3308 defsubr (&Suser_real_uid);
3309 defsubr (&Suser_full_name);
7fd233b3 3310 defsubr (&Semacs_pid);
d940e0e4 3311 defsubr (&Scurrent_time);
a82d387c 3312 defsubr (&Sformat_time_string);
4691c06d 3313 defsubr (&Sdecode_time);
cce7b8a0 3314 defsubr (&Sencode_time);
35692fe0 3315 defsubr (&Scurrent_time_string);
c2662aea 3316 defsubr (&Scurrent_time_zone);
143cb9a9 3317 defsubr (&Sset_time_zone_rule);
35692fe0 3318 defsubr (&Ssystem_name);
35692fe0 3319 defsubr (&Smessage);
cacc3e2c
RS
3320 defsubr (&Smessage_box);
3321 defsubr (&Smessage_or_box);
b14dda8a 3322 defsubr (&Scurrent_message);
35692fe0 3323 defsubr (&Sformat);
35692fe0
JB
3324
3325 defsubr (&Sinsert_buffer_substring);
e9cf2084 3326 defsubr (&Scompare_buffer_substrings);
35692fe0
JB
3327 defsubr (&Ssubst_char_in_region);
3328 defsubr (&Stranslate_region);
3329 defsubr (&Sdelete_region);
3330 defsubr (&Swiden);
3331 defsubr (&Snarrow_to_region);
3332 defsubr (&Ssave_restriction);
b229b8d1 3333 defsubr (&Stranspose_regions);
35692fe0 3334}