Not only comment it out but removing it
[midnight-commander.git] / src / user.c
blob7cb617c3bee4f61b49e069fc72c83a4b9b20f24d
1 /* User Menu implementation
2 Copyright (C) 1994, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 2006, 2007 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
19 #include <config.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <string.h>
26 #include "global.h"
27 #include "tty.h"
28 #include "color.h"
29 #include "dir.h"
30 #include "panel.h"
31 #include "main.h"
32 #include "user.h"
33 #include "layout.h"
34 #include "execute.h"
35 #include "setup.h"
36 #include "history.h"
38 #include "../edit/edit.h" /* BLOCK_FILE */
39 #include "../edit/edit-widget.h" /* WEdit */
41 /* For the simple listbox manager */
42 #include "dialog.h"
43 #include "widget.h"
44 #include "wtools.h"
46 #include "view.h" /* for default_* externs */
48 #define MAX_ENTRIES 16
49 #define MAX_ENTRY_LEN 60
51 static int debug_flag = 0;
52 static int debug_error = 0;
53 static char *menu = NULL;
55 /* Formats defined:
56 %% The % character
57 %f The current file (if non-local vfs, file will be copied locally and
58 %f will be full path to it).
59 %p The current file
60 %d The current working directory
61 %s "Selected files"; the tagged files if any, otherwise the current file
62 %t Tagged files
63 %u Tagged files (and they are untagged on return from expand_format)
64 %view Runs the commands and pipes standard output to the view command.
65 If %view is immediately followed by '{', recognize keywords
66 ascii, hex, nroff and unform
68 If the format letter is in uppercase, it refers to the other panel.
70 With a number followed the % character you can turn quoting on (default)
71 and off. For example:
72 %f quote expanded macro
73 %1f ditto
74 %0f don't quote expanded macro
76 expand_format returns a memory block that must be free()d.
79 /* Returns how many characters we should advance if %view was found */
80 int check_format_view (const char *p)
82 const char *q = p;
83 if (!strncmp (p, "view", 4)) {
84 q += 4;
85 if (*q == '{'){
86 for (q++;*q && *q != '}';q++) {
87 if (!strncmp (q, "ascii", 5)) {
88 default_hex_mode = 0;
89 q += 4;
90 } else if (!strncmp (q, "hex", 3)) {
91 default_hex_mode = 1;
92 q += 2;
93 } else if (!strncmp (q, "nroff", 5)) {
94 default_nroff_flag = 1;
95 q += 4;
96 } else if (!strncmp (q, "unform", 6)) {
97 default_nroff_flag = 0;
98 q += 5;
101 if (*q == '}')
102 q++;
104 return q - p;
106 return 0;
109 int check_format_cd (const char *p)
111 return (strncmp (p, "cd", 2)) ? 0 : 3;
114 /* Check if p has a "^var\{var-name\}" */
115 /* Returns the number of skipped characters (zero on not found) */
116 /* V will be set to the expanded variable name */
117 int check_format_var (const char *p, char **v)
119 const char *q = p;
120 char *var_name;
121 const char *value;
122 const char *dots = 0;
124 *v = 0;
125 if (!strncmp (p, "var{", 4)){
126 for (q += 4; *q && *q != '}'; q++){
127 if (*q == ':')
128 dots = q+1;
130 if (!*q)
131 return 0;
133 if (!dots || dots == q+5){
134 message (1,
135 _(" Format error on file Extensions File "),
136 !dots ? _(" The %%var macro has no default ")
137 : _(" The %%var macro has no variable "));
138 return 0;
141 /* Copy the variable name */
142 var_name = g_strndup (p + 4, dots-2 - (p+3));
144 value = getenv (var_name);
145 g_free (var_name);
146 if (value){
147 *v = g_strdup (value);
148 return q-p;
150 var_name = g_strndup (dots, q - dots);
151 *v = var_name;
152 return q-p;
154 return 0;
157 /* strip file's extension */
158 static char *
159 strip_ext(char *ss)
161 register char *s = ss;
162 char *e = NULL;
163 while(*s) {
164 if(*s == '.') e = s;
165 if(*s == PATH_SEP && e) e=NULL; /* '.' in *directory* name */
166 s++;
168 if(e) *e = 0;
169 return ss;
172 char *
173 expand_format (struct WEdit *edit_widget, char c, int quote)
175 WPanel *panel = NULL;
176 char *(*quote_func) (const char *, int);
177 char *fname;
178 char *result;
179 char c_lc;
181 if (c == '%')
182 return g_strdup ("%");
184 if (edit_one_file != NULL)
185 fname = edit_widget->filename;
186 else {
187 if (islower ((unsigned char) c))
188 panel = current_panel;
189 else {
190 if (get_other_type () != view_listing)
191 return g_strdup ("");
192 panel = other_panel;
194 fname = panel->dir.list[panel->selected].fname;
197 if (quote)
198 quote_func = name_quote;
199 else
200 quote_func = fake_name_quote;
202 c_lc = tolower ((unsigned char) c);
204 switch (c_lc) {
205 case 'f':
206 case 'p':
207 return (*quote_func) (fname, 0);
208 case 'x':
209 return (*quote_func) (extension (fname), 0);
210 case 'd':
212 char *cwd;
213 char *qstr;
215 cwd = g_malloc(MC_MAXPATHLEN + 1);
217 if (panel)
218 g_strlcpy(cwd, panel->cwd, MC_MAXPATHLEN + 1);
219 else
220 mc_get_current_wd(cwd, MC_MAXPATHLEN + 1);
222 qstr = (*quote_func) (cwd, 0);
224 g_free (cwd);
226 return qstr;
228 case 'i': /* indent equal number cursor position in line */
229 if (edit_widget)
230 return g_strnfill (edit_widget->curs_col, ' ');
231 break;
232 case 'y': /* syntax type */
233 if (edit_widget && edit_widget->syntax_type)
234 return g_strdup (edit_widget->syntax_type);
235 break;
236 case 'k': /* block file name */
237 case 'b': /* block file name / strip extension */ {
238 if (edit_widget) {
239 char *file = g_strconcat (home_dir, PATH_SEP_STR BLOCK_FILE, (char *) NULL);
240 fname = (*quote_func) (file, 0);
241 g_free (file);
242 return fname;
243 } else if (c_lc == 'b') {
244 return strip_ext ((*quote_func) (fname, 0));
246 break;
248 case 'n': /* strip extension in editor */
249 if (edit_widget)
250 return strip_ext ((*quote_func) (fname, 0));
251 break;
252 case 'm': /* menu file name */
253 if (menu)
254 return (*quote_func) (menu, 0);
255 break;
256 case 's':
257 if (!panel || !panel->marked)
258 return (*quote_func) (fname, 0);
260 /* Fall through */
262 case 't':
263 case 'u':
265 int length = 2, i;
266 char *block, *tmp;
268 if (!panel)
269 return g_strdup ("");
271 for (i = 0; i < panel->count; i++)
272 if (panel->dir.list[i].f.marked)
273 length += strlen (panel->dir.list[i].fname) + 1; /* for space */
275 block = g_malloc (length * 2 + 1);
276 *block = 0;
277 for (i = 0; i < panel->count; i++)
278 if (panel->dir.list[i].f.marked) {
279 strcat (block, tmp =
280 (*quote_func) (panel->dir.list[i].fname, 0));
281 g_free (tmp);
282 strcat (block, " ");
283 if (c_lc == 'u')
284 do_file_mark (panel, i, 0);
286 return block;
287 } /* sub case block */
288 } /* switch */
289 result = g_strdup ("% ");
290 result[1] = c;
291 return result;
295 * Check for the "shell_patterns" directive. If it's found and valid,
296 * interpret it and move the pointer past the directive. Return the
297 * current pointer.
299 static char *
300 check_patterns (char *p)
302 static const char def_name[] = "shell_patterns=";
303 char *p0 = p;
305 if (strncmp (p, def_name, sizeof (def_name) - 1) != 0)
306 return p0;
308 p += sizeof (def_name) - 1;
309 if (*p == '1')
310 easy_patterns = 1;
311 else if (*p == '0')
312 easy_patterns = 0;
313 else
314 return p0;
316 /* Skip spaces */
317 p++;
318 while (*p == '\n' || *p == '\t' || *p == ' ')
319 p++;
320 return p;
323 /* Copies a whitespace separated argument from p to arg. Returns the
324 point after argument. */
325 static char *extract_arg (char *p, char *arg, int size)
327 while (*p && (*p == ' ' || *p == '\t' || *p == '\n'))
328 p++;
329 /* support quote space .mnu */
330 while (size > 1 && *p && (*p != ' ' || *(p-1) == '\\') && *p != '\t' && *p != '\n') {
331 *arg++ = *p++;
332 size--;
334 *arg = 0;
335 if (!*p || *p == '\n')
336 p --;
337 return p;
340 /* Tests whether the selected file in the panel is of any of the types
341 specified in argument. */
342 static int test_type (WPanel *panel, char *arg)
344 int result = 0; /* False by default */
345 int st_mode = panel->dir.list [panel->selected].st.st_mode;
347 for (;*arg != 0; arg++){
348 switch (*arg){
349 case 'n': /* Not a directory */
350 result |= !S_ISDIR (st_mode);
351 break;
352 case 'r': /* Regular file */
353 result |= S_ISREG (st_mode);
354 break;
355 case 'd': /* Directory */
356 result |= S_ISDIR (st_mode);
357 break;
358 case 'l': /* Link */
359 result |= S_ISLNK (st_mode);
360 break;
361 case 'c': /* Character special */
362 result |= S_ISCHR (st_mode);
363 break;
364 case 'b': /* Block special */
365 result |= S_ISBLK (st_mode);
366 break;
367 case 'f': /* Fifo (named pipe) */
368 result |= S_ISFIFO (st_mode);
369 break;
370 case 's': /* Socket */
371 result |= S_ISSOCK (st_mode);
372 break;
373 case 'x': /* Executable */
374 result |= (st_mode & 0111) ? 1 : 0;
375 break;
376 case 't':
377 result |= panel->marked ? 1 : 0;
378 break;
379 default:
380 debug_error = 1;
381 break;
384 return result;
387 /* Calculates the truth value of the next condition starting from
388 p. Returns the point after condition. */
389 static char *test_condition (WEdit *edit_widget, char *p, int *condition)
391 WPanel *panel;
392 char arg [256];
394 /* Handle one condition */
395 for (;*p != '\n' && *p != '&' && *p != '|'; p++){
396 /* support quote space .mnu */
397 if ((*p == ' ' && *(p-1) != '\\') || *p == '\t')
398 continue;
399 if (*p >= 'a')
400 panel = current_panel;
401 else {
402 if (get_other_type () == view_listing)
403 panel = other_panel;
404 else
405 panel = NULL;
407 *p |= 0x20;
409 switch (*p++){
410 case '!':
411 p = test_condition (edit_widget, p, condition);
412 *condition = ! *condition;
413 p--;
414 break;
415 case 'f': /* file name pattern */
416 p = extract_arg (p, arg, sizeof (arg));
417 *condition = panel && regexp_match (arg, panel->dir.list [panel->selected].fname, match_file);
418 break;
419 case 'y': /* syntax pattern */
420 if (edit_widget && edit_widget->syntax_type) {
421 p = extract_arg (p, arg, sizeof (arg));
422 *condition = panel &&
423 regexp_match (arg, edit_widget->syntax_type, match_normal);
425 break;
426 case 'd':
427 p = extract_arg (p, arg, sizeof (arg));
428 *condition = panel && regexp_match (arg, panel->cwd, match_file);
429 break;
430 case 't':
431 p = extract_arg (p, arg, sizeof (arg));
432 *condition = panel && test_type (panel, arg);
433 break;
434 case 'x': /* executable */
436 struct stat status;
438 p = extract_arg (p, arg, sizeof (arg));
439 if (stat (arg, &status) == 0)
440 *condition = is_exe (status.st_mode);
441 else
442 *condition = 0;
443 break;
445 default:
446 debug_error = 1;
447 break;
448 } /* switch */
450 } /* while */
451 return p;
454 /* General purpose condition debug output handler */
455 static void
456 debug_out (char *start, char *end, int cond)
458 static char *msg;
459 int len;
461 if (start == NULL && end == NULL){
462 /* Show output */
463 if (debug_flag && msg) {
464 len = strlen (msg);
465 if (len)
466 msg [len - 1] = 0;
467 message (0, _(" Debug "), "%s", msg);
470 debug_flag = 0;
471 g_free (msg);
472 msg = NULL;
473 } else {
474 const char *type;
475 char *p;
477 /* Save debug info for later output */
478 if (!debug_flag)
479 return;
480 /* Save the result of the condition */
481 if (debug_error){
482 type = _(" ERROR: ");
483 debug_error = 0;
485 else if (cond)
486 type = _(" True: ");
487 else
488 type = _(" False: ");
489 /* This is for debugging, don't need to be super efficient. */
490 if (end == NULL)
491 p = g_strdup_printf ("%s%s%c \n", msg ? msg : "", type, *start);
492 else
493 p = g_strdup_printf ("%s%s%.*s \n", msg ? msg : "", type,
494 (int) (end - start), start);
495 g_free (msg);
496 msg = p;
500 /* Calculates the truth value of one lineful of conditions. Returns
501 the point just before the end of line. */
502 static char *test_line (WEdit *edit_widget, char *p, int *result)
504 int condition;
505 char operator;
506 char *debug_start, *debug_end;
508 /* Repeat till end of line */
509 while (*p && *p != '\n') {
510 /* support quote space .mnu */
511 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
512 p++;
513 if (!*p || *p == '\n')
514 break;
515 operator = *p++;
516 if (*p == '?'){
517 debug_flag = 1;
518 p++;
520 /* support quote space .mnu */
521 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
522 p++;
523 if (!*p || *p == '\n')
524 break;
525 condition = 1; /* True by default */
527 debug_start = p;
528 p = test_condition (edit_widget, p, &condition);
529 debug_end = p;
530 /* Add one debug statement */
531 debug_out (debug_start, debug_end, condition);
533 switch (operator){
534 case '+':
535 case '=':
536 /* Assignment */
537 *result = condition;
538 break;
539 case '&': /* Logical and */
540 *result &= condition;
541 break;
542 case '|': /* Logical or */
543 *result |= condition;
544 break;
545 default:
546 debug_error = 1;
547 break;
548 } /* switch */
549 /* Add one debug statement */
550 debug_out (&operator, NULL, *result);
552 } /* while (*p != '\n') */
553 /* Report debug message */
554 debug_out (NULL, NULL, 1);
556 if (!*p || *p == '\n')
557 p --;
558 return p;
561 /* FIXME: recode this routine on version 3.0, it could be cleaner */
562 static void
563 execute_menu_command (WEdit *edit_widget, const char *commands)
565 FILE *cmd_file;
566 int cmd_file_fd;
567 int expand_prefix_found = 0;
568 char *parameter = 0;
569 int do_quote = 0;
570 char prompt [80];
571 int col;
572 char *file_name;
573 int run_view = 0;
575 /* Skip menu entry title line */
576 commands = strchr (commands, '\n');
577 if (!commands){
578 return;
581 cmd_file_fd = mc_mkstemps (&file_name, "mcusr", SCRIPT_SUFFIX);
583 if (cmd_file_fd == -1){
584 message (1, MSG_ERROR, _(" Cannot create temporary command file \n %s "),
585 unix_error_string (errno));
586 return;
588 cmd_file = fdopen (cmd_file_fd, "w");
589 fputs ("#! /bin/sh\n", cmd_file);
590 commands++;
592 for (col = 0; *commands; commands++){
593 if (col == 0) {
594 if (*commands != ' ' && *commands != '\t')
595 break;
596 while (*commands == ' ' || *commands == '\t')
597 commands++;
598 if (*commands == 0)
599 break;
601 col++;
602 if (*commands == '\n')
603 col = 0;
604 if (parameter){
605 if (*commands == '}'){
606 char *tmp;
607 *parameter = 0;
608 parameter = input_dialog (_(" Parameter "), prompt, MC_HISTORY_FM_MENU_EXEC_PARAM, "");
609 if (!parameter || !*parameter){
610 /* User canceled */
611 fclose (cmd_file);
612 unlink (file_name);
613 g_free (file_name);
614 return;
616 if (do_quote) {
617 fputs (tmp = name_quote (parameter, 0), cmd_file);
618 g_free (tmp);
619 } else
620 fputs (parameter, cmd_file);
621 g_free (parameter);
622 parameter = 0;
623 } else {
624 if (parameter < &prompt [sizeof (prompt) - 1]) {
625 *parameter++ = *commands;
628 } else if (expand_prefix_found){
629 expand_prefix_found = 0;
630 if (isdigit ((unsigned char) *commands)) {
631 do_quote = atoi (commands);
632 while (isdigit ((unsigned char) *commands))
633 commands++;
635 if (*commands == '{')
636 parameter = prompt;
637 else{
638 char *text = expand_format (edit_widget, *commands, do_quote);
639 fputs (text, cmd_file);
640 g_free (text);
642 } else {
643 if (*commands == '%') {
644 int i = check_format_view (commands + 1);
645 if (i) {
646 commands += i;
647 run_view = 1;
648 } else {
649 do_quote = 1; /* Default: Quote expanded macro */
650 expand_prefix_found = 1;
652 } else
653 fputc (*commands, cmd_file);
656 fclose (cmd_file);
657 chmod (file_name, S_IRWXU);
658 if (run_view) {
659 run_view = 0;
660 mc_internal_viewer (file_name, NULL, &run_view, 0);
661 } else {
662 /* execute the command indirectly to allow execution even
663 * on no-exec filesystems. */
664 char *cmd = g_strconcat("/bin/sh ", file_name, (char *)NULL);
665 shell_execute (cmd, EXECUTE_HIDE);
666 g_free(cmd);
668 unlink (file_name);
669 g_free (file_name);
673 ** Check owner of the menu file. Using menu file is allowed, if
674 ** owner of the menu is root or the actual user. In either case
675 ** file should not be group and word-writable.
677 ** Q. Should we apply this routine to system and home menu (and .ext files)?
679 static int
680 menu_file_own(char* path)
682 struct stat st;
684 if (stat (path, &st) == 0
685 && (!st.st_uid || (st.st_uid == geteuid ()))
686 && ((st.st_mode & (S_IWGRP | S_IWOTH)) == 0)
688 return 1;
690 if (verbose)
692 message (0, _(" Warning -- ignoring file "),
693 _("File %s is not owned by root or you or is world writable.\n"
694 "Using it may compromise your security"),
695 path
698 return 0;
702 * If edit_widget is NULL then we are called from the mc menu,
703 * otherwise we are called from the mcedit menu.
705 void
706 user_menu_cmd (struct WEdit *edit_widget)
708 char *p;
709 char *data, **entries;
710 int max_cols, menu_lines, menu_limit;
711 int col, i, accept_entry = 1;
712 int selected, old_patterns;
713 Listbox *listbox;
715 if (!vfs_current_is_local ()){
716 message (1, MSG_ERROR,
717 _(" Cannot execute commands on non-local filesystems"));
718 return;
721 menu = g_strdup (edit_widget ? CEDIT_LOCAL_MENU : MC_LOCAL_MENU);
722 if (!exist_file (menu) || !menu_file_own (menu)){
723 g_free (menu);
724 menu = concat_dir_and_file \
725 (home_dir, edit_widget ? CEDIT_HOME_MENU : MC_HOME_MENU);
726 if (!exist_file (menu)){
727 g_free (menu);
728 menu = concat_dir_and_file \
729 (mc_home, edit_widget ? CEDIT_GLOBAL_MENU : MC_GLOBAL_MENU);
733 if ((data = load_file (menu)) == NULL){
734 message (1, MSG_ERROR, _(" Cannot open file %s \n %s "),
735 menu, unix_error_string (errno));
736 g_free (menu);
737 menu = NULL;
738 return;
741 max_cols = 0;
742 selected = 0;
743 menu_limit = 0;
744 entries = 0;
746 /* Parse the menu file */
747 old_patterns = easy_patterns;
748 p = check_patterns (data);
749 for (menu_lines = col = 0; *p; p++){
750 if (menu_lines >= menu_limit){
751 char ** new_entries;
753 menu_limit += MAX_ENTRIES;
754 new_entries = g_realloc (entries, sizeof (new_entries[0]) * menu_limit);
756 if (new_entries == 0)
757 break;
759 entries = new_entries;
760 new_entries += menu_limit;
761 while (--new_entries >= &entries[menu_lines])
762 *new_entries = 0;
764 if (col == 0 && !entries [menu_lines]){
765 if (*p == '#'){
766 /* A commented menu entry */
767 accept_entry = 1;
768 } else if (*p == '+'){
769 if (*(p+1) == '='){
770 /* Combined adding and default */
771 p = test_line (edit_widget, p + 1, &accept_entry);
772 if (selected == 0 && accept_entry)
773 selected = menu_lines;
774 } else {
775 /* A condition for adding the entry */
776 p = test_line (edit_widget, p, &accept_entry);
778 } else if (*p == '='){
779 if (*(p+1) == '+'){
780 /* Combined adding and default */
781 p = test_line (edit_widget, p + 1, &accept_entry);
782 if (selected == 0 && accept_entry)
783 selected = menu_lines;
784 } else {
785 /* A condition for making the entry default */
786 i = 1;
787 p = test_line (edit_widget, p, &i);
788 if (selected == 0 && i)
789 selected = menu_lines;
792 else if (*p != ' ' && *p != '\t' && is_printable (*p)) {
793 /* A menu entry title line */
794 if (accept_entry)
795 entries [menu_lines] = p;
796 else
797 accept_entry = 1;
800 if (*p == '\n'){
801 if (entries [menu_lines]){
802 menu_lines++;
803 accept_entry = 1;
805 max_cols = max (max_cols, col);
806 col = 0;
807 } else {
808 if (*p == '\t')
809 *p = ' ';
810 col++;
814 if (menu_lines == 0) {
815 message (1, MSG_ERROR, _(" No suitable entries found in %s "), menu);
816 } else {
818 max_cols = min (max (max_cols, col), MAX_ENTRY_LEN);
820 /* Create listbox */
821 listbox = create_listbox_window (max_cols+2, menu_lines, _(" User menu "),
822 "[Menu File Edit]");
823 /* insert all the items found */
824 for (i = 0; i < menu_lines; i++) {
825 p = entries [i];
826 LISTBOX_APPEND_TEXT (listbox, (unsigned char) p[0],
827 extract_line (p, p + MAX_ENTRY_LEN), p
830 /* Select the default entry */
831 listbox_select_by_number (listbox->list, selected);
833 selected = run_listbox (listbox);
834 if (selected >= 0)
835 execute_menu_command (edit_widget, entries [selected]);
837 do_refresh ();
840 easy_patterns = old_patterns;
841 g_free (menu);
842 menu = NULL;
843 g_free (entries);
844 g_free (data);