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 && *state == marked_text {
222                return;
223            }
224        self.data.push_back(NeovimData::Put {
225            state: marked_text.to_string(),
226        })
227    }
228
229    #[cfg(not(feature = "neovim"))]
230    pub async fn set_state(&mut self, marked_text: &str) {
231        if let Some(NeovimData::Get { mode, state: text }) = self.data.front() {
232            if *mode == Mode::Normal && *text == marked_text {
233                return;
234            }
235            self.data.pop_front();
236        }
237        assert_eq!(
238            self.data.pop_front(),
239            Some(NeovimData::Put {
240                state: marked_text.to_string()
241            }),
242            "operation does not match recorded script. re-record with --features=neovim"
243        );
244    }
245
246    #[cfg(feature = "neovim")]
247    pub async fn set_option(&mut self, value: &str) {
248        self.nvim
249            .command_output(format!("set {}", value).as_str())
250            .await
251            .unwrap();
252
253        self.data.push_back(NeovimData::SetOption {
254            value: value.to_string(),
255        })
256    }
257
258    #[cfg(not(feature = "neovim"))]
259    pub async fn set_option(&mut self, value: &str) {
260        if let Some(NeovimData::Get { .. }) = self.data.front() {
261            self.data.pop_front();
262        };
263        assert_eq!(
264            self.data.pop_front(),
265            Some(NeovimData::SetOption {
266                value: value.to_string(),
267            }),
268            "operation does not match recorded script. re-record with --features=neovim"
269        );
270    }
271
272    #[cfg(feature = "neovim")]
273    pub async fn exec(&mut self, value: &str) {
274        self.nvim.command_output(value).await.unwrap();
275
276        self.data.push_back(NeovimData::Exec {
277            command: value.to_string(),
278        })
279    }
280
281    #[cfg(not(feature = "neovim"))]
282    pub async fn exec(&mut self, value: &str) {
283        if let Some(NeovimData::Get { .. }) = self.data.front() {
284            self.data.pop_front();
285        };
286        assert_eq!(
287            self.data.pop_front(),
288            Some(NeovimData::Exec {
289                command: value.to_string(),
290            }),
291            "operation does not match recorded script. re-record with --features=neovim"
292        );
293    }
294
295    #[cfg(not(feature = "neovim"))]
296    pub async fn read_register(&mut self, register: char) -> String {
297        if let Some(NeovimData::Get { .. }) = self.data.front() {
298            self.data.pop_front();
299        };
300        if let Some(NeovimData::ReadRegister { name, value }) = self.data.pop_front() {
301            if name == register {
302                return value;
303            }
304        }
305
306        panic!("operation does not match recorded script. re-record with --features=neovim")
307    }
308
309    #[cfg(feature = "neovim")]
310    pub async fn read_register(&mut self, name: char) -> String {
311        let value = self
312            .nvim
313            .command_output(format!("echo getreg('{}')", name).as_str())
314            .await
315            .unwrap();
316
317        self.data.push_back(NeovimData::ReadRegister {
318            name,
319            value: value.clone(),
320        });
321
322        value
323    }
324
325    #[cfg(feature = "neovim")]
326    async fn read_position(&mut self, cmd: &str) -> u32 {
327        self.nvim
328            .command_output(cmd)
329            .await
330            .unwrap()
331            .parse::<u32>()
332            .unwrap()
333    }
334
335    #[cfg(feature = "neovim")]
336    pub async fn state(&mut self) -> (Mode, String) {
337        let nvim_buffer = self
338            .nvim
339            .get_current_buf()
340            .await
341            .expect("Could not get neovim buffer");
342        let text = nvim_buffer
343            .get_lines(0, -1, false)
344            .await
345            .expect("Could not get buffer text")
346            .join("\n");
347
348        // nvim columns are 1-based, so -1.
349        let mut cursor_row = self.read_position("echo line('.')").await - 1;
350        let mut cursor_col = self.read_position("echo col('.')").await - 1;
351        let mut selection_row = self.read_position("echo line('v')").await - 1;
352        let mut selection_col = self.read_position("echo col('v')").await - 1;
353        let total_rows = self.read_position("echo line('$')").await - 1;
354
355        let nvim_mode_text = self
356            .nvim
357            .get_mode()
358            .await
359            .expect("Could not get mode")
360            .into_iter()
361            .find_map(|(key, value)| {
362                if key.as_str() == Some("mode") {
363                    Some(value.as_str().unwrap().to_owned())
364                } else {
365                    None
366                }
367            })
368            .expect("Could not find mode value");
369
370        let mode = match nvim_mode_text.as_ref() {
371            "i" => Mode::Insert,
372            "n" => Mode::Normal,
373            "v" => Mode::Visual,
374            "V" => Mode::VisualLine,
375            "R" => Mode::Replace,
376            "\x16" => Mode::VisualBlock,
377            _ => panic!("unexpected vim mode: {nvim_mode_text}"),
378        };
379
380        let mut selections = Vec::new();
381        // Vim uses the index of the first and last character in the selection
382        // Zed uses the index of the positions between the characters, so we need
383        // to add one to the end in visual mode.
384        match mode {
385            Mode::VisualBlock if selection_row != cursor_row => {
386                // in zed we fake a block selection by using multiple cursors (one per line)
387                // this code emulates that.
388                // to deal with casees where the selection is not perfectly rectangular we extract
389                // the content of the selection via the "a register to get the shape correctly.
390                self.nvim.input("\"aygv").await.unwrap();
391                let content = self.nvim.command_output("echo getreg('a')").await.unwrap();
392                let lines = content.split('\n').collect::<Vec<_>>();
393                let top = cmp::min(selection_row, cursor_row);
394                let left = cmp::min(selection_col, cursor_col);
395                for row in top..=cmp::max(selection_row, cursor_row) {
396                    let content = if row - top >= lines.len() as u32 {
397                        ""
398                    } else {
399                        lines[(row - top) as usize]
400                    };
401                    let line_len = self
402                        .read_position(format!("echo strlen(getline({}))", row + 1).as_str())
403                        .await;
404
405                    if left > line_len {
406                        continue;
407                    }
408
409                    let start = Point::new(row, left);
410                    let end = Point::new(row, left + content.len() as u32);
411                    if cursor_col >= selection_col {
412                        selections.push(start..end)
413                    } else {
414                        selections.push(end..start)
415                    }
416                }
417            }
418            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
419                if (selection_row, selection_col) > (cursor_row, cursor_col) {
420                    let selection_line_length =
421                        self.read_position("echo strlen(getline(line('v')))").await;
422                    if selection_line_length > selection_col {
423                        selection_col += 1;
424                    } else if selection_row < total_rows {
425                        selection_col = 0;
426                        selection_row += 1;
427                    }
428                } else {
429                    let cursor_line_length =
430                        self.read_position("echo strlen(getline(line('.')))").await;
431                    if cursor_line_length > cursor_col {
432                        cursor_col += 1;
433                    } else if cursor_row < total_rows {
434                        cursor_col = 0;
435                        cursor_row += 1;
436                    }
437                }
438                selections.push(
439                    Point::new(selection_row, selection_col)..Point::new(cursor_row, cursor_col),
440                )
441            }
442            Mode::Insert | Mode::Normal | Mode::Replace => selections
443                .push(Point::new(selection_row, selection_col)..Point::new(cursor_row, cursor_col)),
444            Mode::HelixNormal => unreachable!(),
445        }
446
447        let ranges = encode_ranges(&text, &selections);
448        let state = NeovimData::Get {
449            mode,
450            state: ranges.clone(),
451        };
452
453        if self.data.back() != Some(&state) {
454            self.data.push_back(state.clone());
455        }
456
457        (mode, ranges)
458    }
459
460    #[cfg(not(feature = "neovim"))]
461    pub async fn state(&mut self) -> (Mode, String) {
462        if let Some(NeovimData::Get { state: raw, mode }) = self.data.front() {
463            (*mode, raw.to_string())
464        } else {
465            panic!("operation does not match recorded script. re-record with --features=neovim");
466        }
467    }
468
469    fn test_data_path(test_case_id: &str) -> PathBuf {
470        let mut data_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
471        data_path.push("test_data");
472        data_path.push(format!("{}.json", test_case_id));
473        data_path
474    }
475
476    #[cfg(not(feature = "neovim"))]
477    fn read_test_data(test_case_id: &str) -> VecDeque<NeovimData> {
478        let path = Self::test_data_path(test_case_id);
479        let json = std::fs::read_to_string(path).expect(
480            "Could not read test data. Is it generated? Try running test with '--features neovim'",
481        );
482
483        let mut result = VecDeque::new();
484        for line in json.lines() {
485            result.push_back(
486                serde_json::from_str(line)
487                    .expect("invalid test data. regenerate it with '--features neovim'"),
488            );
489        }
490        result
491    }
492
493    #[cfg(feature = "neovim")]
494    fn write_test_data(test_case_id: &str, data: &VecDeque<NeovimData>) {
495        let path = Self::test_data_path(test_case_id);
496        let mut json = Vec::new();
497        for entry in data {
498            serde_json::to_writer(&mut json, entry).unwrap();
499            json.push(b'\n');
500        }
501        std::fs::create_dir_all(path.parent().unwrap())
502            .expect("could not create test data directory");
503        std::fs::write(path, json).expect("could not write out test data");
504    }
505}
506
507#[cfg(feature = "neovim")]
508impl Deref for NeovimConnection {
509    type Target = Neovim<nvim_rs::compat::tokio::Compat<ChildStdin>>;
510
511    fn deref(&self) -> &Self::Target {
512        &self.nvim
513    }
514}
515
516#[cfg(feature = "neovim")]
517impl DerefMut for NeovimConnection {
518    fn deref_mut(&mut self) -> &mut Self::Target {
519        &mut self.nvim
520    }
521}
522
523#[cfg(feature = "neovim")]
524impl Drop for NeovimConnection {
525    fn drop(&mut self) {
526        Self::write_test_data(&self.test_case_id, &self.data);
527    }
528}
529
530#[cfg(feature = "neovim")]
531#[derive(Clone)]
532struct NvimHandler {}
533
534#[cfg(feature = "neovim")]
535#[async_trait]
536impl Handler for NvimHandler {
537    type Writer = nvim_rs::compat::tokio::Compat<ChildStdin>;
538
539    async fn handle_request(
540        &self,
541        _event_name: String,
542        _arguments: Vec<Value>,
543        _neovim: Neovim<Self::Writer>,
544    ) -> Result<Value, Value> {
545        unimplemented!();
546    }
547
548    async fn handle_notify(
549        &self,
550        _event_name: String,
551        _arguments: Vec<Value>,
552        _neovim: Neovim<Self::Writer>,
553    ) {
554    }
555}
556
557#[cfg(feature = "neovim")]
558fn parse_state(marked_text: &str) -> (String, Vec<Range<Point>>) {
559    let (text, ranges) = util::test::marked_text_ranges(marked_text, true);
560    let point_ranges = ranges
561        .into_iter()
562        .map(|byte_range| {
563            let mut point_range = Point::zero()..Point::zero();
564            let mut ix = 0;
565            let mut position = Point::zero();
566            for c in text.chars().chain(['\0']) {
567                if ix == byte_range.start {
568                    point_range.start = position;
569                }
570                if ix == byte_range.end {
571                    point_range.end = position;
572                }
573                let len_utf8 = c.len_utf8();
574                ix += len_utf8;
575                if c == '\n' {
576                    position.row += 1;
577                    position.column = 0;
578                } else {
579                    position.column += len_utf8 as u32;
580                }
581            }
582            point_range
583        })
584        .collect::<Vec<_>>();
585    (text, point_ranges)
586}
587
588#[cfg(feature = "neovim")]
589fn encode_ranges(text: &str, point_ranges: &Vec<Range<Point>>) -> String {
590    let byte_ranges = point_ranges
591        .into_iter()
592        .map(|range| {
593            let mut byte_range = 0..0;
594            let mut ix = 0;
595            let mut position = Point::zero();
596            for c in text.chars().chain(['\0']) {
597                if position == range.start {
598                    byte_range.start = ix;
599                }
600                if position == range.end {
601                    byte_range.end = ix;
602                }
603                let len_utf8 = c.len_utf8();
604                ix += len_utf8;
605                if c == '\n' {
606                    position.row += 1;
607                    position.column = 0;
608                } else {
609                    position.column += len_utf8 as u32;
610                }
611            }
612            byte_range
613        })
614        .collect::<Vec<_>>();
615    util::test::generate_marked_text(text, &byte_ranges[..], true)
616}