neovim_connection.rs

  1use std::path::PathBuf;
  2#[cfg(feature = "neovim")]
  3use std::{
  4    cmp,
  5    ops::{Deref, DerefMut, Range},
  6};
  7
  8#[cfg(feature = "neovim")]
  9use async_compat::Compat;
 10#[cfg(feature = "neovim")]
 11use async_trait::async_trait;
 12#[cfg(feature = "neovim")]
 13use gpui::Keystroke;
 14
 15#[cfg(feature = "neovim")]
 16use language::Point;
 17
 18#[cfg(feature = "neovim")]
 19use nvim_rs::{
 20    Handler, Neovim, UiAttachOptions, Value, create::tokio::new_child_cmd, error::LoopError,
 21};
 22#[cfg(feature = "neovim")]
 23use parking_lot::ReentrantMutex;
 24use serde::{Deserialize, Serialize};
 25#[cfg(feature = "neovim")]
 26use tokio::{
 27    process::{Child, ChildStdin, Command},
 28    task::JoinHandle,
 29};
 30
 31use crate::state::Mode;
 32use collections::VecDeque;
 33
 34// Neovim doesn't like to be started simultaneously from multiple threads. We use this lock
 35// to ensure we are only constructing one neovim connection at a time.
 36#[cfg(feature = "neovim")]
 37static NEOVIM_LOCK: ReentrantMutex<()> = ReentrantMutex::new(());
 38
 39#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
 40pub enum NeovimData {
 41    Put { state: String },
 42    Key(String),
 43    Get { state: String, mode: Mode },
 44    ReadRegister { name: char, value: String },
 45    Exec { command: String },
 46    SetOption { value: String },
 47}
 48
 49pub struct NeovimConnection {
 50    data: VecDeque<NeovimData>,
 51    #[cfg(feature = "neovim")]
 52    test_case_id: String,
 53    #[cfg(feature = "neovim")]
 54    nvim: Neovim<nvim_rs::compat::tokio::Compat<ChildStdin>>,
 55    #[cfg(feature = "neovim")]
 56    _join_handle: JoinHandle<Result<(), Box<LoopError>>>,
 57    #[cfg(feature = "neovim")]
 58    _child: Child,
 59}
 60
 61impl NeovimConnection {
 62    pub async fn new(test_case_id: String) -> Self {
 63        #[cfg(feature = "neovim")]
 64        let handler = NvimHandler {};
 65        #[cfg(feature = "neovim")]
 66        let (nvim, join_handle, child) = Compat::new(async {
 67            // Ensure we don't create neovim connections in parallel
 68            let _lock = NEOVIM_LOCK.lock();
 69            let (nvim, join_handle, child) = new_child_cmd(
 70                Command::new("nvim")
 71                    .arg("--embed")
 72                    .arg("--clean")
 73                    // disable swap (otherwise after about 1000 test runs you run out of swap file names)
 74                    .arg("-n")
 75                    // disable writing files (just in case)
 76                    .arg("-m"),
 77                handler,
 78            )
 79            .await
 80            .expect("Could not connect to neovim process");
 81
 82            nvim.ui_attach(100, 100, &UiAttachOptions::default())
 83                .await
 84                .expect("Could not attach to ui");
 85
 86            // Makes system act a little more like zed in terms of indentation
 87            nvim.set_option("smartindent", nvim_rs::Value::Boolean(true))
 88                .await
 89                .expect("Could not set smartindent on startup");
 90
 91            (nvim, join_handle, child)
 92        })
 93        .await;
 94
 95        Self {
 96            #[cfg(feature = "neovim")]
 97            data: Default::default(),
 98            #[cfg(not(feature = "neovim"))]
 99            data: Self::read_test_data(&test_case_id),
100            #[cfg(feature = "neovim")]
101            test_case_id,
102            #[cfg(feature = "neovim")]
103            nvim,
104            #[cfg(feature = "neovim")]
105            _join_handle: join_handle,
106            #[cfg(feature = "neovim")]
107            _child: child,
108        }
109    }
110
111    // Sends a keystroke to the neovim process.
112    #[cfg(feature = "neovim")]
113    pub async fn send_keystroke(&mut self, keystroke_text: &str) {
114        let mut keystroke = Keystroke::parse(keystroke_text).unwrap();
115
116        if keystroke.key == "<" {
117            keystroke.key = "lt".to_string()
118        }
119
120        let special = keystroke.modifiers.shift
121            || keystroke.modifiers.control
122            || keystroke.modifiers.alt
123            || keystroke.modifiers.platform
124            || keystroke.key.len() > 1;
125        let start = if special { "<" } else { "" };
126        let shift = if keystroke.modifiers.shift { "S-" } else { "" };
127        let ctrl = if keystroke.modifiers.control {
128            "C-"
129        } else {
130            ""
131        };
132        let alt = if keystroke.modifiers.alt { "M-" } else { "" };
133        let cmd = if keystroke.modifiers.platform {
134            "D-"
135        } else {
136            ""
137        };
138        let end = if special { ">" } else { "" };
139
140        let key = format!("{start}{shift}{ctrl}{alt}{cmd}{}{end}", keystroke.key);
141
142        self.data
143            .push_back(NeovimData::Key(keystroke_text.to_string()));
144        self.nvim
145            .input(&key)
146            .await
147            .expect("Could not input keystroke");
148    }
149
150    #[cfg(not(feature = "neovim"))]
151    pub async fn send_keystroke(&mut self, keystroke_text: &str) {
152        if matches!(self.data.front(), Some(NeovimData::Get { .. })) {
153            self.data.pop_front();
154        }
155        assert_eq!(
156            self.data.pop_front(),
157            Some(NeovimData::Key(keystroke_text.to_string())),
158            "operation does not match recorded script. re-record with --features=neovim"
159        );
160    }
161
162    #[cfg(feature = "neovim")]
163    pub async fn set_state(&mut self, marked_text: &str) {
164        let (text, selections) = parse_state(marked_text);
165
166        let nvim_buffer = self
167            .nvim
168            .get_current_buf()
169            .await
170            .expect("Could not get neovim buffer");
171        let lines = text
172            .split('\n')
173            .map(|line| line.to_string())
174            .collect::<Vec<_>>();
175
176        nvim_buffer
177            .set_lines(0, -1, false, lines)
178            .await
179            .expect("Could not set nvim buffer text");
180
181        self.nvim
182            .input("<escape>")
183            .await
184            .expect("Could not send escape to nvim");
185        self.nvim
186            .input("<escape>")
187            .await
188            .expect("Could not send escape to nvim");
189
190        let nvim_window = self
191            .nvim
192            .get_current_win()
193            .await
194            .expect("Could not get neovim window");
195
196        if selections.len() != 1 {
197            panic!("must have one selection");
198        }
199        let selection = &selections[0];
200
201        let cursor = selection.start;
202        nvim_window
203            .set_cursor((cursor.row as i64 + 1, cursor.column as i64))
204            .await
205            .expect("Could not set nvim cursor position");
206
207        if !selection.is_empty() {
208            self.nvim
209                .input("v")
210                .await
211                .expect("could not enter visual mode");
212
213            let cursor = selection.end;
214            nvim_window
215                .set_cursor((cursor.row as i64 + 1, cursor.column as i64))
216                .await
217                .expect("Could not set nvim cursor position");
218        }
219
220        if let Some(NeovimData::Get { mode, state }) = self.data.back()
221            && *mode == Mode::Normal
222            && *state == marked_text
223        {
224            return;
225        }
226        self.data.push_back(NeovimData::Put {
227            state: marked_text.to_string(),
228        })
229    }
230
231    #[cfg(not(feature = "neovim"))]
232    pub async fn set_state(&mut self, marked_text: &str) {
233        if let Some(NeovimData::Get { mode, state: text }) = self.data.front() {
234            if *mode == Mode::Normal && *text == marked_text {
235                return;
236            }
237            self.data.pop_front();
238        }
239        assert_eq!(
240            self.data.pop_front(),
241            Some(NeovimData::Put {
242                state: marked_text.to_string()
243            }),
244            "operation does not match recorded script. re-record with --features=neovim"
245        );
246    }
247
248    #[cfg(feature = "neovim")]
249    pub async fn set_option(&mut self, value: &str) {
250        self.nvim
251            .command_output(format!("set {}", value).as_str())
252            .await
253            .unwrap();
254
255        self.data.push_back(NeovimData::SetOption {
256            value: value.to_string(),
257        })
258    }
259
260    #[cfg(not(feature = "neovim"))]
261    pub async fn set_option(&mut self, value: &str) {
262        if let Some(NeovimData::Get { .. }) = self.data.front() {
263            self.data.pop_front();
264        };
265        assert_eq!(
266            self.data.pop_front(),
267            Some(NeovimData::SetOption {
268                value: value.to_string(),
269            }),
270            "operation does not match recorded script. re-record with --features=neovim"
271        );
272    }
273
274    #[cfg(feature = "neovim")]
275    pub async fn exec(&mut self, value: &str) {
276        self.nvim.command_output(value).await.unwrap();
277
278        self.data.push_back(NeovimData::Exec {
279            command: value.to_string(),
280        })
281    }
282
283    #[cfg(not(feature = "neovim"))]
284    pub async fn exec(&mut self, value: &str) {
285        if let Some(NeovimData::Get { .. }) = self.data.front() {
286            self.data.pop_front();
287        };
288        assert_eq!(
289            self.data.pop_front(),
290            Some(NeovimData::Exec {
291                command: value.to_string(),
292            }),
293            "operation does not match recorded script. re-record with --features=neovim"
294        );
295    }
296
297    #[cfg(not(feature = "neovim"))]
298    pub async fn read_register(&mut self, register: char) -> String {
299        if let Some(NeovimData::Get { .. }) = self.data.front() {
300            self.data.pop_front();
301        };
302        if let Some(NeovimData::ReadRegister { name, value }) = self.data.pop_front()
303            && name == register
304        {
305            return value;
306        }
307
308        panic!("operation does not match recorded script. re-record with --features=neovim")
309    }
310
311    #[cfg(feature = "neovim")]
312    pub async fn read_register(&mut self, name: char) -> String {
313        let value = self
314            .nvim
315            .command_output(format!("echo getreg('{}')", name).as_str())
316            .await
317            .unwrap();
318
319        self.data.push_back(NeovimData::ReadRegister {
320            name,
321            value: value.clone(),
322        });
323
324        value
325    }
326
327    #[cfg(feature = "neovim")]
328    async fn read_position(&mut self, cmd: &str) -> u32 {
329        self.nvim
330            .command_output(cmd)
331            .await
332            .unwrap()
333            .parse::<u32>()
334            .unwrap()
335    }
336
337    #[cfg(feature = "neovim")]
338    pub async fn state(&mut self) -> (Mode, String) {
339        let nvim_buffer = self
340            .nvim
341            .get_current_buf()
342            .await
343            .expect("Could not get neovim buffer");
344        let text = nvim_buffer
345            .get_lines(0, -1, false)
346            .await
347            .expect("Could not get buffer text")
348            .join("\n");
349
350        // nvim columns are 1-based, so -1.
351        let mut cursor_row = self.read_position("echo line('.')").await - 1;
352        let mut cursor_col = self.read_position("echo col('.')").await - 1;
353        let mut selection_row = self.read_position("echo line('v')").await - 1;
354        let mut selection_col = self.read_position("echo col('v')").await - 1;
355        let total_rows = self.read_position("echo line('$')").await - 1;
356
357        let nvim_mode_text = self
358            .nvim
359            .get_mode()
360            .await
361            .expect("Could not get mode")
362            .into_iter()
363            .find_map(|(key, value)| {
364                if key.as_str() == Some("mode") {
365                    Some(value.as_str().unwrap().to_owned())
366                } else {
367                    None
368                }
369            })
370            .expect("Could not find mode value");
371
372        let mode = match nvim_mode_text.as_ref() {
373            "i" => Mode::Insert,
374            "n" => Mode::Normal,
375            "v" => Mode::Visual,
376            "V" => Mode::VisualLine,
377            "R" => Mode::Replace,
378            "\x16" => Mode::VisualBlock,
379            _ => panic!("unexpected vim mode: {nvim_mode_text}"),
380        };
381
382        let mut selections = Vec::new();
383        // Vim uses the index of the first and last character in the selection
384        // Zed uses the index of the positions between the characters, so we need
385        // to add one to the end in visual mode.
386        match mode {
387            Mode::VisualBlock if selection_row != cursor_row => {
388                // in zed we fake a block selection by using multiple cursors (one per line)
389                // this code emulates that.
390                // to deal with casees where the selection is not perfectly rectangular we extract
391                // the content of the selection via the "a register to get the shape correctly.
392                self.nvim.input("\"aygv").await.unwrap();
393                let content = self.nvim.command_output("echo getreg('a')").await.unwrap();
394                let lines = content.split('\n').collect::<Vec<_>>();
395                let top = cmp::min(selection_row, cursor_row);
396                let left = cmp::min(selection_col, cursor_col);
397                for row in top..=cmp::max(selection_row, cursor_row) {
398                    let content = if row - top >= lines.len() as u32 {
399                        ""
400                    } else {
401                        lines[(row - top) as usize]
402                    };
403                    let line_len = self
404                        .read_position(format!("echo strlen(getline({}))", row + 1).as_str())
405                        .await;
406
407                    if left > line_len {
408                        continue;
409                    }
410
411                    let start = Point::new(row, left);
412                    let end = Point::new(row, left + content.len() as u32);
413                    if cursor_col >= selection_col {
414                        selections.push(start..end)
415                    } else {
416                        selections.push(end..start)
417                    }
418                }
419            }
420            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
421                if (selection_row, selection_col) > (cursor_row, cursor_col) {
422                    let selection_line_length =
423                        self.read_position("echo strlen(getline(line('v')))").await;
424                    if selection_line_length > selection_col {
425                        selection_col += 1;
426                    } else if selection_row < total_rows {
427                        selection_col = 0;
428                        selection_row += 1;
429                    }
430                } else {
431                    let cursor_line_length =
432                        self.read_position("echo strlen(getline(line('.')))").await;
433                    if cursor_line_length > cursor_col {
434                        cursor_col += 1;
435                    } else if cursor_row < total_rows {
436                        cursor_col = 0;
437                        cursor_row += 1;
438                    }
439                }
440                selections.push(
441                    Point::new(selection_row, selection_col)..Point::new(cursor_row, cursor_col),
442                )
443            }
444            Mode::Insert | Mode::Normal | Mode::Replace => selections
445                .push(Point::new(selection_row, selection_col)..Point::new(cursor_row, cursor_col)),
446            Mode::HelixNormal | Mode::HelixSelect => unreachable!(),
447        }
448
449        let ranges = encode_ranges(&text, &selections);
450        let state = NeovimData::Get {
451            mode,
452            state: ranges.clone(),
453        };
454
455        if self.data.back() != Some(&state) {
456            self.data.push_back(state);
457        }
458
459        (mode, ranges)
460    }
461
462    #[cfg(not(feature = "neovim"))]
463    pub async fn state(&mut self) -> (Mode, String) {
464        if let Some(NeovimData::Get { state: raw, mode }) = self.data.front() {
465            (*mode, raw.to_string())
466        } else {
467            panic!("operation does not match recorded script. re-record with --features=neovim");
468        }
469    }
470
471    fn test_data_path(test_case_id: &str) -> PathBuf {
472        let mut data_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
473        data_path.push("test_data");
474        data_path.push(format!("{}.json", test_case_id));
475        data_path
476    }
477
478    #[cfg(not(feature = "neovim"))]
479    fn read_test_data(test_case_id: &str) -> VecDeque<NeovimData> {
480        let path = Self::test_data_path(test_case_id);
481        let json = std::fs::read_to_string(path).expect(
482            "Could not read test data. Is it generated? Try running test with '--features neovim'",
483        );
484
485        let mut result = VecDeque::new();
486        for line in json.lines() {
487            result.push_back(
488                serde_json::from_str(line)
489                    .expect("invalid test data. regenerate it with '--features neovim'"),
490            );
491        }
492        result
493    }
494
495    #[cfg(feature = "neovim")]
496    fn write_test_data(test_case_id: &str, data: &VecDeque<NeovimData>) {
497        let path = Self::test_data_path(test_case_id);
498        let mut json = Vec::new();
499        for entry in data {
500            serde_json::to_writer(&mut json, entry).unwrap();
501            json.push(b'\n');
502        }
503        std::fs::create_dir_all(path.parent().unwrap())
504            .expect("could not create test data directory");
505        std::fs::write(path, json).expect("could not write out test data");
506    }
507}
508
509#[cfg(feature = "neovim")]
510impl Deref for NeovimConnection {
511    type Target = Neovim<nvim_rs::compat::tokio::Compat<ChildStdin>>;
512
513    fn deref(&self) -> &Self::Target {
514        &self.nvim
515    }
516}
517
518#[cfg(feature = "neovim")]
519impl DerefMut for NeovimConnection {
520    fn deref_mut(&mut self) -> &mut Self::Target {
521        &mut self.nvim
522    }
523}
524
525#[cfg(feature = "neovim")]
526impl Drop for NeovimConnection {
527    fn drop(&mut self) {
528        Self::write_test_data(&self.test_case_id, &self.data);
529    }
530}
531
532#[cfg(feature = "neovim")]
533#[derive(Clone)]
534struct NvimHandler {}
535
536#[cfg(feature = "neovim")]
537#[async_trait]
538impl Handler for NvimHandler {
539    type Writer = nvim_rs::compat::tokio::Compat<ChildStdin>;
540
541    async fn handle_request(
542        &self,
543        _event_name: String,
544        _arguments: Vec<Value>,
545        _neovim: Neovim<Self::Writer>,
546    ) -> Result<Value, Value> {
547        unimplemented!();
548    }
549
550    async fn handle_notify(
551        &self,
552        _event_name: String,
553        _arguments: Vec<Value>,
554        _neovim: Neovim<Self::Writer>,
555    ) {
556    }
557}
558
559#[cfg(feature = "neovim")]
560fn parse_state(marked_text: &str) -> (String, Vec<Range<Point>>) {
561    let (text, ranges) = util::test::marked_text_ranges(marked_text, true);
562    let point_ranges = ranges
563        .into_iter()
564        .map(|byte_range| {
565            let mut point_range = Point::zero()..Point::zero();
566            let mut ix = 0;
567            let mut position = Point::zero();
568            for c in text.chars().chain(['\0']) {
569                if ix == byte_range.start {
570                    point_range.start = position;
571                }
572                if ix == byte_range.end {
573                    point_range.end = position;
574                }
575                let len_utf8 = c.len_utf8();
576                ix += len_utf8;
577                if c == '\n' {
578                    position.row += 1;
579                    position.column = 0;
580                } else {
581                    position.column += len_utf8 as u32;
582                }
583            }
584            point_range
585        })
586        .collect::<Vec<_>>();
587    (text, point_ranges)
588}
589
590#[cfg(feature = "neovim")]
591fn encode_ranges(text: &str, point_ranges: &Vec<Range<Point>>) -> String {
592    let byte_ranges = point_ranges
593        .iter()
594        .map(|range| {
595            let mut byte_range = 0..0;
596            let mut ix = 0;
597            let mut position = Point::zero();
598            for c in text.chars().chain(['\0']) {
599                if position == range.start {
600                    byte_range.start = ix;
601                }
602                if position == range.end {
603                    byte_range.end = ix;
604                }
605                let len_utf8 = c.len_utf8();
606                ix += len_utf8;
607                if c == '\n' {
608                    position.row += 1;
609                    position.column = 0;
610                } else {
611                    position.column += len_utf8 as u32;
612                }
613            }
614            byte_range
615        })
616        .collect::<Vec<_>>();
617    util::test::generate_marked_text(text, &byte_ranges[..], true)
618}