|
| 1 | +library(rstudioapi) |
| 2 | + |
| 3 | +toc <- function() { |
| 4 | + ac <- getActiveDocumentContext() |
| 5 | + content <- ac$contents |
| 6 | + |
| 7 | + is_title <- substr(content, 1, 1) == "#" & substr(content, 2, 2) != "|" |
| 8 | + |
| 9 | + title <- content[is_title] |
| 10 | + |
| 11 | + toc_start <- "<!-- toc: start -->" |
| 12 | + toc_end <- "<!-- toc: end -->" |
| 13 | + |
| 14 | + toc <- NULL |
| 15 | + for(i in seq_along(title)) { |
| 16 | + current_title <- title[i] |
| 17 | + if(substr(current_title, 1, 4) == "### ") { |
| 18 | + new_title <- substr(current_title, 5, nchar(current_title)) |
| 19 | + spacing <- " - " |
| 20 | + } |
| 21 | + if(substr(current_title, 1, 3) == "## ") { |
| 22 | + new_title <- substr(current_title, 4, nchar(current_title)) |
| 23 | + spacing <- "- " |
| 24 | + } |
| 25 | + if(grepl("\\{", new_title)) { |
| 26 | + split_title <- unlist(strsplit(new_title, " ")) |
| 27 | + new_title <- paste0(split_title[1:(length(split_title) - 1)], collapse = " ") |
| 28 | + } |
| 29 | + new_link <- tolower(new_title) |
| 30 | + new_link <- gsub(" ", "-", new_link) |
| 31 | + ret <- paste0(spacing, "[", new_title, "](#", new_link, ")") |
| 32 | + toc <- c(toc, ret) |
| 33 | + } |
| 34 | + |
| 35 | + toc <- paste0(toc_start, "\n", |
| 36 | + paste0(toc, collapse = "\n"), |
| 37 | + "\n\n", toc_end) |
| 38 | + |
| 39 | + pos_start <- as.document_position(c(which(content == toc_start), 1)) |
| 40 | + pos_end <- as.document_position(c(which(content == toc_end), nchar(toc_end) + 1)) |
| 41 | + |
| 42 | + pos_range <- document_range(pos_start, pos_end) |
| 43 | + |
| 44 | + modifyRange(pos_range, toc) |
| 45 | + |
| 46 | +} |
0 commit comments