]> git.madduck.net Git - etc/vim.git/blob - plugin/black.vim

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

All patches and comments are welcome. Please squash your changes to logical commits before using git-format-patch and git-send-email to patches@git.madduck.net. If you'd read over the Git project's submission guidelines and adhered to them, I'd be especially grateful.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

Add blank line after constants in stub file (#360)
[etc/vim.git] / plugin / black.vim
1 " black.vim
2 " Author: Łukasz Langa
3 " Created: Mon Mar 26 23:27:53 2018 -0700
4 " Requires: Vim Ver7.0+
5 " Version:  1.0
6 "
7 " Documentation:
8 "   This plugin formats Python files.
9 "
10 " History:
11 "  1.0:
12 "    - initial version
13
14 if v:version < 700 || !has('python3')
15     echo "This script requires vim7.0+ with Python 3.6 support."
16     finish
17 endif
18
19 if exists("g:load_black")
20    finish
21 endif
22
23 let g:load_black = "py1.0"
24 if !exists("g:black_virtualenv")
25   let g:black_virtualenv = "~/.vim/black"
26 endif
27 if !exists("g:black_fast")
28   let g:black_fast = 0
29 endif
30 if !exists("g:black_linelength")
31   let g:black_linelength = 88
32 endif
33 if !exists("g:black_skip_string_normalization")
34   let g:black_skip_string_normalization = 0
35 endif
36
37 python3 << endpython3
38 import sys
39 import vim
40
41 def _get_python_binary(exec_prefix):
42   if sys.platform[:3] == "win":
43     return exec_prefix / 'python.exe'
44   return exec_prefix / 'bin' / 'python3'
45
46 def _get_pip(venv_path):
47   if sys.platform[:3] == "win":
48     return venv_path / 'Scripts' / 'pip.exe'
49   return venv_path / 'bin' / 'pip'
50
51 def _get_virtualenv_site_packages(venv_path, pyver):
52   if sys.platform[:3] == "win":
53     return venv_path / 'Lib' / 'site-packages'
54   return venv_path / 'lib' / f'python{pyver[0]}.{pyver[1]}' / 'site-packages'
55
56 def _initialize_black_env(upgrade=False):
57   pyver = sys.version_info[:2]
58   if pyver < (3, 6):
59     print("Sorry, Black requires Python 3.6+ to run.")
60     return False
61
62   from pathlib import Path
63   import subprocess
64   import venv
65   virtualenv_path = Path(vim.eval("g:black_virtualenv")).expanduser()
66   virtualenv_site_packages = str(_get_virtualenv_site_packages(virtualenv_path, pyver))
67   first_install = False
68   if not virtualenv_path.is_dir():
69     print('Please wait, one time setup for Black.')
70     _executable = sys.executable
71     try:
72       sys.executable = str(_get_python_binary(Path(sys.exec_prefix)))
73       print(f'Creating a virtualenv in {virtualenv_path}...')
74       print('(this path can be customized in .vimrc by setting g:black_virtualenv)')
75       venv.create(virtualenv_path, with_pip=True)
76     finally:
77       sys.executable = _executable
78     first_install = True
79   if first_install:
80     print('Installing Black with pip...')
81   if upgrade:
82     print('Upgrading Black with pip...')
83   if first_install or upgrade:
84     subprocess.run([str(_get_pip(virtualenv_path)), 'install', '-U', 'black'], stdout=subprocess.PIPE)
85     print('DONE! You are all set, thanks for waiting ✨ 🍰 ✨')
86   if first_install:
87     print('Pro-tip: to upgrade Black in the future, use the :BlackUpgrade command and restart Vim.\n')
88   if sys.path[0] != virtualenv_site_packages:
89     sys.path.insert(0, virtualenv_site_packages)
90   return True
91
92 if _initialize_black_env():
93   import black
94   import time
95
96 def Black():
97   start = time.time()
98   fast = bool(int(vim.eval("g:black_fast")))
99   line_length = int(vim.eval("g:black_linelength"))
100   mode = black.FileMode.AUTO_DETECT
101   if bool(int(vim.eval("g:black_skip_string_normalization"))):
102     mode |= black.FileMode.NO_STRING_NORMALIZATION
103   buffer_str = '\n'.join(vim.current.buffer) + '\n'
104   try:
105     new_buffer_str = black.format_file_contents(buffer_str, line_length=line_length, fast=fast, mode=mode)
106   except black.NothingChanged:
107     print(f'Already well formatted, good job. (took {time.time() - start:.4f}s)')
108   except Exception as exc:
109     print(exc)
110   else:
111     vim.current.buffer[:] = new_buffer_str.split('\n')[:-1]
112     print(f'Reformatted in {time.time() - start:.4f}s.')
113
114 def BlackUpgrade():
115   _initialize_black_env(upgrade=True)
116
117 def BlackVersion():
118   print(f'Black, version {black.__version__} on Python {sys.version}.')
119
120 endpython3
121
122 command! Black :py3 Black()
123 command! BlackUpgrade :py3 BlackUpgrade()
124 command! BlackVersion :py3 BlackVersion()
125
126 nmap ,= :Black<CR>
127 vmap ,= :Black<CR>