From 207a537343ace1d39ac125059456d832a5237f2e Mon Sep 17 00:00:00 2001 From: zimbatm Date: Wed, 23 Oct 2019 16:48:28 +0200 Subject: [PATCH] libutil: add editorFor heuristic --- src/libutil/args.cc | 13 +++++++++++++ src/libutil/args.hh | 3 +++ src/nix/edit.cc | 17 +++++------------ src/nix/repl.cc | 11 ++--------- 4 files changed, 23 insertions(+), 21 deletions(-) diff --git a/src/libutil/args.cc b/src/libutil/args.cc index 7af2a1bf7..35ec3e4ab 100644 --- a/src/libutil/args.cc +++ b/src/libutil/args.cc @@ -178,6 +178,19 @@ Strings argvToStrings(int argc, char * * argv) return args; } +Strings editorFor(std::string filename, int lineno) +{ + auto editor = getEnv("EDITOR", "cat"); + auto args = tokenizeString(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 res; diff --git a/src/libutil/args.hh b/src/libutil/args.hh index ad5fcca39..22702c2d8 100644 --- a/src/libutil/args.hh +++ b/src/libutil/args.hh @@ -190,6 +190,9 @@ public: 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. */ std::string renderLabels(const Strings & labels); diff --git a/src/nix/edit.cc b/src/nix/edit.cc index a6169f118..3a27b9cca 100644 --- a/src/nix/edit.cc +++ b/src/nix/edit.cc @@ -59,22 +59,15 @@ struct CmdEdit : InstallableCommand throw Error("cannot parse line number '%s'", pos); } - auto editor = getEnv("EDITOR", "cat"); - - auto args = tokenizeString(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(); + auto args = editorFor(filename, lineno); + 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); } }; diff --git a/src/nix/repl.cc b/src/nix/repl.cc index 79f365cdb..d4334cf7f 100644 --- a/src/nix/repl.cc +++ b/src/nix/repl.cc @@ -506,15 +506,8 @@ bool NixRepl::processLine(string line) } // Open in EDITOR - auto editor = getEnv("EDITOR", "cat"); - auto args = tokenizeString(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); - editor = args.front(); + auto args = editorFor(filename, lineno); + auto editor = args.front(); args.pop_front(); runProgram(editor, args);