Adding code blocks to Google Docs can help make technical documents more readable and organized. Here is a step-by-step guide on how to add code blocks in Google Docs using markdown formatting.
Why Add Code Blocks?
Here are some key reasons for adding code blocks in Google Docs:
- Improve readability for technical content
- Organize code snippets cleanly
- Apply syntax highlighting for code
- Display code properly with fixed-width font
- Embed code seamlessly within documents
Using code blocks improves the experience for both the writer and readers of technical documents.
Enable Markdown in Google Docs
To use markdown formatting for code blocks, you first need to enable markdown in Google Docs:
- Open Google Docs and go to Tools > Preferences
- Check the box for Automatically detect markdown
- Click OK to save changes
Now markdown formatting will be enabled in the document.
Insert Code Block
With markdown enabled, you can easily insert code blocks:
- Type three backticks
```
- Hit enter and type the name of the programming language (e.g. python)
- Type three more backticks and hit enter again
It will create a blank code block:
```
Then insert your code between the two sets of backticks. The code will have syntax highlighting and monospace formatting.
Here is an example Python code block:
python
def hello():
print(“Hello World!”)
Use new code blocks for each snippet of code you want to display.
## Additional Code Block Options
Markdown supports a few additional options for customizing your code blocks:
- **Line highlighting**: Add line numbers by adding `{linenos}` after the language
- **Line ranges**: Highlight certain lines by adding `{linenostart-end}` after language
- **Caption**: Add a caption above the code block using `::: {.caption} Caption here`
Here is an example with line numbers, highlighted lines, and a caption:
python {linenos=table, hl_lines=[“2-3”]}
::: {.caption} Prints “Hello World!”
def hello():
print(“Hello World!”) # highlighted
“`
Use these options to draw attention to important parts of a code snippet.
Additional Markdown Formatting
Apply other markdown formatting to enhance readability:
- Headings: Use
#
for H1,##
for H2, etc to divide sections - Lists: Use
-
for bullet points and1.
for numbered lists - Bold: Use
**bold**
to emphasize text - Italics: Use
*italics*
for text emphasis
Break up text with frequent paragraph breaks, bulleted lists, and bold text for scannability.
Conclusion
Adding code blocks using markdown formatting is easy in Google Docs. Just enable markdown, use backticks to define blocks, specify a language, and insert code. Additional options allow customizations for improved readability and organization. Use markdown headings, lists, and text formatting to further enhance technical documents.
The ability to cleanly embed code blocks makes Google Docs much more useful for writing technical tutorials, documentation, notes, and more while collaborating with others.