1

I've been using TinyMCE (v4 at the moment, but this question is valid for v5 as well) as an editor for content that is eventually turned into Word documents.

Pressing shift + enter on TinyMCE inserts a line break <br /> rather than a return (i.e., creating a new <p>). Is there any way to make shift + enter behave just as enter? In other words, is there any way to disable shift + enter?

If anyone's interested as to why I'm asking:

To make it as similar to editing text on Word as possible, I made it so that <p> elements have no margins at all. This way, the document looks the same on the editor and on Word. Line breaks look the same on the editor, but when converted to Word, their behaviour is different when the text orientation is set to justified. Lines ending with a line break get stretched to the full width of the document; lines ending with a return don't get stretched at all. That's the behaviour I'd like to have.

sakinobashi
  • 197
  • 2
  • 11

1 Answers1

3

TinyMCE has APIs you can use to be notified when a key is pressed and you can look at that event to see if Shift + Enter has been pressed. The code to do this can go in your configuration:

setup: function(editor) {
    editor.on('keydown', function (event) {
       if (event.keyCode == 13 && event.shiftKey)  {
         console.log(event);
         event.preventDefault();
         event.stopPropagation();
         return false;
       }
    });
}

Here is a complete TinyMCE Fiddle: http://fiddle.tinymce.com/LQgaab

Michael Fromin
  • 13,131
  • 2
  • 20
  • 31
  • That's very helpful, and surely prevents line breaks from being inserted. Thank you so much! However, how can I make it behave as if `enter` as pressed? I tried `editor.insertContent('

    ')` but the behaviour's not the same, I assume because the caret is not moved to between the tags…
    – sakinobashi Sep 17 '19 at 16:18
  • Doing that is not as simple as you would think. In TinyMCE the `Enter` key can lead to 13 different behaviors depending on where you are in the content and what plugins are enabled. If you are looking for a simple way to do that you may want to try changing the event object and seeing if you can remove the shift property. – Michael Fromin Sep 17 '19 at 18:46
  • Changing the code in the if block to just `event.shiftKey = false;` did just that. Now it seems to be working just like I wanted it to. Thank you both for the initial solution and the major hint (which was as good as a solution) on the follow-up! – sakinobashi Sep 18 '19 at 02:35
  • I had success adding `tinymce.activeEditor.execCommand('InsertLineBreak');`. See [exposed editor commands](https://www.tiny.cloud/docs/advanced/editor-command-identifiers/). Also see [Is there a way to make Enter and Shift + Enter work the same way in TinyMCE?](https://stackoverflow.com/questions/64995257/is-there-a-way-to-make-enter-and-shift-enter-work-the-same-way-in-tinymce) – showdev Jun 09 '21 at 04:58