Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

feat: added 'Open URL' code action

Elijah Potterb5392e55a6cd
diff --git a/Cargo.lock b/Cargo.lock
index 3c99cfeda..a06ee6019 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -550,6 +550,7 @@ dependencies = [
"harper-core",
"itertools 0.12.1",
"once_cell",
+ "open",
"resolve-path",
"serde_json",
"tokio",
@@ -688,6 +689,15 @@ dependencies = [
"unicode-normalization",
]
+[[package]]
+name = "is-docker"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3"
+dependencies = [
+ "once_cell",
+]
+
[[package]]
name = "is-macro"
version = "0.3.5"
@@ -700,6 +710,16 @@ dependencies = [
"syn 2.0.48",
]
+[[package]]
+name = "is-wsl"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5"
+dependencies = [
+ "is-docker",
+ "once_cell",
+]
+
[[package]]
name = "itertools"
version = "0.11.0"
@@ -864,6 +884,17 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
+[[package]]
+name = "open"
+version = "5.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68b3fbb0d52bf0cbb5225ba3d2c303aa136031d43abff98284332a9981ecddec"
+dependencies = [
+ "is-wsl",
+ "libc",
+ "pathdiff",
+]
+
[[package]]
name = "option-ext"
version = "0.2.0"
@@ -895,6 +926,12 @@ version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c"
+[[package]]
+name = "pathdiff"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd"
+
[[package]]
name = "percent-encoding"
version = "2.3.1"
diff --git a/harper-core/src/document.rs b/harper-core/src/document.rs
index 1ea260082..dce5bf5a4 100644
--- a/harper-core/src/document.rs
+++ b/harper-core/src/document.rs
@@ -1,3 +1,4 @@
+use std::cmp::Ordering;
use std::fmt::Display;
use itertools::Itertools;
@@ -56,6 +57,21 @@ impl Document {
self.match_quotes();
}
+ pub fn get_token_at_char_index(&self, char_index: usize) -> Option<Token> {
+ let index = self
+ .tokens
+ .binary_search_by(|t| {
+ if t.span.overlaps_with(Span::new_with_len(char_index, 1)) {
+ Ordering::Equal
+ } else {
+ t.span.start.cmp(&char_index)
+ }
+ })
+ .ok()?;
+
+ Some(self.tokens[index])
+ }
+
/// Defensively attempt to grab a specific token.
pub fn get_token(&self, index: usize) -> Option<Token> {
self.tokens.get(index).copied()
@@ -342,6 +358,7 @@ mod tests {
use super::Document;
use crate::parsers::{Markdown, PlainEnglish};
use crate::token::TokenStringExt;
+ use crate::{Span, Token, TokenKind};
#[test]
fn parses_sentences_correctly() {
@@ -401,4 +418,18 @@ mod tests {
fn medium_contraction2() {
assert_condensed_contractions("There's no way", 5);
}
+
+ #[test]
+ fn selects_token_at_char_index() {
+ let text = "There were three little pigs. They built three little homes.";
+ let document = Document::new(text, Box::new(PlainEnglish));
+
+ assert_eq!(
+ document.get_token_at_char_index(19),
+ Some(Token {
+ kind: TokenKind::Word,
+ span: Span::new(17, 23)
+ })
+ )
+ }
}
diff --git a/harper-core/src/lexing/hostname.rs b/harper-core/src/lexing/hostname.rs
index dd731b450..716bdee97 100644
--- a/harper-core/src/lexing/hostname.rs
+++ b/harper-core/src/lexing/hostname.rs
@@ -5,7 +5,7 @@ pub fn lex_hostname(source: &[char]) -> Option<usize> {
for c in label {
passed_chars += 1;
if !matches!(c, 'A'..='Z' | 'a'..='z' | '0'..='9' | '-') {
- return Some(passed_chars);
+ return Some(passed_chars - 1);
}
}
diff --git a/harper-core/src/lexing/url.rs b/harper-core/src/lexing/url.rs
index 0bac6491b..007df7e53 100644
--- a/harper-core/src/lexing/url.rs
+++ b/harper-core/src/lexing/url.rs
@@ -36,6 +36,8 @@ fn lex_ip_schemepart(source: &[char]) -> Option<usize> {
// Parse endpoint path
while cursor != rest.len() {
+ dbg!(&rest[cursor..]);
+
if rest[cursor] != '/' {
break;
}
@@ -82,6 +84,8 @@ fn lex_login(source: &[char]) -> Option<usize> {
fn lex_hostport(source: &[char]) -> Option<usize> {
let hostname_end = lex_hostname(source)?;
+ dbg!(&source[..hostname_end]);
+
if source.get(hostname_end) == Some(&':') {
Some(
source
@@ -221,6 +225,11 @@ mod tests {
#[test]
fn consumes_youtube_not_garbage() {
- assert_consumes_part("https://youtube.com aklsjdha", 20);
+ assert_consumes_part("https://youtube.com aklsjdha", 19);
+ }
+
+ #[test]
+ fn consumes_with_path() {
+ assert_consumes_full("https://elijahpotter.dev/articles/quantifying_hope_on_a_global_scale")
}
}
diff --git a/harper-core/src/span.rs b/harper-core/src/span.rs
index b29bbf46c..dc309959a 100644
--- a/harper-core/src/span.rs
+++ b/harper-core/src/span.rs
@@ -33,8 +33,6 @@ impl Span {
self.start.max(other.start) <= self.end.min(other.end)
}
- pub fn is_valid() {}
-
/// Get the associated content. Will return [`None`] if any aspect is
/// invalid.
pub fn try_get_content<'a>(&self, source: &'a [char]) -> Option<&'a [char]> {
diff --git a/harper-ls/Cargo.toml b/harper-ls/Cargo.toml
index 1b53cf720..d23108855 100644
--- a/harper-ls/Cargo.toml
+++ b/harper-ls/Cargo.toml
@@ -33,3 +33,4 @@ itertools = "0.12.1"
tracing = "0.1.40"
tracing-subscriber = "0.3.18"
resolve-path = "0.1.0"
+open = "5.1.1"
diff --git a/harper-ls/src/backend.rs b/harper-ls/src/backend.rs
index 1992178eb..768ce43df 100644
--- a/harper-ls/src/backend.rs
+++ b/harper-ls/src/backend.rs
@@ -3,8 +3,16 @@ use std::path::PathBuf;
use std::sync::Arc;
use harper_core::parsers::Markdown;
-use harper_core::{Dictionary, Document, FullDictionary, LintSet, Linter, MergedDictionary};
-use itertools::Itertools;
+use harper_core::{
+ Dictionary,
+ Document,
+ FullDictionary,
+ LintSet,
+ Linter,
+ MergedDictionary,
+ Token,
+ TokenKind
+};
use serde_json::Value;
use tokio::sync::Mutex;
use tower_lsp::jsonrpc::Result;
@@ -14,12 +22,14 @@ use tower_lsp::lsp_types::{
CodeActionParams,
CodeActionProviderCapability,
CodeActionResponse,
+ Command,
Diagnostic,
DidChangeConfigurationParams,
DidChangeTextDocumentParams,
DidCloseTextDocumentParams,
DidOpenTextDocumentParams,
DidSaveTextDocumentParams,
+ ExecuteCommandOptions,
ExecuteCommandParams,
InitializeParams,
InitializeResult,
@@ -237,12 +247,25 @@ impl Backend {
// Find lints whose span overlaps with range
let span = range_to_span(source_chars, range);
- let actions = lints
+ let mut actions: Vec<CodeActionOrCommand> = lints
.into_iter()
.filter(|lint| lint.span.overlaps_with(span))
.flat_map(|lint| lint_to_code_actions(&lint, url, source_chars))
.collect();
+ if let Some(Token {
+ kind: TokenKind::Url,
+ span,
+ ..
+ }) = doc_state.document.get_token_at_char_index(span.start)
+ {
+ actions.push(CodeActionOrCommand::Command(Command::new(
+ "Open URL".to_string(),
+ "HarperOpen".to_string(),
+ Some(vec![doc_state.document.get_span_content_str(span).into()])
+ )))
+ }
+
Ok(actions)
}
@@ -290,6 +313,14 @@ impl LanguageServer for Backend {
server_info: None,
capabilities: ServerCapabilities {
code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
+ execute_command_provider: Some(ExecuteCommandOptions {
+ commands: vec![
+ "HarperAddToUserDict".to_owned(),
+ "HarperAddToFileDict".to_owned(),
+ "HarperOpen".to_owned(),
+ ],
+ ..Default::default()
+ }),
text_document_sync: Some(TextDocumentSyncCapability::Options(
TextDocumentSyncOptions {
open_close: Some(true),
@@ -299,6 +330,7 @@ impl LanguageServer for Backend {
save: Some(TextDocumentSyncSaveOptions::Supported(true))
}
)),
+
..Default::default()
}
})
@@ -365,35 +397,68 @@ impl LanguageServer for Backend {
.into_iter()
.map(|v| serde_json::from_value::<String>(v).unwrap());
- let Some((first, second)) = string_args.next_tuple() else {
+ let Some(first) = string_args.next() else {
return Ok(None);
};
- let word = &first.chars().collect::<Vec<_>>();
- let file_url = second.parse().unwrap();
+ info!("Received command: \"{}\"", params.command.as_str());
match params.command.as_str() {
- "AddToUserDict" => {
+ "HarperAddToUserDict" => {
+ let word = &first.chars().collect::<Vec<_>>();
+
+ let Some(second) = string_args.next() else {
+ return Ok(None);
+ };
+
+ let file_url = second.parse().unwrap();
+
let mut dict = self.load_user_dictionary().await;
dict.append_word(word);
if let Err(err) = self.save_user_dictionary(dict).await {
error!("Unable to save user dictionary: {}", err);
}
+
+ let _ = self.update_document_from_file(&file_url).await;
+ self.publish_diagnostics(&file_url).await;
}
- "AddToFileDict" => {
+ "HarperAddToFileDict" => {
+ let word = &first.chars().collect::<Vec<_>>();
+
+ let Some(second) = string_args.next() else {
+ return Ok(None);
+ };
+
+ let file_url = second.parse().unwrap();
+
let mut dict = self.load_file_dictionary(&file_url).await;
dict.append_word(word);
if let Err(err) = self.save_file_dictionary(&file_url, dict).await {
error!("Unable to save file dictionary: {}", err);
}
+
+ let _ = self.update_document_from_file(&file_url).await;
+ self.publish_diagnostics(&file_url).await;
}
+ "HarperOpen" => match open::that(&first) {
+ Ok(()) => {
+ let message = format!(r#"Opened "{}""#, first);
+
+ self.client.log_message(MessageType::INFO, &message).await;
+
+ info!("{}", message);
+ }
+ Err(err) => {
+ self.client
+ .log_message(MessageType::ERROR, "Unable to open URL")
+ .await;
+ error!("Unable to open URL: {}", err);
+ }
+ },
_ => ()
}
- let _ = self.update_document_from_file(&file_url).await;
- self.publish_diagnostics(&file_url).await;
-
Ok(None)
}
diff --git a/harper-ls/src/diagnostics.rs b/harper-ls/src/diagnostics.rs
index 1b5b93936..60ec154dd 100644
--- a/harper-ls/src/diagnostics.rs
+++ b/harper-ls/src/diagnostics.rs
@@ -68,13 +68,13 @@ pub fn lint_to_code_actions<'a>(
results.push(CodeActionOrCommand::Command(Command::new(
format!("Add \"{}\" to the global dictionary.", orig),
- "AddToUserDict".to_string(),
+ "HarperAddToUserDict".to_string(),
Some(vec![orig.clone().into(), url.to_string().into()])
)));
results.push(CodeActionOrCommand::Command(Command::new(
format!("Add \"{}\" to the file dictionary.", orig),
- "AddToFileDict".to_string(),
+ "HarperAddToFileDict".to_string(),
Some(vec![orig.into(), url.to_string().into()])
)))
}