Code Monkey home page Code Monkey logo

prettier-emacs's Introduction

Prettier Banner

Opinionated Code Formatter

JavaScript · TypeScript · Flow · JSX · JSON
CSS · SCSS · Less
HTML · Vue · Angular
GraphQL · Markdown · YAML
Your favorite language?

Github Actions Build Status Github Actions Build Status Github Actions Build Status Codecov Coverage Status Blazing Fast
npm version weekly downloads from npm code style: prettier Follow Prettier on Twitter

Intro

Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.

Input

foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());

Output

foo(
  reallyLongArg(),
  omgSoManyParameters(),
  IShouldRefactorThis(),
  isThereSeriouslyAnotherOne(),
);

Prettier can be run in your editor on-save, in a pre-commit hook, or in CI environments to ensure your codebase has a consistent style without devs ever having to post a nit-picky comment on a code review ever again!


Documentation

Install · Options · CLI · API

Playground


Badge

Show the world you're using Prettiercode style: prettier

[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)

Contributing

See CONTRIBUTING.md.

prettier-emacs's People

Contributors

aaronjensen avatar anmonteiro avatar baerrach avatar clayrisser avatar eqyiel avatar jkseppan avatar jscheid avatar juergenhoetzel avatar mikegolod avatar modulitos avatar sunesimonsen avatar troglotit avatar xuchunyang 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  avatar

prettier-emacs's Issues

How to play nice with Tramp-Mode

When I save a JS file edited via Tramp, this error pops up in a new buffer:

prettier errors:
[warn] Ignored unknown option: --ignore-path /sshx
[error] Invalid configuration file: ENOENT: no such file or directory, scandir '/sshx:<serverName>/path/to/file

It would be great either to disable Prettier for files in Tramp mode, or to make it work.

Prettier options for Typescript

Hey, I am trying to use prettier for typescript. By command line I am using --print-width 80 --single-quote --no-semi --no-bracket-spacing --write. Can you please let me know, how can I replicate this in elisp?

If I try this

  (setq prettier-js-args '(
                           "--print-width" "80"
                           "--single-quote" "true"
                           "--no-semi" "true"
                           "--no-bracket-spacing" "true"

                           ))

I receive the following error.

prettier errors:
Unable to read file: true
Error: ENOENT: no such file or directory, open 'true'
Unable to read file: true
Error: ENOENT: no such file or directory, open 'true'

prettier-js-mode reformats file even when file is in .prettierignore

I have the following in my emacs init.el:

(use-package prettier-js 
  :ensure t
  :config
  (add-hook 'web-mode-hook
	    #'(lambda ()
		(enable-minor-mode
		 '("\\.jsx?\\'" . prettier-js-mode)
		 ))
	    )
  (add-hook 'rjsx-mode-hook 'prettier-js-mode)
  )

In a project, I have this for .prettierignore:

*.spec.js
*.test.js

When I visit a file, src/score_to_grade.spec.js, it shows Prettier in the mode line, but on save, it reformats the file.

I seems that it's ignoring the ignore settings?

Additionally, if I use // prettier-ignore-start ... // prettier-ignore-end these are also not respected and the code between them is formatted in emacs prettier-js-mode.

If I run prettier from my terminal, both of these work as expected.

Versions:

  • Emacs: GNU Emacs 26.2
  • prettier-js: 20180109.726
  • prettier: 1.19.1 (latest)

"prettier errors: env: node: No such file or directory"

Running prettier-js gives the error above. I did some searching and reading, and found that the "env" error usually means something is missing from the Emacs exec-path, so I tried things like this in .emacs:

(add-to-list 'exec-path "/Users/hewwolff/.nvm/versions/node/v10.18.1/bin")

As far as I can tell, node and prettier are both available at that path, but I still get the error.

Environment:

$ prettier -v
1.19.1
$ system_profiler SPSoftwareDataType
Software:

    System Software Overview:

      System Version: macOS 10.15.3 (19D76)
      Kernel Version: Darwin 19.3.0
      Boot Volume: Macintosh HD
      Boot Mode: Normal
      Computer Name: Hew’s MacBook Pro
      User Name: Hew Wolff (hewwolff)
      Secure Virtual Memory: Enabled
      System Integrity Protection: Enabled
      Time since boot: 3 days 1:38

$ node -v
v10.18.1

Nice work

This isn't really an issue, just wanted to say thanks for making this. It works really well for me. 👍 🥇

Only thing I might make a pull request for in the future is for it to read the prettier config from package.json or prettier.config.x. But, for now, this does the trick nicely.

Prettier mode is a bit slow

I notice a delay (half second i asume) when saving the file, any tips ?, I didn't read the code of the package but notice it was writting to a temporal file, maybe there could be some optimization like preloading .prettierrc file or modify the file directly ?

Files in .prettierignore are emptied out on save

Steps to reproduce:

mkdir test
cd test
npm init -y
echo "package.json" > .prettierignore
emacsclient package.json
# make sure prettier-js-mode is running
# insert space then save

Desired result:

File gets saved without modifications.

Observed result:

File contents get deleted and file is saved as empty file.

Unable to run in the org mode source code block

Steps to reproduce

  1. Create any org file temp.org
  2. Create a source code block
#+BEGIN_SRC js
  const a = {
    data: [],
    nextOffset: 1
  }
#+END_SRC
  1. Edit and run prettier-js
prettier errors:
[error] No parser could be inferred for file: /Users/kkweon/temp/temp.org[*Org Src temp.org[ js ]*]

Thank you.

Customize path?

Hi there! Would it be possible to support customizing the path to prettier?

I ask because I tend to locally install dev dependencies instead of globally. I get this at my emacs prompt

$ which prettier
# ./node_modules/.bin/prettier

However if I execute prettier-js I get

helm-M-x: Searching for program: No such file or directory, prettier

If it would be possible to support this, I'm willing to help 😃

Error when running on WIndows 10, GNU Emacs 25.1.1

prettier-js doesn't report any error because it doesn't check for the return value of call-process-region on the diff command at line 189 like it does for the call-process on the prettier-js-command at line 185.

The error message is in the *Messages* buffer

Error: (file-error "Searching for program" "No such file or directory" "diff")

On Windows "diff" is not installed by default. I wonder if there is an elisp function that you could call instead to make it more cross platform?

I've kind of hacked it by adding C:\Program Files\Git\usr\bin\ to the PATH, but causes ^Ms to appear in the output file.

Which hilarously you can't remove as they come back on each save :)

After investigating the cause is diff, as it will be using dos line endings.

Adding --strip-trailing-cr to the diff options fixes the problem.

Saving file loses code from yank buffer

When I yank code (C-w) and save the file, it clears my yank buffer so I can't paste said code in a different file.

Steps to reproduce:

  1. Have JavaScript
  2. Mark some code
  3. C-w
  4. C-x C-s
  5. Open different file
  6. C-y

Observe nothing gets pasted.

My setup:

(require 'prettier-js)
(defun enable-minor-mode (my-pair)
  "Enable minor mode if filename match the regexp.  MY-PAIR is a cons cell (regexp . minor-mode)."
  (if (buffer-file-name)
      (if (string-match (car my-pair) buffer-file-name)
      (funcall (cdr my-pair)))))


(require 'web-mode)
(add-to-list 'auto-mode-alist '("\\.jsx\\'" . web-mode))
(add-to-list 'auto-mode-alist '("\\.js\\'" . web-mode))
(add-hook 'web-mode-hook #'(lambda ()
                            (enable-minor-mode
                             '("\\.jsx?\\'" . prettier-js-mode))))

For full .emacs.d dir you can see here: https://github.com/Swizec/dot.emacs.d

[warn] Ignored unknown option --stdin

Hi there, started to use this package and receiving that warning when try to call (prettier-js).

$ prettier -v
2.3.2

and

$ prettier --help | grep stdin
  --stdin-filepath <path>  Path to the file to pretend that stdin comes from.

Sorry not really upto snuff on the JavaScript side of things but thought it would be good to report it.

Requires `diff` on Windows

When I installed prettier-emacs on Windows and saved a file with an incorrect style, the saved file still had the incorrect style. I did not see an error message displayed on the last line of the window. When I checked the contents of the *Messages* buffer, however, I saw that there was an error trying to run diff:

Saving file c:/Users/mkraai/src/calculator/online/server.js...
Wrote c:/Users/mkraai/AppData/Local/Temp/1/prettier9292Lab.js
Error: (file-error "Searching for program" "No such file or directory" "diff")
Wrote c:/Users/mkraai/src/calculator/online/server.js

Once I installed the MSYS version of diff, added the MSYS bin directory to my path, and restarted Emacs, the style was corrected when I saved the file.

I'm not sure how to fix this. Here are some possibilities:

  • Display an error indicating that diff couldn't be found when saving the file.
  • Note that diff is required in README.md.
  • Modify prettier-emacs to not require diff.

Convenient way to enable/disable per project

I love how little setup this package has, especially how it reads my existing Prettier config, but I'm struggling with finding a good way to disable this on my JavaScript projects that aren't using Prettier. Calling prettier-js-mode isn't very convenient because it's buffer local (I have to run it on every single buffer I want to disable formatting in). It would be great to have some sort of configuration variable to only enable this in certain projects, automatic enable/disable based on if the current project has a Prettier binary or config, or even a global minor mode. I'm not really sure what's best, so I'd appreciate feedback.

prettier empties file

If there's an error in .prettierrc prettier empties the file without error. Also arguments shown below are defined in init.el, not in .prettierrc.

Saving file $FILE...
Wrote /tmp/prettiercbd2uV.js
Applied prettier with args ‘(--print-width 100 --single-quote true --trailing-comma all --no-semi true)’
Wrote $FILE

This looks like prettier/vim-prettier#92 although there is no file .prettierignore existant.

$ emacs --version
GNU Emacs 26.1
$ prettier --version
1.18.2
$ ls -l /usr/local/bin/prettier
lrwxrwxrwx 1 root staff 44 Jun 21 11:38 /usr/local/bin/prettier -> ../lib/node_modules/prettier/bin-prettier.js

Using eslint_d to do the same as this package

To automatically format on save your JS buffer using prettier syntax, you can:

  1. Install and configure eslint if you haven't done so already
  2. Add eslint-plugin-prettier and eslint-config-prettier to your package.json
  3. Add "eslint:recommended" and "plugin:prettier/recommended" to your eslint "extends" configuration
  4. Add "prettier" to your eslint "plugins" configuration
  5. Install and activate eslintd-fix for Emacs
  6. Turn on eslintd-fix-mode in your JS files

Doesn't have effect

I'm afraid that I'm misinterpreting this package, but after putting

(require 'prettier-js)
(setq prettier-js-args '(
  "--trailing-comma" "all"
  "--bracket-spacing" "true"
))
(add-hook 'js2-mode-hook 'prettier-js-mode)

in my .emacs file, it doesn't seem to change anything. If I run prettier --write index.js from the command line it will beautify my code, but Emacs itself doesn't seem to be doing anything...(auto-format on save, etc.)

No files matching the pattern were found: "false".

prettier -v
2.5.1

My prettier emacs config:

(require 'prettier-js)
(setq prettier-js-args '(
						 "--trailing-comma" "es5"
						 "--tab-width" "2"
						 "--use-tabs" "true"
						 "--no-semi" "false"
						 "--single-quote" "true"
						 "--no-bracket-spacing" "true"
						 "--bracket-same-line" "true"
						 "--arrow-parens" "avoid" 
))
(add-hook 'js2-mode-hook 'prettier-js-mode)
(add-hook 'web-mode-hook 'prettier-js-mode)

Then, when I save a js file, I get the following errors:

prettier errors:
[warn] --jsx-bracket-same-line is deprecated.
[warn] Ignored unknown option --stdin.
[error] No files matching the pattern were found: "false".
[error] No files matching the pattern were found: "true".

The first warning is understandable. But those two last errors?

I found two solutions:

The first one is to comment out those two lines:

;;"--no-semi" "false"
;;"--no-bracket-spacing" "true"

The second solution is to just downgrade the version of prettier. (I chose the 1.13.1 and it worked like charm).
For now will just keep the version downgraded, but decided to report the bugs.

Looking for a new maintainer

I'm not having the time to properly maintain this repository anymore. If anyone with enough experience wants to take over I would be happy to hand over the baton 😃

@jscheid I've seen that you're doing a new prettier package for emacs, are you interested in becoming the new maintainer here?

@jlongster I'm mentioning you since this may interest you.

Add support for vue files.

I would love it if this package could suppord .vue files. Basically a file looks like this, and all the JS is in the script tags. I took a look at the code, but my elisp chops simply aren't that good.

<template>
  <h1>Hello World!</h1>
</template>

<script>
const a = "hhhha"
</script>

<style>
</style>

Prettier with spacemacs and js files.

Hi, I am trying to use prettier with spacemacs and .js files that have jsx blocks in them. Notably, if I change the extension to .jsx, then it is applying Prettier (and is notifying me as such with the "Prettier" tag on the bottom of the screen). However, it is not applying to jsx blocks in .js files. How do I fix this? In my user-config, I have this:

(add-hook 'js2-mode-hook 'prettier-js-mode)
(add-hook 'js2-jsx-mode-hook 'prettier-js-mode)
(add-hook 'web-mode-hook 'prettier-js-mode)
(add-hook 'react-mode-hook 'prettier-js-mode)
(push '("\\.js\\'" . react-mode) auto-mode-alist)

diff error on OpenBSD

Running the before-save-hook on OpenBSD fails because diff on that platform doesn't support --strip-trailing-cr (introduced in #13). Removing --strip-trailing-cr fixes the problem.

Internal error when try prettier

My env:
Windows 10
Spacemacs 0.200.10 with emacs 25.3.1
prettier 1.7.4

When I save js file prettier try to run but ends up with error

Wrote c:/Users/Piotr/AppData/Local/Temp/prettier18116vTA.js
helm-M-x: Invalid rcs patch or internal error in prettier-js--apply-rcs-patch

What can be a problem?

Highlighting "flickering" while applying formatting

Under some circumstances, lines lose their syntax highlighting for a while when formatting is applied.

The attached image illustrates it.

demo

I would like for the text not to temporarily turn to the foreground color.

How to set this up?

I am a total emacs noob and am attempting setup right now.

I have created ~/.emacs which contains

File Edit Options Buffers Tools Emacs-Lisp Help

;; Added by Package.el.  This must come before configurations of
;; installed packages.  Don't delete this line.  If you don't want it,
;; just comment it out by adding a semicolon to the start of the line.
;; You may delete these explanatory comments.
(package-initialize)

;; load packages
(add-to-list 'auto-mode-alist '("\\.jsx?\\'" . js2-jsx-mode))
(add-to-list 'load-path "~/.emacs.d/lisp/")

;; prettier config
(require 'prettier-js)

(setq prettier-js-args '(
  "--trailing-comma" "all"
  "--bracket-spacing" "false"
  ))

;; add hooks
(add-hook 'js2-mode-hook 'prettier-js-mode)

and my ~/.emacs.d/lisp/ directory contains

  • prettier-js.el

But it does not do the auto saving when I do C-xs

I have quit and reloaded emacs as well.

Thanks!

Could not apply prettier

When trying to run prettier-js or when saving with prettier-js-mode, all I am getting is the following:

Wrote c:/Users/xxx/AppData/Local/Temp/prettiergc1tvy.jsx
Could not apply prettier

The error buffer only says prettier errors: followed by nothing.
Is there any way to see what errors is causing this?
The file it says it wrote is also not there, I assume because they are deleted right after?

I am on windows and have installed diff and verified that it works.
Running prettier cli on the file returns the formatted code, the issue is just that it fails to apply the diff I guess.
Using emacs version GNU Emacs 26.2 (build 1, x86_64-w64-mingw32) of 2019-04-13
Using Doom-emacs with default config and prettier-emacs added.

I'll set everything up the same on my arch laptop, it's probably just an issue with Windows.

unsure of correct configuration with use-package

Currently my configuration is this:

(use-package prettier-js
  :commands (prettier-mode prettier)
  :init (add-hook 'js2-mode-hook 'prettier-mode)
  :bind (:map js2-mode-map ("M-q" . prettier))
  :config (setq prettier-target-mode "js2-mode"))

But when I hit M-q I get this message in the gutter:

Autoloading failed to define function prettier

If I key M-x and select prettier-js then the code formats.

But if I select M-x and prettier-mode I get the autoloading error:

Autoloading failed to define function prettier

How can I have prettier-js enabled by default and to format the code after every save?

[question] "prettier-js is an available obsolete package."

In Melpa it currently says that "prettier-js is an available obsolete package".

 Status: Available Obsolete from melpa -- Install
    Archive: melpa

    Version: 20180109.726
    Summary: Minor mode to format JS code on file save
   Homepage: https://github.com/prettier/prettier-emacs
   Keywords: convenience wp edit js 
Other versions: 20180109.726 (installed).

Why "obsolete"? What does this mean?

Handle cloned buffers and give error message when not visiting a file

Currently, if I run prettier-js inside a cloned buffer (created by clone-indirect-buffer), prettier-js will fail with an unhelpful error message. Looks like the issue is that it determines where to run the prettier executable by calling buffer-file-name, but buffer-file-name is nil inside cloned buffers. It would be better to either find the base file by calling (buffer-file-name (buffer-base-buffer)) or at least print a more readable error message.

Relatedly, running prettier-js inside a buffer that's not visiting a file gives an unfriendly error message. prettier-js could check whether the buffer has a file and if not, raise a descriptive error message.

I wrote a PR to try to fix this issue: #76

Convenient way to disable per file

There are some files I would like to exclude from prettier formatting, because they are more readable if I can have one line per declaration:

  1. The redux actions definitions files (e.g. like this one)
  2. The reduxjs toolkit reducers (e.g. like this one)

Currently I solve this by switching to fundamental-mode before saving.

But this is a nuisance, and especially when I forget to switch mode before saving, and don't see it until the change has been committed and pushed (like what happened today).

So it would be nice to have the exclusion automated.

Disable formatting on save

I'd like to bind prettier-js to a shortcut instead of having the minor mode run the command on save. Is this possible?

Not working with prettier 3.0.1

Since prettier v3.0.1 this package is not working

Given a svelte file

<script>
        import '@skeletonlabs/skeleton/themes/themes-skeleton.css';
        import '@skeletonlabs/skeleton/styles/skeleton.css';
        import '../app.postcss';
</script>

<slot />

The emacs command M-x prettier-js is returning the error:

prettier errors:
[warn] Ignored unknown option --stdin.
[warn] Ignored unknown option { pluginSearchDirs: ["."] }.
[error] /home/atuleu/devel/github.com/formicidae-tracker/formicidae-tracker.github.io/src/routes/+layout.svelte: Error: printer.embed has too many parameters. The API changed in Prettier v3. Please update your plugin. See https://prettier.io/docs/en/plugins.html#optional-embed
[error]     at printEmbeddedLanguages (file:///home/atuleu/.nvm/versions/node/v18.17.0/lib/node_modules/prettier/index.mjs:17595:11)
[error]     at printAstToDoc (file:///home/atuleu/.nvm/versions/node/v18.17.0/lib/node_modules/prettier/index.mjs:17726:9)
[error]     at async coreFormat (file:///home/atuleu/.nvm/versions/node/v18.17.0/lib/node_modules/prettier/index.mjs:18037:14)
[error]     at async formatWithCursor (file:///home/atuleu/.nvm/versions/node/v18.17.0/lib/node_modules/prettier/index.mjs:18235:\
    14)
[error]     at async formatStdin (file:///home/atuleu/.nvm/versions/node/v18.17.0/lib/node_modules/prettier/internal/cli.mjs:6689:23) 
[error]     at async main (file:///home/atuleu/.nvm/versions/node/v18.17.0/lib/node_modules/prettier/internal/cli.mjs:6972:5)
[error]     at async Module.run (file:///home/atuleu/.nvm/versions/node/v18.17.0/lib/node_modules/prettier/internal/cli.mjs:6928:5)                                                                                                                                

Running npm install -g prettier@2 solved the issue. I guess version 3 removed some options from prettier and this package should be updated.

p.s.: the { pluginSearchDirs: ["."] } comes from svelte default .prettierrc file.

Indentation Problems

when I save, it sets my indentaion to 2 instead of 4

<Table.Row> <Table.Cell key={item.id} collapsing> {" "} <Icon name={"user"} />{" "} </Table.Cell> <Table.Cell> {item.name} </Table.Cell> <Table.Cell collapsing selectable> <Input placeholder="1" type="number" min="0" max="40" name={item.name.split(" ").join("")} onChange={e => this.setState({ [e.target.name]: e.target.value })} value={this.state.value[item.name.split(" ").join("")]} /> </Table.Cell> </Table.Row>

Adding to MELPA stable

Hi.
First of all, thanks for the package!
Is there any chance you could add this to MELPA stable? I think all you need to do is add a tag to the repo (though don't quote me on that).

Cannot find prettier anywhere

If prettier is installed by the package manager, it can be accessed by terminal, using which prettier outputs the path to prettier however the extension can't use it.

However, prettier installed by npm just works.

Prettier was installed using Pacman on EndeavourOS.

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.