Skip to content

Commit

Permalink
MATLAB: improve detection and float boundaries.
Browse files Browse the repository at this point in the history
- Detect `.m` files starting with a function definition as MATLAB, not
  ObjC (pygments#1149).
- Require word boundaries in regexes matching numbers and floats, to
  avoid mishighlighting `load 123file` as starting with a number.
  • Loading branch information
anntzer committed Nov 24, 2019
1 parent a0703ef commit 13c8635
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions pygments/lexers/matlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,12 @@ class MatlabLexer(RegexLexer):
# operators requiring escape for re:
(r'\.\*|\*|\+|\.\^|\.\\|\.\/|\/|\\', Operator),

# numbers (must come before punctuation to handle `.5`; cannot use
# `\b` due to e.g. `5. + .5`).
(r'(?<!\w)((\d+\.\d*)|(\d*\.\d+))([eEf][+-]?\d+)?(?!\w)', Number.Float),
(r'\b\d+[eEf][+-]?[0-9]+\b', Number.Float),
(r'\b\d+\b', Number.Integer),

# punctuation:
(r'\[|\]|\(|\)|\{|\}|:|@|\.|,', Punctuation),
(r'=|:|;', Punctuation),
Expand All @@ -107,10 +113,6 @@ class MatlabLexer(RegexLexer):
# (not great, but handles common cases...)
(r'(?<=[\w)\].])\'+', Operator),

(r'(\d+\.\d*|\d*\.\d+)([eEf][+-]?[0-9]+)?', Number.Float),
(r'\d+[eEf][+-]?[0-9]+', Number.Float),
(r'\d+', Number.Integer),

(r'(?<![\w)\].])\'', String, 'string'),
(r'[a-zA-Z_]\w*', Name),
(r'.', Text),
Expand All @@ -134,9 +136,15 @@ class MatlabLexer(RegexLexer):
}

def analyse_text(text):
if re.match(r'^\s*%', text, re.M): # comment
# function declaration.
if next(line for line in text.splitlines()
if not re.match(r'^\s*%', text)).strip().startswith('function'):
return 1.
# comment
elif re.match(r'^\s*%', text, re.M):
return 0.2
elif re.match(r'^!\w+', text, re.M): # system cmd
# system cmd
elif re.match(r'^!\w+', text, re.M):
return 0.2


Expand Down

0 comments on commit 13c8635

Please sign in to comment.