Emacs ESS Mode TAB stops indenting - r

I'm using Emacs 24 on Windows to write some R code. Up until about 30 minutes ago, whenever I would write a new function, ESS would automatically indent the lines following the function declaration and pressing the tab key on a new blank line would jump me to the appropriately indented starting position inside the declaration.
EG:
foo <- function() {
first line started here
second line here. .etc
}
Now, it is hard wrapping everything to the left, and not responding by automatically indenting after the function declaration or when I hit the tab key.
foo <- function() {
first line
second line
}
I've googled, but my google-fu is failing me on this. Anyone know how to restore default tab behavior to ESS in Emacs?

just for the record. Whenever such things happens, select the whole buffer C-x h and press C-M-\ to indent the whole region. This will show unambiguously the syntax error.

Try to add a space after "#".
I don't think ESS-mode handles # as a comment unless you have space after it.

I just came across the same problem you describe.
None of the above seemed to work, but I narrowed it down to using a carriage return and then an open parenthesis inside a string, like so:
### indent ( <tab> ) working fine up to here
s1 <- "string
(then this in brackets)"
### now indent does nothing!
The fact that it's balanced later doesn't help. I think EMACS reads this as opening a new expression/ block in spite of the fact that it occurs in a quoted string. This seems to apply also to expression openers { and [. It only seems to happen when the 'open expression' symbol appears at the start of the line...
In my case the string was part of a plot label, so the solution was to use \n instead.

Related

buggy ANSI escape sequences in R prompt

When R is run interactively in a terminal which supports colors, it is possible to use ANSI escape sequences in order to put colors in the prompt, such as
options(prompt = "\033[0;31mThis is red\033[0m> ")
Unfortunately, something goes wrong because for long command lines, the line continuation override the prompt instead of being written in the next line.
The problem gets worse when using several colors, because somehow each escape sequence "takes up some space" in the command line, up to the point that the end of the prompt might overwrite the beginning. On my configuration this happens with for instance
options(prompt = paste("\033[0;31m With \033[0;32m multiple",
"\033[0;33m colors \033[0;34m this",
"\033[0;35m gets \033[0;36m really",
"\033[0;37m wrong! \033[0m"))
Why is it so? Is there a workaround?
PS: This rather old post seems related http://r.789695.n4.nabble.com/Xterm-escape-sequences-in-Prompt-td906375.html
update: with R version 3.6.0 and readline 8.0 (don't know which matters here), most of the above described problem disappeared, but some strange behaviors remain. Accepted answer below resolves everything.
you need to surround each «invisible» color code with special «marks»: \001 and \002:
options(prompt = "\001\033[0;31m\002This is red\001\033[0m\002> ")
for explanation see $ info readline (or this short answer).
Gábor Csárdi on the r-devel mailing list says that I cannot easily change this behavior (http://r.789695.n4.nabble.com/buggy-ANSI-escape-sequences-in-R-prompt-td4728671.html). The workaround he proposes is to use a two lines prompt, which suits me well enough.

Issues with Zsh prompt

My Zsh prompt cursor is sometimes (most of the time actually) a line below were it should be (attaching screenshot):
If I hit enter multiple times, the prompt seems to get fixed:
My first thought is that it was an error within my custom prompt, so I replaced by prompt with a simple one containing only one digit:
PROMPT='> '
But the error persisted.
Any clues about what can be missing?
You can find my theme here: http://pastebin.com/cSJwGWKZ.
Notice that I'm using Oh My Zsh.
EDIT: The prompt seems to get fixed when I reach the bottom of the terminal (by hitting enters).
The culprit is %{$(echotc DO 1)%} in your RPROMPT, which moves the cursor one line down when printing RPROMPT. When reaching the bottom of your terminal there is no additional line to go down to, so the cursor just remains where it was.
Depending on where you want your RPROMPT you have basically two options:
On the same line as your input cursor (after λ):
Just remove %{$(echotc DO 1)%} from your RPROMPT:
RPROMPT='$(_git_time_since_commit) $(git_prompt_status) ${_return_status}%'
One line (or any other number of lines, really) above your input:
Add %{$(echotc UP 1)%} at the beginning of your RPROMPT, this will move the cursor up one line, print the right prompt and move back down one line:
RPROMPT='%{$(echotc UP 1)%}$(_git_time_since_commit) $(git_prompt_status) ${_return_status}%{$(echotc DO 1)%}'`
Note: the second method may lead to RPROMPT overwriting parts of PROMPT if both get to long and/or the terminal window to narrow. If RPROMPT remains on the same line as input, it will be hidden once the input reaches it (and will reapper if you delete some of the input).

How do I edit the VIM Omni Completion so that all CSS properties do not end in a colon?

I have been exploring some way in VIM to automatically append closing characters to a line of code. In my case it is CSS. I came across this tip http://vim.wikia.com/wiki/Automatically_append_closing_characters and tweaked the code it tells me to add to my .vimrc like so
inoremap { {}<Left>
inoremap {<CR> {<CR>}<Esc>O
inoremap {{ {
inoremap {} {}
so when I write
body
and then press { and ENTER in rapid succession what results is
body {
}
Note that the cursor will be indented and on the 2nd line so I will be ready to write code in that block.
Also I should mention that I also added the following to my .vimrc
inoremap :: :;<Left>
so that when I type : and : in rapid succession I will get :; with the cursor located in between the : and ;. This exactly where I want to be so I can start writing code right away.
I got that working fine but I quickly realized that the auto complete plug in that I installed (AutoComplPop VIM plug-in http://www.vim.org/scripts/script.php?script_id=1879) conflicts with the above .vimrc tweak.
So for example, if I start to write color I get the drop auto completion drop down menu of all options. The problem is that the option for color is actually color:.
You see it has a colon already added to it so when I select it, the colon is already there and then I have to manually add the closing ; character. This basically defeats the whole purpose of adding the auto appending closing character code to my .vimrc since in this case, it does not auto append the closing semicolon.
So how do I make a custom edit to VIM's Omni Completion so that all CSS properties do not end in a colon?
CSS auto completion options for VIM and came across AutoComplPop here http://www.vim.org/scripts/script.php?script_id=1879
Assuming you are on a UNIX-like system…
Copy
/usr/share/vim/vim7x/autoload/csscomplete.vim
to
~/.vim/autoload/csscomplete.vim
Find the loop that generates the list of properties, for me it's at line 92.
Remove the colon from the second parameter of the two add().
These lines:
call add(res, m . ':')
call add(res2, m . ':')
become:
call add(res, m)
call add(res2, m)
Save the file.
Also there are many plugins for "auto closing" pairs of characters. I use DelimitMate.
And the issue is not related to ACP at all.

Multiline Comment Workarounds?

I (sort of) already know the answer to this question. But I figured it is one that gets asked so frequently on the R Users list, that there should be one solid good answer. To the best of my knowledge there is no multiline comment functionality in R. So, does anyone have any good workarounds?
While quite a bit of work in R usually involves interactive sessions (which casts doubt on the need for multiline comments), there are times when I've had to send scripts to colleagues and classmates, much of which involves nontrivial blocks of code. And for people coming from other languages it is a fairly natural question.
In the past I've used quotes. Since strings support linebreaks, running an R script with
"
Here's my multiline comment.
"
a <- 10
rocknroll.lm <- lm(blah blah blah)
...
works fine. Does anyone have a better solution?
You can do this easily in RStudio:
select the code and click CTR+SHIFT+C
to comment/uncomment code.
This does come up on the mailing list fairly regularly, see for example this recent thread on r-help. The consensus answer usually is the one shown above: that given that the language has no direct support, you have to either
work with an editor that has region-to-comment commands, and most advanced R editors do
use the if (FALSE) constructs suggested earlier but note that it still requires complete parsing and must hence be syntactically correct
A neat trick for RStudio I've just discovered is to use #' as this creates an self-expanding comment section (when you return to new line from such a line or insert new lines into such a section it is automatically comment).
[Update] Based on comments.
# An empty function for Comments
Comment <- function(`#Comments`) {invisible()}
#### Comments ####
Comment( `
# Put anything in here except back-ticks.
api_idea <- function() {
return TRUE
}
# Just to show api_idea isn't really there...
print( api_idea )
`)
####
#### Code. ####
foo <- function() {
print( "The above did not evaluate!")
}
foo()
[Original Answer]
Here's another way... check out the pic at the bottom. Cut and paste the code block into RStudio.
Multiline comments that make using an IDE more effective are a "Good Thing", most IDEs or simple editors don't have highlighting of text within simple commented -out blocks; though some authors have taken the time to ensure parsing within here-strings. With R we don't have multi-line comments or here-strings either, but using invisible expressions in RStudio gives all that goodness.
As long as there aren't any backticks in the section desired to be used for a multiline comments, here-strings, or non-executed comment blocks then this might be something worth-while.
#### Intro Notes & Comments ####
invisible( expression( `
{ <= put the brace here to reset the auto indenting...
Base <- function()
{ <^~~~~~~~~~~~~~~~ Use the function as a header and nesting marker for the comments
that show up in the jump-menu.
--->8---
}
External <- function()
{
If we used a function similar to:
api_idea <- function() {
some_api_example <- function( nested ) {
stopifnot( some required check here )
}
print("Cut and paste this into RStudio to see the code-chunk quick-jump structure.")
return converted object
}
#### Code. ####
^~~~~~~~~~~~~~~~~~~~~~~~~~ <= Notice that this comment section isnt in the jump menu!
Putting an apostrophe in isn't causes RStudio to parse as text
and needs to be matched prior to nested structure working again.
api_idea2 <- function() {
} # That isn't in the jump-menu, but the one below is...
api_idea3 <- function() {
}
}
# Just to show api_idea isn't really there...
print( api_idea )
}`) )
####
#### Code. ####
foo <- function() {
print( "The above did not evaluate and cause an error!")
}
foo()
## [1] "The above did not evaluate and cause an error!"
And here's the pic...
I can think of two options. The first option is to use an editor that allows to block comment and uncomment (eg. Eclipse). The second option is to use an if statement. But that will only allow you to 'comment' correct R syntax. Hence a good editor is the prefered workaround.
if(FALSE){
#everything in this case is not executed
}
If find it incredible that any language would not cater for this.
This is probably the cleanest workaround:
anything="
first comment line
second comment line
"
Apart from using the overkilled way to comment multi-line codes just by installing RStudio, you can use Notepad++ as it supports the syntax highlighting of R
(Select multi-lines) -> Edit -> Comment/Uncomment -> Toggle Block Comment
Note that you need to save the code as a .R source first (highlighted in red)
I use vim to edit the R script.
Let's say the R script is test.R, containing say "Line 1", "Line 2", and "Line 3" on 3 separate lines.
I open test.R on the command line with Vim by typing "vim test.R".
Then I go to the 1st line I want to comment out, type "Control-V", down arrow to the last line I want to comment out, type a capital I i.e. "I" for insert, type "# ", and then hit the Escape key to add "# " to every line that I selected by arrowing down. Save the file in Vim and then exit Vim by typing ":wq". Changes should show up in Rstudio.
To delete the comments in Vim, start at the first line on top of the character "#" you want to delete, again do "Control-V", and arrow down to the last line you want to delete a "#" from. Then type "dd". The "#" signs should be deleted.
There's seconds-worth of lag time between when changes to test.R in Vim are reflected in Rstudio.
Now there is a workaround, by using package ARTofR or bannerCommenter
Examples here:
In RStudio an easy way to do this is to write your comment and once you have used CTRL + Shift + C to comment your line of code, then use CTRL + SHIFT + / to reflow you comment onto multiple lines for ease of reading.
In RStudio you can use a pound sign and quote like this:
#' This is a comment
Now, every time you hit return you don't need to add the #', RStudio will automatically put that in for you.
Incidentally, for adding parameters and items that are returned, for standardization if you type an # symbol inside those comment strings, RStudio will automatically show you a list of codes associated with those comment parameters:
#' #param tracker_df Dataframe of limit names and limits
#' #param invoice_data Dataframe of invoice data
#' #return return_list List of scores for each limit and rejected invoice rows

What are the dark corners of Vim your mom never told you about? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
There are a plethora of questions where people talk about common tricks, notably "Vim+ctags tips and tricks".
However, I don't refer to commonly used shortcuts that someone new to Vim would find cool. I am talking about a seasoned Unix user (be they a developer, administrator, both, etc.), who thinks they know something 99% of us never heard or dreamed about. Something that not only makes their work easier, but also is COOL and hackish. After all, Vim resides in the most dark-corner-rich OS in the world, thus it should have intricacies that only a few privileged know about and want to share with us.
Might not be one that 99% of Vim users don't know about, but it's something I use daily and that any Linux+Vim poweruser must know.
Basic command, yet extremely useful.
:w !sudo tee %
I often forget to sudo before editing a file I don't have write permissions on. When I come to save that file and get a permission error, I just issue that vim command in order to save the file without the need to save it to a temp file and then copy it back again.
You obviously have to be on a system with sudo installed and have sudo rights.
Something I just discovered recently that I thought was very cool:
:earlier 15m
Reverts the document back to how it was 15 minutes ago. Can take various arguments for the amount of time you want to roll back, and is dependent on undolevels. Can be reversed with the opposite command :later
:! [command] executes an external command while you're in Vim.
But add a dot after the colon, :.! [command], and it'll dump the output of the command into your current window. That's : . !
For example:
:.! ls
I use this a lot for things like adding the current date into a document I'm typing:
:.! date
Not exactly obscure, but there are several "delete in" commands which are extremely useful, like..
diw to delete the current word
di( to delete within the current parens
di" to delete the text between the quotes
Others can be found on :help text-objects
de Delete everything till the end of the word by pressing . at your heart's desire.
ci(xyz[Esc] -- This is a weird one. Here, the 'i' does not mean insert mode. Instead it means inside the parenthesis. So this sequence cuts the text inside parenthesis you're standing in and replaces it with "xyz". It also works inside square and figure brackets -- just do ci[ or ci{ correspondingly. Naturally, you can do di (if you just want to delete all text without typing anything. You can also do a instead of i if you want to delete the parentheses as well and not just text inside them.
ci" - cuts the text in current quotes
ciw - cuts the current word. This works just like the previous one except that ( is replaced with w.
C - cut the rest of the line and switch to insert mode.
ZZ -- save and close current file (WAY faster than Ctrl-F4 to close the current tab!)
ddp - move current line one row down
xp -- move current character one position to the right
U - uppercase, so viwU upercases the word
~ - switches case, so viw~ will reverse casing of entire word
Ctrl+u / Ctrl+d scroll the page half-a-screen up or down. This seems to be more useful than the usual full-screen paging as it makes it easier to see how the two screens relate. For those who still want to scroll entire screen at a time there's Ctrl+f for Forward and Ctrl+b for Backward. Ctrl+Y and Ctrl+E scroll down or up one line at a time.
Crazy but very useful command is zz -- it scrolls the screen to make this line appear in the middle. This is excellent for putting the piece of code you're working on in the center of your attention. Sibling commands -- zt and zb -- make this line the top or the bottom one on the sreen which is not quite as useful.
% finds and jumps to the matching parenthesis.
de -- delete from cursor to the end of the word (you can also do dE to delete until the next space)
bde -- delete the current word, from left to right delimiter
df[space] -- delete up until and including the next space
dt. -- delete until next dot
dd -- delete this entire line
ye (or yE) -- yanks text from here to the end of the word
ce - cuts through the end of the word
bye -- copies current word (makes me wonder what "hi" does!)
yy -- copies the current line
cc -- cuts the current line, you can also do S instead. There's also lower cap s which cuts current character and switches to insert mode.
viwy or viwc. Yank or change current word. Hit w multiple times to keep selecting each subsequent word, use b to move backwards
vi{ - select all text in figure brackets. va{ - select all text including {}s
vi(p - highlight everything inside the ()s and replace with the pasted text
b and e move the cursor word-by-word, similarly to how Ctrl+Arrows normally do. The definition of word is a little different though, as several consecutive delmiters are treated as one word. If you start at the middle of a word, pressing b will always get you to the beginning of the current word, and each consecutive b will jump to the beginning of the next word. Similarly, and easy to remember, e gets the cursor to the end of the current, and each subsequent, word.
similar to b/e, capital B and E move the cursor word-by-word using only whitespaces as delimiters.
capital D (take a deep breath) Deletes the rest of the line to the right of the cursor, same as Shift+End/Del in normal editors (notice 2 keypresses -- Shift+D -- instead of 3)
One that I rarely find in most Vim tutorials, but it's INCREDIBLY useful (at least to me), is the
g; and g,
to move (forward, backward) through the changelist.
Let me show how I use it. Sometimes I need to copy and paste a piece of code or string, say a hex color code in a CSS file, so I search, jump (not caring where the match is), copy it and then jump back (g;) to where I was editing the code to finally paste it. No need to create marks. Simpler.
Just my 2cents.
:%!xxd
Make vim into a hex editor.
:%!xxd -r
Revert.
Warning: If you don't edit with binary (-b), you might damage the file. – Josh Lee in the comments.
gv
Reselects last visual selection.
Sometimes a setting in your .vimrc will get overridden by a plugin or autocommand. To debug this a useful trick is to use the :verbose command in conjunction with :set. For example, to figure out where cindent got set/unset:
:verbose set cindent?
This will output something like:
cindent
Last set from /usr/share/vim/vim71/indent/c.vim
This also works with maps and highlights. (Thanks joeytwiddle for pointing this out.) For example:
:verbose nmap U
n U <C-R>
Last set from ~/.vimrc
:verbose highlight Normal
Normal xxx guifg=#dddddd guibg=#111111 font=Inconsolata Medium 14
Last set from ~/src/vim-holodark/colors/holodark.vim
:%TOhtml
Creates an html rendering of the current file.
Not sure if this counts as dark-corner-ish at all, but I've only just learnt it...
:g/match/y A
will yank (copy) all lines containing "match" into the "a/#a register. (The capitalization as A makes vim append yankings instead of replacing the previous register contents.) I used it a lot recently when making Internet Explorer stylesheets.
Want to look at your :command history?
q:
Then browse, edit and finally to execute the command.
Ever make similar changes to two files and switch back and forth between them? (Say, source and header files?)
:set hidden
:map <TAB> :e#<CR>
Then tab back and forth between those files.
Vim will open a URL, for example
vim http://stackoverflow.com/
Nice when you need to pull up the source of a page for reference.
Macros can call other macros, and can also call itself.
eg:
qq0dwj#qq#q
...will delete the first word from every line until the end of the file.
This is quite a simple example but it demonstrates a very powerful feature of vim
Assuming you have Perl and/or Ruby support compiled in, :rubydo and :perldo will run a Ruby or Perl one-liner on every line in a range (defaults to entire buffer), with $_ bound to the text of the current line (minus the newline). Manipulating $_ will change the text of that line.
You can use this to do certain things that are easy to do in a scripting language but not so obvious using Vim builtins. For example to reverse the order of the words in a line:
:perldo $_ = join ' ', reverse split
To insert a random string of 8 characters (A-Z) at the end of every line:
:rubydo $_ += ' ' + (1..8).collect{('A'..'Z').to_a[rand 26]}.join
You are limited to acting on one line at a time and you can't add newlines.
^O and ^I
Go to older/newer position.
When you are moving through the file (by searching, moving commands etc.) vim rember these "jumps", so you can repeat these jumps backward (^O - O for old) and forward (^I - just next to I on keyboard). I find it very useful when writing code and performing a lot of searches.
gi
Go to position where Insert mode was stopped last.
I find myself often editing and then searching for something. To return to editing place press gi.
gf
put cursor on file name (e.g. include header file), press gf and the file is opened
gF
similar to gf but recognizes format "[file name]:[line number]". Pressing gF will open [file name] and set cursor to [line number].
^P and ^N
Auto complete text while editing (^P - previous match and ^N next match)
^X^L
While editing completes to the same line (useful for programming).
You write code and then you recall that you have the same code somewhere in file. Just press ^X^L and the full line completed
^X^F
Complete file names.
You write "/etc/pass" Hmm. You forgot the file name. Just press ^X^F and the filename is completed
^Z or :sh
Move temporary to the shell. If you need a quick bashing:
press ^Z (to put vi in background) to return to original shell and press fg to return to vim back
press :sh to go to sub shell and press ^D/exit to return to vi back
Typing == will correct the indentation of the current line based on the line above.
Actually, you can do one = sign followed by any movement command. ={movement}
For example, you can use the % movement which moves between matching braces. Position the cursor on the { in the following code:
if (thisA == that) {
//not indented
if (some == other) {
x = y;
}
}
And press =% to instantly get this:
if (thisA == that) {
//not indented
if (some == other) {
x = y;
}
}
Alternately, you could do =a{ within the code block, rather than positioning yourself right on the { character.
" insert range ip's
"
" ( O O )
" =======oOO=(_)==OOo======
:for i in range(1,255) | .put='10.0.0.'.i | endfor
This is a nice trick to reopen the current file with a different encoding:
:e ++enc=cp1250 %:p
Useful when you have to work with legacy encodings. The supported encodings are listed in a table under encoding-values (see help encoding-values). Similar thing also works for ++ff, so that you can reopen file with Windows/Unix line ends if you get it wrong for the first time (see help ff).
imap jj <esc>
Let's see some pretty little IDE editor do column transposition.
:%s/\(.*\)^I\(.*\)/\2^I\1/
Explanation
\( and \) is how to remember stuff in regex-land. And \1, \2 etc is how to retrieve the remembered stuff.
>>> \(.*\)^I\(.*\)
Remember everything followed by ^I (tab) followed by everything.
>>> \2^I\1
Replace the above stuff with "2nd stuff you remembered" followed by "1st stuff you remembered" - essentially doing a transpose.
Not exactly a dark secret, but I like to put the following mapping into my .vimrc file, so I can hit "-" (minus) anytime to open the file explorer to show files adjacent to the one I just edit. In the file explorer, I can hit another "-" to move up one directory, providing seamless browsing of a complex directory structures (like the ones used by the MVC frameworks nowadays):
map - :Explore<cr>
These may be also useful for somebody. I like to scroll the screen and advance the cursor at the same time:
map <c-j> j<c-e>
map <c-k> k<c-y>
Tab navigation - I love tabs and I need to move easily between them:
map <c-l> :tabnext<enter>
map <c-h> :tabprevious<enter>
Only on Mac OS X: Safari-like tab navigation:
map <S-D-Right> :tabnext<cr>
map <S-D-Left> :tabprevious<cr>
Often, I like changing current directories while editing - so I have to specify paths less.
cd %:h
I like to use 'sudo bash', and my sysadmin hates this. He locked down 'sudo' so it could only be used with a handful of commands (ls, chmod, chown, vi, etc), but I was able to use vim to get a root shell anyway:
bash$ sudo vi +'silent !bash' +q
Password: ******
root#
I often use many windows when I work on a project and sometimes I need to resize them. Here's what I use:
map + <C-W>+
map - <C-W>-
These mappings allow to increase and decrease the size of the current window. It's quite simple but it's fast.
:r! <command>
pastes the output of an external command into the buffer.
Do some math and get the result directly in the text:
:r! echo $((3 + 5 + 8))
Get the list of files to compile when writing a Makefile:
:r! ls *.c
Don't look up that fact you read on wikipedia, have it directly pasted into the document you are writing:
:r! lynx -dump http://en.wikipedia.org/wiki/Whatever
Not an obscure feature, but very useful and time saving.
If you want to save a session of your open buffers, tabs, markers and other settings, you can issue the following:
mksession session.vim
You can open your session using:
vim -S session.vim
Map F5 to quickly ROT13 your buffer:
map <F5> ggg?G``
You can use it as a boss key :).
I use vim for just about any text editing I do, so I often times use copy and paste. The problem is that vim by default will often times distort imported text via paste. The way to stop this is to use
:set paste
before pasting in your data. This will keep it from messing up.
Note that you will have to issue :set nopaste to recover auto-indentation. Alternative ways of pasting pre-formatted text are the clipboard registers (* and +), and :r!cat (you will have to end the pasted fragment with ^D).
It is also sometimes helpful to turn on a high contrast color scheme. This can be done with
:color blue
I've noticed that it does not work on all the versions of vim I use but it does on most.
I just found this one today via NSFAQ:
Comment blocks of code.
Enter Blockwise Visual mode by hitting CTRL-V.
Mark the block you wish to comment.
Hit I (capital I) and enter your comment string at the beginning of the line. (// for C++)
Hit ESC and all lines selected will have // prepended to the front of the line.

Resources