This repository has been archived by the owner on Nov 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhasky-extensions.el
384 lines (354 loc) · 15.1 KB
/
hasky-extensions.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
;;; hasky-extensions.el --- Toggle Haskell language extensions -*- lexical-binding: t; -*-
;;
;; Copyright © 2016–2019 Mark Karpov <[email protected]>
;;
;; Author: Mark Karpov <[email protected]>
;; URL: https://github.com/hasky-mode/hasky-extensions
;; Version: 0.2.0
;; Package-Requires: ((emacs "24.4") (avy-menu "0.2"))
;; Keywords: programming
;;
;; 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:
;; The package provides a way to add and remove Haskell language extensions
;; easily from any place in a file without moving the point. This is done
;; with help of a menu where the most popular language extensions are
;; assigned just one letter to toggle, while the others require two key
;; strokes.
;;
;; Naturally, when performing toggling of the extensions, they are kept
;; sorted and aligned automatically for you.
;;; Code:
(require 'avy-menu)
(require 'cl-lib)
(require 'simple)
(defgroup hasky-extensions nil
"Toggle Haskell language extensions."
:group 'programming
:tag "Hasky Extensions"
:prefix "hasky-extensions-"
:link '(url-link :tag "GitHub"
"https://github.com/hasky-mode/hasky-extensions"))
(defface hasky-extensions-disabled
'((t (:inherit font-lock-comment-face)))
"Face used to print disabled Haskell extensions in the menu.")
(defface hasky-extensions-enabled
'((t (:inherit font-lock-keyword-face)))
"Face used to print enabled Haskell extensions in the menu.")
(defcustom hasky-extensions
'("OverloadedStrings"
"RecordWildCards"
"CPP"
"FlexibleContexts"
"FlexibleInstances"
"TemplateHaskell"
"Arrows"
"BangPatterns"
"DataKinds"
"DeriveAnyClass"
"DeriveFoldable"
"DeriveFunctor"
"DeriveGeneric"
"DeriveTraversable"
"DerivingVia"
"ExistentialQuantification"
"ExplicitForAll"
"ForeignFunctionInterface"
"FunctionalDependencies"
"GADTs"
"GeneralizedNewtypeDeriving"
"InstanceSigs"
"KindSignatures"
"LambdaCase"
"MagicHash"
"MultiParamTypeClasses"
"MultiWayIf"
"NoImplicitPrelude"
"OverloadedLists"
"PolyKinds"
"QuantifiedConstraints"
"QuasiQuotes"
"RankNTypes"
"RecursiveDo"
"ScopedTypeVariables"
"StandaloneDeriving"
"TupleSections"
"TypeApplications"
"TypeFamilies"
"TypeOperators"
"TypeSynonymInstances"
"UndecidableInstances")
"List of commonly used Haskell extensions."
:tag "List of commonly used Haskell extensions"
:type '(repeat (string :tag "Extension name")))
(defcustom hasky-extensions-docs
'(("AllowAmbiguousTypes" "ambiguous-types-and-the-ambiguity-check")
("ApplicativeDo" "applicative-do-notation")
("Arrows" "arrow-notation")
("BangPatterns" "bang-patterns-informal")
("BinaryLiterals" "ghc-flag--XBinaryLiterals")
("ConstrainedClassMethods" "constrained-class-method-types")
("ConstraintKinds" "the-constraint-kind")
("DataKinds" "datatype-promotion")
("DefaultSignatures" "default-method-signatures")
("DeriveAnyClass" "deriving-any-other-class")
("DeriveDataTypeable" "deriving-data-instances")
("DeriveFoldable" "deriving-instances-of-extra-classes-data-etc")
("DeriveFunctor" "deriving-instances-of-extra-classes-data-etc")
("DeriveGeneric" "deriving-instances-of-extra-classes-data-etc")
("DeriveLift" "deriving-instances-of-extra-classes-data-etc")
("DeriveTraversable" "deriving-instances-of-extra-classes-data-etc")
("DerivingStrategies" "deriving-strategies")
("DerivingVia" "extension-DerivingVia")
("DisambiguateRecordFields" "record-field-disambiguation")
("EmptyCase" "empty-case-alternatives")
("EmptyDataDecls" "data-types-with-no-constructors")
("ExistentialQuantification" "existentially-quantified-data-constructors")
("ExplicitForAll" "explicit-universal-quantification-forall")
("ExplicitNamespaces" "explicit-namespaces-in-import-export")
("FlexibleContexts" "the-superclasses-of-a-class-declaration")
("FlexibleInstances" "relaxed-rules-for-the-instance-head")
("FunctionalDependencies" "functional-dependencies")
("GADTSyntax" "declaring-data-types-with-explicit-constructor-signatures")
("GADTs" "generalised-algebraic-data-types-gadts")
("GeneralizedNewtypeDeriving" "generalised-derived-instances-for-newtypes")
("ImplicitParams" "implicit-parameters")
("ImpredicativeTypes" "impredicative-polymorphism")
("IncoherentInstances" "overlapping-instances")
("InstanceSigs" "instance-signatures-type-signatures-in-instance-declarations")
("KindSignatures" "explicitly-kinded-quantification")
("LambdaCase" "lambda-case")
("LiberalTypeSynonyms" "liberalised-type-synonyms")
("MagicHash" "the-magic-hash")
("MonadComprehensions" "monad-comprehensions")
("MonoLocalBinds" "let-generalisation")
("MultiParamTypeClasses" "multi-parameter-type-classes")
("MultiWayIf" "multi-way-if-expressions")
("NamedFieldPuns" "record-puns")
("NamedWildCards" "named-wildcards")
("NegativeLiterals" "negative-literals")
("NoImplicitPrelude" "rebindable-syntax-and-the-implicit-prelude-import")
("NoMonomorphismRestriction" "switching-off-the-dreaded-monomorphism-restriction")
("NoTraditionalRecordSyntax" "traditional-record-syntax")
("NullaryTypeClasses" "nullary-type-classes")
("NumDecimals" "fractional-looking-integer-literals")
("OverlappingInstances" "overlapping-instances")
("OverloadedLists" "overloaded-lists")
("OverloadedStrings" "overloaded-string-literals")
("PackageImports" "package-qualified-imports")
("ParallelListComp" "parallel-list-comprehensions")
("PartialTypeSignatures" "partial-type-signatures")
("PatternSynonyms" "pattern-synonyms")
("PolyKinds" "kind-polymorphism-and-type-in-type")
("PostfixOperators" "postfix-operators")
("QuantifiedConstraints" "quantified-constraints")
("QuasiQuotes" "template-haskell-quasi-quotation")
("Rank2Types" "arbitrary-rank-polymorphism")
("RankNTypes" "arbitrary-rank-polymorphism")
("RebindableSyntax" "rebindable-syntax-and-the-implicit-prelude-import")
("RecordWildCards" "record-wildcards")
("RecursiveDo" "the-recursive-do-notation")
("RoleAnnotations" "role-annotations")
("Safe" "safe-imports")
("ScopedTypeVariables" "lexically-scoped-type-variables")
("StandaloneDeriving" "stand-alone-deriving-declarations")
("StaticPointers" "static-pointers")
("StrictData" "strict-by-default-data-types")
("TemplateHaskell" "template-haskell")
("TransformListComp" "generalised-sql-like-list-comprehensions")
("Trustworthy" "safe-imports")
("TupleSections" "tuple-sections")
("TypeFamilies" "type-families")
("TypeFamilyDependencies" "injective-type-families")
("TypeInType" "kind-polymorphism-and-type-in-type")
("TypeOperators" "type-operators")
("TypeSynonymInstances" "relaxed-rules-for-the-instance-head")
("UnboxedTuples" "unboxed-tuples")
("UndecidableInstances" "instance-termination-rules")
("UnicodeSyntax" "unicode-syntax")
("Unsafe" "safe-imports")
("ViewPatterns" "view-patterns"))
"A collection of extensions with links to GHC user guide."
:tag "List of all Haskell extensions with links to docs"
:type '(repeat (list (string :tag "Extension name")
(string :tag "Anchor"))))
(defcustom hasky-extensions-reach 5000
"Max number of characters from beginning of file to search.
Very large files can either slow down the process of extensions
detection or cause stack overflows, thus we limit number of
characters the package traverses. The default value should be
appropriate for most users since language extension pragmas are
typically placed at the beginning of a file. If you wish to
disable the limitation, set this value to NIL (not recommended)."
:tag "How many characters from beginning of file to scan"
:type 'integer)
(defcustom hasky-extensions-sorting t
"Whether to keep the collection of extensions sorted."
:tag "Keep list of extensions sorted"
:type 'boolean)
(defcustom hasky-extensions-aligning t
"Whether to keep closing braces of extension pragmas aligned."
:tag "Keep closing braces of extension pragmas aligned"
:type 'boolean)
(defcustom hasky-extensions-prettifying-hook nil
"Hook to run after prettifying of extension section."
:tag "Hooks to run after prettifying list of extensions"
:type 'hook)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The editing itself
(defun hasky-extensions--next-ext (&optional ext)
"Find and return name of next extension in the file or NIL.
If EXT is supplied, find this particular extension."
(re-search-forward
(concat "^\\s-*{-#\\s-*LANGUAGE\\s-+\\("
(if ext
(regexp-quote ext)
"[[:alnum:]]+")
"\\)\\s-*#-}\\s-*?$")
hasky-extensions-reach t))
(defun hasky-extensions-list ()
"List all active Haskell extensions in current file.
Returned list is always a fresh one (you can perform destructive
operations on it without fear).
This does not take into account extensions enabled in Cabal file
with “default-extensions” or similar settings."
(let (exts)
(save-excursion
(goto-char (point-min))
(while (hasky-extensions--next-ext)
(push (match-string-no-properties 1) exts)))
exts))
(defun hasky-extensions--prettify-exts ()
"Find, sort, and align extensions in current file if necessary."
(save-excursion
(goto-char (point-min))
(let ((beg (when (hasky-extensions--next-ext)
(match-beginning 0))))
(when beg
(goto-char beg)
(while (progn
(forward-line)
(when (looking-at "\\(^\\s-+\\){-#")
(delete-region (match-beginning 1) (match-end 1)))
(looking-at "^\\s-*{-#.*?#-}\\s-*?$")))
(let ((end (point))
(indent-tabs-mode nil))
(when hasky-extensions-sorting
(sort-lines nil beg end))
(when hasky-extensions-aligning
(align-regexp beg end "\\(\\s-*\\)#-}"))))))
(run-hooks 'hasky-extensions-prettifying-hook))
(defun hasky-extensions-add (extension)
"Insert EXTENSION into appropriate place in current file."
;; NOTE There are several scenarios we should support. First, if file
;; contains some extensions already, we should add the new one to them.
;; If there is no extensions in the file yet, place the new one before
;; module declaration (with one empty line between them). If The file
;; contains no module declaration yet, place the new extension after
;; header. If the file has no header, place the new extension at the
;; beginning of the file.
(save-excursion
(let ((ext (format "{-# LANGUAGE %s #-}\n" extension)))
(cond ((progn
(goto-char (point-min))
(hasky-extensions--next-ext))
(beginning-of-line))
((progn
(goto-char (point-min))
(re-search-forward
"^module"
hasky-extensions-reach
t))
(beginning-of-line)
(open-line 1))
((let (going)
(goto-char (point-min))
(while (re-search-forward
"^--.*?$"
hasky-extensions-reach
t)
(setq going t))
going)
(goto-char (match-end 0))
(forward-line)
(newline))
(t (goto-char (point-min))))
(insert ext)
(hasky-extensions--prettify-exts))))
(defun hasky-extensions-remove (extension)
"Remove EXTENSION from current file (if present)."
(save-excursion
(goto-char (point-min))
(when (hasky-extensions--next-ext extension)
(delete-region (match-beginning 0) (match-end 0))
(unless (eobp)
(when (looking-at "$")
(delete-char 1)))
(hasky-extensions--prettify-exts))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; User interface
;;;###autoload
(defun hasky-extensions ()
"Invoke a menu for managing Haskell language extensions."
(interactive)
(let ((exts (hasky-extensions-list))
(selected t))
(while selected
(setq
selected
(avy-menu
"*hasky-extensions*"
(cons
"Haskell Extensions"
(list
(cons
"Pane"
(mapcar
(lambda (x)
(let ((active (cl-find x exts :test #'string=)))
(cons
(propertize
x
'face
(if active
'hasky-extensions-enabled
'hasky-extensions-disabled))
(cons x active))))
hasky-extensions))))))
(when selected
(cl-destructuring-bind (ext . active) selected
(if active
(progn
(hasky-extensions-remove ext)
(setq exts (cl-delete ext exts :test #'string=)))
(hasky-extensions-add ext)
(cl-pushnew ext exts :test #'string=)))))))
;;;###autoload
(defun hasky-extensions-browse-docs (extension)
"Browse documentation about EXTENSION from GHC user guide in browser."
(interactive
(list
(let ((exts (mapcar #'car hasky-extensions-docs)))
(completing-read
"Extension: "
exts
nil t nil nil
(car exts)))))
(browse-url
(concat "https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#"
(cadr (assoc extension hasky-extensions-docs)))))
(provide 'hasky-extensions)
;;; hasky-extensions.el ends here