Search code examples
codemirror

How to use CodeMirror to apply some styles to a special marks in the editor


Here is my scenario: I have an input textarea where the user introduces some text. The text is plain text but the user can use some defined macros, such as {{username}}.

Here is an example

<textarea>The user {{Username}} loggedin at {{now}}</textarea>

I don't want that the user has to know the syntax, so I will have some buttons, which when clicked insert the macro automatically in textarea. I want to apply some basic style to this macros. For example, the content above should be transformed in

The user <span class="cm-mystyle">Username</span> logged in at <span class="cm-mystyle">Now</span>

When using the editor the user should handle the 'span' as a block, which means that the user cannot change the content of the span (just delete).

I don't know if CodeMirror is the right tool to handle this scenario.

After reading the documentation, my first approach was to define a mode, to handle my tokens {{Username}}. But it seems that I can only return the style to be applied to the token. So I can have this

The user <span class="cm-mystyle">{{Username}}</span> logged in...

But I want to remove the {{}} chars. Then I read about the widgets, which seems to me that can be used to handle my scenario.

To be honest, I am a litle bit confused how to approach my problem. Any help?


Solution

  • The markText method is probably what you want. Find the macro text, and mark it with the replacedBy option set to some styled span that contains only the text you want to display.

    http://codemirror.net/doc/manual.html#markText