137

Frequently when I ask a question I have to include quite a bit of code for reference purposes.

It would be nice to be able to bold the important lines in the code.

For example this code:

<DataTrigger Value="True">
    <DataTrigger.Binding>
        <MultiBinding Converter="{StaticResource DisableWorkItemConverter}">
            <Binding ElementName="MainForm" Path="PickedWorkItemID"/>
            <Binding Path="Id"/>
        </MultiBinding>
    </DataTrigger.Binding>
    <Setter Property="IsEnabled" Value="False"/>
    <Setter Property="IsSelected" Value="False"/>
</DataTrigger>

Is not way long, but the important part (as seen in this question) is the second to last line. However, if I try to bold it, it ends up looking like this:

<DataTrigger Value="True">
    <DataTrigger.Binding>
        <MultiBinding Converter="{StaticResource DisableWorkItemConverter}">
            <Binding ElementName="MainForm" Path="PickedWorkItemID"/>
            <Binding Path="Id"/>
        </MultiBinding>
    </DataTrigger.Binding>
    <Setter Property="IsEnabled" Value="False"/>
    **<Setter Property="IsSelected" Value="False"/>**
</DataTrigger>

Not what I was going for. It would be nice to be able to draw attention to specific lines of code when needed.

(One suggestion of a different color background sounds nice too (ie a yellow background to draw the eye to the relevant code.)

If there is some other way to bold in code please let me know.

16
  • 29
    I'm almost certain I've seen this suggestion before. I still like it.
    – mmyers
    Dec 11, 2009 at 16:24
  • 7
    I like this idea but the only problem I see with it is people writing C/C++ like this: int main(int argc, char **argv). Now everything after that will be bold.
    – Kredns
    Dec 11, 2009 at 16:25
  • 5
    Maybe some special in code bold syntax? Something sufficiently weird as to not clash with code?
    – Vaccano
    Dec 11, 2009 at 16:26
  • 6
    What could possibly be weird enough as to not clash with at least one language out there?
    – John Rudy
    Dec 11, 2009 at 17:07
  • 5
    Yeah, Perl could clash with pretty much anything from what I've seen.
    – mmyers
    Dec 11, 2009 at 18:00
  • 1
    If you want to avoid the theoretical possibility of clashing, you need an escape mechanism. Begins to sound complex, unlike tvanfosson's suggestion... Dec 11, 2009 at 18:20
  • 2
    +1, I like this suggestion.
    – Heather M
    Dec 11, 2009 at 20:59
  • Started a bounty in hopes that this can actually be done.
    – Vaccano
    Dec 14, 2009 at 17:53
  • Any chance of a comment from the Site owners on this? It would be nice to know if it has been seen, considered or (sigh) rejected.
    – Vaccano
    Dec 21, 2009 at 17:08
  • 2
    Hmmmm, just declined. No reason? Too hard? Not seen as important? Any comment at all?
    – Vaccano
    Dec 23, 2009 at 21:05
  • 3
    I would like to see this feature for answers too, to emphasize the change I made to questioner's original code to make it work.
    – nobody
    Aug 6, 2011 at 19:00
  • Wait, when did we vote on this? I see its marked as declined. Where/how is voting on new features done?
    – Nick
    Feb 19, 2012 at 23:13
  • @Nick - there is no voting. Features for SO are not run in a democratic or republic sense. We submit them and they decide if they are good or not. (Though if this got voted up a lot they may re-look at it.) Jeff shot this one down without even a reason why... (It kind of irked me at the time.)
    – Vaccano
    Feb 20, 2012 at 18:05
  • 1
    For the record, you can do it already if you mark your code with <pre><code> instead of four spaces. You're forfeiting the automatic escape of HTML/XML characters though. Jan 12, 2013 at 12:04
  • 2
    If the code for in code bold needs to be complicated to avoid clashes with other languages just make the bold button context sensitive, it can then put in whatever madness is required Jul 5, 2013 at 12:12

10 Answers 10

71
+100

I see a few options:

  1. Simply add a comment in the appropriate language syntax to draw attention to the important line of code.

  2. However, It might be better to have automatic line numbering for code blocks, so then you can just say "see here on line X...".

If you are including so much code that it is not clear which are the "important" parts, generally you are including too much code. Try to boil it down to the smallest working example possible.

8
  • 4
    This * 100. Line numbering would make it soooo much easier to refer to different sections of code, and could make answers shorter as they wouldn't need to include the whole code if only a few line changes are needed.
    – Pollyanna
    Dec 11, 2009 at 19:58
  • 16
    Line numbering is a bad idea because it makes it difficult to copy and paste the code so that it can be compiled outside of the browser. If you need to hilight a line, simply use a comment in the language if the code. For example: int x = 4 / 0; // ERROR HERE!
    – nb69307
    Dec 11, 2009 at 21:33
  • 1
    @Neil - I agree. I often cut from questions into a file to test -- having to edit a question just to get at the code in a usable form seems wrong.
    – tvanfosson
    Dec 11, 2009 at 21:53
  • 1
    +1 for all the goto answers people will raise
    – Antony
    Dec 11, 2009 at 21:55
  • 19
    It should be possible to separate the line numbers from the code through the proper use of HTML/CSS... I am several years out of date now but shouldn't a separate table cell or div be sufficient here?
    – Ether
    Dec 11, 2009 at 22:42
  • 8
    @Æther: There are even some examples out there. Google does it: code.google.com/p/google-code-prettify/source/browse/trunk/src/… Dec 12, 2009 at 10:53
  • 1
    When changing the rendering, then existing code blocks might suddenly look funny though... Not all pre-formatted text is actually code on these sites.
    – Arjan
    Dec 13, 2009 at 8:42
  • @nb69307, Gosh, this is not the '90s. It's not difficult to copy and paste the code with proper HTML.
    – Pacerier
    Sep 21, 2015 at 8:35
72

You could always try to create the HTML by hand:

<DataTrigger Value="True">
    <DataTrigger.Binding>
        <MultiBinding Converter="{StaticResource DisableWorkItemConverter}">
            <Binding ElementName="MainForm" Path="PickedWorkItemID"/>
            <Binding Path="Id"/>
        </MultiBinding>
    </DataTrigger.Binding>
    <Setter Property="IsEnabled" Value="False"/>
    <Setter Property="IsSelected" Value="False"/>
</DataTrigger>
<pre><code>&lt;DataTrigger Value="True"&gt;
    &lt;DataTrigger.Binding&gt;
        &lt;MultiBinding Converter="{StaticResource DisableWorkItemConverter}"&gt;
            &lt;Binding ElementName="MainForm" Path="PickedWorkItemID"/&gt;
            &lt;Binding Path="Id"/&gt;
        &lt;/MultiBinding&gt;
    &lt;/DataTrigger.Binding&gt;
    &lt;Setter Property="IsEnabled" Value="False"/&gt;
    <b>&lt;Setter Property="IsSelected" Value="False"/&gt;</b>
&lt;/DataTrigger&gt;
</code></pre>

I would like to point out that you will have to replace < with &lt;, and > with &gt;.

9
  • 4
    interesting. i didn't know <pre><code> would trigger the syntax highlighting, thx! Dec 11, 2009 at 19:55
  • 15
    yeah, this is about the only real solution Dec 14, 2009 at 19:39
  • 1
    I'm waiting for the greasemonkey solution for this. Dec 14, 2009 at 22:09
  • 3
    @Jeff: You could always extend the markdown syntax. Dec 15, 2009 at 6:12
  • 6
    This kinda proves that emboldening code is futile since the bold line barely stands out at all (for me, anyway). Apr 20, 2010 at 16:09
  • @DisgruntledGoat, That depends on the font.
    – Pacerier
    Sep 21, 2015 at 8:40
  • 2
    Just want to clarify that you DO NOT have to replace both brackets < and > in your HTML block for it to display properly. You can just replace the first bracket < and it'll do the job. Here's an example: jsfiddle.net/gb5ujy14/1 Mar 7, 2016 at 14:13
  • How do you specify a language to enable highlighting in <pre><code>?
    – Ashark
    Jul 16, 2023 at 5:26
  • It is like this: <pre><code class="language-bash">.
    – Ashark
    Jul 16, 2023 at 6:13
36

I've done this on occasion, though I can't find the answers in which I've done it.

this is bold code and this isn't

And this is how I did it:

<code>this is **bold code** and this isn't</code>

or also:

this is bold code and this isn't

And this is the source:

<code>this is <b>bold code</b> and this isn't</code>
5
  • This is the easiest!
    – nawfal
    Nov 24, 2015 at 8:12
  • this also works on github, where i needed it.
    – eMBee
    Dec 6, 2016 at 10:28
  • 2
    This is single-line only
    – Pacerier
    Jul 30, 2020 at 8:25
  • @Pacerier: you can wrap this all in <p>...</p> and make it multiline Aug 1, 2020 at 18:14
  • @Pacerier Adding a > to make it a quote seems to work...for making it multi-line: i.stack.imgur.com/l1UY2.png. Of course, non of this is really ideal.
    – User1974
    Jun 19, 2022 at 11:23
28

Not pretty, just a workaround.

Ascii art is your friend.

<DataTrigger Value="True">
    <DataTrigger.Binding>
        <MultiBinding Converter="{StaticResource DisableWorkItemConverter}">
            <Binding ElementName="MainForm" Path="PickedWorkItemID"/>
            <Binding Path="Id"/>
        </MultiBinding>
    </DataTrigger.Binding>
    <Setter Property="IsEnabled" Value="False"/>
    <Setter Property="IsSelected" Value="False"/>     <-----+
</DataTrigger>                                              |
                                                            |
                                                            |
             yo, this line here! ----------------------------
4
  • 26
    Normally what I do is take a screenshot of the code and draw free-hand circles around the problem area.
    – Kredns
    Dec 11, 2009 at 16:30
  • 1
    +1 for freehand circles! i think ascii art is probably faster tho... Dec 11, 2009 at 16:32
  • 27
    Uhh, unless the very same code is available as text as well, I dislike screenshots of code, as then others might need to type the code in their answers. (Likewise for screenshots of error messages. And, it's not very SEO-friendly.)
    – Arjan
    Dec 13, 2009 at 8:32
  • 3
    @Dexter, Screenshots make it invisible to Google. Not good. Screenshot + text is a clear violation of DRY.
    – Pacerier
    Sep 21, 2015 at 8:40
25

Usually I will tag a comment on the line I'm trying to highlight. Comments have different syntax highlighting than normal code. Perhaps the highlighting of comments could be made bold to make it more noticeable or the bold highlighting only apply in a commented section?

  var foo = new Bar();  // here is the problem...
8
  • 3
    or use whitespace + comments above & below the problem line to further distinguish it... Dec 11, 2009 at 16:31
  • 3
    True this can work. But bold draws attention much easier. Especially when your code already has other comments in it.
    – Vaccano
    Dec 11, 2009 at 16:54
  • 1
    if you put your code up as whitespace... it's be hard to follow ;)
    – warren
    Dec 11, 2009 at 17:28
  • @warren, indeed: en.wikipedia.org/wiki/Whitespace_%28programming_language%29 ;-)
    – Arjan
    Dec 13, 2009 at 8:36
  • I think comments are the way to go, but what about a way to make specific comments stand out, per [my answer](#32931)?
    – benzado
    Dec 14, 2009 at 21:25
  • I think that just turning on mark up in comment sections would be sufficient, if possible. I don't know that we need to introduce new mark up elements.
    – tvanfosson
    Dec 14, 2009 at 21:55
  • I'm not clear on whether you are saying ALL comments should be highlighted (I disagree) or if bold escape codes should be enabled inside comments (I agree)
    – benzado
    Dec 15, 2009 at 18:11
  • I would experiment with both, but simply changing the style of the comments so that that aren't "grayed out" may be sufficient.
    – tvanfosson
    Dec 15, 2009 at 18:22
9

That sounds like a good idea. Here's how I would implement it:

Unformatted markdown

Here's my example code:

    var fruit = "Apple"
 -> if isRipe(fruit) do
        eat(fruit)
    end

Rendered post

Lines having that arrow should automatically be highlighted with a differently coloured background. Maybe one could add a reference number for each highlighted line.

Here's my example code:


 var fruit = "Apple"
 if isRipe(fruit) do                                                       [1]
     eat(fruit)
 end
10
  • 2
    Pre doesn't apply code highlighting, which is not great. But the idea that we ought to have additional markup which highlights a line with a yellow background is awesome.
    – Pollyanna
    Dec 11, 2009 at 18:43
  • I cannot recall mentioning <pre>… Dec 11, 2009 at 19:56
  • Ah, you have the <code> inside the <pre> - that's not too bad.
    – Pollyanna
    Dec 11, 2009 at 20:01
  • I was ok with this until I started thinking about how I actually use code in a question. If I want to test something I'll cut/paste from the question. Now -- except for inconsistent line breaks -- it works pretty much as advertised. With comments it still works as long as the comment is in the language of the code. With this I'll have to edit it up to get it to work. Not enough of an improvement over comments or a solution highlighting comments to make it worth the drop off in functionality.
    – tvanfosson
    Dec 11, 2009 at 21:59
  • 1
    @tvanfosson: That's a thought worth considering. Have you seen how popular frameworks add line numbers to code? They use their own container which makes it possible to only copy the code. That's certainly something that would be possible for the line marker too. (One negative side of it is that this needs even more horizontal space.) Dec 11, 2009 at 22:35
  • @Pollyanna: You seem to have misunderstood me. I'll try to clarify my post. Dec 11, 2009 at 22:36
  • @tvanfosson: Why not just copy the rendered version of the code? The bold will not require any special fixing if you copy from the rendered version will it?
    – Vaccano
    Dec 12, 2009 at 5:00
  • I like the idea of differently colored background (ie yellow). That would make it even clearer than bold.
    – Vaccano
    Dec 12, 2009 at 23:05
  • 3
    The problem with -> is C++ uses it to access pointer properties.
    – Macha
    Dec 14, 2009 at 19:17
  • 3
    @Macha: But not in the first 4 characters, which tell markdown that it's a code section. Dec 15, 2009 at 6:11
4

Some IDEs look for keywords within comments and treat them like bookmarks. Specifically, if you type TODO: fix this bug in a comment it is added as an item in the "table of contents" pop up menu.

What if a special keyword or syntax within a comment triggered the highlighting? For example:

<DataTrigger Value="True">
    <DataTrigger.Binding>
        <MultiBinding Converter="{StaticResource DisableWorkItemConverter}">
            <Binding ElementName="MainForm" Path="PickedWorkItemID"/>
            <Binding Path="Id"/>
        </MultiBinding>
    </DataTrigger.Binding>
    <Setter Property="IsEnabled" Value="False"/>
    <Setter Property="IsSelected" Value="False"/> <!-- HELP: here is the problem -->
</DataTrigger>

HELP: seems like a reasonable keyword that won't generate too many false positives. Either the background of the line could be colored, or (this may be simpler to implement) that particular comment can receive louder formatting (since the default comment formatting is light gray text).

1
  • And this annotative method could be used by any editor or IDE for the same effect, making it an ad-hoc standard of sorts. Advantages over all the other methods discussed here: 1. Copy-paste safe 2. Rendered text identical to markdown 3. No new MD syntax or tags 4. Comment ensures safe fencing in all languages 5. Safe for renderers who don't adopt it.
    – Amit Naidu
    Feb 24, 2023 at 1:04
3

After looking through all conservations, I still think that bolding in code is handy, especially for those who doesn't have much time. Yeah, there's many other ways to draw attention, but bolding just seems easier for starter.

3
  • If users "don't have much time" then they don't have enough time to thin and write a good question and review the answers
    – mmmmmm
    Jan 12, 2013 at 12:11
  • 1
    @Mark: it's certainly not true. Jan 12, 2013 at 18:06
  • According to your saying, if I don't have much time, I won't eat/sleep/work... as well Jan 12, 2013 at 18:07
3

In addition, sometimes it's useful to be able to have formatting inside code blocks: for instance, to represent some "computer-genic" hierarchical structure (e.g. filesystem) with nested lists. Or should code blocks be used for that at all? Triple backticks are used for block code with ignored formatting. Double backticks are redundantly used same as single ones (except with some added escaping functionality). My suggestion is to use double backticks for block code with allowed formatting. (By the way, it resembles strict equality check === vs loose one == in some programming languages :)

Usage examples (notice the double backticks):

This...:

``
- c:
    - documents and settings
        - admin
        - all users
        - default user
        - *username*
            - application data
            - local settings
                - temp
    - program files
        - Microsoft Office
        - Windows Media Player
    - Windows
        - fonts
        - system32
``

...should generate this:

  • c:
    • documents and settings
      • admin
      • all users
      • default user
      • username
        • application data
        • local settings
          • temp
    • program files
      • Microsoft Office
      • Windows Media Player
    • Windows
      • fonts
      • system32

and this...:

``
create [temp|temporary] table [if not exists] *table-name* (
    *column-name* [*type-name*]
)
``

...should generate this:

create [temp|temporary] table [if not exists] table-name (
    column-name [type-name]
)

and since markdown isn't markup, markup shouldn't be rendered, but stay literal, as written:

``
<book id="bk101">
    <author>Gambardella, Matthew</author>
    <title>XML Developer's Guide</title>
    <genre>Computer</genre>
    **<price>44.95<price> <!-- error: wrong closing tag -->**
    <publish_date>2000-10-01</publish_date>
    <description>An in-depth look at creating applications with XML.</description>
</book>
``

the above generates this (markup is untouched):

<book id="bk101">
    <author>Gambardella, Matthew</author>
    <title>XML Developer's Guide</title>
    <genre>Computer</genre>
    <price>44.95<price> <!-- error: wrong closing tag -->
    <publish_date>2000-10-01</publish_date>
    <description>An in-depth look at creating applications with XML.</description>
</book>

If you need markup formatting flexibility (e.g. colored highlights), you can wrap your code in <pre><code> and style as you wish (until markdown introduces similar styling possibilities).

2

The OP picked XAML to ask the question, when dealing with XML-based languages it would be hard using pre/code, but for the reference, if you're dealing with C# for example or any other language not involving a lot of less-than/greater-than signs, this should be really easy to achieve.

This:

public void Greet()
{
    Console.WriteLine("Hello world!");
}

Would be rendered from the following input:

<pre>
public void Greet()
{
    Console.WriteLine(<b>"Hello world!"</b>);
}
</pre>

You must log in to answer this question.

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