Jump to content

Formatting a code block


John Kelleher
 Share

Recommended Posts

Hi,

 looking to place some programming code into a page and using Markdown Extra as a text-formatter (only). I've used Markdown Extra elsewhere but none of the typical formatting codes seem to be working. For example, placing a fixed number of '~' symbols before and after text should render that block as code. Alternatively, placing min. 4 spaces before a line has the same effect.

Does Markdown Extra work properly or is there another way to accomplish placing of code in a textarea field?

Thanks,

J

Link to comment
Share on other sites

Hi John,

Not sure if I get you correctly but you cannot place PHP code in PW fields (if that is what you mean by programming code). Luckily, we have the module Hanna Code that will do exactly what you want...it will render blocks of PHP, JS and HTML code using a tag system...

http://modules.processwire.com/modules/process-hanna-code/

http://processwire.com/talk/topic/3745-hanna-code/

Edited by kongondo
Link to comment
Share on other sites

@kongondo: I'm pretty sure we're talking about markdown extra code blocks here, not actual, executable code -- see http://michelf.ca/projects/php-markdown/extra/#fenced-code-blocks for an example.

@John: are you sure your syntax is correct and you're not doing anything except simply echoing field value in your templates? Any chance you could post a sample of something that doesn't work for you here..?

I'm testing this right now with above fenced code syntax and not having any issues. I'm running dev branch of ProcessWire though, in case that it makes any difference here.

Link to comment
Share on other sites

@kongondo @teppo thanks but I'm looking to place some pieces of c-sharp or css or whatever into a blog post. I thought just marking it in TinyMCE as <pre> would do the job and there is feedback in the editor that suggests (see image) this works - but it doesn't render as anything but ordinary <p>. I've also tried placing multiple '~' ahead of the code to format it as a code block but no luck. The Markdown Extra seems to work for numbered lists though - I started using the Markdown Extra text formatter since TinyMCE seemed to strip out the numbered list when rendered.

Image is here: http://www.tiikoni.com/tis/view/?id=f411b49

BTW: how do I post an image in this post?

Also, I've just tried to install SyntaxHighlighter but no joy on that front yet.

Link to comment
Share on other sites

@John: it's possible that you'll have to add both pre and code to your field settings.

When you edit that particular field, see Input > TinyMCE Advanced Configuration Options > valid_elements. If these tags are not included there, you'll have to add them first (simply append ,code,pre to existing content there.)

When replying, you can attach an image by hitting "More Reply Options". This way you should get the full editor view and at the bottom there should be file upload options.

Edit: taking another look at your screenshot, I don't think those fenced code blocks even should work. Currently you've probably got a paragraph containing "~~~~", another containing your code and then third paragraph containing again "~~~~" when you view the resulting markup, right?

TinyMCE starts a new paragraph each time you hit enter, which might cause an issue here. You could try adding forced line breaks (shift+enter) after (and most likely before) your fences, to separate fences and code (and each line of code from eachother.) This could work better, but I'm not 100% sure about that either.

Ultimately I don't think that Markdown extra will work nicely together with TinyMCE, so you'll probably be better off with simply using pre or code blocks created by the editor itself. I'm not sure why TinyMCE would strip <pre>, unless it's not include in the valid_elements setting, though.

You could also try dropping TinyMCE and going with CKEditor. I find it more suitable for the kind of stuff I write, including code blocks within text (I use pbckcode plugin for actual code editing.)

  • Like 1
Link to comment
Share on other sites

@John: SyntaxHighlight needs special class attributes ("brush: js" .etc), so make sure you've got those in place. Otherwise it won't highlight anything.

If you're not interested in adding these, you might want to check highlight.js out. Doesn't require anything special from the markup, which can make things easier.

Link to comment
Share on other sites

@teppo: Thanks for suggesting highlight.js - have it working though it needs <pre><code>....</code></pre> - I can format the snippet in TinyMCE for preformatted but is there any easier way to mark up the snippet with <code> than opening the HTML editor and adding the tags?

Guess this is a similar problem to adding 'brush: js' with SyntaxHighlighter - something to do with TinyMCE configuration?

Thanks again,

J

Link to comment
Share on other sites

Highlight.js doesn't really require <pre><code>..</code></pre>, that's just a suggestion in their documentation. See one of my posts here for an example: http://www.flamingruby.com/blog/php-for-template-designers/. All code blocks there are <pre> tags formatted with highlight.js (view page source to see hljs code in the header section.)

You can define which blocks you want to highlight by using proper selector.

Lang attributes etc. in the source are a result of the CKEditor plugin I mentioned above, you don't need to worry about those. They're not necessary and actually required a bit of customization to pbckcode plugin itself.

Link to comment
Share on other sites

@teppo: Hi, I've gone with your suggestion of CKEditor as there are several different formatting needs (css, php, csharp, html). I've installed the PBCKcode plugin and changed the body field to use CKEditor. I've added the PBCKcode as a plugin on the input field too.

However, I'm not getting any changes to the CKEditor when editing the field - I expect I should see the <> button to edit the code. Any ideas?

Thanks,

J

UPDATE: Couldn't get PBCKcode to show as extra option on CKEditor. Switched back to highlight.js but seemingly need to prefix code with both <pre> and <code> in that order. Even then, I'm not sure highlight is working - I'm getting the same formatting as suggested by content.css for TinyMCE.

Surely, this isn't so hard?

Link to comment
Share on other sites

Sorry, on a mobile and can't remember exactly how pbckcode works on UI level but just to make sure: did you also enable it via field settings? Edit: in extra plugins add both sourcedialog and pbckcode to do this.
 
If you view source of the page I linked above, you should notice that pre + code is not the only way to trigger highlight; you can toggle hljs for any element really. I'm using plain pre tags within article element myself.

Link to comment
Share on other sites

@teppo: appreciate your taking time while about answering this. I did add pbckcode to extra plugins (sourcedialog already there). I added the changes to config.js for CKEditor recommended by pbckcode.

I'm also (for the record) using ACF 'On' and Purifier 'On', with regular editor (not inline).

I <pre>'d the code snippets in the PW CKEditor window. But according to ppbkcode I should be seeing an extra button in the toolbar for CKEditor something like '<>' which would throw up a window to let me pick a language and enter the code snippet. Or is this so?

You can see the page I'm editing here: http://www.pw.appsolo.com/blog/blog-posts/azure-deployment/

At the very bottom (away from possible influence of the <ol>), you'll see two lines - one uses <pre> from the CKEditor and the other doesn't. I have the following call to highlight.js in my foot.inc with the following js at the bottom of the page:

hljs.initHighlightingOnLoad()

Also, have the following at the top of the page (in my head.inc), this recommended by highlight.js site:

<link rel="stylesheet" href="http://yandex.st/highlightjs/7.3/styles/default.min.css">

<script src="http://yandex.st/highlightjs/7.3/highlight.min.js"></script>

Appreciate you may be on business so don't let me get in the way of business!

J

Link to comment
Share on other sites

You guys got me curious about PBCKCode, so I tried to install it here. Seems to work nicely. Not sure if this helps, but here's how I installed it. I downloaded the ZIP from here then extracted the contents to /site/modules/InputfieldCKEditor/ckeditor-4.1.2/plugins/pbckcode/. Then I went and edited my 'body' field and added a line for "pbckeditor" to the toolbar, and another for the "extra plugins". Then in "Extra Allowed Content", I added: "pre[class](*)". See the attached screenshot of my config screen for CKEditor. 

post-2-0-46884700-1375609823_thumb.png

I opted not to keep the "data-pbcklang" attribute that it adds to the <pre> tag. Though I'm sure HTMLPurifier would strip that one out anyway. I figured that wasn't necessary since I already had a class tag identifying the language. 

  • Like 2
Link to comment
Share on other sites

@Ryan: thanks for detailed info!

@John: I'll take a closer look at this once I get the chance, though what Ryan explained above should be pretty helpful already. Just got back from quick trip to Stockholm, still on mobile and a bit unsteady connection.. :)

For the record, data-attributes don't work too well with purifier. I needed these for pbckcode to recognize the language next time I edit same code block (for some reason class wasn't enough) so I ended up modifying the plugin itself and changing all mentions of the data-lang simply to lang. Bit ugly perhaps, but that did the trick.

  • Like 1
Link to comment
Share on other sites

@ryan @teppo Thanks guys for weighing in on this. Unfortunately, I'm still getting this. There is some styling happening but not what I'd expect from hightlight.js. I've done the following:

  • all the settings for pbckcode as per @ryan's screenshot
  • have js code in head.inc:
    <script src="http://yandex.st/highlightjs/7.3/highlight.min.js"></script>
  • have css ref in head.inc:
    <link rel="stylesheet" href="http://yandex.st/highlightjs/7.3/styles/default.min.css">
    Also tried:     <link rel="stylesheet" href="/site/templates/styles/highlight.css">
  • have call to highlight.js in foot.inc
    hljs.initHighlightingOnLoad();
  • have my body field for that template using CKEditor (which works) and now PBCKcode showing in toolbar. Added simple php code to the <> modal box but as I say, no styling happening.
  • UPDATE: I have also edited the config.js file in the CKEditor plugin folder as per instructions from PBCKcode.
  • UPDATE: I also added (in foot.inc) the following to target <pre> elements with highlight:
            $(function() {
                if ($('pre').length) {
                    $.getScript('/site/templates/scripts/highlight.pack.js', function() {
                        $('pre').each(function(i, e) {hljs.highlightBlock(e)});
                    });
                }
            });

Should I be providing more explicit styles though I believe hightlight.js just detects the language automatically. This is what I get at the browser:

<pre class="prettyprint linenums"><?php echo 'test'?></pre>

I checked @teppo site and didn't see anything like I found there: i.e. lang and class attributes.

<pre lang="php" class="php" xml:lang="php">

This looks promising but output is bland courier typeface with no decoration. Thanks for the help. J

Update: I do see some syntax highlighting in the pop-up PBCK box when editing the field. However, this is lost on browser rendering. 

Link to comment
Share on other sites

UPDATE: I have also edited the config.js file in the CKEditor plugin folder as per instructions from PBCKcode.

This is not necessary. Admittedly, I don't know these jQuery plugins well enough to know why they aren't working in your case, but it does sound like you've got everything needed to have it work from the admin side. Meaning, it sounds like you need to focus on the front-end and the instructions for the code highlighting plugins you are using. I would also suggest opening up a Javascript console window, just to make sure there aren't any pesky JS errors holding everything up. When I view the page you linked to, I am seeing a couple Javascript errors, which could very likely be the reason why the code highlighting scripts aren't working. None of the JS errors appears to be related to the code highlighting, but they could certainly interfere with it: 

Uncaught ReferenceError: ddsmoothmenu is not defined scripts.js:416

Uncaught TypeError: Object [object Object] has no method 'dcSlickForms' 
Link to comment
Share on other sites

@ryan thanks for the followup. I've been busy trying various options with little luck. I think the problem is with the editor - I've tried both TinyMCE and CKEditor. I've tried highlight.js but also syntaxhighlighter. I have noted with CKEditor (using the settings you gave) it strips out the 'lang="php"' attribute that I suspect PBCKcode inserts. Even if I insert it manually, it gets stripped out on saving that page.

One thing that someone might know about: with CKEditor on saving a code snippet using the PBCKcode popup, the rendered html looks as follows:

<pre class="prettyprint linenums"><?php echo 'hi there' ?></pre>

Note the class 'prettyprint linenums' - this is suggestive of prettify.js (Google Prettify) but I'm not using that anywhere, nor have. I'm at a loss where it's coming from!

Rgds,

J

UPDATE:

  I sorta have it working now. Key was to remove the reference to code from the default.css styling that comes with Highlight.js. PBCKcode wasn't inserting the <code>  element after the <pre>. I did have the js invoke code for highlight.js calling on 'pre code' elements but it didn't work. So I changed it to:

            $('pre').each(function(i, e) {hljs.highlightBlock(e)});

and together with the change in the styling (to just 'pre'), it now works. One small point - it overflows the column without any clipping (bit of a mess) so must insert linebreaks manually to tame it but small price to pay.

Link to comment
Share on other sites

One small point - it overflows the column without any clipping (bit of a mess) so must insert linebreaks manually to tame it but small price to pay.

Glad to hear that you got it working!

It might make sense to add "overflow-x: auto" to your pre element in highlight.css; this isn't perfect as it brings out the scrollbar, but it's usually better than content overflowing somewhere it shouldn't go :)

Link to comment
Share on other sites

  • 1 year later...

...For the record, data-attributes don't work too well with purifier. I needed these for pbckcode to recognize the language next time I edit same code block (for some reason class wasn't enough) so I ended up modifying the plugin itself and changing all mentions of the data-lang simply to lang. Bit ugly perhaps, but that did the trick.

@Teppo. Care to elaborate pls? I tried your trick but pbckcode still doesn't remember language when I edit a code block. Thanks

Link to comment
Share on other sites

@kongondo: all I really did was alter pbckcode's JS file to change all 'data-lang' attributes to 'lang' and add following to exra allowed content: pre[class,lang](*);

Have you made the changes to the plugin already and what sort of markup does it generate? Could you paste an example of a code block, preferably both states, i.e. what it looks before and after saving the page?

As far as I can see, the problem could be a) necessary attributes getting stripped off during page save, b) them not being there in the first place or c) some change still missing from the plugin.

Note: I haven't tested this in a while, so something could've changed since then.

Link to comment
Share on other sites

@Teppo. Works like a charm with CSS and PHP. It remembers code type. With HTML on one occasion it remembered, then forgot. JS, it hasn't remembered. For CSS and PHP code on frontend is generated with lang=PHP or lang=CSS, i.e <pre class='php' lang='php'>. With the HTML and JS, they only get the class=html...etc.

No worries, I can live with it like this..Thanks again.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...