#' @rdname hook_plot
#' @export
hook_plot_asciidoc = function(x, options) {
  base = opts_knit$get('base.url') %n% ''
  cap = .img.cap(options)

  width = sprintf("width=%s", options$out.width)
  height = sprintf("height=%s", options$out.height)
  align = sprintf("align=%s", options$fig.align)
  tags = paste(c(cap, width, height, align), collapse = ",")

  sprintf('.%s\nimage::%s[%s]', cap, .upload.url(x), tags)
}

#' @rdname output_hooks
#' @export
render_asciidoc = function() {
  knit_hooks$restore()
  opts_chunk$set(dev = 'png') # default device is png in HTML and markdown
  opts_knit$set(out.format = 'asciidoc')
  hook.source = function(x, options) {
    sprintf('\n[source,%s]\n----\n%s----\n', tolower(options$engine), x)
  }
  hook.message = function(x, options) {
    sprintf('\n[NOTE]\n%s\n', substring(x, comment_length(options$comment)))
  }
  hook.warning = function(x, options) {
    sprintf('\n[WARNING]\n%s\n', gsub('^.*Warning: ', '', x))
  }
  hook.error = function(x, options) {
    sprintf('\n[CAUTION]\n%s\n', gsub('^.*Error: ', '', x))
  }
  hook.output = function(x, options) {
    if (output_asis(x, options)) x else sprintf('\n----\n%s----\n', x)
  }
  knit_hooks$set(
    source = hook.source, output = hook.output, message = hook.message,
    warning = hook.warning, error = hook.error, plot = hook_plot_asciidoc
  )
}

comment_length = function(x) {
  (if (is.null(x) || !nzchar(x) || is.na(x)) 0L else nchar(x)) + 1L
}
