/
Vim.hs
1787 lines (1552 loc) · 76.7 KB
/
Vim.hs
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
{-# LANGUAGE RelaxedPolyRec, FlexibleContexts, DeriveDataTypeable, TemplateHaskell, CPP, PatternGuards, GeneralizedNewtypeDeriving, FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TH-derived accessors
-- Copyright (c) 2004-5 Don Stewart - http://www.cse.unsw.edu.au/~dons
-- Copyright (c) 2008 Nicolas Pouillard
-- | Vim keymap for Yi. Emulates vim :set nocompatible
module Yi.Keymap.Vim (keymapSet,
viWrite,
defKeymap,
leaveInsRep,
leave,
ModeMap(..),
VimOpts(..),
VimExCmd(..),
nilCmd,
exCmd,
exCmds,
exSimpleComplete,
exInfixComplete', exInfixComplete,
mkExHistComplete,
exHistComplete', exHistComplete,
exHistInfixComplete', exHistInfixComplete,
savingInsertB,
savingInsertCharB,
savingInsertStringB,
savingDeleteB,
savingDeleteCharB,
savingDeleteWordB,
savingCommandY,
savingCommandE,
mkKeymap,
beginIns,
beginInsE,
beginInsB,
listTagStack,
pushTagStack,
popTagStack,
peekTagStack,
exMode,
exEval
) where
import Prelude (maybe, length, filter, map, drop, break, uncurry, reads)
import Yi.Prelude
import Data.Binary
import Data.Char
import Data.List (nub, take, words, dropWhile, takeWhile, intersperse, reverse, isSuffixOf)
import Data.Maybe (fromMaybe, isJust)
import Data.Either (either)
import Data.Prototype
import Data.Accessor.Template
import Numeric (showHex, showOct)
import Shim.Utils (splitBy, uncurry3)
import System.IO (readFile)
#ifdef mingw32_HOST_OS
import System.PosixCompat.Files (fileExist)
#else
import System.Posix (fileExist)
#endif
import System.FilePath (FilePath, takeFileName)
import System.Directory (getCurrentDirectory, setCurrentDirectory)
import Control.Monad.State hiding (mapM_, mapM, sequence)
import Control.Arrow hiding (left, right)
import {-# source #-} Yi.Boot
import Yi.Command (cabalRun, makeBuild, shellCommandV)
import Yi.Core
import Yi.Eval (execEditorAction, getAllNamesInScope)
import Yi.File
import Yi.History
import Yi.Misc (matchingFileNames,adjBlock,adjIndent)
import Yi.String (dropSpace,lines')
import Yi.MiniBuffer
import Yi.Regex (seInput, regexEscapeString)
import Yi.Search
import Yi.Style
import Yi.TextCompletion
import Yi.Completion (containsMatch', mkIsPrefixOf, prefixMatch, completeInListCustomShow)
import Yi.Tag
import Yi.Window (bufkey)
import Yi.Hoogle (hoogle, hoogleSearch)
import qualified Codec.Binary.UTF8.String as UTF8
import Yi.Keymap.Vim.TagStack
--
-- What's missing?
-- gq,gw,fillText should leave the last \n as is.
-- fancier :s// ==> missing /c, ...
-- '.': started look at "TODO repeat" for missing things
-- @:
-- 8g8
-- provide and improve "g@{motion}"
-- integrate unit transposing (transposeB) (gSaw: swap a word)
-- free keys g[bBcClLnNOSWxXyYzZ(){}[/=|\:">.] z[BIJKpPqQSTVyYZ~`!@#$%&*()[]{}/?_:;,<>"'|\]
-- could be reused g[dDhHiQ]
-- free insert keys C-!, C-#, C-$, C-%, C-&, C-*, C-(, C-), C-/, C-+, C-=, C--, C-:, C-;, C-|
-- could be reused insert keys C-_, C-^
-- go
-- gm, g$, g<End>, gp, gP, ]p, ]P, [P, [p, gr, gR, gs, gv, gV
-- &, :&&, g&
-- goto file [{visual}][count]g{f,F}
-- invent a variant of o and O that add spaces to be at the same col
-- invent a "indent as previous" in insert mode
-- :sh[ell]
-- :!!
-- movement parameterised \> \<
-- motion operators [motion.txt]: !
-- C-v: visual block mode: almost works, block yanking/pasting is still to do.
-- Support for marks
-- C-o and C-i: jump list
-- C-a or C-@: insert prev text
-- C-u: delete all entered chars of the current line
-- C-f: reindent the line
-- C-o: execute one command, return to Insert mode (see also C-\ C-O)
-- C-k <C-K><S-Space>: insert a char using it's specification
-- C-r <reg>: insert the content of a register
-- ---------------------------------------------------------------------
type VimMode = Keymap
data ViMove = Move TextUnit Direction
| MaybeMove TextUnit Direction
| GenMove TextUnit (Direction, BoundarySide) Direction
| CharMove Direction
| PercentageFile Int
| ArbMove (BufferM ())
| Replicate ViMove Int
| SeqMove ViMove ViMove
| NoMove
deriving (Typeable)
data ViCmd = ArbCmd !(Int -> YiM ()) !Int
| NoOp
deriving (Typeable)
instance Binary ViCmd where
put = dummyPut
get = dummyGet
instance Initializable ViCmd where
initial = NoOp
instance YiVariable ViCmd
data ViInsertion = ViIns { viActFirst :: Maybe (EditorM ()) -- ^ The action performed first
, viActBefore :: BufferM () -- ^ The action performed before insertion
, viBeginPos :: Point -- ^ The position _before_ insertion
, viEndPos :: Point -- ^ The position _after_ insertion
, viActAfter :: BufferM () -- ^ The action performed after insertion
}
deriving (Typeable)
newtype MViInsertion = MVI { unMVI :: Maybe ViInsertion }
deriving(Typeable, Initializable)
instance Binary MViInsertion where
put = dummyPut
get = dummyGet
instance YiVariable MViInsertion
$(nameDeriveAccessors ''ViInsertion $ Just.(++ "A"))
$(nameDeriveAccessors ''MViInsertion $ Just.(++ "_A"))
data VimOpts = VimOpts { tildeop :: Bool
, completeCaseSensitive :: Bool
, enableTagStack :: Bool
}
data VimExCmd = VimExCmd { cmdNames :: [String]
, cmdFn :: String -> YiM ()
, completeFn :: Maybe (String -> YiM ())
}
type VimExCmdMap = [VimExCmd] -- very simple implementation yet
$(nameDeriveAccessors ''VimOpts $ Just.(++ "A"))
-- | The Vim keymap is divided into several parts, roughly corresponding
-- to the different modes of vi. Each mode is in turn broken up into
-- separate VimProcs for each phase of key input in that mode.
data ModeMap = ModeMap { -- | Top level mode
v_top_level :: VimMode
-- | vim insert mode
, v_ins_char :: VimMode
, v_opts :: VimOpts
, v_ex_cmds :: VimExCmdMap
}
$(nameDeriveAccessors ''ModeMap $ Just.(++ "A"))
lastViCommandA :: Accessor Editor ViCmd
lastViCommandA = dynA
currentViInsertionA :: Accessor FBuffer (Maybe ViInsertion)
currentViInsertionA = unMVI_A . bufferDynamicValueA
applyViCmd :: Maybe Int -> ViCmd -> YiM ()
applyViCmd _ NoOp = return ()
applyViCmd mi (ArbCmd f i') = f $ fromMaybe i' mi
regionOfViMove :: ViMove -> RegionStyle -> BufferM Region
regionOfViMove move regionStyle =
join $ mkRegionOfStyleB <$> pointB
<*> savingPointB (viMove move >> pointB)
<*> pure regionStyle
applyOperator :: (RegionStyle -> Region -> EditorM ()) -> Int -> (RegionStyle, ViMove) -> EditorM ()
applyOperator onRegion i (regionStyle, move) = savingCommandE f i
where f j = onRegion regionStyle =<< withBuffer0' (regionOfViMove (Replicate move j) regionStyle)
emptyViIns :: Point -> ViInsertion
emptyViIns p = ViIns Nothing (return ()) p p (return ())
getViIns :: BufferM ViInsertion
getViIns = maybe def return =<< getA currentViInsertionA
where def = do ins <- emptyViIns <$> pointB
putA currentViInsertionA $ Just ins
return ins
viInsText :: ViInsertion -> BufferM String
viInsText ins = readRegionB $ mkRegion (viBeginPos ins) (viEndPos ins)
-- | The given buffer action should be an insertion action.
savingInsertB :: BufferM () -> BufferM ()
savingInsertB action = do ins0 <- getViIns
oldP <- pointB
action
newP <- pointB
let endP = viEndPos ins0
beginP = viBeginPos ins0
ins1 | endP == oldP = ins0 { viEndPos = newP }
| oldP >= beginP && oldP < endP = ins0 { viEndPos = endP +~ (newP ~- oldP) }
| otherwise = emptyViIns newP
putA currentViInsertionA $ Just ins1
savingInsertCharB :: Char -> BufferM ()
savingInsertCharB = savingInsertB . insertB
savingInsertStringB :: String -> BufferM ()
savingInsertStringB = savingInsertB . insertN
-- | The given action should be a deletion action.
-- The only well tested buffer actions are deleting one character,
-- or one word, forward or backward.
savingDeleteB :: BufferM () -> BufferM ()
savingDeleteB action = do
ins0 <- getViIns
oldP <- pointB
s1 <- sizeB
action
s2 <- sizeB
newP <- pointB
let diff = s2 ~- s1
endP = viEndPos ins0
beginP = viBeginPos ins0
shrinkEndPos = viEndPosA ^: (-~ diff)
ins1 =
if oldP >= beginP && oldP <= endP then
if newP > endP then
viActAfterA ^: (>> action) $ ins0 { viEndPos = newP }
else if newP < beginP then
viActBeforeA ^: (>> action) $ shrinkEndPos $ ins0 { viBeginPos = newP }
else shrinkEndPos ins0
else if newP > oldP then viActAfterA ^: (>> action) $ emptyViIns newP
else viActBeforeA ^: (>> action) $ emptyViIns newP
putA currentViInsertionA $ Just ins1
savingDeleteCharB :: Direction -> BufferM ()
savingDeleteCharB dir = savingDeleteB (adjBlock (-1) >> deleteB Character dir)
savingDeleteWordB :: Direction -> BufferM ()
savingDeleteWordB dir = savingDeleteB $ deleteRegionB =<< regionOfPartNonEmptyB unitViWordOnLine dir
viCommandOfViInsertion :: ViInsertion -> BufferM ViCmd
viCommandOfViInsertion ins@(ViIns mayFirstAct before _ _ after) = do
text <- viInsText ins
return . flip ArbCmd 1 . fmap withEditor $ case mayFirstAct of
Just firstAct -> \n->
replicateM_ n firstAct >> withBuffer0' (before >> insertN text >> after)
Nothing ->
flip replicateM_ $ withBuffer0' $ before >> insertN text >> after
commitLastInsertionE :: EditorM ()
commitLastInsertionE = do mins <- withBuffer0 $ getA currentViInsertionA
withBuffer0 $ putA currentViInsertionA Nothing
putA lastViCommandA =<< maybe (return NoOp) (withBuffer0 . viCommandOfViInsertion) mins
savingCommandY :: (Int -> YiM ()) -> Int -> YiM ()
savingCommandY f i = putA lastViCommandA (ArbCmd f i) >> f i
savingCommandE :: (Int -> EditorM ()) -> Int -> EditorM ()
savingCommandE f i = putA lastViCommandA (ArbCmd (withEditor . f) i) >> f i
savingCommandE'Y :: (Int -> EditorM ()) -> Int -> YiM ()
savingCommandE'Y f = withEditor' . savingCommandE f
savingCommandEY :: (Int -> EditorM ()) -> Int -> YiM ()
savingCommandEY f = withEditor . savingCommandE f
savingCommandB :: (Int -> BufferM ()) -> Int -> EditorM ()
savingCommandB f = savingCommandE (withBuffer0 . f)
savingCommandB' :: (Int -> BufferM ()) -> Int -> EditorM ()
savingCommandB' f = savingCommandE (withBuffer0' . f)
savingCommandB'Y :: (Int -> BufferM ()) -> Int -> YiM ()
savingCommandB'Y f = withEditor . savingCommandB' f
viMove :: ViMove -> BufferM ()
viMove NoMove = return ()
viMove (GenMove unit boundary dir) = genMoveB unit boundary dir
viMove (MaybeMove unit dir) = maybeMoveB unit dir
viMove (Move unit dir) = moveB unit dir
viMove (CharMove Forward) = moveXorEol 1
viMove (CharMove Backward) = moveXorSol 1
viMove (PercentageFile i) = movePercentageFile i
viMove (ArbMove move) = move
viMove (SeqMove move1 move2) = viMove move1 >> viMove move2
viMove (Replicate move i) = viReplicateMove move i
viReplicateMove :: ViMove -> Int -> BufferM ()
viReplicateMove (Move VLine Forward) i = lineMoveRel i >> return ()
viReplicateMove (Move VLine Backward) i = lineMoveRel (-i) >> return ()
viReplicateMove (CharMove Forward) i = moveXorEol i
viReplicateMove (CharMove Backward) i = moveXorSol i
viReplicateMove (Replicate move j) i = viReplicateMove move (i * j)
viReplicateMove move i = replicateM_ i $ viMove move
movePercentageFile :: Int -> BufferM ()
movePercentageFile i = do let f :: Double
f = case fromIntegral i / 100.0 of
x | x > 1.0 -> 1.0
| x < 0.0 -> 0.0 -- Impossible?
| otherwise -> x
Point max_p <- sizeB
setMarkHere '\''
moveTo $ Point $ floor (fromIntegral max_p * f)
firstNonSpaceB
mkKeymap :: Proto ModeMap -> KeymapSet
mkKeymap p = KeymapSet
{ -- if the keymap "crashed" we restart here
-- so we clear the status line to indicate whatever mode we were in
-- has been left
startTopKeymap = do
write clrStatus
write $ setInserting False
write $ setVisibleSelection False
, startInsertKeymap = do
write clrStatus
write $ setInserting True
write $ setVisibleSelection False
write $ setStatus (["-- INSERT --"], defaultStyle)
, topKeymap = v_top_level v
, insertKeymap = v_ins_char v
} where v = extractValue p
keymapSet :: KeymapSet
keymapSet = mkKeymap defKeymap
nilCmd :: VimExCmd
nilCmd = VimExCmd { cmdNames = []
, cmdFn = (return . const ())
, completeFn = Nothing}
exCmd :: String -> (String -> YiM ()) -> Maybe (String -> YiM ()) -> VimExCmd
exCmd names fn cfn = VimExCmd { cmdNames = splitBy isSpace names
, cmdFn = fn
, completeFn = cfn }
exCmds :: [(String, String->YiM (), Maybe (String -> YiM ()))] -> VimExCmdMap
exCmds = map $ uncurry3 exCmd
ignoreExCmd :: String -> String
ignoreExCmd = dropWhile (isSpace) . dropWhile (not . isSpace)
exSimpleComplete :: (String -> YiM [String]) -> String -> YiM ()
exSimpleComplete compl s' = simpleComplete compl s >>=
withBuffer . insertN . drop (length s)
where s = dropWhile isSpace s'
exInfixComplete' :: Bool -> (String -> YiM [String]) -> String -> YiM ()
exInfixComplete' caseSensitive compl s' = do
cs <- infixComplete' caseSensitive compl s
when (not $ null cs)
(withBuffer $ do
leftN (length s)
deleteToEol
insertN cs)
where s = dropWhile isSpace s'
exInfixComplete :: (String -> YiM [String]) -> String -> YiM ()
exInfixComplete = exInfixComplete' True
exFileNameComplete :: String -> YiM ()
exFileNameComplete s' = mkCompleteFn (completeInListCustomShow basename)
prefixMatch (matchingFileNames Nothing) s >>=
withBuffer . insertN . drop (length s)
where s = dropWhile isSpace s'
-- this tries to resemble 'basename' utility:
-- basename "foo/bar.baz" = "bar.baz"
-- basename "foo/bar/" = "bar"
-- but
-- System.FilePath.takeBaseName "foo/bar.baz" = "bar"
-- System.FilePath.takeFileName "foo/bar/" = ""
basename f = takeFileName $ if "/" `isSuffixOf` f then init f
else f
mkExHistComplete :: (String -> String -> Bool) -> (String -> YiM [String]) -> String -> YiM ()
mkExHistComplete matchFn compl s =
mkWordComplete (return s) compl (withEditor . printMsgs . tail) matchFn >>=
(withBuffer . (testDeleteB >> ) . insertN)
where
testDeleteB = if null s then return () else deleteWordB
deleteWordB = deleteUnitB unitSep Backward
deleteUnitB unit dir = deleteRegionB =<< regionOfPartNonEmptyB unit dir
exHistComplete' :: Bool -> (String -> YiM [String]) -> String -> YiM ()
exHistComplete' caseSensitive = mkExHistComplete (mkIsPrefixOf caseSensitive)
exHistComplete :: (String -> YiM [String]) -> String -> YiM ()
exHistComplete = exHistComplete' True
exHistInfixComplete' :: Bool -> (String -> YiM [String]) -> String -> YiM ()
exHistInfixComplete' caseSensitive = mkExHistComplete match
where match x y = isJust $ containsMatch' caseSensitive x y
exHistInfixComplete :: (String -> YiM [String]) -> String -> YiM ()
exHistInfixComplete = exHistInfixComplete' True
defKeymap :: Proto ModeMap
defKeymap = Proto template
where
template self = ModeMap { v_top_level = def_top_level
, v_ins_char = def_ins_char
, v_opts = def_opts
, v_ex_cmds = [] }
where
def_opts = VimOpts { tildeop = False
, completeCaseSensitive = True
, enableTagStack = True }
-- | Top level consists of simple commands that take a count arg,
-- the replace cmd, which consumes one char of input, and commands
-- that switch modes.
def_top_level = choice [cmd_eval,cmd_move,cmd2other,cmd_op]
-- | Replace mode is like insert, except it performs writes, not inserts
-- TODO repeat
rep_mode :: VimMode
rep_mode = write (setStatus (["-- REPLACE --"], defaultStyle)) >> many rep_char >> leaveInsRep >> write (moveXorSol 1)
-- | Reset the selection style to a character-wise mode 'Inclusive'.
resetSelectStyle :: BufferM ()
resetSelectStyle = putA regionStyleA Inclusive
-- | Visual mode, similar to command mode
vis_move :: VimMode
vis_move = (moveKeymap >>= write . viMove . snd)
<|> do cnt <- count
let i = fromMaybe 1 cnt
choice ([events evs >>! action i | (evs,action) <- visOrCmdFM ] ++
[events evs >>! action cnt | (evs, action) <- scrollCmdFM ])
vis_mode :: RegionStyle -> VimMode
vis_mode selStyle = do
write $ do putA rectangleSelectionA $ Block == selStyle
setVisibleSelection True
pointB >>= setSelectionMarkPointB
core_vis_mode selStyle
write (clrStatus >> withBuffer0' (setVisibleSelection False >> resetSelectStyle))
core_vis_mode :: RegionStyle -> VimMode
core_vis_mode selStyle = do
write $ do withBuffer0' $ putA regionStyleA selStyle
setStatus ([msg selStyle], defaultStyle)
discard $ many (vis_move <|>
select_any_unit (withBuffer0' . (\r -> resetSelectStyle >> extendSelectRegionB r >> leftB)))
visual2other selStyle
where msg LineWise = "-- VISUAL LINE --"
msg Block = "-- VISUAL BLOCK --"
msg _ = "-- VISUAL --"
-- | Change visual mode
change_vis_mode :: RegionStyle -> RegionStyle -> VimMode
change_vis_mode src dst | src == dst = return ()
| otherwise = core_vis_mode dst
-- | A KeymapM to accumulate digits.
-- typically what is needed for integer repetition arguments to commands
count :: KeymapM (Maybe Int)
count = (deprioritize >> pure Nothing) <|> do
c <- charOf id '1' '9'
cs <- many $ charOf id '0' '9'
return $ Just $ read (c:cs)
viMoveToNthEol :: Int -> BufferM ()
viMoveToNthEol n = replicateM_ n $ maybeMoveB Line Forward
viMoveToEol :: ViMove
viMoveToEol = MaybeMove Line Forward
viMoveToSol :: ViMove
viMoveToSol = MaybeMove Line Backward
-- ---------------------------------------------------------------------
-- | KeymapM for movement commands
--
-- The may be invoked directly, or sometimes as arguments to other
-- /operator/ commands (like d).
--
cmd_move :: VimMode
cmd_move = moveKeymap >>= write . withBuffer0' . viMove . snd
-- the returned RegionStyle is used when the movement is combined with a 'cut' or 'yank'.
moveKeymap :: KeymapM (RegionStyle, ViMove)
moveKeymap = choice
[ char '0' ?>> return (Exclusive, viMoveToSol)
, char '%' ?>> return percentMove
, do
cnt <- count
let x = fromMaybe 1 cnt
choice ([c ?>> return (Inclusive, a x) | (c,a) <- moveCmdFM_inclusive ] ++
[pString s >> return (Inclusive, a x) | (s,a) <- moveCmdS_inclusive ] ++
[c ?>> return (Exclusive, a x) | (c,a) <- moveCmdFM_exclusive ] ++
[events evs >> return (Exclusive, a x) | (evs,a) <- moveCmdS_exclusive ] ++
[c ?>> return (LineWise, a x) | (c,a) <- moveUpDownCmdFM] ++
[do discard $ event c; c' <- textChar; return (r, a c' x) | (c,r,a) <- move2CmdFM] ++
[char 'G' ?>> return (LineWise, ArbMove $ setMarkHere '\'' >> maybe (botB >> firstNonSpaceB) gotoFNS cnt)
,pString "gg" >> return (LineWise, ArbMove $ setMarkHere '\'' >> gotoFNS (fromMaybe 0 cnt))
,char '\'' ?>> do c <- validMarkIdentifier
return (LineWise, ArbMove $ jumpToMark c >> firstNonSpaceB)
,char '`' ?>> do c <- validMarkIdentifier
return (Exclusive, ArbMove $ jumpToMark c)
-- The count value, in this case, is interpretted as a percentage instead of a repeat
-- count.
,char '%' ?>> return (LineWise, PercentageFile x)])]
where gotoFNS :: Int -> BufferM ()
gotoFNS n = gotoLn n >> firstNonSpaceB
-- | movement commands (with exclusive cut/yank semantics)
moveCmdFM_exclusive :: [(Event, (Int -> ViMove))]
moveCmdFM_exclusive =
-- left/right
[(char 'h', left)
,(ctrlCh 'h', left)
,(spec KBS, left)
,(spec KLeft, left)
,(spec KRight, right)
,(char 'l', right)
,(char ' ', right)
-- eol / sol / special column
,(spec KHome, sol)
,(char '^', const $ ArbMove firstNonSpaceB)
,(char '|', ArbMove . moveToColB . pred)
,(char '$', eol)
,(spec KEnd, eol)
-- words
,(char 'w', jumpF unitViWord)
,(char 'W', jumpF unitViWORD)
,(char 'b', jumpB unitViWord)
,(char 'B', jumpB unitViWORD)
,(ctrl $ spec KLeft, jumpB unitViWORD)
,(ctrl $ spec KRight, jumpF unitViWORD)
-- text
,(char '{', Replicate $ Move unitEmacsParagraph Backward)
,(char '}', Replicate $ Move unitEmacsParagraph Forward)
,(char '(', Replicate $ Move unitSentence Backward)
,(char ')', Replicate $ Move unitSentence Forward)
]
where
left = Replicate $ CharMove Backward
right = Replicate $ CharMove Forward
sol = Replicate viMoveToSol
eol = ArbMove . viMoveToNthEol
jumpF = \unit -> Replicate $ GenMove unit (Backward,InsideBound) Forward
jumpB = \unit -> Replicate $ Move unit Backward
-- | movement *multi-chars* commands (with exclusive cut/yank semantics)
moveCmdS_exclusive :: [([Event], (Int -> ViMove))]
moveCmdS_exclusive =
[(map char "[(", Replicate $ ArbMove (goUnmatchedB Backward '(' ')'))
,(map char "[{", Replicate $ ArbMove (goUnmatchedB Backward '{' '}'))
,(map char "])", Replicate $ ArbMove (goUnmatchedB Forward '(' ')'))
,(map char "]}", Replicate $ ArbMove (goUnmatchedB Forward '{' '}'))
,(map char "gk", up)
,([char 'g', spec KUp], up)
,(map char "gj", down)
,([char 'g', spec KDown], down)
]
where
up = Replicate (Move VLine Backward)
down = Replicate (Move VLine Forward)
-- | movement commands (with inclusive cut/yank semantics)
moveCmdFM_inclusive :: [(Event, (Int -> ViMove))]
moveCmdFM_inclusive =
[(char 'e', Replicate $ GenMove unitViWord (Forward, InsideBound) Forward)
,(char 'E', Replicate $ GenMove unitViWORD (Forward, InsideBound) Forward)]
-- | movement *multi-chars* commands (with inclusive cut/yank semantics)
moveCmdS_inclusive :: [(String, (Int -> ViMove))]
moveCmdS_inclusive =
[("ge", Replicate $ GenMove unitViWord (Forward, InsideBound) Backward)
,("gE", Replicate $ GenMove unitViWORD (Forward, InsideBound) Backward)
,("g_", const $ ArbMove lastNonSpaceB)]
-- | up/down movement commands. these one are separated from moveCmdFM_{inclusive,exclusive}
-- because they behave differently when yanking/cuting (line mode).
moveUpDownCmdFM :: [(Event, Int -> ViMove)]
moveUpDownCmdFM =
[(char 'k', up)
,(spec KUp, up)
,(ctrlCh 'p', up)
,(char 'j', down)
,(spec KDown, down)
,(ctrlCh 'j', down)
,(ctrlCh 'n', down)
,(spec KEnter, down)
,(char '-', fns up)
,(char '+', fns down)
,(ctrlCh 'm', fns down)
,(char '_', fns down . pred)
-- misc
,(char 'H', ArbMove . downFromTosB . pred)
,(char 'M', const $ ArbMove middleB)
,(char 'L', ArbMove . upFromBosB . pred)
]
where
up = Replicate (Move VLine Backward)
down = Replicate (Move VLine Forward)
fns m = (`SeqMove` ArbMove firstNonSpaceB) . m
-- | more movement commands. these ones are paramaterised by a character
-- to find in the buffer.
move2CmdFM :: [(Event, RegionStyle, Char -> Int -> ViMove)]
move2CmdFM =
-- these Inc/Exc in {next,prev}C{Inc,Exc} are not quite the same
-- than Exclusive/Inclusive, look at the vim manual for more details.
[(char 'f', Inclusive, Replicate . ArbMove . nextCInc)
,(char 'F', Exclusive, Replicate . ArbMove . prevCInc)
,(char 't', Inclusive, Replicate . ArbMove . nextCExc)
,(char 'T', Exclusive, Replicate . ArbMove . prevCExc)
]
-- | Other command mode functions
cmd_eval :: VimMode
cmd_eval = do
cnt <- count
let i = fromMaybe 1 cnt
choice $
[events evs >>! action i | (evs, action) <- cmdFM ] ++
[events evs >>! action i | (evs, action) <- visOrCmdFM ] ++
[events evs >>! action cnt | (evs, action) <- scrollCmdFM ] ++
[char 'r' ?>> do c <- textChar
write $ savingCommandB (savingPointB . writeN . flip replicate c) i
,char 'm' ?>> setMark
,char '.' ?>>! applyViCmd cnt =<< withEditor (getA lastViCommandA)]
searchCurrentWord :: Direction -> EditorM ()
searchCurrentWord dir = do
w <- withBuffer0' $ readRegionB =<< regionOfNonEmptyB unitViWord
viSearch (boundedPattern w) [] dir
where
boundedPattern x = "\\<" ++ (regexEscapeString x) ++ "\\>"
gotoPrevTagMark :: Int -> YiM ()
gotoPrevTagMark cnt = do
lastP <- withEditor $ popTagStack cnt
case lastP of
Nothing -> withEditor $ fail "bottom of tag stack"
Just (fp, p) -> do viFnewE fp
withBuffer' $ moveTo p
gotoTagCurrentWord :: YiM ()
gotoTagCurrentWord = gotoTag (v_opts self) =<< withEditor (withBuffer0' (readRegionB =<< regionOfNonEmptyB unitViWord))
continueSearching :: (Direction -> Direction) -> EditorM ()
continueSearching fdir = do
m <- getRegexE
dir <- fdir <$> getA searchDirectionA
printMsg $ directionElim dir '?' '/' : maybe "" seInput m
viSearch "" [] dir
skippingFirst :: ([a] -> [a]) -> [a] -> [a]
skippingFirst f = list [] (\x -> (x :) . f)
skippingLast :: ([a] -> [a]) -> [a] -> [a]
skippingLast f xs = f (init xs) ++ [last xs]
skippingNull :: ([a] -> [b]) -> [a] -> [b]
skippingNull _ [] = []
skippingNull f xs = f xs
joinLinesB :: Region -> BufferM ()
joinLinesB =
savingPointB .
(modifyRegionClever $ skippingLast $
concat . (skippingFirst $ map $ skippingNull ((' ':) . dropWhile isSpace)) . lines')
concatLinesB :: Region -> BufferM ()
concatLinesB = savingPointB . (modifyRegionClever $ skippingLast $ filter (/='\n'))
onCurrentWord :: (String -> String) -> BufferM ()
onCurrentWord f = savingPointB $ modifyRegionClever f =<< regionOfNonEmptyB unitViWord
onNumberInString :: (Read a, Show a, Num a) => (a -> a) -> String -> String
onNumberInString f s = case reads s2 of
[] -> s
(n, rest):_ -> s1 ++ show (f n) ++ rest
where (s1,s2) = break isDigit s
-- as cmdFM but these commands are also valid in visual mode
visOrCmdFM :: [([Event], Int -> YiM ())]
visOrCmdFM =
[([ctrlCh 'l'], const userForceRefresh)
,([ctrlCh 'z'], const suspendEditor)
,([ctrlCh 't'], gotoPrevTagMark)
,([ctrlCh ']'], const gotoTagCurrentWord) -- TODO add support for 'count'
] ++
(fmap.second.fmap) withEditor
[([ctrlW, char 'c'], const tryCloseE)
,([ctrlW, char 'o'], const closeOtherE)
,([ctrlW, char 's'], const splitE)
,([ctrlW, char 'w'], nextWinE')
,([ctrlW, ctrlW], nextWinE')
,([ctrlW, char 'W'], prevWinE')
,([ctrlW, char 'p'], prevWinE')
-- these 4 commands should go to moveKeymap
-- however moveKeymap is currently confined to BufferM
,([char 'n'], const $ continueSearching id)
,([char 'N'], const $ continueSearching reverseDir)
,([char '*'], const $ searchCurrentWord Forward)
,([char '#'], const $ searchCurrentWord Backward)
-- since we don't have vertical splitting,
-- these moving can be done using next/prev.
,([ctrlW,spec KDown], nextWinE')
,([ctrlW,spec KUp], prevWinE')
,([ctrlW,spec KRight], nextWinE')
,([ctrlW,spec KLeft], prevWinE')
,([ctrlW,char 'k'], prevWinE')
,([ctrlW,char 'j'], nextWinE') -- Same as the above pair, when you're a bit slow to release ctl.
,([ctrlW, ctrlCh 'k'], prevWinE')
,([ctrlW, ctrlCh 'j'], nextWinE')
,(map char "ga", const viCharInfo)
,(map char "g8", const viChar8Info)
,(map char "gt", nextTabE')
,(map char "gT", prevTabE')
]
where nextWinE' = flip replicateM_ nextWinE
prevWinE' = flip replicateM_ prevWinE
nextTabE' = flip replicateM_ nextTabE
prevTabE' = flip replicateM_ previousTabE
-- | cmd mode commands
-- An event specified paired with an action that may take an integer argument.
-- Usually the integer argument is the number of times an action should be repeated.
cmdFM :: [([Event], Int -> YiM ())]
cmdFM =
[([ctrlCh 'g'], const $ withEditor viFileInfo)
,([ctrlCh '^'], withEditor . alternateBufferE . (+ (-1)) )
-- undo/redo
,([char 'u'], withBuffer' . flip replicateM_ undoB)
,([char 'U'], withBuffer' . flip replicateM_ undoB) -- NB not correct
,([ctrlCh 'r'], withBuffer' . flip replicateM_ redoB)
,([ctrlCh 'a'], savingCommandB'Y $ onCurrentWord . onNumberInString . (+))
,([ctrlCh 'x'], savingCommandB'Y $ onCurrentWord . onNumberInString . flip (-))
,([char 'D'], savingCommandE'Y $ cut Exclusive . ArbMove . viMoveToNthEol)
,([char 'J'], savingCommandB'Y $ (joinLinesB =<<) . countLinesRegion . max 2)
,(map char "gJ", savingCommandB'Y $ (concatLinesB =<<) . countLinesRegion . max 2)
,([char 'Y'], withEditor . yank LineWise . (Replicate $ Move Line Forward))
,([char 'X'], savingCommandE'Y $ cut Exclusive . (Replicate $ CharMove Backward))
,([char 'x'], savingCommandE'Y $ cut Exclusive . (Replicate $ CharMove Forward))
,([spec KDel], savingCommandE'Y $ cut Exclusive . (Replicate $ CharMove Forward))
-- pasting
,([char 'p'], savingCommandEY $ flip replicateM_ pasteAfter)
,([char 'P'], savingCommandEY $ flip replicateM_ pasteBefore)
,(map char "ZZ", const $ viWriteModified >> closeWindow)
,(map char "ZQ", const closeWindow)
]
++
[ ([char '~'], savingCommandB'Y $
(flip mapRegionB switchCaseChar =<<) .
flip regionOfViMove Exclusive .
Replicate (CharMove Forward))
| not $ tildeop $ v_opts self ]
ctrlW :: Event
ctrlW = ctrlCh 'w'
scrollCmdFM :: [([Event], Maybe Int -> BufferM ())]
scrollCmdFM =
[([ctrlCh 'b'], upScreensB . fromMaybe 1) -- vim does (firstNonSpaceB;moveXorSol)
,([ctrlCh 'f'], downScreensB . fromMaybe 1)
,([ctrlCh 'u'], vimScrollByB (negate . (`div` 2)) . fromMaybe 1)
,([ctrlCh 'd'], vimScrollByB (`div` 2) . fromMaybe 1)
,([ctrlCh 'y'], vimScrollB . negate . fromMaybe 1)
,([ctrlCh 'e'], vimScrollB . fromMaybe 1)
,([spec KPageUp], upScreensB . fromMaybe 1)
,([spec KPageDown], downScreensB . fromMaybe 1)
,([char 'z', spec KEnter], mmGoFNS scrollCursorToTopB)
,(map char "zt", mmGoSC scrollCursorToTopB)
,(map char "z.", mmGoFNS scrollToCursorB)
,(map char "zz", mmGoSC scrollToCursorB)
,(map char "z-", mmGoFNS scrollCursorToBottomB)
,(map char "zb", mmGoSC scrollCursorToBottomB)]
where mayMove :: BufferM () -> Maybe Int -> BufferM ()
mayMove scroll cnt = do
case cnt of
Just n -> gotoLn n >> return ()
Nothing -> return ()
scroll
mmGoFNS scroll = mayMove (scroll >> firstNonSpaceB)
mmGoSC scroll = movingToPrefCol . mayMove scroll
-- | So-called 'operators', which take movement actions as arguments.
--
-- How do we achive this? We parse a known operator char then parse
-- one of the known movement commands. We then apply the returned
-- action and then the operator. For example, we 'd' command stores
-- the current point, does a movement, then deletes from the old to
-- the new point.
cmd_op :: VimMode
cmd_op = do
cnt <- count
let i = fromMaybe 1 cnt
choice [let s1 = prefix [c]
ss = nub [[c], s1]
onRegion = onRegion' 1
in
pString s1 >>
choice ([ forceRegStyle >>= \ frs -> moveKeymap >>= write . applyOperator onRegion i . first frs -- TODO: text units (eg. dViB)
, select_any_unit (onRegion Exclusive) ] ++ -- TODO repeat
[ pString s >>! applyOperator onRegion (i-1) (LineWise, Move VLine Forward) | s <- ss ]
)
| (prefix,_,c,onRegion') <- operators, c /= 'J'
]
where
-- | Forces RegionStyle; see motion.txt, line 116 and below (Vim 7.2)
forceRegStyle = do
style <- many $ choice [ char 'V' ?>> return (const LineWise)
, char 'v' ?>> return swpRsOrIncl
, ctrlCh 'v' ?>> return (const Block) ]
return $ last (id:style)
where swpRsOrIncl Exclusive = Inclusive
swpRsOrIncl _ = Exclusive
-- | operator (i.e. movement-parameterised) actions
operators :: [((String->String), (String->String), Char, (Int -> RegionStyle -> Region -> EditorM ()))]
operators = [ (id, id, 'd', const $ \s r -> cutRegion s r >> withBuffer0 leftOnEol)
, (id, id, 'y', const $ nonBlockRegion "y" yankRegion)
, (id, id, '=', const $ mapRegions_ indentRegion)
, (id, id, '>', mapRegions_ . shiftIndentOfRegion)
, (id, id, '<', mapRegions_ . shiftIndentOfRegion . negate)
, (id, id, 'J', const $ nonBlockRegion "J" (const $ withBuffer0' . joinLinesB))
, (g_, g_, 'J', const $ nonBlockRegion "gJ" (const $ withBuffer0' . concatLinesB))
, (ti, id, '~', const $ viMapRegion switchCaseChar)
, (g_, id, 'u', const $ viMapRegion toLower)
, (g_, id, 'U', const $ viMapRegion toUpper)
, (g_, g_, '?', const $ viMapRegion rot13Char)
, (g_, g_, 'q', const $ nonBlockRegion "gq" (const $ withBuffer0' . fillRegion))
, (g_, g_, 'w', const $ nonBlockRegion "gw" (const $ withBuffer0' . savingPointB . fillRegion))
]
where g_ = ('g':)
ti = if tildeop $ v_opts self then id else g_
nonBlockRegion n _ Block _ = fail (show n ++ " does not works yet for block selections")
nonBlockRegion _ op s r = op s r
mapRegions_ f Block r = withBuffer0' $ mapM_ f =<< blockifyRegion r
mapRegions_ f _ r = withBuffer0' $ f r
toOuter outer _ True = leftBoundaryUnit outer
toOuter _ inner False = inner
char2unit :: [(Char, Bool -> TextUnit)]
char2unit =
[('w', toOuter unitViWord unitViWordAnyBnd)
,('W', toOuter unitViWORD unitViWORDAnyBnd)
,('p', toOuter unitEmacsParagraph unitEmacsParagraph) -- TODO inner could be inproved
,('s', toOuter unitSentence unitSentence) -- TODO inner could be inproved
,('"', unitDelimited '"' '"')
,('`', unitDelimited '`' '`')
,('\'', unitDelimited '\'' '\'')
,('(', unitDelimited '(' ')')
,(')', unitDelimited '(' ')')
,('b', unitDelimited '(' ')')
,('[', unitDelimited '[' ']')
,(']', unitDelimited '[' ']')
,('{', unitDelimited '{' '}')
,('}', unitDelimited '{' '}')
,('B', unitDelimited '{' '}')
,('<', unitDelimited '<' '>')
,('>', unitDelimited '<' '>')
]
select_any_unit :: (MonadInteract m Action Event) => (Region -> EditorM ()) -> m ()
select_any_unit f = do
outer <- (char 'a' ?>> pure True) <|> (char 'i' ?>> pure False)
choice [ char c ?>> write (f =<< withBuffer0' (regionOfNonEmptyB $ unit outer))
| (c, unit) <- char2unit]
regionOfSelection :: BufferM (RegionStyle, Region)
regionOfSelection = do
setMarkHere '>'
regionStyle <- getA regionStyleA
region <- join $ mkRegionOfStyleB <$> getSelectionMarkPointB
<*> pointB
<*> pure regionStyle
return (regionStyle, region)
indentRegion :: Region -> BufferM ()
indentRegion region = do
len <- length . filter (=='\n') <$> readRegionB region
savingPointB $ do
moveTo $ regionStart region
replicateM_ len $ adjIndent IncreaseCycle >> lineDown
firstNonSpaceB
yankRegion :: RegionStyle -> Region -> EditorM ()
yankRegion regionStyle region | regionIsEmpty region = return ()
| otherwise = do
when (regionStyle == Block) $ fail "yankRegion does not work on block regions"
txt <- withBuffer0' $ readRegionB region
setRegE $ if regionStyle == LineWise then '\n':txt else txt
let rowsYanked = length (filter (== '\n') txt)
when (rowsYanked > 2) $ printMsg $ show rowsYanked ++ " lines yanked"
yank :: RegionStyle -> ViMove -> EditorM ()
yank regionStyle move =
yankRegion regionStyle =<< (withBuffer0' $ regionOfViMove move regionStyle)
cutRegion :: RegionStyle -> Region -> EditorM ()
cutRegion Block region = do withBuffer0' $ mapM_ deleteRegionB =<< reverse <$> blockifyRegion region
printMsg "This block region is not cut just deleted"
cutRegion regionStyle region | regionIsEmpty region = return ()
| otherwise = do
(txt, rowsCut) <- withBuffer0 $ do
txt <- readRegionB region
let rowsCut = length $ filter (=='\n') txt
when (rowsCut==0) $ replicateM_ (length txt) (adjBlock (-1))
deleteRegionB region
return (txt, rowsCut)
setRegE $ if regionStyle == LineWise then '\n':txt else txt
when (rowsCut > 2) $ printMsg $ show rowsCut ++ " fewer lines"
cut :: RegionStyle -> ViMove -> EditorM ()
cut regionStyle move = do
region <- withBuffer0 $ regionOfViMove move regionStyle
cutRegion regionStyle region
cutSelection :: EditorM ()
cutSelection = uncurry cutRegion =<< withBuffer0' regionOfSelection
pasteOverSelection :: EditorM ()
pasteOverSelection = do
txt <- getRegE
withBuffer0' $ do
regStyle <- getA regionStyleA
start <- getSelectionMarkPointB
stop <- pointB
region <- mkRegionOfStyleB start stop regStyle
moveTo $ regionStart region
deleteRegionB region
insertN txt
pasteAfter :: EditorM ()
pasteAfter = do
txt' <- getRegE
withBuffer0' $ do
when ('\n' `notElem` txt') $ adjBlock $ length txt'
case txt' of
'\n':txt -> moveToEol >> rightB >> insertN txt >> leftN (length txt)
_ -> moveXorEol 1 >> insertN txt' >> leftB
pasteBefore :: EditorM ()
pasteBefore = do