rouge 2.0.7 → 2.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (94) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +7 -9
  3. data/lib/rouge.rb +1 -0
  4. data/lib/rouge/cli.rb +20 -0
  5. data/lib/rouge/demos/awk +4 -0
  6. data/lib/rouge/demos/console +6 -0
  7. data/lib/rouge/demos/digdag +19 -0
  8. data/lib/rouge/demos/dot +5 -0
  9. data/lib/rouge/demos/graphql +17 -0
  10. data/lib/rouge/demos/hylang +10 -0
  11. data/lib/rouge/demos/igorpro +9 -0
  12. data/lib/rouge/demos/irb +4 -0
  13. data/lib/rouge/demos/irb_output +2 -0
  14. data/lib/rouge/demos/lasso +12 -0
  15. data/lib/rouge/demos/mosel +10 -0
  16. data/lib/rouge/demos/plist +142 -0
  17. data/lib/rouge/demos/pony +17 -0
  18. data/lib/rouge/demos/q +2 -0
  19. data/lib/rouge/demos/sieve +10 -0
  20. data/lib/rouge/demos/tsx +17 -0
  21. data/lib/rouge/demos/turtle +0 -0
  22. data/lib/rouge/demos/wollok +11 -0
  23. data/lib/rouge/formatters/html_inline.rb +9 -1
  24. data/lib/rouge/formatters/html_pygments.rb +2 -2
  25. data/lib/rouge/formatters/html_table.rb +1 -1
  26. data/lib/rouge/formatters/terminal256.rb +1 -1
  27. data/lib/rouge/lexer.rb +124 -37
  28. data/lib/rouge/lexers/abap.rb +2 -2
  29. data/lib/rouge/lexers/apache.rb +1 -1
  30. data/lib/rouge/lexers/awk.rb +161 -0
  31. data/lib/rouge/lexers/clojure.rb +2 -2
  32. data/lib/rouge/lexers/coffeescript.rb +1 -1
  33. data/lib/rouge/lexers/console.rb +136 -0
  34. data/lib/rouge/lexers/csharp.rb +26 -7
  35. data/lib/rouge/lexers/digdag.rb +72 -0
  36. data/lib/rouge/lexers/docker.rb +1 -1
  37. data/lib/rouge/lexers/dot.rb +68 -0
  38. data/lib/rouge/lexers/elixir.rb +52 -27
  39. data/lib/rouge/lexers/fortran.rb +56 -28
  40. data/lib/rouge/lexers/fsharp.rb +1 -1
  41. data/lib/rouge/lexers/gherkin/keywords.rb +4 -4
  42. data/lib/rouge/lexers/graphql.rb +243 -0
  43. data/lib/rouge/lexers/groovy.rb +5 -1
  44. data/lib/rouge/lexers/haml.rb +19 -24
  45. data/lib/rouge/lexers/html.rb +48 -4
  46. data/lib/rouge/lexers/hylang.rb +93 -0
  47. data/lib/rouge/lexers/igorpro.rb +407 -0
  48. data/lib/rouge/lexers/irb.rb +66 -0
  49. data/lib/rouge/lexers/javascript.rb +21 -10
  50. data/lib/rouge/lexers/json.rb +3 -2
  51. data/lib/rouge/lexers/json_doc.rb +6 -0
  52. data/lib/rouge/lexers/jsx.rb +2 -1
  53. data/lib/rouge/lexers/lasso.rb +217 -0
  54. data/lib/rouge/lexers/lasso/keywords.yml +446 -0
  55. data/lib/rouge/lexers/lua.rb +3 -0
  56. data/lib/rouge/lexers/lua/builtins.rb +1 -1
  57. data/lib/rouge/lexers/markdown.rb +2 -3
  58. data/lib/rouge/lexers/matlab/builtins.rb +1 -1
  59. data/lib/rouge/lexers/moonscript.rb +8 -4
  60. data/lib/rouge/lexers/mosel.rb +231 -0
  61. data/lib/rouge/lexers/ocaml.rb +9 -20
  62. data/lib/rouge/lexers/php.rb +40 -20
  63. data/lib/rouge/lexers/php/builtins.rb +27 -37
  64. data/lib/rouge/lexers/plain_text.rb +4 -3
  65. data/lib/rouge/lexers/plist.rb +49 -0
  66. data/lib/rouge/lexers/pony.rb +93 -0
  67. data/lib/rouge/lexers/powershell.rb +36 -0
  68. data/lib/rouge/lexers/properties.rb +2 -2
  69. data/lib/rouge/lexers/q.rb +124 -0
  70. data/lib/rouge/lexers/r.rb +2 -2
  71. data/lib/rouge/lexers/ruby.rb +26 -13
  72. data/lib/rouge/lexers/rust.rb +7 -5
  73. data/lib/rouge/lexers/sed.rb +4 -2
  74. data/lib/rouge/lexers/shell.rb +38 -16
  75. data/lib/rouge/lexers/sieve.rb +96 -0
  76. data/lib/rouge/lexers/sml.rb +3 -2
  77. data/lib/rouge/lexers/tsx.rb +19 -0
  78. data/lib/rouge/lexers/turtle.rb +0 -0
  79. data/lib/rouge/lexers/typescript.rb +3 -27
  80. data/lib/rouge/lexers/typescript/common.rb +33 -0
  81. data/lib/rouge/lexers/viml/keywords.rb +2 -2
  82. data/lib/rouge/lexers/wollok.rb +107 -0
  83. data/lib/rouge/lexers/xml.rb +1 -1
  84. data/lib/rouge/lexers/yaml.rb +4 -1
  85. data/lib/rouge/regex_lexer.rb +1 -0
  86. data/lib/rouge/template_lexer.rb +3 -5
  87. data/lib/rouge/theme.rb +14 -4
  88. data/lib/rouge/themes/igor_pro.rb +20 -0
  89. data/lib/rouge/themes/pastie.rb +69 -0
  90. data/lib/rouge/themes/thankful_eyes.rb +8 -5
  91. data/lib/rouge/version.rb +1 -1
  92. metadata +40 -6
  93. data/lib/rouge/demos/shell_session +0 -10
  94. data/lib/rouge/lexers/shell_session.rb +0 -29
@@ -10,6 +10,9 @@ module Rouge
10
10
 
11
11
  mimetypes 'text/x-lua', 'application/x-lua'
12
12
 
13
+ option :function_highlighting, 'Whether to highlight builtin functions (default: true)'
14
+ option :disabled_modules, 'builtin modules to disable'
15
+
13
16
  def initialize(opts={})
14
17
  @function_highlighting = opts.delete(:function_highlighting) { true }
15
18
  @disabled_modules = opts.delete(:disabled_modules) { [] }
@@ -5,7 +5,7 @@ module Rouge
5
5
  class Lua
6
6
  def self.builtins
7
7
  @builtins ||= {}.tap do |b|
8
- b["basic"] = Set.new %w(_G _VERSION assert collectgarbage dofile error getmetatable ipairs load loadfile next pairs pcall print rawequal rawget rawlen rawset select setmetatable tonumber tostring type xpcall file:close file:flush file:lines file:read file:seek file:setvbuf file:write)
8
+ b["basic"] = Set.new %w(_G _VERSION assert collectgarbage dofile error getmetatable ipairs load loadfile next pairs pcall print rawequal rawget rawlen rawset select setmetatable tonumber tostring type xpcall file:close file:flush file:lines file:read file:seek file:setvbuf file:write LUA_CPATH LUA_CPATH_5_2 LUA_INIT LUA_INIT_5_2 LUA_PATH LUA_PATH_5_2 luaopen_base luaopen_bit32 luaopen_coroutine luaopen_debug luaopen_io luaopen_math luaopen_os luaopen_package luaopen_string luaopen_table LUA_ERRERR LUA_ERRFILE LUA_ERRGCMM LUA_ERRMEM LUA_ERRRUN LUA_ERRSYNTAX LUA_HOOKCALL LUA_HOOKCOUNT LUA_HOOKLINE LUA_HOOKRET LUA_HOOKTAILCALL LUA_MASKCALL LUA_MASKCOUNT LUA_MASKLINE LUA_MASKRET LUA_MINSTACK LUA_MULTRET LUA_NOREF LUA_OK LUA_OPADD LUA_OPDIV LUA_OPEQ LUA_OPLE LUA_OPLT LUA_OPMOD LUA_OPMUL LUA_OPPOW LUA_OPSUB LUA_OPUNM LUA_REFNIL LUA_REGISTRYINDEX LUA_RIDX_GLOBALS LUA_RIDX_MAINTHREAD LUA_TBOOLEAN LUA_TFUNCTION LUA_TLIGHTUSERDATA LUA_TNIL LUA_TNONE LUA_TNUMBER LUA_TSTRING LUA_TTABLE LUA_TTHREAD LUA_TUSERDATA LUA_USE_APICHECK LUA_YIELD LUAL_BUFFERSIZE)
9
9
  b["modules"] = Set.new %w(require package.config package.cpath package.loaded package.loadlib package.path package.preload package.searchers package.searchpath)
10
10
  b["bit32"] = Set.new %w(bit32.arshift bit32.band bit32.bnot bit32.bor bit32.btest bit32.bxor bit32.extract bit32.lrotate bit32.lshift bit32.replace bit32.rrotate bit32.rshift)
11
11
  b["coroutine"] = Set.new %w(coroutine.create coroutine.resume coroutine.running coroutine.status coroutine.wrap coroutine.yield)
@@ -32,9 +32,8 @@ module Rouge
32
32
  rule /^##*.*?$/, Generic::Subheading
33
33
 
34
34
  rule /(\n[ \t]*)(```|~~~)(.*?)(\n.*?\n)(\2)/m do |m|
35
- sublexer = Lexer.find_fancy(m[3].strip, m[4])
36
- sublexer ||= PlainText.new(:token => Str::Backtick)
37
- sublexer.options(self.options)
35
+ sublexer = Lexer.find_fancy(m[3].strip, m[4], @options)
36
+ sublexer ||= PlainText.new(@options.merge(:token => Str::Backtick))
38
37
  sublexer.reset!
39
38
 
40
39
  token Text, m[1]
@@ -4,7 +4,7 @@ module Rouge
4
4
  module Lexers
5
5
  class Matlab
6
6
  def self.builtins
7
- @builtins ||= Set.new %w(ans clc diary format home iskeyword more accumarray blkdiag diag eye false freqspace linspace logspace meshgrid ndgrid ones rand true zeros cat horzcat vertcat colon end ind2sub sub2ind length ndims numel size height width iscolumn isempty ismatrix isrow isscalar isvector blkdiag circshift ctranspose diag flip fliplr flipud ipermute permute repmat reshape rot90 shiftdim issorted sort sortrows squeeze transpose vectorize plus uplus minus uminus times rdivide ldivide power mtimes mrdivide mldivide mpower cumprod cumsum diff prod sum ceil fix floor idivide mod rem round relationaloperators eq ge gt le lt ne isequal isequaln logicaloperatorsshortcircuit and not or xor all any false find islogical logical true intersect ismember issorted setdiff setxor union unique join innerjoin outerjoin bitand bitcmp bitget bitor bitset bitshift bitxor swapbytes specialcharacters colon double single int8 int16 int32 int64 uint8 uint16 uint32 uint64 cast typecast isinteger isfloat isnumeric isreal isfinite isinf isnan eps flintmax inf intmax intmin nan realmax realmin blanks cellstr char iscellstr ischar sprintf strcat strjoin ischar isletter isspace isstrprop sscanf strfind strrep strsplit strtok validatestring symvar regexp regexpi regexprep regexptranslate strcmp strcmpi strncmp strncmpi blanks deblank strtrim lower upper strjust categorical iscategorical categories iscategory isordinal isprotected addcats mergecats removecats renamecats reordercats summary countcats isundefined table array2table cell2table struct2table table2array table2cell table2struct readtable writetable istable height width summary intersect ismember setdiff setxor unique union join innerjoin outerjoin sortrows stack unstack ismissing standardizemissing varfun rowfun struct fieldnames getfield isfield isstruct orderfields rmfield setfield arrayfun structfun table2struct struct2table cell2struct struct2cell cell cell2mat cell2struct cell2table celldisp cellfun cellplot cellstr iscell iscellstr mat2cell num2cell strjoin strsplit struct2cell table2cell function_handle feval func2str str2func localfunctions functions addevent delevent gettsafteratevent gettsafterevent gettsatevent gettsbeforeatevent gettsbeforeevent gettsbetweenevents gettscollection isemptytscollection lengthtscollection settscollection sizetscollection tscollection addsampletocollection addts delsamplefromcollection getabstimetscollection getsampleusingtimetscollection gettimeseriesnames horzcattscollection removets resampletscollection setabstimetscollection settimeseriesnames vertcattscollection is isa iscategorical iscell iscellstr ischar isfield isfloat ishghandle isinteger isjava islogical isnumeric isobject isreal isscalar isstr isstruct istable isvector class validateattributes whos char int2str mat2str num2str str2double str2num native2unicode unicode2native base2dec bin2dec dec2base dec2bin dec2hex hex2dec hex2num num2hex table2array table2cell table2struct array2table cell2table struct2table cell2mat cell2struct cellstr mat2cell num2cell struct2cell datenum datevec datestr now clock date calendar eomday weekday addtodate etime plus uplus minus uminus times rdivide ldivide power mtimes mrdivide mldivide mpower cumprod cumsum diff prod sum ceil fix floor idivide mod rem round sin sind asin asind sinh asinh cos cosd acos acosd cosh acosh tan tand atan atand atan2 atan2d tanh atanh csc cscd acsc acscd csch acsch sec secd asec asecd sech asech cot cotd acot acotd coth acoth hypot exp expm1 log log10 log1p log2 nextpow2 nthroot pow2 reallog realpow realsqrt sqrt abs angle complex conj cplxpair i imag isreal j real sign unwrap factor factorial gcd isprime lcm nchoosek perms primes rat rats poly polyder polyeig polyfit polyint polyval polyvalm residue roots airy besselh besseli besselj besselk bessely beta betainc betaincinv betaln ellipj ellipke erf erfc erfcinv erfcx erfinv expint gamma gammainc gammaincinv gammaln legendre psi cart2pol cart2sph pol2cart sph2cart eps flintmax i j inf pi nan isfinite isinf isnan compan gallery hadamard hankel hilb invhilb magic pascal rosser toeplitz vander wilkinson cross dot kron surfnorm tril triu transpose cond condest funm inv linsolve lscov lsqnonneg pinv rcond sylvester mldivide mrdivide chol ichol cholupdate ilu lu qr qrdelete qrinsert qrupdate planerot ldl cdf2rdf rsf2csf gsvd svd balance cdf2rdf condeig eig eigs gsvd hess ordeig ordqz ordschur poly polyeig qz rsf2csf schur sqrtm ss2tf svd svds bandwidth cond condeig det isbanded isdiag ishermitian issymmetric istril istriu norm normest null orth rank rcond rref subspace trace expm logm sqrtm bsxfun arrayfun accumarray mpower corrcoef cov max mean median min mode std var rand randn randi randperm rng interp1 pchip spline ppval mkpp unmkpp padecoef interpft interp2 interp3 interpn ndgrid meshgrid griddata griddatan fminbnd fminsearch fzero lsqnonneg optimget optimset ode45 ode15s ode23 ode113 ode23t ode23tb ode23s ode15i decic odextend odeget odeset deval bvp4c bvp5c bvpinit bvpxtend bvpget bvpset deval dde23 ddesd ddensd ddeget ddeset deval pdepe pdeval integral integral2 integral3 quadgk quad2d cumtrapz trapz polyint del2 diff gradient polyder abs angle cplxpair fft fft2 fftn fftshift fftw ifft ifft2 ifftn ifftshift nextpow2 unwrap conv conv2 convn deconv detrend filter filter2 spdiags speye sprand sprandn sprandsym sparse spconvert issparse nnz nonzeros nzmax spalloc spfun spones spparms spy find full amd colamd colperm dmperm randperm symamd symrcm condest eigs ichol ilu normest spaugment sprank svds bicg bicgstab bicgstabl cgs gmres lsqr minres pcg qmr symmlq tfqmr etree etreeplot gplot symbfact treelayout treeplot unmesh tetramesh trimesh triplot trisurf delaunay delaunayn tetramesh trimesh triplot trisurf dsearchn tsearchn delaunay delaunayn convhull convhulln patch trisurf patch voronoi voronoin polyarea inpolygon rectint plot plotyy plot3 loglog semilogx semilogy errorbar fplot ezplot ezplot3 linespec colorspec bar bar3 barh bar3h hist histc rose pareto area pie pie3 stem stairs stem3 scatter scatter3 spy plotmatrix polar rose compass ezpolar linespec colorspec contour contourf contourc contour3 contourslice ezcontour ezcontourf feather quiver compass quiver3 streamslice streamline surf surfc surface surfl surfnorm mesh meshc meshz waterfall ribbon contour3 peaks cylinder ellipsoid sphere pcolor surf2patch ezsurf ezsurfc ezmesh ezmeshc contourslice flow isocaps isocolors isonormals isosurface reducepatch reducevolume shrinkfaces slice smooth3 subvolume volumebounds coneplot curl divergence interpstreamspeed stream2 stream3 streamline streamparticles streamribbon streamslice streamtube fill fill3 patch surf2patch movie noanimate drawnow refreshdata frame2im getframe im2frame comet comet3 title xlabel ylabel zlabel clabel datetick texlabel legend colorbar xlim ylim zlim box grid daspect pbaspect axes axis subplot hold gca cla annotation text legend title xlabel ylabel zlabel datacursormode ginput gtext colormap colormapeditor colorbar brighten contrast shading graymon caxis hsv2rgb rgb2hsv rgbplot spinmap colordef whitebg hidden pan reset rotate rotate3d selectmoveresize zoom datacursormode figurepalette plotbrowser plotedit plottools propertyeditor showplottool brush datacursormode linkdata refreshdata view makehgtform viewmtx cameratoolbar campan camzoom camdolly camlookat camorbit campos camproj camroll camtarget camup camva camlight light lightangle lighting diffuse material specular alim alpha alphamap image imagesc imread imwrite imfinfo imformats frame2im im2frame im2java ind2rgb rgb2ind imapprox dither cmpermute cmunique print printopt printdlg printpreview orient savefig openfig hgexport hgsave hgload saveas gca gcf gcbf gcbo gco ancestor allchild findall findfigs findobj gobjects ishghandle ishandle copyobj delete get set propedit rootobject figure axes image light line patch rectangle surface text annotation set get hggroup hgtransform makehgtform figure gcf close clf refresh newplot shg closereq dragrect drawnow rbbox opengl axes hold ishold newplot linkaxes linkprop refreshdata waitfor get set if for parfor switch try while break continue end pause return edit input publish notebook grabcode snapnow function nargin nargout varargin varargout narginchk nargoutchk validateattributes validatestring inputname persistent isvarname namelengthmax assignin global isglobal try error warning lastwarn assert oncleanup dbclear dbcont dbdown dbquit dbstack dbstatus dbstep dbstop dbtype dbup checkcode keyboard mlintrpt edit echo eval evalc evalin feval run builtin mfilename pcode clear clearvars disp openvar who whos load save matfile importdata uiimport csvread csvwrite dlmread dlmwrite textscan readtable writetable type xlsfinfo xlsread xlswrite readtable writetable fclose feof ferror fgetl fgets fileread fopen fprintf fread frewind fscanf fseek ftell fwrite im2java imfinfo imread imwrite nccreate ncdisp ncinfo ncread ncreadatt ncwrite ncwriteatt ncwriteschema netcdf h5create h5disp h5info h5read h5readatt h5write h5writeatt hdfinfo hdfread imread imwrite hdfan hdfhx hdfh hdfhd hdfhe hdfml hdfpt hdfv hdfvf hdfvh hdfvs hdfdf24 hdfdfr8 fitsdisp fitsinfo fitsread fitswrite multibandread multibandwrite cdfepoch cdfinfo cdfread cdfwrite todatenum cdflib audioinfo audioread audiowrite mmfileinfo movie2avi audiodevinfo audioplayer audiorecorder sound soundsc beep lin2mu mu2lin xmlread xmlwrite xslt memmapfile dir ls pwd fileattrib exist isdir type visdiff what which cd copyfile delete recycle mkdir movefile rmdir open winopen fileparts fullfile filemarker filesep tempdir tempname matlabroot toolboxdir zip unzip gzip gunzip tar untar addpath rmpath path savepath userpath genpath pathsep pathtool restoredefaultpath clipboard computer dos getenv perl setenv system unix winqueryreg sendmail urlread urlwrite web instrcallback instrfind instrfindall readasync record serial serialbreak stopasync supportpackageinstaller raspi_examples targetupdater raspi raspi writeled showleds raspi configuredigitalpin readdigitalpin writedigitalpin showpins raspi raspi scani2cbus i2cdev readregister writeregister enablei2c disablei2c raspi spidev writeread enablespi disablespi raspi cameraboard raspi openshell getfile putfile deletefile webcamlist webcam preview snapshot closepreview guide inspect figure axes uicontrol uitable uipanel uibuttongroup actxcontrol uimenu uicontextmenu uitoolbar uipushtool uitoggletool dialog errordlg helpdlg msgbox questdlg uigetpref uisetpref waitbar warndlg export2wsdlg inputdlg listdlg uisetcolor uisetfont printdlg printpreview uigetdir uigetfile uiopen uiputfile uisave menu align movegui getpixelposition setpixelposition listfonts textwrap uistack uiwait uiresume waitfor waitforbuttonpress getappdata setappdata isappdata rmappdata guidata guihandles classdef class isa isequal isobject enumeration events methods properties classdef import properties isprop dynamicprops methods ismethod handle hgsetget dynamicprops isa events empty superclasses enumeration save load saveobj loadobj cat horzcat vertcat empty disp display numel size end subsref subsasgn subsindex substruct disp display details metaclass mexext inmem loadlibrary unloadlibrary libisloaded calllib libfunctions libfunctionsview libstruct libpointer javaarray javaclasspath javaaddpath javarmpath javachk isjava usejava javamethod javamethodedt javaobject javaobjectedt cell class clear depfun exist fieldnames im2java import inmem inspect isa methods methodsview which net enablenetfromnetworkdrive cell begininvoke endinvoke combine remove removeall bitand bitor bitxor bitnot actxserver actxcontrol actxcontrollist actxcontrolselect iscom addproperty deleteproperty inspect fieldnames methods methodsview invoke isevent eventlisteners registerevent unregisterallevents unregisterevent isinterface interfaces release move callsoapservice createclassfromwsdl createsoapmessage parsesoapresponse try addcausemexception getreportmexception lastmexception rethrowmexception throwmexception throwascallermexception mexception functiontests runtests bench cputime memory profile profsave tic timeit toc clear inmem memory pack whos commandhistory commandwindow filebrowser workspace getpref setpref addpref rmpref ispref builddocsearchdb mex execute getchararray putchararray getfullmatrix putfullmatrix getvariable getworkspacedata putworkspacedata maximizecommandwindow minimizecommandwindow actxgetrunningserver enableservice mex dbmex mexext inmem ver computer mexext dbmex inmem mex mexext checkin checkout cmopts customverctrl undocheckout verctrl matlabwindows matlabunix exit quit matlabrc startup finish prefdir preferences ismac ispc isstudent isunix javachk license usejava ver verlessthan version doc help docsearch lookfor demo echodemo)
7
+ @builtins ||= Set.new %w(ans clc diary format home iskeyword more zeros ones rand true false eye diag blkdiag cat horzcat vertcat repelem repmat linspace logspace freqspace meshgrid ndgrid length size ndims numel isscalar isvector ismatrix isrow iscolumn isempty sort sortrows issorted issortedrows flip fliplr flipud rot90 transpose ctranspose permute ipermute circshift shiftdim reshape squeeze colon end ind2sub sub2ind plus uplus minus uminus times rdivide ldivide power mtimes mrdivide mldivide mpower cumprod cumsum diff movsum prod sum ceil fix floor idivide mod rem round bsxfun eq ge gt le lt ne isequal isequaln logicaloperatorsshortcircuit and not or xor all any false find islogical logical true intersect ismember ismembertol issorted setdiff setxor union unique uniquetol join innerjoin outerjoin bitand bitcmp bitget bitor bitset bitshift bitxor swapbytes double single int8 int16 int32 int64 uint8 uint16 uint32 uint64 cast typecast isinteger isfloat isnumeric isreal isfinite isinf isnan eps flintmax inf intmax intmin nan realmax realmin string strings join char cellstr blanks newline compose sprintf strcat ischar iscellstr isstring strlength isstrprop isletter isspace contains count endswith startswith strfind sscanf replace replacebetween strrep join split splitlines strjoin strsplit strtok erase erasebetween extractafter extractbefore extractbetween insertafter insertbefore pad strip lower upper reverse deblank strtrim strjust strcmp strcmpi strncmp strncmpi regexp regexpi regexprep regexptranslate datetime timezones years days hours minutes seconds milliseconds duration calyears calquarters calmonths calweeks caldays calendarduration exceltime juliandate posixtime yyyymmdd year quarter month week day hour minute second ymd hms split time timeofday isdst isweekend tzoffset between caldiff dateshift isbetween isdatetime isduration iscalendarduration isnat nat datenum datevec datestr char cellstr string now clock date calendar eomday weekday addtodate etime categorical iscategorical discretize categories iscategory isordinal isprotected addcats mergecats removecats renamecats reordercats setcats summary countcats isundefined table array2table cell2table struct2table table2array table2cell table2struct readtable writetable detectimportoptions istable head tail height width summary intersect ismember setdiff setxor unique union join innerjoin outerjoin sortrows stack unstack vartype ismissing standardizemissing rmmissing fillmissing varfun rowfun findgroups splitapply timetable retime synchronize lag table2timetable array2timetable timetable2table istimetable isregular timerange withtol vartype rmmissing issorted sortrows unique struct fieldnames getfield isfield isstruct orderfields rmfield setfield arrayfun structfun table2struct struct2table cell2struct struct2cell cell cell2mat cell2struct cell2table celldisp cellfun cellplot cellstr iscell iscellstr mat2cell num2cell strjoin strsplit struct2cell table2cell feval func2str str2func localfunctions functions addevent delevent gettsafteratevent gettsafterevent gettsatevent gettsbeforeatevent gettsbeforeevent gettsbetweenevents gettscollection isemptytscollection lengthtscollection settscollection sizetscollection tscollection addsampletocollection addts delsamplefromcollection getabstimetscollection getsampleusingtimetscollection gettimeseriesnames horzcattscollection removets resampletscollection setabstimetscollection settimeseriesnames vertcattscollection isa iscalendarduration iscategorical iscell iscellstr ischar isdatetime isduration isfield isfloat isgraphics isinteger isjava islogical isnumeric isobject isreal isenum isstruct istable is class validateattributes whos char cellstr int2str mat2str num2str str2double str2num native2unicode unicode2native base2dec bin2dec dec2base dec2bin dec2hex hex2dec hex2num num2hex table2array table2cell table2struct array2table cell2table struct2table cell2mat cell2struct mat2cell num2cell struct2cell plus uplus minus uminus times rdivide ldivide power mtimes mrdivide mldivide mpower cumprod cumsum diff movsum prod sum ceil fix floor idivide mod rem round bsxfun sin sind asin asind sinh asinh cos cosd acos acosd cosh acosh tan tand atan atand atan2 atan2d tanh atanh csc cscd acsc acscd csch acsch sec secd asec asecd sech asech cot cotd acot acotd coth acoth hypot deg2rad rad2deg exp expm1 log log10 log1p log2 nextpow2 nthroot pow2 reallog realpow realsqrt sqrt abs angle complex conj cplxpair i imag isreal j real sign unwrap factor factorial gcd isprime lcm nchoosek perms primes rat rats poly polyeig polyfit residue roots polyval polyvalm conv deconv polyint polyder airy besselh besseli besselj besselk bessely beta betainc betaincinv betaln ellipj ellipke erf erfc erfcinv erfcx erfinv expint gamma gammainc gammaincinv gammaln legendre psi cart2pol cart2sph pol2cart sph2cart eps flintmax i j inf pi nan isfinite isinf isnan compan gallery hadamard hankel hilb invhilb magic pascal rosser toeplitz vander wilkinson mldivide mrdivide linsolve inv pinv lscov lsqnonneg sylvester eig eigs balance svd svds gsvd ordeig ordqz ordschur polyeig qz hess schur rsf2csf cdf2rdf lu ldl chol cholupdate qr qrdelete qrinsert qrupdate planerot transpose ctranspose mtimes mpower sqrtm expm logm funm kron cross dot bandwidth tril triu isbanded isdiag ishermitian issymmetric istril istriu norm normest cond condest rcond condeig det null orth rank rref trace subspace rand randn randi randperm rng interp1 interp2 interp3 interpn pchip spline ppval mkpp unmkpp padecoef interpft ndgrid meshgrid griddata griddatan fminbnd fminsearch lsqnonneg fzero optimget optimset ode45 ode23 ode113 ode15s ode23s ode23t ode23tb ode15i decic odeget odeset deval odextend bvp4c bvp5c bvpinit bvpxtend bvpget bvpset deval dde23 ddesd ddensd ddeget ddeset deval pdepe pdeval integral integral2 integral3 quadgk quad2d cumtrapz trapz polyint del2 diff gradient polyder fft fft2 fftn fftshift fftw ifft ifft2 ifftn ifftshift nextpow2 interpft conv conv2 convn deconv filter filter2 ss2tf padecoef spalloc spdiags speye sprand sprandn sprandsym sparse spconvert issparse nnz nonzeros nzmax spfun spones spparms spy find full amd colamd colperm dmperm randperm symamd symrcm pcg minres symmlq gmres bicg bicgstab bicgstabl cgs qmr tfqmr lsqr ichol ilu eigs svds normest condest sprank etree symbfact spaugment dmperm etreeplot treelayout treeplot gplot unmesh graph digraph tetramesh trimesh triplot trisurf delaunay delaunayn tetramesh trimesh triplot trisurf dsearchn tsearchn delaunay delaunayn boundary alphashape convhull convhulln patch voronoi voronoin polyarea inpolygon rectint plot plot3 loglog semilogx semilogy errorbar fplot fplot3 fimplicit linespec colorspec bar bar3 barh bar3h histogram histcounts histogram2 histcounts2 rose pareto area pie pie3 stem stairs stem3 scatter scatter3 spy plotmatrix heatmap polarplot polarscatter polarhistogram compass ezpolar rlim thetalim rticks thetaticks rticklabels thetaticklabels rtickformat thetatickformat rtickangle polaraxes contour contourf contourc contour3 contourslice clabel fcontour feather quiver compass quiver3 streamslice streamline surf surfc surface surfl surfnorm mesh meshc meshz hidden fsurf fmesh fimplicit3 waterfall ribbon contour3 peaks cylinder ellipsoid sphere pcolor surf2patch contourslice flow isocaps isocolors isonormals isosurface reducepatch reducevolume shrinkfaces slice smooth3 subvolume volumebounds coneplot curl divergence interpstreamspeed stream2 stream3 streamline streamparticles streamribbon streamslice streamtube fill fill3 patch surf2patch movie getframe frame2im im2frame animatedline comet comet3 drawnow refreshdata title xlabel ylabel zlabel clabel legend colorbar text texlabel gtext line rectangle annotation xlim ylim zlim axis box daspect pbaspect grid xticks yticks zticks xticklabels yticklabels zticklabels xtickformat ytickformat ztickformat xtickangle ytickangle ztickangle datetick ruler2num num2ruler hold subplot yyaxis cla axes figure colormap colorbar rgbplot colormapeditor brighten contrast caxis spinmap hsv2rgb rgb2hsv parula jet hsv hot cool spring summer autumn winter gray bone copper pink lines colorcube prism flag view makehgtform viewmtx cameratoolbar campan camzoom camdolly camlookat camorbit campos camproj camroll camtarget camup camva camlight light lightangle lighting shading diffuse material specular alim alpha alphamap imshow image imagesc imread imwrite imfinfo imformats frame2im im2frame im2java im2double ind2rgb rgb2gray rgb2ind imapprox dither cmpermute cmunique print saveas getframe savefig openfig orient hgexport printopt get set reset inspect gca gcf gcbf gcbo gco groot ancestor allchild findall findobj findfigs gobjects isgraphics ishandle copyobj delete gobjects isgraphics isempty isequal isa clf cla close uicontextmenu uimenu dragrect rbbox refresh shg hggroup hgtransform makehgtform eye hold ishold newplot clf cla drawnow opengl readtable detectimportoptions writetable textscan dlmread dlmwrite csvread csvwrite type readtable detectimportoptions writetable xlsfinfo xlsread xlswrite importdata im2java imfinfo imread imwrite nccreate ncdisp ncinfo ncread ncreadatt ncwrite ncwriteatt ncwriteschema h5create h5disp h5info h5read h5readatt h5write h5writeatt hdfinfo hdfread hdftool imread imwrite hdfan hdfhx hdfh hdfhd hdfhe hdfml hdfpt hdfv hdfvf hdfvh hdfvs hdfdf24 hdfdfr8 fitsdisp fitsinfo fitsread fitswrite multibandread multibandwrite cdfinfo cdfread cdfepoch todatenum audioinfo audioread audiowrite videoreader videowriter mmfileinfo lin2mu mu2lin audiodevinfo audioplayer audiorecorder sound soundsc beep xmlread xmlwrite xslt load save matfile disp who whos clear clearvars openvar fclose feof ferror fgetl fgets fileread fopen fprintf fread frewind fscanf fseek ftell fwrite tcpclient web webread webwrite websave weboptions sendmail jsondecode jsonencode readasync serial serialbreak seriallist stopasync instrcallback instrfind instrfindall record tabulartextdatastore imagedatastore spreadsheetdatastore filedatastore datastore tall datastore mapreducer gather head tail topkrows istall classunderlying isaunderlying write mapreduce datastore add addmulti hasnext getnext mapreducer gcmr matfile memmapfile ismissing rmmissing fillmissing missing standardizemissing isoutlier filloutliers smoothdata movmean movmedian detrend filter filter2 discretize histcounts histcounts2 findgroups splitapply rowfun varfun accumarray min max bounds mean median mode std var corrcoef cov cummax cummin movmad movmax movmean movmedian movmin movprod movstd movsum movvar pan zoom rotate rotate3d brush datacursormode ginput linkdata linkaxes linkprop refreshdata figurepalette plotbrowser plotedit plottools propertyeditor propedit showplottool if for parfor switch try while break continue end pause return edit input publish grabcode snapnow function nargin nargout varargin varargout narginchk nargoutchk validateattributes validatestring inputname isvarname namelengthmax persistent assignin global mlock munlock mislocked try error warning lastwarn assert oncleanup addpath rmpath path savepath userpath genpath pathsep pathtool restoredefaultpath rehash dir ls pwd fileattrib exist isdir type visdiff what which cd copyfile delete recycle mkdir movefile rmdir open winopen zip unzip gzip gunzip tar untar fileparts fullfile filemarker filesep tempdir tempname matlabroot toolboxdir dbclear dbcont dbdown dbquit dbstack dbstatus dbstep dbstop dbtype dbup checkcode keyboard mlintrpt edit echo eval evalc evalin feval run builtin mfilename pcode uiaxes uibutton uibuttongroup uicheckbox uidropdown uieditfield uilabel uilistbox uiradiobutton uislider uispinner uitable uitextarea uitogglebutton scroll uifigure uipanel uitabgroup uitab uigauge uiknob uilamp uiswitch uialert questdlg inputdlg listdlg uisetcolor uigetfile uiputfile uigetdir uiopen uisave appdesigner figure axes uicontrol uitable uipanel uibuttongroup uitab uitabgroup uimenu uicontextmenu uitoolbar uipushtool uitoggletool actxcontrol align movegui getpixelposition setpixelposition listfonts textwrap uistack inspect errordlg warndlg msgbox helpdlg waitbar questdlg inputdlg listdlg uisetcolor uisetfont export2wsdlg uigetfile uiputfile uigetdir uiopen uisave printdlg printpreview exportsetupdlg dialog uigetpref guide uiwait uiresume waitfor waitforbuttonpress closereq getappdata setappdata isappdata rmappdata guidata guihandles uisetpref class isobject enumeration events methods properties classdef classdef import properties isprop mustbefinite mustbegreaterthan mustbegreaterthanorequal mustbeinteger mustbelessthan mustbelessthanorequal mustbemember mustbenegative mustbenonempty mustbenonnan mustbenonnegative mustbenonpositive mustbenonsparse mustbenonzero mustbenumeric mustbenumericorlogical mustbepositive mustbereal methods ismethod isequal eq events superclasses enumeration isenum numargumentsfromsubscript subsref subsasgn subsindex substruct builtin empty disp display details saveobj loadobj edit metaclass properties methods events superclasses step clone getnuminputs getnumoutputs islocked resetsystemobject releasesystemobject mexext inmem loadlibrary unloadlibrary libisloaded calllib libfunctions libfunctionsview libstruct libpointer import isjava javaaddpath javaarray javachk javaclasspath javamethod javamethodedt javaobject javaobjectedt javarmpath usejava net enablenetfromnetworkdrive cell begininvoke endinvoke combine remove removeall bitand bitor bitxor bitnot actxserver actxcontrol actxcontrollist actxcontrolselect actxgetrunningserver iscom addproperty deleteproperty inspect fieldnames methods methodsview invoke isevent eventlisteners registerevent unregisterallevents unregisterevent isinterface interfaces release move pyversion pyargs pyargs pyargs builddocsearchdb try assert runtests testsuite functiontests runtests testsuite runtests testsuite runperf testsuite timeit tic toc cputime profile bench memory inmem pack memoize clearallmemoizedcaches clipboard computer system dos unix getenv setenv perl winqueryreg commandhistory commandwindow filebrowser workspace getpref setpref addpref rmpref ispref mex execute getchararray putchararray getfullmatrix putfullmatrix getvariable getworkspacedata putworkspacedata maximizecommandwindow minimizecommandwindow regmatlabserver enableservice mex dbmex mexext inmem ver computer mexext dbmex inmem mex mexext matlabwindows matlabmac matlablinux exit quit matlabrc startup finish prefdir preferences version ver verlessthan license ispc ismac isunix isstudent javachk usejava doc help docsearch lookfor demo echodemo)
8
8
  end
9
9
  end
10
10
  end
@@ -12,10 +12,14 @@ module Rouge
12
12
  filenames '*.moon'
13
13
  mimetypes 'text/x-moonscript', 'application/x-moonscript'
14
14
 
15
- def initialize(opts={})
16
- @function_highlighting = opts.delete(:function_highlighting) { true }
17
- @disabled_modules = opts.delete(:disabled_modules) { [] }
18
- super(opts)
15
+ option :function_highlighting, 'Whether to highlight builtin functions (default: true)'
16
+ option :disabled_modules, 'builtin modules to disable'
17
+
18
+ def initialize(*)
19
+ super
20
+
21
+ @function_highlighting = bool_option(:function_highlighting) { true }
22
+ @disabled_modules = list_option(:disabled_modules)
19
23
  end
20
24
 
21
25
  def self.analyze_text(text)
@@ -0,0 +1,231 @@
1
+ # -*- coding: utf-8 -*- #
2
+
3
+ module Rouge
4
+ module Lexers
5
+ class Mosel < RegexLexer
6
+ tag 'mosel'
7
+ filenames '*.mos'
8
+ title "Mosel"
9
+ desc "An optimization language used by Fico's Xpress."
10
+ # http://www.fico.com/en/products/fico-xpress-optimization-suite
11
+ filenames '*.mos'
12
+
13
+ mimetypes 'text/x-mosel'
14
+
15
+ def self.analyze_text(text)
16
+ return 1 if text =~ /^\s*(model|package)\s+/
17
+ end
18
+
19
+ id = /[a-zA-Z_][a-zA-Z0-9_]*/
20
+
21
+ ############################################################################################################################
22
+ # General language lements
23
+ ############################################################################################################################
24
+
25
+ core_keywords = %w(
26
+ and array as
27
+ boolean break
28
+ case count counter
29
+ declarations div do dynamic
30
+ elif else end evaluation exit
31
+ false forall forward from function
32
+ if imports in include initialisations initializations integer inter is_binary is_continuous is_free is_integer is_partint is_semcont is_semint is_sos1 is_sos2
33
+ linctr list
34
+ max min mod model mpvar
35
+ next not of options or
36
+ package parameters procedure
37
+ public prod range real record repeat requirements
38
+ set string sum
39
+ then to true
40
+ union until uses
41
+ version
42
+ while with
43
+ )
44
+
45
+ core_functions = %w(
46
+ abs arctan assert
47
+ bitflip bitneg bitset bitshift bittest bitval
48
+ ceil cos create currentdate currenttime cuthead cuttail
49
+ delcell exists exit exp exportprob
50
+ fclose fflush finalize findfirst findlast floor fopen fselect fskipline
51
+ getact getcoeff getcoeffs getdual getfid getfirst gethead getfname getlast getobjval getparam getrcost getreadcnt getreverse getsize getslack getsol gettail gettype getvars
52
+ iseof ishidden isodd ln log
53
+ makesos1 makesos2 maxlist minlist
54
+ publish
55
+ random read readln reset reverse round
56
+ setcoeff sethidden setioerr setname setparam setrandseed settype sin splithead splittail sqrt strfmt substr
57
+ timestamp
58
+ unpublish
59
+ write writeln
60
+ )
61
+
62
+ ############################################################################################################################
63
+ # mmxprs module elements
64
+ ############################################################################################################################
65
+
66
+ mmxprs_functions = %w(
67
+ addmipsol
68
+ basisstability
69
+ calcsolinfo clearmipdir clearmodcut command copysoltoinit
70
+ defdelayedrows defsecurevecs
71
+ estimatemarginals
72
+ fixglobal
73
+ getbstat getdualray getiis getiissense getiistype getinfcause getinfeas getlb getloadedlinctrs getloadedmpvars getname getprimalray getprobstat getrange getsensrng getsize getsol getub getvars
74
+ implies indicator isiisvalid isintegral loadbasis
75
+ loadmipsol loadprob
76
+ maximize, minimize
77
+ postsolve
78
+ readbasis readdirs readsol refinemipsol rejectintsol repairinfeas resetbasis resetiis resetsol
79
+ savebasis savemipsol savesol savestate selectsol setbstat setcallback setcbcutoff setgndata setlb setmipdir setmodcut setsol setub setucbdata stopoptimize
80
+ unloadprob
81
+ writebasis writedirs writeprob writesol
82
+ xor
83
+ )
84
+
85
+ mmxpres_constants = %w(XPRS_OPT XPRS_UNF XPRS_INF XPRS_UNB XPRS_OTH)
86
+
87
+ mmxprs_parameters = %w(XPRS_colorder XPRS_enumduplpol XPRS_enummaxsol XPRS_enumsols XPRS_fullversion XPRS_loadnames XPRS_problem XPRS_probname XPRS_verbose)
88
+
89
+
90
+ ############################################################################################################################
91
+ # mmsystem module elements
92
+ ############################################################################################################################
93
+
94
+ mmsystem_functions = %w(
95
+ addmonths
96
+ copytext cuttext
97
+ deltext
98
+ endswith expandpath
99
+ fcopy fdelete findfiles findtext fmove
100
+ getasnumber getchar getcwd getdate getday getdaynum getdays getdirsep
101
+ getendparse setendparse
102
+ getenv getfsize getfstat getftime gethour getminute getmonth getmsec getpathsep
103
+ getqtype, setqtype
104
+ getsecond
105
+ getsepchar, setsepchar
106
+ getsize
107
+ getstart, setstart
108
+ getsucc, setsucc
109
+ getsysinfo getsysstat gettime
110
+ gettmpdir
111
+ gettrim, settrim
112
+ getweekday getyear
113
+ inserttext isvalid
114
+ makedir makepath newtar
115
+ newzip nextfield
116
+ openpipe
117
+ parseextn parseint parsereal parsetext pastetext pathmatch pathsplit
118
+ qsort quote
119
+ readtextline regmatch regreplace removedir removefiles
120
+ setchar setdate setday setenv sethour
121
+ setminute setmonth setmsec setsecond settime setyear sleep startswith system
122
+ tarlist textfmt tolower toupper trim
123
+ untar unzip
124
+ ziplist
125
+ )
126
+
127
+ mmsystem_parameters = %w(datefmt datetimefmt monthnames sys_endparse sys_fillchar sys_pid sys_qtype sys_regcache sys_sepchar)
128
+
129
+ ############################################################################################################################
130
+ # mmjobs module elements
131
+ ############################################################################################################################
132
+
133
+ mmjobs_instance_mgmt_functions = %w(
134
+ clearaliases connect
135
+ disconnect
136
+ findxsrvs
137
+ getaliases getbanner gethostalias
138
+ sethostalias
139
+ )
140
+
141
+ mmjobs_model_mgmt_functions = %w(
142
+ compile
143
+ detach
144
+ getannidents getannotations getexitcode getgid getid getnode getrmtid getstatus getuid
145
+ load
146
+ reset resetmodpar run
147
+ setcontrol setdefstream setmodpar setworkdir stop
148
+ unload
149
+ )
150
+
151
+ mmjobs_synchornization_functions = %w(
152
+ dropnextevent
153
+ getclass getfromgid getfromid getfromuid getnextevent getvalue
154
+ isqueueempty
155
+ nullevent
156
+ peeknextevent
157
+ send setgid setuid
158
+ wait waitfor
159
+ )
160
+
161
+ mmjobs_functions = mmjobs_instance_mgmt_functions + mmjobs_model_mgmt_functions + mmjobs_synchornization_functions
162
+
163
+ mmjobs_parameters = %w(conntmpl defaultnode fsrvdelay fsrvnbiter fsrvport jobid keepalive nodenumber parentnumber)
164
+
165
+
166
+ state :whitespace do
167
+ # Spaces
168
+ rule /\s+/m, Text
169
+ # ! Comments
170
+ rule %r((!).*$\n?), Comment::Single
171
+ # (! Comments !)
172
+ rule %r(\(!.*?!\))m, Comment::Multiline
173
+
174
+ end
175
+
176
+
177
+ # From Mosel documentation:
178
+ # Constant strings of characters must be quoted with single (') or double quote (") and may extend over several lines. Strings enclosed in double quotes may contain C-like escape sequences introduced by the 'backslash'
179
+ # character (\a \b \f \n \r \t \v \xxx with xxx being the character code as an octal number).
180
+ # Each sequence is replaced by the corresponding control character (e.g. \n is the `new line' command) or, if no control character exists, by the second character of the sequence itself (e.g. \\ is replaced by '\').
181
+ # The escape sequences are not interpreted if they are contained in strings that are enclosed in single quotes.
182
+
183
+ state :single_quotes do
184
+ rule /'/, Str::Single, :pop!
185
+ rule /[^']+/, Str::Single
186
+ end
187
+
188
+ state :double_quotes do
189
+ rule /"/, Str::Double, :pop!
190
+ rule /(\\"|\\[0-7]{1,3}\D|\\[abfnrtv]|\\\\)/, Str::Escape
191
+ rule /[^"]/, Str::Double
192
+ end
193
+
194
+ state :base do
195
+
196
+ rule %r{"}, Str::Double, :double_quotes
197
+ rule %r{'}, Str::Single, :single_quotes
198
+
199
+ rule %r{((0(x|X)[0-9a-fA-F]*)|(([0-9]+\.?[0-9]*)|(\.[0-9]+))((e|E)(\+|-)?[0-9]+)?)(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?}, Num
200
+ rule %r{[~!@#\$%\^&\*\(\)\+`\-={}\[\]:;<>\?,\.\/\|\\]}, Punctuation
201
+ # rule %r{'([^']|'')*'}, Str
202
+ # rule /"(\\\\|\\"|[^"])*"/, Str
203
+
204
+
205
+
206
+ rule /(true|false)\b/i, Name::Builtin
207
+ rule /\b(#{core_keywords.join('|')})\b/i, Keyword
208
+ rule /\b(#{core_functions.join('|')})\b/, Name::Builtin
209
+
210
+
211
+
212
+ rule /\b(#{mmxprs_functions.join('|')})\b/, Name::Function
213
+ rule /\b(#{mmxpres_constants.join('|')})\b/, Name::Constant
214
+ rule /\b(#{mmxprs_parameters.join('|')})\b/i, Name::Property
215
+
216
+ rule /\b(#{mmsystem_functions.join('|')})\b/i, Name::Function
217
+ rule /\b(#{mmsystem_parameters.join('|')})\b/, Name::Property
218
+
219
+ rule /\b(#{mmjobs_functions.join('|')})\b/i, Name::Function
220
+ rule /\b(#{mmjobs_parameters.join('|')})\b/, Name::Property
221
+
222
+ rule id, Name
223
+ end
224
+
225
+ state :root do
226
+ mixin :whitespace
227
+ mixin :base
228
+ end
229
+ end
230
+ end
231
+ end
@@ -4,7 +4,7 @@ module Rouge
4
4
  module Lexers
5
5
  class OCaml < RegexLexer
6
6
  title "OCaml"
7
- desc 'Objective CAML (ocaml.org)'
7
+ desc 'Objective Caml (ocaml.org)'
8
8
  tag 'ocaml'
9
9
  filenames '*.ml', '*.mli', '*.mll', '*.mly'
10
10
  mimetypes 'text/x-ocaml'
@@ -14,15 +14,8 @@ module Rouge
14
14
  as assert begin class constraint do done downto else end
15
15
  exception external false for fun function functor if in include
16
16
  inherit initializer lazy let match method module mutable new
17
- object of open private raise rec sig struct then to true try
18
- type value val virtual when while with
19
- )
20
- end
21
-
22
- def self.keyopts
23
- @keyopts ||= Set.new %w(
24
- != # & && ( ) * \+ , - -. -> . .. : :: := :> ; ;; < <- =
25
- > >] >} ? ?? [ [< [> [| ] _ ` { {< | |] } ~
17
+ nonrec object of open private raise rec sig struct then to true
18
+ try type val virtual when while with
26
19
  )
27
20
  end
28
21
 
@@ -34,14 +27,15 @@ module Rouge
34
27
  @primitives ||= Set.new %w(unit int float bool string char list array)
35
28
  end
36
29
 
37
- operator = %r([\[\];,{}_()!$%&*+./:<=>?@^|~#-]+)
38
- id = /[a-z][\w']*/i
30
+ operator = %r([;,_!$%&*+./:<=>?@^|~#-]+)
31
+ id = /[a-z_][\w']*/i
39
32
  upper_id = /[A-Z][\w']*/
40
33
 
41
34
  state :root do
42
35
  rule /\s+/m, Text
43
36
  rule /false|true|[(][)]|\[\]/, Name::Builtin::Pseudo
44
37
  rule /#{upper_id}(?=\s*[.])/, Name::Namespace, :dotted
38
+ rule /`#{id}/, Name::Tag
45
39
  rule upper_id, Name::Class
46
40
  rule /[(][*](?![)])/, Comment, :comment
47
41
  rule id do |m|
@@ -57,14 +51,8 @@ module Rouge
57
51
  end
58
52
  end
59
53
 
60
- rule operator do |m|
61
- match = m[0]
62
- if self.class.keyopts.include? match
63
- token Punctuation
64
- else
65
- token Operator
66
- end
67
- end
54
+ rule /[(){}\[\];]+/, Punctuation
55
+ rule operator, Operator
68
56
 
69
57
  rule /-?\d[\d_]*(.[\d_]*)?(e[+-]?\d[\d_]*)/i, Num::Float
70
58
  rule /0x\h[\h_]*/i, Num::Hex
@@ -105,6 +93,7 @@ module Rouge
105
93
  rule /#{upper_id}(?=\s*[.])/, Name::Namespace
106
94
  rule upper_id, Name::Class, :pop!
107
95
  rule id, Name, :pop!
96
+ rule /[({\[]/, Punctuation, :pop!
108
97
  end
109
98
  end
110
99
  end
@@ -13,16 +13,18 @@ module Rouge
13
13
  '*.module', '*.inc', '*.profile', '*.install', '*.test'
14
14
  mimetypes 'text/x-php'
15
15
 
16
- default_options :parent => 'html'
16
+ option :start_inline, 'Whether to start with inline php or require <?php ... ?>. (default: best guess)'
17
+ option :funcnamehighlighting, 'Whether to highlight builtin functions (default: true)'
18
+ option :disabledmodules, 'Disable certain modules from being highlighted as builtins (default: empty)'
19
+
20
+ def initialize(*)
21
+ super
17
22
 
18
- def initialize(opts={})
19
23
  # if truthy, the lexer starts highlighting with php code
20
24
  # (no <?php required)
21
- @start_inline = opts.delete(:start_inline)
22
- @funcnamehighlighting = opts.delete(:funcnamehighlighting) { true }
23
- @disabledmodules = opts.delete(:disabledmodules) { [] }
24
-
25
- super(opts)
25
+ @start_inline = bool_option(:start_inline) { :guess }
26
+ @funcnamehighlighting = bool_option(:funcnamehighlighting) { true }
27
+ @disabledmodules = list_option(:disabledmodules)
26
28
  end
27
29
 
28
30
  def self.builtins
@@ -41,12 +43,22 @@ module Rouge
41
43
  end
42
44
  end
43
45
 
44
- def start_inline?
45
- !!@start_inline
46
- end
46
+ # source: http://php.net/manual/en/language.variables.basics.php
47
+ # the given regex is invalid utf8, so... we're using the unicode
48
+ # "Letter" property instead.
49
+ id = /[\p{L}_][\p{L}\p{N}_]*/
50
+ nsid = /#{id}(?:\\#{id})*/
47
51
 
48
52
  start do
49
- push :php if start_inline?
53
+ case @start_inline
54
+ when true
55
+ push :template
56
+ push :php
57
+ when false
58
+ push :template
59
+ when :guess
60
+ # pass
61
+ end
50
62
  end
51
63
 
52
64
  def self.keywords
@@ -70,6 +82,14 @@ module Rouge
70
82
  end
71
83
 
72
84
  state :root do
85
+ # some extremely rough heuristics to decide whether to start inline or not
86
+ rule(/\s*(?=<)/m) { delegate parent; push :template }
87
+ rule(/[^$]+(?=<\?(php|=))/) { delegate parent; push :template }
88
+
89
+ rule(//) { push :template; push :php }
90
+ end
91
+
92
+ state :template do
73
93
  rule /<\?(php|=)?/, Comment::Preproc, :php
74
94
  rule(/.*?(?=<\?)|.*/m) { delegate parent }
75
95
  end
@@ -77,7 +97,7 @@ module Rouge
77
97
  state :php do
78
98
  rule /\?>/, Comment::Preproc, :pop!
79
99
  # heredocs
80
- rule /<<<('?)([a-z_]\w*)\1\n.*?\n\2;?\n/im, Str::Heredoc
100
+ rule /<<<('?)(#{id})\1\n.*?\n\2;?\n/im, Str::Heredoc
81
101
  rule /\s+/, Text
82
102
  rule /#.*?\n/, Comment::Single
83
103
  rule %r(//.*?\n), Comment::Single
@@ -85,7 +105,7 @@ module Rouge
85
105
  rule %r(/\*\*/), Comment::Multiline
86
106
  rule %r(/\*\*.*?\*/)m, Str::Doc
87
107
  rule %r(/\*.*?\*/)m, Comment::Multiline
88
- rule /(->|::)(\s*)([a-zA-Z_][a-zA-Z0-9_]*)/ do
108
+ rule /(->|::)(\s*)(#{id})/ do
89
109
  groups Operator, Text, Name::Attribute
90
110
  end
91
111
 
@@ -103,16 +123,16 @@ module Rouge
103
123
  push :funcname
104
124
  end
105
125
 
106
- rule /(const)(\s+)([a-zA-Z_]\w*)/i do
126
+ rule /(const)(\s+)(#{id})/i do
107
127
  groups Keyword, Text, Name::Constant
108
128
  end
109
129
 
110
130
  rule /(true|false|null)\b/, Keyword::Constant
111
- rule /\$\{\$+[a-z_]\w*\}/i, Name::Variable
112
- rule /\$+[a-z_]\w*/i, Name::Variable
131
+ rule /\$\{\$+#{id}\}/i, Name::Variable
132
+ rule /\$+#{id}/i, Name::Variable
113
133
 
114
134
  # may be intercepted for builtin highlighting
115
- rule /[\\a-z_][\\\w]*/i do |m|
135
+ rule /\\?#{nsid}/i do |m|
116
136
  name = m[0]
117
137
 
118
138
  if self.class.keywords.include? name
@@ -136,11 +156,11 @@ module Rouge
136
156
 
137
157
  state :classname do
138
158
  rule /\s+/, Text
139
- rule /[a-z_][\\\w]*/i, Name::Class, :pop!
159
+ rule /#{nsid}/, Name::Class, :pop!
140
160
  end
141
161
 
142
162
  state :funcname do
143
- rule /[a-z_]\w*/i, Name::Function, :pop!
163
+ rule /#{id}/, Name::Function, :pop!
144
164
  end
145
165
 
146
166
  state :string do
@@ -148,7 +168,7 @@ module Rouge
148
168
  rule /[^\\{$"]+/, Str::Double
149
169
  rule /\\([nrt\"$\\]|[0-7]{1,3}|x[0-9A-Fa-f]{1,2})/,
150
170
  Str::Escape
151
- rule /\$[a-zA-Z_][a-zA-Z0-9_]*(\[\S+\]|->[a-zA-Z_][a-zA-Z0-9_]*)?/, Name::Variable
171
+ rule /\$#{id}(\[\S+\]|->#{id})?/, Name::Variable
152
172
 
153
173
  rule /\{\$\{/, Str::Interpol, :interp_double
154
174
  rule /\{(?=\$)/, Str::Interpol, :interp_single