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.
3 " Created: Mon Mar 26 23:27:53 2018 -0700
4 " Requires: Vim Ver7.0+
8 " This plugin formats Python files.
14 " - restore cursor/window position after formatting
16 if v:version < 700 || !has('python3')
17 echo "This script requires vim7.0+ with Python 3.6 support."
21 if exists("g:load_black")
25 let g:load_black = "py1.0"
26 if !exists("g:black_virtualenv")
28 let g:black_virtualenv = "~/.local/share/nvim/black"
30 let g:black_virtualenv = "~/.vim/black"
33 if !exists("g:black_fast")
36 if !exists("g:black_linelength")
37 let g:black_linelength = 88
39 if !exists("g:black_skip_string_normalization")
40 let g:black_skip_string_normalization = 0
48 def _get_python_binary(exec_prefix):
50 default = vim.eval("g:pymode_python").strip()
53 if default and os.path.exists(default):
55 if sys.platform[:3] == "win":
56 return exec_prefix / 'python.exe'
57 return exec_prefix / 'bin' / 'python3'
59 def _get_pip(venv_path):
60 if sys.platform[:3] == "win":
61 return venv_path / 'Scripts' / 'pip.exe'
62 return venv_path / 'bin' / 'pip'
64 def _get_virtualenv_site_packages(venv_path, pyver):
65 if sys.platform[:3] == "win":
66 return venv_path / 'Lib' / 'site-packages'
67 return venv_path / 'lib' / f'python{pyver[0]}.{pyver[1]}' / 'site-packages'
69 def _initialize_black_env(upgrade=False):
70 pyver = sys.version_info[:2]
72 print("Sorry, Black requires Python 3.6+ to run.")
75 from pathlib import Path
78 virtualenv_path = Path(vim.eval("g:black_virtualenv")).expanduser()
79 virtualenv_site_packages = str(_get_virtualenv_site_packages(virtualenv_path, pyver))
81 if not virtualenv_path.is_dir():
82 print('Please wait, one time setup for Black.')
83 _executable = sys.executable
85 sys.executable = str(_get_python_binary(Path(sys.exec_prefix)))
86 print(f'Creating a virtualenv in {virtualenv_path}...')
87 print('(this path can be customized in .vimrc by setting g:black_virtualenv)')
88 venv.create(virtualenv_path, with_pip=True)
90 sys.executable = _executable
93 print('Installing Black with pip...')
95 print('Upgrading Black with pip...')
96 if first_install or upgrade:
97 subprocess.run([str(_get_pip(virtualenv_path)), 'install', '-U', 'black'], stdout=subprocess.PIPE)
98 print('DONE! You are all set, thanks for waiting ✨ 🍰 ✨')
100 print('Pro-tip: to upgrade Black in the future, use the :BlackUpgrade command and restart Vim.\n')
101 if virtualenv_site_packages not in sys.path:
102 sys.path.append(virtualenv_site_packages)
105 if _initialize_black_env():
111 fast = bool(int(vim.eval("g:black_fast")))
112 mode = black.FileMode(
113 line_length=int(vim.eval("g:black_linelength")),
114 string_normalization=not bool(int(vim.eval("g:black_skip_string_normalization"))),
115 is_pyi=vim.current.buffer.name.endswith('.pyi'),
117 buffer_str = '\n'.join(vim.current.buffer) + '\n'
119 new_buffer_str = black.format_file_contents(buffer_str, fast=fast, mode=mode)
120 except black.NothingChanged:
121 print(f'Already well formatted, good job. (took {time.time() - start:.4f}s)')
122 except Exception as exc:
125 current_buffer = vim.current.window.buffer
127 for i, tabpage in enumerate(vim.tabpages):
129 for j, window in enumerate(tabpage.windows):
130 if window.valid and window.buffer == current_buffer:
131 cursors.append((i, j, window.cursor))
132 vim.current.buffer[:] = new_buffer_str.split('\n')[:-1]
133 for i, j, cursor in cursors:
134 window = vim.tabpages[i].windows[j]
136 window.cursor = cursor
138 window.cursor = (len(window.buffer), 0)
139 print(f'Reformatted in {time.time() - start:.4f}s.')
142 _initialize_black_env(upgrade=True)
145 print(f'Black, version {black.__version__} on Python {sys.version}.')
149 command! Black :py3 Black()
150 command! BlackUpgrade :py3 BlackUpgrade()
151 command! BlackVersion :py3 BlackVersion()