on master help sign in
Merge branch 'master' into great_line_ending_and_cursor_range_cleanup
commite462f32723bb61899a390f438d7d856d87fb7614 authorNathan Vegdahl <cessen@cessen.com> dateSun 18 Jul 2021, 22:02 (5 years ago) parent6c038bb5292fe0
11 files changed+114−44
helix-core/src/comment.rs+5−5 helix-core/src/diff.rs+27−29 helix-core/src/indent.rs+2 helix-core/src/syntax.rs+2 helix-core/src/transaction.rs+4−2 helix-lsp/src/client.rs+8−1 helix-lsp/src/lib.rs+6−1 helix-term/src/commands.rs+5−1 helix-term/src/ui/menu.rs+31−3 helix-tui/src/widgets/table.rs+2−2 languages.toml+22
helix-core/src/comment.rs+5−5
@@ -38,18 +38,18 @@ fn find_line_comment(
3838}
3939
4040#[must_use]
41−pub fn toggle_line_comments(doc: &Rope, selection: &Selection) -> Transaction {
41+pub fn toggle_line_comments(doc: &Rope, selection: &Selection, token: Option<&str>) -> Transaction {
4242 let text = doc.slice(..);
4343 let mut changes: Vec<Change> = Vec::new();
4444
45− let token = "//";
45+ let token = token.unwrap_or("//");
4646 let comment = Tendril::from(format!("{} ", token));
4747
4848 for selection in selection {
4949 let start = text.char_to_line(selection.from());
5050 let end = text.char_to_line(selection.to());
5151 let lines = start..end + 1;
52− let (commented, skipped, min) = find_line_comment(token, text, lines.clone());
52+ let (commented, skipped, min) = find_line_comment(&token, text, lines.clone());
5353
5454 changes.reserve((end - start).saturating_sub(skipped.len()));
5555
@@ -95,14 +95,14 @@ mod test {
9595 assert_eq!(res, (false, vec![1], 2));
9696
9797 // comment
98− let transaction = toggle_line_comments(&state.doc, &state.selection);
98+ let transaction = toggle_line_comments(&state.doc, &state.selection, None);
9999 transaction.apply(&mut state.doc);
100100 state.selection = state.selection.clone().map(transaction.changes());
101101
102102 assert_eq!(state.doc, " // 1\n\n // 2\n // 3");
103103
104104 // uncomment
105− let transaction = toggle_line_comments(&state.doc, &state.selection);
105+ let transaction = toggle_line_comments(&state.doc, &state.selection, None);
106106 transaction.apply(&mut state.doc);
107107 state.selection = state.selection.clone().map(transaction.changes());
108108 assert_eq!(state.doc, " 1\n\n 2\n 3");
helix-core/src/diff.rs+27−29
@@ -1,6 +1,4 @@
1−use ropey::Rope;
2−
3−use crate::{Change, Transaction};
1+use crate::{Rope, Transaction};
42
53/// Compares `old` and `new` to generate a [`Transaction`] describing
64/// the steps required to get from `old` to `new`.
@@ -25,34 +23,34 @@ pub fn compare_ropes(old: &Rope, new: &Rope) -> Transaction {
2523 // The current position of the change needs to be tracked to
2624 // construct the `Change`s.
2725 let mut pos = 0;
28− let changes: Vec<Change> = diff
29− .ops()
30− .iter()
31− .map(|op| op.as_tag_tuple())
32− .filter_map(|(tag, old_range, new_range)| {
33− // `old_pos..pos` is equivalent to `start..end` for where
34− // the change should be applied.
35− let old_pos = pos;
36− pos += old_range.end - old_range.start;
26+ Transaction::change(
27+ old,
28+ diff.ops()
29+ .iter()
30+ .map(|op| op.as_tag_tuple())
31+ .filter_map(|(tag, old_range, new_range)| {
32+ // `old_pos..pos` is equivalent to `start..end` for where
33+ // the change should be applied.
34+ let old_pos = pos;
35+ pos += old_range.end - old_range.start;
3736
38− match tag {
39− // Semantically, inserts and replacements are the same thing.
40− similar::DiffTag::Insert | similar::DiffTag::Replace => {
41− // This is the text from the `new` rope that should be
42− // inserted into `old`.
43− let text: &str = {
44− let start = new.char_to_byte(new_range.start);
45− let end = new.char_to_byte(new_range.end);
46− &new_converted[start..end]
47− };
48− Some((old_pos, pos, Some(text.into())))
37+ match tag {
38+ // Semantically, inserts and replacements are the same thing.
39+ similar::DiffTag::Insert | similar::DiffTag::Replace => {
40+ // This is the text from the `new` rope that should be
41+ // inserted into `old`.
42+ let text: &str = {
43+ let start = new.char_to_byte(new_range.start);
44+ let end = new.char_to_byte(new_range.end);
45+ &new_converted[start..end]
46+ };
47+ Some((old_pos, pos, Some(text.into())))
48+ }
49+ similar::DiffTag::Delete => Some((old_pos, pos, None)),
50+ similar::DiffTag::Equal => None,
4951 }
50− similar::DiffTag::Delete => Some((old_pos, pos, None)),
51− similar::DiffTag::Equal => None,
52− }
53− })
54− .collect();
55− Transaction::change(old, changes.into_iter())
52+ }),
53+ )
5654}
5755
5856#[cfg(test)]
helix-core/src/indent.rs+2
@@ -262,8 +262,10 @@ where
262262 file_types: vec!["rs".to_string()],
263263 language_id: "Rust".to_string(),
264264 highlight_config: OnceCell::new(),
265+ config: None,
265266 //
266267 roots: vec![],
268+ comment_token: None,
267269 auto_format: false,
268270 language_server: None,
269271 indent: Some(IndentationConfiguration {
helix-core/src/syntax.rs+2
@@ -35,6 +35,8 @@ pub struct LanguageConfiguration {
3535 pub scope: String, // source.rust
3636 pub file_types: Vec<String>, // filename ends_with? <Gemfile, rb, etc>
3737 pub roots: Vec<String>, // these indicate project roots <.git, Cargo.toml>
38+ pub comment_token: Option<String>,
39+ pub config: Option<String>,
3840
3941 #[serde(default)]
4042 pub auto_format: bool,
helix-core/src/transaction.rs+4−2
@@ -473,11 +473,13 @@ impl Transaction {
473473 /// Generate a transaction from a set of changes.
474474 pub fn change<I>(doc: &Rope, changes: I) -> Self
475475 where
476− I: IntoIterator<Item = Change> + ExactSizeIterator,
476+ I: IntoIterator<Item = Change> + Iterator,
477477 {
478478 let len = doc.len_chars();
479479
480− let mut changeset = ChangeSet::with_capacity(2 * changes.len() + 1); // rough estimate
480+ let (lower, upper) = changes.size_hint();
481+ let size = upper.unwrap_or(lower);
482+ let mut changeset = ChangeSet::with_capacity(2 * size + 1); // rough estimate
481483
482484 // TODO: verify ranges are ordered and not overlapping or change will panic.
483485
helix-lsp/src/client.rs+8−1
@@ -24,12 +24,14 @@ pub struct Client {
2424 request_counter: AtomicU64,
2525 capabilities: Option<lsp::ServerCapabilities>,
2626 offset_encoding: OffsetEncoding,
27+ config: Option<Value>,
2728}
2829
2930impl Client {
3031 pub fn start(
3132 cmd: &str,
3233 args: &[String],
34+ config: Option<Value>,
3335 id: usize,
3436 ) -> Result<(Self, UnboundedReceiver<(usize, Call)>)> {
3537 let process = Command::new(cmd)
@@ -57,6 +59,7 @@ impl Client {
5759 request_counter: AtomicU64::new(0),
5860 capabilities: None,
5961 offset_encoding: OffsetEncoding::Utf8,
62+ config,
6063 };
6164
6265 // TODO: async client.initialize()
@@ -214,13 +217,17 @@ impl Client {
214217 // TODO: delay any requests that are triggered prior to initialize
215218 let root = find_root(None).and_then(|root| lsp::Url::from_file_path(root).ok());
216219
220+ if self.config.is_some() {
221+ log::info!("Using custom LSP config: {}", self.config.as_ref().unwrap());
222+ }
223+
217224 #[allow(deprecated)]
218225 let params = lsp::InitializeParams {
219226 process_id: Some(std::process::id()),
220227 // root_path is obsolete, use root_uri
221228 root_path: None,
222229 root_uri: root,
223− initialization_options: None,
230+ initialization_options: self.config.clone(),
224231 capabilities: lsp::ClientCapabilities {
225232 text_document: Some(lsp::TextDocumentClientCapabilities {
226233 completion: Some(lsp::CompletionClientCapabilities {
helix-lsp/src/lib.rs+6−1
@@ -312,7 +312,12 @@ impl Registry {
312312 Entry::Vacant(entry) => {
313313 // initialize a new client
314314 let id = self.counter.fetch_add(1, Ordering::Relaxed);
315− let (mut client, incoming) = Client::start(&config.command, &config.args, id)?;
315+ let (mut client, incoming) = Client::start(
316+ &config.command,
317+ &config.args,
318+ serde_json::from_str(language_config.config.as_deref().unwrap_or("")).ok(),
319+ id,
320+ )?;
316321 // TODO: run this async without blocking
317322 futures_executor::block_on(client.initialize())?;
318323 s_incoming.push(UnboundedReceiverStream::new(incoming));
helix-term/src/commands.rs+5−1
@@ -3499,7 +3499,11 @@ fn hover(cx: &mut Context) {
34993499// comments
35003500fn toggle_comments(cx: &mut Context) {
35013501 let (view, doc) = current!(cx.editor);
3502− let transaction = comment::toggle_line_comments(doc.text(), doc.selection(view.id));
3502+ let token = doc
3503+ .language_config()
3504+ .and_then(|lc| lc.comment_token.as_ref())
3505+ .map(|tc| tc.as_ref());
3506+ let transaction = comment::toggle_line_comments(doc.text(), doc.selection(view.id), token);
35033507
35043508 doc.apply(&transaction, view.id);
35053509 doc.append_changes_to_history(view.id);
helix-term/src/ui/menu.rs+31−3
@@ -8,6 +8,7 @@ use fuzzy_matcher::skim::SkimMatcherV2 as Matcher;
88use fuzzy_matcher::FuzzyMatcher;
99
1010use helix_view::{graphics::Rect, Editor};
11+use tui::layout::Constraint;
1112
1213pub trait Item {
1314 // TODO: sort_text
@@ -26,6 +27,8 @@ pub struct Menu<T: Item> {
2627 /// (index, score)
2728 matches: Vec<(usize, i64)>,
2829
30+ widths: Vec<Constraint>,
31+
2932 callback_fn: Box<dyn Fn(&mut Editor, Option<&T>, MenuEvent)>,
3033
3134 scroll: usize,
@@ -44,6 +47,7 @@ impl<T: Item> Menu<T> {
4447 matcher: Box::new(Matcher::default()),
4548 matches: Vec::new(),
4649 cursor: None,
50+ widths: Vec::new(),
4751 callback_fn: Box::new(callback_fn),
4852 scroll: 0,
4953 size: (0, 0),
@@ -218,8 +222,33 @@ impl<T: Item + 'static> Component for Menu<T> {
218222 EventResult::Ignored
219223 }
220224
225+ // TODO: completion sorting
226+
221227 fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> {
222− let width = std::cmp::min(30, viewport.0);
228+ let n = self
229+ .options
230+ .first()
231+ .map(|option| option.row().cells.len())
232+ .unwrap_or_default();
233+ let max_lens = self.options.iter().fold(vec![0; n], |mut acc, option| {
234+ let row = option.row();
235+ // maintain max for each column
236+ for (i, cell) in row.cells.iter().enumerate() {
237+ let width = cell.content.width();
238+ if width > acc[i] {
239+ acc[i] = width;
240+ }
241+ }
242+
243+ acc
244+ });
245+ let len = (max_lens.iter().sum::<usize>()) + n + 1; // +1: reserve some space for scrollbar
246+ let width = len.min(viewport.0 as usize);
247+
248+ self.widths = max_lens
249+ .into_iter()
250+ .map(|len| Constraint::Length(len as u16))
251+ .collect();
223252
224253 const MAX: usize = 10;
225254 let height = std::cmp::min(self.options.len(), MAX);
@@ -263,13 +292,12 @@ impl<T: Item + 'static> Component for Menu<T> {
263292 let scroll_line = (win_height - scroll_height) * scroll
264293 / std::cmp::max(1, len.saturating_sub(win_height));
265294
266− use tui::layout::Constraint;
267295 let rows = options.iter().map(|option| option.row());
268296 let table = Table::new(rows)
269297 .style(style)
270298 .highlight_style(selected)
271299 .column_spacing(1)
272− .widths(&[Constraint::Percentage(50), Constraint::Percentage(50)]);
300+ .widths(&self.widths);
273301
274302 use tui::widgets::TableState;
275303
helix-tui/src/widgets/table.rs+2−2
@@ -36,7 +36,7 @@ use std::collections::HashMap;
3636/// capabilities of [`Text`].
3737#[derive(Debug, Clone, PartialEq, Default)]
3838pub struct Cell<'a> {
39− content: Text<'a>,
39+ pub content: Text<'a>,
4040 style: Style,
4141}
4242
@@ -81,7 +81,7 @@ where
8181/// By default, a row has a height of 1 but you can change this using [`Row::height`].
8282#[derive(Debug, Clone, PartialEq, Default)]
8383pub struct Row<'a> {
84− cells: Vec<Cell<'a>>,
84+ pub cells: Vec<Cell<'a>>,
8585 height: u16,
8686 style: Style,
8787 bottom_margin: u16,
languages.toml+22
@@ -5,6 +5,17 @@ injection-regex = "rust"
55file-types = ["rs"]
66roots = []
77auto-format = true
8+comment_token = "//"
9+config = """
10+{
11+ "cargo": {
12+ "loadOutDirsFromCheck": true
13+ },
14+ "procMacro": {
15+ "enable": false
16+ }
17+}
18+"""
819
920language-server = { command = "rust-analyzer" }
1021indent = { tab-width = 4, unit = " " }
@@ -15,6 +26,7 @@ scope = "source.toml"
1526injection-regex = "toml"
1627file-types = ["toml"]
1728roots = []
29+comment_token = "#"
1830
1931indent = { tab-width = 2, unit = " " }
2032
@@ -42,6 +54,7 @@ scope = "source.c"
4254injection-regex = "c"
4355file-types = ["c"] # TODO: ["h"]
4456roots = []
57+comment_token = "//"
4558
4659language-server = { command = "clangd" }
4760indent = { tab-width = 2, unit = " " }
@@ -52,6 +65,7 @@ scope = "source.cpp"
5265injection-regex = "cpp"
5366file-types = ["cc", "cpp", "hpp", "h"]
5467roots = []
68+comment_token = "//"
5569
5670language-server = { command = "clangd" }
5771indent = { tab-width = 2, unit = " " }
@@ -63,6 +77,7 @@ injection-regex = "go"
6377file-types = ["go"]
6478roots = ["Gopkg.toml", "go.mod"]
6579auto-format = true
80+comment_token = "//"
6681
6782language-server = { command = "gopls" }
6883# TODO: gopls needs utf-8 offsets?
@@ -74,6 +89,7 @@ scope = "source.js"
7489injection-regex = "^(js|javascript)$"
7590file-types = ["js"]
7691roots = []
92+comment_token = "//"
7793# TODO: highlights-jsx, highlights-params
7894
7995indent = { tab-width = 2, unit = " " }
@@ -113,6 +129,7 @@ scope = "source.python"
113129injection-regex = "python"
114130file-types = ["py"]
115131roots = []
132+comment_token = "#"
116133
117134language-server = { command = "pyls" }
118135# TODO: pyls needs utf-8 offsets
@@ -133,6 +150,7 @@ scope = "source.ruby"
133150injection-regex = "ruby"
134151file-types = ["rb"]
135152roots = []
153+comment_token = "#"
136154
137155language-server = { command = "solargraph", args = ["stdio"] }
138156indent = { tab-width = 2, unit = " " }
@@ -143,6 +161,7 @@ scope = "source.bash"
143161injection-regex = "bash"
144162file-types = ["sh", "bash"]
145163roots = []
164+comment_token = "#"
146165
147166language-server = { command = "bash-language-server", args = ["start"] }
148167indent = { tab-width = 2, unit = " " }
@@ -162,6 +181,7 @@ scope = "source.tex"
162181injection-regex = "tex"
163182file-types = ["tex"]
164183roots = []
184+comment_token = "%"
165185
166186indent = { tab-width = 4, unit = "\t" }
167187
@@ -171,6 +191,7 @@ scope = "source.julia"
171191injection-regex = "julia"
172192file-types = ["jl"]
173193roots = []
194+comment_token = "#"
174195language-server = { command = "julia", args = [ "--startup-file=no", "--history-file=no", "-e", "using LanguageServer;using Pkg;import StaticLint;import SymbolServer;env_path = dirname(Pkg.Types.Context().env.project_file);server = LanguageServer.LanguageServerInstance(stdin, stdout, env_path, \"\");server.runlinter = true;run(server);" ] }
175196indent = { tab-width = 2, unit = " " }
176197
@@ -180,5 +201,6 @@ indent = { tab-width = 2, unit = " " }
180201# injection-regex = "haskell"
181202# file-types = ["hs"]
182203# roots = []
204+# comment_token = "--"
183205#
184206# indent = { tab-width = 2, unit = " " }