7  nvim + Quarto Tips and Snippets

This chapter is for people who analyse data with qmd files in nvim (LazyVim). It introduces the key bindings and snippets that help with the work in this project. It assumes LazyVim with quarto-nvim, molten-nvim and blink.cmp, plus a custom set of analysis helpers (lua/analysis/).

NoteKey notation
  • \ is the localleader (on this page, \r means “press \, then r”)
  • <leader> is Space
  • When in doubt, \? shows a cheat sheet of the keys available in the current file (select one and press Enter to run it)

7.1 A day in this project (nvim edition)

  1. Open the project with nvim. <leader>e shows the file tree
  2. Open a notebook in analysis/ and start the R kernel (ir) with \mi
  3. Try things while running chunks one by one with \r. Show plots in the browser with \hh (httpgd)
  4. Once decided, move it to a function in scripts/ (Chapter 2)
  5. tar_make() with \tm
  6. Open a section file and write. Preview just that section with \qi
  7. Preview the whole paper from main.qmd with \qp; for submission, \qr (or quarto render ... --to docx)

7.2 Running code (molten)

Key Action
\mi Choose and start a kernel (ir for R, python3 for Python)
\r Run the chunk under the cursor (or the selection in visual mode)
\x Run the chunk and move to the next one
\ra Run everything from the top down to the chunk under the cursor
\rA Run the whole file
\ml Run a single line
\mo Jump into the output window (to scroll through long output)
\md Delete a cell’s output
]x / [x Move to the next / previous chunk
\/ Comment out / uncomment a whole chunk
\o Jump via the outline (headings and chunks)
\hh / \hu / \hc Start httpgd (R plots in the browser) / show its URL / stop it
TipThe same keys work in .R / .py files

In .R and .py files in scripts/, a region delimited by # %% is treated as one cell. You can run it with \r or \x just like in qmd, so you can test functions as you write them.

7.3 Looking at data

Use these with a kernel running and the data loaded.

Key Action
\n (Alt+c in insert mode) Column picker. Select column names (Tab for several) and insert them at the cursor
\vv Variable list. Enter inserts the name; Ctrl+v shows it as a table
\dv Show the data frame under the cursor as a table (in the browser, :8766)
\dh Show a gt / gtsummary table as it looks in HTML
\ps / \pt / \ph Peek at the summary / frequency table / histogram of the variable under the cursor
\yt Copy the table under the cursor as TSV (pastes straight into Excel)
\yw Export the table under the cursor to Word (docx)

A handy use of the column picker: type glm(sarcopenia ~, press Alt+c and choose the variables. No more misspelled column names.

7.4 Inserting code

Key Action
\ir / \ip Insert an R / Python chunk
\if Pick a data file → insert code to read it (csv, xlsx, parquet, rds, etc.)
\iv Paste a range copied from Excel and turn it into code that builds a data frame
\it Type-conversion code (choose columns with the column picker)
\in A template for renaming columns
\aw Analysis recipes. Choose group comparison, regression, survival analysis, etc., pick columns, and complete code is inserted
\ix (Alt+r in insert mode) Insert a cross-reference @fig-xxx / @tbl-xxx from the list of labels

7.5 targets

Key Action
\tm tar_make() (output shown in a floating window)
\to tar_outdated() (targets that need recomputing)
\tl tar_load() the target name under the cursor
:AnalysisTargetsInit Create a _targets.R template

\tm runs inside the R kernel, so start ir with \mi first.

7.6 Quarto preview and render

Key Action
\qp Preview the current file (http://localhost:4200, auto-refreshes on every save)
\qi Preview just the section file (shown with main.qmd’s YAML and setup). Pressed on an include line, it opens that section file
\qI Preview from the top through this section
\qs / \qS Preview only the ## (###) section under the cursor / the whole ## section
\qq Stop the preview
\qr Render to all formats listed in the YAML (html and docx, etc.)
\qx Render to PowerPoint (pptx)
\qe Jump to the line where a render error occurred
\qpc / \qrc Preview / render with caching enabled

7.6.1 How section-only preview (\qi) works

When you press \qi in a section file (e.g. sections/_04_results.qmd), it:

  1. Finds the main.qmd that includes this section
  2. Takes the part of main.qmd before the first include (the YAML and the setup chunk)
  3. Creates a temporary file (part-preview-_04_results.qmd) with only this section’s include line appended
  4. Previews it (the temporary file is deleted when you stop)

In this project the setup chunk of main.qmd only reads num <- tar_read(numbers), so even a section-only preview appears in a few seconds with all the numbers filled in.

7.6.2 Adding section files

:QNew name creates name.qmd in the same folder as main.qmd and appends {{< include name.qmd >}} to the end of main.qmd. That is handy when the parts sit next to main.qmd (e.g. analysis/ notebooks).

In this project, the manuscript keeps its sections in sections/ with _-prefixed names, and the includes are placed where you want them, e.g. before or after References, so add sections by hand:

  1. Copy an existing section file to create sections/_08_supplementary.qmd
  2. Write {{< include sections/_08_supplementary.qmd >}} at the desired position in main.qmd
  3. Press \qi on the include line to open that file

7.7 Writing citations

Typing [@ in a qmd offers references from references.bib as completion candidates.

  • You can filter by author name or year ([@chen → Chen’s papers)
  • The bib is searched in this order: bibliography: in the qmd’s YAML → _quarto.yml in parent folders → *.bib in the same folder and the project root
  • It reloads automatically when the bib file is updated (works well with Paperpile’s automatic export)

7.8 Snippets

Snippets can be used in two ways:

  1. Completion: in insert mode, type a short name (rc, fig, etc.), pick it from the candidates and press Enter
  2. Keys: in qmd files, \s + one character inserts directly (e.g. \so for a callout). \ss lets you choose from a list. Used after a visual selection, it wraps the selected text (e.g. select a paragraph and press \so → it ends up inside a callout)

7.8.1 Chunks, figures and tables (quarto.json)

Name Inserts
rc / pc An R / Python chunk
fig A figure chunk (with label: fig-xxx, fig-cap, width and height; referable as @fig-xxx)
tbl A table chunk (with label: tbl-xxx and tbl-cap)
fold A chunk whose code is shown folded
cache An R chunk with caching
asis Output a Python table as a markdown table
tabs (\st) Tabs (panel-tabset)
callout (\so) A callout box (choose note / tip / warning / important / caution)
cols Two columns (R chunk on the left, explanation on the right)
todo <!-- TODO: --> (a note that is not shown when rendered)

7.8.2 For manuscripts (quarto-extra.json / quarto-layout.json)

Name / key Inserts
inc {{< include xxx.qmd >}}
pb (\sb) A page break {{< pagebreak >}}
cite (\s@) A citation [@key]
fn (\sn) A footnote
eq (\se) A numbered equation block
img (\sf) / imgs (\sF) An image (caption + cross-reference) / images side by side (subfigures)
mdtbl (\sT) A Markdown table (caption + cross-reference)
onlyfmt (\sv) Format-specific content (e.g. shown only in docx)
mark (\sh) / color (\sk) / ul (\su) Highlight / text colour / underline
xrefja YAML that labels figures and tables in Japanese (図1, 表1)
sinfo sessionInfo() at the end (a record of the environment)
ydocx / yhtml / ybib YAML settings for docx / html / references

7.8.3 For slides (quarto-layout.json)

Name / key Inserts
slide (\s-) A new slide
incr (\si) Bullets revealed one by one
pause (\sp) Show the next part on click
notes (\sN) Speaker notes
col2 (\sc) / col3 (\s3) Two / three columns
yreveal / ypptx YAML for revealjs / pptx

7.8.4 R analysis (r-analysis.json)

Name Inserts
tbby A group-comparison table tbl_summary(by = ...) (median IQR + p-values)
uvreg One-variable-at-a-time logistic regression tbl_uvregression()
tbmerge Unadjusted / adjusted tables side by side with tbl_merge()
forest A forest plot from a gtsummary regression table
roc ROC curve and AUC (95% CI)
lrt Likelihood ratio test (comparing nested models)
zscale Standardization (OR per 1 SD)
labels Set variable labels in bulk (used as display names by gtsummary)
todocx Export a table to Word (gtsummary → flextable → docx)
thpub A ggplot theme for publication
ggsave / rds Save a figure / save and load an object
tarl targets::tar_load()

7.8.5 Python analysis (python-analysis.json)

Name Inserts
rpq Read a parquet file and check types and missingness
smlogit statsmodels logistic regression and an OR table
smols statsmodels linear regression

7.9 Useful Quarto techniques

7.9.1 Inline R code

Of the `r num$n_all` participants, ...

You can embed computed results in the prose. In this project, write only num$xxx and leave the computation to numbers.R.

7.9.2 Cross-referencing figures and tables

```{r}
#| label: fig-grip
#| fig-cap: "Handgrip strength according to sarcopenia status"
ggplot(...)
```

Handgrip strength was lower in participants with sarcopenia (@fig-grip).

If a label starts with fig- or tbl-, @fig-grip produces a numbered reference such as “Figure 1”. Reorder figures and the numbers are reassigned automatically.

NoteWhy the submission manuscript doesn’t use cross-references

JCSM requires figures and tables in files separate from the text, so this project’s manuscript places no figures or tables in the text and writes “Figure 1” directly. Cross-references are handy in analysis/ and reports/ notebooks.

7.9.3 Format-specific content

::: {.content-visible when-format="docx"}
This sentence appears only in Word
:::

7.9.4 Faster previews (embed-resources)

embed-resources: true (embedding images and CSS into one HTML file) is convenient for distribution but slows down previews. This project keeps it in a separate profile, _quarto-embed.yml, which is enabled only when rendering with \qr. Don’t put it in _quarto.yml or in a qmd’s YAML (if you do, previews get slow too).

7.9.5 The project’s base folder

With execute-dir: project in _quarto.yml, the working directory is the project root no matter which qmd you run. It matches here::here() (R) and ROOT in scripts.common.utils (Python), so paths are written the same way in analysis/ notebooks and in manuscript/ files.

7.10 Summary

  • Run code with \mi → \r / \x; look at data with \n / \dv / \ps
  • targets: \tm / \to / \tl
  • Section-only preview with \qi, the whole paper with \qp, render with \qr
  • Citations complete after [@; snippets by short name or \s + one character, with the list at \ss
  • When in doubt, \?