buggy ANSI escape sequences in R prompt - r

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.

Related

Zsh + tmux + oh-my-zsh: Autocomplete produces remnant characters

I recently installed Zsh in hope of a better life and brighter mornings. However, I quickly realized Zsh introduces various issues in conjunction with tmux.
The first issue was some weird stuff happening at the end of the prompt, before my commands, but this was resolved by supplying tmux with the -u flag for unicode-support. However, I am stuck with one final issue that needs resolution before I can use Zsh with tmux:
Usecase: Autocomplete a command which contains multiple suggestions
Issue: Autocompletion shifts suggestion one character to the right, while leaving the original character behind (visual bug, it is not included in the command)
Example 1.
Then I hit TAB..
Example 2.
Then I hit TAB..
Note 1: This does NOT occur when using the Bash-shell.
Note 2: I am using "oh-my-zsh". This issue only occurs when using the provided themes. This narrows it down to an "oh-my-zsh"-theme issue, not native zsh/tmux.
In case some people still get a similar issue, see also the top-voted answer of Remnant characters when tab completing with ZSH. The plugin you were using may have had the same non-printable characters issue, that would explain the symptoms.

Perl: Shebang (space?) "#! "?

I've seen both:
#!/path/...
#! /path/...
What's right? Does it matter? Is there a history?
I've heard that an ancient version of Unix required there not be a space. But then I heard that was just a rumor. Does anyone know for certain?
Edit: I couldn't think where better to ask this. It is programming related, since the space could make the program operate in a different way, for all I know. Thus I asked it here.
I also have a vague memory that whitespace was not allowed in some old Unix-like systems, but a bit of research doesn't support that.
According to this Wikipedia article, the #! syntax was introduced in Version 8 Unix in January, 1980. Dennis Ritchie's initial announcement of this feature says:
The system has been changed so that if a file being executed begins
with the magic characters #!, the rest of the line is understood to
be the name of an interpreter for the executed file. Previously (and
in fact still) the shell did much of this job; it automatically
executed itself on a text file with executable mode when the text
file's name was typed as a command. Putting the facility into the
system gives the following benefits.
[SNIP]
To take advantage of this wonderful opportunity, put
#! /bin/sh
at the left margin of the first line of your shell scripts. Blanks
after ! are OK. Use a complete pathname (no search is done). At the
moment the whole line is restricted to 16 characters but this limit
will be raised.
It's conceivable that some later Unix-like system supported the #! syntax but didn't allow blanks after the !, but given that the very first implementation explicitly allowed blanks, that seems unlikely.
leonbloy's answer provides some more context.
UPDATE :
The Perl interpreter itself recognizes a line starting with #!, even on systems where that's not recognized by the kernel. Run perldoc perlrun or see this web page for details.
The #! line is always examined for switches as the line is being
parsed. Thus, if you're on a machine that allows only one argument
with the #! line, or worse, doesn't even recognize the #! line, you
still can get consistent switch behaviour regardless of how Perl was
invoked, even if -x was used to find the beginning of the program.
Perl also permits whitespace after the #!.
(Personally, I prefer to write the #! line without whitespace, but it will work either way.)
And leonjoy's answer points to this web page by Sven Mascheck, which discusses the history of #! in depth. (I mention this now because of a recent discussion on comp.unix.shell.)
It seems to usually work both ways. See here. I'd say that the no-space version is much more common today, and, to me, much more appealing.
BTW, this is not specifically related to Perl (but it's definitely related to programming).

Is it possible to have a multi-line comments in R? [duplicate]

This question already has answers here:
Multiline Comment Workarounds?
(11 answers)
Closed 9 years ago.
I found this old thread (from over a year ago), which explains how come R doesn't support a multi-line comments (like /* comment */ of PHP, for example).
I am wondering if this has been resolved in the past year, or if there are other alternatives? (For example, in notepad++ with npptor, you can mark a bunch of lines and press ctrl+q to mark them all as comments, are there similar solutions for other IDE's ?)
R Studio (and Eclipse + StatET): Highlight the text and use CTRL+SHIFT+C to comment multiple lines in Windows.
For macOS, use command+SHIFT+C.
You can, if you want, use standalone strings for multi-line comments — I've always thought that prettier than if (FALSE) { } blocks. The string will get evaluated and then discarded, so as long as it's not the last line in a function nothing will happen.
"This function takes a value x, and does things and returns things that
take several lines to explain"
doEverythingOften <- function(x) {
# Non! Comment it out! We'll just do it once for now.
"if (x %in% 1:9) {
doTenEverythings()
}"
doEverythingOnce()
...
return(list(
everythingDone = TRUE,
howOftenDone = 1
))
}
The main limitation is that when you're commenting stuff out, you've got to watch your quotation marks: if you've got one kind inside, you'll have to use the other kind for the comment; and if you've got something like "strings with 'postrophes" inside that block, then there's no way this method is a good idea. But then there's still the if (FALSE) block.
The other limitation, one that both methods have, is that you can only use such blocks in places where an expression would be syntactically valid - no commenting out parts of lists, say.
Regarding what do in which IDE: I'm a Vim user, and I find
NERD Commenter an utterly excellent tool for quickly commenting or uncommenting multiple lines. Very user-friendly, very well-documented.
Lastly, at the R prompt (at least under Linux), there's the lovely Alt-Shift-# to comment the current line. Very nice to put a line 'on hold', if you're working on a one-liner and then realise you need a prep step first.
CTRL+SHIFT+C in Eclipse + StatET and Rstudio.
if(FALSE) {
...
}
precludes multiple lines from being executed. However, these lines still have to be syntactically correct, i.e., can't be comments in the proper sense. Still helpful for some cases though.
No multi-line comments in R as of version 2.12 and unlikely to change. In most environments, you can comment blocks by highlighting and toggle-comment. In emacs, this is 'M-x ;'.
Put the following into your ~/.Rprofile file:
exclude <- function(blah) {
"excluded block"
}
Now, you can exclude blocks like follows:
stuffiwant
exclude({
stuffidontwant
morestuffidontwant
})
Unfortunately, there is still no multi-line commenting in R.
If your text editor supports column-mode, then use it to add a bunch of #s at once. If you use UltraEdit, Alt+c will put you in column mode.

Why do <C-PageUp> and <C-PageDown> not work in vim?

I have Vim 7.2 installed on Windows. In GVim, the <C-PageUp> and <C-PageDown> work for navigation between tabs by default. However, it doesn't work for Vim.
I have even added the below lines in _vimrc, but it still does not work.
map <C-PageUp> :tabp<CR>
map <C-PageDown> :tabn<CR>
But, map and works.
map <C-left> :tabp<CR>
map <C-right> :tabn<CR>
Does anybody have a clue why?
The problem you describe is generally caused by vim's terminal settings not knowing the correct character sequence for a given key (on a console, all keystrokes are turned into a sequence of characters). It can also be caused by your console not sending a distinct character sequence for the key you're trying to press.
If it's the former problem, doing something like this can work around it:
:map <CTRL-V><CTRL-PAGEUP> :tabp<CR>
Where <CTRL-V> and <CTRL-PAGEUP> are literally those keys, not "less than, C, T, R, ... etc.".
If it's the latter problem then you need to either adjust the settings of your terminal program or get a different terminal program. (I'm not sure which of these options actually exist on Windows.)
This may seem obvious to many, but konsole users should be aware that some versions bind ctrl-pageup / ctrl-pagedown as secondary bindings to it's own tabbed window feature, (which may not be obvious if you don't use that feature).
Simply clearing them from the 'Configure Shortcuts' menu got them working in vim correctly for me. I guess other terminals may have similar features enabeld by default.
I'm adding this answer, taking details from vi & Vim, to integrate those that are already been given/accepted with some more details that sound very important to me.
The alredy proposed answers
It is true what the other answer says:
map <C-PageUp> :echo "hello"<CR> won't work because Vim doesn't know what escape sequence corresponds to the keycode <C-PageUp>;
one solution is to type the escape sequence explicitly: map ^[[5^ :echo "hello"<CR>, where the escape sequence ^[[5^ (which is in general different from terminal to terminal) can be obtained by Ctrl+VCtrl+PageUp.
One additional important detail
On the other hand the best solution for me is the following
set <F13>=^[[5^
map <F13> :echo "hello"<CR>
which makes use of one of additional function key codes (you can use up to <F37>). Likewise, you could have a bunch of set keycode=escapesequence all together in a single place in your .vimrc (or in another dedicated file that you source from your .vimrc, why not?).

console print w/o scrolling

I see console apps print colors and seen apps such as ffmpeg print text over itself instead of a new line. How do I print over an existing line? I want to display fps in my console app either at the very top or very bottom and have regular printfs go there and scroll normally.
I need this for windows, but this is meant to be cross platform, so I will eventually have a linux and mac implementation.
There is two simple possibilities which work on linux as well as windows, but only for one line:
printf("\b"); will return for one character, so you might count how many character you want to backspace and fire this in a loop, or you know that you only write n numbers and do it likeprintf("\b\b\b\b\b\b\b\b\b\b");
printf("text to be overwritten by next printf\r"); this will return the cursor to the beginning of the line, so any next printf will overwrite it. Make sure to write a string of same length or longer so you overwrite it entirely.
If you want to rewrite several lines, there is nothing so portable as ncurses, there is libs for it on practically every operating system, and you don't have to take care of the ANSI-differences.
edit: added link to ncurses wikipedia page, gives great overview and introduction, as well as link list and maybe a translation to your preferred language
Check out ncurses. It has bindings for most scripting languages.
You can use '\r' instead of '\n'.
The ASCII character number 8 (A.K.A. Ctrl-H, BS or Backspace) lets you back up one character. ASCII Character number 13 (A.K.A Ctrl-M, CR or Carriage Return) returns the cursor at the beggining of the line.
If you are working in C try putchar(8); and putchar(13);
The magic of the colors, cursor locating and bliking and so on are inside ANSI escape codes. Any text console capable of handling ANSI codes can use them just printing them out to console (i.e. by means of echo in a bash script or printf() function in C).
Unix terminals support ANSI escape sequences and Windows world used to support them back in old MS-DOS days, but the multibyte console support put an end to this. There is more information here. However there are other ways out of just ANSI sequences printing available on Windows. Moreover if you have Cygwin installed on your Windows maching ANSI codes work just as great as on any Unix terminal.
Many people mention Ncurses library that is the de-facto standard for any gui-like text based applications. What this library does is to hide all the terminal differences (Windows/Unix flavours) to represent the same information as identical as possible across all the platforms, though from my own experience I tell you this is not always true (i.e. typical text window frames change because the especial chars are not available under all character encodings). The counterpart of using ncurses is that it is a complete API and it is much harder to start out with it than simply writing out some ANSI escape sequences for simple things such as change the font color, cleaning screen or moving back the cursor to a random position.
For the sake of completeness I paste an example of use of ANSI sequence under Linux that changes the prompt to blue and shows the date:
PS1="\[\033[34m\][\$(date +%H%M)][\u#\h:\w]$ "
You can use Ncurses -
ncurses package is a subroutine library for terminal-independent screen-painting and input-event handling which presents a high level screen model to the programmer, hiding differences between terminal types and doing automatic optimization of output to change one screenfull of text into another
Depending on the platform which you are developing on there's probably a more powerful API which you could use, rather than old ASCII control codes.
e.g. If you are working on Win32 you can actually manipulate the console screen buffer directly.
A good place to start might be here
http://msdn.microsoft.com/en-us/library/ms683171(VS.85).aspx
I have been looking for similar functions/API which would allow me to access the console as something other than a stream of text for other platforms. Haven't found anything yet, but then again, I haven't been looking that hard.
Hope it helps.

Resources