Giter Club home page Giter Club logo

blacken's Introduction

MELPA MELPA Stable CI

Blacken

Use the python black package to reformat your python buffers.

usage

The whole buffer can be reformatted with blacken-buffer. If you want to format every time you save, enable blacken-mode in relevant python buffers. Note that if blacken-only-if-project-is-blackened is non-nil, then blacken will only run if your pyproject.toml contains the [tool.black] setting. This setting is off by default.

customization

The following options change the behavior of black when reformatting buffers.

  • blacken-allow-py36 Allow using Python 3.6-only syntax on all input files.
  • blacken-skip-string-normalization Don't normalize string quotes or prefixes.
  • blacken-fast-unsafe Skips temporary sanity checks.
  • blacken-line-length Max line length enforced by blacken.

license

blacken.el is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version.

SPDX-License-Identifier: GPL-3.0-or-later

blacken's People

Contributors

bon avatar celeritascelery avatar dakra avatar dependabot[bot] avatar jakubvalenta avatar jcs090218 avatar jrosdahl avatar kootenpv avatar leungbk avatar max-arnold avatar mvaled avatar newt0311 avatar pmiddend avatar proofit404 avatar purcell avatar simenheg avatar swillner avatar takaakifuruse avatar tgamblin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

blacken's Issues

Blacken is opening to many processes

I am using emacs 28.0.50 on Mac Monterey and am experiencing a "too many files" open error. After looking at the processes list I see that blacken has many open ones. Specifically blacken-error, All I did was automatically start blacken when opening a python file.


(use-package blacken
  :diminish ""
  :custom
  (blacken-skip-string-normalization t)
  (blacken-line-length 120))
(use-package python
  :delight " Py"
  :mode ("\\.py" . python-mode)
  :hook ((python-mode . pyvenv-mode)
         (python-mode . blacken-mode)
         (python-mode . (lambda () (aaronzinhoo--python-setup))))
  :preface
  (defun aaronzinhoo--python-buffer-setup ()
    (setq python-indent-offset 4)
    (setq-local highlight-indentation-offset 4))
  (defun aaronzinhoo--activate-python-shell-complettion ()
    "Return non-nil if can trigger native completion."
    (let ((python-shell-completion-native-enable t)
          (python-shell-completion-native-output-timeout
           python-shell-completion-native-try-output-timeout))
      (python-shell-completion-native-get-completions
       (get-buffer-process (current-buffer))
       nil "_")))
  ;;https://lists.gnu.org/archive/html/help-gnu-emacs/2021-09/msg00535.html
  ;; used to help pyright find venv folders
  (defun aaronzinhoo--pyvenv-workon ()
    (when (buffer-file-name)
      (let* ((python-version ".python-version")
             (project-dir (locate-dominating-file (buffer-file-name) python-version)))
        (when project-dir
	      (progn
	        ;; https://github.com/emacs-lsp/lsp-pyright/issues/62#issuecomment-942845406
	        (lsp-workspace-folders-add project-dir)
	        (pyvenv-workon
             (with-temp-buffer
               (insert-file-contents (expand-file-name python-version project-dir))
               (car (split-string (buffer-string))))))))))
  (defun aaronzinhoo--python-setup ()
    (aaronzinhoo--python-buffer-setup)
    (aaronzinhoo--pyvenv-workon))
  :custom
  (python-check-command "flake8")
  :init
  (setenv "WORKON_HOME" "~/.pyenv/versions")
  (add-to-list 'process-coding-system-alist '("python" . (utf-8 . utf-8)))
  (with-eval-after-load 'python (defun temp () (aaronzinhoo--activate-python-shell-complettion))))

image

Error: Invalid value for "src": Path "-" does not exist.

Added the following to me emacs config
(add-hook 'python-mode-hook 'blacken-mode)

and when running blacken-buffer on a python buffer i get the following in the error buffer.

Usage: black [OPTIONS] [SRC]...

Error: Invalid value for "src": Path "-" does not exist.

Annoying when using two windows on the same buffer

I usually have two windows showing the same buffer, where the point is at different positions within the buffer. When working on one and running blacken, the other window's point is reset all the way to the top of the file. This makes blacken pretty much unusable for me.

Searching for pyproject.toml has a syntax error in Emacs <= v26

The when-let expression here has a syntax error on Emacs <= v26

When M-x byte-compile:

In blacken-project-is-blackened:
blacken.el:133:48:Warning: ‘(parent (locate-dominating-file default-directory
    "pyproject.toml"))’ is a malformed function
blacken.el:137:37:Warning: reference to free variable ‘parent’

If trying to run it anyway:

File mode specification error: (invalid-function (parent (locate-dominating-file default-directory pyproject.toml)))

Black is cutting the code (yes is weird)

Hi, i recently upgrade my blacken-mode

I use it with elpy, this is my config:

Elpy Configuration

Virtualenv........: dev3 (/Users/ovnicraft/.virtualenvs/dev3)
RPC Python........: 3.7.1 (/Users/ovnicraft/.virtualenvs/dev3/bin/python)
Interactive Python: python (/Users/ovnicraft/.virtualenvs/dev3/bin/python)
Emacs.............: 26.1
Elpy..............: 1.28.0
Jedi..............: 0.13.3
Rope..............: 0.11.0
Autopep8..........: 1.4.3
Yapf..............: 0.26.0
Black.............: 18.9b0
Syntax checker....: flake8 (/Users/ovnicraft/.virtualenvs/dev3/bin/flake8)

You can see what happen when i save my file here:

https://drive.google.com/file/d/1YQhajI5QMHYOXLCRs0hNoxAy0HYgrWSs/view

Error message I'm having trouble to understand

Hello!

Thanks for implementing this, I'm very keen on integrating black with my Emacs!

I'm trying to get it running and I'm getting an error I can't seem to understand though:

I have configured my blacken-executable to a valid path. The executable works when I execute it on a Python module from the command line. I have also added a correct LC_ALL as an environment variable in Emacs. After turning on blacken-mode, I get the message "Black failed, see blacken-error buffer for details".

But when I look in the buffer blacken-error, all I see is the line "reformatted -".

Do you have any pointer on what I'm doing wrong?

Apply patch instead of replacing whole buffer

Replacing the entire buffer with copy-to-buffer is disruptive: It's a delete followed by a replace, and many links within emacs (including compilation, grep, and occur buffers) will overreact to the deletion by redirecting all links to the beginning of the file. (Reinserting the whole file also causes it to be reparsed for syntax highlighting, which can be kind of slow)

The support for gofmt in go-mode shows a better way, although it's unfortunately a nontrivial amount of code. go-mode asks for a diff instead of rewriting the whole file, then parses the diff and translates it into editing commands. It would be nice if blacken did the same (It would be even nicer if there were one meta-fmt mode for emacs so that this wheel doesn't have to be reinvented for every formatting tool).

the future of emacs, python, and black

first of all, thanks for writing this package!

i used blacken.el in the past, but i stopped using it recently since i think there are better options available to me… please allow me to explain. :)

a while ago i wrote black-macchiato to allow formatting of partial files using black. (see also #11.)

to integrate black-macchiato with emacs, i wrote black-macchiato.el, which currently lives as a private minimalistic emacs package inside my dotfiles.

as you can see, it looks rather trivial, thanks to reformatter.el, which is a great library. i have positive experiences using it: i recently published a json and jsonlines reformatter: jq-format.el, which, together with my related flycheck json-jq checker (included in flycheck), makes working with json and jsonlines files a breeze.

let's get back to python. what i want is: black integration for python editing in emacs, with buffer reformatting, partial formatting, an on save hook, and minimal configuration. in practice, i want an emacs package that:

  • is based on reformatter.el
  • uses black for normal operations
  • optionally uses black-macchiato for partial reformatting
  • is available on melpa
  • is actively maintained
  • has documentation (could be a README) ;)

i really want to see this happen. compared to the current blacken.el, the above will be simpler (by reusing third party libraries and tools), and it would also solve things like #11 properly.

now, i can see this going forward in a couple of ways:

  • port this package over to reformatter.el and add the missing features. this will likely break backwards compatibility, e.g. different command names, configuration, maybe even the package name.

  • a ‘competing’ package doing exactly what i described above, and publish it on melpa. actually i considered doing this already, then stopped myself… and now i am writing this message instead.

i would be interested in your thoughts. i understand you may not be interested in my ideas/proposal, or you are too busy, and that is totally fine… which leads me to the following:

you could just say ‘go ahead and take over!’ and let me reimplement another emacs-python-black package, since i am actually willing to do all the work to make this happen. once i'm done, you could consider deprecating this package (or just leave it)... and you could sit back, relax, and use my package instead. :)

for reference, i successfully did a similar thing with my relatively widely used emacs-direnv project, which obsoleted multiple half-working earlier attempts to solve the same problem, projectile-direnv and direnv-el, in a friendly, non-competitive way; see here and here.

hope to hear from you!

[idea] Use black --line-length while resizing the buffer

Idea is: reflow the code when the window is resized.

  • When emacs open a file blacken could pass black with --line-length equal to the number of column of the buffer the file is displayed on.
  • Every time the buffer is resized, blacken could pass black again with an updated --line-length so adapt the code to the new width.
  • When the file is saved, blacken could pass black one last time without --line-length for diff stability.

So one could work with a file in full-width with comfort of a big screen, then split the screen in two vertical windows and have the code rewrapped accordingly, the get back to a single buffer and get the code rewrapped automatically again to use the available space.

To be really nice and smooth it would need for the file cursor not to jump to another place, which is probably the hardest thing here...

Redisplay glitch when replacing the whole buffer

Often, but not every time, there is a display glitch when blacken-buffer replaces the buffer content: the top part of the buffer content is shown for a split second and then the window start is restored to what it was.

I'm using Emacs 25.2 and blacken d6929cf.

I guess this would be fixed by implementing #15, but it should be possible to fix this issue in an easier way.

Feature-request: Don't open errors buffer when the error is "can't find black"

👋 First off, thanks for this package!

I like using black to the point where I want to use it in any project I'm working on and I can just sync python-mode and blacken-mode, so the "can't find black" error is pretty much not an issue in these cases. The odd case is when I'm working on a one-off python script and every time I save it spawns the black-errors buffer and it's quite annoying.

Interested in your thoughts about moving this one particular error to the *messages* buffer because it's much less intrusive, and still makes contextual sense since the error isn't really an error about black formatting, but rather a process error.

I'm sure there are work-arounds that I could try in my emacs config but thought this was worth bringing up and thought I'd ask here before I consider trying it out and opening a PR.

Blacken not finding pyproject.toml over TRAMP

I'm working on a project that has this in the pyproject.toml:

[tool.black]
line-length = 100

black says that nothing needs to be reformatted:

$ black --check .
All done! ✨ 🍰 ✨
177 files would be left unchanged.

But when I have blacken-mode running, lines longer than 100 are reformatted on save. I have to set blacken-line-length to 100 to get the desired behavior. Why doesn't black use the configured line length when it's run through blacken-mode?

If it makes a difference, this is over TRAMP.

Buffer locks up after blacken fix it

My Environment

  • OS: MX Linux 18
  • $ uname -r: 4.19.0-5-amd64
  • dotfiles
  • i3wm version 4.13
  • ~/.config/i3
  • GNU Emacs 27.0.50 (build 1, x86_64-pc-linux-gnu, GTK+ Version 3.22.11) of 2019-11-19
  • ~/.emacs.d
  • blacken-20191024.1230

Use-package declaration

(use-package blacken
  :ensure t
  :config
  (setq blacken-fast-unsafe nil)
  (setq blacken-line-length 79))

Issue

Every time blacken-mode fixes the code by itself, or that I run blacken-buffer, Emacs freezes and I have to run C-g to get it back. This is the error I get in *Messages*:

Error while checking syntax automatically: (error "Lisp nesting exceeds  max-lisp-eval-depth ")

Black output added to buffer

With black==18.6b0 installed, after reformatting, part of black output is added to the buffer, for example.

1 file left unchanged.

It looks like black changed it's output between version 18.5b0 (my previous version without this issue). Now when run from command line I get.

All done! ✨ 🍰 ✨
1 file left unchanged.

Support blackd

There doesn't seem to be any support for blackd, it would be nice if this package built in support with it so frequent formatting of large files gets faster.

To be put into the README

Consider adding this:

  • Use: pip3 install autopep8 --user
  • Add:
;; Emacs 24 renamed flet to cl-flet.
     (defalias 'mh-cl-flet
     (if (fboundp 'cl-flet)
     'cl-flet
     'flet))

Screen paint / redisplay glitch

Similar to #16, I'm seeing screen paint/redisplay errors. E.g. starting with

[
1,
2,
3
]

With point at the end of the buffer, on saving, the screen displays

image

But after moving point it displays correctly:

image

Emacs version 26.2.90
blacken.el from melpa, ;; Package-Version: 20190521.841

*blacken-error* appears empty on error if scroll-conservatively is nonzero

If you customize scroll-conservatively to a nonzero value, and try to use blacken-buffer on a Python file with a syntax error, such as

print("oops')

the resulting error message appears empty. What’s actually happened is that the error in the *blacken-error* buffer has been scrolled off-screen:

screenshot

If you scroll the message on-screen and re-run blacken-buffer, the message is scrolled back off-screen.

Expected result, as occurs with scroll-conservatively left at its default of 0:

screenshot

I’m using Emacs 26.3 on Ubuntu 20.04.

Split off from #3, but properly diagnosed this time, I hope.

Adding `blacken_mode` as a python-mode-hook eventually runs out of file handles.

I set the black package so it blacks on save:

(add-hook 'python-mode-hook 'blacken-mode)

That worked fine for about a day, and then my emacs refused to open new files or save existing files after that, until I restart!

(Lucky I am constantly saving my buffers so I lost perhaps ten keystrokes... :-) )

It happened three times before I figured out that it was that one line above. I commented it out and restarted and it's days later and I've seen no issues.

I should have written down the error messages but I was in a hurry - also, I didn't realize it was the black package until I looked at what changes I'd made to my .emacsrc.

The message seemed to me to be implying that emacs had run out of file handles, so my guess is that the black package is somehow leaking file handles.


I'm on Aquamacs for MacOS, a GUI wrapper for emacs. I've been using it for a decade or and the compatibility has been extremely good.

Aquamacs 3.4 GNU Emacs 25.3.50.1 (x86_64-apple-darwin14.5.0, NS appkit-1348.17 Version 10.10.5 (Build 14F27)) dated 2018-07-27 rev. 53e2a47a8fbbfce9586fd76891478ac5851ac3b5

Blacken mode does not save excursion

My Environment

Issue

Rich now blacken-mode does not save-excursion in most of the cases. This breaks the flow of the coding, because every time I run blacken-buffer, or it is run automatically, the cursor goes either to the beginning of the buffer, or to some random place. This makes it impossible to use auto-save modes such as super-save, which are extremely useful. This bug is preventing me from using blacken-mode, which is otherwise extremely useful.

How to change blacken-line-length?

My blacken-line-length is stuck at 79, even though C-h v blacken-line-length returns 100.

I even attempted

(defcustom blacken-executable "black --line-length 100"
  "Name of the executable to run."
  :type 'string)

but that also had no effect.

It looks like black overrides any changes from blacken.el

blacken-region

When working with existing code, it is useful to only re-format a certain region of a file. It would be great if blacken could support re-formatting only the highlighted region of a file.

Show diff?

I often like to see where black changed my file, in order to not make the same mistakes over and over. A function like blacken-buffer-diff showing the diff output in a new buffer would be a great addition.

Custom arguments

First of all, I'm a emacs noob.

I want to execute black with custom arguments, I see there's a function for doing that here but I don't know how to actually use it.

For instance, I want to run black with the "-S" flag.

I don't think this changes anything, but I'm using spacemacs.

Symbol’s function definition is void: replace-buffer-contents

#19 introduced a new way to replace the whole buffer. Unfortunately, this function only exists in Emacs 26 and onwards. As a result, blacken now produces this error message on Emacs versions below 26:

Symbol’s function definition is void: replace-buffer-contents

In my case, I am using the latest Ubuntu LTS (18.04.2) which provides GNU Emacs 25.2.2.

Is there any way to fallback to the old behaviour (or an alternative method) for older Emacs versions?

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.