Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeMirror - language auto-detection

I'm using stand-alone highlighting (not the editor), something like this: http://codemirror.net/demo/runmode.html

How can I auto-detect the language to use when running the highlighter?

There's a mode-autochanging demo here: http://codemirror.net/demo/changemode.html

But I don't know how could I adapt this to work with Codemirror.runMode(). I wish to highlight the entire code block using the auto-detected scheme.

like image 835
Alex Avatar asked Jan 20 '12 15:01

Alex


1 Answers

The "changemode" demo can only distinguish between the "Scheme" programming language and "everything else", see the implementation of

function looksLikeScheme(code) {
    return !/^\s*\(\s*function\b/.test(code) && /^\s*[;\(]/.test(code);
}

So this won't work to auto-detect other programming languages, and as the demo pages says, even for detecting Scheme it's very crude.

Unfortunately, it's not easy to auto-detect a large range of programming languages from a source code snippet (for small snippets, different programming languages might even use the exact same syntax). However, a reasonable approach is suggested in Detecting programming language from a snippet.

like image 95
sschuberth Avatar answered Sep 24 '22 13:09

sschuberth