Skip to content

Commit 9430abd

Browse files
committed
slack: tweak escaping
1 parent d29d6a6 commit 9430abd

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

lib/mrkdwn.ml

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,21 @@
11
open Omd
22
open Base
33

4-
let escape_url_chars str =
5-
let repl c = String.substr_replace_all ~pattern:(Char.to_string c) ~with_:(Printf.sprintf "\\%c" c) in
6-
str |> repl '<' |> repl '>' |> repl '|'
4+
let escape_url_chars = Staged.unstage @@ String.Escaping.escape ~escapeworthy:[ '<'; '>'; '|' ] ~escape_char:'\\'
5+
6+
(* https://api.slack.com/reference/surfaces/formatting#escaping *)
7+
let escape_mrkdwn =
8+
String.concat_map ~f:(function
9+
| '<' -> "&lt;"
10+
| '>' -> "&gt;"
11+
| '&' -> "&amp;"
12+
| c -> String.make 1 c)
13+
14+
(* omd escapes parentheses in text (bug?) *)
15+
let unescape_omd =
16+
Staged.unstage @@ String.Escaping.unescape_gen_exn ~escapeworthy_map:[ '(', '('; ')', ')' ] ~escape_char:'\\'
17+
18+
let transform_text s = escape_mrkdwn @@ unescape_omd s
719

820
let rec transform_list = List.map ~f:transform
921

@@ -33,6 +45,7 @@ and transform = function
3345
| Blockquote t -> Blockquote (transform_list t)
3446
| Img (alt, src, title) -> transform @@ Url (src, [ Text alt ], title)
3547
| Code_block (_, str) -> Code_block ("", str)
36-
| (Text _ | Code _ | Br | Hr | NL | Ref _ | Img_ref _ | Raw _ | Raw_block _ | X _) as e -> e
48+
| Text s -> Text (transform_text s)
49+
| (Code _ | Br | Hr | NL | Ref _ | Img_ref _ | Raw _ | Raw_block _ | X _) as e -> e
3750

3851
let mrkdwn_of_markdown str = to_markdown @@ transform_list @@ of_string str

0 commit comments

Comments
 (0)