-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathprettier.el
1820 lines (1587 loc) · 65.2 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 <[email protected]>
;; Version: 1.3.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") (editorconfig "0.9"))
;; 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 <https://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)
(require 'package)
(require 'editorconfig)
(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#"
anchor))
;; Fallback for Emacs < 27
(defmacro prettier--combine-change-calls (beg end &rest body)
(if (fboundp 'combine-change-calls)
`(combine-change-calls ,beg ,end ,@body)
`(when (>= ,end ,beg) (combine-after-change-calls ,@body))))
;; Fallback for Emacs < 27
(defmacro prettier--replace-buffer-contents (source &optional max-secs max-costs)
(if (>= emacs-major-version 27)
`(replace-buffer-contents ,source ,max-secs ,max-costs)
`(replace-buffer-contents ,source))))
;;;; 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-prettify-on-save-flag t
"Non-nil means to prettify (format) buffer on save."
:type 'boolean
:package-version '(prettier . "1.3.0")
:group 'prettier
:link '(info-link "(prettier)prettier-prettify-on-save-flag")
:link `(url-link ,(eval-when-compile
(prettier--readme-link
"prettier-prettify-on-save-flag"))))
;;;###autoload
(put 'prettier-prettify-on-save-flag 'safe-local-variable 'booleanp)
(defcustom prettier-diff-timeout-seconds 1.0
"How many seconds the diff exploration phase may take in total.
This is the budget available for all diff operations during a
formatting run. It is shared between diffing in the Node process
and any `replace-buffer-contents' invocations resulting from the
edits.
You can set this to zero to disable timeouts altogether, in which
case all diff operations will always run to completion.
This is essentially an upper bound on the duration of the diff
operation, which is the biggest part of the overhead added by
this package on top of formatting itself. If the diff operation
is stopped early, the buffer will still be formatted correctly
but point (and region, overlays, etc.) might not be adjusted
correctly.
This setting shouldn't matter much for small files, or for large
files with only few individual edits resulting from Prettier
formatting, but it does matter for large files with many
edits (such as large foreign files never before formatted with
Prettier, or formatted with different settings) as these tend to
cause quite a lot of work for the diffing operation.
You may want to increase this setting (or disable it by setting
it to zero) if you care about point, region, etc. being moved to
the correct location in all cases, and don't mind waiting a bit
longer for larger files. On the other hand, if you're impatient
or if you don't care that point might be off in some cases, you
may want to decrease it."
:type 'number
:package-version '(prettier . "1.4.0")
:group 'prettier
:link '(info-link "(prettier)prettier-diff-timeout-seconds")
:link `(url-link ,(eval-when-compile
(prettier--readme-link
"prettier-diff-timeout-seconds"))))
;;;###autoload
(put 'prettier-diff-timeout-seconds 'safe-local-variable 'numberp)
(defcustom prettier-diff-edit-cost 100
"The edit cost for diff cleanup, or 0 to disable cleanup.
This setting dictates how aggressively the individual edits
resulting from a formatting operation get coalesced into more
coarsely grained edits. Benchmarks indicate that moderate
coalescence performs best compared to aggressive and conservative
settings.
The default setting should serve well, but you should feel free
to use the benchmarks included with this package, or run your
own, to see if you can tweak it to a value ideal for your system
and use case."
:type 'natnum
:package-version '(prettier . "1.4.0")
:group 'prettier
:link '(info-link "(prettier)prettier-diff-edit-cost")
:link `(url-link ,(eval-when-compile
(prettier--readme-link
"prettier-diff-edit-cost"))))
;;;###autoload
(put 'prettier-diff-edit-cost 'safe-local-variable 'natnump)
(defcustom prettier-enabled-parsers '(angular
babel
babel-flow
babel-ts
css
elm
espree
flow
graphql
html
java
json
json5
json-stringify
less
lua
markdown
mdx
meriyah
php
postgresql
pug
python
ruby
scss
sh
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 "Babel-TS (2.0+)" babel-ts)
(const :tag "CSS (1.4+)" css)
(const :tag "Elm (2.0+?, requires plugin)" elm)
(const :tag "Espree (2.2+)" espree)
(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 "Meriyah (2.2+)" meriyah)
(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 "Shell (2.0+)" sh)
(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
'(((js3-max-columns) ; js3-mode
:printWidth)
((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
((or (and (boundp 'tide-mode)
tide-mode)
(and (fboundp 'lsp-buffer-language)
(ignore-errors
(member (lsp-buffer-language)
'("typescript" "typescriptreact")))))
'(typescript babel-ts babel meriyah espree flow babel-flow))
((and (boundp 'flow-minor-mode)
flow-minor-mode)
'(babel-flow flow babel meriyah espree))
(t
'(babel meriyah espree 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 babel-ts))
(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))
(sh-mode . (sh))
(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 babel-ts))
("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-timeout-seconds 20
"Number of seconds before aborting and restarting Prettier.")
(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'.")
(defvar prettier-parser-history nil
"History for `prettier--read-parsers'.")
(defvar prettier-min-batch-gap 100
"Minimum length of a gap for starting a new change batch.
When grouping the changes resulting from a formatting operation
into batches, for purposes of reducing the number of invocations
of `before-change' and `after-change' hooks, a gap of this many
characters will cause a new batch to be started.
The smaller this number, the more batches will be applied, with
the downside being that the hooks might be invoked too
frequently. The larger this number, the fewer batches will be
applied, with the downside being that the hooks might be called
with a needlessly large region.
If this is set to one or less, only consecutive delete/insert
pairs will be grouped into a batch.
The ideal number for this setting depends on the nature of the
functions that get called in the hooks.")
(defvar prettier--file-less-config-cache (make-hash-table)
"Cache for file-less Prettier configuration.")
;;;;; 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-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)
(setq prettier-nvm-node-command-cache nil))
(defun prettier-restart ()
"Restart Prettier in all buffers.
This will cause all caches to be cleared and the latest version
of the sidecar JavaScript file to be used. It is executed every
time this package is loaded which is intended to ensure you're
running the latest when the package is upgraded.
You should run this function whenever any relevant configuration
changes, such as when you install a new version of Node,
Prettier, or any plugins; when you install or uninstall Prettier
as a local npm package in a directory from which you already have
files open in Emacs; or when you change Prettier settings that
might affect any open files."
(interactive)
(prettier--quit-all-processes)
(let* (wait-timer
(callback
(lambda ()
(when (zerop (hash-table-count prettier-processes))
(cancel-timer wait-timer)
(unless (eq prettier-pre-warm 'none)
(mapc (lambda (buf)
(with-current-buffer buf
(when (and (boundp 'prettier-mode)
prettier-mode)
(prettier--get-process
(eq prettier-pre-warm 'full)))))
(buffer-list)))
(message "Prettier restart complete.")))))
(setq wait-timer (run-with-timer 0.1 0.1 callback))))
(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--maybe-prettify-on-save ()
"Prettify, but only if `prettier-prettify-on-save-flag' is set."
(when prettier-prettify-on-save-flag
(prettier-prettify)))
(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
"Sync Prettier settings and format on file save.
For more information see Info node `(prettier)Top'."
:lighter prettier-lighter
(if prettier-mode
(progn
(unless (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--maybe-prettify-on-save
nil
'local))
(remove-hook 'before-save-hook
#'prettier--maybe-prettify-on-save
'local)
(remove-hook 'after-change-major-mode-hook
#'prettier--maybe-sync-config
'local)
(prettier--revert-synced-config)
(setq prettier-last-parser nil
prettier-last-error-marker nil
prettier-version nil
prettier-previous-local-settings nil)))
(defun prettier--turn-on-if-appropriate ()
"Turn on prettier-mode in current buffer if appropriate."
(when (and (not prettier-mode)
(or (null prettier-mode-ignore-buffer-function)
(not (funcall
prettier-mode-ignore-buffer-function)))
(prettier--parsers))
(with-temp-message
(unless (eq prettier-pre-warm 'none)
"Prettier pre-warming...")
(prettier-mode))))
;;;###autoload
(define-globalized-minor-mode
global-prettier-mode
prettier-mode
prettier--turn-on-if-appropriate
:group 'prettier)
(add-hook
'global-prettier-mode-hook
(lambda ()
(unless global-prettier-mode
(prettier--quit-all-processes))))
;;;; Support
(defun prettier--read-aux-file (file-name)
"Read supplemental file named FILE-NAME, return as string."
(with-temp-buffer
(insert-file-contents-literally
(or
(cl-find-if #'file-exists-p
(list (concat prettier-el-home file-name)
(concat prettier-el-home "dist/" file-name)))
(error "Cannot find supplemental file %S" file-name)))
(buffer-string)))
(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 sync is attempted when
`prettier-mode-sync-config-flag' is non-nil and `prettier' is
enabled in current buffer.
Any failures while loading or setting the configuration are
ignored, a warning is printed in this case."
(when (and prettier-mode
prettier-mode-sync-config-flag)
(condition-case-unless-debug err
(let ((config (prettier--load-config-cached)))
(when config
(prettier--set-config config)))
;; 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)))))
(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
(prettier--read-aux-file "prettier-el.js.gz.base64"))
(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"
(prettier--read-aux-file "bootstrap-min.js")
(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 (%s)"
(process-get proc :server-id)
(string-trim event)
(buffer-string)))
(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