libutil: add editorFor heuristic

This commit is contained in:
Jonas Chevalier 2019-10-23 16:48:28 +02:00
parent 73ff84f6a8
commit 207a537343
No known key found for this signature in database
GPG key ID: 71BAF6D40C1D63D7
4 changed files with 23 additions and 21 deletions

View file

@ -178,6 +178,19 @@ Strings argvToStrings(int argc, char * * argv)
return args; return args;
} }
Strings editorFor(std::string filename, int lineno)
{
auto editor = getEnv("EDITOR", "cat");
auto args = tokenizeString<Strings>(editor);
if (lineno > 0 && (
editor.find("emacs") != std::string::npos ||
editor.find("nano") != std::string::npos ||
editor.find("vim") != std::string::npos))
args.push_back(fmt("+%d", lineno));
args.push_back(filename);
return args;
}
std::string renderLabels(const Strings & labels) std::string renderLabels(const Strings & labels)
{ {
std::string res; std::string res;

View file

@ -190,6 +190,9 @@ public:
Strings argvToStrings(int argc, char * * argv); Strings argvToStrings(int argc, char * * argv);
/* Helper function to generate args that invoke $EDITOR on filename:lineno */
Strings editorFor(std::string filename, int lineno);
/* Helper function for rendering argument labels. */ /* Helper function for rendering argument labels. */
std::string renderLabels(const Strings & labels); std::string renderLabels(const Strings & labels);

View file

@ -59,22 +59,15 @@ struct CmdEdit : InstallableCommand
throw Error("cannot parse line number '%s'", pos); throw Error("cannot parse line number '%s'", pos);
} }
auto editor = getEnv("EDITOR", "cat");
auto args = tokenizeString<Strings>(editor);
if (editor.find("emacs") != std::string::npos ||
editor.find("nano") != std::string::npos ||
editor.find("vim") != std::string::npos)
args.push_back(fmt("+%d", lineno));
args.push_back(filename);
stopProgressBar(); stopProgressBar();
auto args = editorFor(filename, lineno);
execvp(args.front().c_str(), stringsToCharPtrs(args).data()); execvp(args.front().c_str(), stringsToCharPtrs(args).data());
throw SysError("cannot run editor '%s'", editor); std::string command;
for (const auto &arg : args) command += " '" + arg + "'";
throw SysError("cannot run command%s", command);
} }
}; };

View file

@ -506,15 +506,8 @@ bool NixRepl::processLine(string line)
} }
// Open in EDITOR // Open in EDITOR
auto editor = getEnv("EDITOR", "cat"); auto args = editorFor(filename, lineno);
auto args = tokenizeString<Strings>(editor); auto editor = args.front();
if (lineno > 0 && (
editor.find("emacs") != std::string::npos ||
editor.find("nano") != std::string::npos ||
editor.find("vim") != std::string::npos))
args.push_back(fmt("+%d", lineno));
args.push_back(filename);
editor = args.front();
args.pop_front(); args.pop_front();
runProgram(editor, args); runProgram(editor, args);