Ckeditor5: Code blocks

Created on 4 May 2017  ·  39Comments  ·  Source: ckeditor/ckeditor5

Is there any support planned (or available) for code blocks? The example below doesn't seem to function, and the editor renders it as a <p> element.

Example:

<pre><code>if (hardThroughputBrouter &lt;= 5) {
    laserHandleUdp += -3 + cleanDpiAddress + voip;
    input_zebibyte_edutainment = plug_ttl_state;
} else {
    publishing_language_half(3 - tween, shortcut);
    sshHdvGigabyte(aclPharming, kibibyte, ad * public);
}
social.orientation_dvi_systray(vertical.case.northbridgeServiceClient(
        system_requirements, seo + 440195, 1), hypermedia);
if (index_bus) {
    spywareThermistorWrap = control(manet_lpi_readme(encodingDenial, 82,
            framework_supply_website), parse);
    qbe_data.ad_facebook(toolbarApplicationRight.installJava(100));
    cardIrq(leaf_on + webmaster_status_lun, 24);
} else {
    soft_captcha = kilohertz_domain * 3;
    computing = gate(readerCaseMicrophone(address),
            symbolicGpuDot.vectorBig(2));
    keywords_vram_streaming.softwareSyntaxDigital(analyst);
}
</code></pre>

If you'd like to see this feature implemented, please add 👍to this comment.

code-block feature

Most helpful comment

So, we've had a call to wrap up what we did already and problems/ideas/obstacles that appeared. We understood that there are two quite distinctive features and due to limitations and requirements, it's hard to implement just one feature which will support all of them.

Anyway, we'll focus on on the first of them.

Other notes from the meeting:

Code blocks

  • The "smaller" of the features. Easier to implement.
  • No advanced code editing support. Usually created by pasting stuff.
  • But it will work with comments and trackchanges.
  • Things to consider:

    • [x] Contents of the code block is kept in the model as a single text node.

    • [x] Should the button insert a code block at selection position or turn the current line into a code block?

    • [x] Option to choose a code block language (via UI).

    • [x] Option to define what the Tab key's doing (like in CKE4 – via config).

    • [x] The indent buttons should work like Tab.

    • [x] Idea: Enter keeps indentation of the previous line.

    • [x] Double enter leaves a code block. Shift+enter always stays in.



      • [x] Double enter leaves a code block at the beginning.



    • [x] Paste support is critical. Must work with popular IDEs. Probably, the best option is to read the plain text from the clipboard instead of defaulting to HTML.

    • [x] Small UI tweak: print the chosen language on the code snippet (e.g. top right corner)

Code snippets

  • The proper code editing experience.
  • Embedded IDE and syntax highlighting.
  • Most likely, will only support comments and track changes on the entire code snippet.
  • Important: it seems totally feasible to integrate it with real-time collab editing if we use an IDE like Monaco.
  • Milestone: backlog. Let's gather feedback.

All 39 comments

We certainly plan to support code blocks. I added them to the roadmap but for now to the "after 1.0.0" section.

With code blocks there's a question about the amount of work. A simple implementation where you can change the type of block to "code block" (which is kinda similar to applying a heading) would be pretty simple. Then, there's Enter support and white space handling (white spaces need to be preserved during the DOM<->view conversion). That would be step one. We might be able to squeeze this before 1.0.0 (if other things will go well).

However, what I'd love to see is a real code editor (like CodeMirror) embedded directly inside CKEditor. This would provide syntax highlighting, better Tab and indentation handling and other features that you'd expect from a code editor. This, of course, means a lot more work since we haven't yet worked on such embedding in CKEditor 5 (so, we don't know what may go wrong).

How would you see this feature?

Hi Reinmar, thanks for clearing that up :)

I discussed it and for us it would be most useful to simply be able to change something in the editor from plain text to a code block. A proper code editor would be awesome, but it is much more valuable for us to simply be able to display something as a code block for the immediate future, versus a whole editor. Usually the code is just copy pasted from elsewhere, and displaying it would be enough for now.

Our 2 cents :)

It's a good point that most often we're just pasting the code from a real code editor anyway.

One more question – would a possibility to pick a language (JS, HTML, Python, ...) be critical? Some code highlighters can detect a language but I'm not sure how good they are in this.

While certainly a nice feature, we don't consider it as critical currently. Just having the ability to have it displayed as a properly formatted block would help tons already :)

I would think inline code within a paragraph and perhaps simple display of a block would be well-handled by CKEditor, but some way to embed a proper editor as it's own entity would be great.

Hi,

while a code functionality seems to be a must for me, a full embedded code editor seems to be more like a "nice to have". Indeed, as deanvaessen said, most of the time, the code is just copied from the IDE to CKEditor. Of course, the idea is great but it seems to be a lot of work for a small added value compared to simply displaying the code.

Hi,
Could you please share any news/plans on this feature? Completely agree with previous commenters:
1) Just a simple button to wrap or paste text in pre/code block with optional style is very simple to implement and adds great value to the product. Note that most end users of this feature will be developers. And they will be completely happy with it, because a lot of other widely adopted editors do not have rich code support (JIRA/Confluence, GitHub, DZone, etc.) you mention. For my use case this is the only blocker which does not allow we to migrate from TinyMCE. Essentially, you only need to port CKE4 addon [1]
2) Some other minor enhancements, such as line numbers, could be added in regular maintenance releases, based on user feedback.
3) And speaking of fully-fledged rich editor, with tab support, code completion, - this is definitely very cool thing to have, but will require a lot of efforts while hardly driving your sales further.

[1] https://ckeditor.com/cke4/addon/codesnippet

any news on this it's really an important plugin to have when ckeditor5 reach final simple codesnippet like we have in version 4 is more than enough as starting point

Thanks for the feedback :) We need to prioritise missing features and, TBH, in case of this one the priority is unclear.

Theoretically, from all the editor users, only a really small percentage of them (mainly, developers) need to embed code blocks. At the same time, it's one of the most often requested features.

My guess is that early adopters often look for solutions for their own projects which are often developer-oriented. Am I right? Or do we miss something?

With the help of Szymon, I managed to get the up- and downcasting of <pre> wrapped code blocks working while not breaking the existing inline code plugin. It uses custom converters for casting which appears to work fine. However, editing the code block is not working yet since Enter commands are blocked (soft breaks work, but will not result in newlines in <pre>).

I have created a separate plugin to track the progress while we're working on it. https://github.com/opf/ckeditor5-code-block, and would appreciate any input on the issues [1] and [2]

This should be enough to handle the enter key:

editor.editing.view.document.on( 'enter', ( evt, data ) => {
    if ( insideAPre ) {
        editor.execute( 'input', { text: '\n' } );

        evt.stop(); // Prevent executing the default handler.

        data.preventDefault();
        editor.editing.view.scrollToTheSelection();
    } 
} );

However, I'm afraid that we are not handling \n characters in the editing DOM too well yet due to:

https://github.com/ckeditor/ckeditor5-engine/blob/1dc4d71e2c87ab34773dc789b6df8c169d7fa68c/src/view/domconverter.js#L973

Enter does work now, thanks to you both for your support. I also had to listen to backspace to detect an empty code block in order to remove both elements.

What remains now is escaping the code block. I'm wondering whether it's possible to add some kind of placeholder before and after the <pre> tag to allow escaping the code block without further hacks (such as listening to further events and forcing a different selection). I'm tracking the state of this one in https://github.com/opf/ckeditor5-code-block/issues/2

However, I'm afraid that we are not handling \n characters in the editing DOM too well yet due to:

https://github.com/ckeditor/ckeditor5-engine/blob/1dc4d71e2c87ab34773dc789b6df8c169d7fa68c/src/view/domconverter.js#L973

I was wrong, fortunately. We're filtering out content of pre-like elements earlier in that function:

https://github.com/ckeditor/ckeditor5-engine/blob/1dc4d71e2c87ab34773dc789b6df8c169d7fa68c/src/view/domconverter.js#L965-L967

Good for us :)

What remains now is escaping the code block

I replied in your ticket, but I don't have a good idea for how to approach that.

Enter does work now, thanks to you both for your support. I also had to listen to backspace to detect an empty code block in order to remove both elements.

I don't understand why that was needed. Last backspace should remove codeblock element from model. If I remember anything about how removing conversion works now, the codeblock element should be mapped like this:

Model:
<paragraph>Foo</paragraph><codeblock></codeblock><paragraph>Bar</paragraph>

View:
<p>Foo</p>[<pre><code></code></pre>]<p>Bar</p>

Which should remove both blocks. I am curious why it wouldn't work 🤔 .

@oliverguenther @Reinmar I think escaping the code block by hitting enter a couple of times could work well, here is an example of quilljs escaping <pre> https://codepen.io/quill/pen/KzZqZx

any updates on when code block feature (for longer code snippets) will launch..!!

I did not yet manage to address the open issues here since we diverted to a widget with a codemirror instance with proper highlighting (however, not editable within the widget).

I wrote an ugly plugin for code blocks: https://github.com/Yeolar/ckeditor5-code-block
It is modified from official block-quote plugin, and the HTML elements are not handled very well, the rendered source by ckeditor5 with this plugin likes:

<pre><p>def func(x):
  return x</p></pre>

and the page to be displayed can use highlight.js to do more rendering, add:

<script src="/static/highlight/highlight.min.js"></script>
<link rel="stylesheet" type="text/css" href="/static/highlight/styles/default.css" />
<script>
$(document).ready(function() {
    $('pre p').each(function(i, block) {  // use <pre><p>
      hljs.highlightBlock(block);
    });
});
</script>

I am not familiar with ckeditor, anyone would like to enhance this plugin is welcomed.

Some screenshots:
codeblock1
ckeditor
codeblock2
displaying

However, what I'd love to see is a real code editor (like CodeMirror) embedded directly inside CKEditor. This would provide syntax highlighting, better Tab and indentation handling and other features that you'd expect from a code editor.

How would you see this feature?

I like that direction. Would prove helpful for downstream projects as well. Probably if you implement anything less feature-complete, people will ask for those missing features anyway.

Syntax highlighted code blocks embedded in textual notes, possibly with an added copy button to copy the entire block's contents similar to Boostnote, would prove very helpful if you want to document your code snippets. See image for an example of what I mean.


boostnote_2018-10-18_11-40-12


I wrote an ugly plugin for code blocks: https://github.com/Yeolar/ckeditor5-code-block
It is modified from official block-quote plugin, and the HTML elements are not handled very well, the rendered source by ckeditor5 with this plugin likes:

<pre><p>def func(x):
  return x</p></pre>

and the page to be displayed can use highlight.js to do more rendering, add:

<script src="/static/highlight/highlight.min.js"></script>
<link rel="stylesheet" type="text/css" href="/static/highlight/styles/default.css" />
<script>
$(document).ready(function() {
    $('pre p').each(function(i, block) {  // use <pre><p>
      hljs.highlightBlock(block);
    });
});
</script>

I am not familiar with ckeditor, anyone would like to enhance this plugin is welcomed.

Some screenshots:
codeblock1
ckeditor
codeblock2
displaying

兄弟,你这个支持几种语言

I wrote an ugly plugin for code blocks: https://github.com/Yeolar/ckeditor5-code-block
It is modified from official block-quote plugin, and the HTML elements are not handled very well, the rendered source by ckeditor5 with this plugin likes:

<pre><p>def func(x):
  return x</p></pre>

and the page to be displayed can use highlight.js to do more rendering, add:

<script src="/static/highlight/highlight.min.js"></script>
<link rel="stylesheet" type="text/css" href="/static/highlight/styles/default.css" />
<script>
$(document).ready(function() {
    $('pre p').each(function(i, block) {  // use <pre><p>
      hljs.highlightBlock(block);
    });
});
</script>

I am not familiar with ckeditor, anyone would like to enhance this plugin is welcomed.

Some screenshots:
codeblock1
ckeditor
codeblock2
displaying

官方的ckeditor5是不是现在还不能支持代码块

上次回答时候不支持
ckeditor的语言支持还是比较完善的,只要对应配一下就可以

@Yeolar, @EraJohnession: I hide your comments. Please use English.

Hi @Reinmar,
I am one of the developers to whom the code block feature with language selection (<pre><code class="language-php">) happens to be very critical. I just migrated from ckeditor4 to ckeditor5, (which was a really hard thing for me to do because some of the features had been removed in ckeditor5).

I am working on a programming blog and simply can't do without the code snippet feature. So I will have to revert to ckeditor5 if I don't find a way to get the code snippet feature with language support to work in ckeditor5.

I've been thinking of a workaround on this to no avail. Do you have any suggestions? If this feature is upcoming, can you kindly give me a date?

Thanks for the good work!

I wrote an ugly plugin for code blocks: https://github.com/Yeolar/ckeditor5-code-block
It is modified from official block-quote plugin, and the HTML elements are not handled very well, the rendered source by ckeditor5 with this plugin likes:

<pre><p>def func(x):
  return x</p></pre>

and the page to be displayed can use highlight.js to do more rendering, add:

<script src="/static/highlight/highlight.min.js"></script>
<link rel="stylesheet" type="text/css" href="/static/highlight/styles/default.css" />
<script>
$(document).ready(function() {
    $('pre p').each(function(i, block) {  // use <pre><p>
      hljs.highlightBlock(block);
    });
});
</script>

I am not familiar with ckeditor, anyone would like to enhance this plugin is welcomed.

Some screenshots:
codeblock1
ckeditor
codeblock2
displaying

Thank you,it’s just my need. I have been trying to change the editor like this,but the ckeditor's js style is
too difficult to understand for me.

@AwaMelvine

i have updated some language selection option so that we can be able to highlight its syntax with
https://github.com/highlightjs/highlight.js plugin

it can add pre element with language option like <pre class="cpp">your code</pre>
....

its basic code block, you can modify its styles with custom css.

basic code-block => https://github.com/Suraj151/ckeditor5-code-block

hope it will help.

Assuming there hasn't been any movement on adding the <pre> tag capability within CK5 yet? I've tried all of the 3rd party plugins mentioned above but none of them seem to work. All wind up breaking the editor all together.

As of now I'm using the blockquote and just doing a global find and replace to make this happen. Just not very ideal but is working for me

Will code plugin like CodeMirror embedded directly inside CKEditor?

I'm also waiting for CKEditor to add code block plugin, no updates still.

Hi, It has been two years till now. Do we have any update regarding this?

Here's an update. It seems It's on the horizon
https://twitter.com/ckeditor/status/1138803157700624385

Wow finally it’s happening in the next release hopefully will have nice code block plugin

We regret to inform you that due to some unforeseen absences in the development team we will not be able to deliver code blocks in this release 😞

That being said, we know that you want to have it delivered as soon as possible (so do we!) and we’re going to ship it in the next iteration. Stay tuned!

As temp solution.

So, we've had a call to wrap up what we did already and problems/ideas/obstacles that appeared. We understood that there are two quite distinctive features and due to limitations and requirements, it's hard to implement just one feature which will support all of them.

Anyway, we'll focus on on the first of them.

Other notes from the meeting:

Code blocks

  • The "smaller" of the features. Easier to implement.
  • No advanced code editing support. Usually created by pasting stuff.
  • But it will work with comments and trackchanges.
  • Things to consider:

    • [x] Contents of the code block is kept in the model as a single text node.

    • [x] Should the button insert a code block at selection position or turn the current line into a code block?

    • [x] Option to choose a code block language (via UI).

    • [x] Option to define what the Tab key's doing (like in CKE4 – via config).

    • [x] The indent buttons should work like Tab.

    • [x] Idea: Enter keeps indentation of the previous line.

    • [x] Double enter leaves a code block. Shift+enter always stays in.



      • [x] Double enter leaves a code block at the beginning.



    • [x] Paste support is critical. Must work with popular IDEs. Probably, the best option is to read the plain text from the clipboard instead of defaulting to HTML.

    • [x] Small UI tweak: print the chosen language on the code snippet (e.g. top right corner)

Code snippets

  • The proper code editing experience.
  • Embedded IDE and syntax highlighting.
  • Most likely, will only support comments and track changes on the entire code snippet.
  • Important: it seems totally feasible to integrate it with real-time collab editing if we use an IDE like Monaco.
  • Milestone: backlog. Let's gather feedback.

One more requirement to keep in mind – migration from CKE4. There are two related features – "pre" format in the format dropdown and the codesnippet plugin. It'd be great if they were preserved when loaded in CKE5.

@jodator could you open a new ticket for the Code snippets feature described above?

Was this page helpful?
0 / 5 - 0 ratings