101

Many times users paste long code and those who want to refer to a specific line refer to it by its content, which can be misleading or cumbersome if the content appears elsewhere or the line is long.

I was wondering why code blocks don't have line numberings as present in many other sites hosting code files. Something simple like this

01 MainClass {
02
03     AConstructor {
04
05         something something
06         more...
07     }
08
09     void function1(int x) {
10
11         ...
12     }
13 }

can't be hard to implement and of course useful as all IDEs do this. I would go as far as asking to be able to start from a specific line number (e.g. start numbering from 12) in case the user posts a stack trace relating to part of the code and others can see exactly where the error occurred. For example if "error occurred on line 25 of main" the user might just post main which starts on line 12 of the file.

14
  • 4
    meta.stackexchange.com/questions/7119/…
    – Habib
    Commented Apr 28, 2014 at 17:57
  • 18
    If users are posting their entire code files, they're likely doing something wrong, thus the line numbers wouldn't match up with any stack traces, making them not particularly helpful.
    – Servy
    Commented Apr 28, 2014 at 17:58
  • @Habib Oh, I was searching Meta SO and not Meta SE. Commented Apr 28, 2014 at 17:59
  • 16
    How did it jump from line 06 to 97 back to 08? Commented Apr 28, 2014 at 18:10
  • 1
    If the question includes error messages with line numbers, add comments to the source code marking the relevant lines. Numbering every line makes it difficult to copy-and-paste the code and try it on my own system (I'm sure there are ways to render line numbers that avoid that). And if the questioner posts only a subset of the source file (which is sometimes appropriate), then any automatic line number will be meaningless. Commented Apr 28, 2014 at 19:05
  • 8
    The line numbers will help with discussing the code in comments, etc. I think it'll help a lot. The numbers could be initialized to line up with the stack-trace, or we could just all assume that they don't line up (which makes things easy). Copy/Paste isn't really a difficult problem to solve. Commented May 8, 2014 at 20:36
  • 2
    @KeithThompson I once saw a site where line numbers were added and nevertheless, c&p worked. So it is not impossible.
    – glglgl
    Commented Jul 2, 2014 at 21:34
  • 2
    @glglgl: Ok, but that doesn't address the case where the OP posts just 5 lines of code and the error message refers to line 42. Commented Jul 2, 2014 at 22:17
  • 1
    @KeithThompson That's right.
    – glglgl
    Commented Jul 3, 2014 at 5:26
  • 1
    Someone else linked to it in a comment on the post linked above, but in case you didn't see it: UserScript - it also has support for line offsets by adding a comment such as #Line:40. FYI for later readers of this, I will try to keep the link in my profile up-to-date for this script.
    – MDEV
    Commented Aug 8, 2014 at 14:31
  • @SmokeyPHP Very nice, works well. It does create, however, extra empty lines at the bottom of each code block. Commented Sep 10, 2014 at 18:55
  • @user1803551 Oh really? I don't see that issue here - is that using greasemonkey in the latest Firefox?
    – MDEV
    Commented Sep 10, 2014 at 20:41
  • @SmokeyPHP Using Opera 24 with Violentmonkey extension. Commented Sep 11, 2014 at 2:47
  • Editing code block will do mess. Commented Mar 31, 2017 at 9:05

9 Answers 9

47

Adding line numbers is a no-brainer to me. It's frustrating that line numbers aren't included in SO. How many of us code without line numbers? (I sure don't). There simply isn't a better way to refer to an exact location of code (if there was, then compilers would've switched to that method long ago). Especially when making comments (where text length is limited), it would be hugely beneficial to have the option of saying "at line x ..." rather than "where you're dereferencing myVar for the second time ...", or "In myFunc, the second call to myFunc2 ...", or the code substitution that I see frequently that works like "your broken code here->my fixed code here", etc. There are few situations where labeling a location would be more concise than simply referring to a line number.

Now for my counterpoints:

I get error X on line Y, here is my code

Yes, it is true that the line numbers in SO won't match up with the OP's line numbers. So what? 99% of the questions I see like this are syntax errors and they get downvoted and closed as typos anyway. For the remaining 1%, anyone thoughtful enough to be asking a solid question will reference the line numbers that SO provides. If they aren't putting enough effort into their question to do that, then they probably aren't putting enough effort into their question as a whole, and its going to get DVed and closed anyway.

why should it be okay to ask a question with hundreds of lines of code?

It's not (barring the few instances where this may be necessary for an MCVE). How would adding line numbers encourage this behavior? If somebody does a code dump, it's most likely from an impatient new user who hasn't taken the time read How to Ask and wants an answer right now; the thought of whether or not line numbers will get posted with their code won't even enter their brain. It's not from someone nefariously scratching their chin thinking, "hmmmm, I will make those poor saps on SO eyes' bleed with my line number explosion hahahaha!!!", and then proceed to post 6000 lines of code. Even if they did, it would get ignored/DVed/closed.

Additionally, horizontal space is already somewhat limited in code blocks, to add line numbers would only make that worse.

Another valid point, but again, there shouldn't/won't be a ton of code posted in the questions. A great majority of Questions will be <100 lines, and certainly the rest will be <1000 lines. If they aren't, they already get ignored/DVed/closed. I can easily live with 2-3 characters of lost horizontal space for the benefit of line numbers; I live with more than that in Vi every day.

I think line numbers should behave in the following ways.

  • They only apply to block code, not back-ticked code
  • The line numbers scope the entire question. That is, if the OP has a block of code, some text, and another block of code,,, the second block of code starts its numbering where the first left off, not at "1".
  • Line numbers only appear after some threshold of lines (10 for instance).
  • Best case scenario, SO works some magic and makes them optional, so each user could turn them on or off at will.

For at least the tag I hangout under (c), people generally want to help even if the OP hasn't posted the perfect MCVE-well-researched question. Referencing line numbers is the simplest, most concise way to refer to code, particularly if the OP has multiple bugs in their code.

5
  • 2
    I'd like to suggest that the first line number of a block of code can be manually notated, and manually forced. This might be useful for something like one of my answers from a few months ago: stackoverflow.com/questions/51843313/… There were not a lot of lines, but having those line numbers was absolutely critical for my answer to make any sense (which is why I wrote them in the answer). I propose using some formatting like so to force the line numbers at a specific line ```_language_#lineNo\n ...\n ``` Commented Jan 15, 2019 at 15:32
  • 1
    How can we influence SO to get this implemented? I don't understand why this is not implemented already... I was just asking for this in a new post and got closed with a link to this older post (which when I searched could not find). Would love to see line numbers!
    – John
    Commented Aug 22, 2020 at 8:07
  • 1
    I have another argument against line numbers: MCVEs won't necessarily match up with line numbers. This is especially true for cases where other functions or variables are irrelevant, and therefore removed, or just a single function is looked at, causing the numbering to start at 1 when it really should start at 1793. Line numbers are so relative that implementing it comes with other major challenges - honestly, highlighting the relevant line(s) is arguably gonna be more accurate. Also, with languages where multiple classes means multiple files, incrementing code block numbers causes inaccurac Commented Aug 22, 2020 at 8:29
  • 1
    That's not an argument against line numbers - If it fixes the problem in MCVE, the questioner will have learnt sufficiently to fix in the original source. It appears to me that line numbers should have been implemented years ago but haven't for who knows what reason.
    – John
    Commented Aug 22, 2020 at 12:10
  • I would be in favor of this. But it would need to be a specific toggle or associated with a language type and not just ``` since that construct is used for text other than code.
    – WJS
    Commented Mar 3, 2021 at 23:16
12

"I get error X on line Y, here is my code"

User then presents a portion of their code. Line numbers in the code block obviously won't match numbers in the original file, making "line Y" meaningless.

This problem could be averted if there were some way to define the first line number, but that's too much effort.

Additionally, horizontal space is already somewhat limited in code blocks, to add line numbers would only make that worse.

8
  • 2
    optional wrapping? I realise that both of these require extra configuration but maybe it could be a 500 rep privilege or something.
    – jcuenod
    Commented May 12, 2015 at 12:26
  • 3
    What if the reader may enable them if desired?
    – hek2mgl
    Commented Feb 29, 2016 at 9:07
  • What about the ability to assign line numbers to lines?
    – user4639281
    Commented Dec 13, 2016 at 16:19
  • 1
    Yes, these darned Turing machines are just so hard to program.
    – user663031
    Commented Mar 31, 2017 at 18:34
  • "Too much effort"? You could put a line number in the markup.
    – chb
    Commented Feb 20, 2018 at 23:13
  • 1
    all of this could be solved with software... Drag and drop your .py or .java or .cs file here, highlight the relevant parts, then we will figure out the line numbers for you and make all references to line numbers in prose into permalinks so if the code does have to be edited, references will remain correct. Bam.
    – NH.
    Commented Oct 3, 2018 at 19:30
  • incidentally, this would solve some instances of people pasting code as images, too. I think I'll write up a separate answer.
    – NH.
    Commented Oct 3, 2018 at 19:32
  • I think the majority of the questions provide some code and ask why it's not working. It would still be an huge improvement to help answering questions, instead of having to copy (somtimes huge) lines of codes in your answer just so you can refer to a specific point. Regarding horizontal space: it could be implemented collapsable. Commented Dec 11, 2022 at 12:59
3

I hate to answer a question with a question, but why should it be okay to ask a question with hundreds of lines of code?

Reading lots of code takes time. It can lead one down a major rabbit hole and on things that may or may not be related to the question. It could also potentially expose other broken things, which may are completely tangential to the question at hand. That really distracts from the core of the question.

There are people that will happily post their entire projects here, but they really shouldn't be doing that. Instead, they should endeavor to find the simplest slice of code that can reproduce their bug, and post that instead.

Adding line numbers would only seem like posting lots and lots of code is encouraged. That doesn't seem like something we'd want to encourage.

There are some great points also raised in a similar Meta question, such as "any change to the code could potentially invalidate answers", which I do agree with entirely. But, I would disagree with putting line numbers on SO (or any site with code-like support), because it means that someone's going to post a whole project here, and think it's okay.

8
  • 16
    I think that numbering helps for 20 lines, no one said hundreds of lines and I don't think I ever saw a code block of more than 100 lines at most. Commented Apr 28, 2014 at 18:09
  • 2
    Depending on the tags you frequent, and the time of day you frequent them, you come to see quite a few. That said, twenty lines of code isn't enough code to warrant line numbers; if there is an error contained in that code, it's easy enough to identify or highlight without the need for a line number.
    – Makoto
    Commented Apr 28, 2014 at 18:10
  • 1
    To answer "why should it be okay to ask a question with hundreds of lines of code", Stack Overflow tells us time and again that it needs complete examples, not just pieces of code, in the body of the question itself, not in an external link. And very often you just won't be able to compress the code down any further if you want to keep it complete and causing the very same error you're asking about.
    – Mr Lister
    Commented Sep 18, 2015 at 9:56
  • @MrLister: Do you insist on the same line-numbers, identifier-names and other incidental paraphernalia? If so, sure, creating an mcve won't do much. Otherwise, that seems a really extreme outlier. Commented Oct 2, 2015 at 23:11
  • One would struggle to find a better example of the corrosive "whole idea is bad because I thought of one case where there is a problem I can't see a solution for right away" mentality which pervades MSO.
    – user663031
    Commented Mar 31, 2017 at 18:36
  • You okay @torazaburo? I get the feeling that something's not quite okay. Especially given that this answer is almost 3 years old.
    – Makoto
    Commented Mar 31, 2017 at 19:30
  • @Makoto Thanks for reaching out. Yes, I really need to go back on my meds. Is this feeling you have based just on this comment or some other data points? Anyway, I just visited this question because it popped onto the front page due to a new answer. In general, I'm frustrated because although MSO works well for many kinds of questions, it's entirely dysfunctional when it comes to feature ideas.
    – user663031
    Commented Mar 31, 2017 at 19:42
  • 20 lines is already an exceptionally large amount of code in a single block for a legitimately minimal example. Commented Feb 11 at 5:11
3

I will try to boldly fix multiple issues at once

I suggest a special code-pasting box that allows drag-and-drop of both text and source files (with your language's standard file extension, which will update the language tag on the question, making syntax highlighting automatic). This box will keep long sections of code (which are relevant for reproducing the issue, but take too long to read) in a separate place (perhaps a auto-generated GitHub repo). After uploading or pasting the code, the student asker will select the relevant portion to the question and a reference to it will be put into the main question text for them. This reference will link to the correct line of the external source file, and anytime sources need to be updated, the reference will update as well since it will be identified by GUID rather than by line #.

This box will require minimal work for humans, as the computer will handle the:

  • code formatting (similar to https://prettier.io/playground/ )
  • language tagging
  • line numbers references (as said above, these are based on GUID, and don't change when the question is edited).

This will vastly improve the User eXperience for new askers, and thus also fixes https://meta.stackoverflow.com/a/374706/1739000

Bonus: if code is in a lanugage that can be run online (C#.NET, TIO languages, HTML with StackSnippets, etc.), could create a link to run it as well.

1

This is a terrible idea that runs completely counter to the site's design and goals. In particular, it spits in the face of the concept of a minimal reproducible example - or as some might prefer to call it, a short, self-contained, correct example (SSCCE).

Questions that are about an existing piece of code are generally supposed to include a SSCCE, so as not to be closed as "Needs More Focus" or "Needs Debugging Details". But adding line numbers to code blocks in the OP would sabotage every aspect of the SSCCE concept:

  • A SSCCE is short, but line numbers facilitate length.

    The code in the question should be no longer than absolutely necessary to frame the question properly. For almost every question, this is at most a few lines of code. If there are enough lines of code that counting them seems useful, something has probably already gone wrong. (Of course, some languages/platforms/environments entail more boilerplate than others; but the important part is probably just a few lines in the middle.)

  • A SSCCE is self-contained, but line numbers encourage relying on context.

    The code in the question is supposed to be self-contained. If the OP has a file with hundreds of lines of source code, and copies and pastes a few apparently relevant lines and a stack trace, the obvious problem with a line-numbering feature is that it wouldn't know what line number to start with so as to match the stack trace. But the more important problem is that the stack trace doesn't correspond to the code shown - it corresponds to the original context. A proper MRE can be run by itself; therefore, if it's an MRE of an error, the stack trace will show a small line number that can easily be found within the code shown.

  • A SSCCE is correct, but line numbers interfere with corrections.

    Sometimes edits happen. Since the code is supposed to stand by itself and exemplify the problem for third parties (see the next point), naturally it will happen that people have a better idea about how to present that code. Maybe they'll change the bracing or indentation style if the question isn't about those things. Maybe a minor refactoring can be done that doesn't affect the key issue. Maybe there was a secondary problem in the code unrelated to the question being directly asked. When code in the question is edited, this can occasionally invalidate answers, depending on exactly how they are written. But this problem gets much worse with line numbers - because instead of copying code into the answer, people will refer to the question's code by line number. The copied code would still be sufficient to answer the question that's still showcased by the question's code. But if a line number is used instead, it can be invalidated.

  • A SSCCE is an example, but line numbers encourage treating code as unique.

    Questions are supposed to be about a concept, not about a specific piece of code. The purpose of the question is to be able to help other people - who wrote different code in different places within different source code files, but yet have the same problem with the same underlying cause. If an answer starts out "Your problem is here:", that's a failure: aside from any potential offense taken at that wording, the answer is a) providing a debugging service (and thus doing what should be OP's work) and b) making itself needlessly specific to the example code, when it could be explaining a concept generally. Line numbers make this problem dramatically worse, because they allow direct reference to the specific code in the OP, and create the false impression that this specific code is key. The problem where someone tries to use Stack Overflow as a debugging service and someone else complies is magnified, because the line number only has meaning to the OP in this case - since it refers to OP's code. Others with the same problem can't use that line number.

In conclusion, line numbers are useless when questions are written the way they're supposed to be written, and would facilitate a wide array of problematic misuses of the site software. Let's continue not having them; let's mark this ; and let's make sure any future suggestions along the same lines are promptly dealt with.

0

I could agree with some of you here (eg like "I get error X on line Y, here is part of my code")
But I just saw a simple code snippet that produced a error, that made me wanna look for this question enter image description here

For most cases the snippets include all code necessary.
It could make since to add lineno for the runnable code snippets or at least make it optional somehow

-2

I don't have enough credits to comment but I'd like to point out that just because it's meant for code, that's not necessarily the only thing somebody might use code boxes for.

Aren't devs supposed to think outside the box? (no pun). Aren't devs finding all the time ways to make some code do what it was not intended to do…and better?

For code code blocks, I saw something about edits screwing up alignment, is it relevant though; this thing has revisions/history, don't it? Or maybe I'm getting it mixed up with wikis, but as I'm writing this I noticed a little icon that looks like Apple's Time Machine icon next to the answer above this box.

I'm just saying, maybe let users decide for themselves. In HedgeDoc, all it takes to add then is a = character after the syntax highlighter code spec, and a number after that to specify the starting line number. It could be that simple, y'know? Loosen up a little.

1
-3

One drawback of having line numbers is that the answers which reference particular lines of code will potentially be invalidated when the question's code block(s) is/are edited.


This can lead to hilarious situations...


Why does my code cause an error?

1        console.log('hello world);
2    }

Commenter 1: "You missed the closing quote on line 1."


EDIT:

Why does my code cause an error?

1    function gucciGang() {
2        console.log('hello world);
3    }

Oops, LOL, I forgot to add the first line into the question.


Commenter 1: "You missed the closing quote on line 1."

Commenter 2: "What closing quote on line 1? It's on line 2, you idiot!"

Commenter 3: "I flagged your comment as rude/abusive."

Commenter 1: "The OP edited the code block. I'm reporting that to Stack Exchange because that's abuse of the editing system."

OP: "FU"

Commenter 3: "Settle down, guys. Or else I'll have to call up the mods."

{ ARGUING CONTINUES }


Related: https://meta.stackexchange.com/a/77814/296278

3
  • 1
    Why the downvotes?
    – clickbait
    Commented Jul 7, 2018 at 15:07
  • 1
    I dunno.. your point is completely valid in my book.
    – NH.
    Commented Oct 3, 2018 at 19:34
  • 4
    Because your answer equally applies to all edits and all answers, as we have it today. It's not specific to line numbers, and more a problem of not having comments and answers linked to edit versions of the original question.
    – John
    Commented Aug 22, 2020 at 12:42
-11

Answer a question with code by copying the code, edit it and put some comments in it. No lines needed and i believe code lines would only do harm, if one does not copy or edit correctly the lines will be offset and only creates confusion.

You must log in to answer this question.

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