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
Microsoft Word is a very useful writing tool, in recent years thanks to the great features it brings. From creating texts, web articles, monographs among other works, that can be used in the area of files and labor documents. So in this article we will explain how to use a Microsoft Word document to insert or copy source code.
On the other hand, Word allows you to insert audio and music files , and other tools that can further enrich the writing of a document. Not only can it be written, it also allows people who work with programming to access its many functions .
Can you insert source codes into a Word document?
If you work as a programmer or software developer, you could use Microsoft Word technical support for your work. However, it must be recognized that in a Word file it will not allow you to create source codes, but you will be able to copy them onto a sheet in Word .
What problems will you have when using source code?
Programmers often write or create software programs using a coded language that includes Java, C ++, HTML in their work. These produce specific instructions that are recognized as source code groups, which are notably not visible to internet users. But this does not mean that it cannot be printed in a Word format to have a visible presentation of your work.
Sure, pasting source code into a Word file can give you a memory error . This also includes a reformatting of the text , and a continuous creation of links, adding to these annoying spelling errors in the copied file.
But do not worry, we will explain in a simple way how you can insert a programming source code into a Word document quickly and safely.
What to do to paste the code in Word?
To avoid the frequent errors that occur when pasting source code, we recommend that you paste the source code into a different document window . Here are the steps you need to carefully follow in order to insert the code into a Word file successfully.
- Have a second document in a file open in Word.
- You will do this by opening a document in Microsoft Word.
- Left click on the “Insert in the ribbon” tab.
Note: To display the developer tab in Word you must activate it so that it is added to the Word ribbon.
- Then you will click on the “Object” option on the right side of the ribbon.
- Click on « Microsoft Word Document «, to ensure that «Show» as icon is not checked.
- Click “OK” so that you can open a new document window with the file name and save it to documents.
- In the document that has the title, that you have put, copy and paste the source code , the errors that it presents will be ignored. As long as the document is inserted as an original and not on another Word document that you have open on your computer.
- In the upper left a window called “File” appears, click on it.
- When you open a list will appear on the left, you will look for the tab that says “Save as”, click on it, so that the changes are saved.
- Once you save successfully, close the document, when you do it, the source code will appear at the top.
- Click to see the HTML source code of the web page , to select it.
- Copy and paste where you want the final document to appear.
- Once done, resume work on the main document.
By following the steps mentioned above, you will be able to copy and paste the source code you want into a Word document . Note that this may work for one code page only and not for copying and pasting multiple codes.
Abdullah Sam
I’m a teacher, researcher and writer. I write about study subjects to improve the learning of college and university students. I write top Quality study notes Mostly, Tech, Games, Education, And Solutions/Tips and Tricks. I am a person who helps students to acquire knowledge, competence or virtue.
Sometimes one might want to insert a code snippet in Word documents. For instance, I have been creating a closure report for one of my project where I need to insert code snippets. If you are a programmer or developer, then you might want to insert source code into documents. This tutorial will explain how to insert source code in MS Word.
You might think what’s the big deal in inserting source code in Word documents. All it needs is to copy source code and paste it into Word isn’t? Yes, I hear it. But try doing it and you will realize why just copy & paste is not the right way of inserting source code in MS Word. The reason is, just copy paste of source code will have many issues – such as loss of text format, syntax highlighting, indentation and Word highlighting syntax errors.
Ok! What about taking a snapshot of the code and inserting it into Word? Of course, you can do that. But you will not be able to edit the code inside the document. So, here’s the right way of inserting source code in MS Word.
How to Insert Source code in MS Word?
Microsoft Word allows to insert source code into documents as an Object. To do that, follow the below steps.
Step 1: Click on INSERT > Object
. Alternatively, you can press ALT + N
and then 'J'
to open Object dialog box.
Step 2: Select "OpenDocument Text"
under "Create New"
tab in Object dialog box.
Step 3: Click "OK"
Step 4: A new document will be opened with the name as "Document in <name of your parent document>"
Step 5: Copy source code from any programming development environment and paste it in the newly opened document (let’s call it as source code document).
Step 6: Save and close source code document. Remember, you are closing only the newly opened document and not the parent document.
Note:
You will notice lots of spelling errors being highlighted in the new document. But never mind, Word will ignore all those once you save and close the document.
Step 7: You will be taken back to your parent document, where you will find the source code being inserted.
That’s it! You can double-click on the inserted object to edit the source code.
How to copy source code from PuTTY and paste it into Word retaining text formats?
Did you copy source code from PuTTY and pasted it into Word document as an object to only see text formats being removed? Well, it means while copying the source code PuTTY should copy it in RTF (Rich Text Format) format. It does not do that by default and here’s how you can enable it.
Step 1: Right-click on PuTTY title bar and select "Change Settings"
Step 2: Click on Window > Selection
and check “Paste to clipboard in RTF as well as plain text"
under heading "Formatting of pasted characters"
Step 3: Click "Apply"
Step 4: Now copy source code from PuTTY and paste it into Word document.
How to copy source code from Notepad++ and paste it into Word?
Step 1: Open your code in Notepad++.
Step 2: Select the code, right-click and select Plugin commands > Copy Text with Syntax Highlighting
.
Step 3: Paste it into Word document and you will see syntax highlighting being retained.
Still source code in Word does not retain format and syntax highlighting?
Then you can take help from this link, which use Google’s Syntax highlighter to format your code and adds language specific syntax highlighting. Now copy the formatted code and paste it in Word.
Advantages of inserting source code as object in Word
- The text format, indentation and language specific syntax highlighting will be retained
- The source code can be edited anytime by double-clicking the inserted object.
- Word will ignore all spelling and grammatical errors within the source code.
Microsoft Word is a very useful writing tool, in recent years thanks to the great features it brings. From creating texts, web articles, monographs among other works, that can serve in files area and labor documents. So in this article we will explain how to use a Microsoft Word document to insert or copy a source code.
On the other hand, Word allows you to insert audio and music files, and other tools that can further enrich the writing of a document. Not only can it be written, it also helps people who work with programming to access its many functions that has.
Can you insert source codes into a Word document?
If you work as a programmer or software developer, you could use Microsoft Word technical support for your work. However, it must be recognized that in a Word file it will not allow you to create source codes, but Yes you will be able to copy them onto a sheet in Word.
What problems will you have when using source code?
Programmers often write or create software programs using a encoded language including Java, C ++, HTML in their jobs. These produce specific instructions that are recognized as source code groups, which are notably not visible to internet users. But this does not mean that it cannot be printed in a Word format to have a visible presentation of your work.
You may also be interested in:
Sure, pasting source code into a Word file can give you a memory error. This also include a reformatting the text, and a continuous creation of links, adding to these, annoying spelling errors in the copied file.
But do not worry, we will explain in a simple way how you can insert a programming source code in a fast and secure Word document.
What to do to paste the code in Word?
To avoid the frequent errors generated by pasting source code, we recommend paste the source code into a window different document. Here are the steps you need to carefully follow in order to insert the code into a Word file successfully.
- Have a second document in a file open in Word.
- You will do this by opening a document in Microsoft Word.
- Left click on the «Insert in the ribbon» tab.
Note: To show the developer tab in Word you must activate it so that it is added to the Word ribbon.
- Then you will click on the «Object» option which is on the right side of the ribbon.
- Click on «Microsoft Word document«, to ensure that» Show «as icon is not checked.
- Click «OK» so that you can open a new document window with the file name and save it to documents.
- In the document that has the title, that you have put, copy and paste the source code, the errors it presents to you will be ignored. As long as the document is inserted as an original and not on another Word document that you have open on your computer.
- In the upper left part a window called «File» appears, click on it.
- When you open a list will appear on the left, you will find the tab that says «Save as», click on it, so that the changes are saved.
- Once you save successfully, close the document, when you do it, the source code will appear at the top.
- Click to see the HTML source code of the web page, to select it.
- Copy and paste where you want the final document to appear.
- Once done, resume work on the main document.
By following the steps mentioned above, you will achieve copy and paste over a Word document the source code you want. It should be noted that this may work only for one code page and not for copying and pasting multiple codes.
Source by
You may also be interested in:
Эти инструкции работают только с одной страницей кода.
Откройте целевой документ в Microsoft Word и поместите курсор туда, где появится исходный код.
Выберите Вставить .
В группе « Текст » выберите « Объект» .
В диалоговом окне « Объект » выберите вкладку « Создать новый ».
В списке Тип объекта выберите Microsoft Word Document .
В Word 2007 выберите текст OpenDocument .
Снимите флажок Отображать как значок .
Выберите ОК .
Откроется новый документ под названием Document in [ имя файла целевого документа ] . Сохраните документ в той же папке, что и целевой документ.
Скопируйте и вставьте исходный код в новый документ. Word автоматически игнорирует пробелы, вкладки и другие проблемы форматирования. Ошибки орфографии и грамматические ошибки выделены в документе, но когда код вставлен в исходный документ, эти ошибки игнорируются.
Сохраните и закройте исходный код документа. Исходный код появляется в основном документе.
Возобновить работу над основным документом.
Если вы изучаете программирование в университете, то вам приходится писать пояснительные записки к курсовым и дипломным работам, оформлять лабораторные работы в которых надо приводить код или фрагменты программ, написанных, например, на 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 • Просмотров [ 30293 ]
In this article, we learn how to copy from Visual Studio Code with color syntax highlighting to various other applications including Word, PowerPoint, Outlook, OneNote, and Gmail to achieve beautiful, clear code samples for documentation, presentations, and general communication. This will prove useful whether you are using JavaScript, JSON, HTML, CSS, TypeScript, Markdown, C++, Java, PHP, Python, Go, T-SQL, XML, C# or a host of other languages and data formats that Visual Studio Code supports.
How is this accomplished? It’s very simple! When you are in VS Code copy your selected code to the clipboard, VS Code brings the color syntax formatting along for the ride so the formatted text can be pasted into applications such as Word and Gmail. We’ll see this in action with various applications and provide some additional steps to maximize the beauty of your syntax highlighted code.
Article contents
Paste into Word
To copy color syntax highlighted code into Word, copy your selected code from VS Code and paste it into Word. If you are using the “Light (Visual Studio)” theme, the result will look something like this:
How awesome is that? Word is bit problematic due the red squiggly lines it provides for spell checking, but we just achieved color syntax highlighting for free with very little effort on our part. If we are using a theme with a darker background, the results will look something like this:
To keep Word from filling the entire width, you can carry out these steps if you are so inclined:
- Insert a 1 x 1 table into Word. (Insert | Table)
- Copy the selected code from VS Code and paste it into this table.
- Right click on the table and choose
Table Properties
. - Select the “Borders and Shading” button.
- Change the
Fill
background to match your VS Code theme. For the “Dark+ (default dark)” theme, for example, the background color is (Red = 30, Green = 30, Blue = 30). - Select the
OK
button.
- Select the
Options
button. - Change the default cell margins to provide more spacing for the code. For example, 0.1″ all around.
- Select the
OK
button and then select the nextOK
button. - Select the text and change the text/font highlight color to “No Color”.
- Drag the right edge of the table to adjust the table width as needed.
The result looks better with a narrower width:
Note
Working with dark background text requires additional steps. If you typically use a dark background theme, but want to use a white background theme for communication, you can quickly swap VS Code themes using `[Ctrl+K Ctrl+T]` and selecting “Light (Visual Studio)”, for example.
Paste into PowerPoint
We want to be able to share our syntax highlighted code in presentations so let’s run through the steps to make this happen in PowerPoint. Here are the steps for syntax highlighted code with white backgrounds:
- Copy the selected code from VS Code and paste it into Word. If we paste it directly into PowerPoint, we unfortunately lose the tab/spaces indentation.
- Copy the text from Word and paste it into PowerPoint.
- Adjust the line spacing to
1.0
since it comes over from Word with a line spacing value that is less than one. - Change the font to “Consolas” or other monospaced font of your choice, and increase the font size as desired.
The result will look something like this:
For dark backgrounds, do the following:
- Create a text box in PowerPoint.
- Fill the text box with a background color that matches the VS Code theme. For the “Dark+ (default dark)” theme, for example, the background color is (Red = 30, Green = 30, Blue = 30).
- Copy the selected code from VS Code and paste it into Word. If we paste it directly to PowerPoint, we lose the tabs/spacing indentation.
- Copy the text from Word and paste it into PowerPoint. When pasting, be sure the paste option is set to “Keep Source Formatting”.
- Adjust the line spacing to one since it comes over from Word with a line spacing value that is less than one.
- Change the font to “Consolas” or other monospaced font of your choice, and increase the font size as desired.
We are ready to make beautiful presentations!
The red squiggly spell-checking lines go away when viewing the PowerPoint presentation in slide show mode.
Paste into Outlook
Using Outlook to share syntax highlighted code can be very helpful, especially in the corporate world. Once again, we’ll first cover pasting code containing a white background. These steps are easy:
- Copy the selected code from VS Code and paste it into the Outlook email message you are composing.
We’re done! The tab/spacing indentation is retained and thus we don’t need to paste it through Word first.
To paste with a dark background, the procedure is a bit more involved (but may be worth it to you for the aesthetics if you’re like me. 😃)
- Insert a 1 x 1 table into Outlook. (Insert | Table)
- Copy the selected code from VS Code and paste it into this table.
- Right click on the table and choose
Table Properties
. - Select the “Borders and Shading” button.
- Change the
Fill
background to match your VS Code theme. For the “Dark+ (default dark)” theme, for example, the background color is (Red = 30, Green = 30, Blue = 30).
- Select the
OK
button. - Select the
Options
button. - Change the default cell margins to provide more spacing for the code. For example, 0.1″ all around.
- Select the
OK
button and then select the nextOK
button. - Select the text and change the text/font highlight color to “No Color”.
The result looks beautiful and the red squiggly spell-checking lines will go away when the email is sent to the recipients.
Paste into OneNote
OneNote is an amazing tool, and I often paste syntax highlighted code there for future reference. Here’s how it’s done for white background themes:
- Copy the selected code from VS Code and paste it into Word. If we paste it directly to OneNote, we will get the syntax highlighting, but we lose the tab/spaces indentation.
- Copy the text from Word and paste it into OneNote.
- Change the font to “Consolas” or other monospaced font of your choice, and change the font size as desired.
For dark background themes:
- Copy the selected code from VS Code and paste it into Word. If we paste it directly to OneNote, we will get the syntax highlighting, but we lose the tab/spaces indentation.
- Copy the text from Word and paste it into OneNote.
- Highlight the text in OneNote.
- Insert a 1 x 1 table. (Insert | Table). This will create a table that surrounds your code.
- Click inside the table and change the shading (fill) color of the table using the
Shading
toolbar option underTable Tools
:
For the “Dark+ (default dark)” theme, the background color is (Red = 30, Green = 30, Blue = 30). - Click
Hide Borders
in the sameTable Tools
toolbar area. - Change the font to “Consolas” or other monospaced font of your choice, and change the font size as desired.
To remove the red squiggly spelling error indicators, install Onetastic and the No Spell Check macro. Highlight the code you pasted, and from the OneNote toolbar, and select Spell Check
| No Spell Check
:
You now have beautiful code snippets in OneNote that are syntax highlighted!
Paste into Gmail
We can paste syntax highlighted code into Gmail as well. For white background themes:
- Copy the selected code from VS Code and paste it into the Gmail message you are composing.
No additional steps required! The tab/spacing indentation is retained and thus we don’t need to paste it first through Word.
For dark background themes, follow the steps above for white backgrounds and declare victory. The only issue with pasting the dark background theme is that the dark background fills the entire width of the email message no matter what width is used:
If you’re a compulsive, nitpicking perfectionist like me 😉, carry out these steps instead for black background themes:
- Open Google Docs and create a 1 x 1 table. (Insert | Table | 1 x 1)
- Click in the table and change the background color of the table to match the background of your dark theme by selecting the background color button from the toolbar. For the “Dark+ (default dark)” theme, the background color is
#1e1e1e
. - Change the table border color to transparent by selecting the
Border color
icon from the toolbar. - Copy the selected code from VS Code and paste it into the Google Docs table.
- Drag the right edge of the table to adjust the width as needed.
- Copy the table from Google Docs and paste it into your Gmail message.
The result is very pleasing, and your email recipients will be impressed as well!
Conclusion
We can produce some beautiful syntax highlighted code snippets in various applications. To create syntax highlighted code samples with white background themes, you simply paste the code right into the target application and you’re done—except for PowerPoint and OneNote which require that you paste through Word first to retain the tab/spaces indentation. For dark background themes, a little more work is involved, but the result is truly a work of excellence.
Additional articles
Build an Amazing Markdown Editor Using Visual Studio Code and Pandoc
Build an Amazing HTML Editor Using Visual Studio Code
Visual Studio Code Jumpstart for Node.js Developers
Right click on Windows folder and open with Visual Studio Code
Follow @thisDaveJ (Dave Johnson) on Twitter to stay up to date with the latest tutorials and tech articles.