1#[cfg(feature = "neovim")]
2use std::ops::{Deref, DerefMut};
3use std::{ops::Range, path::PathBuf};
4
5#[cfg(feature = "neovim")]
6use async_compat::Compat;
7#[cfg(feature = "neovim")]
8use async_trait::async_trait;
9#[cfg(feature = "neovim")]
10use gpui::keymap_matcher::Keystroke;
11
12use language::Point;
13
14#[cfg(feature = "neovim")]
15use nvim_rs::{
16 create::tokio::new_child_cmd, error::LoopError, Handler, Neovim, UiAttachOptions, Value,
17};
18#[cfg(feature = "neovim")]
19use parking_lot::ReentrantMutex;
20use serde::{Deserialize, Serialize};
21#[cfg(feature = "neovim")]
22use tokio::{
23 process::{Child, ChildStdin, Command},
24 task::JoinHandle,
25};
26
27use crate::state::Mode;
28use collections::VecDeque;
29
30// Neovim doesn't like to be started simultaneously from multiple threads. We use this lock
31// to ensure we are only constructing one neovim connection at a time.
32#[cfg(feature = "neovim")]
33static NEOVIM_LOCK: ReentrantMutex<()> = ReentrantMutex::new(());
34
35#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
36pub enum NeovimData {
37 Put { state: String },
38 Key(String),
39 Get { state: String, mode: Option<Mode> },
40}
41
42pub struct NeovimConnection {
43 data: VecDeque<NeovimData>,
44 #[cfg(feature = "neovim")]
45 test_case_id: String,
46 #[cfg(feature = "neovim")]
47 nvim: Neovim<nvim_rs::compat::tokio::Compat<ChildStdin>>,
48 #[cfg(feature = "neovim")]
49 _join_handle: JoinHandle<Result<(), Box<LoopError>>>,
50 #[cfg(feature = "neovim")]
51 _child: Child,
52}
53
54impl NeovimConnection {
55 pub async fn new(test_case_id: String) -> Self {
56 #[cfg(feature = "neovim")]
57 let handler = NvimHandler {};
58 #[cfg(feature = "neovim")]
59 let (nvim, join_handle, child) = Compat::new(async {
60 // Ensure we don't create neovim connections in parallel
61 let _lock = NEOVIM_LOCK.lock();
62 let (nvim, join_handle, child) = new_child_cmd(
63 &mut Command::new("nvim").arg("--embed").arg("--clean"),
64 handler,
65 )
66 .await
67 .expect("Could not connect to neovim process");
68
69 nvim.ui_attach(100, 100, &UiAttachOptions::default())
70 .await
71 .expect("Could not attach to ui");
72
73 // Makes system act a little more like zed in terms of indentation
74 nvim.set_option("smartindent", nvim_rs::Value::Boolean(true))
75 .await
76 .expect("Could not set smartindent on startup");
77
78 (nvim, join_handle, child)
79 })
80 .await;
81
82 Self {
83 #[cfg(feature = "neovim")]
84 data: Default::default(),
85 #[cfg(not(feature = "neovim"))]
86 data: Self::read_test_data(&test_case_id),
87 #[cfg(feature = "neovim")]
88 test_case_id,
89 #[cfg(feature = "neovim")]
90 nvim,
91 #[cfg(feature = "neovim")]
92 _join_handle: join_handle,
93 #[cfg(feature = "neovim")]
94 _child: child,
95 }
96 }
97
98 // Sends a keystroke to the neovim process.
99 #[cfg(feature = "neovim")]
100 pub async fn send_keystroke(&mut self, keystroke_text: &str) {
101 let keystroke = Keystroke::parse(keystroke_text).unwrap();
102 let special = keystroke.shift
103 || keystroke.ctrl
104 || keystroke.alt
105 || keystroke.cmd
106 || keystroke.key.len() > 1;
107 let start = if special { "<" } else { "" };
108 let shift = if keystroke.shift { "S-" } else { "" };
109 let ctrl = if keystroke.ctrl { "C-" } else { "" };
110 let alt = if keystroke.alt { "M-" } else { "" };
111 let cmd = if keystroke.cmd { "D-" } else { "" };
112 let end = if special { ">" } else { "" };
113
114 let key = format!("{start}{shift}{ctrl}{alt}{cmd}{}{end}", keystroke.key);
115
116 self.data
117 .push_back(NeovimData::Key(keystroke_text.to_string()));
118 self.nvim
119 .input(&key)
120 .await
121 .expect("Could not input keystroke");
122 }
123
124 #[cfg(not(feature = "neovim"))]
125 pub async fn send_keystroke(&mut self, keystroke_text: &str) {
126 if matches!(self.data.front(), Some(NeovimData::Get { .. })) {
127 self.data.pop_front();
128 }
129 assert_eq!(
130 self.data.pop_front(),
131 Some(NeovimData::Key(keystroke_text.to_string())),
132 "operation does not match recorded script. re-record with --features=neovim"
133 );
134 }
135
136 #[cfg(feature = "neovim")]
137 pub async fn set_state(&mut self, marked_text: &str) {
138 let (text, selection) = parse_state(&marked_text);
139
140 let nvim_buffer = self
141 .nvim
142 .get_current_buf()
143 .await
144 .expect("Could not get neovim buffer");
145 let lines = text
146 .split('\n')
147 .map(|line| line.to_string())
148 .collect::<Vec<_>>();
149
150 nvim_buffer
151 .set_lines(0, -1, false, lines)
152 .await
153 .expect("Could not set nvim buffer text");
154
155 self.nvim
156 .input("<escape>")
157 .await
158 .expect("Could not send escape to nvim");
159 self.nvim
160 .input("<escape>")
161 .await
162 .expect("Could not send escape to nvim");
163
164 let nvim_window = self
165 .nvim
166 .get_current_win()
167 .await
168 .expect("Could not get neovim window");
169
170 if !selection.is_empty() {
171 panic!("Setting neovim state with non empty selection not yet supported");
172 }
173 let cursor = selection.start;
174 nvim_window
175 .set_cursor((cursor.row as i64 + 1, cursor.column as i64))
176 .await
177 .expect("Could not set nvim cursor position");
178
179 if let Some(NeovimData::Get { mode, state }) = self.data.back() {
180 if *mode == Some(Mode::Normal) && *state == marked_text {
181 return;
182 }
183 }
184 self.data.push_back(NeovimData::Put {
185 state: marked_text.to_string(),
186 })
187 }
188
189 #[cfg(not(feature = "neovim"))]
190 pub async fn set_state(&mut self, marked_text: &str) {
191 if let Some(NeovimData::Get { mode, state: text }) = self.data.front() {
192 if *mode == Some(Mode::Normal) && *text == marked_text {
193 return;
194 }
195 self.data.pop_front();
196 }
197 assert_eq!(
198 self.data.pop_front(),
199 Some(NeovimData::Put {
200 state: marked_text.to_string()
201 }),
202 "operation does not match recorded script. re-record with --features=neovim"
203 );
204 }
205
206 #[cfg(feature = "neovim")]
207 pub async fn state(&mut self) -> (Option<Mode>, String, Range<Point>) {
208 let nvim_buffer = self
209 .nvim
210 .get_current_buf()
211 .await
212 .expect("Could not get neovim buffer");
213 let text = nvim_buffer
214 .get_lines(0, -1, false)
215 .await
216 .expect("Could not get buffer text")
217 .join("\n");
218
219 let cursor_row: u32 = self
220 .nvim
221 .command_output("echo line('.')")
222 .await
223 .unwrap()
224 .parse::<u32>()
225 .unwrap()
226 - 1; // Neovim rows start at 1
227 let cursor_col: u32 = self
228 .nvim
229 .command_output("echo col('.')")
230 .await
231 .unwrap()
232 .parse::<u32>()
233 .unwrap()
234 - 1; // Neovim columns start at 1
235
236 let nvim_mode_text = self
237 .nvim
238 .get_mode()
239 .await
240 .expect("Could not get mode")
241 .into_iter()
242 .find_map(|(key, value)| {
243 if key.as_str() == Some("mode") {
244 Some(value.as_str().unwrap().to_owned())
245 } else {
246 None
247 }
248 })
249 .expect("Could not find mode value");
250
251 let mode = match nvim_mode_text.as_ref() {
252 "i" => Some(Mode::Insert),
253 "n" => Some(Mode::Normal),
254 "v" => Some(Mode::Visual { line: false }),
255 "V" => Some(Mode::Visual { line: true }),
256 _ => None,
257 };
258
259 let (start, end) = if let Some(Mode::Visual { .. }) = mode {
260 self.nvim
261 .input("<escape>")
262 .await
263 .expect("Could not exit visual mode");
264 let nvim_buffer = self
265 .nvim
266 .get_current_buf()
267 .await
268 .expect("Could not get neovim buffer");
269 let (start_row, start_col) = nvim_buffer
270 .get_mark("<")
271 .await
272 .expect("Could not get selection start");
273 let (end_row, end_col) = nvim_buffer
274 .get_mark(">")
275 .await
276 .expect("Could not get selection end");
277 self.nvim
278 .input("gv")
279 .await
280 .expect("Could not reselect visual selection");
281
282 if cursor_row == start_row as u32 - 1 && cursor_col == start_col as u32 {
283 (
284 Point::new(end_row as u32 - 1, end_col as u32),
285 Point::new(start_row as u32 - 1, start_col as u32),
286 )
287 } else {
288 (
289 Point::new(start_row as u32 - 1, start_col as u32),
290 Point::new(end_row as u32 - 1, end_col as u32),
291 )
292 }
293 } else {
294 (
295 Point::new(cursor_row, cursor_col),
296 Point::new(cursor_row, cursor_col),
297 )
298 };
299
300 let state = NeovimData::Get {
301 mode,
302 state: encode_range(&text, start..end),
303 };
304
305 if self.data.back() != Some(&state) {
306 self.data.push_back(state.clone());
307 }
308
309 (mode, text, start..end)
310 }
311
312 #[cfg(not(feature = "neovim"))]
313 pub async fn state(&mut self) -> (Option<Mode>, String, Range<Point>) {
314 if let Some(NeovimData::Get { state: text, mode }) = self.data.front() {
315 let (text, range) = parse_state(text);
316 (*mode, text, range)
317 } else {
318 panic!("operation does not match recorded script. re-record with --features=neovim");
319 }
320 }
321
322 pub async fn selection(&mut self) -> Range<Point> {
323 self.state().await.2
324 }
325
326 pub async fn mode(&mut self) -> Option<Mode> {
327 self.state().await.0
328 }
329
330 pub async fn text(&mut self) -> String {
331 self.state().await.1
332 }
333
334 fn test_data_path(test_case_id: &str) -> PathBuf {
335 let mut data_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
336 data_path.push("test_data");
337 data_path.push(format!("{}.json", test_case_id));
338 data_path
339 }
340
341 #[cfg(not(feature = "neovim"))]
342 fn read_test_data(test_case_id: &str) -> VecDeque<NeovimData> {
343 let path = Self::test_data_path(test_case_id);
344 let json = std::fs::read_to_string(path).expect(
345 "Could not read test data. Is it generated? Try running test with '--features neovim'",
346 );
347
348 let mut result = VecDeque::new();
349 for line in json.lines() {
350 result.push_back(
351 serde_json::from_str(line)
352 .expect("invalid test data. regenerate it with '--features neovim'"),
353 );
354 }
355 result
356 }
357
358 #[cfg(feature = "neovim")]
359 fn write_test_data(test_case_id: &str, data: &VecDeque<NeovimData>) {
360 let path = Self::test_data_path(test_case_id);
361 let mut json = Vec::new();
362 for entry in data {
363 serde_json::to_writer(&mut json, entry).unwrap();
364 json.push(b'\n');
365 }
366 std::fs::create_dir_all(path.parent().unwrap())
367 .expect("could not create test data directory");
368 std::fs::write(path, json).expect("could not write out test data");
369 }
370}
371
372#[cfg(feature = "neovim")]
373impl Deref for NeovimConnection {
374 type Target = Neovim<nvim_rs::compat::tokio::Compat<ChildStdin>>;
375
376 fn deref(&self) -> &Self::Target {
377 &self.nvim
378 }
379}
380
381#[cfg(feature = "neovim")]
382impl DerefMut for NeovimConnection {
383 fn deref_mut(&mut self) -> &mut Self::Target {
384 &mut self.nvim
385 }
386}
387
388#[cfg(feature = "neovim")]
389impl Drop for NeovimConnection {
390 fn drop(&mut self) {
391 Self::write_test_data(&self.test_case_id, &self.data);
392 }
393}
394
395#[cfg(feature = "neovim")]
396#[derive(Clone)]
397struct NvimHandler {}
398
399#[cfg(feature = "neovim")]
400#[async_trait]
401impl Handler for NvimHandler {
402 type Writer = nvim_rs::compat::tokio::Compat<ChildStdin>;
403
404 async fn handle_request(
405 &self,
406 _event_name: String,
407 _arguments: Vec<Value>,
408 _neovim: Neovim<Self::Writer>,
409 ) -> Result<Value, Value> {
410 unimplemented!();
411 }
412
413 async fn handle_notify(
414 &self,
415 _event_name: String,
416 _arguments: Vec<Value>,
417 _neovim: Neovim<Self::Writer>,
418 ) {
419 }
420}
421
422fn parse_state(marked_text: &str) -> (String, Range<Point>) {
423 let (text, ranges) = util::test::marked_text_ranges(marked_text, true);
424 let byte_range = ranges[0].clone();
425 let mut point_range = Point::zero()..Point::zero();
426 let mut ix = 0;
427 let mut position = Point::zero();
428 for c in text.chars().chain(['\0']) {
429 if ix == byte_range.start {
430 point_range.start = position;
431 }
432 if ix == byte_range.end {
433 point_range.end = position;
434 }
435 let len_utf8 = c.len_utf8();
436 ix += len_utf8;
437 if c == '\n' {
438 position.row += 1;
439 position.column = 0;
440 } else {
441 position.column += len_utf8 as u32;
442 }
443 }
444 (text, point_range)
445}
446
447#[cfg(feature = "neovim")]
448fn encode_range(text: &str, range: Range<Point>) -> String {
449 let mut byte_range = 0..0;
450 let mut ix = 0;
451 let mut position = Point::zero();
452 for c in text.chars().chain(['\0']) {
453 if position == range.start {
454 byte_range.start = ix;
455 }
456 if position == range.end {
457 byte_range.end = ix;
458 }
459 let len_utf8 = c.len_utf8();
460 ix += len_utf8;
461 if c == '\n' {
462 position.row += 1;
463 position.column = 0;
464 } else {
465 position.column += len_utf8 as u32;
466 }
467 }
468 util::test::generate_marked_text(text, &[byte_range], true)
469}