markly/parser/span/
emphasis.rs1use parser::span::parse_spans;
2use parser::Span;
3use parser::Span::Emphasis;
4use regex::Regex;
5
6pub fn parse_emphasis(text: &str) -> Option<(Span, usize)> {
7 lazy_static! {
8 static ref EMPHASIS_UNDERSCORE: Regex = Regex::new(r"^_(?P<text>.+?)_").unwrap();
9 static ref EMPHASIS_STAR: Regex = Regex::new(r"^\*(?P<text>.+?)\*").unwrap();
10 }
11
12 if EMPHASIS_UNDERSCORE.is_match(text) {
13 let caps = EMPHASIS_UNDERSCORE.captures(text).unwrap();
14 let t = caps.name("text").unwrap().as_str();
15 return Some((Emphasis(parse_spans(t)), t.len() + 2));
16 } else if EMPHASIS_STAR.is_match(text) {
17 let caps = EMPHASIS_STAR.captures(text).unwrap();
18 let t = caps.name("text").unwrap().as_str();
19 return Some((Emphasis(parse_spans(t)), t.len() + 2));
20 }
21 None
22}
23
24#[cfg(test)]
25mod test {
26 use super::parse_emphasis;
27 use parser::Span::{Emphasis, Text};
28
29 #[test]
30 fn finds_emphasis() {
31 assert_eq!(
32 parse_emphasis("_testing things_ test"),
33 Some((Emphasis(vec![Text("testing things".to_owned())]), 16))
34 );
35
36 assert_eq!(
37 parse_emphasis("*testing things* test"),
38 Some((Emphasis(vec![Text("testing things".to_owned())]), 16))
39 );
40
41 assert_eq!(
42 parse_emphasis("_testing things_ things_ test"),
43 Some((Emphasis(vec![Text("testing things".to_owned())]), 16))
44 );
45
46 assert_eq!(
47 parse_emphasis("_w_ things_ test"),
48 Some((Emphasis(vec![Text("w".to_owned())]), 3))
49 );
50
51 assert_eq!(
52 parse_emphasis("*w* things* test"),
53 Some((Emphasis(vec![Text("w".to_owned())]), 3))
54 );
55
56 assert_eq!(
57 parse_emphasis("_w__ testing things test"),
58 Some((Emphasis(vec![Text("w".to_owned())]), 3))
59 );
60 }
61
62 #[test]
63 fn no_false_positives() {
64 assert_eq!(parse_emphasis("__ testing things test"), None);
65 assert_eq!(parse_emphasis("_ test"), None);
66 }
67
68 #[test]
69 fn no_early_matching() {
70 assert_eq!(parse_emphasis("were _testing things_ test"), None);
71 assert_eq!(parse_emphasis("were *testing things* test"), None);
72 }
73}