alistair
3 years ago
1 changed files with 40 additions and 18 deletions
@ -1,47 +1,69 @@
@@ -1,47 +1,69 @@
|
||||
use syntect::parsing::SyntaxSet; |
||||
use syntect::highlighting::{ThemeSet, Style}; |
||||
use syntect::highlighting::{ThemeSet}; |
||||
use syntect::html::highlighted_html_for_string; |
||||
|
||||
use std::ptr; |
||||
use std::str::Utf8Error; |
||||
use std::ffi::{CStr, CString}; |
||||
use std::os::raw::c_char; |
||||
|
||||
static mut ps : Option<SyntaxSet> = None; |
||||
static mut PS : Option<SyntaxSet> = None; |
||||
// Load these once at the start of your program
|
||||
static mut ts : Option<ThemeSet> = None; |
||||
static mut TS : Option<ThemeSet> = None; |
||||
|
||||
|
||||
unsafe fn setup_to_html(langext: *const c_char, theme: *const c_char, code: *const c_char |
||||
) -> Option<CString> { |
||||
|
||||
let ext = CStr::from_ptr(langext).to_str().ok()?; |
||||
let thm = CStr::from_ptr(theme).to_str().ok()?; |
||||
let cod = CStr::from_ptr(code).to_str().ok()?; |
||||
|
||||
match (CString::new(to_html(ext, thm, cod)?)) { |
||||
Ok(h) => Some(h), |
||||
Err(r) => None |
||||
} |
||||
|
||||
} |
||||
|
||||
|
||||
#[no_mangle] |
||||
pub extern fn syntect_to_html(langext: *const c_char, theme: *const c_char, code: *const c_char) -> *const c_char { |
||||
unsafe { |
||||
let ext = CStr::from_ptr(langext).to_str().expect("fail"); |
||||
let thm = CStr::from_ptr(theme).to_str().expect("fail"); |
||||
let cod = CStr::from_ptr(code).to_str().expect("fail"); |
||||
match (setup_to_html(langext, theme, code)) { |
||||
Some(h) => h.into_raw(), |
||||
None => ptr::null() |
||||
} |
||||
} |
||||
} |
||||
|
||||
let html = to_html(ext, thm, cod); |
||||
let highlighted = CString::new(html).expect("Makecstr"); |
||||
|
||||
highlighted.into_raw() |
||||
#[no_mangle] |
||||
pub extern fn syntect_release_str(s: *mut c_char) { |
||||
unsafe { |
||||
let _ss = CString::from_raw(s); |
||||
} |
||||
} |
||||
|
||||
|
||||
#[no_mangle] |
||||
pub extern fn syntect_init() { |
||||
unsafe { |
||||
ps = Some(SyntaxSet::load_defaults_newlines()); |
||||
ts = Some(ThemeSet::load_defaults()); |
||||
PS = Some(SyntaxSet::load_defaults_newlines()); |
||||
TS = Some(ThemeSet::load_defaults()); |
||||
} |
||||
} |
||||
|
||||
unsafe fn to_html(langext: &str, theme: &str, code: &str) -> Option<String> { |
||||
|
||||
unsafe fn to_html(langext: &str, theme: &str, code: &str) -> String { |
||||
|
||||
if let Some(pps) = &ps { |
||||
let syntax = pps.find_syntax_by_extension("rs").unwrap(); |
||||
if let Some(tts) = &ts { |
||||
return highlighted_html_for_string(code, &pps, syntax, &tts.themes[theme]); |
||||
if let Some(pps) = &PS { |
||||
let syntax = pps.find_syntax_by_token(langext)?; |
||||
if let Some(tts) = &TS { |
||||
return Some(highlighted_html_for_string(code, &pps, syntax, &tts.themes[theme])); |
||||
} |
||||
}
|
||||
|
||||
return String::from(""); |
||||
None |
||||
|
||||
} |
||||
|
||||
|
Loading…
Reference in new issue