Vivek Rai
Vivek Rai

Reputation: 910

Using Codemirror in Vim Mode

I am having a little trouble making this thing up. I want to use Codemirror edit feature in Vim mode only, without any syntax highlighting. That is, if I click in the text area, it is converted in a similar text editor as shown on the demo page VIM Demo. Thanks!

EDIT : If not Codemirror, Please tell me the method how can I convert the text area in which the user clicks to a VIM type edit area. I want to make it as a plugin, so that whenever I click on a text area on some page, it gives me a VIM like (not exactly vim) environment to edit. How should I go about the keybinding thing? Please help!

Upvotes: 3

Views: 4186

Answers (1)

Eliran Malka
Eliran Malka

Reputation: 16263

CodeMirror takes care of all the key bindings (and key mapping for vim mode), so all you have to do is create an editor instance for the textarea at hand.

Check out CodeMirror.fromTextArea() on the docs, under the section on static methods, to see how it's done.

You can also refer to the vim bindings demo and simply take a look at the source. This is how the CodeMirror instance is initialized there:

1  | CodeMirror.commands.save = function () {
2  |     alert("Saving");
3  | };
4  |
5  | var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
6  |     lineNumbers: true,
7  |     mode: "text/x-csrc",
8  |     keyMap: "vim",
9  |     showCursorWhenSelecting: true
10 | });

Let's take this apart, following line no':

  • 1-3: Assigning a handler for the save command, which maps to :w on vim key bindings. From the docs, on the key bindings section:

    The values of properties in keymaps can be either functions of a single argument (the CodeMirror instance), strings, or false. Such strings refer to properties of the CodeMirror.commands object, which defines a number of common commands that are used by the default keybindings, and maps them to functions

  • 4: The sound of silence.

  • 5: Fetching the textarea element (denoted with code as its ID) from the DOM, and passing it to a static method that will create a CodeMirror instance based on that element.

  • 6-9: Setting various options:

    • 6: Showing line numbers in the gutter.

    • 7: Setting editor mode to C-like to highlight C code.

    • 8: Assign the vim key bindings.

    • 9: Well, showing cursor when selecting.

  • 10: Wrap it up.

In order for the editor mode and key bindings to work, the required scripts need to be loaded, so we'd wanna include those as well:

<script src="../lib/codemirror.js"></script> <!-- main script -->
<script src="../addon/dialog/dialog.js"></script> <!-- addon for vim messages -->
<script src="../addon/search/searchcursor.js"></script> <!-- addon for vim messages -->
<script src="../mode/clike/clike.js"></script> <!-- mode for C-like languages -->
<script src="../keymap/vim.js"></script> <!-- key bindings for vim -->

Upvotes: 8

Related Questions