summaryrefslogtreecommitdiff
path: root/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretImpl.java
blob: e2693b2c835fec1bfed3375b1c1ed2eee5477bd3 (plain)
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
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.openapi.editor.impl;

import com.intellij.diagnostic.LogMessageEx;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.editor.actionSystem.EditorActionManager;
import com.intellij.openapi.editor.actions.EditorActionUtil;
import com.intellij.openapi.editor.event.CaretEvent;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.editor.ex.EditorGutterComponentEx;
import com.intellij.openapi.editor.ex.FoldingModelEx;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.impl.event.DocumentEventImpl;
import com.intellij.openapi.editor.impl.softwrap.SoftWrapHelper;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.UserDataHolderBase;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.diff.FilesTooBigForDiffException;
import com.intellij.util.text.CharArrayUtil;
import com.intellij.util.ui.EmptyClipboardOwner;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.util.List;

public class CaretImpl extends UserDataHolderBase implements Caret {
  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.CaretImpl");

  private final EditorImpl myEditor;
  private boolean isValid = true;

  private LogicalPosition myLogicalCaret;
  private VerticalInfo myCaretInfo;
  private VisualPosition myVisibleCaret;
  private int myOffset;
  private int myVirtualSpaceOffset;
  private int myVisualLineStart;
  private int myVisualLineEnd;
  private RangeMarker savedBeforeBulkCaretMarker;
  private boolean mySkipChangeRequests;
  /**
   * Initial horizontal caret position during vertical navigation.
   * Similar to {@link #myDesiredX}, but represents logical caret position (<code>getLogicalPosition().column</code>) rather than visual.
   */
  private int myLastColumnNumber = 0;
  private int myDesiredSelectionStartColumn = -1;
  private int myDesiredSelectionEndColumn = -1;
  /**
   * We check that caret is located at the target offset at the end of {@link #moveToOffset(int, boolean)} method. However,
   * it's possible that the following situation occurs:
   * <p/>
   * <pre>
   * <ol>
   *   <li>Some client subscribes to caret change events;</li>
   *   <li>{@link #moveToLogicalPosition(LogicalPosition)} is called;</li>
   *   <li>Caret position is changed during {@link #moveToLogicalPosition(LogicalPosition)} processing;</li>
   *   <li>The client receives caret position change event and adjusts the position;</li>
   *   <li>{@link #moveToLogicalPosition(LogicalPosition)} processing is finished;</li>
   *   <li>{@link #moveToLogicalPosition(LogicalPosition)} reports an error because the caret is not located at the target offset;</li>
   * </ol>
   * </pre>
   * <p/>
   * This field serves as a flag that reports unexpected caret position change requests nested from {@link #moveToOffset(int, boolean)}.
   */
  private boolean myReportCaretMoves;
  /**
   * This field holds initial horizontal caret position during vertical navigation. It's used to determine target position when
   * moving to the new line. It is stored in pixels, not in columns, to account for non-monospaced fonts as well.
   * <p/>
   * Negative value means no coordinate should be preserved.
   */
  private int myDesiredX = -1;

  private volatile MyRangeMarker mySelectionMarker;
  private int startBefore;
  private int endBefore;
  boolean myUnknownDirection;
  // offsets of selection start/end position relative to end of line - can be non-zero in column selection mode
  // these are non-negative values, myStartVirtualOffset is always less or equal to myEndVirtualOffset
  private int myStartVirtualOffset;
  private int myEndVirtualOffset;

  CaretImpl(EditorImpl editor) {
    myEditor = editor;

    myLogicalCaret = new LogicalPosition(0, 0);
    myVisibleCaret = new VisualPosition(0, 0);
    myCaretInfo = new VerticalInfo(0, 0);
    myOffset = 0;
    myVisualLineStart = 0;
    Document doc = myEditor.getDocument();
    myVisualLineEnd = doc.getLineCount() > 1 ? doc.getLineStartOffset(1) : doc.getLineCount() == 0 ? 0 : doc.getLineEndOffset(0);
  }

  void onBulkDocumentUpdateStarted(@NotNull Document doc) {
    if (doc != myEditor.getDocument() || myOffset > doc.getTextLength() || savedBeforeBulkCaretMarker != null) return;
    savedBeforeBulkCaretMarker = doc.createRangeMarker(myOffset, myOffset);
  }

  void onBulkDocumentUpdateFinished(@NotNull Document doc) {
    if (doc != myEditor.getDocument() || myEditor.getCaretModel().myIsInUpdate) return;
    LOG.assertTrue(!myReportCaretMoves);

    if (savedBeforeBulkCaretMarker != null) {
      if(savedBeforeBulkCaretMarker.isValid()) {
        if(savedBeforeBulkCaretMarker.getStartOffset() != myOffset) {
          moveToOffset(savedBeforeBulkCaretMarker.getStartOffset());
        }
      } else if (myOffset > doc.getTextLength()) {
        moveToOffset(doc.getTextLength());
      }
      releaseBulkCaretMarker();
    }
  }

  public void beforeDocumentChange() {
    MyRangeMarker marker = mySelectionMarker;
    if (marker != null && marker.isValid()) {
      startBefore = marker.getStartOffset();
      endBefore = marker.getEndOffset();
    }
  }

  public void documentChanged() {
    MyRangeMarker marker = mySelectionMarker;
    if (marker != null) {
      int endAfter;
      int startAfter;
      if (marker.isValid()) {
        startAfter = marker.getStartOffset();
        endAfter = marker.getEndOffset();
        if (myEndVirtualOffset > 0 && (!isVirtualSelectionEnabled()
                                       || !EditorUtil.isAtLineEnd(myEditor, endAfter)
                                       || myEditor.getDocument().getLineNumber(startAfter) != myEditor.getDocument().getLineNumber(endAfter))) {
          myStartVirtualOffset = 0;
          myEndVirtualOffset = 0;
        }
      }
      else {
        startAfter = endAfter = getOffset();
        marker.release();
        myStartVirtualOffset = 0;
        myEndVirtualOffset = 0;
        mySelectionMarker = null;
      }

      if (startBefore != startAfter || endBefore != endAfter) {
        myEditor.getSelectionModel().fireSelectionChanged(startBefore, endBefore, startAfter, endAfter);
      }
    }
  }

  @Override
  public void moveToOffset(int offset) {
    moveToOffset(offset, false);
  }

  @Override
  public void moveToOffset(final int offset, final boolean locateBeforeSoftWrap) {
    assertIsDispatchThread();
    validateCallContext();
    if (mySkipChangeRequests) {
      return;
    }
    myEditor.getCaretModel().doWithCaretMerging(new Runnable() {
      public void run() {
        final LogicalPosition logicalPosition = myEditor.offsetToLogicalPosition(offset);
        CaretEvent event = moveToLogicalPosition(logicalPosition, locateBeforeSoftWrap, null, false);
        final LogicalPosition positionByOffsetAfterMove = myEditor.offsetToLogicalPosition(myOffset);
        if (!positionByOffsetAfterMove.equals(logicalPosition)) {
          StringBuilder debugBuffer = new StringBuilder();
          moveToLogicalPosition(logicalPosition, locateBeforeSoftWrap, debugBuffer, true);
          int textStart = Math.max(0, Math.min(offset, myOffset) - 1);
          final DocumentEx document = myEditor.getDocument();
          int textEnd = Math.min(document.getTextLength() - 1, Math.max(offset, myOffset) + 1);
          CharSequence text = document.getCharsSequence().subSequence(textStart, textEnd);
          StringBuilder positionToOffsetTrace = new StringBuilder();
          int inverseOffset = myEditor.logicalPositionToOffset(logicalPosition, positionToOffsetTrace);
          LogMessageEx.error(
            LOG, "caret moved to wrong offset. Please submit a dedicated ticket and attach current editor's text to it.",
            String.format(
              "Requested: offset=%d, logical position='%s' but actual: offset=%d, logical position='%s' (%s). %s%n"
              + "interested text [%d;%d): '%s'%n debug trace: %s%nLogical position -> offset ('%s'->'%d') trace: %s",
              offset, logicalPosition, myOffset, myLogicalCaret, positionByOffsetAfterMove, myEditor.dumpState(),
              textStart, textEnd, text, debugBuffer, logicalPosition, inverseOffset, positionToOffsetTrace
            )
          );
        }
        if (event != null) {
          myEditor.getCaretModel().fireCaretPositionChanged(event);
          EditorActionUtil.selectNonexpandableFold(myEditor);
        }
      }
    });
  }

  @NotNull
  @Override
  public CaretModel getCaretModel() {
    return myEditor.getCaretModel();
  }

  @Override
  public boolean isValid() {
    return isValid;
  }

  @Override
  public void moveCaretRelatively(int columnShift, int lineShift, boolean withSelection, boolean scrollToCaret) {
    moveCaretRelatively(columnShift, lineShift, withSelection, false, scrollToCaret);
  }

  void moveCaretRelatively(final int columnShift,
                                  final int lineShift,
                                  final boolean withSelection,
                                  final boolean blockSelection,
                                  final boolean scrollToCaret) {
    assertIsDispatchThread();
    if (mySkipChangeRequests) {
      return;
    }
    if (myReportCaretMoves) {
      LogMessageEx.error(LOG, "Unexpected caret move request");
    }
    if (!myEditor.isStickySelection() && !myEditor.getCaretModel().isDocumentChanged) {
      CopyPasteManager.getInstance().stopKillRings();
    }
    myEditor.getCaretModel().doWithCaretMerging(new Runnable() {
      public void run() {
        SelectionModelImpl selectionModel = myEditor.getSelectionModel();
        final int leadSelectionOffset = getLeadSelectionOffset();
        final VisualPosition leadSelectionPosition = getLeadSelectionPosition();
        LogicalPosition blockSelectionStart = selectionModel.hasBlockSelection()
                                              ? selectionModel.getBlockStart()
                                              : getLogicalPosition();
        EditorSettings editorSettings = myEditor.getSettings();
        VisualPosition visualCaret = getVisualPosition();

        int lastColumnNumber = myLastColumnNumber;
        int desiredX = myDesiredX;
        if (columnShift == 0) {
          if (myDesiredX < 0) {
            desiredX = getCurrentX();
          }
        }
        else {
          myDesiredX = desiredX = -1;
        }

        int newLineNumber = visualCaret.line + lineShift;
        int newColumnNumber = visualCaret.column + columnShift;
        if (desiredX >= 0) {
          newColumnNumber = myEditor.xyToVisualPosition(new Point(desiredX, Math.max(0, newLineNumber) * myEditor.getLineHeight())).column;
        }

        Document document = myEditor.getDocument();
        if (!editorSettings.isVirtualSpace() && lineShift == 0 && columnShift == 1) {
          int lastLine = document.getLineCount() - 1;
          if (lastLine < 0) lastLine = 0;
          if (EditorModificationUtil.calcAfterLineEnd(myEditor) >= 0 &&
              newLineNumber < myEditor.logicalToVisualPosition(new LogicalPosition(lastLine, 0)).line) {
            newColumnNumber = 0;
            newLineNumber++;
          }
        }
        else if (!editorSettings.isVirtualSpace() && lineShift == 0 && columnShift == -1) {
          if (newColumnNumber < 0 && newLineNumber > 0) {
            newLineNumber--;
            newColumnNumber = EditorUtil.getLastVisualLineColumnNumber(myEditor, newLineNumber);
          }
        }

        if (newColumnNumber < 0) newColumnNumber = 0;

        // There is a possible case that caret is located at the first line and user presses 'Shift+Up'. We want to select all text
        // from the document start to the current caret position then. So, we have a dedicated flag for tracking that.
        boolean selectToDocumentStart = false;
        if (newLineNumber < 0) {
          selectToDocumentStart = true;
          newLineNumber = 0;

          // We want to move caret to the first column if it's already located at the first line and 'Up' is pressed.
          newColumnNumber = 0;
          desiredX = -1;
          lastColumnNumber = -1;
        }

        VisualPosition pos = new VisualPosition(newLineNumber, newColumnNumber);
        if (!myEditor.getSoftWrapModel().isInsideSoftWrap(pos)) {
          LogicalPosition log = myEditor.visualToLogicalPosition(new VisualPosition(newLineNumber, newColumnNumber));
          int offset = myEditor.logicalPositionToOffset(log);
          if (offset >= document.getTextLength()) {
            int lastOffsetColumn = myEditor.offsetToVisualPosition(document.getTextLength()).column;
            // We want to move caret to the last column if if it's located at the last line and 'Down' is pressed.
            if (lastOffsetColumn > newColumnNumber) {
              newColumnNumber = lastOffsetColumn;
              desiredX = -1;
              lastColumnNumber = -1;
            }
          }
          if (!editorSettings.isCaretInsideTabs()) {
            CharSequence text = document.getCharsSequence();
            if (offset >= 0 && offset < document.getTextLength()) {
              if (text.charAt(offset) == '\t' && (columnShift <= 0 || offset == myOffset)) {
                if (columnShift <= 0) {
                  newColumnNumber = myEditor.offsetToVisualPosition(offset).column;
                }
                else {
                  SoftWrap softWrap = myEditor.getSoftWrapModel().getSoftWrap(offset + 1);
                  // There is a possible case that tabulation symbol is the last document symbol represented on a visual line before
                  // soft wrap. We can't just use column from 'offset + 1' because it would point on a next visual line.
                  if (softWrap == null) {
                    newColumnNumber = myEditor.offsetToVisualPosition(offset + 1).column;
                  }
                  else {
                    newColumnNumber = EditorUtil.getLastVisualLineColumnNumber(myEditor, newLineNumber);
                  }
                }
              }
            }
          }
        }

        pos = new VisualPosition(newLineNumber, newColumnNumber);
        if (columnShift != 0 && lineShift == 0 && myEditor.getSoftWrapModel().isInsideSoftWrap(pos)) {
          LogicalPosition logical = myEditor.visualToLogicalPosition(pos);
          int softWrapOffset = myEditor.logicalPositionToOffset(logical);
          if (columnShift >= 0) {
            moveToOffset(softWrapOffset);
          }
          else {
            int line = myEditor.offsetToVisualLine(softWrapOffset - 1);
            moveToVisualPosition(new VisualPosition(line, EditorUtil.getLastVisualLineColumnNumber(myEditor, line)));
          }
        }
        else {
          moveToVisualPosition(pos);
          if (!editorSettings.isVirtualSpace() && columnShift == 0 && lastColumnNumber >=0) {
            setLastColumnNumber(lastColumnNumber);
          }
        }

        if (withSelection) {
          if (blockSelection && !supportsMultipleCarets()) {
            selectionModel.setBlockSelection(blockSelectionStart, getLogicalPosition());
          }
          else {
            if (selectToDocumentStart) {
              if (supportsMultipleCarets()) {
                setSelection(leadSelectionPosition, leadSelectionOffset, myEditor.offsetToVisualPosition(0), 0);
              }
              else {
                setSelection(leadSelectionOffset, 0);
              }
            }
            else if (pos.line >= myEditor.getVisibleLineCount()) {
              int endOffset = document.getTextLength();
              if (leadSelectionOffset < endOffset) {
                if (supportsMultipleCarets()) {
                  setSelection(leadSelectionPosition, leadSelectionOffset, myEditor.offsetToVisualPosition(endOffset), endOffset);
                }
                else {
                  setSelection(leadSelectionOffset, endOffset);
                }
              }
            }
            else {
              int selectionStartToUse = leadSelectionOffset;
              VisualPosition selectionStartPositionToUse = leadSelectionPosition;
              if (isUnknownDirection()) {
                if (getOffset() > leadSelectionOffset ^ getSelectionStart() < getSelectionEnd()) {
                  selectionStartToUse = getSelectionEnd();
                  selectionStartPositionToUse = getSelectionEndPosition();
                }
                else {
                  selectionStartToUse = getSelectionStart();
                  selectionStartPositionToUse = getSelectionStartPosition();
                }
              }
              if (supportsMultipleCarets()) {
                setSelection(selectionStartPositionToUse, selectionStartToUse, getVisualPosition(), getOffset());
              }
              else {
                setSelection(selectionStartToUse, getVisualPosition(), getOffset());
              }
            }
          }
        }
        else {
          removeSelection();
        }

        if (scrollToCaret) {
          myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
        }

        if (desiredX >= 0) {
          myDesiredX = desiredX;
        }

        EditorActionUtil.selectNonexpandableFold(myEditor);
      }
    });
  }

  @Override
  public void moveToLogicalPosition(@NotNull final LogicalPosition pos) {
    myEditor.getCaretModel().doWithCaretMerging(new Runnable() {
      public void run() {
        moveToLogicalPosition(pos, false, null, true);
      }
    });
  }


  private CaretEvent doMoveToLogicalPosition(@NotNull LogicalPosition pos,
                                             boolean locateBeforeSoftWrap,
                                             @NonNls @Nullable StringBuilder debugBuffer,
                                             boolean fireListeners) {
    assertIsDispatchThread();
    if (debugBuffer != null) {
      debugBuffer.append("Start moveToLogicalPosition(). Locate before soft wrap: ").append(locateBeforeSoftWrap).append(", position: ")
        .append(pos).append("\n");
    }
    myDesiredX = -1;
    validateCallContext();
    int column = pos.column;
    int line = pos.line;
    int softWrapLinesBefore = pos.softWrapLinesBeforeCurrentLogicalLine;
    int softWrapLinesCurrent = pos.softWrapLinesOnCurrentLogicalLine;
    int softWrapColumns = pos.softWrapColumnDiff;

    Document doc = myEditor.getDocument();

    if (column < 0) {
      if (debugBuffer != null) {
        debugBuffer.append("Resetting target logical column to zero as it is negative (").append(column).append(")\n");
      }
      column = 0;
      softWrapColumns = 0;
    }
    if (line < 0) {
      if (debugBuffer != null) {
        debugBuffer.append("Resetting target logical line to zero as it is negative (").append(line).append(")\n");
      }
      line = 0;
      softWrapLinesBefore = 0;
      softWrapLinesCurrent = 0;
    }

    int lineCount = doc.getLineCount();
    if (lineCount == 0) {
      if (debugBuffer != null) {
        debugBuffer.append("Resetting target logical line to zero as the document is empty\n");
      }
      line = 0;
    }
    else if (line > lineCount - 1) {
      if (debugBuffer != null) {
        debugBuffer.append("Resetting target logical line (").append(line).append(") to ").append(lineCount - 1)
          .append(" as it is greater than total document lines number\n");
      }
      line = lineCount - 1;
      softWrapLinesBefore = 0;
      softWrapLinesCurrent = 0;
    }

    EditorSettings editorSettings = myEditor.getSettings();

    if (!editorSettings.isVirtualSpace() && line < lineCount && !myEditor.getSelectionModel().hasBlockSelection()) {
      int lineEndOffset = doc.getLineEndOffset(line);
      final LogicalPosition endLinePosition = myEditor.offsetToLogicalPosition(lineEndOffset);
      int lineEndColumnNumber = endLinePosition.column;
      if (column > lineEndColumnNumber) {
        int oldColumn = column;
        column = lineEndColumnNumber;
        if (softWrapColumns != 0) {
          softWrapColumns -= column - lineEndColumnNumber;
        }
        if (debugBuffer != null) {
          debugBuffer.append("Resetting target logical column (").append(oldColumn).append(") to ").append(lineEndColumnNumber)
            .append(" because caret is not allowed to be located after line end (offset: ").append(lineEndOffset).append(", ")
            .append("logical position: ").append(endLinePosition).append("). Current soft wrap columns value: ").append(softWrapColumns)
            .append("\n");
        }
      }
    }

    myEditor.getFoldingModel().flushCaretPosition();

    VerticalInfo oldInfo = myCaretInfo;
    LogicalPosition oldCaretPosition = myLogicalCaret;

    LogicalPosition logicalPositionToUse;
    if (pos.visualPositionAware) {
      logicalPositionToUse = new LogicalPosition(
        line, column, softWrapLinesBefore, softWrapLinesCurrent, softWrapColumns, pos.foldedLines, pos.foldingColumnDiff
      );
    }
    else {
      logicalPositionToUse = new LogicalPosition(line, column);
    }
    setCurrentLogicalCaret(logicalPositionToUse);
    final int offset = myEditor.logicalPositionToOffset(myLogicalCaret);
    if (debugBuffer != null) {
      debugBuffer.append("Resulting logical position to use: ").append(myLogicalCaret).append(". It's mapped to offset ").append(offset).append("\n");
    }

    FoldRegion collapsedAt = myEditor.getFoldingModel().getCollapsedRegionAtOffset(offset);

    if (collapsedAt != null && offset > collapsedAt.getStartOffset()) {
      if (debugBuffer != null) {
        debugBuffer.append("Scheduling expansion of fold region ").append(collapsedAt).append("\n");
      }
      Runnable runnable = new Runnable() {
        @Override
        public void run() {
          FoldRegion[] allCollapsedAt = myEditor.getFoldingModel().fetchCollapsedAt(offset);
          for (FoldRegion foldRange : allCollapsedAt) {
            foldRange.setExpanded(true);
          }
        }
      };

      mySkipChangeRequests = true;
      try {
        myEditor.getFoldingModel().runBatchFoldingOperation(runnable, false);
      }
      finally {
        mySkipChangeRequests = false;
      }
    }

    setLastColumnNumber(myLogicalCaret.column);
    myDesiredSelectionStartColumn = myDesiredSelectionEndColumn = -1;
    myVisibleCaret = myEditor.logicalToVisualPosition(myLogicalCaret);

    updateOffsetsFromLogicalPosition();
    if (debugBuffer != null) {
      debugBuffer.append("Storing offset ").append(myOffset).append(" (mapped from logical position ").append(myLogicalCaret).append(")\n");
    }
    LOG.assertTrue(myOffset >= 0 && myOffset <= myEditor.getDocument().getTextLength());

    updateVisualLineInfo();

    myEditor.updateCaretCursor();
    requestRepaint(oldInfo);

    if (locateBeforeSoftWrap && SoftWrapHelper.isCaretAfterSoftWrap(this)) {
      int lineToUse = myVisibleCaret.line - 1;
      if (lineToUse >= 0) {
        final VisualPosition visualPosition = new VisualPosition(lineToUse, EditorUtil.getLastVisualLineColumnNumber(myEditor, lineToUse));
        if (debugBuffer != null) {
          debugBuffer.append("Adjusting caret position by moving it before soft wrap. Moving to visual position ").append(visualPosition).append("\n");
        }
        final LogicalPosition logicalPosition = myEditor.visualToLogicalPosition(visualPosition);
        final int tmpOffset = myEditor.logicalPositionToOffset(logicalPosition);
        if (tmpOffset == myOffset) {
          boolean restore = myReportCaretMoves;
          myReportCaretMoves = false;
          try {
            moveToVisualPosition(visualPosition);
            return null;
          }
          finally {
            myReportCaretMoves = restore;
          }
        }
        else {
          LogMessageEx.error(LOG, "Invalid editor dimension mapping", String.format(
            "Expected to map visual position '%s' to offset %d but got the following: -> logical position '%s'; -> offset %d. "
            + "State: %s", visualPosition, myOffset, logicalPosition, tmpOffset, myEditor.dumpState()
          ));
        }
      }
    }

    if (!oldCaretPosition.toVisualPosition().equals(myLogicalCaret.toVisualPosition())) {
      CaretEvent event = new CaretEvent(myEditor, supportsMultipleCarets() ? this : null, oldCaretPosition, myLogicalCaret);
      if (fireListeners) {
        myEditor.getCaretModel().fireCaretPositionChanged(event);
      }
      else {
        return event;
      }
    }
    return null;
  }

  private boolean supportsMultipleCarets() {
    return myEditor.getCaretModel().supportsMultipleCarets();
  }

  private void updateOffsetsFromLogicalPosition() {
    myOffset = myEditor.logicalPositionToOffset(myLogicalCaret);
    myVirtualSpaceOffset = myLogicalCaret.column - myEditor.offsetToLogicalPosition(myOffset).column;
  }

  private void setLastColumnNumber(int lastColumnNumber) {
    myLastColumnNumber = lastColumnNumber;
    myEditor.setLastColumnNumber(lastColumnNumber);
  }

  private void requestRepaint(VerticalInfo oldCaretInfo) {
    int lineHeight = myEditor.getLineHeight();
    Rectangle visibleArea = myEditor.getScrollingModel().getVisibleArea();
    final EditorGutterComponentEx gutter = myEditor.getGutterComponentEx();
    final EditorComponentImpl content = myEditor.getContentComponent();

    int updateWidth = myEditor.getScrollPane().getHorizontalScrollBar().getValue() + visibleArea.width;
    if (Math.abs(myCaretInfo.y - oldCaretInfo.y) <= 2 * lineHeight) {
      int minY = Math.min(oldCaretInfo.y, myCaretInfo.y);
      int maxY = Math.max(oldCaretInfo.y + oldCaretInfo.height, myCaretInfo.y + myCaretInfo.height);
      content.repaintEditorComponent(0, minY, updateWidth, maxY - minY);
      gutter.repaint(0, minY, gutter.getWidth(), maxY - minY);
    }
    else {
      content.repaintEditorComponent(0, oldCaretInfo.y, updateWidth, oldCaretInfo.height + lineHeight);
      gutter.repaint(0, oldCaretInfo.y, updateWidth, oldCaretInfo.height + lineHeight);
      content.repaintEditorComponent(0, myCaretInfo.y, updateWidth, myCaretInfo.height + lineHeight);
      gutter.repaint(0, myCaretInfo.y, updateWidth, myCaretInfo.height + lineHeight);
    }
  }

  @Override
  public void moveToVisualPosition(@NotNull final VisualPosition pos) {
    myEditor.getCaretModel().doWithCaretMerging(new Runnable() {
      public void run() {
        moveToVisualPosition(pos, true);
      }
    });
  }

  void moveToVisualPosition(@NotNull VisualPosition pos, boolean fireListeners) {
    assertIsDispatchThread();
    validateCallContext();
    if (mySkipChangeRequests) {
      return;
    }
    if (myReportCaretMoves) {
      LogMessageEx.error(LOG, "Unexpected caret move request");
    }
    if (!myEditor.isStickySelection() && !myEditor.getCaretModel().isDocumentChanged && !pos.equals(myVisibleCaret)) {
      CopyPasteManager.getInstance().stopKillRings();
    }

    myDesiredX = -1;
    int column = pos.column;
    int line = pos.line;

    if (column < 0) column = 0;

    if (line < 0) line = 0;

    int lastLine = myEditor.getVisibleLineCount() - 1;
    if (lastLine <= 0) {
      lastLine = 0;
    }

    if (line > lastLine) {
      line = lastLine;
    }

    EditorSettings editorSettings = myEditor.getSettings();

    if (!editorSettings.isVirtualSpace() && line <= lastLine) {
      int lineEndColumn = EditorUtil.getLastVisualLineColumnNumber(myEditor, line);
      if (column > lineEndColumn) {
        column = lineEndColumn;
      }

      if (column < 0 && line > 0) {
        line--;
        column = EditorUtil.getLastVisualLineColumnNumber(myEditor, line);
      }
    }

    myVisibleCaret = new VisualPosition(line, column);

    VerticalInfo oldInfo = myCaretInfo;
    LogicalPosition oldPosition = myLogicalCaret;

    setCurrentLogicalCaret(myEditor.visualToLogicalPosition(myVisibleCaret));
    updateOffsetsFromLogicalPosition();
    LOG.assertTrue(myOffset >= 0 && myOffset <= myEditor.getDocument().getTextLength());

    updateVisualLineInfo();

    myEditor.getFoldingModel().flushCaretPosition();

    setLastColumnNumber(myLogicalCaret.column);
    myDesiredSelectionStartColumn = myDesiredSelectionEndColumn = -1;
    myEditor.updateCaretCursor();
    requestRepaint(oldInfo);

    if (fireListeners && !oldPosition.equals(myLogicalCaret)) {
      CaretEvent event = new CaretEvent(myEditor, supportsMultipleCarets() ? this : null, oldPosition, myLogicalCaret);
      myEditor.getCaretModel().fireCaretPositionChanged(event);
    }
  }

  @Nullable
  CaretEvent moveToLogicalPosition(@NotNull LogicalPosition pos,
                                           boolean locateBeforeSoftWrap,
                                           @Nullable StringBuilder debugBuffer,
                                           boolean fireListeners) {
    if (mySkipChangeRequests) {
      return null;
    }
    if (myReportCaretMoves) {
      LogMessageEx.error(LOG, "Unexpected caret move request");
    }
    if (!myEditor.isStickySelection() && !myEditor.getCaretModel().isDocumentChanged && !pos.equals(myLogicalCaret)) {
      CopyPasteManager.getInstance().stopKillRings();
    }

    myReportCaretMoves = true;
    try {
      return doMoveToLogicalPosition(pos, locateBeforeSoftWrap, debugBuffer, fireListeners);
    }
    finally {
      myReportCaretMoves = false;
    }
  }

  private void assertIsDispatchThread() {
    myEditor.assertIsDispatchThread();
  }

  private void validateCallContext() {
    LOG.assertTrue(!myEditor.getCaretModel().myIsInUpdate, "Caret model is in its update process. All requests are illegal at this point.");
  }

  private void releaseBulkCaretMarker() {
    if (savedBeforeBulkCaretMarker != null) {
      savedBeforeBulkCaretMarker.dispose();
      savedBeforeBulkCaretMarker = null;
    }
  }

  @Override
  public void dispose() {
    if (mySelectionMarker != null) {
      mySelectionMarker.release();
      mySelectionMarker = null;
    }
    releaseBulkCaretMarker();
    isValid = false;
  }

  @Override
  public boolean isUpToDate() {
    return !myEditor.getCaretModel().myIsInUpdate && !myReportCaretMoves;
  }

  @NotNull
  @Override
  public LogicalPosition getLogicalPosition() {
    validateCallContext();
    return myLogicalCaret;
  }

  @NotNull
  @Override
  public VisualPosition getVisualPosition() {
    validateCallContext();
    return myVisibleCaret;
  }

  @Override
  public int getOffset() {
    validateCallContext();
    return myOffset;
  }

  @Override
  public int getVisualLineStart() {
    return myVisualLineStart;
  }

  @Override
  public int getVisualLineEnd() {
    return myVisualLineEnd;
  }

  @NotNull
  private VerticalInfo createVerticalInfo(LogicalPosition position) {
    Document document = myEditor.getDocument();
    int logicalLine = position.line;
    if (logicalLine >= document.getLineCount()) {
      logicalLine = Math.max(0, document.getLineCount() - 1);
    }
    int startOffset = document.getLineStartOffset(logicalLine);
    int endOffset = document.getLineEndOffset(logicalLine);

    // There is a possible case that active logical line is represented on multiple lines due to soft wraps processing.
    // We want to highlight those visual lines as 'active' then, so, we calculate 'y' position for the logical line start
    // and height in accordance with the number of occupied visual lines.
    VisualPosition visualPosition = myEditor.offsetToVisualPosition(document.getLineStartOffset(logicalLine));
    int y = myEditor.visualPositionToXY(visualPosition).y;
    int lineHeight = myEditor.getLineHeight();
    int height = lineHeight;
    List<? extends SoftWrap> softWraps = myEditor.getSoftWrapModel().getSoftWrapsForRange(startOffset, endOffset);
    for (SoftWrap softWrap : softWraps) {
      height += StringUtil.countNewLines(softWrap.getText()) * lineHeight;
    }

    return new VerticalInfo(y, height);
  }

  /**
   * Recalculates caret visual position without changing its logical position (called when soft wraps are changing)
   */
  public void updateVisualPosition() {
    VerticalInfo oldInfo = myCaretInfo;
    LogicalPosition visUnawarePos = new LogicalPosition(myLogicalCaret.line, myLogicalCaret.column);
    setCurrentLogicalCaret(visUnawarePos);
    myVisibleCaret = myEditor.logicalToVisualPosition(myLogicalCaret);
    updateVisualLineInfo();

    myEditor.updateCaretCursor();
    requestRepaint(oldInfo);
  }

  private void updateVisualLineInfo() {
    myVisualLineStart = myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line, 0)));
    myVisualLineEnd = myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line + 1, 0)));
  }

  void updateCaretPosition(@NotNull final DocumentEventImpl event) {
    final DocumentEx document = myEditor.getDocument();
    boolean performSoftWrapAdjustment = event.getNewLength() > 0 // We want to put caret just after the last added symbol
                                        // There is a possible case that the user removes text just before the soft wrap. We want to keep caret
                                        // on a visual line with soft wrap start then.
                                        || myEditor.getSoftWrapModel().getSoftWrap(event.getOffset()) != null;

    if (event.isWholeTextReplaced()) {
      int newLength = document.getTextLength();
      if (myOffset == newLength - event.getNewLength() + event.getOldLength() || newLength == 0) {
        moveToOffset(newLength, performSoftWrapAdjustment);
      }
      else {
        try {
          final int line = event.translateLineViaDiff(myLogicalCaret.line);
          moveToLogicalPosition(new LogicalPosition(line, myLogicalCaret.column), performSoftWrapAdjustment, null, true);
        }
        catch (FilesTooBigForDiffException e1) {
          LOG.info(e1);
          moveToOffset(0);
        }
      }
    }
    else {
      if (document.isInBulkUpdate()) return;
      int startOffset = event.getOffset();
      int oldEndOffset = startOffset + event.getOldLength();

      int newOffset = myOffset;

      if (myOffset > oldEndOffset || myOffset == oldEndOffset && needToShiftWhiteSpaces(event)) {
        newOffset += event.getNewLength() - event.getOldLength();
      }
      else if (myOffset >= startOffset && myOffset <= oldEndOffset) {
        newOffset = Math.min(newOffset, startOffset + event.getNewLength());
      }

      newOffset = Math.min(newOffset, document.getTextLength());

      if (supportsMultipleCarets() && myOffset != startOffset) {
        LogicalPosition pos = myEditor.offsetToLogicalPosition(newOffset);
        moveToLogicalPosition(new LogicalPosition(pos.line, pos.column + myVirtualSpaceOffset), // retain caret in the virtual space
                            performSoftWrapAdjustment, null, true);
      }
      else {
        moveToOffset(newOffset, performSoftWrapAdjustment);
      }
    }

    updateVisualLineInfo();
  }

  private boolean needToShiftWhiteSpaces(final DocumentEvent e) {
    if (!CharArrayUtil.containsOnlyWhiteSpaces(e.getNewFragment()) || CharArrayUtil.containLineBreaks(e.getNewFragment()))
      return e.getOldLength() > 0;
    if (e.getOffset() == 0) return false;
    final char charBefore = myEditor.getDocument().getCharsSequence().charAt(e.getOffset() - 1);
    //final char charAfter = myEditor.getDocument().getCharsSequence().charAt(e.getOffset() + e.getNewLength());
    return Character.isWhitespace(charBefore)/* || !Character.isWhitespace(charAfter)*/;
  }

  private void setCurrentLogicalCaret(@NotNull LogicalPosition position) {
    myLogicalCaret = position;
    myCaretInfo = createVerticalInfo(position);
  }

  int getWordAtCaretStart() {
    Document document = myEditor.getDocument();
    int offset = getOffset();
    if (offset == 0) return 0;
    int lineNumber = getLogicalPosition().line;
    CharSequence text = document.getCharsSequence();
    int newOffset = offset - 1;
    int minOffset = lineNumber > 0 ? document.getLineEndOffset(lineNumber - 1) : 0;
    boolean camel = myEditor.getSettings().isCamelWords();
    for (; newOffset > minOffset; newOffset--) {
      if (EditorActionUtil.isWordStart(text, newOffset, camel)) break;
    }

    return newOffset;
  }

  int getWordAtCaretEnd() {
    Document document = myEditor.getDocument();
    int offset = getOffset();

    CharSequence text = document.getCharsSequence();
    if (offset >= document.getTextLength() - 1 || document.getLineCount() == 0) return offset;

    int newOffset = offset + 1;

    int lineNumber = getLogicalPosition().line;
    int maxOffset = document.getLineEndOffset(lineNumber);
    if (newOffset > maxOffset) {
      if (lineNumber + 1 >= document.getLineCount()) return offset;
      maxOffset = document.getLineEndOffset(lineNumber + 1);
    }
    boolean camel = myEditor.getSettings().isCamelWords();
    for (; newOffset < maxOffset; newOffset++) {
      if (EditorActionUtil.isWordEnd(text, newOffset, camel)) break;
    }

    return newOffset;
  }

  CaretImpl cloneWithoutSelection() {
    CaretImpl clone = new CaretImpl(myEditor);
    clone.myLogicalCaret = this.myLogicalCaret;
    clone.myCaretInfo = this.myCaretInfo;
    clone.myVisibleCaret = this.myVisibleCaret;
    clone.myOffset = this.myOffset;
    clone.myVirtualSpaceOffset = this.myVirtualSpaceOffset;
    clone.myVisualLineStart = this.myVisualLineStart;
    clone.myVisualLineEnd = this.myVisualLineEnd;
    clone.savedBeforeBulkCaretMarker = this.savedBeforeBulkCaretMarker;
    clone.mySkipChangeRequests = this.mySkipChangeRequests;
    clone.myLastColumnNumber = this.myLastColumnNumber;
    clone.myReportCaretMoves = this.myReportCaretMoves;
    clone.myDesiredX = this.myDesiredX;
    clone.myDesiredSelectionStartColumn = -1;
    clone.myDesiredSelectionEndColumn = -1;
    return clone;
  }

  @Nullable
  @Override
  public Caret clone(boolean above) {
    assertIsDispatchThread();
    int lineShift = above ? -1 : 1;
    final CaretImpl clone = cloneWithoutSelection();
    final int newSelectionStartOffset, newSelectionEndOffset, newSelectionStartColumn, newSelectionEndColumn;
    final VisualPosition newSelectionStartPosition, newSelectionEndPosition;
    final boolean hasNewSelection;
    if (hasSelection() || myDesiredSelectionStartColumn >=0 || myDesiredSelectionEndColumn >= 0) {
      VisualPosition startPosition = getSelectionStartPosition();
      VisualPosition endPosition = getSelectionEndPosition();
      VisualPosition leadPosition = getLeadSelectionPosition();
      boolean leadIsStart = leadPosition.equals(startPosition);
      boolean leadIsEnd = leadPosition.equals(endPosition);
      LogicalPosition selectionStart = myEditor.visualToLogicalPosition(leadIsStart || leadIsEnd ? leadPosition : startPosition);
      LogicalPosition selectionEnd = myEditor.visualToLogicalPosition(leadIsEnd ? startPosition : endPosition);
      newSelectionStartColumn = myDesiredSelectionStartColumn < 0 ? selectionStart.column : myDesiredSelectionStartColumn;
      newSelectionEndColumn = myDesiredSelectionEndColumn < 0 ? selectionEnd.column : myDesiredSelectionEndColumn;
      LogicalPosition newSelectionStart = truncate(selectionStart.line + lineShift, newSelectionStartColumn);
      LogicalPosition newSelectionEnd = truncate(selectionEnd.line + lineShift, newSelectionEndColumn);
      newSelectionStartOffset = myEditor.logicalPositionToOffset(newSelectionStart);
      newSelectionEndOffset = myEditor.logicalPositionToOffset(newSelectionEnd);
      newSelectionStartPosition = myEditor.logicalToVisualPosition(newSelectionStart);
      newSelectionEndPosition = myEditor.logicalToVisualPosition(newSelectionEnd);
      hasNewSelection = !newSelectionStart.equals(newSelectionEnd);
    }
    else {
      newSelectionStartOffset = 0;
      newSelectionEndOffset = 0;
      newSelectionStartPosition = null;
      newSelectionEndPosition = null;
      hasNewSelection = false;
      newSelectionStartColumn = -1;
      newSelectionEndColumn = -1;
    }
    LogicalPosition oldPosition = getLogicalPosition();
    int newLine = oldPosition.line + lineShift;
    if (newLine < 0 || newLine >= myEditor.getDocument().getLineCount()) {
      Disposer.dispose(clone);
      return null;
    }
    clone.moveToLogicalPosition(new LogicalPosition(newLine, myLastColumnNumber), false, null, false);
    clone.myLastColumnNumber = myLastColumnNumber;
    clone.myDesiredX = myDesiredX >= 0 ? myDesiredX : getCurrentX();
    clone.myDesiredSelectionStartColumn = newSelectionStartColumn;
    clone.myDesiredSelectionEndColumn = newSelectionEndColumn;

    if (myEditor.getCaretModel().addCaret(clone)) {
      if (hasNewSelection) {
        myEditor.getCaretModel().doWithCaretMerging(new Runnable() {
          @Override
          public void run() {
            clone.setSelection(newSelectionStartPosition, newSelectionStartOffset, newSelectionEndPosition, newSelectionEndOffset);
          }
        });
        if (!clone.isValid()) {
          return null;
        }
      }
      myEditor.getScrollingModel().scrollTo(clone.getLogicalPosition(), ScrollType.RELATIVE);
      return clone;
    }
    else {
      Disposer.dispose(clone);
      return null;
    }
  }

  private LogicalPosition truncate(int line, int column) {
    if (line < 0) {
      return new LogicalPosition(0, 0);
    }
    else if (line >= myEditor.getDocument().getLineCount()) {
      return myEditor.offsetToLogicalPosition(myEditor.getDocument().getTextLength());
    }
    else {
      return new LogicalPosition(line, column);
    }
  }

  /**
   * @return  information on whether current selection's direction in known
   * @see #setUnknownDirection(boolean)
   */
  public boolean isUnknownDirection() {
    return myUnknownDirection;
  }

  /**
   * There is a possible case that we don't know selection's direction. For example, a user might triple-click editor (select the
   * whole line). We can't say what selection end is a {@link #getLeadSelectionOffset() leading end} then. However, that matters
   * in a situation when a user clicks before or after that line holding Shift key. It's expected that the selection is expanded
   * up to that point than.
   * <p/>
   * That's why we allow to specify that the direction is unknown and {@link #isUnknownDirection() expose this information}
   * later.
   * <p/>
   * <b>Note:</b> when this method is called with <code>'true'</code>, subsequent calls are guaranteed to return <code>'true'</code>
   * until selection is changed. 'Unknown direction' flag is automatically reset then.
   *
   * @param unknownDirection
   */
  public void setUnknownDirection(boolean unknownDirection) {
    myUnknownDirection = unknownDirection;
  }

  @Override
  public int getSelectionStart() {
    validateContext(false);
    if (hasSelection()) {
      MyRangeMarker marker = mySelectionMarker;
      if (marker != null) {
        return marker.getStartOffset();
      }
    }
    return getOffset();
  }

  @NotNull
  @Override
  public VisualPosition getSelectionStartPosition() {
    validateContext(false);
    VisualPosition position;
    if (hasSelection() && mySelectionMarker != null) {
      position = mySelectionMarker.getStartPosition();
      if (position == null) {
        position = myEditor.offsetToVisualPosition(mySelectionMarker.getStartOffset());
      }
    }
    else {
      position = isVirtualSelectionEnabled() ? getVisualPosition() : myEditor.offsetToVisualPosition(getOffset());
    }
    if (hasVirtualSelection()) {
      position = new VisualPosition(position.line, position.column + myStartVirtualOffset);
    }
    return position;
  }

  @Override
  public int getSelectionEnd() {
    validateContext(false);
    if (hasSelection()) {
      MyRangeMarker marker = mySelectionMarker;
      if (marker != null) {
        return marker.getEndOffset();
      }
    }
    return getOffset();
  }

  @NotNull
  @Override
  public VisualPosition getSelectionEndPosition() {
    validateContext(false);
    VisualPosition position;
    if (hasSelection() && mySelectionMarker != null) {
      position = mySelectionMarker.getEndPosition();
      if (position == null) {
        position = myEditor.offsetToVisualPosition(mySelectionMarker.getEndOffset());
      }
    }
    else {
      position = isVirtualSelectionEnabled() ? getVisualPosition() : myEditor.offsetToVisualPosition(getOffset());
    }
    if (hasVirtualSelection()) {
      position = new VisualPosition(position.line, position.column + myEndVirtualOffset);
    }
    return position;
  }

  @Override
  public boolean hasSelection() {
    validateContext(false);
    MyRangeMarker marker = mySelectionMarker;
    return marker != null && marker.isValid() && (marker.getEndOffset() > marker.getStartOffset()
                                                  || isVirtualSelectionEnabled() && myEndVirtualOffset > myStartVirtualOffset);
  }

  @Override
  public void setSelection(int startOffset, int endOffset) {
    setSelection(startOffset, endOffset, true);
  }

  @Override
  public void setSelection(int startOffset, int endOffset, boolean updateSystemSelection) {
    doSetSelection(myEditor.offsetToVisualPosition(startOffset), startOffset, myEditor.offsetToVisualPosition(endOffset), endOffset, false,
                   updateSystemSelection);
  }

  @Override
  public void setSelection(int startOffset, @Nullable VisualPosition endPosition, int endOffset) {
    VisualPosition startPosition;
    if (hasSelection()) {
      startPosition = getLeadSelectionPosition();
    }
    else {
      startPosition = myEditor.offsetToVisualPosition(startOffset);
    }
    setSelection(startPosition, startOffset, endPosition, endOffset);
  }

  @Override
  public void setSelection(@Nullable VisualPosition startPosition, int startOffset, @Nullable VisualPosition endPosition, int endOffset) {
    setSelection(startPosition, startOffset, endPosition, endOffset, true);
  }

  @Override
  public void setSelection(@Nullable VisualPosition startPosition, int startOffset, @Nullable VisualPosition endPosition, int endOffset, boolean updateSystemSelection) {
    VisualPosition startPositionToUse = startPosition == null ? myEditor.offsetToVisualPosition(startOffset) : startPosition;
    VisualPosition endPositionToUse = endPosition == null ? myEditor.offsetToVisualPosition(endOffset) : endPosition;
    doSetSelection(startPositionToUse, startOffset, endPositionToUse, endOffset, true, updateSystemSelection);
  }

  private void doSetSelection(@NotNull final VisualPosition startPosition,
                              final int _startOffset,
                              @NotNull final VisualPosition endPosition,
                              final int _endOffset,
                              final boolean visualPositionAware,
                              final boolean updateSystemSelection)
  {
    myEditor.getCaretModel().doWithCaretMerging(new Runnable() {
      public void run() {
        int startOffset = _startOffset;
        int endOffset = _endOffset;
        myUnknownDirection = false;
        final Document doc = myEditor.getDocument();

        validateContext(true);

        myEditor.getSelectionModel().removeBlockSelection();

        int textLength = doc.getTextLength();
        if (startOffset < 0 || startOffset > textLength) {
          LOG.error("Wrong startOffset: " + startOffset + ", textLength=" + textLength);
        }
        if (endOffset < 0 || endOffset > textLength) {
          LOG.error("Wrong endOffset: " + endOffset + ", textLength=" + textLength);
        }

        if (!visualPositionAware && startOffset == endOffset) {
          removeSelection();
          return;
        }

    /* Normalize selection */
        boolean switchedOffsets = false;
        if (startOffset > endOffset) {
          int tmp = startOffset;
          startOffset = endOffset;
          endOffset = tmp;
          switchedOffsets = true;
        }

        FoldingModelEx foldingModel = myEditor.getFoldingModel();
        FoldRegion startFold = foldingModel.getCollapsedRegionAtOffset(startOffset);
        if (startFold != null && startFold.getStartOffset() < startOffset) {
          startOffset = startFold.getStartOffset();
        }

        FoldRegion endFold = foldingModel.getCollapsedRegionAtOffset(endOffset);
        if (endFold != null && endFold.getStartOffset() < endOffset) {
          // All visual positions that lay at collapsed fold region placeholder are mapped to the same offset. Hence, there are
          // at least two distinct situations - selection end is located inside collapsed fold region placeholder and just before it.
          // We want to expand selection to the fold region end at the former case and keep selection as-is at the latest one.
          endOffset = endFold.getEndOffset();
        }

        int oldSelectionStart;
        int oldSelectionEnd;

        if (hasSelection()) {
          oldSelectionStart = getSelectionStart();
          oldSelectionEnd = getSelectionEnd();
          if (oldSelectionStart == startOffset && oldSelectionEnd == endOffset && !visualPositionAware) return;
        }
        else {
          oldSelectionStart = oldSelectionEnd = getOffset();
        }

        MyRangeMarker marker = mySelectionMarker;
        if (marker != null) {
          marker.release();
        }

        marker = new MyRangeMarker((DocumentEx)doc, startOffset, endOffset);
        myStartVirtualOffset = 0;
        myEndVirtualOffset = 0;
        if (visualPositionAware) {
          if (endPosition.after(startPosition)) {
            marker.setStartPosition(startPosition);
            marker.setEndPosition(endPosition);
            marker.setEndPositionIsLead(false);
          }
          else {
            marker.setStartPosition(endPosition);
            marker.setEndPosition(startPosition);
            marker.setEndPositionIsLead(true);
          }

          if (isVirtualSelectionEnabled() &&
              myEditor.getDocument().getLineNumber(startOffset) == myEditor.getDocument().getLineNumber(endOffset)) {
            int endLineColumn = myEditor.offsetToVisualPosition(endOffset).column;
            int startDiff =
              EditorUtil.isAtLineEnd(myEditor, switchedOffsets ? endOffset : startOffset) ? startPosition.column - endLineColumn : 0;
            int endDiff =
              EditorUtil.isAtLineEnd(myEditor, switchedOffsets ? startOffset : endOffset) ? endPosition.column - endLineColumn : 0;
            myStartVirtualOffset = Math.max(0, Math.min(startDiff, endDiff));
            myEndVirtualOffset = Math.max(0, Math.max(startDiff, endDiff));
          }
        }
        mySelectionMarker = marker;

        myEditor.getSelectionModel().fireSelectionChanged(oldSelectionStart, oldSelectionEnd, startOffset, endOffset);

        if (updateSystemSelection) {
          updateSystemSelection();
        }
      }
    });
  }

  private void updateSystemSelection() {
    if (GraphicsEnvironment.isHeadless()) return;

    final Clipboard clip = myEditor.getComponent().getToolkit().getSystemSelection();
    if (clip != null) {
      clip.setContents(new StringSelection(myEditor.getSelectionModel().getSelectedText(true)), EmptyClipboardOwner.INSTANCE);
    }
  }

  @Override
  public void removeSelection() {
    if (myEditor.isStickySelection()) {
      // Most of our 'change caret position' actions (like move caret to word start/end etc) remove active selection.
      // However, we don't want to do that for 'sticky selection'.
      return;
    }
    myEditor.getCaretModel().doWithCaretMerging(new Runnable() {
      public void run() {
        validateContext(true);
        myEditor.getSelectionModel().removeBlockSelection();
        int caretOffset = getOffset();
        MyRangeMarker marker = mySelectionMarker;
        if (marker != null) {
          int startOffset = marker.getStartOffset();
          int endOffset = marker.getEndOffset();
          marker.release();
          mySelectionMarker = null;
          myStartVirtualOffset = 0;
          myEndVirtualOffset = 0;
          myEditor.getSelectionModel().fireSelectionChanged(startOffset, endOffset, caretOffset, caretOffset);
        }
      }
    });
  }

  @Override
  public int getLeadSelectionOffset() {
    validateContext(false);
    int caretOffset = getOffset();
    if (hasSelection()) {
      MyRangeMarker marker = mySelectionMarker;
      if (marker != null) {
        int startOffset = marker.getStartOffset();
        int endOffset = marker.getEndOffset();
        if (caretOffset != startOffset && caretOffset != endOffset) {
          // Try to check if current selection is tweaked by fold region.
          FoldingModelEx foldingModel = myEditor.getFoldingModel();
          FoldRegion foldRegion = foldingModel.getCollapsedRegionAtOffset(caretOffset);
          if (foldRegion != null) {
            if (foldRegion.getStartOffset() == startOffset) {
              return endOffset;
            }
            else if (foldRegion.getEndOffset() == endOffset) {
              return startOffset;
            }
          }
        }

        if (caretOffset == endOffset) {
          return startOffset;
        }
        else {
          return endOffset;
        }
      }
    }
    return caretOffset;
  }

  @NotNull
  @Override
  public VisualPosition getLeadSelectionPosition() {
    MyRangeMarker marker = mySelectionMarker;
    VisualPosition caretPosition = getVisualPosition();
    if (isVirtualSelectionEnabled() && !hasSelection()) {
      return caretPosition;
    }
    if (marker == null) {
      return caretPosition;
    }

    if (marker.isEndPositionIsLead()) {
      VisualPosition result = marker.getEndPosition();
      if (result == null) {
        return getSelectionEndPosition();
      }
      else {
        if (hasVirtualSelection()) {
          result = new VisualPosition(result.line, result.column + myEndVirtualOffset);
        }
        return result;
      }
    }
    else {
      VisualPosition result = marker.getStartPosition();
      if (result == null) {
        return getSelectionStartPosition();
      }
      else {
        if (hasVirtualSelection()) {
          result = new VisualPosition(result.line, result.column + myStartVirtualOffset);
        }
        return result;
      }
    }
  }

  @Override
  public void selectLineAtCaret() {
    validateContext(true);
    myEditor.getCaretModel().doWithCaretMerging(new Runnable() {
      public void run() {
        SelectionModelImpl.doSelectLineAtCaret(myEditor);
      }
    });
  }

  @Override
  public void selectWordAtCaret(final boolean honorCamelWordsSettings) {
    validateContext(true);
    myEditor.getCaretModel().doWithCaretMerging(new Runnable() {
      public void run() {
        removeSelection();
        final EditorSettings settings = myEditor.getSettings();
        boolean camelTemp = settings.isCamelWords();

        final boolean needOverrideSetting = camelTemp && !honorCamelWordsSettings;
        if (needOverrideSetting) {
          settings.setCamelWords(false);
        }

        try {
          EditorActionHandler handler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_SELECT_WORD_AT_CARET);
          handler.execute(myEditor, CaretImpl.this, myEditor.getDataContext());
        }
        finally {
          if (needOverrideSetting) {
            settings.resetCamelWords();
          }
        }
      }
    });
  }

  @Nullable
  @Override
  public String getSelectedText() {
    if (!hasSelection()) {
      return null;
    }
    CharSequence text = myEditor.getDocument().getCharsSequence();
    int selectionStart = getSelectionStart();
    int selectionEnd = getSelectionEnd();
    String selectedText = text.subSequence(selectionStart, selectionEnd).toString();
    if (isVirtualSelectionEnabled() && myEndVirtualOffset > myStartVirtualOffset) {
      int padding = myEndVirtualOffset - myStartVirtualOffset;
      StringBuilder builder = new StringBuilder(selectedText.length() + padding);
      builder.append(selectedText);
      for (int i = 0; i < padding; i++) {
        builder.append(' ');
      }
      return builder.toString();
    }
    else {
      return selectedText;
    }
  }

  private void validateContext(boolean isWrite) {
    if (!myEditor.getComponent().isShowing()) return;
    if (isWrite) {
      ApplicationManager.getApplication().assertIsDispatchThread();
    }
    else {
      ApplicationManager.getApplication().assertReadAccessAllowed();
    }
  }

  private boolean isVirtualSelectionEnabled() {
    return myEditor.isColumnMode() && supportsMultipleCarets();
  }

  boolean hasVirtualSelection() {
    validateContext(false);
    MyRangeMarker marker = mySelectionMarker;
    return marker != null && marker.isValid() && isVirtualSelectionEnabled() && myEndVirtualOffset > myStartVirtualOffset;
  }

  private int getCurrentX() {
    return myEditor.visualPositionToXY(myVisibleCaret).x;
  }

  @Override
  @NotNull
  public EditorImpl getEditor() {
    return myEditor;
  }

  @Override
  public String toString() {
    return "Caret at " + myVisibleCaret + (mySelectionMarker == null ? "" : (", selection marker: " + mySelectionMarker.toString()));
  }

  /**
   * Encapsulates information about target vertical range info - its <code>'y'</code> coordinate and height in pixels.
   */
  public static class VerticalInfo {
    public final int y;
    public final int height;

    private VerticalInfo(int y, int height) {
      this.y = y;
      this.height = height;
    }
  }

  private class MyRangeMarker extends RangeMarkerImpl {
    private VisualPosition myStartPosition;
    private VisualPosition myEndPosition;
    private boolean myEndPositionIsLead;
    private boolean myIsReleased;

    MyRangeMarker(DocumentEx document, int start, int end) {
      super(document, start, end, true);
      myIsReleased = false;
    }

    public void release() {
      myIsReleased = true;
      dispose();
    }

    @Nullable
    public VisualPosition getStartPosition() {
      invalidateVisualPositions();
      return myStartPosition;
    }

    public void setStartPosition(@NotNull VisualPosition startPosition) {
      myStartPosition = startPosition;
    }

    @Nullable
    public VisualPosition getEndPosition() {
      invalidateVisualPositions();
      return myEndPosition;
    }

    public void setEndPosition(@NotNull VisualPosition endPosition) {
      myEndPosition = endPosition;
    }

    public boolean isEndPositionIsLead() {
      return myEndPositionIsLead;
    }

    public void setEndPositionIsLead(boolean endPositionIsLead) {
      myEndPositionIsLead = endPositionIsLead;
    }

    int startBefore;
    int endBefore;

    @Override
    protected void changedUpdateImpl(DocumentEvent e) {
      if (myIsReleased) return;
      startBefore = getStartOffset();
      endBefore = getEndOffset();
      super.changedUpdateImpl(e);
    }

    private void invalidateVisualPositions() {
      SoftWrapModelImpl model = myEditor.getSoftWrapModel();
      if (!myEditor.offsetToVisualPosition(getStartOffset()).equals(myStartPosition) && model.getSoftWrap(getStartOffset()) == null
          || !myEditor.offsetToVisualPosition(getEndOffset()).equals(myEndPosition) && model.getSoftWrap(getEndOffset()) == null) {
        myStartPosition = null;
        myEndPosition = null;
      }
    }
  }
}