Reputation: 634
Is there a way to insert a nonbreaking space/hyphen when rendering a word document from rmarkdown? In MS Word, these two are special characters a user can insert with a key shortcut or manually. I'm wondering if this operation can be done from rmarkdown code, for example using officer/officedown packages?
Upvotes: 0
Views: 540
Reputation: 125418
You could add a non-breaking space using the UTF-8-symbol \u00a0
and a non-breaking hyphen (hope I got it right) using \u2014
.
library(officer)
doc <- read_docx() |>
body_add_par(value = "Non-breaking\u00a0space") |>
body_add_par(value = "Non-breaking\u2014space")
print(doc, "foo.docx")
The option I used to figure out these codes was to create a docx with the special characters which I scraped using officer::docx_summary()
. Here is a minimal reprex of this approach:
library(officer)
fn <- tempfile(fileext = ".docx")
doc <- read_docx() |>
body_add_par(value = "Hello\u00a0World") |>
body_add_par(value = "Hello\u2014World")
print(doc, fn)
x <- read_docx(fn)
x <- officer::docx_summary(x)
stringi::stri_escape_unicode(x$text)
#> [1] "Hello\\u00a0World" "Hello\\u2014World"
Upvotes: 1
Reputation: 634
I found the answer, thanks to this post How to insert non breaking space in word xml using java
Non-breaking space and non-breaking hyphens have their own unicode encodings. In my rmarkdown code I can use
ABC`r knitr::asis_output("\U00A0")`DEF # sapce
ABC`r knitr::asis_output("\U2011")`DEF # hyphen
Upvotes: 2