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 func! __BLACK_MISSING()
18 echo "The black.vim plugin requires vim7.0+ with Python 3.6 support."
20 command! Black :call __BLACK_MISSING()
21 command! BlackUpgrade :call __BLACK_MISSING()
22 command! BlackVersion :call __BLACK_MISSING()
26 if exists("g:load_black")
30 let g:load_black = "py1.0"
31 if !exists("g:black_virtualenv")
33 let g:black_virtualenv = "~/.local/share/nvim/black"
35 let g:black_virtualenv = "~/.vim/black"
38 if !exists("g:black_fast")
41 if !exists("g:black_linelength")
42 let g:black_linelength = 88
44 if !exists("g:black_skip_string_normalization")
45 let g:black_skip_string_normalization = 0
55 class Flag(collections.namedtuple("FlagBase", "name, cast")):
58 return self.name.replace("-", "_")
61 def vim_rc_name(self):
63 if name == "line_length":
64 name = name.replace("_", "")
65 if name == "string_normalization":
67 return "g:black_" + name
71 Flag(name="line_length", cast=int),
72 Flag(name="fast", cast=bool),
73 Flag(name="string_normalization", cast=bool),
77 def _get_python_binary(exec_prefix):
79 default = vim.eval("g:pymode_python").strip()
82 if default and os.path.exists(default):
84 if sys.platform[:3] == "win":
85 return exec_prefix / 'python.exe'
86 return exec_prefix / 'bin' / 'python3'
88 def _get_pip(venv_path):
89 if sys.platform[:3] == "win":
90 return venv_path / 'Scripts' / 'pip.exe'
91 return venv_path / 'bin' / 'pip'
93 def _get_virtualenv_site_packages(venv_path, pyver):
94 if sys.platform[:3] == "win":
95 return venv_path / 'Lib' / 'site-packages'
96 return venv_path / 'lib' / f'python{pyver[0]}.{pyver[1]}' / 'site-packages'
98 def _initialize_black_env(upgrade=False):
99 pyver = sys.version_info[:2]
101 print("Sorry, Black requires Python 3.6+ to run.")
104 from pathlib import Path
107 virtualenv_path = Path(vim.eval("g:black_virtualenv")).expanduser()
108 virtualenv_site_packages = str(_get_virtualenv_site_packages(virtualenv_path, pyver))
109 first_install = False
110 if not virtualenv_path.is_dir():
111 print('Please wait, one time setup for Black.')
112 _executable = sys.executable
114 sys.executable = str(_get_python_binary(Path(sys.exec_prefix)))
115 print(f'Creating a virtualenv in {virtualenv_path}...')
116 print('(this path can be customized in .vimrc by setting g:black_virtualenv)')
117 venv.create(virtualenv_path, with_pip=True)
119 sys.executable = _executable
122 print('Installing Black with pip...')
124 print('Upgrading Black with pip...')
125 if first_install or upgrade:
126 subprocess.run([str(_get_pip(virtualenv_path)), 'install', '-U', 'black'], stdout=subprocess.PIPE)
127 print('DONE! You are all set, thanks for waiting ✨ 🍰 ✨')
129 print('Pro-tip: to upgrade Black in the future, use the :BlackUpgrade command and restart Vim.\n')
130 if virtualenv_site_packages not in sys.path:
131 sys.path.append(virtualenv_site_packages)
134 if _initialize_black_env():
140 configs = get_configs()
141 mode = black.FileMode(
142 line_length=configs["line_length"],
143 string_normalization=configs["string_normalization"],
144 is_pyi=vim.current.buffer.name.endswith('.pyi'),
147 buffer_str = '\n'.join(vim.current.buffer) + '\n'
149 new_buffer_str = black.format_file_contents(
151 fast=configs["fast"],
154 except black.NothingChanged:
155 print(f'Already well formatted, good job. (took {time.time() - start:.4f}s)')
156 except Exception as exc:
159 current_buffer = vim.current.window.buffer
161 for i, tabpage in enumerate(vim.tabpages):
163 for j, window in enumerate(tabpage.windows):
164 if window.valid and window.buffer == current_buffer:
165 cursors.append((i, j, window.cursor))
166 vim.current.buffer[:] = new_buffer_str.split('\n')[:-1]
167 for i, j, cursor in cursors:
168 window = vim.tabpages[i].windows[j]
170 window.cursor = cursor
172 window.cursor = (len(window.buffer), 0)
173 print(f'Reformatted in {time.time() - start:.4f}s.')
176 path_pyproject_toml = black.find_pyproject_toml(vim.eval("fnamemodify(getcwd(), ':t')"))
177 if path_pyproject_toml:
178 toml_config = black.parse_pyproject_toml(path_pyproject_toml)
183 flag.var_name: toml_config.get(flag.name, flag.cast(vim.eval(flag.vim_rc_name)))
189 _initialize_black_env(upgrade=True)
192 print(f'Black, version {black.__version__} on Python {sys.version}.')
196 command! Black :py3 Black()
197 command! BlackUpgrade :py3 BlackUpgrade()
198 command! BlackVersion :py3 BlackVersion()