]> 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:

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