Mark the help view as refreshable
[tig.git] / src / prompt.c
blob8c34d3f18c38953490af477dd755ca0d4b97a30c
1 /* Copyright (c) 2006-2014 Jonas Fonseca <jonas.fonseca@gmail.com>
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU General Public License as
5 * published by the Free Software Foundation; either version 2 of
6 * the License, or (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
14 #include "tig/tig.h"
15 #include "tig/view.h"
16 #include "tig/draw.h"
17 #include "tig/display.h"
18 #include "tig/options.h"
19 #include "tig/prompt.h"
20 #include "tig/pager.h"
21 #include "tig/types.h"
23 #ifdef HAVE_READLINE
24 #include <readline/readline.h>
25 #include <readline/history.h>
26 #endif /* HAVE_READLINE */
28 static char *
29 prompt_input(const char *prompt, struct input *input)
31 enum input_status status = INPUT_OK;
32 unsigned char chars_length[SIZEOF_STR];
33 struct key key;
34 size_t promptlen = strlen(prompt);
35 int pos = 0, chars = 0;
37 input->buf[pos] = 0;
39 while (status == INPUT_OK || status == INPUT_SKIP) {
41 update_status("%s%.*s", prompt, pos, input->buf);
43 if (get_input(pos + promptlen, &key, FALSE) == OK) {
44 int len = strlen(key.data.bytes);
46 if (pos + len >= sizeof(input->buf)) {
47 report("Input string too long");
48 return NULL;
51 string_ncopy_do(input->buf + pos, sizeof(input->buf) - pos, key.data.bytes, len);
52 pos += len;
53 chars_length[chars++] = len;
54 status = input->handler(input, &key);
55 if (status != INPUT_OK) {
56 pos -= len;
57 chars--;
58 } else {
59 int changed_pos = strlen(input->buf);
61 if (changed_pos != pos) {
62 pos = changed_pos;
63 chars_length[chars - 1] = changed_pos - (pos - len);
66 } else {
67 status = input->handler(input, &key);
68 if (status == INPUT_DELETE) {
69 int len = chars_length[--chars];
71 pos -= len;
72 status = INPUT_OK;
73 } else {
74 int changed_pos = strlen(input->buf);
76 if (changed_pos != pos) {
77 pos = changed_pos;
78 chars_length[chars++] = changed_pos - pos;
82 input->buf[pos] = 0;
85 report_clear();
87 if (status == INPUT_CANCEL)
88 return NULL;
90 input->buf[pos++] = 0;
92 return input->buf;
95 static enum input_status
96 prompt_default_handler(struct input *input, struct key *key)
98 if (key->modifiers.multibytes)
99 return INPUT_SKIP;
101 switch (key->data.value) {
102 case KEY_RETURN:
103 case KEY_ENTER:
104 case '\n':
105 return *input->buf ? INPUT_STOP : INPUT_CANCEL;
107 case KEY_BACKSPACE:
108 return *input->buf ? INPUT_DELETE : INPUT_CANCEL;
110 case KEY_ESC:
111 return INPUT_CANCEL;
113 default:
114 return INPUT_SKIP;
118 static enum input_status
119 prompt_yesno_handler(struct input *input, struct key *key)
121 unsigned long c = key_to_unicode(key);
123 if (c == 'y' || c == 'Y')
124 return INPUT_STOP;
125 if (c == 'n' || c == 'N')
126 return INPUT_CANCEL;
127 return prompt_default_handler(input, key);
130 bool
131 prompt_yesno(const char *prompt)
133 char prompt2[SIZEOF_STR];
134 struct input input = { prompt_yesno_handler, NULL };
136 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
137 return FALSE;
139 return !!prompt_input(prompt2, &input);
142 struct incremental_input {
143 struct input input;
144 input_handler handler;
145 bool edit_mode;
148 static enum input_status
149 read_prompt_handler(struct input *input, struct key *key)
151 struct incremental_input *incremental = (struct incremental_input *) input;
153 if (incremental->edit_mode && !key->modifiers.multibytes)
154 return prompt_default_handler(input, key);
156 if (!unicode_width(key_to_unicode(key), 8))
157 return INPUT_SKIP;
159 if (!incremental->handler)
160 return INPUT_OK;
162 return incremental->handler(input, key);
165 char *
166 read_prompt_incremental(const char *prompt, bool edit_mode, input_handler handler, void *data)
168 static struct incremental_input incremental = { { read_prompt_handler } };
170 incremental.input.data = data;
171 incremental.handler = handler;
172 incremental.edit_mode = edit_mode;
174 return prompt_input(prompt, (struct input *) &incremental);
177 #ifdef HAVE_READLINE
178 static void
179 readline_display(void)
181 wmove(status_win, 0, 0);
182 waddstr(status_win, rl_display_prompt);
183 waddstr(status_win, rl_line_buffer);
184 wclrtoeol(status_win);
185 wmove(status_win, 0, strlen(rl_display_prompt) + rl_point);
186 wrefresh(status_win);
189 static char *
190 readline_variable_generator(const char *text, int state)
192 static const char *vars[] = {
193 #define FORMAT_VAR(name, ifempty, initval) "%(" #name ")"
194 ARGV_ENV_INFO(FORMAT_VAR),
195 #undef FORMAT_VAR
196 NULL
199 static int index, len;
200 const char *name;
201 char *variable = NULL; /* No match */
203 /* If it is a new word to complete, initialize */
204 if (!state) {
205 index = 0;
206 len = strlen(text);
209 /* Return the next name which partially matches */
210 while ((name = vars[index])) {
211 index++;
213 /* Complete or format a variable */
214 if (strncmp(name, text, len) == 0) {
215 if (strlen(name) > len)
216 variable = strdup(name);
217 else
218 variable = argv_format_arg(&argv_env, text);
219 break;
223 return variable;
226 static char *
227 readline_action_generator(const char *text, int state)
229 static const char *actions[] = {
230 "!",
231 "source",
232 "color",
233 "bind",
234 "set",
235 "toggle",
236 #define REQ_GROUP(help)
237 #define REQ_(req, help) #req
238 REQ_INFO,
239 #undef REQ_GROUP
240 #undef REQ_
241 NULL
244 static int index, len;
245 const char *name;
246 char *match = NULL; /* No match */
248 /* If it is a new word to complete, initialize */
249 if (!state) {
250 index = 0;
251 len = strlen(text);
254 /* Return the next name which partially matches */
255 while ((name = actions[index])) {
256 name = enum_name(name);
257 index++;
259 if (strncmp(name, text, len) == 0) {
260 /* Ignore exact completion */
261 if (strlen(name) > len)
262 match = strdup(name);
263 break;
267 return match;
270 static char *
271 readline_set_generator(const char *text, int state)
273 static const char *words[] = {
274 #define DEFINE_OPTION_NAME(name, type, flags) #name " = ",
275 OPTION_INFO(DEFINE_OPTION_NAME)
276 #undef DEFINE_OPTION_NAME
277 NULL
280 static int index, len;
281 const char *name;
282 char *match = NULL; /* No match */
284 /* If it is a new word to complete, initialize */
285 if (!state) {
286 index = 0;
287 len = strlen(text);
290 /* Return the next name which partially matches */
291 while ((name = words[index])) {
292 name = enum_name(name);
293 index++;
295 if (strncmp(name, text, len) == 0) {
296 /* Ignore exact completion */
297 if (strlen(name) > len)
298 match = strdup(name);
299 break;
303 return match;
306 static char *
307 readline_toggle_generator(const char *text, int state)
309 static const char **words;
310 static int index, len;
311 const char *name;
312 char *match = NULL; /* No match */
314 if (!words) {
315 /* TODO: Only complete column options that are defined
316 * for the view. */
318 #define DEFINE_OPTION_WORD(name, type, flags) argv_append(&words, #name);
319 #define DEFINE_COLUMN_OPTIONS_WORD(name, type, flags) #name,
320 #define DEFINE_COLUMN_OPTIONS_WORDS(name, id, options) \
322 const char *vars[] = { \
323 options(DEFINE_COLUMN_OPTIONS_WORD) \
324 }; \
325 char buf[SIZEOF_STR]; \
326 int i; \
327 for (i = 0; i < ARRAY_SIZE(vars); i++) { \
328 if (enum_name_prefixed(buf, sizeof(buf), #name, vars[i])) \
329 argv_append(&words, buf); \
333 OPTION_INFO(DEFINE_OPTION_WORD)
334 COLUMN_OPTIONS(DEFINE_COLUMN_OPTIONS_WORDS);
337 /* If it is a new word to complete, initialize */
338 if (!state) {
339 index = 0;
340 len = strlen(text);
343 /* Return the next name which partially matches */
344 while ((name = words[index])) {
345 name = enum_name(name);
346 index++;
348 if (strncmp(name, text, len) == 0) {
349 /* Ignore exact completion */
350 if (strlen(name) > len)
351 match = strdup(name);
352 break;
356 return match;
359 static int
360 readline_getc(FILE *stream)
362 return getc(opt_tty);
365 static char **
366 readline_completion(const char *text, int start, int end)
368 /* Do not append a space after a completion */
369 rl_completion_suppress_append = 1;
372 * If the word is at the start of the line,
373 * then it is a tig action to complete.
375 if (start == 0)
376 return rl_completion_matches(text, readline_action_generator);
379 * If the line begins with "toggle", then we complete toggle options.
381 if (start >= 7 && strncmp(rl_line_buffer, "toggle ", 7) == 0)
382 return rl_completion_matches(text, readline_toggle_generator);
385 * If the line begins with "set", then we complete set options.
386 * (unless it is already completed)
388 if (start >= 4 && strncmp(rl_line_buffer, "set ", 4) == 0 &&
389 !strchr(rl_line_buffer, '='))
390 return rl_completion_matches(text, readline_set_generator);
393 * Otherwise it might be a variable name...
395 if (strncmp(text, "%(", 2) == 0)
396 return rl_completion_matches(text, readline_variable_generator);
399 * ... or finally fall back to filename completion.
401 return NULL;
404 static void
405 readline_display_matches(char **matches, int num_matches, int max_length)
407 unsigned int i;
409 wmove(status_win, 0, 0);
410 waddstr(status_win, "matches: ");
412 /* matches[0] is the incomplete word */
413 for (i = 1; i < num_matches + 1; ++i) {
414 waddstr(status_win, matches[i]);
415 waddch(status_win, ' ');
418 wgetch(status_win);
419 wrefresh(status_win);
422 static void
423 readline_init(void)
425 /* Allow conditional parsing of the ~/.inputrc file. */
426 rl_readline_name = "tig";
428 /* Word break caracters (we removed '(' to match variables) */
429 rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{";
431 /* Custom display function */
432 rl_redisplay_function = readline_display;
433 rl_getc_function = readline_getc;
435 /* Completion support */
436 rl_attempted_completion_function = readline_completion;
438 rl_completion_display_matches_hook = readline_display_matches;
441 char *
442 read_prompt(const char *prompt)
444 static char *line = NULL;
446 if (line) {
447 free(line);
448 line = NULL;
451 line = readline(prompt);
452 if (line && *line)
453 add_history(line);
455 return line;
458 void
459 prompt_init(void)
461 readline_init();
463 #else
464 char *
465 read_prompt(const char *prompt)
467 return read_prompt_incremental(prompt, TRUE, NULL, NULL);
470 void
471 prompt_init(void)
474 #endif /* HAVE_READLINE */
476 bool
477 prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
479 enum input_status status = INPUT_OK;
480 struct key key;
481 int size = 0;
483 while (items[size].text)
484 size++;
486 assert(size > 0);
488 while (status == INPUT_OK) {
489 const struct menu_item *item = &items[*selected];
490 char hotkey[] = { '[', (char) item->hotkey, ']', ' ', 0 };
491 int i;
493 update_status("%s (%d of %d) %s%s", prompt, *selected + 1, size,
494 item->hotkey ? hotkey : "", item->text);
496 switch (get_input(COLS - 1, &key, FALSE)) {
497 case KEY_RETURN:
498 case KEY_ENTER:
499 case '\n':
500 status = INPUT_STOP;
501 break;
503 case KEY_LEFT:
504 case KEY_UP:
505 *selected = *selected - 1;
506 if (*selected < 0)
507 *selected = size - 1;
508 break;
510 case KEY_RIGHT:
511 case KEY_DOWN:
512 *selected = (*selected + 1) % size;
513 break;
515 case KEY_ESC:
516 status = INPUT_CANCEL;
517 break;
519 default:
520 for (i = 0; items[i].text; i++)
521 if (items[i].hotkey == key.data.bytes[0]) {
522 *selected = i;
523 status = INPUT_STOP;
524 break;
529 report_clear();
531 return status != INPUT_CANCEL;
534 struct prompt_toggle {
535 const char *name;
536 const char *type;
537 enum view_flag flags;
538 void *opt;
541 static bool
542 find_arg(const char *argv[], const char *arg)
544 int i;
546 for (i = 0; argv[i]; i++)
547 if (!strcmp(argv[i], arg))
548 return TRUE;
549 return FALSE;
552 static enum status_code
553 prompt_toggle_option(struct view *view, const char *argv[], const char *prefix,
554 struct prompt_toggle *toggle, enum view_flag *flags)
556 char name[SIZEOF_STR];
558 if (!enum_name_prefixed(name, sizeof(name), prefix, toggle->name))
559 return error("Failed to toggle option %s", toggle->name);
561 *flags = toggle->flags;
563 if (!strcmp(toggle->type, "bool")) {
564 bool *opt = toggle->opt;
566 *opt = !*opt;
567 if (opt == &opt_mouse)
568 enable_mouse(*opt);
569 return success("set %s = %s", name, *opt ? "yes" : "no");
571 } else if (!strncmp(toggle->type, "enum", 4)) {
572 const char *type = toggle->type + STRING_SIZE("enum ");
573 enum author *opt = toggle->opt;
574 const struct enum_map *map = find_enum_map(type);
576 *opt = (*opt + 1) % map->size;
577 return success("set %s = %s", name, enum_name(map->entries[*opt].name));
579 } else if (!strcmp(toggle->type, "int")) {
580 const char *arg = argv[2] ? argv[2] : "1";
581 int diff = atoi(arg);
582 int *opt = toggle->opt;
584 if (!diff)
585 diff = *arg == '-' ? -1 : 1;
587 if (opt == &opt_diff_context && *opt < 0)
588 *opt = -*opt;
589 if (opt == &opt_diff_context && diff < 0) {
590 if (!*opt)
591 return error("Diff context cannot be less than zero");
592 if (*opt < -diff)
593 diff = -*opt;
596 if (strstr(name, "commit-title-overflow")) {
597 *opt = *opt ? -*opt : 50;
598 if (*opt < 0)
599 return success("set %s = no", name);
600 diff = 0;
603 *opt += diff;
604 return success("set %s = %d", name, *opt);
606 } else if (!strcmp(toggle->type, "double")) {
607 const char *arg = argv[2] ? argv[2] : "1.0";
608 double *opt = toggle->opt;
609 int sign = 1;
610 double diff;
612 if (*arg == '-') {
613 sign = -1;
614 arg++;
617 if (parse_step(&diff, arg) != SUCCESS)
618 diff = strtod(arg, NULL);
620 *opt += sign * diff;
621 return success("set %s = %.2f", name, *opt);
623 } else if (!strcmp(toggle->type, "const char **")) {
624 const char ***opt = toggle->opt;
625 bool found = TRUE;
626 int i;
628 for (i = 2; argv[i]; i++) {
629 if (!find_arg(*opt, argv[i])) {
630 found = FALSE;
631 break;
635 if (found) {
636 int next, pos;
638 for (next = 0, pos = 0; (*opt)[pos]; pos++) {
639 const char *arg = (*opt)[pos];
641 if (find_arg(argv + 2, arg)) {
642 free((void *) arg);
643 continue;
645 (*opt)[next++] = arg;
648 (*opt)[next] = NULL;
650 } else if (!argv_copy(opt, argv + 2)) {
651 return ERROR_OUT_OF_MEMORY;
653 return SUCCESS;
655 } else {
656 return error("Unsupported `:toggle %s` (%s)", name, toggle->type);
660 static struct prompt_toggle *
661 find_prompt_toggle(struct prompt_toggle toggles[], size_t toggles_size,
662 const char *prefix, const char *name, size_t namelen)
664 char prefixed[SIZEOF_STR];
665 int i;
667 if (*prefix && namelen == strlen(prefix) &&
668 !string_enum_compare(prefix, name, namelen)) {
669 name = "display";
670 namelen = strlen(name);
673 for (i = 0; i < toggles_size; i++) {
674 struct prompt_toggle *toggle = &toggles[i];
676 if (namelen == strlen(toggle->name) &&
677 !string_enum_compare(toggle->name, name, namelen))
678 return toggle;
680 if (enum_name_prefixed(prefixed, sizeof(prefixed), prefix, toggle->name) &&
681 namelen == strlen(prefixed) &&
682 !string_enum_compare(prefixed, name, namelen))
683 return toggle;
686 return NULL;
689 static enum status_code
690 prompt_toggle(struct view *view, const char *argv[], enum view_flag *flags)
692 struct prompt_toggle option_toggles[] = {
693 #define DEFINE_OPTION_TOGGLES(name, type, flags) { #name, #type, flags, &opt_ ## name },
694 OPTION_INFO(DEFINE_OPTION_TOGGLES)
696 const char *option = argv[1];
697 size_t optionlen = option ? strlen(option) : 0;
698 struct prompt_toggle *toggle;
699 struct view_column *column;
701 if (!option)
702 return error("%s", "No option name given to :toggle");
704 if (enum_equals_static("sort-field", option, optionlen) ||
705 enum_equals_static("sort-order", option, optionlen)) {
706 if (!view_has_flags(view, VIEW_SORTABLE)) {
707 return error("Sorting is not yet supported for the %s view", view->name);
708 } else {
709 bool sort_field = enum_equals_static("sort-field", option, optionlen);
710 struct sort_state *sort = &view->sort;
712 sort_view(view, sort_field);
713 return success("set %s = %s", option,
714 sort_field ? view_column_name(get_sort_field(view))
715 : sort->reverse ? "descending" : "ascending");
719 toggle = find_prompt_toggle(option_toggles, ARRAY_SIZE(option_toggles),
720 "", option, optionlen);
721 if (toggle)
722 return prompt_toggle_option(view, argv, "", toggle, flags);
724 #define DEFINE_COLUMN_OPTIONS_TOGGLE(name, type, flags) \
725 { #name, #type, flags, &opt->name },
727 #define DEFINE_COLUMN_OPTIONS_CHECK(name, id, options) \
728 if (column->type == VIEW_COLUMN_##id) { \
729 struct name##_options *opt = &column->opt.name; \
730 struct prompt_toggle toggles[] = { \
731 options(DEFINE_COLUMN_OPTIONS_TOGGLE) \
732 }; \
733 toggle = find_prompt_toggle(toggles, ARRAY_SIZE(toggles), #name, option, optionlen); \
734 if (toggle) \
735 return prompt_toggle_option(view, argv, #name, toggle, flags); \
738 for (column = view->columns; column; column = column->next) {
739 COLUMN_OPTIONS(DEFINE_COLUMN_OPTIONS_CHECK);
742 return error("`:toggle %s` not supported", option);
745 enum request
746 run_prompt_command(struct view *view, const char *argv[])
748 enum request request;
749 const char *cmd = argv[0];
750 size_t cmdlen = cmd ? strlen(cmd) : 0;
752 if (!cmd)
753 return REQ_NONE;
755 if (string_isnumber(cmd)) {
756 int lineno = view->pos.lineno + 1;
758 if (parse_int(&lineno, cmd, 1, view->lines + 1) == SUCCESS) {
759 select_view_line(view, lineno - 1);
760 report_clear();
761 } else {
762 report("Unable to parse '%s' as a line number", cmd);
764 } else if (iscommit(cmd)) {
765 int lineno;
767 if (!(view->ops->column_bits & view_column_bit(ID))) {
768 report("Jumping to commits is not supported by the %s view", view->name);
769 return REQ_NONE;
772 for (lineno = 0; lineno < view->lines; lineno++) {
773 struct view_column_data column_data = {};
774 struct line *line = &view->line[lineno];
776 if (view->ops->get_column_data(view, line, &column_data) &&
777 column_data.id &&
778 !strncasecmp(column_data.id, cmd, cmdlen)) {
779 string_ncopy(view->env->search, cmd, cmdlen);
780 select_view_line(view, lineno);
781 report_clear();
782 return REQ_NONE;
786 report("Unable to find commit '%s'", view->env->search);
787 return REQ_NONE;
789 } else if (cmdlen > 1 && (cmd[0] == '/' || cmd[0] == '?')) {
790 char search[SIZEOF_STR];
792 if (!argv_to_string(argv, search, sizeof(search), " ")) {
793 report("Failed to copy search string");
794 return REQ_NONE;
797 if (!strcmp(search + 1, view->env->search))
798 return cmd[0] == '/' ? REQ_FIND_NEXT : REQ_FIND_PREV;
800 string_ncopy(view->env->search, search + 1, strlen(search + 1));
801 return cmd[0] == '/' ? REQ_SEARCH : REQ_SEARCH_BACK;
803 } else if (cmdlen > 1 && cmd[0] == '!') {
804 struct view *next = &pager_view;
805 bool copied;
807 /* Trim the leading '!'. */
808 argv[0] = cmd + 1;
809 copied = argv_format(view->env, &next->argv, argv, FALSE, TRUE);
810 argv[0] = cmd;
812 if (!copied) {
813 report("Argument formatting failed");
814 } else {
815 /* When running random commands, initially show the
816 * command in the title. However, it maybe later be
817 * overwritten if a commit line is selected. */
818 argv_to_string(next->argv, next->ref, sizeof(next->ref), " ");
820 next->dir = NULL;
821 open_pager_view(view, OPEN_PREPARED | OPEN_WITH_STDERR);
824 } else if (!strcmp(cmd, "toggle")) {
825 enum view_flag flags = VIEW_NO_FLAGS;
826 enum status_code code = prompt_toggle(view, argv, &flags);
827 const char *action = get_status_message(code);
828 int i;
830 if (code != SUCCESS) {
831 report("%s", action);
832 return REQ_NONE;
835 if (flags & VIEW_RESET_DISPLAY) {
836 resize_display();
837 redraw_display(TRUE);
840 foreach_displayed_view(view, i) {
841 if (view_has_flags(view, flags) && view_can_refresh(view))
842 reload_view(view);
843 else
844 redraw_view(view);
847 if (*action)
848 report("%s", action);
850 } else {
851 struct key key = {};
853 /* Try :<key> */
854 key.modifiers.multibytes = 1;
855 string_ncopy(key.data.bytes, cmd, cmdlen);
856 request = get_keybinding(view->keymap, &key, 1);
857 if (request != REQ_NONE)
858 return request;
860 /* Try :<command> */
861 request = get_request(cmd);
862 if (request != REQ_UNKNOWN)
863 return request;
865 if (set_option(argv[0], argv_size(argv + 1), &argv[1]) == SUCCESS) {
866 request = view_can_refresh(view) ? REQ_REFRESH : REQ_SCREEN_REDRAW;
867 if (!strcmp(cmd, "color"))
868 init_colors();
869 resize_display();
870 redraw_display(TRUE);
872 return request;
874 return REQ_NONE;
877 enum request
878 open_prompt(struct view *view)
880 char *cmd = read_prompt(":");
881 const char *argv[SIZEOF_ARG] = { NULL };
882 int argc = 0;
884 if (cmd && !argv_from_string(argv, &argc, cmd)) {
885 report("Too many arguments");
886 return REQ_NONE;
889 return run_prompt_command(view, argv);
892 /* vim: set ts=8 sw=8 noexpandtab: */