Skip to content

Commit

Permalink
open urls with goto_file command (#5820)
Browse files Browse the repository at this point in the history
* feat(commands): open urls with goto_file command

Add capability for `goto_file` command to open an URL under cursor.

Fixes: #1472
Superseds: #4398

* open files inside helix

* address code review

* bump deps

* fix based on code review comments
  • Loading branch information
matoous authored Nov 21, 2023
1 parent bfd60a5 commit 3052050
Show file tree
Hide file tree
Showing 4 changed files with 114 additions and 6 deletions.
38 changes: 38 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions helix-term/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ pulldown-cmark = { version = "0.9", default-features = false }
# file type detection
content_inspector = "0.2.4"

# opening URLs
open = "5.0.0"
url = "2.4.1"

# config
toml = "0.7"

Expand Down
76 changes: 71 additions & 5 deletions helix-term/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,13 @@ use crate::{

use crate::job::{self, Jobs};
use futures_util::{stream::FuturesUnordered, TryStreamExt};
use std::{collections::HashMap, fmt, future::Future};
use std::{collections::HashSet, num::NonZeroUsize};
use std::{
collections::{HashMap, HashSet},
fmt,
future::Future,
io::Read,
num::NonZeroUsize,
};

use std::{
borrow::Cow,
Expand All @@ -70,6 +75,7 @@ use std::{

use once_cell::sync::Lazy;
use serde::de::{self, Deserialize, Deserializer};
use url::Url;

use grep_regex::RegexMatcherBuilder;
use grep_searcher::{sinks, BinaryDetection, SearcherBuilder};
Expand Down Expand Up @@ -331,7 +337,7 @@ impl MappableCommand {
goto_implementation, "Goto implementation",
goto_file_start, "Goto line number <n> else file start",
goto_file_end, "Goto file end",
goto_file, "Goto files in selection",
goto_file, "Goto files/URLs in selection",
goto_file_hsplit, "Goto files in selection (hsplit)",
goto_file_vsplit, "Goto files in selection (vsplit)",
goto_reference, "Goto references",
Expand Down Expand Up @@ -1190,10 +1196,53 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
.to_string(),
);
}

for sel in paths {
let p = sel.trim();
if !p.is_empty() {
let path = &rel_path.join(p);
if p.is_empty() {
continue;
}

if let Ok(url) = Url::parse(p) {
return open_url(cx, url, action);
}

let path = &rel_path.join(p);
if path.is_dir() {
let picker = ui::file_picker(path.into(), &cx.editor.config());
cx.push_layer(Box::new(overlaid(picker)));
} else if let Err(e) = cx.editor.open(path, action) {
cx.editor.set_error(format!("Open file failed: {:?}", e));
}
}
}

/// Opens the given url. If the URL points to a valid textual file it is open in helix.
// Otherwise, the file is open using external program.
fn open_url(cx: &mut Context, url: Url, action: Action) {
let doc = doc!(cx.editor);
let rel_path = doc
.relative_path()
.map(|path| path.parent().unwrap().to_path_buf())
.unwrap_or_default();

if url.scheme() != "file" {
return open_external_url(cx, url);
}

let content_type = std::fs::File::open(url.path()).and_then(|file| {
// Read up to 1kb to detect the content type
let mut read_buffer = Vec::new();
let n = file.take(1024).read_to_end(&mut read_buffer)?;
Ok(content_inspector::inspect(&read_buffer[..n]))
});

// we attempt to open binary files - files that can't be open in helix - using external
// program as well, e.g. pdf files or images
match content_type {
Ok(content_inspector::ContentType::BINARY) => open_external_url(cx, url),
Ok(_) | Err(_) => {
let path = &rel_path.join(url.path());
if path.is_dir() {
let picker = ui::file_picker(path.into(), &cx.editor.config());
cx.push_layer(Box::new(overlaid(picker)));
Expand All @@ -1204,6 +1253,23 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
}
}

/// Opens URL in external program.
fn open_external_url(cx: &mut Context, url: Url) {
let commands = open::commands(url.as_str());
cx.jobs.callback(async {
for cmd in commands {
let mut command = tokio::process::Command::new(cmd.get_program());
command.args(cmd.get_args());
if command.output().await.is_ok() {
return Ok(job::Callback::Editor(Box::new(|_| {})));
}
}
Ok(job::Callback::Editor(Box::new(move |editor| {
editor.set_error("Opening URL in external program failed")
})))
});
}

fn extend_word_impl<F>(cx: &mut Context, extend_fn: F)
where
F: Fn(RopeSlice, Range, usize) -> Range,
Expand Down
2 changes: 1 addition & 1 deletion helix-view/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ helix-vcs = { version = "0.6", path = "../helix-vcs" }

# Conversion traits
once_cell = "1.18"
url = "2"
url = "2.4.1"

arc-swap = { version = "1.6.0" }

Expand Down

0 comments on commit 3052050

Please sign in to comment.