1 /* editor high level editing commands.
2 
3    Copyright (C) 1996-2000 the Free Software Foundation
4 
5    Authors: 1996, 1997 Paul Sheer
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20    02111-1307, USA.
21 */
22 
23 /* #define PIPE_BLOCKS_SO_READ_BYTE_BY_BYTE */
24 
25 #include <config.h>
26 #ifdef NEEDS_IO_H
27 #include <io.h>
28 #include <fcntl.h>
29 #endif
30 #include <ctype.h>
31 #include "edit.h"
32 #include "editcmddef.h"
33 
34 #ifndef MIDNIGHT
35 #include <X11/Xatom.h>
36 #ifndef GTK
37 #include "loadfile.h"
38 #endif
39 #endif
40 
41 /* globals: */
42 
43 /* search and replace: */
44 int replace_scanf = 0;
45 int replace_regexp = 0;
46 int replace_all = 0;
47 int replace_prompt = 1;
48 int replace_whole = 0;
49 int replace_case = 0;
50 int replace_backwards = 0;
51 int search_create_bookmark = 0;
52 
53 /* queries on a save */
54 #ifdef MIDNIGHT
55 int edit_confirm_save = 1;
56 #else
57 int edit_confirm_save = 0;
58 #endif
59 
60 #define NUM_REPL_ARGS 64
61 #define MAX_REPL_LEN 8192
62 
63 #if defined(MIDNIGHT) || defined(GTK)
64 
my_lower_case(int c)65 static inline int my_lower_case (int c)
66 {
67     return tolower(c & 0xFF);
68 }
69 
strcasechr(const unsigned char * s,int c)70 char *strcasechr (const unsigned char *s, int c)
71 {
72     for (; my_lower_case ((int) *s) != my_lower_case (c); ++s)
73 	if (*s == '\0')
74 	    return 0;
75     return (char *) s;
76 }
77 
78 #ifdef MIDNIGHT
79 #include "../src/mad.h"
80 #elif !defined (GTK)
81 #include "mad.h"
82 #endif
83 
84 #ifndef HAVE_MEMMOVE
85 /* for Christophe */
memmove(void * dest,const void * src,size_t n)86 static void *memmove (void *dest, const void *src, size_t n)
87 {
88     char *t, *s;
89 
90     if (dest <= src) {
91 	t = (char *) dest;
92 	s = (char *) src;
93 	while (n--)
94 	    *t++ = *s++;
95     } else {
96 	t = (char *) dest + n;
97 	s = (char *) src + n;
98 	while (n--)
99 	    *--t = *--s;
100     }
101     return dest;
102 }
103 #endif
104 
105 /* #define itoa MY_itoa  <---- this line is now in edit.h */
itoa(int i)106 char *itoa (int i)
107 {
108     static char t[14];
109     char *s = t + 13;
110     int j = i;
111     *s-- = 0;
112     do {
113 	*s-- = i % 10 + '0';
114     } while ((i = i / 10));
115     if (j < 0)
116 	*s-- = '-';
117     return ++s;
118 }
119 
120 /*
121    This joins strings end on end and allocates memory for the result.
122    The result is later automatically free'd and must not be free'd
123    by the caller.
124  */
catstrs(const char * first,...)125 char *catstrs (const char *first,...)
126 {
127     static char *stacked[16] =
128     {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
129     static int i = 0;
130     va_list ap;
131     int len;
132     char *data;
133 
134     if (!first)
135 	return 0;
136 
137     len = strlen (first);
138     va_start (ap, first);
139 
140     while ((data = va_arg (ap, char *)) != 0)
141 	 len += strlen (data);
142 
143     len++;
144 
145     i = (i + 1) % 16;
146     if (stacked[i])
147 	free (stacked[i]);
148 
149     stacked[i] = malloc (len);
150     va_end (ap);
151     va_start (ap, first);
152     strcpy (stacked[i], first);
153     while ((data = va_arg (ap, char *)) != 0)
154 	 strcat (stacked[i], data);
155     va_end (ap);
156 
157     return stacked[i];
158 }
159 #endif
160 
161 #ifdef MIDNIGHT
162 
edit_help_cmd(WEdit * edit)163 void edit_help_cmd (WEdit * edit)
164 {
165     char *hlpdir = concat_dir_and_file (mc_home, "mc.hlp");
166     interactive_display (hlpdir, "[Internal File Editor]");
167     free (hlpdir);
168     edit->force |= REDRAW_COMPLETELY;
169 }
170 
edit_refresh_cmd(WEdit * edit)171 void edit_refresh_cmd (WEdit * edit)
172 {
173 #ifndef HAVE_SLANG
174     clr_scr();
175     do_refresh();
176 #else
177     {
178 	int fg, bg;
179 	edit_get_syntax_color (edit, -1, &fg, &bg);
180     }
181     touchwin(stdscr);
182 #endif
183     mc_refresh();
184     doupdate();
185 }
186 
187 #else
188 
edit_help_cmd(WEdit * edit)189 void edit_help_cmd (WEdit * edit)
190 {
191 }
192 
edit_refresh_cmd(WEdit * edit)193 void edit_refresh_cmd (WEdit * edit)
194 {
195     int fg, bg;
196     edit_get_syntax_color (edit, -1, &fg, &bg);
197     edit->force |= REDRAW_COMPLETELY;
198 }
199 
CRefreshEditor(WEdit * edit)200 void CRefreshEditor (WEdit * edit)
201 {
202     edit_refresh_cmd (edit);
203 }
204 
205 #endif
206 
207 #define DEFAULT_CREATE_MODE		(S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
208 
209 /* three argument open */
open_create(const char * pathname,int flags,mode_t mode)210 int open_create (const char *pathname, int flags, mode_t mode)
211 {
212     int file;
213     file = open ((char *) pathname, O_RDONLY, mode);
214     if (file < 0 && (flags & O_CREAT))	/* must it be created ? */
215 	return creat ((char *) pathname, mode);
216     if (file >= 0)
217         close (file);
218     return open ((char *) pathname, flags, mode);
219 }
220 
221 /* "Oleg Yu. Repin" <repin@ssd.sscc.ru> added backup filenames
222     ...thanks -paul */
223 
224 /*  If 0 (quick save) then  a) create/truncate <filename> file,
225 			    b) save to <filename>;
226     if 1 (safe save) then   a) save to <tempnam>,
227 			    b) rename <tempnam> to <filename>;
228     if 2 (do backups) then  a) save to <tempnam>,
229 			    b) rename <filename> to <filename.backup_ext>,
230 			    c) rename <tempnam> to <filename>. */
231 
232 /* returns 0 on error */
edit_save_file(WEdit * edit,const char * filename)233 int edit_save_file (WEdit * edit, const char *filename)
234 {
235     char *p;
236     long filelen = 0;
237     FILE *file;
238     char *savename = 0;
239     int this_save_mode, fd;
240 
241     if (!filename)
242 	return 0;
243     if (!*filename)
244 	return 0;
245 
246     savename = (char *) strdup ((char *) filename);
247 
248     if ((fd = open_create (savename, O_WRONLY, DEFAULT_CREATE_MODE)) == -1) {
249 	this_save_mode = 0;	/* the file does not exists yet, so no safe save or backup necessary */
250     } else {
251 	close (fd);
252 	this_save_mode = option_save_mode;
253     }
254 
255     if (this_save_mode > 0) {
256 	char *savedir, *slashpos;
257 	savedir = (char *) strdup (".");
258 	slashpos = strrchr (filename, '/');
259 	if (slashpos) {
260 	    free (savedir);
261 	    savedir = (char *) strdup (filename);
262 	    savedir[slashpos - filename + 1] = '\0';
263 	}
264 	if (savename)
265 	    free (savename);
266 	savename = (char *) tempnam (savedir, "cooledit");
267 	free (savedir);
268 	if (!savename)
269 	    goto error_save;
270     }
271     if ((file = fopen (savename, "w+")) == 0)
272 	goto error_save;
273 #if 0
274     chmod (savename, edit->stat.st_mode);
275     chown (savename, edit->stat.st_uid, edit->stat.st_gid);
276 #endif
277 
278 /* pipe save */
279     if ((p = (char *) edit_get_write_filter (savename, filename))) {
280 	fclose (file);
281 	file = (FILE *) popen (p, "w");
282 	if (file) {
283 	    filelen = edit_write_stream (edit, file);
284 #if 1
285 	    pclose (file);
286 #else
287 	    if (pclose (file) > 0) {
288 		edit_error_dialog (_ (" Error "), catstrs (_ (" Error writing to pipe: "), p, " ", NULL));
289 		free (p);
290 		goto error_save;
291 	    }
292 #endif
293 	} else {
294 	    edit_error_dialog (_ (" Error "), get_sys_error (catstrs (_ (" Failed trying to open pipe for writing: "), p, " ", NULL)));
295 	    free (p);
296 	    goto error_save;
297 	}
298 	free (p);
299 #ifdef CR_LF_TRANSLATION
300     } else {			/* optimised save */
301 	filelen = edit_write_stream (edit, f);
302 	fclose (file);
303 #else
304     } else {
305 	long buf;
306 	buf = 0;
307 	filelen = edit->last_byte;
308 	while (buf <= (edit->curs1 >> S_EDIT_BUF_SIZE) - 1) {
309 	    if (fwrite ((char *) edit->buffers1[buf], EDIT_BUF_SIZE, 1, file) != 1) {
310 		filelen = -1;
311 		break;
312 	    }
313 	    buf++;
314 	}
315 	if (fwrite ((char *) edit->buffers1[buf], edit->curs1 & M_EDIT_BUF_SIZE, 1, file) == -1) {
316 	    filelen = -1;
317 	} else if (edit->curs2) {
318 	    edit->curs2--;
319 	    buf = (edit->curs2 >> S_EDIT_BUF_SIZE);
320 	    if (fwrite ((char *) edit->buffers2[buf] + EDIT_BUF_SIZE - (edit->curs2 & M_EDIT_BUF_SIZE) - 1, 1 + (edit->curs2 & M_EDIT_BUF_SIZE), 1, file) != 1) {
321 		filelen = -1;
322 	    } else {
323 		buf--;
324 		while (buf >= 0) {
325 		    if (fwrite ((char *) edit->buffers2[buf], EDIT_BUF_SIZE, 1, file) != 1) {
326 			filelen = -1;
327 			break;
328 		    }
329 		    buf--;
330 		}
331 	    }
332 	    edit->curs2++;
333 	}
334 	fclose (file);
335 #endif
336     }
337     if (filelen != edit->last_byte)
338 	goto error_save;
339     if (this_save_mode == 2)
340 	if (rename (filename, catstrs (filename, option_backup_ext, NULL)) == -1)
341 	    goto error_save;
342     if (this_save_mode > 0)
343 	if (rename (savename, filename) == -1)
344 	    goto error_save;
345     stat (filename, &edit->stat);
346     edit->test_file_on_disk_for_changes_m_time = edit->stat.st_mtime;
347     if (savename)
348 	free (savename);
349     return 1;
350   error_save:
351     stat (filename, &edit->stat);
352     edit->test_file_on_disk_for_changes_m_time = edit->stat.st_mtime;
353     if (savename)
354 	free (savename);
355     return 0;
356 }
357 
358 /* returns 0 on ignore */
edit_check_change_on_disk(WEdit * edit,int save_mode)359 int edit_check_change_on_disk (WEdit * edit, int save_mode)
360 {
361     char *fullname;
362     struct stat st;
363     int r = 0;
364 
365     memset(&st, '\0', sizeof(st));
366     if (!edit->filename || !*edit->filename || !edit->dir || !*edit->dir)
367         return 0;
368     fullname = strdup(catstrs (edit->dir, edit->filename, NULL));
369     if (!(stat (fullname, &st) < 0)) {
370         if (st.st_mtime != (save_mode ? edit->stat.st_mtime : edit->test_file_on_disk_for_changes_m_time)) {
371             const char *p;
372             if (save_mode) {
373                 p = _("Overwrite");
374             } else {
375                 p = _("Ignore");
376             }
377             if (edit_query_dialog2 (_(" Warning "), _ (" File has been modified on disk by another program. "), _("Open"), p)) {
378                 if (save_mode) {
379                     edit->test_file_on_disk_for_changes_m_time = st.st_mtime;
380                     edit->stat.st_mtime = st.st_mtime;
381                 } else {
382                     edit->test_file_on_disk_for_changes_m_time = st.st_mtime;
383                     /* edit->stat.st_mtime = st.st_mtime; ===>  [Ignore] after keypress should still result in a query on Save */
384                 }
385             } else {
386                 r = 1;
387                 edit_load_cmd (edit);
388             }
389         }
390     }
391     free(fullname);
392     return r;
393 }
394 
395 #ifdef MIDNIGHT
396 /*
397    I changed this from Oleg's original routine so
398    that option_backup_ext works with coolwidgets as well. This
399    does mean there is a memory leak - paul.
400  */
menu_save_mode_cmd(void)401 void menu_save_mode_cmd (void)
402 {
403 #define DLG_X 38
404 #define DLG_Y 10
405     static char *str_result;
406     static int save_mode_new;
407     static char *str[] =
408     {
409 	N_("Quick save "),
410 	N_("Safe save "),
411 	N_("Do backups -->")};
412     static QuickWidget widgets[] =
413     {
414 	{quick_button, 18, DLG_X, 7, DLG_Y, N_("&Cancel"), 0,
415 	 B_CANCEL, 0, 0, XV_WLAY_DONTCARE, "c"},
416 	{quick_button, 6, DLG_X, 7, DLG_Y, N_("&Ok"), 0,
417 	 B_ENTER, 0, 0, XV_WLAY_DONTCARE, "o"},
418 	{quick_input, 23, DLG_X, 5, DLG_Y, 0, 9,
419 	 0, 0, &str_result, XV_WLAY_DONTCARE, "i"},
420 	{quick_label, 22, DLG_X, 4, DLG_Y, N_("Extension:"), 0,
421 	 0, 0, 0, XV_WLAY_DONTCARE, "savemext"},
422 	{quick_radio, 4, DLG_X, 3, DLG_Y, "", 3,
423 	 0, &save_mode_new, str, XV_WLAY_DONTCARE, "t"},
424 	{0}};
425     static QuickDialog dialog =
426 /* NLS ? */
427     {DLG_X, DLG_Y, -1, -1, N_(" Edit Save Mode "), "[Edit Save Mode]",
428      "esm", widgets};
429     static int i18n_flag = 0;
430 
431     if (!i18n_flag) {
432         int i;
433 
434         for (i = 0; i < 3; i++ )
435             str[i] = _(str[i]);
436         i18n_flag = 1;
437     }
438 
439     widgets[2].text = option_backup_ext;
440     widgets[4].value = option_save_mode;
441     if (quick_dialog (&dialog) != B_ENTER)
442 	return;
443     option_save_mode = save_mode_new;
444     option_backup_ext = str_result;	/* this is a memory leak */
445     option_backup_ext_int = 0;
446     str_result[min (strlen (str_result), sizeof (int))] = '\0';
447     memcpy ((char *) &option_backup_ext_int, str_result, strlen (option_backup_ext));
448 }
449 
450 #endif
451 
452 #ifdef MIDNIGHT
453 
edit_split_filename(WEdit * edit,char * f)454 void edit_split_filename (WEdit * edit, char *f)
455 {
456     if (edit->filename)
457 	free (edit->filename);
458     edit->filename = (char *) strdup (f);
459     if (edit->dir)
460 	free (edit->dir);
461     edit->dir = (char *) strdup ("");
462 }
463 
464 #else
465 
466 #ifdef GTK
467 
468 static char cwd[1040];
469 
canonicalize_pathname(char * p)470 static char *canonicalize_pathname (char *p)
471 {
472     char *q, *r;
473 
474     if (*p != '/') {
475 	if (strlen (cwd) == 0) {
476 #ifdef HAVE_GETCWD
477 	    getcwd (cwd, MAX_PATH_LEN);
478 #else
479 	    getwd (cwd);
480 #endif
481 	}
482 	r = malloc (strlen (cwd) + strlen (p) + 2);
483 	strcpy (r, cwd);
484 	strcat (r, "/");
485 	strcat (r, p);
486 	p = r;
487     }
488     r = q = malloc (strlen (p) + 2);
489     for (;;) {
490 	if (!*p) {
491 	    *q = '\0';
492 	    break;
493 	}
494 	if (*p != '/') {
495 	    *q++ = *p++;
496 	} else {
497 	    while (*p == '/') {
498 		*q = '/';
499 		if (!strncmp (p, "/./", 3) || !strcmp (p, "/."))
500 		    p++;
501 		else if (!strncmp (p, "/../", 4) || !strcmp (p, "/..")) {
502 		    p += 2;
503 		    *q = ' ';
504 		    q = strrchr (r, '/');
505 		    if (!q) {
506 			q = r;
507 			*q = '/';
508 		    }
509 		}
510 		p++;
511 	    }
512 	    q++;
513 	}
514     }
515 /* get rid of trailing / */
516     if (r[0] && r[1])
517 	if (*--q == '/')
518 	    *q = '\0';
519     return r;
520 }
521 
522 #endif		/* GTK */
523 
524 
edit_split_filename(WEdit * edit,char * longname)525 void edit_split_filename (WEdit * edit, char *longname)
526 {
527     char *exp, *p;
528 #if defined(MIDNIGHT) || defined(GTK)
529     exp = canonicalize_pathname (longname);
530 #else
531     exp = pathdup (longname);	/* this ensures a full path */
532 #endif
533     if (edit->filename)
534 	free (edit->filename);
535     if (edit->dir)
536 	free (edit->dir);
537     p = strrchr (exp, '/');
538     edit->filename = (char *) strdup (++p);
539     *p = 0;
540     edit->dir = (char *) strdup (exp);
541     free (exp);
542 }
543 
544 #endif		/* ! MIDNIGHT */
545 
546 /*  here we want to warn the user of overwriting an existing file, but only if they
547    have made a change to the filename */
548 /* returns 1 on success */
edit_save_as_cmd(WEdit * edit)549 int edit_save_as_cmd (WEdit * edit)
550 {
551 /* This heads the 'Save As' dialog box */
552     char *exp = 0;
553     int different_filename = 0;
554 
555     exp = edit_get_save_file (edit->dir, edit->filename, _(" Save As "));
556     edit_push_action (edit, KEY_PRESS + edit->start_display);
557 
558     if (exp) {
559 	if (!*exp) {
560 	    free (exp);
561 	    edit->force |= REDRAW_COMPLETELY;
562 	    return 0;
563 	} else {
564 	    if (strcmp(catstrs (edit->dir, edit->filename, NULL), exp)) {
565 		int file;
566 		different_filename = 1;
567 		if ((file = open_create ((char *) exp, O_RDONLY, DEFAULT_CREATE_MODE)) != -1) {	/* the file exists */
568 		    close (file);
569 		    if (edit_query_dialog2 (_(" Warning "),
570 		    _(" A file already exists with this name. "),
571 /* Push buttons to over-write the current file, or cancel the operation */
572 		    _("Overwrite"), _("Cancel"))) {
573 			edit->force |= REDRAW_COMPLETELY;
574 			return 0;
575 		    }
576 		}
577 	    }
578 	    if (edit_save_file (edit, exp)) {
579 		edit_split_filename (edit, exp);
580 		free (exp);
581 		edit->modified = 0;
582 #if defined(MIDNIGHT) || defined(GTK)
583 	        edit->delete_file = 0;
584 #endif
585 		if (different_filename && !edit->explicit_syntax)
586 		    edit_load_syntax (edit, 0, 0);
587 		edit->force |= REDRAW_COMPLETELY;
588 		return 1;
589 	    } else {
590 		free (exp);
591 		edit_error_dialog (_(" Save as "), get_sys_error (_(" Error trying to save file. ")));
592 		edit->force |= REDRAW_COMPLETELY;
593 		return 0;
594 	    }
595 	}
596     }
597     edit->force |= REDRAW_COMPLETELY;
598     return 0;
599 }
600 
601 /* {{{ Macro stuff starts here */
602 
603 #ifdef MIDNIGHT
raw_callback(struct Dlg_head * h,int key,int Msg)604 int raw_callback (struct Dlg_head *h, int key, int Msg)
605 {
606     switch (Msg) {
607     case DLG_DRAW:
608 	attrset (REVERSE_COLOR);
609 	dlg_erase (h);
610 	draw_box (h, 1, 1, h->lines - 2, h->cols - 2);
611 
612 	attrset (COLOR_HOT_NORMAL);
613 	dlg_move (h, 1, 2);
614 	printw (h->title);
615 	break;
616 
617     case DLG_KEY:
618 	h->running = 0;
619 	h->ret_value = key;
620 	return 1;
621     }
622     return 0;
623 }
624 
625 /* gets a raw key from the keyboard. Passing cancel = 1 draws
626    a cancel button thus allowing c-c etc.. Alternatively, cancel = 0
627    will return the next key pressed */
edit_raw_key_query(char * heading,char * query,int cancel)628 int edit_raw_key_query (char *heading, char *query, int cancel)
629 {
630     int w = strlen (query) + 7;
631     struct Dlg_head *raw_dlg = create_dlg (0, 0, 7, w, dialog_colors,
632 /* NLS ? */
633 					 raw_callback, "[Raw Key Query]",
634 					   "raw_key_input",
635 					   DLG_CENTER | DLG_TRYUP);
636     x_set_dialog_title (raw_dlg, heading);
637     raw_dlg->raw = 1;		/* to return even a tab key */
638     if (cancel)
639 	add_widget (raw_dlg, button_new (4, w / 2 - 5, B_CANCEL, NORMAL_BUTTON, _("Cancel"), 0, 0, 0));
640     add_widget (raw_dlg, label_new (3 - cancel, 2, query, 0));
641     add_widget (raw_dlg, input_new (3 - cancel, w - 5, INPUT_COLOR, 2, "", 0));
642     run_dlg (raw_dlg);
643     w = raw_dlg->ret_value;
644     destroy_dlg (raw_dlg);
645     if (cancel)
646 	if (w == XCTRL ('g') || w == XCTRL ('c') || w == ESC_CHAR || w == B_CANCEL)
647 	    return 0;
648 /* hence ctrl-a (=B_CANCEL), ctrl-g, ctrl-c, and Esc are cannot returned */
649     return w;
650 }
651 
652 #else
653 
edit_raw_key_query(const char * heading,const char * query,int cancel)654 int edit_raw_key_query (const char *heading, const char *query, int cancel)
655 {
656 #ifdef GTK
657     /* *** */
658     return 0;
659 #else
660     return CKeySymMod (CRawkeyQuery (0, 0, 0, heading, "%s", query));
661 #endif
662 }
663 
664 #endif
665 
666 /* creates a macro file if it doesn't exist */
edit_open_macro_file(const char * r)667 static FILE *edit_open_macro_file (const char *r)
668 {
669     char *filename;
670     int file;
671     filename = catstrs (home_dir, MACRO_FILE, NULL);
672     if ((file = open_create (filename, O_CREAT | O_RDWR, DEFAULT_CREATE_MODE)) == -1)
673 	return 0;
674     close (file);
675     return fopen (filename, r);
676 }
677 
678 #define MAX_MACROS 1024
679 static int saved_macro[MAX_MACROS + 1] =
680 {0, 0};
681 static int saved_macros_loaded = 0;
682 
683 /*
684    This is just to stop the macro file be loaded over and over for keys
685    that aren't defined to anything. On slow systems this could be annoying.
686  */
macro_exists(int k)687 int macro_exists (int k)
688 {
689     int i;
690     for (i = 0; i < MAX_MACROS && saved_macro[i]; i++)
691 	if (saved_macro[i] == k)
692 	    return i;
693     return -1;
694 }
695 
696 /* returns 1 on error */
edit_delete_macro(WEdit * edit,int k)697 int edit_delete_macro (WEdit * edit, int k)
698 {
699     struct macro macro[MAX_MACRO_LENGTH];
700     FILE *f, *g;
701     int s, i, n, j = 0, ignore;
702 
703     if (saved_macros_loaded)
704 	if ((j = macro_exists (k)) < 0)
705 	    return 0;
706     g = fopen (catstrs (home_dir, TEMP_FILE, NULL), "w");
707     if (!g) {
708 /* This heads the delete macro error dialog box */
709 	edit_error_dialog (_(" Delete macro "),
710 /* 'Open' = load temp file */
711 		 get_sys_error (_(" Error trying to open temp file ")));
712 	return 1;
713     }
714     f = edit_open_macro_file ("r");
715     if (!f) {
716 /* This heads the delete macro error dialog box */
717 	edit_error_dialog (_(" Delete macro "),
718 /* 'Open' = load temp file */
719 		get_sys_error (_(" Error trying to open macro file ")));
720 	fclose (g);
721 	return 1;
722     }
723     for (;;) {
724 	n = fscanf (f, _("key '%d 0': "), &s);
725 	if (!n || n == EOF)
726 	    break;
727 	n = 0;
728 	while (fscanf (f, "%d %ld, ", &macro[n].command, &macro[n].ch))
729 	    n++;
730 	ignore = fscanf (f, ";\n");
731         (void) ignore;
732 	if (s != k) {
733 	    fprintf (g, _("key '%d 0': "), s);
734 	    for (i = 0; i < n; i++)
735 		fprintf (g, "%d %ld, ", macro[i].command, macro[i].ch);
736 	    fprintf (g, ";\n");
737 	}
738     };
739     fclose (f);
740     fclose (g);
741     if (rename (catstrs (home_dir, TEMP_FILE, NULL), catstrs (home_dir, MACRO_FILE, NULL)) == -1) {
742 /* This heads the delete macro error dialog box */
743 	edit_error_dialog (_(" Delete macro "),
744 	   get_sys_error (_(" Error trying to overwrite macro file ")));
745 	return 1;
746     }
747     if (saved_macros_loaded)
748 	memmove (saved_macro + j, saved_macro + j + 1, sizeof (int) * (MAX_MACROS - j - 1));
749     return 0;
750 }
751 
752 /* returns 0 on error */
edit_save_macro_cmd(WEdit * edit,struct macro macro[],int n)753 int edit_save_macro_cmd (WEdit * edit, struct macro macro[], int n)
754 {
755     FILE *f;
756     int s, i;
757 
758     edit_push_action (edit, KEY_PRESS + edit->start_display);
759 /* This heads the 'Macro' dialog box */
760     s = edit_raw_key_query (_(" Macro "),
761 /* Input line for a single key press follows the ':' */
762     _(" Press the macro's new hotkey: "), 1);
763     edit->force |= REDRAW_COMPLETELY;
764     if (s) {
765 	if (edit_delete_macro (edit, s))
766 	    return 0;
767 	f = edit_open_macro_file ("a+");
768 	if (f) {
769 	    fprintf (f, _("key '%d 0': "), s);
770 	    for (i = 0; i < n; i++)
771 		fprintf (f, "%d %ld, ", macro[i].command, macro[i].ch);
772 	    fprintf (f, ";\n");
773 	    fclose (f);
774 	    if (saved_macros_loaded) {
775 		for (i = 0; i < MAX_MACROS && saved_macro[i]; i++);
776 		saved_macro[i] = s;
777 	    }
778 	    return 1;
779 	} else
780 /* This heads the 'Save Macro' dialog box */
781 	    edit_error_dialog (_(" Save macro "), get_sys_error (_(" Error trying to open macro file ")));
782     }
783     return 0;
784 }
785 
edit_delete_macro_cmd(WEdit * edit)786 void edit_delete_macro_cmd (WEdit * edit)
787 {
788     int command;
789 
790 #ifdef MIDNIGHT
791     command = CK_Macro (edit_raw_key_query (_ (" Delete Macro "), _ (" Press macro hotkey: "), 1));
792 #else
793 /* This heads the 'Delete Macro' dialog box */
794 #ifdef GTK
795 /* *** */
796     command = 0;
797 #else
798     command = CKeySymMod (CRawkeyQuery (0, 0, 0, _ (" Delete Macro "), "%s",
799 /* Input line for a single key press follows the ':' */
800 					_ (" Press macro hotkey: ")));
801 #endif
802 #endif
803 
804     if (!command)
805 	return;
806 
807     edit_delete_macro (edit, command);
808 }
809 
810 /* return 0 on error */
edit_load_macro_cmd(WEdit * edit,struct macro macro[],int * n,int k)811 int edit_load_macro_cmd (WEdit * edit, struct macro macro[], int *n, int k)
812 {
813     FILE *f;
814     int s, i = 0, found = 0;
815 
816     if (saved_macros_loaded)
817 	if (macro_exists (k) < 0)
818 	    return 0;
819 
820     if ((f = edit_open_macro_file ("r"))) {
821 	struct macro dummy;
822 	do {
823 	    int u;
824 	    u = fscanf (f, _("key '%d 0': "), &s);
825 	    if (!u || u == EOF)
826 		break;
827 	    if (!saved_macros_loaded)
828 		saved_macro[i++] = s;
829 	    if (!found) {
830 		*n = 0;
831 		while (*n < MAX_MACRO_LENGTH && 2 == fscanf (f, "%d %ld, ", &macro[*n].command, &macro[*n].ch))
832 		    (*n)++;
833 	    } else {
834 		while (2 == fscanf (f, "%d %ld, ", &dummy.command, &dummy.ch));
835 	    }
836 	    u = fscanf (f, ";\n");
837             (void) u;
838 	    if (s == k)
839 		found = 1;
840 	} while (!found || !saved_macros_loaded);
841 	if (!saved_macros_loaded) {
842 	    saved_macro[i] = 0;
843 	    saved_macros_loaded = 1;
844 	}
845 	fclose (f);
846 	return found;
847     } else
848 /* This heads the 'Load Macro' dialog box */
849 	edit_error_dialog (_(" Load macro "),
850 		get_sys_error (_(" Error trying to open macro file ")));
851     return 0;
852 }
853 
854 /* }}} Macro stuff starts here */
855 
856 /* returns 1 on success */
edit_save_confirm_cmd(WEdit * edit)857 int edit_save_confirm_cmd (WEdit * edit)
858 {
859     char *f;
860 
861     if (edit_confirm_save) {
862 #ifdef MIDNIGHT
863 	f = catstrs (_(" Confirm save file? : "), edit->filename, " ", NULL);
864 #else
865 	f = catstrs (_(" Confirm save file? : "), edit->dir, edit->filename, " ", NULL);
866 #endif
867 /* Buttons to 'Confirm save file' query */
868 	if (edit_query_dialog2 (_(" Save file "), f, _("Save"), _("Cancel")))
869 	    return 0;
870     }
871     return edit_save_cmd (edit);
872 }
873 
874 
875 /* returns 1 on success */
edit_save_cmd(WEdit * edit)876 int edit_save_cmd (WEdit * edit)
877 {
878     if (edit_check_change_on_disk (edit, 1))
879         return 0;
880     if (!edit_save_file (edit, catstrs (edit->dir, edit->filename, NULL)))
881 	return edit_save_as_cmd (edit);
882     edit->force |= REDRAW_COMPLETELY;
883     edit->modified = 0;
884 #if defined(MIDNIGHT) || defined(GTK)
885     edit->delete_file = 0;
886 #endif
887 
888     return 1;
889 }
890 
891 
892 /* returns 1 on success */
edit_new_cmd(WEdit * edit)893 int edit_new_cmd (WEdit * edit)
894 {
895     if (edit->modified) {
896 	if (edit_query_dialog2 (_ (" Warning "), _ (" Current text was modified without a file save. \n Continue discards these changes. "), _ ("Continue"), _ ("Cancel"))) {
897 	    edit->force |= REDRAW_COMPLETELY;
898 	    return 0;
899 	}
900     }
901     edit->force |= REDRAW_COMPLETELY;
902     edit->modified = 0;
903     return edit_renew (edit);	/* if this gives an error, something has really screwed up */
904 }
905 
906 /* returns 1 on error */
edit_load_file_from_filename(WEdit * edit,char * exp)907 int edit_load_file_from_filename (WEdit * edit, char *exp)
908 {
909     if (!edit_reload (edit, exp, 0, "", 0))
910 	return 1;
911     edit_split_filename (edit, exp);
912     edit->modified = 0;
913     return 0;
914 }
915 
edit_load_cmd(WEdit * edit)916 int edit_load_cmd (WEdit * edit)
917 {
918     char *exp;
919 
920     if (edit->modified) {
921 	if (edit_query_dialog2 (_ (" Warning "), _ (" Current text was modified without a file save. \n Continue discards these changes. "), _ ("Continue"), _ ("Cancel"))) {
922 	    edit->force |= REDRAW_COMPLETELY;
923 	    return 0;
924 	}
925     }
926 
927     exp = edit_get_load_file (edit->dir, edit->filename, _ (" Load "));
928 
929     if (exp) {
930 	if (*exp)
931 	    edit_load_file_from_filename (edit, exp);
932 	free (exp);
933     }
934     edit->force |= REDRAW_COMPLETELY;
935     return 0;
936 }
937 
938 /*
939    if mark2 is -1 then marking is from mark1 to the cursor.
940    Otherwise its between the markers. This handles this.
941    Returns 1 if no text is marked.
942  */
eval_marks(WEdit * edit,long * start_mark,long * end_mark)943 int eval_marks (WEdit * edit, long *start_mark, long *end_mark)
944 {
945     if (edit->mark1 != edit->mark2) {
946 	if (edit->mark2 >= 0) {
947 	    *start_mark = min (edit->mark1, edit->mark2);
948 	    *end_mark = max (edit->mark1, edit->mark2);
949 	} else {
950 	    *start_mark = min (edit->mark1, edit->curs1);
951 	    *end_mark = max (edit->mark1, edit->curs1);
952 	    edit->column2 = edit->curs_col;
953 	}
954 	return 0;
955     } else {
956 	*start_mark = *end_mark = 0;
957 	edit->column2 = edit->column1 = 0;
958 	return 1;
959     }
960 }
961 
962 /*Block copy, move and delete commands */
963 extern int column_highlighting;
964 
965 #ifdef MIDNIGHT
966 #define space_width 1
967 #else
968 extern int space_width;
969 #endif
970 
edit_insert_column_of_text(WEdit * edit,unsigned char * data,int size,int width)971 void edit_insert_column_of_text (WEdit * edit, unsigned char *data, int size, int width)
972 {
973     long cursor;
974     int i, col;
975     cursor = edit->curs1;
976     col = edit_get_col (edit);
977     for (i = 0; i < size; i++) {
978 	if (data[i] == '\n') {	/* fill in and move to next line */
979 	    int l;
980 	    long p;
981 	    if (edit_get_byte (edit, edit->curs1) != '\n') {
982 		l = width - (edit_get_col (edit) - col);
983 		while (l > 0) {
984 		    edit_insert (edit, ' ');
985 		    l -= space_width;
986 		}
987 	    }
988 	    for (p = edit->curs1;; p++) {
989 		if (p == edit->last_byte) {
990 		    edit_cursor_move (edit, edit->last_byte - edit->curs1);
991 		    edit_insert_ahead (edit, '\n');
992 		    p++;
993 		    break;
994 		}
995 		if (edit_get_byte (edit, p) == '\n') {
996 		    p++;
997 		    break;
998 		}
999 	    }
1000 	    edit_cursor_move (edit, edit_move_forward3 (edit, p, col, 0) - edit->curs1);
1001 	    l = col - edit_get_col (edit);
1002 	    while (l >= space_width) {
1003 		edit_insert (edit, ' ');
1004 		l -= space_width;
1005 	    }
1006 	    continue;
1007 	}
1008 	edit_insert (edit, data[i]);
1009     }
1010     edit_cursor_move (edit, cursor - edit->curs1);
1011 }
1012 
1013 
edit_block_copy_cmd(WEdit * edit)1014 void edit_block_copy_cmd (WEdit * edit)
1015 {
1016     long start_mark, end_mark, current = edit->curs1;
1017     int size, x;
1018     unsigned char *copy_buf;
1019 
1020     if (eval_marks (edit, &start_mark, &end_mark))
1021 	return;
1022     if (column_highlighting) {
1023 	edit_update_curs_col (edit);
1024 	x = edit->curs_col;
1025 	if (start_mark <= edit->curs1 && end_mark >= edit->curs1)
1026 	    if ((x > edit->column1 && x < edit->column2) || (x > edit->column2 && x < edit->column1))
1027 		return;
1028     }
1029 
1030     copy_buf = edit_get_block (edit, start_mark, end_mark, &size);
1031 
1032 /* all that gets pushed are deletes hence little space is used on the stack */
1033 
1034     edit_push_markers (edit);
1035 
1036     if (column_highlighting) {
1037 	edit_insert_column_of_text (edit, copy_buf, size, abs (edit->column2 - edit->column1));
1038     } else {
1039 	while (size--)
1040 	    edit_insert_ahead (edit, copy_buf[size]);
1041     }
1042 
1043     free (copy_buf);
1044     edit_scroll_screen_over_cursor (edit);
1045 
1046     if (column_highlighting) {
1047 	edit_set_markers (edit, 0, 0, 0, 0);
1048 	edit_push_action (edit, COLUMN_ON);
1049 	column_highlighting = 0;
1050     } else if (start_mark < current && end_mark > current)
1051 	edit_set_markers (edit, start_mark, end_mark + end_mark - start_mark, 0, 0);
1052 
1053     edit->force |= REDRAW_PAGE;
1054 }
1055 
1056 
edit_block_move_cmd(WEdit * edit)1057 void edit_block_move_cmd (WEdit * edit)
1058 {
1059     long count;
1060     long current;
1061     unsigned char *copy_buf;
1062     long start_mark, end_mark;
1063     int deleted = 0;
1064     int x = 0;
1065 
1066     if (eval_marks (edit, &start_mark, &end_mark))
1067 	return;
1068     if (column_highlighting) {
1069 	edit_update_curs_col (edit);
1070 	x = edit->curs_col;
1071 	if (start_mark <= edit->curs1 && end_mark >= edit->curs1)
1072 	    if ((x > edit->column1 && x < edit->column2) || (x > edit->column2 && x < edit->column1))
1073 		return;
1074     } else if (start_mark <= edit->curs1 && end_mark >= edit->curs1)
1075 	return;
1076 
1077     if ((end_mark - start_mark) > option_max_undo / 2)
1078 	if (edit_query_dialog2 (_ (" Warning "), _ (" Block is large, you may not be able to undo this action. "), _ ("Continue"), _ ("Cancel")))
1079 	    return;
1080 
1081     edit_push_markers (edit);
1082     current = edit->curs1;
1083     if (column_highlighting) {
1084 	int size, c1, c2, line;
1085 	line = edit->curs_line;
1086 	if (edit->mark2 < 0)
1087 	    edit_mark_cmd (edit, 0);
1088 	c1 = min (edit->column1, edit->column2);
1089 	c2 = max (edit->column1, edit->column2);
1090 	copy_buf = edit_get_block (edit, start_mark, end_mark, &size);
1091 	if (x < c2) {
1092 	    edit_block_delete_cmd (edit);
1093 	    deleted = 1;
1094 	}
1095 	edit_move_to_line (edit, line);
1096 	edit_cursor_move (edit, edit_move_forward3 (edit, edit_bol (edit, edit->curs1), x, 0) - edit->curs1);
1097 	edit_insert_column_of_text (edit, copy_buf, size, c2 - c1);
1098 	if (!deleted) {
1099 	    line = edit->curs_line;
1100 	    edit_update_curs_col (edit);
1101 	    x = edit->curs_col;
1102 	    edit_block_delete_cmd (edit);
1103 	    edit_move_to_line (edit, line);
1104 	    edit_cursor_move (edit, edit_move_forward3 (edit, edit_bol (edit, edit->curs1), x, 0) - edit->curs1);
1105 	}
1106 	edit_set_markers (edit, 0, 0, 0, 0);
1107 	edit_push_action (edit, COLUMN_ON);
1108 	column_highlighting = 0;
1109     } else {
1110 	copy_buf = malloc (end_mark - start_mark);
1111 	edit_cursor_move (edit, start_mark - edit->curs1);
1112 	edit_scroll_screen_over_cursor (edit);
1113 	count = start_mark;
1114 	while (count < end_mark) {
1115 	    copy_buf[end_mark - count - 1] = edit_delete (edit);
1116 	    count++;
1117 	}
1118 	edit_scroll_screen_over_cursor (edit);
1119 	edit_cursor_move (edit, current - edit->curs1 - (((current - edit->curs1) > 0) ? end_mark - start_mark : 0));
1120 	edit_scroll_screen_over_cursor (edit);
1121 	while (count-- > start_mark)
1122 	    edit_insert_ahead (edit, copy_buf[end_mark - count - 1]);
1123 	edit_set_markers (edit, edit->curs1, edit->curs1 + end_mark - start_mark, 0, 0);
1124     }
1125     edit_scroll_screen_over_cursor (edit);
1126     free (copy_buf);
1127     edit->force |= REDRAW_PAGE;
1128 }
1129 
1130 void edit_cursor_to_bol (WEdit * edit);
1131 
edit_delete_column_of_text(WEdit * edit)1132 void edit_delete_column_of_text (WEdit * edit)
1133 {
1134     long p, q, r, m1, m2;
1135     int b, c, d;
1136     int n;
1137 
1138     eval_marks (edit, &m1, &m2);
1139     n = edit_move_forward (edit, m1, 0, m2) + 1;
1140     c = edit_move_forward3 (edit, edit_bol (edit, m1), 0, m1);
1141     d = edit_move_forward3 (edit, edit_bol (edit, m2), 0, m2);
1142 
1143     b = min (c, d);
1144     c = max (c, d);
1145 
1146     while (n--) {
1147 	r = edit_bol (edit, edit->curs1);
1148 	p = edit_move_forward3 (edit, r, b, 0);
1149 	q = edit_move_forward3 (edit, r, c, 0);
1150 	if (p < m1)
1151 	    p = m1;
1152 	if (q > m2)
1153 	    q = m2;
1154 	edit_cursor_move (edit, p - edit->curs1);
1155 	while (q > p) {		/* delete line between margins */
1156 	    if (edit_get_byte (edit, edit->curs1) != '\n')
1157 		edit_delete (edit);
1158 	    q--;
1159 	}
1160 	if (n)			/* move to next line except on the last delete */
1161 	    edit_cursor_move (edit, edit_move_forward (edit, edit->curs1, 1, 0) - edit->curs1);
1162     }
1163 }
1164 
edit_block_delete(WEdit * edit)1165 int edit_block_delete (WEdit * edit)
1166 {
1167     long count;
1168     long start_mark, end_mark;
1169     if (eval_marks (edit, &start_mark, &end_mark))
1170 	return 0;
1171     if (column_highlighting && edit->mark2 < 0)
1172 	edit_mark_cmd (edit, 0);
1173     if ((end_mark - start_mark) > option_max_undo / 2)
1174 /* Warning message with a query to continue or cancel the operation */
1175 	if (edit_query_dialog2 (_ (" Warning "), _ (" Block is large, you may not be able to undo this action. "), _ (" Continue "), _ (" Cancel ")))
1176 	    return 1;
1177     edit_push_markers (edit);
1178     edit_cursor_move (edit, start_mark - edit->curs1);
1179     edit_scroll_screen_over_cursor (edit);
1180     count = start_mark;
1181     if (start_mark < end_mark) {
1182 	if (column_highlighting) {
1183 	    if (edit->mark2 < 0)
1184 		edit_mark_cmd (edit, 0);
1185 	    edit_delete_column_of_text (edit);
1186 	} else {
1187 	    while (count < end_mark) {
1188 		edit_delete (edit);
1189 		count++;
1190 	    }
1191 	}
1192     }
1193     edit_set_markers (edit, 0, 0, 0, 0);
1194     edit->force |= REDRAW_PAGE;
1195     return 0;
1196 }
1197 
1198 /* returns 1 if canceelled by user */
edit_block_delete_cmd(WEdit * edit)1199 int edit_block_delete_cmd (WEdit * edit)
1200 {
1201     long start_mark, end_mark;
1202     if (eval_marks (edit, &start_mark, &end_mark)) {
1203 	edit_delete_line (edit);
1204 	return 0;
1205     }
1206     return edit_block_delete (edit);
1207 }
1208 
1209 
1210 #ifdef MIDNIGHT
1211 
1212 #define INPUT_INDEX 9
1213 #define SEARCH_DLG_WIDTH 58
1214 #define SEARCH_DLG_HEIGHT 10
1215 #define REPLACE_DLG_WIDTH 58
1216 #define REPLACE_DLG_HEIGHT 15
1217 #define CONFIRM_DLG_WIDTH 79
1218 #define CONFIRM_DLG_HEIGTH 6
1219 #define B_REPLACE_ALL B_USER+1
1220 #define B_REPLACE_ONE B_USER+2
1221 #define B_SKIP_REPLACE B_USER+3
1222 
edit_replace_prompt(WEdit * edit,char * replace_text,int xpos,int ypos)1223 int edit_replace_prompt (WEdit * edit, char *replace_text, int xpos, int ypos)
1224 {
1225     QuickWidget quick_widgets[] =
1226     {
1227 /* NLS  for hotkeys? */
1228 	{quick_button, 63, CONFIRM_DLG_WIDTH, 3, CONFIRM_DLG_HEIGTH, N_ ("&Cancel"),
1229 	 0, B_CANCEL, 0, 0, XV_WLAY_DONTCARE, NULL},
1230 	{quick_button, 50, CONFIRM_DLG_WIDTH, 3, CONFIRM_DLG_HEIGTH, N_ ("o&Ne"),
1231 	 0, B_REPLACE_ONE, 0, 0, XV_WLAY_DONTCARE, NULL},
1232 	{quick_button, 37, CONFIRM_DLG_WIDTH, 3, CONFIRM_DLG_HEIGTH, N_ ("al&L"),
1233 	 0, B_REPLACE_ALL, 0, 0, XV_WLAY_DONTCARE, NULL},
1234 	{quick_button, 21, CONFIRM_DLG_WIDTH, 3, CONFIRM_DLG_HEIGTH, N_ ("&Skip"),
1235 	 0, B_SKIP_REPLACE, 0, 0, XV_WLAY_DONTCARE, NULL},
1236 	{quick_button, 4, CONFIRM_DLG_WIDTH, 3, CONFIRM_DLG_HEIGTH, N_ ("&Replace"),
1237 	 0, B_ENTER, 0, 0, XV_WLAY_DONTCARE, NULL},
1238 	{quick_label, 2, CONFIRM_DLG_WIDTH, 2, CONFIRM_DLG_HEIGTH, 0,
1239 	 0, 0, 0, XV_WLAY_DONTCARE, 0},
1240 	{0}};
1241 
1242     quick_widgets[4].text = catstrs (_ (" Replace with: "), replace_text, NULL);
1243 
1244     {
1245 	QuickDialog Quick_input =
1246 	{CONFIRM_DLG_WIDTH, CONFIRM_DLG_HEIGTH, 0, 0, N_ (" Confirm replace "),
1247 	 "[Input Line Keys]", "quick_input", 0 /*quick_widgets */ };
1248 
1249 	Quick_input.widgets = quick_widgets;
1250 
1251 	Quick_input.xpos = xpos;
1252 	Quick_input.ypos = ypos;
1253 	return quick_dialog (&Quick_input);
1254     }
1255 }
1256 
edit_replace_dialog(WEdit * edit,char ** search_text,char ** replace_text,char ** arg_order)1257 void edit_replace_dialog (WEdit * edit, char **search_text, char **replace_text, char **arg_order)
1258 {
1259     int treplace_scanf = replace_scanf;
1260     int treplace_regexp = replace_regexp;
1261     int treplace_all = replace_all;
1262     int treplace_prompt = replace_prompt;
1263     int treplace_backwards = replace_backwards;
1264     int treplace_whole = replace_whole;
1265     int treplace_case = replace_case;
1266 
1267     char *tsearch_text;
1268     char *treplace_text;
1269     char *targ_order;
1270     QuickWidget quick_widgets[] =
1271     {
1272 	{quick_button, 6, 10, 12, REPLACE_DLG_HEIGHT, N_("&Cancel"), 0, B_CANCEL, 0,
1273 	 0, XV_WLAY_DONTCARE, NULL},
1274 	{quick_button, 2, 10, 12, REPLACE_DLG_HEIGHT, N_("&Ok"), 0, B_ENTER, 0,
1275 	 0, XV_WLAY_DONTCARE, NULL},
1276 	{quick_checkbox, 33, REPLACE_DLG_WIDTH, 11, REPLACE_DLG_HEIGHT, N_("scanf &Expression"), 0, 0,
1277 	 0, 0, XV_WLAY_DONTCARE, NULL},
1278 	{quick_checkbox, 33, REPLACE_DLG_WIDTH, 10, REPLACE_DLG_HEIGHT, N_("replace &All"), 0, 0,
1279 	 0, 0, XV_WLAY_DONTCARE, NULL},
1280 	{quick_checkbox, 33, REPLACE_DLG_WIDTH, 9, REPLACE_DLG_HEIGHT, N_("pr&Ompt on replace"), 0, 0,
1281 	 0, 0, XV_WLAY_DONTCARE, NULL},
1282 	{quick_checkbox, 4, REPLACE_DLG_WIDTH, 11, REPLACE_DLG_HEIGHT, N_("&Backwards"), 0, 0,
1283 	 0, 0, XV_WLAY_DONTCARE, NULL},
1284 	{quick_checkbox, 4, REPLACE_DLG_WIDTH, 10, REPLACE_DLG_HEIGHT, N_("&Regular expression"), 0, 0,
1285 	 0, 0, XV_WLAY_DONTCARE, NULL},
1286 	{quick_checkbox, 4, REPLACE_DLG_WIDTH, 9, REPLACE_DLG_HEIGHT, N_("&Whole words only"), 0, 0,
1287 	 0, 0, XV_WLAY_DONTCARE, NULL},
1288 	{quick_checkbox, 4, REPLACE_DLG_WIDTH, 8, REPLACE_DLG_HEIGHT, N_("case &Sensitive"), 0, 0,
1289 	 0, 0, XV_WLAY_DONTCARE, NULL},
1290 	{quick_input,    3, REPLACE_DLG_WIDTH, 7, REPLACE_DLG_HEIGHT, "", 52, 0, 0,
1291 	 0, XV_WLAY_BELOWCLOSE, "edit-argord"},
1292 	{quick_label, 2, REPLACE_DLG_WIDTH, 6, REPLACE_DLG_HEIGHT, N_(" Enter replacement argument order eg. 3,2,1,4 "), 0, 0,
1293 	 0, 0, XV_WLAY_DONTCARE, 0},
1294 	{quick_input, 3, REPLACE_DLG_WIDTH, 5, REPLACE_DLG_HEIGHT, "", 52, 0, 0,
1295 	 0, XV_WLAY_BELOWCLOSE, "edit-replace"},
1296 	{quick_label, 2, REPLACE_DLG_WIDTH, 4, REPLACE_DLG_HEIGHT, N_(" Enter replacement string:"), 0, 0, 0,
1297 	 0, XV_WLAY_DONTCARE, 0},
1298 	{quick_input, 3, REPLACE_DLG_WIDTH, 3, REPLACE_DLG_HEIGHT, "", 52, 0, 0,
1299 	 0, XV_WLAY_BELOWCLOSE, "edit-search"},
1300 	{quick_label, 2, REPLACE_DLG_WIDTH, 2, REPLACE_DLG_HEIGHT, N_(" Enter search string:"), 0, 0, 0,
1301 	 0, XV_WLAY_DONTCARE, 0},
1302 	{0}};
1303 
1304     quick_widgets[2].result = &treplace_scanf;
1305     quick_widgets[3].result = &treplace_all;
1306     quick_widgets[4].result = &treplace_prompt;
1307     quick_widgets[5].result = &treplace_backwards;
1308     quick_widgets[6].result = &treplace_regexp;
1309     quick_widgets[7].result = &treplace_whole;
1310     quick_widgets[8].result = &treplace_case;
1311     quick_widgets[9].str_result = &targ_order;
1312     quick_widgets[9].text = *arg_order;
1313     quick_widgets[11].str_result = &treplace_text;
1314     quick_widgets[11].text = *replace_text;
1315     quick_widgets[13].str_result = &tsearch_text;
1316     quick_widgets[13].text = *search_text;
1317     {
1318 	QuickDialog Quick_input =
1319 	{REPLACE_DLG_WIDTH, REPLACE_DLG_HEIGHT, -1, 0, N_(" Replace "),
1320 	 "[Input Line Keys]", "quick_input", 0 /*quick_widgets */ };
1321 
1322 	Quick_input.widgets = quick_widgets;
1323 
1324 	if (quick_dialog (&Quick_input) != B_CANCEL) {
1325 	    *arg_order = *(quick_widgets[INPUT_INDEX].str_result);
1326 	    *replace_text = *(quick_widgets[INPUT_INDEX + 2].str_result);
1327 	    *search_text = *(quick_widgets[INPUT_INDEX + 4].str_result);
1328 	    replace_scanf = treplace_scanf;
1329 	    replace_backwards = treplace_backwards;
1330 	    replace_regexp = treplace_regexp;
1331 	    replace_all = treplace_all;
1332 	    replace_prompt = treplace_prompt;
1333 	    replace_whole = treplace_whole;
1334 	    replace_case = treplace_case;
1335 	    return;
1336 	} else {
1337 	    *arg_order = NULL;
1338 	    *replace_text = NULL;
1339 	    *search_text = NULL;
1340 	    return;
1341 	}
1342     }
1343 }
1344 
1345 
edit_search_dialog(WEdit * edit,char ** search_text)1346 void edit_search_dialog (WEdit * edit, char **search_text)
1347 {
1348     int treplace_scanf = replace_scanf;
1349     int treplace_regexp = replace_regexp;
1350     int treplace_whole = replace_whole;
1351     int treplace_case = replace_case;
1352     int treplace_backwards = replace_backwards;
1353 
1354     char *tsearch_text;
1355     QuickWidget quick_widgets[] =
1356     {
1357 	{quick_button, 6, 10, 7, SEARCH_DLG_HEIGHT, N_("&Cancel"), 0, B_CANCEL, 0,
1358 	 0, XV_WLAY_DONTCARE, NULL},
1359 	{quick_button, 2, 10, 7, SEARCH_DLG_HEIGHT, N_("&Ok"), 0, B_ENTER, 0,
1360 	 0, XV_WLAY_DONTCARE, NULL},
1361 	{quick_checkbox, 33, SEARCH_DLG_WIDTH, 6, SEARCH_DLG_HEIGHT, N_("scanf &Expression"), 0, 0,
1362 	 0, 0, XV_WLAY_DONTCARE, NULL },
1363 	{quick_checkbox, 33, SEARCH_DLG_WIDTH, 5, SEARCH_DLG_HEIGHT, N_("&Backwards"), 0, 0,
1364 	 0, 0, XV_WLAY_DONTCARE, NULL},
1365 	{quick_checkbox, 4, SEARCH_DLG_WIDTH, 6, SEARCH_DLG_HEIGHT, N_("&Regular expression"), 0, 0,
1366 	 0, 0, XV_WLAY_DONTCARE, NULL},
1367 	{quick_checkbox, 4, SEARCH_DLG_WIDTH, 5, SEARCH_DLG_HEIGHT, N_("&Whole words only"), 0, 0,
1368 	 0, 0, XV_WLAY_DONTCARE, NULL},
1369 	{quick_checkbox, 4, SEARCH_DLG_WIDTH, 4, SEARCH_DLG_HEIGHT, N_("case &Sensitive"), 0, 0,
1370 	 0, 0, XV_WLAY_DONTCARE, NULL},
1371 	{quick_input, 3, SEARCH_DLG_WIDTH, 3, SEARCH_DLG_HEIGHT, "", 52, 0, 0,
1372 	 0, XV_WLAY_BELOWCLOSE, "edit-search"},
1373 	{quick_label, 2, SEARCH_DLG_WIDTH, 2, SEARCH_DLG_HEIGHT, N_(" Enter search string:"), 0, 0, 0,
1374 	 0, XV_WLAY_DONTCARE, 0},
1375 	{0}};
1376 
1377     quick_widgets[2].result = &treplace_scanf;
1378     quick_widgets[3].result = &treplace_backwards;
1379     quick_widgets[4].result = &treplace_regexp;
1380     quick_widgets[5].result = &treplace_whole;
1381     quick_widgets[6].result = &treplace_case;
1382     quick_widgets[7].str_result = &tsearch_text;
1383     quick_widgets[7].text = *search_text;
1384 
1385     {
1386 	QuickDialog Quick_input =
1387 	{SEARCH_DLG_WIDTH, SEARCH_DLG_HEIGHT, -1, 0, N_(" Search "),
1388 	 "[Input Line Keys]", "quick_input", 0 /*quick_widgets */ };
1389 
1390 	Quick_input.widgets = quick_widgets;
1391 
1392 	if (quick_dialog (&Quick_input) != B_CANCEL) {
1393 	    *search_text = *(quick_widgets[7].str_result);
1394 	    replace_scanf = treplace_scanf;
1395 	    replace_backwards = treplace_backwards;
1396 	    replace_regexp = treplace_regexp;
1397 	    replace_whole = treplace_whole;
1398 	    replace_case = treplace_case;
1399 	    return;
1400 	} else {
1401 	    *search_text = NULL;
1402 	    return;
1403 	}
1404     }
1405 }
1406 
1407 #else
1408 
1409 #define B_ENTER 0
1410 #define B_SKIP_REPLACE 1
1411 #define B_REPLACE_ALL 2
1412 #define B_REPLACE_ONE 3
1413 #define B_CANCEL 4
1414 
1415 extern CWidget *wedit;
1416 
1417 #ifndef GTK
1418 
1419 void edit_backspace_tab (WEdit * edit, int whole_tabs_only);
1420 
my_is_blank(int c)1421 static inline int my_is_blank (int c)
1422 {
1423     return c == ' ' || c == '\t';
1424 }
1425 
edit_indent_left_right_paragraph(WEdit * edit)1426 void edit_indent_left_right_paragraph (WEdit * edit)
1427 {
1428     char id[33];
1429     int width = 0, lines, c;
1430     XEvent xevent;
1431     char *r;
1432     CState s;
1433     CWidget *w, *p = 0, *i;
1434     long start_mark, end_mark;
1435     strcpy (id, CIdentOf (edit->widget));
1436     strcat (id, ".text");
1437     w = CIdent (id);
1438     if (!w)
1439 	return;
1440     if (eval_marks (edit, &start_mark, &end_mark)) {
1441 	edit_error_dialog (_(" Error "),
1442 			   _
1443 			   (" No text highlighted - highlight text, run command again, then use arrow keys. "));
1444 	return;
1445     }
1446     r = 0;
1447     CBackupState (&s);
1448     CDisable ("*");
1449     p =
1450 	CDrawText ("status_prompt", edit->widget->parentid, CXof (w), CYof (w), "%s",
1451 		   _(" <---  ---> (this eats your undo stack) "));
1452     width = CWidthOf (p);
1453     i = CDrawTextInput ("status_input", edit->widget->parentid, CXof (w) + width, CYof (w),
1454 			CWidthOf (edit->widget) - width, AUTO_HEIGHT, 1, "");
1455     CFocus (i);
1456     edit_set_markers (edit, edit_bol (edit, start_mark), edit_eol (edit, end_mark), -1, -1);
1457     edit->force |= REDRAW_PAGE;
1458     edit_render_keypress (edit);
1459     edit_push_action (edit, KEY_PRESS + edit->start_display);
1460 
1461     for (;;) {
1462 	XEvent xev;
1463 	CEvent cev;
1464 	CNextEvent (&xev, &cev);
1465 	if (xev.type == KeyPress) {
1466 	    if (eval_marks (edit, &start_mark, &end_mark))
1467 		break;
1468 	    lines = edit_count_lines (edit, start_mark, end_mark);
1469 	    if (cev.command == CK_Right || cev.command == CK_Tab) {
1470 		long s;
1471 		for (c = 0, s = start_mark; c <= lines; s = edit_eol (edit, s) + 1, c++) {
1472 		    while (my_is_blank (edit_get_byte (edit, s)) && s < edit->last_byte)
1473 			s++;
1474 		    edit_cursor_move (edit, s - edit->curs1);
1475 		    edit_tab_cmd (edit);
1476 		    s = edit->curs1;
1477 		}
1478 		edit->force |= REDRAW_PAGE;
1479 		edit_render_keypress (edit);
1480 		edit_push_action (edit, KEY_PRESS + edit->start_display);
1481 	    } else if (cev.command == CK_Left || cev.command == CK_BackSpace) {
1482 		long s;
1483 		for (c = 0, s = start_mark; c <= lines; s = edit_eol (edit, s) + 1, c++) {
1484 		    while (my_is_blank (edit_get_byte (edit, s)) && s < edit->last_byte)
1485 			s++;
1486 		    edit_cursor_move (edit, s - edit->curs1);
1487 		    edit_backspace_tab (edit, 1);
1488 		    s = edit->curs1;
1489 		}
1490 		edit->force |= REDRAW_PAGE;
1491 		edit_render_keypress (edit);
1492 		edit_push_action (edit, KEY_PRESS + edit->start_display);
1493 	    } else {
1494 		break;
1495 	    }
1496 	}
1497     }
1498     CDestroyWidget ("status_prompt");
1499     CDestroyWidget ("status_input");
1500     CRestoreState (&s);
1501     return;
1502 }
1503 
1504 extern struct look *look;
1505 
edit_search_replace_dialog(Window parent,int x,int y,char ** search_text,char ** replace_text,char ** arg_order,const char * heading,int option)1506 void edit_search_replace_dialog (Window parent, int x, int y, char **search_text,
1507 				 char **replace_text, char **arg_order, const char *heading, int option)
1508 {
1509     (*look->search_replace_dialog) (parent, x, y, search_text, replace_text, arg_order, heading, option);
1510 }
1511 
edit_search_dialog(WEdit * edit,char ** search_text)1512 void edit_search_dialog (WEdit * edit, char **search_text)
1513 {
1514 /* Heads the 'Search' dialog box */
1515     edit_search_replace_dialog (WIN_MESSAGES, search_text, 0, 0, _(" Search "), SEARCH_DIALOG_OPTION_BACKWARDS | SEARCH_DIALOG_OPTION_BOOKMARK);
1516 }
1517 
edit_replace_dialog(WEdit * edit,char ** search_text,char ** replace_text,char ** arg_order)1518 void edit_replace_dialog (WEdit * edit, char **search_text, char **replace_text, char **arg_order)
1519 {
1520 /* Heads the 'Replace' dialog box */
1521     edit_search_replace_dialog (WIN_MESSAGES, search_text, replace_text, arg_order, _(" Replace "), SEARCH_DIALOG_OPTION_BACKWARDS);
1522 }
1523 
1524 #else
1525 
1526 #include <libgnomeui/gtkcauldron.h>
1527 #include <libgnomeui/gnome-stock.h>
1528 
edit_search_dialog(WEdit * edit,char ** search_text)1529 void edit_search_dialog (WEdit * edit, char **search_text)
1530 {
1531     char *s;
1532     s = gtk_dialog_cauldron (
1533 				"Search", GTK_CAULDRON_TOPLEVEL | GTK_CAULDRON_GRAB,
1534 				" ( (Enter search text)d | %Eogxf )xf / ( ( %Cd // %Cd // %Cd ) || ( %Cd // %Cd )xf )xf / ( %Bxfgrq || %Bxfgq )f",
1535 				search_text, "search",
1536 				"&Whole word", &replace_whole,
1537 				"Case &sensitive", &replace_case,
1538 				"&Regular expression", &replace_regexp,
1539 				"&Backwards", &replace_backwards,
1540 				"Scanf &expression", &replace_scanf,
1541 				GNOME_STOCK_BUTTON_OK,
1542 				GNOME_STOCK_BUTTON_CANCEL
1543 	);
1544     if (s == GTK_CAULDRON_ESCAPE || !s || s == GNOME_STOCK_BUTTON_CANCEL)
1545 	*search_text = 0;
1546     return;
1547 }
1548 
edit_replace_dialog(WEdit * edit,char ** search_text,char ** replace_text,char ** arg_order)1549 void edit_replace_dialog (WEdit * edit, char **search_text, char **replace_text, char **arg_order)
1550 {
1551     char *s;
1552     s = gtk_dialog_cauldron (
1553 				"Search", GTK_CAULDRON_TOPLEVEL | GTK_CAULDRON_GRAB,
1554 				" ( (Enter search text)d | %Eogxf )xf / ( (Enter replace text)d | %Egxf )xf / ( (Enter argument order)d | %Egxf )xf / ( ( %Cd // %Cd // %Cd // %Cd ) || ( %Cd // %Cd // %Cd )xf )xf / ( %Bxfgrq || %Bxfgq )f",
1555 				search_text, "search",
1556 				replace_text, "replace",
1557 				arg_order, "arg_order",
1558 				"&Whole word", &replace_whole,
1559 				"Case &sensitive", &replace_case,
1560 				"&Regular expression", &replace_regexp,
1561 				"&Backwards", &replace_backwards,
1562 				"Pr&ompt on replace", &replace_prompt,
1563 				"Replace &all", &replace_all,
1564 				"Scanf &expression", &replace_scanf,
1565 				GNOME_STOCK_BUTTON_OK,
1566 				GNOME_STOCK_BUTTON_CANCEL
1567 	);
1568     if (s == GTK_CAULDRON_ESCAPE || !s || s == GNOME_STOCK_BUTTON_CANCEL)
1569 	*search_text = 0;
1570     return;
1571 }
1572 
1573 #endif
1574 
1575 #ifdef GTK
1576 
edit_replace_prompt(WEdit * edit,char * replace_text,int xpos,int ypos)1577 int edit_replace_prompt (WEdit * edit, char *replace_text, int xpos, int ypos)
1578 {
1579     char *s;
1580     s = gtk_dialog_cauldron (
1581 		    "Replace", GTK_CAULDRON_TOPLEVEL | GTK_CAULDRON_GRAB,
1582 				" ( (Replace with:)d %Ld )xf / ( %Bxfrq || %Bxfq || %Bxfq || %Bxfq || %Bxfgq )f",
1583 				replace_text,
1584 			 "Replace", "Skip", "Replace all", "Replace one",
1585 				GNOME_STOCK_BUTTON_CANCEL
1586 	);
1587     if (s == GTK_CAULDRON_ESCAPE || !s || s == GNOME_STOCK_BUTTON_CANCEL)
1588 	return B_CANCEL;
1589     if (!strcmp (s, "Replace all"))
1590 	return B_REPLACE_ALL;
1591     if (!strcmp (s, "Replace one"))
1592 	return B_REPLACE_ONE;
1593     if (!strcmp (s, "Skip"))
1594 	return B_SKIP_REPLACE;
1595     if (!strcmp (s, "Replace"))
1596 	return B_ENTER;
1597 }
1598 
1599 #else
1600 
edit_replace_prompt(WEdit * edit,char * replace_text,int xpos,int ypos)1601 int edit_replace_prompt (WEdit * edit, char *replace_text, int xpos, int ypos)
1602 {
1603     int q, x[] =
1604     {
1605 	B_CANCEL, B_ENTER, B_SKIP_REPLACE, B_REPLACE_ALL, B_REPLACE_ONE, B_CANCEL
1606     };
1607     q = CQueryDialog (WIN_MESSAGES + (edit->curs_line < 8 ? edit->num_widget_lines / 2 * FONT_PIX_PER_LINE + CYof (edit->widget) : 0),
1608 		      _ (" Replace "), catstrs (_ (" Replace with: "), replace_text, NULL), _ ("Replace"), _ ("Skip"), _ ("Replace all"), _ ("Replace one"), _ ("Cancel"), NULL);
1609     edit->force |= REDRAW_COMPLETELY;
1610     return x[q + 1];
1611 }
1612 
1613 #endif
1614 
1615 #endif
1616 
1617 struct sargs_s {
1618     int u[NUM_REPL_ARGS][256 / sizeof (int)];
1619 };
1620 
1621 struct sargs_s sargs_;
1622 
1623 #define sargs sargs_.u
1624 
1625 #define SCANF_ARGS sargs[0], sargs[1], sargs[2], sargs[3], \
1626 		     sargs[4], sargs[5], sargs[6], sargs[7], \
1627 		     sargs[8], sargs[9], sargs[10], sargs[11], \
1628 		     sargs[12], sargs[13], sargs[14], sargs[15]
1629 
1630 #define PRINTF_ARGS sargs[argord[0]], sargs[argord[1]], sargs[argord[2]], sargs[argord[3]], \
1631 		     sargs[argord[4]], sargs[argord[5]], sargs[argord[6]], sargs[argord[7]], \
1632 		     sargs[argord[8]], sargs[argord[9]], sargs[argord[10]], sargs[argord[11]], \
1633 		     sargs[argord[12]], sargs[argord[13]], sargs[argord[14]], sargs[argord[15]]
1634 
1635 
1636 /* This function is a modification of mc-3.2.10/src/view.c:regexp_view_search() */
1637 /* returns -3 on error in pattern, -1 on not found, found_len = 0 if either */
string_regexp_search(char * pattern,char * string,int len,int match_type,int match_bol,int icase,int * found_len,void * d)1638 int string_regexp_search (char *pattern, char *string, int len, int match_type, int match_bol, int icase, int *found_len, void *d)
1639 {
1640     static regex_t r;
1641     static char *old_pattern = NULL;
1642     static int old_type, old_icase;
1643     regmatch_t *pmatch;
1644     static regmatch_t s[1];
1645 
1646     pmatch = (regmatch_t *) d;
1647     if (!pmatch)
1648 	pmatch = s;
1649 
1650     if (!old_pattern || strcmp (old_pattern, pattern) || old_type != match_type || old_icase != icase) {
1651 	if (old_pattern) {
1652 	    regfree (&r);
1653 	    free (old_pattern);
1654 	    old_pattern = 0;
1655 	}
1656 	memset (&r, '\0', sizeof (r));
1657 	if (regcomp (&r, pattern, REG_EXTENDED | (icase ? REG_ICASE : 0))) {
1658 	    *found_len = 0;
1659 	    return -3;
1660 	}
1661 	old_pattern = (char *) strdup (pattern);
1662 	old_type = match_type;
1663 	old_icase = icase;
1664     }
1665     if (regexec (&r, string, d ? NUM_REPL_ARGS : 1, pmatch, ((match_bol || match_type != match_normal) ? 0 : REG_NOTBOL)) != 0) {
1666 	*found_len = 0;
1667 	return -1;
1668     }
1669     *found_len = pmatch[0].rm_eo - pmatch[0].rm_so;
1670     return (pmatch[0].rm_so);
1671 }
1672 
1673 /* thanks to  Liviu Daia <daia@stoilow.imar.ro>  for getting this
1674    (and the above) routines to work properly - paul */
1675 
edit_find_string(long start,unsigned char * exp,int * len,long last_byte,int (* get_byte)(void *,long),void * data,int once_only,void * d)1676 long edit_find_string (long start, unsigned char *exp, int *len, long last_byte, int (*get_byte) (void *, long), void *data, int once_only, void *d)
1677 {
1678     long p, q = 0;
1679     long l = strlen ((char *) exp), f = 0;
1680     int n = 0;
1681 
1682     memset(&sargs_, '\0', sizeof(sargs_));
1683 
1684     for (p = 0; p < l; p++)	/* count conversions... */
1685 	if (exp[p] == '%')
1686 	    if (exp[++p] != '%')	/* ...except for "%%" */
1687 		n++;
1688 
1689     if (replace_scanf || replace_regexp) {
1690 	int c;
1691 	unsigned char *buf;
1692 	unsigned char mbuf[MAX_REPL_LEN * 2 + 8];
1693 
1694         memset(mbuf, '\0', sizeof(mbuf));
1695 
1696 	replace_scanf = (!replace_regexp);	/* can't have both */
1697 
1698 	buf = mbuf;
1699 
1700 	if (replace_scanf) {
1701 	    unsigned char e[MAX_REPL_LEN + 8];
1702 	    if (n >= NUM_REPL_ARGS)
1703 		return -3;
1704 
1705 	    if (replace_case) {
1706 		for (p = start; p < last_byte && p < start + MAX_REPL_LEN; p++)
1707 		    buf[p - start] = (*get_byte) (data, p);
1708 	    } else {
1709 		for (p = 0; exp[p] != 0; p++)
1710 		    exp[p] = my_lower_case (exp[p]);
1711 		for (p = start; p < last_byte && p < start + MAX_REPL_LEN; p++) {
1712 		    c = (*get_byte) (data, p);
1713 		    buf[p - start] = my_lower_case (c);
1714 		}
1715 	    }
1716 
1717 	    buf[(q = p - start)] = 0;
1718 	    strcpy ((char *) e, (char *) exp);
1719 	    strcat ((char *) e, "%n");
1720 	    exp = e;
1721 
1722 	    while (q) {
1723 		*((int *) sargs[n]) = 0;	/* --> here was the problem - now fixed: good */
1724 		if (n == sscanf ((char *) buf, (char *) exp, SCANF_ARGS)) {
1725 		    if (*((int *) sargs[n])) {
1726 			*len = *((int *) sargs[n]);
1727 			return start;
1728 		    }
1729 		}
1730 		if (once_only)
1731 		    return -2;
1732 		if (q + start < last_byte) {
1733 		    if (replace_case) {
1734 			buf[q] = (*get_byte) (data, q + start);
1735 		    } else {
1736 			c = (*get_byte) (data, q + start);
1737 			buf[q] = my_lower_case (c);
1738 		    }
1739 		    q++;
1740 		}
1741 		buf[q] = 0;
1742 		start++;
1743 		buf++;		/* move the window along */
1744 		if (buf == mbuf + MAX_REPL_LEN) {	/* the window is about to go past the end of array, so... */
1745 		    memmove (mbuf, buf, strlen ((char *) buf) + 1);	/* reset it */
1746 		    buf = mbuf;
1747 		}
1748 		q--;
1749 	    }
1750 	} else {	/* regexp matching */
1751 	    long offset = 0;
1752 	    int found_start, match_bol, move_win = 0;
1753 
1754 	    while (start + offset < last_byte) {
1755                 int big_line = 0;
1756 		match_bol = (offset == 0 || (*get_byte) (data, start + offset - 1) == '\n');
1757 		if (!move_win) {
1758 		    p = start + offset;
1759 		    q = 0;
1760 		}
1761 		for (; p < last_byte && q < MAX_REPL_LEN; p++, q++) {
1762 		    mbuf[q] = (*get_byte) (data, p);
1763 		    if (mbuf[q] == '\n') {
1764 			q++;
1765 			break;
1766                     }
1767 		}
1768                 big_line = (q == MAX_REPL_LEN);
1769 		offset += q;
1770 		mbuf[q] = 0;
1771 
1772 		buf = mbuf;
1773 		while (q) {
1774 		    found_start = string_regexp_search ((char *) exp, (char *) buf, q, match_normal, match_bol, !replace_case, len, d);
1775 
1776 		    if (found_start <= -2) {	/* regcomp/regexec error */
1777 			*len = 0;
1778 			return -3;
1779 		    }
1780 		    else if (found_start == -1)	/* not found: try next line */
1781 			break;
1782 		    else if (*len == 0) { /* null pattern: try again at next character */
1783 			q--;
1784 			buf++;
1785 			match_bol = 0;
1786 			continue;
1787 		    }
1788 		    else	/* found */
1789 			return (start + offset - q + found_start);
1790 		}
1791 		if (once_only)
1792 		    return -2;
1793 
1794 		if (big_line) { /* incomplete line: try to recover */
1795 		    buf = mbuf + MAX_REPL_LEN / 2;
1796 		    q = strlen ((char *) buf);
1797 		    memmove (mbuf, buf, q);
1798 		    p = start + q;
1799 		    move_win = 1;
1800 		}
1801 		else
1802 		    move_win = 0;
1803 	    }
1804 	}
1805     } else {
1806  	*len = strlen ((char *) exp);
1807 	if (replace_case) {
1808 	    for (p = start; p <= last_byte - l; p++) {
1809  		if ((*get_byte) (data, p) == (unsigned char)exp[0]) {	/* check if first char matches */
1810 		    for (f = 0, q = 0; q < l && f < 1; q++)
1811  			if ((*get_byte) (data, q + p) != (unsigned char)exp[q])
1812 			    f = 1;
1813 		    if (f == 0)
1814 			return p;
1815 		}
1816 		if (once_only)
1817 		    return -2;
1818 	    }
1819 	} else {
1820 	    for (p = 0; exp[p] != 0; p++)
1821 		exp[p] = my_lower_case (exp[p]);
1822 
1823 	    for (p = start; p <= last_byte - l; p++) {
1824 		if (my_lower_case ((*get_byte) (data, p)) == (unsigned char)exp[0]) {
1825 		    for (f = 0, q = 0; q < l && f < 1; q++)
1826 			if (my_lower_case ((*get_byte) (data, q + p)) != (unsigned char)exp[q])
1827 			    f = 1;
1828 		    if (f == 0)
1829 			return p;
1830 		}
1831 		if (once_only)
1832 		    return -2;
1833 	    }
1834 	}
1835     }
1836     return -2;
1837 }
1838 
1839 
edit_find_forwards(long search_start,unsigned char * exp,int * len,long last_byte,int (* get_byte)(void *,long),void * data,int once_only,void * d)1840 long edit_find_forwards (long search_start, unsigned char *exp, int *len, long last_byte, int (*get_byte) (void *, long), void *data, int once_only, void *d)
1841 {				/*front end to find_string to check for
1842 				   whole words */
1843     long p;
1844     p = search_start;
1845 
1846     while ((p = edit_find_string (p, exp, len, last_byte, get_byte, data, once_only, d)) >= 0) {
1847 	if (replace_whole) {
1848 /*If the bordering chars are not in option_whole_chars_search then word is whole */
1849 	    if (!strcasechr (option_whole_chars_search, (*get_byte) (data, p - 1))
1850 		&& !strcasechr (option_whole_chars_search, (*get_byte) (data, p + *len)))
1851 		return p;
1852 	    if (once_only)
1853 		return -2;
1854 	} else
1855 	    return p;
1856 	if (once_only)
1857 	    break;
1858 	p++;			/*not a whole word so continue search. */
1859     }
1860     return p;
1861 }
1862 
edit_find(long search_start,unsigned char * exp,int * len,long last_byte,int (* get_byte)(void *,long),void * data,void * d)1863 long edit_find (long search_start, unsigned char *exp, int *len, long last_byte, int (*get_byte) (void *, long), void *data, void *d)
1864 {
1865     long p;
1866     if (replace_backwards) {
1867 	while (search_start >= 0) {
1868 	    p = edit_find_forwards (search_start, exp, len, last_byte, get_byte, data, 1, d);
1869 	    if (p == search_start)
1870 		return p;
1871 	    search_start--;
1872 	}
1873     } else {
1874 	return edit_find_forwards (search_start, exp, len, last_byte, get_byte, data, 0, d);
1875     }
1876     return -2;
1877 }
1878 
1879 #define is_digit(x) ((x) >= '0' && (x) <= '9')
1880 
1881 #define snprintf(v) { \
1882 		*p1++ = *p++; \
1883 		*p1 = '\0'; \
1884 		sprintf(s,q1,v); \
1885 		s += strlen(s); \
1886 	    }
1887 
1888 /* this function uses the sprintf command to do a vprintf */
1889 /* it takes pointers to arguments instead of the arguments themselves */
sprintf_p(char * str,const char * fmt,...)1890 int sprintf_p (char *str, const char *fmt,...)
1891 {
1892     va_list ap;
1893     int n;
1894     char *q, *p, *s = str;
1895     char q1[32];
1896     char *p1;
1897 
1898     va_start (ap, fmt);
1899     p = q = (char *) fmt;
1900 
1901     while ((p = strchr (p, '%'))) {
1902 	n = (int) ((unsigned long) p - (unsigned long) q);
1903 	strncpy (s, q, n);	/* copy stuff between format specifiers */
1904 	s += n;
1905 	*s = 0;
1906 	q = p;
1907 	p1 = q1;
1908 	*p1++ = *p++;
1909 	if (*p == '%') {
1910 	    p++;
1911 	    *s++ = '%';
1912 	    q = p;
1913 	    continue;
1914 	}
1915 	if (*p == 'n') {
1916 	    p++;
1917 /* do nothing */
1918 	    q = p;
1919 	    continue;
1920 	}
1921 	if (*p == '#')
1922 	    *p1++ = *p++;
1923 	if (*p == '0')
1924 	    *p1++ = *p++;
1925 	if (*p == '-')
1926 	    *p1++ = *p++;
1927 	if (*p == '+')
1928 	    *p1++ = *p++;
1929 	if (*p == '*') {
1930 	    p++;
1931 	    strcpy (p1, itoa (*va_arg (ap, int *)));	/* replace field width with a number */
1932 	    p1 += strlen (p1);
1933 	} else {
1934 	    while (is_digit (*p))
1935 		*p1++ = *p++;
1936 	}
1937 	if (*p == '.')
1938 	    *p1++ = *p++;
1939 	if (*p == '*') {
1940 	    p++;
1941 	    strcpy (p1, itoa (*va_arg (ap, int *)));	/* replace precision with a number */
1942 	    p1 += strlen (p1);
1943 	} else {
1944 	    while (is_digit (*p))
1945 		*p1++ = *p++;
1946 	}
1947 /* flags done, now get argument */
1948 	if (*p == 's') {
1949             snprintf (va_arg (ap, char *));
1950 	} else if (*p == 'h') {
1951 	    if (strchr ("diouxX", *p))
1952 		snprintf (*va_arg (ap, short *));
1953 	} else if (*p == 'l') {
1954 	    *p1++ = *p++;
1955 	    if (strchr ("diouxX", *p))
1956 		snprintf (*va_arg (ap, long *));
1957 	} else if (strchr ("cdiouxX", *p)) {
1958 	    snprintf (*va_arg (ap, int *));
1959 	} else if (*p == 'L') {
1960 	    *p1++ = *p++;
1961 	    if (strchr ("EefgG", *p))
1962 		snprintf (*va_arg (ap, double *));	/* should be long double */
1963 	} else if (strchr ("EefgG", *p)) {
1964 	    snprintf (*va_arg (ap, double *));
1965 	} else if (strchr ("DOU", *p)) {
1966 	    snprintf (*va_arg (ap, long *));
1967 	} else if (*p == 'p') {
1968 	    snprintf (*va_arg (ap, void **));
1969 	}
1970 	q = p;
1971     }
1972     va_end (ap);
1973     sprintf (s, q);		/* print trailing leftover */
1974     return (unsigned long) s - (unsigned long) str + strlen (s);
1975 }
1976 
regexp_error(WEdit * edit)1977 static void regexp_error (WEdit *edit)
1978 {
1979 /* "Error: Syntax error in regular expression, or scanf expression contained too many %'s */
1980     edit_error_dialog (_(" Error "), _(" Invalid regular expression, or scanf expression with to many conversions "));
1981 }
1982 
1983 /* call with edit = 0 before shutdown to close memory leaks */
edit_replace_cmd(WEdit * edit,int again)1984 void edit_replace_cmd (WEdit * edit, int again)
1985 {
1986     static regmatch_t pmatch[NUM_REPL_ARGS];
1987     static char *old1 = NULL;
1988     static char *old2 = NULL;
1989     static char *old3 = NULL;
1990     char *exp1 = "";
1991     char *exp2 = "";
1992     char *exp3 = "";
1993     int replace_yes;
1994     int replace_continue;
1995     int treplace_prompt = 0;
1996     int i = 0;
1997     long times_replaced = 0, last_search;
1998     char fin_string[64];
1999     int argord[NUM_REPL_ARGS];
2000 
2001     if (!edit) {
2002 	if (old1) {
2003 	    free (old1);
2004 	    old1 = 0;
2005 	}
2006 	if (old2) {
2007 	    free (old2);
2008 	    old2 = 0;
2009 	}
2010 	if (old3) {
2011 	    free (old3);
2012 	    old3 = 0;
2013 	}
2014 	return;
2015     }
2016     last_search = edit->last_byte;
2017 
2018     edit->force |= REDRAW_COMPLETELY;
2019 
2020     exp1 = old1 ? old1 : exp1;
2021     exp2 = old2 ? old2 : exp2;
2022     exp3 = old3 ? old3 : exp3;
2023 
2024     if (again) {
2025 	if (!old1 || !old2)
2026 	    return;
2027 	exp1 = (char *) strdup (old1);
2028 	exp2 = (char *) strdup (old2);
2029 	exp3 = (char *) strdup (old3);
2030     } else {
2031 	edit_push_action (edit, KEY_PRESS + edit->start_display);
2032 	edit_replace_dialog (edit, &exp1, &exp2, &exp3);
2033 	treplace_prompt = replace_prompt;
2034     }
2035 
2036     if (!exp1 || !*exp1) {
2037 	edit->force = REDRAW_COMPLETELY;
2038 	if (exp1) {
2039 	    free (exp1);
2040 	    free (exp2);
2041 	    free (exp3);
2042 	}
2043 	return;
2044     }
2045     if (old1)
2046 	free (old1);
2047     if (old2)
2048 	free (old2);
2049     if (old3)
2050 	free (old3);
2051     old1 = (char *) strdup (exp1);
2052     old2 = (char *) strdup (exp2);
2053     old3 = (char *) strdup (exp3);
2054 
2055     {
2056 	char *s;
2057 	int ord;
2058 	while ((s = strchr (exp3, ' ')))
2059 	    memmove (s, s + 1, strlen (s));
2060 	s = exp3;
2061 	for (i = 0; i < NUM_REPL_ARGS; i++) {
2062 	    if ((unsigned long) s != 1 && s < exp3 + strlen (exp3)) {
2063 		if ((ord = atoi (s)))
2064 		    argord[i] = ord - 1;
2065 		else
2066 		    argord[i] = i;
2067 		s = strchr (s, ',') + 1;
2068 	    } else
2069 		argord[i] = i;
2070 	}
2071     }
2072 
2073     replace_continue = replace_all;
2074 
2075     if (edit->found_len && edit->search_start == edit->found_start + 1 && replace_backwards)
2076 	edit->search_start--;
2077 
2078     if (edit->found_len && edit->search_start == edit->found_start - 1 && !replace_backwards)
2079 	edit->search_start++;
2080 
2081     do {
2082 	int len = 0;
2083 	long new_start;
2084 	new_start = edit_find (edit->search_start, (unsigned char *) exp1, &len, last_search,
2085 	   (int (*)(void *, long)) edit_get_byte, (void *) edit, pmatch);
2086 	if (new_start == -3) {
2087 	    regexp_error (edit);
2088 	    break;
2089 	}
2090 	edit->search_start = new_start;
2091 	/*returns negative on not found or error in pattern */
2092 
2093 	if (edit->search_start >= 0) {
2094 	    edit->found_start = edit->search_start;
2095 	    i = edit->found_len = len;
2096 
2097 	    edit_cursor_move (edit, edit->search_start - edit->curs1);
2098 	    edit_scroll_screen_over_cursor (edit);
2099 
2100 	    replace_yes = 1;
2101 
2102 	    if (treplace_prompt) {
2103 		int l;
2104 		l = edit->curs_row - edit->num_widget_lines / 3;
2105 		if (l > 0)
2106 		    edit_scroll_downward (edit, l);
2107 		if (l < 0)
2108 		    edit_scroll_upward (edit, -l);
2109 
2110 		edit_scroll_screen_over_cursor (edit);
2111 		edit->force |= REDRAW_PAGE;
2112 		edit_render_keypress (edit);
2113 
2114 		/*so that undo stops at each query */
2115 		edit_push_key_press (edit);
2116 
2117 		switch (edit_replace_prompt (edit, exp2,	/*and prompt 2/3 down */
2118 					     edit->num_widget_columns / 2 - 33, edit->num_widget_lines * 2 / 3)) {
2119 		case B_ENTER:
2120 		    break;
2121 		case B_SKIP_REPLACE:
2122 		    replace_yes = 0;
2123 		    break;
2124 		case B_REPLACE_ALL:
2125 		    treplace_prompt = 0;
2126 		    replace_continue = 1;
2127 		    break;
2128 		case B_REPLACE_ONE:
2129 		    replace_continue = 0;
2130 		    break;
2131 		case B_CANCEL:
2132 		    replace_yes = 0;
2133 		    replace_continue = 0;
2134 		    break;
2135 		}
2136 	    }
2137 	    if (replace_yes) {	/* delete then insert new */
2138 		if (replace_scanf || replace_regexp) {
2139 		    char repl_str[MAX_REPL_LEN + 8];
2140 		    if (replace_regexp) {	/* we need to fill in sargs just like with scanf */
2141 			int k, j;
2142 			for (k = 1; k < NUM_REPL_ARGS && pmatch[k].rm_eo >= 0; k++) {
2143 			    unsigned char *t;
2144 			    t = (unsigned char *) &sargs[k - 1][0];
2145 			    for (j = 0; j < pmatch[k].rm_eo - pmatch[k].rm_so && j < 255; j++, t++)
2146 				*t = (unsigned char) edit_get_byte (edit, edit->search_start - pmatch[0].rm_so + pmatch[k].rm_so + j);
2147 			    *t = '\0';
2148 			}
2149 			for (; k <= NUM_REPL_ARGS; k++)
2150 			    sargs[k - 1][0] = 0;
2151 		    }
2152 		    if (sprintf_p (repl_str, exp2, PRINTF_ARGS) >= 0) {
2153 			times_replaced++;
2154 			while (i--)
2155 			    edit_delete (edit);
2156 			while (repl_str[++i])
2157 			    edit_insert (edit, repl_str[i]);
2158 		    } else {
2159 			edit_error_dialog (_ (" Replace "),
2160 /* "Invalid regexp string or scanf string" */
2161 			    _ (" Error in replacement format string. "));
2162 			replace_continue = 0;
2163 		    }
2164 		} else {
2165 		    times_replaced++;
2166 		    while (i--)
2167 			edit_delete (edit);
2168 		    while (exp2[++i])
2169 			edit_insert (edit, exp2[i]);
2170 		}
2171 		edit->found_len = i;
2172 	    }
2173 /* so that we don't find the same string again */
2174 	    if (replace_backwards) {
2175 		last_search = edit->search_start;
2176 		edit->search_start--;
2177 	    } else {
2178 		edit->search_start += i;
2179 		last_search = edit->last_byte;
2180 	    }
2181 	    edit_scroll_screen_over_cursor (edit);
2182 	} else {
2183 	    edit->search_start = edit->curs1;	/* try and find from right here for next search */
2184 	    edit_update_curs_col (edit);
2185 
2186 	    edit->force |= REDRAW_PAGE;
2187 	    edit_render_keypress (edit);
2188 	    if (times_replaced) {
2189 		sprintf (fin_string, _ (" %ld replacements made. "), times_replaced);
2190 		edit_message_dialog (_ (" Replace "), fin_string);
2191 	    } else
2192 		edit_message_dialog (_ (" Replace "), _ (" Search string not found. "));
2193 	    replace_continue = 0;
2194 	}
2195     } while (replace_continue);
2196 
2197     free (exp1);
2198     free (exp2);
2199     free (exp3);
2200     edit->force = REDRAW_COMPLETELY;
2201     edit_scroll_screen_over_cursor (edit);
2202 }
2203 
2204 
2205 
2206 
edit_search_cmd(WEdit * edit,int again)2207 void edit_search_cmd (WEdit * edit, int again)
2208 {
2209     static char *old = NULL;
2210     char *exp = "";
2211 
2212     if (!edit) {
2213 	if (old) {
2214 	    free (old);
2215 	    old = 0;
2216 	}
2217 	return;
2218     }
2219     exp = old ? old : exp;
2220     if (again) {		/*ctrl-hotkey for search again. */
2221 	if (!old)
2222 	    return;
2223 	exp = (char *) strdup (old);
2224     } else {
2225 	edit_search_dialog (edit, &exp);
2226 	edit_push_action (edit, KEY_PRESS + edit->start_display);
2227     }
2228 
2229     if (exp) {
2230 	if (*exp) {
2231 	    int len = 0;
2232 	    if (old)
2233 		free (old);
2234 	    old = (char *) strdup (exp);
2235 
2236 	    if (search_create_bookmark) {
2237 		int found = 0, books = 0;
2238 		int l = 0, l_last = -1;
2239 		long p, q = 0;
2240 		for (;;) {
2241 		    p = edit_find (q, (unsigned char *) exp, &len, edit->last_byte,
2242 				   (int (*)(void *, long)) edit_get_byte, (void *) edit, 0);
2243 		    if (p < 0)
2244 			break;
2245 		    found++;
2246 		    l += edit_count_lines (edit, q, p);
2247 		    if (l != l_last) {
2248 			book_mark_insert (edit, l, BOOK_MARK_FOUND_COLOR);
2249 			books++;
2250 		    }
2251 		    l_last = l;
2252 		    q = p + 1;
2253 		}
2254 		if (found) {
2255 		    char fin_string[64];
2256 /* in response to number of bookmarks added because of string being found %d times */
2257 		    sprintf (fin_string, _ (" %d finds made, %d bookmarks added "), found, books);
2258 		    edit_message_dialog (_ (" Search "), fin_string);
2259 		} else {
2260 		    edit_error_dialog (_ (" Search "), _ (" Search string not found. "));
2261 		}
2262 	    } else {
2263 
2264 		if (edit->found_len && edit->search_start == edit->found_start && replace_backwards)
2265 		    edit->search_start--;
2266 
2267 		if (edit->found_len && edit->search_start == edit->found_start && !replace_backwards)
2268 		    edit->search_start += edit->found_len;
2269 
2270 		edit->search_start = edit_find (edit->search_start, (unsigned char *) exp, &len, edit->last_byte,
2271 		(int (*)(void *, long)) edit_get_byte, (void *) edit, 0);
2272 
2273 		if (edit->search_start >= 0) {
2274 		    edit->found_start = edit->search_start;
2275 		    edit->found_len = len;
2276 
2277 		    edit_cursor_move (edit, edit->search_start - edit->curs1);
2278 		    edit_scroll_screen_over_cursor (edit);
2279 /*		    if (replace_backwards)
2280 			edit->search_start--;
2281 		    else
2282 			edit->search_start++; */
2283 		} else if (edit->search_start == -3) {
2284 		    edit->search_start = edit->curs1;
2285 		    regexp_error (edit);
2286 		} else {
2287 		    edit->search_start = edit->curs1;
2288 		    edit_error_dialog (_ (" Search "), _ (" Search string not found. "));
2289 		}
2290 	    }
2291 	}
2292 	free (exp);
2293     }
2294     edit->force |= REDRAW_COMPLETELY;
2295     edit_scroll_screen_over_cursor (edit);
2296 }
2297 
2298 
2299 /* Real edit only */
edit_quit_cmd(WEdit * edit)2300 void edit_quit_cmd (WEdit * edit)
2301 {
2302     edit_push_action (edit, KEY_PRESS + edit->start_display);
2303 
2304 #ifndef MIDNIGHT
2305     if (edit->stopped)
2306 	return;
2307 #endif
2308 
2309     edit->force |= REDRAW_COMPLETELY;
2310     if (edit->modified) {
2311 #ifdef GTK
2312 	char *r;
2313 	r = gtk_dialog_cauldron (_ (" Quit "), GTK_CAULDRON_TOPLEVEL | GTK_CAULDRON_GRAB, " [ ( %Lxf )xf ]xf / ( %Bgxfq || %Bgxfq || %Bgxfq ) ",
2314 				     _ (" Current text was modified without a file save. \n Save with exit? "), GNOME_STOCK_BUTTON_CANCEL, GNOME_STOCK_BUTTON_YES, GNOME_STOCK_BUTTON_NO);
2315 	if (!strcmp (r, GNOME_STOCK_BUTTON_YES)) {
2316 	    edit_push_markers (edit);
2317 	    edit_set_markers (edit, 0, 0, 0, 0);
2318 	    if (!edit_save_cmd (edit))
2319 		return;
2320 	} else if (!strcmp (r, GNOME_STOCK_BUTTON_NO)) {
2321 	    if (edit->delete_file)
2322 		unlink (catstrs (edit->dir, edit->filename, NULL));
2323 	} else {
2324 	    return;
2325 	}
2326 #else
2327 #ifdef MIDNIGHT
2328 	switch (edit_query_dialog3 (_ (" Quit "), _ (" File was modified, Save with exit? "), _ ("Cancel quit"), _ ("&Yes"), _ ("&No"))) {
2329 #else
2330 /* Confirm 'Quit' dialog box */
2331 	switch (edit_query_dialog3 (_ (" Quit "),
2332 				    _ (" Current text was modified without a file save. \n Save with exit? "), _ (" &Cancel quit "), _ (" &Yes "), _ (" &No "))) {
2333 #endif
2334 	case 1:
2335 	    edit_push_markers (edit);
2336 	    edit_set_markers (edit, 0, 0, 0, 0);
2337 	    if (!edit_save_cmd (edit))
2338 		return;
2339 	    break;
2340 	case 2:
2341 #ifdef MIDNIGHT
2342 	    if (edit->delete_file)
2343 		unlink (catstrs (edit->dir, edit->filename, NULL));
2344 #endif
2345 	    break;
2346 	case 0:
2347 	case -1:
2348 	    return;
2349 	}
2350 #endif
2351     }
2352 #if defined(MIDNIGHT) || defined(GTK)
2353     else if (edit->delete_file)
2354 	unlink (catstrs (edit->dir, edit->filename, NULL));
2355 #endif
2356 #ifdef MIDNIGHT
2357     dlg_stop (edit->widget.parent);
2358 #else
2359 #ifdef GTK
2360     {
2361            extern char *edit_one_file;
2362 
2363            if (edit_one_file)
2364                    gtk_main_quit ();
2365     }
2366 #endif
2367     edit->stopped = 1;
2368 #endif
2369 }
2370 
2371 #define TEMP_BUF_LEN 1024
2372 
2373 /* returns a null terminated length of text. Result must be free'd */
2374 unsigned char *edit_get_block (WEdit * edit, long start, long finish, int *l)
2375 {
2376     unsigned char *s, *r;
2377     r = s = malloc (finish - start + 1);
2378     if (column_highlighting) {
2379 	*l = 0;
2380 	while (start < finish) {	/* copy from buffer, excluding chars that are out of the column 'margins' */
2381 	    int c, x;
2382 	    x = edit_move_forward3 (edit, edit_bol (edit, start), 0, start);
2383 	    c = edit_get_byte (edit, start);
2384 	    if ((x >= edit->column1 && x < edit->column2)
2385 	     || (x >= edit->column2 && x < edit->column1) || c == '\n') {
2386 		*s++ = c;
2387 		(*l)++;
2388 	    }
2389 	    start++;
2390 	}
2391     } else {
2392 	*l = finish - start;
2393 	while (start < finish)
2394 	    *s++ = edit_get_byte (edit, start++);
2395     }
2396     *s = 0;
2397     return r;
2398 }
2399 
2400 /* save block, returns 1 on success */
2401 int edit_save_block (WEdit * edit, const char *filename, long start, long finish)
2402 {
2403     int len, file;
2404 
2405     if ((file = open_create ((char *) filename, O_CREAT | O_WRONLY | O_TRUNC, DEFAULT_CREATE_MODE)) == -1)
2406 	return 0;
2407 
2408     if (column_highlighting) {
2409 	unsigned char *block, *p;
2410 	int r;
2411 	p = block = edit_get_block (edit, start, finish, &len);
2412 	while (len) {
2413 	    r = write (file, p, len);
2414 	    if (r < 0)
2415 		break;
2416 	    p += r;
2417 	    len -= r;
2418 	}
2419 	free (block);
2420     } else {
2421 	unsigned char *buf;
2422 	int i = start, end;
2423 	len = finish - start;
2424 	buf = malloc (TEMP_BUF_LEN);
2425 	while (start != finish) {
2426 	    end = min (finish, start + TEMP_BUF_LEN);
2427 	    for (; i < end; i++)
2428 		buf[i - start] = edit_get_byte (edit, i);
2429 	    len -= write (file, (char *) buf, end - start);
2430 	    start = end;
2431 	}
2432 	free (buf);
2433     }
2434     close (file);
2435     if (len)
2436 	return 0;
2437     return 1;
2438 }
2439 
2440 /* copies a block to clipboard file */
2441 static int edit_save_block_to_clip_file (WEdit * edit, long start, long finish)
2442 {
2443     return edit_save_block (edit, catstrs (home_dir, CLIP_FILE, NULL), start, finish);
2444 }
2445 
2446 #ifndef MIDNIGHT
2447 
2448 void paste_text (WEdit * edit, unsigned char *data, unsigned int nitems)
2449 {
2450     if (data) {
2451 	data += nitems - 1;
2452 	while (nitems--)
2453 	    edit_insert_ahead (edit, *data--);
2454     }
2455     edit->force |= REDRAW_COMPLETELY;
2456 }
2457 
2458 char *selection_get_line (void *data, int line)
2459 {
2460     static unsigned char t[1024];
2461     struct selection *s;
2462     int i = 0;
2463     s = (struct selection *) data;
2464     line = (current_selection + line + 1) % NUM_SELECTION_HISTORY;
2465     if (s[line].text) {
2466 	unsigned char *p = s[line].text;
2467 	int c, j;
2468 	for (j = 0; j < s[line].len; j++) {
2469 	    c = *p++;
2470 	    if (!isprint (c)) {
2471 		t[i++] = '_';
2472 		t[i++] = '\b';
2473 		t[i++] = '\\';
2474 		t[i++] = '_';
2475 		t[i++] = '\b';
2476 		switch (c) {
2477 		case '\a':
2478 		    t[i++] = 'a';
2479 		    break;
2480 		case '\b':
2481 		    t[i++] = 'b';
2482 		    break;
2483 		case '\t':
2484 		    t[i++] = 't';
2485 		    break;
2486 		case '\n':
2487 		    t[i++] = 'n';
2488 		    break;
2489 		case '\v':
2490 		    t[i++] = 'v';
2491 		    break;
2492 		case '\f':
2493 		    t[i++] = 'f';
2494 		    break;
2495 		case '\r':
2496 		    t[i++] = 'r';
2497 		    break;
2498 		default:
2499 		    i -= 3;
2500 		    t[i++] = '.';
2501 		    break;
2502 		}
2503 	    } else
2504 		t[i++] = c;
2505 	    if (i > 1000)
2506 		break;
2507 	}
2508     }
2509     t[i] = 0;
2510     return (char *) t;
2511 }
2512 
2513 char *edit_get_text_from_selection_history (Window parent, int x, int y, int cols, int lines, long *len)
2514 {
2515     int i;
2516 #ifdef GTK
2517 #if 0
2518 /* *** */
2519     i = gtk_edit_list_box_dialog (c, 10, 0, NUM_SELECTION_HISTORY - 10, NUM_SELECTION_HISTORY - 1,
2520 				  NUM_SELECTION_HISTORY, selection_get_line, (void *) selection_history);
2521 #else
2522     i = -1;
2523 #endif
2524 #else
2525     i = CListboxDialog (parent, x, y, cols, lines, 0, NUM_SELECTION_HISTORY - lines, NUM_SELECTION_HISTORY - 1,
2526 			NUM_SELECTION_HISTORY, selection_get_line, (void *) selection_history);
2527 #endif
2528     if (i < 0) {
2529 	*len = 0;
2530 	return NULL;
2531     }
2532     i = (current_selection + i + 1) % NUM_SELECTION_HISTORY;
2533     *len = selection_history[i].len;
2534     return (char *) selection_history[i].text;
2535 }
2536 
2537 void edit_paste_from_history (WEdit * edit)
2538 {
2539     long len;
2540     char *s;
2541 
2542     edit_update_curs_col (edit);
2543     edit_update_curs_row (edit);
2544     s = edit_get_text_from_selection_history (WIN_MESSAGES, max (20, edit->num_widget_columns - 5), 10, &len);
2545     paste_text (edit, (unsigned char *) s, len);
2546     edit->force |= REDRAW_COMPLETELY;
2547 }
2548 
2549 /* copies a block to the XWindows buffer */
2550 static int edit_XStore_block (WEdit * edit, long start, long finish)
2551 {
2552     edit_get_selection (edit);
2553     if (selection.len <= 512 * 1024) {	/* we don't want to fill up the server */
2554 	XStoreBytes (CDisplay, (char *) selection.text, (int) selection.len);
2555 	return 0;
2556     } else
2557 	return 1;
2558 }
2559 
2560 int edit_copy_to_X_buf_cmd (WEdit * edit)
2561 {
2562     long start_mark, end_mark;
2563     if (eval_marks (edit, &start_mark, &end_mark))
2564 	return 0;
2565     edit_XStore_block (edit, start_mark, end_mark);
2566     if (!edit_save_block_to_clip_file (edit, start_mark, end_mark)) {
2567 	edit_error_dialog (_(" Copy to clipboard "), get_sys_error (_(" Unable to save to file. ")));
2568 	return 1;
2569     }
2570 #ifdef GTK
2571     gtk_selection_owner_set (GTK_WIDGET (edit->widget), GDK_SELECTION_PRIMARY, GDK_CURRENT_TIME);
2572     edit->widget->editable.selection_start_pos = start_mark;
2573     edit->widget->editable.selection_end_pos = end_mark;
2574     edit->widget->editable.has_selection = TRUE;
2575 #else
2576     XSetSelectionOwner (CDisplay, XA_PRIMARY, CWindowOf (edit->widget), CurrentTime);
2577     XSetSelectionOwner (CDisplay, ATOM_ICCCM_P2P_CLIPBOARD, CWindowOf (edit->widget), CurrentTime);
2578 #endif
2579     edit_mark_cmd (edit, 1);
2580     return 0;
2581 }
2582 
2583 int edit_cut_to_X_buf_cmd (WEdit * edit)
2584 {
2585     long start_mark, end_mark;
2586     if (eval_marks (edit, &start_mark, &end_mark))
2587 	return 0;
2588     edit_XStore_block (edit, start_mark, end_mark);
2589     if (!edit_save_block_to_clip_file (edit, start_mark, end_mark)) {
2590 	edit_error_dialog (_(" Cut to clipboard "), _(" Unable to save to file. "));
2591 	return 1;
2592     }
2593     edit_block_delete_cmd (edit);
2594 #ifdef GTK
2595     gtk_selection_owner_set (GTK_WIDGET (edit->widget), GDK_SELECTION_PRIMARY, GDK_CURRENT_TIME);
2596     edit->widget->editable.selection_start_pos = start_mark;
2597     edit->widget->editable.selection_end_pos = end_mark;
2598     edit->widget->editable.has_selection = TRUE;
2599 #else
2600     XSetSelectionOwner (CDisplay, XA_PRIMARY, CWindowOf (edit->widget), CurrentTime);
2601     XSetSelectionOwner (CDisplay, ATOM_ICCCM_P2P_CLIPBOARD, CWindowOf (edit->widget), CurrentTime);
2602 #endif
2603     edit_mark_cmd (edit, 1);
2604     return 0;
2605 }
2606 
2607 void selection_paste (WEdit * edit, Window win, unsigned prop, int delete);
2608 
2609 void edit_paste_from_X_buf_cmd (WEdit * edit)
2610 {
2611     if (selection.text)
2612 	paste_text (edit, selection.text, selection.len);
2613     else if (!XGetSelectionOwner (CDisplay, XA_PRIMARY))
2614 #ifdef GTK
2615 /* *** */
2616 	;
2617 #else
2618 	selection_paste (edit, CRoot, XA_CUT_BUFFER0, False);
2619 #endif
2620     else
2621 #ifdef GTK
2622        gtk_selection_convert (GTK_WIDGET (edit->widget), GDK_SELECTION_PRIMARY,
2623             gdk_atom_intern ("COMPOUND_TEXT", FALSE), GDK_CURRENT_TIME);
2624 #else
2625 	XConvertSelection (CDisplay, XA_PRIMARY, XA_STRING,
2626 			   XInternAtom (CDisplay, "VT_SELECTION", False),
2627 			   CWindowOf (edit->widget), CurrentTime);
2628 #endif
2629     edit->force |= REDRAW_PAGE;
2630 }
2631 
2632 #else				/* MIDNIGHT */
2633 
2634 void edit_paste_from_history (WEdit *edit)
2635 {
2636 }
2637 
2638 int edit_copy_to_X_buf_cmd (WEdit * edit)
2639 {
2640     long start_mark, end_mark;
2641     if (eval_marks (edit, &start_mark, &end_mark))
2642 	return 0;
2643     if (!edit_save_block_to_clip_file (edit, start_mark, end_mark)) {
2644 	edit_error_dialog (_(" Copy to clipboard "), get_sys_error (_(" Unable to save to file. ")));
2645 	return 1;
2646     }
2647     edit_mark_cmd (edit, 1);
2648     return 0;
2649 }
2650 
2651 int edit_cut_to_X_buf_cmd (WEdit * edit)
2652 {
2653     long start_mark, end_mark;
2654     if (eval_marks (edit, &start_mark, &end_mark))
2655 	return 0;
2656     if (!edit_save_block_to_clip_file (edit, start_mark, end_mark)) {
2657 	edit_error_dialog (_(" Cut to clipboard "), _(" Unable to save to file. "));
2658 	return 1;
2659     }
2660     edit_block_delete_cmd (edit);
2661     edit_mark_cmd (edit, 1);
2662     return 0;
2663 }
2664 
2665 void edit_paste_from_X_buf_cmd (WEdit * edit)
2666 {
2667     edit_insert_file (edit, catstrs (home_dir, CLIP_FILE, NULL));
2668 }
2669 
2670 #endif				/* MIDMIGHT */
2671 
2672 void edit_goto_cmd (WEdit *edit)
2673 {
2674     char *f;
2675     static int l = 0;
2676 #ifdef MIDNIGHT
2677     char s[12];
2678     sprintf (s, "%d", l);
2679     f = input_dialog (_(" Goto line "), _(" Enter line: "), l ? s : "");
2680 #else
2681 #ifdef GTK
2682 #if 0
2683     f = gtk_edit_dialog_input ("goto", 150, l ? itoa (l) : "", _(" Goto line "), _(" Enter line: "));
2684 #else
2685     char s [12];
2686 
2687     sprintf (s, "%d", l);
2688     f = (char *) input_dialog (_(" Goto line "), _(" Enter line: "), l ? s : "");
2689 #endif
2690 #else
2691     f = CInputDialog ("goto", WIN_MESSAGES, 150, l ? itoa (l) : "", _(" Goto line "), _(" Enter line: "));
2692 #endif
2693 #endif
2694     if (f) {
2695 	if (*f) {
2696 	    l = atoi (f);
2697 	    edit_move_display (edit, l - edit->num_widget_lines / 2 - 1);
2698 	    edit_move_to_line (edit, l - 1);
2699 	    edit->force |= REDRAW_COMPLETELY;
2700 	    free (f);
2701 	}
2702     }
2703 }
2704 
2705 /*returns 1 on success */
2706 int edit_save_block_cmd (WEdit * edit)
2707 {
2708     long start_mark, end_mark;
2709     char *exp;
2710     if (eval_marks (edit, &start_mark, &end_mark))
2711 	return 1;
2712     exp = edit_get_save_file (edit->dir, catstrs (home_dir, CLIP_FILE, NULL), _ (" Save Block "));
2713     edit_push_action (edit, KEY_PRESS + edit->start_display);
2714     if (exp) {
2715 	if (!*exp) {
2716 	    free (exp);
2717 	    return 0;
2718 	} else {
2719 	    if (edit_save_block (edit, exp, start_mark, end_mark)) {
2720 		free (exp);
2721 		edit->force |= REDRAW_COMPLETELY;
2722 		return 1;
2723 	    } else {
2724 		free (exp);
2725 		edit_error_dialog (_ (" Save Block "), get_sys_error (_ (" Error trying to save file. ")));
2726 		edit->force |= REDRAW_COMPLETELY;
2727 		return 0;
2728 	    }
2729 	}
2730     }
2731     edit->force |= REDRAW_COMPLETELY;
2732     return 0;
2733 }
2734 
2735 
2736 /* returns 1 on success */
2737 int edit_insert_file_cmd (WEdit * edit)
2738 {
2739     char *exp = edit_get_load_file (edit->dir, catstrs (home_dir, CLIP_FILE, NULL), _ (" Insert File "));
2740     edit_push_action (edit, KEY_PRESS + edit->start_display);
2741     if (exp) {
2742 	if (!*exp) {
2743 	    free (exp);
2744 	    return 0;
2745 	} else {
2746 	    if (edit_insert_file (edit, exp)) {
2747 		free (exp);
2748 		edit->force |= REDRAW_COMPLETELY;
2749 		return 1;
2750 	    } else {
2751 		free (exp);
2752 		edit_error_dialog (_ (" Insert file "), get_sys_error (_ (" Error trying to insert file. ")));
2753 		edit->force |= REDRAW_COMPLETELY;
2754 		return 0;
2755 	    }
2756 	}
2757     }
2758     edit->force |= REDRAW_COMPLETELY;
2759     return 0;
2760 }
2761 
2762 #ifdef MIDNIGHT
2763 
2764 /* sorts a block, returns -1 on system fail, 1 on cancel and 0 on success */
2765 int edit_sort_cmd (WEdit * edit)
2766 {
2767     static char *old = 0;
2768     char *exp;
2769     long start_mark, end_mark;
2770     int e;
2771 
2772     if (eval_marks (edit, &start_mark, &end_mark)) {
2773 /* Not essential to translate */
2774 	edit_error_dialog (_(" Sort block "), _(" You must first highlight a block of text. "));
2775 	return 0;
2776     }
2777     edit_save_block (edit, catstrs (home_dir, BLOCK_FILE, NULL), start_mark, end_mark);
2778 
2779     exp = old ? old : "";
2780 
2781     exp = input_dialog (_(" Run Sort "),
2782 /* Not essential to translate */
2783     _(" Enter sort options (see manpage) separated by whitespace: "), "");
2784 
2785     if (!exp)
2786 	return 1;
2787     if (old)
2788 	free (old);
2789     old = exp;
2790 
2791     e = system (catstrs (" sort ", exp, " ", home_dir, BLOCK_FILE, " > ", home_dir, TEMP_FILE, NULL));
2792     if (e) {
2793 	if (e == -1 || e == 127) {
2794 	    edit_error_dialog (_(" Sort "),
2795 /* Not essential to translate */
2796 	    get_sys_error (_(" Error trying to execute sort command ")));
2797 	} else {
2798 	    char q[8];
2799 	    sprintf (q, "%d ", e);
2800 	    edit_error_dialog (_(" Sort "),
2801 /* Not essential to translate */
2802 	    catstrs (_(" Sort returned non-zero: "), q, NULL));
2803 	}
2804 	return -1;
2805     }
2806 
2807     edit->force |= REDRAW_COMPLETELY;
2808 
2809     if (edit_block_delete_cmd (edit))
2810 	return 1;
2811     edit_insert_file (edit, catstrs (home_dir, TEMP_FILE, NULL));
2812     return 0;
2813 }
2814 
2815 /* if block is 1, a block must be highlighted and the shell command
2816    processes it. If block is 0 the shell command is a straight system
2817    command, that just produces some output which is to be inserted */
2818 void edit_block_process_cmd (WEdit * edit, const char *shell_cmd, int block)
2819 {
2820     long start_mark, end_mark;
2821     struct stat s;
2822     char *f = NULL, *b = NULL;
2823 
2824     if (block) {
2825 	if (eval_marks (edit, &start_mark, &end_mark)) {
2826 	    edit_error_dialog (_(" Process block "),
2827 /* Not essential to translate */
2828 		_(" You must first highlight a block of text. "));
2829 	    return;
2830 	}
2831 	edit_save_block (edit, b = catstrs (home_dir, BLOCK_FILE, NULL), start_mark, end_mark);
2832 	my_system (0, shell, catstrs (home_dir, shell_cmd, NULL));
2833 	edit_refresh_cmd (edit);
2834     } else {
2835 	my_system (0, shell, shell_cmd);
2836 	edit_refresh_cmd (edit);
2837     }
2838 
2839     edit->force |= REDRAW_COMPLETELY;
2840 
2841     f = catstrs (home_dir, ERROR_FILE, NULL);
2842 
2843     if (block) {
2844 	if (stat (f, &s) == 0) {
2845 	    if (!s.st_size) {	/* no error messages */
2846 		if (edit_block_delete_cmd (edit))
2847 		    return;
2848 		edit_insert_file (edit, b);
2849 		return;
2850 	    } else {
2851 		edit_insert_file (edit, f);
2852 		return;
2853 	    }
2854 	} else {
2855 /* Not essential to translate */
2856 	    edit_error_dialog (_(" Process block "),
2857 /* Not essential to translate */
2858 	    get_sys_error (_(" Error trying to stat file ")));
2859 	    edit->force |= REDRAW_COMPLETELY;
2860 	    return;
2861 	}
2862     }
2863 }
2864 
2865 #endif
2866 
2867 int edit_execute_cmd (WEdit * edit, int command, int char_for_insertion);
2868 
2869 /* prints at the cursor */
2870 /* returns the number of chars printed */
2871 int edit_print_string (WEdit * e, const char *s)
2872 {
2873     int i = 0;
2874     while (s[i])
2875 	edit_execute_cmd (e, -1, (unsigned char) s[i++]);
2876     e->force |= REDRAW_COMPLETELY;
2877     edit_update_screen (e);
2878     return i;
2879 }
2880 
2881 int edit_printf (WEdit * e, const char *fmt,...)
2882 {
2883     int i;
2884     va_list pa;
2885     char s[1024];
2886     va_start (pa, fmt);
2887     vsprintf (s, fmt, pa);
2888     i = edit_print_string (e, s);
2889     va_end (pa);
2890     return i;
2891 }
2892 
2893 #ifdef MIDNIGHT
2894 
2895 /* FIXME: does this function break NT_OS2 ? */
2896 
2897 static void pipe_mail (WEdit *edit, char *to, char *subject, char *cc)
2898 {
2899     FILE *p;
2900     char *s;
2901     s = malloc (4096);
2902     sprintf (s, "mail -s \"%s\" -c \"%s\" \"%s\"", subject, cc, to);
2903     p = popen (s, "w");
2904     if (!p) {
2905 	free (s);
2906 	return;
2907     } else {
2908 	long i;
2909 	for (i = 0; i < edit->last_byte; i++)
2910 	    fputc (edit_get_byte (edit, i), p);
2911 	pclose (p);
2912     }
2913     free (s);
2914 }
2915 
2916 #define MAIL_DLG_HEIGHT 12
2917 
2918 void edit_mail_dialog (WEdit * edit)
2919 {
2920     char *tmail_to;
2921     char *tmail_subject;
2922     char *tmail_cc;
2923 
2924     static char *mail_cc_last = 0;
2925     static char *mail_subject_last = 0;
2926     static char *mail_to_last = 0;
2927 
2928     QuickDialog Quick_input =
2929     {50, MAIL_DLG_HEIGHT, -1, 0, N_(" Mail "),
2930 /* NLS ? */
2931      "[Input Line Keys]", "quick_input", 0};
2932 
2933     QuickWidget quick_widgets[] =
2934     {
2935 /* NLS ? */
2936 	{quick_button, 6, 10, 9, MAIL_DLG_HEIGHT, N_("&Cancel"), 0, B_CANCEL, 0,
2937 	 0, XV_WLAY_DONTCARE, NULL},
2938 	{quick_button, 2, 10, 9, MAIL_DLG_HEIGHT, N_("&Ok"), 0, B_ENTER, 0,
2939 	 0, XV_WLAY_DONTCARE, NULL},
2940 	{quick_input, 3, 50, 8, MAIL_DLG_HEIGHT, "", 44, 0, 0,
2941 	 0, XV_WLAY_BELOWCLOSE, "mail-dlg-input"},
2942 	{quick_label, 2, 50, 7, MAIL_DLG_HEIGHT, N_(" Copies to"), 0, 0, 0,
2943 	 0, XV_WLAY_DONTCARE, 0},
2944 	{quick_input, 3, 50, 6, MAIL_DLG_HEIGHT, "", 44, 0, 0,
2945 	 0, XV_WLAY_BELOWCLOSE, "mail-dlg-input-2"},
2946 	{quick_label, 2, 50, 5, MAIL_DLG_HEIGHT, N_(" Subject"), 0, 0, 0,
2947 	 0, XV_WLAY_DONTCARE, 0},
2948 	{quick_input, 3, 50, 4, MAIL_DLG_HEIGHT, "", 44, 0, 0,
2949 	 0, XV_WLAY_BELOWCLOSE, "mail-dlg-input-3"},
2950 	{quick_label, 2, 50, 3, MAIL_DLG_HEIGHT, N_(" To"), 0, 0, 0,
2951 	 0, XV_WLAY_DONTCARE, 0},
2952 	{quick_label, 2, 50, 2, MAIL_DLG_HEIGHT, N_(" mail -s <subject> -c <cc> <to>"), 0, 0, 0,
2953 	 0, XV_WLAY_DONTCARE, 0},
2954 	{0}};
2955 
2956     quick_widgets[2].str_result = &tmail_cc;
2957     quick_widgets[2].text = mail_cc_last ? mail_cc_last : "";
2958     quick_widgets[4].str_result = &tmail_subject;
2959     quick_widgets[4].text = mail_subject_last ? mail_subject_last : "";
2960     quick_widgets[6].str_result = &tmail_to;
2961     quick_widgets[6].text = mail_to_last ? mail_to_last : "";
2962 
2963     Quick_input.widgets = quick_widgets;
2964 
2965     if (quick_dialog (&Quick_input) != B_CANCEL) {
2966 	if (mail_cc_last)
2967 	    free (mail_cc_last);
2968 	if (mail_subject_last)
2969 	    free (mail_subject_last);
2970 	if (mail_to_last)
2971 	    free (mail_to_last);
2972 	mail_cc_last = *(quick_widgets[2].str_result);
2973 	mail_subject_last = *(quick_widgets[4].str_result);
2974 	mail_to_last = *(quick_widgets[6].str_result);
2975 	pipe_mail (edit, mail_to_last, mail_subject_last, mail_cc_last);
2976     }
2977 }
2978 
2979 #endif
2980 
2981