HomeMicrosoft Word Tutorial

Insert source code in a Word doc (without spelling issues)

1Add source code to a Word document - Step 1

If you type or paste source code directly into your document, you'll face issues like wrong indenting, accidental reformatting, and -most annoyingly- constant reminders about what Word perceives as spelling errors. But you can reference external content in mini documents, ignored by Word's background processing in the main document, ideally suited for source code! This tutorial was written with Word 2016, but the steps are the same in Word 2013 and Word 2010.

2Add source code to a Word document - Step 2

Once in your document, place the cursor (blinking caret) where you'd like to insert your source code. Select the Insert tab in the ribbon. Tip: it is collapsed by default in Office 2016. See how you can pin it to always show the ribbon.

3Add source code to a Word document - Step 3

Click on the "Object" button on the right. You can press the Alt+N, J, J character sequence to trigger that command. When the Object dialog opens, select the "OpenDocument Text" option near the bottom; typing "open" focuses on the first instance. Ensure that "Display as icon" is unchecked, and click OK.

4Add source code to a Word document - Step 4

A new Microsoft Word window will open, called by default "Document in {your file name}". Paste your source code in that document. Word will ignore leading spaces or tabs, but adding it manually before the second or later lines will automatically indent the entire snippet. Perceived misspellings will be highlighted in this document, but will be ignored in your main Word document.

5Add source code to a Word document - Step 5

Some programming editors and IDEs copy source code as text by default. But some offer the option to copy your code with syntax highlighting. JetBrains editors, for example, leverage by default the multi-format capabilities of the Windows clipboard, by passing the copied text string as RTF (rich text format), which translates into pasting code automatically syntax-highlighted in Word!

*Add source code to a Word document - Step 6

Bonus Tips: you can edit external OpenDocument text by double-clicking on them. Close the secondary window to return to your main document. By default, Word inserts a trailing new line after that text. Erase it (you have to do it every time), to avoid showing that extra vertical spacing below your snippets.