How do you display code snippets in MS Word preserving format and syntax highlighting?

Asked 2023-09-20 20:26:45 View 14,006

Does anyone know a way to display code in Microsoft Word documents that preserves coloring and formatting? Preferably, the method would also be unobtrusive and easy to update.

I have tried to include code as regular text which looks awful and gets in the way when editing regular text. I have also tried inserting objects, a WordPad document and Text Box, into the document then putting the code inside those objects. The code looks much better and is easier to avoid while editing the rest of the text. However, these objects can only span one page which makes editing a nightmare when several pages of code need to be added.

Lastly, I know that there are much better editors/formats that have no problem handling this but I am stuck working with MS word.

  • I have gone with a mixed solution. Copy with RTF formatting, pasting into OpenOffice Writer, removing the background (if there is any) and then pasting the code into MS Word. For some reason I can't remove the background in Word :-( Anyways, the "Copy on steroids" plugin to do this in PhpStorm, WebStorm, PyCharm is awsome! - anyone
  • Starting with Office 365, I don't know maybe even for Word 2013 or 2016. It has Online Addin called "Code Format" . Install that Office Addin and in your word doc you can just select all code (even multiple pages) and click convert it button from the Code Format addin and it converts it into a formatted color code with line numbers. I could not find the option to format without line numbers though !!! But nevertheless, not too bad !! - anyone
  • Outside of any specific add-in that would dedicate to format code the best solution is to use styles or alternatively images. Styles are meant for formatting. I used to use many forks from Star Office to Libre Office today but I just got into Word and I found how to do it just by exploring the style config. Just use Notepad++ to export RTF then use styles. Some of the things I did is add a border, a background color I like, check "Do not add spacing between the same style" or alike (I have the French GUI so I don't know the exact english caption) and anything you like. - anyone
  • Code Format is unavailable - but Easy Code Formatter here works pretty well: appsource.microsoft.com/en-us/product/office/… - anyone
  • Just be careful with online code highlighting tool, once you submit your code, you never know what ll happen to your code. The tool provider may claimed ur code or anything. Just a warning though. - anyone

Answers

Here is the best way, for me, to add code inside word:

  1. Go to Insert tab, Text section, click Object button (it's on the right)
  2. Choose OpenDocument Text which will open a new embedded word document
  3. Copy and paste your code from Visual Studio / Eclipse inside this embedded word page
  4. Save and close

Advantages

The result looks very nice. Here are the advantages of this method:

  • The code keeps its original layout and colors
  • The code is separated from the rest of the document, as if it was a picture or a chart
  • Spelling errors won't be highlighted in the code (this is cool !)

And it takes only few seconds.

Answered   2023-09-20 20:26:45

  • Brilliant! I've been fiddling with styles, tables and other workarounds for years. This fixes everything in one go. Note that you also get the bonus of adding a caption to your code. I added a new label type "Listing" for brownie points :-) - anyone
  • @BetaRide No, it doesn't. I just used this on a document on a machine without OpenOffice installed. OpenDocument refers to a file format with support from MS Office among others: en.wikipedia.org/wiki/OpenDocument - anyone
  • Can't see that option on Word 2011 on OSX :( - anyone
  • For Word 2011 on OSX use: Insert -> Object...Microsoft Word Document - anyone
  • how can we display whole code when it is longer than one page. In that case, whole object is shifting to new page and only shows whatever comes in that page. Is it possible that the object doesn't shift to new page and also shows whole code? - anyone

Download and install Notepad++ and do the following:

  1. Paste your code in the window;

  2. Select the programming language from the language menu;

  3. Select the text to copy;

  4. Right click and select Plugin commands -> Copy Text with Syntax Highlighting;

  5. Paste it into MS Word and you are good to go!

Update 29/06/2013:

Notepad++ has a plugin called "NppExport" (comes pre-installed) that allows you to copy to RTF, HTML and ALL. It permits dozens of languages, whereas the aforementioned IDEs are limited to a handful each (without other plug-ins).

I use Copy all formats to clipboard and "paste as HTML" in MS word.

screenshot from notepad++

Answered   2023-09-20 20:26:45

  • This worked beautifully. I already had Notepad++ for other code projects, but never thought of using it. Combined with a Word style that added a faint blue background, border, and disabled spell check, it looks pretty good, and is fairly fast for a number of files, as opposed to methods involving file exports and imports. Although I wish there was a way to add it as a field that would automatically check the original .java files for updates, and keep the latest source code in the Word file. - anyone
  • Thanks for this hint. Plugins -> NppExport -> Copy RTF to Clipboard also works. - anyone
  • This worked very well. In Word 2007+, to add a border and disable spell check: 1) select your code; 2) 'Home->Styles->Save selection as new Quick Style' (it is a drop button); 3) Name it 'Code' or similar; 4) Modify; 5) Format->Border (lower left) to add border; 6) Format->Language [X] Do not check spelling or grammar. Now, you can apply the same formatting 'Code' to text pasted from NppExport. - anyone
  • This one works great, couldn't get the Word Document inside the Word Document to play nice. Folks this is the way to go! - anyone
  • @BennyNeugebauer : Line Number can be added by configure the Format->Numbering options, Define new number formate, remove the dot in first style. You can get to the Format option by either following @ Blazes 's steps OR in style select the new style->manage styles->Modify - anyone

After reading a lot of related answers, I came across my own solution, which for me is the most suitable one.

Result looks like this: the final result

As you can see, it is the same syntax highlighting like on Stack Overflow which is quite awesome.

Steps to reproduce:

on Stack Overflow

  1. Goto Ask Question (preferably with Chrome)
  2. Paste Code and add a language tag (e.g. Java) to get syntax hightlighting
  3. Copy code from preview

in Word

  1. Insert > Table > 1x1
  2. Paste code (you may need to use Paste Special... > Formatted Text (RTF) from the Edit menu to not lose the syntax hilighting)
  3. Table Design > Borders > No Border
  4. Select code > Edit > Find > Replace
    Search Document ^p (Paragraph Mark) Replace With ^l (Manual Line Break)
    (This is required to remove the gaps between some lines)
  5. Select code again > Review > Language > check "Do not check spelling or grammar"
  6. Finally add a caption using References > Insert Caption > New Label > name it "Listing" or sth

Sample code thanks to this guy

Answered   2023-09-20 20:26:45

  • To add line numbers, you could insert a column to the left and include all line numbers in one cell. - anyone
  • This is my favorite answer, because it allows people reading the document to copy/paste the code. - anyone
  • Under this approach, the code will be labeled as a table when doing auto-captioning. - anyone
  • Loses the pretty syntax highlighting for me on macOS big sur Word 16.50 - anyone
  • @spartygw make sure you use "Paste Special -> Formatted Text (RTF)" - anyone

There is a nice Online Tool for that : https://www.troye.io/planetb/

Just copy the generated code and paste it into your word editing software. So far I've tried it on MS Word and WPS Writer, works really well. Doesn't play nice with Firefox but works just fine on Chrome (and IE too, but who wants to use that).

One of the main benefits is that, unlike the Code Format Add-In for Word, it does NOT mess with your code, and respects various languages' syntax. I tried many other options offered in other answers but I found this one to be the most efficient (quick and really effective).

There is also another online tool quoted in another answer (markup.su) but I find the planetB output more elegant (although less versatile).

Input :

enter image description here

Output :

enter image description here

Answered   2023-09-20 20:26:45

  • Just to let others know, the output above is also how it will appear in the Word Document with the line numbers and green border and syntax highlighting - anyone
  • The only downside is if you want to copy and paste the code, you manually have to remove the line numbers. - anyone
  • The line numbers are just a normal Word numbered list, so you can remove them easily once copy/pasted into Word by deselecting the numbered list option (Home>Paragraph>Numbering = None). - anyone
  • This is the only solution here that worked for me - it's definitely the cleanest looking option! - anyone
  • site no longer working. - anyone

I type my code in Visual Studio, and then copy-paste into word. it preserves the colors.

Answered   2023-09-20 20:26:45

  • But far from 100% fidelity. The copy process seems to remove a lot of formatting for some reason. - anyone
  • This works very well with Eclipse and OpenOffice Writer, by the way (I don't know of Eclipse/Word or VisualStudio/Writer, 'though). - anyone
  • I wonder if it depends whether you use tabs or have Visual Studio convert tabs to spaces. I don't notice any issues with spaces. - anyone
  • Using spaces seems to fix any formatting errors. Kind of a pain, but it does work. - anyone
  • Works, but since I have a black theme... results illegible. blog.wekeroad.com/wp-content/uploads/2007/10/codefile.gif - anyone

When I've done this, I've made extensive use of styles. It helps a lot.

What I do is create a paragraph style (perhaps called "Code Example" or something like that) which uses a monospaced font, carefully chosen tabs, a very light grey background, a thin black border above and below (that helps visibility a lot) and with spelling turned off. I also make sure that inter-line and inter-paragraph spacing are set right. I then create additional character styles on top (e.g., "Comment", "String", "Keyword", "Function Name Decl", "Variable Name Decl") which I layer on top; those set the color and whether the text is bold/italic. It's then pretty simple to go through and mark up a pasted example as being code and have it come out looking really good, and this is works well for short snippets. Long chunks of code probably should not normally be in something that's going to go on a dead tree. :-)

An advantage of doing it this way is that it is easy to adapt to whatever code you're doing; you don't have to rely on some IDE to figure out whatever is going on for you. (The main problem? Printed pages typically aren't as wide as editor windows so wrapping will suck...)

Answered   2023-09-20 20:26:45

  • Thanks Donal for this information. May ask though, how can I use intents to represent nested code lines? If I use a background color and border for my paragraph, when I use indent the whole block is moving. - anyone
  • Would have been nice to share your style/template? - anyone
  • Been doing the same for ages - one big bugbear: whenever I apply the style, Word still red-underlines spelling problems. If I modify-style and select Format->Language, "Do not check spelling and grammar" is checked, and if I now close the format dialog with Ok, the lines will go - but they always appear until I do that. - anyone
  • @Rhubarb, add the "no check" attribute to your style. This works but is a fair amount of work if you want to maintain colors. - anyone
  • Copy from Visual Studio/SSMS/Notepad++ to get the colours. Then make and save this style in word: Font: (Default) Consolas, 9.5 pt, Do not check spelling or grammar, Indent: Left: 2.54 cm Right: 2.54 cm Line spacing: single, Space Before: 16 pt After: 16 pt, Don't add space between paragraphs of the same style, Level 9 Pattern: Clear (Custom Color(RGB(242,242,242))), Don't adjust space between Latin and Asian text, Don't adjust space between Asian text and numbers, Style: Linked, Automatically update, Show in the Styles gallery Based on: Normal - anyone

I'm using Easy Code Formatter. It's also an Office add-in. It allows you to select the coding style / and has a quick formatting button. Pretty neat.

enter image description here

Answered   2023-09-20 20:26:45

  • This seems cool but no way to install it in my word 2016... Error from word all time - anyone
  • @Jebik - if you're using a company account, perhaps your admin might have blocked the installations? I'm using it on 2016...What's your build number? - anyone
  • I had the version 16.0.4849.1000. But as i said i have install 2 other supplément. So my compagny don't seem to block installation. It's jsut this extension i can't install. I don't even find it in store to be honest. From word when i open store and look for app this one is not in list - anyone
  • That means your Word is in a build version that doesn’t support this addin. - anyone
  • Try updating word if you can, your version seems a bit old. - anyone

Maybe this is overly simple, but have you tried pasting in your code and setting the font on it to Courier New?

Answered   2023-09-20 20:26:45

  • It still won't keep syntax highlighting. - anyone
  • @Sk8erPeter: That's not necessarily the case. Copy and paste is more than capable of transferring color information -- it does it all the time when I'd rather it didn't. It depends on whether the source and destination applications both support the same schema for specifying it. - anyone
  • *** IMPORTANT*** for VS users: A LOT of these answers work. HOWEVER, Most will NOT work if you don't have correct options set in Visual Studio. In order to copy COLOR coding from Visual studio, you need to go to Tools > Option > Text Editor > Advanced > make sure the 'Copy rich text on copy/cut' check box is selected. Once you do this, pretty much any of the answers to this question work. - anyone

Try defining a style called 'code' and make it use a small fixed width font, it should look better then.

Use CTRL+SPACEBAR to reset style.

Answered   2023-09-20 20:26:45

  • You won't keep syntax highlighting. - anyone
  • Syntax highlighting is overrated if we're talking a Word document here. But it is also easily implemented in a VB script that colors all text styled as "Code". - anyone
  • That's how I do it too with pretty good results, though I also turn off spelling/grammar checking for my "code" style. - anyone
  • Of course you can keep syntax highlighting: Create a Style without a font color - anyone

If you are using Sublime Text, you can copy the code from Sublime to MS Word preserving the syntax highlighting.

Install the package called SublimeHighlight.

In Sublime, using your cursor, select the code you want to copy, right click it, select 'copy as rtf', and paste into MS Word.

Answered   2023-09-20 20:26:45

  • This worked perfectly for me. Word extension completely messed up my code and comments, making in unreadable. This actually worked perfectly. I'll add that you can simply go to sublime, hit cmd+shift+P, go to Install package and type highlight there. It'll install it right away - anyone
  • Higlight is working fine, however the format is getting messed up. - anyone
  • Or just say "copy as HTML" in the edit menu - anyone

The best way I found is by using the table.

Create a table with 1x1. Then copy the code and paste it.
If you're using the desktop app then it will inherit the code editor theme color and paste it accordingly, else you can change the table style to any color.

enter image description here

UPDATE ------------------

From Word 2021, you can directly paste the code and it will preserve the formatting. No need to create the table. Thank you @RdC1965 for mentioning this.

Answered   2023-09-20 20:26:45

  • This does not copy colors from vba. May work with other languages. - anyone
  • Never tried VBA. But it depends on IDE theme. Try to change the theme and then paste it. - anyone
  • Yeah. thanks you very much! Just create table 1x1, copy code from VSCode. Done! - anyone
  • At least with Word 2021, you just need to copy from VS Code and paste into Word. You don't need the 1x1 table. - anyone

In case you're like me and are too lazy or in a hurry and don't want to download additional software, you can use http://markup.su/highlighter/. It's very straight forward and supports several highlight themes and many programming languages. http://markup.su/highlighter/In my case I was using Visual Studio Code, which doesn't allow copying with format due to CSS involved in styling (as reported here).

Copy the text from the Preview box and then in Word go to Insert -> Textbox, paste the Preview from the website, highlight all the text, and then disable spell checking for that textbox.

This is what the code looks like finally.code as seen in Word

Answered   2023-09-20 20:26:45

  • Is there a way to change the font size? My code is very big and I want to fit it in few pages in word. Changing font size in word doesn't help - anyone
  • Could it be that you're not highlighting the text inside the textbox prior to changing the font size? - anyone
  • @dark32 if I understand your issue correctly, you need to change the line spacing: support.office.com/en-us/article/… - anyone
  • This was working great a week ago, however, as of 12/78/2017 the site markup.su/highlighter no longer works. Hopefully it will be back up soon. - anyone
  • Link is dead again... Just a heads up. - anyone

This is a bit indirect, but it works very nicely. Get LiveWriter and install this plugin:

http://lvildosola.blogspot.com/2007/02/code-snippet-plugin-for-windows-live.html

Insert your code using the plugin into a blog post. Select all and copy it to Word.

It looks great and can include line numbers. It also spans pages decently.

HTH

Colby Africa

Answered   2023-09-20 20:26:45

  • Requires account on Windows Live or Wordpress or some other of 10 blogging platforms. - anyone

Vim has a nifty feature that converts code to HTML format preserving syntax highlighting, font style, background color and even line numbers. Run :TOhtml and vim creates a new buffer containing html markup.

Next, open this html file in a web browser and copy/paste whatever it rendered to Word. Vim tips wiki has more information.

Answered   2023-09-20 20:26:45

In my experience copy-paste from eclipse and Notepad++ works directly with word.

For some reason I had a problem with a file that didn't preserve coloring. I made a new .java file, copy-paste code to that, then copy-paste to word and it worked...

As the other guys said, create a new paragraph style. What I do is use mono-spaced font like courier new, small size close to 8px for fonts, single spaced with no space between paragraphs, make tab stops small (0.5cm,1cm,..,5cm), put a simple line border around the text and disable grammar checks. That way i achieved the line braking of eclipse so I don't have to do anything more.

Hope I helped ;)

Answered   2023-09-20 20:26:45

This is the simplest approach I follow. Consider I want to paste java code.

  1. I paste the code here so that spaces, tabs and flower brackets are neatly formated http://www.tutorialspoint.com/online_java_formatter.htm

  2. Then I paste the code got from step 1 here so that the colors, fonts are added to the code http://markup.su/highlighter/

  3. Then paste the preview code got from step 2 to the MS word. Finally it will look like this

enter image description here

Answered   2023-09-20 20:26:45

You can use VS code to keep code format and highlighting. Directly copy and paste code from VS.enter image description here

Answered   2023-09-20 20:26:45

  • This one i found smartest answer for this question. Thanks! - anyone

you can simply use this Add-in on any office program.

Go to insert tab, then Get Add-ins, and search for Easy Syntax Highlighter

It supports

  • 185 languages and 89 themes.

  • Automatic language detection.

  • Multi-language code highlighting.

Answered   2023-09-20 20:26:45

  • This works in MS Word online too. Thanks a lot. - anyone
  • You're welcome. - anyone
  • WARNING (not only just a waste of time) Asks for your phone number and other personal information and then sends you to a broken link - anyone
  • Skip the link, Just go to the insert tab in the office program you use, then click Get Add-ins, and search for "Easy Syntax Highlighter" and add it. @RobHoff - anyone
  • It's more of a headache than an asset. Just removed it! - anyone

Answer for people trying to resolve this issue in 2019:

Most answers to this question are outdated by now. I wish there was a way to reinspect old questions and answers every now and then!

The method I found for this question that works with Office 365 and its associated programs can be found here.

Answered   2023-09-20 20:26:45

Use a monospaced font like Lucida Console, which comes with Windows. If you cut/paste from Visual Studio or something that supports syntax highlighting, you can often preserve the colour scheme of the syntax highlighter.

Answered   2023-09-20 20:26:45

I'm using Word 2010 and I like copying and paste from a github gist. Just remember to keep source formatting!

I then change the font to DejaVu Sans Mono.

You can opt to copy with or without the numbering.

Answered   2023-09-20 20:26:45

Copying into Eclipse and paste it in Word is also another option.

Answered   2023-09-20 20:26:45

You can also use SciTE to paste code if you don't want to install heavy IDEs and then download plugins for all the code you're making. Simply choose your language from the language menu, type your code, high-light code, select Edit->Copy as RTF, paste into Word with formatting (default paste).

SciTE supports the following languages but probably has support for others: Abaqus*, Ada, ANS.1 MIB definition files*, APDL, Assembler (NASM, MASM), Asymptote*, AutoIt*, Avenue*, Batch files (MS-DOS), Baan*, Bash*, BlitzBasic*, Bullant*, C/C++/C#, Clarion, cmake*, conf (Apache), CSound, CSS*, D, diff files*, E-Script*, Eiffel*, Erlang*, Flagship (Clipper / XBase), Flash (ActionScript), Fortran*, Forth*, GAP*, Gettext, Haskell, HTML*, HTML with embedded JavaScript, VBScript, PHP and ASP*, Gui4Cli*, IDL - both MSIDL and XPIDL*, INI, properties* and similar, InnoSetup*, Java*, JavaScript*, LISP*, LOT*, Lout*, Lua*, Make, Matlab*, Metapost*, MMIXAL, MSSQL, nnCron, NSIS*, Objective Caml*, Opal, Octave*, Pascal/Delphi*, Perl, most of it except for some ambiguous cases*, PL/M*, Progress*, PostScript*, POV-Ray*, PowerBasic*, PowerShell*, PureBasic*, Python*, R*, Rebol*, Ruby*, Scheme*, scriptol*, Specman E*, Spice, Smalltalk, SQL and PLSQL, TADS3*, TeX and LaTeX, Tcl/Tk*, VB and VBScript*, Verilog*, VHDL*, XML*, YAML*.

Answered   2023-09-20 20:26:45

  • Doesn't work when pasting PHP code. Only the start and end brackets are highlighted :( Worked fine for Java though. - anyone

If you are using Intellij IDEA, just copy the code from the IDE and paste it in the word document.

Answered   2023-09-20 20:26:45

A web site for coloration with lots of languages. http://hilite.me/

You can host one yourself since it is open source. The code is on github.

Answered   2023-09-20 20:26:45

  • hilite.me also works on Google docs! - anyone

There really isn't a clean way to do it, and it could still look fishy based on your exact style settings.

What you could try to do is to first run a code-to-HTML conversion (there are many programs that do that), and then try to open up the HTML file with word, that might hopefully provide you with the formatted and pretty code, and then copy and paste it into your document.

Answered   2023-09-20 20:26:45

I was also looking for it and ended up creating something for my code display. Here's a good way:

  • Create a rectangular form and place your text inside.
  • Change the font to Consolas and size ~10.
  • Change the text font to gray near-black (gray 25%, darker 75%)
  • Use darker colors to highlight your text if needed and choose one to be the contour.

enter image description here

Answered   2023-09-20 20:26:45

I have created an easier method using tables, as they are easier to create, manage, and more consistent (with the possibility to save the table's style inside the document itself), but I couldn't find a better way for code colouring scheme, sorry for that.

Steps:

  1. Create a 3x3 table.

  2. Select the table, and make its borders invisible ("No Borders" option), and activate "View Gridlines" option. enter image description here

  3. Make the adjustments to cells' spacing and columns' widths to get the desired aspect. (You will have to get in "Table Properties" for fine tuning). enter image description here

  4. Create a "Paragraph Style" with the name of "Code" just for your code snippets (as mentioned in https://stackoverflow.com/a/25092977/8533804)

  5. Create another "Paragraph Style" with the name of "Code_numberline" that will be based upon the previous created style, but this you will add a numbering line in its definition (this will automate line numbering). enter image description here

  6. Apply "Code_numberline" to the first column, and "Code" to the 3 column. enter image description here

  7. Add a fill in the middle column. enter image description here

  8. Save that table style and enjoy!

Answered   2023-09-20 20:26:45

  • If you copy and paste code you have to manually split lines to the rows. - anyone
  • Last time I used this method, I didn't have to. May be you need to select various rows. - anyone

The best presentation for code in documents is in a fixed-width font (as it should appear in an IDE), with either a faint, shaded background or a light border to distinguish the block from other text.

Answered   2023-09-20 20:26:45

If its Java source code copy it to Visual Studio and then copy it back to Word.

Answered   2023-09-20 20:26:45