Code style in word

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

Word does not natively support syntax highlighting, or other code formatting. As such, it is best to create the highlighting etc in a different program (visual studio, eclipse, notepad++, or this website which can do 14 languages and requires no install).

When pasting the text however, doing it directly in the word document itself can lead to headaches like spelling and grammar underlines.

To fix this, instead of directly copying and pasting, use Insert -> Object -> OpenDocument Text. This will open a new document. Paste the text here, and close the window. Your code will now be shown as an object, complete with all of the formatting that showed in the previous window, but with no spelling or grammar check showing.

While it is possible to format code with styles, there are no built in styles to do this, and it is not really what styles are meant to do. If you with to use styles to format your code, just use this style in all of the objects that you create.

Update: If you want to do this with code styles, here are some ideas.

  • Use a paragraph style with a monospaced font
  • Light background (grey works well)
  • Spelling turned off
  • Make sure the line spacing is the way you want it

If you want to add a little more complexity, you can layer character styles on top of the paragraph style to create something similar to the code preview on stackoverflow with different formatting and/or color for class names, instance names, etc.

Setting up the style like this takes work, but you can get a more customizable result than compared to what you can get using the syntax highlighting from notepad++ or Visual Studio.

As a speedup when formatting code with a style, it may help to first do the syntax highlighting in one of those programs, and then use Word’s Find utility to search for text that matches a color or other font style so that you do not have to manually identify what is a class name for example in the code manually (it is under more->format in the find prompt).

Есть программный код на C++, который необходимо вставить в отчет по работе в Word 2013.

Но если напрямую вставлять его — то получается совершенно не читаемая белиберда.

Хочется оформить так, как код выглядит в компиляторе — с номерами строк, правильным форматированием и подсветкой синтаксиса.

Встроенных средств для этого я не нашел. Подскажите, как это можно сделать?


  • Вопрос задан

    более трёх лет назад

  • 106291 просмотр

Встроенных средств для этого я не нашел

Как так? Создаете свой стиль, там настраивайте шрифт, отступы, табуляцию и тд. Вставляете текст и применяете к нему ваш стиль. Подстветка останется, если в стиле не переопределять цвет шрифта.

С номерами строк придется труднее — надо будет настроить свой стиль нумерации, и в созданном выше стиле абзаца указать, чтобы использовать эту нумерацию.

Например, можно добиться вот таких результатов

d3f872c8ac0f86f21245f705525da54b.png

Скачать док: https://www.dropbox.com/s/8fvq11sw5k0tvky/example….

Пригласить эксперта

tohtml.com/ — онлайн-редактор кода с подсветкой синтаксиса для кучи разных языков. Полученное скопипастить в Word.

Из Microsoft Visual Studi, Qt Creator, Eclipse (да вроде почти из всех IDE), код копируется отформатированный, с подсветкой и т.д.

С номерами строк вам наверное не помогу, но вот подсветка отлично копируется из Qt Creator.

Я для этих целей Notepad++ — у него есть ф-ция копированя RTF в буффер
единственное что не будет номеров строк кажется

Я всегда вставляю preformatted текст в таблицу.
Таблица состоит из одной большой ячейки, если вставляется самодостаточный кусок кода или фрагмент лога, и из нескольких — если нужны заголовки или комментарии.
А по поводу подсветки синтаксиса в копируемом коде коллеги выше уже всё сказали.


  • Показать ещё
    Загружается…

СПСК

Санкт-Петербург

от 80 000 ₽

13 апр. 2023, в 23:50

3000 руб./за проект

13 апр. 2023, в 23:18

1000 руб./за проект

13 апр. 2023, в 22:24

6000 руб./за проект

Минуточку внимания

Если вы изучаете программирование в университете, то вам приходится писать пояснительные записки к курсовым и дипломным работам, оформлять лабораторные работы в которых надо приводить код или фрагменты программ, написанных, например, на 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 • Просмотров [ 30289 ]


Code snippet in Word

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.

Copy in the shortcut menu

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

HTML Format selected in the Paste Special box

When the code appears in your document, you can format the font or the snippet if you like.

Pasted HTML in Word

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

Shaded code block in Word

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

Object on the Insert tab

On the Create New tab, select “OpenDocument Text” as the Object Type. Click “OK.”

OpenDocument Text selected in the Object box

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.

Object inserted in Word

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.

Available windows in the image menu

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.

Inserted image in Word

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.

Screen Clipping tool capturing an image

That image then appears in your document. You can move, resize, or customize the snippet screenshot like any other image in Word.

Screen Clipping inserted 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.

Highlight Selection on the Easy Syntax Highlighter tab

You’ll see your snippet highlighted and your text formatted.

Snippet highlighted with default theme

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.

Language and Theme in the Settings

With your code selected, click “Highlight Selection” in the sidebar.

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.

Snippet highlighted with dark theme

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

Понравилась статья? Поделить с друзьями:
  • Code snippet in word
  • Collection vba excel описание
  • Code select all word
  • Collection of word lists
  • Code of colors in excel