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