Updated italian translation
[midnight-commander.git] / src / user.c
blob932ce9b23e618a29473ccc4db0ef853f32858b5c
1 /* User Menu implementation
2 Copyright (C) 1994 Miguel de Icaza, Janne Kukonlehto
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 #include <config.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <ctype.h>
22 #include <errno.h>
24 #include "global.h"
25 #include "tty.h"
26 #include "color.h"
27 #include "dir.h"
28 #include "panel.h"
29 #include "main.h"
30 #include "subshell.h" /* for subshell_pty */
31 #include "user.h"
32 #include "layout.h"
33 #include "execute.h"
34 #include "setup.h"
36 #include "../edit/edit.h" /* BLOCK_FILE */
37 #include "../edit/edit-widget.h" /* WEdit */
39 /* For the simple listbox manager */
40 #include "dialog.h"
41 #include "widget.h"
42 #include "wtools.h"
44 #include "view.h" /* for default_* externs */
46 #define MAX_ENTRIES 16
47 #define MAX_ENTRY_LEN 60
49 static int debug_flag = 0;
50 static int debug_error = 0;
51 static char *menu = NULL;
53 /* Formats defined:
54 %% The % character
55 %f The current file (if non-local vfs, file will be copied locally and
56 %f will be full path to it).
57 %p The current file
58 %d The current working directory
59 %s "Selected files"; the tagged files if any, otherwise the current file
60 %t Tagged files
61 %u Tagged files (and they are untagged on return from expand_format)
62 %view Runs the commands and pipes standard output to the view command.
63 If %view is immediately followed by '{', recognize keywords
64 ascii, hex, nroff and unform
66 If the format letter is in uppercase, it refers to the other panel.
68 With a number followed the % character you can turn quoting on (default)
69 and off. For example:
70 %f quote expanded macro
71 %1f ditto
72 %0f don't quote expanded macro
74 expand_format returns a memory block that must be free()d.
77 /* Returns how many characters we should advance if %view was found */
78 int check_format_view (const char *p)
80 const char *q = p;
81 if (!strncmp (p, "view", 4)) {
82 q += 4;
83 if (*q == '{'){
84 for (q++;*q && *q != '}';q++) {
85 if (!strncmp (q, "ascii", 5)) {
86 default_hex_mode = 0;
87 q += 4;
88 } else if (!strncmp (q, "hex", 3)) {
89 default_hex_mode = 1;
90 q += 2;
91 } else if (!strncmp (q, "nroff", 5)) {
92 default_nroff_flag = 1;
93 q += 4;
94 } else if (!strncmp (q, "unform", 6)) {
95 default_nroff_flag = 0;
96 q += 5;
99 if (*q == '}')
100 q++;
102 return q - p;
104 return 0;
107 int check_format_cd (const char *p)
109 return (strncmp (p, "cd", 2)) ? 0 : 3;
112 /* Check if p has a "^var\{var-name\}" */
113 /* Returns the number of skipped characters (zero on not found) */
114 /* V will be set to the expanded variable name */
115 int check_format_var (const char *p, char **v)
117 const char *q = p;
118 char *var_name;
119 char *value;
120 const char *dots = 0;
122 *v = 0;
123 if (!strncmp (p, "var{", 4)){
124 for (q += 4; *q && *q != '}'; q++){
125 if (*q == ':')
126 dots = q+1;
128 if (!*q)
129 return 0;
131 if (!dots || dots == q+5){
132 message (1,
133 _(" Format error on file Extensions File "),
134 !dots ? _(" The %%var macro has no default ")
135 : _(" The %%var macro has no variable "));
136 return 0;
139 /* Copy the variable name */
140 var_name = g_malloc (dots - p);
141 strncpy (var_name, p+4, dots-2 - (p+3));
142 var_name [dots-2 - (p+3)] = 0;
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_malloc (q - dots + 1);
151 strncpy (var_name, dots, q - dots + 1);
152 var_name [q-dots] = 0;
153 *v = var_name;
154 return q-p;
156 return 0;
159 /* strip file's extension */
160 static char *
161 strip_ext(char *ss)
163 register char *s = ss;
164 char *e = NULL;
165 while(*s) {
166 if(*s == '.') e = s;
167 if(*s == PATH_SEP && e) e=NULL; /* '.' in *directory* name */
168 s++;
170 if(e) *e = 0;
171 return ss;
174 char *
175 expand_format (struct WEdit *edit_widget, char c, int quote)
177 WPanel *panel;
178 char *(*quote_func) (const char *, int);
179 char *fname;
181 if (c == '%')
182 return g_strdup ("%");
184 if (islower ((unsigned) c))
185 panel = current_panel;
186 else {
187 if (get_other_type () != view_listing)
188 return g_strdup ("");
189 panel = other_panel;
191 if (!panel)
192 panel = current_panel;
194 if (quote)
195 quote_func = name_quote;
196 else
197 quote_func = fake_name_quote;
199 c = tolower (c);
200 fname = panel->dir.list[panel->selected].fname;
202 switch (c) {
203 case 'f':
204 case 'p':
205 return (*quote_func) (fname, 0);
206 case 'x':
207 return (*quote_func) (extension (fname), 0);
208 case 'd':
209 return (*quote_func) (panel->cwd, 0);
210 case 'i': /* indent equal number cursor position in line */
211 if (edit_widget)
212 return g_strnfill (edit_widget->curs_col, ' ');
213 break;
214 case 'y': /* syntax type */
215 if (edit_widget && edit_widget->syntax_type)
216 return g_strdup (edit_widget->syntax_type);
217 break;
218 case 'k': /* block file name */
219 case 'b': /* block file name / strip extension */ {
220 if (edit_widget) {
221 char *file = g_strconcat (home_dir, BLOCK_FILE, NULL);
222 fname = (*quote_func) (file, 0);
223 g_free (file);
224 return fname;
225 } else if (c == 'b') {
226 return strip_ext ((*quote_func) (fname, 0));
228 break;
230 case 'n': /* strip extension in editor */
231 if (edit_widget)
232 return strip_ext ((*quote_func) (fname, 0));
233 break;
234 case 'm': /* menu file name */
235 if (menu)
236 return (*quote_func) (menu, 0);
237 break;
238 case 's':
239 if (!panel->marked)
240 return (*quote_func) (fname, 0);
242 /* Fall through */
244 case 't':
245 case 'u':
247 int length = 2, i;
248 char *block, *tmp;
250 for (i = 0; i < panel->count; i++)
251 if (panel->dir.list[i].f.marked)
252 length += strlen (panel->dir.list[i].fname) + 1; /* for space */
254 block = g_malloc (length * 2 + 1);
255 *block = 0;
256 for (i = 0; i < panel->count; i++)
257 if (panel->dir.list[i].f.marked) {
258 strcat (block, tmp =
259 (*quote_func) (panel->dir.list[i].fname, 0));
260 g_free (tmp);
261 strcat (block, " ");
262 if (c == 'u')
263 do_file_mark (panel, i, 0);
265 return block;
266 } /* sub case block */
267 } /* switch */
268 return g_strdup ("%");
272 * Check for the "shell_patterns" directive. If it's found and valid,
273 * interpret it and move the pointer past the directive. Return the
274 * current pointer.
276 static char *
277 check_patterns (char *p)
279 static const char def_name[] = "shell_patterns=";
280 char *p0 = p;
282 if (strncmp (p, def_name, sizeof (def_name) - 1) != 0)
283 return p0;
285 p += sizeof (def_name) - 1;
286 if (*p == '1')
287 easy_patterns = 1;
288 else if (*p == '0')
289 easy_patterns = 0;
290 else
291 return p0;
293 /* Skip spaces */
294 p++;
295 while (*p == '\n' || *p == '\t' || *p == ' ')
296 p++;
297 return p;
300 /* Copies a whitespace separated argument from p to arg. Returns the
301 point after argument. */
302 static char *extract_arg (char *p, char *arg)
304 while (*p && (*p == ' ' || *p == '\t' || *p == '\n'))
305 p++;
306 /* support quote space .mnu */
307 while (*p && (*p != ' ' || *(p-1) == '\\') && *p != '\t' && *p != '\n')
308 *arg++ = *p++;
309 *arg = 0;
310 if (!*p || *p == '\n')
311 p --;
312 return p;
315 /* Tests whether the selected file in the panel is of any of the types
316 specified in argument. */
317 static int test_type (WPanel *panel, char *arg)
319 int result = 0; /* False by default */
320 int st_mode = panel->dir.list [panel->selected].st.st_mode;
322 for (;*arg != 0; arg++){
323 switch (*arg){
324 case 'n': /* Not a directory */
325 result |= !S_ISDIR (st_mode);
326 break;
327 case 'r': /* Regular file */
328 result |= S_ISREG (st_mode);
329 break;
330 case 'd': /* Directory */
331 result |= S_ISDIR (st_mode);
332 break;
333 case 'l': /* Link */
334 result |= S_ISLNK (st_mode);
335 break;
336 case 'c': /* Character special */
337 result |= S_ISCHR (st_mode);
338 break;
339 case 'b': /* Block special */
340 result |= S_ISBLK (st_mode);
341 break;
342 case 'f': /* Fifo (named pipe) */
343 result |= S_ISFIFO (st_mode);
344 break;
345 case 's': /* Socket */
346 result |= S_ISSOCK (st_mode);
347 break;
348 case 'x': /* Executable */
349 result |= (st_mode & 0111) ? 1 : 0;
350 break;
351 case 't':
352 result |= panel->marked ? 1 : 0;
353 break;
354 default:
355 debug_error = 1;
356 break;
359 return result;
362 /* Calculates the truth value of the next condition starting from
363 p. Returns the point after condition. */
364 static char *test_condition (WEdit *edit_widget, char *p, int *condition)
366 WPanel *panel;
367 char arg [256];
369 /* Handle one condition */
370 for (;*p != '\n' && *p != '&' && *p != '|'; p++){
371 /* support quote space .mnu */
372 if ((*p == ' ' && *(p-1) != '\\') || *p == '\t')
373 continue;
374 if (*p >= 'a')
375 panel = current_panel;
376 else {
377 if (get_other_type () == view_listing)
378 panel = other_panel;
379 else
380 panel = NULL;
382 *p |= 0x20;
384 switch (*p++){
385 case '!':
386 p = test_condition (edit_widget, p, condition);
387 *condition = ! *condition;
388 p--;
389 break;
390 case 'f': /* file name pattern */
391 p = extract_arg (p, arg);
392 *condition = panel && regexp_match (arg, panel->dir.list [panel->selected].fname, match_file);
393 break;
394 case 'y': /* syntax pattern */
395 if (edit_widget && edit_widget->syntax_type) {
396 p = extract_arg (p, arg);
397 *condition = panel &&
398 regexp_match (arg, edit_widget->syntax_type, match_normal);
400 break;
401 case 'd':
402 p = extract_arg (p, arg);
403 *condition = panel && regexp_match (arg, panel->cwd, match_file);
404 break;
405 case 't':
406 p = extract_arg (p, arg);
407 *condition = panel && test_type (panel, arg);
408 break;
409 case 'x': /* executable */
411 struct stat status;
413 p = extract_arg (p, arg);
414 if (stat (arg, &status) == 0)
415 *condition = is_exe (status.st_mode);
416 else
417 *condition = 0;
418 break;
420 default:
421 debug_error = 1;
422 break;
423 } /* switch */
425 } /* while */
426 return p;
429 /* General purpose condition debug output handler */
430 static void
431 debug_out (char *start, char *end, int cond)
433 static char msg [256];
434 int len;
436 if (start == NULL && end == NULL){
437 if (cond == 0){
438 /* Init */
439 msg [0] = 0;
440 } else {
441 /* Show output */
442 if (!debug_flag)
443 return;
444 len = strlen (msg);
445 if (len)
446 msg [len - 1] = 0;
447 message (0, _(" Debug "), "%s", msg);
448 debug_flag = 0;
450 } else {
451 /* Save debug info for later output */
452 if (!debug_flag)
453 return;
454 /* Save the result of the condition */
455 if (debug_error){
456 strcat (msg, _(" ERROR: "));
457 debug_error = 0;
459 else if (cond)
460 strcat (msg, _(" True: "));
461 else
462 strcat (msg, _(" False: "));
463 /* Copy condition statement */
464 len = strlen (msg);
465 if (end == NULL){
466 /* Copy one character */
467 msg [len] = *start;
468 msg [len + 1] = 0;
469 } else {
470 /* Copy many characters */
471 while (start < end){
472 msg [len++] = *start++;
474 msg [len] = 0;
476 strcat (msg, " \n");
480 /* Calculates the truth value of one lineful of conditions. Returns
481 the point just before the end of line. */
482 static char *test_line (WEdit *edit_widget, char *p, int *result)
484 int condition;
485 char operator;
486 char *debug_start, *debug_end;
488 /* Init debugger */
489 debug_out (NULL, NULL, 0);
490 /* Repeat till end of line */
491 while (*p && *p != '\n') {
492 /* support quote space .mnu */
493 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
494 p++;
495 if (!*p || *p == '\n')
496 break;
497 operator = *p++;
498 if (*p == '?'){
499 debug_flag = 1;
500 p++;
502 /* support quote space .mnu */
503 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
504 p++;
505 if (!*p || *p == '\n')
506 break;
507 condition = 1; /* True by default */
509 debug_start = p;
510 p = test_condition (edit_widget, p, &condition);
511 debug_end = p;
512 /* Add one debug statement */
513 debug_out (debug_start, debug_end, condition);
515 switch (operator){
516 case '+':
517 case '=':
518 /* Assignment */
519 *result = condition;
520 break;
521 case '&': /* Logical and */
522 *result &= condition;
523 break;
524 case '|': /* Logical or */
525 *result |= condition;
526 break;
527 default:
528 debug_error = 1;
529 break;
530 } /* switch */
531 /* Add one debug statement */
532 debug_out (&operator, NULL, *result);
534 } /* while (*p != '\n') */
535 /* Report debug message */
536 debug_out (NULL, NULL, 1);
538 if (!*p || *p == '\n')
539 p --;
540 return p;
543 /* FIXME: recode this routine on version 3.0, it could be cleaner */
544 static void
545 execute_menu_command (WEdit *edit_widget, const char *commands)
547 FILE *cmd_file;
548 int cmd_file_fd;
549 int expand_prefix_found = 0;
550 char *parameter = 0;
551 int do_quote = 0;
552 char prompt [80];
553 int col;
554 char *file_name;
555 int run_view = 0;
557 /* Skip menu entry title line */
558 commands = strchr (commands, '\n');
559 if (!commands){
560 return;
563 cmd_file_fd = mc_mkstemps (&file_name, "mcusr", SCRIPT_SUFFIX);
565 if (cmd_file_fd == -1){
566 message (1, MSG_ERROR, _(" Cannot create temporary command file \n %s "),
567 unix_error_string (errno));
568 return;
570 cmd_file = fdopen (cmd_file_fd, "w");
571 fputs ("#! /bin/sh\n", cmd_file);
572 commands++;
574 for (col = 0; *commands; commands++){
575 if (col == 0) {
576 if (*commands != ' ' && *commands != '\t')
577 break;
578 while (*commands == ' ' || *commands == '\t')
579 commands++;
580 if (*commands == 0)
581 break;
583 col++;
584 if (*commands == '\n')
585 col = 0;
586 if (parameter){
587 if (*commands == '}'){
588 char *tmp;
589 *parameter = 0;
590 parameter = input_dialog (_(" Parameter "), prompt, "");
591 if (!parameter || !*parameter){
592 /* User canceled */
593 fclose (cmd_file);
594 unlink (file_name);
595 g_free (file_name);
596 return;
598 if (do_quote) {
599 fputs (tmp = name_quote (parameter, 0), cmd_file);
600 g_free (tmp);
601 } else
602 fputs (parameter, cmd_file);
603 g_free (parameter);
604 parameter = 0;
605 } else {
606 if (parameter < &prompt [sizeof (prompt) - 1]) {
607 *parameter++ = *commands;
610 } else if (expand_prefix_found){
611 expand_prefix_found = 0;
612 if (isdigit ((unsigned)*commands)) {
613 do_quote = atoi (commands);
614 while (isdigit ((unsigned)*commands))
615 commands++;
617 if (*commands == '{')
618 parameter = prompt;
619 else{
620 char *text = expand_format (edit_widget, *commands, do_quote);
621 fputs (text, cmd_file);
622 g_free (text);
624 } else {
625 if (*commands == '%') {
626 int i = check_format_view (commands + 1);
627 if (i) {
628 commands += i;
629 run_view = 1;
630 } else {
631 do_quote = 1; /* Default: Quote expanded macro */
632 expand_prefix_found = 1;
634 } else
635 fputc (*commands, cmd_file);
638 fclose (cmd_file);
639 chmod (file_name, S_IRWXU);
640 if (run_view) {
641 run_view = 0;
642 view (file_name, 0, &run_view, 0);
643 } else {
644 shell_execute (file_name, 0);
646 unlink (file_name);
647 g_free (file_name);
651 ** Check owner of the menu file. Using menu file is allowed, if
652 ** owner of the menu is root or the actual user. In either case
653 ** file should not be group and word-writable.
655 ** Q. Should we apply this routine to system and home menu (and .ext files)?
657 static int
658 menu_file_own(char* path)
660 struct stat st;
662 if (stat (path, &st) == 0
663 && (!st.st_uid || (st.st_uid == geteuid ()))
664 && ((st.st_mode & (S_IWGRP | S_IWOTH)) == 0)
666 return 1;
668 if (verbose)
670 message (0, _(" Warning -- ignoring file "),
671 _("File %s is not owned by root or you or is world writable.\n"
672 "Using it may compromise your security"),
673 path
676 return 0;
680 * If edit_widget is NULL then we are called from the mc menu,
681 * otherwise we are called from the mcedit menu.
683 void
684 user_menu_cmd (struct WEdit *edit_widget)
686 char *p;
687 char *data, **entries;
688 int max_cols, menu_lines, menu_limit;
689 int col, i, accept_entry = 1;
690 int selected, old_patterns;
691 Listbox *listbox;
693 if (!vfs_current_is_local ()){
694 message (1, MSG_ERROR,
695 _(" Cannot execute commands on non-local filesystems"));
696 return;
699 menu = g_strdup (edit_widget ? CEDIT_LOCAL_MENU : MC_LOCAL_MENU);
700 if (!exist_file (menu) || !menu_file_own (menu)){
701 g_free (menu);
702 menu = concat_dir_and_file \
703 (home_dir, edit_widget ? CEDIT_HOME_MENU : MC_HOME_MENU);
704 if (!exist_file (menu)){
705 g_free (menu);
706 menu = concat_dir_and_file \
707 (mc_home, edit_widget ? CEDIT_GLOBAL_MENU : MC_GLOBAL_MENU);
711 if ((data = load_file (menu)) == NULL){
712 message (1, MSG_ERROR, _(" Cannot open file %s \n %s "),
713 menu, unix_error_string (errno));
714 g_free (menu);
715 menu = NULL;
716 return;
719 max_cols = 0;
720 selected = 0;
721 menu_limit = 0;
722 entries = 0;
724 /* Parse the menu file */
725 old_patterns = easy_patterns;
726 p = check_patterns (data);
727 for (menu_lines = col = 0; *p; p++){
728 if (menu_lines >= menu_limit){
729 char ** new_entries;
731 menu_limit += MAX_ENTRIES;
732 new_entries = g_realloc (entries, sizeof (new_entries[0]) * menu_limit);
734 if (new_entries == 0)
735 break;
737 entries = new_entries;
738 new_entries += menu_limit;
739 while (--new_entries >= &entries[menu_lines])
740 *new_entries = 0;
742 if (col == 0 && !entries [menu_lines]){
743 if (*p == '#'){
744 /* A commented menu entry */
745 accept_entry = 1;
746 } else if (*p == '+'){
747 if (*(p+1) == '='){
748 /* Combined adding and default */
749 p = test_line (edit_widget, p, &accept_entry);
750 if (selected == 0 && accept_entry)
751 selected = menu_lines;
752 } else {
753 /* A condition for adding the entry */
754 p = test_line (edit_widget, p, &accept_entry);
756 } else if (*p == '='){
757 if (*(p+1) == '+'){
758 /* Combined adding and default */
759 p = test_line (edit_widget, p, &accept_entry);
760 if (selected == 0 && accept_entry)
761 selected = menu_lines;
762 } else {
763 /* A condition for making the entry default */
764 i = 1;
765 p = test_line (edit_widget, p, &i);
766 if (selected == 0 && i)
767 selected = menu_lines;
770 else if (*p != ' ' && *p != '\t' && is_printable (*p)) {
771 /* A menu entry title line */
772 if (accept_entry)
773 entries [menu_lines] = p;
774 else
775 accept_entry = 1;
778 if (*p == '\n'){
779 if (entries [menu_lines]){
780 menu_lines++;
781 accept_entry = 1;
783 max_cols = max (max_cols, col);
784 col = 0;
785 } else {
786 if (*p == '\t')
787 *p = ' ';
788 col++;
792 if (menu_lines == 0) {
793 message (1, MSG_ERROR, _(" No suitable entries found in %s "), menu);
794 } else {
796 max_cols = min (max (max_cols, col), MAX_ENTRY_LEN);
798 /* Create listbox */
799 listbox = create_listbox_window (max_cols+2, menu_lines, _(" User menu "),
800 "[Menu File Edit]");
801 /* insert all the items found */
802 for (i = 0; i < menu_lines; i++) {
803 p = entries [i];
804 LISTBOX_APPEND_TEXT (listbox, (unsigned char) p[0],
805 extract_line (p, p + MAX_ENTRY_LEN), p
808 /* Select the default entry */
809 listbox_select_by_number (listbox->list, selected);
811 selected = run_listbox (listbox);
812 if (selected >= 0)
813 execute_menu_command (edit_widget, entries [selected]);
815 do_refresh ();
818 easy_patterns = old_patterns;
819 g_free (menu);
820 menu = NULL;
821 if (entries)
822 g_free (entries);
823 g_free (data);