Add test harness for experimental non-null option

// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// These tests are for an experimental feature that treats Dart primitive types
// (int, bool, double, etc.) as non-nullable. This file is not evidence for an
// intention to officially support non-nullable primitives in Dart (or general
// NNBD, for that matter) so don't get too crazy about it.

library analyzer.test.src.task.non_null_primitives.checker_test;

import '../../../reflective_tests.dart';
import '../strong/strong_test_helper.dart';

void main() {
  initStrongModeTests();
  runReflectiveTests(NonNullCheckerTest);
}

@reflectiveTest
class NonNullCheckerTest {
  // Tests simple usage of ints as iterators for a loop. Not directly related to
  // non-nullability, but if it is implemented this should be more efficient,
  // since languages.length will not be null-checked on every iteration.
  void test_forLoop() {
    checkFile('''
class MyList {
  int length;
  MyList() {
    length = 6;
  }
  String operator [](int i) {
    return <String>["Dart", "Java", "JS", "C", "C++", "C#"][i];
  }
}

main() {
  var languages = new MyList();
  for (int i = 0; i < languages.length; ++i) {
    print(languages[i]);
  }
}
''');
  }
}


library compare_to_golden;

import 'dart:async';
import 'dart:io';
import 'dart:mirrors';

import 'package:path/path.dart' as p;
import 'package:test/test.dart';

Future compareSummaryFileToGolden(String dartFileName,
    {String summaryExtension, String goldenExtension}) async {
  var input = getFile(dartFileName, summaryExtension);
  var golden = getFile(dartFileName, goldenExtension);

  expect(await input.readAsString(), await golden.readAsString());
}

File getFile(String dartFileName, String extension) =>
    _getFile('${p.withoutExtension(dartFileName)}${extension}');

File _getFile(String filename) {
  Uri fileUri = new Uri.file(p.join(_testFilesDir, filename));
  return new File.fromUri(fileUri);
}

final String _testFilesDir = p.join(_scriptDir(), 'test_files');

String _scriptDir() =>
    p.dirname(currentMirrorSystem().findLibrary(#compare_to_golden).uri.path);

Format golden files during test.

library compare_to_golden;

import 'dart:async';
import 'dart:io';
import 'dart:mirrors';

import 'package:dart_style/src/dart_formatter.dart';
import 'package:path/path.dart' as p;
import 'package:test/test.dart';

Future compareSummaryFileToGolden(String dartFileName,
    {String summaryExtension, String goldenExtension}) async {
  var input = getFile(dartFileName, summaryExtension);
  var golden = getFile(dartFileName, goldenExtension);

  final formattedInput = _formatter.format(await input.readAsString());
  final formattedGolden = _formatter.format(await golden.readAsString());
  expect(formattedInput, formattedGolden);
}

File getFile(String dartFileName, String extension) =>
    _getFile('${p.withoutExtension(dartFileName)}${extension}');

File _getFile(String filename) {
  Uri fileUri = new Uri.file(p.join(_testFilesDir, filename));
  return new File.fromUri(fileUri);
}

final String _testFilesDir = p.join(_scriptDir(), 'test_files');

String _scriptDir() =>
    p.dirname(currentMirrorSystem().findLibrary(#compare_to_golden).uri.path);

final _formatter = new DartFormatter();


Add core transcode decision icon widget.

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

import '../helpers/color_palette_helper.dart';

class TranscodeDecisionIcon extends StatelessWidget {
  final String transcodeDecision;

  const TranscodeDecisionIcon({
    Key key,
    @required this.transcodeDecision,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return _mapTranscodeDecisionToIcon(transcodeDecision);
  }
}

FaIcon _mapTranscodeDecisionToIcon(String transcodeDecision) {
  switch (transcodeDecision) {
    case ('transcode'):
      return FaIcon(
        FontAwesomeIcons.server,
        size: 15,
        color: TautulliColorPalette.not_white,
      );
    case ('copy'):
      return FaIcon(
        FontAwesomeIcons.stream,
        size: 18,
        color: TautulliColorPalette.not_white,
      );
    case ('direct play'):
      return FaIcon(
        FontAwesomeIcons.playCircle,
        size: 17,
        color: TautulliColorPalette.not_white,
      );
    default:
      return FaIcon(
        FontAwesomeIcons.questionCircle,
        size: 17,
        color: TautulliColorPalette.not_white,
      );
  }
}


" plugin/plugin.ctrlp.vim

" Customize the path of the cache files
let g:ctrlp_cache_dir = g:vim_home . '/tmp/ctrlp'

" Allow to prefix <C-p> with a count to start in a specific mode
let g:ctrlp_cmd = 'exe get(["CtrlPMixed", "CtrlPBuffer", "CtrlPModified", "CtrlPMRU"], v:count)'

" Avoid adding a prefix to each entry in the list
let g:ctrlp_line_prefix = ''

" Open all selected files as hidden buffers
let g:ctrlp_open_multiple_files = 'ijr'

" Use `The Silver Searcher` if available
if executable('ag')
  let g:ctrlp_user_command = 'ag %s
    \ --literal
    \ --nocolor
    \ --nogroup
    \ --depth 40
    \ --files-with-matches
    \ --skip-vcs-ignores
    \ -g ""'
endif

" Search symbols in current file
nnoremap <Leader>r :CtrlPBufTag<CR>

Use CtrlP instead of CtrlPMixed

" plugin/plugin.ctrlp.vim

" Customize the path of the cache files
let g:ctrlp_cache_dir = g:vim_home . '/tmp/ctrlp'

" Allow to prefix <C-p> with a count to start in a specific mode
let g:ctrlp_cmd = 'exe get(["CtrlP", "CtrlPBuffer", "CtrlPMRU"], v:count)'

" Avoid adding a prefix to each entry in the list
let g:ctrlp_line_prefix = ''

" Open all selected files as hidden buffers
let g:ctrlp_open_multiple_files = 'ijr'

" Use `The Silver Searcher` if available
if executable('ag')
  let g:ctrlp_user_command = 'ag %s
    \ --literal
    \ --nocolor
    \ --nogroup
    \ --depth 40
    \ --files-with-matches
    \ --skip-vcs-ignores
    \ -g ""'
endif

" Search symbols in current file
nnoremap <Leader>r :CtrlPBufTag<CR>


setlocal tabstop=4
setlocal shiftwidth=4
setlocal softtabstop=4
setlocal noexpandtab

" Disable using templates for new Go files
let g:go_template_autocreate = 0

" Use goimports when saving
let g:go_fmt_command = 'goimports'

" Enable extra highlighting options
let g:go_highlight_types = 1
let g:go_highlight_extra_types = 1
let g:go_highlight_functions = 1
let g:go_highlight_methods = 1
let g:go_highlight_operators = 1

let g:go_metalinter_autosave = 1
let g:go_metalinter_autosave_enabled = ['golint']

Add typecheck to autosave linters

setlocal tabstop=4
setlocal shiftwidth=4
setlocal softtabstop=4
setlocal noexpandtab

" Disable using templates for new Go files
let g:go_template_autocreate = 0

" Use goimports when saving
let g:go_fmt_command = 'goimports'

" Enable extra highlighting options
let g:go_highlight_types = 1
let g:go_highlight_extra_types = 1
let g:go_highlight_functions = 1
let g:go_highlight_methods = 1
let g:go_highlight_operators = 1

let g:go_metalinter_autosave = 1
let g:go_metalinter_autosave_enabled = ['typecheck', 'golint']


let g:deoplete#enable_at_startup = 1

Enable omni complete for jsx files

let g:deoplete#enable_at_startup = 1

let g:deoplete#omni_patterns = {}
let g:deoplete#omni_patterns['javascript.jsx'] = '[^. *\t]\.\w*'


let g:syntastic_ruby_checkers = ['rubocop']
let g:syntastic_ruby_rubocop_args = '--auto-correct'

let g:syntastic_javascript_checkers = ['eslint']
let g:syntastic_javascript_eslint_args = '--fix'

set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*

let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 1

let g:syntastic_warning_symbol = '⚠'
let g:syntastic_error_symbol = '💩'

Remove Syntastic statusline addition that caused blank statusline

let g:syntastic_ruby_checkers = ['rubocop']
let g:syntastic_ruby_rubocop_args = '--auto-correct'

let g:syntastic_javascript_checkers = ['eslint']
let g:syntastic_javascript_eslint_args = '--fix'

let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 1

let g:syntastic_warning_symbol = '⚠'
let g:syntastic_error_symbol = '💩'


" Only do this when not done yet for this buffer
if exists("b:did_ftplugin")
  finish
endif
let b:did_ftplugin = 1

setlocal textwidth=140
setlocal shiftwidth=2
setlocal softtabstop=2
setlocal expandtab
setlocal formatoptions=tcqr

" Operator notation: transforms a.b(c) to a b c
nmap <leader>s. f.r<space>f(ds(i <esc>

Tweak ftplugin, add visual column at 80 chars

" Only do this when not done yet for this buffer
if exists("b:did_ftplugin")
  finish
endif
let b:did_ftplugin = 1

setlocal shiftwidth=2
setlocal softtabstop=2
setlocal expandtab
setlocal formatoptions=tcqr

" Higlight the 80's line
setlocal colorcolumn=80

" Operator notation: transforms a.b(c) to a b c
nmap <buffer> <leader>s. f.r<space>f(ds(i <esc>


"" Wrapping
set textwidth=79                " Set wrap width to 79 characters

Set ts/sts/sw=4 and noexpandtab for Python

"" Wrapping
set textwidth=79                " Set wrap width to 79 characters

"" Whitespace
set tabstop=4                   " Set literal tab width and display
set softtabstop=4               " Set tab width for insertion and <BS>
set shiftwidth=4                " Set CTRL-T, > (add indent) & CTRL-D, < (remove indent) widths
set noexpandtab                 " Ensure tabs are not expanded to spaces


" Use Nerdfont for GUI
" Clone https://github.com/ryanoasis/nerd-fonts
" ./install.sh SourceCodePro
set guifont=DejaVuSansMonoForPowerline\ Nerd\ Font\ 13

" Remove left and right scrollbars
set guioptions-=L
set guioptions-=R

" Default size
set lines=40
set columns=120

Use 14 font size by default

" Use Nerdfont for GUI
" Clone https://github.com/ryanoasis/nerd-fonts
" ./install.sh SourceCodePro
set guifont=DejaVuSansMonoForPowerline\ Nerd\ Font\ 14

" Remove left and right scrollbars
set guioptions-=L
set guioptions-=R

" Default size
set lines=40
set columns=120


map <leader>tn :tabnew<CR>
map <leader>to :tabonly<CR>
map <leader>tc :tabclose<CR>
map <leader>tm :tabmove
map <leader>te :tabedit <c-r>=expand("%:p:h")<CR>/

nnoremap <C-t> :tabnew<CR>
nnoremap <A-left> <Esc>:tabprevious<CR>
nnoremap <A-right> <Esc>:tabnext<CR>
nnoremap <A-down> <Esc>:tabnew<CR>

Disable command-t to open new tab

map <leader>tn :tabnew<CR>
map <leader>to :tabonly<CR>
map <leader>tc :tabclose<CR>
map <leader>tm :tabmove
map <leader>te :tabedit <c-r>=expand("%:p:h")<CR>/

" nnoremap <C-t> :tabnew<CR>
nnoremap <A-left> <Esc>:tabprevious<CR>
nnoremap <A-right> <Esc>:tabnext<CR>
nnoremap <A-down> <Esc>:tabnew<CR>


call plug#begin('~/.vim/plugged')

  Plug 'bling/vim-airline' " Display more information in statusline. [vim-airline]
  Plug 'tpope/vim-fugitive' " This is a Git helper plugin. [vim-fugitive]
  Plug 'airblade/vim-gitgutter' " Show the diff of changes in the gutter. [vim-gitgutter]
  Plug 'godlygeek/tabular' " I mostly use this for Markdown tables. [tabular]
  Plug 'tpope/vim-markdown' " Highlight with markdown syntax. [vim-markdown]
  Plug 'tpope/vim-sensible'

call plug#end()

" [vim-plug]: https://github.com/junegunn/vim-plug
" [vim-airline]: https://github.com/bling/vim-airline
" [vim-fugitive]: https://github.com/tpope/vim-fugitive
" [vim-gitgutter]: https://github.com/airblade/vim-gitgutter
" [tabular]: https://github.com/godlygeek/tabular
" [vim-markdown]: https://github.com/tpope/vim-markdown

Use vim-airline/vim-airline instead of bling

call plug#begin('~/.vim/plugged')

  Plug 'vim-airline/vim-airline' " Display more information in statusline. [vim-airline]
  Plug 'vim-airline/vim-airline-themes' " Themes for vim-airline.
  Plug 'tpope/vim-fugitive' " This is a Git helper plugin. [vim-fugitive]
  Plug 'airblade/vim-gitgutter' " Show the diff of changes in the gutter. [vim-gitgutter]
  Plug 'godlygeek/tabular' " I mostly use this for Markdown tables. [tabular]
  Plug 'tpope/vim-markdown' " Highlight with markdown syntax. [vim-markdown]
  Plug 'tpope/vim-sensible'

call plug#end()

" [vim-plug]: https://github.com/junegunn/vim-plug
" [vim-airline]: https://github.com/vim-airline/vim-airline
" [vim-fugitive]: https://github.com/tpope/vim-fugitive
" [vim-gitgutter]: https://github.com/airblade/vim-gitgutter
" [tabular]: https://github.com/godlygeek/tabular
" [vim-markdown]: https://github.com/tpope/vim-markdown


" Tabulation
set expandtab
set shiftwidth=2
set tabstop=2
set softtabstop=2

let g:erlang_highlight_bif = 1

Change Erlang indentation to something more standard (4 spaces)

" Tabulation
set expandtab
set shiftwidth=4
set tabstop=4
set softtabstop=4

" App configuration FIXME
au BufNewFile,BufRead *.app.src set ft=erlang

let g:erlang_highlight_bif = 1


syntax region doneItem start='^\z(\s*\)\S.*DONE.*$' skip='^\z1\s' end='^'me=e-1
syntax region doneItem start='^\z(\s*\)\S.*WONTDO.*$' skip='^\z1\s' end='^'me=e-1
highlight link doneItem Ignore

syntax region projectSupport start='\v^\z(\s*)\*\s' skip='^\v\z1\s' end='\v^'me=e-1 contains=VimwikiLink
highlight link projectSupport Comment

Enable highlighting Support material as DONE

syntax region projectSupport start='\v^\z(\s*)\*\s' skip='^\v\z1\s' end='\v^'me=e-1 contains=VimwikiLink
highlight link projectSupport Comment

syntax region doneItem start='^\z(\s*\)\S.*DONE.*$' skip='^\z1\s' end='^'me=e-1
syntax region doneItem start='^\z(\s*\)\S.*WONTDO.*$' skip='^\z1\s' end='^'me=e-1
highlight link doneItem Ignore


" deoplete
call deoplete#custom#var('omni', 'input_patterns', { 'cpp': ['[^. *\t]\.\w*','[^. *\t]\::\w*','[^. *\t]\->\w*','#include\s*[<"][^>"]*'] })

" Linters
let g:ale_linters.c = ['gcc']
let g:ale_linters.cpp = ['gcc']

" Autoformat
let g:ale_fixers.c = ['clang-format']
let g:ale_fixers.cpp = ['clang-format']

Make fswitch recognise .cc files

" deoplete
call deoplete#custom#var('omni', 'input_patterns', { 'cpp': ['[^. *\t]\.\w*','[^. *\t]\::\w*','[^. *\t]\->\w*','#include\s*[<"][^>"]*'] })

" Linters
let g:ale_linters.c = ['gcc']
let g:ale_linters.cpp = ['gcc']

" Autoformat
let g:ale_fixers.c = ['clang-format']
let g:ale_fixers.cpp = ['clang-format']

" fswitch
au BufEnter *.h let b:fswitchdst = 'cpp,cc,c'
au BufEnter *.cc let b:fswitchdst = 'h'


" Recognise files with unusual file extensions
au BufRead,BufNewFile *.md set filetype=markdown
au BufNewFile,BufRead *.ejs set filetype=html
au BufNewFile,BufRead *.html set filetype=htmldjango
au BufNewFile,BufRead *.sh.j2 set ft=sh
au BufNewFile,BufRead *.wsgi set ft=python
au BufNewFile,BufRead *.wsgi.j2 set ft=python
au BufNewFile,BufRead *.py.j2 set ft=python
au BufNewFile,BufRead *.muttrc set ft=muttrc

Mark "Jenkinsfile" files as using language: Groovy

" Recognise files with unusual file extensions
au BufRead,BufNewFile *.md set filetype=markdown
au BufNewFile,BufRead *.ejs set filetype=html
au BufNewFile,BufRead *.html set filetype=htmldjango
au BufNewFile,BufRead *.sh.j2 set ft=sh
au BufNewFile,BufRead *.wsgi set ft=python
au BufNewFile,BufRead *.wsgi.j2 set ft=python
au BufNewFile,BufRead *.py.j2 set ft=python
au BufNewFile,BufRead *.muttrc set ft=muttrc
au BufNewFile,BufRead Jenkinsfile set ft=groovy


if ! has('python') && ! has('python3')
	echohl ErrorMsg
	echomsg 'You need vim compiled with Python 3.3 or Python 2.7 support for Powerline to work. Please consult the documentation for more details.'
	echohl None
	finish
endif

python <<EOF
from __future__ import absolute_import
import sys, vim
sys.path.append(vim.eval('expand("<sfile>:h:h:h:h:h")'))
from powerline.bindings.vim import source_plugin
source_plugin()
EOF

Revert to previous way of sourcing vim plugin

if ! has('python') && ! has('python3')
	echohl ErrorMsg
	echomsg 'You need vim compiled with Python 3.3 or Python 2.7 support for Powerline to work. Please consult the documentation for more details.'
	echohl None
	finish
endif

python import sys, vim
python sys.path.append(vim.eval('expand("<sfile>:h:h:h:h:h")'))

source <sfile>:h:h/powerline.vim


" File:        github-issues.vim
" Version:     1.0.0
" Description: Pulls github issues into Vim
" Maintainer:  Jonathan Warner <jaxbot@gmail.com> <http://github.com/jaxbot>
" Homepage:    http://jaxbot.me/
" Repository:  https://github.com/jaxbot/github-issues.vim
" License:     Copyright (C) 2014 Jonathan Warner
"              Released under the MIT license
"			   ======================================================================
"

if exists("g:github_issues_loaded") || &cp
    finish
endif
let g:github_issues_loaded = "shi"

python <<NOMAS
import sys
import threading
import time
import vim
import json
import urllib2

def pullGithubAPIData():
	data = urllib2.urlopen("https://api.github.com/repos/jaxbot/chrome-devtools.vim/issues").read()
	issues = json.loads(data)
	for issue in issues:
		vim.current.buffer.append(str(issue["number"]) + " " + issue["title"])
	vim.command("1delete _")
NOMAS

function! s:getGithubIssues()
	silent edit github://issues
	normal ggdG
	set buftype=nofile
	nnoremap <buffer> <cr> :normal ^y$<cr><C-^>p
	python pullGithubAPIData()
endfunction

command!        -nargs=0 GIssues             call s:getGithubIssues()

Make window load as split, then close

" File:        github-issues.vim
" Version:     1.0.0
" Description: Pulls github issues into Vim
" Maintainer:  Jonathan Warner <jaxbot@gmail.com> <http://github.com/jaxbot>
" Homepage:    http://jaxbot.me/
" Repository:  https://github.com/jaxbot/github-issues.vim
" License:     Copyright (C) 2014 Jonathan Warner
"              Released under the MIT license
"			   ======================================================================
"

if exists("g:github_issues_loaded") || &cp
    finish
endif
let g:github_issues_loaded = "shi"

python <<NOMAS
import sys
import threading
import time
import vim
import json
import urllib2

def pullGithubAPIData():
	data = urllib2.urlopen("https://api.github.com/repos/jaxbot/chrome-devtools.vim/issues").read()
	issues = json.loads(data)
	for issue in issues:
		vim.current.buffer.append(str(issue["number"]) + " " + issue["title"])
	vim.command("1delete _")
NOMAS

function! s:getGithubIssues()
	silent split github://issues
	normal ggdG
	set buftype=nofile
	nnoremap <buffer> <cr> :normal ^y$<cr>:q<cr><C-w>pp
	python pullGithubAPIData()
endfunction

command!        -nargs=0 GIssues             call s:getGithubIssues()


" Author: richard marmorstein <https://github.com/twitchard>
" Description: plugin for Psalm, static analyzer for PHP

call ale#Set('php_psalm_executable', 'psalm')

function! ale_linters#php#psalm#Handle(buffer, lines) abort
    " Matches patterns like the following:
    let l:pattern = '^.*:\(\d\+\):\(\d\+\):\(\w\+\) - \(.*\)$'
    let l:output = []

    for l:match in ale#util#GetMatches(a:lines, l:pattern)
        call add(l:output, {
        \   'lnum': l:match[1] + 0,
        \   'text': l:match[4],
        \   'type': l:match[3][:0] is# 'e' ? 'E' : 'W',
        \})
    endfor

    return l:output
endfunction

call ale#linter#Define('php', {
\   'name': 'psalm',
\   'command': '%e --diff --output-format=emacs %s',
\   'executable_callback': ale#VarFunc('php_psalm_executable'),
\   'callback': 'ale_linters#php#psalm#Handle',
\   'lint_file': 1,
\})

Update Psalm plugin to use LSP mode

" Author: Matt Brown <https://github.com/muglug>
" Description: plugin for Psalm, static analyzer for PHP

call ale#Set('psalm_langserver_executable', 'psalm-language-server')
call ale#Set('psalm_langserver_use_global', get(g:, 'ale_use_global_executables', 0))

function! ale_linters#php#psalm#GetProjectRoot(buffer) abort
    let l:git_path = ale#path#FindNearestDirectory(a:buffer, '.git')

    return !empty(l:git_path) ? fnamemodify(l:git_path, ':h:h') : ''
endfunction

call ale#linter#Define('php', {
\   'name': 'psalm',
\   'lsp': 'stdio',
\   'executable_callback': ale#node#FindExecutableFunc('psalm_langserver', [
\       'vendor/bin/psalm-language-server',
\   ]),
\   'command': '%e',
\   'project_root_callback': 'ale_linters#php#psalm#GetProjectRoot',
\})


abbrev tableflip (╯°□°）╯︵ ┻━┻)

Add some abbreviations & stop markdown auto-opening

abbrev tableflip (╯°□°）╯︵ ┻━┻)
abbrev nre nREPL
abbrev taht that
abbrev superceded superseded
abbrev Superceded Superseded

let g:markdown_composer_open_browser = 0


set autoindent       " automatically indent new lines
set formatoptions+=o " continue comment marker in new lines
set textwidth=78     " hard-wrap long lines as you type them
set tabstop=4        " render TABs using this many spaces
set expandtab        " insert spaces when TAB is pressed
set softtabstop=4    " ... this many spaces
set shiftwidth=4     " indentation amount for < and > commands

" repeat last character to the maximum width of current line
nnoremap <Leader>_ :execute 's/.$/'. repeat('&', &textwidth+1) .'/'<Enter>
      \:execute 's/\%>'. &textwidth .'v.//g'<Enter>

" insert or update section separator at end of current line
nmap <Leader>- A-<Esc><Leader>_

" format current line as a top-level heading in markdown (uses `z marker)
nmap <Leader>= mzyypVr=:.+1g/^=\+/d<Enter>`z

" format current line as a second-level heading in markdown (uses `z marker)
nmap <Leader>+ mzyypVr-:.+1g/^-\+/d<Enter>`z

Revert "VIm: use 4-spaces indentation"

set autoindent       " automatically indent new lines
set formatoptions+=o " continue comment marker in new lines
set textwidth=78     " hard-wrap long lines as you type them
set tabstop=2        " render TABs using this many spaces
set expandtab        " insert spaces when TAB is pressed
set softtabstop=2    " ... this many spaces
set shiftwidth=2     " indentation amount for < and > commands

" repeat last character to the maximum width of current line
nnoremap <Leader>_ :execute 's/.$/'. repeat('&', &textwidth+1) .'/'<Enter>
      \:execute 's/\%>'. &textwidth .'v.//g'<Enter>

" insert or update section separator at end of current line
nmap <Leader>- A-<Esc><Leader>_

" format current line as a top-level heading in markdown (uses `z marker)
nmap <Leader>= mzyypVr=:.+1g/^=\+/d<Enter>`z

" format current line as a second-level heading in markdown (uses `z marker)
nmap <Leader>+ mzyypVr-:.+1g/^-\+/d<Enter>`z


set nocompatible
filetype off

call plug#begin()

Plug 'majutsushi/tagbar'
Plug 'valloric/youcompleteme'
Plug 'vim-airline/vim-airline'
Plug 'vim-syntastic/syntastic'

call plug#end()

filetype plugin indent on

syntax on

nmap <F8> :TagbarToggle<CR>

let g:airline_powerline_fonts = 1
let g:airline#extensions#syntastic#enabled = 1
let g:airline#extensions#tagbar#enabled = 1

let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 1
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0

Add a few more plugins for nvim

set nocompatible
filetype off

call plug#begin()

Plug 'majutsushi/tagbar'
Plug 'rust-lang/rust.vim'
Plug 'scrooloose/nerdtree'
Plug 'tyrannicaltoucan/vim-quantum'
Plug 'valloric/youcompleteme'
Plug 'vim-airline/vim-airline'
Plug 'vim-syntastic/syntastic'

call plug#end()

filetype plugin indent on

syntax on

nmap <F8> :TagbarToggle<CR>

let g:airline_powerline_fonts = 1
let g:airline#extensions#syntastic#enabled = 1
let g:airline#extensions#tagbar#enabled = 1

let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 1
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0

set background=dark
set termguicolors
let g:quantum_black = 1
let g:quantum_italics = 1
colorscheme quantum


" ~/.vim/colors.vim

if has('syntax')
  " Enable syntax highlight.
  syntax enable
  " Set 256 color terminal support.
  set t_Co=256
  " Set dark background.
  set background=dark

  " Enable True Color (vim >= 8.0).
  if has('termguicolors')
    set termguicolors
  endif
endif

Fix color glitch when using Vim with tmux

" ~/.vim/colors.vim

if has('syntax')
  " Enable syntax highlight.
  syntax enable
  " Set 256 color terminal support.
  set t_Co=256
  " Set dark background.
  set background=dark

  " Enable True Color (vim >= 8.0).
  if has('termguicolors')
    " Set Vim-specific sequences for RGB colors.
    let &t_8f = "\<Esc>[38;2;%lu;%lu;%lum"
    let &t_8b = "\<Esc>[48;2;%lu;%lu;%lum"

    set termguicolors
  endif
endif


" config/misc.vim

" Create a new auto command group
augroup dotmisc

  " Remove all commands for the current group
  au!

  " Jump to last known position
  " @see help docs on last-position-jump
  au BufReadPost *
    \ if (&ft !~ '^git\c') && line("'\"") > 1 && line("'\"") <= line("$") |
    \   execute "normal! g`\"" |
    \ endif

  " Close help window with <q>
  au FileType help nn <silent><buffer> q :q<CR>
  au FileType help nn <silent><buffer> Q :q<CR>

augroup end

" Load matchit.vim which is shipped with
" vim in version 7.x
if !exists('g:loaded_matchit') && findfile('bundle/matchit.vim', &rtp) ==# ''
  runtime! macros/matchit.vim
endif

Add vim command to open current file in MacVim

" config/misc.vim

" -------------------------------------
" Table of Contents
" -------------------------------------
" 1. MacVim
" 2. MatchIt
" 3. Autocommands
" -------------------------------------

" 1. MacVim --------------------------- {{{1

if executable('mvim')

  " Custom function  to open a give set
  " of files in MacVim
  function! s:OpenInMacVim(...)
    let files = ''

    " Escape file names. Use current file
    " if no file name was given.
    if (a:0 == 0)
      let files = expand('%:p')
    else
      for file in a:000
        if (filereadable(file))
          let files .= ' ' . shellescape(file, 1)
        endif
      endfor
    endif

    " Save the current file and open MacVim
    write
    echom files
    silent execute "!mvim " . files

    " Redraw the current window
    redraw!
  endfunction

  " Custom command to open MacVim with a
  " given set of files
  command -nargs=* -complete=file MacVim call <sid>OpenInMacVim(<f-args>)
  command -nargs=* -complete=file Mvim MacVim <args>

endif

" 2. MatchIt -------------------------- {{{1

" Load matchit.vim which is shipped with
" vim in version 7.x
if !exists('g:loaded_matchit') && findfile('bundle/matchit.vim', &rtp) ==# ''
  runtime! macros/matchit.vim
endif

" 3. Autocommands --------------------- {{{1

" Create a new auto command group
augroup dotmisc

  " Remove all commands
  au!

  " Jump to last known position
  " @see help docs on last-position-jump
  au BufReadPost *
    \ if (&ft !~ '^git\c') && line("'\"") > 1 && line("'\"") <= line("$") |
    \   execute "normal! g`\"" |
    \ endif

  " Close help window with <q>
  au FileType help nn <silent><buffer> q :q<CR>
  au FileType help nn <silent><buffer> Q :q<CR>

augroup end


" Use deoplete for tab completion.
let g:deoplete#enable_at_startup = 1
" Enable icons in completions from LSP.
let g:deoplete#lsp#use_icons_for_candidates=v:true
" Make supertab play nice with deoplete's default ordering.
let g:SuperTabDefaultCompletionType = "<c-n>"
" Avoid Deoplete's annoying candidtate preview popup
autocmd FileType python setlocal completeopt-=preview
" Don't autocomplete in the telescope search box
autocmd FileType TelescopePrompt call deoplete#custom#buffer_option('auto_complete', v:false)

Remove obsolete remnant of telescope


" Backspace is managed by vim-sensible, but I need it here too because some
" plugins depend on it during start up.
set backspace=indent,eol,start

" Enable line numbers.
set number

" Enable invisible characters.
set list

" More natural splitting.
set splitbelow
set splitright

" Set a default indent, but vim-sleuth should adjust it.
set tabstop=4

" Enable mouse. Great for resizing windows and keeping co-workers sane.
set mouse=a

" Disable swap files.
set noswapfile

" Disable the completion preview window.
set completeopt-=preview

" Make session files minimal.
set sessionoptions=blank,curdir,folds,help,tabpages,winsize

Make sure Vim uses 4 spaces by default

" Backspace is managed by vim-sensible, but I need it here too because some
" plugins depend on it during start up.
set backspace=indent,eol,start

" Enable line numbers.
set number

" Enable invisible characters.
set list

" More natural splitting.
set splitbelow
set splitright

" Set a default indent, but vim-sleuth should adjust it.
set tabstop=4
set shiftwidth=4
set expandtab

" Enable mouse. Great for resizing windows and keeping co-workers sane.
set mouse=a

" Disable swap files.
set noswapfile

" Disable the completion preview window.
set completeopt-=preview

" Make session files minimal.
set sessionoptions=blank,curdir,folds,help,tabpages,winsize


let g:deoplete#enable_at_startup = 1
autocmd InsertLeave,CompleteDone * if pumvisible() == 0 | pclose | endif
set completeopt-=preview

Add deoplete config for Clojure

let g:deoplete#enable_at_startup = 1
autocmd InsertLeave,CompleteDone * if pumvisible() == 0 | pclose | endif
set completeopt-=preview

let g:deoplete#keyword_patterns = {}
let g:deoplete#keyword_patterns.clojure = '[\w!$%&*+/:<=>?@\^_~\-\.#]*'


" Open Vundle config quickly {{{
  nnoremap <Leader>vu :e ~/.vim/config/00-vundle.vim<CR>
" }}}

" Run Hammer to preview this buffer {{{
  nmap <Leader>p :Hammer<CR>
" }}}

" NERDTree {{{
  let NERDTreeIgnore=['\.rbc$', '\~$']
  map <Leader>n :NERDTreeToggle<CR>
" }}}

" Rake.vim {{{
  nmap <leader>a :AV<CR>
  nmap <c-a> :A<CR>
" }}}

" Bufexplorer {{
  nnoremap <C-B> :BufExplorer<cr>
" }}

" PickHEX {{{
  imap <D-C> <c-o>:PickHEX<CR>
  nmap <D-C> :PickHEX<CR>
" }}}

" Syntastic {{{
  " Mark syntax errors with :signs
  let g:syntastic_enable_signs=1
  let g:syntastic_quiet_warnings=1
" }}}

" NERDCommenter {{{
  let NERDSpaceDelims=1
" }}}

" Powerline {{{
  " Use fancy symbols
  let g:Powerline_symbols = 'fancy'
" }}}

Use consistent capitalisation in Vim config

" Open Vundle config quickly {{{
  nnoremap <Leader>vu :e ~/.vim/config/00-vundle.vim<CR>
" }}}

" Run Hammer to preview this buffer {{{
  nmap <Leader>p :Hammer<CR>
" }}}

" NERDTree {{{
  let NERDTreeIgnore=['\.rbc$', '\~$']
  map <Leader>n :NERDTreeToggle<CR>
" }}}

" Rake.vim {{{
  nmap <Leader>a :AV<CR>
  nmap <C-a> :A<CR>
" }}}

" Bufexplorer {{
  nnoremap <C-B> :BufExplorer<cr>
" }}

" PickHEX {{{
  imap <D-C> <c-o>:PickHEX<CR>
  nmap <D-C> :PickHEX<CR>
" }}}

" Syntastic {{{
  " Mark syntax errors with :signs
  let g:syntastic_enable_signs=1
  let g:syntastic_quiet_warnings=1
" }}}

" NERDCommenter {{{
  let NERDSpaceDelims=1
" }}}

" Powerline {{{
  " Use fancy symbols
  let g:Powerline_symbols = 'fancy'
" }}}


"--------------------------------------
" GUI SETTINGS
"--------------------------------------

set guioptions-=m   " Disable menu bar
set guioptions-=e   " Disable GUI tabs
set guioptions-=T   " Disable toolbar
set guioptions-=r   " Disable right scrollbar
set guioptions-=R   " Disable right scrollbar if vsplit
set guioptions-=l   " Disable left scrollbar
set guioptions-=L   " Disable left scrollbar if vsplit

colorscheme liquidcarbon

set guifont=Monaco:h12

Configure GUI font for Linux environment

"--------------------------------------
" GUI SETTINGS
"--------------------------------------

set guioptions-=m   " Disable menu bar
set guioptions-=e   " Disable GUI tabs
set guioptions-=T   " Disable toolbar
set guioptions-=r   " Disable right scrollbar
set guioptions-=R   " Disable right scrollbar if vsplit
set guioptions-=l   " Disable left scrollbar
set guioptions-=L   " Disable left scrollbar if vsplit

colorscheme liquidcarbon

if has("gui_macvim")
    set guifont=Monaco:h12
else
    set guifont=Ubuntu\ Mono\ 10
endif


" Handle messages received from the server.
function! lsc#dispatch#message(message) abort
  if has_key(a:message, 'method')
    if a:message['method'] ==? 'textDocument/publishDiagnostics'
      let params = a:message['params']
      let file_path = substitute(params['uri'], '^file://', '', 'v')
      call lsc#diagnostics#setForFile(file_path, params['diagnostics'])
    else
      echom 'Got notification: '.a:message['method'].
          \ ' params: '.string(a:message['params'])
    endif
  elseif has_key(a:message, 'error')
    echom 'Got error: '.string(a:message['error'])
  elseif has_key(a:message, 'result')
    let call_id = a:message['id']
    if has_key(s:callbacks, call_id)
      call s:callbacks[call_id](a:message['result'])
      unlet s:callbacks[call_id]
    endif
  else
    echom 'Unknown message type: '.string(a:message)
  endif
endfunction

if !exists('s:callbacks')
  let s:callbacks = {}
endif

function! lsc#dispatch#registerCallback(id, callback) abort
  let s:callbacks[a:id] = a:callback
endfunction

Store callbacks in a List

" Handle messages received from the server.
function! lsc#dispatch#message(message) abort
  if has_key(a:message, 'method')
    if a:message['method'] ==? 'textDocument/publishDiagnostics'
      let params = a:message['params']
      let file_path = substitute(params['uri'], '^file://', '', 'v')
      call lsc#diagnostics#setForFile(file_path, params['diagnostics'])
    else
      echom 'Got notification: '.a:message['method'].
          \ ' params: '.string(a:message['params'])
    endif
  elseif has_key(a:message, 'error')
    echom 'Got error: '.string(a:message['error'])
  elseif has_key(a:message, 'result')
    let call_id = a:message['id']
    if has_key(s:callbacks, call_id)
      call s:callbacks[call_id][0](a:message['result'])
      unlet s:callbacks[call_id]
    endif
  else
    echom 'Unknown message type: '.string(a:message)
  endif
endfunction

if !exists('s:callbacks')
  let s:callbacks = {}
endif

function! lsc#dispatch#registerCallback(id, callback) abort
  let s:callbacks[a:id] = [a:callback]
endfunction


nnoremap <buffer> <Left> :CoqToCursor<CR>
nnoremap <buffer> <Right> :CoqToCursor<CR>
nnoremap <buffer> <Up> :CoqUndo<CR>
nnoremap <buffer> <Down> :CoqNext<CR>

inoremap <buffer> <Left> <C-o>:CoqToCursor<CR>
inoremap <buffer> <Right> <C-o>:CoqToCursor<CR>
inoremap <buffer> <Up> <C-o>:CoqUndo<CR>
inoremap <buffer> <Down> <C-o>:CoqNext<CR>

Add vim binding to go to last evaulated in Coq

nnoremap <buffer> <Left> :GotoDot<CR>
nnoremap <buffer> <Right> :CoqToCursor<CR>
nnoremap <buffer> <Up> :CoqUndo<CR>
nnoremap <buffer> <Down> :CoqNext<CR>

inoremap <buffer> <Left> <C-o>:GotoDot<CR>
inoremap <buffer> <Right> <C-o>:CoqToCursor<CR>
inoremap <buffer> <Up> <C-o>:CoqUndo<CR>
inoremap <buffer> <Down> <C-o>:CoqNext<CR>


if !exists('g:terraform_align')
  let g:terraform_align = 0
endif

if g:terraform_align && exists(':Tabularize')
  inoremap <buffer> <silent> = =<Esc>:call <SID>terraformalign()<CR>a
  function! s:terraformalign()
    let p = '^.*=[^>]*$'
    if exists(':Tabularize') && getline('.') =~# '^.*=' && (getline(line('.')-1) =~# p || getline(line('.')+1) =~# p)
      let column = strlen(substitute(getline('.')[0:col('.')],'[^=]','','g'))
      let position = strlen(matchstr(getline('.')[0:col('.')],'.*=\s*\zs.*'))
      Tabularize/=/l1
      normal! 0
      call search(repeat('[^=]*=',column).'\s\{-\}'.repeat('.',position),'ce',line('.'))
    endif
  endfunction
endif

Add ability to fold sections

if !exists('g:terraform_align')
  let g:terraform_align = 0
endif

if g:terraform_align && exists(':Tabularize')
  inoremap <buffer> <silent> = =<Esc>:call <SID>terraformalign()<CR>a
  function! s:terraformalign()
    let p = '^.*=[^>]*$'
    if exists(':Tabularize') && getline('.') =~# '^.*=' && (getline(line('.')-1) =~# p || getline(line('.')+1) =~# p)
      let column = strlen(substitute(getline('.')[0:col('.')],'[^=]','','g'))
      let position = strlen(matchstr(getline('.')[0:col('.')],'.*=\s*\zs.*'))
      Tabularize/=/l1
      normal! 0
      call search(repeat('[^=]*=',column).'\s\{-\}'.repeat('.',position),'ce',line('.'))
    endif
  endfunction
endif

function! TerraformFolds()
  let thisline = getline(v:lnum)
  if match(thisline, '^resource') >= 0
    return ">1"
  elseif match(thisline, '^provider') >= 0
    return ">1"
  elseif match(thisline, '^module') >= 0
    return ">1"
  elseif match(thisline, '^variable') >= 0
    return ">1"
  else
    return "="
  endif
endfunction
setlocal foldmethod=expr
setlocal foldexpr=TerraformFolds()
setlocal foldlevel=1

function! TerraformFoldText()
  let foldsize = (v:foldend-v:foldstart)
  return getline(v:foldstart).' ('.foldsize.' lines)'
endfunction
setlocal foldtext=TerraformFoldText()

"inoremap <space> <C-O>za
nnoremap <space> za
onoremap <space> <C-C>za
vnoremap <space> zf


" Vim plugin that displays tags in a window, ordered by class etc.
NeoBundle "majutsushi/tagbar", {
      \ 'lazy': 1,
      \ 'autoload' : {'commands': 'TagbarToggle'}
      \}

Fix airline loading on some files

" Vim plugin that displays tags in a window, ordered by class etc.
NeoBundle "majutsushi/tagbar", {
      \ 'autoload' : {'on_cmd': 'TagbarToggle'}
      \}


nmap <S-Enter> O<Esc>j
nmap <CR> o<Esc>k
map <leader>rf :%!astyle<cr>

highlight Pmenu ctermbg=Blue ctermfg=White
highlight PmenuSel ctermbg=Magenta ctermfg=Black

Fix tab complete background and highlight colors

nmap <S-Enter> O<Esc>j
nmap <CR> o<Esc>k
map <leader>rf :%!astyle<cr>

highlight Pmenu ctermbg=Blue ctermfg=White
highlight PmenuSel ctermbg=Magenta ctermfg=Black

imap jj <Esc>


" this is mostly a matter of taste. but LaTeX looks good with just a bit
" of indentation.
set sw=2
" TIP: if you write your \label's as \label{fig:something}, then if you
" type in \ref{fig: and press <C-n> you will automatically cycle through
" all the figure labels. Very useful!
set iskeyword+=:

Disable Indentline in Tex Files

" this is mostly a matter of taste. but LaTeX looks good with just a bit
" of indentation.
set sw=2
" TIP: if you write your \label's as \label{fig:something}, then if you
" type in \ref{fig: and press <C-n> you will automatically cycle through
" all the figure labels. Very useful!
set iskeyword+=:
let g:indentLine_enabled = 0


let g:lightline = {
            \ 'active': {
            \   'left': [ [ 'mode', 'paste'],
            \              [ 'gitdiff', 'gitbranch', 'filename','cocstatus', 'currentfunction' ] ],
            \ 'right':
            \   [ ['lineinfo'], ['percent'], ['fileencoding', 'filetype']  ]
            \ },
            \ 'component' : {
            \   'lineinfo' : "%{printf('%03d/%03d', line('.'),  line('$'))}"
            \ },
            \ 'component_function': {
            \   'gitbranch': 'FugitiveHead',
            \ },
            \ 'component_expand': {
            \   'gitdiff': 'lightline#gitdiff#get',
            \ },
            \ 'component_type': {
            \   'gitdiff': 'middle',
            \ },
            \ }

let g:lightline#gitdiff#indicator_added = '+'
let g:lightline#gitdiff#indicator_deleted = '-'
let g:lightline#gitdiff#indicator_modified = '~'
let g:lightline#gitdiff#separator = ' '
let g:lightline#gitdiff#show_empty_indicators = 1

Remove cocstatus function from lightline

let g:lightline = {
            \ 'active': {
            \   'left': [ [ 'mode', 'paste'],
            \              [ 'gitdiff', 'gitbranch', 'filename', 'currentfunction' ] ],
            \ 'right':
            \   [ ['lineinfo'], ['percent'], ['fileencoding', 'filetype']  ]
            \ },
            \ 'component' : {
            \   'lineinfo' : "%{printf('%03d/%03d', line('.'),  line('$'))}"
            \ },
            \ 'component_function': {
            \   'gitbranch': 'FugitiveHead',
            \ },
            \ 'component_expand': {
            \   'gitdiff': 'lightline#gitdiff#get',
            \ },
            \ 'component_type': {
            \   'gitdiff': 'middle',
            \ },
            \ }

let g:lightline#gitdiff#indicator_added = '+'
let g:lightline#gitdiff#indicator_deleted = '-'
let g:lightline#gitdiff#indicator_modified = '~'
let g:lightline#gitdiff#separator = ' '
let g:lightline#gitdiff#show_empty_indicators = 1


let g:ctrlp_working_path_mode ='a'

" let g:ctrlp_map = '<c-f>'
map <c-b> :CtrlPBuffer<cr>

let g:ctrlp_max_height = 20
let g:ctrlp_custom_ignore = 'node_modules\|^\.DS_Store\|^\.git\|^\.coffee'
let g:ctrlp_follow_symlinks = 1

Make Ctrl-P show hidden files

let g:ctrlp_working_path_mode ='a'

" let g:ctrlp_map = '<c-f>'
map <c-b> :CtrlPBuffer<cr>

let g:ctrlp_max_height = 20
let g:ctrlp_custom_ignore = 'node_modules\|^\.DS_Store\|^\.git\|^\.coffee'
let g:ctrlp_follow_symlinks = 1
let g:ctrlp_show_hidden = 1


let g:nerdtree_tabs_open_on_gui_startup=0
let g:nerdtree_tabs_open_on_new_tab=0

map <Leader>n :NERDTreeMirrorToggle<CR>

Update NERDTree-tabs to open NERDTree in new tabs and use global NERDTree open

let g:nerdtree_tabs_open_on_gui_startup=0
let g:nerdtree_tabs_open_on_new_tab=1

map <Leader>n :NERDTreeTabsToggle<CR>


Plug 'kana/vim-textobj-user'
Plug 'kana/vim-textobj-line'
Plug 'kana/vim-textobj-fold'
Plug 'glts/vim-textobj-comment'
Plug 'jasonlong/vim-textobj-css'
Plug 'whatyouhide/vim-textobj-xmlattr'
Plug 'chaoren/vim-wordmotion'
Plug 'tommcdo/vim-exchange'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-surround'
" Plug 'machakann/vim-sandwich'
Plug 'kana/vim-operator-user'
Plug 'kana/vim-operator-replace'
Plug 'deris/vim-operator-insert'

Switch from commentary to tcomment

Plug 'kana/vim-textobj-user'
Plug 'kana/vim-textobj-line'
Plug 'kana/vim-textobj-fold'
Plug 'glts/vim-textobj-comment'
Plug 'jasonlong/vim-textobj-css'
Plug 'whatyouhide/vim-textobj-xmlattr'
Plug 'chaoren/vim-wordmotion'
Plug 'tommcdo/vim-exchange'
Plug 'tomtom/tcomment_vim'
Plug 'tpope/vim-surround'
" Plug 'machakann/vim-sandwich'
Plug 'kana/vim-operator-user'
Plug 'kana/vim-operator-replace'
Plug 'deris/vim-operator-insert'


call my_plugin#add('sonph/onehalf', {'rtp': 'vim/'})

function! Hook_post_source_onehalf()
  colorscheme onehalflight
  hi! link IncSearch PMenuSel
endf

Disable onehalf for linux console

call my_plugin#add('sonph/onehalf', {'rtp': 'vim/'})

function! Hook_post_source_onehalf()
  if $TERM !=# 'linux'
    colorscheme onehalflight
    hi! link IncSearch PMenuSel
  endif
endf


" Avoid excessive line length in commit comments
setlocal textwidth=70
" Highlight these lines
exec '2match Todo /\%>' .  &textwidth . 'v.\+/'
" Undo the match when leaving, and remove the hook then too.
augroup gitcommit
  au!
  au BufLeave * execute "2match none | augroup gitcommit | au!" | execute "augroup END"
augroup END
" Do a spell check
set spell

Use two spaces for a tab in commit messages when edited in vim

" Avoid excessive line length in commit comments
setlocal textwidth=70
" Highlight these lines
exec '2match Todo /\%>' .  &textwidth . 'v.\+/'
" Undo the match when leaving, and remove the hook then too.
augroup gitcommit
  au!
  au BufLeave * execute "2match none | augroup gitcommit | au!" | execute "augroup END"
augroup END

" Do a spell check
set spell

" Use two spaces for a tab
set tabstop=2


" Quickfix/Location-list specific settings

" Is this a location-list or a quickfix-list?
let b:qf_isloclist = len(getloclist(0)) > 0 ? 1 : 0

" Close using 'q'
" Jump to entry and close using 'O'
if b:qf_isloclist
    nnoremap <buffer><silent> q :lclose<CR>
    nnoremap <buffer><silent> O <CR>:lclose<CR>
else
    nnoremap <buffer><silent> q :cclose<CR>
    nnoremap <buffer><silent> O <CR>:cclose<CR>
endif

Disable cursorline in quickfix and location lists.

" Quickfix/Location-list specific settings

" Is this a location-list or a quickfix-list?
let b:qf_isloclist = len(getloclist(0)) > 0 ? 1 : 0

" Close using 'q'
" Jump to entry and close using 'O'
if b:qf_isloclist
    nnoremap <buffer><silent> q :lclose<CR>
    nnoremap <buffer><silent> O <CR>:lclose<CR>
else
    nnoremap <buffer><silent> q :cclose<CR>
    nnoremap <buffer><silent> O <CR>:cclose<CR>
endif

" Disable cursorline (colorscheme takes care of highlighting)
setlocal nocursorline


if g:at_google
    Glug youcompleteme-google
else
    Plugin 'Valloric/YouCompleteMe'
endif

nnoremap <C-y>g :YcmCompleter GoTo<CR>
nnoremap <C-y>d :YcmCompleter GoToDeclaration<CR>
nnoremap <C-y>f :YcmCompleter GoToDefinition<CR>

let g:ycm_confirm_extra_conf = 0

Add two more YCM key bindings.

if g:at_google
    Glug youcompleteme-google
else
    Plugin 'Valloric/YouCompleteMe'
endif

nnoremap <C-y>g :YcmCompleter GoTo<CR>
nnoremap <C-y>d :YcmCompleter GoToDeclaration<CR>
nnoremap <C-y>f :YcmCompleter GoToDefinition<CR>
nnoremap <C-y>r :YcmForceCompileAndDiagnostics<CR>
nnoremap <C-y>R :YcmRestartServer<CR>

let g:ycm_confirm_extra_conf = 0


syntax keyword flowTypeKeyword type nextgroup=flowTypeIdentifier
syntax region flowTypeIdentifier contained start=/\%(\s\+\k\)/ end=/=\@=/ nextgroup=jsFlowTypeValue
syntax match flowObjectProps contained /[0-9a-zA-Z_$?]*\(\s*:\)\@=/ skipwhite skipempty nextgroup=jsFlowTypeValue containedin=jsFlowObject

highlight link jsThis jsReturn
highlight link jsStorageClass jsClassKeyword
highlight link jsModuleKeywords jsClassKeyword
highlight link jsModuleOperators jsClassKeyword
highlight link jsArrowFunction NONE
highlight link jsImport jsClassKeyword
highlight link jsFrom jsClassKeyword
highlight link jsExport jsClassKeyword
highlight link jsExportDefault jsFuncName
highlight link jsFlowTypeKeyword Keyword
highlight link flowTypeKeyword Keyword
highlight link flowTypeIdentifier Function
highlight link flowObjectProps Special

Tweak highlighting of JavaScript keywords

syntax keyword flowTypeKeyword type nextgroup=flowTypeIdentifier
syntax region flowTypeIdentifier contained start=/\%(\s\+\k\)/ end=/=\@=/ nextgroup=jsFlowTypeValue
syntax match flowObjectProps contained /[0-9a-zA-Z_$?]*\(\s*:\)\@=/ skipwhite skipempty nextgroup=jsFlowTypeValue containedin=jsFlowObject

highlight link jsThis jsReturn
highlight link jsStorageClass jsClassKeyword
highlight link jsModuleKeywords jsClassKeyword
highlight link jsModuleOperators jsClassKeyword
highlight link jsArrowFunction NONE
highlight link jsImport jsClassKeyword
highlight link jsFrom jsClassKeyword
highlight link jsExport jsClassKeyword
highlight link jsExportDefault jsFuncName
highlight link jsFunction Keyword
highlight link jsDo Keyword
highlight link jsRepeat Keyword
highlight link jsFlowTypeKeyword Keyword
highlight link flowTypeKeyword Keyword
highlight link flowTypeIdentifier Function
highlight link flowObjectProps Special


if exists('loaded_gogo') || &cp
	finish
endif
let loaded_gogo = 1

" Quickly launch input data
if has("win32")
    if &shellslash
        " Forwardslashes are great, but cmd.exe won't handle them. Convert to
        " backslash.
        function s:Gogo(filename)
            let fname = substitute(fnamemodify(a:filename, ':p'), '/', '\\', 'g')
            exec '! start '. fname
        endfunction
        command! -nargs=1 -complete=file Gogo silent call s:Gogo("<args>")
    else
        command! -nargs=1 -complete=file Gogo ! start <args>
    endif
elseif has("macunix")
    " TODO: Does this work as expected? Does it need q-quoting?
    command! -nargs=1 -complete=file Gogo ! open <args>
elseif has("unix")
    " TODO: Does this work as expected? Does it need q-quoting?
    command! -nargs=1 -complete=file Gogo ! xdg-open <args>
endif

Support paths containing spaces on Windows

if exists('loaded_gogo') || &cp
	finish
endif
let loaded_gogo = 1

" Quickly launch input data
if has("win32")
    if &shellslash
        " Forwardslashes are great, but cmd.exe won't handle them. Convert to
        " backslash.
        function! s:Gogo(filename)
            let fname = substitute(fnamemodify(a:filename, ':p'), '/', '\\', 'g')
            exec '! start "" "'. fname .'"'
        endfunction
        command! -nargs=1 -complete=file Gogo silent call s:Gogo("<args>")
    else
        command! -nargs=1 -complete=file Gogo ! start "" "<args>"
    endif
elseif has("macunix")
    " TODO: Does this work as expected? Does it need q-quoting?
    command! -nargs=1 -complete=file Gogo ! open <args>
elseif has("unix")
    " TODO: Does this work as expected? Does it need q-quoting?
    command! -nargs=1 -complete=file Gogo ! xdg-open <args>
endif


" from http://vimcasts.org/episodes/tidying-whitespace/
function! Preserve(command)
  " Preparation: save last search, and cursor position.
  let save_cursor = getpos('.')
  let last_search = getreg('/')
  " Do the business:
  execute a:command
  " Clean up: restore previous search history, and cursor position
  call setpos('.', save_cursor)
  call setreg('/', last_search)
endfunction

Add :DiffOrig function to show diff btw last save and current edits

" from http://vimcasts.org/episodes/tidying-whitespace/
function! Preserve(command)
  " Preparation: save last search, and cursor position.
  let save_cursor = getpos('.')
  let last_search = getreg('/')
  " Do the business:
  execute a:command
  " Clean up: restore previous search history, and cursor position
  call setpos('.', save_cursor)
  call setreg('/', last_search)
endfunction

" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
  command DiffOrig vert new | set bt=nofile | r ++edit # | 0d_ | diffthis
        \ | wincmd p | diffthis
endif


augroup filetypes
    autocmd!
    autocmd BufRead,BufNewFile .jshintrc set filetype=javascript
    autocmd BufRead,BufNewFile *.es6 set filetype=javascript
    autocmd BufRead,BufNewFile *.nasm set filetype=nasm
    autocmd BufRead,BufNewFile *.tc set filetype=c
    autocmd BufRead,BufNewFile *.webapp set filetype=json
    autocmd BufRead,BufNewFile Podfile set filetype=ruby
augroup END

Use *.pyi as a Python file

augroup filetypes
    autocmd!
    autocmd BufRead,BufNewFile .jshintrc set filetype=javascript
    autocmd BufRead,BufNewFile *.es6 set filetype=javascript
    autocmd BufRead,BufNewFile *.nasm set filetype=nasm
    autocmd BufRead,BufNewFile *.pyi set filetype=python
    autocmd BufRead,BufNewFile *.tc set filetype=c
    autocmd BufRead,BufNewFile *.webapp set filetype=json
    autocmd BufRead,BufNewFile Podfile set filetype=ruby
augroup END


" tab
set expandtab
set tabstop=4
set shiftwidth=4
set softtabstop=4
set smarttab

" appearance
set showmatch
set list
set listchars=tab:>.,trail:_,eol:↲,extends:>,precedes:<,nbsp:%

" control
set backspace=start,eol,indent
set whichwrap=b,s,[,],,~

Add tab setting for HTML.

" tab
set expandtab
set tabstop=4
set shiftwidth=4
set softtabstop=4
set smarttab

augroup fileTypeIndent
    autocmd!
    autocmd BufNewFile,BufRead *.html setlocal tabstop=2 shiftwidth=2 softtabstop=2
augroup END

" appearance
set showmatch
set list
set listchars=tab:>.,trail:_,eol:↲,extends:>,precedes:<,nbsp:%

" control
set backspace=start,eol,indent
set whichwrap=b,s,[,],,~


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Override settings for vim-autoformat
" let g:formatprg_args_javascript='%'

" Define formatters for supertypes and some overrides
let g:formatters_javascript_jsx = ['prettier']
let g:formatters_jsx = ['prettier']
let g:formatters_javascript = ['prettier']
let g:formatters_javascriptreact = ['prettier']
let g:formatters_typescriptreact = ['prettier']

" Autoformat on write
au BufWrite * :Autoformat

autocmd FileType snippets,terraform,vim,yaml,sh,zsh,conf let b:autoformat_autoindent=0
autocmd FileType vim let g:autoformat_remove_trailing_spaces = 0

Fix autoformat config for Prettier 2.x

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Override settings for vim-autoformat
" let g:formatprg_args_javascript='%'

" Define formatters for supertypes and some overrides
let g:formatters_javascript = ['prettier']
let g:formatters_javascript_jsx = ['prettier']
let g:formatters_javascriptreact = ['prettier']
let g:formatters_jsx = ['prettier']
let g:formatters_typescript = ['prettier']
let g:formatters_typescriptreact = ['prettier']

" 2.0 doesn't know about `--stdin`, this just copy, pastes, and removes that
" flag from the default definition in the plugin
let g:formatdef_prettier = '"prettier --stdin-filepath ".expand("%:p").(&textwidth ? " --print-width ".&textwidth : "")." --tab-width=".shiftwidth()'

" Autoformat on write
au BufWrite * :Autoformat

autocmd FileType snippets,terraform,vim,yaml,sh,zsh,conf let b:autoformat_autoindent=0
autocmd FileType vim let g:autoformat_remove_trailing_spaces = 0


"mark syntax errors with :signs
let g:syntastic_enable_signs=1
"automatically jump to the error when saving the file
let g:syntastic_auto_jump=0
"show the error list automatically
let g:syntastic_auto_loc_list=1
let g:syntastic_ruby_checkers=['rubocop', 'mri']

Use jshint for JS syntax checking

" Mark syntax errors with :signs
let g:syntastic_enable_signs=1

" Automatically jump to the error when saving the file
let g:syntastic_auto_jump=0

" Show the error list automatically
let g:syntastic_auto_loc_list=1

" Syntax checkers
let g:syntastic_ruby_checkers=['rubocop', 'mri']
let g:syntastic_python_checkers=['pep8', 'pylint', 'python']
let g:syntastic_javascript_checkers=['jshint']


" Copyright 2011 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" fmt.vim: Vim command to format Go files with gofmt.
"
" This filetype plugin add a new commands for go buffers:
"
"   :Fmt
"
"       Filter the current Go buffer through gofmt.
"       It tries to preserve cursor position and avoids
"       replacing the buffer with stderr output.
"

command! -buffer Fmt call s:GoFormat()

function! s:GoFormat()
    let view = winsaveview()
    %!gofmt
    if v:shell_error
        %| " output errors returned by gofmt
           " TODO(dchest): perhaps, errors should go to quickfix
        undo
	echohl Error | echomsg "Gofmt returned error" | echohl None
    endif
    call winrestview(view)
endfunction

" vim:ts=4:sw=4:et

Send GoFmt errors to a location list

" Copyright 2011 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" fmt.vim: Vim command to format Go files with gofmt.
"
" This filetype plugin add a new commands for go buffers:
"
"   :Fmt
"
"       Filter the current Go buffer through gofmt.
"       It tries to preserve cursor position and avoids
"       replacing the buffer with stderr output.
"

command! -buffer Fmt call s:GoFormat()

function! s:GoFormat()
    let view = winsaveview()
    silent %!gofmt
    if v:shell_error
        let errors = []
        for line in getline(1, line('$'))
            let tokens = matchlist(line, '^\(.\{-}\):\(\d\+\):\(\d\+\)\s*\(.*\)')
            if !empty(tokens)
                call add(errors, {"filename": @%,
                                 \"lnum":     tokens[2],
                                 \"col":      tokens[3],
                                 \"text":     tokens[4]})
            endif
        endfor
        if empty(errors)
            % | " Couldn't detect gofmt error format, output errors
        endif
        undo
        if !empty(errors)
            call setloclist(0, errors, 'r')
        endif
        echohl Error | echomsg "Gofmt returned error" | echohl None
    endif
    call winrestview(view)
endfunction

" vim:ts=4:sw=4:et


" Set up ALE (linting)
let g:airline#extensions#ale#enabled = 1
let g:ale_sign_column_always = 1
let g:ale_linters = {
\   'bash': ['shellcheck', 'bashate'],
\   'docker': ['hadolint'],
\   'javascript': ['eslint'],
\   'html': ['alex'],
\   'mail': ['alex'],
\   'markdown': ['alex'],
\   'python': ['isort'],
\   'yaml': ['yamllint'],
\}

let g:neoformat_enabled_rust = ['rustfmt']
let g:neoformat_enabled_python = ['isort', 'black']
let g:neoformat_enabled_sql = ['sqlfmt']
let g:neoformat_sql_sqlfmt = {
\   'exe': 'sqlfmt',
\   'args': ['--align full', '--use-spaces'],
\   'stdin': 1,
\}
let g:neoformat_enabled_html = ['html-beautify']
let g:neoformat_run_all_formatters = 1
let g:neoformat_enabled_terraform = ['terraform']
command F :Neoformat

Work around loss of highlighting after autoformat

" Set up ALE (linting)
let g:airline#extensions#ale#enabled = 1
let g:ale_sign_column_always = 1
let g:ale_linters = {
\   'bash': ['shellcheck', 'bashate'],
\   'docker': ['hadolint'],
\   'javascript': ['eslint'],
\   'html': ['alex'],
\   'mail': ['alex'],
\   'markdown': ['alex'],
\   'python': ['isort'],
\   'yaml': ['yamllint'],
\}

let g:neoformat_enabled_rust = ['rustfmt']
let g:neoformat_enabled_python = ['isort', 'black']
let g:neoformat_enabled_sql = ['sqlfmt']
let g:neoformat_sql_sqlfmt = {
\   'exe': 'sqlfmt',
\   'args': ['--align full', '--use-spaces'],
\   'stdin': 1,
\}
let g:neoformat_enabled_html = ['html-beautify']
let g:neoformat_run_all_formatters = 1
let g:neoformat_enabled_terraform = ['terraform']
command F :Neoformat <bar> :Semshi highlight


" ==========================================
" Syntastic settings

let g:syntastic_javascript_syntax_checker = "jshint"
let g:syntastic_coffee_coffeelint_args = "--csv --file $HOME/.coffeelint.json"
let g:syntastic_ruby_checkers = ['mri', 'rubocop']
let g:syntastic_check_on_open = 0
let g:syntastic_scss_checkers = ['scss_lint']

Add Cane to Ruby syntax checking

" ==========================================
" Syntastic settings

let g:syntastic_javascript_syntax_checker = "jshint"
let g:syntastic_coffee_coffeelint_args = "--csv --file $HOME/.coffeelint.json"
let g:syntastic_ruby_checkers = ['mri', 'rubocop', 'cane']
let g:syntastic_check_on_open = 0
let g:syntastic_scss_checkers = ['scss_lint']


setlocal spell

highlight htmlItalic cterm=italic
highlight htmlBold cterm=bold

" Highlight words to avoid in tech writing
" http://css-tricks.com/words-avoid-educational-writing/
" https://github.com/pengwynn/dotfiles
highlight TechWordsToAvoid ctermbg=red ctermfg=white
function! MatchTechWordsToAvoid()
  match TechWordsToAvoid /\c\(obviously\|basically\|simply\|of\scourse\|clearly\|just\|everyone\sknows\|however\|so,\|easy\)/
endfunction
call MatchTechWordsToAvoid()
autocmd BufWinEnter *.md call MatchTechWordsToAvoid()
autocmd InsertEnter *.md call MatchTechWordsToAvoid()
autocmd InsertLeave *.md call MatchTechWordsToAvoid()
autocmd BufWinLeave *.md call clearmatches()
command! -nargs=* Wrap set wrap linebreak nolist

" en and em dashes
inoremap <buffer> --<space> –<space>
inoremap <buffer> ---<space> —<space>

Tweak en and em dash mappings.

setlocal spell

highlight htmlItalic cterm=italic
highlight htmlBold cterm=bold

" Highlight words to avoid in tech writing
" http://css-tricks.com/words-avoid-educational-writing/
" https://github.com/pengwynn/dotfiles
highlight TechWordsToAvoid ctermbg=red ctermfg=white
function! MatchTechWordsToAvoid()
  match TechWordsToAvoid /\c\(obviously\|basically\|simply\|of\scourse\|clearly\|just\|everyone\sknows\|however\|so,\|easy\)/
endfunction
call MatchTechWordsToAvoid()
autocmd BufWinEnter *.md call MatchTechWordsToAvoid()
autocmd InsertEnter *.md call MatchTechWordsToAvoid()
autocmd InsertLeave *.md call MatchTechWordsToAvoid()
autocmd BufWinLeave *.md call clearmatches()
command! -nargs=* Wrap set wrap linebreak nolist

" en and em dashes
inoremap <buffer> --<space> –
inoremap <buffer> ---<space> —


autocmd FileType markdown
      \ let b:dispatch = 'octodown %'
autocmd FileType python
      \ let b:start = executable('ipython') ? 'ipython -i %' : 'python -i %' |
      \ let b:dispatch = 'python %'
autocmd FileType ruby
      \ let b:start = executable('pry') ? 'pry -r "%:p"' : 'irb -r "%:p"' |
      \ if expand('%') =~# '_test\.rb$' |
      \   let b:dispatch = 'testrb %' |
      \ elseif expand('%') =~# '_spec\.rb$' |
      \   let b:dispatch = 'rspec %' |
      \ elseif !exists('b:dispatch') |
      \   let b:dispatch = 'ruby -wc %' |
      \ endif
autocmd FileType java
      \ let b:dispatch = 'javac %'
autocmd FileType scala
      \ let b:start = 'sbt' |
      \ let b:dispatch = 'sbt'
autocmd FileType javascript
      \ let b:start = 'node' |
      \ let b:dispatch = 'grunt test'

nnoremap <silent> <leader>d :Dispatch<CR>
nnoremap <silent> <leader>s :Start<CR>

Add better settings for scala dispatch

autocmd FileType markdown
      \ let b:dispatch = 'octodown %'
autocmd FileType python
      \ let b:start = executable('ipython') ? 'ipython -i %' : 'python -i %' |
      \ let b:dispatch = 'python %'
autocmd FileType ruby
      \ let b:start = executable('pry') ? 'pry -r "%:p"' : 'irb -r "%:p"' |
      \ if expand('%') =~# '_test\.rb$' |
      \   let b:dispatch = 'testrb %' |
      \ elseif expand('%') =~# '_spec\.rb$' |
      \   let b:dispatch = 'rspec %' |
      \ elseif !exists('b:dispatch') |
      \   let b:dispatch = 'ruby -wc %' |
      \ endif
autocmd FileType java
      \ let b:dispatch = 'javac %'
autocmd FileType scala
      \ let b:start = 'sbt console' |
      \ let b:dispatch = 'sbt run'
autocmd FileType javascript
      \ let b:start = 'node' |
      \ let b:dispatch = 'grunt test'

nnoremap <silent> <leader>d :Dispatch<CR>
nnoremap <silent> <leader>s :Start<CR>


" Don't automatically comment the next/previous line after hitting 'o' or 'O'
setlocal formatoptions-=o

" highlight ruby whitespace errors
let ruby_space_errors = 1
let g:rubycomplete_buffer_loading = 1
let g:rubycomplete_classes_in_global = 1

" set the 'foldmethod' option to 'syntax' and allow folding of
" classes, modules, methods, code blocks, heredocs and comments.
let ruby_fold = 1

" Gary Bernhardt's hashrocket
inoremap <c-l> <space>=><space>

" Use v or # to get a variable interpolation (inside of a string)}
" ysiw#   Wrap the token under the cursor in #{}
" v...s#  Wrap the selection in #{}
let b:surround_118 = "#{ \r }"    " v
let b:surround_35  = "#{ \r }"    " #

" Select text in an ERb file with visual mode and then press s- or s=
" Or yss- to do entire line.
let b:surround_45 = "<% \r -%>"   " -
let b:surround_61 = "<%= \r %>"   " =

" The compiler plugins contain instructions which allow Vim to run the
" specified source file with an appropriate executable, parse any errors, and
" jump to the corresponding error location if required.
compiler ruby

Add abbrevs for TODO:, FIXME:, OPTIMIZE:, etc

" Don't automatically comment the next/previous line after hitting 'o' or 'O'
setlocal formatoptions-=o

" highlight ruby whitespace errors
let ruby_space_errors = 1
let g:rubycomplete_buffer_loading = 1
let g:rubycomplete_classes_in_global = 1

" set the 'foldmethod' option to 'syntax' and allow folding of
" classes, modules, methods, code blocks, heredocs and comments.
let ruby_fold = 1

" Gary Bernhardt's hashrocket
inoremap <c-l> <space>=><space>

" Use v or # to get a variable interpolation (inside of a string)}
" ysiw#   Wrap the token under the cursor in #{}
" v...s#  Wrap the selection in #{}
let b:surround_118 = "#{ \r }"    " v
let b:surround_35  = "#{ \r }"    " #

" Select text in an ERb file with visual mode and then press s- or s=
" Or yss- to do entire line.
let b:surround_45 = "<% \r -%>"   " -
let b:surround_61 = "<%= \r %>"   " =

" The compiler plugins contain instructions which allow Vim to run the
" specified source file with an appropriate executable, parse any errors, and
" jump to the corresponding error location if required.
compiler ruby

" From https://github.com/bbatsov/ruby-style-guide#comment-annotations
inoreabbrev <buffer> todo TODO:
inoreabbrev <buffer> fixme FIXME:
inoreabbrev <buffer> optimize OPTIMIZE:
inoreabbrev <buffer> hack HACK:
inoreabbrev <buffer> review REVIEW:


set textwidth=0

set autoindent
set nosmartindent

" use TAB character when TAB key is pressed
set noexpandtab

" number of spaces to show for a TAB
set tabstop=4

" number of spaces for indent with >>
set shiftwidth=4

" number of spaces for a tab in editing operations
set softtabstop=4

" F1 comment line
map <F1> I<!-- A -->j

" F2 uncomment line
map <F2> :s/\v^(\s*)\<!-- (.+)\s*--\>/\1\2/<enter>

" F3 create blank comment ready for insertion
map <F3> i<!--   -->
k5li

" html5 template
map <F4> gg:r /home/conan/csoft/library/html/html5.simple.html<enter>ggdd

Update tab settings to comply with CSW rules

set textwidth=0

set autoindent
set nosmartindent

" use TAB character when TAB key is pressed
set expandtab

" number of spaces to show for a TAB
set tabstop=2

" number of spaces for indent with >>
set shiftwidth=2

" number of spaces for a tab in editing operations
set softtabstop=2

" F1 comment line
map <F1> I<!-- A -->j

" F2 uncomment line
map <F2> :s/\v^(\s*)\<!-- (.+)\s*--\>/\1\2/<enter>

" F3 create blank comment ready for insertion
map <F3> i<!--   -->
k5li

" html5 template
map <F4> gg:r /home/conan/csoft/library/html/html5.simple.html<enter>ggdd


"
" vim-javascript
"

" Enable JSDoc syntax highlighting
let g:javascript_plugin_jsdoc = 1

" JS conceal characters
let g:javascript_conceal_function = "ƒ"
let g:javascript_conceal_null = "ø"
let g:javascript_conceal_this = "@"
let g:javascript_conceal_return = "⇚"
let g:javascript_conceal_undefined = "¿"
let g:javascript_conceal_NaN = "ℕ"
let g:javascript_conceal_prototype = "¶"
let g:javascript_conceal_static = "•"
let g:javascript_conceal_super = "Ω"
let g:javascript_conceal_arrow_function = "⇒"

Enable other NGDock and JSX syntax highlighting

"
" vim-javascript
"

" Enable JSDoc syntax highlighting
let g:javascript_plugin_jsdoc = 1

" Enable NGDock syntax highlighting
" NOTE: Requires that JSDoc is enabled
let g:javascript_plugin_ngdoc = 1

" Enable Flow syntax highlighting
let g:javascript_plugin_flow = 1

" JS conceal characters
let g:javascript_conceal_function = "ƒ"
let g:javascript_conceal_null = "ø"
let g:javascript_conceal_this = "@"
let g:javascript_conceal_return = "⇚"
let g:javascript_conceal_undefined = "¿"
let g:javascript_conceal_NaN = "ℕ"
let g:javascript_conceal_prototype = "¶"
let g:javascript_conceal_static = "•"
let g:javascript_conceal_super = "Ω"
let g:javascript_conceal_arrow_function = "⇒"


source /Users/xgjo/.vim/bundle/powerline/powerline/ext/vim/powerline.vim

let g:Powerline_symbols='fancy'
let g:Powerline_colorscheme='solarized256'

Use /Users/xgjo instead of explicit path to my home dir

source $HOME/.vim/bundle/powerline/powerline/ext/vim/powerline.vim

let g:Powerline_symbols='fancy'
let g:Powerline_colorscheme='solarized256'


setlocal expandtab
ino <buffer><silent> ( ()<Left>
ino <buffer><silent> [ []<Left>
ino <buffer><silent> { {}<Left>
au BufWritePre *.py :%s/\s\+$//e

Support for pylint and pep8.

setlocal expandtab
ino <buffer><silent> ( ()<Left>
ino <buffer><silent> [ []<Left>
ino <buffer><silent> { {}<Left>
au BufWritePre *.py :%s/\s\+$//e

function! <SID>PythonGrep(tool)
	setlocal lazyredraw
	cclose
	let l:grepformat_save = &grepformat
	let l:grepprogram_save = &grepprg
	setlocal grepformat&vim
	let &grepformat = '%f:%l:%m'
	if a:tool == "pylint"
		let &grepprg = 'pylint --output-format=parseable --reports=no'
	elseif a:tool == "pep8"
		let &grepprg = 'pep8'
	else
		echohl WarningMsg
		echo "PythonGrep Error: Unknown Tool"
		echohl none
	endif
	if &readonly == 0 | update | endif
	silent! grep! %
	let &grepformat = l:grepformat_save
	let &grepprg = l:grepprogram_save
	" Open cwindow
	execute 'belowright copen'
	setlocal nolazyredraw
	redraw!
endfunction

ino <F3> <C-o>:call <SID>PythonGrep('pylint')<CR>
nno <F3> :call <SID>PythonGrep('pylint')<CR>
ino <F4> <C-o>:call <SID>PythonGrep('pep8')<CR>
nno <F4> :call <SID>PythonGrep('pep8')<CR>


function! CommandTWithFlush()
  CommandTFlush
  CommandT
endfunction

function! UpdateTags()
  if exists('b:git_dir')
    call system('cd "'.b:git_dir.'/.." && nice /usr/local/bin/ctags --tag-relative -R -f .git/tags --exclude=.git --langmap="ruby:+.rake.builder.rjs" .')
  endif
endfunction

Set colorcolumn to the current textwidth.

function! CommandTWithFlush()
  CommandTFlush
  CommandT
endfunction

function! UpdateTags()
  if exists('b:git_dir')
    call system('cd "'.b:git_dir.'/.." && nice /usr/local/bin/ctags --tag-relative -R -f .git/tags --exclude=.git --langmap="ruby:+.rake.builder.rjs" .')
  endif
endfunction

" Set colorcolumn to the current textwidth or fallback to the specified column.
function! ColorColumnAtTextWidth(column)
  if &textwidth > 0
    execute ':set cc=' . &textwidth
  else
    execute ':set cc=' . a:column
  endif
endfunction

" Set colorcolumn to the current textwidth or fallback to 80
autocmd BufWinEnter * call ColorColumnAtTextWidth(80)


let perl_fold = 1
let perl_nofold_packages = 1
setlocal foldlevel=100
setlocal foldcolumn=1
compiler perl
let g:perl_compiler_force_warnings = 0
let b:ale_linters = ['perlcritic']
let b:ale_fixers = ['perltidy']

Use spaces for indentation in Perl

let perl_fold = 1
let perl_nofold_packages = 1
setlocal foldlevel=100
setlocal foldcolumn=1
compiler perl
let g:perl_compiler_force_warnings = 0
let b:ale_linters = ['perlcritic']
let b:ale_fixers = ['perltidy']
setlocal expandtab


let g:syntastic_enable_signs=1

Choose JSCS as the JS linter if .jscsrc is present

let g:syntastic_enable_signs=1
autocmd FileType javascript let b:syntastic_checkers = findfile('.jscsrc', '.;') != '' ? ['jscs'] : ['jshint']


" set rtp+=~/.vim/bundle/vundle/
" call vundle#rc()

Bundle 'gmarik/vundle'
Bundle 'scrooloose/nerdtree'
Bundle 'nathanaelkane/vim-command-w'
Bundle 'nathanaelkane/snipmate-snippets'
Bundle 'nathanaelkane/vim-indent-guides'
Bundle 'wincent/Command-T'
Bundle 'bronson/vim-trailing-whitespace'
Bundle 'tpope/vim-rails'

Bundle 'bufkill.vim'
Bundle 'bufexplorer.zip'
Bundle 'vimwiki'
Bundle 'haml.zip'
Bundle 'ack.vim'
Bundle 'snipMate'
Bundle 'tomtom/tcomment_vim'
Bundle 'EasyMotion'

Add upAndDown vim plugin for bubbling lines.

" set rtp+=~/.vim/bundle/vundle/
" call vundle#rc()

Bundle 'gmarik/vundle'
Bundle 'scrooloose/nerdtree'
Bundle 'nathanaelkane/vim-command-w'
Bundle 'nathanaelkane/snipmate-snippets'
Bundle 'nathanaelkane/vim-indent-guides'
Bundle 'wincent/Command-T'
Bundle 'bronson/vim-trailing-whitespace'
Bundle 'tpope/vim-rails'
Bundle 'upAndDown'

Bundle 'bufkill.vim'
Bundle 'bufexplorer.zip'
Bundle 'vimwiki'
Bundle 'haml.zip'
Bundle 'ack.vim'
Bundle 'snipMate'
Bundle 'tomtom/tcomment_vim'
Bundle 'EasyMotion'


iabbrev bb require 'pry'; binding.pry<Esc>
iabbrev BB require 'byebug'; byebug<Esc>
iabbrev Bb binding.irb<Esc>

setlocal foldmethod=indent

" {{{ ALE config
if executable('rubocop')
  let b:ale_linters = ['rubocop']
  let b:ale_fixers = ['rubocop']
elseif executable('prettier')
  let b:ale_linters = ['standardrb']
  let b:ale_fixers = ['standardrb']
endif
"}}}

Fix rubocop / standardrb config

iabbrev bb require 'pry'; binding.pry<Esc>
iabbrev BB require 'byebug'; byebug<Esc>
iabbrev Bb binding.irb<Esc>

setlocal foldmethod=indent

" {{{ ALE config
function! s:set_ale_config_for_ruby() abort
  let l:root_path = system('git rev-parse --show-toplevel 2>/dev/null | tr -d "\n"')
  if l:root_path == ''
    let l:root_path = getcwd()
  endif
  if executable('rubocop') && filereadable(l:root_path . '/.rubocop.yml')
    let b:ale_linters = ['rubocop']
    let b:ale_fixers = ['rubocop']
  elseif executable('standardrb')
    let b:ale_linters = ['standardrb']
    let b:ale_fixers = ['standardrb']
  endif
endfunction
call s:set_ale_config_for_ruby()
"}}}


call Pl#Theme#InsertSegment(['raw', '%{system("[[ -n \"$([[ -n " . shellescape(expand("%")) . " ]] && git status --porcelain " . shellescape(expand("%")) . ")\" ]] && echo -n +")}'],  'after', 'lineinfo')
call Pl#Theme#InsertSegment('ws_marker',  'after', 'lineinfo')

Fix Git file status when editing a file outside the current Git dir

call Pl#Theme#InsertSegment(['raw', '%{system("[[ -n \"$([[ -n " . shellescape(expand("%")) . " ]] && git status --porcelain " . shellescape(expand("%")) . " 2> /dev/null)\" ]] && echo -n +")}'],  'after', 'lineinfo')
call Pl#Theme#InsertSegment('ws_marker',  'after', 'lineinfo')


if !executable('ctags')
    finish
elseif globpath(&rtp, 'plugin/tagbar.vim') == ""
    finish
endif

function! s:SetTagbar()
    if !exists("g:tagbar_type_elm")
        let g:tagbar_type_elm = {
                    \ 'ctagstype' : 'elm',
                    \ 'kinds'     : [
                    \ 'c:contants',
                    \ 'f:functions',
                    \ 'p:ports'
                    \ ]
                    \ }
    endif
endfunction

call s:SetTagbar()

Fix typo in tagbr support

if !executable('ctags')
    finish
elseif globpath(&rtp, 'plugin/tagbar.vim') == ""
    finish
endif

function! s:SetTagbar()
    if !exists("g:tagbar_type_elm")
        let g:tagbar_type_elm = {
                    \ 'ctagstype' : 'elm',
                    \ 'kinds'     : [
                    \ 'c:constants',
                    \ 'f:functions',
                    \ 'p:ports'
                    \ ]
                    \ }
    endif
endfunction

call s:SetTagbar()


" Use Nerdfont for GUI
" Clone https://github.com/ryanoasis/nerd-fonts
" ./install.sh SourceCodePro
" set guifont=DejaVuSansMonoForPowerline\ Nerd\ Font\ 10

" Remove left and right scrollbars
set guioptions-=L
set guioptions-=R

" Remove toolbar
set guioptions-=T

" Default size
set lines=40
set columns=120

Use source code pro as default font in gvim

" Use Nerdfont for GUI
" Clone https://github.com/ryanoasis/nerd-fonts
" ./install.sh SourceCodePro
set guifont=SauceCodePro\ Nerd\ Font\ 12

" Remove left and right scrollbars
set guioptions-=L
set guioptions-=R

" Remove toolbar
set guioptions-=T

" Default size
set lines=40
set columns=120


call plug#begin('~/.local/share/nvim/plugged')

Plug 'DankNeon/vim'
Plug 'fenetikm/falcon'

call plug#end()

set termguicolors

set cursorline
set cursorcolumn

set mouse-=a

hi CursorLine cterm=reverse
hi CursorColumn cterm=reverse
hi Search cterm=reverse ctermbg=NONE
hi Visual cterm=reverse ctermbg=NONE

au FileType markdown set shiftwidth=2 tabstop=2 expandtab autoindent
au FileType sh set shiftwidth=2 tabstop=2 expandtab autoindent
au FileType yaml set shiftwidth=2 tabstop=2 expandtab autoindent

colo falcon

Set `ai` and `et` always

call plug#begin('~/.local/share/nvim/plugged')

Plug 'DankNeon/vim'
Plug 'fenetikm/falcon'

call plug#end()

set termguicolors

set cursorline
set cursorcolumn

set mouse-=a

hi CursorLine cterm=reverse
hi CursorColumn cterm=reverse
hi Search cterm=reverse ctermbg=NONE
hi Visual cterm=reverse ctermbg=NONE

au FileType markdown set shiftwidth=2 tabstop=2
au FileType sh set shiftwidth=2 tabstop=2
au FileType yaml set shiftwidth=2 tabstop=2

set expandtab autoindent

colo falcon


" ----------------------------------------
" Platform Specific Configuration
" ----------------------------------------

set shell=bash

let g:has_powerline_font = 0

let s:uname = system("uname -s")
if s:uname =~ "Darwin"
  let g:has_powerline_font = filereadable("/Library/Fonts/Meslo LG M Regular for Powerline.otf") || filereadable($HOME."/Library/Fonts/Meslo LG M Regular for Powerline.otf")
else
  let g:has_powerline_font = filereadable($HOME."/.fonts/Meslo LG M Regular for Powerline.otf") || filereadable("/usr/local/share/fonts/Meslo LG M Regular for Powerline.otf")
endif
if g:has_powerline_font
  set guifont=Meslo\ LG\ M\ for\ Powerline:h12
elseif has('gui_running')
  set guifont=Monaco:h12
else
  set guifont=Monospace:h12
endif

Add comment about airline fonts in neovim

" ----------------------------------------
" Platform Specific Configuration
" ----------------------------------------

set shell=bash

let g:has_powerline_font = 0

let s:uname = system("uname -s")
if s:uname =~ "Darwin"
  let g:has_powerline_font = filereadable("/Library/Fonts/Meslo LG M Regular for Powerline.otf") || filereadable($HOME."/Library/Fonts/Meslo LG M Regular for Powerline.otf")
else
  let g:has_powerline_font = filereadable($HOME."/.fonts/Meslo LG M Regular for Powerline.otf") || filereadable("/usr/local/share/fonts/Meslo LG M Regular for Powerline.otf")
endif
# FIXME: neovim does not correctly render powerline fonts in airline
if g:has_powerline_font
  set guifont=Meslo\ LG\ M\ for\ Powerline:h12
elseif has('gui_running')
  set guifont=Monaco:h12
else
  set guifont=Monospace:h12
endif


" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"   DESCRIPTION: Plugin settings for Vim
"        AUTHOR: Igor Kalnitsky <igor@kalnitsky.org>
" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

" XPTemplate
" ----------
let g:xptemplate_vars = 'SParg='
let g:xptemplate_brace_complete = ''

" NERDtree
" --------
let NERDTreeQuitOnOpen = 1 " close NERD Tree when file is open

" jedi-vim
" --------
let g:jedi#popup_on_dot = 1

" vim-flake8
" ----------

" clang_complete
" --------------
let g:clang_periodic_quickfix=1
let g:clang_hl_errors=1
let g:clang_use_library=1
let g:clang_user_options="-std=c++11 -Wall -Wextra -pedantic"

" QFixToggle
" ----------
let g:QFixToggle_Height = 3

" Tagbar
" ------
let g:tagbar_width = 30
let g:tagbar_autoclose = 1
let g:tagbar_autofocus = 1
let g:tagbar_iconchars = ['+', '-']

Change MaxLength of PEP8 to a new Standard.

" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"   DESCRIPTION: Plugin settings for Vim
"        AUTHOR: Igor Kalnitsky <igor@kalnitsky.org>
" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

" XPTemplate
" ----------
let g:xptemplate_vars = 'SParg='
let g:xptemplate_brace_complete = ''

" NERDtree
" --------
let NERDTreeQuitOnOpen = 1 " close NERD Tree when file is open

" jedi-vim
" --------
let g:jedi#popup_on_dot = 1

" vim-flake8
" ----------
let g:flake8_max_line_length=99 " that is in the new PEP8

" clang_complete
" --------------
let g:clang_periodic_quickfix=1
let g:clang_hl_errors=1
let g:clang_use_library=1
let g:clang_user_options="-std=c++11 -Wall -Wextra -pedantic"
let g:clang_library_path="/usr/local/lib"

" QFixToggle
" ----------
let g:QFixToggle_Height = 3

" Tagbar
" ------
let g:tagbar_width = 30
let g:tagbar_autoclose = 1
let g:tagbar_autofocus = 1
let g:tagbar_iconchars = ['+', '-']


" Librarian-Chef Cheffiles are Ruby files
au BufRead,BufNewFile Cheffile set filetype=ruby

Add Berksfile to Ruby ftdetect

" Librarian-Chef Cheffiles are Ruby files
au BufRead,BufNewFile Cheffile set filetype=ruby
au BufRead,BufNewFile Berksfile set filetype=ruby


lua << EOF
require("lspconfig").pylsp.setup({
  enable = true,
  settings = {
    pylsp = {
      configurationSources = {"pyls-flake8"},
      plugins = {
        flake8 = {enabled = true},
        pyls_flake8 = {enabled = true},
        jedi_completion = {fuzzy = true}
      }
    }
  }
})
EOF

Split import from use of config

lua << EOF
nvim_lsp = require("lspconfig")
nvim_lsp.pylsp.setup({
  enable = true,
  settings = {
    pylsp = {
      configurationSources = {"pyls-flake8"},
      plugins = {
        flake8 = {enabled = true},
        pyls_flake8 = {enabled = true},
        jedi_completion = {fuzzy = true}
      }
    }
  }
})
EOF


" Syntax checking hacks.
Plug 'scrooloose/syntastic'

set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*

let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 1
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0

" Use JavaScript Standard Style.
let g:syntastic_javascript_checkers = ['standard']

Use ESLint instead of Standard with Syntastic.

" Syntax checking hacks.
Plug 'scrooloose/syntastic'

set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*

let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 1
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0

" Use ESLint to check Javascript.
let g:syntastic_javascript_checkers = ['eslint']


let g:ale_sign_column_always = 1
let g:ale_fix_on_save = 0
let g:airline#extensions#ale#enabled = 1

nmap <silent> <C-k> <Plug>(ale_previous_wrap)
nmap <silent> <C-j> <Plug>(ale_next_wrap)

let g:ale_lint_on_text_changed = 'never'
let g:ale_lint_on_insert_leave = 0
let g:ale_lint_on_enter = 0
let g:ale_set_loclist = 0
let g:ale_set_quickfix = 1

let g:ale_open_list = 1
let g:ale_list_window_size = 5
let g:ale_fixers = {
\   '*': ['remove_trailing_lines', 'trim_whitespace'],
\   'javascript': ['eslint'],
\}
let g:ale_linters = {
\  'go': ['gofmt'],
\}

Move javascript options to correct locations

let g:ale_sign_column_always = 1
let g:ale_fix_on_save = 0
let g:airline#extensions#ale#enabled = 1

nmap <silent> <C-k> <Plug>(ale_previous_wrap)
nmap <silent> <C-j> <Plug>(ale_next_wrap)

let g:ale_lint_on_text_changed = 'never'
let g:ale_lint_on_insert_leave = 0
let g:ale_lint_on_enter = 0
let g:ale_set_loclist = 0
let g:ale_set_quickfix = 1
let g:ale_pattern_options_enabled = 1

let g:ale_open_list = 1
let g:ale_list_window_size = 5
let g:ale_fixers = {
\  '*': ['remove_trailing_lines', 'trim_whitespace'],
\   'vim': ['vint'],
\   'javascript': ['eslint'],
\   'sh': ['shfmt'],
\}
let g:ale_linters = {
\  'go': ['gofmt'],
\}

" Enable eslint for ale
let g:ale_pattern_options = {
\ '\.min\.js$': {'ale_linters': [], 'ale_fixers': []},
\ '\.min\.css$': {'ale_linters': [], 'ale_fixers': []},
\}


set shell=sh
set shortmess+=I
set runtimepath+=$GOROOT/misc/vim
set backup
set backupdir=~/.cache/vim
set undofile
set undodir=~/.cache/vim
set ai smartindent
set hlsearch
set ignorecase
set smartcase
set showmatch
let c_space_errors=1

if v:version >= 704
	set cryptmethod=blowfish2
else
	" unsecure, but Debian likes it
	set cryptmethod=blowfish
endif

set exrc
set secure

set vb
set modeline
set noexpandtab
set shiftwidth=8
set tabstop=8
set t_Co=256

set wildmenu
set lazyredraw

set history=1000
set autoread

if exists('$DISPLAY')
	let &t_SI .= "\<Esc>[5 q"
	let &t_EI .= "\<Esc>[2 q"
endif

" Spelling support
set nospell spelllang=en_us,de
set spellfile=~/.vim/spell/spellfile.add

helptags ~/.vim/pack
syntax on
filetype plugin indent on

Fix doc paths for plugins

set shell=sh
set shortmess+=I
set runtimepath+=$GOROOT/misc/vim
set backup
set backupdir=~/.cache/vim
set undofile
set undodir=~/.cache/vim
set ai smartindent
set hlsearch
set ignorecase
set smartcase
set showmatch
let c_space_errors=1

if v:version >= 704
	set cryptmethod=blowfish2
else
	" unsecure, but Debian likes it
	set cryptmethod=blowfish
endif

set exrc
set secure

set vb
set modeline
set noexpandtab
set shiftwidth=8
set tabstop=8
set t_Co=256

set wildmenu
set lazyredraw

set history=1000
set autoread

if exists('$DISPLAY')
	let &t_SI .= "\<Esc>[5 q"
	let &t_EI .= "\<Esc>[2 q"
endif

" Spelling support
set nospell spelllang=en_us,de
set spellfile=~/.vim/spell/spellfile.add

for s:v in split(glob("~/.vim/pack/vim/start/*/doc"))
	execute "helptags" s:v
endfor
syntax on
filetype plugin indent on


" Often useful for picking out the this pointer and parameters.
function! vshelp#guess_correct_pointer()
	%smagic/\v(.\u{-}.=.\x+) /\1
/g
	" Heap pointers on my platform start with the same bitpattern, so they're
	" easy to identify.
	v/07FF/d
	%sort /=/u
endf

Use \r to insert a newline in :substitute

" Often useful for picking out the this pointer and parameters.
function! vshelp#guess_correct_pointer()
	%smagic/\v(.\u{-}.=.\x+) /\1\r/g
	" Heap pointers on my platform start with the same bitpattern, so they're
	" easy to identify.
	v/07FF/d
	%sort /=/u
endf


let python_highlight_all = 1
syn keyword pythonDecorator True None False self

" Special types
au BufNewFile,BufRead *.jinja set syntax=htmljinja
au BufNewFile,BufRead *.mako set ft=mako

" Folding
map <buffer> F :set foldmethod=indent<cr>

" AsyncRun
map <F9> :AsyncRun -raw python3 %<cr>
map <F10> :AsyncRun python3 %<cr>

" Jedi
let g:jedi#goto_command = "gd"
let g:jedi#goto_assignments_command = "ga"
let g:jedi#usages_command = "<leader>u"

" Linters
let b:ale_linters = ['flake8']

" Autoformat
let g:ale_fixers.python = ['isort', 'black']
let g:ale_python_black_options = '-l 79'

" Disable ALE source in favour of Jedi
call deoplete#custom#option('ignore_sources', {'python': ['ale']})

Add splits for Jedi goto

let python_highlight_all = 1
syn keyword pythonDecorator True None False self

" Special types
au BufNewFile,BufRead *.jinja set syntax=htmljinja
au BufNewFile,BufRead *.mako set ft=mako

" Folding
map <buffer> F :set foldmethod=indent<cr>

" AsyncRun
map <buffer> <F9> :AsyncRun -raw python3 %<cr>
map <buffer> <F10> :AsyncRun python3 %<cr>

" Jedi
let g:jedi#goto_command = "gd"
let g:jedi#goto_assignments_command = "ga"
let g:jedi#usages_command = "<leader>u"

nnoremap <buffer> gsd :sp<CR>:call jedi#goto()<CR>
nnoremap <buffer> gvd :vs<CR>:call jedi#goto()<CR>
nnoremap <buffer> gtd :tabe<CR>:call jedi#goto()<CR>

" Linters
let b:ale_linters = ['flake8']

" Autoformat
let g:ale_fixers.python = ['isort', 'black']
let g:ale_python_black_options = '-l 79'

" Disable ALE source in favour of Jedi
call deoplete#custom#option('ignore_sources', {'python': ['ale']})


filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

" Plugins {{{
Plugin 'gmarik/Vundle.vim'
Plugin 'tpope/vim-fugitive'
Plugin 'kien/ctrlp.vim'
Plugin 'mattn/emmet-vim'
Plugin 'tpope/vim-surround'

" Make gvim-only colorschemes work transparently in terminal vim
Plugin 'godlygeek/csapprox'
" }}}
" Syntax {{{
Plugin 'cakebaker/scss-syntax.vim'
Plugin 'jelera/vim-javascript-syntax'
" }}}
" Colorschemes {{{
Plugin 'tomasr/molokai'
Plugin 'vim-scripts/Wombat'
Plugin 'wombat256.vim'
Plugin 'summerfruit256.vim'
" }}}

call vundle#end()

Add tmux syntax to vim

filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

" Plugins {{{
Plugin 'gmarik/Vundle.vim'
Plugin 'tpope/vim-fugitive'
Plugin 'kien/ctrlp.vim'
Plugin 'mattn/emmet-vim'
Plugin 'tpope/vim-surround'

" Make gvim-only colorschemes work transparently in terminal vim
Plugin 'godlygeek/csapprox'
" }}}
" Syntax {{{
Plugin 'cakebaker/scss-syntax.vim'
Plugin 'jelera/vim-javascript-syntax'
Plugin 'zaiste/tmux.vim'
" }}}
" Colorschemes {{{
Plugin 'tomasr/molokai'
Plugin 'vim-scripts/Wombat'
Plugin 'wombat256.vim'
Plugin 'summerfruit256.vim'
" }}}

call vundle#end()


" set a map leader for more key combos
let mapleader = ','
let g:mapleader = ','

" scroll the viewport faster
nnoremap <C-e> 3<C-e>
nnoremap <C-y> 3<C-y>

" scroll by visual lines
nnoremap <silent> j gj
nnoremap <silent> k gk

" disable search highlights
nnoremap <silent> <CR> :nohlsearch<CR><CR>

" fold with spacebar
nnoremap <space> za

" use tab for indenting
nnoremap <Tab> >>_
nnoremap <S-Tab> <<_
inoremap <S-Tab> <C-D>
vnoremap <Tab> >gV
vnoremap <S-Tab> <gV

Add remap to split vim horizontally with "h"

" set a map leader for more key combos
let mapleader = ','
let g:mapleader = ','

" scroll the viewport faster
nnoremap <C-e> 3<C-e>
nnoremap <C-y> 3<C-y>

" scroll by visual lines
nnoremap <silent> j gj
nnoremap <silent> k gk

" disable search highlights
nnoremap <silent> <CR> :nohlsearch<CR><CR>

" fold with spacebar
nnoremap <space> za

" use tab for indenting
nnoremap <Tab> >>_
nnoremap <S-Tab> <<_
inoremap <S-Tab> <C-D>
vnoremap <Tab> >gV
vnoremap <S-Tab> <gV

" split horizontally with h
nnoremap <C-w>h <C-w>s


" Allow variables to include dashes
set iskeyword+=-
set iskeyword+=$

Add tab completion handling for sass

" Allow variables to include dashes
set iskeyword+=-
set iskeyword+=$

inoremap <buffer> <expr> <Tab> (pumvisible() ? (col('.') > 1 ? '<Esc>i<Right>' : '<Esc>i') : '') .
            \ '<C-x><C-o><C-r>=pumvisible() ? "\<lt>C-n>\<lt>C-p>\<lt>Down>" : ""<CR>'
" open user completion menu closing previous if open and opening new menu without changing the text
inoremap  <buffer> <expr> <S-Tab> (pumvisible() ? (col('.') > 1 ? '<Esc>i<Right>' : '<Esc>i') : '') .
            \ '<C-x><C-u><C-r>=pumvisible() ? "\<lt>C-n>\<lt>C-p>\<lt>Down>" : ""<CR>'


if !exists('g:tmux_complete_location') || g:tmux_complete_location == ''
    let g:tmux_complete_location =
        \ "$HOME/.vim/bundle/tmux-complete.vim"
endif

function! CompleteScript(findstart, base)
    if a:findstart
        " locate the start of the word
        let line = getline('.')
        let start = col('.') - 1
        while start > 0 && line[start - 1] =~ '\a'
            let start -= 1
        endwhile
        return start
    endif

    " find months matching with "a:base"
    let command = 'sh ' . shellescape(expand(s:script)) . ' ' . shellescape(a:base)
    let words = system(command)
    for word in split(words)
        call complete_add(word)
    endfor
    return []
endfun

let s:script = g:tmux_complete_location . "/sh/tmuxwords.sh"
set completefunc=CompleteScript

Use expand <sfile> instead of g:tmux_complete_location

function! CompleteScript(findstart, base)
    if a:findstart
        " locate the start of the word
        let line = getline('.')
        let start = col('.') - 1
        while start > 0 && line[start - 1] =~ '\a'
            let start -= 1
        endwhile
        return start
    endif

    " find months matching with "a:base"
    let command = 'sh ' . shellescape(expand(s:script)) . ' ' . shellescape(a:base)
    let words = system(command)
    for word in split(words)
        call complete_add(word)
    endfor
    return []
endfun

let s:script = expand('<sfile>:h:h') . "/sh/tmuxwords.sh"
set completefunc=CompleteScript


" Small default height for CommandT
let g:CommandTMaxHeight=20
let g:CommandTMaxFiles=20000

" Make ESC work in CommandT while in terminal Vim
if &term =~ "xterm" || &term =~ "screen"
  let g:CommandTCancelMap=['<ESC>']
end

let g:CommandTWildIgnore=&wildignore . ",**/bower_components/*,**/node_modules/*"

Remove redundant wildignore for CommandT


let g:XkbSwitchEnabled = 1
" enable Insert mode mappings duplicates
let g:XkbSwitchIMappings = ['ru', 'ua']
" issue workaround
let g:XkbSwitchIMappingsSkipFt = ['tex']

Set english layout as default for normal mode.

let g:XkbSwitchEnabled = 1
" enable Insert mode mappings duplicates
" let g:XkbSwitchIMappings = ['ru', 'ua']
" issue workaround
" let g:XkbSwitchIMappingsSkipFt = ['tex']

let g:XkbSwitchNLayout = 'us'


" Indentation
set autoindent
set smarttab
set shiftwidth=4
set softtabstop=4
set tabstop=4
set textwidth=100
set expandtab

" Auto indent pasted text
nnoremap p p=`]<C-o>
nnoremap P P=`]<C-o>

filetype plugin indent on

Disable auto-indent of pasted text

" Indentation
set autoindent
set smarttab
set shiftwidth=4
set softtabstop=4
set tabstop=4
set textwidth=100
set expandtab

filetype plugin indent on


function! gina#command#_raw#call(range, args, mods) abort
  let git = gina#core#get()
  let args = gina#command#parse_args(matchstr(a:args, '^_raw\s\+\zs.*'))
  let pipe = copy(s:pipe)
  return gina#process#open(git, args, pipe)
endfunction

function! gina#command#_raw#complete(arglead, cmdline, cursorpos) abort
  return gina#complete#filename#any(a:arglead, a:cmdline, a:cursorpos)
endfunction

" Pipe -----------------------------------------------------------------------
let s:pipe_super = gina#process#pipe#echo()
let s:pipe = deepcopy(s:pipe_super)

function! s:pipe.on_exit(job, msg, event) abort
  call call(s:pipe_super.on_exit, [a:job, a:msg, a:event], self)
  call gina#core#emitter#emit(
        \ 'command:called:raw',
        \ self.params.scheme,
        \)
endfunction

" Event ----------------------------------------------------------------------
function! s:on_command_called_raw(...) abort
  call gina#core#emitter#emit('modified:delay')
endfunction

if !exists('s:subscribed')
  let s:subscribed = 1
  call gina#core#emitter#subscribe(
        \ 'command:called:raw',
        \ function('s:on_command_called_raw')
        \)
endif

Fix messaging bug on Vim 8

function! gina#command#_raw#call(range, args, mods) abort
  let git = gina#core#get()
  let args = gina#command#parse_args(matchstr(a:args, '^_raw\s\+\zs.*'))
  let pipe = extend(gina#process#pipe#echo(), s:pipe)
  return gina#process#open(git, args, pipe)
endfunction

function! gina#command#_raw#complete(arglead, cmdline, cursorpos) abort
  return gina#complete#filename#any(a:arglead, a:cmdline, a:cursorpos)
endfunction

" Pipe -----------------------------------------------------------------------
let s:pipe_super = gina#process#pipe#echo()
let s:pipe = {}

function! s:pipe.on_exit(job, msg, event) abort
  call call(s:pipe_super.on_exit, [a:job, a:msg, a:event], self)
  call gina#core#emitter#emit(
        \ 'command:called:raw',
        \ self.params.scheme,
        \)
endfunction

" Event ----------------------------------------------------------------------
function! s:on_command_called_raw(...) abort
  call gina#core#emitter#emit('modified:delay')
endfunction

if !exists('s:subscribed')
  let s:subscribed = 1
  call gina#core#emitter#subscribe(
        \ 'command:called:raw',
        \ function('s:on_command_called_raw')
        \)
endif


" File type specific configurations
"
" Mostly consisting of Auto commands applied when matching files are opened

au BufRead,BufNewFile *.md        set filetype=markdown
au BufRead,BufNewFile Vagrantfile set filetype=ruby
au BufRead,BufNewFile /etc/nginx/*,/usr/local/nginx/conf/* set filetype=nginx

Use YAML for RAML files

" File type specific configurations
"
" Mostly consisting of Auto commands applied when matching files are opened

au BufRead,BufNewFile *.md        set filetype=markdown
au BufRead,BufNewFile *.raml      set filetype=yaml
au BufRead,BufNewFile Vagrantfile set filetype=ruby
au BufRead,BufNewFile /etc/nginx/*,/usr/local/nginx/conf/* set filetype=nginx


" Prevent vim-session from asking us to load the session.
" If you want to load the session, use :SaveSession and :OpenSession
let g:session_autosave = 'no'

Add vim-session config for nvim

" Prevent vim-session from asking us to load the session.
" If you want to load the session, use :SaveSession and :OpenSession
let g:session_autosave = 'no'
let g:session_directory = '~/.local/share/nvim/sessions'


set colorcolumn=80
set clipboard+=unnamedplus,unnamed

" Let me run off and modify files without write
set hidden
" Make hidden less "evil"
set autowrite
" Macro redrawing
set lazyredraw
" Stop file watchers from freaking out
set directory=~/.local/share/nvim/tmp
set backupdir=~/.local/share/nvim/backup
" Better diffing
set diffexpr=py3diff#diffexpr()

let g:localrc_filename = ".local.vim"

autocmd BufNewFile,BufRead init.vim
		  \ setlocal cc=60 |
		  \ setlocal foldmethod=marker |
		  \ setlocal autoindent

highlight! link ExtraWhitespace Error
autocmd BufWinEnter *
      \ call matchadd('ExtraWhitespace', '\s\+$')

noremap <leader>vs :source $MYVIMRC<CR>
noremap <leader>ve :62vsplit $MYVIMRC<CR>

function! s:EditLayerComplete(ArgLead, CmdLine, CursorPos)
  return join(g:layer_names, "\n")
endfunction

function! s:EditLayer(args)
  exec ':10split '.g:config_base_dir.'/layer/'.a:args.'/config.vim'
  exec ':vsplit '.g:config_base_dir.'/layer/'.a:args.'/package.vim'
endfunction

" Use custom, not customlist because vim filters the former
command! -complete=custom,s:EditLayerComplete -nargs=1 EditLayer :exe s:EditLayer(<q-args>)

Edit a layer in a new tab

set colorcolumn=80
set clipboard+=unnamedplus,unnamed

" Let me run off and modify files without write
set hidden
" Make hidden less "evil"
set autowrite
" Macro redrawing
set lazyredraw
" Stop file watchers from freaking out
set directory=~/.local/share/nvim/tmp
set backupdir=~/.local/share/nvim/backup
" Better diffing
set diffexpr=py3diff#diffexpr()

let g:localrc_filename = ".local.vim"

autocmd BufNewFile,BufRead init.vim
		  \ setlocal cc=60 |
		  \ setlocal foldmethod=marker |
		  \ setlocal autoindent

highlight! link ExtraWhitespace Error
autocmd BufWinEnter *
      \ call matchadd('ExtraWhitespace', '\s\+$')

noremap <leader>vs :source $MYVIMRC<CR>
noremap <leader>ve :62vsplit $MYVIMRC<CR>

function! s:EditLayerComplete(ArgLead, CmdLine, CursorPos)
  return join(g:layer_names, "\n")
endfunction

function! s:EditLayer(args)
  tabnew
  exec ':e '.g:config_base_dir.'/layer/'.a:args.'/after'
  exec ':vsplit '.g:config_base_dir.'/layer/'.a:args.'/config.vim'
  exec ':vsplit '.g:config_base_dir.'/layer/'.a:args.'/package.vim'
endfunction

" Use custom, not customlist because vim filters the former
command! -complete=custom,s:EditLayerComplete -nargs=1 EditLayer :exe s:EditLayer(<q-args>)


lua <<EOF
require'nvim-treesitter.configs'.setup {
  ensure_installed = "maintained",
  highlight = {
    additional_vim_regex_highlighting = false,
  },
  indent = {
    disable = {"python", },
  },
}
EOF

Replace deprecated shortcut with explicit list

lua <<EOF
require'nvim-treesitter.configs'.setup {
  -- https://github.com/nvim-treesitter/nvim-treesitter#supported-languages
  ensure_installed = {
    "bash",
    "css",
    "dockerfile",
    "go",
    "html",
    "javascript",
    "json",
    "kotlin",
    "lua",
    "make",
    "python",
    "rst",
    "rust",
    "scss",
    "toml",
    "typescript",
    "vim",
    "vue",
  },
  highlight = {
    additional_vim_regex_highlighting = false,
  },
  indent = {
    disable = {"python", },
  },
}
EOF


" dockerfile.vim - Syntax highlighting for Dockerfiles
" Maintainer:   Honza Pokorny <http://honza.ca>
" Version:      0.5

if exists("b:current_syntax")
    finish
endif

let b:current_syntax = "dockerfile"

syntax case ignore

syntax match dockerfileKeyword /\v^\s*(FROM|MAINTAINER|RUN|CMD|EXPOSE|ENV|ADD)\s/
syntax match dockerfileKeyword /\v^\s*(ENTRYPOINT|VOLUME|USER|WORKDIR)\s/
highlight link dockerfileKeyword Keyword

syntax region dockerfileString start=/\v"/ skip=/\v\\./ end=/\v"/
highlight link dockerfileString String

syntax match dockerfileComment "\v^\s*#.*$"
highlight link dockerfileComment Comment

Set commentstring in Vim syntax plugin

" dockerfile.vim - Syntax highlighting for Dockerfiles
" Maintainer:   Honza Pokorny <http://honza.ca>
" Version:      0.5

if exists("b:current_syntax")
    finish
endif

let b:current_syntax = "dockerfile"

syntax case ignore

syntax match dockerfileKeyword /\v^\s*(FROM|MAINTAINER|RUN|CMD|EXPOSE|ENV|ADD)\s/
syntax match dockerfileKeyword /\v^\s*(ENTRYPOINT|VOLUME|USER|WORKDIR)\s/
highlight link dockerfileKeyword Keyword

syntax region dockerfileString start=/\v"/ skip=/\v\\./ end=/\v"/
highlight link dockerfileString String

syntax match dockerfileComment "\v^\s*#.*$"
highlight link dockerfileComment Comment

set commentstring=#\ %s


call add(g:groups, "mappings")

function! layers#mappings#plugins() abort
	return ['junegunn/fzf', 'junegunn/fzf.vim']
endfunction

function! layers#mappings#configure() abort
	" Vim edition
	nnoremap <leader>ve :e $MYVIMRC<cr>
	nnoremap <leader>vs :source $MYVIMRC<cr>

	" Window navigation
	nnoremap <silent> <tab> :wincmd w<cr>

	" Fzf mapping
	nnoremap <leader>w :Windows<cr>
	nnoremap <leader>b :Buffers<cr>
	nnoremap <leader>f :Files<cr>
endfunction

Enable primary selection using mouse

call add(g:groups, "mappings")

function! layers#mappings#plugins() abort
	return ['junegunn/fzf', 'junegunn/fzf.vim']
endfunction

function! layers#mappings#configure() abort
	" Vim edition
	nnoremap <leader>ve :e $MYVIMRC<cr>
	nnoremap <leader>vs :source $MYVIMRC<cr>

	" Window navigation
	nnoremap <silent> <tab> :wincmd w<cr>

	" Fzf mapping
	nnoremap <leader>w :Windows<cr>
	nnoremap <leader>b :Buffers<cr>
	nnoremap <leader>f :Files<cr>

	vnoremap <LeftRelease> "*ygv
endfunction


" Language:    CoffeeScript
" Maintainer:  Mick Koch <kchmck@gmail.com>
" URL:         http://github.com/kchmck/vim-coffee-script
" License:     WTFPL

autocmd BufNewFile,BufRead *.coffee setfiletype coffee

Fix filetype detection in most cases

" Language:    CoffeeScript
" Maintainer:  Mick Koch <kchmck@gmail.com>
" URL:         http://github.com/kchmck/vim-coffee-script
" License:     WTFPL

autocmd BufNewFile,BufRead *.coffee set filetype=coffee