[ms-word] 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.

This question is related to ms-word

The answer is


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


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.


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.


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.


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!


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


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


enter image description here

Code Format Addin is now available in Office Addins with Office 365 ! Just select the code and click convert it and it converts the code text to formatted color code with line numbers !!!

Bit Rejoice!

Code Format is available here: https://appsource.microsoft.com/en-us/product/office/WA104379501?tab=Overview


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*.


Simplest solution, for me atleast, is to 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.


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


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


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


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.


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!


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


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


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#


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.


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++


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#


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.


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.


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


The best way what 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 colour.

enter image description here


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


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


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


Ok, this is weird, but to address the background color issue I paste in the text as normal, select the whole block, click on the highlighter tool to highlight (even if the highlight is set to "No Color"), and then I can style the text block without the background color of the text remaining white. I am using VS 11 and Word 2010, but the problem has been around for a long time (see http://www.visualstudiodev.com/visual-studio-setup-installation/copypaste-code-from-vs-1305.shtml)


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


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...)


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.


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.


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.


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.


If you're using TextMate (On OS X), use the "copy as rtf" command. It will place pretty-printed text onto the clipboard. rtf command

From there you can paste into word or anything else.


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


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


The best way what 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 colour.

enter image description here


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


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


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.


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...)


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!


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.


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


If you're using TextMate (On OS X), use the "copy as rtf" command. It will place pretty-printed text onto the clipboard. rtf command

From there you can paste into word or anything else.


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.


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.


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


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.


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


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.


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.


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.


Just paste your code in MS Words, select it -> then right click -> Numbering. In this case MS Word will interpret your code as marker/numbered list.

Here is the screens:

Screen1.

Screen2.


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


Ok, this is weird, but to address the background color issue I paste in the text as normal, select the whole block, click on the highlighter tool to highlight (even if the highlight is set to "No Color"), and then I can style the text block without the background color of the text remaining white. I am using VS 11 and Word 2010, but the problem has been around for a long time (see http://www.visualstudiodev.com/visual-studio-setup-installation/copypaste-code-from-vs-1305.shtml)


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


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


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


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


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.


You can just use PlanetB: http://planetb.ca/syntax-highlight-word

Copy and Past, choose the language and enjoy the result.


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


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.


If you are using Android Studio, you can simply copy and paste, and the code aspect is going to be preserved and the colors as well. Simple enough!


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


enter image description here

Code Format Addin is now available in Office Addins with Office 365 ! Just select the code and click convert it and it converts the code text to formatted color code with line numbers !!!

Bit Rejoice!

Code Format is available here: https://appsource.microsoft.com/en-us/product/office/WA104379501?tab=Overview


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


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.


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.


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
  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


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!


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.


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.


If you are using Android Studio, you can simply copy and paste, and the code aspect is going to be preserved and the colors as well. Simple enough!


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*.


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


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.


Just paste your code in MS Words, select it -> then right click -> Numbering. In this case MS Word will interpret your code as marker/numbered list.

Here is the screens:

Screen1.

Screen2.


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 ;)


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++


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.


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
  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


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.


Simplest solution, for me atleast, is to 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.


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.


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


You can just use PlanetB: http://planetb.ca/syntax-highlight-word

Copy and Past, choose the language and enjoy the result.


There is a nice Online Tool for that : http://www.planetb.ca/syntax-highlight-word

Just copy the generated code and paste it in 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 answer but I found this one to be the most efficient (quick and really effective).

There is also another onlinz 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


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.


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.


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 ;)


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.


There is a nice Online Tool for that : http://www.planetb.ca/syntax-highlight-word

Just copy the generated code and paste it in 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 answer but I found this one to be the most efficient (quick and really effective).

There is also another onlinz 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


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


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