5

I frequently make answers with code samples that are surrounded with pre tags instead of having each line indented with an extra four spaces, because doing the latter either means I have to add four spaces each line, or go into gedit, change the tab settings to four-spaced tabs, then type away, then indent. I'm a little too lazy to do that sometimes.

My question is, as most of the time when I do this, someone quickly swoops in and changes it to four-spaced indents to invoke code mode. Why is this? Is there a benefit to that method? Is there a rule against pre tags?

7

Well, you can just select the lines you want and press ctrl+k (or click the code-sample button) and it'll do the indent for you...

IIRC there are some things that the <pre> doesn't like, but I can't think of them off the top of my head. Indented is generally easier to work with, IMO.

  • 9
    +1 -- in additon, <pre> content doesn't get code highlighting, which is probably the reason why people prefere four-space-indent – balpha Sep 15 '10 at 10:29
  • 1
    +1 for Ctr-k. Didn't know about that. I've been indenting in my editor. – Peter Ajtai Sep 15 '10 at 11:46
  • Thanks! A great tip there, and now I know that the indented code block has syntax highlighting and automatically escapes special HTML characters. – Delan Azabani Sep 15 '10 at 12:00
7

I use the 4 white spaces for code blocks (and the CTRL+K shortcut) when I want syntax highlighting.

I use <pre> when I want pre-formatted text without syntax highlighting (e.g. for console output).

I sometimes use <pre><code> when I want pre-formatted text for code with syntax highlighting and more advanced formatting options, like bold and italic, for special emphasis:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("you can't do that with 4 spaces");
    }
}
5

Well, if my code actually involves HTML/XML, then this will most certainly not work.

My code!
Hello world!

Nop!

versus

<pre>Arrge!</pre>
<div>Hello world!</div>
<p>Nop!</p>

Of course you would could to rewrite all that angular brackets diligently as &gt; and &lt;, but that's just a waste of time...

4

Semantically, <pre> is for pre-formatted text, not code: it's to make sure whitespace is preserved and little else.

As others have pointed out, syntax highlighting is only invoked on code blocks, so consider it a gift that others are taking the time to fix your mistake and properly enclose the code with the correct markup.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .