Google Docs – Number Lines in Formatted Code

google docs

There is a few questions regarding inserting and appropriately formatting code in Google Docs (here and here for example). Indeed there is a very useful Google-Docs add-on called Code Blocks which works very well.

However, I would like the option to number the lines of code.

I got the idea from the output seen on this page (scroll down a bit and you 'll see what I mean). I am writing student notes for a beginners class I am teaching and it would be helpful to have similar numbers in the code formatted by Code Blocks within Google Docs.

I searched for a solution (this thread seemed promising, but no real solution).

Does anyone know of a way to have formatted code with numbered lines in Google Docs?

An (easily attainable) output like this would be ideal:

enter image description here

Thanks.

PS – I also searched for a 'reverse' solution, i.e. copy code WITH line numbers. My IDE is Visual Studio 2017 Community edition – and it doesn't seem to provide this option, I have only found extensions which work for Visual Studio Code (an altogether different application). However, it would be better to find a way to 'add' line numbers in google docs – this way one would not be restricted by the IDE/editor. Copying code and pasting in an editor and then re-copying with line numbers would be a choice, but way too cumbersome.

Best Answer

The workaround I use is codepad.org.
I paste the code, select the language and then the website outputs the code in a colour coded way along with the line numbers.

  1. I paste the code:

I pasted my code here.

  1. Then Copy the formatted code (If you want the line numbers, then include them in your selection too):

enter image description here

  1. Pasting it in Google Docs will add it as a table preserving all the formatting.

enter image description here

You can use other "syntax highlighters" too, but when pasting the code in Google Docs, you may have to adjust some line numbers manually.