| 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 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 22 |
pub enum Variable { |
| 23 |
|
| 24 |
CursorLine, |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
CursorColumn, |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
BufferName, |
| 34 |
|
| 35 |
|
| 36 |
FilePathAbsolute, |
| 37 |
|
| 38 |
LineEnding, |
| 39 |
|
| 40 |
CurrentWorkingDirectory, |
| 41 |
|
| 42 |
WorkspaceDirectory, |
| 43 |
|
| 44 |
Language, |
| 45 |
|
| 46 |
Selection, |
| 47 |
|
| 48 |
SelectionLineStart, |
| 49 |
|
| 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 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
pub fn expand<'a>(editor: &Editor, token: Token<'a>) -> Result<Cow<'a, str>> { |
| 107 |
|
| 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 |
|
| 133 |
TokenKind::ExpansionKind => unreachable!( |
| 134 |
"expansion name tokens cannot be emitted when command line validation is enabled" |
| 135 |
), |
| 136 |
} |
| 137 |
} |
| 138 |
|
| 139 |
|
| 140 |
pub fn expand_shell<'a>(editor: &Editor, content: Cow<'a, str>) -> Result<Cow<'a, str>> { |
| 141 |
use std::process::{Command, Stdio}; |
| 142 |
|
| 143 |
|
| 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 |
|
| 157 |
|
| 158 |
|
| 159 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 212 |
escaped.push_str(&content[start..=idx]); |
| 213 |
|
| 214 |
start = idx + ('%'.len_utf8() * 2); |
| 215 |
} else { |
| 216 |
|
| 217 |
|
| 218 |
escaped.push_str(&content[start..idx]); |
| 219 |
|
| 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 |
|
| 226 |
let expanded = expand(editor, token)?; |
| 227 |
escaped.push_str(expanded.as_ref()); |
| 228 |
|
| 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 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 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 |
|
| 263 |
|
| 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 |
} |