Skip to content

Instantly share code, notes, and snippets.

@fahrradflucht
Last active July 21, 2018 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fahrradflucht/37692f3d559b1cc3b68891525b812b01 to your computer and use it in GitHub Desktop.
Save fahrradflucht/37692f3d559b1cc3b68891525b812b01 to your computer and use it in GitHub Desktop.
extern crate tempfile;
use self::tempfile::NamedTempFile;
use std::error::Error;
use std::ffi::OsString;
use std::io::prelude::*;
use std::process::Command;
pub fn edit_string(s: &str) -> Result<String, Box<Error>> {
let mut file = NamedTempFile::new()?;
file.write_all(s.as_bytes())?;
editor_output(&mut file)
}
fn editor_output(file: &mut NamedTempFile) -> Result<String, Box<Error>> {
use std::io::SeekFrom::Start;
let status = Command::new(editor_command()?)
.arg(file.path().as_os_str())
.spawn()?
.wait()?;
if !status.success() {
return Err("Editor did not exit successfully. Aborting".into());
}
let mut buffer = String::new();
file.reopen()?;
file.seek(Start(0))?;
file.read_to_string(&mut buffer)?;
Ok(buffer)
}
fn editor_command() -> Result<OsString, Box<Error>> {
use std::env;
env::var_os("VISUAL")
.or_else(|| env::var_os("EDITOR"))
.ok_or_else(|| "Either $VISUAL or $EDITOR must be set to edit files".into())
}
fn main() {
let input = edit_string("Change Me");
println!("{:?}", input);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment