text: improve text_line_down on the last line of the file
[vis.git] / vis.c
blobc4e8fa1cac7851e86bd55563c1bb16ef1eed8422
1 #include <stdlib.h>
2 #include <unistd.h>
3 #include <string.h>
4 #include <strings.h>
5 #include <signal.h>
6 #include <stdarg.h>
7 #include <stdio.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <limits.h>
11 #include <ctype.h>
12 #include <time.h>
13 #include <sys/select.h>
14 #include <sys/types.h>
15 #include <sys/wait.h>
16 #include <sys/stat.h>
17 #include <sys/ioctl.h>
18 #include <sys/mman.h>
19 #include <pwd.h>
20 #include <libgen.h>
21 #include <termkey.h>
23 #include "vis.h"
24 #include "text-util.h"
25 #include "text-motions.h"
26 #include "text-objects.h"
27 #include "util.h"
28 #include "vis-core.h"
29 #include "sam.h"
30 #include "ui.h"
33 static void macro_replay(Vis *vis, const Macro *macro);
34 static void macro_replay_internal(Vis *vis, const Macro *macro);
35 static void vis_keys_push(Vis *vis, const char *input, size_t pos, bool record);
37 bool vis_event_emit(Vis *vis, enum VisEvents id, ...) {
38 if (!vis->event)
39 return true;
41 if (!vis->initialized) {
42 vis->initialized = true;
43 vis->ui->init(vis->ui, vis);
44 if (vis->event->init)
45 vis->event->init(vis);
48 va_list ap;
49 va_start(ap, id);
50 bool ret = true;
52 switch (id) {
53 case VIS_EVENT_INIT:
54 break;
55 case VIS_EVENT_START:
56 if (vis->event->start)
57 vis->event->start(vis);
58 break;
59 case VIS_EVENT_FILE_OPEN:
60 case VIS_EVENT_FILE_SAVE_PRE:
61 case VIS_EVENT_FILE_SAVE_POST:
62 case VIS_EVENT_FILE_CLOSE:
64 File *file = va_arg(ap, File*);
65 if (file->internal)
66 break;
67 if (id == VIS_EVENT_FILE_OPEN && vis->event->file_open) {
68 vis->event->file_open(vis, file);
69 } else if (id == VIS_EVENT_FILE_SAVE_PRE && vis->event->file_save_pre) {
70 const char *path = va_arg(ap, const char*);
71 ret = vis->event->file_save_pre(vis, file, path);
72 } else if (id == VIS_EVENT_FILE_SAVE_POST && vis->event->file_save_post) {
73 const char *path = va_arg(ap, const char*);
74 vis->event->file_save_post(vis, file, path);
75 } else if (id == VIS_EVENT_FILE_CLOSE && vis->event->file_close) {
76 vis->event->file_close(vis, file);
78 break;
80 case VIS_EVENT_WIN_OPEN:
81 case VIS_EVENT_WIN_CLOSE:
82 case VIS_EVENT_WIN_HIGHLIGHT:
83 case VIS_EVENT_WIN_STATUS:
85 Win *win = va_arg(ap, Win*);
86 if (win->file->internal && id != VIS_EVENT_WIN_STATUS)
87 break;
88 if (vis->event->win_open && id == VIS_EVENT_WIN_OPEN) {
89 vis->event->win_open(vis, win);
90 } else if (vis->event->win_close && id == VIS_EVENT_WIN_CLOSE) {
91 vis->event->win_close(vis, win);
92 } else if (vis->event->win_highlight && id == VIS_EVENT_WIN_HIGHLIGHT) {
93 vis->event->win_highlight(vis, win);
94 } else if (vis->event->win_status && id == VIS_EVENT_WIN_STATUS) {
95 vis->event->win_status(vis, win);
97 break;
99 case VIS_EVENT_QUIT:
100 if (vis->event->quit)
101 vis->event->quit(vis);
102 break;
105 va_end(ap);
106 return ret;
109 /** window / file handling */
111 static void file_free(Vis *vis, File *file) {
112 if (!file)
113 return;
114 if (file->refcount > 1) {
115 --file->refcount;
116 return;
118 vis_event_emit(vis, VIS_EVENT_FILE_CLOSE, file);
119 for (size_t i = 0; i < LENGTH(file->marks); i++)
120 mark_release(&file->marks[i]);
121 text_free(file->text);
122 free((char*)file->name);
124 if (file->prev)
125 file->prev->next = file->next;
126 if (file->next)
127 file->next->prev = file->prev;
128 if (vis->files == file)
129 vis->files = file->next;
130 free(file);
133 static File *file_new_text(Vis *vis, Text *text) {
134 File *file = calloc(1, sizeof(*file));
135 if (!file)
136 return NULL;
137 file->fd = -1;
138 file->text = text;
139 file->stat = text_stat(text);
140 for (size_t i = 0; i < LENGTH(file->marks); i++)
141 mark_init(&file->marks[i]);
142 if (vis->files)
143 vis->files->prev = file;
144 file->next = vis->files;
145 vis->files = file;
146 return file;
149 char *absolute_path(const char *name) {
150 if (!name)
151 return NULL;
152 char *copy1 = strdup(name);
153 char *copy2 = strdup(name);
154 char *path_absolute = NULL;
155 char path_normalized[PATH_MAX] = "";
157 if (!copy1 || !copy2)
158 goto err;
160 char *dir = dirname(copy1);
161 char *base = basename(copy2);
162 if (!(path_absolute = realpath(dir, NULL)))
163 goto err;
164 if (strcmp(path_absolute, "/") == 0)
165 path_absolute[0] = '\0';
167 snprintf(path_normalized, sizeof(path_normalized), "%s/%s",
168 path_absolute, base);
169 err:
170 free(copy1);
171 free(copy2);
172 free(path_absolute);
173 return path_normalized[0] ? strdup(path_normalized) : NULL;
176 static File *file_new(Vis *vis, const char *name) {
177 char *name_absolute = NULL;
178 if (name) {
179 if (!(name_absolute = absolute_path(name)))
180 return NULL;
181 File *existing = NULL;
182 /* try to detect whether the same file is already open in another window
183 * TODO: do this based on inodes */
184 for (File *file = vis->files; file; file = file->next) {
185 if (file->name && strcmp(file->name, name_absolute) == 0) {
186 existing = file;
187 break;
190 if (existing) {
191 free(name_absolute);
192 return existing;
196 File *file = NULL;
197 Text *text = text_load_method(name, vis->load_method);
198 if (!text && name && errno == ENOENT)
199 text = text_load(NULL);
200 if (!text)
201 goto err;
202 if (!(file = file_new_text(vis, text)))
203 goto err;
204 file->name = name_absolute;
205 vis_event_emit(vis, VIS_EVENT_FILE_OPEN, file);
206 return file;
207 err:
208 free(name_absolute);
209 text_free(text);
210 file_free(vis, file);
211 return NULL;
214 static File *file_new_internal(Vis *vis, const char *filename) {
215 File *file = file_new(vis, filename);
216 if (file) {
217 file->refcount = 1;
218 file->internal = true;
220 return file;
223 void file_name_set(File *file, const char *name) {
224 if (name == file->name)
225 return;
226 free((char*)file->name);
227 file->name = absolute_path(name);
230 const char *file_name_get(File *file) {
231 /* TODO: calculate path relative to working directory, cache result */
232 if (!file->name)
233 return NULL;
234 char cwd[PATH_MAX];
235 if (!getcwd(cwd, sizeof cwd))
236 return file->name;
237 const char *path = strstr(file->name, cwd);
238 if (path != file->name)
239 return file->name;
240 size_t cwdlen = strlen(cwd);
241 return file->name[cwdlen] == '/' ? file->name+cwdlen+1 : file->name;
244 void vis_window_status(Win *win, const char *status) {
245 win->ui->status(win->ui, status);
248 void window_selection_save(Win *win) {
249 Vis *vis = win->vis;
250 View *view = win->view;
251 Array sel = view_selections_get_all(view);
252 vis_mark_set(win, VIS_MARK_SELECTION, &sel);
253 array_release(&sel);
254 vis_jumplist_save(vis);
258 static void window_free(Win *win) {
259 if (!win)
260 return;
261 Vis *vis = win->vis;
262 for (Win *other = vis->windows; other; other = other->next) {
263 if (other->parent == win)
264 other->parent = NULL;
266 if (vis->ui)
267 vis->ui->window_free(win->ui);
268 view_free(win->view);
269 for (size_t i = 0; i < LENGTH(win->modes); i++)
270 map_free(win->modes[i].bindings);
271 marklist_release(&win->jumplist);
272 mark_release(&win->saved_selections);
273 free(win);
276 static void window_draw_colorcolumn(Win *win) {
277 View *view = win->view;
278 int cc = view_colorcolumn_get(view);
279 if (cc <= 0)
280 return;
281 CellStyle style = win->ui->style_get(win->ui, UI_STYLE_COLOR_COLUMN);
282 size_t lineno = 0;
283 int line_cols = 0; /* Track the number of columns we've passed on each line */
284 bool line_cc_set = false; /* Has the colorcolumn attribute been set for this line yet */
285 int width = view_width_get(view);
287 for (Line *l = view_lines_first(view); l; l = l->next) {
288 if (l->lineno != lineno) {
289 line_cols = 0;
290 line_cc_set = false;
291 if (!(lineno = l->lineno))
292 break;
294 if (line_cc_set)
295 continue;
297 /* This screen line contains the cell we want to highlight */
298 if (cc <= line_cols + width) {
299 CellStyle *orig = &l->cells[cc - 1 - line_cols].style;
300 orig->attr = style.attr;
301 orig->fg = is_default_color(style.fg) ? orig->fg : style.fg;
302 orig->bg = is_default_color(style.bg) ? orig->bg : style.bg;
303 line_cc_set = true;
304 } else {
305 line_cols += width;
310 static void window_draw_cursorline(Win *win) {
311 Vis *vis = win->vis;
312 View *view = win->view;
313 enum UiOption options = view_options_get(view);
314 if (!(options & UI_OPTION_CURSOR_LINE))
315 return;
316 if (vis->mode->visual || vis->win != win)
317 return;
318 if (view_selections_count(view) > 1)
319 return;
321 int width = view_width_get(view);
322 CellStyle style = win->ui->style_get(win->ui, UI_STYLE_CURSOR_LINE);
323 Selection *sel = view_selections_primary_get(view);
324 size_t lineno = view_cursors_line_get(sel)->lineno;
325 for (Line *l = view_lines_first(view); l; l = l->next) {
326 if (l->lineno == lineno) {
327 for (int x = 0; x < width; x++) {
328 l->cells[x].style.attr |= style.attr;
329 l->cells[x].style.bg = style.bg;
331 } else if (l->lineno > lineno) {
332 break;
337 static void window_draw_selection(View *view, Selection *cur, CellStyle *style) {
338 Filerange sel = view_selections_get(cur);
339 if (!text_range_valid(&sel))
340 return;
341 Line *start_line; int start_col;
342 Line *end_line; int end_col;
343 view_coord_get(view, sel.start, &start_line, NULL, &start_col);
344 view_coord_get(view, sel.end, &end_line, NULL, &end_col);
345 if (!start_line && !end_line)
346 return;
347 if (!start_line) {
348 start_line = view_lines_first(view);
349 start_col = 0;
351 if (!end_line) {
352 end_line = view_lines_last(view);
353 end_col = end_line->width;
355 for (Line *l = start_line; l != end_line->next; l = l->next) {
356 int col = (l == start_line) ? start_col : 0;
357 int end = (l == end_line) ? end_col : l->width;
358 while (col < end) {
359 if (cell_color_equal(l->cells[col].style.fg, style->bg)) {
360 CellStyle old = l->cells[col].style;
361 if (!cell_color_equal(old.fg, old.bg)) {
362 l->cells[col].style.fg = old.bg;
363 l->cells[col].style.bg = old.fg;
364 } else {
365 l->cells[col].style.attr = style->attr;
367 } else {
368 l->cells[col].style.bg = style->bg;
370 col++;
375 static void window_draw_cursor_matching(Win *win, Selection *cur, CellStyle *style) {
376 if (win->vis->mode->visual)
377 return;
378 Line *line_match; int col_match;
379 size_t pos = view_cursors_pos(cur);
380 Filerange limits = view_viewport_get(win->view);
381 size_t pos_match = text_bracket_match_symbol(win->file->text, pos, "(){}[]\"'`", &limits);
382 if (pos == pos_match)
383 return;
384 if (!view_coord_get(win->view, pos_match, &line_match, NULL, &col_match))
385 return;
386 if (cell_color_equal(line_match->cells[col_match].style.fg, style->fg)) {
387 CellStyle old = line_match->cells[col_match].style;
388 line_match->cells[col_match].style.fg = old.bg;
389 line_match->cells[col_match].style.bg = old.fg;
390 } else {
391 line_match->cells[col_match].style.bg = style->bg;
395 static void window_draw_cursor(Win *win, Selection *cur, CellStyle *style, CellStyle *sel_style) {
396 if (win->vis->win != win)
397 return;
398 Line *line = view_cursors_line_get(cur);
399 int col = view_cursors_cell_get(cur);
400 if (!line || col == -1)
401 return;
402 line->cells[col].style = *style;
403 window_draw_cursor_matching(win, cur, sel_style);
404 return;
407 static void window_draw_selections(Win *win) {
408 View *view = win->view;
409 Filerange viewport = view_viewport_get(view);
410 Selection *sel = view_selections_primary_get(view);
411 CellStyle style_cursor = win->ui->style_get(win->ui, UI_STYLE_CURSOR);
412 CellStyle style_cursor_primary = win->ui->style_get(win->ui, UI_STYLE_CURSOR_PRIMARY);
413 CellStyle style_selection = win->ui->style_get(win->ui, UI_STYLE_SELECTION);
414 for (Selection *s = view_selections_prev(sel); s; s = view_selections_prev(s)) {
415 window_draw_selection(win->view, s, &style_selection);
416 size_t pos = view_cursors_pos(s);
417 if (pos < viewport.start)
418 break;
419 window_draw_cursor(win, s, &style_cursor, &style_selection);
421 window_draw_selection(win->view, sel, &style_selection);
422 window_draw_cursor(win, sel, &style_cursor_primary, &style_selection);
423 for (Selection *s = view_selections_next(sel); s; s = view_selections_next(s)) {
424 window_draw_selection(win->view, s, &style_selection);
425 size_t pos = view_cursors_pos(s);
426 if (pos > viewport.end)
427 break;
428 window_draw_cursor(win, s, &style_cursor, &style_selection);
432 static void window_draw_eof(Win *win) {
433 View *view = win->view;
434 if (view_width_get(view) == 0)
435 return;
436 CellStyle style = win->ui->style_get(win->ui, UI_STYLE_EOF);
437 for (Line *l = view_lines_last(view)->next; l; l = l->next) {
438 strncpy(l->cells[0].data, view_symbol_eof_get(view), sizeof(l->cells[0].data)-1);
439 l->cells[0].style = style;
443 void vis_window_draw(Win *win) {
444 if (!win->ui || !view_update(win->view))
445 return;
446 Vis *vis = win->vis;
447 vis_event_emit(vis, VIS_EVENT_WIN_HIGHLIGHT, win);
449 window_draw_colorcolumn(win);
450 window_draw_cursorline(win);
451 if (!vis->win || vis->win == win || vis->win->parent == win)
452 window_draw_selections(win);
453 window_draw_eof(win);
455 vis_event_emit(vis, VIS_EVENT_WIN_STATUS, win);
459 void vis_window_invalidate(Win *win) {
460 for (Win *w = win->vis->windows; w; w = w->next) {
461 if (w->file == win->file)
462 view_draw(w->view);
466 Win *window_new_file(Vis *vis, File *file, enum UiOption options) {
467 Win *win = calloc(1, sizeof(Win));
468 if (!win)
469 return NULL;
470 win->vis = vis;
471 win->file = file;
472 win->view = view_new(file->text);
473 win->ui = vis->ui->window_new(vis->ui, win, options);
474 if (!win->view || !win->ui) {
475 window_free(win);
476 return NULL;
478 marklist_init(&win->jumplist, 32);
479 mark_init(&win->saved_selections);
480 file->refcount++;
481 view_options_set(win->view, view_options_get(win->view));
482 view_tabwidth_set(win->view, vis->tabwidth);
484 if (vis->windows)
485 vis->windows->prev = win;
486 win->next = vis->windows;
487 vis->windows = win;
488 vis->win = win;
489 vis->ui->window_focus(win->ui);
490 for (size_t i = 0; i < LENGTH(win->modes); i++)
491 win->modes[i].parent = &vis_modes[i];
492 vis_event_emit(vis, VIS_EVENT_WIN_OPEN, win);
493 return win;
496 bool vis_window_reload(Win *win) {
497 const char *name = win->file->name;
498 if (!name)
499 return false; /* can't reload unsaved file */
500 /* temporarily unset file name, otherwise file_new returns the same File */
501 win->file->name = NULL;
502 File *file = file_new(win->vis, name);
503 win->file->name = name;
504 if (!file)
505 return false;
506 file_free(win->vis, win->file);
507 file->refcount = 1;
508 win->file = file;
509 view_reload(win->view, file->text);
510 return true;
513 bool vis_window_split(Win *original) {
514 Win *win = window_new_file(original->vis, original->file, UI_OPTION_STATUSBAR);
515 if (!win)
516 return false;
517 for (size_t i = 0; i < LENGTH(win->modes); i++) {
518 if (original->modes[i].bindings)
519 win->modes[i].bindings = map_new();
520 if (win->modes[i].bindings)
521 map_copy(win->modes[i].bindings, original->modes[i].bindings);
523 win->file = original->file;
524 view_options_set(win->view, view_options_get(original->view));
525 view_cursor_to(win->view, view_cursor_get(original->view));
526 return true;
529 void vis_window_focus(Win *win) {
530 if (!win)
531 return;
532 Vis *vis = win->vis;
533 vis->win = win;
534 vis->ui->window_focus(win->ui);
537 void vis_window_next(Vis *vis) {
538 Win *sel = vis->win;
539 if (!sel)
540 return;
541 vis_window_focus(sel->next ? sel->next : vis->windows);
544 void vis_window_prev(Vis *vis) {
545 Win *sel = vis->win;
546 if (!sel)
547 return;
548 sel = sel->prev;
549 if (!sel)
550 for (sel = vis->windows; sel->next; sel = sel->next);
551 vis_window_focus(sel);
554 int vis_window_width_get(const Win *win) {
555 return win->ui->window_width(win->ui);
558 int vis_window_height_get(const Win *win) {
559 return win->ui->window_height(win->ui);
562 void vis_draw(Vis *vis) {
563 for (Win *win = vis->windows; win; win = win->next)
564 view_draw(win->view);
567 void vis_redraw(Vis *vis) {
568 vis->ui->redraw(vis->ui);
569 vis_update(vis);
572 void vis_update(Vis *vis) {
573 vis->ui->draw(vis->ui);
576 void vis_suspend(Vis *vis) {
577 vis->ui->suspend(vis->ui);
580 void vis_resume(Vis *vis) {
581 vis->ui->resume(vis->ui);
584 bool vis_window_new(Vis *vis, const char *filename) {
585 File *file = file_new(vis, filename);
586 if (!file)
587 return false;
588 Win *win = window_new_file(vis, file, UI_OPTION_STATUSBAR|UI_OPTION_SYMBOL_EOF);
589 if (!win) {
590 file_free(vis, file);
591 return false;
594 return true;
597 bool vis_window_new_fd(Vis *vis, int fd) {
598 if (fd == -1)
599 return false;
600 if (!vis_window_new(vis, NULL))
601 return false;
602 vis->win->file->fd = fd;
603 return true;
606 bool vis_window_closable(Win *win) {
607 if (!win || !text_modified(win->file->text))
608 return true;
609 return win->file->refcount > 1;
612 void vis_window_swap(Win *a, Win *b) {
613 if (a == b || !a || !b)
614 return;
615 Vis *vis = a->vis;
616 Win *tmp = a->next;
617 a->next = b->next;
618 b->next = tmp;
619 if (a->next)
620 a->next->prev = a;
621 if (b->next)
622 b->next->prev = b;
623 tmp = a->prev;
624 a->prev = b->prev;
625 b->prev = tmp;
626 if (a->prev)
627 a->prev->next = a;
628 if (b->prev)
629 b->prev->next = b;
630 if (vis->windows == a)
631 vis->windows = b;
632 else if (vis->windows == b)
633 vis->windows = a;
634 vis->ui->window_swap(a->ui, b->ui);
635 if (vis->win == a)
636 vis_window_focus(b);
637 else if (vis->win == b)
638 vis_window_focus(a);
641 void vis_window_close(Win *win) {
642 if (!win)
643 return;
644 Vis *vis = win->vis;
645 vis_event_emit(vis, VIS_EVENT_WIN_CLOSE, win);
646 file_free(vis, win->file);
647 if (win->prev)
648 win->prev->next = win->next;
649 if (win->next)
650 win->next->prev = win->prev;
651 if (vis->windows == win)
652 vis->windows = win->next;
653 if (vis->win == win)
654 vis->win = win->next ? win->next : win->prev;
655 if (win == vis->message_window)
656 vis->message_window = NULL;
657 window_free(win);
658 if (vis->win)
659 vis->ui->window_focus(vis->win->ui);
660 vis_draw(vis);
663 Vis *vis_new(Ui *ui, VisEvent *event) {
664 if (!ui)
665 return NULL;
666 Vis *vis = calloc(1, sizeof(Vis));
667 if (!vis)
668 return NULL;
669 vis->exit_status = -1;
670 vis->ui = ui;
671 vis->tabwidth = 8;
672 vis->expandtab = false;
673 vis->change_colors = true;
674 for (size_t i = 0; i < LENGTH(vis->registers); i++)
675 register_init(&vis->registers[i]);
676 vis->registers[VIS_REG_BLACKHOLE].type = REGISTER_BLACKHOLE;
677 vis->registers[VIS_REG_CLIPBOARD].type = REGISTER_CLIPBOARD;
678 vis->registers[VIS_REG_PRIMARY].type = REGISTER_CLIPBOARD;
679 vis->registers[VIS_REG_NUMBER].type = REGISTER_NUMBER;
680 array_init(&vis->operators);
681 array_init(&vis->motions);
682 array_init(&vis->textobjects);
683 array_init(&vis->bindings);
684 array_init(&vis->actions_user);
685 action_reset(&vis->action);
686 buffer_init(&vis->input_queue);
687 if (!(vis->command_file = file_new_internal(vis, NULL)))
688 goto err;
689 if (!(vis->search_file = file_new_internal(vis, NULL)))
690 goto err;
691 if (!(vis->error_file = file_new_internal(vis, NULL)))
692 goto err;
693 if (!(vis->actions = map_new()))
694 goto err;
695 if (!(vis->keymap = map_new()))
696 goto err;
697 if (!sam_init(vis))
698 goto err;
699 struct passwd *pw;
700 char *shell = getenv("SHELL");
701 if ((!shell || !*shell) && (pw = getpwuid(getuid())))
702 shell = pw->pw_shell;
703 if (!shell || !*shell)
704 shell = "/bin/sh";
705 if (!(vis->shell = strdup(shell)))
706 goto err;
707 vis->mode_prev = vis->mode = &vis_modes[VIS_MODE_NORMAL];
708 vis->event = event;
709 if (event) {
710 if (event->mode_insert_input)
711 vis_modes[VIS_MODE_INSERT].input = event->mode_insert_input;
712 if (event->mode_replace_input)
713 vis_modes[VIS_MODE_REPLACE].input = event->mode_replace_input;
715 return vis;
716 err:
717 vis_free(vis);
718 return NULL;
721 void vis_free(Vis *vis) {
722 if (!vis)
723 return;
724 vis_event_emit(vis, VIS_EVENT_QUIT);
725 vis->event = NULL;
726 while (vis->windows)
727 vis_window_close(vis->windows);
728 file_free(vis, vis->command_file);
729 file_free(vis, vis->search_file);
730 file_free(vis, vis->error_file);
731 for (int i = 0; i < LENGTH(vis->registers); i++)
732 register_release(&vis->registers[i]);
733 vis->ui->free(vis->ui);
734 if (vis->usercmds) {
735 const char *name;
736 while (map_first(vis->usercmds, &name) && vis_cmd_unregister(vis, name));
738 map_free(vis->usercmds);
739 map_free(vis->cmds);
740 if (vis->options) {
741 const char *name;
742 while (map_first(vis->options, &name) && vis_option_unregister(vis, name));
744 map_free(vis->options);
745 map_free(vis->actions);
746 map_free(vis->keymap);
747 buffer_release(&vis->input_queue);
748 for (int i = 0; i < VIS_MODE_INVALID; i++)
749 map_free(vis_modes[i].bindings);
750 array_release_full(&vis->operators);
751 array_release_full(&vis->motions);
752 array_release_full(&vis->textobjects);
753 while (array_length(&vis->bindings))
754 vis_binding_free(vis, array_get_ptr(&vis->bindings, 0));
755 array_release(&vis->bindings);
756 while (array_length(&vis->actions_user))
757 vis_action_free(vis, array_get_ptr(&vis->actions_user, 0));
758 array_release(&vis->actions_user);
759 free(vis->shell);
760 free(vis);
763 void vis_insert(Vis *vis, size_t pos, const char *data, size_t len) {
764 Win *win = vis->win;
765 if (!win)
766 return;
767 text_insert(win->file->text, pos, data, len);
768 vis_window_invalidate(win);
771 void vis_insert_key(Vis *vis, const char *data, size_t len) {
772 Win *win = vis->win;
773 if (!win)
774 return;
775 for (Selection *s = view_selections(win->view); s; s = view_selections_next(s)) {
776 size_t pos = view_cursors_pos(s);
777 vis_insert(vis, pos, data, len);
778 view_cursors_scroll_to(s, pos + len);
782 void vis_replace(Vis *vis, size_t pos, const char *data, size_t len) {
783 Win *win = vis->win;
784 if (!win)
785 return;
786 Text *txt = win->file->text;
787 Iterator it = text_iterator_get(txt, pos);
788 int chars = text_char_count(data, len);
789 for (char c; chars-- > 0 && text_iterator_byte_get(&it, &c) && c != '\n'; )
790 text_iterator_char_next(&it, NULL);
792 text_delete(txt, pos, it.pos - pos);
793 vis_insert(vis, pos, data, len);
796 void vis_replace_key(Vis *vis, const char *data, size_t len) {
797 Win *win = vis->win;
798 if (!win)
799 return;
800 for (Selection *s = view_selections(win->view); s; s = view_selections_next(s)) {
801 size_t pos = view_cursors_pos(s);
802 vis_replace(vis, pos, data, len);
803 view_cursors_scroll_to(s, pos + len);
807 void vis_delete(Vis *vis, size_t pos, size_t len) {
808 Win *win = vis->win;
809 if (!win)
810 return;
811 text_delete(win->file->text, pos, len);
812 vis_window_invalidate(win);
815 bool vis_action_register(Vis *vis, const KeyAction *action) {
816 return map_put(vis->actions, action->name, action);
819 bool vis_keymap_add(Vis *vis, const char *key, const char *mapping) {
820 return map_put(vis->keymap, key, mapping);
823 void vis_keymap_disable(Vis *vis) {
824 vis->keymap_disabled = true;
827 void vis_interrupt(Vis *vis) {
828 vis->interrupted = true;
831 bool vis_interrupt_requested(Vis *vis) {
832 return vis->interrupted;
835 void vis_do(Vis *vis) {
836 Win *win = vis->win;
837 if (!win)
838 return;
839 File *file = win->file;
840 Text *txt = file->text;
841 View *view = win->view;
842 Action *a = &vis->action;
844 int count = MAX(a->count, 1);
845 if (a->op == &vis_operators[VIS_OP_MODESWITCH])
846 count = 1; /* count should apply to inserted text not motion */
847 bool repeatable = a->op && !vis->macro_operator && !vis->win->parent;
848 bool multiple_cursors = view_selections_count(view) > 1;
850 bool linewise = !(a->type & CHARWISE) && (
851 a->type & LINEWISE || (a->movement && a->movement->type & LINEWISE) ||
852 vis->mode == &vis_modes[VIS_MODE_VISUAL_LINE]);
854 Register *reg = a->reg;
855 size_t reg_slot = multiple_cursors ? EPOS : 0;
856 size_t last_reg_slot = reg_slot;
857 if (!reg)
858 reg = &vis->registers[file->internal ? VIS_REG_PROMPT : VIS_REG_DEFAULT];
859 if (a->op == &vis_operators[VIS_OP_PUT_AFTER] && multiple_cursors && vis_register_count(vis, reg) == 1)
860 reg_slot = 0;
862 if (vis->mode->visual && a->op)
863 window_selection_save(win);
865 for (Selection *sel = view_selections(view), *next; sel; sel = next) {
866 if (vis->interrupted)
867 break;
869 next = view_selections_next(sel);
871 size_t pos = view_cursors_pos(sel);
872 if (pos == EPOS) {
873 if (!view_selections_dispose(sel))
874 view_cursors_to(sel, 0);
875 continue;
878 OperatorContext c = {
879 .count = count,
880 .pos = pos,
881 .newpos = EPOS,
882 .range = text_range_empty(),
883 .reg = reg,
884 .reg_slot = reg_slot == EPOS ? (size_t)view_selections_number(sel) : reg_slot,
885 .linewise = linewise,
886 .arg = &a->arg,
887 .context = a->op ? a->op->context : NULL,
890 last_reg_slot = c.reg_slot;
892 bool err = false;
893 if (a->movement) {
894 size_t start = pos;
895 for (int i = 0; i < count; i++) {
896 size_t pos_prev = pos;
897 if (a->movement->txt)
898 pos = a->movement->txt(txt, pos);
899 else if (a->movement->cur)
900 pos = a->movement->cur(sel);
901 else if (a->movement->file)
902 pos = a->movement->file(vis, file, sel);
903 else if (a->movement->vis)
904 pos = a->movement->vis(vis, txt, pos);
905 else if (a->movement->view)
906 pos = a->movement->view(vis, view);
907 else if (a->movement->win)
908 pos = a->movement->win(vis, win, pos);
909 else if (a->movement->user)
910 pos = a->movement->user(vis, win, a->movement->data, pos);
911 if (pos == EPOS || a->movement->type & IDEMPOTENT || pos == pos_prev) {
912 err = a->movement->type & COUNT_EXACT;
913 break;
917 if (err) {
918 repeatable = false;
919 continue; // break?
922 if (pos == EPOS) {
923 c.range.start = start;
924 c.range.end = start;
925 pos = start;
926 } else {
927 c.range = text_range_new(start, pos);
928 c.newpos = pos;
931 if (!a->op) {
932 if (a->movement->type & CHARWISE)
933 view_cursors_scroll_to(sel, pos);
934 else
935 view_cursors_to(sel, pos);
936 if (vis->mode->visual)
937 c.range = view_selections_get(sel);
938 } else if (a->movement->type & INCLUSIVE && c.range.end > start) {
939 c.range.end = text_char_next(txt, c.range.end);
940 } else if (linewise && (a->movement->type & LINEWISE_INCLUSIVE)) {
941 c.range.end = text_char_next(txt, c.range.end);
943 } else if (a->textobj) {
944 if (vis->mode->visual)
945 c.range = view_selections_get(sel);
946 else
947 c.range.start = c.range.end = pos;
948 for (int i = 0; i < count; i++) {
949 Filerange r = text_range_empty();
950 if (a->textobj->txt)
951 r = a->textobj->txt(txt, pos);
952 else if (a->textobj->vis)
953 r = a->textobj->vis(vis, txt, pos);
954 else if (a->textobj->user)
955 r = a->textobj->user(vis, win, a->textobj->data, pos);
956 if (!text_range_valid(&r))
957 break;
958 if (a->textobj->type & TEXTOBJECT_DELIMITED_OUTER) {
959 r.start--;
960 r.end++;
963 if (vis->mode->visual || (i > 0 && !(a->textobj->type & TEXTOBJECT_NON_CONTIGUOUS)))
964 c.range = text_range_union(&c.range, &r);
965 else
966 c.range = r;
968 if (i < count - 1) {
969 if (a->textobj->type & TEXTOBJECT_EXTEND_BACKWARD) {
970 pos = c.range.start;
971 if ((a->textobj->type & TEXTOBJECT_DELIMITED_INNER) && pos > 0)
972 pos--;
973 } else {
974 pos = c.range.end;
975 if (a->textobj->type & TEXTOBJECT_DELIMITED_INNER)
976 pos++;
980 } else if (vis->mode->visual) {
981 c.range = view_selections_get(sel);
982 if (!text_range_valid(&c.range))
983 c.range.start = c.range.end = pos;
986 if (linewise && vis->mode != &vis_modes[VIS_MODE_VISUAL])
987 c.range = text_range_linewise(txt, &c.range);
988 if (vis->mode->visual) {
989 view_selections_set(sel, &c.range);
990 view_selections_anchor(sel, true);
993 if (a->op) {
994 size_t pos = a->op->func(vis, txt, &c);
995 if (pos == EPOS) {
996 view_selections_dispose(sel);
997 } else if (pos <= text_size(txt)) {
998 view_selection_clear(sel);
999 view_cursors_to(sel, pos);
1004 view_selections_normalize(view);
1005 if (a->movement && (a->movement->type & JUMP))
1006 vis_jumplist_save(vis);
1008 if (a->op) {
1010 if (a->op == &vis_operators[VIS_OP_YANK] ||
1011 a->op == &vis_operators[VIS_OP_DELETE] ||
1012 a->op == &vis_operators[VIS_OP_CHANGE] ||
1013 a->op == &vis_operators[VIS_OP_REPLACE]) {
1014 register_resize(reg, last_reg_slot+1);
1017 /* we do not support visual repeat, still do something resonable */
1018 if (vis->mode->visual && !a->movement && !a->textobj)
1019 a->movement = &vis_motions[VIS_MOVE_NOP];
1021 /* operator implementations must not change the mode,
1022 * they might get called multiple times (once for every cursor)
1024 if (a->op == &vis_operators[VIS_OP_CHANGE]) {
1025 vis_mode_switch(vis, VIS_MODE_INSERT);
1026 } else if (a->op == &vis_operators[VIS_OP_MODESWITCH]) {
1027 vis_mode_switch(vis, a->mode);
1028 } else if (vis->mode == &vis_modes[VIS_MODE_OPERATOR_PENDING]) {
1029 mode_set(vis, vis->mode_prev);
1030 } else if (vis->mode->visual) {
1031 vis_mode_switch(vis, VIS_MODE_NORMAL);
1034 if (vis->mode == &vis_modes[VIS_MODE_NORMAL])
1035 vis_file_snapshot(vis, file);
1036 vis_draw(vis);
1039 if (a != &vis->action_prev) {
1040 if (repeatable) {
1041 if (!a->macro)
1042 a->macro = vis->macro_operator;
1043 vis->action_prev = *a;
1045 action_reset(a);
1049 void action_reset(Action *a) {
1050 memset(a, 0, sizeof(*a));
1051 a->count = VIS_COUNT_UNKNOWN;
1054 void vis_cancel(Vis *vis) {
1055 action_reset(&vis->action);
1058 void vis_die(Vis *vis, const char *msg, ...) {
1059 va_list ap;
1060 va_start(ap, msg);
1061 vis->ui->die(vis->ui, msg, ap);
1062 va_end(ap);
1065 const char *vis_keys_next(Vis *vis, const char *keys) {
1066 if (!keys || !*keys)
1067 return NULL;
1068 TermKeyKey key;
1069 TermKey *termkey = vis->ui->termkey_get(vis->ui);
1070 const char *next = NULL;
1071 /* first try to parse a special key of the form <Key> */
1072 if (*keys == '<' && keys[1] && (next = termkey_strpkey(termkey, keys+1, &key, TERMKEY_FORMAT_VIM)) && *next == '>')
1073 return next+1;
1074 if (strncmp(keys, "<vis-", 5) == 0) {
1075 const char *start = keys + 1, *end = start;
1076 while (*end && *end != '>')
1077 end++;
1078 if (end > start && end - start - 1 < VIS_KEY_LENGTH_MAX && *end == '>') {
1079 char key[VIS_KEY_LENGTH_MAX];
1080 memcpy(key, start, end - start);
1081 key[end - start] = '\0';
1082 if (map_get(vis->actions, key))
1083 return end + 1;
1086 if (ISUTF8(*keys))
1087 keys++;
1088 while (!ISUTF8(*keys))
1089 keys++;
1090 return keys;
1093 long vis_keys_codepoint(Vis *vis, const char *keys) {
1094 long codepoint = -1;
1095 const char *next;
1096 TermKeyKey key;
1097 TermKey *termkey = vis->ui->termkey_get(vis->ui);
1099 if (!keys[0])
1100 return -1;
1101 if (keys[0] == '<' && !keys[1])
1102 return '<';
1104 if (keys[0] == '<' && (next = termkey_strpkey(termkey, keys+1, &key, TERMKEY_FORMAT_VIM)) && *next == '>')
1105 codepoint = (key.type == TERMKEY_TYPE_UNICODE) ? key.code.codepoint : -1;
1106 else if ((next = termkey_strpkey(termkey, keys, &key, TERMKEY_FORMAT_VIM)))
1107 codepoint = (key.type == TERMKEY_TYPE_UNICODE) ? key.code.codepoint : -1;
1109 if (codepoint != -1) {
1110 if (key.modifiers == TERMKEY_KEYMOD_CTRL)
1111 codepoint &= 0x1f;
1112 return codepoint;
1115 if (!next || key.type != TERMKEY_TYPE_KEYSYM)
1116 return -1;
1118 const int keysym[] = {
1119 TERMKEY_SYM_ENTER, '\n',
1120 TERMKEY_SYM_TAB, '\t',
1121 TERMKEY_SYM_BACKSPACE, '\b',
1122 TERMKEY_SYM_ESCAPE, 0x1b,
1123 TERMKEY_SYM_DELETE, 0x7f,
1127 for (const int *k = keysym; k[0]; k += 2) {
1128 if (key.code.sym == k[0])
1129 return k[1];
1132 return -1;
1135 bool vis_keys_utf8(Vis *vis, const char *keys, char utf8[static UTFmax+1]) {
1136 Rune rune = vis_keys_codepoint(vis, keys);
1137 if (rune == (Rune)-1)
1138 return false;
1139 size_t len = runetochar(utf8, &rune);
1140 utf8[len] = '\0';
1141 return true;
1144 typedef struct {
1145 Vis *vis;
1146 size_t len; // length of the prefix
1147 int count; // how many bindings can complete this prefix
1148 bool angle_bracket; // does the prefix end with '<'
1149 } PrefixCompletion;
1151 static bool isprefix(const char *key, void *value, void *data) {
1152 PrefixCompletion *completion = data;
1153 if (!completion->angle_bracket) {
1154 completion->count++;
1155 } else {
1156 const char *start = key + completion->len;
1157 const char *end = vis_keys_next(completion->vis, start);
1158 if (end && start + 1 == end)
1159 completion->count++;
1161 return completion->count == 1;
1164 static void vis_keys_process(Vis *vis, size_t pos) {
1165 Buffer *buf = &vis->input_queue;
1166 char *keys = buf->data + pos, *start = keys, *cur = keys, *end = keys, *binding_end = keys;;
1167 bool prefix = false;
1168 KeyBinding *binding = NULL;
1170 while (cur && *cur) {
1172 if (!(end = (char*)vis_keys_next(vis, cur))) {
1173 buffer_remove(buf, keys - buf->data, strlen(keys));
1174 return;
1177 char tmp = *end;
1178 *end = '\0';
1179 prefix = false;
1181 for (Mode *global_mode = vis->mode; global_mode && !prefix; global_mode = global_mode->parent) {
1182 for (int global = 0; global < 2 && !prefix; global++) {
1183 Mode *mode = (global || !vis->win) ?
1184 global_mode :
1185 &vis->win->modes[global_mode->id];
1186 if (!mode->bindings)
1187 continue;
1188 /* keep track of longest matching binding */
1189 KeyBinding *match = map_get(mode->bindings, start);
1190 if (match && end > binding_end) {
1191 binding = match;
1192 binding_end = end;
1195 const Map *pmap = map_prefix(mode->bindings, start);
1196 PrefixCompletion completions = {
1197 .vis = vis,
1198 .len = cur - start,
1199 .count = 0,
1200 .angle_bracket = !strcmp(cur, "<"),
1202 map_iterate(pmap, isprefix, &completions);
1204 prefix = (!match && completions.count > 0) ||
1205 ( match && completions.count > 1);
1209 *end = tmp;
1211 if (prefix) {
1212 /* input sofar is ambigious, wait for more */
1213 cur = end;
1214 end = start;
1215 } else if (binding) { /* exact match */
1216 if (binding->action) {
1217 size_t len = binding_end - start;
1218 strcpy(vis->key_prev, vis->key_current);
1219 strncpy(vis->key_current, start, len);
1220 vis->key_current[len] = '\0';
1221 end = (char*)binding->action->func(vis, binding_end, &binding->action->arg);
1222 if (!end) {
1223 end = start;
1224 break;
1226 start = cur = end;
1227 } else if (binding->alias) {
1228 buffer_remove(buf, start - buf->data, binding_end - start);
1229 buffer_insert0(buf, start - buf->data, binding->alias);
1230 cur = end = start;
1232 binding = NULL;
1233 binding_end = start;
1234 } else { /* no keybinding */
1235 KeyAction *action = NULL;
1236 if (start[0] == '<' && end[-1] == '>') {
1237 /* test for special editor key command */
1238 char tmp = end[-1];
1239 end[-1] = '\0';
1240 action = map_get(vis->actions, start+1);
1241 end[-1] = tmp;
1242 if (action) {
1243 size_t len = end - start;
1244 strcpy(vis->key_prev, vis->key_current);
1245 strncpy(vis->key_current, start, len);
1246 vis->key_current[len] = '\0';
1247 end = (char*)action->func(vis, end, &action->arg);
1248 if (!end) {
1249 end = start;
1250 break;
1254 if (!action && vis->mode->input) {
1255 end = (char*)vis_keys_next(vis, start);
1256 vis->mode->input(vis, start, end - start);
1258 start = cur = end;
1262 buffer_remove(buf, keys - buf->data, end - keys);
1265 void vis_keys_feed(Vis *vis, const char *input) {
1266 if (!input)
1267 return;
1268 Macro macro;
1269 macro_init(&macro);
1270 if (!macro_append(&macro, input))
1271 return;
1272 /* use internal function, to keep Lua based tests which use undo points working */
1273 macro_replay_internal(vis, &macro);
1274 macro_release(&macro);
1277 static void vis_keys_push(Vis *vis, const char *input, size_t pos, bool record) {
1278 if (!input)
1279 return;
1280 if (record && vis->recording)
1281 macro_append(vis->recording, input);
1282 if (vis->macro_operator)
1283 macro_append(vis->macro_operator, input);
1284 if (buffer_append0(&vis->input_queue, input))
1285 vis_keys_process(vis, pos);
1288 static const char *getkey(Vis *vis) {
1289 TermKeyKey key = { 0 };
1290 if (!vis->ui->getkey(vis->ui, &key))
1291 return NULL;
1292 vis_info_hide(vis);
1293 bool use_keymap = vis->mode->id != VIS_MODE_INSERT &&
1294 vis->mode->id != VIS_MODE_REPLACE &&
1295 !vis->keymap_disabled;
1296 vis->keymap_disabled = false;
1297 if (key.type == TERMKEY_TYPE_UNICODE && use_keymap) {
1298 const char *mapped = map_get(vis->keymap, key.utf8);
1299 if (mapped) {
1300 size_t len = strlen(mapped)+1;
1301 if (len <= sizeof(key.utf8))
1302 memcpy(key.utf8, mapped, len);
1306 TermKey *termkey = vis->ui->termkey_get(vis->ui);
1307 termkey_strfkey(termkey, vis->key, sizeof(vis->key), &key, TERMKEY_FORMAT_VIM);
1308 return vis->key;
1311 bool vis_signal_handler(Vis *vis, int signum, const siginfo_t *siginfo, const void *context) {
1312 switch (signum) {
1313 case SIGBUS:
1314 for (File *file = vis->files; file; file = file->next) {
1315 if (text_mmaped(file->text, siginfo->si_addr))
1316 file->truncated = true;
1318 vis->sigbus = true;
1319 if (vis->running)
1320 siglongjmp(vis->sigbus_jmpbuf, 1);
1321 return true;
1322 case SIGINT:
1323 vis->interrupted = true;
1324 return true;
1325 case SIGCONT:
1326 vis->resume = true;
1327 /* fall through */
1328 case SIGWINCH:
1329 vis->need_resize = true;
1330 return true;
1331 case SIGTERM:
1332 case SIGHUP:
1333 vis->terminate = true;
1334 return true;
1336 return false;
1339 int vis_run(Vis *vis) {
1340 if (!vis->windows)
1341 return EXIT_SUCCESS;
1342 if (vis->exit_status != -1)
1343 return vis->exit_status;
1344 vis->running = true;
1346 vis_event_emit(vis, VIS_EVENT_START);
1348 struct timespec idle = { .tv_nsec = 0 }, *timeout = NULL;
1350 sigset_t emptyset;
1351 sigemptyset(&emptyset);
1352 vis_draw(vis);
1353 vis->exit_status = EXIT_SUCCESS;
1355 sigsetjmp(vis->sigbus_jmpbuf, 1);
1357 while (vis->running) {
1358 fd_set fds;
1359 FD_ZERO(&fds);
1360 FD_SET(STDIN_FILENO, &fds);
1362 if (vis->sigbus) {
1363 char *name = NULL;
1364 for (Win *next, *win = vis->windows; win; win = next) {
1365 next = win->next;
1366 if (win->file->truncated) {
1367 free(name);
1368 name = strdup(win->file->name);
1369 vis_window_close(win);
1372 if (!vis->windows)
1373 vis_die(vis, "WARNING: file `%s' truncated!\n", name ? name : "-");
1374 else
1375 vis_info_show(vis, "WARNING: file `%s' truncated!\n", name ? name : "-");
1376 vis->sigbus = false;
1377 free(name);
1380 if (vis->terminate)
1381 vis_die(vis, "Killed by SIGTERM\n");
1382 if (vis->interrupted) {
1383 vis->interrupted = false;
1384 vis_keys_feed(vis, "<C-c>");
1387 if (vis->resume) {
1388 vis_resume(vis);
1389 vis->resume = false;
1392 if (vis->need_resize) {
1393 vis->ui->resize(vis->ui);
1394 vis->need_resize = false;
1397 vis_update(vis);
1398 idle.tv_sec = vis->mode->idle_timeout;
1399 int r = pselect(1, &fds, NULL, NULL, timeout, &emptyset);
1400 if (r == -1 && errno == EINTR)
1401 continue;
1403 if (r < 0) {
1404 /* TODO save all pending changes to a ~suffixed file */
1405 vis_die(vis, "Error in mainloop: %s\n", strerror(errno));
1408 if (!FD_ISSET(STDIN_FILENO, &fds)) {
1409 if (vis->mode->idle)
1410 vis->mode->idle(vis);
1411 timeout = NULL;
1412 continue;
1415 TermKey *termkey = vis->ui->termkey_get(vis->ui);
1416 termkey_advisereadable(termkey);
1417 const char *key;
1419 while ((key = getkey(vis)))
1420 vis_keys_push(vis, key, 0, true);
1422 if (vis->mode->idle)
1423 timeout = &idle;
1425 return vis->exit_status;
1428 Macro *macro_get(Vis *vis, enum VisRegister id) {
1429 if (id == VIS_MACRO_LAST_RECORDED)
1430 return vis->last_recording;
1431 if (VIS_REG_A <= id && id <= VIS_REG_Z)
1432 id -= VIS_REG_A;
1433 if (id < LENGTH(vis->registers))
1434 return array_get(&vis->registers[id].values, 0);
1435 return NULL;
1438 void macro_operator_record(Vis *vis) {
1439 if (vis->macro_operator)
1440 return;
1441 vis->macro_operator = macro_get(vis, VIS_MACRO_OPERATOR);
1442 macro_reset(vis->macro_operator);
1445 void macro_operator_stop(Vis *vis) {
1446 if (!vis->macro_operator)
1447 return;
1448 Macro *dot = macro_get(vis, VIS_REG_DOT);
1449 buffer_put(dot, vis->macro_operator->data, vis->macro_operator->len);
1450 vis->action_prev.macro = dot;
1451 vis->macro_operator = NULL;
1454 bool vis_macro_record(Vis *vis, enum VisRegister id) {
1455 Macro *macro = macro_get(vis, id);
1456 if (vis->recording || !macro)
1457 return false;
1458 if (!(VIS_REG_A <= id && id <= VIS_REG_Z))
1459 macro_reset(macro);
1460 vis->recording = macro;
1461 vis_event_emit(vis, VIS_EVENT_WIN_STATUS, vis->win);
1462 return true;
1465 bool vis_macro_record_stop(Vis *vis) {
1466 if (!vis->recording)
1467 return false;
1468 /* XXX: hack to remove last recorded key, otherwise upon replay
1469 * we would start another recording */
1470 if (vis->recording->len > 1) {
1471 vis->recording->len--;
1472 vis->recording->data[vis->recording->len-1] = '\0';
1474 vis->last_recording = vis->recording;
1475 vis->recording = NULL;
1476 vis_event_emit(vis, VIS_EVENT_WIN_STATUS, vis->win);
1477 return true;
1480 bool vis_macro_recording(Vis *vis) {
1481 return vis->recording;
1484 static void macro_replay(Vis *vis, const Macro *macro) {
1485 const Macro *replaying = vis->replaying;
1486 vis->replaying = macro;
1487 macro_replay_internal(vis, macro);
1488 vis->replaying = replaying;
1491 static void macro_replay_internal(Vis *vis, const Macro *macro) {
1492 size_t pos = buffer_length0(&vis->input_queue);
1493 for (char *key = macro->data, *next; key; key = next) {
1494 char tmp;
1495 next = (char*)vis_keys_next(vis, key);
1496 if (next) {
1497 tmp = *next;
1498 *next = '\0';
1501 vis_keys_push(vis, key, pos, false);
1503 if (next)
1504 *next = tmp;
1508 bool vis_macro_replay(Vis *vis, enum VisRegister id) {
1509 if (id == VIS_REG_SEARCH)
1510 return vis_motion(vis, VIS_MOVE_SEARCH_REPEAT_FORWARD);
1511 if (id == VIS_REG_COMMAND) {
1512 const char *cmd = register_get(vis, &vis->registers[id], NULL);
1513 return vis_cmd(vis, cmd);
1516 Macro *macro = macro_get(vis, id);
1517 if (!macro || macro == vis->recording)
1518 return false;
1519 int count = vis_count_get_default(vis, 1);
1520 vis_cancel(vis);
1521 for (int i = 0; i < count; i++)
1522 macro_replay(vis, macro);
1523 Win *win = vis->win;
1524 if (win)
1525 vis_file_snapshot(vis, win->file);
1526 return true;
1529 void vis_repeat(Vis *vis) {
1530 const Macro *macro = vis->action_prev.macro;
1531 int count = vis->action.count;
1532 if (count != VIS_COUNT_UNKNOWN)
1533 vis->action_prev.count = count;
1534 else
1535 count = vis->action_prev.count;
1536 vis->action = vis->action_prev;
1537 vis_mode_switch(vis, VIS_MODE_OPERATOR_PENDING);
1538 vis_do(vis);
1539 if (macro) {
1540 Mode *mode = vis->mode;
1541 Action action_prev = vis->action_prev;
1542 if (count < 1 || action_prev.op == &vis_operators[VIS_OP_CHANGE])
1543 count = 1;
1544 if (vis->action_prev.op == &vis_operators[VIS_OP_MODESWITCH])
1545 vis->action_prev.count = 1;
1546 for (int i = 0; i < count; i++) {
1547 if (vis->interrupted)
1548 break;
1549 mode_set(vis, mode);
1550 macro_replay(vis, macro);
1552 vis->action_prev = action_prev;
1554 vis_cancel(vis);
1555 Win *win = vis->win;
1556 if (win)
1557 vis_file_snapshot(vis, win->file);
1560 int vis_count_get(Vis *vis) {
1561 return vis->action.count;
1564 int vis_count_get_default(Vis *vis, int def) {
1565 if (vis->action.count == VIS_COUNT_UNKNOWN)
1566 return def;
1567 return vis->action.count;
1570 void vis_count_set(Vis *vis, int count) {
1571 vis->action.count = (count >= 0 ? count : VIS_COUNT_UNKNOWN);
1574 VisCountIterator vis_count_iterator_get(Vis *vis, int def) {
1575 return (VisCountIterator) {
1576 .vis = vis,
1577 .iteration = 0,
1578 .count = vis_count_get_default(vis, def),
1582 VisCountIterator vis_count_iterator_init(Vis *vis, int count) {
1583 return (VisCountIterator) {
1584 .vis = vis,
1585 .iteration = 0,
1586 .count = count,
1590 bool vis_count_iterator_next(VisCountIterator *it) {
1591 if (it->vis->interrupted)
1592 return false;
1593 return it->iteration++ < it->count;
1596 void vis_exit(Vis *vis, int status) {
1597 vis->running = false;
1598 vis->exit_status = status;
1601 void vis_insert_tab(Vis *vis) {
1602 Win *win = vis->win;
1603 if (!win)
1604 return;
1605 if (!vis->expandtab) {
1606 vis_insert_key(vis, "\t", 1);
1607 return;
1609 char spaces[9];
1610 int tabwidth = MIN(vis->tabwidth, LENGTH(spaces) - 1);
1611 for (Selection *s = view_selections(win->view); s; s = view_selections_next(s)) {
1612 size_t pos = view_cursors_pos(s);
1613 int width = text_line_width_get(win->file->text, pos);
1614 int count = tabwidth - (width % tabwidth);
1615 for (int i = 0; i < count; i++)
1616 spaces[i] = ' ';
1617 spaces[count] = '\0';
1618 vis_insert(vis, pos, spaces, count);
1619 view_cursors_scroll_to(s, pos + count);
1623 size_t vis_text_insert_nl(Vis *vis, Text *txt, size_t pos) {
1624 size_t indent_len = 0;
1625 char byte, *indent = NULL;
1626 /* insert second newline at end of file, except if there is already one */
1627 bool eof = pos == text_size(txt);
1628 bool nl2 = eof && !(pos > 0 && text_byte_get(txt, pos-1, &byte) && byte == '\n');
1630 if (vis->autoindent) {
1631 /* copy leading white space of current line */
1632 size_t begin = text_line_begin(txt, pos);
1633 size_t start = text_line_start(txt, begin);
1634 size_t end = text_line_end(txt, start);
1635 if (start > pos)
1636 start = pos;
1637 indent_len = start >= begin ? start-begin : 0;
1638 if (start == end) {
1639 pos = begin;
1640 } else {
1641 indent = malloc(indent_len+1);
1642 if (indent)
1643 indent_len = text_bytes_get(txt, begin, indent_len, indent);
1647 text_insert(txt, pos, "\n", 1);
1648 if (eof) {
1649 if (nl2)
1650 text_insert(txt, text_size(txt), "\n", 1);
1651 else
1652 pos--; /* place cursor before, not after nl */
1654 pos++;
1656 if (indent)
1657 text_insert(txt, pos, indent, indent_len);
1658 free(indent);
1659 return pos + indent_len;
1662 void vis_insert_nl(Vis *vis) {
1663 Win *win = vis->win;
1664 if (!win)
1665 return;
1666 View *view = win->view;
1667 Text *txt = win->file->text;
1668 for (Selection *s = view_selections(view); s; s = view_selections_next(s)) {
1669 size_t pos = view_cursors_pos(s);
1670 size_t newpos = vis_text_insert_nl(vis, txt, pos);
1671 /* This is a bit of a hack to fix cursor positioning when
1672 * inserting a new line at the start of the view port.
1673 * It has the effect of reseting the mark used by the view
1674 * code to keep track of the start of the visible region.
1676 view_cursors_to(s, pos);
1677 view_cursors_to(s, newpos);
1679 vis_window_invalidate(win);
1682 Regex *vis_regex(Vis *vis, const char *pattern) {
1683 if (!pattern && !(pattern = register_get(vis, &vis->registers[VIS_REG_SEARCH], NULL)))
1684 return NULL;
1685 Regex *regex = text_regex_new();
1686 if (!regex)
1687 return NULL;
1688 if (text_regex_compile(regex, pattern, REG_EXTENDED|REG_NEWLINE) != 0) {
1689 text_regex_free(regex);
1690 return NULL;
1692 register_put0(vis, &vis->registers[VIS_REG_SEARCH], pattern);
1693 return regex;
1696 int vis_pipe(Vis *vis, File *file, Filerange *range, const char *argv[],
1697 void *stdout_context, ssize_t (*read_stdout)(void *stdout_context, char *data, size_t len),
1698 void *stderr_context, ssize_t (*read_stderr)(void *stderr_context, char *data, size_t len)) {
1700 /* if an invalid range was given, stdin (i.e. key board input) is passed
1701 * through the external command. */
1702 Text *text = file->text;
1703 int pin[2], pout[2], perr[2], status = -1;
1704 bool interactive = !text_range_valid(range);
1705 Filerange rout = interactive ? text_range_new(0, 0) : *range;
1707 if (pipe(pin) == -1)
1708 return -1;
1709 if (pipe(pout) == -1) {
1710 close(pin[0]);
1711 close(pin[1]);
1712 return -1;
1715 if (pipe(perr) == -1) {
1716 close(pin[0]);
1717 close(pin[1]);
1718 close(pout[0]);
1719 close(pout[1]);
1720 return -1;
1723 vis->ui->terminal_save(vis->ui);
1724 pid_t pid = fork();
1726 if (pid == -1) {
1727 close(pin[0]);
1728 close(pin[1]);
1729 close(pout[0]);
1730 close(pout[1]);
1731 close(perr[0]);
1732 close(perr[1]);
1733 vis_info_show(vis, "fork failure: %s", strerror(errno));
1734 return -1;
1735 } else if (pid == 0) { /* child i.e filter */
1736 sigset_t sigterm_mask;
1737 sigemptyset(&sigterm_mask);
1738 sigaddset(&sigterm_mask, SIGTERM);
1739 if (sigprocmask(SIG_UNBLOCK, &sigterm_mask, NULL) == -1) {
1740 fprintf(stderr, "failed to reset signal mask");
1741 exit(EXIT_FAILURE);
1744 int null = open("/dev/null", O_RDWR);
1745 if (null == -1) {
1746 fprintf(stderr, "failed to open /dev/null");
1747 exit(EXIT_FAILURE);
1750 if (!interactive) {
1751 /* If we have nothing to write, let stdin point to
1752 * /dev/null instead of a pipe which is immediately
1753 * closed. Some programs behave differently when used
1754 * in a pipeline.
1756 if (text_range_size(range) == 0)
1757 dup2(null, STDIN_FILENO);
1758 else
1759 dup2(pin[0], STDIN_FILENO);
1762 close(pin[0]);
1763 close(pin[1]);
1764 if (interactive) {
1765 dup2(STDERR_FILENO, STDOUT_FILENO);
1766 /* For some reason the first byte written by the
1767 * interactive application is not being displayed.
1768 * It probably has something to do with the terminal
1769 * state change. By writing a dummy byte ourself we
1770 * ensure that the complete output is visible.
1772 while(write(STDOUT_FILENO, " ", 1) == -1 && errno == EINTR);
1773 } else if (read_stdout) {
1774 dup2(pout[1], STDOUT_FILENO);
1775 } else {
1776 dup2(null, STDOUT_FILENO);
1778 close(pout[1]);
1779 close(pout[0]);
1780 if (!interactive) {
1781 if (read_stderr)
1782 dup2(perr[1], STDERR_FILENO);
1783 else
1784 dup2(null, STDERR_FILENO);
1786 close(perr[0]);
1787 close(perr[1]);
1788 close(null);
1790 if (file->name) {
1791 char *name = strrchr(file->name, '/');
1792 setenv("vis_filepath", file->name, 1);
1793 setenv("vis_filename", name ? name+1 : file->name, 1);
1796 if (!argv[1])
1797 execlp(vis->shell, vis->shell, "-c", argv[0], (char*)NULL);
1798 else
1799 execvp(argv[0], (char* const*)argv);
1800 fprintf(stderr, "exec failure: %s", strerror(errno));
1801 exit(EXIT_FAILURE);
1804 vis->interrupted = false;
1806 close(pin[0]);
1807 close(pout[1]);
1808 close(perr[1]);
1810 if (fcntl(pout[0], F_SETFL, O_NONBLOCK) == -1 ||
1811 fcntl(perr[0], F_SETFL, O_NONBLOCK) == -1)
1812 goto err;
1814 fd_set rfds, wfds;
1816 do {
1817 if (vis->interrupted) {
1818 kill(0, SIGTERM);
1819 break;
1822 FD_ZERO(&rfds);
1823 FD_ZERO(&wfds);
1824 if (pin[1] != -1)
1825 FD_SET(pin[1], &wfds);
1826 if (pout[0] != -1)
1827 FD_SET(pout[0], &rfds);
1828 if (perr[0] != -1)
1829 FD_SET(perr[0], &rfds);
1831 if (select(FD_SETSIZE, &rfds, &wfds, NULL, NULL) == -1) {
1832 if (errno == EINTR)
1833 continue;
1834 vis_info_show(vis, "Select failure");
1835 break;
1838 if (pin[1] != -1 && FD_ISSET(pin[1], &wfds)) {
1839 Filerange junk = rout;
1840 if (junk.end > junk.start + PIPE_BUF)
1841 junk.end = junk.start + PIPE_BUF;
1842 ssize_t len = text_write_range(text, &junk, pin[1]);
1843 if (len > 0) {
1844 rout.start += len;
1845 if (text_range_size(&rout) == 0) {
1846 close(pout[1]);
1847 pout[1] = -1;
1849 } else {
1850 close(pin[1]);
1851 pin[1] = -1;
1852 if (len == -1)
1853 vis_info_show(vis, "Error writing to external command");
1857 if (pout[0] != -1 && FD_ISSET(pout[0], &rfds)) {
1858 char buf[BUFSIZ];
1859 ssize_t len = read(pout[0], buf, sizeof buf);
1860 if (len > 0) {
1861 if (read_stdout)
1862 (*read_stdout)(stdout_context, buf, len);
1863 } else if (len == 0) {
1864 close(pout[0]);
1865 pout[0] = -1;
1866 } else if (errno != EINTR && errno != EWOULDBLOCK) {
1867 vis_info_show(vis, "Error reading from filter stdout");
1868 close(pout[0]);
1869 pout[0] = -1;
1873 if (perr[0] != -1 && FD_ISSET(perr[0], &rfds)) {
1874 char buf[BUFSIZ];
1875 ssize_t len = read(perr[0], buf, sizeof buf);
1876 if (len > 0) {
1877 if (read_stderr)
1878 (*read_stderr)(stderr_context, buf, len);
1879 } else if (len == 0) {
1880 close(perr[0]);
1881 perr[0] = -1;
1882 } else if (errno != EINTR && errno != EWOULDBLOCK) {
1883 vis_info_show(vis, "Error reading from filter stderr");
1884 close(perr[0]);
1885 perr[0] = -1;
1889 } while (pin[1] != -1 || pout[0] != -1 || perr[0] != -1);
1891 err:
1892 if (pin[1] != -1)
1893 close(pin[1]);
1894 if (pout[0] != -1)
1895 close(pout[0]);
1896 if (perr[0] != -1)
1897 close(perr[0]);
1899 for (;;) {
1900 if (vis->interrupted)
1901 kill(0, SIGTERM);
1902 pid_t died = waitpid(pid, &status, 0);
1903 if ((died == -1 && errno == ECHILD) || pid == died)
1904 break;
1907 /* clear any pending SIGTERM */
1908 struct sigaction sigterm_ignore, sigterm_old;
1909 sigterm_ignore.sa_handler = SIG_IGN;
1910 sigterm_ignore.sa_flags = 0;
1911 sigemptyset(&sigterm_ignore.sa_mask);
1913 sigaction(SIGTERM, &sigterm_ignore, &sigterm_old);
1914 sigaction(SIGTERM, &sigterm_old, NULL);
1916 vis->interrupted = false;
1917 vis->ui->terminal_restore(vis->ui);
1919 return status;
1922 static ssize_t read_buffer(void *context, char *data, size_t len) {
1923 buffer_append(context, data, len);
1924 return len;
1927 int vis_pipe_collect(Vis *vis, File *file, Filerange *range, const char *argv[], char **out, char **err) {
1928 Buffer bufout, buferr;
1929 buffer_init(&bufout);
1930 buffer_init(&buferr);
1931 int status = vis_pipe(vis, file, range, argv,
1932 &bufout, out ? read_buffer : NULL,
1933 &buferr, err ? read_buffer : NULL);
1934 buffer_terminate(&bufout);
1935 buffer_terminate(&buferr);
1936 if (out)
1937 *out = buffer_move(&bufout);
1938 if (err)
1939 *err = buffer_move(&buferr);
1940 buffer_release(&bufout);
1941 buffer_release(&buferr);
1942 return status;
1945 bool vis_cmd(Vis *vis, const char *cmdline) {
1946 if (!cmdline)
1947 return true;
1948 while (*cmdline == ':')
1949 cmdline++;
1950 char *line = strdup(cmdline);
1951 if (!line)
1952 return false;
1954 size_t len = strlen(line);
1955 while (len > 0 && isspace((unsigned char)line[len-1]))
1956 len--;
1957 line[len] = '\0';
1959 enum SamError err = sam_cmd(vis, line);
1960 if (err != SAM_ERR_OK)
1961 vis_info_show(vis, "%s", sam_error(err));
1962 free(line);
1963 return err == SAM_ERR_OK;
1966 void vis_file_snapshot(Vis *vis, File *file) {
1967 if (!vis->replaying)
1968 text_snapshot(file->text);
1971 Text *vis_text(Vis *vis) {
1972 Win *win = vis->win;
1973 return win ? win->file->text : NULL;
1976 View *vis_view(Vis *vis) {
1977 Win *win = vis->win;
1978 return win ? win->view : NULL;
1981 Win *vis_window(Vis *vis) {
1982 return vis->win;
1985 bool vis_get_autoindent(const Vis *vis) {
1986 return vis->autoindent;