blob: d8340031d24828483697c10257806efedfe041f5 [file] [log] [blame]
Stephan Beyerd82f33e2008-07-25 18:28:41 +02001#include "cache.h"
2#include "strbuf.h"
3#include "run-command.h"
4
Jonathan Nieder8f4b5762009-10-30 20:44:41 -05005#ifndef DEFAULT_EDITOR
6#define DEFAULT_EDITOR "vi"
7#endif
8
Jonathan Nieder44fcb492009-11-11 18:01:27 -06009const char *git_editor(void)
Stephan Beyerd82f33e2008-07-25 18:28:41 +020010{
Jonathan Niederd33738d2009-11-11 17:56:07 -060011 const char *editor = getenv("GIT_EDITOR");
12 const char *terminal = getenv("TERM");
13 int terminal_is_dumb = !terminal || !strcmp(terminal, "dumb");
Stephan Beyerd82f33e2008-07-25 18:28:41 +020014
Stephan Beyerd82f33e2008-07-25 18:28:41 +020015 if (!editor && editor_program)
16 editor = editor_program;
Jonathan Niederd33738d2009-11-11 17:56:07 -060017 if (!editor && !terminal_is_dumb)
Stephan Beyerd82f33e2008-07-25 18:28:41 +020018 editor = getenv("VISUAL");
19 if (!editor)
20 editor = getenv("EDITOR");
21
Jonathan Niederd33738d2009-11-11 17:56:07 -060022 if (!editor && terminal_is_dumb)
Jonathan Nieder44fcb492009-11-11 18:01:27 -060023 return NULL;
Stephan Beyerd82f33e2008-07-25 18:28:41 +020024
25 if (!editor)
Jonathan Nieder8f4b5762009-10-30 20:44:41 -050026 editor = DEFAULT_EDITOR;
Stephan Beyerd82f33e2008-07-25 18:28:41 +020027
Jonathan Nieder44fcb492009-11-11 18:01:27 -060028 return editor;
29}
30
31int launch_editor(const char *path, struct strbuf *buffer, const char *const *env)
32{
33 const char *editor = git_editor();
34
35 if (!editor)
36 return error("Terminal is dumb, but EDITOR unset");
37
Stephan Beyerd82f33e2008-07-25 18:28:41 +020038 if (strcmp(editor, ":")) {
Jeff Kingbac80372009-12-30 05:56:16 -050039 const char *args[] = { editor, path, NULL };
Stephan Beyerd82f33e2008-07-25 18:28:41 +020040
Jeff Kingbac80372009-12-30 05:56:16 -050041 if (run_command_v_opt_cd_env(args, RUN_USING_SHELL, NULL, env))
Stephan Beyer71982032008-07-25 18:28:42 +020042 return error("There was a problem with the editor '%s'.",
43 editor);
Stephan Beyerd82f33e2008-07-25 18:28:41 +020044 }
45
46 if (!buffer)
Stephan Beyer71982032008-07-25 18:28:42 +020047 return 0;
Stephan Beyerd82f33e2008-07-25 18:28:41 +020048 if (strbuf_read_file(buffer, path, 0) < 0)
Stephan Beyer71982032008-07-25 18:28:42 +020049 return error("could not read file '%s': %s",
50 path, strerror(errno));
51 return 0;
Stephan Beyerd82f33e2008-07-25 18:28:41 +020052}