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*.
It can be done without taking snapshots of each segment
What to Know
- To embed a second document into a Word document: Insert > Object > Create New > Word Document > clear Display as icon > OK.
- You can also use Paste Special to insert a variety of data into a document, including code.
This article explains issues with using source code in Word for Microsoft 365, Word 2019, Word 2016, Word 2013, Word 2010, and Word 2007 and instructions for embedding a second document in a Word file. It also provides information on pasting other data into a Word document.
The Problem With Using Source Code in Word
Programmers write software programs using languages such as Java, C++, and HTML. Programming languages use different formatting and symbols from regular languages, so pasting a snippet of code into Word from a programming application causes errors such as text reformatting, indentation shifts, link creation, and misspellings.
Given how Microsoft Word structures documents, inserting and working with source code is more difficult than working in a dedicated code editor. However, document embeds create a container that protects source code from being reformatted.
One way to avoid these formatting issues is to paste the source code into a separate document within the main Word document.
Embed a Second Document Into a Word Document
Here’s how to paste source code into a Word document using a second embedded document.
These instructions only work with a single page of code.
-
Open the target document in Microsoft Word and place the cursor where the source code will appear.
-
Select Insert.
-
In the Text group, select Object.
-
In the Object dialog box, select the Create New tab.
-
In the Object type list, Select Microsoft Word Document.
In Word 2007, select OpenDocument Text.
-
Clear the Display as icon check box.
-
Select OK.
-
A new document opens, titled Document in [target document file name]. Save the document in the same folder as the target document.
-
Copy and paste the source code into the new document. Word automatically ignores the spaces, tabs, and other formatting problems. Spelling errors and grammatical errors are highlighted in the document, but these errors are ignored when the code is inserted in the original document.
-
Save and close the source code document. The source code appears in the main document.
-
Resume work on the main document.
Using Different Paste Types in Word
The most up-to-date versions of Word handle code better than they used to. Word for Microsoft 365 supports several forms of pasting, including with and without source formatting. So pasting a block of code from, for example, Microsoft Visual Studio Code will look different based on the paste type. If you select Paste Special, each of the three options yields a different result:
- Unformatted Text: All code is pasted as unformatted, so you’ll lose indenting, color, typeface, and related contextual clues.
- HTML Format: From VSC, a paste-as-HTML renders what appears to be a photo of the code, complete with the text editor’s background color. This code block is editable, and you can remove the background color in the Paragraph Fill menu option.
- Unformatted Unicode Text: Pastes the text as is but strips the text and background colors. Re-format the code as needed.
FAQ
-
How do I see formatting marks and codes in Word?
To see formatting marks and codes in Word temporarily, go to Home and select the Show/Hide icon to toggle marks on and off. To keep them on permanently, go to File > Options > Display > Show all formatting marks > OK.
-
How do I add links in Word documents?
To add a link in a Word document, highlight the text you want to hyperlink, right-click it, and select Link. Alternatively, select Insert > Links > Link and enter the URL.
-
How do I convert a Word document to HTML?
To convert a Word document to HTML, go to File > Save As. Under Save as Type, choose .html. You can also use an editor like Dreamweaver.
Thanks for letting us know!
Get the Latest Tech News Delivered Every Day
Subscribe
If you’re creating an article, instructional piece, or essay in Microsoft Word, you may need to include a snippet of code. Whether HTML, JavaScript, or Python, you likely want it to appear different than the document text.
There are a few ways to insert command or code blocks in your Word document. Depending on if you want the reader to simply view the code or have the ability to copy it, let’s walk through the options.
Option 1: Paste Special as HTML
One of the quickest ways to add code to your document is with the Paste Special option for HTML. This inserts the code you’ve copied without the other formatting of your document. And, this option allows your reader to copy the code or command straight from your document.
RELATED: How to Paste Text Without Formatting Almost Anywhere
Select the code or command from your application and copy it using the toolbar, the context menu, or the keyboard shortcut Ctrl+C on Windows or Command+C on Mac.
Place your cursor in your Word document where you want to paste it. Then go to the Home tab, click the Paste drop-down arrow, and choose Paste Special. Select “HTML Format” and click “OK.”
When the code appears in your document, you can format the font or the snippet if you like.
Use the Home tab to color specific pieces of code with the Font section of the ribbon. To add a border or shade, select the Borders drop-down arrow in the Paragraph section and pick “Borders and Shading.”
Option 2: Insert an Object
If you want to insert the code or command in your document only for the reader to see and not copy or edit, you can insert an object containing the snippet.
RELATED: How to Insert a Picture or Other Object in Microsoft Office
Go to the Insert tab, click the Object drop-down arrow, and pick “Object.”
On the Create New tab, select “OpenDocument Text” as the Object Type. Click “OK.”
A new Word document will open for you to insert your code or command. You can use the Paste Special HTML format described earlier if you like. After you add the snippet, close the document.
Your code then appears in your original Word document as an object. You can then move it, resize it, or add a border if you wish.
Option 3: Attach a Screenshot
Another option for adding your snippet as an item instead of text is using an image. If you have your code or command in an active application window like Notepad++ or Command Prompt, you can easily add it to your document. The drawbacks here are that the reader can’t easily copy your code if they need to and that resizing may negatively affect readability.
Go to the Insert tab and click the Screenshot drop-down arrow. You should see the application window as an option.
Select it and it’ll pop into your document as an image. You can then crop the image to remove the surrounding application window if you like.
Alternatively, you can use the Screen Clipping option in the Screenshot drop-down. When you select this tool, your cursor changes to a crosshair. Use it to drag the area of your screen or other application window you want to capture and release.
That image then appears in your document. You can move, resize, or customize the snippet screenshot like any other image in Word.
Option 4: Use a Syntax Highlighter
One more option is to use a syntax highlighter like Easy Syntax Highlighter. This is a free add-in for Microsoft Word that highlights your code for you including a background and colors for pieces of the code. Plus, you can customize the language and appearance.
RELATED: How to Install and Use Add-ins for Microsoft Office
After you install the add-in, place the code or command in your document. You can type or paste it, whichever you prefer.
Select the code and go to the Easy Syntax Highlighter tab that now displays. To apply the default formatting with the language automatically detected, select “Highlight Selection” in the ribbon.
You’ll see your snippet highlighted and your text formatted.
If you want to select a specific language or formatting, select “Settings” in the ribbon instead. When the sidebar opens, choose a Language and Theme.
With your code selected, click “Highlight Selection” in the sidebar.
You’ll then see your snippet formatted per the settings you picked. This keeps your code or command as text so your reader can copy it, but makes it stand out as its own block.
There’s more than one way to add a code or command block to your Word document. Depending on the purpose for your reader, choose the option that’s best for you!
READ NEXT
- › BLUETTI Slashed Hundreds off Its Best Power Stations for Easter Sale
- › How to Adjust and Change Discord Fonts
- › Google Chrome Is Getting Faster
- › Expand Your Tech Career Skills With Courses From Udemy
- › The New NVIDIA GeForce RTX 4070 Is Like an RTX 3080 for $599
- › Mozilla Wants Your Feature Suggestions for Thunderbird
Finding a way to decently show our source code on the web recently became a rather trivial task thanks to many JavaScript + CSS based libraries such as highlightjs, PrismJS, Prettify, SyntaxHighlighter & more. It’s not so easy to achieve the same results inside a text-editing software such as MS Word, to the point that I’ve seen more than few devs adopting the awful & dreadful screenshot method, which consist in blindly capture a portion of their developer framework GUI and then embedding it as an image inside the Word document.
Should we do that? Of course no! There is at least one better way to do that, which also is far less intrusive (and size-intensive) and also gives us the chance to modify/review our code snippet after it has been pasted. Let’s see how we can do it.
- Open MS Word and place the cursor where you want to paste the snippet.
- Go to the Insert tab, from there click to the Object… button close to the right-end of the toolbar. A popup will show up: select OpenDocument Text.
- A new «embedded» document will appear: go to your favourite Developer Framework, such as Visual Studio, Eclipse, Android Studio, Notepad++ or the one doing the highlight the way you want it to be. Copy the code from there and paste it to the new document.
- Save and close the new document.
Your efforts will be rewarded with something like that:
This solution, other than being visually nice, grants you the following benefits:
- the source code will be entirely editable.
- all the layout, coloring, spaces, tabs, linefeeds from the developer framework will be kept.
- the code will be treated like a separated, embedded element, just like images and charts, so you’ll be able to move, resize, shape, applying borders, shadows, background color and basically anything else you want to and/or Word allows.
- the code won’t be affected by grammar checker, meaning that spelling errors won’t be highlighted in the code: no red underlining, yay!
- it takes only few seconds to do it — you’ll love that if you need to insert multiple snippets.
- It works on all Word builds since 2007: Word 2007, Word 2010, Word 2013 and newer versions.
If you find an even better way, please let me know.
Meanwhile… Happy coding!
IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it’s also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies. Microsoft MVP for Development Technologies since 2018.
View all posts by Ryan →
Если вы изучаете программирование в университете, то вам приходится писать пояснительные записки к курсовым и дипломным работам, оформлять лабораторные работы в которых надо приводить код или фрагменты программ, написанных, например, на Python, C++, Pascal, Javascript и так далее. Прочитав эту публикацию, вы научитесь делать это красиво и правильно. Например, так как показано на скрине ниже, если вы используете в своей работе Ворд:
officerelease.com/word/ для подготовки текстов.
Согласитесь, выглядит такой код в тексте очень солидно. Вы можете сами убедиться в этом, скачав файл с примером, скрин которого здесь приведен. Ну а теперь расскажем как повторить такой же код быстро и без проблем. Научившись делать это один раз, вы будете использовать этот прием постоянно.
Алгоритм добавления кода с подсветкой в Word
- Получите подсветку нужного вам кода кода в любом онлайн сервисе, который генерирует css стиль подсветки и код html-страницы. Это можно сделать здесь.
- В любом текстовом редакторе, например в Notepad+, создайте простейший html-файл, добавив в него код, полученный в предыдущем пункте.
- Сохраните этот файл в кодировке utf-8 с расширением html.
- Перейдите в ваш редактор Word и в нужное место вставьте сохраненный html-файл.
- Если надо, отредактируйте формат вставленного кода.
Важное замечание. Надо понимать, что стили html-файла Word обрабатывает своеобразно, игнорируя некоторые стили. И самое важно — когда ваш файл будет добавлен в редактор, то html-список строк кода превратится в список, оформленный по правилам Word. Выделите полученный код и выберите в стилях (Формат-Списки). Настройте список как вам надо. Рекомендуем убирать нумерацию строк списка, как в нашем примере, хотя вы можете и сохранить авто-нумерацию или изменить ее стиль.
Если у вас до сих пор по какой-то причине не установлен Microsoft Office для Windows, то вам сюда: https://officerelease.com/ и ваши курсовые с программным кодом с учетом наших рекомендаций будут выглядеть отлично, а ваш преподаватель будет спрашивать вас, как вы сумели так красиво вставить код с подсветкой в вашу работу.
Похожие публикации
2019-10-04 • Просмотров [ 30297 ]