Improvements to Python F-strings and string prefixes (#1642) This PR adds support for [string interpolation](https://www.python.org/dev/peps/pep-0498/) (aka. f-strings) and makes the [string prefixes](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals) part of the string. Resolves #1636. ### Known issues Assumes that strings inside the interpolation expression are 'nice'. So strings with unfortunate numbers of curley braces will cause incorrect highlighting: E.g.: `f"{'}'}"`.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
diff --git a/components/prism-python.js b/components/prism-python.js
index b326a5c..ea1a515 100644
--- a/components/prism-python.js
+++ b/components/prism-python.js
@@ -3,13 +3,36 @@ Prism.languages.python = {
pattern: /(^|[^\\])#.*/,
lookbehind: true
},
+ 'string-interpolation': {
+ pattern: /(?:f|rf|fr)(?:("""|''')[\s\S]+?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,
+ greedy: true,
+ inside: {
+ 'interpolation': {
+ // "{" <expression> <optional "!s", "!r", or "!a"> <optional ":" format specifier> "}"
+ pattern: /((?:^|[^{])(?:{{)*){(?!{)(?:[^{}]|{(?!{)(?:[^{}]|{(?!{)(?:[^{}])+})+})+}/,
+ lookbehind: true,
+ inside: {
+ 'format-spec': {
+ pattern: /(:)[^:(){}]+(?=}$)/,
+ lookbehind: true
+ },
+ 'conversion-option': {
+ pattern: /![sra](?=[:}]$)/,
+ alias: 'punctuation'
+ },
+ rest: null
+ }
+ },
+ 'string': /[\s\S]+/
+ }
+ },
'triple-quoted-string': {
- pattern: /("""|''')[\s\S]+?\1/,
+ pattern: /(?:[rub]|rb|br)?("""|''')[\s\S]+?\1/i,
greedy: true,
alias: 'string'
},
'string': {
- pattern: /("|')(?:\\.|(?!\1)[^\\\r\n])*\1/,
+ pattern: /(?:[rub]|rb|br)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,
greedy: true
},
'function': {
@@ -35,3 +58,5 @@ Prism.languages.python = {
'operator': /[-+%=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,
'punctuation': /[{}[\];(),.:]/
};
+
+Prism.languages.python['string-interpolation'].inside['interpolation'].inside.rest = Prism.languages.python;
diff --git a/components/prism-python.min.js b/components/prism-python.min.js
index 8956dae..7f9ee42 100644
--- a/components/prism-python.min.js
+++ b/components/prism-python.min.js
@@ -1 +1 @@
-Prism.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0},"triple-quoted-string":{pattern:/("""|''')[\s\S]+?\1/,greedy:!0,alias:"string"},string:{pattern:/("|')(?:\\.|(?!\1)[^\\\r\n])*\1/,greedy:!0},"function":{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^\s*)@\w+(?:\.\w+)*/i,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:and|as|assert|async|await|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,"boolean":/\b(?:True|False|None)\b/,number:/(?:\b(?=\d)|\B(?=\.))(?:0[bo])?(?:(?:\d|0x[\da-f])[\da-f]*\.?\d*|\.\d+)(?:e[+-]?\d+)?j?\b/i,operator:/[-+%=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/};
\ No newline at end of file
+Prism.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0},"string-interpolation":{pattern:/(?:f|rf|fr)(?:("""|''')[\s\S]+?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^{])(?:{{)*){(?!{)(?:[^{}]|{(?!{)(?:[^{}]|{(?!{)(?:[^{}])+})+})+}/,lookbehind:!0,inside:{"format-spec":{pattern:/(:)[^:(){}]+(?=}$)/,lookbehind:!0},"conversion-option":{pattern:/![sra](?=[:}]$)/,alias:"punctuation"},rest:null}},string:/[\s\S]+/}},"triple-quoted-string":{pattern:/(?:[rub]|rb|br)?("""|''')[\s\S]+?\1/i,greedy:!0,alias:"string"},string:{pattern:/(?:[rub]|rb|br)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,greedy:!0},"function":{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^\s*)@\w+(?:\.\w+)*/i,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:and|as|assert|async|await|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,"boolean":/\b(?:True|False|None)\b/,number:/(?:\b(?=\d)|\B(?=\.))(?:0[bo])?(?:(?:\d|0x[\da-f])[\da-f]*\.?\d*|\.\d+)(?:e[+-]?\d+)?j?\b/i,operator:/[-+%=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/},Prism.languages.python["string-interpolation"].inside.interpolation.inside.rest=Prism.languages.python;
\ No newline at end of file
diff --git a/examples/prism-python.html b/examples/prism-python.html
index ca7a397..ce6efc0 100644
--- a/examples/prism-python.html
+++ b/examples/prism-python.html
@@ -57,8 +57,5 @@ if __name__ == '__main__':
If a failure is listed here, it doesn’t mean it will never be fixed. This is more of a “known bugs” list, just with a certain type of bug.
</p>
-<h3>Triple-quoted strings with what look like strings inside</h3>
-<pre><code>def antique(string):
- """Replace anachronistic Latin "j" with "i"."""
- return string.replace("j", "i").replace("J", "I")
- </code></pre>
+<h3>Interpolation expressions containing strings with <code>{</code> or <code>}</code></h3>
+<pre><code>f"{'}'}"</code></pre>
diff --git a/tests/languages/python/string-interpolation_feature.test b/tests/languages/python/string-interpolation_feature.test
new file mode 100644
index 0000000..789cb83
--- /dev/null
+++ b/tests/languages/python/string-interpolation_feature.test
@@ -0,0 +1,147 @@
+f'The value is {value}.'
+
+f"The value is {'4'}."
+
+f'input={value!s:#06x}'
+
+f'{{{4*10}}}'
+
+fr'x={4*10}\n'
+
+f'''{x
++1}'''
+
+f'mapping is { {a:b for (a, b) in ((1, 2), (3, 4))} }'
+
+f'{(lambda x: x*2)(3)}'
+
+----------------------------------------------------
+
+[
+ ["string-interpolation", [
+ ["string", "f'The value is "],
+ ["interpolation", [
+ ["punctuation", "{"],
+ "value",
+ ["punctuation", "}"]
+ ]],
+ ["string", ".'"]
+ ]],
+
+ ["string-interpolation", [
+ ["string", "f\"The value is "],
+ ["interpolation", [
+ ["punctuation", "{"],
+ ["string", "'4'"],
+ ["punctuation", "}"]
+ ]],
+ ["string", ".\""]
+ ]],
+
+ ["string-interpolation", [
+ ["string", "f'input="],
+ ["interpolation", [
+ ["punctuation", "{"],
+ "value",
+ ["conversion-option", "!s"],
+ ["punctuation", ":"],
+ ["format-spec", "#06x"],
+ ["punctuation", "}"]
+ ]],
+ ["string", "'"]
+ ]],
+
+ ["string-interpolation", [
+ ["string", "f'{{"],
+ ["interpolation", [
+ ["punctuation", "{"],
+ ["number", "4"],
+ ["operator", "*"],
+ ["number", "10"],
+ ["punctuation", "}"]
+ ]],
+ ["string", "}}'"]
+ ]],
+
+ ["string-interpolation", [
+ ["string", "fr'x="],
+ ["interpolation", [
+ ["punctuation", "{"],
+ ["number", "4"],
+ ["operator", "*"],
+ ["number", "10"],
+ ["punctuation", "}"]
+ ]],
+ ["string", "\\n'"]
+ ]],
+
+ ["string-interpolation", [
+ ["string", "f'''"],
+ ["interpolation", [
+ ["punctuation", "{"],
+ "x\r\n",
+ ["operator", "+"],
+ ["number", "1"],
+ ["punctuation", "}"]
+ ]],
+ ["string", "'''"]
+ ]],
+
+ ["string-interpolation", [
+ ["string", "f'mapping is "],
+ ["interpolation", [
+ ["punctuation", "{"],
+ ["punctuation", "{"],
+ "a",
+ ["punctuation", ":"],
+ "b ",
+ ["keyword", "for"],
+ ["punctuation", "("],
+ "a",
+ ["punctuation", ","],
+ " b",
+ ["punctuation", ")"],
+ ["keyword", "in"],
+ ["punctuation", "("],
+ ["punctuation", "("],
+ ["number", "1"],
+ ["punctuation", ","],
+ ["number", "2"],
+ ["punctuation", ")"],
+ ["punctuation", ","],
+ ["punctuation", "("],
+ ["number", "3"],
+ ["punctuation", ","],
+ ["number", "4"],
+ ["punctuation", ")"],
+ ["punctuation", ")"],
+ ["punctuation", "}"],
+ ["punctuation", "}"]
+ ]],
+ ["string", "'"]
+ ]],
+
+ ["string-interpolation", [
+ ["string", "f'"],
+ ["interpolation", [
+ ["punctuation", "{"],
+ ["punctuation", "("],
+ ["keyword", "lambda"],
+ " x",
+ ["punctuation", ":"],
+ " x",
+ ["operator", "*"],
+ ["number", "2"],
+ ["punctuation", ")"],
+ ["punctuation", "("],
+ ["number", "3"],
+ ["punctuation", ")"],
+ ["punctuation", "}"]
+ ]],
+ ["string", "'"]
+ ]]
+]
+
+----------------------------------------------------
+
+Checks for string interpolation.
\ No newline at end of file
diff --git a/tests/languages/python/string_feature.test b/tests/languages/python/string_feature.test
index 9e21c4d..0bb5119 100644
--- a/tests/languages/python/string_feature.test
+++ b/tests/languages/python/string_feature.test
@@ -4,6 +4,11 @@
'fo\'obar'
"fo\" # comment obar"
+r"\n"
+b'foo'
+rb"foo\n"
+u"foo"
+
----------------------------------------------------
[
@@ -11,7 +16,12 @@
["string", "\"fo\\\"obar\""],
["string", "''"],
["string", "'fo\\'obar'"],
- ["string", "\"fo\\\" # comment obar\""]
+ ["string", "\"fo\\\" # comment obar\""],
+
+ ["string", "r\"\\n\""],
+ ["string", "b'foo'"],
+ ["string", "rb\"foo\\n\""],
+ ["string", "u\"foo\""]
]
----------------------------------------------------