Debian Codegraph @

texmf-dist/doc/support/cluttex/src/safe-name.sml

raw
1 structure SafeName:
2 sig
3 val escapeJobname: string -> string
4 val safeInput: {name: string, isPdfTeX: bool} -> string
5 end =
6 struct
7 local
8 fun escapeChar #" " = "_"
9 | escapeChar c =
10 if
11 Char.isSpace c orelse c = #"\"" orelse c = #"$" orelse c = #"%"
12 orelse c = #"&" orelse c = #"'" orelse c = #"(" orelse c = #")"
13 orelse c = #";" orelse c = #"<" orelse c = #">" orelse c = #"\\"
14 orelse c = #"^" orelse c = #"`" orelse c = #"|"
15 then
16 let
17 val x = Char.ord c
18 val s = Int.fmt StringCvt.HEX x
19 in
20 if x <= 0xf then "_0" ^ s else "_" ^ s
21 end
22 else
23 String.str c
24 in
25 fun escapeJobname name = String.translate escapeChar name
26 end
27
28 local
29 fun handleSpecialChar #"\\" = "~\\\\"
30 | handleSpecialChar #"%" = "~\\%"
31 | handleSpecialChar #"^" = "~\\^"
32 | handleSpecialChar #"{" = "~\\{"
33 | handleSpecialChar #"}" = "~\\}"
34 | handleSpecialChar #"~" = "~\\~"
35 | handleSpecialChar #"#" = "~\\#"
36 | handleSpecialChar c = String.str c
37 fun handleSpaces s =
38 let
39 fun go (s, acc) =
40 if Substring.isEmpty s then
41 Substring.concat (List.rev acc)
42 else
43 let
44 val (a, b) = Substring.splitl (fn c => c <> #" ") s
45 val (c, d) = Substring.splitl (fn c => c = #" ") b
46 val c' = Substring.full (String.concatWith "~"
47 (List.map String.str (Substring.explode c)))
48 in
49 go (d, c' :: a :: acc)
50 end
51 in
52 go (Substring.full s, [])
53 end
54 fun handleNonAscii s =
55 let
56 fun go (s, acc) =
57 if Substring.isEmpty s then
58 Substring.concat (List.rev acc)
59 else
60 let
61 val (a, b) = Substring.splitl Char.isAscii s
62 val (c, d) = Substring.splitl (Bool.not o Char.isAscii) b
63 val c' =
64 if Substring.isEmpty c then c
65 else Substring.full ("\\detokenize{" ^ Substring.string c ^ "}")
66 in
67 go (d, c' :: a :: acc)
68 end
69 in
70 go (Substring.full s, [])
71 end
72 in
73 fun safeInput {name, isPdfTeX} =
74 let
75 val escaped = handleSpaces (String.translate handleSpecialChar name)
76 val escaped = if isPdfTeX then handleNonAscii escaped else escaped
77 in
78 if name = escaped then
79 "\\input\"" ^ name ^ "\""
80 else
81 "\\begingroup\\escapechar-1\\let~\\string\\edef\\x{\"" ^ escaped
82 ^ "\" }\\expandafter\\endgroup\\expandafter\\input\\x"
83 end
84 end
85 end;