R/insert_aux_file_dir.R

insert.aux.file.dir <- function(){
    if(!dir.exists("aux_files")){
        dir.create("aux_files/")
    }
    ctx = rstudioapi::getSourceEditorContext()
    if (ctx$path == '') stop(
    'Please select the blog post source file before using this addin', call. = FALSE
    )
    ctx_ext = tolower(xfun::file_ext(ctx$path))
    
    path = normalizePath(ctx$path)
    
    path <- paste0("aux_files/",xfun::sans_ext(basename(path)))
    if(!dir.exists(path)){
        dir.create(path)
    }
    rstudioapi::insertText(paste0("../../", path), id = ctx$id)
    
    txt = ctx$contents
    res = blogdown:::split_yaml_body(txt); yml = res$yaml_list; rng = res$yaml_range
    if (length(yml) == 0) return(
    warning("The current document does not seem to contain YAML metadata", call. = FALSE)
    )
    if (!"aux_files_dir" %in% names(yml)){
        rstudioapi::setSelectionRanges(list(c(rng[1] + 1, 1, rng[2], 1)))
        slct = rstudioapi::getSourceEditorContext()$selection[[1]]
        yml$aux_files_dir <- path
        seq_keys = Filter(function(key) {
            identical(attr(yml[[key]], 'yml_type'), 'seq')
        }, names(yml))
        seq_keys = unique(c(seq_keys, 'categories', 'tags'))
        
        
        for (i in seq_keys) yml[[i]] = if (length(yml[[i]]) > 0) as.list(yml[[i]])
        if (!getOption('blogdown.yaml.empty', TRUE)) yml = blogdown:::filter_list(yml)
        rstudioapi::modifyRange(
        slct$range, blogdown:::as.yaml(yml, .trim_ws = FALSE)
        )
    }
    
    
}
beeflavor/useful-blogdown-addins documentation built on May 31, 2019, 5:11 p.m.