matlab.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. # -*- coding: utf-8 -*-
  2. """
  3. pygments.lexers.matlab
  4. ~~~~~~~~~~~~~~~~~~~~~~
  5. Lexers for Matlab and related languages.
  6. :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
  7. :license: BSD, see LICENSE for details.
  8. """
  9. import re
  10. from pygments.lexer import Lexer, RegexLexer, bygroups, words, do_insertions
  11. from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
  12. Number, Punctuation, Generic, Whitespace
  13. from pygments.lexers import _scilab_builtins
  14. __all__ = ['MatlabLexer', 'MatlabSessionLexer', 'OctaveLexer', 'ScilabLexer']
  15. class MatlabLexer(RegexLexer):
  16. """
  17. For Matlab source code.
  18. .. versionadded:: 0.10
  19. """
  20. name = 'Matlab'
  21. aliases = ['matlab']
  22. filenames = ['*.m']
  23. mimetypes = ['text/matlab']
  24. #
  25. # These lists are generated automatically.
  26. # Run the following in bash shell:
  27. #
  28. # for f in elfun specfun elmat; do
  29. # echo -n "$f = "
  30. # matlab -nojvm -r "help $f;exit;" | perl -ne \
  31. # 'push(@c,$1) if /^ (\w+)\s+-/; END {print q{["}.join(q{","},@c).qq{"]\n};}'
  32. # done
  33. #
  34. # elfun: Elementary math functions
  35. # specfun: Special Math functions
  36. # elmat: Elementary matrices and matrix manipulation
  37. #
  38. # taken from Matlab version 7.4.0.336 (R2007a)
  39. #
  40. elfun = ("sin", "sind", "sinh", "asin", "asind", "asinh", "cos", "cosd", "cosh",
  41. "acos", "acosd", "acosh", "tan", "tand", "tanh", "atan", "atand", "atan2",
  42. "atanh", "sec", "secd", "sech", "asec", "asecd", "asech", "csc", "cscd",
  43. "csch", "acsc", "acscd", "acsch", "cot", "cotd", "coth", "acot", "acotd",
  44. "acoth", "hypot", "exp", "expm1", "log", "log1p", "log10", "log2", "pow2",
  45. "realpow", "reallog", "realsqrt", "sqrt", "nthroot", "nextpow2", "abs",
  46. "angle", "complex", "conj", "imag", "real", "unwrap", "isreal", "cplxpair",
  47. "fix", "floor", "ceil", "round", "mod", "rem", "sign")
  48. specfun = ("airy", "besselj", "bessely", "besselh", "besseli", "besselk", "beta",
  49. "betainc", "betaln", "ellipj", "ellipke", "erf", "erfc", "erfcx",
  50. "erfinv", "expint", "gamma", "gammainc", "gammaln", "psi", "legendre",
  51. "cross", "dot", "factor", "isprime", "primes", "gcd", "lcm", "rat",
  52. "rats", "perms", "nchoosek", "factorial", "cart2sph", "cart2pol",
  53. "pol2cart", "sph2cart", "hsv2rgb", "rgb2hsv")
  54. elmat = ("zeros", "ones", "eye", "repmat", "rand", "randn", "linspace", "logspace",
  55. "freqspace", "meshgrid", "accumarray", "size", "length", "ndims", "numel",
  56. "disp", "isempty", "isequal", "isequalwithequalnans", "cat", "reshape",
  57. "diag", "blkdiag", "tril", "triu", "fliplr", "flipud", "flipdim", "rot90",
  58. "find", "end", "sub2ind", "ind2sub", "bsxfun", "ndgrid", "permute",
  59. "ipermute", "shiftdim", "circshift", "squeeze", "isscalar", "isvector",
  60. "ans", "eps", "realmax", "realmin", "pi", "i", "inf", "nan", "isnan",
  61. "isinf", "isfinite", "j", "why", "compan", "gallery", "hadamard", "hankel",
  62. "hilb", "invhilb", "magic", "pascal", "rosser", "toeplitz", "vander",
  63. "wilkinson")
  64. _operators = r'-|==|~=|<=|>=|<|>|&&|&|~|\|\|?|\.\*|\*|\+|\.\^|\.\\|\.\/|\/|\\'
  65. tokens = {
  66. 'root': [
  67. # line starting with '!' is sent as a system command. not sure what
  68. # label to use...
  69. (r'^!.*', String.Other),
  70. (r'%\{\s*\n', Comment.Multiline, 'blockcomment'),
  71. (r'%.*$', Comment),
  72. (r'^\s*function\b', Keyword, 'deffunc'),
  73. # from 'iskeyword' on version 7.11 (R2010):
  74. # Check that there is no preceding dot, as keywords are valid field
  75. # names.
  76. (words(('break', 'case', 'catch', 'classdef', 'continue', 'else',
  77. 'elseif', 'end', 'enumerated', 'events', 'for', 'function',
  78. 'global', 'if', 'methods', 'otherwise', 'parfor',
  79. 'persistent', 'properties', 'return', 'spmd', 'switch',
  80. 'try', 'while'),
  81. prefix=r'(?<!\.)', suffix=r'\b'),
  82. Keyword),
  83. ("(" + "|".join(elfun + specfun + elmat) + r')\b', Name.Builtin),
  84. # line continuation with following comment:
  85. (r'\.\.\..*$', Comment),
  86. # command form:
  87. # "How MATLAB Recognizes Command Syntax" specifies that an operator
  88. # is recognized if it is either surrounded by spaces or by no
  89. # spaces on both sides; only the former case matters for us. (This
  90. # allows distinguishing `cd ./foo` from `cd ./ foo`.)
  91. (r'(?:^|(?<=;))(\s*)(\w+)(\s+)(?!=|\(|(%s)\s+)' % _operators,
  92. bygroups(Text, Name, Text), 'commandargs'),
  93. # operators:
  94. (_operators, Operator),
  95. # numbers (must come before punctuation to handle `.5`; cannot use
  96. # `\b` due to e.g. `5. + .5`).
  97. (r'(?<!\w)((\d+\.\d*)|(\d*\.\d+))([eEf][+-]?\d+)?(?!\w)', Number.Float),
  98. (r'\b\d+[eEf][+-]?[0-9]+\b', Number.Float),
  99. (r'\b\d+\b', Number.Integer),
  100. # punctuation:
  101. (r'\[|\]|\(|\)|\{|\}|:|@|\.|,', Punctuation),
  102. (r'=|:|;', Punctuation),
  103. # quote can be transpose, instead of string:
  104. # (not great, but handles common cases...)
  105. (r'(?<=[\w)\].])\'+', Operator),
  106. (r'"(""|[^"])*"', String),
  107. (r'(?<![\w)\].])\'', String, 'string'),
  108. (r'[a-zA-Z_]\w*', Name),
  109. (r'.', Text),
  110. ],
  111. 'blockcomment': [
  112. (r'^\s*%\}', Comment.Multiline, '#pop'),
  113. (r'^.*\n', Comment.Multiline),
  114. (r'.', Comment.Multiline),
  115. ],
  116. 'deffunc': [
  117. (r'(\s*)(?:(.+)(\s*)(=)(\s*))?(.+)(\()(.*)(\))(\s*)',
  118. bygroups(Whitespace, Text, Whitespace, Punctuation,
  119. Whitespace, Name.Function, Punctuation, Text,
  120. Punctuation, Whitespace), '#pop'),
  121. # function with no args
  122. (r'(\s*)([a-zA-Z_]\w*)', bygroups(Text, Name.Function), '#pop'),
  123. ],
  124. 'string': [
  125. (r"[^']*'", String, '#pop'),
  126. ],
  127. 'commandargs': [
  128. (r"[ \t]+", Text),
  129. ("'[^']*'", String),
  130. (r"[^';\s]+", String),
  131. (";?", Punctuation, '#pop'),
  132. ]
  133. }
  134. def analyse_text(text):
  135. # function declaration.
  136. first_non_comment = next((line for line in text.splitlines()
  137. if not re.match(r'^\s*%', text)), '').strip()
  138. if (first_non_comment.startswith('function')
  139. and '{' not in first_non_comment):
  140. return 1.
  141. # comment
  142. elif re.search(r'^\s*%', text, re.M):
  143. return 0.2
  144. # system cmd
  145. elif re.search(r'^!\w+', text, re.M):
  146. return 0.2
  147. line_re = re.compile('.*?\n')
  148. class MatlabSessionLexer(Lexer):
  149. """
  150. For Matlab sessions. Modeled after PythonConsoleLexer.
  151. Contributed by Ken Schutte <kschutte@csail.mit.edu>.
  152. .. versionadded:: 0.10
  153. """
  154. name = 'Matlab session'
  155. aliases = ['matlabsession']
  156. def get_tokens_unprocessed(self, text):
  157. mlexer = MatlabLexer(**self.options)
  158. curcode = ''
  159. insertions = []
  160. for match in line_re.finditer(text):
  161. line = match.group()
  162. if line.startswith('>> '):
  163. insertions.append((len(curcode),
  164. [(0, Generic.Prompt, line[:3])]))
  165. curcode += line[3:]
  166. elif line.startswith('>>'):
  167. insertions.append((len(curcode),
  168. [(0, Generic.Prompt, line[:2])]))
  169. curcode += line[2:]
  170. elif line.startswith('???'):
  171. idx = len(curcode)
  172. # without is showing error on same line as before...?
  173. # line = "\n" + line
  174. token = (0, Generic.Traceback, line)
  175. insertions.append((idx, [token]))
  176. else:
  177. if curcode:
  178. for item in do_insertions(
  179. insertions, mlexer.get_tokens_unprocessed(curcode)):
  180. yield item
  181. curcode = ''
  182. insertions = []
  183. yield match.start(), Generic.Output, line
  184. if curcode: # or item:
  185. for item in do_insertions(
  186. insertions, mlexer.get_tokens_unprocessed(curcode)):
  187. yield item
  188. class OctaveLexer(RegexLexer):
  189. """
  190. For GNU Octave source code.
  191. .. versionadded:: 1.5
  192. """
  193. name = 'Octave'
  194. aliases = ['octave']
  195. filenames = ['*.m']
  196. mimetypes = ['text/octave']
  197. # These lists are generated automatically.
  198. # Run the following in bash shell:
  199. #
  200. # First dump all of the Octave manual into a plain text file:
  201. #
  202. # $ info octave --subnodes -o octave-manual
  203. #
  204. # Now grep through it:
  205. # for i in \
  206. # "Built-in Function" "Command" "Function File" \
  207. # "Loadable Function" "Mapping Function";
  208. # do
  209. # perl -e '@name = qw('"$i"');
  210. # print lc($name[0]),"_kw = [\n"';
  211. #
  212. # perl -n -e 'print "\"$1\",\n" if /-- '"$i"': .* (\w*) \(/;' \
  213. # octave-manual | sort | uniq ;
  214. # echo "]" ;
  215. # echo;
  216. # done
  217. # taken from Octave Mercurial changeset 8cc154f45e37 (30-jan-2011)
  218. builtin_kw = (
  219. "addlistener", "addpath", "addproperty", "all",
  220. "and", "any", "argnames", "argv", "assignin",
  221. "atexit", "autoload",
  222. "available_graphics_toolkits", "beep_on_error",
  223. "bitand", "bitmax", "bitor", "bitshift", "bitxor",
  224. "cat", "cell", "cellstr", "char", "class", "clc",
  225. "columns", "command_line_path",
  226. "completion_append_char", "completion_matches",
  227. "complex", "confirm_recursive_rmdir", "cputime",
  228. "crash_dumps_octave_core", "ctranspose", "cumprod",
  229. "cumsum", "debug_on_error", "debug_on_interrupt",
  230. "debug_on_warning", "default_save_options",
  231. "dellistener", "diag", "diff", "disp",
  232. "doc_cache_file", "do_string_escapes", "double",
  233. "drawnow", "e", "echo_executing_commands", "eps",
  234. "eq", "errno", "errno_list", "error", "eval",
  235. "evalin", "exec", "exist", "exit", "eye", "false",
  236. "fclear", "fclose", "fcntl", "fdisp", "feof",
  237. "ferror", "feval", "fflush", "fgetl", "fgets",
  238. "fieldnames", "file_in_loadpath", "file_in_path",
  239. "filemarker", "filesep", "find_dir_in_path",
  240. "fixed_point_format", "fnmatch", "fopen", "fork",
  241. "formula", "fprintf", "fputs", "fread", "freport",
  242. "frewind", "fscanf", "fseek", "fskipl", "ftell",
  243. "functions", "fwrite", "ge", "genpath", "get",
  244. "getegid", "getenv", "geteuid", "getgid",
  245. "getpgrp", "getpid", "getppid", "getuid", "glob",
  246. "gt", "gui_mode", "history_control",
  247. "history_file", "history_size",
  248. "history_timestamp_format_string", "home",
  249. "horzcat", "hypot", "ifelse",
  250. "ignore_function_time_stamp", "inferiorto",
  251. "info_file", "info_program", "inline", "input",
  252. "intmax", "intmin", "ipermute",
  253. "is_absolute_filename", "isargout", "isbool",
  254. "iscell", "iscellstr", "ischar", "iscomplex",
  255. "isempty", "isfield", "isfloat", "isglobal",
  256. "ishandle", "isieee", "isindex", "isinteger",
  257. "islogical", "ismatrix", "ismethod", "isnull",
  258. "isnumeric", "isobject", "isreal",
  259. "is_rooted_relative_filename", "issorted",
  260. "isstruct", "isvarname", "kbhit", "keyboard",
  261. "kill", "lasterr", "lasterror", "lastwarn",
  262. "ldivide", "le", "length", "link", "linspace",
  263. "logical", "lstat", "lt", "make_absolute_filename",
  264. "makeinfo_program", "max_recursion_depth", "merge",
  265. "methods", "mfilename", "minus", "mislocked",
  266. "mkdir", "mkfifo", "mkstemp", "mldivide", "mlock",
  267. "mouse_wheel_zoom", "mpower", "mrdivide", "mtimes",
  268. "munlock", "nargin", "nargout",
  269. "native_float_format", "ndims", "ne", "nfields",
  270. "nnz", "norm", "not", "numel", "nzmax",
  271. "octave_config_info", "octave_core_file_limit",
  272. "octave_core_file_name",
  273. "octave_core_file_options", "ones", "or",
  274. "output_max_field_width", "output_precision",
  275. "page_output_immediately", "page_screen_output",
  276. "path", "pathsep", "pause", "pclose", "permute",
  277. "pi", "pipe", "plus", "popen", "power",
  278. "print_empty_dimensions", "printf",
  279. "print_struct_array_contents", "prod",
  280. "program_invocation_name", "program_name",
  281. "putenv", "puts", "pwd", "quit", "rats", "rdivide",
  282. "readdir", "readlink", "read_readline_init_file",
  283. "realmax", "realmin", "rehash", "rename",
  284. "repelems", "re_read_readline_init_file", "reset",
  285. "reshape", "resize", "restoredefaultpath",
  286. "rethrow", "rmdir", "rmfield", "rmpath", "rows",
  287. "save_header_format_string", "save_precision",
  288. "saving_history", "scanf", "set", "setenv",
  289. "shell_cmd", "sighup_dumps_octave_core",
  290. "sigterm_dumps_octave_core", "silent_functions",
  291. "single", "size", "size_equal", "sizemax",
  292. "sizeof", "sleep", "source", "sparse_auto_mutate",
  293. "split_long_rows", "sprintf", "squeeze", "sscanf",
  294. "stat", "stderr", "stdin", "stdout", "strcmp",
  295. "strcmpi", "string_fill_char", "strncmp",
  296. "strncmpi", "struct", "struct_levels_to_print",
  297. "strvcat", "subsasgn", "subsref", "sum", "sumsq",
  298. "superiorto", "suppress_verbose_help_message",
  299. "symlink", "system", "tic", "tilde_expand",
  300. "times", "tmpfile", "tmpnam", "toc", "toupper",
  301. "transpose", "true", "typeinfo", "umask", "uminus",
  302. "uname", "undo_string_escapes", "unlink", "uplus",
  303. "upper", "usage", "usleep", "vec", "vectorize",
  304. "vertcat", "waitpid", "warning", "warranty",
  305. "whos_line_format", "yes_or_no", "zeros",
  306. "inf", "Inf", "nan", "NaN")
  307. command_kw = ("close", "load", "who", "whos")
  308. function_kw = (
  309. "accumarray", "accumdim", "acosd", "acotd",
  310. "acscd", "addtodate", "allchild", "ancestor",
  311. "anova", "arch_fit", "arch_rnd", "arch_test",
  312. "area", "arma_rnd", "arrayfun", "ascii", "asctime",
  313. "asecd", "asind", "assert", "atand",
  314. "autoreg_matrix", "autumn", "axes", "axis", "bar",
  315. "barh", "bartlett", "bartlett_test", "beep",
  316. "betacdf", "betainv", "betapdf", "betarnd",
  317. "bicgstab", "bicubic", "binary", "binocdf",
  318. "binoinv", "binopdf", "binornd", "bitcmp",
  319. "bitget", "bitset", "blackman", "blanks",
  320. "blkdiag", "bone", "box", "brighten", "calendar",
  321. "cast", "cauchy_cdf", "cauchy_inv", "cauchy_pdf",
  322. "cauchy_rnd", "caxis", "celldisp", "center", "cgs",
  323. "chisquare_test_homogeneity",
  324. "chisquare_test_independence", "circshift", "cla",
  325. "clabel", "clf", "clock", "cloglog", "closereq",
  326. "colon", "colorbar", "colormap", "colperm",
  327. "comet", "common_size", "commutation_matrix",
  328. "compan", "compare_versions", "compass",
  329. "computer", "cond", "condest", "contour",
  330. "contourc", "contourf", "contrast", "conv",
  331. "convhull", "cool", "copper", "copyfile", "cor",
  332. "corrcoef", "cor_test", "cosd", "cotd", "cov",
  333. "cplxpair", "cross", "cscd", "cstrcat", "csvread",
  334. "csvwrite", "ctime", "cumtrapz", "curl", "cut",
  335. "cylinder", "date", "datenum", "datestr",
  336. "datetick", "datevec", "dblquad", "deal",
  337. "deblank", "deconv", "delaunay", "delaunayn",
  338. "delete", "demo", "detrend", "diffpara", "diffuse",
  339. "dir", "discrete_cdf", "discrete_inv",
  340. "discrete_pdf", "discrete_rnd", "display",
  341. "divergence", "dlmwrite", "dos", "dsearch",
  342. "dsearchn", "duplication_matrix", "durbinlevinson",
  343. "ellipsoid", "empirical_cdf", "empirical_inv",
  344. "empirical_pdf", "empirical_rnd", "eomday",
  345. "errorbar", "etime", "etreeplot", "example",
  346. "expcdf", "expinv", "expm", "exppdf", "exprnd",
  347. "ezcontour", "ezcontourf", "ezmesh", "ezmeshc",
  348. "ezplot", "ezpolar", "ezsurf", "ezsurfc", "factor",
  349. "factorial", "fail", "fcdf", "feather", "fftconv",
  350. "fftfilt", "fftshift", "figure", "fileattrib",
  351. "fileparts", "fill", "findall", "findobj",
  352. "findstr", "finv", "flag", "flipdim", "fliplr",
  353. "flipud", "fpdf", "fplot", "fractdiff", "freqz",
  354. "freqz_plot", "frnd", "fsolve",
  355. "f_test_regression", "ftp", "fullfile", "fzero",
  356. "gamcdf", "gaminv", "gampdf", "gamrnd", "gca",
  357. "gcbf", "gcbo", "gcf", "genvarname", "geocdf",
  358. "geoinv", "geopdf", "geornd", "getfield", "ginput",
  359. "glpk", "gls", "gplot", "gradient",
  360. "graphics_toolkit", "gray", "grid", "griddata",
  361. "griddatan", "gtext", "gunzip", "gzip", "hadamard",
  362. "hamming", "hankel", "hanning", "hggroup",
  363. "hidden", "hilb", "hist", "histc", "hold", "hot",
  364. "hotelling_test", "housh", "hsv", "hurst",
  365. "hygecdf", "hygeinv", "hygepdf", "hygernd",
  366. "idivide", "ifftshift", "image", "imagesc",
  367. "imfinfo", "imread", "imshow", "imwrite", "index",
  368. "info", "inpolygon", "inputname", "interpft",
  369. "interpn", "intersect", "invhilb", "iqr", "isa",
  370. "isdefinite", "isdir", "is_duplicate_entry",
  371. "isequal", "isequalwithequalnans", "isfigure",
  372. "ishermitian", "ishghandle", "is_leap_year",
  373. "isletter", "ismac", "ismember", "ispc", "isprime",
  374. "isprop", "isscalar", "issquare", "isstrprop",
  375. "issymmetric", "isunix", "is_valid_file_id",
  376. "isvector", "jet", "kendall",
  377. "kolmogorov_smirnov_cdf",
  378. "kolmogorov_smirnov_test", "kruskal_wallis_test",
  379. "krylov", "kurtosis", "laplace_cdf", "laplace_inv",
  380. "laplace_pdf", "laplace_rnd", "legend", "legendre",
  381. "license", "line", "linkprop", "list_primes",
  382. "loadaudio", "loadobj", "logistic_cdf",
  383. "logistic_inv", "logistic_pdf", "logistic_rnd",
  384. "logit", "loglog", "loglogerr", "logm", "logncdf",
  385. "logninv", "lognpdf", "lognrnd", "logspace",
  386. "lookfor", "ls_command", "lsqnonneg", "magic",
  387. "mahalanobis", "manova", "matlabroot",
  388. "mcnemar_test", "mean", "meansq", "median", "menu",
  389. "mesh", "meshc", "meshgrid", "meshz", "mexext",
  390. "mget", "mkpp", "mode", "moment", "movefile",
  391. "mpoles", "mput", "namelengthmax", "nargchk",
  392. "nargoutchk", "nbincdf", "nbininv", "nbinpdf",
  393. "nbinrnd", "nchoosek", "ndgrid", "newplot", "news",
  394. "nonzeros", "normcdf", "normest", "norminv",
  395. "normpdf", "normrnd", "now", "nthroot", "null",
  396. "ocean", "ols", "onenormest", "optimget",
  397. "optimset", "orderfields", "orient", "orth",
  398. "pack", "pareto", "parseparams", "pascal", "patch",
  399. "pathdef", "pcg", "pchip", "pcolor", "pcr",
  400. "peaks", "periodogram", "perl", "perms", "pie",
  401. "pink", "planerot", "playaudio", "plot",
  402. "plotmatrix", "plotyy", "poisscdf", "poissinv",
  403. "poisspdf", "poissrnd", "polar", "poly",
  404. "polyaffine", "polyarea", "polyderiv", "polyfit",
  405. "polygcd", "polyint", "polyout", "polyreduce",
  406. "polyval", "polyvalm", "postpad", "powerset",
  407. "ppder", "ppint", "ppjumps", "ppplot", "ppval",
  408. "pqpnonneg", "prepad", "primes", "print",
  409. "print_usage", "prism", "probit", "qp", "qqplot",
  410. "quadcc", "quadgk", "quadl", "quadv", "quiver",
  411. "qzhess", "rainbow", "randi", "range", "rank",
  412. "ranks", "rat", "reallog", "realpow", "realsqrt",
  413. "record", "rectangle_lw", "rectangle_sw",
  414. "rectint", "refresh", "refreshdata",
  415. "regexptranslate", "repmat", "residue", "ribbon",
  416. "rindex", "roots", "rose", "rosser", "rotdim",
  417. "rref", "run", "run_count", "rundemos", "run_test",
  418. "runtests", "saveas", "saveaudio", "saveobj",
  419. "savepath", "scatter", "secd", "semilogx",
  420. "semilogxerr", "semilogy", "semilogyerr",
  421. "setaudio", "setdiff", "setfield", "setxor",
  422. "shading", "shift", "shiftdim", "sign_test",
  423. "sinc", "sind", "sinetone", "sinewave", "skewness",
  424. "slice", "sombrero", "sortrows", "spaugment",
  425. "spconvert", "spdiags", "spearman", "spectral_adf",
  426. "spectral_xdf", "specular", "speed", "spencer",
  427. "speye", "spfun", "sphere", "spinmap", "spline",
  428. "spones", "sprand", "sprandn", "sprandsym",
  429. "spring", "spstats", "spy", "sqp", "stairs",
  430. "statistics", "std", "stdnormal_cdf",
  431. "stdnormal_inv", "stdnormal_pdf", "stdnormal_rnd",
  432. "stem", "stft", "strcat", "strchr", "strjust",
  433. "strmatch", "strread", "strsplit", "strtok",
  434. "strtrim", "strtrunc", "structfun", "studentize",
  435. "subplot", "subsindex", "subspace", "substr",
  436. "substruct", "summer", "surf", "surface", "surfc",
  437. "surfl", "surfnorm", "svds", "swapbytes",
  438. "sylvester_matrix", "symvar", "synthesis", "table",
  439. "tand", "tar", "tcdf", "tempdir", "tempname",
  440. "test", "text", "textread", "textscan", "tinv",
  441. "title", "toeplitz", "tpdf", "trace", "trapz",
  442. "treelayout", "treeplot", "triangle_lw",
  443. "triangle_sw", "tril", "trimesh", "triplequad",
  444. "triplot", "trisurf", "triu", "trnd", "tsearchn",
  445. "t_test", "t_test_regression", "type", "unidcdf",
  446. "unidinv", "unidpdf", "unidrnd", "unifcdf",
  447. "unifinv", "unifpdf", "unifrnd", "union", "unique",
  448. "unix", "unmkpp", "unpack", "untabify", "untar",
  449. "unwrap", "unzip", "u_test", "validatestring",
  450. "vander", "var", "var_test", "vech", "ver",
  451. "version", "view", "voronoi", "voronoin",
  452. "waitforbuttonpress", "wavread", "wavwrite",
  453. "wblcdf", "wblinv", "wblpdf", "wblrnd", "weekday",
  454. "welch_test", "what", "white", "whitebg",
  455. "wienrnd", "wilcoxon_test", "wilkinson", "winter",
  456. "xlabel", "xlim", "ylabel", "yulewalker", "zip",
  457. "zlabel", "z_test")
  458. loadable_kw = (
  459. "airy", "amd", "balance", "besselh", "besseli",
  460. "besselj", "besselk", "bessely", "bitpack",
  461. "bsxfun", "builtin", "ccolamd", "cellfun",
  462. "cellslices", "chol", "choldelete", "cholinsert",
  463. "cholinv", "cholshift", "cholupdate", "colamd",
  464. "colloc", "convhulln", "convn", "csymamd",
  465. "cummax", "cummin", "daspk", "daspk_options",
  466. "dasrt", "dasrt_options", "dassl", "dassl_options",
  467. "dbclear", "dbdown", "dbstack", "dbstatus",
  468. "dbstop", "dbtype", "dbup", "dbwhere", "det",
  469. "dlmread", "dmperm", "dot", "eig", "eigs",
  470. "endgrent", "endpwent", "etree", "fft", "fftn",
  471. "fftw", "filter", "find", "full", "gcd",
  472. "getgrent", "getgrgid", "getgrnam", "getpwent",
  473. "getpwnam", "getpwuid", "getrusage", "givens",
  474. "gmtime", "gnuplot_binary", "hess", "ifft",
  475. "ifftn", "inv", "isdebugmode", "issparse", "kron",
  476. "localtime", "lookup", "lsode", "lsode_options",
  477. "lu", "luinc", "luupdate", "matrix_type", "max",
  478. "min", "mktime", "pinv", "qr", "qrdelete",
  479. "qrinsert", "qrshift", "qrupdate", "quad",
  480. "quad_options", "qz", "rand", "rande", "randg",
  481. "randn", "randp", "randperm", "rcond", "regexp",
  482. "regexpi", "regexprep", "schur", "setgrent",
  483. "setpwent", "sort", "spalloc", "sparse", "spparms",
  484. "sprank", "sqrtm", "strfind", "strftime",
  485. "strptime", "strrep", "svd", "svd_driver", "syl",
  486. "symamd", "symbfact", "symrcm", "time", "tsearch",
  487. "typecast", "urlread", "urlwrite")
  488. mapping_kw = (
  489. "abs", "acos", "acosh", "acot", "acoth", "acsc",
  490. "acsch", "angle", "arg", "asec", "asech", "asin",
  491. "asinh", "atan", "atanh", "beta", "betainc",
  492. "betaln", "bincoeff", "cbrt", "ceil", "conj", "cos",
  493. "cosh", "cot", "coth", "csc", "csch", "erf", "erfc",
  494. "erfcx", "erfinv", "exp", "finite", "fix", "floor",
  495. "fmod", "gamma", "gammainc", "gammaln", "imag",
  496. "isalnum", "isalpha", "isascii", "iscntrl",
  497. "isdigit", "isfinite", "isgraph", "isinf",
  498. "islower", "isna", "isnan", "isprint", "ispunct",
  499. "isspace", "isupper", "isxdigit", "lcm", "lgamma",
  500. "log", "lower", "mod", "real", "rem", "round",
  501. "roundb", "sec", "sech", "sign", "sin", "sinh",
  502. "sqrt", "tan", "tanh", "toascii", "tolower", "xor")
  503. builtin_consts = (
  504. "EDITOR", "EXEC_PATH", "I", "IMAGE_PATH", "NA",
  505. "OCTAVE_HOME", "OCTAVE_VERSION", "PAGER",
  506. "PAGER_FLAGS", "SEEK_CUR", "SEEK_END", "SEEK_SET",
  507. "SIG", "S_ISBLK", "S_ISCHR", "S_ISDIR", "S_ISFIFO",
  508. "S_ISLNK", "S_ISREG", "S_ISSOCK", "WCONTINUE",
  509. "WCOREDUMP", "WEXITSTATUS", "WIFCONTINUED",
  510. "WIFEXITED", "WIFSIGNALED", "WIFSTOPPED", "WNOHANG",
  511. "WSTOPSIG", "WTERMSIG", "WUNTRACED")
  512. tokens = {
  513. 'root': [
  514. # We should look into multiline comments
  515. (r'[%#].*$', Comment),
  516. (r'^\s*function\b', Keyword, 'deffunc'),
  517. # from 'iskeyword' on hg changeset 8cc154f45e37
  518. (words((
  519. '__FILE__', '__LINE__', 'break', 'case', 'catch', 'classdef', 'continue', 'do', 'else',
  520. 'elseif', 'end', 'end_try_catch', 'end_unwind_protect', 'endclassdef',
  521. 'endevents', 'endfor', 'endfunction', 'endif', 'endmethods', 'endproperties',
  522. 'endswitch', 'endwhile', 'events', 'for', 'function', 'get', 'global', 'if', 'methods',
  523. 'otherwise', 'persistent', 'properties', 'return', 'set', 'static', 'switch', 'try',
  524. 'until', 'unwind_protect', 'unwind_protect_cleanup', 'while'), suffix=r'\b'),
  525. Keyword),
  526. (words(builtin_kw + command_kw + function_kw + loadable_kw + mapping_kw,
  527. suffix=r'\b'), Name.Builtin),
  528. (words(builtin_consts, suffix=r'\b'), Name.Constant),
  529. # operators in Octave but not Matlab:
  530. (r'-=|!=|!|/=|--', Operator),
  531. # operators:
  532. (r'-|==|~=|<|>|<=|>=|&&|&|~|\|\|?', Operator),
  533. # operators in Octave but not Matlab requiring escape for re:
  534. (r'\*=|\+=|\^=|\/=|\\=|\*\*|\+\+|\.\*\*', Operator),
  535. # operators requiring escape for re:
  536. (r'\.\*|\*|\+|\.\^|\.\\|\.\/|\/|\\', Operator),
  537. # punctuation:
  538. (r'[\[\](){}:@.,]', Punctuation),
  539. (r'=|:|;', Punctuation),
  540. (r'"[^"]*"', String),
  541. (r'(\d+\.\d*|\d*\.\d+)([eEf][+-]?[0-9]+)?', Number.Float),
  542. (r'\d+[eEf][+-]?[0-9]+', Number.Float),
  543. (r'\d+', Number.Integer),
  544. # quote can be transpose, instead of string:
  545. # (not great, but handles common cases...)
  546. (r'(?<=[\w)\].])\'+', Operator),
  547. (r'(?<![\w)\].])\'', String, 'string'),
  548. (r'[a-zA-Z_]\w*', Name),
  549. (r'.', Text),
  550. ],
  551. 'string': [
  552. (r"[^']*'", String, '#pop'),
  553. ],
  554. 'deffunc': [
  555. (r'(\s*)(?:(.+)(\s*)(=)(\s*))?(.+)(\()(.*)(\))(\s*)',
  556. bygroups(Whitespace, Text, Whitespace, Punctuation,
  557. Whitespace, Name.Function, Punctuation, Text,
  558. Punctuation, Whitespace), '#pop'),
  559. # function with no args
  560. (r'(\s*)([a-zA-Z_]\w*)', bygroups(Text, Name.Function), '#pop'),
  561. ],
  562. }
  563. class ScilabLexer(RegexLexer):
  564. """
  565. For Scilab source code.
  566. .. versionadded:: 1.5
  567. """
  568. name = 'Scilab'
  569. aliases = ['scilab']
  570. filenames = ['*.sci', '*.sce', '*.tst']
  571. mimetypes = ['text/scilab']
  572. tokens = {
  573. 'root': [
  574. (r'//.*?$', Comment.Single),
  575. (r'^\s*function\b', Keyword, 'deffunc'),
  576. (words((
  577. '__FILE__', '__LINE__', 'break', 'case', 'catch', 'classdef', 'continue', 'do', 'else',
  578. 'elseif', 'end', 'end_try_catch', 'end_unwind_protect', 'endclassdef',
  579. 'endevents', 'endfor', 'endfunction', 'endif', 'endmethods', 'endproperties',
  580. 'endswitch', 'endwhile', 'events', 'for', 'function', 'get', 'global', 'if', 'methods',
  581. 'otherwise', 'persistent', 'properties', 'return', 'set', 'static', 'switch', 'try',
  582. 'until', 'unwind_protect', 'unwind_protect_cleanup', 'while'), suffix=r'\b'),
  583. Keyword),
  584. (words(_scilab_builtins.functions_kw +
  585. _scilab_builtins.commands_kw +
  586. _scilab_builtins.macros_kw, suffix=r'\b'), Name.Builtin),
  587. (words(_scilab_builtins.variables_kw, suffix=r'\b'), Name.Constant),
  588. # operators:
  589. (r'-|==|~=|<|>|<=|>=|&&|&|~|\|\|?', Operator),
  590. # operators requiring escape for re:
  591. (r'\.\*|\*|\+|\.\^|\.\\|\.\/|\/|\\', Operator),
  592. # punctuation:
  593. (r'[\[\](){}@.,=:;]', Punctuation),
  594. (r'"[^"]*"', String),
  595. # quote can be transpose, instead of string:
  596. # (not great, but handles common cases...)
  597. (r'(?<=[\w)\].])\'+', Operator),
  598. (r'(?<![\w)\].])\'', String, 'string'),
  599. (r'(\d+\.\d*|\d*\.\d+)([eEf][+-]?[0-9]+)?', Number.Float),
  600. (r'\d+[eEf][+-]?[0-9]+', Number.Float),
  601. (r'\d+', Number.Integer),
  602. (r'[a-zA-Z_]\w*', Name),
  603. (r'.', Text),
  604. ],
  605. 'string': [
  606. (r"[^']*'", String, '#pop'),
  607. (r'.', String, '#pop'),
  608. ],
  609. 'deffunc': [
  610. (r'(\s*)(?:(.+)(\s*)(=)(\s*))?(.+)(\()(.*)(\))(\s*)',
  611. bygroups(Whitespace, Text, Whitespace, Punctuation,
  612. Whitespace, Name.Function, Punctuation, Text,
  613. Punctuation, Whitespace), '#pop'),
  614. # function with no args
  615. (r'(\s*)([a-zA-Z_]\w*)', bygroups(Text, Name.Function), '#pop'),
  616. ],
  617. }