1
0
mirror of https://github.com/chylex/IntelliJ-IdeaVim.git synced 2025-06-12 17:34:04 +02:00

Revert "Update formatting"

This reverts commit bf0fba9c58.
This commit is contained in:
Alex Plate 2023-03-27 11:32:59 +03:00
parent bf0fba9c58
commit 832c1c0be3
No known key found for this signature in database
GPG Key ID: 0B97153C8FFEC09F
71 changed files with 1875 additions and 1887 deletions
.idea/fileTemplates/code
src
vim-engine/src/main/kotlin/com/maddyhome/idea/vim

View File

@ -1 +1 @@
com.maddyhome.idea.vim.helper.MessageHelper.message("${PROPERTY_KEY}",${PARAMETERS}) com.maddyhome.idea.vim.helper.MessageHelper.message("${PROPERTY_KEY}", ${PARAMETERS})

View File

@ -30,17 +30,14 @@ import java.awt.event.MouseListener;
* @author vlan * @author vlan
*/ */
public class EventFacade { public class EventFacade {
private static final @NotNull private static final @NotNull EventFacade ourInstance = new EventFacade();
EventFacade ourInstance = new EventFacade();
private @Nullable private @Nullable TypedActionHandler myOriginalTypedActionHandler;
TypedActionHandler myOriginalTypedActionHandler;
private EventFacade() { private EventFacade() {
} }
public static @NotNull public static @NotNull EventFacade getInstance() {
EventFacade getInstance() {
return ourInstance; return ourInstance;
} }
@ -146,8 +143,7 @@ public class EventFacade {
editor.getSelectionModel().removeSelectionListener(listener); editor.getSelectionModel().removeSelectionListener(listener);
} }
private @NotNull private @NotNull TypedAction getTypedAction() {
TypedAction getTypedAction() {
return TypedAction.getInstance(); return TypedAction.getInstance();
} }
} }

View File

@ -43,15 +43,13 @@ public class RegisterActions {
}, VimPlugin.getInstance()); }, VimPlugin.getInstance());
} }
public static @Nullable public static @Nullable EditorActionHandlerBase findAction(@NotNull String id) {
EditorActionHandlerBase findAction(@NotNull String id) {
return VIM_ACTIONS_EP.getExtensionList(ApplicationManager.getApplication()).stream() return VIM_ACTIONS_EP.getExtensionList(ApplicationManager.getApplication()).stream()
.filter(vimActionBean -> vimActionBean.getActionId().equals(id)).findFirst().map(ActionBeanClass::getInstance) .filter(vimActionBean -> vimActionBean.getActionId().equals(id)).findFirst().map(ActionBeanClass::getInstance)
.orElse(null); .orElse(null);
} }
public static @NotNull public static @NotNull EditorActionHandlerBase findActionOrDie(@NotNull String id) {
EditorActionHandlerBase findActionOrDie(@NotNull String id) {
EditorActionHandlerBase action = findAction(id); EditorActionHandlerBase action = findAction(id);
if (action == null) throw new RuntimeException("Action " + id + " is not registered"); if (action == null) throw new RuntimeException("Action " + id + " is not registered");
return action; return action;

View File

@ -70,8 +70,7 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
VimInjectorKt.setInjector(new IjVimInjector()); VimInjectorKt.setInjector(new IjVimInjector());
} }
private final @NotNull private final @NotNull VimState state = new VimState();
VimState state = new VimState();
public Disposable onOffDisposable; public Disposable onOffDisposable;
private int previousStateVersion = 0; private int previousStateVersion = 0;
private String previousKeyMap = ""; private String previousKeyMap = "";
@ -87,160 +86,130 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
/** /**
* @return NotificationService as applicationService if project is null and projectService otherwise * @return NotificationService as applicationService if project is null and projectService otherwise
*/ */
public static @NotNull public static @NotNull NotificationService getNotifications(@Nullable Project project) {
NotificationService getNotifications(@Nullable Project project) {
if (project == null) { if (project == null) {
return ApplicationManager.getApplication().getService(NotificationService.class); return ApplicationManager.getApplication().getService(NotificationService.class);
} else { }
else {
return project.getService(NotificationService.class); return project.getService(NotificationService.class);
} }
} }
public static @NotNull public static @NotNull VimState getVimState() {
VimState getVimState() {
return getInstance().state; return getInstance().state;
} }
public static @NotNull public static @NotNull MotionGroup getMotion() {
MotionGroup getMotion() {
return ApplicationManager.getApplication().getService(MotionGroup.class); return ApplicationManager.getApplication().getService(MotionGroup.class);
} }
public static @NotNull public static @NotNull XMLGroup getXML() {
XMLGroup getXML() {
return ApplicationManager.getApplication().getService(XMLGroup.class); return ApplicationManager.getApplication().getService(XMLGroup.class);
} }
public static @NotNull public static @NotNull ChangeGroup getChange() {
ChangeGroup getChange() { return ((ChangeGroup)VimInjectorKt.getInjector().getChangeGroup());
return ((ChangeGroup) VimInjectorKt.getInjector().getChangeGroup());
} }
public static @NotNull public static @NotNull CommandGroup getCommand() {
CommandGroup getCommand() {
return ApplicationManager.getApplication().getService(CommandGroup.class); return ApplicationManager.getApplication().getService(CommandGroup.class);
} }
@Deprecated // "Please use `injector.markService` instead" @Deprecated // "Please use `injector.markService` instead"
@ApiStatus.ScheduledForRemoval(inVersion = "2.3") @ApiStatus.ScheduledForRemoval(inVersion = "2.3")
public static @NotNull public static @NotNull MarkGroup getMark() {
MarkGroup getMark() {
return ApplicationManager.getApplication().getService(MarkGroup.class); return ApplicationManager.getApplication().getService(MarkGroup.class);
} }
public static @NotNull public static @NotNull RegisterGroup getRegister() {
RegisterGroup getRegister() { return ((RegisterGroup)VimInjectorKt.getInjector().getRegisterGroup());
return ((RegisterGroup) VimInjectorKt.getInjector().getRegisterGroup());
} }
public static @NotNull public static @NotNull FileGroup getFile() {
FileGroup getFile() { return (FileGroup)VimInjectorKt.getInjector().getFile();
return (FileGroup) VimInjectorKt.getInjector().getFile();
} }
public static @NotNull public static @NotNull SearchGroup getSearch() {
SearchGroup getSearch() {
return ApplicationManager.getApplication().getService(SearchGroup.class); return ApplicationManager.getApplication().getService(SearchGroup.class);
} }
public static @Nullable public static @Nullable SearchGroup getSearchIfCreated() {
SearchGroup getSearchIfCreated() {
return ApplicationManager.getApplication().getServiceIfCreated(SearchGroup.class); return ApplicationManager.getApplication().getServiceIfCreated(SearchGroup.class);
} }
public static @NotNull public static @NotNull ProcessGroup getProcess() {
ProcessGroup getProcess() { return ((ProcessGroup)VimInjectorKt.getInjector().getProcessGroup());
return ((ProcessGroup) VimInjectorKt.getInjector().getProcessGroup());
} }
public static @NotNull public static @NotNull MacroGroup getMacro() {
MacroGroup getMacro() { return (MacroGroup)VimInjectorKt.getInjector().getMacro();
return (MacroGroup) VimInjectorKt.getInjector().getMacro();
} }
public static @NotNull public static @NotNull DigraphGroup getDigraph() {
DigraphGroup getDigraph() { return (DigraphGroup)VimInjectorKt.getInjector().getDigraphGroup();
return (DigraphGroup) VimInjectorKt.getInjector().getDigraphGroup();
} }
public static @NotNull public static @NotNull HistoryGroup getHistory() {
HistoryGroup getHistory() {
return ApplicationManager.getApplication().getService(HistoryGroup.class); return ApplicationManager.getApplication().getService(HistoryGroup.class);
} }
public static @NotNull public static @NotNull KeyGroup getKey() {
KeyGroup getKey() { return ((KeyGroup)VimInjectorKt.getInjector().getKeyGroup());
return ((KeyGroup) VimInjectorKt.getInjector().getKeyGroup());
} }
public static @Nullable public static @Nullable KeyGroup getKeyIfCreated() {
KeyGroup getKeyIfCreated() { return ((KeyGroup)ApplicationManager.getApplication().getServiceIfCreated(VimKeyGroup.class));
return ((KeyGroup) ApplicationManager.getApplication().getServiceIfCreated(VimKeyGroup.class));
} }
public static @NotNull public static @NotNull WindowGroup getWindow() {
WindowGroup getWindow() { return ((WindowGroup)VimInjectorKt.getInjector().getWindow());
return ((WindowGroup) VimInjectorKt.getInjector().getWindow());
} }
public static @NotNull public static @NotNull EditorGroup getEditor() {
EditorGroup getEditor() {
return ApplicationManager.getApplication().getService(EditorGroup.class); return ApplicationManager.getApplication().getService(EditorGroup.class);
} }
public static @Nullable public static @Nullable EditorGroup getEditorIfCreated() {
EditorGroup getEditorIfCreated() {
return ApplicationManager.getApplication().getServiceIfCreated(EditorGroup.class); return ApplicationManager.getApplication().getServiceIfCreated(EditorGroup.class);
} }
public static @NotNull public static @NotNull VisualMotionGroup getVisualMotion() {
VisualMotionGroup getVisualMotion() { return (VisualMotionGroup)VimInjectorKt.getInjector().getVisualMotionGroup();
return (VisualMotionGroup) VimInjectorKt.getInjector().getVisualMotionGroup();
} }
public static @NotNull public static @NotNull YankGroupBase getYank() {
YankGroupBase getYank() { return (YankGroupBase)VimInjectorKt.getInjector().getYank();
return (YankGroupBase) VimInjectorKt.getInjector().getYank();
} }
public static @NotNull public static @NotNull PutGroup getPut() {
PutGroup getPut() { return (PutGroup)VimInjectorKt.getInjector().getPut();
return (PutGroup) VimInjectorKt.getInjector().getPut();
} }
public static @NotNull public static @NotNull VariableService getVariableService() {
VariableService getVariableService() {
return ApplicationManager.getApplication().getService(VariableService.class); return ApplicationManager.getApplication().getService(VariableService.class);
} }
public static @NotNull public static @NotNull VimOptionGroup getOptionGroup() {
VimOptionGroup getOptionGroup() {
return VimInjectorKt.getInjector().getOptionGroup(); return VimInjectorKt.getInjector().getOptionGroup();
} }
/** /** Deprecated: Use getOptionGroup */
* Deprecated: Use getOptionGroup
*/
@Deprecated @Deprecated
// Used by which-key 0.8.0, IdeaVimExtension 1.6.5 + 1.6.8 // Used by which-key 0.8.0, IdeaVimExtension 1.6.5 + 1.6.8
public static @NotNull public static @NotNull OptionService getOptionService() {
OptionService getOptionService() {
return VimInjectorKt.getInjector().getOptionService(); return VimInjectorKt.getInjector().getOptionService();
} }
private static @NotNull private static @NotNull NotificationService getNotifications() {
NotificationService getNotifications() {
return getNotifications(null); return getNotifications(null);
} }
public static @NotNull public static @NotNull PluginId getPluginId() {
PluginId getPluginId() {
return PluginId.getId(IDEAVIM_PLUGIN_ID); return PluginId.getId(IDEAVIM_PLUGIN_ID);
} }
public static @NotNull public static @NotNull String getVersion() {
String getVersion() {
final IdeaPluginDescriptor plugin = PluginManagerCore.getPlugin(getPluginId()); final IdeaPluginDescriptor plugin = PluginManagerCore.getPlugin(getPluginId());
return plugin != null ? plugin.getVersion() : "SNAPSHOT"; return plugin != null ? plugin.getVersion() : "SNAPSHOT";
} }
@ -284,8 +253,7 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
VimInjectorKt.getInjector().getMessages().showStatusBarMessage(null, msg); VimInjectorKt.getInjector().getMessages().showStatusBarMessage(null, msg);
} }
public static @NotNull public static @NotNull VimPlugin getInstance() {
VimPlugin getInstance() {
return ApplicationManager.getApplication().getService(VimPlugin.class); return ApplicationManager.getApplication().getService(VimPlugin.class);
} }
@ -296,7 +264,8 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
Application application = ApplicationManager.getApplication(); Application application = ApplicationManager.getApplication();
if (application.isUnitTestMode()) { if (application.isUnitTestMode()) {
application.invokeAndWait(this::turnOnPlugin); application.invokeAndWait(this::turnOnPlugin);
} else { }
else {
application.invokeLater(this::turnOnPlugin); application.invokeLater(this::turnOnPlugin);
} }
} }
@ -400,7 +369,8 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
if (showNotification && VimPlugin.getNotifications().enableRepeatingMode() == Messages.YES) { if (showNotification && VimPlugin.getNotifications().enableRepeatingMode() == Messages.YES) {
getEditor().setKeyRepeat(true); getEditor().setKeyRepeat(true);
keyRepeat.setEnabled(true); keyRepeat.setEnabled(true);
} else { }
else {
getEditor().setKeyRepeat(false); getEditor().setKeyRepeat(false);
} }
} }
@ -432,7 +402,8 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
if (state != null) { if (state != null) {
try { try {
previousStateVersion = Integer.parseInt(state.getAttributeValue("version")); previousStateVersion = Integer.parseInt(state.getAttributeValue("version"));
} catch (NumberFormatException ignored) { }
catch (NumberFormatException ignored) {
} }
enabled = Boolean.parseBoolean(state.getAttributeValue("enabled")); enabled = Boolean.parseBoolean(state.getAttributeValue("enabled"));
previousKeyMap = state.getAttributeValue("keymap"); previousKeyMap = state.getAttributeValue("keymap");
@ -461,8 +432,8 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
private void legacyStateLoading(@NotNull Element element) { private void legacyStateLoading(@NotNull Element element) {
if (previousStateVersion > 0 && previousStateVersion < 5) { if (previousStateVersion > 0 && previousStateVersion < 5) {
// Migrate settings from 4 to 5 version // Migrate settings from 4 to 5 version
((VimMarkServiceImpl) VimInjectorKt.getInjector().getMarkService()).loadState(element); ((VimMarkServiceImpl)VimInjectorKt.getInjector().getMarkService()).loadState(element);
((VimJumpServiceImpl) VimInjectorKt.getInjector().getJumpService()).loadState(element); ((VimJumpServiceImpl)VimInjectorKt.getInjector().getJumpService()).loadState(element);
getRegister().readData(element); getRegister().readData(element);
getSearch().readData(element); getSearch().readData(element);
getHistory().readData(element); getHistory().readData(element);

View File

@ -28,13 +28,11 @@ public class VimScriptGlobalEnvironment {
private VimScriptGlobalEnvironment() { private VimScriptGlobalEnvironment() {
} }
public static @NotNull public static @NotNull VimScriptGlobalEnvironment getInstance() {
VimScriptGlobalEnvironment getInstance() {
return ourInstance; return ourInstance;
} }
public @NotNull public @NotNull Map<String, Object> getVariables() {
Map<String, Object> getVariables() {
return myVariables; return myVariables;
} }
} }

View File

@ -18,12 +18,10 @@ import org.jetbrains.annotations.NotNull;
* @author vlan * @author vlan
*/ */
public interface VimExtension { public interface VimExtension {
@NotNull @NotNull ExtensionPointName<ExtensionBeanClass> EP_NAME = ExtensionPointName.create("IdeaVIM.vimExtension");
ExtensionPointName<ExtensionBeanClass> EP_NAME = ExtensionPointName.create("IdeaVIM.vimExtension");
@VimNlsSafe @VimNlsSafe
@NotNull @NotNull String getName();
String getName();
default MappingOwner getOwner() { default MappingOwner getOwner() {
return MappingOwner.Plugin.Companion.get(getName()); return MappingOwner.Plugin.Companion.get(getName());

View File

@ -42,8 +42,7 @@ import static com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMappingI
public class VimArgTextObjExtension implements VimExtension { public class VimArgTextObjExtension implements VimExtension {
@Override @Override
public @NotNull public @NotNull String getName() {
String getName() {
return "argtextobj"; return "argtextobj";
} }
@ -62,10 +61,8 @@ public class VimArgTextObjExtension implements VimExtension {
*/ */
private static class BracketPairs { private static class BracketPairs {
// NOTE: brackets must match by the position, and ordered by rank (highest to lowest). // NOTE: brackets must match by the position, and ordered by rank (highest to lowest).
@NotNull @NotNull private final String openBrackets;
private final String openBrackets; @NotNull private final String closeBrackets;
@NotNull
private final String closeBrackets;
static class ParseException extends Exception { static class ParseException extends Exception {
public ParseException(@NotNull String message) { public ParseException(@NotNull String message) {
@ -213,8 +210,8 @@ public class VimArgTextObjExtension implements VimExtension {
return null; return null;
} }
} }
final ArgBoundsFinder finder = new ArgBoundsFinder(((IjVimEditor) editor).getEditor().getDocument(), bracketPairs); final ArgBoundsFinder finder = new ArgBoundsFinder(((IjVimEditor)editor).getEditor().getDocument(), bracketPairs);
int pos = ((IjVimCaret) caret).getCaret().getOffset(); int pos = ((IjVimCaret)caret).getCaret().getOffset();
for (int i = 0; i < count; ++i) { for (int i = 0; i < count; ++i) {
if (!finder.findBoundsAt(pos)) { if (!finder.findBoundsAt(pos)) {
@ -261,7 +258,7 @@ public class VimArgTextObjExtension implements VimExtension {
if (vimStateMachine.getMode() == VimStateMachine.Mode.VISUAL) { if (vimStateMachine.getMode() == VimStateMachine.Mode.VISUAL) {
com.maddyhome.idea.vim.group.visual.EngineVisualGroupKt.vimSetSelection(caret, range.getStartOffset(), range.getEndOffset() - 1, true); com.maddyhome.idea.vim.group.visual.EngineVisualGroupKt.vimSetSelection(caret, range.getStartOffset(), range.getEndOffset() - 1, true);
} else { } else {
InlayHelperKt.moveToInlayAwareOffset(((IjVimCaret) caret).getCaret(), range.getStartOffset()); InlayHelperKt.moveToInlayAwareOffset(((IjVimCaret)caret).getCaret(), range.getStartOffset());
} }
} }
} }
@ -278,18 +275,14 @@ public class VimArgTextObjExtension implements VimExtension {
* position * position
*/ */
private static class ArgBoundsFinder { private static class ArgBoundsFinder {
@NotNull @NotNull private final CharSequence text;
private final CharSequence text; @NotNull private final Document document;
@NotNull @NotNull private final BracketPairs brackets;
private final Document document;
@NotNull
private final BracketPairs brackets;
private int leftBound = Integer.MAX_VALUE; private int leftBound = Integer.MAX_VALUE;
private int rightBound = Integer.MIN_VALUE; private int rightBound = Integer.MIN_VALUE;
private int leftBracket; private int leftBracket;
private int rightBracket; private int rightBracket;
private @Nls private @Nls String error = null;
String error = null;
private static final String QUOTES = "\"'"; private static final String QUOTES = "\"'";
private static final int MAX_SEARCH_LINES = 10; private static final int MAX_SEARCH_LINES = 10;
@ -419,7 +412,7 @@ public class VimArgTextObjExtension implements VimExtension {
/** /**
* Detects if current position is inside a quoted string and adjusts * Detects if current position is inside a quoted string and adjusts
* left and right bounds to the boundaries of the string. * left and right bounds to the boundaries of the string.
* <p> *
* NOTE: Does not support line continuations for quoted string ('\' at the end of line). * NOTE: Does not support line continuations for quoted string ('\' at the end of line).
*/ */
private void getOutOfQuotedText() { private void getOutOfQuotedText() {

View File

@ -44,7 +44,7 @@ import static com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMappingI
* <li>Then copy the resulting text to another application ("*yie)</li> * <li>Then copy the resulting text to another application ("*yie)</li>
* </ul> * </ul>
* </ul> * </ul>
* <p> *
* See also the reference manual for more details at: * See also the reference manual for more details at:
* https://github.com/kana/vim-textobj-entire/blob/master/doc/textobj-entire.txt * https://github.com/kana/vim-textobj-entire/blob/master/doc/textobj-entire.txt
* *
@ -97,12 +97,12 @@ public class VimTextObjEntireExtension implements VimExtension {
int count, int count,
int rawCount, int rawCount,
@Nullable Argument argument) { @Nullable Argument argument) {
int start = 0, end = ((IjVimEditor) editor).getEditor().getDocument().getTextLength(); int start = 0, end = ((IjVimEditor)editor).getEditor().getDocument().getTextLength();
// for the `ie` text object we don't want leading an trailing spaces // for the `ie` text object we don't want leading an trailing spaces
// so we have to scan the document text to find the correct start & end // so we have to scan the document text to find the correct start & end
if (ignoreLeadingAndTrailing) { if (ignoreLeadingAndTrailing) {
String content = ((IjVimEditor) editor).getEditor().getDocument().getText(); String content = ((IjVimEditor)editor).getEditor().getDocument().getText();
for (int i = 0; i < content.length(); ++i) { for (int i = 0; i < content.length(); ++i) {
if (!Character.isWhitespace(content.charAt(i))) { if (!Character.isWhitespace(content.charAt(i))) {
start = i; start = i;

View File

@ -41,7 +41,7 @@ import static com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMapping;
* <li><code>aI</code> <b>A</b>n <b>I</b>ndentation level and lines above and below.</li> * <li><code>aI</code> <b>A</b>n <b>I</b>ndentation level and lines above and below.</li>
* <li><code>iI</code> <b>I</b>nner <b>I</b>ndentation level (no lines above and below). Synonym of <code>ii</code></li> * <li><code>iI</code> <b>I</b>nner <b>I</b>ndentation level (no lines above and below). Synonym of <code>ii</code></li>
* </ul> * </ul>
* <p> *
* See also the reference manual for more details at: * See also the reference manual for more details at:
* https://github.com/michaeljsmith/vim-indent-object/blob/master/doc/indent-object.txt * https://github.com/michaeljsmith/vim-indent-object/blob/master/doc/indent-object.txt
* *
@ -100,8 +100,8 @@ public class VimIndentObject implements VimExtension {
int count, int count,
int rawCount, int rawCount,
@Nullable Argument argument) { @Nullable Argument argument) {
final CharSequence charSequence = ((IjVimEditor) editor).getEditor().getDocument().getCharsSequence(); final CharSequence charSequence = ((IjVimEditor)editor).getEditor().getDocument().getCharsSequence();
final int caretOffset = ((IjVimCaret) caret).getCaret().getOffset(); final int caretOffset = ((IjVimCaret)caret).getCaret().getOffset();
// Part 1: Find the start of the caret line. // Part 1: Find the start of the caret line.
int caretLineStartOffset = caretOffset; int caretLineStartOffset = caretOffset;
@ -257,14 +257,14 @@ public class VimIndentObject implements VimExtension {
@Override @Override
public void execute(@NotNull VimEditor editor, @NotNull ExecutionContext context, @NotNull OperatorArguments operatorArguments) { public void execute(@NotNull VimEditor editor, @NotNull ExecutionContext context, @NotNull OperatorArguments operatorArguments) {
IjVimEditor vimEditor = (IjVimEditor) editor; IjVimEditor vimEditor = (IjVimEditor)editor;
@NotNull VimStateMachine vimStateMachine = VimStateMachine.getInstance(vimEditor); @NotNull VimStateMachine vimStateMachine = VimStateMachine.getInstance(vimEditor);
int count = Math.max(1, vimStateMachine.getCommandBuilder().getCount()); int count = Math.max(1, vimStateMachine.getCommandBuilder().getCount());
final IndentObjectHandler textObjectHandler = new IndentObjectHandler(includeAbove, includeBelow); final IndentObjectHandler textObjectHandler = new IndentObjectHandler(includeAbove, includeBelow);
if (!vimStateMachine.isOperatorPending()) { if (!vimStateMachine.isOperatorPending()) {
((IjVimEditor) editor).getEditor().getCaretModel().runForEachCaret((Caret caret) -> { ((IjVimEditor)editor).getEditor().getCaretModel().runForEachCaret((Caret caret) -> {
final TextRange range = textObjectHandler.getRange(vimEditor, new IjVimCaret(caret), context, count, 0, null); final TextRange range = textObjectHandler.getRange(vimEditor, new IjVimCaret(caret), context, count, 0, null);
if (range != null) { if (range != null) {
try (VimListenerSuppressor.Locked ignored = SelectionVimListenerSuppressor.INSTANCE.lock()) { try (VimListenerSuppressor.Locked ignored = SelectionVimListenerSuppressor.INSTANCE.lock()) {

View File

@ -77,8 +77,7 @@ public class ChangeGroup extends VimChangeGroupBase {
private long lastShownTime = 0L; private long lastShownTime = 0L;
private final @NotNull private final @NotNull EditorMouseListener listener = new EditorMouseListener() {
EditorMouseListener listener = new EditorMouseListener() {
@Override @Override
public void mouseClicked(@NotNull EditorMouseEvent event) { public void mouseClicked(@NotNull EditorMouseEvent event) {
Editor editor = event.getEditor(); Editor editor = event.getEditor();
@ -108,9 +107,9 @@ public class ChangeGroup extends VimChangeGroupBase {
} }
@Override @Override
public @Nullable public @Nullable Pair<@NotNull TextRange, @NotNull SelectionType> getDeleteRangeAndType2(@NotNull VimEditor editor,
Pair<@NotNull TextRange, @NotNull SelectionType> getDeleteRangeAndType2(@NotNull VimEditor editor,
@NotNull VimCaret caret, @NotNull VimCaret caret,
@NotNull ExecutionContext context, @NotNull ExecutionContext context,
final @NotNull Argument argument, final @NotNull Argument argument,
@ -126,7 +125,8 @@ public class ChangeGroup extends VimChangeGroupBase {
SelectionType type; SelectionType type;
if (argument.getMotion().isLinewiseMotion()) { if (argument.getMotion().isLinewiseMotion()) {
type = SelectionType.LINE_WISE; type = SelectionType.LINE_WISE;
} else { }
else {
type = SelectionType.CHARACTER_WISE; type = SelectionType.CHARACTER_WISE;
} }
final Command motion = argument.getMotion(); final Command motion = argument.getMotion();
@ -161,11 +161,11 @@ public class ChangeGroup extends VimChangeGroupBase {
Motion motion = injector.getMotion().getHorizontalMotion(editor, caret, count, true, allowWrap); Motion motion = injector.getMotion().getHorizontalMotion(editor, caret, count, true, allowWrap);
if (motion instanceof Motion.Error) return false; if (motion instanceof Motion.Error) return false;
changeCase(editor, caret, caret.getOffset().getPoint(), ((Motion.AbsoluteOffset) motion).getOffset(), CharacterHelper.CASE_TOGGLE); changeCase(editor, caret, caret.getOffset().getPoint(), ((Motion.AbsoluteOffset)motion).getOffset(), CharacterHelper.CASE_TOGGLE);
motion = injector.getMotion().getHorizontalMotion(editor, caret, count, false, allowWrap); // same but without allow end because we can change till end, but can't move caret there motion = injector.getMotion().getHorizontalMotion(editor, caret, count, false, allowWrap); // same but without allow end because we can change till end, but can't move caret there
if (motion instanceof Motion.AbsoluteOffset) { if (motion instanceof Motion.AbsoluteOffset) {
caret.moveToOffset(EngineEditorHelperKt.normalizeOffset(editor, ((Motion.AbsoluteOffset) motion).getOffset(), false)); caret.moveToOffset(EngineEditorHelperKt.normalizeOffset(editor, ((Motion.AbsoluteOffset)motion).getOffset(), false));
} }
return true; return true;
} }
@ -186,7 +186,8 @@ public class ChangeGroup extends VimChangeGroupBase {
int column = startPosition.getColumn(); int column = startPosition.getColumn();
if (!visualBlockMode) { if (!visualBlockMode) {
column = 0; column = 0;
} else if (append) { }
else if (append) {
column += range.getMaxLength(); column += range.getMaxLength();
if (caret.getVimLastColumn() == VimMotionGroupBase.LAST_COLUMN) { if (caret.getVimLastColumn() == VimMotionGroupBase.LAST_COLUMN) {
column = VimMotionGroupBase.LAST_COLUMN; column = VimMotionGroupBase.LAST_COLUMN;
@ -201,7 +202,7 @@ public class ChangeGroup extends VimChangeGroupBase {
} }
if (visualBlockMode || !append) { if (visualBlockMode || !append) {
InlayHelperKt.moveToInlayAwareLogicalPosition(((IjVimCaret) caret).getCaret(), new LogicalPosition(line, column)); InlayHelperKt.moveToInlayAwareLogicalPosition(((IjVimCaret)caret).getCaret(), new LogicalPosition(line, column));
} }
if (visualBlockMode) { if (visualBlockMode) {
setInsertRepeat(lines, column, append); setInsertRepeat(lines, column, append);
@ -210,7 +211,8 @@ public class ChangeGroup extends VimChangeGroupBase {
if (visualBlockMode || !append) { if (visualBlockMode || !append) {
insertBeforeCursor(editor, context); insertBeforeCursor(editor, context);
} else { }
else {
insertAfterCursor(editor, context); insertAfterCursor(editor, context);
} }
@ -352,7 +354,7 @@ public class ChangeGroup extends VimChangeGroupBase {
final int startOffset = EngineEditorHelperKt.getLineStartForOffset(editor, range.getStartOffset()); final int startOffset = EngineEditorHelperKt.getLineStartForOffset(editor, range.getStartOffset());
final int endOffset = EngineEditorHelperKt.getLineEndForOffset(editor, range.getEndOffset()); final int endOffset = EngineEditorHelperKt.getLineEndForOffset(editor, range.getEndOffset());
Editor ijEditor = ((IjVimEditor) editor).getEditor(); Editor ijEditor = ((IjVimEditor)editor).getEditor();
VisualModeHelperKt.vimSetSystemSelectionSilently(ijEditor.getSelectionModel(), startOffset, endOffset); VisualModeHelperKt.vimSetSystemSelectionSilently(ijEditor.getSelectionModel(), startOffset, endOffset);
Project project = ijEditor.getProject(); Project project = ijEditor.getProject();
@ -367,7 +369,7 @@ public class ChangeGroup extends VimChangeGroupBase {
final int firstLine = editor.offsetToBufferPosition(Math.min(startOffset, endOffset)).getLine(); final int firstLine = editor.offsetToBufferPosition(Math.min(startOffset, endOffset)).getLine();
final int newOffset = injector.getMotion().moveCaretToLineStartSkipLeading(editor, firstLine); final int newOffset = injector.getMotion().moveCaretToLineStartSkipLeading(editor, firstLine);
caret.moveToOffset(newOffset); caret.moveToOffset(newOffset);
restoreCursor(editor, caret, ((IjVimCaret) caret).getCaret().getLogicalPosition().line); restoreCursor(editor, caret, ((IjVimCaret)caret).getCaret().getLogicalPosition().line);
return null; return null;
}; };
if (project != null) { if (project != null) {
@ -440,7 +442,8 @@ public class ChangeGroup extends VimChangeGroupBase {
insertText(editor, caret, spos, indent); insertText(editor, caret, spos, indent);
} }
} }
} else { }
else {
// Left shift blockwise selection // Left shift blockwise selection
CharSequence chars = editor.text(); CharSequence chars = editor.text();
for (int l = sline; l <= eline; l++) { for (int l = sline; l <= eline; l++) {
@ -462,7 +465,8 @@ public class ChangeGroup extends VimChangeGroupBase {
} }
} }
} }
} else { }
else {
// Shift non-blockwise selection // Shift non-blockwise selection
for (int l = sline; l <= eline; l++) { for (int l = sline; l <= eline; l++) {
final int soff = editor.getLineStartOffset(l); final int soff = editor.getLineStartOffset(l);
@ -483,7 +487,8 @@ public class ChangeGroup extends VimChangeGroupBase {
VimCaret newCaret = caret.setVimLastColumnAndGetCaret(intendedColumn); VimCaret newCaret = caret.setVimLastColumnAndGetCaret(intendedColumn);
final int offset = injector.getMotion().moveCaretToLineWithStartOfLineOption(editor, sline, caret); final int offset = injector.getMotion().moveCaretToLineWithStartOfLineOption(editor, sline, caret);
newCaret.moveToOffset(offset); newCaret.moveToOffset(offset);
} else { }
else {
caret.moveToOffset(range.getStartOffset()); caret.moveToOffset(range.getStartOffset());
} }
} }
@ -561,7 +566,7 @@ public class ChangeGroup extends VimChangeGroupBase {
.createHtmlTextBalloonBuilder("Wow, nice vim skills!", VimIcons.IDEAVIM, .createHtmlTextBalloonBuilder("Wow, nice vim skills!", VimIcons.IDEAVIM,
MessageType.INFO.getTitleForeground(), MessageType.INFO.getPopupBackground(), MessageType.INFO.getTitleForeground(), MessageType.INFO.getPopupBackground(),
null).createBalloon(); null).createBalloon();
balloon.show(JBPopupFactory.getInstance().guessBestPopupLocation(((IjVimEditor) editor).getEditor()), balloon.show(JBPopupFactory.getInstance().guessBestPopupLocation(((IjVimEditor)editor).getEditor()),
Balloon.Position.below); Balloon.Position.below);
}); });
} }
@ -612,7 +617,8 @@ public class ChangeGroup extends VimChangeGroupBase {
String newNumber = changeNumberInRange(editor, range, count, alpha, hex, octal); String newNumber = changeNumberInRange(editor, range, count, alpha, hex, octal);
if (newNumber == null) { if (newNumber == null) {
return false; return false;
} else { }
else {
replaceText(editor, caret, range.getFirst().getStartOffset(), range.getFirst().getEndOffset(), newNumber); replaceText(editor, caret, range.getFirst().getStartOffset(), range.getFirst().getEndOffset(), newNumber);
InlayHelperKt.moveToInlayAwareOffset(((IjVimCaret) caret).getCaret(), range.getFirst().getStartOffset() + newNumber.length() - 1); InlayHelperKt.moveToInlayAwareOffset(((IjVimCaret) caret).getCaret(), range.getFirst().getStartOffset() + newNumber.length() - 1);
return true; return true;
@ -634,8 +640,7 @@ public class ChangeGroup extends VimChangeGroupBase {
strokes.add(chars); strokes.add(chars);
} }
private @Nullable private @Nullable String changeNumberInRange(final @NotNull VimEditor editor,
String changeNumberInRange(final @NotNull VimEditor editor,
Pair<TextRange, NumberType> range, Pair<TextRange, NumberType> range,
final int count, final int count,
boolean alpha, boolean alpha,
@ -678,7 +683,8 @@ public class ChangeGroup extends VimChangeGroupBase {
} }
number = text.substring(0, 2) + number; number = text.substring(0, 2) + number;
} else if (octal && NumberType.OCT.equals(numberType) && text.length() > 1) { }
else if (octal && NumberType.OCT.equals(numberType) && text.length() > 1) {
if (!text.startsWith("0")) throw new RuntimeException("Oct number should start with 0: " + text); if (!text.startsWith("0")) throw new RuntimeException("Oct number should start with 0: " + text);
BigInteger num = new BigInteger(text, 8).add(BigInteger.valueOf(count)); BigInteger num = new BigInteger(text, 8).add(BigInteger.valueOf(count));
@ -687,13 +693,15 @@ public class ChangeGroup extends VimChangeGroupBase {
} }
number = num.toString(8); number = num.toString(8);
number = "0" + StringsKt.padStart(number, text.length() - 1, '0'); number = "0" + StringsKt.padStart(number, text.length() - 1, '0');
} else if (alpha && NumberType.ALPHA.equals(numberType)) { }
else if (alpha && NumberType.ALPHA.equals(numberType)) {
if (!Character.isLetter(ch)) throw new RuntimeException("Not alpha number : " + text); if (!Character.isLetter(ch)) throw new RuntimeException("Not alpha number : " + text);
ch += count; ch += count;
if (Character.isLetter(ch)) { if (Character.isLetter(ch)) {
number = String.valueOf(ch); number = String.valueOf(ch);
} }
} else if (NumberType.DEC.equals(numberType)) { }
else if (NumberType.DEC.equals(numberType)) {
if (ch != '-' && !Character.isDigit(ch)) throw new RuntimeException("Not dec number : " + text); if (ch != '-' && !Character.isDigit(ch)) throw new RuntimeException("Not dec number : " + text);
boolean pad = ch == '0'; boolean pad = ch == '0';
int len = text.length(); int len = text.length();
@ -732,7 +740,7 @@ public class ChangeGroup extends VimChangeGroupBase {
@Override @Override
public void notifyListeners(@NotNull VimEditor editor) { public void notifyListeners(@NotNull VimEditor editor) {
insertListeners.forEach(listener -> listener.insertModeStarted(((IjVimEditor) editor).getEditor())); insertListeners.forEach(listener -> listener.insertModeStarted(((IjVimEditor)editor).getEditor()));
} }
@Override @Override
@ -742,5 +750,6 @@ public class ChangeGroup extends VimChangeGroupBase {
} }
private static final Logger logger = Logger.getInstance(ChangeGroup.class.getName()); private static final Logger logger = Logger.getInstance(ChangeGroup.class.getName());
} }

View File

@ -24,7 +24,7 @@ public class DigraphGroup extends VimDigraphGroupBase {
width = 80; width = 80;
} }
int colCount = width / 12; int colCount = width / 12;
int height = (int) Math.ceil((double) getDigraphs().size() / (double) colCount); int height = (int)Math.ceil((double) getDigraphs().size() / (double)colCount);
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("width=" + width); logger.debug("width=" + width);
@ -41,11 +41,13 @@ public class DigraphGroup extends VimDigraphGroupBase {
res.append(' '); res.append(' ');
if (code < 32) { if (code < 32) {
res.append('^'); res.append('^');
res.append((char) (code + '@')); res.append((char)(code + '@'));
} else if (code >= 128 && code <= 159) { }
else if (code >= 128 && code <= 159) {
res.append('~'); res.append('~');
res.append((char) (code - 128 + '@')); res.append((char)(code - 128 + '@'));
} else { }
else {
res.append(code); res.append(code);
res.append(' '); res.append(' ');
} }

View File

@ -49,8 +49,7 @@ import static com.maddyhome.idea.vim.helper.CaretVisualAttributesHelperKt.update
*/ */
@State(name = "VimEditorSettings", storages = {@Storage(value = "$APP_CONFIG$/vim_settings.xml")}) @State(name = "VimEditorSettings", storages = {@Storage(value = "$APP_CONFIG$/vim_settings.xml")})
public class EditorGroup implements PersistentStateComponent<Element>, VimEditorGroup { public class EditorGroup implements PersistentStateComponent<Element>, VimEditorGroup {
public static final @NonNls public static final @NonNls String EDITOR_STORE_ELEMENT = "editor";
String EDITOR_STORE_ELEMENT = "editor";
private Boolean isKeyRepeat = null; private Boolean isKeyRepeat = null;
@ -126,7 +125,8 @@ public class EditorGroup implements PersistentStateComponent<Element>, VimEditor
if (!hasRelativeLineNumbersInstalled(editor)) { if (!hasRelativeLineNumbersInstalled(editor)) {
installRelativeLineNumbers(editor); installRelativeLineNumbers(editor);
} }
} else if (hasRelativeLineNumbersInstalled(editor)) { }
else if (hasRelativeLineNumbersInstalled(editor)) {
removeRelativeLineNumbers(editor); removeRelativeLineNumbers(editor);
} }
} }
@ -192,8 +192,7 @@ public class EditorGroup implements PersistentStateComponent<Element>, VimEditor
} }
} }
public @Nullable public @Nullable Boolean isKeyRepeat() {
Boolean isKeyRepeat() {
return isKeyRepeat; return isKeyRepeat;
} }
@ -277,7 +276,7 @@ public class EditorGroup implements PersistentStateComponent<Element>, VimEditor
@Override @Override
public void processLocalValueChange(@Nullable VimDataType oldValue, @NotNull VimEditor editor) { public void processLocalValueChange(@Nullable VimDataType oldValue, @NotNull VimEditor editor) {
Editor ijEditor = ((IjVimEditor) editor).getEditor(); Editor ijEditor = ((IjVimEditor)editor).getEditor();
if (UserDataManager.getVimEditorGroup(ijEditor) && supportsVimLineNumbers(ijEditor)) { if (UserDataManager.getVimEditorGroup(ijEditor) && supportsVimLineNumbers(ijEditor)) {
updateLineNumbers(ijEditor); updateLineNumbers(ijEditor);
@ -294,7 +293,8 @@ public class EditorGroup implements PersistentStateComponent<Element>, VimEditor
// lineNumber is 1 based // lineNumber is 1 based
if (number && (lineNumber - 1) == caretLine) { if (number && (lineNumber - 1) == caretLine) {
return lineNumber; return lineNumber;
} else { }
else {
final int visualLine = new IjVimEditor(editor).bufferLineToVisualLine(lineNumber - 1); final int visualLine = new IjVimEditor(editor).bufferLineToVisualLine(lineNumber - 1);
final int currentVisualLine = new IjVimEditor(editor).bufferLineToVisualLine(caretLine); final int currentVisualLine = new IjVimEditor(editor).bufferLineToVisualLine(caretLine);
return Math.abs(currentVisualLine - visualLine); return Math.abs(currentVisualLine - visualLine);

View File

@ -72,20 +72,21 @@ public class FileGroup extends VimFileBase {
fem.openFile(found, true); fem.openFile(found, true);
return true; return true;
} else { }
else {
// There was no type and user didn't pick one. Don't open the file // There was no type and user didn't pick one. Don't open the file
// Return true here because we found the file but the user canceled by not picking a type. // Return true here because we found the file but the user canceled by not picking a type.
return true; return true;
} }
} else { }
else {
VimPlugin.showMessage(MessageHelper.message("unable.to.find.0", filename)); VimPlugin.showMessage(MessageHelper.message("unable.to.find.0", filename));
return false; return false;
} }
} }
@Nullable @Nullable VirtualFile findFile(@NotNull String filename, @NotNull Project project) {
VirtualFile findFile(@NotNull String filename, @NotNull Project project) {
VirtualFile found; VirtualFile found;
if (filename.length() > 2 && filename.charAt(0) == '~' && filename.charAt(1) == File.separatorChar) { if (filename.length() > 2 && filename.charAt(0) == '~' && filename.charAt(1) == File.separatorChar) {
String homefile = filename.substring(2); String homefile = filename.substring(2);
@ -95,7 +96,8 @@ public class FileGroup extends VimFileBase {
logger.debug("looking for " + homefile + " in " + dir); logger.debug("looking for " + homefile + " in " + dir);
} }
found = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(dir, homefile)); found = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(dir, homefile));
} else { }
else {
found = LocalFileSystem.getInstance().findFileByIoFile(new File(filename)); found = LocalFileSystem.getInstance().findFileByIoFile(new File(filename));
if (found == null) { if (found == null) {
@ -141,11 +143,11 @@ public class FileGroup extends VimFileBase {
*/ */
@Override @Override
public void closeFile(@NotNull VimEditor editor, @NotNull ExecutionContext context) { public void closeFile(@NotNull VimEditor editor, @NotNull ExecutionContext context) {
final Project project = PlatformDataKeys.PROJECT.getData(((DataContext) context.getContext())); final Project project = PlatformDataKeys.PROJECT.getData(((DataContext)context.getContext()));
if (project != null) { if (project != null) {
final FileEditorManagerEx fileEditorManager = FileEditorManagerEx.getInstanceEx(project); final FileEditorManagerEx fileEditorManager = FileEditorManagerEx.getInstanceEx(project);
final EditorWindow window = fileEditorManager.getCurrentWindow(); final EditorWindow window = fileEditorManager.getCurrentWindow();
final VirtualFile virtualFile = EditorHelper.getVirtualFile(((IjVimEditor) editor).getEditor()); final VirtualFile virtualFile = EditorHelper.getVirtualFile(((IjVimEditor)editor).getEditor());
if (virtualFile != null && window != null) { if (virtualFile != null && window != null) {
window.closeFile(virtualFile); window.closeFile(virtualFile);
@ -171,8 +173,7 @@ public class FileGroup extends VimFileBase {
if (number >= 0 && number < editors.length) { if (number >= 0 && number < editors.length) {
fileEditorManager.closeFile(editors[number], window); fileEditorManager.closeFile(editors[number], window);
} }
} } if (!ApplicationManager.getApplication().isUnitTestMode()) {
if (!ApplicationManager.getApplication().isUnitTestMode()) {
// This thing doesn't have an implementation in test mode // This thing doesn't have an implementation in test mode
EditorsSplitters.focusDefaultComponentInSplittersIfPresent(project); EditorsSplitters.focusDefaultComponentInSplittersIfPresent(project);
} }
@ -186,7 +187,8 @@ public class FileGroup extends VimFileBase {
NativeAction action; NativeAction action;
if (globalOptions(injector).hasValue(IjOptionConstants.ideawrite, IjOptionConstants.ideawrite_all)) { if (globalOptions(injector).hasValue(IjOptionConstants.ideawrite, IjOptionConstants.ideawrite_all)) {
action = injector.getNativeActionManager().getSaveAll(); action = injector.getNativeActionManager().getSaveAll();
} else { }
else {
action = injector.getNativeActionManager().getSaveCurrent(); action = injector.getNativeActionManager().getSaveCurrent();
} }
ExecuteExtensionKt.execute(action, context); ExecuteExtensionKt.execute(action, context);
@ -243,12 +245,13 @@ public class FileGroup extends VimFileBase {
*/ */
@Override @Override
public void selectPreviousTab(@NotNull ExecutionContext context) { public void selectPreviousTab(@NotNull ExecutionContext context) {
Project project = PlatformDataKeys.PROJECT.getData(((DataContext) context.getContext())); Project project = PlatformDataKeys.PROJECT.getData(((DataContext)context.getContext()));
if (project == null) return; if (project == null) return;
VirtualFile vf = LastTabService.getInstance(project).getLastTab(); VirtualFile vf = LastTabService.getInstance(project).getLastTab();
if (vf != null && vf.isValid()) { if (vf != null && vf.isValid()) {
FileEditorManager.getInstance(project).openFile(vf, true); FileEditorManager.getInstance(project).openFile(vf, true);
} else { }
else {
VimPlugin.indicateError(); VimPlugin.indicateError();
} }
} }
@ -256,8 +259,7 @@ public class FileGroup extends VimFileBase {
/** /**
* Returns the previous tab. * Returns the previous tab.
*/ */
public @Nullable public @Nullable VirtualFile getPreviousTab(@NotNull DataContext context) {
VirtualFile getPreviousTab(@NotNull DataContext context) {
Project project = PlatformDataKeys.PROJECT.getData(context); Project project = PlatformDataKeys.PROJECT.getData(context);
if (project == null) return null; if (project == null) return null;
VirtualFile vf = LastTabService.getInstance(project).getLastTab(); VirtualFile vf = LastTabService.getInstance(project).getLastTab();
@ -267,13 +269,12 @@ public class FileGroup extends VimFileBase {
return null; return null;
} }
@Nullable @Nullable Editor selectEditor(Project project, @NotNull VirtualFile file) {
Editor selectEditor(Project project, @NotNull VirtualFile file) {
FileEditorManager fMgr = FileEditorManager.getInstance(project); FileEditorManager fMgr = FileEditorManager.getInstance(project);
FileEditor[] feditors = fMgr.openFile(file, true); FileEditor[] feditors = fMgr.openFile(file, true);
if (feditors.length > 0) { if (feditors.length > 0) {
if (feditors[0] instanceof TextEditor) { if (feditors[0] instanceof TextEditor) {
Editor editor = ((TextEditor) feditors[0]).getEditor(); Editor editor = ((TextEditor)feditors[0]).getEditor();
if (!editor.isDisposed()) { if (!editor.isDisposed()) {
return editor; return editor;
} }
@ -285,7 +286,7 @@ public class FileGroup extends VimFileBase {
@Override @Override
public void displayLocationInfo(@NotNull VimEditor vimEditor) { public void displayLocationInfo(@NotNull VimEditor vimEditor) {
Editor editor = ((IjVimEditor) vimEditor).getEditor(); Editor editor = ((IjVimEditor)vimEditor).getEditor();
StringBuilder msg = new StringBuilder(); StringBuilder msg = new StringBuilder();
Document doc = editor.getDocument(); Document doc = editor.getDocument();
@ -322,7 +323,8 @@ public class FileGroup extends VimFileBase {
int size = EditorHelperRt.getFileSize(editor); int size = EditorHelperRt.getFileSize(editor);
msg.append("; Character ").append(offset + 1).append(" of ").append(size); msg.append("; Character ").append(offset + 1).append(" of ").append(size);
} else { }
else {
msg.append("Selected "); msg.append("Selected ");
TextRange vr = new TextRange(editor.getSelectionModel().getBlockSelectionStarts(), TextRange vr = new TextRange(editor.getSelectionModel().getBlockSelectionStarts(),
@ -343,7 +345,8 @@ public class FileGroup extends VimFileBase {
cp = SearchHelper.countWords(editor, vr.getStartOffsets()[i], vr.getEndOffsets()[i] - 1); cp = SearchHelper.countWords(editor, vr.getStartOffsets()[i], vr.getEndOffsets()[i] - 1);
word += cp.getCount(); word += cp.getCount();
} }
} else { }
else {
LogicalPosition slp = editor.offsetToLogicalPosition(vr.getStartOffset()); LogicalPosition slp = editor.offsetToLogicalPosition(vr.getStartOffset());
LogicalPosition elp = editor.offsetToLogicalPosition(vr.getEndOffset()); LogicalPosition elp = editor.offsetToLogicalPosition(vr.getEndOffset());
@ -370,39 +373,43 @@ public class FileGroup extends VimFileBase {
@Override @Override
public void displayFileInfo(@NotNull VimEditor vimEditor, boolean fullPath) { public void displayFileInfo(@NotNull VimEditor vimEditor, boolean fullPath) {
Editor editor = ((IjVimEditor) vimEditor).getEditor(); Editor editor = ((IjVimEditor)vimEditor).getEditor();
StringBuilder msg = new StringBuilder(); StringBuilder msg = new StringBuilder();
VirtualFile vf = EditorHelper.getVirtualFile(editor); VirtualFile vf = EditorHelper.getVirtualFile(editor);
if (vf != null) { if (vf != null) {
msg.append('"'); msg.append('"');
if (fullPath) { if (fullPath) {
msg.append(vf.getPath()); msg.append(vf.getPath());
} else { }
else {
Project project = editor.getProject(); Project project = editor.getProject();
if (project != null) { if (project != null) {
VirtualFile root = ProjectRootManager.getInstance(project).getFileIndex().getContentRootForFile(vf); VirtualFile root = ProjectRootManager.getInstance(project).getFileIndex().getContentRootForFile(vf);
if (root != null) { if (root != null) {
msg.append(vf.getPath().substring(root.getPath().length() + 1)); msg.append(vf.getPath().substring(root.getPath().length() + 1));
} else { }
else {
msg.append(vf.getPath()); msg.append(vf.getPath());
} }
} }
} }
msg.append("\" "); msg.append("\" ");
} else { }
else {
msg.append("\"[No File]\" "); msg.append("\"[No File]\" ");
} }
Document doc = editor.getDocument(); Document doc = editor.getDocument();
if (!doc.isWritable()) { if (!doc.isWritable()) {
msg.append("[RO] "); msg.append("[RO] ");
} else if (FileDocumentManager.getInstance().isDocumentUnsaved(doc)) { }
else if (FileDocumentManager.getInstance().isDocumentUnsaved(doc)) {
msg.append("[+] "); msg.append("[+] ");
} }
int lline = editor.getCaretModel().getLogicalPosition().line; int lline = editor.getCaretModel().getLogicalPosition().line;
int total = new IjVimEditor(editor).lineCount(); int total = new IjVimEditor(editor).lineCount();
int pct = (int) ((float) lline / (float) total * 100f + 0.5); int pct = (int)((float)lline / (float)total * 100f + 0.5);
msg.append("line ").append(lline + 1).append(" of ").append(total); msg.append("line ").append(lline + 1).append(" of ").append(total);
msg.append(" --").append(pct).append("%-- "); msg.append(" --").append(pct).append("%-- ");
@ -418,8 +425,7 @@ public class FileGroup extends VimFileBase {
VimPlugin.showMessage(msg.toString()); VimPlugin.showMessage(msg.toString());
} }
private static final @NotNull private static final @NotNull Logger logger = Logger.getInstance(FileGroup.class.getName());
Logger logger = Logger.getInstance(FileGroup.class.getName());
/** /**
* This method listens for editor tab changes so any insert/replace modes that need to be reset can be. * This method listens for editor tab changes so any insert/replace modes that need to be reset can be.

View File

@ -55,13 +55,10 @@ import static java.util.stream.Collectors.toList;
* @author vlan * @author vlan
*/ */
@State(name = "VimKeySettings", storages = {@Storage(value = "$APP_CONFIG$/vim_settings.xml")}) @State(name = "VimKeySettings", storages = {@Storage(value = "$APP_CONFIG$/vim_settings.xml")})
public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponent<Element> { public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponent<Element>{
public static final @NonNls public static final @NonNls String SHORTCUT_CONFLICTS_ELEMENT = "shortcut-conflicts";
String SHORTCUT_CONFLICTS_ELEMENT = "shortcut-conflicts"; private static final @NonNls String SHORTCUT_CONFLICT_ELEMENT = "shortcut-conflict";
private static final @NonNls private static final @NonNls String OWNER_ATTRIBUTE = "owner";
String SHORTCUT_CONFLICT_ELEMENT = "shortcut-conflict";
private static final @NonNls
String OWNER_ATTRIBUTE = "owner";
private static final String TEXT_ELEMENT = "text"; private static final String TEXT_ELEMENT = "text";
private static final Logger logger = Logger.getInstance(KeyGroup.class); private static final Logger logger = Logger.getInstance(KeyGroup.class);
@ -69,7 +66,7 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
public void registerRequiredShortcutKeys(@NotNull VimEditor editor) { public void registerRequiredShortcutKeys(@NotNull VimEditor editor) {
EventFacade.getInstance() EventFacade.getInstance()
.registerCustomShortcutSet(VimShortcutKeyAction.getInstance(), toShortcutSet(getRequiredShortcutKeys()), .registerCustomShortcutSet(VimShortcutKeyAction.getInstance(), toShortcutSet(getRequiredShortcutKeys()),
((IjVimEditor) editor).getEditor().getComponent()); ((IjVimEditor)editor).getEditor().getComponent());
} }
public void registerShortcutsForLookup(@NotNull LookupImpl lookup) { public void registerShortcutsForLookup(@NotNull LookupImpl lookup) {
@ -80,7 +77,7 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
void unregisterShortcutKeys(@NotNull VimEditor editor) { void unregisterShortcutKeys(@NotNull VimEditor editor) {
EventFacade.getInstance().unregisterCustomShortcutSet(VimShortcutKeyAction.getInstance(), EventFacade.getInstance().unregisterCustomShortcutSet(VimShortcutKeyAction.getInstance(),
((IjVimEditor) editor).getEditor().getComponent()); ((IjVimEditor)editor).getEditor().getComponent());
} }
public boolean showKeyMappings(@NotNull Set<? extends MappingMode> modes, @NotNull Editor editor) { public boolean showKeyMappings(@NotNull Set<? extends MappingMode> modes, @NotNull Editor editor) {
@ -116,10 +113,12 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
final ShortcutOwner owner; final ShortcutOwner owner;
ShortcutOwnerInfo myValue = entry.getValue(); ShortcutOwnerInfo myValue = entry.getValue();
if (myValue instanceof ShortcutOwnerInfo.AllModes) { if (myValue instanceof ShortcutOwnerInfo.AllModes) {
owner = ((ShortcutOwnerInfo.AllModes) myValue).getOwner(); owner = ((ShortcutOwnerInfo.AllModes)myValue).getOwner();
} else if (myValue instanceof ShortcutOwnerInfo.PerMode) { }
else if (myValue instanceof ShortcutOwnerInfo.PerMode) {
owner = null; owner = null;
} else { }
else {
throw new RuntimeException(); throw new RuntimeException();
} }
if (owner != null && owner != ShortcutOwner.UNDEFINED) { if (owner != null && owner != ShortcutOwner.UNDEFINED) {
@ -143,7 +142,8 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
ShortcutOwner owner = ShortcutOwner.UNDEFINED; ShortcutOwner owner = ShortcutOwner.UNDEFINED;
try { try {
owner = ShortcutOwner.fromString(ownerValue); owner = ShortcutOwner.fromString(ownerValue);
} catch (IllegalArgumentException ignored) { }
catch (IllegalArgumentException ignored) {
} }
final Element textElement = conflictElement.getChild(TEXT_ELEMENT); final Element textElement = conflictElement.getChild(TEXT_ELEMENT);
if (textElement != null) { if (textElement != null) {
@ -160,8 +160,7 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
} }
@Override @Override
public @NotNull public @NotNull List<NativeAction> getKeymapConflicts(@NotNull KeyStroke keyStroke) {
List<NativeAction> getKeymapConflicts(@NotNull KeyStroke keyStroke) {
final KeymapManagerEx keymapManager = KeymapManagerEx.getInstanceEx(); final KeymapManagerEx keymapManager = KeymapManagerEx.getInstanceEx();
final Keymap keymap = keymapManager.getActiveKeymap(); final Keymap keymap = keymapManager.getActiveKeymap();
final KeyboardShortcut shortcut = new KeyboardShortcut(keyStroke, null); final KeyboardShortcut shortcut = new KeyboardShortcut(keyStroke, null);
@ -176,8 +175,7 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
return actions.stream().map(IjNativeAction::new).collect(toList()); return actions.stream().map(IjNativeAction::new).collect(toList());
} }
public @NotNull public @NotNull Map<KeyStroke, ShortcutOwnerInfo> getShortcutConflicts() {
Map<KeyStroke, ShortcutOwnerInfo> getShortcutConflicts() {
final Set<RequiredShortcut> requiredShortcutKeys = this.getRequiredShortcutKeys(); final Set<RequiredShortcut> requiredShortcutKeys = this.getRequiredShortcutKeys();
final Map<KeyStroke, ShortcutOwnerInfo> savedConflicts = getSavedShortcutConflicts(); final Map<KeyStroke, ShortcutOwnerInfo> savedConflicts = getSavedShortcutConflicts();
final Map<KeyStroke, ShortcutOwnerInfo> results = new HashMap<>(); final Map<KeyStroke, ShortcutOwnerInfo> results = new HashMap<>();
@ -212,7 +210,7 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
} }
public void registerCommandAction(@NotNull VimActionsInitiator actionHolder) { public void registerCommandAction(@NotNull VimActionsInitiator actionHolder) {
IjVimActionsInitiator holder = (IjVimActionsInitiator) actionHolder; IjVimActionsInitiator holder = (IjVimActionsInitiator)actionHolder;
if (!VimPlugin.getPluginId().equals(holder.getBean().getPluginDescriptor().getPluginId())) { if (!VimPlugin.getPluginId().equals(holder.getBean().getPluginDescriptor().getPluginId())) {
logger.error("IdeaVim doesn't accept contributions to `vimActions` extension points. " + logger.error("IdeaVim doesn't accept contributions to `vimActions` extension points. " +
@ -226,8 +224,9 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
if (actionKeys == null) { if (actionKeys == null) {
final EditorActionHandlerBase action = actionHolder.getInstance(); final EditorActionHandlerBase action = actionHolder.getInstance();
if (action instanceof ComplicatedKeysAction) { if (action instanceof ComplicatedKeysAction) {
actionKeys = ((ComplicatedKeysAction) action).getKeyStrokesSet(); actionKeys = ((ComplicatedKeysAction)action).getKeyStrokesSet();
} else { }
else {
throw new RuntimeException("Cannot register action: " + action.getClass().getName()); throw new RuntimeException("Cannot register action: " + action.getClass().getName());
} }
} }
@ -262,8 +261,7 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
} }
} }
public static @NotNull public static @NotNull ShortcutSet toShortcutSet(@NotNull Collection<RequiredShortcut> requiredShortcuts) {
ShortcutSet toShortcutSet(@NotNull Collection<RequiredShortcut> requiredShortcuts) {
final List<Shortcut> shortcuts = new ArrayList<>(); final List<Shortcut> shortcuts = new ArrayList<>();
for (RequiredShortcut key : requiredShortcuts) { for (RequiredShortcut key : requiredShortcuts) {
shortcuts.add(new KeyboardShortcut(key.getKeyStroke(), null)); shortcuts.add(new KeyboardShortcut(key.getKeyStroke(), null));
@ -271,8 +269,7 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
return new CustomShortcutSet(shortcuts.toArray(new Shortcut[0])); return new CustomShortcutSet(shortcuts.toArray(new Shortcut[0]));
} }
private static @NotNull private static @NotNull List<Pair<EnumSet<MappingMode>, MappingInfo>> getKeyMappingRows(@NotNull Set<? extends MappingMode> modes) {
List<Pair<EnumSet<MappingMode>, MappingInfo>> getKeyMappingRows(@NotNull Set<? extends MappingMode> modes) {
final Map<ImmutableList<KeyStroke>, EnumSet<MappingMode>> actualModes = new HashMap<>(); final Map<ImmutableList<KeyStroke>, EnumSet<MappingMode>> actualModes = new HashMap<>();
for (MappingMode mode : modes) { for (MappingMode mode : modes) {
final KeyMapping mapping = VimPlugin.getKey().getKeyMapping(mode); final KeyMapping mapping = VimPlugin.getKey().getKeyMapping(mode);
@ -283,7 +280,8 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
if (value != null) { if (value != null) {
newValue = value.clone(); newValue = value.clone();
newValue.add(mode); newValue.add(mode);
} else { }
else {
newValue = EnumSet.of(mode); newValue = EnumSet.of(mode);
} }
actualModes.put(key, newValue); actualModes.put(key, newValue);
@ -306,22 +304,21 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
return rows; return rows;
} }
private static @NotNull private static @NotNull @NonNls String getModesStringCode(@NotNull Set<MappingMode> modes) {
@NonNls
String getModesStringCode(@NotNull Set<MappingMode> modes) {
if (modes.equals(MappingMode.NVO)) { if (modes.equals(MappingMode.NVO)) {
return ""; return "";
} else if (modes.contains(MappingMode.INSERT)) { }
else if (modes.contains(MappingMode.INSERT)) {
return "i"; return "i";
} else if (modes.contains(MappingMode.NORMAL)) { }
else if (modes.contains(MappingMode.NORMAL)) {
return "n"; return "n";
} }
// TODO: Add more codes // TODO: Add more codes
return ""; return "";
} }
private @NotNull private @NotNull List<AnAction> getActions(@NotNull Component component, @NotNull KeyStroke keyStroke) {
List<AnAction> getActions(@NotNull Component component, @NotNull KeyStroke keyStroke) {
final List<AnAction> results = new ArrayList<>(); final List<AnAction> results = new ArrayList<>();
results.addAll(getLocalActions(component, keyStroke)); results.addAll(getLocalActions(component, keyStroke));
results.addAll(getKeymapActions(keyStroke)); results.addAll(getKeymapActions(keyStroke));
@ -329,19 +326,17 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
} }
@Override @Override
public @NotNull public @NotNull List<NativeAction> getActions(@NotNull VimEditor editor, @NotNull KeyStroke keyStroke) {
List<NativeAction> getActions(@NotNull VimEditor editor, @NotNull KeyStroke keyStroke) { return getActions(((IjVimEditor)editor).getEditor().getComponent(), keyStroke).stream()
return getActions(((IjVimEditor) editor).getEditor().getComponent(), keyStroke).stream()
.map(IjNativeAction::new).collect(toList()); .map(IjNativeAction::new).collect(toList());
} }
private static @NotNull private static @NotNull List<AnAction> getLocalActions(@NotNull Component component, @NotNull KeyStroke keyStroke) {
List<AnAction> getLocalActions(@NotNull Component component, @NotNull KeyStroke keyStroke) {
final List<AnAction> results = new ArrayList<>(); final List<AnAction> results = new ArrayList<>();
final KeyboardShortcut keyStrokeShortcut = new KeyboardShortcut(keyStroke, null); final KeyboardShortcut keyStrokeShortcut = new KeyboardShortcut(keyStroke, null);
for (Component c = component; c != null; c = c.getParent()) { for (Component c = component; c != null; c = c.getParent()) {
if (c instanceof JComponent) { if (c instanceof JComponent) {
final List<AnAction> actions = ActionUtil.getActions((JComponent) c); final List<AnAction> actions = ActionUtil.getActions((JComponent)c);
for (AnAction action : actions) { for (AnAction action : actions) {
if (action instanceof VimShortcutKeyAction) { if (action instanceof VimShortcutKeyAction) {
continue; continue;
@ -358,8 +353,7 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
return results; return results;
} }
private static @NotNull private static @NotNull List<AnAction> getKeymapActions(@NotNull KeyStroke keyStroke) {
List<AnAction> getKeymapActions(@NotNull KeyStroke keyStroke) {
final List<AnAction> results = new ArrayList<>(); final List<AnAction> results = new ArrayList<>();
final Keymap keymap = KeymapManager.getInstance().getActiveKeymap(); final Keymap keymap = KeymapManager.getInstance().getActiveKeymap();
for (String id : keymap.getActionIds(keyStroke)) { for (String id : keymap.getActionIds(keyStroke)) {

View File

@ -59,7 +59,7 @@ public class MarkGroup {
@Nullable @Nullable
public Mark createSystemMark(char ch, int line, int col, @NotNull VimEditor editor) { public Mark createSystemMark(char ch, int line, int col, @NotNull VimEditor editor) {
Editor ijEditor = ((IjVimEditor) editor).getEditor(); Editor ijEditor = ((IjVimEditor)editor).getEditor();
@Nullable LineBookmark systemMark = SystemMarks.createOrGetSystemMark(ch, line, ijEditor); @Nullable LineBookmark systemMark = SystemMarks.createOrGetSystemMark(ch, line, ijEditor);
if (systemMark == null) { if (systemMark == null) {
return null; return null;

View File

@ -387,8 +387,7 @@ internal class MotionGroup : VimMotionGroupBase() {
} else if (cmd.action is TextObjectActionHandler) { } else if (cmd.action is TextObjectActionHandler) {
val action = cmd.action as TextObjectActionHandler val action = cmd.action as TextObjectActionHandler
val range = val range =
action.getRange(editor.vim, caret.vim, IjEditorExecutionContext(context!!), cnt, raw, cmd.argument) action.getRange(editor.vim, caret.vim, IjEditorExecutionContext(context!!), cnt, raw, cmd.argument) ?: return null
?: return null
start = range.startOffset start = range.startOffset
end = range.endOffset end = range.endOffset
if (cmd.isLinewiseMotion()) end-- if (cmd.isLinewiseMotion()) end--

View File

@ -57,7 +57,7 @@ public class ProcessGroup extends VimProcessGroupBase {
@Override @Override
public void startSearchCommand(@NotNull VimEditor editor, ExecutionContext context, int count, char leader) { public void startSearchCommand(@NotNull VimEditor editor, ExecutionContext context, int count, char leader) {
if (((IjVimEditor) editor).getEditor().isOneLineMode()) // Don't allow searching in one line editors if (((IjVimEditor)editor).getEditor().isOneLineMode()) // Don't allow searching in one line editors
{ {
return; return;
} }
@ -66,12 +66,11 @@ public class ProcessGroup extends VimProcessGroupBase {
String label = String.valueOf(leader); String label = String.valueOf(leader);
ExEntryPanel panel = ExEntryPanel.getInstance(); ExEntryPanel panel = ExEntryPanel.getInstance();
panel.activate(((IjVimEditor) editor).getEditor(), ((DataContext) context.getContext()), label, initText, count); panel.activate(((IjVimEditor)editor).getEditor(), ((DataContext)context.getContext()), label, initText, count);
} }
@Override @Override
public @NotNull public @NotNull String endSearchCommand() {
String endSearchCommand() {
ExEntryPanel panel = ExEntryPanel.getInstance(); ExEntryPanel panel = ExEntryPanel.getInstance();
panel.deactivate(true); panel.deactivate(true);
@ -99,7 +98,8 @@ public class ProcessGroup extends VimProcessGroupBase {
panel.handleKey(stroke); panel.handleKey(stroke);
return true; return true;
} else { }
else {
VimStateMachine.getInstance(editor).popModes(); VimStateMachine.getInstance(editor).popModes();
KeyHandler.getInstance().reset(editor); KeyHandler.getInstance().reset(editor);
return false; return false;
@ -127,11 +127,13 @@ public class ProcessGroup extends VimProcessGroupBase {
if (logger.isDebugEnabled()) logger.debug("swing=" + SwingUtilities.isEventDispatchThread()); if (logger.isDebugEnabled()) logger.debug("swing=" + SwingUtilities.isEventDispatchThread());
VimInjectorKt.getInjector().getVimscriptExecutor().execute(text, editor, context, skipHistory(editor), true, CommandLineVimLContext.INSTANCE); VimInjectorKt.getInjector().getVimscriptExecutor().execute(text, editor, context, skipHistory(editor), true, CommandLineVimLContext.INSTANCE);
} catch (ExException e) { }
catch (ExException e) {
VimPlugin.showMessage(e.getMessage()); VimPlugin.showMessage(e.getMessage());
VimPlugin.indicateError(); VimPlugin.indicateError();
res = false; res = false;
} catch (Exception bad) { }
catch (Exception bad) {
ProcessGroup.logger.error(bad); ProcessGroup.logger.error(bad);
VimPlugin.indicateError(); VimPlugin.indicateError();
res = false; res = false;
@ -160,15 +162,16 @@ public class ProcessGroup extends VimProcessGroupBase {
panel.activate(((IjVimEditor) editor).getEditor(), ((IjEditorExecutionContext) context).getContext(), ":", initText, 1); panel.activate(((IjVimEditor) editor).getEditor(), ((IjEditorExecutionContext) context).getContext(), ":", initText, 1);
} }
private @NotNull private @NotNull String getRange(Editor editor, @NotNull Command cmd) {
String getRange(Editor editor, @NotNull Command cmd) {
String initText = ""; String initText = "";
if (VimStateMachine.getInstance(new IjVimEditor(editor)).getMode() == VimStateMachine.Mode.VISUAL) { if (VimStateMachine.getInstance(new IjVimEditor(editor)).getMode() == VimStateMachine.Mode.VISUAL) {
initText = "'<,'>"; initText = "'<,'>";
} else if (cmd.getRawCount() > 0) { }
else if (cmd.getRawCount() > 0) {
if (cmd.getCount() == 1) { if (cmd.getCount() == 1) {
initText = "."; initText = ".";
} else { }
else {
initText = ".,.+" + (cmd.getCount() - 1); initText = ".,.+" + (cmd.getCount() - 1);
} }
} }
@ -176,8 +179,7 @@ public class ProcessGroup extends VimProcessGroupBase {
return initText; return initText;
} }
public @Nullable public @Nullable String executeCommand(@NotNull VimEditor editor, @NotNull String command, @Nullable CharSequence input, @Nullable String currentDirectoryPath)
String executeCommand(@NotNull VimEditor editor, @NotNull String command, @Nullable CharSequence input, @Nullable String currentDirectoryPath)
throws ExecutionException, ProcessCanceledException { throws ExecutionException, ProcessCanceledException {
// This is a much simplified version of how Vim does this. We're using stdin/stdout directly, while Vim will // This is a much simplified version of how Vim does this. We're using stdin/stdout directly, while Vim will
@ -229,7 +231,8 @@ public class ProcessGroup extends VimProcessGroupBase {
final BufferedWriter outputStreamWriter = new BufferedWriter(new OutputStreamWriter(handler.getProcessInput())); final BufferedWriter outputStreamWriter = new BufferedWriter(new OutputStreamWriter(handler.getProcessInput()));
copy(charSequenceReader, outputStreamWriter); copy(charSequenceReader, outputStreamWriter);
outputStreamWriter.close(); outputStreamWriter.close();
} catch (IOException e) { }
catch (IOException e) {
logger.error(e); logger.error(e);
} }
} }

View File

@ -57,7 +57,8 @@ public class RegisterGroup extends VimRegisterGroupBase implements PersistentSta
final Element textElement = new Element("text"); final Element textElement = new Element("text");
VimPlugin.getXML().setSafeXmlText(textElement, text); VimPlugin.getXML().setSafeXmlText(textElement, text);
registerElement.addContent(textElement); registerElement.addContent(textElement);
} else { }
else {
logger.trace("Save register as 'keys'"); logger.trace("Save register as 'keys'");
final Element keys = new Element("keys"); final Element keys = new Element("keys");
final List<KeyStroke> list = register.getKeys(); final List<KeyStroke> list = register.getKeys();
@ -101,11 +102,13 @@ public class RegisterGroup extends VimRegisterGroupBase implements PersistentSta
if (text != null) { if (text != null) {
logger.trace("Register data parsed"); logger.trace("Register data parsed");
register = new Register(key, type, text, Collections.emptyList()); register = new Register(key, type, text, Collections.emptyList());
} else { }
else {
logger.trace("Cannot parse register data"); logger.trace("Cannot parse register data");
register = null; register = null;
} }
} else { }
else {
logger.trace("Register has 'keys' element"); logger.trace("Register has 'keys' element");
final Element keysElement = registerElement.getChild("keys"); final Element keysElement = registerElement.getChild("keys");
final List<Element> keyElements = keysElement.getChildren("key"); final List<Element> keyElements = keysElement.getChildren("key");
@ -113,7 +116,7 @@ public class RegisterGroup extends VimRegisterGroupBase implements PersistentSta
for (Element keyElement : keyElements) { for (Element keyElement : keyElements) {
final int code = Integer.parseInt(keyElement.getAttributeValue("code")); final int code = Integer.parseInt(keyElement.getAttributeValue("code"));
final int modifiers = Integer.parseInt(keyElement.getAttributeValue("mods")); final int modifiers = Integer.parseInt(keyElement.getAttributeValue("mods"));
final char c = (char) Integer.parseInt(keyElement.getAttributeValue("char")); final char c = (char)Integer.parseInt(keyElement.getAttributeValue("char"));
//noinspection MagicConstant //noinspection MagicConstant
strokes.add(c == KeyEvent.CHAR_UNDEFINED ? strokes.add(c == KeyEvent.CHAR_UNDEFINED ?
KeyStroke.getKeyStroke(code, modifiers) : KeyStroke.getKeyStroke(code, modifiers) :

View File

@ -110,18 +110,15 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
* *
* @return The pattern used for last search. Can be null * @return The pattern used for last search. Can be null
*/ */
public @Nullable public @Nullable String getLastSearchPattern() {
String getLastSearchPattern() {
return lastSearch; return lastSearch;
} }
/** /**
* Get the last pattern used in substitution. * Get the last pattern used in substitution.
*
* @return The pattern used for the last substitute command. Can be null * @return The pattern used for the last substitute command. Can be null
*/ */
public @Nullable public @Nullable String getLastSubstitutePattern() {
String getLastSubstitutePattern() {
return lastSubstitute; return lastSubstitute;
} }
@ -130,13 +127,10 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
* *
* @return The pattern last used for either searching or substitution. Can be null * @return The pattern last used for either searching or substitution. Can be null
*/ */
public @Nullable public @Nullable String getLastUsedPattern() {
String getLastUsedPattern() {
switch (lastPatternIdx) { switch (lastPatternIdx) {
case RE_SEARCH: case RE_SEARCH: return lastSearch;
return lastSearch; case RE_SUBST: return lastSubstitute;
case RE_SUBST:
return lastSubstitute;
} }
return null; return null;
} }
@ -213,17 +207,17 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
/** /**
* Find all occurrences of the pattern * Find all occurrences of the pattern
* *
* @deprecated Use SearchHelper#findAll instead. Kept for compatibility with existing plugins
*
* @param editor The editor to search in * @param editor The editor to search in
* @param pattern The pattern to search for * @param pattern The pattern to search for
* @param startLine The start line of the range to search for * @param startLine The start line of the range to search for
* @param endLine The end line of the range to search for, or -1 for the whole document * @param endLine The end line of the range to search for, or -1 for the whole document
* @param ignoreCase Case sensitive or insensitive searching * @param ignoreCase Case sensitive or insensitive searching
* @return A list of TextRange objects representing the results * @return A list of TextRange objects representing the results
* @deprecated Use SearchHelper#findAll instead. Kept for compatibility with existing plugins
*/ */
@Deprecated() @Deprecated()
public static @NotNull public static @NotNull List<TextRange> findAll(@NotNull Editor editor,
List<TextRange> findAll(@NotNull Editor editor,
@NotNull String pattern, @NotNull String pattern,
int startLine, int startLine,
int endLine, int endLine,
@ -281,13 +275,16 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
end.inc(); end.inc();
patternOffset = end.toString(); patternOffset = end.toString();
if (logger.isDebugEnabled()) logger.debug("Pattern contains offset " + patternOffset); if (logger.isDebugEnabled()) logger.debug("Pattern contains offset " + patternOffset);
} else { }
else {
logger.debug("no offset"); logger.debug("no offset");
patternOffset = ""; patternOffset = "";
} }
} else if (command.length() == 1) { }
else if (command.length() == 1) {
patternOffset = ""; patternOffset = "";
} else { }
else {
patternOffset = command.substring(1); patternOffset = command.substring(1);
if (logger.isDebugEnabled()) logger.debug("offset=" + patternOffset); if (logger.isDebugEnabled()) logger.debug("offset=" + patternOffset);
} }
@ -340,7 +337,7 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
resetShowSearchHighlight(); resetShowSearchHighlight();
forceUpdateSearchHighlights(); forceUpdateSearchHighlights();
return findItOffset(((IjVimEditor) editor).getEditor(), startOffset, 1, lastDir); return findItOffset(((IjVimEditor)editor).getEditor(), startOffset, 1, lastDir);
} }
/** /**
@ -413,13 +410,13 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
*/ */
@Override @Override
public int searchWord(@NotNull VimEditor editor, @NotNull ImmutableVimCaret caret, int count, boolean whole, @NotNull Direction dir) { public int searchWord(@NotNull VimEditor editor, @NotNull ImmutableVimCaret caret, int count, boolean whole, @NotNull Direction dir) {
TextRange range = SearchHelper.findWordUnderCursor(((IjVimEditor) editor).getEditor(), ((IjVimCaret) caret).getCaret()); TextRange range = SearchHelper.findWordUnderCursor(((IjVimEditor)editor).getEditor(), ((IjVimCaret)caret).getCaret());
if (range == null) { if (range == null) {
logger.warn("No range was found"); logger.warn("No range was found");
return -1; return -1;
} }
@NotNull final Editor editor1 = ((IjVimEditor) editor).getEditor(); @NotNull final Editor editor1 = ((IjVimEditor)editor).getEditor();
final int start = range.getStartOffset(); final int start = range.getStartOffset();
final int end = range.getEndOffset(); final int end = range.getEndOffset();
final String pattern = SearchHelper.makeSearchPattern( final String pattern = SearchHelper.makeSearchPattern(
@ -437,7 +434,7 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
resetShowSearchHighlight(); resetShowSearchHighlight();
forceUpdateSearchHighlights(); forceUpdateSearchHighlights();
final int offset = findItOffset(((IjVimEditor) editor).getEditor(), range.getStartOffset(), count, lastDir); final int offset = findItOffset(((IjVimEditor)editor).getEditor(), range.getStartOffset(), count, lastDir);
return offset == -1 ? range.getStartOffset() : offset; return offset == -1 ? range.getStartOffset() : offset;
} }
@ -454,7 +451,7 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
*/ */
@Override @Override
public int searchNext(@NotNull VimEditor editor, @NotNull ImmutableVimCaret caret, int count) { public int searchNext(@NotNull VimEditor editor, @NotNull ImmutableVimCaret caret, int count) {
return searchNextWithDirection(((IjVimEditor) editor).getEditor(), ((IjVimCaret) caret).getCaret(), count, lastDir); return searchNextWithDirection(((IjVimEditor)editor).getEditor(), ((IjVimCaret)caret).getCaret(), count, lastDir);
} }
/** /**
@ -470,7 +467,7 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
*/ */
@Override @Override
public int searchPrevious(@NotNull VimEditor editor, @NotNull ImmutableVimCaret caret, int count) { public int searchPrevious(@NotNull VimEditor editor, @NotNull ImmutableVimCaret caret, int count) {
return searchNextWithDirection(((IjVimEditor) editor).getEditor(), ((IjVimCaret) caret).getCaret(), count, return searchNextWithDirection(((IjVimEditor)editor).getEditor(), ((IjVimCaret)caret).getCaret(), count,
lastDir.reverse()); lastDir.reverse());
} }
@ -534,7 +531,8 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
int which_pat; int which_pat;
if ("~".equals(excmd)) { if ("~".equals(excmd)) {
which_pat = RE_LAST; /* use last used regexp */ which_pat = RE_LAST; /* use last used regexp */
} else { }
else {
which_pat = RE_SUBST; /* use last substitute regexp */ which_pat = RE_SUBST; /* use last substitute regexp */
} }
@ -566,7 +564,8 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
pat = new CharPointer(""); /* empty search pattern */ pat = new CharPointer(""); /* empty search pattern */
delimiter = cmd.charAt(); /* remember delimiter character */ delimiter = cmd.charAt(); /* remember delimiter character */
cmd.inc(); cmd.inc();
} else { }
else {
/* find the end of the regexp */ /* find the end of the regexp */
which_pat = RE_LAST; /* use last used regexp */ which_pat = RE_LAST; /* use last used regexp */
delimiter = cmd.charAt(); /* remember delimiter character */ delimiter = cmd.charAt(); /* remember delimiter character */
@ -594,7 +593,8 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
} }
cmd.inc(); cmd.inc();
} }
} else { }
else {
/* use previous pattern and substitution */ /* use previous pattern and substitution */
if (lastReplace == null) { if (lastReplace == null) {
/* there is no previous command */ /* there is no previous command */
@ -610,7 +610,8 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
*/ */
if (cmd.charAt() == '&') { if (cmd.charAt() == '&') {
cmd.inc(); cmd.inc();
} else { }
else {
// :h :&& - "Note that :s and :& don't keep the flags" // :h :&& - "Note that :s and :& don't keep the flags"
do_all = options(injector, editor).isSet(OptionConstants.gdefault); do_all = options(injector, editor).isSet(OptionConstants.gdefault);
do_ask = false; do_ask = false;
@ -624,20 +625,26 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
*/ */
if (cmd.charAt() == 'g') { if (cmd.charAt() == 'g') {
do_all = !do_all; do_all = !do_all;
} else if (cmd.charAt() == 'c') { }
else if (cmd.charAt() == 'c') {
do_ask = !do_ask; do_ask = !do_ask;
} else if (cmd.charAt() == 'e') { }
else if (cmd.charAt() == 'e') {
do_error = !do_error; do_error = !do_error;
} else if (cmd.charAt() == 'r') { }
else if (cmd.charAt() == 'r') {
/* use last used regexp */ /* use last used regexp */
which_pat = RE_LAST; which_pat = RE_LAST;
} else if (cmd.charAt() == 'i') { }
else if (cmd.charAt() == 'i') {
/* ignore case */ /* ignore case */
do_ic = 'i'; do_ic = 'i';
} else if (cmd.charAt() == 'I') { }
else if (cmd.charAt() == 'I') {
/* don't ignore case */ /* don't ignore case */
do_ic = 'I'; do_ic = 'I';
} else if (cmd.charAt() != 'p' && cmd.charAt() != 'l' && cmd.charAt() != '#' && cmd.charAt() != 'n') { }
else if (cmd.charAt() != 'p' && cmd.charAt() != 'l' && cmd.charAt() != '#' && cmd.charAt() != 'n') {
// TODO: Support printing last changed line, with options for line number/list format // TODO: Support printing last changed line, with options for line number/list format
// TODO: Support 'n' to report number of matches without substituting // TODO: Support 'n' to report number of matches without substituting
break; break;
@ -692,7 +699,8 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
/* the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' */ /* the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' */
if (do_ic == 'i') { if (do_ic == 'i') {
regmatch.rmm_ic = true; regmatch.rmm_ic = true;
} else if (do_ic == 'I') { }
else if (do_ic == 'I') {
regmatch.rmm_ic = false; regmatch.rmm_ic = false;
} }
@ -822,14 +830,17 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
if (newpos != null) { if (newpos != null) {
lnum = newpos.line; lnum = newpos.line;
searchcol = newpos.column; searchcol = newpos.column;
} else { }
else {
searchcol = endpos.column; searchcol = endpos.column;
} }
} else { }
else {
searchcol = 0; searchcol = 0;
lnum++; lnum++;
} }
} else { }
else {
lnum++; lnum++;
searchcol = 0; searchcol = 0;
} }
@ -839,7 +850,8 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
if (lastMatch != -1) { if (lastMatch != -1) {
caret.moveToOffset( caret.moveToOffset(
VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, editor.offsetToBufferPosition(lastMatch).getLine())); VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, editor.offsetToBufferPosition(lastMatch).getLine()));
} else { }
else {
VimPlugin.showMessage(MessageHelper.message(Msg.e_patnotf2, pattern)); VimPlugin.showMessage(MessageHelper.message(Msg.e_patnotf2, pattern));
} }
} }
@ -910,7 +922,8 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
VimPlugin.showMessage(errorMessage); VimPlugin.showMessage(errorMessage);
return new Pair<>(false, null); return new Pair<>(false, null);
} }
} else { }
else {
pattern = pat.toString(); pattern = pat.toString();
} }
@ -932,8 +945,7 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
return new Pair<>(true, new Triple<>(regmatch, pattern, sp)); return new Pair<>(true, new Triple<>(regmatch, pattern, sp));
} }
private static @NotNull private static @NotNull ReplaceConfirmationChoice confirmChoice(@NotNull Editor editor, @NotNull String match, @NotNull Caret caret, int startoff) {
ReplaceConfirmationChoice confirmChoice(@NotNull Editor editor, @NotNull String match, @NotNull Caret caret, int startoff) {
final Ref<ReplaceConfirmationChoice> result = Ref.create(ReplaceConfirmationChoice.QUIT); final Ref<ReplaceConfirmationChoice> result = Ref.create(ReplaceConfirmationChoice.QUIT);
final Function1<KeyStroke, Boolean> keyStrokeProcessor = key -> { final Function1<KeyStroke, Boolean> keyStrokeProcessor = key -> {
final ReplaceConfirmationChoice choice; final ReplaceConfirmationChoice choice;
@ -963,11 +975,12 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
break; break;
} }
} }
} else { }
else {
// XXX: The Ex entry panel is used only for UI here, its logic might be inappropriate for this method // XXX: The Ex entry panel is used only for UI here, its logic might be inappropriate for this method
final ExEntryPanel exEntryPanel = ExEntryPanel.getInstanceWithoutShortcuts(); final ExEntryPanel exEntryPanel = ExEntryPanel.getInstanceWithoutShortcuts();
ExecutionContext.Editor context = injector.getExecutionContextManager().onEditor(new IjVimEditor(editor), null); ExecutionContext.Editor context = injector.getExecutionContextManager().onEditor(new IjVimEditor(editor), null);
exEntryPanel.activate(editor, ((IjEditorExecutionContext) context).getContext(), MessageHelper.message("replace.with.0", match), "", 1); exEntryPanel.activate(editor, ((IjEditorExecutionContext)context).getContext(), MessageHelper.message("replace.with.0", match), "", 1);
new IjVimCaret(caret).moveToOffset(startoff); new IjVimCaret(caret).moveToOffset(startoff);
ModalEntry.INSTANCE.activate(new IjVimEditor(editor), keyStrokeProcessor); ModalEntry.INSTANCE.activate(new IjVimEditor(editor), keyStrokeProcessor);
exEntryPanel.deactivate(true, false); exEntryPanel.deactivate(true, false);
@ -997,14 +1010,14 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
* @return The TextRange of the next occurrence or null if not found * @return The TextRange of the next occurrence or null if not found
*/ */
@Override @Override
public @Nullable public @Nullable TextRange getNextSearchRange(@NotNull VimEditor editor, int count, boolean forwards) {
TextRange getNextSearchRange(@NotNull VimEditor editor, int count, boolean forwards) {
editor.removeSecondaryCarets(); editor.removeSecondaryCarets();
TextRange current = findUnderCaret(editor); TextRange current = findUnderCaret(editor);
if (current == null || CommandStateHelper.inVisualMode(((IjVimEditor) editor).getEditor()) && atEdgeOfGnRange(current, ((IjVimEditor) editor).getEditor(), forwards)) { if (current == null || CommandStateHelper.inVisualMode(((IjVimEditor)editor).getEditor()) && atEdgeOfGnRange(current, ((IjVimEditor)editor).getEditor(), forwards)) {
current = findNextSearchForGn(editor, count, forwards); current = findNextSearchForGn(editor, count, forwards);
} else if (count > 1) { }
else if (count > 1) {
current = findNextSearchForGn(editor, count - 1, forwards); current = findNextSearchForGn(editor, count - 1, forwards);
} }
return current; return current;
@ -1014,13 +1027,13 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
int currentPosition = editor.getCaretModel().getOffset(); int currentPosition = editor.getCaretModel().getOffset();
if (forwards) { if (forwards) {
return nextRange.getEndOffset() - VimPlugin.getVisualMotion().getSelectionAdj() == currentPosition; return nextRange.getEndOffset() - VimPlugin.getVisualMotion().getSelectionAdj() == currentPosition;
} else { }
else {
return nextRange.getStartOffset() == currentPosition; return nextRange.getStartOffset() == currentPosition;
} }
} }
private @Nullable private @Nullable TextRange findNextSearchForGn(@NotNull VimEditor editor, int count, boolean forwards) {
TextRange findNextSearchForGn(@NotNull VimEditor editor, int count, boolean forwards) {
if (forwards) { if (forwards) {
final EnumSet<SearchOptions> searchOptions = EnumSet.of(SearchOptions.WRAP, SearchOptions.WHOLE_FILE); final EnumSet<SearchOptions> searchOptions = EnumSet.of(SearchOptions.WRAP, SearchOptions.WHOLE_FILE);
return VimInjectorKt.getInjector().getSearchHelper().findPattern(editor, getLastUsedPattern(), editor.primaryCaret().getOffset().getPoint(), count, searchOptions); return VimInjectorKt.getInjector().getSearchHelper().findPattern(editor, getLastUsedPattern(), editor.primaryCaret().getOffset().getPoint(), count, searchOptions);
@ -1045,7 +1058,7 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
final TextRange foundBackward = VimInjectorKt.getInjector().getSearchHelper().findPattern(editor, getLastUsedPattern(), offset, count, searchOptions); final TextRange foundBackward = VimInjectorKt.getInjector().getSearchHelper().findPattern(editor, getLastUsedPattern(), offset, count, searchOptions);
if (foundBackward == null) return null; if (foundBackward == null) return null;
int startOffset = foundBackward.getStartOffset() - 1; int startOffset = foundBackward.getStartOffset() - 1;
if (startOffset < 0) startOffset = (int) editor.fileSize(); if (startOffset < 0) startOffset = (int)editor.fileSize();
searchOptions.remove(SearchOptions.BACKWARDS); searchOptions.remove(SearchOptions.BACKWARDS);
return VimInjectorKt.getInjector().getSearchHelper().findPattern(editor, getLastUsedPattern(), startOffset, 1, searchOptions); return VimInjectorKt.getInjector().getSearchHelper().findPattern(editor, getLastUsedPattern(), startOffset, 1, searchOptions);
} }
@ -1125,7 +1138,7 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
public static DocumentSearchListener INSTANCE = new DocumentSearchListener(); public static DocumentSearchListener INSTANCE = new DocumentSearchListener();
@Contract(pure = true) @Contract(pure = true)
private DocumentSearchListener() { private DocumentSearchListener () {
} }
@Override @Override
@ -1271,7 +1284,8 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
// TODO: Don't move the caret! // TODO: Don't move the caret!
res = VimPlugin.getMotion().moveCaretToLineStart(new IjVimEditor(editor), newLine); res = VimPlugin.getMotion().moveCaretToLineStart(new IjVimEditor(editor), newLine);
} else if (hasEndOffset || offset != 0) { }
else if (hasEndOffset || offset != 0) {
int base = hasEndOffset ? range.getEndOffset() - 1 : range.getStartOffset(); int base = hasEndOffset ? range.getEndOffset() - 1 : range.getStartOffset();
res = Math.max(0, Math.min(base + offset, EditorHelperRt.getFileSize(editor) - 1)); res = Math.max(0, Math.min(base + offset, EditorHelperRt.getFileSize(editor) - 1));
} }
@ -1281,9 +1295,11 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
final Direction nextDir; final Direction nextDir;
if (lastPatternOffset.charAt(ppos + 1) == '/') { if (lastPatternOffset.charAt(ppos + 1) == '/') {
nextDir = Direction.FORWARDS; nextDir = Direction.FORWARDS;
} else if (lastPatternOffset.charAt(ppos + 1) == '?') { }
else if (lastPatternOffset.charAt(ppos + 1) == '?') {
nextDir = Direction.BACKWARDS; nextDir = Direction.BACKWARDS;
} else { }
else {
return res; return res;
} }
@ -1339,14 +1355,16 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
final String lastPatternText = getSafeChildText(search, "last-pattern"); final String lastPatternText = getSafeChildText(search, "last-pattern");
if (lastPatternText == null || lastPatternText.equals(lastSearch)) { if (lastPatternText == null || lastPatternText.equals(lastSearch)) {
lastPatternIdx = RE_SEARCH; lastPatternIdx = RE_SEARCH;
} else { }
else {
lastPatternIdx = RE_SUBST; lastPatternIdx = RE_SUBST;
} }
Element dir = search.getChild("last-dir"); Element dir = search.getChild("last-dir");
try { try {
lastDir = Direction.Companion.fromInt(Integer.parseInt(dir.getText())); lastDir = Direction.Companion.fromInt(Integer.parseInt(dir.getText()));
} catch (NumberFormatException e) { }
catch (NumberFormatException e) {
lastDir = Direction.FORWARDS; lastDir = Direction.FORWARDS;
} }
@ -1359,15 +1377,13 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
} }
} }
private static @Nullable private static @Nullable String getSafeChildText(@NotNull Element element, @NotNull String name) {
String getSafeChildText(@NotNull Element element, @NotNull String name) {
final Element child = element.getChild(name); final Element child = element.getChild(name);
return child != null ? VimPlugin.getXML().getSafeXmlText(child) : null; return child != null ? VimPlugin.getXML().getSafeXmlText(child) : null;
} }
@SuppressWarnings("SameParameterValue") @SuppressWarnings("SameParameterValue")
private static @NotNull private static @NotNull String getSafeChildText(@NotNull Element element, @NotNull String name, @NotNull String defaultValue) {
String getSafeChildText(@NotNull Element element, @NotNull String name, @NotNull String defaultValue) {
final Element child = element.getChild(name); final Element child = element.getChild(name);
if (child != null) { if (child != null) {
final String value = VimPlugin.getXML().getSafeXmlText(child); final String value = VimPlugin.getXML().getSafeXmlText(child);
@ -1405,18 +1421,13 @@ public class SearchGroup extends VimSearchGroupBase implements PersistentStateCo
// The trailing tilde tracks which was the last used pattern, but line/end/off is only used for search, not substitution // The trailing tilde tracks which was the last used pattern, but line/end/off is only used for search, not substitution
// Search values can contain new lines, etc. Vim saves these as CTRL chars, e.g. ^M // Search values can contain new lines, etc. Vim saves these as CTRL chars, e.g. ^M
// Before saving, Vim reads existing viminfo, merges and writes // Before saving, Vim reads existing viminfo, merges and writes
private @Nullable private @Nullable String lastSearch; // Pattern used for last search command (`/`)
String lastSearch; // Pattern used for last search command (`/`) private @Nullable String lastSubstitute; // Pattern used for last substitute command (`:s`)
private @Nullable
String lastSubstitute; // Pattern used for last substitute command (`:s`)
private int lastPatternIdx; // Which pattern was used last? RE_SEARCH or RE_SUBST? private int lastPatternIdx; // Which pattern was used last? RE_SEARCH or RE_SUBST?
private @Nullable private @Nullable String lastReplace; // `# Last Substitute String` from viminfo
String lastReplace; // `# Last Substitute String` from viminfo private @NotNull String lastPatternOffset = ""; // /{pattern}/{offset}. Do not confuse with caret offset!
private @NotNull
String lastPatternOffset = ""; // /{pattern}/{offset}. Do not confuse with caret offset!
private boolean lastIgnoreSmartCase; private boolean lastIgnoreSmartCase;
private @NotNull private @NotNull Direction lastDir = Direction.FORWARDS;
Direction lastDir = Direction.FORWARDS;
private boolean showSearchHighlight = globalOptions(injector).isSet(OptionConstants.hlsearch); private boolean showSearchHighlight = globalOptions(injector).isSet(OptionConstants.hlsearch);
private boolean do_all = false; /* do multiple substitutions per line */ private boolean do_all = false; /* do multiple substitutions per line */

View File

@ -31,7 +31,6 @@ internal class VimJumpServiceImpl : VimJumpServiceBase(), PersistentStateCompone
companion object { companion object {
private val logger = vimLogger<VimJumpServiceImpl>() private val logger = vimLogger<VimJumpServiceImpl>()
} }
override var lastJumpTimeStamp: Long = 0 override var lastJumpTimeStamp: Long = 0
override fun includeCurrentCommandAsNavigation(editor: VimEditor) { override fun includeCurrentCommandAsNavigation(editor: VimEditor) {

View File

@ -37,7 +37,7 @@ import java.util.*;
public class WindowGroup extends WindowGroupBase { public class WindowGroup extends WindowGroupBase {
@Override @Override
public void closeCurrentWindow(@NotNull ExecutionContext context) { public void closeCurrentWindow(@NotNull ExecutionContext context) {
final FileEditorManagerEx fileEditorManager = getFileEditorManager((DataContext) context.getContext()); final FileEditorManagerEx fileEditorManager = getFileEditorManager((DataContext)context.getContext());
final EditorWindow window = fileEditorManager.getSplitters().getCurrentWindow(); final EditorWindow window = fileEditorManager.getSplitters().getCurrentWindow();
if (window != null) { if (window != null) {
window.closeAllExcept(null); window.closeAllExcept(null);
@ -46,7 +46,7 @@ public class WindowGroup extends WindowGroupBase {
@Override @Override
public void closeAllExceptCurrent(@NotNull ExecutionContext context) { public void closeAllExceptCurrent(@NotNull ExecutionContext context) {
final FileEditorManagerEx fileEditorManager = getFileEditorManager(((DataContext) context.getContext())); final FileEditorManagerEx fileEditorManager = getFileEditorManager(((DataContext)context.getContext()));
final EditorWindow current = fileEditorManager.getCurrentWindow(); final EditorWindow current = fileEditorManager.getCurrentWindow();
for (final EditorWindow window : fileEditorManager.getWindows()) { for (final EditorWindow window : fileEditorManager.getWindows()) {
if (window != current) { if (window != current) {
@ -61,7 +61,7 @@ public class WindowGroup extends WindowGroupBase {
@Override @Override
public void selectNextWindow(@NotNull ExecutionContext context) { public void selectNextWindow(@NotNull ExecutionContext context) {
final FileEditorManagerEx fileEditorManager = getFileEditorManager(((DataContext) context.getContext())); final FileEditorManagerEx fileEditorManager = getFileEditorManager(((DataContext)context.getContext()));
final EditorWindow current = fileEditorManager.getCurrentWindow(); final EditorWindow current = fileEditorManager.getCurrentWindow();
if (current != null) { if (current != null) {
EditorWindow nextWindow = fileEditorManager.getNextWindow(current); EditorWindow nextWindow = fileEditorManager.getNextWindow(current);
@ -73,7 +73,7 @@ public class WindowGroup extends WindowGroupBase {
@Override @Override
public void selectPreviousWindow(@NotNull ExecutionContext context) { public void selectPreviousWindow(@NotNull ExecutionContext context) {
final FileEditorManagerEx fileEditorManager = getFileEditorManager(((DataContext) context.getContext())); final FileEditorManagerEx fileEditorManager = getFileEditorManager(((DataContext)context.getContext()));
final EditorWindow current = fileEditorManager.getCurrentWindow(); final EditorWindow current = fileEditorManager.getCurrentWindow();
if (current != null) { if (current != null) {
EditorWindow prevWindow = fileEditorManager.getPrevWindow(current); EditorWindow prevWindow = fileEditorManager.getPrevWindow(current);
@ -85,7 +85,7 @@ public class WindowGroup extends WindowGroupBase {
@Override @Override
public void selectWindow(@NotNull ExecutionContext context, int index) { public void selectWindow(@NotNull ExecutionContext context, int index) {
final FileEditorManagerEx fileEditorManager = getFileEditorManager(((DataContext) context.getContext())); final FileEditorManagerEx fileEditorManager = getFileEditorManager(((DataContext)context.getContext()));
final EditorWindow[] windows = fileEditorManager.getWindows(); final EditorWindow[] windows = fileEditorManager.getWindows();
if (index - 1 < windows.length) { if (index - 1 < windows.length) {
windows[index - 1].setAsCurrentWindow(true); windows[index - 1].setAsCurrentWindow(true);
@ -94,12 +94,12 @@ public class WindowGroup extends WindowGroupBase {
@Override @Override
public void splitWindowHorizontal(@NotNull ExecutionContext context, @NotNull String filename) { public void splitWindowHorizontal(@NotNull ExecutionContext context, @NotNull String filename) {
splitWindow(SwingConstants.HORIZONTAL, (DataContext) context.getContext(), filename); splitWindow(SwingConstants.HORIZONTAL, (DataContext)context.getContext(), filename);
} }
@Override @Override
public void splitWindowVertical(@NotNull ExecutionContext context, @NotNull String filename) { public void splitWindowVertical(@NotNull ExecutionContext context, @NotNull String filename) {
splitWindow(SwingConstants.VERTICAL, (DataContext) context.getContext(), filename); splitWindow(SwingConstants.VERTICAL, (DataContext)context.getContext(), filename);
} }
@Override @Override
@ -107,7 +107,7 @@ public class WindowGroup extends WindowGroupBase {
@RequiresReadLock @RequiresReadLock
public void selectWindowInRow(@NotNull VimCaret caret, @NotNull ExecutionContext context, int relativePosition, boolean vertical) { public void selectWindowInRow(@NotNull VimCaret caret, @NotNull ExecutionContext context, int relativePosition, boolean vertical) {
final Caret ijCaret = ((IjVimCaret) caret).getCaret(); final Caret ijCaret = ((IjVimCaret) caret).getCaret();
final FileEditorManagerEx fileEditorManager = getFileEditorManager(((DataContext) context.getContext())); final FileEditorManagerEx fileEditorManager = getFileEditorManager(((DataContext)context.getContext()));
final EditorWindow currentWindow = fileEditorManager.getCurrentWindow(); final EditorWindow currentWindow = fileEditorManager.getCurrentWindow();
if (currentWindow != null) { if (currentWindow != null) {
final EditorWindow[] windows = fileEditorManager.getWindows(); final EditorWindow[] windows = fileEditorManager.getWindows();
@ -124,8 +124,7 @@ public class WindowGroup extends WindowGroupBase {
windows.get(normalized).setAsCurrentWindow(true); windows.get(normalized).setAsCurrentWindow(true);
} }
private static @NotNull private static @NotNull List<EditorWindow> findWindowsInRow(@NotNull Caret caret,
List<EditorWindow> findWindowsInRow(@NotNull Caret caret,
@NotNull EditorWindow editorWindow, @NotNull EditorWindow editorWindow,
@NotNull List<EditorWindow> windows, final boolean vertical) { @NotNull List<EditorWindow> windows, final boolean vertical) {
final Point anchorPoint = getCaretPoint(caret); final Point anchorPoint = getCaretPoint(caret);
@ -156,8 +155,7 @@ public class WindowGroup extends WindowGroupBase {
return Collections.singletonList(editorWindow); return Collections.singletonList(editorWindow);
} }
private static @NotNull private static @NotNull FileEditorManagerEx getFileEditorManager(@NotNull DataContext context) {
FileEditorManagerEx getFileEditorManager(@NotNull DataContext context) {
final Project project = PlatformDataKeys.PROJECT.getData(context); final Project project = PlatformDataKeys.PROJECT.getData(context);
return FileEditorManagerEx.getInstanceEx(Objects.requireNonNull(project)); return FileEditorManagerEx.getInstanceEx(Objects.requireNonNull(project));
} }
@ -182,8 +180,7 @@ public class WindowGroup extends WindowGroupBase {
} }
} }
private static @NotNull private static @NotNull Point getCaretPoint(@NotNull Caret caret) {
Point getCaretPoint(@NotNull Caret caret) {
final Editor editor = caret.getEditor(); final Editor editor = caret.getEditor();
final Point caretLocation = editor.logicalPositionToXY(caret.getLogicalPosition()); final Point caretLocation = editor.logicalPositionToXY(caret.getLogicalPosition());
Point caretScreenLocation = editor.getContentComponent().getLocationOnScreen(); Point caretScreenLocation = editor.getContentComponent().getLocationOnScreen();
@ -191,8 +188,7 @@ public class WindowGroup extends WindowGroupBase {
return caretScreenLocation; return caretScreenLocation;
} }
private static @Nullable private static @Nullable Rectangle getSplitRectangle(@NotNull EditorWindow window) {
Rectangle getSplitRectangle(@NotNull EditorWindow window) {
final EditorComposite editorComposite = window.getSelectedComposite(); final EditorComposite editorComposite = window.getSelectedComposite();
if (editorComposite != null) { if (editorComposite != null) {
final EditorTabbedContainer split = window.getTabbedPane(); final EditorTabbedContainer split = window.getTabbedPane();

View File

@ -42,8 +42,7 @@ public class EditorHelper {
// Code Vision) // Code Vision)
private static final int BLOCK_INLAY_MAX_LINE_HEIGHT = 3; private static final int BLOCK_INLAY_MAX_LINE_HEIGHT = 3;
public static @NotNull public static @NotNull Rectangle getVisibleArea(final @NotNull Editor editor) {
Rectangle getVisibleArea(final @NotNull Editor editor) {
return editor.getScrollingModel().getVisibleAreaOnScrollingFinished(); return editor.getScrollingModel().getVisibleAreaOnScrollingFinished();
} }
@ -156,7 +155,7 @@ public class EditorHelper {
* @return The number of screen columns * @return The number of screen columns
*/ */
public static int getApproximateScreenWidth(final @NotNull Editor editor) { public static int getApproximateScreenWidth(final @NotNull Editor editor) {
return (int) (getVisibleArea(editor).width / getPlainSpaceWidthFloat(editor)); return (int)(getVisibleArea(editor).width / getPlainSpaceWidthFloat(editor));
} }
/** /**
@ -204,8 +203,7 @@ public class EditorHelper {
* @param file The virtual file get the editor for * @param file The virtual file get the editor for
* @return The matching editor or null if no match was found * @return The matching editor or null if no match was found
*/ */
public static @Nullable public static @Nullable Editor getEditor(final @Nullable VirtualFile file) {
Editor getEditor(final @Nullable VirtualFile file) {
if (file == null) { if (file == null) {
return null; return null;
} }
@ -222,8 +220,7 @@ public class EditorHelper {
return null; return null;
} }
public static @NotNull public static @NotNull String pad(final @NotNull Editor editor,
String pad(final @NotNull Editor editor,
@NotNull DataContext context, @NotNull DataContext context,
int line, int line,
final int to) { final int to) {
@ -239,8 +236,7 @@ public class EditorHelper {
* *
* @param editor The editor from which the carets are taken * @param editor The editor from which the carets are taken
*/ */
public static @NotNull public static @NotNull List<Caret> getOrderedCaretsList(@NotNull Editor editor) {
List<Caret> getOrderedCaretsList(@NotNull Editor editor) {
@NotNull List<Caret> carets = editor.getCaretModel().getAllCarets(); @NotNull List<Caret> carets = editor.getCaretModel().getAllCarets();
carets.sort(Comparator.comparingInt(Caret::getOffset)); carets.sort(Comparator.comparingInt(Caret::getOffset));
@ -279,7 +275,8 @@ public class EditorHelper {
int inlayOffset = 0; int inlayOffset = 0;
if (topInlayHeight > caretScreenOffset) { if (topInlayHeight > caretScreenOffset) {
inlayOffset = topInlayHeight; inlayOffset = topInlayHeight;
} else if (bottomInlayHeight > visibleArea.height - caretScreenOffset + editor.getLineHeight()) { }
else if (bottomInlayHeight > visibleArea.height - caretScreenOffset + editor.getLineHeight()) {
inlayOffset = -bottomInlayHeight; inlayOffset = -bottomInlayHeight;
} }
@ -346,7 +343,8 @@ public class EditorHelper {
// screen // screen
if (!allowVirtualSpace && offset > offsetForLastLineAtBottom) { if (!allowVirtualSpace && offset > offsetForLastLineAtBottom) {
scrollVertically(editor, offsetForLastLineAtBottom); scrollVertically(editor, offsetForLastLineAtBottom);
} else { }
else {
scrollVertically(editor, offset); scrollVertically(editor, offset);
} }
} }
@ -397,7 +395,8 @@ public class EditorHelper {
Inlay<?> inlay = editor.getInlayModel().getInlineElementAt(new VisualPosition(visualLine, visualColumn)); Inlay<?> inlay = editor.getInlayModel().getInlineElementAt(new VisualPosition(visualLine, visualColumn));
if (inlay != null && inlay.isRelatedToPrecedingText()) { if (inlay != null && inlay.isRelatedToPrecedingText()) {
targetVisualColumn = visualColumn + 1; targetVisualColumn = visualColumn + 1;
} else if (visualColumn > 0) { }
else if (visualColumn > 0) {
inlay = editor.getInlayModel().getInlineElementAt(new VisualPosition(visualLine, visualColumn - 1)); inlay = editor.getInlayModel().getInlineElementAt(new VisualPosition(visualLine, visualColumn - 1));
if (inlay != null && !inlay.isRelatedToPrecedingText()) { if (inlay != null && !inlay.isRelatedToPrecedingText()) {
targetVisualColumn = visualColumn - 1; targetVisualColumn = visualColumn - 1;
@ -431,7 +430,8 @@ public class EditorHelper {
Inlay<?> inlay = editor.getInlayModel().getInlineElementAt(new VisualPosition(visualLine, visualColumn)); Inlay<?> inlay = editor.getInlayModel().getInlineElementAt(new VisualPosition(visualLine, visualColumn));
if (inlay != null && !inlay.isRelatedToPrecedingText()) { if (inlay != null && !inlay.isRelatedToPrecedingText()) {
targetVisualColumn = visualColumn - 1; targetVisualColumn = visualColumn - 1;
} else { }
else {
// If the target column is followed by an inlay which is associated with it, make the inlay the target column so // If the target column is followed by an inlay which is associated with it, make the inlay the target column so
// it is visible // it is visible
inlay = editor.getInlayModel().getInlineElementAt(new VisualPosition(visualLine, visualColumn + 1)); inlay = editor.getInlayModel().getInlineElementAt(new VisualPosition(visualLine, visualColumn + 1));
@ -471,7 +471,8 @@ public class EditorHelper {
// If we're on the last page, end nicely on the last line, otherwise move the caret to the last line of the file // If we're on the last page, end nicely on the last line, otherwise move the caret to the last line of the file
if (i == pages - 1) { if (i == pages - 1) {
caretVisualLine = lastVisualLine; caretVisualLine = lastVisualLine;
} else { }
else {
@NotNull final VimEditor editor1 = new IjVimEditor(editor); @NotNull final VimEditor editor1 = new IjVimEditor(editor);
caretVisualLine = EngineEditorHelperKt.getVisualLineCount(editor1) - 1; caretVisualLine = EngineEditorHelperKt.getVisualLineCount(editor1) - 1;
completed = false; completed = false;
@ -523,7 +524,8 @@ public class EditorHelper {
if (targetBottomVisualLine == 1) { if (targetBottomVisualLine == 1) {
completed = i == pages - 1; completed = i == pages - 1;
break; break;
} else if (targetBottomVisualLine == lastVisualLine) { }
else if (targetBottomVisualLine == lastVisualLine) {
// Vim normally scrolls up window height minus two. When there are only one or two lines in the screen, due to // Vim normally scrolls up window height minus two. When there are only one or two lines in the screen, due to
// end of file and virtual space, it scrolls window height minus one, or just plain windows height. IntelliJ // end of file and virtual space, it scrolls window height minus one, or just plain windows height. IntelliJ
// doesn't allow us only one line when virtual space is enabled, so we only need to handle the two line case. // doesn't allow us only one line when virtual space is enabled, so we only need to handle the two line case.
@ -549,7 +551,8 @@ public class EditorHelper {
int yActual = editor.visualLineToY(line); int yActual = editor.visualLineToY(line);
if (yActual < topBound) { if (yActual < topBound) {
line++; line++;
} else if (yActual + editor.getLineHeight() > bottomBound) { }
else if (yActual + editor.getLineHeight() > bottomBound) {
line--; line--;
} }
return line; return line;
@ -580,7 +583,8 @@ public class EditorHelper {
} }
return getPreviousNonInlayVisualPosition(editor, closestVisualPosition).column; return getPreviousNonInlayVisualPosition(editor, closestVisualPosition).column;
} else { }
else {
return getNextNonInlayVisualPosition(editor, closestVisualPosition).column; return getNextNonInlayVisualPosition(editor, closestVisualPosition).column;
} }
} }
@ -613,8 +617,7 @@ public class EditorHelper {
* @param editor The editor * @param editor The editor
* @return The virtual file for the editor * @return The virtual file for the editor
*/ */
public static @Nullable public static @Nullable VirtualFile getVirtualFile(@NotNull Editor editor) {
VirtualFile getVirtualFile(@NotNull Editor editor) {
return FileDocumentManager.getInstance().getFile(editor.getDocument()); return FileDocumentManager.getInstance().getFile(editor.getDocument());
} }

View File

@ -21,41 +21,34 @@ import java.io.InputStreamReader;
* @author vlan * @author vlan
*/ */
public class MacKeyRepeat { public class MacKeyRepeat {
@VimNlsSafe @VimNlsSafe public static final String FMT = "defaults %s -globalDomain ApplePressAndHoldEnabled";
public static final String FMT = "defaults %s -globalDomain ApplePressAndHoldEnabled"; @NotNull private static final MacKeyRepeat INSTANCE = new MacKeyRepeat();
@NotNull @NonNls private static final String EXEC_COMMAND = "launchctl stop com.apple.SystemUIServer.agent";
private static final MacKeyRepeat INSTANCE = new MacKeyRepeat(); @NonNls private static final String delete = "delete";
@NonNls @NonNls private static final String write = "write";
private static final String EXEC_COMMAND = "launchctl stop com.apple.SystemUIServer.agent"; @NonNls private static final String read = "read";
@NonNls
private static final String delete = "delete";
@NonNls
private static final String write = "write";
@NonNls
private static final String read = "read";
public static @NotNull public static @NotNull MacKeyRepeat getInstance() {
MacKeyRepeat getInstance() {
return INSTANCE; return INSTANCE;
} }
private static @NotNull private static @NotNull String read(@NotNull InputStream stream) throws IOException {
String read(@NotNull InputStream stream) throws IOException {
return CharStreams.toString(new InputStreamReader(stream)); return CharStreams.toString(new InputStreamReader(stream));
} }
public @Nullable public @Nullable Boolean isEnabled() {
Boolean isEnabled() {
final String command = String.format(FMT, read); final String command = String.format(FMT, read);
try { try {
final Process process = Runtime.getRuntime().exec(command); final Process process = Runtime.getRuntime().exec(command);
final String data = read(process.getInputStream()).trim(); final String data = read(process.getInputStream()).trim();
try { try {
return Integer.parseInt(data) == 0; return Integer.parseInt(data) == 0;
} catch (NumberFormatException e) { }
catch (NumberFormatException e) {
return null; return null;
} }
} catch (IOException e) { }
catch (IOException e) {
return null; return null;
} }
} }
@ -64,7 +57,8 @@ public class MacKeyRepeat {
final String command; final String command;
if (value == null) { if (value == null) {
command = String.format(FMT, delete); command = String.format(FMT, delete);
} else { }
else {
final String arg = value ? "0" : "1"; final String arg = value ? "0" : "1";
command = String.format(FMT, write) + " " + arg; command = String.format(FMT, write) + " " + arg;
} }
@ -74,7 +68,8 @@ public class MacKeyRepeat {
defaults.waitFor(); defaults.waitFor();
final Process restartSystemUI = runtime.exec(EXEC_COMMAND); final Process restartSystemUI = runtime.exec(EXEC_COMMAND);
restartSystemUI.waitFor(); restartSystemUI.waitFor();
} catch (IOException | InterruptedException ignored) { }
catch (IOException | InterruptedException ignored) {
} }
} }
} }

View File

@ -61,7 +61,8 @@ public class PsiHelper {
index = i; index = i;
if (count > 0) count--; if (count > 0) count--;
break; break;
} else if (navigationOffsets.get(i) == offset) { }
else if (navigationOffsets.get(i) == offset) {
index = i; index = i;
break; break;
} }
@ -69,7 +70,8 @@ public class PsiHelper {
int resultIndex = index + count; int resultIndex = index + count;
if (resultIndex < 0) { if (resultIndex < 0) {
resultIndex = 0; resultIndex = 0;
} else if (resultIndex >= navigationOffsets.size()) { }
else if (resultIndex >= navigationOffsets.size()) {
resultIndex = navigationOffsets.size() - 1; resultIndex = navigationOffsets.size() - 1;
} }
@ -80,7 +82,7 @@ public class PsiHelper {
@NotNull List<Integer> navigationOffsets, @NotNull List<Integer> navigationOffsets,
boolean start) { boolean start) {
if (root instanceof PsiTreeElementBase) { if (root instanceof PsiTreeElementBase) {
PsiElement element = ((PsiTreeElementBase<?>) root).getValue(); PsiElement element = ((PsiTreeElementBase<?>)root).getValue();
int offset; int offset;
if (start) { if (start) {
offset = element.getTextRange().getStartOffset(); offset = element.getTextRange().getStartOffset();
@ -93,7 +95,8 @@ public class PsiHelper {
offset += braceIndex; offset += braceIndex;
} }
} }
} else { }
else {
offset = element.getTextRange().getEndOffset() - 1; offset = element.getTextRange().getEndOffset() - 1;
} }
if (!navigationOffsets.contains(offset)) { if (!navigationOffsets.contains(offset)) {
@ -105,8 +108,7 @@ public class PsiHelper {
} }
} }
public static @Nullable public static @Nullable PsiFile getFile(@NotNull Editor editor) {
PsiFile getFile(@NotNull Editor editor) {
VirtualFile vf = EditorHelper.getVirtualFile(editor); VirtualFile vf = EditorHelper.getVirtualFile(editor);
if (vf != null) { if (vf != null) {
Project proj = editor.getProject(); Project proj = editor.getProject();

View File

@ -146,7 +146,8 @@ public class SearchHelper {
if (dir == Direction.BACKWARDS && start_pos.col == 0) { if (dir == Direction.BACKWARDS && start_pos.col == 0) {
lnum = pos.lnum - 1; lnum = pos.lnum - 1;
at_first_line = false; at_first_line = false;
} else { }
else {
lnum = pos.lnum; lnum = pos.lnum;
} }
@ -220,7 +221,7 @@ public class SearchHelper {
* relative to the end of the match. * relative to the end of the match.
*/ */
match_ok = false; match_ok = false;
for (; ; ) { for (;;) {
if (loop != 0 || if (loop != 0 ||
(searchOptions.contains(SearchOptions.WANT_ENDPOS) (searchOptions.contains(SearchOptions.WANT_ENDPOS)
? (lnum + regmatch.endpos[0].lnum < start_pos.lnum || (lnum + regmatch.endpos[0].lnum == start_pos.lnum && regmatch.endpos[0].col - 1 < start_pos.col + extra_col)) ? (lnum + regmatch.endpos[0].lnum < start_pos.lnum || (lnum + regmatch.endpos[0].lnum == start_pos.lnum && regmatch.endpos[0].col - 1 < start_pos.col + extra_col))
@ -230,7 +231,8 @@ public class SearchHelper {
match_ok = true; match_ok = true;
matchpos = new RegExp.lpos_T(regmatch.startpos[0]); matchpos = new RegExp.lpos_T(regmatch.startpos[0]);
endpos = new RegExp.lpos_T(regmatch.endpos[0]); endpos = new RegExp.lpos_T(regmatch.endpos[0]);
} else { }
else {
break; break;
} }
@ -308,7 +310,8 @@ public class SearchHelper {
lnum = lineCount - 1; lnum = lineCount - 1;
//if (!shortmess(SHM_SEARCH) && (options & SEARCH_MSG)) //if (!shortmess(SHM_SEARCH) && (options & SEARCH_MSG))
// give_warning((char_u *)_(top_bot_msg), TRUE); // give_warning((char_u *)_(top_bot_msg), TRUE);
} else { }
else {
lnum = 0; lnum = 0;
//if (!shortmess(SHM_SEARCH) && (options & SEARCH_MSG)) //if (!shortmess(SHM_SEARCH) && (options & SEARCH_MSG))
// give_warning((char_u *)_(bot_top_msg), TRUE); // give_warning((char_u *)_(bot_top_msg), TRUE);
@ -324,9 +327,11 @@ public class SearchHelper {
if (searchOptions.contains(SearchOptions.SHOW_MESSAGES)) { if (searchOptions.contains(SearchOptions.SHOW_MESSAGES)) {
if (searchOptions.contains(SearchOptions.WRAP)) { if (searchOptions.contains(SearchOptions.WRAP)) {
VimPlugin.showMessage(MessageHelper.message(Msg.e_patnotf2, pattern)); VimPlugin.showMessage(MessageHelper.message(Msg.e_patnotf2, pattern));
} else if (lnum <= 0) { }
else if (lnum <= 0) {
VimPlugin.showMessage(MessageHelper.message(Msg.E384, pattern)); VimPlugin.showMessage(MessageHelper.message(Msg.E384, pattern));
} else { }
else {
VimPlugin.showMessage(MessageHelper.message(Msg.E385, pattern)); VimPlugin.showMessage(MessageHelper.message(Msg.E385, pattern));
} }
} }
@ -351,8 +356,7 @@ public class SearchHelper {
* @param ignoreCase Case sensitive or insensitive searching * @param ignoreCase Case sensitive or insensitive searching
* @return A list of TextRange objects representing the results * @return A list of TextRange objects representing the results
*/ */
public static @NotNull public static @NotNull List<TextRange> findAll(@NotNull Editor editor,
List<TextRange> findAll(@NotNull Editor editor,
@NotNull String pattern, @NotNull String pattern,
int startLine, int startLine,
int endLine, int endLine,
@ -385,11 +389,13 @@ public class SearchHelper {
if (start != end) { if (start != end) {
line += matchedLines - 1; line += matchedLines - 1;
col = endPos.column; col = endPos.column;
} else { }
else {
line += matchedLines; line += matchedLines;
col = 0; col = 0;
} }
} else { }
else {
line++; line++;
col = 0; col = 0;
} }
@ -440,8 +446,7 @@ public class SearchHelper {
return findBlockLocation(chars, found, match, dir, pos, count, false); return findBlockLocation(chars, found, match, dir, pos, count, false);
} }
public static @Nullable public static @Nullable TextRange findBlockRange(@NotNull Editor editor,
TextRange findBlockRange(@NotNull Editor editor,
@NotNull Caret caret, @NotNull Caret caret,
char type, char type,
int count, int count,
@ -540,7 +545,8 @@ public class SearchHelper {
if (allWhite) { if (allWhite) {
bend = o - 2; bend = o - 2;
} else { }
else {
bend--; bend--;
} }
} }
@ -560,7 +566,8 @@ public class SearchHelper {
final int endOffset = comment.getTextOffset() + comment.getTextLength(); final int endOffset = comment.getTextOffset() + comment.getTextLength();
if (pos < comment.getTextOffset() + prefix.length()) { if (pos < comment.getTextOffset() + prefix.length()) {
return endOffset; return endOffset;
} else if (pos >= endOffset - suffix.length()) { }
else if (pos >= endOffset - suffix.length()) {
return comment.getTextOffset(); return comment.getTextOffset();
} }
} }
@ -692,7 +699,8 @@ public class SearchHelper {
else if (c == '\n') { else if (c == '\n') {
inString = false; inString = false;
inChar = false; inChar = false;
} else if (pos != initialPos) { }
else if (pos != initialPos) {
// We found another character like our original - belongs to another pair // We found another character like our original - belongs to another pair
if (!inString && !inChar && c == found) { if (!inString && !inChar && c == found) {
stack++; stack++;
@ -700,7 +708,8 @@ public class SearchHelper {
// We found the start/end of a string // We found the start/end of a string
else if (!inChar) { else if (!inChar) {
inString = checkInString(chars, inCheckPosF.apply(pos), true); inString = checkInString(chars, inCheckPosF.apply(pos), true);
} else if (!inString) { }
else if (!inString) {
inChar = checkInString(chars, inCheckPosF.apply(pos), false); inChar = checkInString(chars, inCheckPosF.apply(pos), false);
} }
} }
@ -723,8 +732,7 @@ public class SearchHelper {
return backslashCounter % 2 == 0; return backslashCounter % 2 == 0;
} }
public static @Nullable public static @Nullable Pair<Character, Integer> findPositionOfFirstCharacter(@NotNull CharSequence chars,
Pair<Character, Integer> findPositionOfFirstCharacter(@NotNull CharSequence chars,
int pos, int pos,
final Set<Character> needles, final Set<Character> needles,
boolean searchEscaped, boolean searchEscaped,
@ -768,8 +776,7 @@ public class SearchHelper {
} }
public static @Nullable public static @Nullable TextRange findBlockTagRange(@NotNull Editor editor,
TextRange findBlockTagRange(@NotNull Editor editor,
@NotNull Caret caret, @NotNull Caret caret,
int count, int count,
boolean isOuter) { boolean isOuter) {
@ -786,7 +793,8 @@ public class SearchHelper {
final int line = caret.getLogicalPosition().line; final int line = caret.getLogicalPosition().line;
final int lineBegin = editor.getDocument().getLineStartOffset(line); final int lineBegin = editor.getDocument().getLineStartOffset(line);
searchStartPosition = ignoreWhitespaceAtLineStart(sequence, lineBegin, position); searchStartPosition = ignoreWhitespaceAtLineStart(sequence, lineBegin, position);
} else { }
else {
searchStartPosition = selectionEnd; searchStartPosition = selectionEnd;
} }
@ -795,7 +803,8 @@ public class SearchHelper {
while (searchStartPosition < sequence.length() && sequence.charAt(searchStartPosition) != '>') { while (searchStartPosition < sequence.length() && sequence.charAt(searchStartPosition) != '>') {
searchStartPosition++; searchStartPosition++;
} }
} else if (isInHTMLTag(sequence, searchStartPosition, true)) { }
else if (isInHTMLTag(sequence, searchStartPosition, true)) {
// caret is inside closing tag. Move to starting '<'. // caret is inside closing tag. Move to starting '<'.
while (searchStartPosition > 0 && sequence.charAt(searchStartPosition) != '<') { while (searchStartPosition > 0 && sequence.charAt(searchStartPosition) != '<') {
searchStartPosition--; searchStartPosition--;
@ -835,7 +844,8 @@ public class SearchHelper {
// Special case: if the inner tag is already selected we should like isOuter is active // Special case: if the inner tag is already selected we should like isOuter is active
// Note that we need to ignore newlines, because their selection is lost between multiple "it" invocations // Note that we need to ignore newlines, because their selection is lost between multiple "it" invocations
isOuter = true; isOuter = true;
} else if (openingTag.getEndOffset() == closingTagTextRange.getStartOffset() && }
else if (openingTag.getEndOffset() == closingTagTextRange.getStartOffset() &&
selectionStart == openingTag.getEndOffset()) { selectionStart == openingTag.getEndOffset()) {
// Special case: for an empty tag pair (e.g. <a></a>) the whole tag is selected if the caret is in the middle. // Special case: for an empty tag pair (e.g. <a></a>) the whole tag is selected if the caret is in the middle.
isOuter = true; isOuter = true;
@ -844,7 +854,8 @@ public class SearchHelper {
if (isOuter) { if (isOuter) {
return new TextRange(openingTag.getStartOffset(), closingTagTextRange.getEndOffset()); return new TextRange(openingTag.getStartOffset(), closingTagTextRange.getEndOffset());
} else { }
else {
return new TextRange(openingTag.getEndOffset(), closingTagTextRange.getStartOffset()); return new TextRange(openingTag.getEndOffset(), closingTagTextRange.getStartOffset());
} }
} }
@ -885,8 +896,7 @@ public class SearchHelper {
return closingBracket != -1 && sequence.charAt(closingBracket - 1) != '/'; return closingBracket != -1 && sequence.charAt(closingBracket - 1) != '/';
} }
private static @Nullable private static @Nullable Pair<TextRange, String> findUnmatchedClosingTag(final @NotNull CharSequence sequence,
Pair<TextRange, String> findUnmatchedClosingTag(final @NotNull CharSequence sequence,
final int position, final int position,
int count) { int count) {
// The tag name may contain any characters except slashes, whitespace and '>' // The tag name may contain any characters except slashes, whitespace and '>'
@ -910,13 +920,16 @@ public class SearchHelper {
if (openTags.isEmpty()) { if (openTags.isEmpty()) {
if (count <= 1) { if (count <= 1) {
return new Pair<>(new TextRange(position + matcher.start(), position + matcher.end()), tagName); return new Pair<>(new TextRange(position + matcher.start(), position + matcher.end()), tagName);
} else { }
else {
count--; count--;
} }
} else { }
else {
openTags.pop(); openTags.pop();
} }
} else { }
else {
final String tagName = matcher.group(1); final String tagName = matcher.group(1);
openTags.push(tagName); openTags.push(tagName);
} }
@ -924,8 +937,7 @@ public class SearchHelper {
return null; return null;
} }
private static @Nullable private static @Nullable TextRange findUnmatchedOpeningTag(@NotNull CharSequence sequence,
TextRange findUnmatchedOpeningTag(@NotNull CharSequence sequence,
int position, int position,
@NotNull String tagName) { @NotNull String tagName) {
final String quotedTagName = Pattern.quote(tagName); final String quotedTagName = Pattern.quote(tagName);
@ -950,14 +962,16 @@ public class SearchHelper {
if (!openTags.isEmpty()) { if (!openTags.isEmpty()) {
openTags.pop(); openTags.pop();
} }
} else { }
else {
openTags.push(match); openTags.push(match);
} }
} }
if (openTags.isEmpty()) { if (openTags.isEmpty()) {
return null; return null;
} else { }
else {
return openTags.pop(); return openTags.pop();
} }
} }
@ -965,8 +979,7 @@ public class SearchHelper {
/** /**
* This counts all the words in the file. * This counts all the words in the file.
*/ */
public static @NotNull public static @NotNull CountPosition countWords(@NotNull Editor editor) {
CountPosition countWords(@NotNull Editor editor) {
int size = EditorHelperRt.getFileSize(editor); int size = EditorHelperRt.getFileSize(editor);
return countWords(editor, 0, size); return countWords(editor, 0, size);
@ -975,22 +988,20 @@ public class SearchHelper {
/** /**
* This counts all the words in the file. * This counts all the words in the file.
*/ */
public static @NotNull public static @NotNull CountPosition countWords(@NotNull Editor editor, int start, int end) {
CountPosition countWords(@NotNull Editor editor, int start, int end) {
CharSequence chars = editor.getDocument().getCharsSequence(); CharSequence chars = editor.getDocument().getCharsSequence();
int offset = editor.getCaretModel().getOffset(); int offset = editor.getCaretModel().getOffset();
return countWords(chars, start, end, offset); return countWords(chars, start, end, offset);
} }
public static @NotNull public static @NotNull CountPosition countWords(@NotNull CharSequence chars, int start, int end, int offset) {
CountPosition countWords(@NotNull CharSequence chars, int start, int end, int offset) {
int count = 1; int count = 1;
int position = 0; int position = 0;
int last = -1; int last = -1;
int res = start; int res = start;
while (true) { while (true) {
res = (int) VimSearchHelperBase.Companion.findNextWordOne(chars, res, end, 1, true, false); res = (int)VimSearchHelperBase.Companion.findNextWordOne(chars, res, end, 1, true, false);
if (res == start || res == 0 || res > end || res == last) { if (res == start || res == 0 || res > end || res == last) {
break; break;
} }
@ -999,10 +1010,12 @@ public class SearchHelper {
if (res == offset) { if (res == offset) {
position = count; position = count;
} else if (last < offset && res >= offset) { }
else if (last < offset && res >= offset) {
if (count == 2) { if (count == 2) {
position = 1; position = 1;
} else { }
else {
position = count - 1; position = count - 1;
} }
} }
@ -1017,8 +1030,7 @@ public class SearchHelper {
return new CountPosition(count, position); return new CountPosition(count, position);
} }
public static @NotNull public static @NotNull List<Pair<TextRange, NumberType>> findNumbersInRange(final @NotNull Editor editor,
List<Pair<TextRange, NumberType>> findNumbersInRange(final @NotNull Editor editor,
@NotNull TextRange textRange, @NotNull TextRange textRange,
final boolean alpha, final boolean alpha,
final boolean hex, final boolean hex,
@ -1070,8 +1082,7 @@ public class SearchHelper {
return result; return result;
} }
public static @Nullable public static @Nullable Pair<TextRange, NumberType> findNumberUnderCursor(final @NotNull Editor editor,
Pair<TextRange, NumberType> findNumberUnderCursor(final @NotNull Editor editor,
@NotNull Caret caret, @NotNull Caret caret,
final boolean alpha, final boolean alpha,
final boolean hex, final boolean hex,
@ -1098,8 +1109,7 @@ public class SearchHelper {
* @param startPosOnLine - start offset to search * @param startPosOnLine - start offset to search
* @return - text range with number * @return - text range with number
*/ */
public static @Nullable public static @Nullable Pair<TextRange, NumberType> findNumberInText(final @NotNull String textInRange,
Pair<TextRange, NumberType> findNumberInText(final @NotNull String textInRange,
int startPosOnLine, int startPosOnLine,
final boolean alpha, final boolean alpha,
final boolean hex, final boolean hex,
@ -1132,7 +1142,8 @@ public class SearchHelper {
pos < lineEndOffset - 1 && pos < lineEndOffset - 1 &&
"xX".indexOf(textInRange.charAt(pos + 1)) >= 0) { "xX".indexOf(textInRange.charAt(pos + 1)) >= 0) {
pos += 2; pos += 2;
} else if ("xX".indexOf(textInRange.charAt(pos)) >= 0 && pos > 0 && textInRange.charAt(pos - 1) == '0') { }
else if ("xX".indexOf(textInRange.charAt(pos)) >= 0 && pos > 0 && textInRange.charAt(pos - 1) == '0') {
pos++; pos++;
} }
@ -1149,10 +1160,12 @@ public class SearchHelper {
if (!isHexChar || alpha) { if (!isHexChar || alpha) {
break; break;
} else { }
else {
pos++; pos++;
} }
} else { }
else {
break; break;
} }
} }
@ -1195,8 +1208,7 @@ public class SearchHelper {
/** /**
* Searches for digits block that matches parameters * Searches for digits block that matches parameters
*/ */
private static @NotNull private static @NotNull Pair<Integer, Integer> findRange(final @NotNull String text,
Pair<Integer, Integer> findRange(final @NotNull String text,
final int pos, final int pos,
final boolean alpha, final boolean alpha,
final boolean hex, final boolean hex,
@ -1228,11 +1240,14 @@ public class SearchHelper {
private static boolean isNumberChar(char ch, boolean alpha, boolean hex, boolean octal, boolean decimal) { private static boolean isNumberChar(char ch, boolean alpha, boolean hex, boolean octal, boolean decimal) {
if (alpha && ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) { if (alpha && ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) {
return true; return true;
} else if (octal && (ch >= '0' && ch <= '7')) { }
else if (octal && (ch >= '0' && ch <= '7')) {
return true; return true;
} else if (hex && ((ch >= '0' && ch <= '9') || "abcdefABCDEF".indexOf(ch) >= 0)) { }
else if (hex && ((ch >= '0' && ch <= '9') || "abcdefABCDEF".indexOf(ch) >= 0)) {
return true; return true;
} else { }
else {
return decimal && (ch >= '0' && ch <= '9'); return decimal && (ch >= '0' && ch <= '9');
} }
@ -1245,8 +1260,7 @@ public class SearchHelper {
* @param caret The caret to find word under * @param caret The caret to find word under
* @return The text range of the found word or null if there is no word under/after the cursor on the line * @return The text range of the found word or null if there is no word under/after the cursor on the line
*/ */
public static @Nullable public static @Nullable TextRange findWordUnderCursor(@NotNull Editor editor, @NotNull Caret caret) {
TextRange findWordUnderCursor(@NotNull Editor editor, @NotNull Caret caret) {
CharSequence chars = editor.getDocument().getCharsSequence(); CharSequence chars = editor.getDocument().getCharsSequence();
int stop = EngineEditorHelperKt.getLineEndOffset(new IjVimEditor(editor), caret.getLogicalPosition().line, true); int stop = EngineEditorHelperKt.getLineEndOffset(new IjVimEditor(editor), caret.getLogicalPosition().line, true);
@ -1266,7 +1280,8 @@ public class SearchHelper {
while (start > 0 && CharacterHelper.charType(chars.charAt(start - 1), false) == types[i]) { while (start > 0 && CharacterHelper.charType(chars.charAt(start - 1), false) == types[i]) {
start--; start--;
} }
} else { }
else {
// Search forward for start of word // Search forward for start of word
while (start < stop && CharacterHelper.charType(chars.charAt(start), false) != types[i]) { while (start < stop && CharacterHelper.charType(chars.charAt(start), false) != types[i]) {
start++; start++;
@ -1288,7 +1303,8 @@ public class SearchHelper {
(start >= chars.length() - 1 || (start >= chars.length() - 1 ||
CharacterHelper.charType(chars.charAt(start + 1), false) != CharacterHelper.CharacterType.KEYWORD)) { CharacterHelper.charType(chars.charAt(start + 1), false) != CharacterHelper.CharacterType.KEYWORD)) {
end = start + 1; end = start + 1;
} else { }
else {
end = VimSearchHelperBase.Companion.findNextWordEnd(chars, start, stop, 1, false, false) + 1; end = VimSearchHelperBase.Companion.findNextWordEnd(chars, start, stop, 1, false, false) + 1;
} }
@ -1296,8 +1312,7 @@ public class SearchHelper {
} }
@Contract("_, _, _, _, _, _, _ -> new") @Contract("_, _, _, _, _, _, _ -> new")
public static @NotNull public static @NotNull TextRange findWordUnderCursor(@NotNull Editor editor,
TextRange findWordUnderCursor(@NotNull Editor editor,
@NotNull Caret caret, @NotNull Caret caret,
int count, int count,
int dir, int dir,
@ -1341,9 +1356,10 @@ public class SearchHelper {
if ((!onWordStart && !(startSpace && isOuter)) || hasSelection || (count > 1 && dir == -1)) { if ((!onWordStart && !(startSpace && isOuter)) || hasSelection || (count > 1 && dir == -1)) {
if (dir == 1) { if (dir == 1) {
start = (int) VimSearchHelperBase.Companion.findNextWord(chars, pos, max, -1, isBig, !isOuter); start = (int)VimSearchHelperBase.Companion.findNextWord(chars, pos, max, -1, isBig, !isOuter);
} else { }
start = (int) VimSearchHelperBase.Companion.findNextWord(chars, pos, max, -(count - (onWordStart && !hasSelection ? 1 : 0)), isBig, !isOuter); else {
start = (int)VimSearchHelperBase.Companion.findNextWord(chars, pos, max, -(count - (onWordStart && !hasSelection ? 1 : 0)), isBig, !isOuter);
} }
start = EngineEditorHelperKt.normalizeOffset(new IjVimEditor(editor), start, false); start = EngineEditorHelperKt.normalizeOffset(new IjVimEditor(editor), start, false);
@ -1366,7 +1382,8 @@ public class SearchHelper {
!hasSelection && !hasSelection &&
(!(startSpace && isOuter) || (startSpace && !isOuter)) ? 1 : 0), isBig, (!(startSpace && isOuter) || (startSpace && !isOuter)) ? 1 : 0), isBig,
!isOuter); !isOuter);
} else { }
else {
end = VimSearchHelperBase.Companion.findNextWordEnd(chars, pos, max, 1, isBig, !isOuter); end = VimSearchHelperBase.Companion.findNextWordEnd(chars, pos, max, 1, isBig, !isOuter);
} }
} }
@ -1475,7 +1492,8 @@ public class SearchHelper {
if (found == Math.abs(count)) { if (found == Math.abs(count)) {
return pos; return pos;
} else { }
else {
return -1; return -1;
} }
} }
@ -1503,9 +1521,11 @@ public class SearchHelper {
if (res < 0 && (!requireAll || total == 1)) { if (res < 0 && (!requireAll || total == 1)) {
res = dir > 0 ? max - 1 : 0; res = dir > 0 ? max - 1 : 0;
} else if (count > 0 && total > 1 && !requireAll) { }
else if (count > 0 && total > 1 && !requireAll) {
res = dir > 0 ? max - 1 : 0; res = dir > 0 ? max - 1 : 0;
} else if (count > 0 && total > 1 && requireAll) { }
else if (count > 0 && total > 1 && requireAll) {
res = -count; res = -count;
} }
@ -1535,9 +1555,11 @@ public class SearchHelper {
if (res < 0 && (!requireAll || total == 1)) { if (res < 0 && (!requireAll || total == 1)) {
res = dir > 0 ? max - 1 : 0; res = dir > 0 ? max - 1 : 0;
} else if (count > 0 && total > 1 && !requireAll) { }
else if (count > 0 && total > 1 && !requireAll) {
res = dir > 0 ? max - 1 : 0; res = dir > 0 ? max - 1 : 0;
} else if (count > 0 && total > 1 && requireAll) { }
else if (count > 0 && total > 1 && requireAll) {
res = -count; res = -count;
} }
@ -1559,7 +1581,8 @@ public class SearchHelper {
// start < max was added to avoid exception and it may be incorrect // start < max was added to avoid exception and it may be incorrect
if (start < max && chars.charAt(start) == '\n' && !countCurrent) { if (start < max && chars.charAt(start) == '\n' && !countCurrent) {
end = findSentenceEnd(editor, chars, start, max, -1, false, multiple); end = findSentenceEnd(editor, chars, start, max, -1, false, multiple);
} else { }
else {
end = findSentenceEnd(editor, chars, start, max, -1, true, multiple); end = findSentenceEnd(editor, chars, start, max, -1, true, multiple);
} }
if (end == start && countCurrent && chars.charAt(end) == '\n') { if (end == start && countCurrent && chars.charAt(end) == '\n') {
@ -1580,13 +1603,16 @@ public class SearchHelper {
if (dir > 0) { if (dir > 0) {
if (offset == start && countCurrent) { if (offset == start && countCurrent) {
return offset; return offset;
} else if (offset > start) { }
else if (offset > start) {
return offset; return offset;
} }
} else { }
else {
if (offset == start && countCurrent) { if (offset == start && countCurrent) {
return offset; return offset;
} else if (offset < start) { }
else if (offset < start) {
return offset; return offset;
} }
} }
@ -1594,7 +1620,8 @@ public class SearchHelper {
if (dir > 0) { if (dir > 0) {
end = findSentenceEnd(editor, chars, start, max, dir, true, multiple); end = findSentenceEnd(editor, chars, start, max, dir, true, multiple);
} else { }
else {
end = findSentenceEnd(editor, chars, pos, max, dir, countCurrent, multiple); end = findSentenceEnd(editor, chars, pos, max, dir, countCurrent, multiple);
} }
@ -1616,12 +1643,14 @@ public class SearchHelper {
if (np < res || res < start) { if (np < res || res < start) {
res = np; res = np;
} }
} else { }
else {
if (np > res || (res >= start && !countCurrent)) { if (np > res || (res >= start && !countCurrent)) {
res = np; res = np;
} }
} }
} else if (res == -1 && np >= 0) { }
else if (res == -1 && np >= 0) {
res = np; res = np;
} }
// else we found neither, res already -1 // else we found neither, res already -1
@ -1638,7 +1667,8 @@ public class SearchHelper {
boolean multiple) { boolean multiple) {
if (dir > 0 && start >= EditorHelperRt.getFileSize(editor) - 1) { if (dir > 0 && start >= EditorHelperRt.getFileSize(editor) - 1) {
return -1; return -1;
} else if (dir < 0 && start <= 0) { }
else if (dir < 0 && start <= 0) {
return -1; return -1;
} }
@ -1679,16 +1709,19 @@ public class SearchHelper {
// Skip back to the sentence end so we can search backward from there // Skip back to the sentence end so we can search backward from there
// for the real previous sentence. // for the real previous sentence.
offset = end; offset = end;
} else { }
else {
// Yeah - we found the real end-of-sentence. Save it off. // Yeah - we found the real end-of-sentence. Save it off.
res = offset - 1; res = offset - 1;
found = true; found = true;
} }
} else { }
else {
// Turned out not to be an end-of-sentence so move back to where we were. // Turned out not to be an end-of-sentence so move back to where we were.
offset = end; offset = end;
} }
} else if (ch == '\n') { }
else if (ch == '\n') {
int end = offset; // Save where we found the newline. int end = offset; // Save where we found the newline.
if (dir > 0) { if (dir > 0) {
offset++; offset++;
@ -1707,18 +1740,21 @@ public class SearchHelper {
if (offset == np && (end - 1 != start || countCurrent)) { if (offset == np && (end - 1 != start || countCurrent)) {
res = end - 1; res = end - 1;
found = true; found = true;
} else if (offset > end) { }
else if (offset > end) {
res = offset; res = offset;
np = res; np = res;
found = true; found = true;
} else if (offset == end) { }
else if (offset == end) {
if (offset > 0 && chars.charAt(offset - 1) == '\n' && countCurrent) { if (offset > 0 && chars.charAt(offset - 1) == '\n' && countCurrent) {
res = end; res = end;
np = res; np = res;
found = true; found = true;
} }
} }
} else { }
else {
if (offset > 0) { if (offset > 0) {
offset--; offset--;
while (offset > 0) { while (offset > 0) {
@ -1735,7 +1771,8 @@ public class SearchHelper {
if (offset < end) { if (offset < end) {
if (end == start && countCurrent) { if (end == start && countCurrent) {
res = end; res = end;
} else { }
else {
res = offset - 1; res = offset - 1;
} }
@ -1761,7 +1798,8 @@ public class SearchHelper {
if (np < res || res < start) { if (np < res || res < start) {
res = np; res = np;
} }
} else { }
else {
if (np > res || (res >= start && !countCurrent)) { if (np > res || (res >= start && !countCurrent)) {
res = np; res = np;
} }
@ -1805,10 +1843,12 @@ public class SearchHelper {
which = 0; which = 0;
if (oneway) { if (oneway) {
findend = dir > 0; findend = dir > 0;
} else if (dir > 0 && start < max - 1 && !Character.isSpaceChar(chars.charAt(start + 1))) { }
else if (dir > 0 && start < max - 1 && !Character.isSpaceChar(chars.charAt(start + 1))) {
findend = true; findend = true;
} }
} else if (start == snext) // On sentence start }
else if (start == snext) // On sentence start
{ {
if (dir < 0 && !oneway) { if (dir < 0 && !oneway) {
return start; return start;
@ -1818,7 +1858,8 @@ public class SearchHelper {
if (dir < 0 && oneway) { if (dir < 0 && oneway) {
findend = false; findend = false;
} }
} else if (start == enext) // On sentence end }
else if (start == enext) // On sentence end
{ {
if (dir > 0 && !oneway) { if (dir > 0 && !oneway) {
return start; return start;
@ -1828,30 +1869,37 @@ public class SearchHelper {
if (dir > 0 && oneway) { if (dir > 0 && oneway) {
findend = true; findend = true;
} }
} else if (start >= sprev && start <= enext && enext < snext) // Middle of sentence }
else if (start >= sprev && start <= enext && enext < snext) // Middle of sentence
{ {
which = dir > 0 ? 1 : 0; which = dir > 0 ? 1 : 0;
} else // Between sentences }
else // Between sentences
{ {
which = dir > 0 ? 0 : 1; which = dir > 0 ? 0 : 1;
if (dir > 0) { if (dir > 0) {
if (oneway) { if (oneway) {
if (start < snext - 1) { if (start < snext - 1) {
findend = true; findend = true;
} else if (start == snext - 1) { }
else if (start == snext - 1) {
count++; count++;
} }
} else { }
else {
findend = true; findend = true;
} }
} else { }
else {
if (oneway) { if (oneway) {
if (start > eprev + 1) { if (start > eprev + 1) {
findend = false; findend = false;
} else if (start == eprev + 1) { }
else if (start == eprev + 1) {
count++; count++;
} }
} else { }
else {
findend = true; findend = true;
} }
} }
@ -1861,7 +1909,8 @@ public class SearchHelper {
for (; count > 0 && res >= 0 && res <= max - 1; count--) { for (; count > 0 && res >= 0 && res <= max - 1; count--) {
if ((toggle && which % 2 == 1) || (isOuter && findend)) { if ((toggle && which % 2 == 1) || (isOuter && findend)) {
res = findSentenceEnd(editor, chars, res, max, dir, false, total > 1); res = findSentenceEnd(editor, chars, res, max, dir, false, total > 1);
} else { }
else {
res = findSentenceStart(editor, chars, res, max, dir, false, total > 1); res = findSentenceStart(editor, chars, res, max, dir, false, total > 1);
} }
if (res == 0 || res == max - 1) { if (res == 0 || res == max - 1) {
@ -1871,7 +1920,8 @@ public class SearchHelper {
if (toggle) { if (toggle) {
if (which % 2 == 1 && dir < 0) { if (which % 2 == 1 && dir < 0) {
res++; res++;
} else if (which % 2 == 0 && dir > 0) { }
else if (which % 2 == 0 && dir > 0) {
res--; res--;
} }
} }
@ -1881,7 +1931,8 @@ public class SearchHelper {
if (res < 0 || count > 0) { if (res < 0 || count > 0) {
res = dir > 0 ? (max > 0 ? max - 1 : 0) : 0; res = dir > 0 ? (max > 0 ? max - 1 : 0) : 0;
} else if (isOuter && ((dir < 0 && findend) || (dir > 0 && !findend))) { }
else if (isOuter && ((dir < 0 && findend) || (dir > 0 && !findend))) {
if (res != 0 && res != max - 1) { if (res != 0 && res != max - 1) {
res -= dir; res -= dir;
} }
@ -1895,8 +1946,7 @@ public class SearchHelper {
} }
@Contract("_, _, _, _ -> new") @Contract("_, _, _, _ -> new")
public static @NotNull public static @NotNull TextRange findSentenceRange(@NotNull Editor editor,
TextRange findSentenceRange(@NotNull Editor editor,
@NotNull Caret caret, @NotNull Caret caret,
int count, int count,
boolean isOuter) { boolean isOuter) {
@ -1923,7 +1973,8 @@ public class SearchHelper {
return new TextRange(end, start + 1); return new TextRange(end, start + 1);
} }
} else { }
else {
int end = findSentenceRangeEnd(editor, chars, offset, max, count, isOuter, false); int end = findSentenceRangeEnd(editor, chars, offset, max, count, isOuter, false);
boolean space = isOuter; boolean space = isOuter;
@ -1943,9 +1994,11 @@ public class SearchHelper {
int maxline = new IjVimEditor(editor).lineCount(); int maxline = new IjVimEditor(editor).lineCount();
if (line >= 0 && line < maxline) { if (line >= 0 && line < maxline) {
return new IjVimEditor(editor).getLineStartOffset(line); return new IjVimEditor(editor).getLineStartOffset(line);
} else if (line == maxline) { }
else if (line == maxline) {
return count > 0 ? EditorHelperRt.getFileSize(editor) - 1 : 0; return count > 0 ? EditorHelperRt.getFileSize(editor) - 1 : 0;
} else { }
else {
return -1; return -1;
} }
} }
@ -1959,7 +2012,8 @@ public class SearchHelper {
if (line >= 0) { if (line >= 0) {
return new IjVimEditor(editor).getLineStartOffset(line); return new IjVimEditor(editor).getLineStartOffset(line);
} else { }
else {
return dir > 0 ? EditorHelperRt.getFileSize(editor) - 1 : 0; return dir > 0 ? EditorHelperRt.getFileSize(editor) - 1 : 0;
} }
} }
@ -1982,7 +2036,8 @@ public class SearchHelper {
if (total == 1 && line < 0) { if (total == 1 && line < 0) {
line = dir > 0 ? maxline - 1 : 0; line = dir > 0 ? maxline - 1 : 0;
} else if (total > 1 && count == 0 && line < 0) { }
else if (total > 1 && count == 0 && line < 0) {
line = dir > 0 ? maxline - 1 : 0; line = dir > 0 ? maxline - 1 : 0;
} }
@ -2025,8 +2080,7 @@ public class SearchHelper {
return line; return line;
} }
public static @Nullable public static @Nullable TextRange findParagraphRange(@NotNull Editor editor,
TextRange findParagraphRange(@NotNull Editor editor,
@NotNull Caret caret, @NotNull Caret caret,
int count, int count,
boolean isOuter) { boolean isOuter) {
@ -2040,7 +2094,8 @@ public class SearchHelper {
if (isOuter) { if (isOuter) {
if (EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), line, true)) { if (EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), line, true)) {
sline = line; sline = line;
} else { }
else {
sline = findNextParagraphLine(editor, caret, -1, true); sline = findNextParagraphLine(editor, caret, -1, true);
} }
@ -2054,25 +2109,30 @@ public class SearchHelper {
if (sline == line) { if (sline == line) {
eline--; eline--;
fixstart = true; fixstart = true;
} else { }
else {
sline++; sline++;
fixend = true; fixend = true;
} }
} else if (!EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), eline, true) && }
else if (!EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), eline, true) &&
!EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), sline, true) && !EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), sline, true) &&
sline > 0) { sline > 0) {
sline--; sline--;
fixstart = true; fixstart = true;
} else { }
else {
if (EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), eline, true)) { if (EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), eline, true)) {
fixend = true; fixend = true;
} else { }
else {
if (EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), sline, true)) { if (EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), sline, true)) {
fixstart = true; fixstart = true;
} }
} }
} }
} else { }
else {
sline = line; sline = line;
if (!EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), sline, true)) { if (!EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), sline, true)) {
sline = findNextParagraphLine(editor, caret, -1, true); sline = findNextParagraphLine(editor, caret, -1, true);
@ -2080,7 +2140,8 @@ public class SearchHelper {
sline++; sline++;
} }
eline = line; eline = line;
} else { }
else {
eline = line - 1; eline = line - 1;
} }
@ -2091,11 +2152,13 @@ public class SearchHelper {
if (eline < 0) { if (eline < 0) {
if (i == count - 1) { if (i == count - 1) {
eline = maxline - 1; eline = maxline - 1;
} else { }
else {
return null; return null;
} }
} }
} else { }
else {
eline++; eline++;
} }
which++; which++;
@ -2109,7 +2172,8 @@ public class SearchHelper {
while (sline > 0) { while (sline > 0) {
if (EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), sline - 1, true)) { if (EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), sline - 1, true)) {
sline--; sline--;
} else { }
else {
break; break;
} }
} }
@ -2121,7 +2185,8 @@ public class SearchHelper {
while (eline < maxline - 1) { while (eline < maxline - 1) {
if (EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), eline + 1, true)) { if (EngineEditorHelperKt.isLineEmpty(new IjVimEditor(editor), eline + 1, true)) {
eline++; eline++;
} else { }
else {
break; break;
} }
} }
@ -2146,8 +2211,7 @@ public class SearchHelper {
return PsiHelper.findMethodEnd(editor, caret.getOffset(), count); return PsiHelper.findMethodEnd(editor, caret.getOffset(), count);
} }
private static @NotNull private static @NotNull String getPairChars() {
String getPairChars() {
if (pairsChars == null) { if (pairsChars == null) {
VimPlugin.getOptionGroup().addListener( VimPlugin.getOptionGroup().addListener(
OptionConstants.matchpairs, OptionConstants.matchpairs,
@ -2164,8 +2228,7 @@ public class SearchHelper {
return pairsChars; return pairsChars;
} }
private static @NotNull private static @NotNull String parseMatchPairsOption() {
String parseMatchPairsOption() {
List<String> pairs = globalOptions(injector).getStringListValues(OptionConstants.matchpairs); List<String> pairs = globalOptions(injector).getStringListValues(OptionConstants.matchpairs);
StringBuilder res = new StringBuilder(); StringBuilder res = new StringBuilder();
for (String s : pairs) { for (String s : pairs) {
@ -2195,10 +2258,8 @@ public class SearchHelper {
private final int position; private final int position;
} }
private static @Nullable private static @Nullable String pairsChars = null;
String pairsChars = null; private static final @NotNull String blockChars = "{}()[]<>";
private static final @NotNull
String blockChars = "{}()[]<>";
private static final Logger logger = Logger.getInstance(SearchHelper.class.getName()); private static final Logger logger = Logger.getInstance(SearchHelper.class.getName());
} }

View File

@ -79,11 +79,9 @@ internal var Caret.vimLastColumn: Int
_vimLastColumn = value _vimLastColumn = value
_vimLastColumnPos = visualPosition _vimLastColumnPos = visualPosition
} }
internal fun Caret.resetVimLastColumn() { internal fun Caret.resetVimLastColumn() {
_vimLastColumnPos = null _vimLastColumnPos = null
} }
private var Caret._vimLastColumn: Int by userDataCaretToEditorOr { (this as Caret).inlayAwareVisualColumn } private var Caret._vimLastColumn: Int by userDataCaretToEditorOr { (this as Caret).inlayAwareVisualColumn }
private var Caret._vimLastColumnPos: VisualPosition? by userDataCaretToEditor() private var Caret._vimLastColumnPos: VisualPosition? by userDataCaretToEditor()

View File

@ -15,17 +15,12 @@ import org.jetbrains.annotations.NotNull;
import javax.swing.*; import javax.swing.*;
public final class VimIcons { public final class VimIcons {
public static final @NotNull public static final @NotNull Icon IDEAVIM = load("/icons/ideavim.svg");
Icon IDEAVIM = load("/icons/ideavim.svg"); public static final @NotNull Icon IDEAVIM_DISABLED = load("/icons/ideavim_disabled.svg");
public static final @NotNull public static final @NotNull Icon TWITTER = load("/icons/twitter.svg");
Icon IDEAVIM_DISABLED = load("/icons/ideavim_disabled.svg"); public static final @NotNull Icon YOUTRACK = load("/icons/youtrack.svg");
public static final @NotNull
Icon TWITTER = load("/icons/twitter.svg");
public static final @NotNull
Icon YOUTRACK = load("/icons/youtrack.svg");
private static @NotNull private static @NotNull Icon load(@NotNull @NonNls String path) {
Icon load(@NotNull @NonNls String path) {
return IconManager.getInstance().getIcon(path, VimIcons.class); return IconManager.getInstance().getIcon(path, VimIcons.class);
} }
} }

View File

@ -72,8 +72,7 @@ internal object IdeaSpecifics {
val isVimAction = (action as? AnActionWrapper)?.delegate is VimShortcutKeyAction val isVimAction = (action as? AnActionWrapper)?.delegate is VimShortcutKeyAction
if (!isVimAction && injector.globalOptions().isSet(IjOptionConstants.trackactionids)) { if (!isVimAction && injector.globalOptions().isSet(IjOptionConstants.trackactionids)) {
if (action !is NotificationService.ActionIdNotifier.CopyActionId && action !is NotificationService.ActionIdNotifier.StopTracking) { if (action !is NotificationService.ActionIdNotifier.CopyActionId && action !is NotificationService.ActionIdNotifier.StopTracking) {
val id: String? = ActionManager.getInstance().getId(action) val id: String? = ActionManager.getInstance().getId(action) ?: (action.shortcutSet as? ProxyShortcutSet)?.actionId
?: (action.shortcutSet as? ProxyShortcutSet)?.actionId
VimPlugin.getNotifications(event.dataContext.getData(CommonDataKeys.PROJECT)).notifyActionId(id) VimPlugin.getNotifications(event.dataContext.getData(CommonDataKeys.PROJECT)).notifyActionId(id)
} }
} }

View File

@ -33,7 +33,8 @@ internal class IntellijMark(bookmark: LineBookmark, override val col: Int, proje
} }
private fun getMark(): LineBookmark? = private fun getMark(): LineBookmark? =
getProject()?.let { project -> getProject()?.let {
project ->
BookmarksManager.getInstance(project)?.getBookmark(BookmarkType.get(key)) as? LineBookmark BookmarksManager.getInstance(project)?.getBookmark(BookmarkType.get(key)) as? LineBookmark
} }

View File

@ -84,7 +84,6 @@ internal class IjVimCaret(val caret: Caret) : VimCaretBase() {
set(value) { set(value) {
caret.vimLastColumn = value caret.vimLastColumn = value
} }
override fun resetLastColumn() = caret.resetVimLastColumn() override fun resetLastColumn() = caret.resetVimLastColumn()
override val selectionStart: Int override val selectionStart: Int
get() = caret.selectionStart get() = caret.selectionStart

View File

@ -8,13 +8,13 @@
/** /**
* IdeaVim command index. * IdeaVim command index.
* <p> *
* <p> *
* 1. Insert mode * 1. Insert mode
* <p> *
* tag action * tag action
* ------------------------------------------------------------------------------------------------------------------- * -------------------------------------------------------------------------------------------------------------------
* <p> *
* |i_CTRL-@| {@link com.maddyhome.idea.vim.action.change.insert.InsertPreviousInsertExitAction} * |i_CTRL-@| {@link com.maddyhome.idea.vim.action.change.insert.InsertPreviousInsertExitAction}
* |i_CTRL-A| {@link com.maddyhome.idea.vim.action.change.insert.InsertPreviousInsertAction} * |i_CTRL-A| {@link com.maddyhome.idea.vim.action.change.insert.InsertPreviousInsertAction}
* |i_CTRL-C| {@link com.maddyhome.idea.vim.action.change.insert.InsertExitModeAction} * |i_CTRL-C| {@link com.maddyhome.idea.vim.action.change.insert.InsertExitModeAction}
@ -80,13 +80,13 @@
* |i_<F1>| IntelliJ help * |i_<F1>| IntelliJ help
* |i_<Insert>| IntelliJ editor toggle insert/replace * |i_<Insert>| IntelliJ editor toggle insert/replace
* |i_CTRL-X_index| TO BE IMPLEMENTED * |i_CTRL-X_index| TO BE IMPLEMENTED
* <p> *
* <p> *
* 2. Normal mode * 2. Normal mode
* <p> *
* tag action * tag action
* ------------------------------------------------------------------------------------------------------------------- * -------------------------------------------------------------------------------------------------------------------
* <p> *
* |CTRL-A| {@link com.maddyhome.idea.vim.action.change.change.number.ChangeNumberIncAction} * |CTRL-A| {@link com.maddyhome.idea.vim.action.change.change.number.ChangeNumberIncAction}
* |CTRL-B| {@link com.maddyhome.idea.vim.action.motion.scroll.MotionScrollPageUpAction} * |CTRL-B| {@link com.maddyhome.idea.vim.action.motion.scroll.MotionScrollPageUpAction}
* |CTRL-C| TO BE IMPLEMENTED * |CTRL-C| TO BE IMPLEMENTED
@ -241,18 +241,18 @@
* |<S-Home>| {@link com.maddyhome.idea.vim.action.motion.leftright.MotionShiftHomeAction} * |<S-Home>| {@link com.maddyhome.idea.vim.action.motion.leftright.MotionShiftHomeAction}
* |<S-End>| {@link com.maddyhome.idea.vim.action.motion.leftright.MotionShiftEndAction} * |<S-End>| {@link com.maddyhome.idea.vim.action.motion.leftright.MotionShiftEndAction}
* |<Up>| {@link com.maddyhome.idea.vim.action.motion.updown.MotionArrowUpAction} * |<Up>| {@link com.maddyhome.idea.vim.action.motion.updown.MotionArrowUpAction}
* <p> *
* <p> *
* 2.1. Text objects * 2.1. Text objects
* <p> *
* Text object commands are listed in the visual mode section. * Text object commands are listed in the visual mode section.
* <p> *
* <p> *
* 2.2. Window commands * 2.2. Window commands
* <p> *
* tag action * tag action
* ------------------------------------------------------------------------------------------------------------------- * -------------------------------------------------------------------------------------------------------------------
* <p> *
* |CTRL-W_+| TO BE IMPLEMENTED * |CTRL-W_+| TO BE IMPLEMENTED
* |CTRL-W_-| TO BE IMPLEMENTED * |CTRL-W_-| TO BE IMPLEMENTED
* |CTRL-W_<| TO BE IMPLEMENTED * |CTRL-W_<| TO BE IMPLEMENTED
@ -305,10 +305,10 @@
* |CTRL-W_CTRL-J| {@link com.maddyhome.idea.vim.action.window.WindowDownAction} * |CTRL-W_CTRL-J| {@link com.maddyhome.idea.vim.action.window.WindowDownAction}
* |CTRL-W_CTRL-K| {@link com.maddyhome.idea.vim.action.window.WindowUpAction} * |CTRL-W_CTRL-K| {@link com.maddyhome.idea.vim.action.window.WindowUpAction}
* |CTRL-W_CTRL-L| {@link com.maddyhome.idea.vim.action.window.WindowRightAction} * |CTRL-W_CTRL-L| {@link com.maddyhome.idea.vim.action.window.WindowRightAction}
* <p> *
* <p> *
* 2.3. Square bracket commands * 2.3. Square bracket commands
* <p> *
* tag action * tag action
* ------------------------------------------------------------------------------------------------------------------- * -------------------------------------------------------------------------------------------------------------------
* |[_CTRL-D| TO BE IMPLEMENTED * |[_CTRL-D| TO BE IMPLEMENTED
@ -361,13 +361,13 @@
* |]s| TO BE IMPLEMENTED * |]s| TO BE IMPLEMENTED
* |]z| TO BE IMPLEMENTED * |]z| TO BE IMPLEMENTED
* |]}| {@link com.maddyhome.idea.vim.action.motion.text.MotionUnmatchedBraceCloseAction} * |]}| {@link com.maddyhome.idea.vim.action.motion.text.MotionUnmatchedBraceCloseAction}
* <p> *
* <p> *
* 2.4. Commands starting with 'g' * 2.4. Commands starting with 'g'
* <p> *
* tag action * tag action
* ------------------------------------------------------------------------------------------------------------------- * -------------------------------------------------------------------------------------------------------------------
* <p> *
* |g_CTRL-A| not applicable * |g_CTRL-A| not applicable
* |g_CTRL-G| {@link com.maddyhome.idea.vim.action.file.FileGetLocationInfoAction} * |g_CTRL-G| {@link com.maddyhome.idea.vim.action.file.FileGetLocationInfoAction}
* |g_CTRL-H| {@link com.maddyhome.idea.vim.action.motion.select.SelectEnableBlockModeAction} * |g_CTRL-H| {@link com.maddyhome.idea.vim.action.motion.select.SelectEnableBlockModeAction}
@ -434,10 +434,10 @@
* |g<End>| {@link com.maddyhome.idea.vim.action.motion.leftright.MotionLastScreenColumnAction} * |g<End>| {@link com.maddyhome.idea.vim.action.motion.leftright.MotionLastScreenColumnAction}
* |g<Home>| {@link com.maddyhome.idea.vim.action.motion.leftright.MotionFirstScreenColumnAction} * |g<Home>| {@link com.maddyhome.idea.vim.action.motion.leftright.MotionFirstScreenColumnAction}
* |g<Up>| {@link com.maddyhome.idea.vim.action.motion.updown.MotionUpNotLineWiseAction} * |g<Up>| {@link com.maddyhome.idea.vim.action.motion.updown.MotionUpNotLineWiseAction}
* <p> *
* <p> *
* 2.5. Commands starting with 'z' * 2.5. Commands starting with 'z'
* <p> *
* tag action * tag action
* ------------------------------------------------------------------------------------------------------------------- * -------------------------------------------------------------------------------------------------------------------
* |z<CR>| {@link com.maddyhome.idea.vim.action.motion.scroll.MotionScrollFirstScreenLineStartAction} * |z<CR>| {@link com.maddyhome.idea.vim.action.motion.scroll.MotionScrollFirstScreenLineStartAction}
@ -484,13 +484,13 @@
* |zz| {@link com.maddyhome.idea.vim.action.motion.scroll.MotionScrollMiddleScreenLineAction} * |zz| {@link com.maddyhome.idea.vim.action.motion.scroll.MotionScrollMiddleScreenLineAction}
* |z<Left>| {@link com.maddyhome.idea.vim.action.motion.scroll.MotionScrollColumnRightAction} * |z<Left>| {@link com.maddyhome.idea.vim.action.motion.scroll.MotionScrollColumnRightAction}
* |z<Right>| {@link com.maddyhome.idea.vim.action.motion.scroll.MotionScrollColumnLeftAction} * |z<Right>| {@link com.maddyhome.idea.vim.action.motion.scroll.MotionScrollColumnLeftAction}
* <p> *
* <p> *
* 3. Visual mode * 3. Visual mode
* <p> *
* tag action * tag action
* ------------------------------------------------------------------------------------------------------------------- * -------------------------------------------------------------------------------------------------------------------
* <p> *
* |v_CTRL-\_CTRL-N| {@link com.maddyhome.idea.vim.action.motion.visual.VisualExitModeAction} * |v_CTRL-\_CTRL-N| {@link com.maddyhome.idea.vim.action.motion.visual.VisualExitModeAction}
* |v_CTRL-\_CTRL-G| TO BE IMPLEMENTED * |v_CTRL-\_CTRL-G| TO BE IMPLEMENTED
* |v_CTRL-A| {@link com.maddyhome.idea.vim.action.change.change.number.ChangeVisualNumberIncAction} * |v_CTRL-A| {@link com.maddyhome.idea.vim.action.change.change.number.ChangeVisualNumberIncAction}
@ -578,10 +578,10 @@
* |v_~| {@link com.maddyhome.idea.vim.action.change.change.ChangeCaseToggleVisualAction} * |v_~| {@link com.maddyhome.idea.vim.action.change.change.ChangeCaseToggleVisualAction}
* |v_`| {@link com.maddyhome.idea.vim.action.motion.mark.MotionGotoFileMarkAction} * |v_`| {@link com.maddyhome.idea.vim.action.motion.mark.MotionGotoFileMarkAction}
* |v_'| {@link com.maddyhome.idea.vim.action.motion.mark.MotionGotoFileMarkLineAction} * |v_'| {@link com.maddyhome.idea.vim.action.motion.mark.MotionGotoFileMarkLineAction}
* <p> *
* <p> *
* 4. Select mode * 4. Select mode
* <p> *
* tag action * tag action
* ------------------------------------------------------------------------------------------------------------------- * -------------------------------------------------------------------------------------------------------------------
* |<BS>| {@link com.maddyhome.idea.vim.action.motion.select.SelectDeleteAction} * |<BS>| {@link com.maddyhome.idea.vim.action.motion.select.SelectDeleteAction}
@ -597,12 +597,12 @@
* |<Left>| {@link com.maddyhome.idea.vim.action.motion.select.motion.SelectMotionLeftAction} * |<Left>| {@link com.maddyhome.idea.vim.action.motion.select.motion.SelectMotionLeftAction}
* |<Right>| {@link com.maddyhome.idea.vim.action.motion.select.motion.SelectMotionRightAction} * |<Right>| {@link com.maddyhome.idea.vim.action.motion.select.motion.SelectMotionRightAction}
* |<Up>| {@link com.maddyhome.idea.vim.action.motion.updown.MotionArrowUpAction} * |<Up>| {@link com.maddyhome.idea.vim.action.motion.updown.MotionArrowUpAction}
* <p> *
* 5. Command line editing * 5. Command line editing
* <p> *
* tag action * tag action
* ------------------------------------------------------------------------------------------------------------------- * -------------------------------------------------------------------------------------------------------------------
* <p> *
* |c_CTRL-A| TO BE IMPLEMENTED * |c_CTRL-A| TO BE IMPLEMENTED
* |c_CTRL-B| {@link javax.swing.text.DefaultEditorKit#beginLineAction} * |c_CTRL-B| {@link javax.swing.text.DefaultEditorKit#beginLineAction}
* |c_CTRL-C| {@link com.maddyhome.idea.vim.ui.ex.CancelEntryAction} * |c_CTRL-C| {@link com.maddyhome.idea.vim.ui.ex.CancelEntryAction}
@ -665,13 +665,13 @@
* |c_digraph| {char1} <BS> {char2} * |c_digraph| {char1} <BS> {char2}
* |c_wildchar| TO BE IMPLEMENTED * |c_wildchar| TO BE IMPLEMENTED
* |'cedit'| TO BE IMPLEMENTED * |'cedit'| TO BE IMPLEMENTED
* <p> *
* <p> *
* 6. Ex commands * 6. Ex commands
* <p> *
* tag handler * tag handler
* ------------------------------------------------------------------------------------------------------------------- * -------------------------------------------------------------------------------------------------------------------
* <p> *
* |:map| {@link com.maddyhome.idea.vim.vimscript.model.commands.mapping.MapCommand} * |:map| {@link com.maddyhome.idea.vim.vimscript.model.commands.mapping.MapCommand}
* |:nmap| ... * |:nmap| ...
* |:vmap| ... * |:vmap| ...
@ -696,12 +696,12 @@
* |:delcommand| {@link com.maddyhome.idea.vim.vimscript.model.commands.DelCmdCommand} * |:delcommand| {@link com.maddyhome.idea.vim.vimscript.model.commands.DelCmdCommand}
* |:comclear| {@link com.maddyhome.idea.vim.vimscript.model.commands.CmdClearCommand} * |:comclear| {@link com.maddyhome.idea.vim.vimscript.model.commands.CmdClearCommand}
* ... * ...
* <p> *
* The list of supported Ex commands is incomplete. * The list of supported Ex commands is incomplete.
* <p> *
* <p> *
* A. Misc commands * A. Misc commands
* <p> *
* tag handler * tag handler
* ------------------------------------------------------------------------------------------------------------------- * -------------------------------------------------------------------------------------------------------------------
* |]b| {@link com.maddyhome.idea.vim.action.motion.text.MotionCamelEndLeftAction} * |]b| {@link com.maddyhome.idea.vim.action.motion.text.MotionCamelEndLeftAction}
@ -710,8 +710,8 @@
* |[w| {@link com.maddyhome.idea.vim.action.motion.text.MotionCamelRightAction} * |[w| {@link com.maddyhome.idea.vim.action.motion.text.MotionCamelRightAction}
* |g(| {@link com.maddyhome.idea.vim.action.motion.text.MotionSentencePreviousEndAction} * |g(| {@link com.maddyhome.idea.vim.action.motion.text.MotionSentencePreviousEndAction}
* |g)| {@link com.maddyhome.idea.vim.action.motion.text.MotionSentenceNextEndAction} * |g)| {@link com.maddyhome.idea.vim.action.motion.text.MotionSentenceNextEndAction}
* <p> *
* <p> *
* See also :help index. * See also :help index.
* *
* @author vlan * @author vlan

View File

@ -1845,8 +1845,7 @@ internal class RegExp {
RE_COL -> if (!re_num_cmp(reginput!!.pointer() - regline!!.pointer() + 1, scan)) { RE_COL -> if (!re_num_cmp(reginput!!.pointer() - regline!!.pointer() + 1, scan)) {
return false return false
} }
RE_VCOL -> { RE_VCOL -> {}
}
BOW -> if (c == '\u0000') /* Can't match at end of line */ { BOW -> if (c == '\u0000') /* Can't match at end of line */ {
return false return false
} else { } else {
@ -2064,10 +2063,8 @@ internal class RegExp {
} }
reginput!!.inc() reginput!!.inc()
} }
NOTHING -> { NOTHING -> {}
} BACK -> {}
BACK -> {
}
MOPEN, MOPEN + 1, MOPEN + 2, MOPEN + 3, MOPEN + 4, MOPEN + 5, MOPEN + 6, MOPEN + 7, MOPEN + 8, MOPEN + 9 -> { MOPEN, MOPEN + 1, MOPEN + 2, MOPEN + 3, MOPEN + 4, MOPEN + 5, MOPEN + 6, MOPEN + 7, MOPEN + 8, MOPEN + 9 -> {
val no: Int val no: Int
val save = save_se_T() val save = save_se_T()
@ -3937,8 +3934,8 @@ internal class RegExp {
private const val MULTI_MULT = 2 private const val MULTI_MULT = 2
/* /*
* Flags to be passed up and down. * Flags to be passed up and down.
*/ */
private const val HASWIDTH = 0x1 /* Known never to match null string. */ private const val HASWIDTH = 0x1 /* Known never to match null string. */
private const val SIMPLE = 0x2 /* Simple enough to be STAR/PLUS operand. */ private const val SIMPLE = 0x2 /* Simple enough to be STAR/PLUS operand. */
private const val SPSTART = 0x4 /* Starts with * or +. */ private const val SPSTART = 0x4 /* Starts with * or +. */
@ -3946,16 +3943,16 @@ internal class RegExp {
private const val WORST = 0 /* Worst case. */ private const val WORST = 0 /* Worst case. */
/* /*
* REGEXP_INRANGE contains all characters which are always special in a [] * REGEXP_INRANGE contains all characters which are always special in a []
* range after '\'. * range after '\'.
* REGEXP_ABBR contains all characters which act as abbreviations after '\'. * REGEXP_ABBR contains all characters which act as abbreviations after '\'.
* These are: * These are:
* \n - New line (NL). * \n - New line (NL).
* \r - Carriage Return (CR). * \r - Carriage Return (CR).
* \t - Tab (TAB). * \t - Tab (TAB).
* \e - Escape (ESC). * \e - Escape (ESC).
* \b - Backspace (Ctrl_H). * \b - Backspace (Ctrl_H).
*/ */
private const val REGEXP_INRANGE = "]^-n\\" private const val REGEXP_INRANGE = "]^-n\\"
private const val REGEXP_ABBR = "nrteb" private const val REGEXP_ABBR = "nrteb"
@ -4093,8 +4090,8 @@ internal class RegExp {
// private boolean can_f_submatch = false; /* true when submatch() can be used */ // private boolean can_f_submatch = false; /* true when submatch() can be used */
/* These pointers are used instead of reg_match and reg_mmatch for /* These pointers are used instead of reg_match and reg_mmatch for
* reg_submatch(). Needed for when the substitution string is an expression * reg_submatch(). Needed for when the substitution string is an expression
* that contains a call to substitute() and submatch(). */ * that contains a call to substitute() and submatch(). */
// private regmatch_T submatch_match; // private regmatch_T submatch_match;
// private regmmatch_T submatch_mmatch; // private regmmatch_T submatch_mmatch;
private val logger: VimLogger = injector.getLogger<RegExp>(RegExp::class.java) private val logger: VimLogger = injector.getLogger<RegExp>(RegExp::class.java)

View File

@ -39,8 +39,7 @@ internal class ShortcutConflictState : ApplicationUsagesCollector() {
} }
private fun getHandlersForShortcut(shortcut: KeyStroke): List<HandledModes> { private fun getHandlersForShortcut(shortcut: KeyStroke): List<HandledModes> {
val modes = VimPlugin.getKey().shortcutConflicts[shortcut] val modes = VimPlugin.getKey().shortcutConflicts[shortcut] ?: return listOf(HandledModes.NORMAL_UNDEFINED, HandledModes.INSERT_UNDEFINED, HandledModes.VISUAL_AND_SELECT_UNDEFINED)
?: return listOf(HandledModes.NORMAL_UNDEFINED, HandledModes.INSERT_UNDEFINED, HandledModes.VISUAL_AND_SELECT_UNDEFINED)
return when (modes) { return when (modes) {
is ShortcutOwnerInfo.AllModes -> { is ShortcutOwnerInfo.AllModes -> {

View File

@ -23,8 +23,7 @@ internal class VimscriptState : ApplicationUsagesCollector() {
return setOf( return setOf(
VIMSCRIPT.metric( VIMSCRIPT.metric(
SOURCED_FILES with sourcedFiles.size, SOURCED_FILES with sourcedFiles.size,
IDEAVIMRC_SIZE with (VimRcService.findIdeaVimRc()?.readLines()?.filter { !it.matches(Regex("\\s*\".*")) && it.isNotBlank() }?.size IDEAVIMRC_SIZE with (VimRcService.findIdeaVimRc()?.readLines()?.filter { !it.matches(Regex("\\s*\".*")) && it.isNotBlank() }?.size ?: -1),
?: -1),
EXTENSIONS_ENABLED_BY_SET with (PluginState.enabledExtensions - extensionsEnabledWithPlug).toList(), EXTENSIONS_ENABLED_BY_SET with (PluginState.enabledExtensions - extensionsEnabledWithPlug).toList(),
EXTENSIONS_ENABLED_BY_PLUG with extensionsEnabledWithPlug.toList(), EXTENSIONS_ENABLED_BY_PLUG with extensionsEnabledWithPlug.toList(),
IS_IDE_SPECIFIC_CONFIGURATION_USED with isIDESpecificConfigurationUsed, IS_IDE_SPECIFIC_CONFIGURATION_USED with isIDESpecificConfigurationUsed,

View File

@ -44,25 +44,18 @@ import static com.maddyhome.idea.vim.api.VimInjectorKt.injector;
* This panel displays text in a <code>more</code> like window. * This panel displays text in a <code>more</code> like window.
*/ */
public class ExOutputPanel extends JPanel { public class ExOutputPanel extends JPanel {
private final @NotNull private final @NotNull Editor myEditor;
Editor myEditor;
private final @NotNull private final @NotNull JLabel myLabel = new JLabel("more");
JLabel myLabel = new JLabel("more"); private final @NotNull JTextArea myText = new JTextArea();
private final @NotNull private final @NotNull JScrollPane myScrollPane =
JTextArea myText = new JTextArea();
private final @NotNull
JScrollPane myScrollPane =
new JBScrollPane(myText, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); new JBScrollPane(myText, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
private final @NotNull private final @NotNull ComponentAdapter myAdapter;
ComponentAdapter myAdapter;
private boolean myAtEnd = false; private boolean myAtEnd = false;
private int myLineHeight = 0; private int myLineHeight = 0;
private @Nullable private @Nullable JComponent myOldGlass = null;
JComponent myOldGlass = null; private @Nullable LayoutManager myOldLayout = null;
private @Nullable
LayoutManager myOldLayout = null;
private boolean myWasOpaque = false; private boolean myWasOpaque = false;
private boolean myActive = false; private boolean myActive = false;
@ -97,8 +90,7 @@ public class ExOutputPanel extends JPanel {
return UserDataManager.getVimMorePanel(editor) != null; return UserDataManager.getVimMorePanel(editor) != null;
} }
public static @NotNull public static @NotNull ExOutputPanel getInstance(@NotNull Editor editor) {
ExOutputPanel getInstance(@NotNull Editor editor) {
ExOutputPanel panel = UserDataManager.getVimMorePanel(editor); ExOutputPanel panel = UserDataManager.getVimMorePanel(editor);
if (panel == null) { if (panel == null) {
panel = new ExOutputPanel(editor); panel = new ExOutputPanel(editor);
@ -191,7 +183,7 @@ public class ExOutputPanel extends JPanel {
*/ */
private void activate() { private void activate() {
JRootPane root = SwingUtilities.getRootPane(myEditor.getContentComponent()); JRootPane root = SwingUtilities.getRootPane(myEditor.getContentComponent());
myOldGlass = (JComponent) root.getGlassPane(); myOldGlass = (JComponent)root.getGlassPane();
if (myOldGlass != null) { if (myOldGlass != null) {
myOldLayout = myOldGlass.getLayout(); myOldLayout = myOldGlass.getLayout();
myWasOpaque = myOldGlass.isOpaque(); myWasOpaque = myOldGlass.isOpaque();
@ -228,13 +220,14 @@ public class ExOutputPanel extends JPanel {
private void scrollHalfPage() { private void scrollHalfPage() {
double sa = myScrollPane.getVerticalScrollBar().getVisibleAmount() / 2.0; double sa = myScrollPane.getVerticalScrollBar().getVisibleAmount() / 2.0;
double offset = Math.ceil(sa / myLineHeight) * myLineHeight; double offset = Math.ceil(sa / myLineHeight) * myLineHeight;
scrollOffset((int) offset); scrollOffset((int)offset);
} }
private void handleEnter() { private void handleEnter() {
if (myAtEnd) { if (myAtEnd) {
close(); close();
} else { }
else {
scrollLine(); scrollLine();
} }
} }
@ -253,7 +246,8 @@ public class ExOutputPanel extends JPanel {
myScrollPane.getVerticalScrollBar().getMaximum() - myScrollPane.getVerticalScrollBar().getVisibleAmount()) { myScrollPane.getVerticalScrollBar().getMaximum() - myScrollPane.getVerticalScrollBar().getVisibleAmount()) {
myAtEnd = true; myAtEnd = true;
myLabel.setText(MessageHelper.message("hit.enter.or.type.command.to.continue")); myLabel.setText(MessageHelper.message("hit.enter.or.type.command.to.continue"));
} else { }
else {
myLabel.setText(MessageHelper.message("ex.output.panel.more")); myLabel.setText(MessageHelper.message("ex.output.panel.more"));
} }
myLabel.setFont(UiHelper.selectFont(myLabel.getText())); myLabel.setFont(UiHelper.selectFont(myLabel.getText()));
@ -284,7 +278,8 @@ public class ExOutputPanel extends JPanel {
if (!globalOptions(injector).isSet(OptionConstants.more)) { if (!globalOptions(injector).isSet(OptionConstants.more)) {
// FIX // FIX
scrollOffset(100000); scrollOffset(100000);
} else { }
else {
scrollOffset(0); scrollOffset(0);
} }
} }
@ -324,7 +319,8 @@ public class ExOutputPanel extends JPanel {
public void keyTyped(@NotNull KeyEvent e) { public void keyTyped(@NotNull KeyEvent e) {
if (myExOutputPanel.myAtEnd) { if (myExOutputPanel.myAtEnd) {
myExOutputPanel.close(e); myExOutputPanel.close(e);
} else { }
else {
switch (e.getKeyChar()) { switch (e.getKeyChar()) {
case ' ': case ' ':
myExOutputPanel.scrollPage(); myExOutputPanel.scrollPage();

View File

@ -145,7 +145,7 @@ public class ExEntryPanel extends JPanel {
if (!ApplicationManager.getApplication().isUnitTestMode()) { if (!ApplicationManager.getApplication().isUnitTestMode()) {
JRootPane root = SwingUtilities.getRootPane(parent); JRootPane root = SwingUtilities.getRootPane(parent);
if (root == null) return; if (root == null) return;
oldGlass = (JComponent) root.getGlassPane(); oldGlass = (JComponent)root.getGlassPane();
oldLayout = oldGlass.getLayout(); oldLayout = oldGlass.getLayout();
wasOpaque = oldGlass.isOpaque(); wasOpaque = oldGlass.isOpaque();
oldGlass.setLayout(null); oldGlass.setLayout(null);
@ -203,7 +203,8 @@ public class ExEntryPanel extends JPanel {
} }
entry.deactivate(); entry.deactivate();
} finally { }
finally {
// Make sure we hide the UI, especially if something goes wrong // Make sure we hide the UI, especially if something goes wrong
if (!ApplicationManager.getApplication().isUnitTestMode()) { if (!ApplicationManager.getApplication().isUnitTestMode()) {
@ -240,8 +241,7 @@ public class ExEntryPanel extends JPanel {
} }
} }
private final @NotNull private final @NotNull DocumentListener fontListener = new DocumentAdapter() {
DocumentListener fontListener = new DocumentAdapter() {
@Override @Override
protected void textChanged(@NotNull DocumentEvent e) { protected void textChanged(@NotNull DocumentEvent e) {
String text = entry.getActualText(); String text = entry.getActualText();
@ -252,8 +252,7 @@ public class ExEntryPanel extends JPanel {
} }
}; };
private final @NotNull private final @NotNull DocumentListener incSearchDocumentListener = new DocumentAdapter() {
DocumentListener incSearchDocumentListener = new DocumentAdapter() {
@Override @Override
protected void textChanged(@NotNull DocumentEvent e) { protected void textChanged(@NotNull DocumentEvent e) {
final Editor editor = entry.getEditor(); final Editor editor = entry.getEditor();
@ -297,15 +296,15 @@ public class ExEntryPanel extends JPanel {
final int matchOffset = SearchHighlightsHelper.updateIncsearchHighlights(editor, pattern, forwards, caretOffset, searchRange); final int matchOffset = SearchHighlightsHelper.updateIncsearchHighlights(editor, pattern, forwards, caretOffset, searchRange);
if (matchOffset != -1) { if (matchOffset != -1) {
new IjVimCaret(editor.getCaretModel().getPrimaryCaret()).moveToOffset(matchOffset); new IjVimCaret(editor.getCaretModel().getPrimaryCaret()).moveToOffset(matchOffset);
} else { }
else {
resetCaretOffset(editor); resetCaretOffset(editor);
} }
} }
} }
@Contract("null -> null") @Contract("null -> null")
private @Nullable private @Nullable Command getIncsearchCommand(@Nullable String commandText) {
Command getIncsearchCommand(@Nullable String commandText) {
if (commandText == null) return null; if (commandText == null) return null;
try { try {
final Command exCommand = VimscriptParser.INSTANCE.parseCommand(commandText); final Command exCommand = VimscriptParser.INSTANCE.parseCommand(commandText);
@ -313,7 +312,8 @@ public class ExEntryPanel extends JPanel {
if (exCommand instanceof SubstituteCommand) { if (exCommand instanceof SubstituteCommand) {
return exCommand; return exCommand;
} }
} catch (Exception e) { }
catch(Exception e) {
logger.warn("Cannot parse command for incsearch", e); logger.warn("Cannot parse command for incsearch", e);
} }
@ -353,13 +353,11 @@ public class ExEntryPanel extends JPanel {
* *
* @return The user entered text * @return The user entered text
*/ */
public @NotNull public @NotNull String getText() {
String getText() {
return entry.getActualText(); return entry.getActualText();
} }
public @NotNull public @NotNull ExTextField getEntry() {
ExTextField getEntry() {
return entry; return entry;
} }
@ -412,7 +410,7 @@ public class ExEntryPanel extends JPanel {
if (parent == null) return; if (parent == null) return;
Container scroll = SwingUtilities.getAncestorOfClass(JScrollPane.class, parent); Container scroll = SwingUtilities.getAncestorOfClass(JScrollPane.class, parent);
int height = (int) getPreferredSize().getHeight(); int height = (int)getPreferredSize().getHeight();
if (scroll != null) { if (scroll != null) {
Rectangle bounds = scroll.getBounds(); Rectangle bounds = scroll.getBounds();
bounds.translate(0, scroll.getHeight() - height); bounds.translate(0, scroll.getHeight() - height);
@ -432,12 +430,9 @@ public class ExEntryPanel extends JPanel {
private int count; private int count;
// UI stuff // UI stuff
private @Nullable private @Nullable JComponent parent;
JComponent parent; private final @NotNull JLabel label;
private final @NotNull private final @NotNull ExTextField entry;
JLabel label;
private final @NotNull
ExTextField entry;
private JComponent oldGlass; private JComponent oldGlass;
private LayoutManager oldLayout; private LayoutManager oldLayout;
private boolean wasOpaque; private boolean wasOpaque;
@ -447,8 +442,7 @@ public class ExEntryPanel extends JPanel {
private int horizontalOffset; private int horizontalOffset;
private int caretOffset; private int caretOffset;
private final @NotNull private final @NotNull ComponentListener resizePanelListener = new ComponentAdapter() {
ComponentListener resizePanelListener = new ComponentAdapter() {
@Override @Override
public void componentResized(ComponentEvent e) { public void componentResized(ComponentEvent e) {
positionPanel(); positionPanel();

View File

@ -47,8 +47,7 @@ import static java.lang.Math.*;
*/ */
public class ExTextField extends JTextField { public class ExTextField extends JTextField {
public static final @NonNls public static final @NonNls String KEYMAP_NAME = "ex";
String KEYMAP_NAME = "ex";
public boolean useHandleKeyFromEx = true; public boolean useHandleKeyFromEx = true;
@ -142,7 +141,7 @@ public class ExTextField extends JTextField {
/** /**
* Stores the current text for use in filtering history. Required for scrolling through multiple history entries * Stores the current text for use in filtering history. Required for scrolling through multiple history entries
* <p> *
* Called whenever the text is changed, either by typing, or by special characters altering the text (e.g. Delete) * Called whenever the text is changed, either by typing, or by special characters altering the text (e.g. Delete)
*/ */
void saveLastEntry() { void saveLastEntry() {
@ -162,7 +161,8 @@ public class ExTextField extends JTextField {
String txt; String txt;
if (i == history.size()) { if (i == history.size()) {
txt = lastEntry; txt = lastEntry;
} else { }
else {
HistoryEntry entry = history.get(i); HistoryEntry entry = history.get(i);
txt = entry.getEntry(); txt = entry.getEntry();
} }
@ -176,12 +176,14 @@ public class ExTextField extends JTextField {
} }
VimPlugin.indicateError(); VimPlugin.indicateError();
} else { }
else {
histIndex += dir; histIndex += dir;
String txt; String txt;
if (histIndex == history.size()) { if (histIndex == history.size()) {
txt = lastEntry; txt = lastEntry;
} else { }
else {
HistoryEntry entry = history.get(histIndex); HistoryEntry entry = history.get(histIndex);
txt = entry.getEntry(); txt = entry.getEntry();
} }
@ -254,7 +256,8 @@ public class ExTextField extends JTextField {
// dispatch to ExEntryPanel#handleKey and if it's processed, mark the event as consumed. // dispatch to ExEntryPanel#handleKey and if it's processed, mark the event as consumed.
if (currentAction != null) { if (currentAction != null) {
currentAction.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, String.valueOf(c), modifiers)); currentAction.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, String.valueOf(c), modifiers));
} else { }
else {
KeyEvent event = new KeyEvent(this, keyChar != KeyEvent.CHAR_UNDEFINED ? KeyEvent.KEY_TYPED : KeyEvent event = new KeyEvent(this, keyChar != KeyEvent.CHAR_UNDEFINED ? KeyEvent.KEY_TYPED :
(stroke.isOnKeyRelease() ? KeyEvent.KEY_RELEASED : KeyEvent.KEY_PRESSED), (stroke.isOnKeyRelease() ? KeyEvent.KEY_RELEASED : KeyEvent.KEY_PRESSED),
(new Date()).getTime(), modifiers, keyCode, c); (new Date()).getTime(), modifiers, keyCode, c);
@ -262,7 +265,7 @@ public class ExTextField extends JTextField {
useHandleKeyFromEx = false; useHandleKeyFromEx = false;
try { try {
super.processKeyEvent(event); super.processKeyEvent(event);
} finally { }finally {
useHandleKeyFromEx = true; useHandleKeyFromEx = true;
} }
} }
@ -282,8 +285,7 @@ public class ExTextField extends JTextField {
* @return the default model implementation * @return the default model implementation
*/ */
@Override @Override
protected @NotNull protected @NotNull Document createDefaultModel() {
Document createDefaultModel() {
return new ExDocument(); return new ExDocument();
} }
@ -293,7 +295,8 @@ public class ExTextField extends JTextField {
void escape() { void escape() {
if (currentAction != null) { if (currentAction != null) {
clearCurrentAction(); clearCurrentAction();
} else { }
else {
cancel(); cancel();
} }
} }
@ -321,7 +324,7 @@ public class ExTextField extends JTextField {
/** /**
* Text to show while composing a digraph or inserting a literal or register * Text to show while composing a digraph or inserting a literal or register
* <p> *
* The prompt character is inserted directly into the text of the text field, rather than drawn over the top of the * The prompt character is inserted directly into the text of the text field, rather than drawn over the top of the
* current character. When the action has been completed, the new character(s) are either inserted or overwritten, * current character. When the action has been completed, the new character(s) are either inserted or overwritten,
* depending on the insert/overwrite status of the text field. This mimics Vim's behaviour. * depending on the insert/overwrite status of the text field. This mimics Vim's behaviour.
@ -360,7 +363,7 @@ public class ExTextField extends JTextField {
} }
private void setInsertMode() { private void setInsertMode() {
ExDocument doc = (ExDocument) getDocument(); ExDocument doc = (ExDocument)getDocument();
if (doc.isOverwrite()) { if (doc.isOverwrite()) {
doc.toggleInsertReplace(); doc.toggleInsertReplace();
} }
@ -368,7 +371,7 @@ public class ExTextField extends JTextField {
} }
void toggleInsertReplace() { void toggleInsertReplace() {
ExDocument doc = (ExDocument) getDocument(); ExDocument doc = (ExDocument)getDocument();
doc.toggleInsertReplace(); doc.toggleInsertReplace();
resetCaret(); resetCaret();
} }
@ -376,11 +379,13 @@ public class ExTextField extends JTextField {
private void resetCaret() { private void resetCaret() {
if (getCaretPosition() == super.getText().length() || currentActionPromptCharacterOffset == super.getText().length() - 1) { if (getCaretPosition() == super.getText().length() || currentActionPromptCharacterOffset == super.getText().length() - 1) {
setNormalModeCaret(); setNormalModeCaret();
} else { }
ExDocument doc = (ExDocument) getDocument(); else {
ExDocument doc = (ExDocument)getDocument();
if (doc.isOverwrite()) { if (doc.isOverwrite()) {
setReplaceModeCaret(); setReplaceModeCaret();
} else { }
else {
setInsertModeCaret(); setInsertModeCaret();
} }
} }
@ -475,19 +480,21 @@ public class ExTextField extends JTextField {
final Area area = new Area(new Rectangle2D.Double(r.getX(), r.getY(), caretWidth, r.getHeight())); final Area area = new Area(new Rectangle2D.Double(r.getX(), r.getY(), caretWidth, r.getHeight()));
area.subtract(new Area(new Rectangle2D.Double(r.getX() + outlineThickness, r.getY() + outlineThickness, caretWidth - (2 * outlineThickness), r.getHeight() - (2 * outlineThickness)))); area.subtract(new Area(new Rectangle2D.Double(r.getX() + outlineThickness, r.getY() + outlineThickness, caretWidth - (2 * outlineThickness), r.getHeight() - (2 * outlineThickness))));
g2d.fill(area); g2d.fill(area);
} else { }
else {
final double caretHeight = getCaretHeight(r.getHeight()); final double caretHeight = getCaretHeight(r.getHeight());
final double caretWidth = getCaretWidth(fm, r.getX(), thickness); final double caretWidth = getCaretWidth(fm, r.getX(), thickness);
g2d.fill(new Rectangle2D.Double(r.getX(), r.getY() + r.getHeight() - caretHeight, caretWidth, caretHeight)); g2d.fill(new Rectangle2D.Double(r.getX(), r.getY() + r.getHeight() - caretHeight, caretWidth, caretHeight));
} }
} finally { }
finally {
g2d.dispose(); g2d.dispose();
} }
} }
/** /**
* Updates the bounds of the caret and repaints those bounds. * Updates the bounds of the caret and repaints those bounds.
* <p> *
* This method is not guaranteed to be called before paint(). The bounds are for use by repaint(). * This method is not guaranteed to be called before paint(). The bounds are for use by repaint().
* *
* @param r The current location of the caret, usually provided by MapToView. The x and y appear to be the upper * @param r The current location of the caret, usually provided by MapToView. The x and y appear to be the upper
@ -505,21 +512,21 @@ public class ExTextField extends JTextField {
final FontMetrics fm = getComponent().getFontMetrics(getComponent().getFont()); final FontMetrics fm = getComponent().getFontMetrics(getComponent().getFont());
x = r.x; x = r.x;
y = r.y; y = r.y;
width = (int) ceil(getCaretWidth(fm, r.x, 100)) + 1; width = (int)ceil(getCaretWidth(fm, r.x, 100)) + 1;
height = r.height; height = r.height;
repaint(); repaint();
} }
} }
private @Nullable private @Nullable Rectangle2D modelToView(int dot) {
Rectangle2D modelToView(int dot) {
if (dot > getComponent().getDocument().getLength()) { if (dot > getComponent().getDocument().getLength()) {
return null; return null;
} }
try { try {
return getComponent().getUI().modelToView2D(getComponent(), dot, getDotBias()); return getComponent().getUI().modelToView2D(getComponent(), dot, getDotBias());
} catch (BadLocationException e) { }
catch (BadLocationException e) {
return null; return null;
} }
} }
@ -532,13 +539,15 @@ public class ExTextField extends JTextField {
final Rectangle2D r = modelToView(getDot() + 1); final Rectangle2D r = modelToView(getDot() + 1);
if (r != null) { if (r != null) {
width = r.getX() - dotX; width = r.getX() - dotX;
} else { }
else {
char c = ' '; char c = ' ';
try { try {
if (getDot() < getComponent().getDocument().getLength()) { if (getDot() < getComponent().getDocument().getLength()) {
c = getComponent().getText(getDot(), 1).charAt(0); c = getComponent().getText(getDot(), 1).charAt(0);
} }
} catch (BadLocationException e) { }
catch (BadLocationException e) {
// Ignore // Ignore
} }
width = fm.charWidth(c); width = fm.charWidth(c);
@ -556,8 +565,7 @@ public class ExTextField extends JTextField {
} }
@TestOnly @TestOnly
public @NonNls public @NonNls String getCaretShape() {
String getCaretShape() {
CommandLineCaret caret = (CommandLineCaret) getCaret(); CommandLineCaret caret = (CommandLineCaret) getCaret();
return String.format("%s %d", caret.mode, caret.thickness); return String.format("%s %d", caret.mode, caret.thickness);
} }
@ -568,8 +576,7 @@ public class ExTextField extends JTextField {
private String actualText; private String actualText;
private List<HistoryEntry> history; private List<HistoryEntry> history;
private int histIndex = 0; private int histIndex = 0;
private @Nullable private @Nullable MultiStepAction currentAction;
MultiStepAction currentAction;
private char currentActionPromptCharacter; private char currentActionPromptCharacter;
private int currentActionPromptCharacterOffset = -1; private int currentActionPromptCharacterOffset = -1;

View File

@ -37,15 +37,11 @@ internal class GetFunctionHandler : FunctionHandler() {
return when (container) { return when (container) {
is VimList -> { is VimList -> {
val idx = argumentValues[1].evaluate(editor, context, vimContext).asDouble().toInt() val idx = argumentValues[1].evaluate(editor, context, vimContext).asDouble().toInt()
container.values.getOrElse(idx) { container.values.getOrElse(idx) { argumentValues.getOrNull(2)?.evaluate(editor, context, vimContext) ?: VimInt(-1) }
argumentValues.getOrNull(2)?.evaluate(editor, context, vimContext) ?: VimInt(-1)
}
} }
is VimDictionary -> { is VimDictionary -> {
val key = argumentValues[1].evaluate(editor, context, vimContext).asString() val key = argumentValues[1].evaluate(editor, context, vimContext).asString()
container.dictionary.getOrElse(VimString(key)) { container.dictionary.getOrElse(VimString(key)) { argumentValues.getOrNull(2)?.evaluate(editor, context, vimContext) ?: VimInt(0) }
argumentValues.getOrNull(2)?.evaluate(editor, context, vimContext) ?: VimInt(0)
}
} }
is VimBlob, is VimFuncref -> throw ExException("Blobs and Funcref are not supported as an argument for get(). If you need it, request support in YouTrack") is VimBlob, is VimFuncref -> throw ExException("Blobs and Funcref are not supported as an argument for get(). If you need it, request support in YouTrack")
else -> throw ExException("E896: Argument of get() must be a List, Dictionary or Blob") else -> throw ExException("E896: Argument of get() must be a List, Dictionary or Blob")

View File

@ -29,7 +29,6 @@ internal object IdeaRefactorModeHelper {
fun keepMode() = fun keepMode() =
injector.globalOptions().hasValue(IjOptionConstants.idearefactormode, IjOptionConstants.idearefactormode_keep) injector.globalOptions().hasValue(IjOptionConstants.idearefactormode, IjOptionConstants.idearefactormode_keep)
fun selectMode() = fun selectMode() =
injector.globalOptions().hasValue(IjOptionConstants.idearefactormode, IjOptionConstants.idearefactormode_select) injector.globalOptions().hasValue(IjOptionConstants.idearefactormode, IjOptionConstants.idearefactormode_select)

View File

@ -17,7 +17,6 @@ import org.antlr.v4.runtime.Recognizer
internal class IdeavimErrorListener : BaseErrorListener() { internal class IdeavimErrorListener : BaseErrorListener() {
private val logger = logger<IdeavimErrorListener>() private val logger = logger<IdeavimErrorListener>()
companion object { companion object {
val testLogger = mutableListOf<String>() val testLogger = mutableListOf<String>()
} }

View File

@ -219,8 +219,7 @@ internal object ExpressionVisitor : VimscriptBaseVisitor<Expression>() {
} }
override fun visitOptionExpression(ctx: OptionExpressionContext): Expression { override fun visitOptionExpression(ctx: OptionExpressionContext): Expression {
val result = OptionExpression(Scope.getByValue(ctx.option()?.text ?: "") val result = OptionExpression(Scope.getByValue(ctx.option()?.text ?: "") ?: Scope.GLOBAL_VARIABLE, ctx.option().optionName().text)
?: Scope.GLOBAL_VARIABLE, ctx.option().optionName().text)
result.originalString = ctx.text result.originalString = ctx.text
return result return result
} }

View File

@ -602,7 +602,7 @@ class MotionActionTest : VimTestCase() {
doTest(keys, before, after, VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE) doTest(keys, before, after, VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE)
} }
// VIM-2733 // VIM-2733
@Test @Test
fun testDeleteOuterQuoteEmptyString2() { fun testDeleteOuterQuoteEmptyString2() {
val keys = listOf("da'") val keys = listOf("da'")
@ -653,7 +653,7 @@ class MotionActionTest : VimTestCase() {
doTest(keys, before, after, VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE) doTest(keys, before, after, VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE)
} }
// VIM-1427 // VIM-1427
@Test @Test
fun testDeleteOuterTagWithCount() { fun testDeleteOuterTagWithCount() {
val keys = listOf("d2at") val keys = listOf("d2at")

View File

@ -23,7 +23,7 @@ zl Move the view on the text [count] characters to the
class ScrollColumnLeftActionTest : VimTestCase() { class ScrollColumnLeftActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.DIFFERENT) @TestWithoutNeovim(SkipNeovimReason.DIFFERENT)
@Test @Test
fun `test scrolls column to left`() { fun`test scrolls column to left`() {
configureByColumns(200) configureByColumns(200)
typeText("100|", "zl") typeText("100|", "zl")
assertPosition(0, 99) assertPosition(0, 99)
@ -32,7 +32,7 @@ class ScrollColumnLeftActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.DIFFERENT) @TestWithoutNeovim(SkipNeovimReason.DIFFERENT)
@Test @Test
fun `test scrolls column to left with zRight`() { fun`test scrolls column to left with zRight`() {
configureByColumns(200) configureByColumns(200)
typeText("100|", "z<Right>") typeText("100|", "z<Right>")
assertPosition(0, 99) assertPosition(0, 99)
@ -41,7 +41,7 @@ class ScrollColumnLeftActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.DIFFERENT) @TestWithoutNeovim(SkipNeovimReason.DIFFERENT)
@Test @Test
fun `test scroll first column to left moves cursor`() { fun`test scroll first column to left moves cursor`() {
configureByColumns(200) configureByColumns(200)
typeText("100|", "zs", "zl") typeText("100|", "zs", "zl")
assertPosition(0, 100) assertPosition(0, 100)
@ -50,7 +50,7 @@ class ScrollColumnLeftActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.DIFFERENT) @TestWithoutNeovim(SkipNeovimReason.DIFFERENT)
@Test @Test
fun `test scrolls count columns to left`() { fun`test scrolls count columns to left`() {
configureByColumns(200) configureByColumns(200)
typeText("100|", "10zl") typeText("100|", "10zl")
assertPosition(0, 99) assertPosition(0, 99)
@ -59,7 +59,7 @@ class ScrollColumnLeftActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.DIFFERENT) @TestWithoutNeovim(SkipNeovimReason.DIFFERENT)
@Test @Test
fun `test scrolls count columns to left with zRight`() { fun`test scrolls count columns to left with zRight`() {
configureByColumns(200) configureByColumns(200)
typeText("100|", "10z<Right>") typeText("100|", "10z<Right>")
assertPosition(0, 99) assertPosition(0, 99)
@ -68,7 +68,7 @@ class ScrollColumnLeftActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.DIFFERENT) @TestWithoutNeovim(SkipNeovimReason.DIFFERENT)
@Test @Test
fun `test scrolls column to left with sidescrolloff moves cursor`() { fun`test scrolls column to left with sidescrolloff moves cursor`() {
configureByColumns(200) configureByColumns(200)
enterCommand("set sidescrolloff=10") enterCommand("set sidescrolloff=10")
typeText("100|", "zs", "zl") typeText("100|", "zs", "zl")
@ -78,7 +78,7 @@ class ScrollColumnLeftActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.DIFFERENT) @TestWithoutNeovim(SkipNeovimReason.DIFFERENT)
@Test @Test
fun `test scroll column to left ignores sidescroll`() { fun`test scroll column to left ignores sidescroll`() {
configureByColumns(200) configureByColumns(200)
enterCommand("set sidescroll=10") enterCommand("set sidescroll=10")
typeText("100|") typeText("100|")
@ -95,7 +95,7 @@ class ScrollColumnLeftActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.DIFFERENT) @TestWithoutNeovim(SkipNeovimReason.DIFFERENT)
@Test @Test
fun `test scroll column to left on last page enters virtual space`() { fun`test scroll column to left on last page enters virtual space`() {
configureByColumns(200) configureByColumns(200)
typeText("200|", "ze", "zl") typeText("200|", "ze", "zl")
assertPosition(0, 199) assertPosition(0, 199)
@ -111,7 +111,7 @@ class ScrollColumnLeftActionTest : VimTestCase() {
@VimBehaviorDiffers(description = "Vim has virtual space at end of line") @VimBehaviorDiffers(description = "Vim has virtual space at end of line")
@TestWithoutNeovim(SkipNeovimReason.DIFFERENT) @TestWithoutNeovim(SkipNeovimReason.DIFFERENT)
@Test @Test
fun `test scroll columns to left on last page does not have full virtual space`() { fun`test scroll columns to left on last page does not have full virtual space`() {
configureByColumns(200) configureByColumns(200)
typeText("200|", "ze", "50zl") typeText("200|", "ze", "50zl")
assertPosition(0, 199) assertPosition(0, 199)
@ -122,7 +122,7 @@ class ScrollColumnLeftActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.DIFFERENT) @TestWithoutNeovim(SkipNeovimReason.DIFFERENT)
@Test @Test
fun `test scroll column to left correctly scrolls inline inlay associated with preceding text`() { fun`test scroll column to left correctly scrolls inline inlay associated with preceding text`() {
configureByColumns(200) configureByColumns(200)
addInlay(67, true, 5) addInlay(67, true, 5)
typeText("100|") typeText("100|")
@ -136,7 +136,7 @@ class ScrollColumnLeftActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.DIFFERENT) @TestWithoutNeovim(SkipNeovimReason.DIFFERENT)
@Test @Test
fun `test scroll column to left correctly scrolls inline inlay associated with following text`() { fun`test scroll column to left correctly scrolls inline inlay associated with following text`() {
configureByColumns(200) configureByColumns(200)
addInlay(67, false, 5) addInlay(67, false, 5)
typeText("100|") typeText("100|")

View File

@ -23,7 +23,7 @@ zh Move the view on the text [count] characters to the
class ScrollColumnRightActionTest : VimTestCase() { class ScrollColumnRightActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.SCROLL) @TestWithoutNeovim(SkipNeovimReason.SCROLL)
@Test @Test
fun `test scrolls column to right`() { fun`test scrolls column to right`() {
configureByColumns(200) configureByColumns(200)
typeText("100|", "zh") typeText("100|", "zh")
assertPosition(0, 99) assertPosition(0, 99)
@ -32,7 +32,7 @@ class ScrollColumnRightActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.SCROLL) @TestWithoutNeovim(SkipNeovimReason.SCROLL)
@Test @Test
fun `test scrolls column to right with zLeft`() { fun`test scrolls column to right with zLeft`() {
configureByColumns(200) configureByColumns(200)
typeText("100|", "z<Left>") typeText("100|", "z<Left>")
assertPosition(0, 99) assertPosition(0, 99)
@ -42,7 +42,7 @@ class ScrollColumnRightActionTest : VimTestCase() {
@VimBehaviorDiffers(description = "Vim has virtual space at the end of line. IdeaVim will scroll up to length of longest line") @VimBehaviorDiffers(description = "Vim has virtual space at the end of line. IdeaVim will scroll up to length of longest line")
@TestWithoutNeovim(SkipNeovimReason.SCROLL) @TestWithoutNeovim(SkipNeovimReason.SCROLL)
@Test @Test
fun `test scroll last column to right moves cursor 1`() { fun`test scroll last column to right moves cursor 1`() {
configureByColumns(200) configureByColumns(200)
typeText("$") typeText("$")
// Assert we got initial scroll correct // Assert we got initial scroll correct
@ -57,7 +57,7 @@ class ScrollColumnRightActionTest : VimTestCase() {
@VimBehaviorDiffers(description = "Vim has virtual space at the end of line. IdeaVim will scroll up to length of longest line") @VimBehaviorDiffers(description = "Vim has virtual space at the end of line. IdeaVim will scroll up to length of longest line")
@TestWithoutNeovim(SkipNeovimReason.SCROLL) @TestWithoutNeovim(SkipNeovimReason.SCROLL)
@Test @Test
fun `test scroll last column to right moves cursor 2`() { fun`test scroll last column to right moves cursor 2`() {
configureByText( configureByText(
buildString { buildString {
repeat(300) { append("0") } repeat(300) { append("0") }
@ -78,7 +78,7 @@ class ScrollColumnRightActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.SCROLL) @TestWithoutNeovim(SkipNeovimReason.SCROLL)
@Test @Test
fun `test scrolls count columns to right`() { fun`test scrolls count columns to right`() {
configureByColumns(200) configureByColumns(200)
typeText("100|", "10zh") typeText("100|", "10zh")
assertPosition(0, 99) assertPosition(0, 99)
@ -87,7 +87,7 @@ class ScrollColumnRightActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.SCROLL) @TestWithoutNeovim(SkipNeovimReason.SCROLL)
@Test @Test
fun `test scrolls count columns to right with zLeft`() { fun`test scrolls count columns to right with zLeft`() {
configureByColumns(200) configureByColumns(200)
typeText("100|", "10z<Left>") typeText("100|", "10z<Left>")
assertPosition(0, 99) assertPosition(0, 99)
@ -96,7 +96,7 @@ class ScrollColumnRightActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.SCROLL) @TestWithoutNeovim(SkipNeovimReason.SCROLL)
@Test @Test
fun `test scrolls column to right with sidescrolloff moves cursor`() { fun`test scrolls column to right with sidescrolloff moves cursor`() {
configureByColumns(200) configureByColumns(200)
enterCommand("set sidescrolloff=10") enterCommand("set sidescrolloff=10")
typeText("100|", "ze", "zh") typeText("100|", "ze", "zh")
@ -106,7 +106,7 @@ class ScrollColumnRightActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.SCROLL) @TestWithoutNeovim(SkipNeovimReason.SCROLL)
@Test @Test
fun `test scroll column to right ignores sidescroll`() { fun`test scroll column to right ignores sidescroll`() {
configureByColumns(200) configureByColumns(200)
enterCommand("set sidescroll=10") enterCommand("set sidescroll=10")
typeText("100|") typeText("100|")
@ -122,7 +122,7 @@ class ScrollColumnRightActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.SCROLL) @TestWithoutNeovim(SkipNeovimReason.SCROLL)
@Test @Test
fun `test scroll column to right on first page does nothing`() { fun`test scroll column to right on first page does nothing`() {
configureByColumns(200) configureByColumns(200)
typeText("10|", "zh") typeText("10|", "zh")
assertPosition(0, 9) assertPosition(0, 9)
@ -131,7 +131,7 @@ class ScrollColumnRightActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.SCROLL) @TestWithoutNeovim(SkipNeovimReason.SCROLL)
@Test @Test
fun `test scroll column to right correctly scrolls inline inlay associated with preceding text`() { fun`test scroll column to right correctly scrolls inline inlay associated with preceding text`() {
configureByColumns(200) configureByColumns(200)
addInlay(130, true, 5) addInlay(130, true, 5)
typeText("100|") typeText("100|")
@ -147,7 +147,7 @@ class ScrollColumnRightActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.SCROLL) @TestWithoutNeovim(SkipNeovimReason.SCROLL)
@Test @Test
fun `test scroll column to right correctly scrolls inline inlay associated with following text`() { fun`test scroll column to right correctly scrolls inline inlay associated with following text`() {
configureByColumns(200) configureByColumns(200)
addInlay(130, false, 5) addInlay(130, false, 5)
typeText("100|") typeText("100|")
@ -163,7 +163,7 @@ class ScrollColumnRightActionTest : VimTestCase() {
@TestWithoutNeovim(SkipNeovimReason.SCROLL) @TestWithoutNeovim(SkipNeovimReason.SCROLL)
@Test @Test
fun `test scroll column to right with preceding inline inlay moves cursor at end of screen`() { fun`test scroll column to right with preceding inline inlay moves cursor at end of screen`() {
configureByColumns(200) configureByColumns(200)
addInlay(90, false, 5) addInlay(90, false, 5)
typeText("100|", "ze", "zh") typeText("100|", "ze", "zh")

View File

@ -45,7 +45,7 @@ class Editor(
get() = callJs("component.getEditor().getCaretModel().getOffset()", runInEdt = true) get() = callJs("component.getEditor().getCaretModel().getOffset()", runInEdt = true)
val isBlockCursor: Boolean val isBlockCursor: Boolean
// get() = callJs("component.getEditor().getSettings().isBlockCursor()", true) // get() = callJs("component.getEditor().getSettings().isBlockCursor()", true)
// Doesn't work at the moment because remote robot can't resolve classes from a plugin classloader // Doesn't work at the moment because remote robot can't resolve classes from a plugin classloader
get() = callJs("com.maddyhome.idea.vim.helper.CaretVisualAttributesHelperKt.hasBlockOrUnderscoreCaret(component.getEditor())", true) get() = callJs("com.maddyhome.idea.vim.helper.CaretVisualAttributesHelperKt.hasBlockOrUnderscoreCaret(component.getEditor())", true)

View File

@ -31,7 +31,6 @@ fun uiTest(testName: String = "test_${System.currentTimeMillis()}", url: String
throw e throw e
} }
} }
private val client by lazy { OkHttpClient() } private val client by lazy { OkHttpClient() }
private fun BufferedImage.save(name: String) { private fun BufferedImage.save(name: String) {
val bytes = ByteArrayOutputStream().use { b -> val bytes = ByteArrayOutputStream().use { b ->

View File

@ -33,8 +33,7 @@ public class MotionShiftDownAction : ShiftedArrowKeyHandler(false) {
} }
is Motion.AbsoluteOffset -> caret.moveToOffset(vertical.offset) is Motion.AbsoluteOffset -> caret.moveToOffset(vertical.offset)
is Motion.NoMotion -> { is Motion.NoMotion -> {}
}
is Motion.Error -> injector.messages.indicateError() is Motion.Error -> injector.messages.indicateError()
} }
} }

View File

@ -33,8 +33,7 @@ public class MotionShiftUpAction : ShiftedArrowKeyHandler(false) {
} }
is Motion.AbsoluteOffset -> caret.moveToOffset(vertical.offset) is Motion.AbsoluteOffset -> caret.moveToOffset(vertical.offset)
is Motion.NoMotion -> { is Motion.NoMotion -> {}
}
is Motion.Error -> injector.messages.indicateError() is Motion.Error -> injector.messages.indicateError()
} }
} }

View File

@ -245,12 +245,10 @@ public fun VimEditor.getText(range: TextRange): String {
public fun VimEditor.getOffset(line: Int, column: Int): Int { public fun VimEditor.getOffset(line: Int, column: Int): Int {
return bufferPositionToOffset(BufferPosition(line, column)) return bufferPositionToOffset(BufferPosition(line, column))
} }
public fun VimEditor.getLineBuffer(line: Int): CharBuffer { public fun VimEditor.getLineBuffer(line: Int): CharBuffer {
val start: Int = getLineStartOffset(line) val start: Int = getLineStartOffset(line)
return CharBuffer.wrap(text(), start, start + getLineEndOffset(line, true) - getLineStartOffset(line)) return CharBuffer.wrap(text(), start, start + getLineEndOffset(line, true) - getLineStartOffset(line))
} }
public fun VimEditor.anyNonWhitespace(offset: Int, dir: Int): Boolean { public fun VimEditor.anyNonWhitespace(offset: Int, dir: Int): Boolean {
val start: Int val start: Int
val end: Int val end: Int

View File

@ -94,7 +94,6 @@ public interface VimChangeGroup {
operatorArguments: OperatorArguments, operatorArguments: OperatorArguments,
saveToRegister: Boolean = true, saveToRegister: Boolean = true,
): Boolean ): Boolean
public fun changeCharacters(editor: VimEditor, caret: VimCaret, operatorArguments: OperatorArguments): Boolean public fun changeCharacters(editor: VimEditor, caret: VimCaret, operatorArguments: OperatorArguments): Boolean
public fun changeEndOfLine(editor: VimEditor, caret: VimCaret, count: Int, operatorArguments: OperatorArguments): Boolean public fun changeEndOfLine(editor: VimEditor, caret: VimCaret, count: Int, operatorArguments: OperatorArguments): Boolean

View File

@ -178,8 +178,7 @@ public abstract class VimChangeGroupBase : VimChangeGroup {
val startOffsets = updatedRange.startOffsets val startOffsets = updatedRange.startOffsets
val endOffsets = updatedRange.endOffsets val endOffsets = updatedRange.endOffsets
for (i in updatedRange.size() - 1 downTo 0) { for (i in updatedRange.size() - 1 downTo 0) {
val (newRange, _) = editor.search(startOffsets[i].offset to endOffsets[i].offset, editor, LineDeleteShift.NL_ON_END) val (newRange, _) = editor.search(startOffsets[i].offset to endOffsets[i].offset, editor, LineDeleteShift.NL_ON_END) ?: continue
?: continue
editor.deleteString(TextRange(newRange.first.point, newRange.second.point)) editor.deleteString(TextRange(newRange.first.point, newRange.second.point))
} }
if (type != null) { if (type != null) {

View File

@ -16,7 +16,6 @@ public abstract class VimCommandGroupBase : VimCommandGroup {
public companion object { public companion object {
private const val overridePrefix = "!" private const val overridePrefix = "!"
} }
private var aliases = HashMap<String, CommandAlias>() private var aliases = HashMap<String, CommandAlias>()
override fun isAlias(command: String): Boolean { override fun isAlias(command: String): Boolean {

View File

@ -84,8 +84,7 @@ public abstract class VimDigraphGroupBase() : VimDigraphGroup {
return true return true
} }
private val defaultDigraphs = charArrayOf( private val defaultDigraphs = charArrayOf( /*
/*
'N', 'U', // 0 ^@ 'N', 'U', // 0 ^@
'S', 'H', // 1 ^A 'S', 'H', // 1 ^A
'S', 'X', // 2 ^B 'S', 'X', // 2 ^B

View File

@ -13,7 +13,6 @@ import com.maddyhome.idea.vim.mark.Jump
public abstract class VimJumpServiceBase : VimJumpService { public abstract class VimJumpServiceBase : VimJumpService {
@JvmField @JvmField
protected val jumps: MutableList<Jump> = ArrayList() // todo should it be mutable? protected val jumps: MutableList<Jump> = ArrayList() // todo should it be mutable?
@JvmField @JvmField
protected var jumpSpot: Int = -1 protected var jumpSpot: Int = -1

View File

@ -52,8 +52,7 @@ public abstract class VimOptionGroupBase : VimOptionGroup {
NumberOption(OptionConstants.scroll, "scr", 0), NumberOption(OptionConstants.scroll, "scr", 0),
NumberOption(OptionConstants.scrolloff, "so", 0), NumberOption(OptionConstants.scrolloff, "so", 0),
StringOption(OptionConstants.selection, "sel", "inclusive", isList = false, setOf("old", "inclusive", "exclusive")), StringOption(OptionConstants.selection, "sel", "inclusive", isList = false, setOf("old", "inclusive", "exclusive")),
StringOption(OptionConstants.shell, "sh", if (injector.systemInfoService.isWindows) "cmd.exe" else System.getenv("SHELL") StringOption(OptionConstants.shell, "sh", if (injector.systemInfoService.isWindows) "cmd.exe" else System.getenv("SHELL") ?: "sh"),
?: "sh"),
StringOption(OptionConstants.shellxescape, "sxe", if (injector.systemInfoService.isWindows) "\"&|<>()@^" else "", isList = false), StringOption(OptionConstants.shellxescape, "sxe", if (injector.systemInfoService.isWindows) "\"&|<>()@^" else "", isList = false),
ToggleOption(OptionConstants.showcmd, "sc", true), ToggleOption(OptionConstants.showcmd, "sc", true),
ToggleOption(OptionConstants.showmode, "smd", true), ToggleOption(OptionConstants.showmode, "smd", true),

View File

@ -52,7 +52,7 @@ public interface VimSearchHelper {
*/ */
public fun findPreviousCamelStart(chars: CharSequence, endIndex: Int, count: Int): Int? public fun findPreviousCamelStart(chars: CharSequence, endIndex: Int, count: Int): Int?
/** /**
* @param chars the char sequence to search in * @param chars the char sequence to search in
* @param startIndex the start index (inclusive) * @param startIndex the start index (inclusive)
* @param count search for the count-th occurrence * @param count search for the count-th occurrence

View File

@ -201,7 +201,6 @@ public abstract class VimSearchHelperBase : VimSearchHelper {
} }
return res return res
} }
public fun findNextWordEnd( public fun findNextWordEnd(
chars: CharSequence, chars: CharSequence,
pos: Int, pos: Int,

View File

@ -18,8 +18,7 @@ import com.maddyhome.idea.vim.command.OperatorArguments
*/ */
public interface ExtensionHandler { public interface ExtensionHandler {
@Deprecated("Please use ExtensionHandler#execute(VimEditor, ExecutionContext, OperatorArguments) instead") @Deprecated("Please use ExtensionHandler#execute(VimEditor, ExecutionContext, OperatorArguments) instead")
public fun execute(editor: VimEditor, context: ExecutionContext) { public fun execute(editor: VimEditor, context: ExecutionContext) {}
}
/** /**
* Executes the action. * Executes the action.

View File

@ -54,12 +54,8 @@ public sealed class ShortcutOwnerInfo {
owners[ShortcutOwner.IDE] = mutableListOf("a") owners[ShortcutOwner.IDE] = mutableListOf("a")
} }
val ideOwners = (owners[ShortcutOwner.IDE] ?: emptyList()).sortedBy { val ideOwners = (owners[ShortcutOwner.IDE] ?: emptyList()).sortedBy { wights[it] ?: 1000 }.joinToString(separator = "-")
wights[it] ?: 1000 val vimOwners = (owners[ShortcutOwner.VIM] ?: emptyList()).sortedBy { wights[it] ?: 1000 }.joinToString(separator = "-")
}.joinToString(separator = "-")
val vimOwners = (owners[ShortcutOwner.VIM] ?: emptyList()).sortedBy {
wights[it] ?: 1000
}.joinToString(separator = "-")
return if (ideOwners.isNotEmpty() && vimOwners.isNotEmpty()) { return if (ideOwners.isNotEmpty() && vimOwners.isNotEmpty()) {
ideOwners + ":" + ShortcutOwner.IDE.ownerName + " " + vimOwners + ":" + ShortcutOwner.VIM.ownerName ideOwners + ":" + ShortcutOwner.IDE.ownerName + " " + vimOwners + ":" + ShortcutOwner.VIM.ownerName

View File

@ -31,8 +31,7 @@ public data class ActionCommand(val ranges: Ranges, val argument: String) : Comm
override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult { override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult {
val actionName = argument.trim() val actionName = argument.trim()
val action = injector.actionExecutor.getAction(actionName) val action = injector.actionExecutor.getAction(actionName) ?: throw ExException(injector.messages.message("action.not.found.0", actionName))
?: throw ExException(injector.messages.message("action.not.found.0", actionName))
if (injector.application.isUnitTest()) { if (injector.application.isUnitTest()) {
executeAction(editor, action, context) executeAction(editor, action, context)
} else { } else {

View File

@ -49,8 +49,7 @@ public class CallCommand(public val ranges: Ranges, public val functionCall: Exp
return ExecutionResult.Success return ExecutionResult.Success
} }
val name = (functionCall.scope?.toString() val name = (functionCall.scope?.toString() ?: "") + functionCall.functionName.evaluate(editor, context, vimContext)
?: "") + functionCall.functionName.evaluate(editor, context, vimContext)
val funcref = injector.variableService.getNullableVariableValue(Variable(functionCall.scope, functionCall.functionName), editor, context, vimContext) val funcref = injector.variableService.getNullableVariableValue(Variable(functionCall.scope, functionCall.functionName), editor, context, vimContext)
if (funcref is VimFuncref) { if (funcref is VimFuncref) {
funcref.handler.ranges = ranges funcref.handler.ranges = ranges

View File

@ -48,7 +48,6 @@ public data class CmdCommand(val ranges: Ranges, val argument: String) : Command
const val zeroOrOneArguments = "?" const val zeroOrOneArguments = "?"
const val moreThanZeroArguments = "+" const val moreThanZeroArguments = "+"
} }
override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult { override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult {
val result: Boolean = if (argument.trim().isEmpty()) { val result: Boolean = if (argument.trim().isEmpty()) {
this.listAlias(editor, "") this.listAlias(editor, "")

View File

@ -53,7 +53,6 @@ public data class LetCommand(
private companion object { private companion object {
private val logger = vimLogger<LetCommand>() private val logger = vimLogger<LetCommand>()
} }
override val argFlags: CommandHandlerFlags = flags(RangeFlag.RANGE_FORBIDDEN, ArgumentFlag.ARGUMENT_OPTIONAL, Access.READ_ONLY) override val argFlags: CommandHandlerFlags = flags(RangeFlag.RANGE_FORBIDDEN, ArgumentFlag.ARGUMENT_OPTIONAL, Access.READ_ONLY)
@Throws(ExException::class) @Throws(ExException::class)

View File

@ -31,8 +31,7 @@ public data class PlugCommand(val ranges: Ranges, val argument: String) : Comman
return ExecutionResult.Error return ExecutionResult.Error
} }
injector.statisticsService.addExtensionEnabledWithPlug(injector.extensionRegistrator.getExtensionNameByAlias(pluginAlias) injector.statisticsService.addExtensionEnabledWithPlug(injector.extensionRegistrator.getExtensionNameByAlias(pluginAlias) ?: "unknown extension")
?: "unknown extension")
return ExecutionResult.Success return ExecutionResult.Success
} }
} }

View File

@ -45,8 +45,7 @@ public data class UnknownCommand(val ranges: Ranges, val name: String, val argum
val message = injector.messages.message(Msg.NOT_EX_CMD, name) val message = injector.messages.message(Msg.NOT_EX_CMD, name)
throw InvalidCommandException(message, null) throw InvalidCommandException(message, null)
} }
val parsedCommand = injector.vimscriptParser.parseCommand(commandAlias.command) val parsedCommand = injector.vimscriptParser.parseCommand(commandAlias.command) ?: throw ExException("E492: Not an editor command: ${commandAlias.command}")
?: throw ExException("E492: Not an editor command: ${commandAlias.command}")
return if (parsedCommand is UnknownCommand) { return if (parsedCommand is UnknownCommand) {
processPossiblyAliasCommand(commandAlias.command, editor, context, aliasCountdown - 1) processPossiblyAliasCommand(commandAlias.command, editor, context, aliasCountdown - 1)
} else { } else {

View File

@ -183,8 +183,7 @@ public data class MapCommand(val ranges: Ranges, val argument: String, val cmd:
} }
return fromKeys?.let { return fromKeys?.let {
val toExpr = if (specialArguments.contains(EXPR)) { val toExpr = if (specialArguments.contains(EXPR)) {
injector.vimscriptParser.parseExpression(toKeysBuilder.toString().trim()) injector.vimscriptParser.parseExpression(toKeysBuilder.toString().trim()) ?: throw ExException("E15: Invalid expression: ${toKeysBuilder.toString().trim()}")
?: throw ExException("E15: Invalid expression: ${toKeysBuilder.toString().trim()}")
} else { } else {
SimpleExpression(toKeysBuilder.toString().trimStart()) SimpleExpression(toKeysBuilder.toString().trimStart())
} }

View File

@ -90,8 +90,7 @@ public data class DefinedFunctionHandler(val function: FunctionDeclaration) : Fu
is ExecutionResult.Continue -> exceptionsCaught.add(ExException("E586: :continue without :while or :for: continue")) is ExecutionResult.Continue -> exceptionsCaught.add(ExException("E586: :continue without :while or :for: continue"))
is ExecutionResult.Error -> exceptionsCaught.add(ExException("unknown error occurred")) // todo is ExecutionResult.Error -> exceptionsCaught.add(ExException("unknown error occurred")) // todo
is ExecutionResult.Return -> returnValue = result.value is ExecutionResult.Return -> returnValue = result.value
is ExecutionResult.Success -> { is ExecutionResult.Success -> {}
}
} }
} else { } else {
// todo in release 1.9. in this case multiple exceptions can be thrown at once but we don't support it // todo in release 1.9. in this case multiple exceptions can be thrown at once but we don't support it
@ -107,8 +106,7 @@ public data class DefinedFunctionHandler(val function: FunctionDeclaration) : Fu
returnValue = result.value returnValue = result.value
break break
} }
is ExecutionResult.Success -> { is ExecutionResult.Success -> {}
}
} }
} catch (e: ExException) { } catch (e: ExException) {
if (e is FinishException) { if (e is FinishException) {