What is the difference between knitHTML and rmarkdown render? - knitr

I am using RStudio version 0.98.501, R version 3.0.2 on Windows 7. I have following code written in a .Rmd file:
---
title: "Sample Document"
output:
html_document:
toc: true
theme: united
---
Title
========================================================
This is an R Markdown document. Markdown is a simple formatting syntax for authoring web pages (click the **Help** toolbar button for more details on using R Markdown).
When you click the **Knit HTML** button a web page 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}
summary(cars)
```
You can also embed plots, for example:
```{r fig.width=7, fig.height=6}
plot(cars)
```
Literature Review
==================
this is sample text
Hello
------
World!
### Subsection
this is subsection
When I click knitHtml button the created html file DOES NOT contain the table of contents. However when I use following code, it creates the table of contents and change the theme to united:
rmarkdown::render('C:/Users/durraniu/Documents/Trajectory1/knitHtml/test.Rmd')
What is the difference and how can I make knitHtml button work the way the code does?

RStudio version 0.98.501 does not support the rmarkdown package. You have to check out the latest preview version (at this moment, v0.98.894).

Related

Get rid of file name and date in VScode markdown

I am very new to markdown. I use VScode editor with Markdown All in One and Markdown PDF extensions.
Let's say I open test.md file and write the following text
### This is my first markdown text
Hello
When I export the text into pdf, using Ctrl+Shift+P - markdown-pdf: Export (pdf), I get the following output:
The question is, how do I get rid of the name and the date in the upper part of the page?
Please refer to Markdown-Pdf's README doc,in the chapter Options,disable the markdown-pdf.displayHeaderFoote may solve your problem.

How to create a nested list in Eclipse WikiText using Markdown format

I am using the WikiText plugin in Eclipse to write Markdown documentation of my current project.
Unfortunately, despite the Help pages stating that the Markdown implementation complies with CommonMark, I can't seem to create nested lists such as:
Handles
Alfa
Bravo
Charlie
Equipment
Alfa: AWP
Bravo: BAR
Charlie: M24 SWS
The same text and "formatting", ie 4 spaces before nested list items gives me, in the Preview, something like
- Handles - Alfa - Bravo - Charlie
- Equipment - Alfa: AWP - Bravo: BAR - Charlie: M24 SWS
But 4 spaces before nested items is reported by CommonMark as correct (meaning that it gives me what I want, ie a sublist).
I have tried adding a blank line before - Alfa but it turns the list items into code.
I've tried the WikiText > Generate Markdown command in the context menu and the generated file has two differences:
- The marker for first-level is turned from my given hyphen into an asterisk.
- The second-level items are prepended with eight whitespace characters.
Still, the Preview shows exactly what I've reported above: nested list items are on the same line as their parent.
How do I create nested lists using that plugin? Or does it not support nested lists?
EDIT: after Jmini's answer, here is a screen capture of what I get. I'm using version 2.7.0.v20151009-1723 on Mars.2. Also, I don't have line numbers although the preference is enabled for all editors.
EDIT #2: A search on Eclipse Bugzilla revealed this bug which seems relevant. Given the difference in version numbers in Jmini's answer, I've updated Mylyn WikiText plugin to the latest weekly build and lo and behold, I now have correctly rendered nested lists in the Preview tab of the WikiText Markdown editor. Conclusion: it was a bug. The thing I can't fathom though is how a release which happened 7 months after the bug has been fixed didn't contain the fix.
I am not sure to understand your problem.
I have tried this source:
- Lorem
- first
- second
- Ipsum
- first
- second
- Dolor
Here a screenshot:
The HTML output I got with WikiText (Version 2.8.0v20160121-2126, Eclipse Neon):
<body>
<ul>
<li>Lorem</li>
<ul>
<li>first</li>
<li>second</li>
</ul>
<li>Ipsum</li>
<ul>
<li>first</li>
<li>second</li>
</ul>
<li>Dolor</li>
</ul>
</body>

How to generate pdf from lyx files containing knitr chunks when knitr is deactivated ?

I would like a co-author to edit a lyx file I created. He doesn't have knitr installed and he is going to edit only text and equations parts of the document where knitr generated content is not present. I would still like him to be able to generate the pdf file from lyx though. Under Documents / settings / modules, I can delete the Rnw (knitr) module. But then there are errors appearing.
I posted a sample lyx file under knitr_iris.lyx.
When the knitr module is activated, Pdf generation works fine, but when you deselect the knitr module under Documents / settings / modules, the following errors pop up:
! You can't use `macro parameter character #' in horizontal mode.
! Missing $ inserted.
These are due to the use of $ and # in R. How to tell Lyx that knitr chunks are not latex code but something else that it should ignore?
You can do what you want to do by using LyX branches. First, highlight an ERT or knitr chunk (there are two ways to insert knitr in LyX) and go to Insert > Branch > Insert New Branch. Call the branch as you like, for example "knitrChunks". Now highlight the rest of the ERT or knitr chunks and go to Insert > Branch > knitrChunks (this branch exists now that you created it). When you see an "X" in front of the branch, that means it's deactivated. So when your co-author edits and wants to compile, he/she can just right-click on the branch inset and go to "deactivate branch" and remove the module. To reverse that, you can right click and go to "activate branch" and add the module back.

How to make a figure caption in Rmarkdown?

I am thinking about writing my thesis with rmarkdown and latex. I'm getting the hang of how it all works, however, when I try to add a figure (not an R plot) to the text and render it to pdf, the caption and in-text reference dissappear.
This is the code snippet I use to add a figure:
---
title: "Untitled"
output: pdf_document
---
see figure \ref{fig1}.
![picture \label{fig1}](figure1.png)
This is what knitr creates:
This is what pandoc creates:
Question:
How do I make figure captions and in-text references to those figures in Rmarkdown that will display when rendered to pdf?
OR
How do I tell pandoc what Rmarkdown is so it will render R code and plots?
Please see the documentation of R Markdown for PDF output, and in particular, look for fig_caption. Figure captions are turned off by default in R Markdown, and you have to turn them on (fig_caption: true). You can also find this setting from the gear button on the toolbar of RStudio IDE.
Update: please check https://github.com/yihui/knitr/issues/1063.
Question: How do I make figure captions and in-text references to those figures in Rmarkdown that will display when rendered to pdf?
To get the cross-reference in the PDF produce by LaTeX you need to run LaTeX more than once. Some LaTeX IDE does it for you.
knitr is only running LaTeX once and that is the reason that you only get ??. To confirm that this was the problem I ran
library(knitr)
knitr()
in R that returned
see figure \ref{fig1}.
\begin{figure}[htbp]
\centering
\includegraphics{imagem.jpg}
\caption{picture \label{fig1}}
\end{figure}
which is a valid LaTeX code.
How do I tell pandoc what Rmarkdown is so it will render R code and plots?
Pandoc only understand Markdown (not RMarkdown). First you have to call knitr to generate the Markdown from the RMarkdown and after it call Pandoc to convert the Markdown to LaTeX.
I just found a very useful solution here.
First, include the following chunk:
```{r functions, include=FALSE}
# A function for captioning and referencing images
fig <- local({
i <- 0
ref <- list()
list(
cap=function(refName, text) {
i <<- i + 1
ref[[refName]] <<- i
paste("Figure ", i, ": ", text, sep="")
},
ref=function(refName) {
ref[[refName]]
})
})
```
After, we can add the caption of the figure/table in the figure chunk options like:
```{r, fig.cap=paste("Your caption.")}
See that fig.cap works better with paste.
In Rmarkdown
for markdown figures
![caption \label{labelx}](link_to_figure, or path of figure){figure dimensions}
# how to cite markdown figure
\ref{labelx}
for latex figures
Add following in the figure environment of latex which starts with
\begin{figure}
includegraphics[]{/path to figure}
\label{label}
\end{figure}
# how to cite latex
\ref{label}
for bookdown
add chunk names as label names like
{r label2,echo=F}
# to cite by using bookdown use
\#ref(fig:label2)
similarly for tab we cite table as \#ref(tab:table_label)
For captioner package
add a chunk at the top of rmarkdown document
tab_cap <- captioner(prefix = "table")
fig_cap <- captioner(prefix = "figure")
where prefix is the prefix for cross referencing a figure.
add this in chunk options
{r fig_cap("labelforcaptioner","caption for captioner figure"}
note that fig_cap is similar to fig_cap in chunk code for captioner.
and to cite use
`r fig_cap("label4",display='cite')

How do you display code snippets in MS Word preserving format and syntax highlighting?

Does anyone know a way to display code in Microsoft Word documents that preserves coloring and formatting? Preferably, the method would also be unobtrusive and easy to update.
I have tried to include code as regular text which looks awful and gets in the way when editing regular text. I have also tried inserting objects, a WordPad document and Text Box, into the document then putting the code inside those objects. The code looks much better and is easier to avoid while editing the rest of the text. However, these objects can only span one page which makes editing a nightmare when several pages of code need to be added.
Lastly, I know that there are much better editors/formats that have no problem handling this but I am stuck working with MS word.
Here is the best way, for me, to add code inside word:
Go to Insert tab, Text section, click Object button (it's on the right)
Choose OpenDocument Text which will open a new embedded word document
Copy and paste your code from Visual Studio / Eclipse inside this embedded word page
Save and close
Advantages
The result looks very nice. Here are the advantages of this method:
The code keeps its original layout and colors
The code is separated from the rest of the document, as if it was a picture or a chart
Spelling errors won't be highlighted in the code (this is cool !)
And it takes only few seconds.
Download and install Notepad++ and do the following:
Paste your code in the window;
Select the programming language from the language menu;
Select the text to copy;
Right click and select Plugin commands -> Copy Text with Syntax Highlighting;
Paste it into MS Word and you are good to go!
Update 29/06/2013:
Notepad++ has a plugin called "NppExport" (comes pre-installed) that allows you to copy to RTF, HTML and ALL. It permits dozens of languages, whereas the aforementioned IDEs are limited to a handful each (without other plug-ins).
I use Copy all formats to clipboard and "paste as HTML" in MS word.
After reading a lot of related answers, I came across my own solution, which for me is the most suitable one.
Result looks like this:
As you can see, it is the same syntax highlighting like on Stack Overflow which is quite awesome.
Steps to reproduce:
on Stack Overflow
Goto Ask Question (preferably with Chrome)
Paste Code and add a language tag (e.g. Java) to get syntax hightlighting
Copy code from preview
in Word
Insert > Table > 1x1
Paste code (you may need to use Paste Special... > Formatted Text (RTF) from the Edit menu to not lose the syntax hilighting)
Table Design > Borders > No Border
Select code > Edit > Find > Replace
Search Document ^p (Paragraph Mark)
Replace With ^l (Manual Line Break)
(This is required to remove the gaps between some lines)
Select code again > Review > Language > check "Do not check spelling or grammar"
Finally add a caption using References > Insert Caption > New Label > name it "Listing" or sth
Sample code thanks to this guy
There is a nice Online Tool for that : https://www.troye.io/planetb/
Just copy the generated code and paste it into your word editing software. So far I've tried it on MS Word and WPS Writer, works really well.
Doesn't play nice with Firefox but works just fine on Chrome (and IE too, but who wants to use that).
One of the main benefits is that, unlike the Code Format Add-In for Word, it does NOT mess with your code, and respects various languages' syntax.
I tried many other options offered in other answers but I found this one to be the most efficient (quick and really effective).
There is also another online tool quoted in another answer (markup.su) but I find the planetB output more elegant (although less versatile).
Input :
Output :
I type my code in Visual Studio, and then copy-paste into word. it preserves the colors.
When I've done this, I've made extensive use of styles. It helps a lot.
What I do is create a paragraph style (perhaps called "Code Example" or something like that) which uses a monospaced font, carefully chosen tabs, a very light grey background, a thin black border above and below (that helps visibility a lot) and with spelling turned off. I also make sure that inter-line and inter-paragraph spacing are set right. I then create additional character styles on top (e.g., "Comment", "String", "Keyword", "Function Name Decl", "Variable Name Decl") which I layer on top; those set the color and whether the text is bold/italic. It's then pretty simple to go through and mark up a pasted example as being code and have it come out looking really good, and this is works well for short snippets. Long chunks of code probably should not normally be in something that's going to go on a dead tree. :-)
An advantage of doing it this way is that it is easy to adapt to whatever code you're doing; you don't have to rely on some IDE to figure out whatever is going on for you. (The main problem? Printed pages typically aren't as wide as editor windows so wrapping will suck...)
Maybe this is overly simple, but have you tried pasting in your code and setting the font on it to Courier New?
Try defining a style called 'code' and make it use a small fixed width font, it should look better then.
Use CTRL+SPACEBAR to reset style.
If you are using Sublime Text, you can copy the code from Sublime to MS Word preserving the syntax highlighting.
Install the package called SublimeHighlight.
In Sublime, using your cursor, select the code you want to copy, right click it, select 'copy as rtf', and paste into MS Word.
I'm using Easy Code Formatter. It's also an Office add-in. It allows you to select the coding style / and has a quick formatting button. Pretty neat.
In case you're like me and are too lazy or in a hurry and don't want to download additional software, you can use http://markup.su/highlighter/. It's very straight forward and supports several highlight themes and many programming languages. In my case I was using Visual Studio Code, which doesn't allow copying with format due to CSS involved in styling (as reported here).
Copy the text from the Preview box and then in Word go to Insert -> Textbox, paste the Preview from the website, highlight all the text, and then disable spell checking for that textbox.
This is what the code looks like finally.
The best way I found is by using the table.
Create a table with 1x1. Then copy the code and paste it.
If you're using the desktop app then it will inherit the code editor theme color and paste it accordingly, else you can change the table style to any color.
UPDATE ------------------
From Word 2021, you can directly paste the code and it will preserve the formatting. No need to create the table.
Thank you #RdC1965 for mentioning this.
This is a bit indirect, but it works very nicely. Get LiveWriter and install this plugin:
http://lvildosola.blogspot.com/2007/02/code-snippet-plugin-for-windows-live.html
Insert your code using the plugin into a blog post. Select all and copy it to Word.
It looks great and can include line numbers. It also spans pages decently.
HTH
Colby Africa
Vim has a nifty feature that converts code to HTML format preserving syntax highlighting, font style, background color and even line numbers. Run :TOhtml and vim creates a new buffer containing html markup.
Next, open this html file in a web browser and copy/paste whatever it rendered to Word. Vim tips wiki has more information.
In my experience copy-paste from eclipse and Notepad++ works directly with word.
For some reason I had a problem with a file that didn't preserve coloring. I made a new .java file, copy-paste code to that, then copy-paste to word and it worked...
As the other guys said, create a new paragraph style. What I do is use mono-spaced font like courier new, small size close to 8px for fonts, single spaced with no space between paragraphs, make tab stops small (0.5cm,1cm,..,5cm), put a simple line border around the text and disable grammar checks. That way i achieved the line braking of eclipse so I don't have to do anything more.
Hope I helped ;)
This is the simplest approach I follow. Consider I want to paste java code.
I paste the code here so that spaces, tabs and flower brackets are neatly formated http://www.tutorialspoint.com/online_java_formatter.htm
Then I paste the code got from step 1 here so that the colors, fonts are added to the code http://markup.su/highlighter/
Then paste the preview code got from step 2 to the MS word. Finally it will look like this
You can use VS code to keep code format and highlighting. Directly copy and paste code from VS.
you can simply use this Add-in on any office program.
Go to insert tab, then Get Add-ins, and search for Easy Syntax Highlighter
It supports
185 languages and 89 themes.
Automatic language detection.
Multi-language code highlighting.
Use a monospaced font like Lucida Console, which comes with Windows. If you cut/paste from Visual Studio or something that supports syntax highlighting, you can often preserve the colour scheme of the syntax highlighter.
Answer for people trying to resolve this issue in 2019:
Most answers to this question are outdated by now. I wish there was a way to reinspect old questions and answers every now and then!
The method I found for this question that works with Office 365 and its associated programs can be found here.
I'm using Word 2010 and I like copying and paste from a github gist. Just remember to keep source formatting!
I then change the font to DejaVu Sans Mono.
You can opt to copy with or without the numbering.
Copying into Eclipse and paste it in Word is also another option.
You can also use SciTE to paste code if you don't want to install heavy IDEs and then download plugins for all the code you're making. Simply choose your language from the language menu, type your code, high-light code, select Edit->Copy as RTF, paste into Word with formatting (default paste).
SciTE supports the following languages but probably has support for others: Abaqus*, Ada, ANS.1 MIB definition files*, APDL, Assembler (NASM, MASM), Asymptote*, AutoIt*, Avenue*, Batch files (MS-DOS), Baan*, Bash*, BlitzBasic*, Bullant*, C/C++/C#, Clarion, cmake*, conf (Apache), CSound, CSS*, D, diff files*, E-Script*, Eiffel*, Erlang*, Flagship (Clipper / XBase), Flash (ActionScript), Fortran*, Forth*, GAP*, Gettext, Haskell, HTML*, HTML with embedded JavaScript, VBScript, PHP and ASP*, Gui4Cli*, IDL - both MSIDL and XPIDL*, INI, properties* and similar, InnoSetup*, Java*, JavaScript*, LISP*, LOT*, Lout*, Lua*, Make, Matlab*, Metapost*, MMIXAL, MSSQL, nnCron, NSIS*, Objective Caml*, Opal, Octave*, Pascal/Delphi*, Perl, most of it except for some ambiguous cases*, PL/M*, Progress*, PostScript*, POV-Ray*, PowerBasic*, PowerShell*, PureBasic*, Python*, R*, Rebol*, Ruby*, Scheme*, scriptol*, Specman E*, Spice, Smalltalk, SQL and PLSQL, TADS3*, TeX and LaTeX, Tcl/Tk*, VB and VBScript*, Verilog*, VHDL*, XML*, YAML*.
If you are using Intellij IDEA, just copy the code from the IDE and paste it in the word document.
A web site for coloration with lots of languages.
http://hilite.me/
You can host one yourself since it is open source. The code is on github.
There really isn't a clean way to do it, and it could still look fishy based on your exact style settings.
What you could try to do is to first run a code-to-HTML conversion (there are many programs that do that), and then try to open up the HTML file with word, that might hopefully provide you with the formatted and pretty code, and then copy and paste it into your document.
I was also looking for it and ended up creating something for my code display.
Here's a good way:
Create a rectangular form and place your text inside.
Change the font to Consolas and size ~10.
Change the text font to gray near-black (gray 25%, darker 75%)
Use darker colors to highlight your text if needed and choose one to be the contour.
I have created an easier method using tables, as they are easier to create, manage, and more consistent (with the possibility to save the table's style inside the document itself), but I couldn't find a better way for code colouring scheme, sorry for that.
Steps:
Create a 3x3 table.
Select the table, and make its borders invisible ("No Borders" option), and activate "View Gridlines" option.
Make the adjustments to cells' spacing and columns' widths to get the desired aspect. (You will have to get in "Table Properties" for fine tuning).
Create a "Paragraph Style" with the name of "Code" just for your code snippets (as mentioned in https://stackoverflow.com/a/25092977/8533804)
Create another "Paragraph Style" with the name of "Code_numberline" that will be based upon the previous created style, but this you will add a numbering line in its definition (this will automate line numbering).
Apply "Code_numberline" to the first column, and "Code" to the 3 column.
Add a fill in the middle column.
Save that table style and enjoy!
The best presentation for code in documents is in a fixed-width font (as it should appear in an IDE), with either a faint, shaded background or a light border to distinguish the block from other text.
If its Java source code copy it to Visual Studio and then copy it back to Word.