lisp-syntax-swine.lisp 61.9 KB
Newer Older
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
;;; -*- Mode: Lisp; Package: CLIMACS-LISP-SYNTAX -*-

;;;  (c) copyright 2005 by
;;;           Robert Strandh (strandh@labri.fr)
;;;  (c) copyright 2006 by
;;;           Troels Henriksen (athas@sigkill.dk)
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Library General Public
;;; License as published by the Free Software Foundation; either
;;; version 2 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Library General Public License for more details.
;;;
;;; You should have received a copy of the GNU Library General Public
;;; License along with this library; if not, write to the
;;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;;; Boston, MA  02111-1307  USA.

;;; Functionality designed to aid development of Common Lisp code.

(in-package :climacs-lisp-syntax)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Code interrogation/form analysis

(defparameter +cl-arglist-keywords+
  lambda-list-keywords)

(defparameter +cl-garbage-keywords+
  '(&whole &environment))

(defun arglist-keyword-p (arg)
  "Return T if `arg' is an arglist keyword. NIL otherwise."
  (when (member arg +cl-arglist-keywords+)
    t))

(defun split-arglist-on-keywords (arglist)
  "Return an alist keying lambda list keywords of `arglist'
to the symbols affected by the keywords."
  (let ((sing-result '())
        (env (position '&environment arglist)))
    (when env
      (push (list '&environment (elt arglist (1+ env))) sing-result)
      (setf arglist (remove-if (constantly t) arglist :start env :end (+ env 2))))
    (when (eq '&whole (first arglist))
      (push (subseq arglist 0 2) sing-result)
      (setf arglist (cddr arglist)))
    (do ((llk '(&mandatory &optional &key &allow-other-keys &aux &rest &body))
         (args (if (arglist-keyword-p (first arglist))
                   arglist
                   (cons '&mandatory arglist))
               (cdr args))
         (chunk '())
         (result '()))
        ((null args)
         (when chunk (push (nreverse chunk) result))
         (nreverse (nconc sing-result result)))
      (if (member (car args) llk)
          (progn
            (when chunk (push (nreverse chunk) result))
            (setf chunk (list (car args))))
          (push (car args) chunk)))))

(defun find-optional-argument-values (arglist provided-args &optional
                                      (split-arglist
                                       (split-arglist-on-keywords
                                        arglist)))
  "Return an association list mapping symbols of optional or
  keyword arguments from `arglist' to the specified values in
  `provided-args'. `Split-arglist' should be either a split
  arglist or nil, in which case it will be calculated from
  `arglist'."
  (flet ((get-args (keyword)
           (rest (assoc keyword split-arglist))))
    (let* ((mandatory-args-count (length (get-args '&mandatory)))
           (optional-args-count (length (get-args '&optional)))
           (keyword-args-count (length (get-args '&key)))
           (provided-args-count (length provided-args))
           (nonmandatory-args-count (+ keyword-args-count
                                       optional-args-count)))
      ;; First we check whether any optional arguments have even been
      ;; provided.
      (when (> provided-args-count
               mandatory-args-count)
        ;; We have optional arguments.
        (let (
              ;; Find the part of the provided arguments that concern
              ;; optional arguments.
              (opt-args-values (subseq provided-args
                                       mandatory-args-count
                                       (min provided-args-count
                                            nonmandatory-args-count)))
              ;; Find the part of the provided arguments that concern
              ;; keyword arguments.
              (keyword-args-values (subseq provided-args
                                           (min (+ mandatory-args-count
                                                   optional-args-count)
                                                provided-args-count))))
          (append (mapcar #'cons
                          (mapcar #'unlisted (get-args '&optional))
                          opt-args-values)

                  (loop
                     ;; Loop over the provided keyword symbols and
                     ;; values in the argument list. Note that
                     ;; little checking is done to ensure that the
                     ;; given symbols are valid - this is not a
                     ;; compiler, so extra mappings do not
                     ;; matter.
                     for (keyword value) on keyword-args-values by #'cddr
                     if (keywordp keyword)
                     collect (let ((argument-symbol
                                    (unlisted (find (symbol-name keyword)
                                                    (get-args '&key)
                                                    :key #'(lambda (arg)
                                                             (symbol-name (unlisted arg)))
                                                    :test #'string=))))
                               ;; We have to find the associated
                               ;; symbol in the argument list... ugly.
                               (cons argument-symbol
                                     value)))))))))

(defun find-affected-simple-arguments (arglist current-arg-index preceding-arg
                                       &optional (split-arglist (split-arglist-on-keywords arglist)))
  "Find the simple arguments of `arglist' that would be affected
  if an argument was intered at index `current-arg-index' in the
  arglist. If `current-arg-index' is nil, no calculation will be
  done (this function will just return nil). `Preceding-arg'
  should either be nil or the argument directly preceding
  point. `Split-arglist' should either be a split arglist or nil,
  in which case `split-arglist' will be computed from
  `arglist'. This function returns two values: The primary value
  is a list of symbols that should be emphasized, the secondary
  value is a list of symbols that should be highlighted."
  (when current-arg-index
    (flet ((get-args (keyword)
             (rest (assoc keyword split-arglist))))
      (let ((mandatory-argument-count (length (get-args '&mandatory))))
        (cond ((> mandatory-argument-count
                  current-arg-index)
               ;; We are in the main, mandatory, positional arguments.
               (let ((relevant-arg (elt (get-args '&mandatory)
                                        current-arg-index)))
                 ;; We do not handle complex argument lists here, only
                 ;; pure standard arguments.
                 (unless (and (listp relevant-arg)
                              (< current-arg-index mandatory-argument-count))
                   (values nil (list (unlisted relevant-arg))))))
              ((> (+ (length (get-args '&optional))
                     (length (get-args '&mandatory)))
                  current-arg-index)
               ;; We are in the &optional arguments.
               (values nil
                       (list (unlisted (elt (get-args '&optional)
                                            (- current-arg-index
                                               (length (get-args '&mandatory))))))))
              (t
               (let ((body-or-rest-args (or (get-args '&rest)
                                            (get-args '&body)))
                     (key-arg (find (format nil "~A" preceding-arg)
                                    (get-args '&key)
                                    :test #'string=
                                    :key #'(lambda (arg)
                                             (symbol-name (unlisted arg))))))
                 ;; We are in the &body, &rest or &key arguments.
                 (values
                  ;; Only emphasize the &key
                  ;; symbol if we are in a position to add a new
                  ;; keyword-value pair, and not just in a position to
                  ;; specify a value for a keyword.
                  (when (and (null key-arg)
                             (get-args '&key))
                    '(&key))
                  (append (when key-arg
                            (list (unlisted key-arg)))
                          body-or-rest-args)))))))))

(defun analyze-arglist-impl (arglist current-arg-indices preceding-arg provided-args)
  "The implementation for `analyze-arglist'."
  (let* ((split-arglist (split-arglist-on-keywords arglist))
         (user-supplied-arg-values (find-optional-argument-values
                                    arglist
                                    provided-args
                                    split-arglist))
         (mandatory-argument-count
          (length (rest (assoc '&mandatory split-arglist))))
         
         (current-arg-index (or (first current-arg-indices)
                                0))
         ret-arglist
         emphasized-symbols
         highlighted-symbols)
    ;; First, we find any standard arguments that should be
    ;; highlighted or emphasized, more complex, destructuring
    ;; arguments will be handled specially.
    (multiple-value-bind (es hs)
        (find-affected-simple-arguments arglist
                                        ;; If `current-arg-indices' is
                                        ;; nil, that means that we do
                                        ;; not have enough information
                                        ;; to properly highlight
                                        ;; symbols in the arglist.
                                        (and current-arg-indices
                                             current-arg-index)
                                        preceding-arg
                                        split-arglist)
      (setf emphasized-symbols es)
      (setf highlighted-symbols hs))
    ;; We loop over the arglist and build a new list, and if we have a
    ;; default value for a given argument, we insert it into the
    ;; list. Also, whenever we encounter a list in a mandatory
    ;; argument position, we assume that it is a destructuring arglist
    ;; and recursively call `analyze-arglist' on it to find the
    ;; arglist and emphasized and highlighted symbols for it.
    (labels ((generate-arglist (arglist)
               (loop
                  for arg-element in arglist
                  for arg-name = (unlisted arg-element)
                  for index from 0
                    
                  if (and (listp arg-element)
                          (> mandatory-argument-count
                             index))
                  collect (multiple-value-bind (arglist
                                                sublist-emphasized-symbols
                                                sublist-highlighted-symbols)
                              (analyze-arglist arg-element
                                               (rest current-arg-indices)
                                               preceding-arg
                                               (when (< index (length provided-args))
                                                 (listed (elt provided-args index))))
                            ;; Unless our `current-arg-index'
                            ;; actually refers to this sublist, its
                            ;; highlighted and emphasized symbols
                            ;; are ignored. Also, if
                            ;; `current-arg-indices' is nil, we do
                            ;; not have enough information to
                            ;; properly highlight symbols in the
                            ;; arglist.
                            (when (and current-arg-indices
                                       (= index current-arg-index))
                              (if (and (rest current-arg-indices))
                                  (setf emphasized-symbols
                                        (union (mapcar #'unlisted
                                                       sublist-emphasized-symbols)
                                               emphasized-symbols)
                                        highlighted-symbols
                                        (union sublist-highlighted-symbols
                                               highlighted-symbols))
                                  (setf emphasized-symbols
                                        (union (mapcar #'unlisted
                                                       arg-element)
                                               emphasized-symbols))))
                            arglist)
                  else if (assoc arg-name user-supplied-arg-values)
                  collect (list arg-name
                                (rest (assoc
                                       arg-name
                                       user-supplied-arg-values)))
                  else
                  collect arg-element)))
      (setf ret-arglist (generate-arglist arglist)))
    (list ret-arglist emphasized-symbols highlighted-symbols)))

(defun analyze-arglist (arglist current-arg-indices
                        preceding-arg provided-args)
  "Analyze argument list and provide information for highlighting
it. `Arglist' is the argument list that is to be analyzed,
`current-arg-index' is the index where the next argument would be
written (0 is just after the operator), `preceding-arg' is the
written argument preceding point and `provided-args' is a list of
the args already written.

Three values are returned: 

* An argument list with values for &optional and &key arguments
inserted from `provided-args'.

* A list of symbols that should be emphasized.

* A list of symbols that should be highlighted."
  (apply #'values (analyze-arglist-impl
                   arglist
                   current-arg-indices
                   preceding-arg
                   provided-args)))

(defun cleanup-arglist (arglist)
  "Remove elements of `arglist' that we are not interested in."
  (loop
     for arg in arglist
     with in-&aux                       ; If non-NIL, we are in the
                                        ; &aux parameters that should
                                        ; not be displayed.
                    
     with in-garbage                    ; If non-NIL, the next
                                        ; argument is a garbage
                                        ; parameter that should not be
                                        ; displayed.
     if in-garbage
     do (setf in-garbage nil)
     else if (not in-&aux)
     if (eq arg '&aux)
     do (setf in-&aux t)
     else if (member arg +cl-garbage-keywords+ :test #'eq)
     do (setf in-garbage t)
     else
     collect arg))

(defgeneric arglist-for-form (syntax operator &optional arguments)
  (:documentation
   "Return an arglist for `operator'")
  (:method (syntax operator &optional arguments)
    (declare (ignore arguments))
    (cleanup-arglist
     (arglist (get-usable-image syntax) operator))))

(defmethod arglist-for-form (syntax (operator list) &optional arguments)
  (declare (ignore arguments))
  (case (first operator)
    ('cl:lambda (cleanup-arglist (second operator)))))

(defun find-argument-indices-for-operand (syntax operand-form operator-form)
  "Return a list of argument indices for `argument-form' relative
  to `operator-form'. These lists take the form of (n m p), which
  means (aref form-operand-list n m p). A list of
  argument indices can have arbitrary length (but they are
  practically always at most 2 elements long). "
  (declare (ignore syntax))
  (let ((operator (first-form (children operator-form))))
    (labels ((worker (operand-form &optional the-first)
               ;; Cannot find index for top-level-form.
               (when (parent operand-form)
                 (let ((form-operand-list
                        (remove-if #'(lambda (form)
                                       (or (not (typep form 'form))
                                           (eq form operator)))
                                   (children (parent operand-form)))))

                   (let ((operand-position (position operand-form form-operand-list))
                         (go-on (not (eq operator-form (parent operand-form)))))
                     ;; If we find anything, we have to increment the
                     ;; position by 1, since we consider the existance
                     ;; of a first operand to mean point is at operand
                     ;; 2. Likewise, a position of nil is interpreted
                     ;; as 0.
                     (cons (if operand-position
                               (if (or the-first)
                                   (1+ operand-position)
                                   operand-position)
                               0)
                           (when go-on
                             (worker (parent operand-form)))))))))
      (nreverse (worker operand-form t)))))

(defun find-operand-info (mark-or-offset syntax operator-form)
  "Returns two values: The operand preceding `mark-or-offset' and
  the path from `operator-form' to the operand."
  (as-offsets ((mark-or-offset offset))
    (let* ((preceding-arg-token (form-before syntax offset))
           (indexing-start-arg
            (let* ((candidate-before preceding-arg-token)
                   (candidate-after (when (null candidate-before)
                                      (let ((after (form-after syntax offset)))
                                        (when after
                                          (parent after)))))
                   (candidate-around (when (null candidate-after)
                                       (form-around syntax offset)))
                   (candidate (or candidate-before
                                  candidate-after
                                  candidate-around)))
              (if (or (and candidate-before
                           (typep candidate-before 'incomplete-list-form))
                      (and (null candidate-before)
                           (typep (or candidate-after candidate-around)
                                  'list-form)))
                  ;; HACK: We should not attempt to find the location of
                  ;; the list form itself, so we create a new parser
                  ;; symbol, attach the list form as a parent and try to
                  ;; find the new symbol. That way we can get a list of
                  ;; argument-indices to the first element of the list
                  ;; form, even if it is empty or incomplete.
                  (let ((obj (make-instance 'parser-symbol)))
                    (setf (parent obj) candidate)
                    obj)
                  candidate)))
           (argument-indices (find-argument-indices-for-operand
                              syntax
                              indexing-start-arg
                              operator-form))
           (preceding-arg-obj (when preceding-arg-token
                                (token-to-object syntax preceding-arg-token
                                                 :no-error t))))
      (values preceding-arg-obj argument-indices))))

(defun valid-operator-p (operator)
  "Check whether or not `operator' is a valid
  operator. `Operator' is considered a valid operator if it is a
  symbol bound to a function, or if it is a lambda expression."
  (cond ((symbolp operator)
         (or (fboundp operator)
             (macro-function operator)
             (special-operator-p operator)))
        ((listp operator)
         (eq (first operator) 'cl:lambda))))

(defun indices-match-arglist (arglist arg-indices)
  "Check whether the argument indices `arg-indices' could refer
  to a direct argument for the operator with the argument list
  `arglist'. Returns T if they could, NIL otherwise. This
  functions does not care about the argument quantity, only their
  structure."
  (let* ((index (first arg-indices))
         (pure-arglist (remove-if #'arglist-keyword-p arglist))
         (arg (when (< index (length pure-arglist))
                (elt pure-arglist index))))
    (cond ((or (and (>= index (or (position-if #'arglist-keyword-p arglist)
                                  (1+ index)))
                    (not (null (rest arg-indices))))
               (and (not (null (rest arg-indices)))
                    (> (length pure-arglist)
                       index)
                    (not (listp (elt pure-arglist index)))))
           nil)
          ((and (not (null arg))
                (listp arg)
                (rest arg-indices))
           (indices-match-arglist arg (rest arg-indices)))
          (t t))))

(defun direct-arg-p (form syntax)
  "Check whether `form' is a direct argument to one of its
   parents."
  (labels ((recurse (parent)
             (let ((operator (form-operator
                              parent
                              syntax)))
               (or (and
                    ;; An operator is not an argument to itself...
                    (not (= (start-offset form)
                            (start-offset (first-form (children parent)))))
                    (valid-operator-p operator)
                    (indices-match-arglist
                     (arglist (image syntax)
                              operator)
                     (second
                      (multiple-value-list
                       (find-operand-info
                        (start-offset form)
                        syntax
                        parent)))))
                   (when (parent parent)
                     (recurse (parent parent)))))))
    (when (parent form)
      (recurse (parent form)))))

(defun relevant-keywords (arglist arg-indices)
  "Return a list of the keyword arguments that it would make
  sense to use at the position `arg-indices' relative to the
  operator that has the argument list `arglist'."
  (let* ((key-position (position '&key arglist))
         (rest-position (position '&rest arglist))
         (cleaned-arglist (remove-if #'arglist-keyword-p
                                     arglist))
         (index (first arg-indices))
         (difference (+ (- (length arglist)
                           (length cleaned-arglist))
                        (if rest-position 1 0))))
    (cond ((and (null key-position)
                (rest arg-indices)
                (> (length cleaned-arglist)
                   index)
                (listp (elt cleaned-arglist index)))
           ;; Look in a nested argument list.
           (relevant-keywords (elt cleaned-arglist index)
                              (rest arg-indices)))
          ((and (not (null key-position))
                (>= (+ index
                       difference) 
                    key-position)
                (evenp (- index (- key-position
                                   (1- difference)))))
           (mapcar #'unlisted (subseq cleaned-arglist
                                      (+ (- key-position
                                            difference)
                                         (if rest-position 2 1))))))))

(defgeneric possible-completions (syntax operator token operands indices)
  (:documentation "Get the applicable completions for completing
  `token' (which should be a token-lexeme), which is part of a
  form with the operator `operator' (which should be a valid
  operator object), and which has the operands
  `operands'. `Indices' should be the argument indices from the
  operator to `token' (see
  `find-argument-indices-for-operands').")
  (:method :around (syntax operator token operands indices)
           (declare (ignore syntax operator token operands indices))
           (with-syntax-package (syntax (start-offset token))
             (call-next-method)))
  (:method (syntax operator token operands indices)
    (let ((completions (first (simple-completions (get-usable-image syntax)
                                                  (token-string syntax (fully-unquoted-form token))
                                                  (package-at-mark syntax (start-offset token))))))
      (or (when (valid-operator-p operator)
            (let* ((relevant-keywords
                    (relevant-keywords (arglist-for-form syntax operator operands) indices))
                   (relevant-completions
                    (remove-if-not #'(lambda (compl)
                                       (member compl relevant-keywords
                                               :test #'(lambda (a b)
                                                         (string-equal a b
                                                                       :start1 1))
                                               :key #'symbol-name))
                                   (mapcar #'string-downcase completions))))
              relevant-completions))
          completions))))

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defgeneric code-for-argument-type-completion (argument-type syntax-symbol token-symbol all-completions-symbol)
    (:documentation "Generate completion code for an argument of
   type `argument-type'.")
    (:method (argument-type syntax-symbol token-symbol all-completions-symbol)
      '(call-next-method)))

  (defgeneric code-for-argument-list-modification (argument-type syntax-symbol arglist-symbol arguments-symbol)
    (:documentation "Generate argument list modification code for
    a form having an argument of type `argument-type'.")
    (:method (argument-type syntax-symbol arglist-symbol arguments-symbol)))

  (defmacro define-argument-type (name (&optional inherit-from)
                                  &rest options)
    (let ((completion-code (rest (assoc :completion options)))
          (modification-code (rest (assoc :arglist-modification options))))
        `(progn
           ,(if (or completion-code inherit-from)
                `(defmethod code-for-argument-type-completion ((argument-type (eql ',name))
                                                               ,@(if completion-code
                                                                     (first completion-code)
                                                                     '(syntax token)))
                   ,(if completion-code
                        `'(let ((,(third (first completion-code))
                                 (call-next-method)))
                           ,@(rest completion-code))
                        (code-for-argument-type-completion inherit-from 'syntax 'token 'all-completions)))
                (let ((method (find-method #'code-for-argument-type-completion nil `((eql ,name) t t t) nil)))
                  (when method
                    (remove-method #'code-for-argument-type-completion method))))
           ,(if (or modification-code inherit-from)
                `(defmethod code-for-argument-list-modification ((argument-type (eql ',name))
                                                                 ,@(if modification-code
                                                                       (first modification-code)
                                                                       '(syntax arglist arguments)))
                   ,(if modification-code
                        `'(progn ,@(rest modification-code))
                        `',(code-for-argument-list-modification inherit-from 'syntax 'arglist 'arguments)))
                (let ((method (find-method #'code-for-argument-list-modification nil `((eql ,name) t t t) nil)))
                  (when method
                    (remove-method #'code-for-argument-list-modification method)))))))

  (define-argument-type class-name ()
    (:completion (syntax token all-completions)
                 (loop for completion in all-completions
                    when (find-class (ignore-errors (read-from-string (string-upcase completion)))
                                     nil)
                    collect completion))
    (:arglist-modification (syntax arglist arguments)
                           (if (and (plusp (length arguments))
                                    (listp (first arguments))
                                    (> (length (first arguments)) 1)
                                    (eq (caar arguments) 'cl:quote))
                               (nconc arglist
                                      (cons '&key (get-class-keyword-parameters
                                                   (get-usable-image syntax)
                                                   (first arguments)))))))

  (define-argument-type package-designator ()
    (:completion (syntax token all-completions)
                 (declare (ignore all-completions))
                 (let* ((string (token-string syntax token))
                        (keyworded (char= (aref string 0) #\:)))
                   (loop for package in (list-all-packages)
                      for package-name = (if keyworded
                                             (concatenate 'string ":" (package-name package))
                                             (package-name package))
                      when (search string package-name
                                   :test #'char-equal
                                   :end2 (min (length string)
                                              (length package-name)))
                      collect (if (every #'upper-case-p string)
                                  package-name
                                  (string-downcase package-name)))))))

(defmacro define-form-traits ((operator &rest arguments))
  ;; FIXME: This macro should also define indentation rules.
  (labels ((build-completions-codd-body (arguments)
             (append (loop for argument in arguments
                        for i from 0
                        collect `((and (= (first indices) ,i))
                                  ,(cond ((listp argument)
                                          (if (eq (first argument) 'quote)
                                              `(cond ((typep token 'quote-form)
                                                      ,(code-for-argument-type-completion (second argument) 'syntax 'token 'all-completions))
                                                     (t (call-next-method)))
                                              `(cond ((not (endp (rest indices)))
                                                      (pop indices)
                                                      (cond ,@(build-completions-codd-body argument)))
                                                     (t (call-next-method)))))
                                         (t
                                          (code-for-argument-type-completion argument 'syntax 'token 'all-completions)))))
                     '((t (call-next-method))))))
    `(progn
       (defmethod possible-completions (syntax (operator (eql ',operator)) token operands indices)
         (cond ,@(build-completions-codd-body arguments)))
       (defmethod arglist-for-form (syntax (operator (eql ',operator)) &optional arguments)
         (let ((arglist (call-next-method)))
           ,@(mapcar #'(lambda (arg)
                         (code-for-argument-list-modification
                          (unlisted arg #'second)
                          'syntax 'arglist 'arguments))
                     arguments))))))

(defmacro with-code-insight (mark-or-offset syntax (&key operator preceding-operand
                                                         form preceding-operand-indices
                                                         operands)
                             &body body)
  "Evaluate `body' with the provided symbols lexically bound to
  interesting details about the code at `mark'. If `mark' is not
  within a form, everything will be bound to nil."
  ;; This macro is pretty complicated and deals with tons of border
  ;; issues. If it at all possible, please don't modify it. It is the
  ;; main interface for syntax module code to get high-level
  ;; information about the forms in the buffer, so if it breaks, most
  ;; of the user-oriented functionality of this syntax module breaks
  ;; as well.
  (let ((operator-sym (or operator (gensym)))
        (preceding-operand-sym (or preceding-operand (gensym)))
        (operands-sym (or operands (gensym)))
        (form-sym (or form (gensym)))
        (operand-indices-sym (or preceding-operand-indices (gensym)))
        ;; My kingdom for with-gensyms (or once-only)!
        (mark-value-sym (gensym))
        (syntax-value-sym (gensym)))
    `(let* ((,mark-value-sym ,mark-or-offset)
            (,syntax-value-sym ,syntax)
            (,form-sym
             ;; Find a form with a valid (fboundp) operator.
             (let ((immediate-form
                    (preceding-form ,mark-value-sym ,syntax-value-sym)))
               ;; Recurse upwards until we find a form with a valid
               ;; operator. This could be improved a lot, as we could
               ;; inspect the lambda list of the found operator and
               ;; check if the position of mark makes sense with
               ;; regard to the structure of the lambda list. If we
               ;; cannot find a form with a valid operator, just
               ;; return the form `mark' is in.
               (unless (null immediate-form)
                 (labels ((recurse (form)
                            (unless (null (parent form))
                              (or (unless (eq (first-form (children (parent form)))
                                              form)
                                    (recurse (parent form)))
                                  (and (valid-operator-p (form-operator
                                                          form
                                                          ,syntax-value-sym))
                                       (indices-match-arglist
                                        (arglist-for-form
                                         ,syntax-value-sym
                                         (form-operator
                                          form
                                          ,syntax-value-sym)
                                         (form-operands
                                          form
                                          ,syntax-value-sym))
                                        (second
                                         (multiple-value-list
                                          (find-operand-info ,mark-value-sym ,syntax-value-sym form))))
                                       (not (direct-arg-p form ,syntax-value-sym))
                                       form)))))
                   (or (recurse (parent immediate-form))
                       (parent immediate-form))))))
            ;; If we cannot find a form, there's no point in looking
            ;; up any of this stuff.
            (,operator-sym (when ,form-sym (form-operator ,form-sym ,syntax-value-sym)))
            (,operands-sym (when ,form-sym (form-operands ,form-sym ,syntax-value-sym))))
       (declare (ignorable ,mark-value-sym ,syntax-value-sym ,form-sym
                           ,operator-sym ,operands-sym))
       (multiple-value-bind (,preceding-operand-sym ,operand-indices-sym)
           (when ,form-sym (find-operand-info ,mark-value-sym ,syntax-value-sym ,form-sym))
         (declare (ignorable ,preceding-operand-sym ,operand-indices-sym))
         ,@body))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Form trait definitions

(define-form-traits (make-instance 'class-name))
(define-form-traits (make-pane 'class-name))
(define-form-traits (find-class 'class-name))
(define-form-traits (in-package package-designator))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Compiler note hyperlinking

(defun make-compiler-note (note-list)
  (let ((severity (getf note-list :severity))
        (message (getf note-list :message))
        (location (getf note-list :location))
        (references (getf note-list :references))
        (short-message (getf note-list :short-message)))
    (make-instance
     (ecase severity
       (:error 'error-compiler-note)
       (:read-error 'read-error-compiler-note)
       (:warning 'warning-compiler-note)
       (:style-warning 'style-warning-compiler-note)
       (:note 'note-compiler-note))
     :message message :location location
     :references references :short-message short-message)))

(defclass compiler-note ()
  ((message :initarg :message :initform nil :accessor message)
   (location :initarg :location :initform nil :accessor location)
   (references :initarg :references :initform nil :accessor references)
   (short-message :initarg :short-message :initform nil :accessor short-message))
  (:documentation "The base for all compiler-notes."))

(defclass error-compiler-note (compiler-note) ())

(defclass read-error-compiler-note (compiler-note) ())

(defclass warning-compiler-note (compiler-note) ())

(defclass style-warning-compiler-note (compiler-note) ())

(defclass note-compiler-note (compiler-note) ())

(defclass location ()()
  (:documentation "The base for all locations."))

(defclass error-location (location)
  ((error-message :initarg :error-message :accessor error-message)))

(defclass actual-location (location)
  ((source-position :initarg :position :accessor source-position)
   (snippet :initarg :snippet :accessor snippet :initform nil))
  (:documentation "The base for all non-error locations."))

(defclass buffer-location (actual-location)
  ((buffer-name :initarg :buffer :accessor buffer-name)))

(defclass file-location (actual-location)
  ((file-name :initarg :file :accessor file-name)))

(defclass source-location (actual-location)
  ((source-form :initarg :source-form :accessor source-form)))

(defclass basic-position () ()
  (:documentation "The base for all positions."))

(defclass char-position (basic-position)
  ((char-position :initarg :position :accessor char-position)
   (align-p :initarg :align-p :initform nil :accessor align-p)))

(defun make-char-position (position-list)
  (make-instance 'char-position :position (second position-list)
                 :align-p (third position-list)))

(defclass line-position (basic-position)
  ((start-line :initarg :line :accessor start-line)
   (end-line :initarg :end-line :initform nil :accessor end-line)))

(defun make-line-position (position-list)
  (make-instance 'line-position :line (second position-list)
                 :end-line (third position-list)))

(defclass function-name-position (basic-position)
  ((function-name :initarg :function-name)))

(defun make-function-name-position (position-list)
  (make-instance 'function-name-position :function-name (second position-list)))

(defclass source-path-position (basic-position)
  ((path :initarg :source-path :accessor path)
   (start-position :initarg :start-position :accessor start-position)))

(defun make-source-path-position (position-list)
  (make-instance 'source-path-position :source-path (second position-list)
                 :start-position (third position-list)))

(defclass text-anchored-position (basic-position)
  ((start :initarg :text-anchored :accessor start)
   (text :initarg :text :accessor text)
   (delta :initarg :delta :accessor delta)))

(defun make-text-anchored-position (position-list)
  (make-instance 'text-anchored-position :text-anchored (second position-list)
                 :text (third position-list)
                 :delta (fourth position-list)))

(defclass method-position (basic-position)
  ((name :initarg :method :accessor name)
   (specializers :initarg :specializers :accessor specializers)
   (qualifiers :initarg :qualifiers :accessor qualifiers)))

(defun make-method-position (position-list)
  (make-instance 'method-position :method (second position-list)
                 :specializers (third position-list)
                 :qualifiers (last position-list)))

(defun make-location (location-list)
  (ecase (first location-list)
    (:error (make-instance 'error-location :error-message (second location-list)))
    (:location
     (destructuring-bind (l buf pos hints) location-list
       (declare (ignore l))
       (let ((location
              (apply #'make-instance
                     (ecase (first buf)
                       (:file 'file-location)
                       (:buffer 'buffer-location)
                       (:source-form 'source-location))
                     buf))
             (position
              (funcall
               (ecase (first pos)
                 (:position #'make-char-position)
                 (:line #'make-line-position)
                 (:function-name #'make-function-name-position)
                 (:source-path #'make-source-path-position)
                 (:text-anchored #'make-text-anchored-position)
                 (:method #'make-method-position))
               pos)))
         (setf (source-position location) position)
         (when hints
           (setf (snippet location) (rest hints)))
         location)))))

(defmethod initialize-instance :after ((note compiler-note) &rest args)
  (declare (ignore args))
  (setf (location note) (make-location (location note))))

(defun show-note-counts (notes &optional seconds)
  (loop with nerrors = 0
     with nwarnings = 0
     with nstyle-warnings = 0
     with nnotes = 0
     for note in notes
     do (etypecase note
          (error-compiler-note (incf nerrors))
          (read-error-compiler-note (incf nerrors))
          (warning-compiler-note (incf nwarnings))
          (style-warning-compiler-note (incf nstyle-warnings))
          (note-compiler-note (incf nnotes)))
     finally
     (esa:display-message "Compilation finished: ~D error~:P ~
                            ~D warning~:P ~D style-warning~:P ~D note~:P ~
                            ~@[[~D secs]~]"
                          nerrors nwarnings nstyle-warnings nnotes seconds)))

(defun one-line-ify (string)
  "Return a single-line version of STRING.
Each newline and following whitespace is replaced by a single space."
  (loop with count = 0
     while (< count (length string))
     with new-string = (make-array 0 :element-type 'character :adjustable t
                                   :fill-pointer 0)
     when (char= (char string count) #\Newline)
     do (loop while (and (< count (length string))
                         (whitespacep nil (char string count)))
           do (incf count)
           ;; Just ignore whitespace if it is last in the
           ;; string.
           finally (when (< count (length string))
                     (vector-push-extend #\Space new-string)))
     else
     do (vector-push-extend (char string count) new-string)
     (incf count)
     finally (return new-string)))

(defgeneric print-for-menu (object stream))

(defun print-note-for-menu (note stream severity ink)
  (with-accessors ((message message) (short-message short-message)) note
    (with-drawing-options (stream :ink ink
                                  :text-style (make-text-style :sans-serif :italic nil))
      (princ severity stream)
      (princ " " stream))
    (princ (if short-message
               (one-line-ify short-message)
               (one-line-ify message))
           stream)))

(defmacro def-print-for-menu (class name colour)
  `(defmethod print-for-menu ((object ,class) stream)
     (print-note-for-menu object stream ,name ,colour)))

(def-print-for-menu error-compiler-note "Error" +red+)
(def-print-for-menu read-error-compiler-note "Read Error" +red+)
(def-print-for-menu warning-compiler-note "Warning" +dark-red+)
(def-print-for-menu style-warning-compiler-note "Style Warning" +brown+)
(def-print-for-menu note-compiler-note "Note" +brown+)

(defun show-notes (notes buffer-name definition)
  (let ((stream (typeout-window
                 (format nil "~10TCompiler Notes: ~A  ~A" buffer-name definition))))
    (loop for note in notes
       do (with-output-as-presentation (stream note 'compiler-note)
            (print-for-menu note stream))
       (terpri stream)
       count note into length
       finally (change-space-requirements stream
                                          :height (* length (stream-line-height stream)))
       (scroll-extent stream 0 0))))

(defgeneric goto-location (location))

(defmethod goto-location ((location error-location))
  (esa:display-message (error-message location)))

(defmethod goto-location ((location buffer-location))
  (let ((buffer (find (buffer-name location)
                      (buffers *application-frame*)
                      :test #'string= :key #'name)))
    (unless buffer
      (esa:display-message "No buffer ~A" (buffer-name location))
      (beep)
      (return-from goto-location))
    (switch-to-buffer buffer)
    (goto-position (point (current-window))
                   (char-position (source-position location)))))

(defmethod goto-location ((location file-location))
  (let ((buffer (find (file-name location)
                      (buffers *application-frame*)
                      :test #'string= :key #'(lambda (buffer)
                                               (let ((path (filepath buffer)))
                                                 (when path
                                                   (namestring path)))))))
    (if buffer
        (switch-to-buffer buffer)
        (find-file (file-name location) *application-frame*))
    (goto-position (point (current-window))
                   (char-position (source-position location)))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Macroexpansion and evaluation

(defun macroexpand-token (syntax token &optional (all nil))
  (with-syntax-package (syntax (start-offset token))
    (let* ((string (token-string syntax token))
           (expression (read-from-string string))
           (expansion (macroexpand-for-climacs (get-usable-image syntax)
                                               expression
                                               all))
           (expansion-string (with-output-to-string (s)
                               (pprint expansion s))))
      (let ((buffer (switch-to-buffer "*Macroexpansion*")))
        (set-syntax buffer "Lisp"))
      (let ((point (point (current-window)))
            (header-string (one-line-ify (subseq string 0
                                                 (min 40 (length string))))))
        (end-of-buffer point)
        (unless (beginning-of-buffer-p point)
          (insert-object point #\Newline))
        (insert-sequence point
                         (format nil ";;; Macroexpand-~:[1~;all~] ~A...~%"
                                 all header-string))
        (insert-sequence point expansion-string)
        (insert-object point #\Newline)))))

(defun eval-string (syntax string)
  "Evaluate all expressions in STRING and return a list of
results."
  (with-input-from-string (stream string)
    (loop for form = (read stream nil stream)
       while (not (eq form stream))
       collecting (multiple-value-list
                   (eval-form-for-climacs (get-usable-image syntax)
                                          form)))))

(defun eval-region (start end syntax)
  ;; Must be (mark>= end start).
  (with-syntax-package (syntax start)
    (let ((*read-base* (base syntax)))
      (let* ((string (buffer-substring (buffer start)
                                       (offset start)
                                       (offset end)))
             (values (multiple-value-list
                      (eval-string syntax string)))
             ;; Enclose each set of values in {}.
             (result (apply #'format nil "~{{~:[No values~;~:*~{~S~^,~}~]}~}"
                            values)))
        (esa:display-message result)))))

(defun compile-definition-interactively (mark syntax)
  (let* ((token (definition-at-mark mark syntax))
         (string (token-string syntax token))
         (m (clone-mark mark))
         (buffer-name (name (buffer syntax)))
         (*read-base* (base syntax)))
    (with-syntax-package (syntax mark)
      (forward-definition m syntax)
      (backward-definition m syntax)
      (multiple-value-bind (result notes)
          (compile-form-for-climacs (get-usable-image syntax)
                                    (token-to-object syntax token
                                                     :read t
                                                     :package (package-at-mark syntax mark))
                                    (buffer syntax)
                                    m)
        (show-note-counts notes (second result))
        (when (not (null notes))
          (show-notes notes buffer-name
                      (one-line-ify (subseq string 0 (min (length string) 20)))))))))

(defun compile-file-interactively (buffer &optional load-p)
  (cond ((null (filepath buffer))
         (esa:display-message "Buffer ~A is not associated with a file" (name buffer)))
        (t
         (when (and (needs-saving buffer)
                    (accept 'boolean :prompt (format nil "Save buffer ~A ?" (name buffer))))
           (save-buffer buffer))
         (let ((*read-base* (base (syntax buffer))))
           (multiple-value-bind (result notes)
               (compile-file-for-climacs (get-usable-image (syntax buffer))
                                         (filepath buffer)
                                         (package-at-mark (syntax buffer) 0) load-p)
             (show-note-counts notes (second result))
             (when notes (show-notes notes (name buffer) "")))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Parameter hinting

(defgeneric operator-for-display (operator)
  (:documentation "Return what should be displayed whenever
  `operator' is displayed as an operator.")
  (:method (operator)
    operator))

(defmethod operator-for-display ((operator list))
  (case (first operator)
    ('cl:lambda '|Lambda-Expression|)))

(defun display-arglist-to-stream (stream operator arglist
                                  &optional emphasized-symbols
                                  highlighted-symbols)
  "Display the operator and arglist to stream, format as
  appropriate."
  ;; FIXME: This is fairly ugly.
  (labels ((display-symbol (symbol)
             (with-text-style
                 (stream
                  `(nil
                    ,(cond ((member symbol
                                    highlighted-symbols)
                            :bold)
                           ((member symbol
                                    emphasized-symbols)
                            :italic))
                    nil))
               (format stream "~A" symbol)))
           (display-list (list)
             (if (and (eq (first list) 'quote)
                      (= (length list) 2))
                 (progn
                   (format stream "'")
                   (display-argument (second list)))
                 (progn
                   (format stream "(")
                   (display-argument (first list))
                   (dolist (arg (rest list))
                     (format stream " ")
                     (display-argument arg))
                   (format stream ")"))))
           (display-argument (arg)
             (if (and (listp arg)
                      (not (null arg)))
                 (display-list arg)
                 (display-symbol arg))))
    (display-argument (cons (operator-for-display operator)
                            arglist))))

(defun show-arglist-silent (operator &optional
                            current-arg-indices
                            preceding-arg arguments)
  "Display the arglist for `operator' in the minibuffer, do not
complain if `operator' is not bound to, or is not, a function.

`Current-arg-index' and `preceding-arg' are used to add extra
information to the arglist display. `Arguments' should be either
nil or a list of provided arguments in the form housing symbol.

Returns NIL if an arglist cannot be displayed."
  (multiple-value-bind (arglist emphasized-symbols highlighted-symbols)
      (analyze-arglist
       (arglist-for-form (syntax (current-buffer *application-frame*)) operator arguments)
       current-arg-indices
       preceding-arg
       arguments)
    (esa:with-minibuffer-stream (minibuffer)
      (display-arglist-to-stream minibuffer operator
                                 arglist emphasized-symbols
                                 highlighted-symbols))))

(defun show-arglist (symbol)
  (unless (and (fboundp symbol)
               (show-arglist-silent symbol))
    (esa:display-message "Function ~a not found." symbol)))

(defun show-arglist-for-form-at-mark (mark syntax)
  "Display the argument list for the operator of `form'. The
list need not be complete. If an argument list cannot be
retrieved for the operator, nothing will be displayed."
  (with-code-insight mark syntax (:operator operator
                                            :preceding-operand preceding-operand
                                            :preceding-operand-indices preceding-operand-indices
                                            :operands operands)
    (when (valid-operator-p operator) 
      (show-arglist-silent operator preceding-operand-indices preceding-operand operands))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Definition editing

(defparameter *find-definition-stack* '())

(defun pop-find-definition-stack ()
  (unless (null *find-definition-stack*)
    (let* ((offset+buffer (pop *find-definition-stack*))
           (offset (first offset+buffer))
           (buffer (second offset+buffer)))
      (if (find buffer (buffers *application-frame*))
          (progn (switch-to-buffer buffer)
                 (goto-position (point (current-window)) offset))
          (pop-find-definition-stack)))))

;; KLUDGE: We need to put more info in the definition objects to begin
;; with.
(defun definition-type (definition)
  (let ((data (read-from-string (first definition))))
    (case (first data)
      ((or cl:defclass)
       'cl:class)
      ((or cl:defgeneric
           cl:defmethod
           cl:defun
           cl:defmacro)
       'cl:function)
      (t t))))

(defun edit-definition (symbol &optional type)
  (let ((all-definitions (find-definitions-for-climacs
                          (get-usable-image (syntax (current-buffer *application-frame*)))
                          symbol)))
    (let ((definitions (if (not type)
                           all-definitions
                           (remove-if-not #'(lambda (definition)
                                              (eq (definition-type definition) type))
                                          all-definitions))))
      (cond ((null definitions)
             (esa:display-message "No known definitions for: ~A" symbol)
             (beep))
            (t
             (goto-definition symbol definitions))))))

(defun goto-definition (name definitions)
  (let* ((pane (current-window))
         (buffer (buffer pane))
         (point (point pane))
         (offset (offset point)))
    (push (list offset buffer) *find-definition-stack*))
  (cond ((null (cdr definitions))
         (let* ((def (car definitions))
                (xref (make-xref def)))
           (goto-location xref)))
        (t
         (let ((xref (show-definitions name definitions)))
           (when xref (goto-location xref))))))

(defclass xref ()
  ((dspec :initarg :dspec :accessor dspec)
   (location :initarg :location :accessor location)))

(defun make-xref (xref-list)
  (destructuring-bind (dspec location) xref-list
    (make-instance 'xref
                   :dspec dspec
                   :location (make-location location))))

(defmethod goto-location ((xref xref))
  (goto-location (location xref)))

(defun show-definitions (name definitions)
  (show-xrefs (loop for xref-list in definitions
                 collect (make-xref xref-list))
              'definition name))

(defun show-xrefs (xrefs type symbol)
  (cond ((null xrefs)
         (esa:display-message "No references found for ~A." symbol)
         (beep))
        (t
         (flet ((printer (item stream)
                  (with-drawing-options (stream :ink +dark-blue+
                                                :text-style (make-text-style :fixed nil nil))
                    (princ (dspec item) stream))))
           (let ((stream (typeout-window
                          (format nil "~10T~A ~A" type symbol))))
             (loop for xref in xrefs
                do (with-output-as-presentation (stream xref 'xref)
                     (printer xref stream))
                (terpri stream)
                count xref into length
                finally (change-space-requirements stream
                                                   :height (* length (stream-line-height stream)))
                (scroll-extent stream 0 0)))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Symbol completion

;;; The following helper stuff is from Swank.

(defun longest-completion (completions)
  "Return the longest completion of `completions', which must be a
list of sequences."
  (untokenize-completion
   (mapcar #'longest-common-prefix
           (transpose-lists (mapcar #'tokenize-completion completions)))))

(defun tokenize-completion (string)
  "Return all substrings of STRING delimited by #\-."
  (loop with end
     for start = 0 then (1+ end)
     until (> start (length string))
     do (setq end (or (position #\- string :start start) (length string)))
     collect (subseq string start end)))

(defun untokenize-completion (tokens)
  (format nil "~{~A~^-~}" tokens))

(defun longest-common-prefix (strings)
  "Return the longest string that is a common prefix of STRINGS."
  (if (null strings)
      ""
      (flet ((common-prefix (s1 s2)
               (let ((diff-pos (mismatch s1 s2)))
                 (if diff-pos (subseq s1 0 diff-pos) s1))))
        (reduce #'common-prefix strings))))

(defun transpose-lists (lists)
  "Turn a list-of-lists on its side.
If the rows are of unequal length, truncate uniformly to the shortest.

For example:
\(transpose-lists '((ONE TWO THREE) (1 2)))
  => ((ONE 1) (TWO 2))"
  (cond ((null lists) '())
        ((some #'null lists) '())
        (t (cons (mapcar #'car lists)
                 (transpose-lists (mapcar #'cdr lists))))))

;;; The interface used by the commands.

(defun clear-completions ()
  (let ((completions-pane
         (find "Completions" (esa:windows *application-frame*)
               :key #'pane-name
               :test #'string=)))
    (unless (null completions-pane)
      (delete-window completions-pane)
      (setf completions-pane nil))))

(defun find-completion-by-fn (fn symbol package)
  (esa:display-message (format nil "~a completions" symbol))
  (let* ((result (funcall fn symbol (package-name package)))
         (set (first result))
         (longest (second result)))
    (values longest set)))

(defun find-completion (syntax token)
  (let* ((symbol-name (token-string syntax token))
         (result (with-code-insight (start-offset token) syntax
                     (:operator operator
                                :operands operands
                                :preceding-operand-indices indices)
                   (let ((completions (possible-completions syntax operator token operands indices)))
                     (list completions (longest-completion completions)))))
         (set (first result))
         (longest (second result)))
    (esa:display-message (format nil "~a completions" symbol-name))
    (values longest set)))

(defun find-fuzzy-completion (syntax token package)
  (let ((symbol-name (token-string syntax token)))
    (esa:display-message (format nil "~a completions" symbol-name))
    (let* ((set (fuzzy-completions (get-usable-image syntax) symbol-name package 10))
           (best (caar set)))
      (values best set))))

(defun complete-symbol-at-mark-with-fn (syntax mark &optional (fn #'find-completion))
  "Attempt to find and complete the symbol at `mark' using the
  function `fn' to get the list of completions. If the completion
  is ambiguous, a list of possible completions will be
  displayed. If no symbol can be found at `mark', return nil."
  (let ((token (form-around syntax (offset mark))))
    (when (and (not (null token))
               (typep token 'complete-token-lexeme)
               (not (= (start-offset token)
                       (offset mark))))
      (multiple-value-bind (longest completions)
          (funcall fn syntax (fully-quoted-form token))
        (if (> (length longest) 0)
            (if (= (length completions) 1)
                (replace-symbol-at-mark mark syntax longest)
                (progn
                  (esa:display-message (format nil "Longest is ~a|" longest))
                  (let ((selection (menu-choose (mapcar
                                                 ;; FIXME: this can
                                                 ;; get ugly.
                                                 #'(lambda (completion)
                                                     (if (listp completion)
                                                         (cons completion
                                                               (first completion))
                                                         completion))
                                                 completions)
                                                :label "Possible completions"
                                                :scroll-bars :vertical)))
                    (replace-symbol-at-mark mark syntax (or selection
                                                            longest)))))
            (esa:display-message "No completions found")))
      t)))

(defun complete-symbol-at-mark (syntax mark)
  "Attempt to find and complete the symbol at `mark'. If the
  completion is ambiguous, a list of possible completions will be
  displayed. If no symbol can be found at `mark', return nil."
  (complete-symbol-at-mark-with-fn syntax mark))

(defun fuzzily-complete-symbol-at-mark (syntax mark)
  "Attempt to find and complete the symbol at `mark' using fuzzy
  completion. If the completion is ambiguous, a list of possible
  completions will be displayed. If no symbol can be found at
  `mark', return nil."
  (complete-symbol-at-mark-with-fn syntax mark #'find-fuzzy-completion))