Conditional colorscheme in .vimrc - vim

I am using vim and MacVim. I have a 256-colour colorscheme which I like for my MacVim, but if I load it into regular vim, it obviously does not work (I get blinkies instead). I would like to be able to use the same vim config on all my systems, so:
Is there a way to check for palette size in .vimrc and set one of the two colorschemes accordingly? If that is not feasible, then checking for MacVim vs. vim would also be okay.

You've got several options.
I think your best bet is to load one colorscheme in .vimrc, and another in .gvimrc (or in your case, just don't load a colorscheme in .vimrc at all). The .gvimrc colorscheme will only be loaded when you're running the GUI version of MacVim.
If you don't want to split your configuration across multiple files, you can also use a conditional like this one in .vimrc:
if has('gui_running')
colorscheme mycrazycolors
endif
Finally, if you really do want to know the number of colors available, you can check the t_Co setting:
:echo &t_Co
t_Co is empty in the GUI version of MacVim, so you'll probably still want to use a variation of the has() technique. In fact, the default .vimrc does something similar to determine when to enable syntax highlighting:
if &t_Co > 2 || has("gui_running")
syntax on
endif
For the sake of completeness, I should mention that you could also expand your colorscheme file to include reasonable settings for color terminals. This is a fair amount of work, however, and it might be easier to just switch to a terminal application that supports more colors.
See these topics for more info:
:help has()
:help termcap
:help termcap-colors

I recently did something like this to use the same .vimrc on all our Linux systems, but use the Ubuntu monospace font if I was running on Ubuntu:
if (match(system("cat /etc/issue"), "Ubuntu") != -1)
set guifont=Ubuntu\ Mono\ 13
else
set guifont=Monospace\ 11
endif
It seems to me that you could do something similar to detect if you are running on a Mac or otherwise:
if (match(system("uname -s"), "Darwin") != -1)
colorscheme macscheme
else
colorscheme otherscheme
endif
Note that I used http://en.wikipedia.org/wiki/Uname to find out what uname reports on OS X. I don't have a Mac here handy to try it on but I imagine that's accurate.

Related

Coloring bug with Vim's ctermbg; workaround with VimLeave?

I recently discovered Vim colorschemes, and in the process have discovered a rather curious bug: when I run hi Normal ctermbg in Vim, the color change carries over to the shell that I'm running Vim in, like so:
I'm using PuTTYtray (but also see the behavior in PuTTY) with 256 colors enabled , bolded text indicated by font changes, and $TERM set to "putty-256color"; my .vimrc is as follows:
set t_Co=256
colors zenburn
and zenburn.vim can be found here. I've isolated the problem specifically to specifically line 298, where it first configures ctermbg for Normal highlighting.
(As an aside: it seems that when using PuTTY tray with specific color settings, in Normal highlighting, ctermbg has to be first set simultaneously with guifg or guibg, e.g. hi Normal guifg=#dcdccc ctermbg=237, and only after that will hi Normal ctermbg=some_val work.)
Does anyone happen to have any idea why this is happening?
I've also tried to do a workaround by running hi Normal ctermbg=None on VimLeave (although I recognize that this is problematic if I run multiple Vim instances, so if anyone can suggest an alternative that would also be welcome), but with no success. Adding the following to my .vimrc does not work:
function! RESET_ctermbg()
"reset $ctermbg to None"
exec "hi Normal ctermbg=None"
endfunction
au VimLeave * call RESET_ctermbg()
I've fixed the problem by changing $TERM to xterm-256color; my best bet is that putty-256color is not well-supported enough as a shell to handle behavior like the vim colorscheme I was doing, so I don't even need to try to make the workaround work anymore.

ConEmu: Vim Syntax Highlight

Is it possible to get vim syntax highlighting in ConEmu?
Note. Some updated information may exists on the project site.
Well, builds since 130120 supports 256 colors in vim. You need to
Check options "Inject ConEmuHk" and "ANSI X3.64 / xterm 256 colors" on "Features" page
Check option "TrueMod (24bit color) support" on "Colors" page
Edit your vimrc file, sample lines are here. Of course, you need some 256-color vim scheme, it is zenburn in the last line of this example.
set term=xterm
set t_Co=256
let &t_AB="\e[48;5;%dm"
let &t_AF="\e[38;5;%dm"
colorscheme zenburn
And "vim" must be vim.exe ATM.
Note. 'Original' Vim (Win32 console executable from gvim##.exe and vim##w32.zip) passed tests. MinGW's Vim fails to switch to using Ansi sequences.
I know is an old question. But what worked for me was similar to the selected answer except that instead of setting term to xterm, set it to pcansi that way the keyboard keys will still work. For ConEmu in the %HOMEPATH%_vimrc
if !empty($CONEMUBUILD)
set term=pcansi
set t_Co=256
let &t_AB="\e[48;5;%dm"
let &t_AF="\e[38;5;%dm"
set bs=indent,eol,start
colorscheme wombat256
endif

Vim doesn't show colors that macvim does

I have tried two schemes, desert and wombat and I have set the colorscheme in my .vimrc file. When I open vim from my shell I don't see the color of the scheme, but when I open with MacVim I do. In both, when I type :colorscheme I see the scheme that is set in the .vimrc file, but I fail to see why I don't see the colors.
As a note, I installed the spf13 distro and uninstalled it using the script provided.
Any thoughts of how can I troubleshoot this?
First, check how many colors are supported by your terminal:
:echo $TERM
:set t_Co?
The colorscheme must actually support terminals by providing term= and cterm= definitions; many don't. See https://stackoverflow.com/a/12949536/813602 for how to work around this with the CSApprox plugin.
Inspect the colorscheme file (found in the colors/ subdirectory), or use the :highlight command to list the current color definitions.
Terminal emulators are limited to 256 colors max and often need manual setup to go beyond 8 or 16.
The coolest Vim colorschemes are designed for GVim/MacVim which can display thousands of colors.
Because of 1 and 2 it is impossible to fully emulate a GUI colorscheme in a terminal emulator if the GUI colorscheme uses colors outside the 256 colors in the X11 palette.
However, you could:
use a colorscheme that works in GUI and CLI
use a colorscheme that works only in CLI and another that works only in GUI and switch between them in your ~/.vimrc depending on the context
use a plugin that converts your GUI colorscheme on the fly: this one, this one, this one or this one
edit your colorscheme manually to add terminal support
Terminals support 88 or 256 colors. Even if your terminal supports 256 colors, you have to specify that your terminal support it in your vimrc. (cf. Using GUI color settings in a terminal)
set t_Co=256
Concerning your background, you should maybe specify that you are using a dark or a light background if your theme doesn't already declare it.
set background=dark
set background=light

In my .vimrc, how can I check for the existence of a color scheme?

In a .vimrc, is it possible to load a color scheme only if it exists?
Using :colorscheme in a try-catch as Randy has done may be enough if you just want to load it if it exists and do something else otherwise. If you are not interested in the else part, a simple :silent! colorscheme is enough.
Otherwise, globpath() is the way to go. You may, then, check each path returned with filereadable() if you really wish to.
" {rtp}/autoload/has.vim
function! has#colorscheme(name) abort
let pat = 'colors/'.a:name.'.vim'
return !empty(globpath(&rtp, pat))
endfunction
" .vimrc
if has#colorscheme('desert')
...
EDIT: filereadable($HOME.'/.vim/colors/'.name.'.vim') may seem simple and it's definitively attractive, but this is not enough if the colorscheme we're looking for is elsewhere. Typically if it has been installed in another directory thanks to a plugin manager. In that case the only reliable way is to check in the vim 'runtimepath' (a.k.a. 'rtp'). Hence globpath(). Note that :colorscheme name command searches in {rtp}/colors/{name}.vim.
An alternative to #eckes answer would be to try to load the colorscheme and deal with the error if it doesn't exist:
try
colorscheme mayormaynotexist
catch /^Vim\%((\a\+)\)\=:E185/
" deal with it
endtry
You could use the filereadable function to check if a color scheme (e.g. schemename) exists: check once under ~/vimfiles/colors (Win32, for Unix use ~/.vim/colors/) and once under $VIMRUNTIME/colors/:
if filereadable("/path/to/schemename.vim")
colo schemename
endif
My method is similar,
if filereadable( expand("$HOME/.vim/colors/railscast.vim") )
colorscheme railscast
endif
This is a little more robust than hardcoding the entire path.
Normally I use a favorite colorscheme with a fallback if my favorite is not available. A nested try will make this work:
try
colorscheme solarized
catch
try
colorscheme peachpuff
catch
endtry
endtry
If neither colorscheme is available, the default one is loaded (whatever that happens to be on your system). No errors are shown if one or both of the colorschemes are not available. Put your preferred colorscheme first.
Also, catch with no arguments catches any error. This is handy if you are dealing with different locales that give different error messages.
This is wat I have in my .vimrc file.
if filereadable( expand("$HOME/.vim/colors/sublimemonokai.vim") )
colorscheme sublimemonokai "https://github.com/ErichDonGubler/vim-sublime-monokai
" vim-sublime-monokai only support 256 colours in terminal. If you are using a terminal which support truecolor like iterm2, enable the GUI color
set termguicolors
" Otherwise, use below setting to activate the 256 color in terminal
set t_Co=256
else
echom "The sublimemonokai.vim were not found to be used as colorscheme. elflord will be set for the timebeing..."
colorscheme elflord
endif
basically it does check to see if the color scheme I like exists on the machine or not. If it does, it will select it and apply all the setting necessary for it. Otherwise it choose a suitable color scheme that is shipped with vim.
By looking at other answers, my answer shares bit part with #user427390 answer and it has an additional else condition.
The following link has helped me a lot in scripting my own .vimrc and vim related files:
http://learnvimscriptthehardway.stevelosh.com/

vim colorschemes not changing background color

I try to apply various color schemes in vim that I have seen on the net. Whatever scheme I choose, the background remains white, even though screenshots of the applied scheme shows that the background should be colored.
In some schemes, some of the background change color, but space right of lines containing text still remains white.
I'm using Vim 7.2 on a mac. I have just started messing with non-gui applications, so everything should be pretty much as it was out of the box..
Does the overall settings for the terminal window have something to do with it?
When running macvim, everything looks ok. Its only when starting vim from the terminal things looks strange..
I have this in my .vimrc and it solved this problem for me using while using PuTTY.
set t_Co=256
set background=dark
colorscheme mustang
highlight Normal ctermbg=NONE
highlight nonText ctermbg=NONE
It's important to load the colorscheme before the ctermbg settings in .vimrc because they need to override the same ones set by the colorscheme. This also means you can't switch colorscheme while Vim is running and expect it to work.
I'm adding a second answer from me because it's very different from my first answer and may point to actual problem.
If you look at the actual website for the colorscheme here:
Molokai website
you will see a question very similar to yours. Here's answer given, which suggests trying command :set t_Co=256 in your vimrc to see if it fixes things:
"- Make sure you’re using a console terminal capable of 256 colors; not all of them do (particularly on mac). You might need to explicitly force Vim to use that by doing “set t_Co=256″ on your .vimrc file.
- The windows console is well… totally unsupported, that only does 16 colors so it’s a mess"
In linux I had export TERM=xterm-256color in my .bashrc. That caused vim to look like this (after setting set t_Co=256):
When I removed that line from my .bashrc and opened a new terminal (exec bash didn't do it) This is what I get:
Terminals are usually limited to 256 colors while GUI are only limited by color depth of your desktop environment, typically 2^32.
So even if there is lots of vim color scheme available around, implicitly they are often designed for the GUI and won't work for the terminal version.
If you look at color schemes on vim.org, there is often a mention of GUI or 256. So you have to chose which to use depending on the context.
To convert a GUI scheme to terminal you can use the following plugin :
CSApprox.
You can also use a different colorscheme depending on the context, add the following in your .vimrc:
if has("gui_running")
colorscheme [using any color you want]
else
colorscheme [using 256 colors]
endif
I think the problem could be the way the default color is changed by the colorscheme. I've looked at some colorschemes that set default merely by:
set background=light
or
set background=dark
Not sure what limitations of those are. I don't think those work in terminals.
In any case, you should be able to manually set background in a terminal by using the 'Normal' highlight. Insert it into a spot before most of the 'hi' commands in the colorscheme file and it should provide defaults they will work with. For example:
hi Normal ctermbg=White ctermfg=Black guifg=Black guibg=White
Change ctermfg (color terminal foreground) and ctermbg (color terminal background) to be whatever you want (or whatever color you were expecting to see in the colorscheme but now aren't seeing). (Remember, though, if the colorscheme already has a setting for hi Normal then this probably isn't your problem.)
For ctermbg and ctermfg you can enter color names, but I think there is only a fairly limited number:
Black
DarkBlue
DarkGreen
DarkCyan
DarkRed
DarkMagenta
Brown, DarkYellow
LightGray, LightGrey, Gray, Grey
DarkGray, DarkGrey
Blue, LightBlue
Green, LightGreen
Cyan, LightCyan
Red, LightRed
Magenta, LightMagenta
Yellow, LightYellow
White
Otherwise you should be able to use a number from 0 to 255 in place of the color name. Or this script gives rough idea, and lets you see how you could also set up to use more color names:
Vim script with color settings
Also, there are a number of scripts that help you use or convert colorschemes written for gui for use with cterm. E.g.,:
Colorscheme support for cterm
Does the overall settings for the terminal window have something to do with it?
Maybe, but I'm pretty sure a properly written Vim colorscheme will override any terminal settings you've made. At least they do for me in Windows and on Ubuntu. . .
You need to add set termguicolors to your ~/.vimrc
I tested t_Co=256 and other options, but none worked, only set termguicolors
After this you can use the command set bg=light or set bg=dark to see witch one looks better (some vim color schemes accept both options).
Here is a list of terminals that are compatible with termguicolors: https://gist.github.com/XVilka/8346728#now-supporting-true-color
I had the same problem and found out that the answer to this question is actually threefold, where fixing only two of the three isn't enough. You'll need to have:
256-color support in your terminal - Putty with default settings does have this
Vim has to recognize that the terminal is 256-color capable: "set t_Co=256" in your .vimrc will do it
The color scheme needs to have support for color terminals with ctermbg and ctermfg attributes for highlights, not just the gui*-versions. http://www.vim.org/scripts/script.php?script_id=2682 should be able to provide these automatically, and CSApprox I'm using most definitely does, but requires either +gui -compiled Vim or a recent enough Vim version (7.3 or newer).
The third one seems to be the most commonly missed requirement. I wrote a short piece on my own fumblings on this subject just this morning: http://codeandlife.com/2013/09/22/vim-colorschemes-with-putty-aka-gui-vs-xterm-color256/
Final gotcha that happened to me while trying different settings was that when the colors did work, only areas of screen with text had the proper background color. Re-checking Putty Terminal setting "Use background colour to erase screen" fixed that final issue for me.
Does the overall settings for the terminal window have something to do with it?
Yes, terminal parameters override vim parameters (at least in OSX and iTerm). For example, I have a following script in /Users/[username]/.bashrc
setBackground() {
osascript -e "tell application \"iTerm\"
set current_terminal to (current terminal)
tell current_terminal
set current_session to (current session)
tell current_session
set background color to $1
end tell
end tell
end tell"
}
vim() {
(setBackground "{65025,65025,65025}" &)
(exec vim $*)
}
The above remaps terminal vim command to execute a background color change before executing vim. Background color function is applescript (I copied the script from somewhere...). It works for iTerm. I belive that you can adapt this to work with terminal (apple product + apple script -> should work).
br,
Juha
Use this rule if you use Vim through SSH:
Add to your local .bashrc:
export TERM=xterm-256color
Remove from .bashrc any TERM definitions.
If you use same .bashrc on both (local and remote), use temporary environment variable and never set TERM globally:
alias color-ssh='TERM=xterm-256color ssh user#host'
This works for me for switching backgrounds:
colorscheme hemisu
function! g:ToggleBackground()
if &background != 'dark'
set background=dark
else
set background=light
colorscheme hemisu
endif
endfunction
nnoremap <silent> <F3> :call g:ToggleBackground()<CR>
Also try setting light background to something like ctermbg=231, so that tmux handles it better.
I have similar issue that the background color of indentation guides (nathanaelkane's vim-indent-guides) cannot be displayed in my Windows Cygwin's mintty terminal.
I solved the issue with a line Term=xterm-256color in ~/.minttyrc (equivalent to set via mintty's Options GUI: Terminal -> Type -> xterm-256color. This has the effect export TERM=xterm-256color. Without this, mintty default to TERM="xterm", which result in vim's t_Co=8 (instead of t_Co=256) and cannot show some background color.
Checklist:
echo $TERM in bash should give xterm-256color.
in vim, :set t_Co should give t_Co=256.

Resources