summaryrefslogtreecommitdiff
path: root/input.c
blob: 36670e201deb738a45112c0d51c8edcee4272f27 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include "input.h"

#include "editor.h"
#include "file.h"
#include "line.h"

void input_process_textinput(struct editor_state *editor, const char *text)
{
	/* Ignore the first letter after entering insert mode. */
	if (editor->pressed_insert_key) {
		editor->pressed_insert_key = 0;
		return;
	}

	if (editor->mode == EDITOR_MODE_INSERT) {
		editor_insert_char(editor, *text);
	} else if (editor->mode == EDITOR_MODE_COMMAND) {
		textbuf_append(&editor->cmdline, text, 1);
	}
}

void editor_process_keypress(struct editor_state *editor, SDL_Keysym *keysym)
{
	/* Handle keypresses for typing modes separately. */
	if (editor->mode == EDITOR_MODE_INSERT) {
		if (keysym->sym == SDLK_BACKSPACE)
			editor_delete_char(editor);

		if (keysym->sym == SDLK_RETURN)
			editor_insert_newline(editor);

		if (keysym->sym == SDLK_TAB)
			editor_insert_char(editor, '\t');

		if (keysym->sym == SDLK_ESCAPE)
			editor->mode = EDITOR_MODE_NORMAL;
		return;
	}

	if (editor->mode == EDITOR_MODE_COMMAND) {
		if (keysym->sym == SDLK_BACKSPACE)
			textbuf_delete(&editor->cmdline);

		if (keysym->sym == SDLK_RETURN)
			editor_run_command(editor);

		if (keysym->sym == SDLK_ESCAPE)
			editor->mode = EDITOR_MODE_NORMAL;
		return;
	}

	switch (keysym->sym) {
		/* TODO: Reimplement page up/down on Shift+W/S. */
		case SDLK_w:
			editor_move_up(editor);
			break;
		case SDLK_s:
			if (keysym->mod & KMOD_CTRL) {
				editor_save(editor);
				break;
			}
			editor_move_down(editor);
			break;
		case SDLK_a:
			editor_move_left(editor);
			break;
		case SDLK_d:
			editor_move_right(editor);
			break;
		case SDLK_q:
			if (keysym->mod & KMOD_CTRL) {
				editor_try_quit(editor);
				break;
			}
			editor->cursor_x = 0;
			break;
		case SDLK_e:
			editor_move_end(editor);
			break;
		case SDLK_n:
			editor_delete_char(editor);
			break;
		case SDLK_m:
			editor_move_right(editor);
			editor_delete_char(editor);
			break;
		case SDLK_i:
			editor->mode = EDITOR_MODE_INSERT;
			editor->pressed_insert_key = 1;
			break;
		case SDLK_l:
			if (keysym->mod & KMOD_SHIFT)
				editor_move_end(editor);
			else
				editor_move_right(editor);
			editor->mode = EDITOR_MODE_INSERT;
			editor->pressed_insert_key = 1;
			break;
		case SDLK_o:
			if (keysym->mod & KMOD_SHIFT)
				editor_add_line_above(editor);
			else
				editor_add_line_below(editor);
			editor->mode = EDITOR_MODE_INSERT;
			editor->pressed_insert_key = 1;
			break;
		case SDLK_SLASH:
			editor_find(editor);
			break;
		case SDLK_SEMICOLON:
			editor->mode = EDITOR_MODE_COMMAND;
			break;
	}
}