Search code examples
javascriptregexcodemirror

Weird regex behavior using codemirror's simple mode


I'm trying to create a mode that allows Todo.txt format which is very very simple but having a weird regex behavior when codemirror is matching results.

Basically, I'm trying to mark all lines starts with "x" following a space character and having this condition only at the beginning of a line but regex picks up a string in the middle of the line.

My regex doesn't match this condition when trying on other javascript regex tools: https://regex101.com/r/kUXTqf/1

Here is my regex line from the simple mode definition:

{regex: /^(x ).*$/, token: "task-completed"} 

And the text I'm testing against:

x 2017-12-12 @geek add file location preference option +todotxtapp
(A) @geek completed task syntax highlighter rule needs tweak - it includes any character follows with whitespace - starting in the middle of the line +todotxtapp
(B) @geek design new app icon +todotxtapp
(C) @geek add priority shortcut cmd+up/down or similar +todotxtapp
asdasdasdasdasa x dsljhdsfkljg dhsklf sdaf

In practice, it only needs to match the first line. But it matches the half part of the second line and the last line. See result here: http://take.ms/S2PEL


Solution

  • I am not familiar with CodeMirror, but going off of documentation,

    Simple modes (loosely based on the Common JavaScript Syntax Highlighting Specification, which never took off), are state machines, where each state has a number of rules that match tokens.

    The regexp does not work on lines, it works on tokens. Thus, asdasdasdasdasa, x, dsljhdsfklhg are all tested individually; and, unsurprisingly, x matches /^(x ).*$/.

    It seems you want something like this (you might need to tweak it, as I can't test it):

    {regex: /x/, token: "task-completed", sol: true} 
    

    sol: boolean

    When true, this token will only match at the start of the line. (The ^ regexp marker doesn't work as you'd expect in this context because of limitations in JavaScript's RegExp API.)

    EDIT: I must say, I am not quite sure what's happening at syntax.