forked from jscheid/prettier.el
-
Notifications
You must be signed in to change notification settings - Fork 1
/
prettier.el
1361 lines (1183 loc) · 47.1 KB
/
prettier.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; prettier.el --- Code formatting with Prettier -*- lexical-binding: t; -*-
;; Copyright (c) 2018-present Julian Scheid
;; Author: Julian Scheid <julians37@gmail.com>
;; Version: 0.9.0
;; Created: 7 Nov 2018
;; Keywords: convenience, languages, files
;; Homepage: https://github.com/jscheid/prettier.el
;; Package-Requires: ((emacs "26.1") (iter2 "0.9") (nvm "0.2"))
;; This file is not part of GNU Emacs.
;; This program 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 of the
;; License, or (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Reformats your code by running Prettier on file save or on request,
;; with minimal overhead. By default, adjusts buffer-local
;; indentation settings and such to match Prettier config when used as
;; a minor mode.
;; See Info manual or README for further details.
;;; Code:
;;;; Requirements
(require 'iter2)
(require 'json)
(require 'nvm)
(require 'tramp)
(require 'subr-x)
(require 'compile)
(require 'ansi-color)
(eval-when-compile
(require 'cl-lib)
(require 'rx)
(defun prettier--readme-link (anchor)
"Return the URL of the Readme section identified by ANCHOR."
(concat "https://github.com/jscheid/prettier.el/README#"
anchor)))
;;;; Customization
(defgroup prettier nil
"Code reformatting using Prettier."
:group 'files
:prefix "prettier"
:link '(url-link :tag "Repository"
"https://github.com/jscheid/prettier.el"))
(defcustom prettier-pre-warm 'full
"Choose how to pre-warm Prettier caches.
Essentially this selects when you wait for Prettier startup
overhead: with `none', you tend to wait for it on first save.
With `full', you wait when command `prettier-mode' is first
activated. `some' is a compromise, with it you wait some on
first activation and some on first save."
:type '(choice
(const :tag "No pre-warming, everything on-demand" none)
(const :tag "Start server early, no other pre-warming" some)
(const :tag "Pre-warm as much as possible" full))
:package-version '(prettier . "0.1.0")
:group 'prettier
:link '(info-link "(prettier)prettier-pre-warm")
:link `(url-link ,(eval-when-compile
(prettier--readme-link
"prettier-pre-warm"))))
(defcustom prettier-inline-errors-flag nil
"Non-nil means to show Prettier errors inline using overlays.
When non-nil, create an overlay under the line with the error to
show the message, aligned with the column. This doesn't
currently work well when the error is outside window.
When nil, send errors to the default error buffer."
:type 'boolean
:package-version '(prettier . "0.1.0")
:group 'prettier
:link '(info-link "(prettier)prettier-inline-errors-flag")
:link `(url-link ,(eval-when-compile
(prettier--readme-link
"prettier-inline-errors-flag"))))
(defcustom prettier-mode-sync-config-flag t
"Non-nil means to attempt syncing Prettier configuration to Emacs."
:type 'boolean
:package-version '(prettier . "0.1.0")
:group 'prettier
:link '(info-link "(prettier)prettier-mode-sync-config-flag")
:link `(url-link ,(eval-when-compile
(prettier--readme-link
"prettier-mode-sync-config-flag"))))
;;;###autoload
(put 'prettier-mode-sync-config-flag 'safe-local-variable 'booleanp)
(defcustom prettier-editorconfig-flag t
"Non-nil means to use `.editorconfig' files when present.
Requires Prettier 1.9+."
:type 'boolean
:package-version '(prettier . "0.1.0")
:group 'prettier
:link '(info-link "(prettier)prettier-editorconfig-flag")
:link `(url-link ,(eval-when-compile
(prettier--readme-link
"prettier-editorconfig-flag"))))
;;;###autoload
(put 'prettier-editorconfig-flag 'safe-local-variable 'booleanp)
(defcustom prettier-infer-parser-flag t
"Non-nil means to fall back to inferring a parser."
:type 'boolean
:package-version '(prettier . "0.5.0")
:group 'prettier
:link '(info-link "(prettier)prettier-infer-parser-flag")
:link `(url-link ,(eval-when-compile
(prettier--readme-link
"prettier-infer-parser-flag"))))
;;;###autoload
(put 'prettier-infer-parser-flag 'safe-local-variable 'booleanp)
(defcustom prettier-enabled-parsers '(angular
babel
babel-flow
css
elm
flow
graphql
html
java
json
less
lua
markdown
mdx
php
postgresql
pug
python
ruby
scss
solidity
svelte
swift
toml
typescript
vue
xml
yaml)
"Prettier parsers to enable.
A disabled parser won't be used unless
`prettier-infer-parser-flag' is non-nil and Prettier falls back
on it. Enabled parsers are not necessarily available, depending
on your Prettier version and which plug-ins you have installed."
:type
'(set
(const :tag "Angular (1.15+)" angular)
(const :tag "Babel (formerly Babylon)" babel)
(const :tag "Babel-Flow (1.15+)" babel-flow)
(const :tag "CSS (1.4+)" css)
(const :tag "Elm (2.0+?, requires plugin)" elm)
(const :tag "Flow" flow)
(const :tag "GraphQL (1.5+)" graphql)
(const :tag "Java (2.0+?, requires plugin)" java)
(const :tag "JSON (1.5+)" json)
(const :tag "JSON 5 (1.5+)" json5)
(const :tag "JSON.stringify (1.5+)" json-stringify)
(const :tag "LESS (1.4+)" less)
(const :tag "Lua (1.10+, requires plugin)" lua)
(const :tag "HTML (1.16+)" html)
(const :tag "Markdown (1.8+)" markdown)
(const :tag "MDX (1.15+)" mdx)
(const :tag "PHP (1.10+, requires plugin)" php)
(const :tag "PostgreSQL (1.10+, requires plugin" postgresql)
(const :tag "Pug (2.0+, requires plugin)" pug)
(const :tag "Python (1.10+, requires plugin)" python)
(const :tag "Ruby (1.10+, requires plugin)" ruby)
(const :tag "SCSS (1.4+)" scss)
(const :tag "Solidity (2.0+?, requires plugin)" solidity)
(const :tag "Svelte (1.16+, requires plugin)" svelte)
(const :tag "Swift (1.10+, requires plugin)" swift)
(const :tag "TOML (1.16+, requires plugin)" toml)
(const :tag "TypeScript (1.4+)" typescript)
(const :tag "Vue (1.10+)" vue)
(const :tag "XML (1.10+, requires plugin)" xml)
(const :tag "YAML (1.14+)" yaml))
:package-version '(prettier . "0.1.0")
:group 'prettier
:link '(info-link "(prettier)prettier-enabled-parsers")
:link `(url-link ,(eval-when-compile
(prettier--readme-link
"prettier-enabled-parsers"))))
(defcustom prettier-mode-ignore-buffer-function
#'prettier--in-node-modules-p
"A function called to selectively ignore certain buffers.
The function should return non-nil if command `prettier-mode'
should not be enabled for the current buffer."
:type 'function
:package-version '(prettier . "0.2.0")
:group 'prettier
:link '(info-link "(prettier)prettier-ignore-buffer-function")
:link `(url-link ,(eval-when-compile
(prettier--readme-link
"prettier-ignore-buffer-function"))))
(defcustom prettier-lighter
'(:eval
(concat
" Prettier"
(when (and prettier-last-parser prettier-version)
(format "[%s:%s]" prettier-last-parser prettier-version))))
"Mode line lighter for Prettier.
The value of this variable is a mode line template as in
`mode-line-format'. See Info Node `(elisp)Mode Line Format' for
more information. Note that it should contain a _single_ mode
line construct only.
Customize this variable to change how Prettier reports its status
in the mode line.
Set this variable to nil to disable the mode line completely."
:type 'sexp
:package-version '(prettier . "0.5.0")
:group 'prettier
:risky t
:link '(info-link "(prettier)prettier-lighter")
:link `(url-link ,(eval-when-compile
(prettier--readme-link
"prettier-lighter"))))
(defface prettier-inline-error
'((t :inherit compilation-error))
"Prettier face for errors."
:package-version '(prettier . "0.1.0")
:group 'prettier)
;;;; Non-customizable
(defconst prettier-benign-errors
'("Error: Couldn't resolve parser")
"Errors in this list are shown in the echo area.
Other errors are shown inline or in the error buffer.")
(defconst prettier-sync-settings
'(((fill-column ; built-in
js3-max-columns) ; js3-mode
:printWidth)
((enh-ruby-indent-tabs-mode ; enh-ruby-mode
indent-tabs-mode ; built-in
js3-indent-tabs-mode ; js3-mode
ruby-indent-tabs-mode) ; ruby-mode
:useTabs)
((c-basic-offset ; cc-mode, java-mode
css-indent-offset ; css-mode, scss-mode etc
elm-indent-offset ; elm-mode
enh-ruby-indent-level ; enh-ruby-mode
graphql-indent-level ; graphql-mode
handlebars-basic-offset ; handlebars-mode
js-indent-level ; js-mode
js2-basic-offset ; js2-mode
js3-indent-level ; js3-mode
lua-indent-level ; lua-mode
nxml-attribute-indent ; nxml-mode
nxml-child-indent ; nxml-mode
nxml-outline-child-indent ; nxml-mode
pug-tab-width ; pug-mode
python-indent ; python-mode
ruby-indent-level ; ruby-mode
sgml-basic-offset ; js2-mode, html-mode, svelte-mode
smie-indent-basic ; smie.el (generic)
standard-indent ; indent.el (generic)
swift-mode:basic-offset ; swift-mode.el
tab-width ; built-in
typescript-indent-level ; typescript-mode
web-mode-code-indent-offset ; web-mode
web-mode-css-indent-offset ; web-mode
yaml-indent-offset) ; yaml-mode
:tabWidth)
((js-indent-first-init)
nil)
;; Unless prettier has trailing commas disabled, don't warn
;; about their presence
((js2-strict-trailing-comma-warning
js3-strict-trailing-comma-warning)
:trailingComma
(lambda (trailing-comma)
(pcase trailing-comma
("es5" nil)
("all" nil)
(_ 'unchanged))))
;; When prettier has semicolons disabled, don't warn
;; about their absence
((js2-strict-missing-semi-warning
js3-strict-missing-semi-warning)
:semi
(lambda (semi)
(if semi 'unchanged nil)))
((web-mode-auto-quote-style)
:singleQuote
(lambda (single-quote)
(if single-quote 2 1)))
;; Force dtrt-indent mode off when we're controlling local config
((dtrt-indent)
nil))
"Settings to sync from Prettier to Emacs configuration.
A list of lists of two or three elements:
`(VAR-LIST SOURCE-CONFIGURATION [TRANSFORM-FUNCTION])'
VAR-LIST is a list of Emacs variables to set.
SOURCE-CONFIGURATION is either a keyword that specifies which
Prettier configuration option to use for setting the Emacs
variables, or - when not a keyword - a static value to set the
variables to.
TRANSFORM-FUNCTION is an optional function; when present, it is
called with the value of the Prettier option and the result is
used for setting the Emacs variables, unless it is the symbol
`unchanged'. If that symbol is returned, the Emacs variables
won't be touched.")
(eval-when-compile
(defconst prettier-error-rx
'(and (submatch (minimal-match
(zero-or-more (not cntrl))))
(zero-or-more " ")
"("
(submatch (one-or-more digit))
":"
(submatch (one-or-more digit))
")")))
(defun prettier--guess-js-ish ()
"Return which parsers to use for a buffer with a JS-like mode."
(cond
((and (boundp 'tide-mode)
tide-mode)
'(typescript babel flow babel-flow))
((and (boundp 'flow-minor-mode)
flow-minor-mode)
'(babel-flow flow babel))
(t
'(babel flow babel-flow))))
(defconst prettier-major-mode-parsers
`((angular-mode . (angular))
(elm-mode . (elm))
(svelte-mode . (svelte html))
(html-mode . (html))
(mhtml-mode . (html))
(java-mode . (java))
(js-mode . ,#'prettier--guess-js-ish)
(js2-mode . ,#'prettier--guess-js-ish)
(js3-mode . ,#'prettier--guess-js-ish)
(typescript-mode . (typescript))
(css-mode . (css))
(scss-mode . (scss))
(less-mode . (less))
(json-mode . (lambda ()
(if (and
buffer-file-name
(seq-contains
'("package.json"
"package-lock.json"
"composer.json")
(file-name-nondirectory buffer-file-name)))
'(json-stringify json json5)
'(json json5 json-stringify))))
(graphql-mode . (graphql))
(markdown-mode . (markdown))
(nxml-mode . (xml))
(pug-mode . (pug))
(solidity-mode . (solidity))
(toml-mode . (toml))
(vue-mode . (vue))
(yaml-mode . (yaml))
(lua-mode . (lua))
(ruby-mode . (ruby))
(enh-ruby-mode . (ruby))
(python-mode . (python))
(php-mode . (php))
(sql-mode . (postgresql))
(swift-mode . (swift)))
"Map from major mode to Prettier parsers.
In each element, car is the mode and cdr is either a list of
parser names as symbols, or a function (without arguments) that,
when called with buffer current, returns such a list.")
(defconst prettier-web-mode-content-type-parsers
`((nil . (html))
("javascript" . ,#'prettier--guess-js-ish)
("jsx" . ,#'prettier--guess-js-ish)
("typescript" . (typescript))
("css" . (css))
("json" . (json json5))
("markdown" . (markdown))
("ruby" . (ruby))
("sql" . (postgresql)))
"Map from `web-mode' content type to Prettier parsers.
In each element, car is the mode and cdr is either a list of
parser names as symbols, or a function (without arguments) that,
when called with buffer current, returns such a list.")
;;;; Variables
(defvar prettier-el-home (file-name-directory
(or load-file-name buffer-file-name))
"Directory with `prettier.el' and auxiliary files.")
(defvar prettier-error-regex
(eval-when-compile
(rx-to-string prettier-error-rx))
"Regular expression to use for parsing Prettier errors.")
(defvar prettier-compilation-regexps
(eval-when-compile
`(,(rx-to-string
`(and
line-start
(submatch (one-or-more (not (any ":" cntrl))))
":"
(zero-or-more " ")
,prettier-error-rx))
1 3 4 nil 2))
"Specifications for matching errors in prettier invocations.
See `compilation-error-regexp-alist' for help on their format.")
(defvar prettier-error-buffer-name
"*prettier errors*"
"Name to use for the buffer showing Prettier error messages.")
(defvar prettier-keep-server-buffer-flag nil
"Non-nil means not to kill server buffer when process ends.
For debugging only.")
(defvar prettier-show-benchmark-flag nil
"Non-nil means to show timing information.
For debugging and performance tuning only.")
(defvar prettier-processes (make-hash-table :test 'equal)
"Keep track of running node processes, keyed by `node-command'.
It's the name or path of the node executable `prettier--find-node'
returns.")
(defvar prettier-nvm-node-command-cache nil
"Cache for the result of `prettier--node-from-nvm'.")
;;;;; Local Variables
(defvar-local prettier-parsers nil
"Non-nil means to force Prettier to use these parsers.
The first parser (in list order) supported by the Prettier
version or any plug-ins will be used. If none of the given
parsers is supported, Prettier will fall back to inferring a
parser unless `prettier-infer-parser-flag' is nil.")
;;;###autoload
(put 'prettier-parsers 'safe-local-variable 'listp)
(defvar-local prettier-previous-local-settings nil
"Used to backup settings so they can be restored later.")
(defvar-local prettier-config-cache nil
"Used to memoize Prettier options")
(defvar-local prettier-error-overlay nil
"Used to remember the last error overlay")
(defvar-local prettier-last-error-marker nil
"Used to remember the last error marker")
(defvar-local prettier-last-parser nil
"The last parser used to format the whole file")
(defvar-local prettier-version nil
"The Prettier version used for this buffer")
;;;;; Imported Variables
;; For interop with web-mode.el
(defvar web-mode-content-type)
;;;; Commands
;;;###autoload
(defun prettier-prettify ()
"Prettify the whole current buffer, or the part it is narrowed to.
With prefix, ask for the parser to use"
(interactive "*")
(prettier--prettify
(or (when current-prefix-arg
(prettier--read-parsers))
(prettier--parsers))))
;;;###autoload
(defun prettier-prettify-region ()
"Prettify the current region.
With prefix, ask for the parser to use"
(interactive "*")
(prettier--prettify
(or (when current-prefix-arg
(prettier--read-parsers))
(prettier--parsers))
(region-beginning)
(region-end)))
(defun prettier--quit-all-processes ()
"Quit all Prettier sub-processes."
(maphash (lambda (_key process)
(quit-process process))
prettier-processes)
(clrhash prettier-processes))
(defun prettier--buffer-remote-p (&optional identification connected)
"Return `file-remote-p' result for the current buffer.
IDENTIFICATION and CONNECTED have the same meaning as
`file-remote-p'."
(and buffer-file-name
(apply #'file-remote-p
buffer-file-name
identification
connected)))
(defun prettier--pkg-version ()
"Return the version of the `prettier' package."
(package-version-join
(package-desc-version
(with-temp-buffer
(let ((src (or
;; load-file-name seemed like it would be useful
;; here, but didn't work in practice.
(locate-library "prettier.el")
;; This one shouldn't be needed:
(concat prettier-el-home "/prettier.el"))))
(insert-file-contents src))
(package-buffer-info)))))
(defun prettier-info ()
"Show a temporary buffer with diagnostic info.
Can be used when there is a problem finding Node or Prettier, and
should be used when filing bug reports."
(interactive)
(let ((info
(list
:emacs-version (emacs-version)
:prettier-el-version (prettier--pkg-version)
:buffer-file-name buffer-file-name
:remote-id (prettier--buffer-remote-p)
:major-mode major-mode
:exec-path exec-path
:env process-environment
:prettier-options
(condition-case err
(prettier--load-config)
(error (print err))))))
(with-current-buffer (get-buffer-create "prettier-info.el")
(setq buffer-read-only nil)
(erase-buffer)
(princ
";; Please create a Gist with the contents of this buffer.\n
;; MAKE SURE TO REMOVE ANY SENSITIVE INFORMATION FIRST\n\n"
(current-buffer))
(pp info (current-buffer))
(setq buffer-read-only t)
(emacs-lisp-mode)
(goto-char (point-min))
(display-buffer (current-buffer)))))
;;;;; Modes
;;;###autoload
(define-minor-mode prettier-mode
"Runs prettier on file save when this mode is turned on"
:lighter prettier-lighter
(if prettier-mode
(progn
(when (not (eq prettier-pre-warm 'none))
(prettier--get-process
(eq prettier-pre-warm 'full)))
(when prettier-mode-sync-config-flag
(prettier--maybe-sync-config)
(add-hook 'after-change-major-mode-hook
#'prettier--maybe-sync-config
'append
'local))
(add-hook 'before-save-hook
#'prettier-prettify
nil
'local))
(remove-hook 'before-save-hook
#'prettier-prettify
'local)
(remove-hook 'after-change-major-mode-hook
#'prettier--maybe-sync-config
'local)))
;;;###autoload
(define-globalized-minor-mode
global-prettier-mode
prettier-mode
(lambda ()
(when (and (not prettier-mode)
(or (null prettier-mode-ignore-buffer-function)
(not (funcall
prettier-mode-ignore-buffer-function)))
(prettier--parsers))
(with-temp-message
(when (not (eq prettier-pre-warm 'none))
"Prettier pre-warming...")
(prettier-mode))))
:group 'prettier)
(add-hook
'global-prettier-mode-hook
(lambda ()
(unless global-prettier-mode
(prettier--quit-all-processes)
(setq prettier-nvm-node-command-cache nil))))
;;;; Support
(defun prettier--in-node-modules-p ()
"Return t if current buffer's file is beneath `node_modules'."
(and buffer-file-name
(string-match "/node_modules/" buffer-file-name)))
(defun prettier--read-parsers ()
"Read a Prettier parser from the minibuffer.
Returns a symbol identifying the parser (matching a known
Prettier parser name) or nil when nothing was selected."
(let*
((parsers (prettier--parsers))
(default (when parsers (symbol-name (car parsers))))
(result
(completing-read
(if default
(format
"Prettier parser (%s): "
default)
"Prettier parser (infer): ")
(mapcar (apply-partially #'nth 3)
(cdr (get 'prettier-enabled-parsers
'custom-type))) ; collection
nil ; predicate
nil ; require-match
nil ; initial
'prettier-parser-history ; history
default))) ; default
(when (> (length result) 0)
(list (intern result)))))
(defun prettier--maybe-sync-config ()
"Sync Prettier configuration in current buffer when appropriate.
Configuration is synced when `prettier-mode-sync-config-flag' is
non-nil and `prettier' is enabled in current buffer."
(when (and prettier-mode
prettier-mode-sync-config-flag
(null prettier-config-cache))
(with-temp-message "Prettier syncing config"
(prettier--sync-config))))
(defun prettier--create-process (server-id node-command)
"Create a new server process for SERVER-ID.
The process is a long-running server process that receives
requests, performs corresponding actions (such as formatting code
with Prettier) and returning a response.
SERVER-ID should be the symbol `local' for launching a local
process, or a remote identification as defined by `tramp-mode'
when launching a remote process. Each process is started with
NODE-COMMAND.
The process is launched by running `node' with a minified version
of `bootstrap.js` as a script provided on the command line; this
then loads a minified version of `prettier-el.js' from stdin.
This setup is used for the following reasons:
- The script can't be loaded from the local file system because
the process might be launched remotely.
- The whole script can't be put on the command line because doing
so doesn't work reliably via `tramp'.
Additional considerations were:
- The payload sent via stdin is base64-encoded with line breaks
to ensure it can be sent via `tramp'.
- The payload is minified and gzip-compressed to help with
startup time via `tramp' on slow, non-compressed connections."
(let* ((buf (get-buffer-create
(format "*prettier %s*"
(or (prettier--buffer-remote-p 'host)
"(local)"))))
(payload
(with-temp-buffer
(insert-file-contents-literally
(concat prettier-el-home
"prettier-el.js.gz.base64"))
(buffer-string)))
(new-process
(progn
(with-current-buffer buf
(erase-buffer)
(setq buffer-undo-list t))
(start-file-process
"prettier"
buf
(prettier--pick-localname node-command)
"--eval"
(with-temp-buffer
(insert-file-contents-literally
(concat prettier-el-home "bootstrap-min.js"))
(buffer-string))
(number-to-string (length payload))))))
(set-process-query-on-exit-flag new-process nil)
(set-process-sentinel
new-process
(lambda (proc event)
(unless (and (eq (process-status proc) 'signal)
(eq (process-exit-status proc) 3))
(message "prettier-process (%s) quit unexpectedly: %s"
(process-get proc :server-id)
(string-trim event)))
(unless prettier-keep-server-buffer-flag
(kill-buffer (process-buffer proc)))
(remhash node-command prettier-processes)))
(set-process-coding-system new-process 'binary 'binary)
(process-put new-process :server-id server-id)
(condition-case nil
(process-send-string new-process payload)
(file-error
(prettier--show-error
"Cannot start prettier server on `%s': %s
%s"
server-id
(with-current-buffer (process-buffer new-process)
(decode-coding-region (point-min) (point-max) 'utf-8 t))
(prettier--startup-error-info server-id))))
new-process))
(defun prettier--startup-error-info (server-id)
"Return text explaining how to fix startup on host SERVER-ID.
SERVER-ID should be the symbol `local' for explaining issues with
a local process, or a remote identification as defined by
`tramp-mode' for a remote process."
(if (eq server-id 'local)
"Install Node or set `exec-path' so that it can be found.
Consider using package `exec-path-from-shell' or `nvm'."
"Install Node on that host or set `tramp-remote-path' so that
it can be found."))
(defun prettier--get-process (&optional warmup-p)
"Get or create a sub-process for the current buffer.
Non-nil WARMUP-P means that the process will be warmed up for the
current file.
If there is already a sub-process running on the host (local or
remote) corresponding to the current buffer, return that;
otherwise, launch a new one."
(let* ((server-id (or (prettier--buffer-remote-p)
'local))
(node-command (prettier--find-node server-id))
(existing-process
(gethash node-command prettier-processes))
(existing-live-process
(when (and existing-process
(process-live-p existing-process))
existing-process)))
(if (and existing-live-process (null warmup-p))
existing-live-process
(let ((start-time (current-time)))
(prog1
(let ((process
(or existing-live-process
(puthash
node-command
(prettier--create-process server-id
node-command)
prettier-processes))))
(when warmup-p
(prettier--request-iter
process
(list
"w"
(if prettier-editorconfig-flag "E" "e")
(prettier--local-file-name)
"\n\n")
t))
process)
(when prettier-show-benchmark-flag
(prettier--delayed-message
"Prettier process preparation for %s took %.1fms"
(prettier--local-file-name)
(* 1000 (float-time (time-subtract (current-time)
start-time))))))))))
(defun prettier--delayed-message (string &rest objects)
"Like `message', but delayed slightly.
STRING and OBJECTS are like for `format'."
(run-at-time
"1 sec"
nil
(lambda ()
(apply #'message string objects))))
(defun prettier--show-error (string &rest objects)
"Show STRING and OBJECTS as formatted error message.
The error is shown in a dedicated buffer that is shown in a
separate window."
(let ((errbuf (get-buffer-create
prettier-error-buffer-name)))
(with-current-buffer errbuf
(setq buffer-read-only nil)
(save-excursion
(erase-buffer)
(insert (ansi-color-apply
(apply #'format string objects))))
(compilation-mode)
(setq-local compilation-error-screen-columns nil)
(display-buffer errbuf))))
(defun prettier--show-remote-error (filename error-msg)
"Show the remote ERROR-MSG for FILENAME as appropriate."
(cond
((seq-some
(lambda (prefix)
(string-prefix-p prefix error-msg))
prettier-benign-errors)
(prettier--delayed-message "%s" error-msg))
((and prettier-inline-errors-flag
(string-match
(concat "^" prettier-error-regex "$")
error-msg))
(let ((row (string-to-number (match-string 2 error-msg)))
(column (string-to-number (match-string 3 error-msg)))
(first-line (match-string 1 error-msg)))
(when prettier-error-overlay
(delete-overlay prettier-error-overlay))
(save-excursion
(widen)
(goto-char (point-min))
(forward-line row)
(end-of-line)
(let* ((eol (point))
(ov (make-overlay eol (1+ eol)))
(str (concat (when (eq eol (point-max)) "\n")
(make-string (1- column) 32)
"^ "
(propertize first-line
'face
'prettier-inline-error)
"\n")))
(overlay-put ov 'phantom t)
(overlay-put ov 'after-string str)
(setq prettier-error-overlay ov)))))
(t
(prettier--show-error "%s: %s" filename error-msg))))
(defun prettier--clear-errors ()
"Kill any error buffers and remove any overlays."
(let ((errbuf (get-buffer prettier-error-buffer-name)))
(when prettier-error-overlay
(delete-overlay prettier-error-overlay))
(when errbuf
(let ((win (get-buffer-window errbuf)))
(if win
(quit-window t win)
(kill-buffer errbuf))))))
(defun prettier--sync-config ()
"Try to sync prettier configuration for current buffer.
Tries loading the configuration, ignoring failure with a message.
If loaded successfully, uses it to set a variety of buffer-local
variables in an effort to make pre-formatting indentation etc as
close to post-formatting as possible."
(condition-case-unless-debug err
(let ((config (prettier--load-config)))
(setq
prettier-config-cache
(plist-get config :options)
prettier-last-parser
(plist-get config :bestParser)
prettier-version
(plist-get (plist-get config :versions) :prettier)
prettier-previous-local-settings
(seq-filter
#'identity
(apply
#'append
(mapcar
(lambda (setting)
(let* ((vars (nth 0 setting))
(source (nth 1 setting))
(value (funcall
(or (nth 2 setting) #'identity)
(if (keywordp source)
(plist-get prettier-config-cache
source)
source))))
(unless (eq value 'unchanged)
(mapcar
(lambda (var)
(when (boundp var)
(let ((result
(list var (local-variable-p var)
(eval var)
value)))
(set (make-local-variable var) value)
result)))
vars))))
prettier-sync-settings)))))
;; Ignore any errors but print a warning
((debug error)
(message "Could not sync Prettier config, consider setting \
`prettier-mode-sync-config-flag' to nil: %S" err))))
(iter2-defun prettier--request-iter (prettier-process
request
&optional fire-and-forget-p)
"Send REQUEST to PRETTIER-PROCESS, yield commands."
(condition-case err
(let* ((p (point-min))
(buf (process-buffer prettier-process)))
(process-send-string prettier-process
(apply #'concat request))
(unless fire-and-forget-p
(unwind-protect
(catch 'end-of-message
(with-current-buffer buf
(while t
(while
(null
(save-excursion
(goto-char p)
(when