Can I have vim highlight code in R markup? - r

Say I have an .Rmd file like this:
The total number of steps per day can also be calculated
using `tapply`.
```{r}
tapply(d$steps, INDEX=d$date, FUN=sum)[1:5]
```
What seems to be different is that, per default, `xtabs`
returns 0 for `NA` values and `tapply` returns `NA`.
In my terminal window, this looks like this:
It would be great if somehow I could inform vim that the R chunk is actually R code which it could highlight just as it does when working in an actual .R file.
Is this possible?

Yes you can. This code is taken from here.
Put this in the ~/.vim/r.vim file (if any of these files do not exist, create them)
function! TextEnableCodeSnip(filetype,start,end,textSnipHl) abort
let ft=toupper(a:filetype)
let group='textGroup'.ft
if exists('b:current_syntax')
let s:current_syntax=b:current_syntax
" Remove current syntax definition, as some syntax files (e.g. cpp.vim)
" do nothing if b:current_syntax is defined.
unlet b:current_syntax
endif
execute 'syntax include #'.group.' syntax/'.a:filetype.'.vim'
try
execute 'syntax include #'.group.' after/syntax/'.a:filetype.'.vim'
catch
endtry
if exists('s:current_syntax')
let b:current_syntax=s:current_syntax
else
unlet b:current_syntax
endif
execute 'syntax region textSnip'.ft.'
\ matchgroup='.a:textSnipHl.'
\ start="'.a:start.'" end="'.a:end.'"
\ contains=#'.group
endfunction
Now you can use
:call TextEnableCodeSnip( 'r', '```{r}', '```', 'SpecialComment')
As long as there is an r.vim syntax file.
You could also automatically call this method every time you open a .Rmd file:
autocmd BufNewFile,BufRead *.Rmd :call TextEnableCodeSnip( 'r', '```{r}', '```', 'SpecialComment')
If you wanted to highlight with r followed by any number of characters you can use regular expressions:
:call TextEnableCodeSnip( 'r', '```{r.*}', '```', 'SpecialComment')
Or in your .vimrc:
autocmd BufNewFile,BufRead *.Rmd :call TextEnableCodeSnip( 'r', '```{r.*}', '```', 'SpecialComment')
The .* regular expression means any repeating character. So r.* means r followed by any number of characters.
Therefore this will work with
```{r whatever you want to put here}`
Some r code here
```

You might also be interested in my SyntaxRange plugin, which is based on the Vim Tip in #Zach's answer. It simplifies the setup of such syntax regions.
The setup would be like this (e.g. in ~/.vim/ftplugin/markdown.vim):
call SyntaxRange#Include('^````{r}', '^````', 'r', 'SpecialComment')

Related

Fortran90: Scripting of Standard In not working as expected

Working with Fortran90 in Unix...
I have a programme which needs to read in the input parameters from a file "input-deck.par". This filename is currently hard-coded but I want to run a number of runs using different input-deck files (input-deck01.par, input-deck02.par, input-deck03.par etc.) so I've set-up the code to do a simple "read(*,*) inpfile" to allow the user to input the name of this file directly on run-time with a view to scripting this later.
This works fine interactively. If I execute the programme it asks for the file name, you type it in and the filename is accepted, the file is opened and the programme picks up the parameters from that file.
The issue lies in scripting this. I've tried scripting using the "<" pipe command so:
myprog.e < input-deck01.par
But I get an error saying:
Fortran runtime error: Cannot open file '----------------': No such file or directory
If I print the filename right after the input line, it prints that the filename is '----------------' (I initialise the variable as having 16 characters hence the 16 hyphens I think)
It seems like the "<" pipe is not passing the keyboard input in correctly. I've tried with spaces and quotes around the filename (various combinations) but the errors are the same.
Can anyone help?
(Please be gentle- this is my first post on SO and Fortran is not my primary language....)
Fortran has the ability to read the command line arguments. A simple example is
program foo
implicit none
character(len=80) name
logical available
integer fd
if (command_argument_count() == 1) then
call get_command_argument(1, name)
else
call usage
end if
inquire(file=name, exist=available)
if (.not. available) then
call usage
end if
open(newunit=fd, file=name, status='old')
! Read file
contains
subroutine usage
write(*,'(A)') 'Usage: foo filename'
write(*,'(A)') ' filename --> file containing input info'
stop
end subroutine usage
end program foo
Instead of piping the file into the executable you simply do
% foo input.txt

Python Interpreting things from document

So, I am essentially just dreaming up ideas right now.
I was wondering if it was possible to make a python program that can read a document, take a line from the document, make an if/else statement with it (Like if the text on that line is equal to Hello, than say hello back), and then continue onto the next line. I have already kind of done this in a shell fashion but I want to see if it is possible to have python read the line of a document, interpret it, display something, and move on to the next line of the document.
(I am prepared for this post to get tons of -1's for not knowing how to program a lot of python, and probably just not being clear enough. So before you -1, just add a comment saying what you need me to be clear about.)
The version of python of my choice would be 2.5.
Since you don't know any Python, try this:
with open("file.txt") as f:
for line in f:
if line.strip() == "Hello":
print "Hello back"
or without the exception-safe clause:
for line in open("file.txt"):
if line.strip() == "Hello":
print "Hello back"
the strip() removes the ending newline \n from the line
That is actually a very simple task in Python:
file = open("file.txt") # open the file
while True:
word = file.readline() # read a line from the file
print word # print it to the console
if word == "": # if out of words...
file.close() # ...close the file
break # and break from while loop and exit program

Using Variables in Declared in Different File on Unix Script

How can I keep variables used in a script in a secondary file? For example, use store variables in myscript.env for use in a script myscript.sh.
So whenever I need to change variables I can edit myscript.env instead of myscript.sh.
Simply include the file using the "dot operator".
assuming these two files are in the same directory, the following will work:
t.sh:
#!/usr/bin/sh
# Note the first dot on the following line
. ./t.env
echo $TESTVAR
t.env:
TESTVAR="Hello world"
When run:
~/tmp$ sh ./t.sh
Hello world
This is quite a usual design pattern. Think along the lines of
myscript.sh:
#!/path/to/shell
CONFIG_FILE=myscript.env
CONFIG_DIR=`dirname $0`
# or e.g. CONFIG_DIR=/etc/myscript
CONFIG="$CONFIG_DIR/$CONFIG_FILE"
. $CONFIG
echo "SOMEVAR=$SOMEVAR"
myscript.env
SOMEVAR="The value of some var"
Now /path/to/myscript.sh will output SOMEVAR=The value of some var

Customize zsh's prompt when displaying previous command exit code

Zsh includes the ability to display the return code/exit code of the previous command in the prompt by using the %? escape sequence.
However I would like to have the following prompt:
user#host ~ [%?] %
when the exit code is different from 0 and:
user#host ~ %
when exit code is 0.
If I use %? alone it is always displayed, even if %? is 0.
In addition I want the square brackets but only when the exit code not 0.
What is the simplest way to do this?
Add this in the position in PS1 where you want the exit code to appear:
%(?..[%?] )
It's a conditional expression. The part between the two dots (nothing in this case) is output if the expression before the first dot is true. The part after the second dot is output if it's false.
For example:
PS1='%n%m %~ %(?..[%?] )%# '
Alternatively, you can:
setopt PRINT_EXIT_VALUE
to always print a newline showing previous return value.
I don't prefer this for ordinary use, but it is often good for debugging shell scripts.

Printing hard copies of code

I have to hand in a software project that requires either a paper or .pdf copy of all the code included.
One solution I have considered is grouping classes by context and doing a cat *.extension > out.txt to provide all the code, then by catting the final text files I should have a single text file that has classes grouped by context. This is not an ideal solution; there will be no page breaks.
Another idea I had was a shell script to inject latex page breaks in between files to be joined, this would be more acceptable. Although I'm not too adept at scripting or latex.
Are there any tools that will do this for me?
Take a look at enscript (or nenscript), which will convert to Postscript, render in columns, add headers/footers and perform syntax highlighting. If you want to print code in a presentable fashion, this works very nicely.
e.g. here's my setting (within a zsh function)
# -2 = 2 columns
# -G = fancy header
# -E = syntax filter
# -r = rotated (landscape)
# syntax is picked up from .enscriptrc / .enscript dir
enscript -2GrE $*
For a quick solution, see a2ps, followed by ps2pdf. For a nicer, more complex solution I would go for a simple script that puts each file in a LaTeX listings environment and combines the result.

Resources