Search code examples
javascriptcodemirroremmet

expand abbreviation with javascript in Codemirror/emmet


I'am using codemirror and emmet for my project. expansion of emmet abbreviations works great in codemirror editor when done interactively (CTRL+E). I want to get a step further and create code by expanding abbreviations within JavaScript code.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" type="text/css" href="codemirror/lib/codemirror.css">
        <link rel="stylesheet" type="text/css" href="codemirror/lib/codemirror.css">
        <script type="text/javascript" src="codemirror/lib/codemirror.js"></script>
        <script type="text/javascript" src="codemirror/lib/codemirror.js"></script>
        <script type="text/javascript" src="codemirror/mode/xml/xml.js"></script>
        <script type="text/javascript" src="codemirror/mode/javascript/javascript.js"></script>
        <script type="text/javascript" src="codemirror/mode/css/css.js"></script>
        <script type="text/javascript" src="codemirror/mode/htmlmixed/htmlmixed.js"></script>
        <script type="text/javascript" src="resource/emmet.js"></script>
    </head>
    <body>
        <div id="editorContainer"></div>
        <script type="text/javascript">

            var Test = {};
            Test.editor = null;

            Test.init = function() {
                Test.editor = CodeMirror(document.getElementById('editorContainer'), {
                    autofocus: true,
                    lineNumbers: true,
                    mode: "text/html",
                    profile: 'xhtml', /* define Emmet output profile */
                });
                emmetCodeMirror(Test.editor);
                Test.ol();
            }

            Test.ol = function() {
                Test.editor.getDoc().replaceSelection('ol>li*3', 'end');
                Test.editor.focus();
                emmetCodeMirror.emmet.run('expand_abbreviation', Test.editor);
            };

            Test.init();
        </script>
    </body>
</html>

by calling Test.ol() the text ol>li*3 gets inserted but the following execution of

emmetCodeMirror.emmet.run('expand_abbreviation', Test.editor);

results in an TypeError: editor.getProfileName is not a function emmet.js:41541

Can anybody please tell me what I'm doing wrong?

You can download the project here.

Thanks a lot!


Solution

  • You’re passing CodeMirror editor instance to emmet.run() instead of EmmetEditor. Anyway, the ultimate solution is to simply exec registered Emmet command, e.g.

    Test.editor.execCommand('emmet.expand_abbreviation')