refactor "dumb" terminal determination
[git/git.git] / editor.c
1 #include "cache.h"
2 #include "strbuf.h"
3 #include "run-command.h"
4 #include "sigchain.h"
5
6 #ifndef DEFAULT_EDITOR
7 #define DEFAULT_EDITOR "vi"
8 #endif
9
10 int is_terminal_dumb(void)
11 {
12 const char *terminal = getenv("TERM");
13 return !terminal || !strcmp(terminal, "dumb");
14 }
15
16 const char *git_editor(void)
17 {
18 const char *editor = getenv("GIT_EDITOR");
19 int terminal_is_dumb = is_terminal_dumb();
20
21 if (!editor && editor_program)
22 editor = editor_program;
23 if (!editor && !terminal_is_dumb)
24 editor = getenv("VISUAL");
25 if (!editor)
26 editor = getenv("EDITOR");
27
28 if (!editor && terminal_is_dumb)
29 return NULL;
30
31 if (!editor)
32 editor = DEFAULT_EDITOR;
33
34 return editor;
35 }
36
37 int launch_editor(const char *path, struct strbuf *buffer, const char *const *env)
38 {
39 const char *editor = git_editor();
40
41 if (!editor)
42 return error("Terminal is dumb, but EDITOR unset");
43
44 if (strcmp(editor, ":")) {
45 const char *args[] = { editor, real_path(path), NULL };
46 struct child_process p = CHILD_PROCESS_INIT;
47 int ret, sig;
48
49 p.argv = args;
50 p.env = env;
51 p.use_shell = 1;
52 if (start_command(&p) < 0)
53 return error("unable to start editor '%s'", editor);
54
55 sigchain_push(SIGINT, SIG_IGN);
56 sigchain_push(SIGQUIT, SIG_IGN);
57 ret = finish_command(&p);
58 sig = ret - 128;
59 sigchain_pop(SIGINT);
60 sigchain_pop(SIGQUIT);
61 if (sig == SIGINT || sig == SIGQUIT)
62 raise(sig);
63 if (ret)
64 return error("There was a problem with the editor '%s'.",
65 editor);
66 }
67
68 if (!buffer)
69 return 0;
70 if (strbuf_read_file(buffer, path, 0) < 0)
71 return error_errno("could not read file '%s'", path);
72 return 0;
73 }