Lawrence Barsanti
Lawrence Barsanti

Reputation: 33222

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

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.

Upvotes: 2783

Views: 2623804

Answers (30)

Hemendr
Hemendr

Reputation: 1038

I have created a solution here using VBA that you can run using CTRL+V. How to Setup VBA script in Word Document is 5 min job and I have explained it here. Here is the output you get with the syntax highlighting and background colour removed.

enter image description here

Upvotes: 0

Pedram Porbaha
Pedram Porbaha

Reputation: 121

The easy way for me is to just copy and paste from VS code! You can change the VS code theme to a light theme which you prefer and then copy it directly (I used light modern theme).

enter image description here

Upvotes: 2

user3605767
user3605767

Reputation: 85

The easiest way is to download the code blocks extension in Google Docs, then download the file as a Word doc.

Upvotes: 0

Fahmi
Fahmi

Reputation: 2673

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

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

Upvotes: 156

Pingui
Pingui

Reputation: 1496

  1. Go to Dillinger.io (or any other on- or offline markdown editor)
  2. Type your text and multiple programming languages' code snippets in easy markdown-style (just like you would right here on stackoverflow.com)
  3. Copy & paste into e.g. MS Word

enter image description here

This works with almost any programming language and Markdown-Editor. E.g. VS Code is a Markdown-Editor, too. Just create a new .md-file, right-click it's tab and click Open Preview. That preview you can copy-paste just like explained above, too. You can also just save the .md-file as it is or (in the case of online services like Dillinger.io) explicitly export it e.g. to .html, .pdf, .rtf or .docx.

Upvotes: 2

Nicicalu
Nicicalu

Reputation: 795

For people looking for a tool in 2023. Here's a tool which works with Word 2016 and 2019.

https://syntax-highlighter.k26.ch/

I made it, because there were many tools like it and all of them were going offline or stopped working. If you have feedback or problems, please create a GitHub issue. It's also very simple, small and fits into one HTML file. You can download or clone the repo and host it yourself.

Upvotes: 6

laker93
laker93

Reputation: 802

Create a 'code' style. To do this:

  1. In 'Home' tab in the 'Styles' box, click drop down arrow and 'Create a Style'
  2. name it 'code'
  3. click Modify
  4. Format

Then format as you wish (suggested options)

  1. Paragraph -> Line and Page Breaks -> Keep lines together
  2. Border -> Shading -> Fill -> grey

Then once your code style has been created. Paste your code into the document, highlight it, then navigate to:

home -> styles -> << click drop down arrow by styles >> -> code

This has the advantage that the code is now searchable within the document (unlike gargamel's solution), as well as being able to format code that is multiple pages.

Upvotes: 4

Shubham Chadokar
Shubham Chadokar

Reputation: 2763

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.

Upvotes: 26

monty.py
monty.py

Reputation: 2789

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

Upvotes: 182

Rohit Salecha
Rohit Salecha

Reputation: 1033

  • What I do is I use Google Backup and Sync and put the docx file in the folder that syncs with Google Drive.
  • Then Open the file in chrome as google drive has functionality to parse docx file.
  • Then run this plugin https://workspace.google.com/marketplace/app/code_blocks/100740430168 which formats the code in different languages with good theme.
  • Once done save it and open the docx file in the system once it is synced.

Upvotes: 0

gargamel
gargamel

Reputation: 27930

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.

Upvotes: 2773

Marawan Mamdouh
Marawan Mamdouh

Reputation: 1015

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.

Upvotes: 11

Edward Olamisan
Edward Olamisan

Reputation: 891

You can paste your code into LINQPad. Then copy from LINQPad into MS Word. LINQPad supports following programming languages: C#, VB, SQL, ESQL and F#

Upvotes: 1

Ognyan Dimitrov
Ognyan Dimitrov

Reputation: 6251

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.

Upvotes: 6

RFAI
RFAI

Reputation: 469

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.

Upvotes: 9

meistermuh
meistermuh

Reputation: 522

Hilite doesn't seem to be mentioned yet in the answers, so: Hilite supports lots of languages (20+), can be used online also via API, and is on Github (so you can clone, modify, and run it on your own if you don't trust the online service). The online version can also be adjusted to one's needs via CSS rules.

I just found it some minutes ago since I needed a tool for copying xQuery into Word, but couldn't find a proper tool for doing so. The source program is baseX and for some reason, its formatting could not be transmitted to Word (also not via Keep format etc. when pasting). Also, many of the given answers are now, i.e. 06/2019, not working anymore or do not support xQuery. Hilite, however, did the job quite well.

Edit: a code block is not part of the result, unfortunatelly, just the highlighting. Nevertheless, it's better than nothing and adjusting the result by adding a block around is still less work than formating every single line by hand

Upvotes: 0

Mavi Domates
Mavi Domates

Reputation: 4511

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

Upvotes: 39

Steven Spyrka
Steven Spyrka

Reputation: 678

I've read and tried all the posts and I would like to give an overview of all the solutions. The best way is depending on your requirements. If there are only short snippets that are not longer than a page then go with Insert Object. If the code is longer than one page go with RTF Formatting.

Insert Textbox

  • No page break possible
  • Spell check available
  • Formatting can be ruined very quickly
  • In a document with thousands of pages Word 2016 started to make problems. At some point Word always crashed while trying to insert a new Textbox.

Insert Object > Document

  • No page break possible
  • No spell check
  • Formatting and content stays safe

RTF Formatting

Or any other wysiwyg-editor/online tool/library to style the code.

Some plug-ins/add-ons

All down or doesn't work anymore.

Upvotes: 4

Mitch
Mitch

Reputation: 661

Simply right click and paste using the "Keep Source Formatting" option. I do this almost everyday to document my work. Further, you can set the 'default paste' for pasting from various soures in File/Options/Advanced/Cut,CopyPaste. Also useful: enable "Show paste options" in the same section of Word Options.

Note that all of the text properties from your Code Editor's theme (colors, fonts, etc.) will be added to the Stylesheet in your Word doc, so I would recommend that you not make any changes directly to the pasted text as that will add clutter to your stylesheet and subsequent pastes will not match. It will be to your great advantage to do a quick study on using 'Styles' in Word (which are actually CSS). They are very powerful. Using Word's Stylesheet you can make global changes to the pasted text, but it will probably cause subsequent pasted text to add new styles.

Upvotes: 1

Nader Belal
Nader Belal

Reputation: 167

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!

Upvotes: 5

Joe Cheng
Joe Cheng

Reputation: 9524

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

Upvotes: 6

Capan
Capan

Reputation: 736

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

Upvotes: 13

maaw
maaw

Reputation: 1344

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

Upvotes: 23

Chabo
Chabo

Reputation: 3000

A quick approach I use is to use the Snipping Tool (already built in Microsoft tool) with stack overflow's preview.

Once I input my code into an Ask Question box, I then capture the preview and insert it into the MS Word document as a picture.

enter image description here

This above is the result, a picture, (not SO code ) you can put into word.

No worries about formatting, grammar checks, or downloading new software or add-ins!

Upvotes: 2

Siddarth Kanted
Siddarth Kanted

Reputation: 5906

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

Upvotes: 11

EaziLuizi
EaziLuizi

Reputation: 1615

If you already have the document created with plenty of code snippets in it and you are racing against time (as I unfortunately was). Save the file as a .doc as opposed to .docx and voila! Worked for me. Phew!

NOTE: Obviously your document can't have fancy features from > word 2007.

NOTE 2: File size becomes bigger if this is a concern to you.

Upvotes: 1

Patrick G.
Patrick G.

Reputation: 727

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.

Upvotes: 27

Andrei Karcheuski
Andrei Karcheuski

Reputation: 3306

From Powershell ISE copy and paste to Word.
Same with Visual Studio.

Upvotes: 4

Pedro Louren&#231;o
Pedro Louren&#231;o

Reputation: 610

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

Upvotes: 5

Gowtham
Gowtham

Reputation: 1475

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.

Upvotes: 13

Related Questions