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