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

Make the two wikilinks extensions mutually exclusive (and other assorted improvements) #497

Closed
wants to merge 4 commits into from
Closed
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
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,7 @@ clap = { version = "4.0", optional = true, features = [
"string",
"wrap_help",
] }

[[example]]
name = "syntect"
required-features = [ "syntect" ]
5 changes: 2 additions & 3 deletions examples/s-expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const INDENT: usize = 4;
const CLOSE_NEWLINE: bool = false;

use comrak::nodes::{AstNode, NodeValue};
use comrak::{parse_document, Arena, ExtensionOptions, Options};
use comrak::{parse_document, Arena, ExtensionOptions, Options, WikiLinksMode};
use std::env;
use std::error::Error;
use std::fs::File;
Expand Down Expand Up @@ -86,8 +86,7 @@ fn dump(source: &str) -> io::Result<()> {
.multiline_block_quotes(true)
.math_dollars(true)
.math_code(true)
.wikilinks_title_after_pipe(true)
.wikilinks_title_before_pipe(true)
.wikilinks(WikiLinksMode::TitleFirst)
.build();

let opts = Options {
Expand Down
6 changes: 3 additions & 3 deletions src/cm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::nodes::{
use crate::nodes::{NodeList, TableAlignment};
#[cfg(feature = "shortcodes")]
use crate::parser::shortcodes::NodeShortCode;
use crate::parser::Options;
use crate::parser::{Options, WikiLinksMode};
use crate::scanners;
use crate::strings::trim_start_match;
use crate::{nodes, Plugins};
Expand Down Expand Up @@ -761,12 +761,12 @@ impl<'a, 'o> CommonMarkFormatter<'a, 'o> {
fn format_wikilink(&mut self, nl: &NodeWikiLink, entering: bool) -> bool {
if entering {
write!(self, "[[").unwrap();
if self.options.extension.wikilinks_title_after_pipe {
if self.options.extension.wikilinks == Some(WikiLinksMode::UrlFirst) {
self.output(nl.url.as_bytes(), false, Escaping::Url);
write!(self, "|").unwrap();
}
} else {
if self.options.extension.wikilinks_title_before_pipe {
if self.options.extension.wikilinks == Some(WikiLinksMode::TitleFirst) {
write!(self, "|").unwrap();
self.output(nl.url.as_bytes(), false, Escaping::Url);
}
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ pub use parser::{
parse_document, BrokenLinkCallback, BrokenLinkReference, ExtensionOptions,
ExtensionOptionsBuilder, ListStyleType, Options, ParseOptions, ParseOptionsBuilder, Plugins,
PluginsBuilder, RenderOptions, RenderOptionsBuilder, RenderPlugins, RenderPluginsBuilder,
ResolvedReference, URLRewriter,
ResolvedReference, URLRewriter, WikiLinksMode,
};
pub use typed_arena::Arena;
pub use xml::format_document as format_xml;
Expand Down
20 changes: 17 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use std::path::PathBuf;
use std::process;

use clap::{Parser, ValueEnum};
use comrak::{ExtensionOptions, ParseOptions, RenderOptions};
use comrak::{ExtensionOptions, ParseOptions, RenderOptions, WikiLinksMode};

const EXIT_SUCCESS: i32 = 0;
const EXIT_PARSE_CONFIG: i32 = 2;
Expand Down Expand Up @@ -252,6 +252,21 @@ fn main() -> Result<(), Box<dyn Error>> {

let exts = &cli.extensions;

let wikilinks_title_after_pipe = exts.contains(&Extension::WikilinksTitleAfterPipe);
let wikilinks_title_before_pipe = exts.contains(&Extension::WikilinksTitleBeforePipe);
let wikilinks_mode = match (wikilinks_title_after_pipe, wikilinks_title_before_pipe) {
(false, false) => None,
(true, false) => Some(WikiLinksMode::UrlFirst),
(false, true) => Some(WikiLinksMode::TitleFirst),
(true, true) => {
eprintln!(concat!(
"cannot enable both wikilinks-title-after-pipe ",
"and wikilinks-title-before-pipe at the same time"
));
process::exit(EXIT_PARSE_CONFIG);
}
};

let extension = ExtensionOptions::builder()
.strikethrough(exts.contains(&Extension::Strikethrough) || cli.gfm)
.tagfilter(exts.contains(&Extension::Tagfilter) || cli.gfm)
Expand All @@ -265,8 +280,7 @@ fn main() -> Result<(), Box<dyn Error>> {
.multiline_block_quotes(exts.contains(&Extension::MultilineBlockQuotes))
.math_dollars(exts.contains(&Extension::MathDollars))
.math_code(exts.contains(&Extension::MathCode))
.wikilinks_title_after_pipe(exts.contains(&Extension::WikilinksTitleAfterPipe))
.wikilinks_title_before_pipe(exts.contains(&Extension::WikilinksTitleBeforePipe))
.maybe_wikilinks(wikilinks_mode)
.underline(exts.contains(&Extension::Underline))
.subscript(exts.contains(&Extension::Subscript))
.spoiler(exts.contains(&Extension::Spoiler))
Expand Down
2 changes: 2 additions & 0 deletions src/nodes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ pub enum NodeValue {
MultilineBlockQuote(NodeMultilineBlockQuote),

/// **Inline**. A character that has been [escaped](https://github.github.com/gfm/#backslash-escapes)
///
/// Enabled with [`escaped_char_spans`](crate::RenderOptionsBuilder::escaped_char_spans).
Escaped,

/// **Inline**. A wikilink to some URL.
Expand Down
17 changes: 9 additions & 8 deletions src/parser/inlines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ use std::str;
use typed_arena::Arena;
use unicode_categories::UnicodeCategories;

use super::WikiLinksMode;

const MAXBACKTICKS: usize = 80;
const MAX_LINK_LABEL_LENGTH: usize = 1000;
const MAX_MATH_DOLLARS: usize = 2;
Expand Down Expand Up @@ -235,8 +237,7 @@ impl<'a, 'r, 'o, 'd, 'i> Subject<'a, 'r, 'o, 'd, 'i> {

let mut wikilink_inl = None;

if (self.options.extension.wikilinks_title_after_pipe
|| self.options.extension.wikilinks_title_before_pipe)
if self.options.extension.wikilinks.is_some()
&& !self.within_brackets
&& self.peek_char() == Some(&(b'['))
{
Expand Down Expand Up @@ -1804,16 +1805,16 @@ impl<'a, 'r, 'o, 'd, 'i> Subject<'a, 'r, 'o, 'd, 'i> {
if self.peek_char() == Some(&(b']')) && self.peek_char_n(1) == Some(&(b']')) {
self.pos += 2;

if self.options.extension.wikilinks_title_after_pipe {
Some(WikilinkComponents {
match self.options.extension.wikilinks {
Some(WikiLinksMode::UrlFirst) => Some(WikilinkComponents {
url: left,
link_label: Some((right, right_startpos + 1, self.pos - 3)),
})
} else {
Some(WikilinkComponents {
}),
Some(WikiLinksMode::TitleFirst) => Some(WikilinkComponents {
url: right,
link_label: Some((left, left_startpos + 1, right_startpos - 1)),
})
}),
None => unreachable!(),
}
} else {
self.pos = left_startpos;
Expand Down
44 changes: 26 additions & 18 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,21 @@ where
}
}

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Copy)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
/// Selects between wikilinks with the title first or the URL first.
///
/// See [`ExtensionOptions::wikilinks`].
pub enum WikiLinksMode {
/// Indicates that the URL precedes the title. For example: `[[http://example.com|link
/// title]]`.
UrlFirst,

/// Indicates that the title precedes the URL. For example: `[[link title|http://example.com]]`.
TitleFirst,
}

#[non_exhaustive]
#[derive(Default, Debug, Clone, Builder)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
Expand Down Expand Up @@ -466,37 +481,28 @@ pub struct ExtensionOptions {
#[builder(default)]
pub shortcodes: bool,

/// Enables wikilinks using title after pipe syntax
/// Enables wikilinks
///
/// With [`WikiLinksMode::TitleFirst`]:
///
/// ```` md
/// [[url|link label]]
/// [[link label|url]]
/// ````
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// options.extension.wikilinks_title_after_pipe = true;
/// assert_eq!(markdown_to_html("[[url|link label]]", &options),
/// "<p><a href=\"url\" data-wikilink=\"true\">link label</a></p>\n");
/// ```
#[builder(default)]
pub wikilinks_title_after_pipe: bool,

/// Enables wikilinks using title before pipe syntax
/// With [`WikiLinksMode::UrlFirst`]:
///
/// ```` md
/// [[link label|url]]
/// [[url|link label]]
/// ````
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// # use comrak::{markdown_to_html, Options, WikiLinksMode};
/// let mut options = Options::default();
/// options.extension.wikilinks_title_before_pipe = true;
/// options.extension.wikilinks = Some(WikiLinksMode::TitleFirst);
/// assert_eq!(markdown_to_html("[[link label|url]]", &options),
/// "<p><a href=\"url\" data-wikilink=\"true\">link label</a></p>\n");
/// ```
#[builder(default)]
pub wikilinks_title_before_pipe: bool,
pub wikilinks: Option<WikiLinksMode>,

/// Enables underlines using double underscores
///
Expand Down Expand Up @@ -865,6 +871,8 @@ pub struct RenderOptions {
/// let xml = markdown_to_commonmark_xml(input, &options);
/// assert!(xml.contains("<text sourcepos=\"1:4-1:15\" xml:space=\"preserve\">"));
/// ```
///
/// [`experimental_inline_sourcepos`]: crate::RenderOptionsBuilder::experimental_inline_sourcepos
#[builder(default)]
pub sourcepos: bool,

Expand Down
30 changes: 26 additions & 4 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,20 +127,35 @@ macro_rules! html_opts {
([$($optclass:ident.$optname:ident),*], $lhs:expr, $rhs:expr) => {
html_opts!([$($optclass.$optname),*], $lhs, $rhs,)
};
([$($optclass:ident.$optname:ident = $val:expr),*], $lhs:expr, $rhs:expr) => {
html_opts!([$($optclass.$optname = $val),*], $lhs, $rhs,)
};
([$($optclass:ident.$optname:ident),*], $lhs:expr, $rhs:expr,) => {
html_opts!([$($optclass.$optname),*], $lhs, $rhs, roundtrip)
};
([$($optclass:ident.$optname:ident = $val:expr),*], $lhs:expr, $rhs:expr,) => {
html_opts!([$($optclass.$optname = $val),*], $lhs, $rhs, roundtrip)
};
([$($optclass:ident.$optname:ident),*], $lhs:expr, $rhs:expr, $rt:ident) => {
html_opts!([$($optclass.$optname),*], $lhs, $rhs, $rt,)
};
([$($optclass:ident.$optname:ident = $val:expr),*], $lhs:expr, $rhs:expr, $rt:ident) => {
html_opts!([$($optclass.$optname = $val),*], $lhs, $rhs, $rt,)
};
([$($optclass:ident.$optname:ident),*], $lhs:expr, $rhs:expr, roundtrip,) => {
html_opts!([$($optclass.$optname = true),*], $lhs, $rhs, roundtrip,)
};
([$($optclass:ident.$optname:ident = $val:expr),*], $lhs:expr, $rhs:expr, roundtrip,) => {
$crate::tests::html_opts_i($lhs, $rhs, true, |opts| {
$(opts.$optclass.$optname = true;)*
$(opts.$optclass.$optname = $val;)*
});
};
([$($optclass:ident.$optname:ident),*], $lhs:expr, $rhs:expr, no_roundtrip,) => {
html_opts!([$($optclass.$optname = true),*], $lhs, $rhs, no_roundtrip,)
};
([$($optclass:ident.$optname:ident = $val:expr),*], $lhs:expr, $rhs:expr, no_roundtrip,) => {
$crate::tests::html_opts_i($lhs, $rhs, false, |opts| {
$(opts.$optclass.$optname = true;)*
$(opts.$optclass.$optname = $val;)*
});
};
}
Expand Down Expand Up @@ -312,13 +327,20 @@ macro_rules! assert_ast_match {
$amt
)
};
([ $( $optclass:ident.$optname:ident ),* ], $( $md:literal )+, $amt:tt) => {
([ $( $optclass:ident.$optname:ident = $val:expr ),* ], $( $md:literal )+, $amt:tt) => {
crate::tests::assert_ast_match_i(
concat!( $( $md ),+ ),
ast!($amt),
|#[allow(unused_variables)] opts| {$(opts.$optclass.$optname = true;)*},
|#[allow(unused_variables)] opts| {$(opts.$optclass.$optname = $val;)*},
);
};
([ $( $optclass:ident.$optname:ident ),* ], $( $md:literal )+, $amt:tt) => {
assert_ast_match!(
[ $( $optclass.$optname = true),* ],
$( $md )+,
$amt
)
};
}

pub(crate) use assert_ast_match;
Expand Down
5 changes: 2 additions & 3 deletions src/tests/api.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::sync::{Arc, Mutex};

use parser::BrokenLinkReference;
use parser::{BrokenLinkReference, WikiLinksMode};

use crate::{
adapters::{HeadingAdapter, HeadingMeta, SyntaxHighlighterAdapter},
Expand Down Expand Up @@ -69,8 +69,7 @@ fn exercise_full_api() {
let extension = extension.shortcodes(true);

let _extension = extension
.wikilinks_title_after_pipe(true)
.wikilinks_title_before_pipe(true)
.wikilinks(WikiLinksMode::UrlFirst)
.underline(true)
.subscript(true)
.spoiler(true)
Expand Down
3 changes: 2 additions & 1 deletion src/tests/commonmark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use self::nodes::{Ast, LineColumn, ListType, NodeList};

use super::*;
use ntest::test_case;
use parser::WikiLinksMode;

#[test]
fn commonmark_removes_redundant_strong() {
Expand Down Expand Up @@ -83,7 +84,7 @@ fn math(markdown: &str, cm: &str) {
#[test_case("This [[url|link label]] that", "This [[url|link%20label]] that\n")]
fn wikilinks(markdown: &str, cm: &str) {
let mut options = Options::default();
options.extension.wikilinks_title_before_pipe = true;
options.extension.wikilinks = Some(WikiLinksMode::TitleFirst);

commonmark(markdown, cm, Some(&options));
}
Expand Down
Loading
Loading