书本中的代码折叠

亚历克斯P:

RMarkdown中用于html文档的Code折叠选项很棒。该选项使程序设计方法对于感兴趣的人透明,而不会强迫观众滚动几英里的代码。带有散文和交互式图形输出的紧紧的代码位置使整个项目对于更广泛的受众来说更易于访问,而且还减少了对其他文档的需求。

对于较大的项目,我正在使用bookdown,效果很好。唯一的问题是没有代码折叠选项。当前在书本中未启用代码折叠。(请参阅在书本中启用代码折叠

我知道我不需要任何选择来实现它。我只需要在正确的位置粘贴正确的代码。但是什么代码在哪里?

一个可行的选择是将代码块放在页面中块的输出下方。或者,最后,将它们作为附录。我可以用html来做到这一点,但不能像rbookdown这样复制。

塞巴斯蒂安·罗切特(SébastienRochette):

整个页面的全局隐藏/显示按钮

要将@Yihui的提示用于折叠html输出中所有代码的按钮,您需要将以下代码粘贴到外部文件中(我header.html在这里将其命名):

编辑:我修改了功能,toggle_R以便按钮显示出来Hide GlobalShow Global单击它。

<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';
  }

  for (i = 0; i < 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>

在此脚本中,您可以直接使用style选项修改与按钮关联的位置和CSS代码,或将其添加到CSS文件中。我必须将设置z-index为较高的值,以确保它出现在其他部门中。
请注意,此javascript代码仅折叠用调用的R代码echo=TRUE,该代码class="r"在html中归因于a 这是由命令定义的var x = document.getElementsByClassName('r');

然后,在rmarkdown脚本的YAML标头中调用此文件,如下例所示:

---
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

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r cars}
summary(cars)
```

新增编辑:每个块的本地隐藏/显示按钮

我终于找到了解决方案!
在查看普通html输出(无bookdown)的代码折叠行为时,我能够将其添加到bookdown中。主要的javascript函数需要查找.sourceCode类分区才能与Bookdown一起使用。但是,这还需要bootstrap的互补javascript函数,但不是全部。gitbook和一起使用html_document2
步骤如下:

  1. js在与Rmd文件相同的目录中创建一个文件夹
  2. 下载javascript函数transition.jscollapse.js例如:https//github.com/twbs/bootstrap/tree/v3.3.7/js并将它们存储在您的js文件夹中
  3. 使用以下代码js文件夹中创建一个新文件codefolding.js这与rmarkdown code_folding选项相同,但pre.sourceCode增加了查找R代码块的功能:

codefolding.js 码:

window.initializeCodeFolding = function(show) {

  // handlers for show-all and hide all
  $("#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 for unique code element ids
  var currentIndex = 1;

  // select all R code blocks
  var rCodeBlocks = $('pre.sourceCode, pre.r, pre.python, pre.bash, pre.sql, pre.cpp, pre.stan');
  rCodeBlocks.each(function() {

    // create a collapsable div to wrap the 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 a 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. 在下面的rmarkdown脚本中,所有三个函数均按标头的形式读取和包含,因此该js文件夹对最终文档本身没有用处。阅读js函数时,show默认情况下,我还向代码块添加了该选项,但您可以选择使用隐藏它们hide

rmarkdown代码:

---
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 a common class name for 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

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r cars}
summary(cars)
```

```{r plot}
plot(cars)
```

该脚本显示了Rstudio浏览器中的按钮,但是效果不佳。但是,Firefox可以这样做。
您会看到css此代码中有一些内容,但是您当然可以使用更多的CSS来修改位置和颜色以及这些按钮上的所需内容。

编辑:结合全局和本地按钮

编辑2017-11-13:全局代码折叠按钮与单独的整体按钮很好地集成在一起。toggle_R最后没有必要使用功能,但是您需要dropdown.js在引导程序中获取功能

调用js文件时,在代码块中直接调用全局按钮

```{r htmlTemp3, echo=FALSE, eval=TRUE}
codejs <- readr::read_lines("/mnt/Data/autoentrepreneur/js/codefolding.js")
collapsejs <- readr::read_lines("/mnt/Data/autoentrepreneur/js/collapse.js")
transitionjs <- readr::read_lines("/mnt/Data/autoentrepreneur/js/transition.js")
dropdownjs <- readr::read_lines("/mnt/Data/autoentrepreneur/js/dropdown.js")

htmlhead <- c(
  paste('
<script>',
paste(transitionjs, collapse = "\n"),
'</script>
<script>',
paste(collapsejs, collapse = "\n"),
'</script>
<script>',
paste(codejs, collapse = "\n"),
'</script>
<script>',
paste(dropdownjs, collapse = "\n"),
'</script>
<style type="text/css">
.code-folding-btn { margin-bottom: 4px; }
.row { display: flex; }
.collapse { display: none; }
.in { display:block }
.pull-right > .dropdown-menu {
    right: 0;
    left: auto;
}
.open > .dropdown-menu {
    display: block;
}
.dropdown-menu {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    display: none;
    float: left;
    min-width: 160px;
    padding: 5px 0;
    margin: 2px 0 0;
    font-size: 14px;
    text-align: left;
    list-style: none;
    background-color: #fff;
    -webkit-background-clip: padding-box;
    background-clip: padding-box;
    border: 1px solid #ccc;
    border: 1px solid rgba(0,0,0,.15);
    border-radius: 4px;
    -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175);
    box-shadow: 0 6px 12px rgba(0,0,0,.175);
}
</style>
<script>
$(document).ready(function () {
  window.initializeCodeFolding("show" === "show");
});
</script>
', sep = "\n"),
  paste0('
<script>
document.write(\'<div class="btn-group pull-right" style="position: absolute; top: 20%; right: 2%; z-index: 200"><button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true" data-_extension-text-contrast=""><span>Code</span> <span class="caret"></span></button><ul class="dropdown-menu" style="min-width: 50px;"><li><a id="rmd-show-all-code" href="#">Show All Code</a></li><li><a id="rmd-hide-all-code" href="#">Hide All Code</a></li></ul></div>\')
</script>
')
)

readr::write_lines(htmlhead, path = "/mnt/Data/autoentrepreneur/header.html")
```

新的全局按钮显示一个下拉菜单,供您在“显示所有代码”或“隐藏所有代码”之间进行选择。window.initializeCodeFolding("show" === "show")默认情况下显示使用所有代码,而使用window.initializeCodeFolding("show" === "hide"),默认情况下隐藏所有代码。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章