Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Syntax highlight code fences #6

Merged
merged 1 commit into from
Sep 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions lib/mdex.ex
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,13 @@ defmodule MDEx do
* `:extension` - https://docs.rs/comrak/latest/comrak/struct.ComrakExtensionOptions.html
* `:parse` - https://docs.rs/comrak/latest/comrak/struct.ComrakParseOptions.html
* `:render` - https://docs.rs/comrak/latest/comrak/struct.ComrakRenderOptions.html
* `:features` - see the available options below.

### Features Options

* `:sanitize` (default `false`) - sanitize output using [ammonia](https://crates.io/crates/ammonia).\n Recommended if passing `render: [unsafe_: true]`
* `:syntax_highlighting` (default `"InspiredGithub`) - syntax highlight code fences using [syntect](https://crates.io/crates/syntect).
See a list of available themes at [struct.ThemeSet](https://docs.rs/syntect/latest/syntect/highlighting/struct.ThemeSet.html#method.load_defaults)

## Examples

Expand All @@ -50,7 +56,7 @@ defmodule MDEx do
iex> MDEx.to_html("<marquee>visit https://https://beaconcms.org</marquee>", extension: [autolink: true], render: [unsafe_: true])
"<p><marquee>visit <a href=\\"https://https://beaconcms.org\\">https://https://beaconcms.org</a></marquee></p>\\n"

iex> MDEx.to_html("# Title with <script>console.log('dangerous script')</script>", render: [unsafe_: true], sanitize: true)
iex> MDEx.to_html("# Title with <script>console.log('dangerous script')</script>", render: [unsafe_: true], features: [sanitize: true])
"<h1>Title with </h1>\\n"

"""
Expand All @@ -59,13 +65,13 @@ defmodule MDEx do
extension = Keyword.get(opts, :extension, %{})
parse = Keyword.get(opts, :parse, %{})
render = Keyword.get(opts, :render, %{})
sanitize = Keyword.get(opts, :sanitize, false)
features = Keyword.get(opts, :features, %{})

opts = %MDEx.Options{
extension: struct(MDEx.ExtensionOptions, extension),
parse: struct(MDEx.ParseOptions, parse),
render: struct(MDEx.RenderOptions, render),
sanitize: sanitize
features: struct(MDEx.FeaturesOptions, features)
}

Native.to_html_with_options(markdown, opts)
Expand Down
8 changes: 7 additions & 1 deletion lib/mdex/options.ex
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,16 @@ defmodule MDEx.RenderOptions do
sourcepos: false
end

defmodule MDEx.FeaturesOptions do
@moduledoc false
defstruct sanitize: false,
syntax_highlighting: "InspiredGitHub"
end

defmodule MDEx.Options do
@moduledoc false
defstruct extension: %MDEx.ExtensionOptions{},
parse: %MDEx.ParseOptions{},
render: %MDEx.RenderOptions{},
sanitize: false
features: %MDEx.FeaturesOptions{}
end
45 changes: 35 additions & 10 deletions native/comrak_nif/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
extern crate rustler;

use ammonia::clean;
use comrak::markdown_to_html;
use comrak::plugins::syntect::SyntectAdapter;
use comrak::{markdown_to_html, markdown_to_html_with_plugins};
use rustler::{Env, NifResult, Term};
use serde_rustler::to_term;

Expand Down Expand Up @@ -51,18 +52,28 @@ pub struct RenderOptions {
pub sourcepos: bool,
}

#[derive(Debug, NifStruct)]
#[module = "MDEx.FeaturesOptions"]
pub struct FeaturesOptions {
pub sanitize: bool,
pub syntax_highlighting: Option<String>,
}

#[derive(Debug, NifStruct)]
#[module = "MDEx.Options"]
pub struct Options {
pub extension: ExtensionOptions,
pub parse: ParseOptions,
pub render: RenderOptions,
pub sanitize: bool,
pub features: FeaturesOptions,
}

#[rustler::nif(schedule = "DirtyCpu")]
fn to_html(md: &str) -> String {
markdown_to_html(md, &comrak::ComrakOptions::default())
let syntec_adapter = SyntectAdapter::new("InspiredGitHub");
let mut plugins = comrak::ComrakPlugins::default();
plugins.render.codefence_syntax_highlighter = Some(&syntec_adapter);
markdown_to_html_with_plugins(md, &comrak::ComrakOptions::default(), &plugins)
}

#[rustler::nif(schedule = "DirtyCpu")]
Expand Down Expand Up @@ -97,16 +108,30 @@ fn to_html_with_options<'a>(env: Env<'a>, md: &str, options: Options) -> NifResu
},
};

let unsafe_html = markdown_to_html(md, &comrak_options);

if options.sanitize {
let safe_html = clean(&unsafe_html);
to_term(env, safe_html).map_err(|err| err.into())
} else {
to_term(env, unsafe_html).map_err(|err| err.into())
match options.features.syntax_highlighting {
Some(theme) => {
let mut plugins = comrak::ComrakPlugins::default();
let syntec_adapter = SyntectAdapter::new(theme.as_str());
plugins.render.codefence_syntax_highlighter = Some(&syntec_adapter);
let unsafe_html = markdown_to_html_with_plugins(md, &comrak_options, &plugins);
render(env, unsafe_html, options.features.sanitize)
}
None => {
let unsafe_html = markdown_to_html(md, &comrak_options);
render(env, unsafe_html, options.features.sanitize)
}
}
}

fn render(env: Env, unsafe_html: String, sanitize: bool) -> NifResult<Term> {
let html = match sanitize {
true => clean(&unsafe_html),
false => unsafe_html,
};

to_term(env, html).map_err(|err| err.into())
}

fn list_style(list_style: ListStyleType) -> comrak::ListStyleType {
match list_style {
ListStyleType::Dash => comrak::ListStyleType::Dash,
Expand Down
35 changes: 35 additions & 0 deletions test/mdex_test.exs
Original file line number Diff line number Diff line change
@@ -1,4 +1,39 @@
defmodule MDExTest do
use ExUnit.Case
doctest MDEx

describe "syntax highlighting" do
test "enabled by default" do
assert MDEx.to_html(~S"""
```elixir
{:mdex, "~> 0.1"}
```
""") ==
"<pre style=\"background-color:#ffffff;\"><code class=\"language-elixir\"><span style=\"color:#323232;\">{:mdex, &quot;~&gt; 0.1&quot;}\n</span></code></pre>\n"
end

test "change theme name" do
assert MDEx.to_html(
~S"""
```elixir
{:mdex, "~> 0.1"}
```
""",
features: [syntax_highlighting: "base16-mocha.dark"]
) ==
"<pre style=\"background-color:#3b3228;\"><code class=\"language-elixir\"><span style=\"color:#d0c8c6;\">{:mdex, &quot;~&gt; 0.1&quot;}\n</span></code></pre>\n"
end

test "can be disabled" do
assert MDEx.to_html(
~S"""
```elixir
{:mdex, "~> 0.1"}
```
""",
features: [syntax_highlighting: nil]
) ==
"<pre><code class=\"language-elixir\">{:mdex, &quot;~&gt; 0.1&quot;}\n</code></pre>\n"
end
end
end
Loading