matlab.py 30 KB

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