javascript - Code folding in bookdown -


the code folding option in rmarkdown html documents awesome. option makes programmatic methodology transparent interested, without forcing audience scroll through miles of code. tight placement of code prose , interactive graphical output makes whole project more accessible wider audience, , furthermore reduces need additional documentation.

for larger project, i'm using bookdown, , works great. problem there no code-folding option. code folding not enabled in bookdown. (see enable code folding in bookdown )

i know don't need option make happen. need paste right code in right place or places. code , where?

a viable alternative put code chunk below chunk's outputs in page. or, finally, put them appendix. html not reproducible rbookdown.

global hide/show button entire page

to use @yihui's hint button fold code in html output, need paste following code in external file (i named header.html here):

edit: modified function toggle_r button shows hide global or show global when clicking on it.

<script type="text/javascript">  // toggle visibility of r source blocks in r markdown output function toggle_r() {   var x = document.getelementsbyclassname('r');   if (x.length == 0) return;   function toggle_vis(o) {     var d = o.style.display;     o.style.display = (d == 'block' || d == '') ? 'none':'block';   }    (i = 0; < x.length; i++) {     var y = x[i];     if (y.tagname.tolowercase() === 'pre') toggle_vis(y);   }      var elem = document.getelementbyid("mybutton1");     if (elem.value === "hide global") elem.value = "show global";     else elem.value = "hide global"; }  document.write('<input onclick="toggle_r();" type="button" value="hide global" id="mybutton1" style="position: absolute; top: 10%; right: 2%; z-index: 200"></input>')  </script> 

in script, able modify position , css code associated button directly style options or add in css file. had set z-index @ high value sure appears on other divisions.
note javascript code fold r code called echo=true, attributed class="r" in html. defined command var x = document.getelementsbyclassname('r');

then, call file in yaml header of rmarkdown script, in example below:

--- title: "toggle r code" author: "statnmap" date: '`r format(sys.time(), "%d %b, %y")`' output:   bookdown::html_document2:     includes:       in_header: header.html   bookdown::gitbook:     includes:       in_header: header.html ---  stackoverflow question <https://stackoverflow.com/questions/45360998/code-folding-in-bookdown>  ```{r setup, include=false} knitr::opts_chunk$set(echo = true) ```  ## r markdown  r markdown document. markdown simple formatting syntax authoring html, pdf, , ms word documents. more details on using r markdown see <http://rmarkdown.rstudio.com>.  when click **knit** button document generated includes both content output of embedded r code chunks within document. can embed r code chunk this:  ```{r cars} summary(cars) ``` 

new edit: local hide/show button each chunk

i found solution !
while looking @ code folding behavior normal html output (no bookdown), able add bookdown. main javascript function needs find .sourcecode class divisions work bookdown. however, requires complementary javascript functions of bootstrap, not all. works gitbook , html_document2.
here steps:

  1. create js folder in same directory rmd file
  2. download javascript functions transition.js , collapse.js here instance: https://github.com/twbs/bootstrap/tree/v3.3.7/js , store them in js folder
  3. create new file in js folder called codefolding.js following code. same rmarkdown code_folding option pre.sourcecode added find r code chunks:

codefolding.js code:

window.initializecodefolding = function(show) {    // handlers show-all , hide   $("#rmd-show-all-code").click(function() {     $('div.r-code-collapse').each(function() {       $(this).collapse('show');     });   });   $("#rmd-hide-all-code").click(function() {     $('div.r-code-collapse').each(function() {       $(this).collapse('hide');     });   });    // index unique code element ids   var currentindex = 1;    // select r code blocks   var rcodeblocks = $('pre.sourcecode, pre.r, pre.python, pre.bash, pre.sql, pre.cpp, pre.stan');   rcodeblocks.each(function() {      // create collapsable div wrap code in     var div = $('<div class="collapse r-code-collapse"></div>');     if (show)       div.addclass('in');     var id = 'rcode-643e0f36' + currentindex++;     div.attr('id', id);     $(this).before(div);     $(this).detach().appendto(div);      // add show code button right above     var showcodetext = $('<span>' + (show ? 'hide' : 'code') + '</span>');     var showcodebutton = $('<button type="button" class="btn btn-default btn-xs code-folding-btn pull-right"></button>');     showcodebutton.append(showcodetext);     showcodebutton         .attr('data-toggle', 'collapse')         .attr('data-target', '#' + id)         .attr('aria-expanded', show)         .attr('aria-controls', id);      var buttonrow = $('<div class="row"></div>');     var buttoncol = $('<div class="col-md-12"></div>');      buttoncol.append(showcodebutton);     buttonrow.append(buttoncol);      div.before(buttonrow);      // update state of button on show/hide     div.on('hidden.bs.collapse', function () {       showcodetext.text('code');     });     div.on('show.bs.collapse', function () {       showcodetext.text('hide');     });   });  } 
  1. in following rmarkdown script, 3 functions read , included in header, js folder in not useful final document itself. when reading js functions, added option show code blocks default, can choose hide them hide.

rmarkdown code:

--- title: "toggle r code" author: "statnmap" date: '`r format(sys.time(), "%d %b, %y")`' output:   bookdown::html_document2:     includes:       in_header: header.html   bookdown::gitbook:     includes:       in_header: header.html ---  stackoverflow question <https://stackoverflow.com/questions/45360998/code-folding-in-bookdown>   ```{r setup, include=false} # add common class name every chunks knitr::opts_chunk$set(   echo = true) ``` ```{r htmltemp3, echo=false, eval=true} codejs <- readr::read_lines("js/codefolding.js") collapsejs <- readr::read_lines("js/collapse.js") transitionjs <- readr::read_lines("js/transition.js")  htmlhead <-    paste(' <script>', paste(transitionjs, collapse = "\n"), '</script> <script>', paste(collapsejs, collapse = "\n"), '</script> <script>', paste(codejs, collapse = "\n"), '</script> <style type="text/css"> .code-folding-btn { margin-bottom: 4px; } .row { display: flex; } .collapse { display: none; } .in { display:block } </style> <script> $(document).ready(function () {   window.initializecodefolding("show" === "show"); }); </script> ', sep = "\n")  readr::write_lines(htmlhead, path = "header.html") ```  ## r markdown  r markdown document. markdown simple formatting syntax authoring html, pdf, , ms word documents. more details on using r markdown see <http://rmarkdown.rstudio.com>.  when click **knit** button document generated includes both content output of embedded r code chunks within document. can embed r code chunk this:  ```{r cars} summary(cars) ```  ```{r plot} plot(cars) ``` 

this script shows buttons in rstudio browser not work well. however, ok firefox.
you'll see there little css in code, of course can modify position , color , whatever want on these buttons more css.

combine global , local buttons

both types of buttons can combined together. need write global function in file in js folder, globalfolding.js.
code in file global function:

function toggle_r() {   var x = document.getelementsbyclassname('r');   if (x.length == 0) return;   function toggle_vis(o) {     var d = o.style.display;     o.style.display = (d == 'block' || d == '') ? 'none':'block';   }    (i = 0; < x.length; i++) {     var y = x[i];     if (y.tagname.tolowercase() === 'pre') toggle_vis(y);   }      var elem = document.getelementbyid("mybutton1");     if (elem.value === "hide global") elem.value = "show global";     else elem.value = "hide global"; }  document.write('<input onclick="toggle_r();" type="button" value="hide global" id="mybutton1" style="position: absolute; top: 10%; right: 2%; z-index: 200"></input>') 

and need add in list of read functions in chunk:

```{r htmltemp3, echo=false, eval=true} globaljs <- readr::read_lines("js/globalfolding.js") codejs <- readr::read_lines("js/codefolding.js") collapsejs <- readr::read_lines("js/collapse.js") transitionjs <- readr::read_lines("js/transition.js")  htmlhead <-    paste(' <script>', paste(globaljs, collapse = "\n"), '</script> <script>', paste(transitionjs, collapse = "\n"), '</script> <script>', paste(collapsejs, collapse = "\n"), '</script> <script>', paste(codejs, collapse = "\n"), '</script> <style type="text/css"> .code-folding-btn { margin-bottom: 4px; } .row { display: flex; } .collapse { display: none; } .in { display:block } </style> <script> $(document).ready(function () {   window.initializecodefolding("show" === "show"); }); </script> ', sep = "\n")  readr::write_lines(htmlhead, path = "header.html") ``` 

the new global function shows button hide global or show global.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

.htaccess - ERR_TOO_MANY_REDIRECTS htaccess -