Debian Codegraph @

helix-view/src/expansion.rs

raw symbols SCIP
1 use std::borrow::Cow;
2
3 use helix_core::command_line::{ExpansionKind, Token, TokenKind, Tokenizer};
4
5 use anyhow::{anyhow, bail, ensure, Result};
6
7 use crate::Editor;
8
9 /// Variables that can be expanded in the command mode (`:`) via the expansion syntax.
10 ///
11 /// For example `%{cursor_line}`.
12 //
13 // To add a new variable follow these steps:
14 //
15 // * Add the new enum member to `Variable` below.
16 // * Add an item to the `VARIANTS` constant - this enables completion.
17 // * Add a branch in `Variable::as_str`, converting the name from TitleCase to snake_case.
18 // * Add a branch in `Variable::from_name` with the reverse association.
19 // * Add a branch in the `expand_variable` function to read the value from the editor.
20 // * Add the new variable to the documentation in `book/src/command-line.md`.
21 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
22 pub enum Variable {
23 /// The one-indexed line number of the primary cursor in the currently focused document.
24 CursorLine,
25 /// The one-indexed column number of the primary cursor in the currently focused document.
26 ///
27 /// Note that this is the count of grapheme clusters from the start of the line (regardless of
28 /// softwrap) - the same as the `position` element in the statusline.
29 CursorColumn,
30 /// The display name of the currently focused document.
31 ///
32 /// This corresponds to `crate::Document::display_name`.
33 BufferName,
34 /// The absolute path of the currently focused document. For scratch buffers this will default
35 /// to the current working directory.
36 FilePathAbsolute,
37 /// A string containing the line-ending of the currently focused document.
38 LineEnding,
39 /// Curreng working directory
40 CurrentWorkingDirectory,
41 /// Nearest ancestor directory of the current working directory that contains `.git`, `.svn`, `jj` or `.helix`
42 WorkspaceDirectory,
43 // The name of current buffers language as set in `languages.toml`
44 Language,
45 // Primary selection
46 Selection,
47 // The one-indexed line number of the start of the primary selection in the currently focused document.
48 SelectionLineStart,
49 // The one-indexed line number of the end of the primary selection in the currently focused document.
50 SelectionLineEnd,
51 }
52
53 impl Variable {
54 pub const VARIANTS: &'static [Self] = &[
55 Self::CursorLine,
56 Self::CursorColumn,
57 Self::BufferName,
58 Self::FilePathAbsolute,
59 Self::LineEnding,
60 Self::CurrentWorkingDirectory,
61 Self::WorkspaceDirectory,
62 Self::Language,
63 Self::Selection,
64 Self::SelectionLineStart,
65 Self::SelectionLineEnd,
66 ];
67
68 pub const fn as_str(&self) -> &'static str {
69 match self {
70 Self::CursorLine => "cursor_line",
71 Self::CursorColumn => "cursor_column",
72 Self::BufferName => "buffer_name",
73 Self::FilePathAbsolute => "file_path_absolute",
74 Self::LineEnding => "line_ending",
75 Self::CurrentWorkingDirectory => "current_working_directory",
76 Self::WorkspaceDirectory => "workspace_directory",
77 Self::Language => "language",
78 Self::Selection => "selection",
79 Self::SelectionLineStart => "selection_line_start",
80 Self::SelectionLineEnd => "selection_line_end",
81 }
82 }
83
84 pub fn from_name(s: &str) -> Option<Self> {
85 match s {
86 "cursor_line" => Some(Self::CursorLine),
87 "cursor_column" => Some(Self::CursorColumn),
88 "buffer_name" => Some(Self::BufferName),
89 "file_path_absolute" => Some(Self::FilePathAbsolute),
90 "line_ending" => Some(Self::LineEnding),
91 "workspace_directory" => Some(Self::WorkspaceDirectory),
92 "current_working_directory" => Some(Self::CurrentWorkingDirectory),
93 "language" => Some(Self::Language),
94 "selection" => Some(Self::Selection),
95 "selection_line_start" => Some(Self::SelectionLineStart),
96 "selection_line_end" => Some(Self::SelectionLineEnd),
97 _ => None,
98 }
99 }
100 }
101
102 /// Expands the given command line token.
103 ///
104 /// Note that the lifetime of the expanded variable is only bound to the input token and not the
105 /// `Editor`. See `expand_variable` below for more discussion of lifetimes.
106 pub fn expand<'a>(editor: &Editor, token: Token<'a>) -> Result<Cow<'a, str>> {
107 // Note: see the `TokenKind` documentation for more details on how each branch should expand.
108 match token.kind {
109 TokenKind::Unquoted | TokenKind::Quoted(_) => Ok(token.content),
110 TokenKind::Expansion(ExpansionKind::Variable) => {
111 let var = Variable::from_name(&token.content)
112 .ok_or_else(|| anyhow!("unknown variable '{}'", token.content))?;
113
114 expand_variable(editor, var)
115 }
116 TokenKind::Expansion(ExpansionKind::Unicode) => {
117 if let Some(ch) = u32::from_str_radix(token.content.as_ref(), 16)
118 .ok()
119 .and_then(char::from_u32)
120 {
121 Ok(Cow::Owned(ch.to_string()))
122 } else {
123 Err(anyhow!(
124 "could not interpret '{}' as a Unicode character code",
125 token.content
126 ))
127 }
128 }
129 TokenKind::Expand => expand_inner(editor, token.content),
130 TokenKind::Expansion(ExpansionKind::Shell) => expand_shell(editor, token.content),
131 TokenKind::Expansion(ExpansionKind::Register) => expand_register(editor, token.content),
132 // Note: see the docs for this variant.
133 TokenKind::ExpansionKind => unreachable!(
134 "expansion name tokens cannot be emitted when command line validation is enabled"
135 ),
136 }
137 }
138
139 /// Expand a shell command.
140 pub fn expand_shell<'a>(editor: &Editor, content: Cow<'a, str>) -> Result<Cow<'a, str>> {
141 use std::process::{Command, Stdio};
142
143 // Recursively expand the expansion's content before executing the shell command.
144 let content = expand_inner(editor, content)?;
145
146 let config = editor.config();
147 let shell = &config.shell;
148 let mut process = Command::new(&shell[0]);
149 process
150 .args(&shell[1..])
151 .arg(content.as_ref())
152 .stdin(Stdio::null())
153 .stdout(Stdio::piped())
154 .stderr(Stdio::piped());
155
156 // TODO: there is no protection here against a shell command taking a long time.
157 // Ideally you should be able to hit `<ret>` in command mode and then be able to
158 // cancel the invocation (for example with `<C-c>`) if it takes longer than you'd
159 // like.
160 let output = match process.spawn() {
161 Ok(process) => process.wait_with_output()?,
162 Err(err) => {
163 bail!("Failed to start shell: {err}");
164 }
165 };
166
167 let mut text = String::from_utf8_lossy(&output.stdout).into_owned();
168
169 if !output.stderr.is_empty() {
170 log::warn!(
171 "Shell expansion command `{content}` failed: {}",
172 String::from_utf8_lossy(&output.stderr)
173 );
174 }
175
176 // Trim exactly one trailing line ending if it exists.
177 if text.ends_with('\n') {
178 text.pop();
179 if text.ends_with('\r') {
180 text.pop();
181 }
182 }
183
184 Ok(Cow::Owned(text))
185 }
186
187 /// Expand a register's contents
188 pub fn expand_register<'a>(editor: &Editor, content: Cow<'a, str>) -> Result<Cow<'a, str>> {
189 let mut chars = content.chars();
190 let Some(r) = chars.next() else {
191 bail!("Missing register name");
192 };
193 ensure!(
194 chars.next().is_none(),
195 "Invalid register `{content}`: should only be a single character"
196 );
197 match editor.registers.read(r, editor) {
198 Some(values) => Ok(Cow::Owned(values.collect())),
199 None => Ok(Cow::Borrowed("")),
200 }
201 }
202
203 /// Expand a token's contents recursively.
204 fn expand_inner<'a>(editor: &Editor, content: Cow<'a, str>) -> Result<Cow<'a, str>> {
205 let mut escaped = String::new();
206 let mut start = 0;
207
208 while let Some(offset) = content[start..].find('%') {
209 let idx = start + offset;
210 if content.as_bytes().get(idx + '%'.len_utf8()).copied() == Some(b'%') {
211 // Treat two percents in a row as an escaped percent.
212 escaped.push_str(&content[start..=idx]);
213 // Skip over both percents.
214 start = idx + ('%'.len_utf8() * 2);
215 } else {
216 // Otherwise interpret the percent as an expansion. Push up to (but not
217 // including) the percent token.
218 escaped.push_str(&content[start..idx]);
219 // Then parse the expansion,
220 let mut tokenizer = Tokenizer::new(&content[idx..], true);
221 let token = tokenizer
222 .parse_percent_token()
223 .unwrap()
224 .map_err(|err| anyhow!("{err}"))?;
225 // expand it (this is the recursive part),
226 let expanded = expand(editor, token)?;
227 escaped.push_str(expanded.as_ref());
228 // and move forward to the end of the expansion.
229 start = idx + tokenizer.pos();
230 }
231 }
232
233 if escaped.is_empty() {
234 Ok(content)
235 } else {
236 escaped.push_str(&content[start..]);
237 Ok(Cow::Owned(escaped))
238 }
239 }
240
241 // Note: the lifetime of the expanded variable (the `Cow`) must not be tied to the lifetime of
242 // the borrow of `Editor`. That would prevent commands from mutating the `Editor` until the
243 // command consumed or cloned all arguments - this is poor ergonomics. A sensible thing for this
244 // function to return then, instead, would normally be a `String`. We can return some statically
245 // known strings like the scratch buffer name or line ending strings though, so this function
246 // returns a `Cow<'static, str>` instead.
247 fn expand_variable(editor: &Editor, variable: Variable) -> Result<Cow<'static, str>> {
248 let (view, doc) = current_ref!(editor);
249 let text = doc.text().slice(..);
250
251 match variable {
252 Variable::CursorLine => {
253 let cursor_line = doc.selection(view.id).primary().cursor_line(text);
254 Ok(Cow::Owned((cursor_line + 1).to_string()))
255 }
256 Variable::CursorColumn => {
257 let cursor = doc.selection(view.id).primary().cursor(text);
258 let position = helix_core::coords_at_pos(text, cursor);
259 Ok(Cow::Owned((position.col + 1).to_string()))
260 }
261 Variable::BufferName => {
262 // Note: usually we would use `Document::display_name` but we can statically borrow
263 // the scratch buffer name by partially reimplementing `display_name`.
264 if let Some(path) = doc.relative_path() {
265 Ok(Cow::Owned(path.to_string_lossy().into_owned()))
266 } else {
267 Ok(Cow::Borrowed(crate::document::SCRATCH_BUFFER_NAME))
268 }
269 }
270 Variable::FilePathAbsolute => {
271 let path = match doc.path() {
272 Some(path) => path.to_owned(),
273 None => helix_stdx::env::current_working_dir(),
274 }
275 .to_string_lossy()
276 .to_string();
277 Ok(Cow::Owned(path))
278 }
279 Variable::LineEnding => Ok(Cow::Borrowed(doc.line_ending.as_str())),
280 Variable::CurrentWorkingDirectory => Ok(std::borrow::Cow::Owned(
281 helix_stdx::env::current_working_dir()
282 .to_string_lossy()
283 .to_string(),
284 )),
285 Variable::WorkspaceDirectory => Ok(std::borrow::Cow::Owned(
286 helix_loader::find_workspace()
287 .0
288 .to_string_lossy()
289 .to_string(),
290 )),
291 Variable::Language => Ok(match doc.language_name() {
292 Some(lang) => Cow::Owned(lang.to_owned()),
293 None => Cow::Borrowed("text"),
294 }),
295 Variable::Selection => Ok(Cow::Owned(
296 doc.selection(view.id).primary().fragment(text).to_string(),
297 )),
298 Variable::SelectionLineStart => {
299 let start_line = doc.selection(view.id).primary().line_range(text).0;
300 Ok(Cow::Owned((start_line + 1).to_string()))
301 }
302 Variable::SelectionLineEnd => {
303 let end_line = doc.selection(view.id).primary().line_range(text).1;
304 Ok(Cow::Owned((end_line + 1).to_string()))
305 }
306 }
307 }