TeX highlight in Markdown/GFM mode

I am working on a markdown editor. And I have math syntax $...$ and $$...$$. To highlight them, I tried to use multiplexing mode. Like this:

CodeMirror.defineMode('mathdown', function(config) {
    var options = [];
    var ref = [['$$', '$$'], ['$', '$']];
    for (var i = 0, len = ref.length; i < len; i++) {
        var x = ref[i];
            open: x[0],
            close: x[1],
            mode: CodeMirror.getMode(config, 'stex')
    return CodeMirror.multiplexingMode.apply(CodeMirror, [CodeMirror.getMode(config, 'gfm')].concat([].slice.call(options)));

There’s a problem is the math syntax conflicts with the code syntax. For example when I write


The $ begins a inline math, but It should be in a code and display a $.

Is there a better way?