Skip to content

Commit

Permalink
add str_insert() to insert a string after the i-th character of anoth…
Browse files Browse the repository at this point in the history
…er string; this should be faster than str_replace() for insert_header_[latex|html]
  • Loading branch information
yihui committed Dec 23, 2022
1 parent 94422a6 commit b1ce0c7
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
6 changes: 2 additions & 4 deletions R/header.R
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,7 @@ insert_header_latex = function(doc, b) {
doc[j] = sub(p, '\n\\\\IfFileExists{upquote.sty}{\\\\usepackage{upquote}}{}\n\\2', doc[j], perl = TRUE)
}
i = i[1L]; l = str_locate(doc[i], b, FALSE)
tmp = substr(doc[i], l[, 1], l[, 2])
doc[i] = str_replace(doc[i], l, paste0(tmp, make_header_latex(doc)))
doc[i] = str_insert(doc[i], l[, 2], make_header_latex(doc))
} else if (parent_mode() && !child_mode()) {
# in parent mode, we fill doc to be a complete document
doc[1L] = one_string(c(
Expand Down Expand Up @@ -87,8 +86,7 @@ insert_header_html = function(doc, b) {
i = grep(b, doc)
if (length(i) == 1L) {
l = str_locate(doc[i], b, FALSE)
tmp = substr(doc[i], l[, 1], l[, 2])
doc[i] = str_replace(doc[i], l, paste0(tmp, '\n', make_header_html()))
doc[i] = str_insert(doc[i], l[, 2], paste0('\n', make_header_html()))
}
doc
}
Expand Down
8 changes: 8 additions & 0 deletions R/utils-string.R
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@ str_replace = function(x, pos, value) {
paste(rbind(y, c(value, '')), collapse = '')
}

# insert a value after i-th character in the string x
str_insert = function(x, i, value) {
if (i <= 0) return(paste0(value, x))
n = nchar(x)
if (n == 0 || i >= n) return(paste0(x, value))
paste0(substr(x, 1, i), value, substr(x, i + 1, n))
}

# a wrapper function to make strwrap() return a character vector of the same
# length as the input vector; each element of the output vector is a string
# formed by concatenating wrapped strings by \n
Expand Down

0 comments on commit b1ce0c7

Please sign in to comment.