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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
use std::{
env,
path::{Path, PathBuf},
};
/// Resolve VISUAL, EDITOR, or the deterministic fallback without invoking a shell.
pub fn resolve_editor() -> Result<(PathBuf, Vec<String>), String> {
for key in ["VISUAL", "EDITOR"] {
if let Ok(value) = env::var(key)
&& !value.trim().is_empty()
{
let mut words = match split_words(&value) {
Ok(words) => words,
Err(_) => continue,
};
if words.is_empty() {
continue;
}
// An unusable value in one variable must not hide the next
// candidate: fall through to EDITOR, then to the fallback list.
let program = words[0].clone();
if let Some(resolved) = resolve_program(&program) {
words.remove(0);
return Ok((resolved, words));
}
}
}
for name in ["hx", "vim", "vi", "nano"] {
if let Some(program) = find_on_path(name) {
return Ok((program, Vec::new()));
}
}
Err(
"no editor found; set VISUAL or EDITOR to an executable, or install hx, vim, vi, or nano"
.into(),
)
}
fn resolve_program(spec: &str) -> Option<PathBuf> {
let path = Path::new(spec);
if path.components().count() > 1 || path.is_absolute() {
// An explicit path has to be *runnable*, not merely present. A file
// that cannot be executed resolves to a launch that fails with
// "Permission denied", and the operator is told to point VISUAL or
// EDITOR at an executable — so accepting one would hide the next
// candidate behind a value the resolver already knows is unusable.
return runnable_file(path).then(|| path.to_path_buf());
}
find_on_path(spec)
}
fn find_on_path(name: &str) -> Option<PathBuf> {
let paths = env::var_os("PATH")?;
for dir in env::split_paths(&paths) {
#[cfg(windows)]
{
let mut suffixes = vec![String::new()];
if Path::new(name).extension().is_none() {
let pathext =
env::var_os("PATHEXT").unwrap_or_else(|| ".COM;.EXE;.BAT;.CMD".into());
suffixes.extend(
pathext
.to_string_lossy()
.split(';')
.filter(|s| !s.is_empty())
.map(str::to_owned),
);
}
for suffix in suffixes {
let p = dir.join(format!("{name}{suffix}"));
if runnable_file(&p) {
return Some(p);
}
}
}
#[cfg(not(windows))]
{
let p = dir.join(name);
if runnable_file(&p) {
return Some(p);
}
}
}
None
}
fn runnable_file(path: &Path) -> bool {
if !path.is_file() {
return false;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
path.metadata()
.is_ok_and(|m| m.permissions().mode() & 0o111 != 0)
}
#[cfg(not(unix))]
{
true
}
}
fn split_words(spec: &str) -> Result<Vec<String>, String> {
let mut words = Vec::new();
let mut word = String::new();
let mut quote = None;
let mut started = false;
let mut chars = spec.chars().peekable();
while let Some(ch) = chars.next() {
// Inside a quoted run only the opening quote closes it, and only a
// double-quoted run honours backslash escapes.
if let Some(open) = quote {
match ch {
c if c == open => quote = None,
'\\' if open == '"' && matches!(chars.peek(), Some('"' | '\\')) => {
word.push(chars.next().unwrap())
}
c => word.push(c),
}
continue;
}
match ch {
'\'' | '"' => {
quote = Some(ch);
started = true;
}
'\\' => {
if let Some(next) = chars.next() {
if next.is_whitespace() || next == '\\' || next == '\'' || next == '"' {
word.push(next)
} else {
word.push('\\');
word.push(next)
}
} else {
return Err("VISUAL/EDITOR has an unfinished escape".into());
}
started = true;
}
c if c.is_whitespace() => {
if started {
words.push(std::mem::take(&mut word));
started = false;
}
}
c => {
word.push(c);
started = true;
}
}
}
if quote.is_some() {
return Err("VISUAL/EDITOR has an unfinished quote".into());
}
if started {
words.push(word)
}
Ok(words)
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn parser_preserves_arguments_and_windows_backslashes() {
assert_eq!(
split_words("code --wait 'path with spaces'").unwrap(),
["code", "--wait", "path with spaces"]
);
assert_eq!(
split_words(r#"editor "C:\Users\Jane\file.toml""#).unwrap(),
["editor", r"C:\Users\Jane\file.toml"]
);
assert!(split_words("vim 'unfinished").is_err());
}
/// An unusable `VISUAL` falls through to `EDITOR`.
///
/// *Fails if:* the resolver hard-fails on an unusable `VISUAL` even when
/// `EDITOR` names a usable program (L19). The environment mutation runs
/// in a child process: `VISUAL`/`EDITOR` are process-global, and the
/// lock this test used to take covered the writers only — another thread
/// in this binary could read them while they were being rewritten.
#[test]
fn unresolvable_visual_falls_through_to_the_next_candidate() {
let out = crate::progress::test_env::run_in_child(
"EDITOR_ENV_PROBE_ARMED",
"editor::tests::unresolvable_visual_probe",
);
crate::progress::test_env::assert_probe_ran(&out);
}
/// Probe for the test above.
///
/// Passes vacuously without the arming marker, so a direct `cargo test`
/// run never mutates the shared environment. With the marker — a child
/// process running exactly this one test — it mutates `VISUAL`/`EDITOR`
/// and asserts on the fall-through.
#[test]
fn unresolvable_visual_probe() {
if std::env::var("EDITOR_ENV_PROBE_ARMED").is_err() {
return;
}
let program = tempfile::tempdir().unwrap();
let editor = program.path().join("ed");
// fixture-scope: never executed on any platform, so the `#!` line is
// not a claim that this file is an executable. `resolve_editor` only
// *resolves* a program (`resolve_program` accepts an existing
// runnable file for an explicit path); it never spawns it. The case
// asserts the fall-through from an unusable VISUAL to a usable EDITOR.
fs::write(&editor, "#!/bin/sh\nexit 0\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&editor, fs::Permissions::from_mode(0o755)).unwrap();
}
let dir = program.path();
// SAFETY: this process runs exactly this one test, so no other
// thread can observe the mutation.
unsafe {
std::env::set_var("VISUAL", "/nonexistent/editor");
std::env::set_var("EDITOR", &editor);
}
let (resolved, args) = resolve_editor().unwrap();
assert_eq!(resolved, editor, "must fall through to EDITOR");
assert!(args.is_empty());
unsafe { std::env::remove_var("VISUAL") };
let (resolved, _) = resolve_editor().unwrap();
assert_eq!(resolved, editor);
let _ = dir;
}
/// A `VISUAL` that cannot be executed falls through to `EDITOR`.
///
/// The contract at the top of this file says an unusable value in one
/// variable must not hide the next candidate. A file that is present but
/// not executable is unusable: accepting it produced a launch that failed
/// with "Permission denied", while the resolver had already decided the
/// value was good and never consulted `EDITOR` or the fallback list.
///
/// Platform scope: on Windows every file is a candidate to spawn, so
/// there is no "not executable" state to fall through from.
#[cfg(unix)]
#[test]
fn an_unexecutable_visual_falls_through_to_the_next_candidate() {
let out = crate::progress::test_env::run_in_child(
"EDITOR_ENV_PROBE_ARMED",
"editor::tests::unexecutable_visual_probe",
);
crate::progress::test_env::assert_probe_ran(&out);
}
/// Probe for the test above.
///
/// Passes vacuously without the arming marker, so a direct `cargo test`
/// run never mutates the shared environment.
#[cfg(unix)]
#[test]
fn unexecutable_visual_probe() {
if std::env::var("EDITOR_ENV_PROBE_ARMED").is_err() {
return;
}
let program = tempfile::tempdir().unwrap();
// Present, readable, and not executable: a value the resolver must
// reject rather than resolve.
let unusable = program.path().join("not-executable");
fs::write(&unusable, "#!/bin/sh\nexit 0\n").unwrap();
let editor = program.path().join("ed");
fs::write(&editor, "#!/bin/sh\nexit 0\n").unwrap();
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&editor, fs::Permissions::from_mode(0o755)).unwrap();
}
// SAFETY: this process runs exactly this one test, so no other
// thread can observe the mutation.
unsafe {
std::env::set_var("VISUAL", &unusable);
std::env::set_var("EDITOR", &editor);
}
let (resolved, args) = resolve_editor().unwrap();
assert_eq!(
resolved, editor,
"a VISUAL that cannot be executed must not hide EDITOR"
);
assert!(args.is_empty());
unsafe {
std::env::remove_var("VISUAL");
std::env::remove_var("EDITOR");
}
}
}