Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a new text at given cursor position

Tags:

codemirror

I am working on customizing the codemirror for my new language mode. As part of this new mode implementation, I am writing a new tool bar where user can select some text and say insert. This command should insert the text where user was typing just before clicking on tool bar.

I could not find any API level support to do so. If there is any other way can someone help me out on this?

Basically get the current cursor positio- line number and position at which cursor is currently present. May be a Position object

API for inserting a text, something like insertText("Text", PositionObject)

like image 986
Chetan Avatar asked May 19 '14 08:05

Chetan


People also ask

Is the position of cursor where we insert text?

First, get the current position of cursor with the help of property named as selectionStart on textarea/inputbox. To insert the text at the given position we will use slice function to break the string into two parts and then we will append both parts to the text(text_to_insert) in front and end of the text.

How do I change the cursor position in textarea?

To set the cursor at the end of a textarea: Use the setSelectionRange() method to set the current text selection position to the end of the textarea. Call the focus() method on the textarea element. The focus method will move the cursor to the end of the element's value.

How do you get the cursor position in TinyMCE editor?

Setting the cursor position You can also hold down shift and then move the cursor with the arrow keys on the keyboard to select content. It has the same effect. The TinyMCE bookmarks this location with the Bookmark Manager API, and then loads the selected location later.


2 Answers

Here's how I did it:

function insertTextAtCursor(editor, text) {
    var doc = editor.getDoc();
    var cursor = doc.getCursor();
    doc.replaceRange(text, cursor);
}
like image 157
Sue Maurizio Avatar answered Oct 19 '22 23:10

Sue Maurizio


How about replaceSelection (http://codemirror.net/doc/manual.html#replaceSelection)?

doc.replaceSelection(replacement: string, ?select: string) Replace the selection(s) with the given string. By default, the new selection ends up after the inserted text. The optional select argument can be used to change this—passing "around" will cause the new text to be selected, passing "start" will collapse the selection to the start of the inserted text.

like image 40
Marijn Avatar answered Oct 19 '22 22:10

Marijn