HTML Editor Syntax Highlighter (Updated 2022-03-09)

cesbrandt
Community Champion
77
19003

Original Post

Disclaimer

This is my second blog post to the Canvas Community, but I'm going to stick with my tl;dr format.

 

The Situation

Who doesn't like their code to be easier to read!? Oh, you use the Rich Content Editor (RCE)? Well, why are you in this blog? I see, you thought this was to add syntax highlighting to the content of an activity. Yeah...about that...no.

 

I know there have been a few idea requests to add a syntax highlighter to the core of Canvas for supplying syntax highlighted code within the content of activities. While I have no doubt I could do this, I'm not going to.

 

So what's this blog all about? The HTML Editor is SO boring! We load ~95% of our content via the HTML Editor, having written it in third-party applications (i.e., Notepad++), because the HTML Editor in Canvas isn't particularly inspiring, nor is it easy to read.

 

Reason for Creating

Simply put, I did this to allow our developers to more easily read the code from within Canvas. There really isn't anything more to it.

 

The Solution

A userscript the "replaces" the HTML Editor with an Ace Editor (https://ace.c9.io/) and utilizes JS-Beautify to "beautify" the HTML in the editor. So, without further ado, the Q&A:

 

Q: What does this userscript do?
A: Simply put, it "replaces" the HTML Editor provided by Canvas with an Ace Editor.

 

Q: Why did you put "replaces" in quotation marks?
A: Ah, the long answer.

 

The userscript doesn't actually change any of the Canvas functionality. What it actually does is to hide the HTML Editor and add the Ace Editor to display in its place. When changes are made via the Ace Editor and the user clicks out of it (i.e., to see the Rich Content Editor or save), the HTML Editor is updated with the code from the Ace Editor and Canvas processes it normally.

 

Q: Will the syntax highlighter always be enabled?
A: It can be. The userscript adds a toggle anchor to the line immediately above the editors where the toggle between editors is. This will allow you to enable/disable the syntax highlighter.

 

Q: Will it remember if I had it enabled or do I have to enable it every time?
A: It will remember. The userscript uses cookies to remember the state of the toggle. This means you could enable it while working in one assignment and it will already be enabled when you open a discussion in another course.

 

Q: What about multiple Canvas instances? I want it to be enabled in one, but not another.
A: It will! Rather, it should! I configured the userscript to use the very first part of the domain name it's toggled on to give it a unique name for the instance. I have tested it on three different Canvas instances and it created unique toggle cookies for each Canvas production instance.

 

Q: You just said it was for "production" Canvas. Why can't I use it for "Test" or "Beta" instances?
A: You can. Taking the entire previous answer to give context, I said that there would be unique cookies based upon the first part of a domain name. So, if your production URL is https://abc123.instructure.com/ with a test URL of https://abc123.test.instructure.com/, your cookie will be the same between the two: abc123_Canvas_syntaxHighlighter. However, compatibility between the different instances can be an issue. The editor toggling is dependent upon the wording of certain components of the overall UI of the editor area. When this wording changes (which they seem to like to do frequently), the userscript is unable to load properly.

 

Q: Can I integrate this into my global JavaScript?
A: Knock yourself out, but I won't be supporting that.

 

Q: Can I use this in German? Japanese? Italian?
A: Yes? There are a few settings that can be adjusted at the top of the script (keep an eye out for the "DO NOT EDIT BELOW" line). Included in this area are variables for adjusting to different languages. These will need to be manually adjusted if your Canvas is not in English.

 

Q: Can I use this with a self-hosted instance?
A: Yes? I won't commit that it'll work, but if you update the userscript @include and @exclude values to match your actual domain, I don't see why it wouldn't. Having said that, I will not support use of this code for self-hosted instances.

 

Q: Will it work with the #editor_tabs for inserting links, files, and images?
A: No. To be blunt, the functionality of the #editor_tabs has always been a bit "wonky" for me, so I'm not even going to try to make this new editor work with it. You can, of course, toggle the editor on/off or switch back to the Rich Content Editor, make your inserts, then toggle back.

 

Q: So, it adds this to ALL editors in Canvas?
A: No. For simplicity only the first editor on a page will have the editor applied (so it won't be available to quiz questions). Furthermore, there are some editors (i.e., global announcements) that lack the HTML Editor, which the script is dependent upon.

 

Having said that, the userscript was designed to be as inclusive as possible. If, however, you do find pages where the editor doesn't work correctly, please let me know so I can either fix it or prevent it from loading there.

 

Q: Does it support the new RCE?
A: Yes.

 

Q: Does it support the old RCE?
A: Sorta. In the GitHub repository, there is an "old" version of the userscript that is an "honourary" version using the code that was compatible with the old RCE at the time that the new RCE was enforced. This is not supported in any capacity.

 

Q: Does it replace the "Pretty HTML Editor" in the new RCE?
A: No. This userscript adds an editor, it doesn't replace any. Before the "Pretty HTML Editor" was added, this userscript simply added the Ace editor as an option, it didn't replace the original HTML or RCE editors. This has not changed.

 

Dependencies

 

How It Works

  1. Load the userscript to your Userscript Manager of choice
  2. Enable the userscript
  3.  
    1. If you're using the "old" RCE, access the "HTML Editor" of an activity edit page
    2. If you're using the "new" RCE, access the "Switch to raw html editor" of an activity edit page
  4.  
    1. If you're using the "old" RCE, click the "Enable Syntax Highlighter" anchor right next to the toggle that allowed you to access the HTML Editor
    2. If you're using the "new" RCE, click the toggle that appears next to the "Switch to rich text editor" button

 

Appearance (Old RCE)

BEFORE

290635_pastedImage_1.png

AFTER

290639_pastedImage_2.png

 

Appearance (New RCE)

BEFORE

AceNewBefore.jpg

AFTER

AceNewAfter.jpg

Releated Ideas/Discussion

https://community.canvaslms.com/ideas/2274

77 Comments
ProfessorBeyrer
Community Coach
Community Coach

Brilliant! Having a syntax editor built in makes things so much easier when editing HTML. It's especially helpful with the gradual deprecation of HTML experience among general faculty users. Fewer and fewer of us had to learn code, and so familiarity with it is less than it used to be. The use of WYSIWYG editors is of course something to be celebrated, but sometimes you just need to tinker with the code to make things right.

Chris_Hofer
Community Coach
Community Coach

cesbrandt...  Four words...

Wait What_Mind Blown

Also, for your reference, this is the Feature Idea I've had posted for the past three years: https://community.canvaslms.com/ideas/2274-html-formatter" modifiedtitle="true" title="HTML Formatte....  Thanks for this blog, Christopher!

cesbrandt
Community Champion
Author

I see why I didn't find it, "HTML Formatter." I've never heard it called that before. ^^'

I've updated the blog post to reflect (and voted for your idea Smiley Wink)!

Chris_Hofer
Community Coach
Community Coach

Ah....because I was asking for an ability to format the HTML ... not thinking about the name "HTML Editor".  🙂

cesbrandt
Community Champion
Author

Ah, no, I meant "syntax highlighting" as the primary name. I don't remember the last time I saw a "HTML formatter" that wasn't a "syntax highlighter." xD

Chris_Hofer
Community Coach
Community Coach

Gotcha.  I've added some tags to my Feature Idea so that it's easier to search here in the Community.  Thanks!

cesbrandt
Community Champion
Author

I understand the need for WYSIWYG editors, I just wish no one ever came up with the concept for them. To be blunt, a lot of the code created by those are horrendous.

Don't get me wrong, there are MANY people I think shouldn't touch the HTML, but others could save us a LOT of trouble if they could do a few simple things. Not to mention a syntax highlighter always helps with readability. Smiley Wink

Chris_Hofer
Community Coach
Community Coach

One odd behavior I've found is related to Global Announcements at the account level.  If you enable the Ace Editor via any course page and then create a new Global Announcement, I see a gray box between the RCE and the check-boxes where I can pick who should see the Global Announcement.  I assume this might be because the RCE for Global Announcements doesn't allow us to modify HTML code at all compared to in courses?

No Ace Editor in Global Announcements; Gray Box Instead

If you turn off the Ace Editor in a course page, then this gray box goes away in the Global Announcements.

cesbrandt
Community Champion
Author

I've updated the script to prevent from running on the /accounts/:id/settings page.

You are absolutely correct in why it won't load correct. So, the script looks for Rich Content Editor and appends the Ace Editor. However, it doesn't properly load/initialize because the initialization is dependent upon the state of the toggle to switch between editors. The Global Announcements editors lack this toggle.

I also updated the script to validate the location as part of the script, instead of using the @excludes, which should make it easier to add to global JavaScript for anyone that REALLY wants to do that (I still don't recommend nor support doing so).

Boekenoogen
Community Contributor

Great idea of changing the editor. I hope Instructure takes a look at this...

brian_t_anders
Community Contributor

Is there a way to resize the window when the syntax highlighter is enabled?

cesbrandt
Community Champion
Author

Sadly, Ace doesn't natively support it being dynamically resizable. I spent a little bit of time looking into options to do this, but I couldn't dedicate more to it when I had other things to work on.

If I find myself with spare time, it is on my list of things to revisit. Until then, anyone is welcome to make code update suggestions. Smiley Happy

Boekenoogen
Community Contributor

Yes, we would have liked the tool to have been dynamic, but we just changed the with to 600 px and it works fine.

cesbrandt
Community Champion
Author

Yeah, since I couldn't get it to resize, I decided to just get it as close to the default size of the HTML Editor. ^^'

With the next update, I'll make the size values part of the "configurable" options section. Smiley Happy

brian_t_anders
Community Contributor

Where did you make this change?

cesbrandt
Community Champion
Author

I've updated the userscript to make the width and height configurable variables at the top of the script. It'll accept any valid measurement for an HTML element (%, px, vh/vw, etc.). If left blank or deleted, it'll default to the current sizing.

Important Note: There is no validation to confirm the values supplied are valid. If you're not sure what you supply is valid, I don't suggest supplying anything.

cesbrandt
Community Champion
Author

I updated the Q&A block with a new question I've been messaged about: the Ace Editor will NOT work with the insert tabs on the right-side of the edit page. In fact, trying to use them while in the Ace Editor will result in whatever is "inserted" being added to the front of the code in the HTML Editor. Depending on what is then done, it may or may not be updated into the Ace Editor after using the toggles.

Since the behaviour was inconsistent in my testing, I've updated the userscript to simply remove the entire block while the Ace Editor is active to prevent potential disasters in content development/management as a result.

The inserting functionality can still be used normally by switching back to the Rich Content Editor or toggling the Ace Editor off and inserting to the HTML Editor.

mjennings
Community Contributor

cesbrandt - this is amazing!! Great work. Since you asked about letting you know when it wasn't working some where, I can't seem to get it to load on the Syllabus page. If you could take a look and let me know how to get it to work there I would appreciate it. Thanks!!

cesbrandt
Community Champion
Author

Sorry for the wait in response, it was a busy week(end) for me this past week. I'll take a look into this this afternoon.

cesbrandt
Community Champion
Author

 @mjennings , I'm so sorry for the wait on this. It has really just been so busy the last two weeks. ^^'

carroll-ccsd was kind enough to assist me in making sure that it is working at /courses/:course_id/assignments/syllabus. Are you using the most current version of the script?

cesbrandt
Community Champion
Author

 @mjennings , I think I know what the problem was. As I looked into the issue, it occurred to me that the Syllabus can be edited directly as the Course Homepage as it can from the Syllabus.

It's just a guess, but I suspect that's what you were doing. When I tested it, the editor did not work there. I've made a minor update to the code to correct this, so it should work whether you edit the Syllabus from either /courses/:course_id or /courses/:course_id/assignments/syllabus.

Please give the updated script a try and let me know if you're still having the issue.

mjennings
Community Contributor

Thanks! This is working now. 

292656_salute.gif

Chris_Hofer
Community Coach
Community Coach

Hi cesbrandt...

I am finding that the syntax highlighter view isn't showing immediately when creating a new page in a course.  You first have to put some content on the page, save the page, and then go back in to edit the page in order to access the syntax highlighter.  Is that your experience, too?  If so, is there a way you can fix this in your script?

cesbrandt
Community Champion
Author

Sorry for the slow response, I've been quite busy of late and am just catching up on my community notifications. ^^'

This is because the script is only loading on the edit pages. Content Pages act the same as the Syllabus page in that there is no /edit when creating a new one. Discussions and Assignments both use /new. Quizzes will actually create the quiz and then move into the editor, so it works there.

I'll look at updating the script to account for the /new and see what can be done for the Content Pages, but I make no promises for a quick update. If I feel up to it, I'll work on it this weekend.

Chris_Hofer
Community Coach
Community Coach

Good morning, cesbrandt...

This morning a co-worker and I aren't able to use your syntax highlighter script.  The link in the RCE isn't visible any more.  Would any updates that were pushed out to Canvas this past Saturday have affected your script?  All was working fine last week for me.

cesbrandt
Community Champion
Author

It appears so. I'm looking into it, now.

Chris_Hofer
Community Coach
Community Coach

Awesome...thank you!

cesbrandt
Community Champion
Author

I found the issue. For some reason, the switch detection is not identifying the anchors onload. I've updated the userscript with a `setInterval` to give it a change to load even if the first attempt fails. If it can't identify the switch anchors after 15 seconds it'll log an error in the console.

I've tested it in our production instances on all the "supported" content types (assignments, discussions, pages, syllabus, and quiz description). Let me know if you have any more trouble.

Chris_Hofer
Community Coach
Community Coach

Excellent!  Thanks for the quick turn-around on this.  It's working again.

cesbrandt
Community Champion
Author

I'm glad it's working for you, again! It's something we use, so I was already looking into it. I'd've gotten to it sooner, but we've been sorting out a few problems that arose over the weekend, so I was kinda just working on this in between other things. ^^'

Chris_Hofer
Community Coach
Community Coach

Hi cesbrandt...

It looks like Instructure has been working on a new RCE (mentioned briefly at a session at InstructureCon 2019 last week).  Have you seen this?  You can access it in your "beta" environment.  As an admin, go to your admin "Settings" page, and then turn on the "RCE Enhancements" Feature Option.  When editing a content page with the new RCE, I don't see your syntax highlighter as an option.  Your thoughts?

cesbrandt
Community Champion
Author

Yes, the IRC chat is probably annoyed with my talking about how troublesome updating this and other RCE modifications is.

I've already gotten the Ace editor to load with the new RCE, but I've been having some trouble with the new layout and it's toggle. I know how to deal with it, I just need to find the time to do so.

When I get it updated, I plan to release a version that supports both versions of the RCE. I've already sorted out the detection of the version, so that shouldn't be a problem. Just don't expect it to be released in the next few days. ^^'

Chris_Hofer
Community Coach
Community Coach

No worries.  It's only in "beta" and labeled as such in the Feature Options.  Thanks for the reply.  Smiley Happy

cesbrandt
Community Champion
Author

I have updated the userscript to support the new RCE (https://community.canvaslms.com/docs/DOC-17764) scheduled to be released on 10/19 (https://community.canvaslms.com/docs/DOC-17761#jive_content_id_Rich_Content_Editor).

The new version will support both the current and new RCEs, so there shouldn't be any harm in updating the userscript, even if you're sticking with the old RCE for a bit.

A few people from the community helped with testing it, but bare in mind the new RCE has only been available on Beta, which is not where it could get thoroughly put through its paces.

Please report any issues you encounter here.

Shar
Community Champion

I just discovering this userscript today and like the rest of the folks on this thread, I'm so grateful and enthusiastic! I got so happy I immediately emailed a bunch of other ID-types that I know.

I see on Ace's how-to it mentions changing the font size.

Set the font size:

document.getElementById('editor').style.fontSize='12px';

But where do I put this? I didn't see a variable in config section of the userscript. And I have a need to provide larger font-size.

When I inspect, I see .ace_editor font attribute: 12px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace

Should I edit this in my .css so that folks using the script at my canvas site will have the larger font size? I'm thinking 1 rem. Is there a drawback I'm not thinking of to customizing it for my instance?

Thanks again so much for this script,
Cheers - Shar

cesbrandt
Community Champion
Author

Excellent request! That JavaScript line is fine for injecting the styling after the page is rendered and you can't supply custom CSS files to the page, but the ID of the editor in my userscript is dynamically generated based upon the Canvas instance. Besides, I've always been a fan of adding it to the core whenever possible. It generally results in a more stable product than stacking one thing on top of another on top of another. Smiley Wink

Having said all that, I just made an update to the userscript to add the font-size to the settings area. It defaults to 12px (defined in the generic Ace editor CSS loaded) when left blank.

Shar
Community Champion

Woohoo!! Wonderful bravo!

I can change it back and forth for when I'm projecting my screen or when I'm working on the little screen of my laptop.

I feel so spiffy!

Thank-you for your excellent contribution and have an easy feasting season!
Cheers - Shar  

Shar
Community Champion

One more question, cesbrandt‌,

Canvas Syntax Highlighter options

I'm not getting any line wrapping, I have to scroll horizontally. Does 80 mean, 80 individual characters or 80 character-width columns? Is there something else I'm missing (like the unit)? Or is this standard behavior? I've been (ugh) using the Canvas monochrome HTML for so long with no indentation and wrapping.

Sorry to be a bother,
Cheers - Shar

cesbrandt
Community Champion
Author

That's odd. With it set to "80" it should render like this:

333810_pastedImage_1.png

Odder still is that I'm getting mixed results from load to load. Sometimes it's breaking it correctly and sometimes it's not.

I've updated the JS-Beautify code to the latest version. Give that a try to see if it improves it.

Shar
Community Champion

Yes, something improved.. for the most part my lines are breaking at the 80 column. But long URLS are not and I'm okay with that.

HTML syntax highlighter breaking at column 80

I've got my font set at 1rem and height set at 600px. Now I just have to decide my best word wrap length for the monitor I use most often.

Thanks for the quick fix!

Cheers - Shar

cesbrandt
Community Champion
Author

I believe I addressed the lines not being cut in the comments on the configuration section:

At what character count should the line wrap to a new line? Note: This is soft value and should it occur in the middle of a string of characters the wrap will occur at the next word-break

I'm glad updating that helped. 🙂

yoder1
Community Participant

cesbrandt
For newbies like me, can you please define the acronym RCE right in the original post,

replacing:

Oh, you use the Rich Content Editor?

with

Oh, you use the Rich Content Editor (RCE)?

That will help me know what you are talking about!

And yes, I do use the Rich Content Editor rather than the HTML editor for most of my editing :-). But this is still a great extension! Thank you!

cesbrandt
Community Champion
Author

I added it to that first mention of "Rich Content Editor," but additional uses vary in purpose and, honestly, I assume that most people that pursue the use of this userscript know what an RCE is. ^^'

lorewap3
Community Member

HI @cesbrandt ! We've used your syntax highlighter for a few years now and are extremely appreciative of it! 

 

Now that the new RCE is taking over this weekend and deprecating the current one, we've been testing it out. We were using an old version of the syntax highlighter (1.6) so we just upgraded to (2.2), but no button is being added to the DOM to allow the user to turn syntax highlighting on. Is there a current issue with it? 

We're just now testing it, so perhaps I've set it up incorrectly, but everything matches from the old version. I embed the code in our canvas subaccount so everyone doesn't have to have tampermonkey to use it. 

 

Any insight would be most appreciated! Thanks again for an awesome tool!

Will

cesbrandt
Community Champion
Author

@lorewap3, we haven't switched to the new editor and this is the first report I've received of it not working. I just tried pulling it up on our Beta instance and found it isn't working, also.

I'm going to work on a fix and also strip out the old editor code (I'll release it as an unmaintained version for non-Instructure hosted instances) so it'll only work for the new editor.

I'll post an update when I get this done, but it probably won't be done today.

lorewap3
Community Member

Thanks so much! Don't stress yourself on our account! It's a great tool and just happy you built it 🙂 

 

If you wouldn't mind tagging me (if you remember) whenever you have the time to fix it I'd most appreciate it!

 

Will

 

cesbrandt
Community Champion
Author

@lorewap3, remembering to tag you won't be difficult. 😉

I've pushed an update that's maintaining both versions, fixes the new RCE compatibility, and updates both the Ace editor and JS-Beautify versions to their newest editions.

Please give it a test, see if it works, and let me know. If it still doesn't work, though, try testing it via Tampermonkey. While, technically speaking, it should work fine being loaded via custom JavaScript, it's not a method I actually support. I never intended this tool to be released for all users. Despite how useful it is, it can give a false sense of capability to users that otherwise should stay out of the code. I'd rather remove the HTML editor from some user roles, but the permission controls are not quite so good.

As I previously mentioned, we're still using the old editor, so I could only test on our Beta instance. I had to entirely rebuild the toggle logic for the new RCE. If there's a discrepancy between the RCEs on Production and Beta, I don't know if I'll be able to address them until after the enforcement goes live.

dwarden
Community Member

Hi @cesbrandt 

Firstly, thanks so much for creating this. It's a feature that has really improved my experience when designing in Canvas. 

As mentioned, I've tested it this morning and now the toggle anchor doesn't appear (and I can only use the standard raw HTML editor).

I'm using the new RCE and have been using this feature via Tampermonkey. It was working brilliantly until a few hours ago. Hope this feedback is helpful.

Many thanks again!

cesbrandt
Community Champion
Author

@dwarden, are you using v2.3 that I released yesterday? I just tested it from another computer and it seems to be working for me regardless of the browser. I've tested in editing/creating discussions, assignments, quizzes, pages, and the course syllabus in 3 different Instructure-hosted instances (all Beta).

The visual is different due to the new UI. You won't see the toggle when you first load up the editor:

cesbrandt_0-1610718533117.png

The toggle will appear after you switch to the HTML Editor:

 

cesbrandt_2-1610718714979.pngcesbrandt_3-1610718815577.png

 

 

If you are and it's still not working, I'm afraid that it may be a difference between Production and Beta instances, meaning I won't be able to troubleshoot it until after the enforcement.

dwarden
Community Member

Hi @cesbrandt , thanks for the quick response.

I confirm I've installed v2.3 on two devices and it's the same result. Must be be the difference between the Production and Beta instances as you say.

Many thanks again. I look forward to the enforcement 😁