Skip to content

Instantly share code, notes, and snippets.

@Thell
Created March 21, 2014 15:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Thell/9689152 to your computer and use it in GitHub Desktop.
Save Thell/9689152 to your computer and use it in GitHub Desktop.
---
title: "SO22524822"
author: "Thell"
date: "03/21/2014"
output: html_document
---
```{r setup}
# A killPrefix hook.
default_output_hook <- knitr::knit_hooks$get("output")
knitr::knit_hooks$set( output = function(x, options) {
comment <- knitr::opts_current$get("comment")
if( is.na(comment) ) comment <- ""
can_null <- grepl( paste0( comment, "\\s*\\[\\d?\\]" ),
x, perl = TRUE)
do_null <- isTRUE( knitr::opts_current$get("null_prefix") )
if( can_null && do_null ) {
# By default R print output aligns at the left brace.
align_index <- regexpr( "\\]", x )[1] - 1
# Two cases: start or newline
re <- paste0( "^.{", align_index, "}\\]")
rep <- comment
x <- gsub( re, rep, x )
re <- paste0( "\\\n.{", align_index, "}\\]")
rep <- paste0( "\n", comment )
x <- gsub( re, rep, x )
}
default_output_hook( x, options )
})
knitr::opts_template$set("kill_prefix"=list(comment=NA, null_prefix=TRUE))
```
Normal
```{r}
print( 1:50 )
```
Null prefix
```{r, null_prefix=TRUE}
print( 1:50 )
```
Set option default:
```{r}
knitr::opts_chunk$set(opts.label="kill_prefix")
```
```{r}
print( 1:50 )
```
Ensure we aren't killing strings with [:digit:] patterns.
```{r}
print( paste0( paste0("[", 1:50), "]" ),quote = FALSE)
```
@haakonstorm
Copy link

Any chance of getting this to run in 2018? :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment