eric6/ThirdParty/Pygments/pygments/lexers/matlab.py

changeset 7701
25f42e208e08
parent 7547
21b0534faebc
child 7983
54c5cfbb1e29
equal deleted inserted replaced
7700:a3cf077a8db3 7701:25f42e208e08
3 pygments.lexers.matlab 3 pygments.lexers.matlab
4 ~~~~~~~~~~~~~~~~~~~~~~ 4 ~~~~~~~~~~~~~~~~~~~~~~
5 5
6 Lexers for Matlab and related languages. 6 Lexers for Matlab and related languages.
7 7
8 :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS. 8 :copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS.
9 :license: BSD, see LICENSE for details. 9 :license: BSD, see LICENSE for details.
10 """ 10 """
11 11
12 import re 12 import re
13 13
14 from pygments.lexer import Lexer, RegexLexer, bygroups, words, do_insertions 14 from pygments.lexer import Lexer, RegexLexer, bygroups, default, words, \
15 do_insertions
15 from pygments.token import Text, Comment, Operator, Keyword, Name, String, \ 16 from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
16 Number, Punctuation, Generic, Whitespace 17 Number, Punctuation, Generic, Whitespace
17 18
18 from pygments.lexers import _scilab_builtins 19 from pygments.lexers import _scilab_builtins
19 20
43 # 44 #
44 # elfun: Elementary math functions 45 # elfun: Elementary math functions
45 # specfun: Special Math functions 46 # specfun: Special Math functions
46 # elmat: Elementary matrices and matrix manipulation 47 # elmat: Elementary matrices and matrix manipulation
47 # 48 #
48 # taken from Matlab version 7.4.0.336 (R2007a) 49 # taken from Matlab version 9.4 (R2018a)
49 # 50 #
50 elfun = ("sin", "sind", "sinh", "asin", "asind", "asinh", "cos", "cosd", "cosh", 51 elfun = ("sin", "sind", "sinh", "asin", "asind", "asinh", "cos", "cosd", "cosh",
51 "acos", "acosd", "acosh", "tan", "tand", "tanh", "atan", "atand", "atan2", 52 "acos", "acosd", "acosh", "tan", "tand", "tanh", "atan", "atand", "atan2",
52 "atanh", "sec", "secd", "sech", "asec", "asecd", "asech", "csc", "cscd", 53 "atan2d", "atanh", "sec", "secd", "sech", "asec", "asecd", "asech", "csc", "cscd",
53 "csch", "acsc", "acscd", "acsch", "cot", "cotd", "coth", "acot", "acotd", 54 "csch", "acsc", "acscd", "acsch", "cot", "cotd", "coth", "acot", "acotd",
54 "acoth", "hypot", "exp", "expm1", "log", "log1p", "log10", "log2", "pow2", 55 "acoth", "hypot", "deg2rad", "rad2deg", "exp", "expm1", "log", "log1p", "log10", "log2", "pow2",
55 "realpow", "reallog", "realsqrt", "sqrt", "nthroot", "nextpow2", "abs", 56 "realpow", "reallog", "realsqrt", "sqrt", "nthroot", "nextpow2", "abs",
56 "angle", "complex", "conj", "imag", "real", "unwrap", "isreal", "cplxpair", 57 "angle", "complex", "conj", "imag", "real", "unwrap", "isreal", "cplxpair",
57 "fix", "floor", "ceil", "round", "mod", "rem", "sign") 58 "fix", "floor", "ceil", "round", "mod", "rem", "sign")
58 specfun = ("airy", "besselj", "bessely", "besselh", "besseli", "besselk", "beta", 59 specfun = ("airy", "besselj", "bessely", "besselh", "besseli", "besselk", "beta",
59 "betainc", "betaln", "ellipj", "ellipke", "erf", "erfc", "erfcx", 60 "betainc", "betaincinv", "betaln", "ellipj", "ellipke", "erf", "erfc", "erfcx",
60 "erfinv", "expint", "gamma", "gammainc", "gammaln", "psi", "legendre", 61 "erfinv", "erfcinv", "expint", "gamma", "gammainc", "gammaincinv", "gammaln", "psi", "legendre",
61 "cross", "dot", "factor", "isprime", "primes", "gcd", "lcm", "rat", 62 "cross", "dot", "factor", "isprime", "primes", "gcd", "lcm", "rat",
62 "rats", "perms", "nchoosek", "factorial", "cart2sph", "cart2pol", 63 "rats", "perms", "nchoosek", "factorial", "cart2sph", "cart2pol",
63 "pol2cart", "sph2cart", "hsv2rgb", "rgb2hsv") 64 "pol2cart", "sph2cart", "hsv2rgb", "rgb2hsv")
64 elmat = ("zeros", "ones", "eye", "repmat", "rand", "randn", "linspace", "logspace", 65 elmat = ("zeros", "ones", "eye", "repmat", "repelem", "linspace", "logspace",
65 "freqspace", "meshgrid", "accumarray", "size", "length", "ndims", "numel", 66 "freqspace", "meshgrid", "accumarray", "size", "length", "ndims", "numel",
66 "disp", "isempty", "isequal", "isequalwithequalnans", "cat", "reshape", 67 "disp", "isempty", "isequal", "isequaln", "cat", "reshape",
67 "diag", "blkdiag", "tril", "triu", "fliplr", "flipud", "flipdim", "rot90", 68 "diag", "blkdiag", "tril", "triu", "fliplr", "flipud", "flip", "rot90",
68 "find", "end", "sub2ind", "ind2sub", "bsxfun", "ndgrid", "permute", 69 "find", "end", "sub2ind", "ind2sub", "bsxfun", "ndgrid", "permute",
69 "ipermute", "shiftdim", "circshift", "squeeze", "isscalar", "isvector", 70 "ipermute", "shiftdim", "circshift", "squeeze", "isscalar", "isvector",
70 "ans", "eps", "realmax", "realmin", "pi", "i", "inf", "nan", "isnan", 71 "isrow", "iscolumn", "ismatrix", "eps", "realmax", "realmin", "intmax", "intmin", "flintmax", "pi", "i", "inf", "nan", "isnan",
71 "isinf", "isfinite", "j", "why", "compan", "gallery", "hadamard", "hankel", 72 "isinf", "isfinite", "j", "true", "false", "compan", "gallery", "hadamard", "hankel",
72 "hilb", "invhilb", "magic", "pascal", "rosser", "toeplitz", "vander", 73 "hilb", "invhilb", "magic", "pascal", "rosser", "toeplitz", "vander",
73 "wilkinson") 74 "wilkinson")
74 75
75 _operators = r'-|==|~=|<=|>=|<|>|&&|&|~|\|\|?|\.\*|\*|\+|\.\^|\.\\|\.\/|\/|\\' 76 _operators = r'-|==|~=|<=|>=|<|>|&&|&|~|\|\|?|\.\*|\*|\+|\.\^|\.\\|\./|/|\\'
76 77
77 tokens = { 78 tokens = {
78 'root': [ 79 'root': [
79 # line starting with '!' is sent as a system command. not sure what 80 # line starting with '!' is sent as a system command. not sure what
80 # label to use... 81 # label to use...
81 (r'^!.*', String.Other), 82 (r'^!.*', String.Other),
82 (r'%\{\s*\n', Comment.Multiline, 'blockcomment'), 83 (r'%\{\s*\n', Comment.Multiline, 'blockcomment'),
83 (r'%.*$', Comment), 84 (r'%.*$', Comment),
84 (r'^\s*function\b', Keyword, 'deffunc'), 85 (r'^\s*function\b', Keyword, 'deffunc'),
85 86
86 # from 'iskeyword' on version 7.11 (R2010): 87 # from 'iskeyword' on version 9.4 (R2018a):
87 # Check that there is no preceding dot, as keywords are valid field 88 # Check that there is no preceding dot, as keywords are valid field
88 # names. 89 # names.
89 (words(('break', 'case', 'catch', 'classdef', 'continue', 'else', 90 (words(('break', 'case', 'catch', 'classdef', 'continue', 'else',
90 'elseif', 'end', 'enumerated', 'events', 'for', 'function', 91 'elseif', 'end', 'for', 'function',
91 'global', 'if', 'methods', 'otherwise', 'parfor', 92 'global', 'if', 'otherwise', 'parfor',
92 'persistent', 'properties', 'return', 'spmd', 'switch', 93 'persistent', 'return', 'spmd', 'switch',
93 'try', 'while'), 94 'try', 'while'),
94 prefix=r'(?<!\.)', suffix=r'\b'), 95 prefix=r'(?<!\.)', suffix=r'\b'),
95 Keyword), 96 Keyword),
96 97
97 ("(" + "|".join(elfun + specfun + elmat) + r')\b', Name.Builtin), 98 ("(" + "|".join(elfun + specfun + elmat) + r')\b', Name.Builtin),
98 99
99 # line continuation with following comment: 100 # line continuation with following comment:
100 (r'\.\.\..*$', Comment), 101 (r'(\.\.\.)(.*)$', bygroups(Keyword, Comment)),
101 102
102 # command form: 103 # command form:
103 # "How MATLAB Recognizes Command Syntax" specifies that an operator 104 # "How MATLAB Recognizes Command Syntax" specifies that an operator
104 # is recognized if it is either surrounded by spaces or by no 105 # is recognized if it is either surrounded by spaces or by no
105 # spaces on both sides; only the former case matters for us. (This 106 # spaces on both sides; only the former case matters for us. (This
106 # allows distinguishing `cd ./foo` from `cd ./ foo`.) 107 # allows distinguishing `cd ./foo` from `cd ./ foo`.)
107 (r'(?:^|(?<=;))(\s*)(\w+)(\s+)(?!=|\(|(%s)\s+)' % _operators, 108 (r'(?:^|(?<=;))(\s*)(\w+)(\s+)(?!=|\(|(?:%s)\s+)' % _operators,
108 bygroups(Text, Name, Text), 'commandargs'), 109 bygroups(Text, Name, Text), 'commandargs'),
109 110
110 # operators: 111 # operators:
111 (_operators, Operator), 112 (_operators, Operator),
112 113
145 ], 146 ],
146 'string': [ 147 'string': [
147 (r"[^']*'", String, '#pop'), 148 (r"[^']*'", String, '#pop'),
148 ], 149 ],
149 'commandargs': [ 150 'commandargs': [
151 # If an equal sign or other operator is encountered, this
152 # isn't a command. It might be a variable assignment or
153 # comparison operation with multiple spaces before the
154 # equal sign or operator
155 (r"=", Punctuation, '#pop'),
156 (_operators, Operator, '#pop'),
150 (r"[ \t]+", Text), 157 (r"[ \t]+", Text),
151 ("'[^']*'", String), 158 ("'[^']*'", String),
152 (r"[^';\s]+", String), 159 (r"[^';\s]+", String),
153 (";?", Punctuation, '#pop'), 160 (";", Punctuation, '#pop'),
161 default('#pop'),
154 ] 162 ]
155 } 163 }
156 164
157 def analyse_text(text): 165 def analyse_text(text):
158 # function declaration. 166 # function declaration.
185 def get_tokens_unprocessed(self, text): 193 def get_tokens_unprocessed(self, text):
186 mlexer = MatlabLexer(**self.options) 194 mlexer = MatlabLexer(**self.options)
187 195
188 curcode = '' 196 curcode = ''
189 insertions = [] 197 insertions = []
198 continuation = False
190 199
191 for match in line_re.finditer(text): 200 for match in line_re.finditer(text):
192 line = match.group() 201 line = match.group()
193 202
194 if line.startswith('>> '): 203 if line.startswith('>> '):
207 216
208 # without is showing error on same line as before...? 217 # without is showing error on same line as before...?
209 # line = "\n" + line 218 # line = "\n" + line
210 token = (0, Generic.Traceback, line) 219 token = (0, Generic.Traceback, line)
211 insertions.append((idx, [token])) 220 insertions.append((idx, [token]))
212 221 elif continuation:
222 # line_start is the length of the most recent prompt symbol
223 line_start = len(insertions[-1][-1][-1])
224 # Set leading spaces with the length of the prompt to be a generic prompt
225 # This keeps code aligned when prompts are removed, say with some Javascript
226 if line.startswith(' '*line_start):
227 insertions.append((len(curcode),
228 [(0, Generic.Prompt, line[:line_start])]))
229 curcode += line[line_start:]
230 else:
231 curcode += line
213 else: 232 else:
214 if curcode: 233 if curcode:
215 for item in do_insertions( 234 yield from do_insertions(
216 insertions, mlexer.get_tokens_unprocessed(curcode)): 235 insertions, mlexer.get_tokens_unprocessed(curcode))
217 yield item
218 curcode = '' 236 curcode = ''
219 insertions = [] 237 insertions = []
220 238
221 yield match.start(), Generic.Output, line 239 yield match.start(), Generic.Output, line
222 240
241 # Does not allow continuation if a comment is included after the ellipses.
242 # Continues any line that ends with ..., even comments (lines that start with %)
243 if line.strip().endswith('...'):
244 continuation = True
245 else:
246 continuation = False
247
223 if curcode: # or item: 248 if curcode: # or item:
224 for item in do_insertions( 249 yield from do_insertions(
225 insertions, mlexer.get_tokens_unprocessed(curcode)): 250 insertions, mlexer.get_tokens_unprocessed(curcode))
226 yield item
227 251
228 252
229 class OctaveLexer(RegexLexer): 253 class OctaveLexer(RegexLexer):
230 """ 254 """
231 For GNU Octave source code. 255 For GNU Octave source code.

eric ide

mercurial