matlab.py 28 KB

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