Ticket #2695: fixed segfault on newly created files in editor
[midnight-commander.git] / src / editor / editcmd.c
blobcd06b8de8abab287df1c330f1180f616a31872ca
1 /*
2 Editor high level editing commands
4 Copyright (C) 1996, 1997, 1998, 2001, 2002, 2003, 2004, 2005, 2006,
5 2007, 2011
6 The Free Software Foundation, Inc.
8 Written by:
9 Paul Sheer, 1996, 1997
11 This file is part of the Midnight Commander.
13 The Midnight Commander is free software: you can redistribute it
14 and/or modify it under the terms of the GNU General Public License as
15 published by the Free Software Foundation, either version 3 of the License,
16 or (at your option) any later version.
18 The Midnight Commander is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 GNU General Public License for more details.
23 You should have received a copy of the GNU General Public License
24 along with this program. If not, see <http://www.gnu.org/licenses/>.
27 /** \file
28 * \brief Source: editor high level editing commands
29 * \author Paul Sheer
30 * \date 1996, 1997
33 /* #define PIPE_BLOCKS_SO_READ_BYTE_BY_BYTE */
35 #include <config.h>
37 #include <assert.h>
38 #include <ctype.h>
40 #include <stdio.h>
41 #include <stdarg.h>
42 #include <sys/types.h>
43 #include <unistd.h>
44 #include <string.h>
45 #include <errno.h>
46 #include <sys/stat.h>
47 #include <stdlib.h>
48 #include <fcntl.h>
50 #include "lib/global.h"
51 #include "lib/tty/tty.h"
52 #include "lib/tty/key.h" /* XCTRL */
53 #include "lib/mcconfig.h"
54 #include "lib/skin.h"
55 #include "lib/strutil.h" /* utf string functions */
56 #include "lib/lock.h"
57 #include "lib/util.h" /* tilde_expand() */
58 #include "lib/vfs/vfs.h"
59 #include "lib/widget.h"
60 #include "lib/charsets.h"
61 #include "lib/event.h" /* mc_event_raise() */
63 #include "src/history.h"
64 #include "src/setup.h" /* option_tab_spacing */
65 #include "src/main.h" /* mactos_t */
66 #include "src/selcodepage.h"
67 #include "src/keybind-defaults.h"
68 #include "src/util.h" /* check_for_default() */
69 #include "src/filemanager/layout.h" /* mc_refresh() */
71 #include "edit-impl.h"
72 #include "edit-widget.h"
73 #include "editcmd_dialogs.h"
74 #include "etags.h"
76 /*** global variables ****************************************************************************/
78 /* search and replace: */
79 int search_create_bookmark = FALSE;
81 /* queries on a save */
82 int edit_confirm_save = 1;
84 /*** file scope macro definitions ****************************************************************/
86 #define space_width 1
88 #define TEMP_BUF_LEN 1024
90 #define INPUT_INDEX 9
92 /* thanks to Liviu Daia <daia@stoilow.imar.ro> for getting this
93 (and the above) routines to work properly - paul */
95 #define is_digit(x) ((x) >= '0' && (x) <= '9')
97 #define MAIL_DLG_HEIGHT 12
99 #define MAX_WORD_COMPLETIONS 100 /* in listbox */
101 /*** file scope type declarations ****************************************************************/
103 /*** file scope variables ************************************************************************/
105 /*** file scope functions ************************************************************************/
106 /* --------------------------------------------------------------------------------------------- */
108 /* If 0 (quick save) then a) create/truncate <filename> file,
109 b) save to <filename>;
110 if 1 (safe save) then a) save to <tempnam>,
111 b) rename <tempnam> to <filename>;
112 if 2 (do backups) then a) save to <tempnam>,
113 b) rename <filename> to <filename.backup_ext>,
114 c) rename <tempnam> to <filename>. */
116 /* returns 0 on error, -1 on abort */
118 static int
119 edit_save_file (WEdit * edit, const vfs_path_t * filename_vpath)
121 char *p;
122 gchar *tmp;
123 long filelen = 0;
124 int this_save_mode, fd = -1;
125 vfs_path_t *real_filename_vpath;
126 vfs_path_t *savename_vpath = NULL;
127 const char *start_filename;
128 const vfs_path_element_t *vpath_element;
130 vpath_element = vfs_path_get_by_index (filename_vpath, 0);
131 if (vpath_element == NULL)
132 return 0;
134 start_filename = vpath_element->path;
135 if (*start_filename == '\0')
136 return 0;
138 if (*start_filename != PATH_SEP && edit->dir_vpath != NULL)
140 real_filename_vpath = vfs_path_append_vpath_new (edit->dir_vpath, filename_vpath, NULL);
142 else
144 real_filename_vpath = vfs_path_clone (filename_vpath);
147 this_save_mode = option_save_mode;
148 if (this_save_mode != EDIT_QUICK_SAVE)
150 if (!vfs_file_is_local (real_filename_vpath)
151 || (fd = mc_open (real_filename_vpath, O_RDONLY | O_BINARY)) == -1)
154 * The file does not exists yet, so no safe save or
155 * backup are necessary.
157 this_save_mode = EDIT_QUICK_SAVE;
159 if (fd != -1)
160 mc_close (fd);
163 if (this_save_mode == EDIT_QUICK_SAVE && !edit->skip_detach_prompt)
165 int rv;
166 struct stat sb;
168 rv = mc_stat (real_filename_vpath, &sb);
169 if (rv == 0 && sb.st_nlink > 1)
171 rv = edit_query_dialog3 (_("Warning"),
172 _("File has hard-links. Detach before saving?"),
173 _("&Yes"), _("&No"), _("&Cancel"));
174 switch (rv)
176 case 0:
177 this_save_mode = EDIT_SAFE_SAVE;
178 /* fallthrough */
179 case 1:
180 edit->skip_detach_prompt = 1;
181 break;
182 default:
183 vfs_path_free (real_filename_vpath);
184 return -1;
188 /* Prevent overwriting changes from other editor sessions. */
189 if (rv == 0 && edit->stat1.st_mtime != 0 && edit->stat1.st_mtime != sb.st_mtime)
191 /* The default action is "Cancel". */
192 query_set_sel (1);
194 rv = edit_query_dialog2 (_("Warning"),
195 _("The file has been modified in the meantime. Save anyway?"),
196 _("&Yes"), _("&Cancel"));
197 if (rv != 0)
199 vfs_path_free (real_filename_vpath);
200 return -1;
205 if (this_save_mode != EDIT_QUICK_SAVE)
207 char *savedir, *saveprefix;
209 savedir = vfs_path_tokens_get (real_filename_vpath, 0, -1);
210 if (savedir == NULL)
211 savedir = g_strdup (".");
213 saveprefix = mc_build_filename (savedir, "cooledit", NULL);
214 g_free (savedir);
215 fd = mc_mkstemps (&savename_vpath, saveprefix, NULL);
216 g_free (saveprefix);
217 if (savename_vpath == NULL)
219 vfs_path_free (real_filename_vpath);
220 return 0;
222 /* FIXME:
223 * Close for now because mc_mkstemps use pure open system call
224 * to create temporary file and it needs to be reopened by
225 * VFS-aware mc_open().
227 close (fd);
229 else
230 savename_vpath = vfs_path_clone (real_filename_vpath);
232 (void) mc_chown (savename_vpath, edit->stat1.st_uid, edit->stat1.st_gid);
233 (void) mc_chmod (savename_vpath, edit->stat1.st_mode);
235 fd = mc_open (savename_vpath, O_CREAT | O_WRONLY | O_TRUNC | O_BINARY, edit->stat1.st_mode);
236 if (fd == -1)
237 goto error_save;
239 /* pipe save */
240 p = edit_get_write_filter (savename_vpath, real_filename_vpath);
241 if (p != NULL)
243 FILE *file;
245 mc_close (fd);
246 file = (FILE *) popen (p, "w");
248 if (file)
250 filelen = edit_write_stream (edit, file);
251 #if 1
252 pclose (file);
253 #else
254 if (pclose (file) != 0)
256 tmp = g_strdup_printf (_("Error writing to pipe: %s"), p);
257 edit_error_dialog (_("Error"), tmp);
258 g_free (tmp);
259 g_free (p);
260 goto error_save;
262 #endif
264 else
266 tmp = g_strdup_printf (_("Cannot open pipe for writing: %s"), p);
267 edit_error_dialog (_("Error"), get_sys_error (tmp));
268 g_free (p);
269 g_free (tmp);
270 goto error_save;
272 g_free (p);
274 else if (edit->lb == LB_ASIS)
275 { /* do not change line breaks */
276 long buf;
277 buf = 0;
278 filelen = edit->last_byte;
279 while (buf <= (edit->curs1 >> S_EDIT_BUF_SIZE) - 1)
281 if (mc_write (fd, (char *) edit->buffers1[buf], EDIT_BUF_SIZE) != EDIT_BUF_SIZE)
283 mc_close (fd);
284 goto error_save;
286 buf++;
288 if (mc_write
289 (fd, (char *) edit->buffers1[buf],
290 edit->curs1 & M_EDIT_BUF_SIZE) != (edit->curs1 & M_EDIT_BUF_SIZE))
292 filelen = -1;
294 else if (edit->curs2)
296 edit->curs2--;
297 buf = (edit->curs2 >> S_EDIT_BUF_SIZE);
298 if (mc_write
299 (fd,
300 (char *) edit->buffers2[buf] + EDIT_BUF_SIZE -
301 (edit->curs2 & M_EDIT_BUF_SIZE) - 1,
302 1 + (edit->curs2 & M_EDIT_BUF_SIZE)) != 1 + (edit->curs2 & M_EDIT_BUF_SIZE))
304 filelen = -1;
306 else
308 while (--buf >= 0)
310 if (mc_write (fd, (char *) edit->buffers2[buf], EDIT_BUF_SIZE) != EDIT_BUF_SIZE)
312 filelen = -1;
313 break;
317 edit->curs2++;
319 if (mc_close (fd))
320 goto error_save;
322 /* Update the file information, especially the mtime. */
323 if (mc_stat (savename_vpath, &edit->stat1) == -1)
324 goto error_save;
326 else
327 { /* change line breaks */
328 FILE *file;
329 const vfs_path_element_t *path_element;
331 mc_close (fd);
333 path_element = vfs_path_get_by_index (savename_vpath, -1);
334 file = (FILE *) fopen (path_element->path, "w");
335 if (file != NULL)
337 filelen = edit_write_stream (edit, file);
338 fclose (file);
340 else
342 char *msg;
344 msg = g_strdup_printf (_("Cannot open file for writing: %s"), path_element->path);
345 edit_error_dialog (_("Error"), msg);
346 g_free (msg);
347 goto error_save;
351 if (filelen != edit->last_byte)
352 goto error_save;
354 if (this_save_mode == EDIT_DO_BACKUP)
356 vfs_path_t *tmp_vpath;
357 gboolean ok;
359 assert (option_backup_ext != NULL);
360 tmp_vpath = vfs_path_append_new (real_filename_vpath, option_backup_ext, (char *) NULL);
361 ok = (mc_rename (real_filename_vpath, tmp_vpath) != -1);
362 vfs_path_free (tmp_vpath);
363 if (!ok)
364 goto error_save;
367 if (this_save_mode != EDIT_QUICK_SAVE)
368 if (mc_rename (savename_vpath, real_filename_vpath) == -1)
369 goto error_save;
371 vfs_path_free (real_filename_vpath);
372 vfs_path_free (savename_vpath);
373 return 1;
374 error_save:
375 /* FIXME: Is this safe ?
376 * if (this_save_mode != EDIT_QUICK_SAVE)
377 * mc_unlink (savename);
379 vfs_path_free (real_filename_vpath);
380 vfs_path_free (savename_vpath);
381 return 0;
384 /* --------------------------------------------------------------------------------------------- */
386 static gboolean
387 edit_check_newline (WEdit * edit)
389 return !(option_check_nl_at_eof && edit->last_byte > 0
390 && edit_get_byte (edit, edit->last_byte - 1) != '\n'
391 && edit_query_dialog2 (_("Warning"),
392 _("The file you are saving is not finished with a newline"),
393 _("C&ontinue"), _("&Cancel")));
396 /* --------------------------------------------------------------------------------------------- */
398 static vfs_path_t *
399 edit_get_save_file_as (WEdit * edit)
401 #define DLG_WIDTH 64
402 #define DLG_HEIGHT 14
404 static LineBreaks cur_lb = LB_ASIS;
406 char *filename = vfs_path_to_str (edit->filename_vpath);
407 char *filename_res;
409 const char *lb_names[LB_NAMES] = {
410 N_("&Do not change"),
411 N_("&Unix format (LF)"),
412 N_("&Windows/DOS format (CR LF)"),
413 N_("&Macintosh format (CR)")
416 QuickWidget quick_widgets[] = {
417 QUICK_BUTTON (6, 10, DLG_HEIGHT - 3, DLG_HEIGHT, N_("&Cancel"), B_CANCEL, NULL),
418 QUICK_BUTTON (2, 10, DLG_HEIGHT - 3, DLG_HEIGHT, N_("&OK"), B_ENTER, NULL),
419 QUICK_RADIO (5, DLG_WIDTH, DLG_HEIGHT - 8, DLG_HEIGHT, LB_NAMES, lb_names, (int *) &cur_lb),
420 QUICK_LABEL (3, DLG_WIDTH, DLG_HEIGHT - 9, DLG_HEIGHT, N_("Change line breaks to:")),
421 QUICK_INPUT (3, DLG_WIDTH, DLG_HEIGHT - 11, DLG_HEIGHT, filename, DLG_WIDTH - 6, 0,
422 "save-as", &filename_res),
423 QUICK_LABEL (3, DLG_WIDTH, DLG_HEIGHT - 12, DLG_HEIGHT, N_("Enter file name:")),
424 QUICK_END
427 QuickDialog Quick_options = {
428 DLG_WIDTH, DLG_HEIGHT, -1, -1,
429 N_("Save As"), "[Save File As]",
430 quick_widgets, NULL, FALSE
433 if (quick_dialog (&Quick_options) != B_CANCEL)
435 char *fname;
436 vfs_path_t *ret_vpath;
438 edit->lb = cur_lb;
439 fname = tilde_expand (filename_res);
440 g_free (filename_res);
441 ret_vpath = vfs_path_from_str (fname);
442 g_free (fname);
443 return ret_vpath;
445 g_free (filename);
447 return NULL;
449 #undef DLG_WIDTH
450 #undef DLG_HEIGHT
453 /* --------------------------------------------------------------------------------------------- */
455 /** returns 1 on success */
457 static int
458 edit_save_cmd (WEdit * edit)
460 int res, save_lock = 0;
462 if (!edit->locked && !edit->delete_file)
463 save_lock = lock_file (edit->filename_vpath);
464 res = edit_save_file (edit, edit->filename_vpath);
466 /* Maintain modify (not save) lock on failure */
467 if ((res > 0 && edit->locked) || save_lock)
468 edit->locked = unlock_file (edit->filename_vpath);
470 /* On failure try 'save as', it does locking on its own */
471 if (!res)
472 return edit_save_as_cmd (edit);
473 edit->force |= REDRAW_COMPLETELY;
474 if (res > 0)
476 edit->delete_file = 0;
477 edit->modified = 0;
480 return 1;
483 /* --------------------------------------------------------------------------------------------- */
484 /** returns 1 on error */
486 static int
487 edit_load_file_from_filename (WEdit * edit, const vfs_path_t * exp_vpath)
489 int prev_locked = edit->locked;
490 vfs_path_t *prev_filename;
492 prev_filename = vfs_path_clone (edit->filename_vpath);
493 if (!edit_reload (edit, exp_vpath))
495 vfs_path_free (prev_filename);
496 return 1;
499 if (prev_locked)
501 vfs_path_t *fullpath;
503 fullpath = vfs_path_append_vpath_new (edit->dir_vpath, prev_filename, (char *) NULL);
504 unlock_file (fullpath);
505 vfs_path_free (fullpath);
507 vfs_path_free (prev_filename);
508 return 0;
511 /* --------------------------------------------------------------------------------------------- */
513 static void
514 edit_load_syntax_file (WEdit * edit)
516 vfs_path_t *extdir_vpath;
517 int dir = 0;
519 if (geteuid () == 0)
521 dir = query_dialog (_("Syntax file edit"),
522 _("Which syntax file you want to edit?"), D_NORMAL, 2,
523 _("&User"), _("&System Wide"));
526 extdir_vpath =
527 vfs_path_build_filename (mc_global.sysconfig_dir, "syntax", "Syntax", (char *) NULL);
528 if (!exist_file (vfs_path_get_last_path_str (extdir_vpath)))
530 vfs_path_free (extdir_vpath);
531 extdir_vpath =
532 vfs_path_build_filename (mc_global.share_data_dir, "syntax", "Syntax", (char *) NULL);
535 if (dir == 0)
537 vfs_path_t *user_syntax_file_vpath;
539 user_syntax_file_vpath = mc_config_get_full_vpath (EDIT_SYNTAX_FILE);
540 check_for_default (extdir_vpath, user_syntax_file_vpath);
541 edit_load_file_from_filename (edit, user_syntax_file_vpath);
542 vfs_path_free (user_syntax_file_vpath);
544 else if (dir == 1)
545 edit_load_file_from_filename (edit, extdir_vpath);
547 vfs_path_free (extdir_vpath);
550 /* --------------------------------------------------------------------------------------------- */
552 static void
553 edit_load_menu_file (WEdit * edit)
555 vfs_path_t *buffer_vpath;
556 vfs_path_t *menufile_vpath;
557 int dir = 0;
559 dir = query_dialog (_("Menu edit"),
560 _("Which menu file do you want to edit?"), D_NORMAL,
561 geteuid () != 0 ? 2 : 3, _("&Local"), _("&User"), _("&System Wide"));
563 menufile_vpath = vfs_path_build_filename (mc_global.sysconfig_dir, EDIT_GLOBAL_MENU, NULL);
565 if (!exist_file (vfs_path_get_last_path_str (menufile_vpath)))
567 vfs_path_free (menufile_vpath);
568 menufile_vpath = vfs_path_build_filename (mc_global.share_data_dir, EDIT_GLOBAL_MENU, NULL);
571 switch (dir)
573 case 0:
574 buffer_vpath = vfs_path_from_str (EDIT_LOCAL_MENU);
575 check_for_default (menufile_vpath, buffer_vpath);
576 chmod (vfs_path_get_last_path_str (buffer_vpath), 0600);
577 break;
579 case 1:
580 buffer_vpath = mc_config_get_full_vpath (EDIT_HOME_MENU);
581 check_for_default (menufile_vpath, buffer_vpath);
582 break;
584 case 2:
585 buffer_vpath = vfs_path_build_filename (mc_global.sysconfig_dir, EDIT_GLOBAL_MENU, NULL);
586 if (!exist_file (vfs_path_get_last_path_str (buffer_vpath)))
588 vfs_path_free (buffer_vpath);
589 buffer_vpath =
590 vfs_path_build_filename (mc_global.share_data_dir, EDIT_GLOBAL_MENU, NULL);
592 break;
594 default:
595 vfs_path_free (menufile_vpath);
596 return;
599 edit_load_file_from_filename (edit, buffer_vpath);
601 vfs_path_free (buffer_vpath);
602 vfs_path_free (menufile_vpath);
605 /* --------------------------------------------------------------------------------------------- */
607 static void
608 edit_delete_column_of_text (WEdit * edit)
610 long p, q, r, m1, m2;
611 long b, c, d, n;
613 eval_marks (edit, &m1, &m2);
614 n = edit_move_forward (edit, m1, 0, m2) + 1;
615 c = edit_move_forward3 (edit, edit_bol (edit, m1), 0, m1);
616 d = edit_move_forward3 (edit, edit_bol (edit, m2), 0, m2);
617 b = max (min (c, d), min (edit->column1, edit->column2));
618 c = max (c, max (edit->column1, edit->column2));
620 while (n--)
622 r = edit_bol (edit, edit->curs1);
623 p = edit_move_forward3 (edit, r, b, 0);
624 q = edit_move_forward3 (edit, r, c, 0);
625 if (p < m1)
626 p = m1;
627 if (q > m2)
628 q = m2;
629 edit_cursor_move (edit, p - edit->curs1);
630 while (q > p)
632 /* delete line between margins */
633 if (edit_get_byte (edit, edit->curs1) != '\n')
634 edit_delete (edit, 1);
635 q--;
637 if (n)
638 /* move to next line except on the last delete */
639 edit_cursor_move (edit, edit_move_forward (edit, edit->curs1, 1, 0) - edit->curs1);
643 /* --------------------------------------------------------------------------------------------- */
644 /** if success return 0 */
646 static int
647 edit_block_delete (WEdit * edit)
649 long count;
650 long start_mark, end_mark;
651 int curs_pos, line_width;
652 long curs_line, c1, c2;
654 if (eval_marks (edit, &start_mark, &end_mark))
655 return 0;
656 if (edit->column_highlight && edit->mark2 < 0)
657 edit_mark_cmd (edit, 0);
658 if ((end_mark - start_mark) > option_max_undo / 2)
660 /* Warning message with a query to continue or cancel the operation */
661 if (edit_query_dialog2
662 (_("Warning"),
664 ("Block is large, you may not be able to undo this action"),
665 _("C&ontinue"), _("&Cancel")))
667 return 1;
670 c1 = min (edit->column1, edit->column2);
671 c2 = max (edit->column1, edit->column2);
672 edit->column1 = c1;
673 edit->column2 = c2;
675 edit_push_markers (edit);
677 curs_line = edit->curs_line;
679 /* calculate line width and cursor position before cut */
680 line_width = edit_move_forward3 (edit, edit_bol (edit, edit->curs1), 0,
681 edit_eol (edit, edit->curs1));
682 curs_pos = edit->curs_col + edit->over_col;
684 /* move cursor to start of selection */
685 edit_cursor_move (edit, start_mark - edit->curs1);
686 edit_scroll_screen_over_cursor (edit);
687 count = start_mark;
688 if (start_mark < end_mark)
690 if (edit->column_highlight)
692 if (edit->mark2 < 0)
693 edit_mark_cmd (edit, 0);
694 edit_delete_column_of_text (edit);
695 /* move cursor to the saved position */
696 edit_move_to_line (edit, curs_line);
697 /* calculate line width after cut */
698 line_width = edit_move_forward3 (edit, edit_bol (edit, edit->curs1), 0,
699 edit_eol (edit, edit->curs1));
700 if (option_cursor_beyond_eol && curs_pos > line_width)
701 edit->over_col = curs_pos - line_width;
703 else
705 while (count < end_mark)
707 edit_delete (edit, 1);
708 count++;
712 edit_set_markers (edit, 0, 0, 0, 0);
713 edit->force |= REDRAW_PAGE;
714 return 0;
717 /* --------------------------------------------------------------------------------------------- */
719 static gboolean
720 editcmd_find (WEdit * edit, gsize * len)
722 off_t search_start = edit->search_start;
723 off_t search_end;
724 long start_mark = 0;
725 long end_mark = edit->last_byte;
726 int mark_res = 0;
728 if (edit_search_options.only_in_selection)
730 mark_res = eval_marks (edit, &start_mark, &end_mark);
731 if (mark_res != 0)
733 edit->search->error = MC_SEARCH_E_NOTFOUND;
734 edit->search->error_str = g_strdup (_("Search string not found"));
735 return FALSE;
737 if (edit_search_options.backwards)
739 if (search_start > end_mark || search_start <= start_mark)
741 search_start = end_mark;
744 else
746 if (search_start < start_mark || search_start >= end_mark)
748 search_start = start_mark;
752 else
754 if (edit_search_options.backwards)
755 end_mark = max (1, edit->curs1) - 1;
757 if (edit_search_options.backwards)
759 search_end = end_mark;
760 while ((int) search_start >= start_mark)
762 if (search_end > (off_t) (search_start + edit->search->original_len) &&
763 mc_search_is_fixed_search_str (edit->search))
765 search_end = search_start + edit->search->original_len;
767 if (mc_search_run (edit->search, (void *) edit, search_start, search_end, len)
768 && edit->search->normal_offset == search_start)
770 return TRUE;
772 search_start--;
774 edit->search->error_str = g_strdup (_("Search string not found"));
776 else
778 return mc_search_run (edit->search, (void *) edit, search_start, end_mark, len);
780 return FALSE;
783 /* --------------------------------------------------------------------------------------------- */
785 static char *
786 edit_replace_cmd__conv_to_display (char *str)
788 #ifdef HAVE_CHARSET
789 GString *tmp;
791 tmp = str_convert_to_display (str);
792 if (tmp != NULL)
794 if (tmp->len != 0)
795 return g_string_free (tmp, FALSE);
796 g_string_free (tmp, TRUE);
798 #endif
799 return g_strdup (str);
802 /* --------------------------------------------------------------------------------------------- */
804 static char *
805 edit_replace_cmd__conv_to_input (char *str)
807 #ifdef HAVE_CHARSET
808 GString *tmp;
810 tmp = str_convert_to_input (str);
811 if (tmp != NULL)
813 if (tmp->len != 0)
814 return g_string_free (tmp, FALSE);
815 g_string_free (tmp, TRUE);
817 #endif
818 return g_strdup (str);
821 /* --------------------------------------------------------------------------------------------- */
823 static void
824 edit_do_search (WEdit * edit)
826 gsize len = 0;
828 if (edit->search == NULL)
829 edit->search_start = edit->curs1;
831 edit_push_undo_action (edit, KEY_PRESS + edit->start_display);
833 if (search_create_bookmark)
835 int found = 0, books = 0;
836 long l = 0, l_last = -1;
837 long q = 0;
839 search_create_bookmark = FALSE;
840 book_mark_flush (edit, -1);
842 while (TRUE)
844 if (!mc_search_run (edit->search, (void *) edit, q, edit->last_byte, &len))
845 break;
846 if (found == 0)
847 edit->search_start = edit->search->normal_offset;
848 found++;
849 l += edit_count_lines (edit, q, edit->search->normal_offset);
850 if (l != l_last)
852 book_mark_insert (edit, l, BOOK_MARK_FOUND_COLOR);
853 books++;
855 l_last = l;
856 q = edit->search->normal_offset + 1;
859 if (found == 0)
860 edit_error_dialog (_("Search"), _("Search string not found"));
861 else
862 edit_cursor_move (edit, edit->search_start - edit->curs1);
864 else
866 if (edit->found_len != 0 && edit->search_start == edit->found_start + 1
867 && edit_search_options.backwards)
868 edit->search_start--;
870 if (edit->found_len != 0 && edit->search_start == edit->found_start - 1
871 && !edit_search_options.backwards)
872 edit->search_start++;
874 if (editcmd_find (edit, &len))
876 edit->found_start = edit->search_start = edit->search->normal_offset;
877 edit->found_len = len;
878 edit->over_col = 0;
879 edit_cursor_move (edit, edit->search_start - edit->curs1);
880 edit_scroll_screen_over_cursor (edit);
881 if (edit_search_options.backwards)
882 edit->search_start--;
883 else
884 edit->search_start++;
886 else
888 edit->search_start = edit->curs1;
889 if (edit->search->error_str != NULL)
890 edit_error_dialog (_("Search"), edit->search->error_str);
894 edit->force |= REDRAW_COMPLETELY;
895 edit_scroll_screen_over_cursor (edit);
898 /* --------------------------------------------------------------------------------------------- */
900 static void
901 edit_search (WEdit * edit)
903 if (editcmd_dialog_search_show (edit))
904 edit_do_search (edit);
907 /* --------------------------------------------------------------------------------------------- */
908 /** Return a null terminated length of text. Result must be g_free'd */
910 static unsigned char *
911 edit_get_block (WEdit * edit, long start, long finish, int *l)
913 unsigned char *s, *r;
914 r = s = g_malloc0 (finish - start + 1);
915 if (edit->column_highlight)
917 *l = 0;
918 /* copy from buffer, excluding chars that are out of the column 'margins' */
919 while (start < finish)
921 int c;
922 long x;
923 x = edit_move_forward3 (edit, edit_bol (edit, start), 0, start);
924 c = edit_get_byte (edit, start);
925 if ((x >= edit->column1 && x < edit->column2)
926 || (x >= edit->column2 && x < edit->column1) || c == '\n')
928 *s++ = c;
929 (*l)++;
931 start++;
934 else
936 *l = finish - start;
937 while (start < finish)
938 *s++ = edit_get_byte (edit, start++);
940 *s = 0;
941 return r;
944 /* --------------------------------------------------------------------------------------------- */
945 /** copies a block to clipboard file */
947 static int
948 edit_save_block_to_clip_file (WEdit * edit, long start, long finish)
950 int ret;
951 gchar *tmp;
952 tmp = mc_config_get_full_path (EDIT_CLIP_FILE);
953 ret = edit_save_block (edit, tmp, start, finish);
954 g_free (tmp);
955 return ret;
958 /* --------------------------------------------------------------------------------------------- */
960 static void
961 pipe_mail (WEdit * edit, char *to, char *subject, char *cc)
963 FILE *p = 0;
964 char *s;
966 to = name_quote (to, 0);
967 subject = name_quote (subject, 0);
968 cc = name_quote (cc, 0);
969 s = g_strconcat ("mail -s ", subject, *cc ? " -c " : "", cc, " ", to, (char *) NULL);
970 g_free (to);
971 g_free (subject);
972 g_free (cc);
974 if (s)
976 p = popen (s, "w");
977 g_free (s);
980 if (p)
982 long i;
983 for (i = 0; i < edit->last_byte; i++)
984 fputc (edit_get_byte (edit, i), p);
985 pclose (p);
989 /* --------------------------------------------------------------------------------------------- */
991 static gboolean
992 is_break_char (char c)
994 return (isspace (c) || strchr ("{}[]()<>=|/\\!?~-+`'\",.;:#$%^&*", c));
997 /* --------------------------------------------------------------------------------------------- */
998 /** find first character of current word */
1000 static int
1001 edit_find_word_start (WEdit * edit, long *word_start, gsize * word_len)
1003 int c, last;
1004 gsize i;
1006 /* return if at begin of file */
1007 if (edit->curs1 <= 0)
1008 return 0;
1010 c = (unsigned char) edit_get_byte (edit, edit->curs1 - 1);
1011 /* return if not at end or in word */
1012 if (is_break_char (c))
1013 return 0;
1015 /* search start of word to be completed */
1016 for (i = 2;; i++)
1018 /* return if at begin of file */
1019 if ((gsize) edit->curs1 < i)
1020 return 0;
1022 last = c;
1023 c = (unsigned char) edit_get_byte (edit, edit->curs1 - i);
1025 if (is_break_char (c))
1027 /* return if word starts with digit */
1028 if (isdigit (last))
1029 return 0;
1031 *word_start = edit->curs1 - (i - 1); /* start found */
1032 *word_len = i - 1;
1033 break;
1036 /* success */
1037 return 1;
1040 /* --------------------------------------------------------------------------------------------- */
1042 * Get current word under cursor
1044 * @param edit editor object
1045 * @param srch mc_search object
1046 * @param word_start start word position
1048 * @return newly allocated string or NULL if no any words under cursor
1051 static char *
1052 edit_collect_completions_get_current_word (WEdit * edit, mc_search_t * srch, long word_start)
1054 gsize len = 0, i;
1055 GString *temp;
1057 if (!mc_search_run (srch, (void *) edit, word_start, edit->last_byte, &len))
1058 return NULL;
1060 temp = g_string_sized_new (len);
1062 for (i = 0; i < len; i++)
1064 int chr;
1066 chr = edit_get_byte (edit, word_start + i);
1067 if (!isspace (chr))
1068 g_string_append_c (temp, chr);
1071 return g_string_free (temp, temp->len == 0);
1074 /* --------------------------------------------------------------------------------------------- */
1075 /** collect the possible completions */
1077 static gsize
1078 edit_collect_completions (WEdit * edit, long word_start, gsize word_len,
1079 char *match_expr, struct selection *compl, gsize * num)
1081 gsize len = 0;
1082 gsize max_len = 0;
1083 gsize i;
1084 int skip;
1085 GString *temp;
1086 mc_search_t *srch;
1087 long last_byte, start = -1;
1088 char *current_word;
1090 srch = mc_search_new (match_expr, -1);
1091 if (srch == NULL)
1092 return 0;
1094 if (mc_config_get_bool
1095 (mc_main_config, CONFIG_APP_SECTION, "editor_wordcompletion_collect_entire_file", 0))
1097 last_byte = edit->last_byte;
1099 else
1101 last_byte = word_start;
1104 srch->search_type = MC_SEARCH_T_REGEX;
1105 srch->is_case_sensitive = TRUE;
1106 srch->search_fn = edit_search_cmd_callback;
1108 current_word = edit_collect_completions_get_current_word (edit, srch, word_start);
1110 temp = g_string_new ("");
1112 /* collect max MAX_WORD_COMPLETIONS completions */
1113 while (mc_search_run (srch, (void *) edit, start + 1, last_byte, &len))
1115 g_string_set_size (temp, 0);
1116 start = srch->normal_offset;
1118 /* add matched completion if not yet added */
1119 for (i = 0; i < len; i++)
1121 skip = edit_get_byte (edit, start + i);
1122 if (isspace (skip))
1123 continue;
1125 /* skip current word */
1126 if (start + (long) i == word_start)
1127 break;
1129 g_string_append_c (temp, skip);
1132 if (temp->len == 0)
1133 continue;
1135 if (current_word != NULL && strcmp (current_word, temp->str) == 0)
1136 continue;
1138 skip = 0;
1140 for (i = 0; i < *num; i++)
1142 if (strncmp
1143 ((char *) &compl[i].text[word_len],
1144 (char *) &temp->str[word_len], max (len, compl[i].len) - word_len) == 0)
1146 struct selection this = compl[i];
1147 for (++i; i < *num; i++)
1149 compl[i - 1] = compl[i];
1151 compl[*num - 1] = this;
1152 skip = 1;
1153 break; /* skip it, already added */
1156 if (skip != 0)
1157 continue;
1159 if (*num == MAX_WORD_COMPLETIONS)
1161 g_free (compl[0].text);
1162 for (i = 1; i < *num; i++)
1164 compl[i - 1] = compl[i];
1166 (*num)--;
1168 #ifdef HAVE_CHARSET
1170 GString *recoded;
1171 recoded = str_convert_to_display (temp->str);
1173 if (recoded && recoded->len)
1174 g_string_assign (temp, recoded->str);
1176 g_string_free (recoded, TRUE);
1178 #endif
1179 compl[*num].text = g_strdup (temp->str);
1180 compl[*num].len = temp->len;
1181 (*num)++;
1182 start += len;
1184 /* note the maximal length needed for the completion dialog */
1185 if (len > max_len)
1186 max_len = len;
1189 mc_search_free (srch);
1190 g_string_free (temp, TRUE);
1191 g_free (current_word);
1193 return max_len;
1196 /* --------------------------------------------------------------------------------------------- */
1198 static void
1199 edit_insert_column_of_text (WEdit * edit, unsigned char *data, int size, int width,
1200 long *start_pos, long *end_pos, int *col1, int *col2)
1202 long cursor;
1203 int i, col;
1205 cursor = edit->curs1;
1206 col = edit_get_col (edit);
1208 for (i = 0; i < size; i++)
1210 if (data[i] != '\n')
1211 edit_insert (edit, data[i]);
1212 else
1213 { /* fill in and move to next line */
1214 int l;
1215 long p;
1217 if (edit_get_byte (edit, edit->curs1) != '\n')
1219 l = width - (edit_get_col (edit) - col);
1220 while (l > 0)
1222 edit_insert (edit, ' ');
1223 l -= space_width;
1226 for (p = edit->curs1;; p++)
1228 if (p == edit->last_byte)
1230 edit_cursor_move (edit, edit->last_byte - edit->curs1);
1231 edit_insert_ahead (edit, '\n');
1232 p++;
1233 break;
1235 if (edit_get_byte (edit, p) == '\n')
1237 p++;
1238 break;
1241 edit_cursor_move (edit, edit_move_forward3 (edit, p, col, 0) - edit->curs1);
1242 l = col - edit_get_col (edit);
1243 while (l >= space_width)
1245 edit_insert (edit, ' ');
1246 l -= space_width;
1251 *col1 = col;
1252 *col2 = col + width;
1253 *start_pos = cursor;
1254 *end_pos = edit->curs1;
1255 edit_cursor_move (edit, cursor - edit->curs1);
1258 /* --------------------------------------------------------------------------------------------- */
1260 static int
1261 edit_macro_comparator (gconstpointer * macro1, gconstpointer * macro2)
1263 const macros_t *m1 = (const macros_t *) macro1;
1264 const macros_t *m2 = (const macros_t *) macro2;
1266 return m1->hotkey - m2->hotkey;
1269 /* --------------------------------------------------------------------------------------------- */
1271 static void
1272 edit_macro_sort_by_hotkey (void)
1274 if (macros_list != NULL && macros_list->len != 0)
1275 g_array_sort (macros_list, (GCompareFunc) edit_macro_comparator);
1278 /* --------------------------------------------------------------------------------------------- */
1280 static gboolean
1281 edit_get_macro (WEdit * edit, int hotkey, const macros_t ** macros, guint * indx)
1283 const macros_t *array_start = &g_array_index (macros_list, struct macros_t, 0);
1284 macros_t *result;
1285 macros_t search_macro;
1287 (void) edit;
1289 search_macro.hotkey = hotkey;
1290 result = bsearch (&search_macro, macros_list->data, macros_list->len,
1291 sizeof (macros_t), (GCompareFunc) edit_macro_comparator);
1293 if (result != NULL && result->macro != NULL)
1295 *indx = (result - array_start);
1296 *macros = result;
1297 return TRUE;
1299 *indx = 0;
1300 return FALSE;
1303 /* --------------------------------------------------------------------------------------------- */
1304 /** returns FALSE on error */
1306 static gboolean
1307 edit_delete_macro (WEdit * edit, int hotkey)
1309 mc_config_t *macros_config = NULL;
1310 const char *section_name = "editor";
1311 gchar *macros_fname;
1312 guint indx;
1313 char *skeyname;
1314 const macros_t *macros = NULL;
1316 /* clear array of actions for current hotkey */
1317 while (edit_get_macro (edit, hotkey, &macros, &indx))
1319 if (macros->macro != NULL)
1320 g_array_free (macros->macro, TRUE);
1321 macros = NULL;
1322 g_array_remove_index (macros_list, indx);
1323 edit_macro_sort_by_hotkey ();
1326 macros_fname = mc_config_get_full_path (MC_MACRO_FILE);
1327 macros_config = mc_config_init (macros_fname);
1328 g_free (macros_fname);
1330 if (macros_config == NULL)
1331 return FALSE;
1333 skeyname = lookup_key_by_code (hotkey);
1334 while (mc_config_del_key (macros_config, section_name, skeyname))
1336 g_free (skeyname);
1337 mc_config_save_file (macros_config, NULL);
1338 mc_config_deinit (macros_config);
1339 return TRUE;
1343 /* --------------------------------------------------------------------------------------------- */
1344 /*** public functions ****************************************************************************/
1345 /* --------------------------------------------------------------------------------------------- */
1347 void
1348 edit_help_cmd (WEdit * edit)
1350 ev_help_t event_data = { NULL, "[Internal File Editor]" };
1351 mc_event_raise (MCEVENT_GROUP_CORE, "help", &event_data);
1353 edit->force |= REDRAW_COMPLETELY;
1356 /* --------------------------------------------------------------------------------------------- */
1358 void
1359 edit_refresh_cmd (WEdit * edit)
1361 #ifdef HAVE_SLANG
1362 int color;
1364 edit_get_syntax_color (edit, -1, &color);
1365 tty_touch_screen ();
1366 mc_refresh ();
1367 #else
1368 (void) edit;
1370 clr_scr ();
1371 repaint_screen ();
1372 #endif /* !HAVE_SLANG */
1373 tty_keypad (TRUE);
1376 /* --------------------------------------------------------------------------------------------- */
1378 void
1379 menu_save_mode_cmd (void)
1381 /* diaog sizes */
1382 const int DLG_X = 38;
1383 const int DLG_Y = 13;
1385 char *str_result;
1387 const char *str[] = {
1388 N_("&Quick save"),
1389 N_("&Safe save"),
1390 N_("&Do backups with following extension:")
1393 QuickWidget widgets[] = {
1394 /* 0 */
1395 QUICK_BUTTON (18, DLG_X, DLG_Y - 3, DLG_Y, N_("&Cancel"), B_CANCEL, NULL),
1396 /* 1 */
1397 QUICK_BUTTON (6, DLG_X, DLG_Y - 3, DLG_Y, N_("&OK"), B_ENTER, NULL),
1398 /* 2 */
1399 QUICK_CHECKBOX (4, DLG_X, 8, DLG_Y, N_("Check &POSIX new line"), &option_check_nl_at_eof),
1400 /* 3 */
1401 QUICK_INPUT (8, DLG_X, 6, DLG_Y, option_backup_ext, 9, 0, "edit-backup-ext", &str_result),
1402 /* 4 */
1403 QUICK_RADIO (4, DLG_X, 3, DLG_Y, 3, str, &option_save_mode),
1404 QUICK_END
1407 QuickDialog dialog = {
1408 DLG_X, DLG_Y, -1, -1, N_("Edit Save Mode"),
1409 "[Edit Save Mode]", widgets, NULL, FALSE
1412 size_t i;
1413 size_t maxlen = 0;
1414 size_t w0, w1, b_len, w3;
1416 assert (option_backup_ext != NULL);
1418 /* OK/Cancel buttons */
1419 w0 = str_term_width1 (_(widgets[0].u.button.text)) + 3;
1420 w1 = str_term_width1 (_(widgets[1].u.button.text)) + 5; /* default button */
1421 b_len = w0 + w1 + 3;
1423 maxlen = max (b_len, (size_t) str_term_width1 (_(dialog.title)) + 2);
1425 w3 = 0;
1426 for (i = 0; i < 3; i++)
1428 #ifdef ENABLE_NLS
1429 str[i] = _(str[i]);
1430 #endif
1431 w3 = max (w3, (size_t) str_term_width1 (str[i]));
1434 maxlen = max (maxlen, w3 + 4);
1436 dialog.xlen = min ((size_t) COLS, maxlen + 8);
1438 widgets[3].u.input.len = w3;
1439 widgets[1].relative_x = (dialog.xlen - b_len) / 2;
1440 widgets[0].relative_x = widgets[1].relative_x + w0 + 2;
1442 for (i = 0; i < sizeof (widgets) / sizeof (widgets[0]); i++)
1443 widgets[i].x_divisions = dialog.xlen;
1445 if (quick_dialog (&dialog) != B_CANCEL)
1447 g_free (option_backup_ext);
1448 option_backup_ext = str_result;
1452 /* --------------------------------------------------------------------------------------------- */
1454 void
1455 edit_set_filename (WEdit * edit, const vfs_path_t * name_vpath)
1457 vfs_path_free (edit->filename_vpath);
1458 edit->filename_vpath = vfs_path_clone (name_vpath);
1460 if (edit->dir_vpath == NULL)
1461 edit->dir_vpath = vfs_path_clone (vfs_get_raw_current_dir ());
1464 /* --------------------------------------------------------------------------------------------- */
1465 /* Here we want to warn the users of overwriting an existing file,
1466 but only if they have made a change to the filename */
1467 /* returns 1 on success */
1469 edit_save_as_cmd (WEdit * edit)
1471 /* This heads the 'Save As' dialog box */
1472 vfs_path_t *exp_vpath;
1473 int save_lock = 0;
1474 int different_filename = 0;
1476 if (!edit_check_newline (edit))
1477 return 0;
1479 exp_vpath = edit_get_save_file_as (edit);
1480 edit_push_undo_action (edit, KEY_PRESS + edit->start_display);
1482 if (exp_vpath != NULL)
1484 if (vfs_path_len (exp_vpath) == 0)
1485 goto ret;
1486 else
1488 int rv;
1490 if (vfs_path_cmp (edit->filename_vpath, exp_vpath) != 0)
1492 int file;
1494 different_filename = 1;
1495 file = mc_open (exp_vpath, O_RDONLY | O_BINARY);
1497 if (file != -1)
1499 /* the file exists */
1500 mc_close (file);
1501 /* Overwrite the current file or cancel the operation */
1502 if (edit_query_dialog2
1503 (_("Warning"),
1504 _("A file already exists with this name"), _("&Overwrite"), _("&Cancel")))
1505 goto ret;
1507 else
1509 edit->stat1.st_mode |= S_IWUSR;
1511 save_lock = lock_file (exp_vpath);
1513 else
1515 /* filenames equal, check if already locked */
1516 if (!edit->locked && !edit->delete_file)
1517 save_lock = lock_file (exp_vpath);
1520 if (different_filename)
1523 * Allow user to write into saved (under another name) file
1524 * even if original file had r/o user permissions.
1526 edit->stat1.st_mode |= S_IWRITE;
1529 rv = edit_save_file (edit, exp_vpath);
1530 switch (rv)
1532 case 1:
1533 /* Succesful, so unlock both files */
1534 if (different_filename)
1536 if (save_lock)
1537 unlock_file (exp_vpath);
1538 if (edit->locked)
1539 edit->locked = unlock_file (edit->filename_vpath);
1541 else
1543 if (edit->locked || save_lock)
1544 edit->locked = unlock_file (edit->filename_vpath);
1547 edit_set_filename (edit, exp_vpath);
1548 if (edit->lb != LB_ASIS)
1549 edit_reload (edit, exp_vpath);
1550 edit->modified = 0;
1551 edit->delete_file = 0;
1552 if (different_filename)
1553 edit_load_syntax (edit, NULL, edit->syntax_type);
1554 vfs_path_free (exp_vpath);
1555 edit->force |= REDRAW_COMPLETELY;
1556 return 1;
1557 default:
1558 edit_error_dialog (_("Save as"), get_sys_error (_("Cannot save file")));
1559 /* fallthrough */
1560 case -1:
1561 /* Failed, so maintain modify (not save) lock */
1562 if (save_lock)
1563 unlock_file (exp_vpath);
1564 break;
1569 ret:
1570 vfs_path_free (exp_vpath);
1571 edit->force |= REDRAW_COMPLETELY;
1572 return 0;
1575 /* {{{ Macro stuff starts here */
1576 /* --------------------------------------------------------------------------------------------- */
1578 void
1579 edit_delete_macro_cmd (WEdit * edit)
1581 int hotkey;
1583 hotkey = editcmd_dialog_raw_key_query (_("Delete macro"), _("Press macro hotkey:"), 1);
1585 if (hotkey != 0 && !edit_delete_macro (edit, hotkey))
1586 message (D_ERROR, _("Delete macro"), _("Macro not deleted"));
1589 /* --------------------------------------------------------------------------------------------- */
1591 /** returns FALSE on error */
1592 gboolean
1593 edit_execute_macro (WEdit * edit, int hotkey)
1595 gboolean res = FALSE;
1597 if (hotkey != 0)
1599 const macros_t *macros;
1600 guint indx;
1602 if (edit_get_macro (edit, hotkey, &macros, &indx) &&
1603 macros->macro != NULL && macros->macro->len != 0)
1605 guint i;
1607 edit->force |= REDRAW_PAGE;
1609 for (i = 0; i < macros->macro->len; i++)
1611 const macro_action_t *m_act;
1613 m_act = &g_array_index (macros->macro, struct macro_action_t, i);
1614 edit_execute_cmd (edit, m_act->action, m_act->ch);
1615 res = TRUE;
1619 edit_update_screen (edit);
1620 return res;
1623 /* --------------------------------------------------------------------------------------------- */
1625 /** returns FALSE on error */
1626 gboolean
1627 edit_store_macro_cmd (WEdit * edit)
1629 int i;
1630 int hotkey;
1631 GString *marcros_string;
1632 mc_config_t *macros_config = NULL;
1633 const char *section_name = "editor";
1634 gchar *macros_fname;
1635 GArray *macros; /* current macro */
1636 int tmp_act;
1637 gboolean have_macro = FALSE;
1638 char *skeyname = NULL;
1640 hotkey = editcmd_dialog_raw_key_query (_("Save macro"), _("Press the macro's new hotkey:"), 1);
1641 if (hotkey == ESC_CHAR)
1642 return FALSE;
1644 tmp_act = keybind_lookup_keymap_command (editor_map, hotkey);
1646 /* return FALSE if try assign macro into restricted hotkeys */
1647 if (tmp_act == CK_MacroStartRecord
1648 || tmp_act == CK_MacroStopRecord || tmp_act == CK_MacroStartStopRecord)
1649 return FALSE;
1651 edit_delete_macro (edit, hotkey);
1653 macros_fname = mc_config_get_full_path (MC_MACRO_FILE);
1654 macros_config = mc_config_init (macros_fname);
1655 g_free (macros_fname);
1657 if (macros_config == NULL)
1658 return FALSE;
1660 edit_push_undo_action (edit, KEY_PRESS + edit->start_display);
1662 marcros_string = g_string_sized_new (250);
1663 macros = g_array_new (TRUE, FALSE, sizeof (macro_action_t));
1665 skeyname = lookup_key_by_code (hotkey);
1667 for (i = 0; i < macro_index; i++)
1669 macro_action_t m_act;
1670 const char *action_name;
1672 action_name = keybind_lookup_actionname (record_macro_buf[i].action);
1674 if (action_name == NULL)
1675 break;
1677 m_act.action = record_macro_buf[i].action;
1678 m_act.ch = record_macro_buf[i].ch;
1679 g_array_append_val (macros, m_act);
1680 have_macro = TRUE;
1681 g_string_append_printf (marcros_string, "%s:%i;", action_name,
1682 (int) record_macro_buf[i].ch);
1684 if (have_macro)
1686 macros_t macro;
1687 macro.hotkey = hotkey;
1688 macro.macro = macros;
1689 g_array_append_val (macros_list, macro);
1690 mc_config_set_string (macros_config, section_name, skeyname, marcros_string->str);
1692 else
1693 mc_config_del_key (macros_config, section_name, skeyname);
1695 g_free (skeyname);
1696 edit_macro_sort_by_hotkey ();
1698 g_string_free (marcros_string, TRUE);
1699 mc_config_save_file (macros_config, NULL);
1700 mc_config_deinit (macros_config);
1701 return TRUE;
1704 /* --------------------------------------------------------------------------------------------- */
1706 gboolean
1707 edit_repeat_macro_cmd (WEdit * edit)
1709 int i, j;
1710 char *f;
1711 long count_repeat;
1712 char *error = NULL;
1714 f = input_dialog (_("Repeat last commands"), _("Repeat times:"), MC_HISTORY_EDIT_REPEAT, NULL);
1715 if (f == NULL || *f == '\0')
1717 g_free (f);
1718 return FALSE;
1721 count_repeat = strtol (f, &error, 0);
1723 if (*error != '\0')
1725 g_free (f);
1726 return FALSE;
1729 g_free (f);
1731 edit_push_undo_action (edit, KEY_PRESS + edit->start_display);
1732 edit->force |= REDRAW_PAGE;
1734 for (j = 0; j < count_repeat; j++)
1735 for (i = 0; i < macro_index; i++)
1736 edit_execute_cmd (edit, record_macro_buf[i].action, record_macro_buf[i].ch);
1737 edit_update_screen (edit);
1738 return TRUE;
1741 /* --------------------------------------------------------------------------------------------- */
1742 /** return FALSE on error */
1744 gboolean
1745 edit_load_macro_cmd (WEdit * edit)
1747 mc_config_t *macros_config = NULL;
1748 gchar **profile_keys, **keys;
1749 gchar **values, **curr_values;
1750 gsize len, values_len;
1751 const char *section_name = "editor";
1752 gchar *macros_fname;
1753 int hotkey;
1755 (void) edit;
1757 macros_fname = mc_config_get_full_path (MC_MACRO_FILE);
1758 macros_config = mc_config_init (macros_fname);
1759 g_free (macros_fname);
1761 if (macros_config == NULL)
1762 return FALSE;
1764 profile_keys = keys = mc_config_get_keys (macros_config, section_name, &len);
1765 while (*profile_keys != NULL)
1767 gboolean have_macro;
1768 GArray *macros;
1769 macros_t macro;
1771 macros = g_array_new (TRUE, FALSE, sizeof (macro_action_t));
1773 curr_values = values = mc_config_get_string_list (macros_config, section_name,
1774 *profile_keys, &values_len);
1775 hotkey = lookup_key (*profile_keys, NULL);
1776 have_macro = FALSE;
1778 while (*curr_values != NULL && *curr_values[0] != '\0')
1780 char **macro_pair = NULL;
1782 macro_pair = g_strsplit (*curr_values, ":", 2);
1784 if (macro_pair != NULL)
1786 macro_action_t m_act;
1787 if (macro_pair[0] == NULL || macro_pair[0][0] == '\0')
1788 m_act.action = 0;
1789 else
1791 m_act.action = keybind_lookup_action (macro_pair[0]);
1792 g_free (macro_pair[0]);
1793 macro_pair[0] = NULL;
1795 if (macro_pair[1] == NULL || macro_pair[1][0] == '\0')
1796 m_act.ch = -1;
1797 else
1799 m_act.ch = strtol (macro_pair[1], NULL, 0);
1800 g_free (macro_pair[1]);
1801 macro_pair[1] = NULL;
1803 if (m_act.action != 0)
1805 /* a shell command */
1806 if ((m_act.action / CK_PipeBlock (0)) == 1)
1808 m_act.action = CK_PipeBlock (0) + (m_act.ch > 0 ? m_act.ch : 0);
1809 m_act.ch = -1;
1811 g_array_append_val (macros, m_act);
1812 have_macro = TRUE;
1814 g_strfreev (macro_pair);
1815 macro_pair = NULL;
1817 curr_values++;
1819 if (have_macro)
1821 macro.hotkey = hotkey;
1822 macro.macro = macros;
1823 g_array_append_val (macros_list, macro);
1825 profile_keys++;
1826 g_strfreev (values);
1828 g_strfreev (keys);
1829 mc_config_deinit (macros_config);
1830 edit_macro_sort_by_hotkey ();
1831 return TRUE;
1834 /* }}} Macro stuff end here */
1836 /* --------------------------------------------------------------------------------------------- */
1837 /** returns 1 on success */
1840 edit_save_confirm_cmd (WEdit * edit)
1842 gchar *f = NULL;
1844 if (edit->filename_vpath == NULL)
1845 return edit_save_as_cmd (edit);
1847 if (!edit_check_newline (edit))
1848 return 0;
1850 if (edit_confirm_save)
1852 char *filename;
1853 gboolean ok;
1855 filename = vfs_path_to_str (edit->filename_vpath);
1856 f = g_strdup_printf (_("Confirm save file: \"%s\""), filename);
1857 g_free (filename);
1858 ok = (edit_query_dialog2 (_("Save file"), f, _("&Save"), _("&Cancel")) == 0);
1859 g_free (f);
1860 if (!ok)
1861 return 0;
1863 return edit_save_cmd (edit);
1866 /* --------------------------------------------------------------------------------------------- */
1867 /** returns 1 on success */
1870 edit_new_cmd (WEdit * edit)
1872 if (edit->modified)
1874 if (edit_query_dialog2
1875 (_("Warning"),
1877 ("Current text was modified without a file save.\nContinue discards these changes"),
1878 _("C&ontinue"), _("&Cancel")))
1880 edit->force |= REDRAW_COMPLETELY;
1881 return 0;
1884 edit->force |= REDRAW_COMPLETELY;
1886 return edit_renew (edit); /* if this gives an error, something has really screwed up */
1889 /* --------------------------------------------------------------------------------------------- */
1892 edit_load_cmd (WEdit * edit, edit_current_file_t what)
1894 if (edit->modified
1895 && (edit_query_dialog2
1896 (_("Warning"),
1897 _("Current text was modified without a file save.\n"
1898 "Continue discards these changes"), _("C&ontinue"), _("&Cancel")) == 1))
1900 edit->force |= REDRAW_COMPLETELY;
1901 return 0;
1904 switch (what)
1906 case EDIT_FILE_COMMON:
1908 char *filename, *exp;
1910 filename = vfs_path_to_str (edit->filename_vpath);
1911 exp = input_expand_dialog (_("Load"), _("Enter file name:"),
1912 MC_HISTORY_EDIT_LOAD, filename);
1913 g_free (filename);
1915 if (exp != NULL)
1917 if (*exp != '\0')
1919 vfs_path_t *exp_vpath;
1921 exp_vpath = vfs_path_from_str (exp);
1922 edit_load_file_from_filename (edit, exp_vpath);
1923 vfs_path_free (exp_vpath);
1925 g_free (exp);
1928 break;
1930 case EDIT_FILE_SYNTAX:
1931 edit_load_syntax_file (edit);
1932 break;
1934 case EDIT_FILE_MENU:
1935 edit_load_menu_file (edit);
1936 break;
1938 default:
1939 break;
1942 edit->force |= REDRAW_COMPLETELY;
1943 return 0;
1946 /* --------------------------------------------------------------------------------------------- */
1948 if mark2 is -1 then marking is from mark1 to the cursor.
1949 Otherwise its between the markers. This handles this.
1950 Returns 1 if no text is marked.
1954 eval_marks (WEdit * edit, long *start_mark, long *end_mark)
1956 if (edit->mark1 != edit->mark2)
1958 long start_bol, start_eol;
1959 long end_bol, end_eol;
1960 long col1, col2;
1961 long diff1, diff2;
1962 long end_mark_curs;
1964 if (edit->end_mark_curs < 0)
1965 end_mark_curs = edit->curs1;
1966 else
1967 end_mark_curs = edit->end_mark_curs;
1969 if (edit->mark2 >= 0)
1971 *start_mark = min (edit->mark1, edit->mark2);
1972 *end_mark = max (edit->mark1, edit->mark2);
1974 else
1976 *start_mark = min (edit->mark1, end_mark_curs);
1977 *end_mark = max (edit->mark1, end_mark_curs);
1978 edit->column2 = edit->curs_col + edit->over_col;
1981 if (edit->column_highlight
1982 && (((edit->mark1 > end_mark_curs) && (edit->column1 < edit->column2))
1983 || ((edit->mark1 < end_mark_curs) && (edit->column1 > edit->column2))))
1985 start_bol = edit_bol (edit, *start_mark);
1986 start_eol = edit_eol (edit, start_bol - 1) + 1;
1987 end_bol = edit_bol (edit, *end_mark);
1988 end_eol = edit_eol (edit, *end_mark);
1989 col1 = min (edit->column1, edit->column2);
1990 col2 = max (edit->column1, edit->column2);
1992 diff1 =
1993 edit_move_forward3 (edit, start_bol, col2, 0) - edit_move_forward3 (edit, start_bol,
1994 col1, 0);
1995 diff2 =
1996 edit_move_forward3 (edit, end_bol, col2, 0) - edit_move_forward3 (edit, end_bol,
1997 col1, 0);
1999 *start_mark -= diff1;
2000 *end_mark += diff2;
2001 *start_mark = max (*start_mark, start_eol);
2002 *end_mark = min (*end_mark, end_eol);
2004 return 0;
2006 else
2008 *start_mark = *end_mark = 0;
2009 edit->column2 = edit->column1 = 0;
2010 return 1;
2014 /* --------------------------------------------------------------------------------------------- */
2016 void
2017 edit_insert_over (WEdit * edit)
2019 int i;
2021 for (i = 0; i < edit->over_col; i++)
2023 edit_insert (edit, ' ');
2025 edit->over_col = 0;
2028 /* --------------------------------------------------------------------------------------------- */
2031 edit_insert_column_of_text_from_file (WEdit * edit, int file,
2032 long *start_pos, long *end_pos, int *col1, int *col2)
2034 long cursor;
2035 int col;
2036 int blocklen = -1, width = 0;
2037 unsigned char *data;
2039 cursor = edit->curs1;
2040 col = edit_get_col (edit);
2041 data = g_malloc0 (TEMP_BUF_LEN);
2043 while ((blocklen = mc_read (file, (char *) data, TEMP_BUF_LEN)) > 0)
2045 int i;
2046 for (width = 0; width < blocklen; width++)
2048 if (data[width] == '\n')
2049 break;
2051 for (i = 0; i < blocklen; i++)
2053 if (data[i] == '\n')
2054 { /* fill in and move to next line */
2055 int l;
2056 long p;
2057 if (edit_get_byte (edit, edit->curs1) != '\n')
2059 l = width - (edit_get_col (edit) - col);
2060 while (l > 0)
2062 edit_insert (edit, ' ');
2063 l -= space_width;
2066 for (p = edit->curs1;; p++)
2068 if (p == edit->last_byte)
2070 edit_cursor_move (edit, edit->last_byte - edit->curs1);
2071 edit_insert_ahead (edit, '\n');
2072 p++;
2073 break;
2075 if (edit_get_byte (edit, p) == '\n')
2077 p++;
2078 break;
2081 edit_cursor_move (edit, edit_move_forward3 (edit, p, col, 0) - edit->curs1);
2082 l = col - edit_get_col (edit);
2083 while (l >= space_width)
2085 edit_insert (edit, ' ');
2086 l -= space_width;
2088 continue;
2090 edit_insert (edit, data[i]);
2093 *col1 = col;
2094 *col2 = col + width;
2095 *start_pos = cursor;
2096 *end_pos = edit->curs1;
2097 edit_cursor_move (edit, cursor - edit->curs1);
2098 g_free (data);
2100 return blocklen;
2103 /* --------------------------------------------------------------------------------------------- */
2105 void
2106 edit_block_copy_cmd (WEdit * edit)
2108 long start_mark, end_mark, current = edit->curs1;
2109 long col_delta = 0;
2110 long mark1, mark2;
2111 int c1, c2;
2112 int size;
2113 unsigned char *copy_buf;
2115 edit_update_curs_col (edit);
2116 if (eval_marks (edit, &start_mark, &end_mark))
2117 return;
2119 copy_buf = edit_get_block (edit, start_mark, end_mark, &size);
2121 /* all that gets pushed are deletes hence little space is used on the stack */
2123 edit_push_markers (edit);
2125 if (edit->column_highlight)
2127 col_delta = abs (edit->column2 - edit->column1);
2128 edit_insert_column_of_text (edit, copy_buf, size, col_delta, &mark1, &mark2, &c1, &c2);
2130 else
2132 while (size--)
2133 edit_insert_ahead (edit, copy_buf[size]);
2136 g_free (copy_buf);
2137 edit_scroll_screen_over_cursor (edit);
2139 if (edit->column_highlight)
2140 edit_set_markers (edit, edit->curs1, mark2, c1, c2);
2141 else if (start_mark < current && end_mark > current)
2142 edit_set_markers (edit, start_mark, end_mark + end_mark - start_mark, 0, 0);
2144 edit->force |= REDRAW_PAGE;
2148 /* --------------------------------------------------------------------------------------------- */
2150 void
2151 edit_block_move_cmd (WEdit * edit)
2153 long current;
2154 unsigned char *copy_buf = NULL;
2155 long start_mark, end_mark;
2156 long line;
2158 if (eval_marks (edit, &start_mark, &end_mark))
2159 return;
2161 line = edit->curs_line;
2162 if (edit->mark2 < 0)
2163 edit_mark_cmd (edit, 0);
2164 edit_push_markers (edit);
2166 if (edit->column_highlight)
2168 long mark1, mark2;
2169 int size;
2170 int b_width = 0;
2171 int c1, c2;
2172 int x, x2;
2174 c1 = min (edit->column1, edit->column2);
2175 c2 = max (edit->column1, edit->column2);
2176 b_width = (c2 - c1);
2178 edit_update_curs_col (edit);
2180 x = edit->curs_col;
2181 x2 = x + edit->over_col;
2183 /* do nothing when cursor inside first line of selected area */
2184 if ((edit_eol (edit, edit->curs1) == edit_eol (edit, start_mark)) && (x2 > c1 && x2 <= c2))
2185 return;
2187 if (edit->curs1 > start_mark && edit->curs1 < edit_eol (edit, end_mark))
2189 if (x > c2)
2190 x -= b_width;
2191 else if (x > c1 && x <= c2)
2192 x = c1;
2194 /* save current selection into buffer */
2195 copy_buf = edit_get_block (edit, start_mark, end_mark, &size);
2197 /* remove current selection */
2198 edit_block_delete_cmd (edit);
2200 edit->over_col = max (0, edit->over_col - b_width);
2201 /* calculate the cursor pos after delete block */
2202 current = edit_move_forward3 (edit, edit_bol (edit, edit->curs1), x, 0);
2203 edit_cursor_move (edit, current - edit->curs1);
2204 edit_scroll_screen_over_cursor (edit);
2206 /* add TWS if need before block insertion */
2207 if (option_cursor_beyond_eol && edit->over_col > 0)
2208 edit_insert_over (edit);
2210 edit_insert_column_of_text (edit, copy_buf, size, b_width, &mark1, &mark2, &c1, &c2);
2211 edit_set_markers (edit, mark1, mark2, c1, c2);
2213 else
2215 long count;
2217 current = edit->curs1;
2218 copy_buf = g_malloc0 (end_mark - start_mark);
2219 edit_cursor_move (edit, start_mark - edit->curs1);
2220 edit_scroll_screen_over_cursor (edit);
2221 count = start_mark;
2222 while (count < end_mark)
2224 copy_buf[end_mark - count - 1] = edit_delete (edit, 1);
2225 count++;
2227 edit_scroll_screen_over_cursor (edit);
2228 edit_cursor_move (edit,
2229 current - edit->curs1 -
2230 (((current - edit->curs1) > 0) ? end_mark - start_mark : 0));
2231 edit_scroll_screen_over_cursor (edit);
2232 while (count-- > start_mark)
2233 edit_insert_ahead (edit, copy_buf[end_mark - count - 1]);
2234 edit_set_markers (edit, edit->curs1, edit->curs1 + end_mark - start_mark, 0, 0);
2237 edit_scroll_screen_over_cursor (edit);
2238 g_free (copy_buf);
2239 edit->force |= REDRAW_PAGE;
2242 /* --------------------------------------------------------------------------------------------- */
2243 /** returns 1 if canceelled by user */
2246 edit_block_delete_cmd (WEdit * edit)
2248 long start_mark, end_mark;
2249 if (eval_marks (edit, &start_mark, &end_mark))
2251 edit_delete_line (edit);
2252 return 0;
2254 return edit_block_delete (edit);
2257 /* --------------------------------------------------------------------------------------------- */
2258 /** call with edit = 0 before shutdown to close memory leaks */
2260 void
2261 edit_replace_cmd (WEdit * edit, int again)
2263 /* 1 = search string, 2 = replace with */
2264 static char *saved1 = NULL; /* saved default[123] */
2265 static char *saved2 = NULL;
2266 char *input1 = NULL; /* user input from the dialog */
2267 char *input2 = NULL;
2268 char *disp1 = NULL;
2269 char *disp2 = NULL;
2270 long times_replaced = 0;
2271 gboolean once_found = FALSE;
2273 if (!edit)
2275 g_free (saved1), saved1 = NULL;
2276 g_free (saved2), saved2 = NULL;
2277 return;
2280 edit->force |= REDRAW_COMPLETELY;
2282 if (again && !saved1 && !saved2)
2283 again = 0;
2285 if (again)
2287 input1 = g_strdup (saved1 ? saved1 : "");
2288 input2 = g_strdup (saved2 ? saved2 : "");
2290 else
2292 char *tmp_inp1, *tmp_inp2;
2293 disp1 = edit_replace_cmd__conv_to_display (saved1 ? saved1 : (char *) "");
2294 disp2 = edit_replace_cmd__conv_to_display (saved2 ? saved2 : (char *) "");
2296 edit_push_undo_action (edit, KEY_PRESS + edit->start_display);
2298 editcmd_dialog_replace_show (edit, disp1, disp2, &input1, &input2);
2300 g_free (disp1);
2301 g_free (disp2);
2303 if (input1 == NULL || *input1 == '\0')
2305 edit->force = REDRAW_COMPLETELY;
2306 goto cleanup;
2309 tmp_inp1 = input1;
2310 tmp_inp2 = input2;
2311 input1 = edit_replace_cmd__conv_to_input (input1);
2312 input2 = edit_replace_cmd__conv_to_input (input2);
2313 g_free (tmp_inp1);
2314 g_free (tmp_inp2);
2316 g_free (saved1), saved1 = g_strdup (input1);
2317 g_free (saved2), saved2 = g_strdup (input2);
2319 mc_search_free (edit->search);
2320 edit->search = NULL;
2323 if (!edit->search)
2325 edit->search = mc_search_new (input1, -1);
2326 if (edit->search == NULL)
2328 edit->search_start = edit->curs1;
2329 goto cleanup;
2331 edit->search->search_type = edit_search_options.type;
2332 edit->search->is_all_charsets = edit_search_options.all_codepages;
2333 edit->search->is_case_sensitive = edit_search_options.case_sens;
2334 edit->search->whole_words = edit_search_options.whole_words;
2335 edit->search->search_fn = edit_search_cmd_callback;
2338 if (edit->found_len && edit->search_start == edit->found_start + 1
2339 && edit_search_options.backwards)
2340 edit->search_start--;
2342 if (edit->found_len && edit->search_start == edit->found_start - 1
2343 && !edit_search_options.backwards)
2344 edit->search_start++;
2348 gsize len = 0;
2350 if (!editcmd_find (edit, &len))
2352 if (!(edit->search->error == MC_SEARCH_E_OK ||
2353 (once_found && edit->search->error == MC_SEARCH_E_NOTFOUND)))
2355 edit_error_dialog (_("Search"), edit->search->error_str);
2357 break;
2359 once_found = TRUE;
2361 edit->search_start = edit->search->normal_offset;
2362 /*returns negative on not found or error in pattern */
2364 if ((edit->search_start >= 0) && (edit->search_start < edit->last_byte))
2366 gsize i;
2367 GString *tmp_str, *repl_str;
2369 edit->found_start = edit->search_start;
2370 i = edit->found_len = len;
2372 edit_cursor_move (edit, edit->search_start - edit->curs1);
2373 edit_scroll_screen_over_cursor (edit);
2375 if (edit->replace_mode == 0)
2377 int l;
2378 int prompt;
2380 l = edit->curs_row - edit->widget.lines / 3;
2381 if (l > 0)
2382 edit_scroll_downward (edit, l);
2383 if (l < 0)
2384 edit_scroll_upward (edit, -l);
2386 edit_scroll_screen_over_cursor (edit);
2387 edit->force |= REDRAW_PAGE;
2388 edit_render_keypress (edit);
2390 /*so that undo stops at each query */
2391 edit_push_key_press (edit);
2392 /* and prompt 2/3 down */
2393 disp1 = edit_replace_cmd__conv_to_display (saved1);
2394 disp2 = edit_replace_cmd__conv_to_display (saved2);
2395 prompt = editcmd_dialog_replace_prompt_show (edit, disp1, disp2, -1, -1);
2396 g_free (disp1);
2397 g_free (disp2);
2399 if (prompt == B_REPLACE_ALL)
2400 edit->replace_mode = 1;
2401 else if (prompt == B_SKIP_REPLACE)
2403 if (edit_search_options.backwards)
2404 edit->search_start--;
2405 else
2406 edit->search_start++;
2407 continue; /* loop */
2409 else if (prompt == B_CANCEL)
2411 edit->replace_mode = -1;
2412 break; /* loop */
2416 /* don't process string each time */
2417 tmp_str = g_string_new (input2);
2418 repl_str = mc_search_prepare_replace_str (edit->search, tmp_str);
2419 g_string_free (tmp_str, TRUE);
2421 if (edit->search->error != MC_SEARCH_E_OK)
2423 edit_error_dialog (_("Replace"), edit->search->error_str);
2424 g_string_free (repl_str, TRUE);
2425 break;
2428 /* delete then insert new */
2429 for (i = 0; i < len; i++)
2430 edit_delete (edit, 1);
2432 for (i = 0; i < repl_str->len; i++)
2433 edit_insert (edit, repl_str->str[i]);
2435 edit->found_len = repl_str->len;
2436 g_string_free (repl_str, TRUE);
2437 times_replaced++;
2439 /* so that we don't find the same string again */
2440 if (edit_search_options.backwards)
2441 edit->search_start--;
2442 else
2444 edit->search_start += edit->found_len;
2446 if (edit->search_start >= edit->last_byte)
2447 break;
2450 edit_scroll_screen_over_cursor (edit);
2452 else
2454 /* try and find from right here for next search */
2455 edit->search_start = edit->curs1;
2456 edit_update_curs_col (edit);
2458 edit->force |= REDRAW_PAGE;
2459 edit_render_keypress (edit);
2461 if (times_replaced == 0)
2462 query_dialog (_("Replace"), _("Search string not found"), D_NORMAL, 1, _("&OK"));
2463 break;
2466 while (edit->replace_mode >= 0);
2468 edit_scroll_screen_over_cursor (edit);
2469 edit->force |= REDRAW_COMPLETELY;
2470 edit_render_keypress (edit);
2472 if ((edit->replace_mode == 1) && (times_replaced != 0))
2473 message (D_NORMAL, _("Replace"), _("%ld replacements made"), times_replaced);
2475 cleanup:
2476 g_free (input1);
2477 g_free (input2);
2480 /* --------------------------------------------------------------------------------------------- */
2483 edit_search_cmd_callback (const void *user_data, gsize char_offset)
2485 return edit_get_byte ((WEdit *) user_data, (long) char_offset);
2488 /* --------------------------------------------------------------------------------------------- */
2490 void
2491 edit_search_cmd (WEdit * edit, gboolean again)
2493 if (edit == NULL)
2494 return;
2496 if (!again)
2497 edit_search (edit);
2498 else if (edit->last_search_string != NULL)
2499 edit_do_search (edit);
2500 else
2502 /* find last search string in history */
2503 GList *history;
2505 history = history_get (MC_HISTORY_SHARED_SEARCH);
2506 if (history != NULL && history->data != NULL)
2508 edit->last_search_string = (char *) history->data;
2509 history->data = NULL;
2510 history = g_list_first (history);
2511 g_list_foreach (history, (GFunc) g_free, NULL);
2512 g_list_free (history);
2514 edit->search = mc_search_new (edit->last_search_string, -1);
2515 if (edit->search == NULL)
2517 /* if not... then ask for an expression */
2518 g_free (edit->last_search_string);
2519 edit->last_search_string = NULL;
2520 edit_search (edit);
2522 else
2524 edit->search->search_type = edit_search_options.type;
2525 edit->search->is_all_charsets = edit_search_options.all_codepages;
2526 edit->search->is_case_sensitive = edit_search_options.case_sens;
2527 edit->search->whole_words = edit_search_options.whole_words;
2528 edit->search->search_fn = edit_search_cmd_callback;
2529 edit_do_search (edit);
2532 else
2534 /* if not... then ask for an expression */
2535 g_free (edit->last_search_string);
2536 edit->last_search_string = NULL;
2537 edit_search (edit);
2543 /* --------------------------------------------------------------------------------------------- */
2545 * Check if it's OK to close the editor. If there are unsaved changes,
2546 * ask user. Return 1 if it's OK to exit, 0 to continue editing.
2549 gboolean
2550 edit_ok_to_exit (WEdit * edit)
2552 int act;
2554 if (!edit->modified)
2555 return TRUE;
2557 if (!mc_global.widget.midnight_shutdown)
2559 if (!edit_check_newline (edit))
2560 return FALSE;
2562 query_set_sel (2);
2563 act = edit_query_dialog3 (_("Quit"), _("File was modified. Save with exit?"),
2564 _("&Yes"), _("&No"), _("&Cancel quit"));
2566 else
2568 act =
2569 edit_query_dialog2 (_("Quit"),
2570 _("Midnight Commander is being shut down.\nSave modified file?"),
2571 _("&Yes"), _("&No"));
2573 /* Esc is No */
2574 if (act == -1)
2575 act = 1;
2578 switch (act)
2580 case 0: /* Yes */
2581 edit_push_markers (edit);
2582 edit_set_markers (edit, 0, 0, 0, 0);
2583 if (!edit_save_cmd (edit) || mc_global.widget.midnight_shutdown)
2584 return mc_global.widget.midnight_shutdown;
2585 break;
2586 case 1: /* No */
2587 break;
2588 case 2: /* Cancel quit */
2589 case -1: /* Esc */
2590 return FALSE;
2593 return TRUE;
2596 /* --------------------------------------------------------------------------------------------- */
2597 /** save block, returns 1 on success */
2600 edit_save_block (WEdit * edit, const char *filename, long start, long finish)
2602 int len, file;
2603 vfs_path_t *vpath;
2605 vpath = vfs_path_from_str (filename);
2606 file = mc_open (vpath, O_CREAT | O_WRONLY | O_TRUNC,
2607 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH | O_BINARY);
2608 vfs_path_free (vpath);
2609 if (file == -1)
2610 return 0;
2612 if (edit->column_highlight)
2614 int r;
2616 r = mc_write (file, VERTICAL_MAGIC, sizeof (VERTICAL_MAGIC));
2617 if (r > 0)
2619 unsigned char *block, *p;
2621 p = block = edit_get_block (edit, start, finish, &len);
2622 while (len)
2624 r = mc_write (file, p, len);
2625 if (r < 0)
2626 break;
2627 p += r;
2628 len -= r;
2630 g_free (block);
2633 else
2635 unsigned char *buf;
2636 int i = start, end;
2638 len = finish - start;
2639 buf = g_malloc0 (TEMP_BUF_LEN);
2640 while (start != finish)
2642 end = min (finish, start + TEMP_BUF_LEN);
2643 for (; i < end; i++)
2644 buf[i - start] = edit_get_byte (edit, i);
2645 len -= mc_write (file, (char *) buf, end - start);
2646 start = end;
2648 g_free (buf);
2650 mc_close (file);
2651 if (len)
2652 return 0;
2653 return 1;
2656 /* --------------------------------------------------------------------------------------------- */
2658 void
2659 edit_paste_from_history (WEdit * edit)
2661 (void) edit;
2662 edit_error_dialog (_("Error"), _("This function is not implemented"));
2665 /* --------------------------------------------------------------------------------------------- */
2668 edit_copy_to_X_buf_cmd (WEdit * edit)
2670 long start_mark, end_mark;
2671 if (eval_marks (edit, &start_mark, &end_mark))
2672 return 0;
2673 if (!edit_save_block_to_clip_file (edit, start_mark, end_mark))
2675 edit_error_dialog (_("Copy to clipboard"), get_sys_error (_("Unable to save to file")));
2676 return 1;
2678 /* try use external clipboard utility */
2679 mc_event_raise (MCEVENT_GROUP_CORE, "clipboard_file_to_ext_clip", NULL);
2681 return 0;
2684 /* --------------------------------------------------------------------------------------------- */
2687 edit_cut_to_X_buf_cmd (WEdit * edit)
2689 long start_mark, end_mark;
2690 if (eval_marks (edit, &start_mark, &end_mark))
2691 return 0;
2692 if (!edit_save_block_to_clip_file (edit, start_mark, end_mark))
2694 edit_error_dialog (_("Cut to clipboard"), _("Unable to save to file"));
2695 return 1;
2697 /* try use external clipboard utility */
2698 mc_event_raise (MCEVENT_GROUP_CORE, "clipboard_file_to_ext_clip", NULL);
2700 edit_block_delete_cmd (edit);
2701 edit_mark_cmd (edit, 1);
2702 return 0;
2705 /* --------------------------------------------------------------------------------------------- */
2707 void
2708 edit_paste_from_X_buf_cmd (WEdit * edit)
2710 vfs_path_t *tmp;
2712 /* try use external clipboard utility */
2713 mc_event_raise (MCEVENT_GROUP_CORE, "clipboard_file_from_ext_clip", NULL);
2714 tmp = mc_config_get_full_vpath (EDIT_CLIP_FILE);
2715 edit_insert_file (edit, tmp);
2716 vfs_path_free (tmp);
2720 /* --------------------------------------------------------------------------------------------- */
2722 * Ask user for the line and go to that line.
2723 * Negative numbers mean line from the end (i.e. -1 is the last line).
2726 void
2727 edit_goto_cmd (WEdit * edit)
2729 char *f;
2730 static long line = 0; /* line as typed, saved as default */
2731 long l;
2732 char *error;
2733 char s[32];
2735 g_snprintf (s, sizeof (s), "%ld", line);
2736 f = input_dialog (_("Goto line"), _("Enter line:"), MC_HISTORY_EDIT_GOTO_LINE, line ? s : "");
2737 if (!f)
2738 return;
2740 if (!*f)
2742 g_free (f);
2743 return;
2746 l = strtol (f, &error, 0);
2747 if (*error)
2749 g_free (f);
2750 return;
2753 line = l;
2754 if (l < 0)
2755 l = edit->total_lines + l + 2;
2756 edit_move_display (edit, l - edit->widget.lines / 2 - 1);
2757 edit_move_to_line (edit, l - 1);
2758 edit->force |= REDRAW_COMPLETELY;
2759 g_free (f);
2763 /* --------------------------------------------------------------------------------------------- */
2764 /** Return 1 on success */
2767 edit_save_block_cmd (WEdit * edit)
2769 long start_mark, end_mark;
2770 char *exp, *tmp;
2772 if (eval_marks (edit, &start_mark, &end_mark))
2773 return 1;
2775 tmp = mc_config_get_full_path (EDIT_CLIP_FILE);
2776 exp =
2777 input_expand_dialog (_("Save block"), _("Enter file name:"),
2778 MC_HISTORY_EDIT_SAVE_BLOCK, tmp);
2779 g_free (tmp);
2780 edit_push_undo_action (edit, KEY_PRESS + edit->start_display);
2781 if (exp)
2783 if (!*exp)
2785 g_free (exp);
2786 return 0;
2788 else
2790 if (edit_save_block (edit, exp, start_mark, end_mark))
2792 g_free (exp);
2793 edit->force |= REDRAW_COMPLETELY;
2794 return 1;
2796 else
2798 g_free (exp);
2799 edit_error_dialog (_("Save block"), get_sys_error (_("Cannot save file")));
2803 edit->force |= REDRAW_COMPLETELY;
2804 return 0;
2808 /* --------------------------------------------------------------------------------------------- */
2809 /** returns TRUE on success */
2811 gboolean
2812 edit_insert_file_cmd (WEdit * edit)
2814 char *tmp;
2815 char *exp;
2816 gboolean ret = FALSE;
2818 tmp = mc_config_get_full_path (EDIT_CLIP_FILE);
2819 exp = input_expand_dialog (_("Insert file"), _("Enter file name:"),
2820 MC_HISTORY_EDIT_INSERT_FILE, tmp);
2821 g_free (tmp);
2823 edit_push_undo_action (edit, KEY_PRESS + edit->start_display);
2825 if (exp != NULL && *exp != '\0')
2827 vfs_path_t *exp_vpath;
2829 exp_vpath = vfs_path_from_str (exp);
2830 ret = (edit_insert_file (edit, exp_vpath) >= 0);
2831 vfs_path_free (exp_vpath);
2833 if (!ret)
2834 edit_error_dialog (_("Insert file"), get_sys_error (_("Cannot insert file")));
2837 g_free (exp);
2839 edit->force |= REDRAW_COMPLETELY;
2840 return ret;
2843 /* --------------------------------------------------------------------------------------------- */
2844 /** sorts a block, returns -1 on system fail, 1 on cancel and 0 on success */
2847 edit_sort_cmd (WEdit * edit)
2849 static char *old = 0;
2850 char *exp, *tmp, *tmp_edit_block_name, *tmp_edit_temp_name;
2851 long start_mark, end_mark;
2852 int e;
2854 if (eval_marks (edit, &start_mark, &end_mark))
2856 edit_error_dialog (_("Sort block"), _("You must first highlight a block of text"));
2857 return 0;
2860 tmp = mc_config_get_full_path (EDIT_BLOCK_FILE);
2861 edit_save_block (edit, tmp, start_mark, end_mark);
2862 g_free (tmp);
2864 exp = input_dialog (_("Run sort"),
2865 _("Enter sort options (see manpage) separated by whitespace:"),
2866 MC_HISTORY_EDIT_SORT, (old != NULL) ? old : "");
2868 if (!exp)
2869 return 1;
2870 g_free (old);
2871 old = exp;
2872 tmp_edit_block_name = mc_config_get_full_path (EDIT_BLOCK_FILE);
2873 tmp_edit_temp_name = mc_config_get_full_path (EDIT_TEMP_FILE);
2874 tmp =
2875 g_strconcat (" sort ", exp, " ", tmp_edit_block_name,
2876 " > ", tmp_edit_temp_name, (char *) NULL);
2877 g_free (tmp_edit_temp_name);
2878 g_free (tmp_edit_block_name);
2880 e = system (tmp);
2881 g_free (tmp);
2882 if (e)
2884 if (e == -1 || e == 127)
2886 edit_error_dialog (_("Sort"), get_sys_error (_("Cannot execute sort command")));
2888 else
2890 char q[8];
2891 sprintf (q, "%d ", e);
2892 tmp = g_strdup_printf (_("Sort returned non-zero: %s"), q);
2893 edit_error_dialog (_("Sort"), tmp);
2894 g_free (tmp);
2896 return -1;
2899 edit->force |= REDRAW_COMPLETELY;
2901 if (edit_block_delete_cmd (edit))
2902 return 1;
2905 vfs_path_t *tmp_vpath;
2907 tmp_vpath = mc_config_get_full_vpath (EDIT_TEMP_FILE);
2908 edit_insert_file (edit, tmp_vpath);
2909 vfs_path_free (tmp_vpath);
2911 return 0;
2914 /* --------------------------------------------------------------------------------------------- */
2916 * Ask user for a command, execute it and paste its output back to the
2917 * editor.
2921 edit_ext_cmd (WEdit * edit)
2923 char *exp, *tmp, *tmp_edit_temp_file;
2924 int e;
2926 exp =
2927 input_dialog (_("Paste output of external command"),
2928 _("Enter shell command(s):"), MC_HISTORY_EDIT_PASTE_EXTCMD, NULL);
2930 if (!exp)
2931 return 1;
2933 tmp_edit_temp_file = mc_config_get_full_path (EDIT_TEMP_FILE);
2934 tmp = g_strconcat (exp, " > ", tmp_edit_temp_file, (char *) NULL);
2935 g_free (tmp_edit_temp_file);
2936 e = system (tmp);
2937 g_free (tmp);
2938 g_free (exp);
2940 if (e)
2942 edit_error_dialog (_("External command"), get_sys_error (_("Cannot execute command")));
2943 return -1;
2946 edit->force |= REDRAW_COMPLETELY;
2949 vfs_path_t *tmp_vpath;
2951 tmp_vpath = mc_config_get_full_vpath (EDIT_TEMP_FILE);
2952 edit_insert_file (edit, tmp_vpath);
2953 vfs_path_free (tmp_vpath);
2955 return 0;
2958 /* --------------------------------------------------------------------------------------------- */
2959 /** if block is 1, a block must be highlighted and the shell command
2960 processes it. If block is 0 the shell command is a straight system
2961 command, that just produces some output which is to be inserted */
2963 void
2964 edit_block_process_cmd (WEdit * edit, int macro_number)
2966 char *fname;
2967 char *macros_fname = NULL;
2969 fname = g_strdup_printf ("%s.%i.sh", MC_EXTMACRO_FILE, macro_number);
2970 macros_fname = g_build_filename (mc_config_get_data_path (), fname, (char *) NULL);
2971 user_menu (edit, macros_fname, 0);
2972 g_free (fname);
2973 g_free (macros_fname);
2974 edit->force |= REDRAW_COMPLETELY;
2977 /* --------------------------------------------------------------------------------------------- */
2979 void
2980 edit_mail_dialog (WEdit * edit)
2982 char *tmail_to;
2983 char *tmail_subject;
2984 char *tmail_cc;
2986 static char *mail_cc_last = 0;
2987 static char *mail_subject_last = 0;
2988 static char *mail_to_last = 0;
2990 QuickWidget quick_widgets[] = {
2991 /* 0 */ QUICK_BUTTON (6, 10, 9, MAIL_DLG_HEIGHT, N_("&Cancel"), B_CANCEL, NULL),
2992 /* 1 */ QUICK_BUTTON (2, 10, 9, MAIL_DLG_HEIGHT, N_("&OK"), B_ENTER, NULL),
2993 /* 2 */ QUICK_INPUT (3, 50, 8, MAIL_DLG_HEIGHT, "", 44, 0, "mail-dlg-input", &tmail_cc),
2994 /* 3 */ QUICK_LABEL (3, 50, 7, MAIL_DLG_HEIGHT, N_("Copies to")),
2995 /* 4 */ QUICK_INPUT (3, 50, 6, MAIL_DLG_HEIGHT, "", 44, 0, "mail-dlg-input-2",
2996 &tmail_subject),
2997 /* 5 */ QUICK_LABEL (3, 50, 5, MAIL_DLG_HEIGHT, N_("Subject")),
2998 /* 6 */ QUICK_INPUT (3, 50, 4, MAIL_DLG_HEIGHT, "", 44, 0, "mail-dlg-input-3", &tmail_to),
2999 /* 7 */ QUICK_LABEL (3, 50, 3, MAIL_DLG_HEIGHT, N_("To")),
3000 /* 8 */ QUICK_LABEL (3, 50, 2, MAIL_DLG_HEIGHT, N_("mail -s <subject> -c <cc> <to>")),
3001 QUICK_END
3004 QuickDialog Quick_input = {
3005 50, MAIL_DLG_HEIGHT, -1, -1, N_("Mail"),
3006 "[Input Line Keys]", quick_widgets, NULL, FALSE
3009 quick_widgets[2].u.input.text = mail_cc_last ? mail_cc_last : "";
3010 quick_widgets[4].u.input.text = mail_subject_last ? mail_subject_last : "";
3011 quick_widgets[6].u.input.text = mail_to_last ? mail_to_last : "";
3013 if (quick_dialog (&Quick_input) != B_CANCEL)
3015 g_free (mail_cc_last);
3016 g_free (mail_subject_last);
3017 g_free (mail_to_last);
3018 mail_cc_last = tmail_cc;
3019 mail_subject_last = tmail_subject;
3020 mail_to_last = tmail_to;
3021 pipe_mail (edit, mail_to_last, mail_subject_last, mail_cc_last);
3026 /*******************/
3027 /* Word Completion */
3028 /*******************/
3030 /* --------------------------------------------------------------------------------------------- */
3032 * Complete current word using regular expression search
3033 * backwards beginning at the current cursor position.
3036 void
3037 edit_complete_word_cmd (WEdit * edit)
3039 gsize i, max_len, word_len = 0, num_compl = 0;
3040 long word_start = 0;
3041 unsigned char *bufpos;
3042 char *match_expr;
3043 struct selection compl[MAX_WORD_COMPLETIONS]; /* completions */
3045 /* search start of word to be completed */
3046 if (!edit_find_word_start (edit, &word_start, &word_len))
3047 return;
3049 /* prepare match expression */
3050 bufpos = &edit->buffers1[word_start >> S_EDIT_BUF_SIZE][word_start & M_EDIT_BUF_SIZE];
3052 /* match_expr = g_strdup_printf ("\\b%.*s[a-zA-Z_0-9]+", word_len, bufpos); */
3053 match_expr =
3054 g_strdup_printf
3055 ("(^|\\s+|\\b)%.*s[^\\s\\.=\\+\\[\\]\\(\\)\\,\\;\\:\\\"\\'\\-\\?\\/\\|\\\\\\{\\}\\*\\&\\^\\%%\\$#@\\!]+",
3056 (int) word_len, bufpos);
3058 /* collect the possible completions */
3059 /* start search from begin to end of file */
3060 max_len =
3061 edit_collect_completions (edit, word_start, word_len, match_expr,
3062 (struct selection *) &compl, &num_compl);
3064 if (num_compl > 0)
3066 /* insert completed word if there is only one match */
3067 if (num_compl == 1)
3069 for (i = word_len; i < compl[0].len; i++)
3070 edit_insert (edit, *(compl[0].text + i));
3072 /* more than one possible completion => ask the user */
3073 else
3075 /* !!! usually only a beep is expected and when <ALT-TAB> is !!! */
3076 /* !!! pressed again the selection dialog pops up, but that !!! */
3077 /* !!! seems to require a further internal state !!! */
3078 /*tty_beep (); */
3080 /* let the user select the preferred completion */
3081 editcmd_dialog_completion_show (edit, max_len, word_len,
3082 (struct selection *) &compl, num_compl);
3086 g_free (match_expr);
3087 /* release memory before return */
3088 for (i = 0; i < num_compl; i++)
3089 g_free (compl[i].text);
3092 /* --------------------------------------------------------------------------------------------- */
3094 void
3095 edit_select_codepage_cmd (WEdit * edit)
3097 #ifdef HAVE_CHARSET
3098 if (do_select_codepage ())
3099 edit_set_codeset (edit);
3101 edit->force = REDRAW_COMPLETELY;
3102 edit_refresh_cmd (edit);
3103 #else
3104 (void) edit;
3105 #endif
3108 /* --------------------------------------------------------------------------------------------- */
3110 void
3111 edit_insert_literal_cmd (WEdit * edit)
3113 int char_for_insertion = editcmd_dialog_raw_key_query (_("Insert literal"),
3114 _("Press any key:"), 0);
3115 edit_execute_key_command (edit, -1, ascii_alpha_to_cntrl (char_for_insertion));
3118 /* --------------------------------------------------------------------------------------------- */
3120 void
3121 edit_begin_end_macro_cmd (WEdit * edit)
3123 /* edit is a pointer to the widget */
3124 if (edit != NULL)
3126 unsigned long command = macro_index < 0 ? CK_MacroStartRecord : CK_MacroStopRecord;
3127 edit_execute_key_command (edit, command, -1);
3131 /* --------------------------------------------------------------------------------------------- */
3133 void
3134 edit_begin_end_repeat_cmd (WEdit * edit)
3136 /* edit is a pointer to the widget */
3137 if (edit != NULL)
3139 unsigned long command = macro_index < 0 ? CK_RepeatStartRecord : CK_RepeatStopRecord;
3140 edit_execute_key_command (edit, command, -1);
3144 /* --------------------------------------------------------------------------------------------- */
3147 edit_load_forward_cmd (WEdit * edit)
3149 if (edit->modified)
3151 if (edit_query_dialog2
3152 (_("Warning"),
3153 _("Current text was modified without a file save\n"
3154 "Continue discards these changes"), _("C&ontinue"), _("&Cancel")))
3156 edit->force |= REDRAW_COMPLETELY;
3157 return 0;
3160 if (edit_stack_iterator + 1 < MAX_HISTORY_MOVETO)
3162 if (edit_history_moveto[edit_stack_iterator + 1].line < 1)
3164 return 1;
3166 edit_stack_iterator++;
3167 if (edit_history_moveto[edit_stack_iterator].filename_vpath)
3169 edit_reload_line (edit, edit_history_moveto[edit_stack_iterator].filename_vpath,
3170 edit_history_moveto[edit_stack_iterator].line);
3171 return 0;
3173 else
3175 return 1;
3178 else
3180 return 1;
3184 /* --------------------------------------------------------------------------------------------- */
3187 edit_load_back_cmd (WEdit * edit)
3189 if (edit->modified)
3191 if (edit_query_dialog2
3192 (_("Warning"),
3193 _("Current text was modified without a file save\n"
3194 "Continue discards these changes"), _("C&ontinue"), _("&Cancel")))
3196 edit->force |= REDRAW_COMPLETELY;
3197 return 0;
3200 if (edit_stack_iterator > 0)
3202 edit_stack_iterator--;
3203 if (edit_history_moveto[edit_stack_iterator].filename_vpath)
3205 edit_reload_line (edit, edit_history_moveto[edit_stack_iterator].filename_vpath,
3206 edit_history_moveto[edit_stack_iterator].line);
3207 return 0;
3209 else
3211 return 1;
3214 else
3216 return 1;
3220 /* --------------------------------------------------------------------------------------------- */
3222 void
3223 edit_get_match_keyword_cmd (WEdit * edit)
3225 gsize word_len = 0, max_len = 0;
3226 int num_def = 0;
3227 int i;
3228 long word_start = 0;
3229 unsigned char *bufpos;
3230 char *match_expr;
3231 char *path = NULL;
3232 char *ptr = NULL;
3233 char *tagfile = NULL;
3235 etags_hash_t def_hash[MAX_DEFINITIONS];
3237 for (i = 0; i < MAX_DEFINITIONS; i++)
3239 def_hash[i].filename = NULL;
3242 /* search start of word to be completed */
3243 if (!edit_find_word_start (edit, &word_start, &word_len))
3244 return;
3246 /* prepare match expression */
3247 bufpos = &edit->buffers1[word_start >> S_EDIT_BUF_SIZE][word_start & M_EDIT_BUF_SIZE];
3248 match_expr = g_strdup_printf ("%.*s", (int) word_len, bufpos);
3250 ptr = g_get_current_dir ();
3251 path = g_strconcat (ptr, G_DIR_SEPARATOR_S, (char *) NULL);
3252 g_free (ptr);
3254 /* Recursive search file 'TAGS' in parent dirs */
3257 ptr = g_path_get_dirname (path);
3258 g_free (path);
3259 path = ptr;
3260 g_free (tagfile);
3261 tagfile = mc_build_filename (path, TAGS_NAME, (char *) NULL);
3262 if (exist_file (tagfile))
3263 break;
3265 while (strcmp (path, G_DIR_SEPARATOR_S) != 0);
3267 if (tagfile)
3269 num_def =
3270 etags_set_definition_hash (tagfile, path, match_expr, (etags_hash_t *) & def_hash);
3271 g_free (tagfile);
3273 g_free (path);
3275 max_len = MAX_WIDTH_DEF_DIALOG;
3276 word_len = 0;
3277 if (num_def > 0)
3279 editcmd_dialog_select_definition_show (edit, match_expr, max_len, word_len,
3280 (etags_hash_t *) & def_hash, num_def);
3282 g_free (match_expr);
3285 /* --------------------------------------------------------------------------------------------- */