1
0
mirror of https://github.com/chylex/IntelliJ-IdeaVim.git synced 2025-09-14 14:32:10 +02:00

Compare commits

..

1 Commits

Author SHA1 Message Date
120d889dfb Implement motions to go to next/previous misspelled word 2024-02-23 10:16:31 +02:00
301 changed files with 36171 additions and 11004 deletions

1
.gitattributes vendored
View File

@@ -1 +0,0 @@
* text=auto eol=lf

View File

@@ -11,7 +11,7 @@ on:
jobs: jobs:
build: build:
if: false if: github.event.pull_request.merged == true && github.repository == 'JetBrains/ideavim'
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:

View File

@@ -9,13 +9,20 @@ jobs:
runs-on: macos-latest runs-on: macos-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Apply Patch
run: |
git apply tests/ui-ij-tests/src/test/kotlin/ui/octopus.patch
- name: Setup Java - name: Setup Java
uses: actions/setup-java@v4 uses: actions/setup-java@v4
with: with:
distribution: zulu distribution: zulu
java-version: 17 java-version: 17
- name: Setup FFmpeg - name: Setup FFmpeg
run: brew install ffmpeg uses: FedericoCarboni/setup-ffmpeg@v3
with:
# Not strictly necessary, but it may prevent rate limit
# errors especially on GitHub-hosted macos machines.
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Setup Gradle - name: Setup Gradle
uses: gradle/gradle-build-action@v2.4.2 uses: gradle/gradle-build-action@v2.4.2
- name: Build Plugin - name: Build Plugin
@@ -23,7 +30,7 @@ jobs:
- name: Run Idea - name: Run Idea
run: | run: |
mkdir -p build/reports mkdir -p build/reports
gradle runIdeForUiTests -Doctopus.handler=false > build/reports/idea.log & gradle runIdeForUiTests > build/reports/idea.log &
- name: Wait for Idea started - name: Wait for Idea started
uses: jtalk/url-health-check-action@v3 uses: jtalk/url-health-check-action@v3
with: with:

View File

@@ -18,7 +18,11 @@ jobs:
with: with:
python-version: '3.10' python-version: '3.10'
- name: Setup FFmpeg - name: Setup FFmpeg
run: brew install ffmpeg uses: FedericoCarboni/setup-ffmpeg@v3
with:
# Not strictly necessary, but it may prevent rate limit
# errors especially on GitHub-hosted macos machines.
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Setup Gradle - name: Setup Gradle
uses: gradle/gradle-build-action@v2.4.2 uses: gradle/gradle-build-action@v2.4.2
- name: Build Plugin - name: Build Plugin

View File

@@ -15,7 +15,11 @@ jobs:
distribution: zulu distribution: zulu
java-version: 17 java-version: 17
- name: Setup FFmpeg - name: Setup FFmpeg
run: brew install ffmpeg uses: FedericoCarboni/setup-ffmpeg@v3
with:
# Not strictly necessary, but it may prevent rate limit
# errors especially on GitHub-hosted macos machines.
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Setup Gradle - name: Setup Gradle
uses: gradle/gradle-build-action@v2.4.2 uses: gradle/gradle-build-action@v2.4.2
- name: Build Plugin - name: Build Plugin

View File

@@ -0,0 +1,34 @@
# This workflow will build a package using Gradle and then publish it to GitHub packages when a release is created
# For more information see: https://github.com/actions/setup-java/blob/main/docs/advanced-usage.md#Publishing-using-gradle
# This workflow syncs changes from the docs folder of IdeaVim to the IdeaVim.wiki repository
name: Update Affected Rate field on YouTrack
on:
workflow_dispatch:
schedule:
- cron: '0 8 * * *'
jobs:
build:
runs-on: ubuntu-latest
if: github.repository == 'JetBrains/ideavim'
steps:
- name: Fetch origin repo
uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v2
with:
java-version: '17'
distribution: 'adopt'
server-id: github # Value of the distributionManagement/repository/id field of the pom.xml
settings-path: ${{ github.workspace }} # location for the settings.xml file
- name: Update YouTrack
run: ./gradlew scripts:updateAffectedRates
env:
YOUTRACK_TOKEN: ${{ secrets.YOUTRACK_TOKEN }}

View File

@@ -7,12 +7,15 @@ on:
workflow_dispatch: workflow_dispatch:
schedule: schedule:
- cron: '0 10 * * *' - cron: '0 10 * * *'
# Workflow run on push is disabled to avoid conflicts when merging PR
# push:
# branches: [ master ]
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: false if: github.repository == 'JetBrains/ideavim'
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3

View File

@@ -25,7 +25,6 @@ object Project : Project({
// Active tests // Active tests
buildType(TestingBuildType("Latest EAP", "<default>", version = "LATEST-EAP-SNAPSHOT")) buildType(TestingBuildType("Latest EAP", "<default>", version = "LATEST-EAP-SNAPSHOT"))
buildType(TestingBuildType("2023.3", "<default>", version = "2023.3")) buildType(TestingBuildType("2023.3", "<default>", version = "2023.3"))
buildType(TestingBuildType("2024.1", "<default>"))
buildType(TestingBuildType("Latest EAP With Xorg", "<default>", version = "LATEST-EAP-SNAPSHOT")) buildType(TestingBuildType("Latest EAP With Xorg", "<default>", version = "LATEST-EAP-SNAPSHOT"))
buildType(PropertyBased) buildType(PropertyBased)

View File

@@ -97,14 +97,14 @@ sealed class ReleasePlugin(private val releaseType: String) : IdeaVimBuildType({
name = "Set TeamCity build number" name = "Set TeamCity build number"
tasks = "scripts:setTeamCityBuildNumber" tasks = "scripts:setTeamCityBuildNumber"
} }
// gradle { gradle {
// name = "Update change log" name = "Update change log"
// tasks = "scripts:changelogUpdateUnreleased" tasks = "scripts:changelogUpdateUnreleased"
// } }
// gradle { gradle {
// name = "Commit preparation changes" name = "Commit preparation changes"
// tasks = "scripts:commitChanges" tasks = "scripts:commitChanges"
// } }
gradle { gradle {
name = "Add release tag" name = "Add release tag"
tasks = "scripts:addReleaseTag" tasks = "scripts:addReleaseTag"
@@ -117,24 +117,33 @@ sealed class ReleasePlugin(private val releaseType: String) : IdeaVimBuildType({
name = "Publish release" name = "Publish release"
tasks = "publishPlugin" tasks = "publishPlugin"
} }
// script { script {
// name = "Checkout master branch" name = "Checkout master branch"
// scriptContent = """ scriptContent = """
// echo Checkout master echo Checkout master
// git checkout master git checkout master
// """.trimIndent() """.trimIndent()
// } }
// gradle { gradle {
// name = "Update change log in master" name = "Update change log in master"
// tasks = "scripts:changelogUpdateUnreleased" tasks = "scripts:changelogUpdateUnreleased"
// } }
// gradle { gradle {
// name = "Commit preparation changes in master" name = "Commit preparation changes in master"
// tasks = "scripts:commitChanges" tasks = "scripts:commitChanges"
// } }
script { script {
name = "Push changes to the repo" name = "Push changes to the repo"
scriptContent = """ scriptContent = """
branch=$(git branch --show-current)
echo Current branch is ${'$'}branch
if [ "master" != "${'$'}branch" ];
then
git checkout master
fi
git push origin
git checkout release git checkout release
echo checkout release branch echo checkout release branch
git branch --set-upstream-to=origin/release release git branch --set-upstream-to=origin/release release

View File

@@ -495,14 +495,6 @@ Contributors:
[![icon][github]](https://github.com/emanuelgestosa) [![icon][github]](https://github.com/emanuelgestosa)
&nbsp; &nbsp;
Emanuel Gestosa Emanuel Gestosa
* [![icon][mail]](mailto:81118900+lippfi@users.noreply.github.com)
[![icon][github]](https://github.com/lippfi)
&nbsp;
lippfi,
* [![icon][mail]](mailto:fillipser143@gmail.com)
[![icon][github]](https://github.com/Parker7123)
&nbsp;
FilipParker
Previous contributors: Previous contributors:

View File

@@ -23,12 +23,15 @@ It is important to distinguish EAP from traditional pre-release software.
Please note that the quality of EAP versions may at times be way below even Please note that the quality of EAP versions may at times be way below even
usual beta standards. usual beta standards.
## End of changelog file maintenance ## To Be Released
Since version 2.9.0, the changelog can be found on YouTrack ### Fixes:
* [VIM-3291](https://youtrack.jetbrains.com/issue/VIM-3291) Remove sync of editor selection between different opened editors
To Be Released: https://youtrack.jetbrains.com/issues/VIM?q=%23%7BReady%20To%20Release%7D%20 * [VIM-3234](https://youtrack.jetbrains.com/issue/VIM-3234) The space character won't mix in the tab chars after >> and << commands
Latest Fixes: https://youtrack.jetbrains.com/issues/VIM?q=State:%20Fixed%20sort%20by:%20updated%20 *
### Merged PRs:
* [805](https://github.com/JetBrains/ideavim/pull/805) by [chylex](https://github.com/chylex): VIM-3238 Fix recording a macro that replays another macro
* [806](https://github.com/JetBrains/ideavim/pull/806) by [chylex](https://github.com/chylex): Enforce LF line separator in project code style
## 2.9.0, 2024-02-20 ## 2.9.0, 2024-02-20

View File

@@ -21,7 +21,7 @@ repositories {
} }
dependencies { dependencies {
compileOnly("com.google.devtools.ksp:symbol-processing-api:1.9.23-1.0.20") compileOnly("com.google.devtools.ksp:symbol-processing-api:1.9.22-1.0.17")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:$kotlinxSerializationVersion") { implementation("org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:$kotlinxSerializationVersion") {
// kotlin stdlib is provided by IJ, so there is no need to include it into the distribution // kotlin stdlib is provided by IJ, so there is no need to include it into the distribution
exclude("org.jetbrains.kotlin", "kotlin-stdlib") exclude("org.jetbrains.kotlin", "kotlin-stdlib")

View File

@@ -32,6 +32,7 @@ import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.RepositoryBuilder import org.eclipse.jgit.lib.RepositoryBuilder
import org.intellij.markdown.ast.getTextInNode import org.intellij.markdown.ast.getTextInNode
import org.jetbrains.changelog.Changelog import org.jetbrains.changelog.Changelog
import org.jetbrains.changelog.exceptions.MissingVersionException
import org.kohsuke.github.GHUser import org.kohsuke.github.GHUser
import java.net.HttpURLConnection import java.net.HttpURLConnection
import java.net.URL import java.net.URL
@@ -48,14 +49,14 @@ buildscript {
classpath("org.eclipse.jgit:org.eclipse.jgit:6.6.0.202305301015-r") classpath("org.eclipse.jgit:org.eclipse.jgit:6.6.0.202305301015-r")
// This is needed for jgit to connect to ssh // This is needed for jgit to connect to ssh
classpath("org.eclipse.jgit:org.eclipse.jgit.ssh.apache:6.9.0.202403050737-r") classpath("org.eclipse.jgit:org.eclipse.jgit.ssh.apache:6.8.0.202311291450-r")
classpath("org.kohsuke:github-api:1.305") classpath("org.kohsuke:github-api:1.305")
classpath("io.ktor:ktor-client-core:2.3.10") classpath("io.ktor:ktor-client-core:2.3.8")
classpath("io.ktor:ktor-client-cio:2.3.10") classpath("io.ktor:ktor-client-cio:2.3.8")
classpath("io.ktor:ktor-client-auth:2.3.10") classpath("io.ktor:ktor-client-auth:2.3.8")
classpath("io.ktor:ktor-client-content-negotiation:2.3.10") classpath("io.ktor:ktor-client-content-negotiation:2.3.8")
classpath("io.ktor:ktor-serialization-kotlinx-json:2.3.10") classpath("io.ktor:ktor-serialization-kotlinx-json:2.3.8")
// This comes from the changelog plugin // This comes from the changelog plugin
// classpath("org.jetbrains:markdown:0.3.1") // classpath("org.jetbrains:markdown:0.3.1")
@@ -69,11 +70,11 @@ plugins {
application application
id("java-test-fixtures") id("java-test-fixtures")
id("org.jetbrains.intellij") version "1.17.3" id("org.jetbrains.intellij") version "1.17.2"
id("org.jetbrains.changelog") version "2.2.0" id("org.jetbrains.changelog") version "2.2.0"
id("org.jetbrains.kotlinx.kover") version "0.6.1" id("org.jetbrains.kotlinx.kover") version "0.6.1"
id("com.dorongold.task-tree") version "3.0.0" id("com.dorongold.task-tree") version "2.1.1"
id("com.google.devtools.ksp") version "1.9.22-1.0.17" id("com.google.devtools.ksp") version "1.9.22-1.0.17"
} }
@@ -141,7 +142,7 @@ dependencies {
testFixturesImplementation("org.jetbrains.kotlin:kotlin-test:$kotlinVersion") testFixturesImplementation("org.jetbrains.kotlin:kotlin-test:$kotlinVersion")
// https://mvnrepository.com/artifact/org.mockito.kotlin/mockito-kotlin // https://mvnrepository.com/artifact/org.mockito.kotlin/mockito-kotlin
testImplementation("org.mockito.kotlin:mockito-kotlin:5.3.1") testImplementation("org.mockito.kotlin:mockito-kotlin:5.2.1")
testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.2") testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.2")
testImplementation("org.junit.jupiter:junit-jupiter-engine:5.10.2") testImplementation("org.junit.jupiter:junit-jupiter-engine:5.10.2")
@@ -206,11 +207,6 @@ tasks {
systemProperty("jb.privacy.policy.text", "<!--999.999-->") systemProperty("jb.privacy.policy.text", "<!--999.999-->")
systemProperty("jb.consents.confirmation.enabled", "false") systemProperty("jb.consents.confirmation.enabled", "false")
systemProperty("ide.show.tips.on.startup.default.value", "false") systemProperty("ide.show.tips.on.startup.default.value", "false")
systemProperty("octopus.handler", System.getProperty("octopus.handler") ?: true)
}
runIde {
systemProperty("octopus.handler", System.getProperty("octopus.handler") ?: true)
} }
} }
@@ -264,6 +260,7 @@ tasks {
runPluginVerifier { runPluginVerifier {
downloadDir.set("${project.buildDir}/pluginVerifier/ides") downloadDir.set("${project.buildDir}/pluginVerifier/ides")
teamCityOutputFormat.set(true) teamCityOutputFormat.set(true)
// ideVersions.set(listOf("IC-2021.3.4"))
} }
generateGrammarSource { generateGrammarSource {
@@ -308,12 +305,26 @@ tasks {
from(createOpenApiSourceJar) { into("lib/src") } from(createOpenApiSourceJar) { into("lib/src") }
} }
val pluginVersion = version
// Don't forget to update plugin.xml
patchPluginXml { patchPluginXml {
// Don't forget to update plugin.xml sinceBuild.set("233.11799.30")
sinceBuild.set("233.11799.67")
// Get the latest available change notes from the changelog file
changeNotes.set( changeNotes.set(
"""<a href="https://youtrack.jetbrains.com/issues/VIM?q=State:%20Fixed%20Fix%20versions:%20${version.get()}">Changelog</a>""" provider {
with(changelog) {
val log = try {
getUnreleased()
} catch (e: MissingVersionException) {
getOrNull(pluginVersion.toString()) ?: getLatest()
}
renderItem(
log,
org.jetbrains.changelog.Changelog.OutputType.HTML,
)
}
},
) )
} }
} }

View File

@@ -8,18 +8,16 @@
# suppress inspection "UnusedProperty" for whole file # suppress inspection "UnusedProperty" for whole file
#ideaVersion=LATEST-EAP-SNAPSHOT ideaVersion=2023.3.2
ideaVersion=2024.1
# Values for type: https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#intellij-extension-type # Values for type: https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#intellij-extension-type
ideaType=IC ideaType=IC
downloadIdeaSources=true downloadIdeaSources=true
instrumentPluginCode=true instrumentPluginCode=true
version=chylex-34 version=SNAPSHOT
javaVersion=17 javaVersion=17
remoteRobotVersion=0.11.22 remoteRobotVersion=0.11.22
antlrVersion=4.10.1 antlrVersion=4.10.1
kotlin.incremental.useClasspathSnapshot=false
# Please don't forget to update kotlin version in buildscript section # Please don't forget to update kotlin version in buildscript section
# Also update kotlinxSerializationVersion version # Also update kotlinxSerializationVersion version
@@ -29,7 +27,7 @@ publishChannels=eap
# Kotlinx serialization also uses some version of kotlin stdlib under the hood. However, # Kotlinx serialization also uses some version of kotlin stdlib under the hood. However,
# we exclude this version from the dependency and use our own version of kotlin that is specified above # we exclude this version from the dependency and use our own version of kotlin that is specified above
kotlinxSerializationVersion=1.6.2 kotlinxSerializationVersion=1.5.1
slackUrl= slackUrl=
youtrackToken= youtrackToken=
@@ -41,4 +39,4 @@ org.gradle.jvmargs='-Dfile.encoding=UTF-8'
kotlin.stdlib.default.dependency=false kotlin.stdlib.default.dependency=false
# Disable incremental annotation processing # Disable incremental annotation processing
ksp.incremental=false ksp.incremental=false

File diff suppressed because it is too large Load Diff

View File

@@ -20,17 +20,17 @@ repositories {
} }
dependencies { dependencies {
compileOnly("org.jetbrains.kotlin:kotlin-stdlib:1.9.23") compileOnly("org.jetbrains.kotlin:kotlin-stdlib:1.9.22")
implementation("io.ktor:ktor-client-core:2.3.10") implementation("io.ktor:ktor-client-core:2.3.8")
implementation("io.ktor:ktor-client-cio:2.3.10") implementation("io.ktor:ktor-client-cio:2.3.8")
implementation("io.ktor:ktor-client-content-negotiation:2.3.10") implementation("io.ktor:ktor-client-content-negotiation:2.3.8")
implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.10") implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.8")
implementation("io.ktor:ktor-client-auth:2.3.10") implementation("io.ktor:ktor-client-auth:2.3.8")
implementation("org.eclipse.jgit:org.eclipse.jgit:6.6.0.202305301015-r") implementation("org.eclipse.jgit:org.eclipse.jgit:6.6.0.202305301015-r")
// This is needed for jgit to connect to ssh // This is needed for jgit to connect to ssh
implementation("org.eclipse.jgit:org.eclipse.jgit.ssh.apache:6.9.0.202403050737-r") implementation("org.eclipse.jgit:org.eclipse.jgit.ssh.apache:6.8.0.202311291450-r")
implementation("com.vdurmont:semver4j:3.1.0") implementation("com.vdurmont:semver4j:3.1.0")
} }
@@ -58,6 +58,13 @@ tasks.register("checkNewPluginDependencies", JavaExec::class) {
classpath = sourceSets["main"].runtimeClasspath classpath = sourceSets["main"].runtimeClasspath
} }
tasks.register("updateAffectedRates", JavaExec::class) {
group = "verification"
description = "This job updates Affected Rate field on YouTrack"
mainClass.set("scripts.YouTrackUsersAffectedKt")
classpath = sourceSets["main"].runtimeClasspath
}
tasks.register("calculateNewVersion", JavaExec::class) { tasks.register("calculateNewVersion", JavaExec::class) {
group = "release" group = "release"
mainClass.set("scripts.release.CalculateNewVersionKt") mainClass.set("scripts.release.CalculateNewVersionKt")

View File

@@ -49,13 +49,17 @@ suspend fun main() {
} }
val output = response.body<List<String>>().toSet() val output = response.body<List<String>>().toSet()
println(output) println(output)
val newPlugins = (output - knownPlugins).map { it to (getPluginLinkByXmlId(it) ?: "Can't find plugin link") } if (knownPlugins != output) {
if (newPlugins.isNotEmpty()) { val newPlugins = (output - knownPlugins).map { it to (getPluginLinkByXmlId(it) ?: "Can't find plugin link") }
// val removedPlugins = (knownPlugins - output.toSet()).map { it to (getPluginLinkByXmlId(it) ?: "Can't find plugin link") } val removedPlugins = (knownPlugins - output.toSet()).map { it to (getPluginLinkByXmlId(it) ?: "Can't find plugin link") }
error( error(
""" """
Unregistered plugins: Unregistered plugins:
${newPlugins.joinToString(separator = "\n") { it.first + "(" + it.second + ")" }} ${if (newPlugins.isNotEmpty()) newPlugins.joinToString(separator = "\n") { it.first + "(" + it.second + ")" } else "No unregistered plugins"}
Removed plugins:
${if (removedPlugins.isNotEmpty()) removedPlugins.joinToString(separator = "\n") { it.first + "(" + it.second + ")" } else "No removed plugins"}
""".trimIndent() """.trimIndent()
) )
} }

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2003-2023 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package scripts
import io.ktor.client.call.*
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
val areaWeights = setOf(
Triple("118-53212", "Plugins", 50),
Triple("118-53220", "Vim Script", 30),
Triple("118-54084", "Esc", 100),
)
suspend fun updateRates() {
println("Updating rates of the issues")
areaWeights.forEach { (id, name, weight) ->
val unmappedIssues = unmappedIssues(name)
println("Got ${unmappedIssues.size} for $name area")
unmappedIssues.forEach { issueId ->
print("Trying to update issue $issueId: ")
val response = updateCustomField(issueId) {
put("name", "Affected Rate")
put("\$type", "SimpleIssueCustomField")
put("value", weight)
}
println(response)
}
}
}
private suspend fun unmappedIssues(area: String): List<String> {
val areaProcessed = if (" " in area) "{$area}" else area
val res = issuesQuery(
query = "project: VIM Affected Rate: {No affected rate} Area: $areaProcessed #Unresolved",
fields = "id,idReadable"
)
return res.body<JsonArray>().map { it.jsonObject }.map { it["idReadable"]!!.jsonPrimitive.content }
}
suspend fun getAreasWithoutWeight(): Set<Pair<String, String>> {
val allAreas = getAreaValues()
return allAreas
.filterNot { it.key in areaWeights.map { it.first }.toSet() }
.entries
.map { it.key to it.value }
.toSet()
}
suspend fun main() {
updateRates()
}

View File

@@ -11,6 +11,7 @@ package com.maddyhome.idea.vim;
import com.intellij.openapi.Disposable; import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.ShortcutSet; import com.intellij.openapi.actionSystem.ShortcutSet;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.actionSystem.TypedAction; import com.intellij.openapi.editor.actionSystem.TypedAction;
@@ -79,6 +80,14 @@ public class EventFacade {
action.unregisterCustomShortcutSet(component); action.unregisterCustomShortcutSet(component);
} }
public void addDocumentListener(@NotNull Document document, @NotNull DocumentListener listener) {
document.addDocumentListener(listener);
}
public void removeDocumentListener(@NotNull Document document, @NotNull DocumentListener listener) {
document.removeDocumentListener(listener);
}
public void addEditorFactoryListener(@NotNull EditorFactoryListener listener, @NotNull Disposable parentDisposable) { public void addEditorFactoryListener(@NotNull EditorFactoryListener listener, @NotNull Disposable parentDisposable) {
EditorFactory.getInstance().addEditorFactoryListener(listener, parentDisposable); EditorFactory.getInstance().addEditorFactoryListener(listener, parentDisposable);
} }
@@ -89,12 +98,20 @@ public class EventFacade {
editor.getCaretModel().addCaretListener(listener, disposable); editor.getCaretModel().addCaretListener(listener, disposable);
} }
public void removeCaretListener(@NotNull Editor editor, @NotNull CaretListener listener) {
editor.getCaretModel().removeCaretListener(listener);
}
public void addEditorMouseListener(@NotNull Editor editor, public void addEditorMouseListener(@NotNull Editor editor,
@NotNull EditorMouseListener listener, @NotNull EditorMouseListener listener,
@NotNull Disposable disposable) { @NotNull Disposable disposable) {
editor.addEditorMouseListener(listener, disposable); editor.addEditorMouseListener(listener, disposable);
} }
public void removeEditorMouseListener(@NotNull Editor editor, @NotNull EditorMouseListener listener) {
editor.removeEditorMouseListener(listener);
}
public void addComponentMouseListener(@NotNull Component component, public void addComponentMouseListener(@NotNull Component component,
@NotNull MouseListener mouseListener, @NotNull MouseListener mouseListener,
@NotNull Disposable disposable) { @NotNull Disposable disposable) {
@@ -102,18 +119,30 @@ public class EventFacade {
Disposer.register(disposable, () -> component.removeMouseListener(mouseListener)); Disposer.register(disposable, () -> component.removeMouseListener(mouseListener));
} }
public void removeComponentMouseListener(@NotNull Component component, @NotNull MouseListener mouseListener) {
component.removeMouseListener(mouseListener);
}
public void addEditorMouseMotionListener(@NotNull Editor editor, public void addEditorMouseMotionListener(@NotNull Editor editor,
@NotNull EditorMouseMotionListener listener, @NotNull EditorMouseMotionListener listener,
@NotNull Disposable disposable) { @NotNull Disposable disposable) {
editor.addEditorMouseMotionListener(listener, disposable); editor.addEditorMouseMotionListener(listener, disposable);
} }
public void removeEditorMouseMotionListener(@NotNull Editor editor, @NotNull EditorMouseMotionListener listener) {
editor.removeEditorMouseMotionListener(listener);
}
public void addEditorSelectionListener(@NotNull Editor editor, public void addEditorSelectionListener(@NotNull Editor editor,
@NotNull SelectionListener listener, @NotNull SelectionListener listener,
@NotNull Disposable disposable) { @NotNull Disposable disposable) {
editor.getSelectionModel().addSelectionListener(listener, disposable); editor.getSelectionModel().addSelectionListener(listener, disposable);
} }
public void removeEditorSelectionListener(@NotNull Editor editor, @NotNull SelectionListener listener) {
editor.getSelectionModel().removeSelectionListener(listener);
}
private @NotNull TypedAction getTypedAction() { private @NotNull TypedAction getTypedAction() {
return TypedAction.getInstance(); return TypedAction.getInstance();
} }

View File

@@ -14,7 +14,7 @@ import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.startup.ProjectActivity import com.intellij.openapi.startup.ProjectActivity
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.helper.EditorHelper import com.maddyhome.idea.vim.helper.EditorHelper
import com.maddyhome.idea.vim.newapi.IjVimEditor import com.maddyhome.idea.vim.helper.localEditors
import com.maddyhome.idea.vim.newapi.globalIjOptions import com.maddyhome.idea.vim.newapi.globalIjOptions
/** /**
@@ -36,10 +36,8 @@ internal class PluginStartup : ProjectActivity/*, LightEditCompatible*/ {
// This is a temporal workaround for VIM-2487 // This is a temporal workaround for VIM-2487
internal class PyNotebooksCloseWorkaround : ProjectManagerListener { internal class PyNotebooksCloseWorkaround : ProjectManagerListener {
override fun projectClosingBeforeSave(project: Project) { override fun projectClosingBeforeSave(project: Project) {
// TODO: Confirm context in CWM scenario
if (injector.globalIjOptions().closenotebooks) { if (injector.globalIjOptions().closenotebooks) {
injector.editorGroup.getEditors().forEach { vimEditor -> localEditors().forEach { editor ->
val editor = (vimEditor as IjVimEditor).editor
val virtualFile = EditorHelper.getVirtualFile(editor) val virtualFile = EditorHelper.getVirtualFile(editor)
if (virtualFile?.extension == "ipynb") { if (virtualFile?.extension == "ipynb") {
val fileEditorManager = FileEditorManagerEx.getInstanceEx(project) val fileEditorManager = FileEditorManagerEx.getInstanceEx(project)

View File

@@ -21,7 +21,7 @@ public object RegisterActions {
@JvmStatic @JvmStatic
public fun registerActions() { public fun registerActions() {
registerVimCommandActions() registerVimCommandActions()
registerShortcutsWithoutActions() registerEmptyShortcuts() // todo most likely it is not needed
} }
public fun findAction(id: String): EditorActionHandlerBase? { public fun findAction(id: String): EditorActionHandlerBase? {
@@ -46,11 +46,12 @@ public object RegisterActions {
IntellijCommandProvider.getCommands().forEach { parser.registerCommandAction(it) } IntellijCommandProvider.getCommands().forEach { parser.registerCommandAction(it) }
} }
private fun registerShortcutsWithoutActions() { private fun registerEmptyShortcuts() {
val parser = VimPlugin.getKey() val parser = VimPlugin.getKey()
// The {char1} <BS> {char2} shortcut is handled directly by KeyHandler#handleKey, so doesn't have an action. But we // The {char1} <BS> {char2} shortcut is handled directly by KeyHandler#handleKey, so doesn't have an action. But we
// still need to register the shortcut, to make sure the editor doesn't swallow it. // still need to register the shortcut, to make sure the editor doesn't swallow it.
parser.registerShortcutWithoutAction(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), MappingOwner.IdeaVim.System) parser
.registerShortcutWithoutAction(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), MappingOwner.IdeaVim.System)
} }
} }

View File

@@ -211,22 +211,22 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
public static void setEnabled(final boolean enabled) { public static void setEnabled(final boolean enabled) {
if (isEnabled() == enabled) return; if (isEnabled() == enabled) return;
if (!enabled) {
getInstance().turnOffPlugin(true);
}
getInstance().enabled = enabled; getInstance().enabled = enabled;
if (enabled) {
getInstance().turnOnPlugin();
}
if (enabled) { if (enabled) {
VimInjectorKt.getInjector().getListenersNotifier().notifyPluginTurnedOn(); VimInjectorKt.getInjector().getListenersNotifier().notifyPluginTurnedOn();
} else { } else {
VimInjectorKt.getInjector().getListenersNotifier().notifyPluginTurnedOff(); VimInjectorKt.getInjector().getListenersNotifier().notifyPluginTurnedOff();
} }
if (!enabled) {
getInstance().turnOffPlugin(true);
}
if (enabled) {
getInstance().turnOnPlugin();
}
StatusBarIconFactory.Util.INSTANCE.updateIcon(); StatusBarIconFactory.Util.INSTANCE.updateIcon();
} }
@@ -353,7 +353,6 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
if (onOffDisposable != null) { if (onOffDisposable != null) {
Disposer.dispose(onOffDisposable); Disposer.dispose(onOffDisposable);
onOffDisposable = null;
} }
} }

View File

@@ -77,7 +77,7 @@ public class VimTypedActionHandler(origHandler: TypedActionHandler) : TypedActio
val modifiers = if (charTyped == ' ' && VimKeyListener.isSpaceShift) KeyEvent.SHIFT_DOWN_MASK else 0 val modifiers = if (charTyped == ' ' && VimKeyListener.isSpaceShift) KeyEvent.SHIFT_DOWN_MASK else 0
val keyStroke = KeyStroke.getKeyStroke(charTyped, modifiers) val keyStroke = KeyStroke.getKeyStroke(charTyped, modifiers)
val startTime = if (traceTime) System.currentTimeMillis() else null val startTime = if (traceTime) System.currentTimeMillis() else null
handler.handleKey(editor.vim, keyStroke, context.vim, handler.keyHandlerState) handler.handleKey(editor.vim, keyStroke, injector.executionContextManager.onEditor(editor.vim, context.vim))
if (startTime != null) { if (startTime != null) {
val duration = System.currentTimeMillis() - startTime val duration = System.currentTimeMillis() - startTime
LOG.info("VimTypedAction '$charTyped': $duration ms") LOG.info("VimTypedAction '$charTyped': $duration ms")

View File

@@ -44,6 +44,7 @@ import com.maddyhome.idea.vim.listener.AceJumpService
import com.maddyhome.idea.vim.listener.AppCodeTemplates.appCodeTemplateCaptured import com.maddyhome.idea.vim.listener.AppCodeTemplates.appCodeTemplateCaptured
import com.maddyhome.idea.vim.newapi.globalIjOptions import com.maddyhome.idea.vim.newapi.globalIjOptions
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.state.mode.mode
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString
import java.awt.event.InputEvent import java.awt.event.InputEvent
import java.awt.event.KeyEvent import java.awt.event.KeyEvent
@@ -78,8 +79,11 @@ public class VimShortcutKeyAction : AnAction(), DumbAware/*, LightEditCompatible
// Should we use HelperKt.getTopLevelEditor(editor) here, as we did in former EditorKeyHandler? // Should we use HelperKt.getTopLevelEditor(editor) here, as we did in former EditorKeyHandler?
try { try {
val start = if (traceTime) System.currentTimeMillis() else null val start = if (traceTime) System.currentTimeMillis() else null
val keyHandler = KeyHandler.getInstance() KeyHandler.getInstance().handleKey(
keyHandler.handleKey(editor.vim, keyStroke, e.dataContext.vim, keyHandler.keyHandlerState) editor.vim,
keyStroke,
injector.executionContextManager.onEditor(editor.vim, e.dataContext.vim),
)
if (start != null) { if (start != null) {
val duration = System.currentTimeMillis() - start val duration = System.currentTimeMillis() - start
LOG.info("VimShortcut update '$keyStroke': $duration ms") LOG.info("VimShortcut update '$keyStroke': $duration ms")
@@ -376,10 +380,6 @@ private class ActionEnableStatus(
} }
} }
override fun toString(): String {
return "ActionEnableStatus(isEnabled=$isEnabled, message='$message', logLevel=$logLevel)"
}
companion object { companion object {
private val LOG = logger<ActionEnableStatus>() private val LOG = logger<ActionEnableStatus>()

View File

@@ -7,9 +7,9 @@
*/ */
package com.maddyhome.idea.vim.action.change package com.maddyhome.idea.vim.action.change
import com.intellij.openapi.command.CommandProcessor
import com.intellij.vim.annotations.CommandOrMotion import com.intellij.vim.annotations.CommandOrMotion
import com.intellij.vim.annotations.Mode import com.intellij.vim.annotations.Mode
import com.intellij.openapi.command.CommandProcessor
import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor

View File

@@ -34,7 +34,7 @@ public class DeleteJoinLinesSpacesAction : ChangeEditorActionHandler.SingleExecu
} }
injector.editorGroup.notifyIdeaJoin(editor) injector.editorGroup.notifyIdeaJoin(editor)
var res = true var res = true
editor.nativeCarets().sortedByDescending { it.offset }.forEach { caret -> editor.nativeCarets().sortedByDescending { it.offset.point }.forEach { caret ->
if (!injector.changeGroup.deleteJoinLines(editor, caret, operatorArguments.count1, true, operatorArguments)) { if (!injector.changeGroup.deleteJoinLines(editor, caret, operatorArguments.count1, true, operatorArguments)) {
res = false res = false
} }

View File

@@ -39,7 +39,7 @@ public class DeleteJoinVisualLinesAction : VisualOperatorActionHandler.SingleExe
return true return true
} }
var res = true var res = true
editor.nativeCarets().sortedByDescending { it.offset }.forEach { caret -> editor.nativeCarets().sortedByDescending { it.offset.point }.forEach { caret ->
if (!caret.isValid) return@forEach if (!caret.isValid) return@forEach
val range = caretsAndSelections[caret] ?: return@forEach val range = caretsAndSelections[caret] ?: return@forEach
if (!injector.changeGroup.deleteJoinRange( if (!injector.changeGroup.deleteJoinRange(

View File

@@ -39,7 +39,7 @@ public class DeleteJoinVisualLinesSpacesAction : VisualOperatorActionHandler.Sin
return true return true
} }
var res = true var res = true
editor.carets().sortedByDescending { it.offset }.forEach { caret -> editor.carets().sortedByDescending { it.offset.point }.forEach { caret ->
if (!caret.isValid) return@forEach if (!caret.isValid) return@forEach
val range = caretsAndSelections[caret] ?: return@forEach val range = caretsAndSelections[caret] ?: return@forEach
if (!injector.changeGroup.deleteJoinRange( if (!injector.changeGroup.deleteJoinRange(

View File

@@ -21,7 +21,7 @@ import com.maddyhome.idea.vim.state.mode.SelectionType
public class CommandState(private val machine: VimStateMachine) { public class CommandState(private val machine: VimStateMachine) {
public val isOperatorPending: Boolean public val isOperatorPending: Boolean
get() = machine.isOperatorPending(machine.mode) get() = machine.isOperatorPending
public val mode: Mode public val mode: Mode
get() { get() {

View File

@@ -9,6 +9,8 @@
package com.maddyhome.idea.vim.common package com.maddyhome.idea.vim.common
import com.intellij.application.options.CodeStyle import com.intellij.application.options.CodeStyle
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.intellij.psi.codeStyle.CommonCodeStyleSettings.IndentOptions import com.intellij.psi.codeStyle.CommonCodeStyleSettings.IndentOptions
@@ -37,12 +39,13 @@ internal class IndentConfig private constructor(indentOptions: IndentOptions) {
companion object { companion object {
@JvmStatic @JvmStatic
fun create(editor: Editor): IndentConfig { fun create(editor: Editor, context: DataContext): IndentConfig {
return create(editor, editor.project) return create(editor, PlatformDataKeys.PROJECT.getData(context))
} }
@JvmStatic @JvmStatic
fun create(editor: Editor, project: Project?): IndentConfig { @JvmOverloads
fun create(editor: Editor, project: Project? = editor.project): IndentConfig {
val indentOptions = if (project != null) { val indentOptions = if (project != null) {
CodeStyle.getIndentOptions(project, editor.document) CodeStyle.getIndentOptions(project, editor.document)
} else { } else {

View File

@@ -7,7 +7,6 @@
*/ */
package com.maddyhome.idea.vim.extension package com.maddyhome.idea.vim.extension
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.logger
@@ -143,9 +142,8 @@ public object VimExtensionFacade {
*/ */
@JvmStatic @JvmStatic
public fun executeNormalWithoutMapping(keys: List<KeyStroke>, editor: Editor) { public fun executeNormalWithoutMapping(keys: List<KeyStroke>, editor: Editor) {
val context = injector.executionContextManager.getEditorExecutionContext(editor.vim) val context = injector.executionContextManager.onEditor(editor.vim)
val keyHandler = KeyHandler.getInstance() keys.forEach { KeyHandler.getInstance().handleKey(editor.vim, it, context, false, false) }
keys.forEach { keyHandler.handleKey(editor.vim, it, context, false, false, keyHandler.keyHandlerState) }
} }
/** Returns a single key stroke from the user input similar to 'getchar()'. */ /** Returns a single key stroke from the user input similar to 'getchar()'. */
@@ -161,7 +159,7 @@ public object VimExtensionFacade {
LOG.trace("Unit test mode is active") LOG.trace("Unit test mode is active")
val mappingStack = KeyHandler.getInstance().keyStack val mappingStack = KeyHandler.getInstance().keyStack
mappingStack.feedSomeStroke() ?: TestInputModel.getInstance(editor).nextKeyStroke()?.also { mappingStack.feedSomeStroke() ?: TestInputModel.getInstance(editor).nextKeyStroke()?.also {
if (injector.registerGroup.isRecording) { if (editor.vim.vimStateMachine.isRecording) {
KeyHandler.getInstance().modalEntryKeys += it KeyHandler.getInstance().modalEntryKeys += it
} }
} }
@@ -182,8 +180,8 @@ public object VimExtensionFacade {
/** Returns a string typed in the input box similar to 'input()'. */ /** Returns a string typed in the input box similar to 'input()'. */
@JvmStatic @JvmStatic
public fun inputString(editor: Editor, context: DataContext, prompt: String, finishOn: Char?): String { public fun inputString(editor: Editor, prompt: String, finishOn: Char?): String {
return service<CommandLineHelper>().inputString(editor.vim, context.vim, prompt, finishOn) ?: "" return service<CommandLineHelper>().inputString(editor.vim, prompt, finishOn) ?: ""
} }
/** Get the current contents of the given register similar to 'getreg()'. */ /** Get the current contents of the given register similar to 'getreg()'. */

View File

@@ -67,7 +67,7 @@ internal object VimExtensionRegistrar : VimExtensionRegistrator {
VimPlugin.getOptionGroup().addGlobalOptionChangeListener(option) { VimPlugin.getOptionGroup().addGlobalOptionChangeListener(option) {
if (injector.optionGroup.getOptionValue(option, OptionAccessScope.GLOBAL(null)).asBoolean()) { if (injector.optionGroup.getOptionValue(option, OptionAccessScope.GLOBAL(null)).asBoolean()) {
initExtension(extensionBean, name) initExtension(extensionBean, name)
PluginState.Util.enabledExtensions.add(name) PluginState.enabledExtensions.add(name)
} else { } else {
extensionBean.instance.dispose() extensionBean.instance.dispose()
} }

View File

@@ -251,7 +251,7 @@ public class VimArgTextObjExtension implements VimExtension {
final ArgumentTextObjectHandler textObjectHandler = new ArgumentTextObjectHandler(isInner); final ArgumentTextObjectHandler textObjectHandler = new ArgumentTextObjectHandler(isInner);
//noinspection DuplicatedCode //noinspection DuplicatedCode
if (!vimStateMachine.isOperatorPending(editor.getMode())) { if (!vimStateMachine.isOperatorPending()) {
editor.nativeCarets().forEach((VimCaret caret) -> { editor.nativeCarets().forEach((VimCaret caret) -> {
final TextRange range = textObjectHandler.getRange(editor, caret, context, count, 0); final TextRange range = textObjectHandler.getRange(editor, caret, context, count, 0);
if (range != null) { if (range != null) {

View File

@@ -55,7 +55,10 @@ import java.util.*
internal class CommentaryExtension : VimExtension { internal class CommentaryExtension : VimExtension {
object Util { companion object {
private const val OPERATOR_FUNC = "CommentaryOperatorFunc"
fun doCommentary( fun doCommentary(
editor: VimEditor, editor: VimEditor,
context: ExecutionContext, context: ExecutionContext,
@@ -121,10 +124,6 @@ internal class CommentaryExtension : VimExtension {
} }
} }
companion object {
private const val OPERATOR_FUNC = "CommentaryOperatorFunc"
}
override fun getName() = "commentary" override fun getName() = "commentary"
override fun init() { override fun init() {
@@ -159,7 +158,7 @@ internal class CommentaryExtension : VimExtension {
// todo make it multicaret // todo make it multicaret
override fun apply(editor: VimEditor, context: ExecutionContext, selectionType: SelectionType?): Boolean { override fun apply(editor: VimEditor, context: ExecutionContext, selectionType: SelectionType?): Boolean {
val range = injector.markService.getChangeMarks(editor.primaryCaret()) ?: return false val range = injector.markService.getChangeMarks(editor.primaryCaret()) ?: return false
return Util.doCommentary(editor, context, range, selectionType ?: SelectionType.CHARACTER_WISE, true) return doCommentary(editor, context, range, selectionType ?: SelectionType.CHARACTER_WISE, true)
} }
} }
@@ -249,7 +248,7 @@ internal class CommentaryExtension : VimExtension {
*/ */
private class CommentaryCommandAliasHandler : CommandAliasHandler { private class CommentaryCommandAliasHandler : CommandAliasHandler {
override fun execute(command: String, ranges: Ranges, editor: VimEditor, context: ExecutionContext) { override fun execute(command: String, ranges: Ranges, editor: VimEditor, context: ExecutionContext) {
Util.doCommentary(editor, context, ranges.getTextRange(editor, -1), SelectionType.LINE_WISE, false) doCommentary(editor, context, ranges.getTextRange(editor, -1), SelectionType.LINE_WISE, false)
} }
} }
} }

View File

@@ -24,6 +24,8 @@ import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.api.setChangeMarks import com.maddyhome.idea.vim.api.setChangeMarks
import com.maddyhome.idea.vim.command.MappingMode import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.state.mode.selectionType
import com.maddyhome.idea.vim.common.TextRange import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.extension.ExtensionHandler import com.maddyhome.idea.vim.extension.ExtensionHandler
import com.maddyhome.idea.vim.extension.VimExtension import com.maddyhome.idea.vim.extension.VimExtension
@@ -35,6 +37,7 @@ import com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMappingIfMissin
import com.maddyhome.idea.vim.extension.VimExtensionFacade.setRegister import com.maddyhome.idea.vim.extension.VimExtensionFacade.setRegister
import com.maddyhome.idea.vim.extension.exportOperatorFunction import com.maddyhome.idea.vim.extension.exportOperatorFunction
import com.maddyhome.idea.vim.helper.fileSize import com.maddyhome.idea.vim.helper.fileSize
import com.maddyhome.idea.vim.state.mode.mode
import com.maddyhome.idea.vim.helper.moveToInlayAwareLogicalPosition import com.maddyhome.idea.vim.helper.moveToInlayAwareLogicalPosition
import com.maddyhome.idea.vim.helper.moveToInlayAwareOffset import com.maddyhome.idea.vim.helper.moveToInlayAwareOffset
import com.maddyhome.idea.vim.key.OperatorFunction import com.maddyhome.idea.vim.key.OperatorFunction
@@ -43,8 +46,6 @@ import com.maddyhome.idea.vim.mark.VimMarkConstants
import com.maddyhome.idea.vim.newapi.IjVimEditor import com.maddyhome.idea.vim.newapi.IjVimEditor
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.state.mode.selectionType
import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.NonNls
/** /**
@@ -76,9 +77,24 @@ internal class VimExchangeExtension : VimExtension {
VimExtensionFacade.exportOperatorFunction(OPERATOR_FUNC, Operator()) VimExtensionFacade.exportOperatorFunction(OPERATOR_FUNC, Operator())
} }
object Util { companion object {
@NonNls private const val EXCHANGE_CMD = "<Plug>(Exchange)"
@NonNls private const val EXCHANGE_CLEAR_CMD = "<Plug>(ExchangeClear)"
@NonNls private const val EXCHANGE_LINE_CMD = "<Plug>(ExchangeLine)"
@NonNls private const val OPERATOR_FUNC = "ExchangeOperatorFunc"
val EXCHANGE_KEY = Key<Exchange>("exchange") val EXCHANGE_KEY = Key<Exchange>("exchange")
// End mark has always greater of eq offset than start mark
class Exchange(val type: SelectionType, val start: Mark, val end: Mark, val text: String) {
private var myHighlighter: RangeHighlighter? = null
fun setHighlighter(highlighter: RangeHighlighter) {
myHighlighter = highlighter
}
fun getHighlighter(): RangeHighlighter? = myHighlighter
}
fun clearExchange(editor: Editor) { fun clearExchange(editor: Editor) {
editor.getUserData(EXCHANGE_KEY)?.getHighlighter()?.let { editor.getUserData(EXCHANGE_KEY)?.getHighlighter()?.let {
editor.markupModel.removeHighlighter(it) editor.markupModel.removeHighlighter(it)
@@ -87,13 +103,6 @@ internal class VimExchangeExtension : VimExtension {
} }
} }
companion object {
@NonNls private const val EXCHANGE_CMD = "<Plug>(Exchange)"
@NonNls private const val EXCHANGE_CLEAR_CMD = "<Plug>(ExchangeClear)"
@NonNls private const val EXCHANGE_LINE_CMD = "<Plug>(ExchangeLine)"
@NonNls private const val OPERATOR_FUNC = "ExchangeOperatorFunc"
}
private class ExchangeHandler(private val isLine: Boolean) : ExtensionHandler { private class ExchangeHandler(private val isLine: Boolean) : ExtensionHandler {
override val isRepeatable = true override val isRepeatable = true
@@ -105,7 +114,7 @@ internal class VimExchangeExtension : VimExtension {
private class ExchangeClearHandler : ExtensionHandler { private class ExchangeClearHandler : ExtensionHandler {
override fun execute(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments) { override fun execute(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments) {
Util.clearExchange(editor.ij) clearExchange(editor.ij)
} }
} }
@@ -149,11 +158,11 @@ internal class VimExchangeExtension : VimExtension {
} }
val currentExchange = getExchange(ijEditor, isVisual, selectionType ?: SelectionType.CHARACTER_WISE) val currentExchange = getExchange(ijEditor, isVisual, selectionType ?: SelectionType.CHARACTER_WISE)
val exchange1 = ijEditor.getUserData(Util.EXCHANGE_KEY) val exchange1 = ijEditor.getUserData(EXCHANGE_KEY)
if (exchange1 == null) { if (exchange1 == null) {
val highlighter = highlightExchange(currentExchange) val highlighter = highlightExchange(currentExchange)
currentExchange.setHighlighter(highlighter) currentExchange.setHighlighter(highlighter)
ijEditor.putUserData(Util.EXCHANGE_KEY, currentExchange) ijEditor.putUserData(EXCHANGE_KEY, currentExchange)
return true return true
} else { } else {
val cmp = compareExchanges(exchange1, currentExchange) val cmp = compareExchanges(exchange1, currentExchange)
@@ -179,7 +188,7 @@ internal class VimExchangeExtension : VimExtension {
} }
} }
exchange(ijEditor, ex1, ex2, reverse, expand) exchange(ijEditor, ex1, ex2, reverse, expand)
Util.clearExchange(ijEditor) clearExchange(ijEditor)
return true return true
} }
} }
@@ -344,14 +353,4 @@ internal class VimExchangeExtension : VimExtension {
} }
} }
} }
// End mark has always greater of eq offset than start mark
class Exchange(val type: SelectionType, val start: Mark, val end: Mark, val text: String) {
private var myHighlighter: RangeHighlighter? = null
fun setHighlighter(highlighter: RangeHighlighter) {
myHighlighter = highlighter
}
fun getHighlighter(): RangeHighlighter? = myHighlighter
}
} }

View File

@@ -99,7 +99,7 @@ internal class Matchit : VimExtension {
// Normally we want to jump to the start of the matching pair. But when moving forward in operator // Normally we want to jump to the start of the matching pair. But when moving forward in operator
// pending mode, we want to include the entire match. isInOpPending makes that distinction. // pending mode, we want to include the entire match. isInOpPending makes that distinction.
val isInOpPending = commandState.isOperatorPending(editor.mode) val isInOpPending = commandState.isOperatorPending
if (isInOpPending) { if (isInOpPending) {
val matchitAction = MatchitAction() val matchitAction = MatchitAction()
@@ -233,7 +233,7 @@ private object FileTypePatterns {
} else if (fileTypeName == "CMakeLists.txt" || fileName == "CMakeLists") { } else if (fileTypeName == "CMakeLists.txt" || fileName == "CMakeLists") {
this.cMakePatterns this.cMakePatterns
} else { } else {
this.htmlPatterns return null
} }
} }

View File

@@ -130,15 +130,15 @@ internal class NerdTree : VimExtension {
addCommand("NERDTreeFind", IjCommandHandler("SelectInProjectView")) addCommand("NERDTreeFind", IjCommandHandler("SelectInProjectView"))
addCommand("NERDTreeRefreshRoot", IjCommandHandler("Synchronize")) addCommand("NERDTreeRefreshRoot", IjCommandHandler("Synchronize"))
synchronized(Util.monitor) { synchronized(monitor) {
Util.commandsRegistered = true commandsRegistered = true
ProjectManager.getInstance().openProjects.forEach { project -> installDispatcher(project) } ProjectManager.getInstance().openProjects.forEach { project -> installDispatcher(project) }
} }
} }
class IjCommandHandler(private val actionId: String) : CommandAliasHandler { class IjCommandHandler(private val actionId: String) : CommandAliasHandler {
override fun execute(command: String, ranges: Ranges, editor: VimEditor, context: ExecutionContext) { override fun execute(command: String, ranges: Ranges, editor: VimEditor, context: ExecutionContext) {
Util.callAction(editor, actionId, context) callAction(editor, actionId, context)
} }
} }
@@ -149,7 +149,7 @@ internal class NerdTree : VimExtension {
if (toolWindow.isVisible) { if (toolWindow.isVisible) {
toolWindow.hide() toolWindow.hide()
} else { } else {
Util.callAction(editor, "ActivateProjectToolWindow", context) callAction(editor, "ActivateProjectToolWindow", context)
} }
} }
} }
@@ -187,8 +187,8 @@ internal class NerdTree : VimExtension {
// TODO I'm not sure is this activity runs at all? Should we use [RunOnceUtil] instead? // TODO I'm not sure is this activity runs at all? Should we use [RunOnceUtil] instead?
class NerdStartupActivity : ProjectActivity { class NerdStartupActivity : ProjectActivity {
override suspend fun execute(project: Project) { override suspend fun execute(project: Project) {
synchronized(Util.monitor) { synchronized(monitor) {
if (!Util.commandsRegistered) return if (!commandsRegistered) return
installDispatcher(project) installDispatcher(project)
} }
} }
@@ -214,7 +214,7 @@ internal class NerdTree : VimExtension {
val action = nextNode.actionHolder val action = nextNode.actionHolder
when (action) { when (action) {
is NerdAction.ToIj -> Util.callAction(null, action.name, e.dataContext.vim) is NerdAction.ToIj -> callAction(null, action.name, e.dataContext.vim)
is NerdAction.Code -> e.project?.let { action.action(it, e.dataContext, e) } is NerdAction.Code -> e.project?.let { action.action(it, e.dataContext, e) }
} }
} }
@@ -356,7 +356,7 @@ internal class NerdTree : VimExtension {
currentWindow?.split(SwingConstants.VERTICAL, true, file, true) currentWindow?.split(SwingConstants.VERTICAL, true, file, true)
// FIXME: 22.01.2021 This solution bouncing a bit // FIXME: 22.01.2021 This solution bouncing a bit
Util.callAction(null, "ActivateProjectToolWindow", context.vim) callAction(null, "ActivateProjectToolWindow", context.vim)
}, },
) )
registerCommand( registerCommand(
@@ -368,7 +368,7 @@ internal class NerdTree : VimExtension {
val currentWindow = splitters.currentWindow val currentWindow = splitters.currentWindow
currentWindow?.split(SwingConstants.HORIZONTAL, true, file, true) currentWindow?.split(SwingConstants.HORIZONTAL, true, file, true)
Util.callAction(null, "ActivateProjectToolWindow", context.vim) callAction(null, "ActivateProjectToolWindow", context.vim)
}, },
) )
registerCommand( registerCommand(
@@ -504,9 +504,14 @@ internal class NerdTree : VimExtension {
) )
} }
object Util { companion object {
const val pluginName = "NERDTree"
internal val monitor = Any() internal val monitor = Any()
internal var commandsRegistered = false internal var commandsRegistered = false
private val LOG = logger<NerdTree>()
fun callAction(editor: VimEditor?, name: String, context: ExecutionContext) { fun callAction(editor: VimEditor?, name: String, context: ExecutionContext) {
val action = ActionManager.getInstance().getAction(name) ?: run { val action = ActionManager.getInstance().getAction(name) ?: run {
VimPlugin.showMessage(MessageHelper.message("action.not.found.0", name)) VimPlugin.showMessage(MessageHelper.message("action.not.found.0", name))
@@ -521,51 +526,45 @@ internal class NerdTree : VimExtension {
} }
} }
} }
}
companion object { private fun addCommand(alias: String, handler: CommandAliasHandler) {
const val pluginName = "NERDTree" VimPlugin.getCommand().setAlias(alias, CommandAlias.Call(0, -1, alias, handler))
private val LOG = logger<NerdTree>() }
private fun registerCommand(variable: String, default: String, action: NerdAction) {
val variableValue = VimPlugin.getVariableService().getGlobalVariableValue(variable)
val mappings = if (variableValue is VimString) {
variableValue.value
} else {
default
}
actionsRoot.addLeafs(mappings, action)
}
private fun registerCommand(default: String, action: NerdAction) {
actionsRoot.addLeafs(default, action)
}
private val actionsRoot: RootNode<NerdAction> = RootNode()
private var currentNode: CommandPartNode<NerdAction> = actionsRoot
private fun collectShortcuts(node: Node<NerdAction>): Set<KeyStroke> {
return if (node is CommandPartNode<NerdAction>) {
val res = node.keys.toMutableSet()
res += node.values.map { collectShortcuts(it) }.flatten()
res
} else {
emptySet()
}
}
private fun installDispatcher(project: Project) {
val dispatcher = NerdDispatcher.getInstance(project)
val shortcuts = collectShortcuts(actionsRoot).map { RequiredShortcut(it, MappingOwner.Plugin.get(pluginName)) }
dispatcher.registerCustomShortcutSet(
KeyGroup.toShortcutSet(shortcuts),
(ProjectView.getInstance(project) as ProjectViewImpl).component,
)
}
} }
} }
private fun addCommand(alias: String, handler: CommandAliasHandler) {
VimPlugin.getCommand().setAlias(alias, CommandAlias.Call(0, -1, alias, handler))
}
private fun registerCommand(variable: String, default: String, action: NerdAction) {
val variableValue = VimPlugin.getVariableService().getGlobalVariableValue(variable)
val mappings = if (variableValue is VimString) {
variableValue.value
} else {
default
}
actionsRoot.addLeafs(mappings, action)
}
private fun registerCommand(default: String, action: NerdAction) {
actionsRoot.addLeafs(default, action)
}
private val actionsRoot: RootNode<NerdAction> = RootNode()
private var currentNode: CommandPartNode<NerdAction> = actionsRoot
private fun collectShortcuts(node: Node<NerdAction>): Set<KeyStroke> {
return if (node is CommandPartNode<NerdAction>) {
val res = node.keys.toMutableSet()
res += node.values.map { collectShortcuts(it) }.flatten()
res
} else {
emptySet()
}
}
private fun installDispatcher(project: Project) {
val dispatcher = NerdTree.NerdDispatcher.getInstance(project)
val shortcuts =
collectShortcuts(actionsRoot).map { RequiredShortcut(it, MappingOwner.Plugin.get(NerdTree.pluginName)) }
dispatcher.registerCustomShortcutSet(
KeyGroup.toShortcutSet(shortcuts),
(ProjectView.getInstance(project) as ProjectViewImpl).component,
)
}

View File

@@ -9,7 +9,6 @@
package com.maddyhome.idea.vim.extension.paragraphmotion package com.maddyhome.idea.vim.extension.paragraphmotion
import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Caret
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
@@ -21,10 +20,8 @@ import com.maddyhome.idea.vim.extension.VimExtension
import com.maddyhome.idea.vim.extension.VimExtensionFacade import com.maddyhome.idea.vim.extension.VimExtensionFacade
import com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMappingIfMissing import com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMappingIfMissing
import com.maddyhome.idea.vim.helper.vimForEachCaret import com.maddyhome.idea.vim.helper.vimForEachCaret
import com.maddyhome.idea.vim.key.MappingOwner
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import javax.swing.KeyStroke
internal class ParagraphMotion : VimExtension { internal class ParagraphMotion : VimExtension {
override fun getName(): String = "vim-paragraph-motion" override fun getName(): String = "vim-paragraph-motion"
@@ -33,8 +30,8 @@ internal class ParagraphMotion : VimExtension {
VimExtensionFacade.putExtensionHandlerMapping(MappingMode.NXO, injector.parser.parseKeys("<Plug>(ParagraphNextMotion)"), owner, ParagraphMotionHandler(1), false) VimExtensionFacade.putExtensionHandlerMapping(MappingMode.NXO, injector.parser.parseKeys("<Plug>(ParagraphNextMotion)"), owner, ParagraphMotionHandler(1), false)
VimExtensionFacade.putExtensionHandlerMapping(MappingMode.NXO, injector.parser.parseKeys("<Plug>(ParagraphPrevMotion)"), owner, ParagraphMotionHandler(-1), false) VimExtensionFacade.putExtensionHandlerMapping(MappingMode.NXO, injector.parser.parseKeys("<Plug>(ParagraphPrevMotion)"), owner, ParagraphMotionHandler(-1), false)
putKeyMappingIfMissingFromAndToKeys(MappingMode.NXO, injector.parser.parseKeys("}"), owner, injector.parser.parseKeys("<Plug>(ParagraphNextMotion)"), true) putKeyMappingIfMissing(MappingMode.NXO, injector.parser.parseKeys("}"), owner, injector.parser.parseKeys("<Plug>(ParagraphNextMotion)"), true)
putKeyMappingIfMissingFromAndToKeys(MappingMode.NXO, injector.parser.parseKeys("{"), owner, injector.parser.parseKeys("<Plug>(ParagraphPrevMotion)"), true) putKeyMappingIfMissing(MappingMode.NXO, injector.parser.parseKeys("{"), owner, injector.parser.parseKeys("<Plug>(ParagraphPrevMotion)"), true)
} }
private class ParagraphMotionHandler(private val count: Int) : ExtensionHandler { private class ParagraphMotionHandler(private val count: Int) : ExtensionHandler {
@@ -52,17 +49,4 @@ internal class ParagraphMotion : VimExtension {
?.let { editor.normalizeOffset(it, true) } ?.let { editor.normalizeOffset(it, true) }
} }
} }
// For VIM-3306
@Suppress("SameParameterValue")
private fun putKeyMappingIfMissingFromAndToKeys(
modes: Set<MappingMode>,
fromKeys: List<KeyStroke>,
pluginOwner: MappingOwner,
toKeys: List<KeyStroke>,
recursive: Boolean,
) {
val filteredModes = modes.filterNotTo(HashSet()) { VimPlugin.getKey().hasmapfrom(it, fromKeys) }
putKeyMappingIfMissing(filteredModes, fromKeys, pluginOwner, toKeys, recursive)
}
} }

View File

@@ -8,7 +8,6 @@
package com.maddyhome.idea.vim.extension.replacewithregister package com.maddyhome.idea.vim.extension.replacewithregister
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
@@ -18,7 +17,11 @@ import com.maddyhome.idea.vim.api.getLineEndOffset
import com.maddyhome.idea.vim.api.globalOptions import com.maddyhome.idea.vim.api.globalOptions
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.MappingMode import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.state.mode.isLine
import com.maddyhome.idea.vim.state.mode.selectionType
import com.maddyhome.idea.vim.common.TextRange import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.extension.ExtensionHandler import com.maddyhome.idea.vim.extension.ExtensionHandler
import com.maddyhome.idea.vim.extension.VimExtension import com.maddyhome.idea.vim.extension.VimExtension
@@ -28,6 +31,7 @@ import com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMappingIfMissin
import com.maddyhome.idea.vim.extension.exportOperatorFunction import com.maddyhome.idea.vim.extension.exportOperatorFunction
import com.maddyhome.idea.vim.group.visual.VimSelection import com.maddyhome.idea.vim.group.visual.VimSelection
import com.maddyhome.idea.vim.helper.exitVisualMode import com.maddyhome.idea.vim.helper.exitVisualMode
import com.maddyhome.idea.vim.state.mode.mode
import com.maddyhome.idea.vim.helper.vimStateMachine import com.maddyhome.idea.vim.helper.vimStateMachine
import com.maddyhome.idea.vim.key.OperatorFunction import com.maddyhome.idea.vim.key.OperatorFunction
import com.maddyhome.idea.vim.newapi.IjVimEditor import com.maddyhome.idea.vim.newapi.IjVimEditor
@@ -35,10 +39,6 @@ import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.options.helpers.ClipboardOptionHelper import com.maddyhome.idea.vim.options.helpers.ClipboardOptionHelper
import com.maddyhome.idea.vim.put.PutData import com.maddyhome.idea.vim.put.PutData
import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.state.mode.isLine
import com.maddyhome.idea.vim.state.mode.selectionType
import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.NonNls
internal class ReplaceWithRegister : VimExtension { internal class ReplaceWithRegister : VimExtension {
@@ -65,7 +65,7 @@ internal class ReplaceWithRegister : VimExtension {
val selectionEnd = caret.selectionEnd val selectionEnd = caret.selectionEnd
val visualSelection = caret to VimSelection.create(selectionStart, selectionEnd - 1, typeInEditor, editor) val visualSelection = caret to VimSelection.create(selectionStart, selectionEnd - 1, typeInEditor, editor)
doReplace(editor.ij, context.ij, caret, PutData.VisualSelection(mapOf(visualSelection), typeInEditor)) doReplace(editor.ij, caret, PutData.VisualSelection(mapOf(visualSelection), typeInEditor))
} }
editor.exitVisualMode() editor.exitVisualMode()
} }
@@ -93,7 +93,7 @@ internal class ReplaceWithRegister : VimExtension {
val visualSelection = caret to VimSelection.create(lineStart, lineEnd, SelectionType.LINE_WISE, editor) val visualSelection = caret to VimSelection.create(lineStart, lineEnd, SelectionType.LINE_WISE, editor)
caretsAndSelections += visualSelection caretsAndSelections += visualSelection
doReplace(editor.ij, context.ij, caret, PutData.VisualSelection(mapOf(visualSelection), SelectionType.LINE_WISE)) doReplace(editor.ij, caret, PutData.VisualSelection(mapOf(visualSelection), SelectionType.LINE_WISE))
} }
editor.sortedCarets().forEach { caret -> editor.sortedCarets().forEach { caret ->
@@ -121,7 +121,7 @@ internal class ReplaceWithRegister : VimExtension {
selectionType ?: SelectionType.CHARACTER_WISE, selectionType ?: SelectionType.CHARACTER_WISE,
) )
// todo multicaret // todo multicaret
doReplace(ijEditor, context.ij, editor.primaryCaret(), visualSelection) doReplace(ijEditor, editor.primaryCaret(), visualSelection)
return true return true
} }
@@ -138,45 +138,44 @@ internal class ReplaceWithRegister : VimExtension {
@NonNls private const val RWR_LINE = "<Plug>ReplaceWithRegisterLine" @NonNls private const val RWR_LINE = "<Plug>ReplaceWithRegisterLine"
@NonNls private const val RWR_VISUAL = "<Plug>ReplaceWithRegisterVisual" @NonNls private const val RWR_VISUAL = "<Plug>ReplaceWithRegisterVisual"
@NonNls private const val OPERATOR_FUNC = "ReplaceWithRegisterOperatorFunc" @NonNls private const val OPERATOR_FUNC = "ReplaceWithRegisterOperatorFunc"
private fun doReplace(editor: Editor, caret: ImmutableVimCaret, visualSelection: PutData.VisualSelection) {
val registerGroup = injector.registerGroup
val lastRegisterChar = if (editor.caretModel.caretCount == 1) registerGroup.currentRegister else registerGroup.getCurrentRegisterForMulticaret()
val savedRegister = caret.registerStorage.getRegister(lastRegisterChar) ?: return
var usedType = savedRegister.type
var usedText = savedRegister.text
if (usedType.isLine && usedText?.endsWith('\n') == true) {
// Code from original plugin implementation. Correct text for linewise selected text
usedText = usedText.dropLast(1)
usedType = SelectionType.CHARACTER_WISE
}
val textData = PutData.TextData(usedText, usedType, savedRegister.transferableData, savedRegister.name)
val putData = PutData(
textData,
visualSelection,
1,
insertTextBeforeCaret = true,
rawIndent = true,
caretAfterInsertedText = false,
putToLine = -1,
)
ClipboardOptionHelper.IdeaputDisabler().use {
VimPlugin.getPut().putText(
IjVimEditor(editor),
injector.executionContextManager.onEditor(editor.vim),
putData,
operatorArguments = OperatorArguments(
editor.vimStateMachine?.isOperatorPending ?: false,
0,
editor.vim.mode,
),
saveToRegister = false
)
}
}
} }
} }
private fun doReplace(editor: Editor, context: DataContext, caret: ImmutableVimCaret, visualSelection: PutData.VisualSelection) {
val registerGroup = injector.registerGroup
val lastRegisterChar = if (editor.caretModel.caretCount == 1) registerGroup.currentRegister else registerGroup.getCurrentRegisterForMulticaret()
val savedRegister = caret.registerStorage.getRegister(lastRegisterChar) ?: return
var usedType = savedRegister.type
var usedText = savedRegister.text
if (usedType.isLine && usedText?.endsWith('\n') == true) {
// Code from original plugin implementation. Correct text for linewise selected text
usedText = usedText.dropLast(1)
usedType = SelectionType.CHARACTER_WISE
}
val textData = PutData.TextData(usedText, usedType, savedRegister.transferableData, savedRegister.name)
val putData = PutData(
textData,
visualSelection,
1,
insertTextBeforeCaret = true,
rawIndent = true,
caretAfterInsertedText = false,
putToLine = -1,
)
val vimEditor = editor.vim
ClipboardOptionHelper.IdeaputDisabler().use {
VimPlugin.getPut().putText(
vimEditor,
context.vim,
putData,
operatorArguments = OperatorArguments(
editor.vimStateMachine?.isOperatorPending(vimEditor.mode) ?: false,
0,
editor.vim.mode,
),
saveToRegister = false
)
}
}

View File

@@ -36,7 +36,6 @@ import com.maddyhome.idea.vim.helper.StrictMode
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import java.awt.Font import java.awt.Font
import java.awt.event.KeyEvent import java.awt.event.KeyEvent
import java.util.*
import javax.swing.Timer import javax.swing.Timer
@@ -49,20 +48,17 @@ internal class IdeaVimSneakExtension : VimExtension {
override fun init() { override fun init() {
val highlightHandler = HighlightHandler() val highlightHandler = HighlightHandler()
mapToFunctionAndProvideKeys("s", SneakHandler(highlightHandler, Direction.FORWARD), MappingMode.NXO) mapToFunctionAndProvideKeys("s", SneakHandler(highlightHandler, Direction.FORWARD))
mapToFunctionAndProvideKeys("S", SneakHandler(highlightHandler, Direction.BACKWARD))
// vim-sneak uses `Z` for visual mode because `S` conflict with vim-sneak plugin VIM-3330
mapToFunctionAndProvideKeys("S", SneakHandler(highlightHandler, Direction.BACKWARD), MappingMode.NO)
mapToFunctionAndProvideKeys("Z", SneakHandler(highlightHandler, Direction.BACKWARD), MappingMode.X)
// workaround to support ; and , commands // workaround to support ; and , commands
mapToFunctionAndProvideKeys("f", SneakMemoryHandler("f"), MappingMode.NXO) mapToFunctionAndProvideKeys("f", SneakMemoryHandler("f"))
mapToFunctionAndProvideKeys("F", SneakMemoryHandler("F"), MappingMode.NXO) mapToFunctionAndProvideKeys("F", SneakMemoryHandler("F"))
mapToFunctionAndProvideKeys("t", SneakMemoryHandler("t"), MappingMode.NXO) mapToFunctionAndProvideKeys("t", SneakMemoryHandler("t"))
mapToFunctionAndProvideKeys("T", SneakMemoryHandler("T"), MappingMode.NXO) mapToFunctionAndProvideKeys("T", SneakMemoryHandler("T"))
mapToFunctionAndProvideKeys(";", SneakRepeatHandler(highlightHandler, RepeatDirection.IDENTICAL), MappingMode.NXO) mapToFunctionAndProvideKeys(";", SneakRepeatHandler(highlightHandler, RepeatDirection.IDENTICAL))
mapToFunctionAndProvideKeys(",", SneakRepeatHandler(highlightHandler, RepeatDirection.REVERSE), MappingMode.NXO) mapToFunctionAndProvideKeys(",", SneakRepeatHandler(highlightHandler, RepeatDirection.REVERSE))
} }
private class SneakHandler( private class SneakHandler(
@@ -118,7 +114,7 @@ internal class IdeaVimSneakExtension : VimExtension {
var lastSymbols: String = "" var lastSymbols: String = ""
fun jumpTo(editor: VimEditor, charone: Char, chartwo: Char, sneakDirection: Direction): TextRange? { fun jumpTo(editor: VimEditor, charone: Char, chartwo: Char, sneakDirection: Direction): TextRange? {
val caret = editor.primaryCaret() val caret = editor.primaryCaret()
val position = caret.offset val position = caret.offset.point
val chars = editor.text() val chars = editor.text()
val foundPosition = sneakDirection.findBiChar(editor, chars, position, charone, chartwo) val foundPosition = sneakDirection.findBiChar(editor, chars, position, charone, chartwo)
if (foundPosition != null) { if (foundPosition != null) {
@@ -277,18 +273,16 @@ internal class IdeaVimSneakExtension : VimExtension {
* Map some <Plug>(keys) command to given handler * Map some <Plug>(keys) command to given handler
* and create mapping to <Plug>(prefix)[keys] * and create mapping to <Plug>(prefix)[keys]
*/ */
private fun VimExtension.mapToFunctionAndProvideKeys( private fun VimExtension.mapToFunctionAndProvideKeys(keys: String, handler: ExtensionHandler) {
keys: String, handler: ExtensionHandler, mappingModes: EnumSet<MappingMode>
) {
VimExtensionFacade.putExtensionHandlerMapping( VimExtensionFacade.putExtensionHandlerMapping(
mappingModes, MappingMode.NXO,
injector.parser.parseKeys(command(keys)), injector.parser.parseKeys(command(keys)),
owner, owner,
handler, handler,
false false
) )
VimExtensionFacade.putExtensionHandlerMapping( VimExtensionFacade.putExtensionHandlerMapping(
mappingModes, MappingMode.NXO,
injector.parser.parseKeys(commandFromOriginalPlugin(keys)), injector.parser.parseKeys(commandFromOriginalPlugin(keys)),
owner, owner,
handler, handler,
@@ -300,17 +294,17 @@ private fun VimExtension.mapToFunctionAndProvideKeys(
// - The shortcut should not be registered if any of these mappings is overridden in .ideavimrc // - The shortcut should not be registered if any of these mappings is overridden in .ideavimrc
// - The shortcut should not be registered if some other shortcut for this key exists // - The shortcut should not be registered if some other shortcut for this key exists
val fromKeys = injector.parser.parseKeys(keys) val fromKeys = injector.parser.parseKeys(keys)
val filteredModes = mappingModes.filterNotTo(HashSet()) { val filteredModes = MappingMode.NXO.filterNotTo(HashSet()) {
VimPlugin.getKey().hasmapto(it, injector.parser.parseKeys(command(keys))) VimPlugin.getKey().hasmapto(it, injector.parser.parseKeys(command(keys)))
} }
val filteredModes2 = mappingModes.filterNotTo(HashSet()) { val filteredModes2 = MappingMode.NXO.filterNotTo(HashSet()) {
VimPlugin.getKey().hasmapto(it, injector.parser.parseKeys(commandFromOriginalPlugin(keys))) VimPlugin.getKey().hasmapto(it, injector.parser.parseKeys(commandFromOriginalPlugin(keys)))
} }
val filteredFromModes = mappingModes.filterNotTo(HashSet()) { val filteredFromModes = MappingMode.NXO.filterNotTo(HashSet()) {
injector.keyGroup.hasmapfrom(it, fromKeys) injector.keyGroup.hasmapfrom(it, fromKeys)
} }
val doubleFiltered = mappingModes val doubleFiltered = MappingMode.NXO
.filter { it in filteredModes2 && it in filteredModes && it in filteredFromModes } .filter { it in filteredModes2 && it in filteredModes && it in filteredFromModes }
.toSet() .toSet()
putKeyMapping(doubleFiltered, fromKeys, owner, injector.parser.parseKeys(command(keys)), true) putKeyMapping(doubleFiltered, fromKeys, owner, injector.parser.parseKeys(command(keys)), true)

View File

@@ -1,30 +0,0 @@
package com.maddyhome.idea.vim.extension.surround
import com.intellij.util.text.CharSequenceSubSequence
internal data class RepeatedCharSequence(val text: CharSequence, val count: Int) : CharSequence {
override val length = text.length * count
override fun get(index: Int): Char {
if (index < 0 || index >= length) throw IndexOutOfBoundsException()
return text[index % text.length]
}
override fun subSequence(startIndex: Int, endIndex: Int): CharSequence {
return CharSequenceSubSequence(this, startIndex, endIndex)
}
override fun toString(): String {
return text.repeat(count)
}
companion object {
fun of(text: CharSequence, count: Int): CharSequence {
return when (count) {
0 -> ""
1 -> text
else -> RepeatedCharSequence(text, count)
}
}
}
}

View File

@@ -7,14 +7,12 @@
*/ */
package com.maddyhome.idea.vim.extension.surround package com.maddyhome.idea.vim.extension.surround
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimChangeGroup
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.endsWithNewLine import com.maddyhome.idea.vim.api.endsWithNewLine
import com.maddyhome.idea.vim.api.getLeadingCharacterOffset import com.maddyhome.idea.vim.api.getLeadingCharacterOffset
@@ -35,17 +33,15 @@ import com.maddyhome.idea.vim.extension.VimExtensionFacade.putExtensionHandlerMa
import com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMappingIfMissing import com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMappingIfMissing
import com.maddyhome.idea.vim.extension.VimExtensionFacade.setRegisterForCaret import com.maddyhome.idea.vim.extension.VimExtensionFacade.setRegisterForCaret
import com.maddyhome.idea.vim.extension.exportOperatorFunction import com.maddyhome.idea.vim.extension.exportOperatorFunction
import com.maddyhome.idea.vim.group.findBlockRange import com.maddyhome.idea.vim.state.mode.mode
import com.maddyhome.idea.vim.helper.runWithEveryCaretAndRestore
import com.maddyhome.idea.vim.key.OperatorFunction import com.maddyhome.idea.vim.key.OperatorFunction
import com.maddyhome.idea.vim.newapi.IjVimCaret
import com.maddyhome.idea.vim.newapi.IjVimEditor
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.options.helpers.ClipboardOptionHelper import com.maddyhome.idea.vim.options.helpers.ClipboardOptionHelper
import com.maddyhome.idea.vim.put.PutData import com.maddyhome.idea.vim.put.PutData
import com.maddyhome.idea.vim.state.mode.Mode import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.SelectionType import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.state.mode.mode
import com.maddyhome.idea.vim.state.mode.selectionType import com.maddyhome.idea.vim.state.mode.selectionType
import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.NonNls
import java.awt.event.KeyEvent import java.awt.event.KeyEvent
@@ -82,7 +78,7 @@ internal class VimSurroundExtension : VimExtension {
putKeyMappingIfMissing(MappingMode.XO, injector.parser.parseKeys("S"), owner, injector.parser.parseKeys("<Plug>VSurround"), true) putKeyMappingIfMissing(MappingMode.XO, injector.parser.parseKeys("S"), owner, injector.parser.parseKeys("<Plug>VSurround"), true)
} }
VimExtensionFacade.exportOperatorFunction(OPERATOR_FUNC, Operator(supportsMultipleCursors = false, count = 1)) // TODO VimExtensionFacade.exportOperatorFunction(OPERATOR_FUNC, Operator())
} }
private class YSurroundHandler : ExtensionHandler { private class YSurroundHandler : ExtensionHandler {
@@ -101,7 +97,7 @@ internal class VimSurroundExtension : VimExtension {
val ijEditor = editor.ij val ijEditor = editor.ij
val c = getChar(ijEditor) val c = getChar(ijEditor)
if (c.code == 0) return if (c.code == 0) return
val pair = getOrInputPair(c, ijEditor, context.ij) ?: return val pair = getOrInputPair(c, ijEditor) ?: return
editor.forEachCaret { editor.forEachCaret {
val line = it.getBufferPosition().line val line = it.getBufferPosition().line
@@ -110,7 +106,7 @@ internal class VimSurroundExtension : VimExtension {
val lastNonWhiteSpaceOffset = getLastNonWhitespaceCharacterOffset(editor.text(), lineStartOffset, lineEndOffset) val lastNonWhiteSpaceOffset = getLastNonWhitespaceCharacterOffset(editor.text(), lineStartOffset, lineEndOffset)
if (lastNonWhiteSpaceOffset != null) { if (lastNonWhiteSpaceOffset != null) {
val range = TextRange(lineStartOffset, lastNonWhiteSpaceOffset + 1) val range = TextRange(lineStartOffset, lastNonWhiteSpaceOffset + 1)
performSurround(pair, range, it, count = operatorArguments.count1) performSurround(pair, range, it)
} }
// it.moveToOffset(lineStartOffset) // it.moveToOffset(lineStartOffset)
} }
@@ -130,13 +126,15 @@ internal class VimSurroundExtension : VimExtension {
private class VSurroundHandler : ExtensionHandler { private class VSurroundHandler : ExtensionHandler {
override fun execute(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments) { override fun execute(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments) {
val selectionStart = editor.ij.caretModel.primaryCaret.selectionStart
// NB: Operator ignores SelectionType anyway // NB: Operator ignores SelectionType anyway
if (!Operator(supportsMultipleCursors = true, count = operatorArguments.count1).apply(editor, context, editor.mode.selectionType)) { if (!Operator().apply(editor, context, editor.mode.selectionType)) {
return return
} }
runWriteAction { runWriteAction {
// Leave visual mode // Leave visual mode
executeNormalWithoutMapping(injector.parser.parseKeys("<Esc>"), editor.ij) executeNormalWithoutMapping(injector.parser.parseKeys("<Esc>"), editor.ij)
editor.ij.caretModel.moveToOffset(selectionStart)
} }
} }
} }
@@ -151,16 +149,12 @@ internal class VimSurroundExtension : VimExtension {
val charTo = getChar(editor.ij) val charTo = getChar(editor.ij)
if (charTo.code == 0) return if (charTo.code == 0) return
val newSurround = getOrInputPair(charTo, editor.ij, context.ij) ?: return val newSurround = getOrInputPair(charTo, editor.ij) ?: return
runWriteAction { change(editor, context, charFrom, newSurround) } runWriteAction { change(editor, context, charFrom, newSurround) }
} }
companion object { companion object {
fun change(editor: VimEditor, context: ExecutionContext, charFrom: Char, newSurround: Pair<String, String>?) { fun change(editor: VimEditor, context: ExecutionContext, charFrom: Char, newSurround: Pair<String, String>?) {
editor.ij.runWithEveryCaretAndRestore { changeAtCaret(editor, context, charFrom, newSurround) }
}
fun changeAtCaret(editor: VimEditor, context: ExecutionContext, charFrom: Char, newSurround: Pair<String, String>?) {
// Save old register values for carets // Save old register values for carets
val surroundings = editor.sortedCarets() val surroundings = editor.sortedCarets()
.map { .map {
@@ -228,12 +222,12 @@ internal class VimSurroundExtension : VimExtension {
val searchHelper = injector.searchHelper val searchHelper = injector.searchHelper
return when (char) { return when (char) {
't' -> searchHelper.findBlockTagRange(editor, caret, 1, true) 't' -> searchHelper.findBlockTagRange(editor, caret, 1, true)
'(', ')', 'b' -> findBlockRange(editor, caret, '(', 1, true) '(', ')', 'b' -> searchHelper.findBlockRange(editor, caret, '(', 1, true)
'[', ']' -> findBlockRange(editor, caret, '[', 1, true) '[', ']' -> searchHelper.findBlockRange(editor, caret, '[', 1, true)
'{', '}', 'B' -> findBlockRange(editor, caret, '{', 1, true) '{', '}', 'B' -> searchHelper.findBlockRange(editor, caret, '{', 1, true)
'<', '>' -> findBlockRange(editor, caret, '<', 1, true) '<', '>' -> searchHelper.findBlockRange(editor, caret, '<', 1, true)
'`', '\'', '"' -> { '`', '\'', '"' -> {
val caretOffset = caret.offset val caretOffset = caret.offset.point
val text = editor.text() val text = editor.text()
if (text.getOrNull(caretOffset - 1) == char && text.getOrNull(caretOffset) == char) { if (text.getOrNull(caretOffset - 1) == char && text.getOrNull(caretOffset) == char) {
TextRange(caretOffset - 1, caretOffset + 1) TextRange(caretOffset - 1, caretOffset + 1)
@@ -268,40 +262,19 @@ internal class VimSurroundExtension : VimExtension {
} }
} }
private class Operator(private val supportsMultipleCursors: Boolean, private val count: Int) : OperatorFunction { private class Operator : OperatorFunction {
override fun apply(vimEditor: VimEditor, context: ExecutionContext, selectionType: SelectionType?): Boolean { override fun apply(editor: VimEditor, context: ExecutionContext, selectionType: SelectionType?): Boolean {
val ijEditor = vimEditor.ij val ijEditor = editor.ij
val c = getChar(ijEditor) val c = getChar(ijEditor)
if (c.code == 0) return true if (c.code == 0) return true
val pair = getOrInputPair(c, ijEditor, context.ij) ?: return false val pair = getOrInputPair(c, ijEditor) ?: return false
runWriteAction {
val change = VimPlugin.getChange()
if (supportsMultipleCursors) {
ijEditor.runWithEveryCaretAndRestore {
applyOnce(ijEditor, change, pair, count)
}
}
else {
applyOnce(ijEditor, change, pair, count)
// Jump back to start
executeNormalWithoutMapping(injector.parser.parseKeys("`["), ijEditor)
}
}
return true
}
private fun applyOnce(editor: Editor, change: VimChangeGroup, pair: Pair<String, String>, count: Int) {
// XXX: Will it work with line-wise or block-wise selections? // XXX: Will it work with line-wise or block-wise selections?
val primaryCaret = editor.caretModel.primaryCaret val range = getSurroundRange(editor.currentCaret()) ?: return false
val range = getSurroundRange(primaryCaret.vim) performSurround(pair, range, editor.currentCaret(), selectionType == SelectionType.LINE_WISE)
if (range != null) { // Jump back to start
val start = RepeatedCharSequence.of(pair.first, count) executeNormalWithoutMapping(injector.parser.parseKeys("`["), ijEditor)
val end = RepeatedCharSequence.of(pair.second, count) return true
change.insertText(IjVimEditor(editor), IjVimCaret(primaryCaret), range.startOffset, start)
change.insertText(IjVimEditor(editor), IjVimCaret(primaryCaret), range.endOffset + start.length, end)
}
} }
private fun getSurroundRange(caret: VimCaret): TextRange? { private fun getSurroundRange(caret: VimCaret): TextRange? {
@@ -348,8 +321,8 @@ private fun getSurroundPair(c: Char): Pair<String, String>? = if (c in SURROUND_
null null
} }
private fun inputTagPair(editor: Editor, context: DataContext): Pair<String, String>? { private fun inputTagPair(editor: Editor): Pair<String, String>? {
val tagInput = inputString(editor, context, "<", '>') val tagInput = inputString(editor, "<", '>')
val matcher = tagNameAndAttributesCapturePattern.matcher(tagInput) val matcher = tagNameAndAttributesCapturePattern.matcher(tagInput)
return if (matcher.find()) { return if (matcher.find()) {
val tagName = matcher.group(1) val tagName = matcher.group(1)
@@ -362,18 +335,17 @@ private fun inputTagPair(editor: Editor, context: DataContext): Pair<String, Str
private fun inputFunctionName( private fun inputFunctionName(
editor: Editor, editor: Editor,
context: DataContext,
withInternalSpaces: Boolean, withInternalSpaces: Boolean,
): Pair<String, String>? { ): Pair<String, String>? {
val functionNameInput = inputString(editor, context, "function: ", null) val functionNameInput = inputString(editor, "function: ", null)
if (functionNameInput.isEmpty()) return null if (functionNameInput.isEmpty()) return null
return if (withInternalSpaces) "$functionNameInput( " to " )" else "$functionNameInput(" to ")" return if (withInternalSpaces) "$functionNameInput( " to " )" else "$functionNameInput(" to ")"
} }
private fun getOrInputPair(c: Char, editor: Editor, context: DataContext): Pair<String, String>? = when (c) { private fun getOrInputPair(c: Char, editor: Editor): Pair<String, String>? = when (c) {
'<', 't' -> inputTagPair(editor, context) '<', 't' -> inputTagPair(editor)
'f' -> inputFunctionName(editor, context, false) 'f' -> inputFunctionName(editor, false)
'F' -> inputFunctionName(editor, context, true) 'F' -> inputFunctionName(editor, true)
else -> getSurroundPair(c) else -> getSurroundPair(c)
} }
@@ -389,15 +361,15 @@ private fun getChar(editor: Editor): Char {
return res return res
} }
private fun performSurround(pair: Pair<String, String>, range: TextRange, caret: VimCaret, count: Int, tagsOnNewLines: Boolean = false) { private fun performSurround(pair: Pair<String, String>, range: TextRange, caret: VimCaret, tagsOnNewLines: Boolean = false) {
runWriteAction { runWriteAction {
val editor = caret.editor val editor = caret.editor
val change = VimPlugin.getChange() val change = VimPlugin.getChange()
val leftSurround = RepeatedCharSequence.of(pair.first + if (tagsOnNewLines) "\n" else "", count) val leftSurround = pair.first + if (tagsOnNewLines) "\n" else ""
val isEOF = range.endOffset == editor.text().length val isEOF = range.endOffset == editor.text().length
val hasNewLine = editor.endsWithNewLine() val hasNewLine = editor.endsWithNewLine()
val rightSurround = (if (tagsOnNewLines) { val rightSurround = if (tagsOnNewLines) {
if (isEOF && !hasNewLine) { if (isEOF && !hasNewLine) {
"\n" + pair.second "\n" + pair.second
} else { } else {
@@ -405,7 +377,7 @@ private fun performSurround(pair: Pair<String, String>, range: TextRange, caret:
} }
} else { } else {
pair.second pair.second
}).let { RepeatedCharSequence.of(it, count) } }
change.insertText(editor, caret, range.startOffset, leftSurround) change.insertText(editor, caret, range.startOffset, leftSurround)
change.insertText(editor, caret, range.endOffset + leftSurround.length, rightSurround) change.insertText(editor, caret, range.endOffset + leftSurround.length, rightSurround)

View File

@@ -138,7 +138,7 @@ public class VimTextObjEntireExtension implements VimExtension {
final EntireTextObjectHandler textObjectHandler = new EntireTextObjectHandler(ignoreLeadingAndTrailing); final EntireTextObjectHandler textObjectHandler = new EntireTextObjectHandler(ignoreLeadingAndTrailing);
//noinspection DuplicatedCode //noinspection DuplicatedCode
if (!vimStateMachine.isOperatorPending(editor.getMode())) { if (!vimStateMachine.isOperatorPending()) {
((IjVimEditor) editor).getEditor().getCaretModel().runForEachCaret((Caret caret) -> { ((IjVimEditor) editor).getEditor().getCaretModel().runForEachCaret((Caret caret) -> {
final TextRange range = textObjectHandler.getRange(editor, new IjVimCaret(caret), context, count, 0); final TextRange range = textObjectHandler.getRange(editor, new IjVimCaret(caret), context, count, 0);
if (range != null) { if (range != null) {

View File

@@ -267,7 +267,7 @@ public class VimIndentObject implements VimExtension {
final IndentObjectHandler textObjectHandler = new IndentObjectHandler(includeAbove, includeBelow); final IndentObjectHandler textObjectHandler = new IndentObjectHandler(includeAbove, includeBelow);
if (!vimStateMachine.isOperatorPending(editor.getMode())) { 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); final TextRange range = textObjectHandler.getRange(vimEditor, new IjVimCaret(caret), context, count, 0);
if (range != null) { if (range != null) {

View File

@@ -68,17 +68,17 @@ import com.maddyhome.idea.vim.newapi.IjEditorExecutionContext
import com.maddyhome.idea.vim.newapi.IjVimCaret import com.maddyhome.idea.vim.newapi.IjVimCaret
import com.maddyhome.idea.vim.newapi.IjVimEditor import com.maddyhome.idea.vim.newapi.IjVimEditor
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.regexp.VimRegex
import com.maddyhome.idea.vim.regexp.match.VimMatchResult
import com.maddyhome.idea.vim.state.mode.Mode import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.Mode.VISUAL import com.maddyhome.idea.vim.state.mode.Mode.VISUAL
import com.maddyhome.idea.vim.state.mode.SelectionType import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.state.mode.mode
import com.maddyhome.idea.vim.vimscript.model.commands.SortOption import com.maddyhome.idea.vim.vimscript.model.commands.SortOption
import org.jetbrains.annotations.TestOnly import org.jetbrains.annotations.TestOnly
import java.math.BigInteger import java.math.BigInteger
import java.util.* import java.util.*
import java.util.function.Consumer import java.util.function.Consumer
import kotlin.math.max import kotlin.math.max
import kotlin.math.min
/** /**
* Provides all the insert/replace related functionality * Provides all the insert/replace related functionality
@@ -197,7 +197,7 @@ public class ChangeGroup : VimChangeGroupBase() {
val allowWrap = injector.options(editor).whichwrap.contains("~") val allowWrap = injector.options(editor).whichwrap.contains("~")
var motion = injector.motion.getHorizontalMotion(editor, caret, count, true, allowWrap) var motion = injector.motion.getHorizontalMotion(editor, caret, count, true, allowWrap)
if (motion is Motion.Error) return false if (motion is Motion.Error) return false
changeCase(editor, caret, caret.offset, (motion as AbsoluteOffset).offset, CharacterHelper.CASE_TOGGLE) changeCase(editor, caret, caret.offset.point, (motion as AbsoluteOffset).offset, CharacterHelper.CASE_TOGGLE)
motion = injector.motion.getHorizontalMotion( motion = injector.motion.getHorizontalMotion(
editor, editor,
caret, caret,
@@ -235,7 +235,8 @@ public class ChangeGroup : VimChangeGroupBase() {
} }
val lineLength = editor.lineLength(line) val lineLength = editor.lineLength(line)
if (column < VimMotionGroupBase.LAST_COLUMN && lineLength < column) { if (column < VimMotionGroupBase.LAST_COLUMN && lineLength < column) {
val pad = EditorHelper.pad((editor as IjVimEditor).editor, line, column) val pad =
EditorHelper.pad((editor as IjVimEditor).editor, (context as IjEditorExecutionContext).context, line, column)
val offset = editor.getLineEndOffset(line) val offset = editor.getLineEndOffset(line)
insertText(editor, caret, offset, pad) insertText(editor, caret, offset, pad)
} }
@@ -394,7 +395,6 @@ public class ChangeGroup : VimChangeGroupBase() {
context: ExecutionContext, context: ExecutionContext,
range: TextRange, range: TextRange,
) { ) {
val startPos = editor.offsetToBufferPosition(caret.offset)
val startOffset = editor.getLineStartForOffset(range.startOffset) val startOffset = editor.getLineStartForOffset(range.startOffset)
val endOffset = editor.getLineEndForOffset(range.endOffset) val endOffset = editor.getLineEndForOffset(range.endOffset)
val ijEditor = (editor as IjVimEditor).editor val ijEditor = (editor as IjVimEditor).editor
@@ -419,7 +419,11 @@ public class ChangeGroup : VimChangeGroupBase() {
} }
} }
val afterAction = { val afterAction = {
caret.moveToOffset(injector.motion.moveCaretToLineStartSkipLeading(editor, startPos.line)) val firstLine = editor.offsetToBufferPosition(
min(startOffset.toDouble(), endOffset.toDouble()).toInt()
).line
val newOffset = injector.motion.moveCaretToLineStartSkipLeading(editor, firstLine)
caret.moveToOffset(newOffset)
restoreCursor(editor, caret, (caret as IjVimCaret).caret.logicalPosition.line) restoreCursor(editor, caret, (caret as IjVimCaret).caret.logicalPosition.line)
} }
if (project != null) { if (project != null) {
@@ -450,7 +454,7 @@ public class ChangeGroup : VimChangeGroupBase() {
dir: Int, dir: Int,
operatorArguments: OperatorArguments, operatorArguments: OperatorArguments,
) { ) {
val start = caret.offset val start = caret.offset.point
val end = injector.motion.moveCaretToRelativeLineEnd(editor, caret, lines - 1, true) val end = injector.motion.moveCaretToRelativeLineEnd(editor, caret, lines - 1, true)
indentRange(editor, caret, context, TextRange(start, end), 1, dir, operatorArguments) indentRange(editor, caret, context, TextRange(start, end), 1, dir, operatorArguments)
} }
@@ -484,7 +488,7 @@ public class ChangeGroup : VimChangeGroupBase() {
// Remember the current caret column // Remember the current caret column
val intendedColumn = caret.vimLastColumn val intendedColumn = caret.vimLastColumn
val indentConfig = create((editor as IjVimEditor).editor) val indentConfig = create((editor as IjVimEditor).editor, (context as IjEditorExecutionContext).context)
val sline = editor.offsetToBufferPosition(range.startOffset).line val sline = editor.offsetToBufferPosition(range.startOffset).line
val endLogicalPosition = editor.offsetToBufferPosition(range.endOffset) val endLogicalPosition = editor.offsetToBufferPosition(range.endOffset)
val eline = if (endLogicalPosition.column == 0) max((endLogicalPosition.line - 1).toDouble(), 0.0) val eline = if (endLogicalPosition.column == 0) max((endLogicalPosition.line - 1).toDouble(), 0.0)
@@ -573,62 +577,48 @@ public class ChangeGroup : VimChangeGroupBase() {
} }
val startOffset = editor.getLineStartOffset(startLine) val startOffset = editor.getLineStartOffset(startLine)
val endOffset = editor.getLineEndOffset(endLine) val endOffset = editor.getLineEndOffset(endLine)
return sortTextRange(editor, caret, startOffset, endOffset, lineComparator, sortOptions)
}
val selectedText = (editor as IjVimEditor).editor.document.getText(TextRangeInterval(startOffset, endOffset)) /**
val lines = selectedText.split("\n") * Sorts a text range with a comparator. Returns true if a replace was performed, false otherwise.
val modifiedLines = sortOptions.pattern?.let { *
if (sortOptions.sortOnPattern) { * @param editor The editor to replace text in
extractPatternFromLines(editor, lines, startLine, it) * @param start The starting position for the sort
} else { * @param end The ending position for the sort
deletePatternFromLines(editor, lines, startLine, it) * @param lineComparator The comparator to use to sort
} * @param sortOption The option to sort the range
} ?: lines * @return true if able to sort the text, false if not
val sortedLines = lines.zip(modifiedLines) */
.sortedWith { l1, l2 -> lineComparator.compare(l1.second, l2.second) } private fun sortTextRange(
.map {it.first} editor: VimEditor,
.toMutableList() caret: VimCaret,
start: Int,
if (sortOptions.unique) { end: Int,
val iterator = sortedLines.iterator() lineComparator: Comparator<String>,
sortOption: SortOption,
): Boolean {
val selectedText = (editor as IjVimEditor).editor.document.getText(TextRangeInterval(start, end))
val lines: MutableList<String> = selectedText.split("\n").sortedWith(lineComparator).toMutableList()
if (sortOption.unique) {
val iterator = lines.iterator()
var previous: String? = null var previous: String? = null
while (iterator.hasNext()) { while (iterator.hasNext()) {
val current = iterator.next() val current = iterator.next()
if (current == previous || sortOptions.ignoreCase && current.equals(previous, ignoreCase = true)) { if (current == previous || sortOption.ignoreCase && current.equals(previous, ignoreCase = true)) {
iterator.remove() iterator.remove()
} else { } else {
previous = current previous = current
} }
} }
} }
if (sortedLines.isEmpty()) { if (lines.size < 1) {
return false return false
} }
replaceText(editor, caret, startOffset, endOffset, StringUtil.join(sortedLines, "\n")) replaceText(editor, caret, start, end, StringUtil.join(lines, "\n"))
return true return true
} }
private fun extractPatternFromLines(editor: VimEditor, lines: List<String>, startLine: Int, pattern: String): List<String> {
val regex = VimRegex(pattern)
return lines.mapIndexed { i: Int, line: String ->
val result = regex.findInLine(editor, startLine + i, 0)
when (result) {
is VimMatchResult.Success -> result.value
is VimMatchResult.Failure -> line
}
}
}
private fun deletePatternFromLines(editor: VimEditor, lines: List<String>, startLine: Int, pattern: String): List<String> {
val regex = VimRegex(pattern)
return lines.mapIndexed { i: Int, line: String ->
val result = regex.findInLine(editor, startLine + i, 0)
when (result) {
is VimMatchResult.Success -> line.substring(result.value.length, line.length)
is VimMatchResult.Failure -> line
}
}
}
/** /**
* Perform increment and decrement for numbers in visual mode * Perform increment and decrement for numbers in visual mode
* *

View File

@@ -11,9 +11,6 @@ package com.maddyhome.idea.vim.group;
import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.execution.impl.ConsoleViewImpl;
import com.intellij.find.EditorSearchSession; import com.intellij.find.EditorSearchSession;
import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.client.ClientAppSession;
import com.intellij.openapi.client.ClientKind;
import com.intellij.openapi.client.ClientSessionsManager;
import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State; import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.Storage;
@@ -25,10 +22,7 @@ import com.intellij.openapi.project.Project;
import com.maddyhome.idea.vim.KeyHandler; import com.maddyhome.idea.vim.KeyHandler;
import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.api.*; import com.maddyhome.idea.vim.api.*;
import com.maddyhome.idea.vim.helper.CaretVisualAttributesHelperKt; import com.maddyhome.idea.vim.helper.*;
import com.maddyhome.idea.vim.helper.CommandStateHelper;
import com.maddyhome.idea.vim.helper.EditorHelper;
import com.maddyhome.idea.vim.helper.UserDataManager;
import com.maddyhome.idea.vim.newapi.IjVimDocument; import com.maddyhome.idea.vim.newapi.IjVimDocument;
import com.maddyhome.idea.vim.newapi.IjVimEditor; import com.maddyhome.idea.vim.newapi.IjVimEditor;
import com.maddyhome.idea.vim.options.EffectiveOptionValueChangeListener; import com.maddyhome.idea.vim.options.EffectiveOptionValueChangeListener;
@@ -40,10 +34,10 @@ import org.jetbrains.annotations.Nullable;
import java.util.Collection; import java.util.Collection;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.maddyhome.idea.vim.api.VimInjectorKt.injector; import static com.maddyhome.idea.vim.api.VimInjectorKt.injector;
import static com.maddyhome.idea.vim.api.VimInjectorKt.options; import static com.maddyhome.idea.vim.api.VimInjectorKt.options;
import static com.maddyhome.idea.vim.helper.CaretVisualAttributesHelperKt.updateCaretsVisualAttributes;
import static com.maddyhome.idea.vim.newapi.IjVimInjectorKt.ijOptions; import static com.maddyhome.idea.vim.newapi.IjVimInjectorKt.ijOptions;
/** /**
@@ -210,8 +204,7 @@ public class EditorGroup implements PersistentStateComponent<Element>, VimEditor
} }
public void editorCreated(@NotNull Editor editor) { public void editorCreated(@NotNull Editor editor) {
UserDataManager.setVimInitialised(editor, true); DocumentManager.INSTANCE.addListeners(editor.getDocument());
VimPlugin.getKey().registerRequiredShortcutKeys(new IjVimEditor(editor)); VimPlugin.getKey().registerRequiredShortcutKeys(new IjVimEditor(editor));
initLineNumbers(editor); initLineNumbers(editor);
@@ -235,7 +228,7 @@ public class EditorGroup implements PersistentStateComponent<Element>, VimEditor
// Note that we need a similar check in `VimEditor.isWritable` to allow Escape to work to exit insert mode. We need // Note that we need a similar check in `VimEditor.isWritable` to allow Escape to work to exit insert mode. We need
// to know that a read-only editor that is hosting a console view with a running process can be treated as writable. // to know that a read-only editor that is hosting a console view with a running process can be treated as writable.
Runnable switchToInsertMode = () -> { Runnable switchToInsertMode = () -> {
ExecutionContext context = injector.getExecutionContextManager().getEditorExecutionContext(new IjVimEditor(editor)); ExecutionContext.Editor context = injector.getExecutionContextManager().onEditor(new IjVimEditor(editor), null);
VimPlugin.getChange().insertBeforeCursor(new IjVimEditor(editor), context); VimPlugin.getChange().insertBeforeCursor(new IjVimEditor(editor), context);
KeyHandler.getInstance().reset(new IjVimEditor(editor)); KeyHandler.getInstance().reset(new IjVimEditor(editor));
}; };
@@ -253,13 +246,14 @@ public class EditorGroup implements PersistentStateComponent<Element>, VimEditor
switchToInsertMode.run(); switchToInsertMode.run();
} }
}); });
updateCaretsVisualAttributes(new IjVimEditor(editor)); updateCaretsVisualAttributes(editor);
} }
public void editorDeinit(@NotNull Editor editor, boolean isReleased) { public void editorDeinit(@NotNull Editor editor, boolean isReleased) {
deinitLineNumbers(editor, isReleased); deinitLineNumbers(editor, isReleased);
UserDataManager.unInitializeEditor(editor); UserDataManager.unInitializeEditor(editor);
VimPlugin.getKey().unregisterShortcutKeys(new IjVimEditor(editor)); VimPlugin.getKey().unregisterShortcutKeys(new IjVimEditor(editor));
DocumentManager.INSTANCE.removeListeners(editor.getDocument());
CaretVisualAttributesHelperKt.removeCaretsVisualAttributes(editor); CaretVisualAttributesHelperKt.removeCaretsVisualAttributes(editor);
} }
@@ -290,18 +284,6 @@ public class EditorGroup implements PersistentStateComponent<Element>, VimEditor
notifyIdeaJoin(((IjVimEditor) editor).getEditor().getProject(), editor); notifyIdeaJoin(((IjVimEditor) editor).getEditor().getProject(), editor);
} }
@Override
public void updateCaretsVisualAttributes(@NotNull VimEditor editor) {
Editor ijEditor = ((IjVimEditor) editor).getEditor();
CaretVisualAttributesHelperKt.updateCaretsVisualAttributes(ijEditor);
}
@Override
public void updateCaretsVisualPosition(@NotNull VimEditor editor) {
Editor ijEditor = ((IjVimEditor) editor).getEditor();
CaretVisualAttributesHelperKt.updateCaretsVisualAttributes(ijEditor);
}
public static class NumberChangeListener implements EffectiveOptionValueChangeListener { public static class NumberChangeListener implements EffectiveOptionValueChangeListener {
public static NumberChangeListener INSTANCE = new NumberChangeListener(); public static NumberChangeListener INSTANCE = new NumberChangeListener();
@@ -342,45 +324,20 @@ public class EditorGroup implements PersistentStateComponent<Element>, VimEditor
} }
} }
@NotNull
@Override @Override
public @NotNull Collection<VimEditor> getEditorsRaw() { public Collection<VimEditor> localEditors() {
return getLocalEditors() return HelperKt.localEditors().stream()
.map(IjVimEditor::new) .map(IjVimEditor::new)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@NotNull @NotNull
@Override @Override
public Collection<VimEditor> getEditors() { public Collection<VimEditor> localEditors(@NotNull VimDocument buffer) {
return getLocalEditors()
.filter(UserDataManager::getVimInitialised)
.map(IjVimEditor::new)
.collect(Collectors.toList());
}
@NotNull
@Override
public Collection<VimEditor> getEditors(@NotNull VimDocument buffer) {
final Document document = ((IjVimDocument)buffer).getDocument(); final Document document = ((IjVimDocument)buffer).getDocument();
return getLocalEditors() return HelperKt.localEditors(document).stream()
.filter(editor -> UserDataManager.getVimInitialised(editor) && editor.getDocument().equals(document))
.map(IjVimEditor::new) .map(IjVimEditor::new)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
private Stream<Editor> getLocalEditors() {
// Always fetch local editors. If we're hosting a Code With Me session, any connected guests will create hidden
// editors to handle syntax highlighting, completion requests, etc. We need to make sure that IdeaVim only makes
// changes (e.g. adding search highlights) to local editors, so things don't incorrectly flow through to any Clients.
// In non-CWM scenarios, or if IdeaVim is installed on the Client, there are only ever local editors, so this will
// also work there. In Gateway remote development scenarios, IdeaVim should not be installed on the host, only the
// Client, so all should work there too.
// Note that most IdeaVim operations are in response to interactive keystrokes, which would mean that
// ClientEditorManager.getCurrentInstance would return local editors. However, some operations are in response to
// events such as document change (to update search highlights) and these can come from CWM guests, and we'd get the
// remote editors.
// This invocation will always get local editors, regardless of current context.
final ClientAppSession localSession = ClientSessionsManager.getAppSessions(ClientKind.LOCAL).get(0);
return localSession.getService(ClientEditorManager.class).editors();
}
} }

View File

@@ -22,17 +22,16 @@ import com.intellij.openapi.fileEditor.impl.EditorsSplitters;
import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.project.Project; import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.VirtualFileSystem;
import com.intellij.psi.search.FilenameIndex; import com.intellij.psi.search.FilenameIndex;
import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.ProjectScope; import com.intellij.psi.search.ProjectScope;
import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.api.*; import com.maddyhome.idea.vim.api.*;
import com.maddyhome.idea.vim.state.mode.Mode;
import com.maddyhome.idea.vim.state.VimStateMachine;
import com.maddyhome.idea.vim.common.TextRange; import com.maddyhome.idea.vim.common.TextRange;
import com.maddyhome.idea.vim.helper.EditorHelper; import com.maddyhome.idea.vim.helper.EditorHelper;
import com.maddyhome.idea.vim.helper.EditorHelperRt; import com.maddyhome.idea.vim.helper.EditorHelperRt;
@@ -41,13 +40,10 @@ import com.maddyhome.idea.vim.helper.SearchHelper;
import com.maddyhome.idea.vim.newapi.ExecuteExtensionKt; import com.maddyhome.idea.vim.newapi.ExecuteExtensionKt;
import com.maddyhome.idea.vim.newapi.IjEditorExecutionContext; import com.maddyhome.idea.vim.newapi.IjEditorExecutionContext;
import com.maddyhome.idea.vim.newapi.IjVimEditor; import com.maddyhome.idea.vim.newapi.IjVimEditor;
import com.maddyhome.idea.vim.state.VimStateMachine;
import com.maddyhome.idea.vim.state.mode.Mode;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import static com.maddyhome.idea.vim.api.VimInjectorKt.injector; import static com.maddyhome.idea.vim.api.VimInjectorKt.injector;
@@ -442,35 +438,14 @@ public class FileGroup extends VimFileBase {
private static final @NotNull Logger logger = Logger.getInstance(FileGroup.class.getName()); private static final @NotNull Logger logger = Logger.getInstance(FileGroup.class.getName());
/** /**
* Respond to editor tab selection and remember the last used tab * This method listens for editor tab changes so any insert/replace modes that need to be reset can be.
*/ */
public static void fileEditorManagerSelectionChangedCallback(@NotNull FileEditorManagerEvent event) { public static void fileEditorManagerSelectionChangedCallback(@NotNull FileEditorManagerEvent event) {
// The user has changed the editor they are working with - exit insert/replace mode, and complete any
// appropriate repeat
if (event.getOldFile() != null) { if (event.getOldFile() != null) {
LastTabService.getInstance(event.getManager().getProject()).setLastTab(event.getOldFile()); LastTabService.getInstance(event.getManager().getProject()).setLastTab(event.getOldFile());
} }
} }
@Nullable
@Override
public VimEditor selectEditor(@NotNull String projectId, @NotNull String documentPath, @Nullable String protocol) {
VirtualFileSystem fileSystem = VirtualFileManager.getInstance().getFileSystem(protocol);
if (fileSystem == null) return null;
VirtualFile virtualFile = fileSystem.findFileByPath(documentPath);
if (virtualFile == null) return null;
Project project = Arrays.stream(ProjectManager.getInstance().getOpenProjects())
.filter(p -> injector.getFile().getProjectId(p).equals(projectId))
.findFirst().orElseThrow();
Editor editor = selectEditor(project, virtualFile);
if (editor == null) return null;
return new IjVimEditor(editor);
}
@NotNull
@Override
public String getProjectId(@NotNull Object project) {
if (!(project instanceof Project)) throw new IllegalArgumentException();
return ((Project) project).getName();
}
} }

View File

@@ -34,6 +34,7 @@ public open class GlobalIjOptions(scope: OptionAccessScope) : OptionsPropertiesB
public var commandOrMotionAnnotation: Boolean by optionProperty(IjOptions.commandOrMotionAnnotation) public var commandOrMotionAnnotation: Boolean by optionProperty(IjOptions.commandOrMotionAnnotation)
public var exCommandAnnotation: Boolean by optionProperty(IjOptions.exCommandAnnotation) public var exCommandAnnotation: Boolean by optionProperty(IjOptions.exCommandAnnotation)
public var oldundo: Boolean by optionProperty(IjOptions.oldundo) public var oldundo: Boolean by optionProperty(IjOptions.oldundo)
public var showmodewidget: Boolean by optionProperty(IjOptions.showmodewidget)
public var unifyjumps: Boolean by optionProperty(IjOptions.unifyjumps) public var unifyjumps: Boolean by optionProperty(IjOptions.unifyjumps)
public var useNewRegex: Boolean by optionProperty(IjOptions.useNewRegex) public var useNewRegex: Boolean by optionProperty(IjOptions.useNewRegex)
public var vimscriptFunctionAnnotation: Boolean by optionProperty(IjOptions.vimscriptFunctionAnnotation) public var vimscriptFunctionAnnotation: Boolean by optionProperty(IjOptions.vimscriptFunctionAnnotation)

View File

@@ -85,7 +85,8 @@ public object IjOptions {
public val closenotebooks: ToggleOption = addOption(ToggleOption("closenotebooks", GLOBAL, "closenotebooks", true, isHidden = true)) public val closenotebooks: ToggleOption = addOption(ToggleOption("closenotebooks", GLOBAL, "closenotebooks", true, isHidden = true))
public val commandOrMotionAnnotation: ToggleOption = addOption(ToggleOption("commandormotionannotation", GLOBAL, "commandormotionannotation", true, isHidden = true)) public val commandOrMotionAnnotation: ToggleOption = addOption(ToggleOption("commandormotionannotation", GLOBAL, "commandormotionannotation", true, isHidden = true))
public val exCommandAnnotation: ToggleOption = addOption(ToggleOption("excommandannotation", GLOBAL, "excommandannotation", true, isHidden = true)) public val exCommandAnnotation: ToggleOption = addOption(ToggleOption("excommandannotation", GLOBAL, "excommandannotation", true, isHidden = true))
public val oldundo: ToggleOption = addOption(ToggleOption("oldundo", GLOBAL, "oldundo", true, isHidden = true)) public val oldundo: ToggleOption = addOption(ToggleOption("oldundo", GLOBAL, "oldundo", false, isHidden = true))
public val showmodewidget: ToggleOption = addOption(ToggleOption("showmodewidget", GLOBAL, "showmodewidget", false, isHidden = true))
public val unifyjumps: ToggleOption = addOption(ToggleOption("unifyjumps", GLOBAL, "unifyjumps", true, isHidden = true)) public val unifyjumps: ToggleOption = addOption(ToggleOption("unifyjumps", GLOBAL, "unifyjumps", true, isHidden = true))
public val useNewRegex: ToggleOption = addOption(ToggleOption("usenewregex", GLOBAL, "usenewregex", true, isHidden = true)) public val useNewRegex: ToggleOption = addOption(ToggleOption("usenewregex", GLOBAL, "usenewregex", true, isHidden = true))
public val vimscriptFunctionAnnotation: ToggleOption = addOption(ToggleOption("vimscriptfunctionannotation", GLOBAL, "vimscriptfunctionannotation", true, isHidden = true)) public val vimscriptFunctionAnnotation: ToggleOption = addOption(ToggleOption("vimscriptfunctionannotation", GLOBAL, "vimscriptfunctionannotation", true, isHidden = true))

View File

@@ -15,38 +15,38 @@ import com.maddyhome.idea.vim.statistic.VimscriptState
internal class IjStatisticsService : VimStatistics { internal class IjStatisticsService : VimStatistics {
override fun logTrackedAction(actionId: String) { override fun logTrackedAction(actionId: String) {
ActionTracker.Util.logTrackedAction(actionId) ActionTracker.logTrackedAction(actionId)
} }
override fun logCopiedAction(actionId: String) { override fun logCopiedAction(actionId: String) {
ActionTracker.Util.logCopiedAction(actionId) ActionTracker.logCopiedAction(actionId)
} }
override fun setIfLoopUsed(value: Boolean) { override fun setIfLoopUsed(value: Boolean) {
VimscriptState.Util.isLoopUsed = value VimscriptState.isLoopUsed = value
} }
override fun setIfMapExprUsed(value: Boolean) { override fun setIfMapExprUsed(value: Boolean) {
VimscriptState.Util.isMapExprUsed = value VimscriptState.isMapExprUsed = value
} }
override fun setIfFunctionCallUsed(value: Boolean) { override fun setIfFunctionCallUsed(value: Boolean) {
VimscriptState.Util.isFunctionCallUsed = value VimscriptState.isFunctionCallUsed = value
} }
override fun setIfFunctionDeclarationUsed(value: Boolean) { override fun setIfFunctionDeclarationUsed(value: Boolean) {
VimscriptState.Util.isFunctionDeclarationUsed = value VimscriptState.isFunctionDeclarationUsed = value
} }
override fun setIfIfUsed(value: Boolean) { override fun setIfIfUsed(value: Boolean) {
VimscriptState.Util.isIfUsed = value VimscriptState.isIfUsed = value
} }
override fun addExtensionEnabledWithPlug(extension: String) { override fun addExtensionEnabledWithPlug(extension: String) {
VimscriptState.Util.extensionsEnabledWithPlug.add(extension) VimscriptState.extensionsEnabledWithPlug.add(extension)
} }
override fun addSourcedFile(path: String) { override fun addSourcedFile(path: String) {
VimscriptState.Util.sourcedFiles.add(path) VimscriptState.sourcedFiles.add(path)
} }
} }

View File

@@ -1,61 +0,0 @@
/*
* Copyright 2003-2024 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.group
import com.intellij.lang.CodeDocumentationAwareCommenter
import com.intellij.lang.LanguageCommenters
import com.intellij.openapi.components.Service
import com.intellij.psi.PsiComment
import com.intellij.psi.util.PsiTreeUtil
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimPsiService
import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.helper.PsiHelper
import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim
@Service
public class IjVimPsiService: VimPsiService {
override fun getCommentAtPos(editor: VimEditor, pos: Int): Pair<TextRange, Pair<String, String>?>? {
val psiFile = PsiHelper.getFile(editor.ij) ?: return null
val psiElement = psiFile.findElementAt(pos) ?: return null
val language = psiElement.language
val commenter = LanguageCommenters.INSTANCE.forLanguage(language)
val psiComment = PsiTreeUtil.getParentOfType(psiElement, PsiComment::class.java, false) ?: return null
val commentText = psiComment.text
val blockCommentPrefix = commenter.blockCommentPrefix
val blockCommentSuffix = commenter.blockCommentSuffix
val docCommentPrefix = (commenter as? CodeDocumentationAwareCommenter)?.documentationCommentPrefix
val docCommentSuffix = (commenter as? CodeDocumentationAwareCommenter)?.documentationCommentSuffix
val prefixToSuffix: Pair<String, String>? =
if (docCommentPrefix != null && docCommentSuffix != null && commentText.startsWith(docCommentPrefix) && commentText.endsWith(docCommentSuffix)) {
docCommentPrefix to docCommentSuffix
}
else if (blockCommentPrefix != null && blockCommentSuffix != null && commentText.startsWith(blockCommentPrefix) && commentText.endsWith(blockCommentSuffix)) {
blockCommentPrefix to blockCommentSuffix
}
else {
null
}
return Pair(psiComment.textRange.vim, prefixToSuffix)
}
override fun getDoubleQuotedString(editor: VimEditor, pos: Int, isInner: Boolean): TextRange? {
// TODO[ideavim] It wasn't implemented before, but implementing it will significantly improve % motion
return getDoubleQuotesRangeNoPSI(editor.text(), pos, isInner)
}
override fun getSingleQuotedString(editor: VimEditor, pos: Int, isInner: Boolean): TextRange? {
// TODO[ideavim] It wasn't implemented before, but implementing it will significantly improve % motion
return getSingleQuotesRangeNoPSI(editor.text(), pos, isInner)
}
}

View File

@@ -26,12 +26,10 @@ import com.maddyhome.idea.vim.EventFacade;
import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.action.VimShortcutKeyAction; import com.maddyhome.idea.vim.action.VimShortcutKeyAction;
import com.maddyhome.idea.vim.action.change.LazyVimCommand; import com.maddyhome.idea.vim.action.change.LazyVimCommand;
import com.maddyhome.idea.vim.api.NativeAction; import com.maddyhome.idea.vim.api.*;
import com.maddyhome.idea.vim.api.VimEditor;
import com.maddyhome.idea.vim.api.VimInjectorKt;
import com.maddyhome.idea.vim.api.VimKeyGroupBase;
import com.maddyhome.idea.vim.command.MappingMode; import com.maddyhome.idea.vim.command.MappingMode;
import com.maddyhome.idea.vim.ex.ExOutputModel; import com.maddyhome.idea.vim.ex.ExOutputModel;
import com.maddyhome.idea.vim.helper.HelperKt;
import com.maddyhome.idea.vim.key.*; import com.maddyhome.idea.vim.key.*;
import com.maddyhome.idea.vim.newapi.IjNativeAction; import com.maddyhome.idea.vim.newapi.IjNativeAction;
import com.maddyhome.idea.vim.newapi.IjVimEditor; import com.maddyhome.idea.vim.newapi.IjVimEditor;
@@ -101,9 +99,9 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
@Override @Override
public void updateShortcutKeysRegistration() { public void updateShortcutKeysRegistration() {
for (VimEditor editor : injector.getEditorGroup().getEditors()) { for (Editor editor : HelperKt.localEditors()) {
unregisterShortcutKeys(editor); unregisterShortcutKeys(new IjVimEditor(editor));
registerRequiredShortcutKeys(editor); registerRequiredShortcutKeys(new IjVimEditor(editor));
} }
} }
@@ -230,7 +228,7 @@ public class KeyGroup extends VimKeyGroupBase implements PersistentStateComponen
private void registerRequiredShortcut(@NotNull List<KeyStroke> keys, MappingOwner owner) { private void registerRequiredShortcut(@NotNull List<KeyStroke> keys, MappingOwner owner) {
for (KeyStroke key : keys) { for (KeyStroke key : keys) {
if (key.getKeyChar() == KeyEvent.CHAR_UNDEFINED) { if (key.getKeyChar() == KeyEvent.CHAR_UNDEFINED) {
if (!injector.getApplication().isOctopusEnabled() || if (!injector.getOptionGroup().getGlobalOptions().getOctopushandler() ||
!(key.getKeyCode() == KeyEvent.VK_ESCAPE && key.getModifiers() == 0) && !(key.getKeyCode() == KeyEvent.VK_ESCAPE && key.getModifiers() == 0) &&
!(key.getKeyCode() == KeyEvent.VK_ENTER && key.getModifiers() == 0)) { !(key.getKeyCode() == KeyEvent.VK_ENTER && key.getModifiers() == 0)) {
getRequiredShortcutKeys().add(new RequiredShortcut(key, owner)); getRequiredShortcutKeys().add(new RequiredShortcut(key, owner));

View File

@@ -1,68 +0,0 @@
package com.maddyhome.idea.vim.group
import com.intellij.codeInsight.daemon.ReferenceImporter
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiRecursiveElementWalkingVisitor
import java.util.function.BooleanSupplier
internal object MacroAutoImport {
fun run(editor: Editor, dataContext: DataContext) {
val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return
if (!FileDocumentManager.getInstance().requestWriting(editor.document, project)) {
return
}
val importers = ReferenceImporter.EP_NAME.extensionList
if (importers.isEmpty()) {
return
}
ProgressManager.getInstance().run(object : Task.Backgroundable(project, "Auto import", true) {
override fun run(indicator: ProgressIndicator) {
val fixes = ReadAction.nonBlocking<List<BooleanSupplier>> {
val fixes = mutableListOf<BooleanSupplier>()
file.accept(object : PsiRecursiveElementWalkingVisitor() {
override fun visitElement(element: PsiElement) {
for (reference in element.references) {
if (reference.resolve() != null) {
continue
}
for (importer in importers) {
importer.computeAutoImportAtOffset(editor, file, element.textRange.startOffset, true)
?.let(fixes::add)
}
}
super.visitElement(element)
}
})
return@nonBlocking fixes
}.executeSynchronously()
ApplicationManager.getApplication().invokeAndWait {
WriteCommandAction.writeCommandAction(project)
.withName("Auto Import")
.withGroupId("IdeaVimAutoImportAfterMacro")
.shouldRecordActionForActiveDocument(true)
.run<RuntimeException> {
fixes.forEach { it.asBoolean }
}
}
}
})
}
}

View File

@@ -22,7 +22,6 @@ import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.helper.MessageHelper.message import com.maddyhome.idea.vim.helper.MessageHelper.message
import com.maddyhome.idea.vim.macro.VimMacroBase import com.maddyhome.idea.vim.macro.VimMacroBase
import com.maddyhome.idea.vim.newapi.IjVimEditor import com.maddyhome.idea.vim.newapi.IjVimEditor
import com.maddyhome.idea.vim.newapi.ij
/** /**
* Used to handle playback of macros * Used to handle playback of macros
@@ -78,12 +77,11 @@ internal class MacroGroup : VimMacroBase() {
} catch (e: ProcessCanceledException) { } catch (e: ProcessCanceledException) {
return@runnable return@runnable
} }
val keyHandler = getInstance()
ProgressManager.getInstance().executeNonCancelableSection { ProgressManager.getInstance().executeNonCancelableSection {
// Prevent autocompletion during macros. // Prevent autocompletion during macros.
// See https://github.com/JetBrains/ideavim/pull/772 for details // See https://github.com/JetBrains/ideavim/pull/772 for details
CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion) CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion)
keyHandler.handleKey(editor, key, context, keyHandler.keyHandlerState) getInstance().handleKey(editor, key, context)
} }
if (injector.messages.isError()) return@runnable if (injector.messages.isError()) return@runnable
} }
@@ -94,9 +92,6 @@ internal class MacroGroup : VimMacroBase() {
} finally { } finally {
keyStack.removeFirst() keyStack.removeFirst()
} }
if (!isInternalMacro) {
MacroAutoImport.run(editor.ij, context.ij)
}
} }
if (isInternalMacro) { if (isInternalMacro) {

View File

@@ -11,24 +11,41 @@ import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.components.Service import com.intellij.openapi.components.Service
import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.editor.VisualPosition import com.intellij.openapi.editor.VisualPosition
import com.intellij.openapi.fileEditor.FileEditorManagerEvent import com.intellij.openapi.fileEditor.FileEditorManagerEvent
import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.fileEditor.impl.EditorWindow import com.intellij.openapi.fileEditor.impl.EditorWindow
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.VirtualFileSystem
import com.intellij.util.MathUtil.clamp
import com.maddyhome.idea.vim.KeyHandler import com.maddyhome.idea.vim.KeyHandler
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.BufferPosition
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.ImmutableVimCaret import com.maddyhome.idea.vim.api.ImmutableVimCaret
import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimChangeGroupBase import com.maddyhome.idea.vim.api.VimChangeGroupBase
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimMotionGroupBase import com.maddyhome.idea.vim.api.VimMotionGroupBase
import com.maddyhome.idea.vim.api.addJump
import com.maddyhome.idea.vim.api.anyNonWhitespace import com.maddyhome.idea.vim.api.anyNonWhitespace
import com.maddyhome.idea.vim.api.getJump
import com.maddyhome.idea.vim.api.getJumpSpot
import com.maddyhome.idea.vim.api.getLeadingCharacterOffset import com.maddyhome.idea.vim.api.getLeadingCharacterOffset
import com.maddyhome.idea.vim.api.getVisualLineCount import com.maddyhome.idea.vim.api.getVisualLineCount
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.api.lineLength import com.maddyhome.idea.vim.api.lineLength
import com.maddyhome.idea.vim.api.normalizeColumn
import com.maddyhome.idea.vim.api.normalizeLine
import com.maddyhome.idea.vim.api.normalizeOffset
import com.maddyhome.idea.vim.api.normalizeVisualColumn import com.maddyhome.idea.vim.api.normalizeVisualColumn
import com.maddyhome.idea.vim.api.normalizeVisualLine import com.maddyhome.idea.vim.api.normalizeVisualLine
import com.maddyhome.idea.vim.api.options
import com.maddyhome.idea.vim.api.visualLineToBufferLine import com.maddyhome.idea.vim.api.visualLineToBufferLine
import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.MotionType import com.maddyhome.idea.vim.command.MotionType
@@ -37,9 +54,12 @@ import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.ex.ExOutputModel import com.maddyhome.idea.vim.ex.ExOutputModel
import com.maddyhome.idea.vim.handler.Motion import com.maddyhome.idea.vim.handler.Motion
import com.maddyhome.idea.vim.handler.Motion.AbsoluteOffset import com.maddyhome.idea.vim.handler.Motion.AbsoluteOffset
import com.maddyhome.idea.vim.handler.Motion.AdjustedOffset
import com.maddyhome.idea.vim.handler.MotionActionHandler import com.maddyhome.idea.vim.handler.MotionActionHandler
import com.maddyhome.idea.vim.handler.TextObjectActionHandler import com.maddyhome.idea.vim.handler.TextObjectActionHandler
import com.maddyhome.idea.vim.handler.toMotionOrError
import com.maddyhome.idea.vim.helper.EditorHelper import com.maddyhome.idea.vim.helper.EditorHelper
import com.maddyhome.idea.vim.helper.SearchHelper
import com.maddyhome.idea.vim.helper.exitVisualMode import com.maddyhome.idea.vim.helper.exitVisualMode
import com.maddyhome.idea.vim.helper.fileSize import com.maddyhome.idea.vim.helper.fileSize
import com.maddyhome.idea.vim.helper.getNormalizedScrollOffset import com.maddyhome.idea.vim.helper.getNormalizedScrollOffset
@@ -47,13 +67,17 @@ import com.maddyhome.idea.vim.helper.getNormalizedSideScrollOffset
import com.maddyhome.idea.vim.helper.isEndAllowed import com.maddyhome.idea.vim.helper.isEndAllowed
import com.maddyhome.idea.vim.helper.vimLastColumn import com.maddyhome.idea.vim.helper.vimLastColumn
import com.maddyhome.idea.vim.listener.AppCodeTemplates import com.maddyhome.idea.vim.listener.AppCodeTemplates
import com.maddyhome.idea.vim.mark.Mark
import com.maddyhome.idea.vim.newapi.IjEditorExecutionContext import com.maddyhome.idea.vim.newapi.IjEditorExecutionContext
import com.maddyhome.idea.vim.newapi.IjVimCaret
import com.maddyhome.idea.vim.newapi.IjVimEditor
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.state.VimStateMachine import com.maddyhome.idea.vim.state.VimStateMachine
import com.maddyhome.idea.vim.state.mode.Mode import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.ui.ex.ExEntryPanel import com.maddyhome.idea.vim.ui.ex.ExEntryPanel
import org.jetbrains.annotations.Range import org.jetbrains.annotations.Range
import java.io.File
import kotlin.math.max import kotlin.math.max
import kotlin.math.min import kotlin.math.min
@@ -66,6 +90,24 @@ internal class MotionGroup : VimMotionGroupBase() {
AppCodeTemplates.onMovement(editor.ij, caret.ij, oldOffset < offset) AppCodeTemplates.onMovement(editor.ij, caret.ij, oldOffset < offset)
} }
private fun selectEditor(project: Project, mark: Mark): Editor? {
val virtualFile = markToVirtualFile(mark) ?: return null
return selectEditor(project, virtualFile)
}
private fun markToVirtualFile(mark: Mark): VirtualFile? {
val protocol = mark.protocol
val fileSystem: VirtualFileSystem? = VirtualFileManager.getInstance().getFileSystem(protocol)
return fileSystem?.findFileByPath(mark.filepath)
}
private fun selectEditor(project: Project?, file: VirtualFile) =
VimPlugin.getFile().selectEditor(project, file)
override fun moveCaretToMatchingPair(editor: VimEditor, caret: ImmutableVimCaret): Motion {
return SearchHelper.findMatchingPairOnCurrentLine(editor.ij, caret.ij).toMotionOrError()
}
override fun moveCaretToFirstDisplayLine( override fun moveCaretToFirstDisplayLine(
editor: VimEditor, editor: VimEditor,
caret: ImmutableVimCaret, caret: ImmutableVimCaret,
@@ -88,12 +130,85 @@ internal class MotionGroup : VimMotionGroupBase() {
return moveCaretToScreenLocation(editor.ij, caret.ij, ScreenLocation.MIDDLE, 0, false) return moveCaretToScreenLocation(editor.ij, caret.ij, ScreenLocation.MIDDLE, 0, false)
} }
override fun moveCaretToMark(caret: ImmutableVimCaret, ch: Char, toLineStart: Boolean): Motion {
val markService = injector.markService
val mark = markService.getMark(caret, ch) ?: return Motion.Error
val caretEditor = caret.editor
val caretVirtualFile = EditorHelper.getVirtualFile((caretEditor as IjVimEditor).editor)
val line = mark.line
if (caretVirtualFile!!.path == mark.filepath) {
val offset = if (toLineStart) {
moveCaretToLineStartSkipLeading(caretEditor, line)
} else {
caretEditor.bufferPositionToOffset(BufferPosition(line, mark.col, false))
}
return offset.toMotionOrError()
}
val project = caretEditor.editor.project
val markEditor = selectEditor(project!!, mark)
if (markEditor != null) {
// todo should we move all the carets or only one?
for (carett in markEditor.caretModel.allCarets) {
val offset = if (toLineStart) {
moveCaretToLineStartSkipLeading(IjVimEditor(markEditor), line)
} else {
// todo should it be the same as getting offset above?
markEditor.logicalPositionToOffset(LogicalPosition(line, mark.col))
}
IjVimCaret(carett!!).moveToOffset(offset)
}
}
return Motion.Error
}
override fun moveCaretToJump(editor: VimEditor, caret: ImmutableVimCaret, count: Int): Motion {
val jumpService = injector.jumpService
val spot = jumpService.getJumpSpot(editor)
val (line, col, fileName) = jumpService.getJump(editor, count) ?: return Motion.Error
val vf = EditorHelper.getVirtualFile(editor.ij) ?: return Motion.Error
val lp = BufferPosition(line, col, false)
val lpNative = LogicalPosition(line, col, false)
return if (vf.path != fileName) {
val newFile = LocalFileSystem.getInstance().findFileByPath(fileName.replace(File.separatorChar, '/'))
?: return Motion.Error
selectEditor(editor.ij.project, newFile)?.let { newEditor ->
if (spot == -1) {
jumpService.addJump(editor, false)
}
newEditor.vim.let {
it.currentCaret().moveToOffset(it.normalizeOffset(newEditor.logicalPositionToOffset(lpNative), false))
}
}
Motion.Error
} else {
if (spot == -1) {
jumpService.addJump(editor, false)
}
editor.bufferPositionToOffset(lp).toMotionOrError()
}
}
override fun moveCaretToCurrentDisplayLineMiddle(editor: VimEditor, caret: ImmutableVimCaret): Motion { override fun moveCaretToCurrentDisplayLineMiddle(editor: VimEditor, caret: ImmutableVimCaret): Motion {
val width = EditorHelper.getApproximateScreenWidth(editor.ij) / 2 val width = EditorHelper.getApproximateScreenWidth(editor.ij) / 2
val len = editor.lineLength(editor.currentCaret().getBufferPosition().line) val len = editor.lineLength(editor.currentCaret().getBufferPosition().line)
return moveCaretToColumn(editor, caret, max(0, min(len - 1, width)), false) return moveCaretToColumn(editor, caret, max(0, min(len - 1, width)), false)
} }
override fun moveCaretToColumn(editor: VimEditor, caret: ImmutableVimCaret, count: Int, allowEnd: Boolean): Motion {
val line = caret.getLine().line
val column = editor.normalizeColumn(line, count, allowEnd)
val offset = editor.bufferPositionToOffset(BufferPosition(line, column, false))
return if (column != count) {
AdjustedOffset(offset, count)
} else {
AbsoluteOffset(offset)
}
}
override fun moveCaretToCurrentDisplayLineStart(editor: VimEditor, caret: ImmutableVimCaret): Motion { override fun moveCaretToCurrentDisplayLineStart(editor: VimEditor, caret: ImmutableVimCaret): Motion {
val col = EditorHelper.getVisualColumnAtLeftOfDisplay(editor.ij, caret.getVisualPosition().line) val col = EditorHelper.getVisualColumnAtLeftOfDisplay(editor.ij, caret.getVisualPosition().line)
return moveCaretToColumn(editor, caret, col, false) return moveCaretToColumn(editor, caret, col, false)
@@ -104,7 +219,7 @@ internal class MotionGroup : VimMotionGroupBase() {
caret: ImmutableVimCaret, caret: ImmutableVimCaret,
): @Range(from = 0, to = Int.MAX_VALUE.toLong()) Int { ): @Range(from = 0, to = Int.MAX_VALUE.toLong()) Int {
val col = EditorHelper.getVisualColumnAtLeftOfDisplay(editor.ij, caret.getVisualPosition().line) val col = EditorHelper.getVisualColumnAtLeftOfDisplay(editor.ij, caret.getVisualPosition().line)
val bufferLine = caret.getLine() val bufferLine = caret.getLine().line
return editor.getLeadingCharacterOffset(bufferLine, col) return editor.getLeadingCharacterOffset(bufferLine, col)
} }
@@ -117,6 +232,36 @@ internal class MotionGroup : VimMotionGroupBase() {
return moveCaretToColumn(editor, caret, col, allowEnd) return moveCaretToColumn(editor, caret, col, allowEnd)
} }
override fun moveCaretToLineWithSameColumn(
editor: VimEditor,
line: Int,
caret: ImmutableVimCaret,
): @Range(from = 0, to = Int.MAX_VALUE.toLong()) Int {
var c = caret.vimLastColumn
var l = line
if (l < 0) {
l = 0
c = 0
} else if (l >= editor.lineCount()) {
l = editor.normalizeLine(editor.lineCount() - 1)
c = editor.lineLength(l)
}
val newPos = BufferPosition(l, editor.normalizeColumn(l, c, false))
return editor.bufferPositionToOffset(newPos)
}
override fun moveCaretToLineWithStartOfLineOption(
editor: VimEditor,
line: Int,
caret: ImmutableVimCaret,
): @Range(from = 0, to = Int.MAX_VALUE.toLong()) Int {
return if (injector.options(editor).startofline) {
moveCaretToLineStartSkipLeading(editor, line)
} else {
moveCaretToLineWithSameColumn(editor, line, caret)
}
}
/** /**
* If 'absolute' is true, then set tab index to 'value', otherwise add 'value' to tab index with wraparound. * If 'absolute' is true, then set tab index to 'value', otherwise add 'value' to tab index with wraparound.
*/ */
@@ -134,18 +279,30 @@ internal class MotionGroup : VimMotionGroupBase() {
} }
override fun moveCaretGotoPreviousTab(editor: VimEditor, context: ExecutionContext, rawCount: Int): Int { override fun moveCaretGotoPreviousTab(editor: VimEditor, context: ExecutionContext, rawCount: Int): Int {
val project = editor.ij.project ?: return editor.currentCaret().offset val project = editor.ij.project ?: return editor.currentCaret().offset.point
val currentWindow = FileEditorManagerEx.getInstanceEx(project).splitters.currentWindow val currentWindow = FileEditorManagerEx.getInstanceEx(project).splitters.currentWindow
switchEditorTab(currentWindow, if (rawCount >= 1) -rawCount else -1, false) switchEditorTab(currentWindow, if (rawCount >= 1) -rawCount else -1, false)
return editor.currentCaret().offset return editor.currentCaret().offset.point
} }
override fun moveCaretGotoNextTab(editor: VimEditor, context: ExecutionContext, rawCount: Int): Int { override fun moveCaretGotoNextTab(editor: VimEditor, context: ExecutionContext, rawCount: Int): Int {
val absolute = rawCount >= 1 val absolute = rawCount >= 1
val project = editor.ij.project ?: return editor.currentCaret().offset val project = editor.ij.project ?: return editor.currentCaret().offset.point
val currentWindow = FileEditorManagerEx.getInstanceEx(project).splitters.currentWindow val currentWindow = FileEditorManagerEx.getInstanceEx(project).splitters.currentWindow
switchEditorTab(currentWindow, if (absolute) rawCount - 1 else 1, absolute) switchEditorTab(currentWindow, if (absolute) rawCount - 1 else 1, absolute)
return editor.currentCaret().offset return editor.currentCaret().offset.point
}
override fun moveCaretToLinePercent(
editor: VimEditor,
caret: ImmutableVimCaret,
count: Int,
): @Range(from = 0, to = Int.MAX_VALUE.toLong()) Int {
return moveCaretToLineWithStartOfLineOption(
editor,
editor.normalizeLine((editor.lineCount() * clamp(count, 0, 100) + 99) / 100 - 1),
caret,
)
} }
private enum class ScreenLocation { private enum class ScreenLocation {

View File

@@ -278,7 +278,7 @@ internal class NotificationService(private val project: Project?) {
} }
if (id != null) { if (id != null) {
ActionTracker.Util.logTrackedAction(id) ActionTracker.logTrackedAction(id)
} }
} }
@@ -286,7 +286,7 @@ internal class NotificationService(private val project: Project?) {
override fun actionPerformed(e: AnActionEvent) { override fun actionPerformed(e: AnActionEvent) {
CopyPasteManager.getInstance().setContents(StringSelection(id ?: "")) CopyPasteManager.getInstance().setContents(StringSelection(id ?: ""))
if (id != null) { if (id != null) {
ActionTracker.Util.logCopiedAction(id) ActionTracker.logCopiedAction(id)
} }
notification?.expire() notification?.expire()

View File

@@ -20,7 +20,6 @@ import com.intellij.openapi.progress.ProgressManager
import com.intellij.util.execution.ParametersListUtil import com.intellij.util.execution.ParametersListUtil
import com.intellij.util.text.CharSequenceReader import com.intellij.util.text.CharSequenceReader
import com.maddyhome.idea.vim.KeyHandler.Companion.getInstance import com.maddyhome.idea.vim.KeyHandler.Companion.getInstance
import com.maddyhome.idea.vim.KeyProcessResult
import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
@@ -38,6 +37,7 @@ import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.Mode.NORMAL import com.maddyhome.idea.vim.state.mode.Mode.NORMAL
import com.maddyhome.idea.vim.state.mode.Mode.VISUAL import com.maddyhome.idea.vim.state.mode.Mode.VISUAL
import com.maddyhome.idea.vim.state.mode.ReturnableFromCmd import com.maddyhome.idea.vim.state.mode.ReturnableFromCmd
import com.maddyhome.idea.vim.state.mode.mode
import com.maddyhome.idea.vim.ui.ex.ExEntryPanel import com.maddyhome.idea.vim.ui.ex.ExEntryPanel
import com.maddyhome.idea.vim.vimscript.model.CommandLineVimLContext import com.maddyhome.idea.vim.vimscript.model.CommandLineVimLContext
import java.io.BufferedWriter import java.io.BufferedWriter
@@ -85,27 +85,24 @@ public class ProcessGroup : VimProcessGroupBase() {
modeBeforeCommandProcessing = currentMode modeBeforeCommandProcessing = currentMode
val initText = getRange(editor, cmd) val initText = getRange(editor, cmd)
injector.markService.setVisualSelectionMarks(editor) injector.markService.setVisualSelectionMarks(editor)
editor.mode = Mode.CMD_LINE(currentMode) editor.vimStateMachine.mode = Mode.CMD_LINE(currentMode)
val panel = ExEntryPanel.getInstance() val panel = ExEntryPanel.getInstance()
panel.activate(editor.ij, context.ij, ":", initText, 1) panel.activate(editor.ij, context.ij, ":", initText, 1)
} }
public override fun processExKey(editor: VimEditor, stroke: KeyStroke, processResultBuilder: KeyProcessResult.KeyProcessResultBuilder): Boolean { public override fun processExKey(editor: VimEditor, stroke: KeyStroke): Boolean {
// This will only get called if somehow the key focus ended up in the editor while the ex entry window // This will only get called if somehow the key focus ended up in the editor while the ex entry window
// is open. So I'll put focus back in the editor and process the key. // is open. So I'll put focus back in the editor and process the key.
val panel = ExEntryPanel.getInstance() val panel = ExEntryPanel.getInstance()
if (panel.isActive) { if (panel.isActive) {
processResultBuilder.addExecutionStep { _, _, _ -> requestFocus(panel.entry)
requestFocus(panel.entry) panel.handleKey(stroke)
panel.handleKey(stroke)
}
return true return true
} else { } else {
processResultBuilder.addExecutionStep { _, lambdaEditor, _ -> getInstance(editor).mode = NORMAL()
lambdaEditor.mode = NORMAL() getInstance().reset(editor)
getInstance().reset(lambdaEditor)
}
return false return false
} }
} }
@@ -115,7 +112,7 @@ public class ProcessGroup : VimProcessGroupBase() {
panel.deactivate(true) panel.deactivate(true)
var res = true var res = true
try { try {
editor.mode = NORMAL() getInstance(editor).mode = NORMAL()
logger.debug("processing command") logger.debug("processing command")
@@ -155,7 +152,7 @@ public class ProcessGroup : VimProcessGroupBase() {
} }
public override fun cancelExEntry(editor: VimEditor, resetCaret: Boolean) { public override fun cancelExEntry(editor: VimEditor, resetCaret: Boolean) {
editor.mode = NORMAL() editor.vimStateMachine.mode = NORMAL()
getInstance().reset(editor) getInstance().reset(editor)
val panel = ExEntryPanel.getInstance() val panel = ExEntryPanel.getInstance()
panel.deactivate(true, resetCaret) panel.deactivate(true, resetCaret)
@@ -165,7 +162,7 @@ public class ProcessGroup : VimProcessGroupBase() {
val initText = getRange(editor, cmd) + "!" val initText = getRange(editor, cmd) + "!"
val currentMode = editor.mode val currentMode = editor.mode
check(currentMode is ReturnableFromCmd) { "Cannot enable cmd mode from $currentMode" } check(currentMode is ReturnableFromCmd) { "Cannot enable cmd mode from $currentMode" }
editor.mode = Mode.CMD_LINE(currentMode) editor.vimStateMachine.mode = Mode.CMD_LINE(currentMode)
val panel = ExEntryPanel.getInstance() val panel = ExEntryPanel.getInstance()
panel.activate(editor.ij, context.ij, ":", initText, 1) panel.activate(editor.ij, context.ij, ":", initText, 1)
} }

View File

@@ -14,9 +14,9 @@ import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.diagnostic.Logger;
import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.state.mode.SelectionType;
import com.maddyhome.idea.vim.register.Register; import com.maddyhome.idea.vim.register.Register;
import com.maddyhome.idea.vim.register.VimRegisterGroupBase; import com.maddyhome.idea.vim.register.VimRegisterGroupBase;
import com.maddyhome.idea.vim.state.mode.SelectionType;
import org.jdom.Element; import org.jdom.Element;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -37,10 +37,6 @@ public class RegisterGroup extends VimRegisterGroupBase implements PersistentSta
private static final Logger logger = Logger.getInstance(RegisterGroup.class); private static final Logger logger = Logger.getInstance(RegisterGroup.class);
public RegisterGroup() {
this.initClipboardOptionListener();
}
public void saveData(final @NotNull Element element) { public void saveData(final @NotNull Element element) {
logger.debug("Save registers data"); logger.debug("Save registers data");
final Element registersElement = new Element("registers"); final Element registersElement = new Element("registers");

View File

@@ -21,6 +21,8 @@ import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent; import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.Ref;
import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.api.*; import com.maddyhome.idea.vim.api.*;
@@ -31,11 +33,12 @@ import com.maddyhome.idea.vim.ex.ExException;
import com.maddyhome.idea.vim.ex.ranges.LineRange; import com.maddyhome.idea.vim.ex.ranges.LineRange;
import com.maddyhome.idea.vim.helper.*; import com.maddyhome.idea.vim.helper.*;
import com.maddyhome.idea.vim.history.HistoryConstants; import com.maddyhome.idea.vim.history.HistoryConstants;
import com.maddyhome.idea.vim.newapi.*; import com.maddyhome.idea.vim.newapi.IjEditorExecutionContext;
import com.maddyhome.idea.vim.newapi.IjVimCaret;
import com.maddyhome.idea.vim.newapi.IjVimEditor;
import com.maddyhome.idea.vim.newapi.IjVimSearchGroup;
import com.maddyhome.idea.vim.options.GlobalOptionChangeListener; import com.maddyhome.idea.vim.options.GlobalOptionChangeListener;
import com.maddyhome.idea.vim.regexp.CharPointer; import com.maddyhome.idea.vim.regexp.*;
import com.maddyhome.idea.vim.regexp.CharacterClasses;
import com.maddyhome.idea.vim.regexp.RegExp;
import com.maddyhome.idea.vim.ui.ModalEntry; import com.maddyhome.idea.vim.ui.ModalEntry;
import com.maddyhome.idea.vim.ui.ex.ExEntryPanel; import com.maddyhome.idea.vim.ui.ex.ExEntryPanel;
import com.maddyhome.idea.vim.vimscript.model.VimLContext; import com.maddyhome.idea.vim.vimscript.model.VimLContext;
@@ -56,6 +59,7 @@ import java.text.ParsePosition;
import java.util.*; import java.util.*;
import static com.maddyhome.idea.vim.api.VimInjectorKt.*; import static com.maddyhome.idea.vim.api.VimInjectorKt.*;
import static com.maddyhome.idea.vim.helper.HelperKt.localEditors;
import static com.maddyhome.idea.vim.helper.SearchHelperKtKt.shouldIgnoreCase; import static com.maddyhome.idea.vim.helper.SearchHelperKtKt.shouldIgnoreCase;
import static com.maddyhome.idea.vim.newapi.IjVimInjectorKt.globalIjOptions; import static com.maddyhome.idea.vim.newapi.IjVimInjectorKt.globalIjOptions;
import static com.maddyhome.idea.vim.register.RegisterConstants.LAST_SEARCH_REGISTER; import static com.maddyhome.idea.vim.register.RegisterConstants.LAST_SEARCH_REGISTER;
@@ -210,8 +214,8 @@ public class SearchGroup extends IjVimSearchGroup implements PersistentStateComp
* @param patternOffset The pattern offset, e.g. `/{pattern}/{offset}` * @param patternOffset The pattern offset, e.g. `/{pattern}/{offset}`
* @param direction The direction to search * @param direction The direction to search
*/ */
@Override @TestOnly
public void setLastSearchState(@SuppressWarnings("unused") @NotNull VimEditor editor, @NotNull String pattern, public void setLastSearchState(@SuppressWarnings("unused") @NotNull Editor editor, @NotNull String pattern,
@NotNull String patternOffset, Direction direction) { @NotNull String patternOffset, Direction direction) {
if (globalIjOptions(injector).getUseNewRegex()) { if (globalIjOptions(injector).getUseNewRegex()) {
super.setLastSearchState(pattern, patternOffset, direction); super.setLastSearchState(pattern, patternOffset, direction);
@@ -538,24 +542,20 @@ public class SearchGroup extends IjVimSearchGroup implements PersistentStateComp
* *
* @param editor The editor to search in * @param editor The editor to search in
* @param caret The caret to use for initial search offset, and to move for interactive substitution * @param caret The caret to use for initial search offset, and to move for interactive substitution
* @param context
* @param range Only search and substitute within the given line range. Must be valid * @param range Only search and substitute within the given line range. Must be valid
* @param excmd The command part of the ex command line, e.g. `s` or `substitute`, or `~` * @param excmd The command part of the ex command line, e.g. `s` or `substitute`, or `~`
* @param exarg The argument to the substitute command, such as `/{pattern}/{string}/[flags]` * @param exarg The argument to the substitute command, such as `/{pattern}/{string}/[flags]`
* @return True if the substitution succeeds, false on error. Will succeed even if nothing is modified * @return True if the substitution succeeds, false on error. Will succeed even if nothing is modified
*/ */
@Override @Override
@RWLockLabel.SelfSynchronized @RWLockLabel.SelfSynchronized
public boolean processSubstituteCommand(@NotNull VimEditor editor, public boolean processSubstituteCommand(@NotNull VimEditor editor,
@NotNull VimCaret caret, @NotNull VimCaret caret,
@NotNull ExecutionContext context,
@NotNull LineRange range, @NotNull LineRange range,
@NotNull @NonNls String excmd, @NotNull @NonNls String excmd,
@NotNull @NonNls String exarg, @NotNull @NonNls String exarg,
@NotNull VimLContext parent) { @NotNull VimLContext parent) {
if (globalIjOptions(injector).getUseNewRegex()) { if (globalIjOptions(injector).getUseNewRegex()) return super.processSubstituteCommand(editor, caret, range, excmd, exarg, parent);
return super.processSubstituteCommand(editor, caret, context, range, excmd, exarg, parent);
}
// Explicitly exit visual mode here, so that visual mode marks don't change when we move the cursor to a match. // Explicitly exit visual mode here, so that visual mode marks don't change when we move the cursor to a match.
List<ExException> exceptions = new ArrayList<>(); List<ExException> exceptions = new ArrayList<>();
@@ -812,7 +812,7 @@ public class SearchGroup extends IjVimSearchGroup implements PersistentStateComp
RangeHighlighter hl = RangeHighlighter hl =
SearchHighlightsHelper.addSubstitutionConfirmationHighlight(((IjVimEditor)editor).getEditor(), startoff, SearchHighlightsHelper.addSubstitutionConfirmationHighlight(((IjVimEditor)editor).getEditor(), startoff,
endoff); endoff);
final ReplaceConfirmationChoice choice = confirmChoice(((IjVimEditor)editor).getEditor(), context, match, ((IjVimCaret)caret).getCaret(), startoff); final ReplaceConfirmationChoice choice = confirmChoice(((IjVimEditor)editor).getEditor(), match, ((IjVimCaret)caret).getCaret(), startoff);
((IjVimEditor)editor).getEditor().getMarkupModel().removeHighlighter(hl); ((IjVimEditor)editor).getEditor().getMarkupModel().removeHighlighter(hl);
switch (choice) { switch (choice) {
case SUBSTITUTE_THIS: case SUBSTITUTE_THIS:
@@ -841,7 +841,8 @@ public class SearchGroup extends IjVimSearchGroup implements PersistentStateComp
caret.moveToOffset(startoff); caret.moveToOffset(startoff);
if (expression != null) { if (expression != null) {
try { try {
match = expression.evaluate(editor, context, parent).toInsertableString(); match =
expression.evaluate(editor, injector.getExecutionContextManager().onEditor(editor, null), parent).toInsertableString();
} }
catch (Exception e) { catch (Exception e) {
exceptions.add((ExException)e); exceptions.add((ExException)e);
@@ -992,9 +993,7 @@ public class SearchGroup extends IjVimSearchGroup implements PersistentStateComp
return new Pair<>(true, new Triple<>(regmatch, pattern, sp)); return new Pair<>(true, new Triple<>(regmatch, pattern, sp));
} }
private static @NotNull ReplaceConfirmationChoice confirmChoice(@NotNull Editor editor, private static @NotNull ReplaceConfirmationChoice confirmChoice(@NotNull Editor editor, @NotNull String match, @NotNull Caret caret, int startoff) {
@NotNull ExecutionContext context,
@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;
@@ -1028,6 +1027,7 @@ public class SearchGroup extends IjVimSearchGroup implements PersistentStateComp
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);
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);
@@ -1085,9 +1085,9 @@ public class SearchGroup extends IjVimSearchGroup implements PersistentStateComp
private @Nullable TextRange findNextSearchForGn(@NotNull VimEditor editor, int count, boolean forwards) { private @Nullable 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(), count, searchOptions); return VimInjectorKt.getInjector().getSearchHelper().findPattern(editor, getLastUsedPattern(), editor.primaryCaret().getOffset().getPoint(), count, searchOptions);
} else { } else {
return searchBackward(editor, editor.primaryCaret().getOffset(), count); return searchBackward(editor, editor.primaryCaret().getOffset().getPoint(), count);
} }
} }
@@ -1200,50 +1200,47 @@ public class SearchGroup extends IjVimSearchGroup implements PersistentStateComp
public static DocumentSearchListener INSTANCE = new DocumentSearchListener(); public static DocumentSearchListener INSTANCE = new DocumentSearchListener();
@Contract(pure = true) @Contract(pure = true)
private DocumentSearchListener() { private DocumentSearchListener () {
} }
@Override @Override
public void documentChanged(@NotNull DocumentEvent event) { public void documentChanged(@NotNull DocumentEvent event) {
// Loop over all local editors for the changed document, across all projects, and update search highlights. for (Project project : ProjectManager.getInstance().getOpenProjects()) {
// Note that the change may have come from a remote guest in Code With Me scenarios (in which case final Document document = event.getDocument();
// ClientId.current will be a guest ID), but we don't care - we still need to add/remove highlights for the
// changed text. Make sure we only update local editors, though.
final Document document = event.getDocument();
for (VimEditor vimEditor : injector.getEditorGroup().getEditors(new IjVimDocument(document))) {
final Editor editor = ((IjVimEditor)vimEditor).getEditor();
Collection<RangeHighlighter> hls = UserDataManager.getVimLastHighlighters(editor);
if (hls == null) {
continue;
}
if (logger.isDebugEnabled()) { for (Editor editor : localEditors(document, project)) {
logger.debug("hls=" + hls); Collection<RangeHighlighter> hls = UserDataManager.getVimLastHighlighters(editor);
logger.debug("event=" + event); if (hls == null) {
} continue;
// We can only re-highlight whole lines, so clear any highlights in the affected lines
final LogicalPosition startPosition = editor.offsetToLogicalPosition(event.getOffset());
final LogicalPosition endPosition = editor.offsetToLogicalPosition(event.getOffset() + event.getNewLength());
final int startLineOffset = document.getLineStartOffset(startPosition.line);
final int endLineOffset = document.getLineEndOffset(endPosition.line);
final Iterator<RangeHighlighter> iter = hls.iterator();
while (iter.hasNext()) {
final RangeHighlighter highlighter = iter.next();
if (!highlighter.isValid() ||
(highlighter.getStartOffset() >= startLineOffset && highlighter.getEndOffset() <= endLineOffset)) {
iter.remove();
editor.getMarkupModel().removeHighlighter(highlighter);
} }
}
VimPlugin.getSearch().highlightSearchLines(editor, startPosition.line, endPosition.line); if (logger.isDebugEnabled()) {
logger.debug("hls=" + hls);
logger.debug("event=" + event);
}
if (logger.isDebugEnabled()) { // We can only re-highlight whole lines, so clear any highlights in the affected lines
hls = UserDataManager.getVimLastHighlighters(editor); final LogicalPosition startPosition = editor.offsetToLogicalPosition(event.getOffset());
logger.debug("sl=" + startPosition.line + ", el=" + endPosition.line); final LogicalPosition endPosition = editor.offsetToLogicalPosition(event.getOffset() + event.getNewLength());
logger.debug("hls=" + hls); final int startLineOffset = document.getLineStartOffset(startPosition.line);
final int endLineOffset = document.getLineEndOffset(endPosition.line);
final Iterator<RangeHighlighter> iter = hls.iterator();
while (iter.hasNext()) {
final RangeHighlighter highlighter = iter.next();
if (!highlighter.isValid() || (highlighter.getStartOffset() >= startLineOffset && highlighter.getEndOffset() <= endLineOffset)) {
iter.remove();
editor.getMarkupModel().removeHighlighter(highlighter);
}
}
VimPlugin.getSearch().highlightSearchLines(editor, startPosition.line, endPosition.line);
if (logger.isDebugEnabled()) {
hls = UserDataManager.getVimLastHighlighters(editor);
logger.debug("sl=" + startPosition.line + ", el=" + endPosition.line);
logger.debug("hls=" + hls);
}
} }
} }
} }

View File

@@ -111,7 +111,7 @@ internal class JumpsListener(val project: Project) : RecentPlacesListener {
} }
private fun buildJump(place: PlaceInfo): Jump? { private fun buildJump(place: PlaceInfo): Jump? {
val editor = injector.editorGroup.getEditors().firstOrNull { it.ij.virtualFile == place.file } ?: return null val editor = injector.editorGroup.localEditors().firstOrNull { it.ij.virtualFile == place.file } ?: return null
val offset = place.caretPosition?.startOffset ?: return null val offset = place.caretPosition?.startOffset ?: return null
val bufferPosition = editor.offsetToBufferPosition(offset) val bufferPosition = editor.offsetToBufferPosition(offset)

View File

@@ -7,7 +7,6 @@
*/ */
package com.maddyhome.idea.vim.group package com.maddyhome.idea.vim.group
import com.intellij.codeWithMe.ClientId
import com.intellij.ide.bookmark.Bookmark import com.intellij.ide.bookmark.Bookmark
import com.intellij.ide.bookmark.BookmarkGroup import com.intellij.ide.bookmark.BookmarkGroup
import com.intellij.ide.bookmark.BookmarksListener import com.intellij.ide.bookmark.BookmarksListener
@@ -19,7 +18,7 @@ import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage import com.intellij.openapi.components.Storage
import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.FileEditorManager
@@ -29,11 +28,11 @@ import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.asSafely import com.intellij.util.asSafely
import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimEditorGroup
import com.maddyhome.idea.vim.api.VimMarkService import com.maddyhome.idea.vim.api.VimMarkService
import com.maddyhome.idea.vim.api.VimMarkServiceBase import com.maddyhome.idea.vim.api.VimMarkServiceBase
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.group.SystemMarks.Companion.createOrGetSystemMark import com.maddyhome.idea.vim.group.SystemMarks.Companion.createOrGetSystemMark
import com.maddyhome.idea.vim.helper.localEditors
import com.maddyhome.idea.vim.mark.IntellijMark import com.maddyhome.idea.vim.mark.IntellijMark
import com.maddyhome.idea.vim.mark.Mark import com.maddyhome.idea.vim.mark.Mark
import com.maddyhome.idea.vim.mark.VimMark.Companion.create import com.maddyhome.idea.vim.mark.VimMark.Companion.create
@@ -194,10 +193,6 @@ internal class VimMarkServiceImpl : VimMarkServiceBase(), PersistentStateCompone
* This event indicates that a document is about to be changed. We use this event to update all the * This event indicates that a document is about to be changed. We use this event to update all the
* editor's marks if text is about to be deleted. * editor's marks if text is about to be deleted.
* *
* Note that the event is fired for both local changes and changes from remote guests in Code With Me scenarios (in
* which case [ClientId.current] will be the remote client). We don't care who caused it, we just need to update the
* stored marks.
*
* @param event The change event * @param event The change event
*/ */
override fun beforeDocumentChange(event: DocumentEvent) { override fun beforeDocumentChange(event: DocumentEvent) {
@@ -205,18 +200,15 @@ internal class VimMarkServiceImpl : VimMarkServiceBase(), PersistentStateCompone
if (logger.isDebugEnabled) logger.debug("MarkUpdater before, event = $event") if (logger.isDebugEnabled) logger.debug("MarkUpdater before, event = $event")
if (event.oldLength == 0) return if (event.oldLength == 0) return
val doc = event.document val doc = event.document
val anEditor = getAnyEditorForDocument(doc) ?: return val anEditor = getAnEditor(doc) ?: return
injector.markService.updateMarksFromDelete(anEditor, event.offset, event.oldLength) injector.markService
.updateMarksFromDelete(IjVimEditor(anEditor), event.offset, event.oldLength)
} }
/** /**
* This event indicates that a document was just changed. We use this event to update all the editor's * This event indicates that a document was just changed. We use this event to update all the editor's
* marks if text was just added. * marks if text was just added.
* *
* Note that the event is fired for both local changes and changes from remote guests in Code With Me scenarios (in
* which case [ClientId.current] will be the remote client). We don't care who caused it, we just need to update the
* stored marks.
*
* @param event The change event * @param event The change event
*/ */
override fun documentChanged(event: DocumentEvent) { override fun documentChanged(event: DocumentEvent) {
@@ -224,19 +216,19 @@ internal class VimMarkServiceImpl : VimMarkServiceBase(), PersistentStateCompone
if (logger.isDebugEnabled) logger.debug("MarkUpdater after, event = $event") if (logger.isDebugEnabled) logger.debug("MarkUpdater after, event = $event")
if (event.newLength == 0 || event.newLength == 1 && event.newFragment[0] != '\n') return if (event.newLength == 0 || event.newLength == 1 && event.newFragment[0] != '\n') return
val doc = event.document val doc = event.document
val anEditor = getAnyEditorForDocument(doc) ?: return val anEditor = getAnEditor(doc) ?: return
injector.markService.updateMarksFromInsert(anEditor, event.offset, event.newLength) injector.markService
.updateMarksFromInsert(IjVimEditor(anEditor), event.offset, event.newLength)
} }
/** private fun getAnEditor(doc: Document): Editor? {
* Get any editor for the given document val editors = localEditors(doc)
* return if (editors.size > 0) {
* We need an editor to help calculate offsets for marks, and it doesn't matter which one we use, because they would editors[0]
* all return the same results. However, we cannot use [VimEditorGroup.getEditors] because the change might have } else {
* come from a remote guest and there might not be an open local editor. null
*/ }
private fun getAnyEditorForDocument(doc: Document) = }
EditorFactory.getInstance().getEditors(doc).firstOrNull()?.let { IjVimEditor(it) }
} }
class VimBookmarksListener(private val myProject: Project) : BookmarksListener { class VimBookmarksListener(private val myProject: Project) : BookmarksListener {

View File

@@ -20,8 +20,9 @@ import com.maddyhome.idea.vim.helper.exitVisualMode
import com.maddyhome.idea.vim.helper.hasVisualSelection import com.maddyhome.idea.vim.helper.hasVisualSelection
import com.maddyhome.idea.vim.helper.inInsertMode import com.maddyhome.idea.vim.helper.inInsertMode
import com.maddyhome.idea.vim.helper.inNormalMode import com.maddyhome.idea.vim.helper.inNormalMode
import com.maddyhome.idea.vim.helper.isIdeaVimDisabledHere
import com.maddyhome.idea.vim.helper.isTemplateActive import com.maddyhome.idea.vim.helper.isTemplateActive
import com.maddyhome.idea.vim.helper.vimDisabled import com.maddyhome.idea.vim.helper.vimStateMachine
import com.maddyhome.idea.vim.listener.VimListenerManager import com.maddyhome.idea.vim.listener.VimListenerManager
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.options.OptionConstants import com.maddyhome.idea.vim.options.OptionConstants
@@ -29,6 +30,7 @@ import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.inNormalMode import com.maddyhome.idea.vim.state.mode.inNormalMode
import com.maddyhome.idea.vim.state.mode.inSelectMode import com.maddyhome.idea.vim.state.mode.inSelectMode
import com.maddyhome.idea.vim.state.mode.inVisualMode import com.maddyhome.idea.vim.state.mode.inVisualMode
import com.maddyhome.idea.vim.state.mode.mode
import com.maddyhome.idea.vim.vimscript.model.options.helpers.IdeaRefactorModeHelper import com.maddyhome.idea.vim.vimscript.model.options.helpers.IdeaRefactorModeHelper
import com.maddyhome.idea.vim.vimscript.model.options.helpers.isIdeaRefactorModeKeep import com.maddyhome.idea.vim.vimscript.model.options.helpers.isIdeaRefactorModeKeep
import com.maddyhome.idea.vim.vimscript.model.options.helpers.isIdeaRefactorModeSelect import com.maddyhome.idea.vim.vimscript.model.options.helpers.isIdeaRefactorModeSelect
@@ -53,7 +55,9 @@ internal object IdeaSelectionControl {
selectionSource: VimListenerManager.SelectionSource = VimListenerManager.SelectionSource.OTHER, selectionSource: VimListenerManager.SelectionSource = VimListenerManager.SelectionSource.OTHER,
) { ) {
VimVisualTimer.singleTask(editor.vim.mode) { initialMode -> VimVisualTimer.singleTask(editor.vim.mode) { initialMode ->
if (vimDisabled(editor)) return@singleTask
if (VimPlugin.isNotEnabled()) return@singleTask
if (editor.isIdeaVimDisabledHere) return@singleTask
logger.debug("Adjust non-vim selection. Source: $selectionSource, initialMode: $initialMode") logger.debug("Adjust non-vim selection. Source: $selectionSource, initialMode: $initialMode")
@@ -75,7 +79,7 @@ internal object IdeaSelectionControl {
logger.debug("Some carets have selection. State before adjustment: ${editor.vim.mode}") logger.debug("Some carets have selection. State before adjustment: ${editor.vim.mode}")
editor.vim.mode = Mode.NORMAL() editor.vim.vimStateMachine.mode = Mode.NORMAL()
activateMode(editor, chooseSelectionMode(editor, selectionSource, true)) activateMode(editor, chooseSelectionMode(editor, selectionSource, true))
} else { } else {
@@ -117,7 +121,7 @@ internal object IdeaSelectionControl {
is Mode.VISUAL -> VimPlugin.getVisualMotion().enterVisualMode(editor.vim, mode.selectionType) is Mode.VISUAL -> VimPlugin.getVisualMotion().enterVisualMode(editor.vim, mode.selectionType)
is Mode.SELECT -> VimPlugin.getVisualMotion().enterSelectMode(editor.vim, mode.selectionType) is Mode.SELECT -> VimPlugin.getVisualMotion().enterSelectMode(editor.vim, mode.selectionType)
is Mode.INSERT -> VimPlugin.getChange() is Mode.INSERT -> VimPlugin.getChange()
.insertBeforeCursor(editor.vim, injector.executionContextManager.getEditorExecutionContext(editor.vim)) .insertBeforeCursor(editor.vim, injector.executionContextManager.onEditor(editor.vim))
is Mode.NORMAL -> Unit is Mode.NORMAL -> Unit
else -> error("Unexpected mode: $mode") else -> error("Unexpected mode: $mode")

View File

@@ -12,13 +12,13 @@ import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.api.getLineEndForOffset import com.maddyhome.idea.vim.api.getLineEndForOffset
import com.maddyhome.idea.vim.api.getLineStartForOffset import com.maddyhome.idea.vim.api.getLineStartForOffset
import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.inBlockSelection
import com.maddyhome.idea.vim.helper.isEndAllowed import com.maddyhome.idea.vim.helper.isEndAllowed
import com.maddyhome.idea.vim.helper.moveToInlayAwareOffset import com.maddyhome.idea.vim.helper.moveToInlayAwareOffset
import com.maddyhome.idea.vim.helper.vimSelectionStart import com.maddyhome.idea.vim.helper.vimSelectionStart
import com.maddyhome.idea.vim.newapi.IjVimEditor import com.maddyhome.idea.vim.newapi.IjVimEditor
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.inBlockSelection
internal fun moveCaretOneCharLeftFromSelectionEnd(editor: Editor, predictedMode: Mode) { internal fun moveCaretOneCharLeftFromSelectionEnd(editor: Editor, predictedMode: Mode) {
if (predictedMode !is Mode.VISUAL) { if (predictedMode !is Mode.VISUAL) {

View File

@@ -13,10 +13,10 @@ import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimVisualMotionGroupBase import com.maddyhome.idea.vim.api.VimVisualMotionGroupBase
import com.maddyhome.idea.vim.command.CommandState import com.maddyhome.idea.vim.command.CommandState
import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.command.engine import com.maddyhome.idea.vim.command.engine
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.state.mode.SelectionType
/** /**
* @author Alex Plate * @author Alex Plate

View File

@@ -27,6 +27,7 @@ import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.removeUserData import com.intellij.openapi.util.removeUserData
import com.maddyhome.idea.vim.KeyHandler import com.maddyhome.idea.vim.KeyHandler
import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.globalOptions
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.api.key import com.maddyhome.idea.vim.api.key
import com.maddyhome.idea.vim.group.IjOptionConstants import com.maddyhome.idea.vim.group.IjOptionConstants
@@ -38,6 +39,7 @@ import com.maddyhome.idea.vim.newapi.actionStartedFromVim
import com.maddyhome.idea.vim.newapi.globalIjOptions import com.maddyhome.idea.vim.newapi.globalIjOptions
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.state.mode.Mode import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.mode
import java.awt.event.KeyEvent import java.awt.event.KeyEvent
import javax.swing.KeyStroke import javax.swing.KeyStroke
@@ -337,9 +339,8 @@ internal abstract class VimKeyHandler(nextHandler: EditorActionHandler?) : Octop
override fun executeHandler(editor: Editor, caret: Caret?, dataContext: DataContext?) { override fun executeHandler(editor: Editor, caret: Caret?, dataContext: DataContext?) {
val enterKey = key(key) val enterKey = key(key)
val context = dataContext?.vim ?: injector.executionContextManager.getEditorExecutionContext(editor.vim) val context = injector.executionContextManager.onEditor(editor.vim, dataContext?.vim)
val keyHandler = KeyHandler.getInstance() KeyHandler.getInstance().handleKey(editor.vim, enterKey, context)
keyHandler.handleKey(editor.vim, enterKey, context, keyHandler.keyHandlerState)
} }
override fun isHandlerEnabled(editor: Editor, dataContext: DataContext?): Boolean { override fun isHandlerEnabled(editor: Editor, dataContext: DataContext?): Boolean {
@@ -361,4 +362,4 @@ internal fun isOctopusEnabled(s: KeyStroke, editor: Editor): Boolean {
} }
internal val enableOctopus: Boolean internal val enableOctopus: Boolean
get() = injector.application.isOctopusEnabled() get() = injector.globalOptions().octopushandler

View File

@@ -19,17 +19,14 @@ import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.globalOptions import com.maddyhome.idea.vim.api.globalOptions
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.common.IsReplaceCharListener
import com.maddyhome.idea.vim.common.ModeChangeListener
import com.maddyhome.idea.vim.newapi.IjVimEditor
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.options.EffectiveOptionValueChangeListener import com.maddyhome.idea.vim.options.EffectiveOptionValueChangeListener
import com.maddyhome.idea.vim.options.helpers.GuiCursorMode import com.maddyhome.idea.vim.options.helpers.GuiCursorMode
import com.maddyhome.idea.vim.options.helpers.GuiCursorOptionHelper import com.maddyhome.idea.vim.options.helpers.GuiCursorOptionHelper
import com.maddyhome.idea.vim.options.helpers.GuiCursorType import com.maddyhome.idea.vim.options.helpers.GuiCursorType
import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.inBlockSelection import com.maddyhome.idea.vim.state.mode.inBlockSelection
import com.maddyhome.idea.vim.state.mode.mode
import org.jetbrains.annotations.TestOnly import org.jetbrains.annotations.TestOnly
import java.awt.Color import java.awt.Color
@@ -90,8 +87,6 @@ private fun Editor.updatePrimaryCaretVisualAttributes() {
// Make sure the caret is visible as soon as it's set. It might be invisible while blinking // Make sure the caret is visible as soon as it's set. It might be invisible while blinking
// NOTE: At the moment, this causes project leak in tests // NOTE: At the moment, this causes project leak in tests
// IJPL-928 - this will be fixed in 2024.2
// [VERSION UPDATE] 2024.2 - remove if wrapping
if (!ApplicationManager.getApplication().isUnitTestMode) { if (!ApplicationManager.getApplication().isUnitTestMode) {
(this as? EditorEx)?.setCaretVisible(true) (this as? EditorEx)?.setCaretVisible(true)
} }
@@ -143,31 +138,3 @@ private object AttributesCache {
@TestOnly @TestOnly
internal fun getGuiCursorMode(editor: Editor) = editor.guicursorMode() internal fun getGuiCursorMode(editor: Editor) = editor.guicursorMode()
public class CaretVisualAttributesListener : IsReplaceCharListener, ModeChangeListener {
override fun isReplaceCharChanged(editor: VimEditor) {
updateCaretsVisual(editor)
}
override fun modeChanged(editor: VimEditor, oldMode: Mode) {
updateCaretsVisual(editor)
}
private fun updateCaretsVisual(editor: VimEditor) {
if (injector.globalOptions().ideaglobalmode) {
updateAllEditorsCaretsVisual()
} else {
val ijEditor = (editor as IjVimEditor).editor
ijEditor.updateCaretsVisualAttributes()
ijEditor.updateCaretsVisualPosition()
}
}
public fun updateAllEditorsCaretsVisual() {
injector.editorGroup.getEditors().forEach { editor ->
val ijEditor = (editor as IjVimEditor).editor
ijEditor.updateCaretsVisualAttributes()
ijEditor.updateCaretsVisualPosition()
}
}
}

View File

@@ -11,8 +11,8 @@ package com.maddyhome.idea.vim.helper
import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service import com.intellij.openapi.components.Service
import com.maddyhome.idea.vim.action.change.Extension import com.maddyhome.idea.vim.action.change.Extension
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.ui.ModalEntry import com.maddyhome.idea.vim.ui.ModalEntry
@@ -23,7 +23,7 @@ import javax.swing.KeyStroke
@Service @Service
internal class CommandLineHelper : VimCommandLineHelper { internal class CommandLineHelper : VimCommandLineHelper {
override fun inputString(vimEditor: VimEditor, context: ExecutionContext, prompt: String, finishOn: Char?): String? { override fun inputString(vimEditor: VimEditor, prompt: String, finishOn: Char?): String? {
val editor = vimEditor.ij val editor = vimEditor.ij
if (vimEditor.vimStateMachine.isDotRepeatInProgress) { if (vimEditor.vimStateMachine.isDotRepeatInProgress) {
val input = Extension.consumeString() val input = Extension.consumeString()
@@ -53,7 +53,7 @@ internal class CommandLineHelper : VimCommandLineHelper {
var text: String? = null var text: String? = null
// XXX: The Ex entry panel is used only for UI here, its logic might be inappropriate for input() // XXX: The Ex entry panel is used only for UI here, its logic might be inappropriate for input()
val exEntryPanel = ExEntryPanel.getInstanceWithoutShortcuts() val exEntryPanel = ExEntryPanel.getInstanceWithoutShortcuts()
exEntryPanel.activate(editor, context.ij, prompt.ifEmpty { " " }, "", 1) exEntryPanel.activate(editor, injector.executionContextManager.onEditor(editor.vim).ij, prompt.ifEmpty { " " }, "", 1)
ModalEntry.activate(editor.vim) { key: KeyStroke -> ModalEntry.activate(editor.vim) { key: KeyStroke ->
return@activate when { return@activate when {
key.isCloseKeyStroke() -> { key.isCloseKeyStroke() -> {

View File

@@ -20,6 +20,7 @@ import com.maddyhome.idea.vim.options.OptionAccessScope
import com.maddyhome.idea.vim.options.OptionConstants import com.maddyhome.idea.vim.options.OptionConstants
import com.maddyhome.idea.vim.state.mode.Mode import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.inVisualMode import com.maddyhome.idea.vim.state.mode.inVisualMode
import com.maddyhome.idea.vim.state.mode.mode
internal val Mode.hasVisualSelection internal val Mode.hasVisualSelection
get() = when (this) { get() = when (this) {

View File

@@ -0,0 +1,45 @@
/*
* Copyright 2003-2023 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.helper
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.util.Key
import com.maddyhome.idea.vim.EventFacade
import com.maddyhome.idea.vim.group.SearchGroup
import com.maddyhome.idea.vim.group.VimMarkServiceImpl
internal object DocumentManager {
private val docListeners = mutableSetOf<DocumentListener>()
private val LISTENER_MARKER = Key<String>("VimlistenerMarker")
init {
docListeners += VimMarkServiceImpl.MarkUpdater
docListeners += SearchGroup.DocumentSearchListener.INSTANCE
}
fun addListeners(doc: Document) {
val marker = doc.getUserData(LISTENER_MARKER)
if (marker != null) return
doc.putUserData(LISTENER_MARKER, "foo")
for (docListener in docListeners) {
EventFacade.getInstance().addDocumentListener(doc, docListener)
}
}
fun removeListeners(doc: Document) {
doc.getUserData(LISTENER_MARKER) ?: return
doc.putUserData(LISTENER_MARKER, null)
for (docListener in docListeners) {
EventFacade.getInstance().removeDocumentListener(doc, docListener)
}
}
}

View File

@@ -14,7 +14,6 @@ import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.util.Key import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.util.UserDataHolder
@Deprecated("Do not use context wrappers, use existing provided contexts. If no context available, use `injector.getExecutionContextManager().getEditorExecutionContext(editor)`")
internal class EditorDataContext @Deprecated("Please use `init` method") constructor( internal class EditorDataContext @Deprecated("Please use `init` method") constructor(
private val editor: Editor, private val editor: Editor,
private val editorContext: DataContext, private val editorContext: DataContext,

View File

@@ -17,7 +17,6 @@ import com.intellij.testFramework.LightVirtualFile;
import com.maddyhome.idea.vim.api.EngineEditorHelperKt; import com.maddyhome.idea.vim.api.EngineEditorHelperKt;
import com.maddyhome.idea.vim.api.VimEditor; import com.maddyhome.idea.vim.api.VimEditor;
import com.maddyhome.idea.vim.common.IndentConfig; import com.maddyhome.idea.vim.common.IndentConfig;
import com.maddyhome.idea.vim.newapi.IjVimDocument;
import com.maddyhome.idea.vim.newapi.IjVimEditor; import com.maddyhome.idea.vim.newapi.IjVimEditor;
import com.maddyhome.idea.vim.ui.ex.ExEntryPanel; import com.maddyhome.idea.vim.ui.ex.ExEntryPanel;
import kotlin.Pair; import kotlin.Pair;
@@ -30,7 +29,6 @@ import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import static com.maddyhome.idea.vim.api.VimInjectorKt.injector;
import static java.lang.Integer.max; import static java.lang.Integer.max;
import static java.lang.Integer.min; import static java.lang.Integer.min;
@@ -199,7 +197,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 VimEditor getEditor(final @Nullable VirtualFile file) { public static @Nullable Editor getEditor(final @Nullable VirtualFile file) {
if (file == null) { if (file == null) {
return null; return null;
} }
@@ -208,15 +206,23 @@ public class EditorHelper {
if (doc == null) { if (doc == null) {
return null; return null;
} }
return injector.getEditorGroup().getEditors(new IjVimDocument(doc)).stream().findFirst().orElse(null); final List<Editor> editors = HelperKt.localEditors(doc);
if (editors.size() > 0) {
return editors.get(0);
}
return null;
} }
public static @NotNull String pad(final @NotNull Editor editor, int line, final int to) { public static @NotNull String pad(final @NotNull Editor editor,
@NotNull DataContext context,
int line,
final int to) {
final int len = EngineEditorHelperKt.lineLength(new IjVimEditor(editor), line); final int len = EngineEditorHelperKt.lineLength(new IjVimEditor(editor), line);
if (len >= to) return ""; if (len >= to) return "";
final int limit = to - len; final int limit = to - len;
return IndentConfig.create(editor).createIndentBySize(limit); return IndentConfig.create(editor, context).createIndentBySize(limit);
} }
/** /**
@@ -323,7 +329,7 @@ public class EditorHelper {
final int offset = y - ((screenHeight - lineHeight) / lineHeight / 2 * lineHeight); final int offset = y - ((screenHeight - lineHeight) / lineHeight / 2 * lineHeight);
@NotNull final VimEditor editor1 = new IjVimEditor(editor); @NotNull final VimEditor editor1 = new IjVimEditor(editor);
final int lastVisualLine = EngineEditorHelperKt.getVisualLineCount(editor1) + editor.getSettings().getAdditionalLinesCount(); final int lastVisualLine = EngineEditorHelperKt.getVisualLineCount(editor1) - 1;
final int offsetForLastLineAtBottom = getOffsetToScrollVisualLineToBottomOfScreen(editor, lastVisualLine); final int offsetForLastLineAtBottom = getOffsetToScrollVisualLineToBottomOfScreen(editor, lastVisualLine);
// For `zz`, we want to use virtual space and move any line, including the last one, to the middle of the screen. // For `zz`, we want to use virtual space and move any line, including the last one, to the middle of the screen.

View File

@@ -12,17 +12,13 @@ package com.maddyhome.idea.vim.helper
import com.intellij.codeWithMe.ClientId import com.intellij.codeWithMe.ClientId
import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.CaretState
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.util.ui.table.JBTableRowEditor import com.intellij.util.ui.table.JBTableRowEditor
import com.maddyhome.idea.vim.api.StringListOptionValue
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.group.IjOptionConstants import com.maddyhome.idea.vim.group.IjOptionConstants
import com.maddyhome.idea.vim.newapi.globalIjOptions import com.maddyhome.idea.vim.newapi.globalIjOptions
import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.state.mode.inBlockSelection
import java.awt.Component import java.awt.Component
import javax.swing.JComponent import javax.swing.JComponent
import javax.swing.JTable import javax.swing.JTable
@@ -38,27 +34,25 @@ public val Editor.fileSize: Int
internal val Editor.isIdeaVimDisabledHere: Boolean internal val Editor.isIdeaVimDisabledHere: Boolean
get() { get() {
val ideaVimSupportValue = injector.globalIjOptions().ideavimsupport val ideaVimSupportValue = injector.globalIjOptions().ideavimsupport
return (ideaVimDisabledInDialog(ideaVimSupportValue) && isInDialog()) || return disabledInDialog ||
!ClientId.isCurrentlyUnderLocalId || // CWM-927 (!ClientId.isCurrentlyUnderLocalId) || // CWM-927
(ideaVimDisabledForSingleLine(ideaVimSupportValue) && isSingleLine()) (!ideaVimSupportValue.contains(IjOptionConstants.ideavimsupport_singleline) && isDatabaseCell()) ||
(!ideaVimSupportValue.contains(IjOptionConstants.ideavimsupport_singleline) && isOneLineMode)
} }
private fun ideaVimDisabledInDialog(ideaVimSupportValue: StringListOptionValue): Boolean { private fun Editor.isDatabaseCell(): Boolean {
return !ideaVimSupportValue.contains(IjOptionConstants.ideavimsupport_dialog) return isTableCellEditor(this.component)
&& !ideaVimSupportValue.contains(IjOptionConstants.ideavimsupport_dialoglegacy)
} }
private fun ideaVimDisabledForSingleLine(ideaVimSupportValue: StringListOptionValue): Boolean { private val Editor.disabledInDialog: Boolean
return !ideaVimSupportValue.contains(IjOptionConstants.ideavimsupport_singleline) get() {
} val ideaVimSupportValue = injector.globalIjOptions().ideavimsupport
return (
private fun Editor.isInDialog(): Boolean { !ideaVimSupportValue.contains(IjOptionConstants.ideavimsupport_dialog) &&
return !this.isPrimaryEditor() && !EditorHelper.isFileEditor(this) !ideaVimSupportValue.contains(IjOptionConstants.ideavimsupport_dialoglegacy)
} ) &&
(!this.isPrimaryEditor() && !EditorHelper.isFileEditor(this))
private fun Editor.isSingleLine(): Boolean { }
return isTableCellEditor(this.component) || isOneLineMode
}
/** /**
* Checks if the editor is a primary editor in the main editing area. * Checks if the editor is a primary editor in the main editing area.
@@ -99,41 +93,3 @@ internal val Caret.vimLine: Int
*/ */
internal val Editor.vimLine: Int internal val Editor.vimLine: Int
get() = this.caretModel.currentCaret.vimLine get() = this.caretModel.currentCaret.vimLine
internal inline fun Editor.runWithEveryCaretAndRestore(action: () -> Unit) {
val caretModel = this.caretModel
val carets = if (this.vim.inBlockSelection) null else caretModel.allCarets
if (carets == null || carets.size == 1) {
action()
}
else {
var initialDocumentSize = this.document.textLength
var documentSizeDifference = 0
val caretOffsets = carets.map { it.selectionStart to it.selectionEnd }
val restoredCarets = mutableListOf<CaretState>()
caretModel.removeSecondaryCarets()
for ((selectionStart, selectionEnd) in caretOffsets) {
if (selectionStart == selectionEnd) {
caretModel.primaryCaret.moveToOffset(selectionStart + documentSizeDifference)
}
else {
caretModel.primaryCaret.setSelection(
selectionStart + documentSizeDifference,
selectionEnd + documentSizeDifference
)
}
action()
restoredCarets.add(caretModel.caretsAndSelections.single())
val documentLength = this.document.textLength
documentSizeDifference += documentLength - initialDocumentSize
initialDocumentSize = documentLength
}
caretModel.caretsAndSelections = restoredCarets
}
}

View File

@@ -9,12 +9,19 @@
package com.maddyhome.idea.vim.helper package com.maddyhome.idea.vim.helper
import com.intellij.codeInsight.template.TemplateManager import com.intellij.codeInsight.template.TemplateManager
import com.intellij.codeWithMe.ClientId
import com.intellij.injected.editor.EditorWindow import com.intellij.injected.editor.EditorWindow
import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.ClientEditorManager
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.state.mode.inBlockSelection import com.maddyhome.idea.vim.state.mode.inBlockSelection
import java.util.stream.Collectors
internal fun <T : Comparable<T>> sort(a: T, b: T) = if (a > b) b to a else a to b internal fun <T : Comparable<T>> sort(a: T, b: T) = if (a > b) b to a else a to b
@@ -29,6 +36,34 @@ internal inline fun Editor.vimForEachCaret(action: (caret: Caret) -> Unit) {
internal fun Editor.getTopLevelEditor() = if (this is EditorWindow) this.delegate else this internal fun Editor.getTopLevelEditor() = if (this is EditorWindow) this.delegate else this
/**
* Return list of editors for local host (for code with me plugin)
*/
public fun localEditors(): List<Editor> {
return ClientEditorManager.getCurrentInstance().editors().collect(Collectors.toList())
}
public fun localEditors(doc: Document): List<Editor> {
return EditorFactory.getInstance().getEditors(doc)
.filter { editor -> editor.editorClientId.let { it == null || it == ClientId.currentOrNull } }
}
public fun localEditors(doc: Document, project: Project): List<Editor> {
return EditorFactory.getInstance().getEditors(doc, project)
.filter { editor -> editor.editorClientId.let { it == null || it == ClientId.currentOrNull } }
}
private val Editor.editorClientId: ClientId?
get() {
if (editorClientKey == null) {
@Suppress("DEPRECATION")
editorClientKey = Key.findKeyByName("editorClientIdby userData()") ?: return null
}
return editorClientKey?.let { this.getUserData(it) as? ClientId }
}
private var editorClientKey: Key<*>? = null
@Suppress("IncorrectParentDisposable") @Suppress("IncorrectParentDisposable")
internal fun Editor.isTemplateActive(): Boolean { internal fun Editor.isTemplateActive(): Boolean {
val project = this.project ?: return false val project = this.project ?: return false

View File

@@ -21,7 +21,6 @@ import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.actionSystem.ex.ActionManagerEx import com.intellij.openapi.actionSystem.ex.ActionManagerEx
import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.ProxyShortcutSet import com.intellij.openapi.actionSystem.impl.ProxyShortcutSet
import com.intellij.openapi.actionSystem.impl.Utils
import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.UndoConfirmationPolicy import com.intellij.openapi.command.UndoConfirmationPolicy
import com.intellij.openapi.components.Service import com.intellij.openapi.components.Service
@@ -35,6 +34,7 @@ import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.NativeAction import com.maddyhome.idea.vim.api.NativeAction
import com.maddyhome.idea.vim.api.VimActionExecutor import com.maddyhome.idea.vim.api.VimActionExecutor
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.handler.EditorActionHandlerBase import com.maddyhome.idea.vim.handler.EditorActionHandlerBase
import com.maddyhome.idea.vim.newapi.IjNativeAction import com.maddyhome.idea.vim.newapi.IjNativeAction
@@ -78,7 +78,6 @@ internal class IjActionExecutor : VimActionExecutor {
val dataContext = DataContextWrapper(context.ij) val dataContext = DataContextWrapper(context.ij)
dataContext.putUserData(runFromVimKey, true) dataContext.putUserData(runFromVimKey, true)
val actionId = ActionManager.getInstance().getId(ijAction)
val event = AnActionEvent( val event = AnActionEvent(
null, null,
dataContext, dataContext,
@@ -87,20 +86,11 @@ internal class IjActionExecutor : VimActionExecutor {
ActionManager.getInstance(), ActionManager.getInstance(),
0, 0,
) )
Utils.initUpdateSession(event)
// beforeActionPerformedUpdate should be called to update the action. It fixes some rider-specific problems. // beforeActionPerformedUpdate should be called to update the action. It fixes some rider-specific problems.
// because rider use async update method. See VIM-1819. // because rider use async update method. See VIM-1819.
// This method executes inside of lastUpdateAndCheckDumb // This method executes inside of lastUpdateAndCheckDumb
// Another related issue: VIM-2604 // Another related issue: VIM-2604
if (!ActionUtil.lastUpdateAndCheckDumb(ijAction, event, false)) return false
// This is a hack to fix the tests and fix VIM-3332
// We should get rid of it in VIM-3376
if (actionId == "RunClass" || actionId == IdeActions.ACTION_COMMENT_LINE || actionId == IdeActions.ACTION_COMMENT_BLOCK) {
ijAction.beforeActionPerformedUpdate(event)
if (!event.presentation.isEnabled) return false
} else {
if (!ActionUtil.lastUpdateAndCheckDumb(ijAction, event, false)) return false
}
if (ijAction is ActionGroup && !event.presentation.isPerformGroup) { if (ijAction is ActionGroup && !event.presentation.isPerformGroup) {
// Some ActionGroups should not be performed, but shown as a popup // Some ActionGroups should not be performed, but shown as a popup
val popup = JBPopupFactory.getInstance() val popup = JBPopupFactory.getInstance()
@@ -224,7 +214,7 @@ internal class IjActionExecutor : VimActionExecutor {
CommandProcessor.getInstance() CommandProcessor.getInstance()
.executeCommand( .executeCommand(
editor.ij.project, editor.ij.project,
{ cmd.execute(editor, context, operatorArguments) }, { cmd.execute(editor, injector.executionContextManager.onEditor(editor, context), operatorArguments) },
cmd.id, cmd.id,
DocCommandGroupId.noneGroupId(editor.ij.document), DocCommandGroupId.noneGroupId(editor.ij.document),
UndoConfirmationPolicy.DEFAULT, UndoConfirmationPolicy.DEFAULT,

View File

@@ -14,6 +14,7 @@ import com.intellij.openapi.editor.VisualPosition
import com.intellij.openapi.editor.actionSystem.EditorActionManager import com.intellij.openapi.editor.actionSystem.EditorActionManager
import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.editor.ex.util.EditorUtil
import com.maddyhome.idea.vim.api.EngineEditorHelper import com.maddyhome.idea.vim.api.EngineEditorHelper
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimVisualPosition import com.maddyhome.idea.vim.api.VimVisualPosition
import com.maddyhome.idea.vim.newapi.IjVimEditor import com.maddyhome.idea.vim.newapi.IjVimEditor
@@ -50,8 +51,8 @@ internal class IjEditorHelper : EngineEditorHelper {
return EditorHelper.getVisualLineAtBottomOfScreen(editor.ij) return EditorHelper.getVisualLineAtBottomOfScreen(editor.ij)
} }
override fun pad(editor: VimEditor, line: Int, to: Int): String { override fun pad(editor: VimEditor, context: ExecutionContext, line: Int, to: Int): String {
return EditorHelper.pad(editor.ij, line, to) return EditorHelper.pad(editor.ij, context.ij, line, to)
} }
override fun inlayAwareOffsetToVisualPosition(editor: VimEditor, offset: Int): VimVisualPosition { override fun inlayAwareOffsetToVisualPosition(editor: VimEditor, offset: Int): VimVisualPosition {

View File

@@ -34,15 +34,15 @@ internal fun Editor.exitSelectMode(adjustCaretPosition: Boolean) {
val returnTo = this.vim.vimStateMachine.mode.returnTo val returnTo = this.vim.vimStateMachine.mode.returnTo
when (returnTo) { when (returnTo) {
ReturnTo.INSERT -> { ReturnTo.INSERT -> {
this.vim.mode = Mode.INSERT this.vim.vimStateMachine.mode = Mode.INSERT
} }
ReturnTo.REPLACE -> { ReturnTo.REPLACE -> {
this.vim.mode = Mode.REPLACE this.vim.vimStateMachine.mode = Mode.REPLACE
} }
null -> { null -> {
this.vim.mode = Mode.NORMAL() this.vim.vimStateMachine.mode = Mode.NORMAL()
} }
} }
SelectionVimListenerSuppressor.lock().use { SelectionVimListenerSuppressor.lock().use {
@@ -67,15 +67,15 @@ internal fun VimEditor.exitSelectMode(adjustCaretPosition: Boolean) {
val returnTo = this.vimStateMachine.mode.returnTo val returnTo = this.vimStateMachine.mode.returnTo
when (returnTo) { when (returnTo) {
ReturnTo.INSERT -> { ReturnTo.INSERT -> {
this.mode = Mode.INSERT this.vimStateMachine.mode = Mode.INSERT
} }
ReturnTo.REPLACE -> { ReturnTo.REPLACE -> {
this.mode = Mode.REPLACE this.vimStateMachine.mode = Mode.REPLACE
} }
null -> { null -> {
this.mode = Mode.NORMAL() this.vimStateMachine.mode = Mode.NORMAL()
} }
} }
SelectionVimListenerSuppressor.lock().use { SelectionVimListenerSuppressor.lock().use {

View File

@@ -14,6 +14,7 @@ import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.api.normalizeVisualColumn import com.maddyhome.idea.vim.api.normalizeVisualColumn
import com.maddyhome.idea.vim.api.options import com.maddyhome.idea.vim.api.options
import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.state.VimStateMachine
import com.maddyhome.idea.vim.helper.EditorHelper.getApproximateScreenHeight import com.maddyhome.idea.vim.helper.EditorHelper.getApproximateScreenHeight
import com.maddyhome.idea.vim.helper.EditorHelper.getApproximateScreenWidth import com.maddyhome.idea.vim.helper.EditorHelper.getApproximateScreenWidth
import com.maddyhome.idea.vim.helper.EditorHelper.getNonNormalizedVisualLineAtBottomOfScreen import com.maddyhome.idea.vim.helper.EditorHelper.getNonNormalizedVisualLineAtBottomOfScreen
@@ -28,7 +29,6 @@ import com.maddyhome.idea.vim.helper.EditorHelper.scrollVisualLineToBottomOfScre
import com.maddyhome.idea.vim.helper.EditorHelper.scrollVisualLineToMiddleOfScreen import com.maddyhome.idea.vim.helper.EditorHelper.scrollVisualLineToMiddleOfScreen
import com.maddyhome.idea.vim.helper.EditorHelper.scrollVisualLineToTopOfScreen import com.maddyhome.idea.vim.helper.EditorHelper.scrollVisualLineToTopOfScreen
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.state.VimStateMachine
import kotlin.math.max import kotlin.math.max
import kotlin.math.min import kotlin.math.min
import kotlin.math.roundToInt import kotlin.math.roundToInt
@@ -56,7 +56,7 @@ internal object ScrollViewHelper {
// that this needs to be replaced as a more or less dumb line for line rewrite. // that this needs to be replaced as a more or less dumb line for line rewrite.
val topLine = getVisualLineAtTopOfScreen(editor) val topLine = getVisualLineAtTopOfScreen(editor)
val bottomLine = getVisualLineAtBottomOfScreen(editor) val bottomLine = getVisualLineAtBottomOfScreen(editor)
val lastLine = vimEditor.getVisualLineCount() + editor.settings.additionalLinesCount val lastLine = vimEditor.getVisualLineCount() - 1
// We need the non-normalised value here, so we can handle cases such as so=999 to keep the current line centred // We need the non-normalised value here, so we can handle cases such as so=999 to keep the current line centred
val scrollOffset = injector.options(vimEditor).scrolloff val scrollOffset = injector.options(vimEditor).scrolloff

View File

@@ -632,6 +632,113 @@ public class SearchHelper {
return new TextRange(bstart, bend + 1); return new TextRange(bstart, bend + 1);
} }
private static int findMatchingBlockCommentPair(@NotNull PsiComment comment,
int pos,
@Nullable String prefix,
@Nullable String suffix) {
if (prefix != null && suffix != null) {
// TODO: Try to get rid of `getText()` because it takes a lot of time to calculate the string
final String commentText = comment.getText();
if (commentText.startsWith(prefix) && commentText.endsWith(suffix)) {
final int endOffset = comment.getTextOffset() + comment.getTextLength();
if (pos < comment.getTextOffset() + prefix.length()) {
return endOffset;
}
else if (pos >= endOffset - suffix.length()) {
return comment.getTextOffset();
}
}
}
return -1;
}
private static int findMatchingBlockCommentPair(@NotNull PsiElement element, int pos) {
final Language language = element.getLanguage();
final Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(language);
final PsiComment comment = PsiTreeUtil.getParentOfType(element, PsiComment.class, false);
if (comment != null) {
final int ret = findMatchingBlockCommentPair(comment, pos, commenter.getBlockCommentPrefix(),
commenter.getBlockCommentSuffix());
if (ret >= 0) {
return ret;
}
if (commenter instanceof CodeDocumentationAwareCommenter docCommenter) {
return findMatchingBlockCommentPair(comment, pos, docCommenter.getDocumentationCommentPrefix(),
docCommenter.getDocumentationCommentSuffix());
}
}
return -1;
}
/**
* This looks on the current line, starting at the cursor position for one of {, }, (, ), [, or ]. It then searches
* forward or backward, as appropriate for the associated match pair. String in double quotes are skipped over.
* Single characters in single quotes are skipped too.
*
* @param editor The editor to search in
* @return The offset within the editor of the found character or -1 if no match was found or none of the characters
* were found on the remainder of the current line.
*/
public static int findMatchingPairOnCurrentLine(@NotNull Editor editor, @NotNull Caret caret) {
int pos = caret.getOffset();
final int commentPos = findMatchingComment(editor, pos);
if (commentPos >= 0) {
return commentPos;
}
int line = caret.getLogicalPosition().line;
final IjVimEditor vimEditor = new IjVimEditor(editor);
int end = EngineEditorHelperKt.getLineEndOffset(vimEditor, line, true);
// To handle the case where visual mode allows the user to go past the end of the line,
// which will prevent loc from finding a pairable character below
if (pos > 0 && pos == end) {
pos = end - 1;
}
final String pairChars = parseMatchPairsOption(vimEditor);
CharSequence chars = editor.getDocument().getCharsSequence();
int loc = -1;
// Search the remainder of the current line for one of the candidate characters
while (pos < end) {
loc = pairChars.indexOf(chars.charAt(pos));
if (loc >= 0) {
break;
}
pos++;
}
int res = -1;
// If we found one ...
if (loc >= 0) {
// What direction should we go now (-1 is backward, 1 is forward)
Direction dir = loc % 2 == 0 ? Direction.FORWARDS : Direction.BACKWARDS;
// Which character did we find and which should we now search for
char found = pairChars.charAt(loc);
char match = pairChars.charAt(loc + dir.toInt());
res = findBlockLocation(chars, found, match, dir, pos, 1, true);
}
return res;
}
/**
* If on the start/end of a block comment, jump to the matching of that comment, or vice versa.
*/
private static int findMatchingComment(@NotNull Editor editor, int pos) {
final PsiFile psiFile = PsiHelper.getFile(editor);
if (psiFile != null) {
final PsiElement element = psiFile.findElementAt(pos);
if (element != null) {
return findMatchingBlockCommentPair(element, pos);
}
}
return -1;
}
private static int findBlockLocation(@NotNull CharSequence chars, private static int findBlockLocation(@NotNull CharSequence chars,
char found, char found,
char match, char match,
@@ -1504,17 +1611,11 @@ public class SearchHelper {
} }
else { else {
IntIterator offsetIterator = offsets.iterator(); IntIterator offsetIterator = offsets.iterator();
skip(offsetIterator, skipCount); offsetIterator.skip(skipCount);
return offsetIterator.nextInt(); return offsetIterator.nextInt();
} }
} }
private static void skip(IntIterator iterator, final int n) {
if (n < 0) throw new IllegalArgumentException("Argument must be nonnegative: " + n);
int i = n;
while (i-- != 0 && iterator.hasNext()) iterator.nextInt();
}
private static @NotNull String parseMatchPairsOption(final VimEditor vimEditor) { private static @NotNull String parseMatchPairsOption(final VimEditor vimEditor) {
List<String> pairs = options(injector, vimEditor).getMatchpairs(); List<String> pairs = options(injector, vimEditor).getMatchpairs();
StringBuilder res = new StringBuilder(); StringBuilder res = new StringBuilder();

View File

@@ -26,7 +26,6 @@ import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.api.options import com.maddyhome.idea.vim.api.options
import com.maddyhome.idea.vim.common.TextRange import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.ex.ranges.LineRange import com.maddyhome.idea.vim.ex.ranges.LineRange
import com.maddyhome.idea.vim.newapi.IjVimDocument
import com.maddyhome.idea.vim.newapi.IjVimEditor import com.maddyhome.idea.vim.newapi.IjVimEditor
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import org.jetbrains.annotations.Contract import org.jetbrains.annotations.Contract
@@ -87,24 +86,11 @@ private fun updateSearchHighlights(
): Int { ): Int {
var currentMatchOffset = -1 var currentMatchOffset = -1
val projectManager = ProjectManager.getInstanceIfCreated() ?: return currentMatchOffset val projectManager = ProjectManager.getInstanceIfCreated() ?: return currentMatchOffset
// TODO: This implementation needs rethinking
// It's a bit weird that we update search highlights across all open projects. It would make more sense to treat top
// level project frame windows as separate applications, but we can't do this because IdeaVim does not maintain state
// per-project.
// So, to be clear, this will loop over each project, and therefore, for each project top-level frame, will update
// search highlights in all editors for the document of the currently selected editor. It does not update highlights
// for editors for the document that are in other projects.
for (project in projectManager.openProjects) { for (project in projectManager.openProjects) {
val current = FileEditorManager.getInstance(project).selectedTextEditor ?: continue val current = FileEditorManager.getInstance(project).selectedTextEditor ?: continue
val editors = injector.editorGroup.getEditors(IjVimDocument(current.document)) // [VERSION UPDATE] 202+ Use editors
for (vimEditor in editors) { val editors = localEditors(current.document, project)
val editor = (vimEditor as IjVimEditor).editor for (editor in editors) {
if (editor.project != project) {
continue
}
// Try to keep existing highlights if possible. Update if hlsearch has changed or if the pattern has changed. // Try to keep existing highlights if possible. Update if hlsearch has changed or if the pattern has changed.
// Force update for the situations where the text is the same, but the ignore case values have changed. // Force update for the situations where the text is the same, but the ignore case values have changed.
// E.g. Use `*` to search for a word (which ignores smartcase), then use `/<Up>` to search for the same pattern, // E.g. Use `*` to search for a word (which ignores smartcase), then use `/<Up>` to search for the same pattern,

View File

@@ -10,14 +10,10 @@ package com.maddyhome.idea.vim.helper
import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.components.Service import com.intellij.openapi.components.Service
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider
import com.intellij.openapi.util.registry.Registry
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
@@ -25,8 +21,6 @@ import com.maddyhome.idea.vim.common.ChangesListener
import com.maddyhome.idea.vim.listener.SelectionVimListenerSuppressor import com.maddyhome.idea.vim.listener.SelectionVimListenerSuppressor
import com.maddyhome.idea.vim.newapi.globalIjOptions import com.maddyhome.idea.vim.newapi.globalIjOptions
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.state.mode.inVisualMode
import com.maddyhome.idea.vim.undo.UndoRedoBase import com.maddyhome.idea.vim.undo.UndoRedoBase
/** /**
@@ -43,11 +37,22 @@ internal class UndoRedoHelper : UndoRedoBase() {
val scrollingModel = editor.getScrollingModel() val scrollingModel = editor.getScrollingModel()
scrollingModel.accumulateViewportChanges() scrollingModel.accumulateViewportChanges()
// [VERSION UPDATE] 241+ remove this if if (injector.globalIjOptions().oldundo) {
if (ApplicationInfo.getInstance().build.baselineVersion >= 241) { SelectionVimListenerSuppressor.lock().use { undoManager.undo(fileEditor) }
undoFor241plus(editor, undoManager, fileEditor)
} else { } else {
undoForLessThan241(undoManager, fileEditor, editor) // TODO refactor me after VIM-308 when restoring selection and caret movement will be ignored by undo
editor.runWithChangeTracking {
undoManager.undo(fileEditor)
// We execute undo one more time if the previous one just restored selection
if (!hasChanges && hasSelection(editor) && undoManager.isUndoAvailable(fileEditor)) {
undoManager.undo(fileEditor)
}
}
CommandProcessor.getInstance().runUndoTransparentAction {
removeSelections(editor)
}
} }
scrollingModel.flushViewportChanges() scrollingModel.flushViewportChanges()
@@ -57,134 +62,42 @@ internal class UndoRedoHelper : UndoRedoBase() {
return false return false
} }
private fun undoForLessThan241(
undoManager: UndoManager,
fileEditor: TextEditor,
editor: VimEditor,
) {
if (injector.globalIjOptions().oldundo) {
SelectionVimListenerSuppressor.lock().use { undoManager.undo(fileEditor) }
restoreVisualMode(editor)
} else {
// TODO refactor me after VIM-308 when restoring selection and caret movement will be ignored by undo
editor.runWithChangeTracking {
undoManager.undo(fileEditor)
restoreVisualMode(editor)
}
CommandProcessor.getInstance().runUndoTransparentAction {
removeSelections(editor)
}
}
}
private fun undoFor241plus(
editor: VimEditor,
undoManager: UndoManager,
fileEditor: TextEditor,
) {
if (injector.globalIjOptions().oldundo) {
// TODO refactor me after VIM-308 when restoring selection and caret movement will be ignored by undo
editor.runWithChangeTracking {
undoManager.undo(fileEditor)
restoreVisualMode(editor)
}
} else {
runWithBooleanRegistryOption("ide.undo.transparent.caret.movement", true) {
undoManager.undo(fileEditor)
}
CommandProcessor.getInstance().runUndoTransparentAction {
removeSelections(editor)
}
}
}
private fun hasSelection(editor: VimEditor): Boolean { private fun hasSelection(editor: VimEditor): Boolean {
return editor.primaryCaret().ij.hasSelection() return editor.primaryCaret().ij.hasSelection()
} }
override fun redo(editor: VimEditor, context: ExecutionContext): Boolean { override fun redo(editor: VimEditor, context: ExecutionContext): Boolean {
val ijContext = context.context as DataContext val ijContext = context.context as DataContext
val project = PlatformDataKeys.PROJECT.getData(ijContext) ?: return false val project = PlatformDataKeys.PROJECT.getData(ijContext) ?: return false
val fileEditor = TextEditorProvider.getInstance().getTextEditor(editor.ij) val fileEditor = TextEditorProvider.getInstance().getTextEditor(editor.ij)
val undoManager = UndoManager.getInstance(project) val undoManager = UndoManager.getInstance(project)
if (undoManager.isRedoAvailable(fileEditor)) { if (undoManager.isRedoAvailable(fileEditor)) {
// [VERSION UPDATE] 241+ remove this if if (injector.globalIjOptions().oldundo) {
if (ApplicationInfo.getInstance().build.baselineVersion >= 241) { SelectionVimListenerSuppressor.lock().use { undoManager.redo(fileEditor) }
redoFor241Plus(undoManager, fileEditor, editor)
} else { } else {
redoForLessThan241(undoManager, fileEditor, editor) undoManager.redo(fileEditor)
} CommandProcessor.getInstance().runUndoTransparentAction {
editor.carets().forEach { it.ij.removeSelection() }
}
// TODO refactor me after VIM-308 when restoring selection and caret movement will be ignored by undo
editor.runWithChangeTracking {
undoManager.redo(fileEditor)
// We execute undo one more time if the previous one just restored selection
if (!hasChanges && hasSelection(editor) && undoManager.isRedoAvailable(fileEditor)) {
undoManager.redo(fileEditor)
}
}
CommandProcessor.getInstance().runUndoTransparentAction {
removeSelections(editor)
}
}
return true return true
} }
return false return false
} }
private fun redoForLessThan241(
undoManager: UndoManager,
fileEditor: TextEditor,
editor: VimEditor,
) {
if (injector.globalIjOptions().oldundo) {
SelectionVimListenerSuppressor.lock().use { undoManager.redo(fileEditor) }
} else {
undoManager.redo(fileEditor)
CommandProcessor.getInstance().runUndoTransparentAction {
editor.carets().forEach { it.ij.removeSelection() }
}
// TODO refactor me after VIM-308 when restoring selection and caret movement will be ignored by undo
editor.runWithChangeTracking {
undoManager.redo(fileEditor)
// We execute undo one more time if the previous one just restored selection
if (!hasChanges && hasSelection(editor) && undoManager.isRedoAvailable(fileEditor)) {
undoManager.redo(fileEditor)
}
}
CommandProcessor.getInstance().runUndoTransparentAction {
removeSelections(editor)
}
}
}
private fun redoFor241Plus(
undoManager: UndoManager,
fileEditor: TextEditor,
editor: VimEditor,
) {
if (injector.globalIjOptions().oldundo) {
undoManager.redo(fileEditor)
CommandProcessor.getInstance().runUndoTransparentAction {
editor.carets().forEach { it.ij.removeSelection() }
}
// TODO refactor me after VIM-308 when restoring selection and caret movement will be ignored by undo
editor.runWithChangeTracking {
undoManager.redo(fileEditor)
// We execute undo one more time if the previous one just restored selection
if (!hasChanges && hasSelection(editor) && undoManager.isRedoAvailable(fileEditor)) {
undoManager.redo(fileEditor)
}
}
CommandProcessor.getInstance().runUndoTransparentAction {
removeSelections(editor)
}
} else {
runWithBooleanRegistryOption("ide.undo.transparent.caret.movement", true) {
undoManager.redo(fileEditor)
}
CommandProcessor.getInstance().runUndoTransparentAction {
removeSelections(editor)
}
}
}
private fun removeSelections(editor: VimEditor) { private fun removeSelections(editor: VimEditor) {
editor.carets().forEach { editor.carets().forEach {
val ijCaret = it.ij val ijCaret = it.ij
@@ -196,17 +109,6 @@ internal class UndoRedoHelper : UndoRedoBase() {
} }
} }
private fun runWithBooleanRegistryOption(option: String, value: Boolean, block: () -> Unit) {
val registry = Registry.get(option)
val oldValue = registry.asBoolean()
registry.setValue(value)
try {
block()
} finally {
registry.setValue(oldValue)
}
}
private fun VimEditor.runWithChangeTracking(block: ChangeTracker.() -> Unit) { private fun VimEditor.runWithChangeTracking(block: ChangeTracker.() -> Unit) {
val tracker = ChangeTracker(this) val tracker = ChangeTracker(this)
tracker.block() tracker.block()
@@ -229,21 +131,4 @@ internal class UndoRedoHelper : UndoRedoBase() {
val hasChanges: Boolean val hasChanges: Boolean
get() = changeListener.hasChanged || initialPath != editor.getPath() get() = changeListener.hasChanged || initialPath != editor.getPath()
} }
private fun restoreVisualMode(editor: VimEditor) {
if (!editor.inVisualMode && editor.getSelectionModel().hasSelection()) {
val detectedMode = VimPlugin.getVisualMotion().autodetectVisualSubmode(editor)
// Visual block selection is restored into multiple carets, so multi-carets that form a block are always
// identified as visual block mode, leading to false positives.
// Since I use visual block mode much less often than multi-carets, this is a judgment call to never restore
// visual block mode.
val wantedMode = if (detectedMode == SelectionType.BLOCK_WISE)
SelectionType.CHARACTER_WISE
else
detectedMode
VimPlugin.getVisualMotion().enterVisualMode(editor, wantedMode)
}
}
} }

View File

@@ -21,13 +21,13 @@ import com.intellij.openapi.util.UserDataHolder
import com.maddyhome.idea.vim.api.CaretRegisterStorageBase import com.maddyhome.idea.vim.api.CaretRegisterStorageBase
import com.maddyhome.idea.vim.api.LocalMarkStorage import com.maddyhome.idea.vim.api.LocalMarkStorage
import com.maddyhome.idea.vim.api.SelectionInfo import com.maddyhome.idea.vim.api.SelectionInfo
import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.state.VimStateMachine
import com.maddyhome.idea.vim.ex.ExOutputModel import com.maddyhome.idea.vim.ex.ExOutputModel
import com.maddyhome.idea.vim.group.visual.VisualChange import com.maddyhome.idea.vim.group.visual.VisualChange
import com.maddyhome.idea.vim.group.visual.vimLeadSelectionOffset import com.maddyhome.idea.vim.group.visual.vimLeadSelectionOffset
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.state.VimStateMachine
import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.ui.ExOutputPanel import com.maddyhome.idea.vim.ui.ExOutputPanel
import kotlin.properties.ReadWriteProperty import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty import kotlin.reflect.KProperty
@@ -99,8 +99,6 @@ internal var Caret.registerStorage: CaretRegisterStorageBase? by userDataCaretTo
internal var Caret.markStorage: LocalMarkStorage? by userDataCaretToEditor() internal var Caret.markStorage: LocalMarkStorage? by userDataCaretToEditor()
internal var Caret.lastSelectionInfo: SelectionInfo? by userDataCaretToEditor() internal var Caret.lastSelectionInfo: SelectionInfo? by userDataCaretToEditor()
internal var Editor.vimInitialised: Boolean by userDataOr { false }
// ------------------ Editor // ------------------ Editor
internal fun unInitializeEditor(editor: Editor) { internal fun unInitializeEditor(editor: Editor) {
editor.vimLastSelectionType = null editor.vimLastSelectionType = null
@@ -108,7 +106,6 @@ internal fun unInitializeEditor(editor: Editor) {
editor.vimMorePanel = null editor.vimMorePanel = null
editor.vimExOutput = null editor.vimExOutput = null
editor.vimLastHighlighters = null editor.vimLastHighlighters = null
editor.vimInitialised = false
} }
internal var Editor.vimLastSearch: String? by userData() internal var Editor.vimLastSearch: String? by userData()

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2003-2023 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.helper
import com.intellij.ide.plugins.StandalonePluginUpdateChecker
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.group.NotificationService
import com.maddyhome.idea.vim.icons.VimIcons
@Service(Service.Level.APP)
internal class VimStandalonePluginUpdateChecker : StandalonePluginUpdateChecker(
VimPlugin.getPluginId(),
updateTimestampProperty = PROPERTY_NAME,
NotificationService.IDEAVIM_STICKY_GROUP,
VimIcons.IDEAVIM,
) {
override fun skipUpdateCheck(): Boolean = VimPlugin.isNotEnabled() || "dev" in VimPlugin.getVersion()
companion object {
private const val PROPERTY_NAME = "ideavim.statistics.timestamp"
val instance: VimStandalonePluginUpdateChecker = service()
}
}

View File

@@ -19,7 +19,6 @@ import com.intellij.codeInsight.template.TemplateManagerListener
import com.intellij.codeInsight.template.impl.TemplateState import com.intellij.codeInsight.template.impl.TemplateState
import com.intellij.find.FindModelListener import com.intellij.find.FindModelListener
import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.AnActionResult import com.intellij.openapi.actionSystem.AnActionResult
@@ -28,7 +27,6 @@ import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.ex.AnActionListener import com.intellij.openapi.actionSystem.ex.AnActionListener
import com.intellij.openapi.actionSystem.impl.ProxyShortcutSet import com.intellij.openapi.actionSystem.impl.ProxyShortcutSet
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.impl.ScrollingModelImpl
import com.intellij.openapi.project.DumbAwareToggleAction import com.intellij.openapi.project.DumbAwareToggleAction
import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.TextRange
import com.maddyhome.idea.vim.KeyHandler import com.maddyhome.idea.vim.KeyHandler
@@ -58,7 +56,6 @@ internal object IdeaSpecifics {
private val surrounderAction = private val surrounderAction =
"com.intellij.codeInsight.generation.surroundWith.SurroundWithHandler\$InvokeSurrounderAction" "com.intellij.codeInsight.generation.surroundWith.SurroundWithHandler\$InvokeSurrounderAction"
private var editor: Editor? = null private var editor: Editor? = null
private var caretOffset = -1
private var completionPrevDocumentLength: Int? = null private var completionPrevDocumentLength: Int? = null
private var completionPrevDocumentOffset: Int? = null private var completionPrevDocumentOffset: Int? = null
override fun beforeActionPerformed(action: AnAction, event: AnActionEvent) { override fun beforeActionPerformed(action: AnAction, event: AnActionEvent) {
@@ -67,7 +64,6 @@ internal object IdeaSpecifics {
val hostEditor = event.dataContext.getData(CommonDataKeys.HOST_EDITOR) val hostEditor = event.dataContext.getData(CommonDataKeys.HOST_EDITOR)
if (hostEditor != null) { if (hostEditor != null) {
editor = hostEditor editor = hostEditor
caretOffset = hostEditor.caretModel.offset
} }
val isVimAction = (action as? AnActionWrapper)?.delegate is VimShortcutKeyAction val isVimAction = (action as? AnActionWrapper)?.delegate is VimShortcutKeyAction
@@ -78,7 +74,7 @@ internal object IdeaSpecifics {
} }
} }
if (hostEditor != null && action is ChooseItemAction && injector.registerGroup.isRecording) { if (hostEditor != null && action is ChooseItemAction && hostEditor.vimStateMachine?.isRecording == true) {
val lookup = LookupManager.getActiveLookup(hostEditor) val lookup = LookupManager.getActiveLookup(hostEditor)
if (lookup != null) { if (lookup != null) {
val charsToRemove = hostEditor.caretModel.primaryCaret.offset - lookup.lookupStart val charsToRemove = hostEditor.caretModel.primaryCaret.offset - lookup.lookupStart
@@ -99,58 +95,43 @@ internal object IdeaSpecifics {
if (VimPlugin.isNotEnabled()) return if (VimPlugin.isNotEnabled()) return
val editor = editor val editor = editor
if (editor != null) { if (editor != null && action is ChooseItemAction && editor.vimStateMachine?.isRecording == true) {
if (action is ChooseItemAction && injector.registerGroup.isRecording) { val prevDocumentLength = completionPrevDocumentLength
val prevDocumentLength = completionPrevDocumentLength val prevDocumentOffset = completionPrevDocumentOffset
val prevDocumentOffset = completionPrevDocumentOffset
if (prevDocumentLength != null && prevDocumentOffset != null) { if (prevDocumentLength != null && prevDocumentOffset != null) {
val register = VimPlugin.getRegister() val register = VimPlugin.getRegister()
val addedTextLength = editor.document.textLength - prevDocumentLength val addedTextLength = editor.document.textLength - prevDocumentLength
val caretShift = addedTextLength - (editor.caretModel.primaryCaret.offset - prevDocumentOffset) val caretShift = addedTextLength - (editor.caretModel.primaryCaret.offset - prevDocumentOffset)
val leftArrow = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0) val leftArrow = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0)
register.recordText(editor.document.getText(TextRange(prevDocumentOffset, prevDocumentOffset + addedTextLength))) register.recordText(editor.document.getText(TextRange(prevDocumentOffset, prevDocumentOffset + addedTextLength)))
repeat(caretShift.coerceAtLeast(0)) { repeat(caretShift.coerceAtLeast(0)) {
register.recordKeyStroke(leftArrow) register.recordKeyStroke(leftArrow)
}
}
this.completionPrevDocumentLength = null
this.completionPrevDocumentOffset = null
}
//region Enter insert mode after surround with if
if (surrounderAction == action.javaClass.name && surrounderItems.any {
action.templatePresentation.text.endsWith(
it,
)
}
) {
editor?.let {
val commandState = it.vim.vimStateMachine
it.vim.mode = Mode.NORMAL()
VimPlugin.getChange().insertBeforeCursor(it.vim, event.dataContext.vim)
KeyHandler.getInstance().reset(it.vim)
} }
} }
//endregion
if (caretOffset != -1 && caretOffset != editor.caretModel.offset) { this.completionPrevDocumentLength = null
val scrollModel = editor.scrollingModel as ScrollingModelImpl this.completionPrevDocumentOffset = null
if (scrollModel.isScrollingNow) {
val v = scrollModel.verticalScrollOffset
val h = scrollModel.horizontalScrollOffset
scrollModel.finishAnimation()
scrollModel.scroll(h, v)
scrollModel.finishAnimation()
}
injector.scroll.scrollCaretIntoView(editor.vim)
}
} }
//region Enter insert mode after surround with if
if (surrounderAction == action.javaClass.name && surrounderItems.any {
action.templatePresentation.text.endsWith(
it,
)
}
) {
editor?.let {
val commandState = it.vim.vimStateMachine
commandState.mode = Mode.NORMAL()
VimPlugin.getChange().insertBeforeCursor(it.vim, event.dataContext.vim)
KeyHandler.getInstance().reset(it.vim)
}
}
//endregion
this.editor = null this.editor = null
this.caretOffset = -1
} }
} }
@@ -182,7 +163,7 @@ internal object IdeaSpecifics {
if (editor.vim.inNormalMode) { if (editor.vim.inNormalMode) {
VimPlugin.getChange().insertBeforeCursor( VimPlugin.getChange().insertBeforeCursor(
editor.vim, editor.vim,
injector.executionContextManager.getEditorExecutionContext(editor.vim), injector.executionContextManager.onEditor(editor.vim),
) )
KeyHandler.getInstance().reset(editor.vim) KeyHandler.getInstance().reset(editor.vim)
} }
@@ -232,7 +213,5 @@ internal class FindActionIdAction : DumbAwareToggleAction() {
override fun setSelected(e: AnActionEvent, state: Boolean) { override fun setSelected(e: AnActionEvent, state: Boolean) {
injector.globalIjOptions().trackactionids = !injector.globalIjOptions().trackactionids injector.globalIjOptions().trackactionids = !injector.globalIjOptions().trackactionids
} }
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
} }
//endregion //endregion

View File

@@ -8,7 +8,6 @@
package com.maddyhome.idea.vim.listener package com.maddyhome.idea.vim.listener
import com.intellij.codeWithMe.ClientId
import com.intellij.ide.ui.UISettings import com.intellij.ide.ui.UISettings
import com.intellij.openapi.Disposable import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationManager
@@ -21,8 +20,6 @@ import com.intellij.openapi.editor.EditorKind
import com.intellij.openapi.editor.actionSystem.TypedAction import com.intellij.openapi.editor.actionSystem.TypedAction
import com.intellij.openapi.editor.event.CaretEvent import com.intellij.openapi.editor.event.CaretEvent
import com.intellij.openapi.editor.event.CaretListener import com.intellij.openapi.editor.event.CaretListener
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.event.EditorFactoryEvent import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.editor.event.EditorMouseEvent import com.intellij.openapi.editor.event.EditorMouseEvent
@@ -35,7 +32,6 @@ import com.intellij.openapi.editor.ex.DocumentEx
import com.intellij.openapi.editor.ex.EditorEventMulticasterEx import com.intellij.openapi.editor.ex.EditorEventMulticasterEx
import com.intellij.openapi.editor.ex.FocusChangeListener import com.intellij.openapi.editor.ex.FocusChangeListener
import com.intellij.openapi.editor.impl.EditorComponentImpl import com.intellij.openapi.editor.impl.EditorComponentImpl
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.FileEditorManagerEvent import com.intellij.openapi.fileEditor.FileEditorManagerEvent
import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.intellij.openapi.fileEditor.FileEditorManagerListener
@@ -46,17 +42,13 @@ import com.intellij.openapi.fileEditor.ex.FileEditorWithProvider
import com.intellij.openapi.fileEditor.impl.EditorComposite import com.intellij.openapi.fileEditor.impl.EditorComposite
import com.intellij.openapi.fileEditor.impl.EditorWindow import com.intellij.openapi.fileEditor.impl.EditorWindow
import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.rd.createLifetime
import com.intellij.openapi.rd.createNestedDisposable
import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key import com.intellij.openapi.util.Key
import com.intellij.openapi.util.removeUserData import com.intellij.openapi.util.removeUserData
import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.ExceptionUtil import com.intellij.util.ExceptionUtil
import com.jetbrains.rd.util.lifetime.Lifetime
import com.maddyhome.idea.vim.EventFacade import com.maddyhome.idea.vim.EventFacade
import com.maddyhome.idea.vim.KeyHandler import com.maddyhome.idea.vim.KeyHandler
import com.maddyhome.idea.vim.KeyHandlerStateResetter
import com.maddyhome.idea.vim.VimKeyListener import com.maddyhome.idea.vim.VimKeyListener
import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.VimTypedActionHandler import com.maddyhome.idea.vim.VimTypedActionHandler
@@ -70,41 +62,42 @@ import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.ex.ExOutputModel import com.maddyhome.idea.vim.ex.ExOutputModel
import com.maddyhome.idea.vim.group.EditorGroup import com.maddyhome.idea.vim.group.EditorGroup
import com.maddyhome.idea.vim.group.FileGroup import com.maddyhome.idea.vim.group.FileGroup
import com.maddyhome.idea.vim.group.IjOptions
import com.maddyhome.idea.vim.group.MotionGroup import com.maddyhome.idea.vim.group.MotionGroup
import com.maddyhome.idea.vim.group.OptionGroup import com.maddyhome.idea.vim.group.OptionGroup
import com.maddyhome.idea.vim.group.ScrollGroup import com.maddyhome.idea.vim.group.ScrollGroup
import com.maddyhome.idea.vim.group.SearchGroup
import com.maddyhome.idea.vim.group.VimMarkServiceImpl
import com.maddyhome.idea.vim.group.visual.IdeaSelectionControl import com.maddyhome.idea.vim.group.visual.IdeaSelectionControl
import com.maddyhome.idea.vim.group.visual.VimVisualTimer import com.maddyhome.idea.vim.group.visual.VimVisualTimer
import com.maddyhome.idea.vim.group.visual.moveCaretOneCharLeftFromSelectionEnd import com.maddyhome.idea.vim.group.visual.moveCaretOneCharLeftFromSelectionEnd
import com.maddyhome.idea.vim.handler.correctorRequester import com.maddyhome.idea.vim.handler.correctorRequester
import com.maddyhome.idea.vim.handler.keyCheckRequests import com.maddyhome.idea.vim.handler.keyCheckRequests
import com.maddyhome.idea.vim.helper.CaretVisualAttributesListener
import com.maddyhome.idea.vim.helper.GuicursorChangeListener import com.maddyhome.idea.vim.helper.GuicursorChangeListener
import com.maddyhome.idea.vim.helper.StrictMode import com.maddyhome.idea.vim.helper.StrictMode
import com.maddyhome.idea.vim.helper.VimStandalonePluginUpdateChecker
import com.maddyhome.idea.vim.helper.exitSelectMode import com.maddyhome.idea.vim.helper.exitSelectMode
import com.maddyhome.idea.vim.helper.exitVisualMode import com.maddyhome.idea.vim.helper.exitVisualMode
import com.maddyhome.idea.vim.helper.forceBarCursor import com.maddyhome.idea.vim.helper.forceBarCursor
import com.maddyhome.idea.vim.helper.inVisualMode import com.maddyhome.idea.vim.helper.inVisualMode
import com.maddyhome.idea.vim.helper.isEndAllowed import com.maddyhome.idea.vim.helper.isEndAllowed
import com.maddyhome.idea.vim.helper.isIdeaVimDisabledHere
import com.maddyhome.idea.vim.helper.localEditors
import com.maddyhome.idea.vim.helper.moveToInlayAwareOffset import com.maddyhome.idea.vim.helper.moveToInlayAwareOffset
import com.maddyhome.idea.vim.helper.resetVimLastColumn import com.maddyhome.idea.vim.helper.resetVimLastColumn
import com.maddyhome.idea.vim.helper.updateCaretsVisualAttributes import com.maddyhome.idea.vim.helper.updateCaretsVisualAttributes
import com.maddyhome.idea.vim.helper.vimDisabled import com.maddyhome.idea.vim.helper.vimDisabled
import com.maddyhome.idea.vim.listener.MouseEventsDataHolder.skipEvents
import com.maddyhome.idea.vim.listener.MouseEventsDataHolder.skipNDragEvents
import com.maddyhome.idea.vim.listener.VimListenerManager.EditorListeners.add
import com.maddyhome.idea.vim.newapi.IjVimEditor import com.maddyhome.idea.vim.newapi.IjVimEditor
import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.inSelectMode import com.maddyhome.idea.vim.state.mode.inSelectMode
import com.maddyhome.idea.vim.state.mode.mode
import com.maddyhome.idea.vim.state.mode.selectionType import com.maddyhome.idea.vim.state.mode.selectionType
import com.maddyhome.idea.vim.ui.ShowCmdOptionChangeListener import com.maddyhome.idea.vim.ui.ShowCmdOptionChangeListener
import com.maddyhome.idea.vim.ui.ShowCmdWidgetUpdater
import com.maddyhome.idea.vim.ui.ex.ExEntryPanel import com.maddyhome.idea.vim.ui.ex.ExEntryPanel
import com.maddyhome.idea.vim.ui.widgets.macro.MacroWidgetListener
import com.maddyhome.idea.vim.ui.widgets.macro.macroWidgetOptionListener import com.maddyhome.idea.vim.ui.widgets.macro.macroWidgetOptionListener
import com.maddyhome.idea.vim.ui.widgets.mode.listeners.ModeWidgetListener
import com.maddyhome.idea.vim.ui.widgets.mode.modeWidgetOptionListener import com.maddyhome.idea.vim.ui.widgets.mode.modeWidgetOptionListener
import com.maddyhome.idea.vim.vimDisposable
import java.awt.event.MouseAdapter import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent import java.awt.event.MouseEvent
import javax.swing.SwingUtilities import javax.swing.SwingUtilities
@@ -134,7 +127,6 @@ private fun getOpeningEditor(newEditor: Editor) = newEditor.project?.let { proje
internal object VimListenerManager { internal object VimListenerManager {
private val logger = Logger.getInstance(VimListenerManager::class.java) private val logger = Logger.getInstance(VimListenerManager::class.java)
private val editorListenersDisposableKey = Key.create<Disposable>("IdeaVim listeners disposable")
private var firstEditorInitialised = false private var firstEditorInitialised = false
fun turnOn() { fun turnOn() {
@@ -142,30 +134,11 @@ internal object VimListenerManager {
EditorListeners.addAll() EditorListeners.addAll()
check(correctorRequester.tryEmit(Unit)) check(correctorRequester.tryEmit(Unit))
check(keyCheckRequests.tryEmit(Unit)) check(keyCheckRequests.tryEmit(Unit))
val caretVisualAttributesListener = CaretVisualAttributesListener()
injector.listenersNotifier.modeChangeListeners.add(caretVisualAttributesListener)
injector.listenersNotifier.isReplaceCharListeners.add(caretVisualAttributesListener)
caretVisualAttributesListener.updateAllEditorsCaretsVisual()
val modeWidgetListener = ModeWidgetListener()
injector.listenersNotifier.modeChangeListeners.add(modeWidgetListener)
injector.listenersNotifier.myEditorListeners.add(modeWidgetListener)
injector.listenersNotifier.vimPluginListeners.add(modeWidgetListener)
val macroWidgetListener = MacroWidgetListener()
injector.listenersNotifier.macroRecordingListeners.add(macroWidgetListener)
injector.listenersNotifier.vimPluginListeners.add(macroWidgetListener)
injector.listenersNotifier.myEditorListeners.add(KeyHandlerStateResetter())
injector.listenersNotifier.myEditorListeners.add(ShowCmdWidgetUpdater())
} }
fun turnOff() { fun turnOff() {
GlobalListeners.disable() GlobalListeners.disable()
EditorListeners.removeAll() EditorListeners.removeAll()
injector.listenersNotifier.reset()
check(correctorRequester.tryEmit(Unit)) check(correctorRequester.tryEmit(Unit))
} }
@@ -183,29 +156,23 @@ internal object VimListenerManager {
optionGroup.addEffectiveOptionValueChangeListener(Options.number, EditorGroup.NumberChangeListener.INSTANCE) optionGroup.addEffectiveOptionValueChangeListener(Options.number, EditorGroup.NumberChangeListener.INSTANCE)
optionGroup.addEffectiveOptionValueChangeListener(Options.relativenumber, EditorGroup.NumberChangeListener.INSTANCE) optionGroup.addEffectiveOptionValueChangeListener(Options.relativenumber, EditorGroup.NumberChangeListener.INSTANCE)
optionGroup.addEffectiveOptionValueChangeListener(Options.scrolloff, ScrollGroup.ScrollOptionsChangeListener) optionGroup.addEffectiveOptionValueChangeListener(Options.scrolloff, ScrollGroup.ScrollOptionsChangeListener)
optionGroup.addEffectiveOptionValueChangeListener(Options.guicursor, GuicursorChangeListener)
optionGroup.addGlobalOptionChangeListener(Options.showcmd, ShowCmdOptionChangeListener) optionGroup.addGlobalOptionChangeListener(Options.showcmd, ShowCmdOptionChangeListener)
// This code is executed after ideavimrc execution, so we trigger onGlobalOptionChanged just in case // This code is executed after ideavimrc execution, so we trigger onGlobalOptionChanged just in case
optionGroup.addGlobalOptionChangeListener(Options.showmode, modeWidgetOptionListener) optionGroup.addGlobalOptionChangeListener(IjOptions.showmodewidget, modeWidgetOptionListener)
optionGroup.addGlobalOptionChangeListener(Options.showmode, macroWidgetOptionListener) optionGroup.addGlobalOptionChangeListener(IjOptions.showmodewidget, macroWidgetOptionListener)
modeWidgetOptionListener.onGlobalOptionChanged() modeWidgetOptionListener.onGlobalOptionChanged()
macroWidgetOptionListener.onGlobalOptionChanged() macroWidgetOptionListener.onGlobalOptionChanged()
// Listen for and initialise new editors optionGroup.addEffectiveOptionValueChangeListener(Options.guicursor, GuicursorChangeListener)
EventFacade.getInstance().addEditorFactoryListener(VimEditorFactoryListener, VimPlugin.getInstance().onOffDisposable) EventFacade.getInstance().addEditorFactoryListener(VimEditorFactoryListener, VimPlugin.getInstance().onOffDisposable)
val busConnection = ApplicationManager.getApplication().messageBus.connect(VimPlugin.getInstance().onOffDisposable) val busConnection = ApplicationManager.getApplication().messageBus.connect(VimPlugin.getInstance().onOffDisposable)
busConnection.subscribe(FileOpenedSyncListener.TOPIC, VimEditorFactoryListener) busConnection.subscribe(FileOpenedSyncListener.TOPIC, VimEditorFactoryListener)
// Listen for focus change to update various features such as mode widget EditorFactory.getInstance().eventMulticaster.addCaretListener(VimCaretListener, VimPlugin.getInstance().onOffDisposable)
val eventMulticaster = EditorFactory.getInstance().eventMulticaster val eventMulticaster = EditorFactory.getInstance().eventMulticaster as? EditorEventMulticasterEx
(eventMulticaster as? EditorEventMulticasterEx)?.addFocusChangeListener( eventMulticaster?.addFocusChangeListener(VimFocusListener, VimPlugin.getInstance().onOffDisposable)
VimFocusListener,
VimPlugin.getInstance().onOffDisposable
)
// Listen for document changes to update document state such as marks
eventMulticaster.addDocumentListener(VimDocumentListener, VimPlugin.getInstance().onOffDisposable)
} }
fun disable() { fun disable() {
@@ -216,8 +183,8 @@ internal object VimListenerManager {
optionGroup.removeEffectiveOptionValueChangeListener(Options.relativenumber, EditorGroup.NumberChangeListener.INSTANCE) optionGroup.removeEffectiveOptionValueChangeListener(Options.relativenumber, EditorGroup.NumberChangeListener.INSTANCE)
optionGroup.removeEffectiveOptionValueChangeListener(Options.scrolloff, ScrollGroup.ScrollOptionsChangeListener) optionGroup.removeEffectiveOptionValueChangeListener(Options.scrolloff, ScrollGroup.ScrollOptionsChangeListener)
optionGroup.removeGlobalOptionChangeListener(Options.showcmd, ShowCmdOptionChangeListener) optionGroup.removeGlobalOptionChangeListener(Options.showcmd, ShowCmdOptionChangeListener)
optionGroup.removeGlobalOptionChangeListener(Options.showmode, modeWidgetOptionListener) optionGroup.removeGlobalOptionChangeListener(IjOptions.showmodewidget, modeWidgetOptionListener)
optionGroup.removeGlobalOptionChangeListener(Options.showmode, macroWidgetOptionListener) optionGroup.removeGlobalOptionChangeListener(IjOptions.showmodewidget, macroWidgetOptionListener)
optionGroup.removeEffectiveOptionValueChangeListener(Options.guicursor, GuicursorChangeListener) optionGroup.removeEffectiveOptionValueChangeListener(Options.guicursor, GuicursorChangeListener)
} }
} }
@@ -246,9 +213,7 @@ internal object VimListenerManager {
// We could have a split window in this list, but since they're all being initialised from the same opening editor // We could have a split window in this list, but since they're all being initialised from the same opening editor
// there's no need to use the SPLIT scenario // there's no need to use the SPLIT scenario
// Make sure we get all editors, including uninitialised localEditors().forEach { editor ->
injector.editorGroup.getEditorsRaw().forEach { vimEditor ->
val editor = vimEditor.ij
if (!initialisedEditors.contains(editor)) { if (!initialisedEditors.contains(editor)) {
add(editor, getOpeningEditor(editor)?.vim ?: injector.fallbackWindow, LocalOptionInitialisationScenario.NEW) add(editor, getOpeningEditor(editor)?.vim ?: injector.fallbackWindow, LocalOptionInitialisationScenario.NEW)
} }
@@ -256,24 +221,18 @@ internal object VimListenerManager {
} }
fun removeAll() { fun removeAll() {
injector.editorGroup.getEditors().forEach { editor -> localEditors().forEach { editor ->
remove(editor.ij) remove(editor, false)
} }
} }
fun add(editor: Editor, openingEditor: VimEditor, scenario: LocalOptionInitialisationScenario) { fun add(editor: Editor, openingEditor: VimEditor, scenario: LocalOptionInitialisationScenario) {
// We shouldn't be called with anything other than local editors, but let's just be sure. This will prevent any // As I understand, there is no need to pass a disposable that also disposes on editor close
// unsupported editor from incorrectly being initialised. // because all editor resources will be garbage collected anyway on editor close
// TODO: If the user changes the 'ideavimsupport' option, existing editors won't be initialised val disposable = editor.project?.vimDisposable ?: return
if (vimDisabled(editor)) return
val pluginLifetime = VimPlugin.getInstance().createLifetime()
val editorLifetime = (editor as EditorImpl).disposable.createLifetime()
val disposable =
Lifetime.intersect(pluginLifetime, editorLifetime).createNestedDisposable("MyLifetimedDisposable")
val listenersDisposable = Disposer.newDisposable(disposable) val listenersDisposable = Disposer.newDisposable(disposable)
editor.putUserData(editorListenersDisposableKey, listenersDisposable) editor.putUserData(editorListenersDisposable, listenersDisposable)
Disposer.register(listenersDisposable) { Disposer.register(listenersDisposable) {
if (VimListenerTestObject.enabled) { if (VimListenerTestObject.enabled) {
@@ -296,79 +255,54 @@ internal object VimListenerManager {
eventFacade.addCaretListener(editor, EditorCaretHandler, listenersDisposable) eventFacade.addCaretListener(editor, EditorCaretHandler, listenersDisposable)
VimPlugin.getEditor().editorCreated(editor) VimPlugin.getEditor().editorCreated(editor)
VimPlugin.getChange().editorCreated(editor, listenersDisposable) VimPlugin.getChange().editorCreated(editor, listenersDisposable)
injector.listenersNotifier.notifyEditorCreated(vimEditor) injector.listenersNotifier.notifyEditorCreated(vimEditor)
Disposer.register(listenersDisposable) { Disposer.register(listenersDisposable) {
VimPlugin.getEditor().editorDeinit(editor, true) VimPlugin.getEditorIfCreated()?.editorDeinit(editor, true)
} }
} }
fun remove(editor: Editor) { fun remove(editor: Editor, isReleased: Boolean) {
val editorDisposable = editor.removeUserData(editorListenersDisposableKey) val editorDisposable = editor.getUserData(editorListenersDisposable)
if (editorDisposable != null) { if (editorDisposable != null) {
Disposer.dispose(editorDisposable) Disposer.dispose(editorDisposable)
} }
else { else StrictMode.fail("Editor doesn't have disposable attached. $editor")
// We definitely do not expect this to happen
StrictMode.fail("Editor doesn't have disposable attached. $editor") VimPlugin.getEditorIfCreated()?.editorDeinit(editor, isReleased)
}
} }
} }
/**
* Notifies other IdeaVim components of focus gain/loss, e.g. the mode widget. This will be called with non-local Code
* With Me editors.
*/
private object VimFocusListener : FocusChangeListener { private object VimFocusListener : FocusChangeListener {
override fun focusGained(editor: Editor) { override fun focusGained(editor: Editor) {
if (vimDisabled(editor)) return
injector.listenersNotifier.notifyEditorFocusGained(editor.vim) injector.listenersNotifier.notifyEditorFocusGained(editor.vim)
} }
override fun focusLost(editor: Editor) { override fun focusLost(editor: Editor) {
if (vimDisabled(editor)) return
injector.listenersNotifier.notifyEditorFocusLost(editor.vim) injector.listenersNotifier.notifyEditorFocusLost(editor.vim)
} }
} }
/** val editorListenersDisposable = Key.create<Disposable>("IdeaVim listeners disposable")
* Notifies other IdeaVim components of document changes. This will be called for all documents, even those only
* open in non-local Code With Me guest editors, which we still want to process (e.g. to update marks when a guest object VimCaretListener : CaretListener {
* edits a file. Updating search highlights will be a no-op if there are no open local editors) override fun caretAdded(event: CaretEvent) {
*/ if (vimDisabled(event.editor)) return
private object VimDocumentListener : DocumentListener { event.editor.updateCaretsVisualAttributes()
override fun beforeDocumentChange(event: DocumentEvent) {
VimMarkServiceImpl.MarkUpdater.beforeDocumentChange(event)
SearchGroup.DocumentSearchListener.INSTANCE.beforeDocumentChange(event)
} }
override fun documentChanged(event: DocumentEvent) { override fun caretRemoved(event: CaretEvent) {
VimMarkServiceImpl.MarkUpdater.documentChanged(event) if (vimDisabled(event.editor)) return
SearchGroup.DocumentSearchListener.INSTANCE.documentChanged(event) event.editor.updateCaretsVisualAttributes()
} }
} }
/**
* Called when the selected file editor changes. In other words, when the user selects a new tab. Used to remember the
* last selected file, update search highlights in the new tab, etc. This will be called with non-local Code With Me
* guest editors.
*/
class VimFileEditorManagerListener : FileEditorManagerListener { class VimFileEditorManagerListener : FileEditorManagerListener {
override fun selectionChanged(event: FileEditorManagerEvent) { override fun selectionChanged(event: FileEditorManagerEvent) {
// We can't rely on being passed a non-null editor, so check for Code With Me scenarios explicitly if (VimPlugin.isNotEnabled()) return
if (VimPlugin.isNotEnabled() || !ClientId.isCurrentlyUnderLocalId) return
val newEditor = event.newEditor
if (newEditor is TextEditor) {
val editor = newEditor.editor
if (editor.isInsertMode) {
editor.vim.mode = Mode.NORMAL()
KeyHandler.getInstance().reset(editor.vim)
}
}
MotionGroup.fileEditorManagerSelectionChangedCallback(event) MotionGroup.fileEditorManagerSelectionChangedCallback(event)
FileGroup.fileEditorManagerSelectionChangedCallback(event) FileGroup.fileEditorManagerSelectionChangedCallback(event)
VimPlugin.getSearch().fileEditorManagerSelectionChangedCallback(event) VimPlugin.getSearch().fileEditorManagerSelectionChangedCallback(event)
@@ -376,10 +310,6 @@ internal object VimListenerManager {
} }
} }
/**
* Listen to editor creation events in order to initialise IdeaVim compatible editors. This listener is called for all
* editors, including non-local hidden Code With Me editors.
*/
private object VimEditorFactoryListener : EditorFactoryListener, FileOpenedSyncListener { private object VimEditorFactoryListener : EditorFactoryListener, FileOpenedSyncListener {
private data class OpeningEditor( private data class OpeningEditor(
val editor: Editor, val editor: Editor,
@@ -391,8 +321,6 @@ internal object VimListenerManager {
private val openingEditorKey: Key<OpeningEditor> = Key("IdeaVim::OpeningEditor") private val openingEditorKey: Key<OpeningEditor> = Key("IdeaVim::OpeningEditor")
override fun editorCreated(event: EditorFactoryEvent) { override fun editorCreated(event: EditorFactoryEvent) {
if (vimDisabled(event.editor)) return
// This callback is called when an editor is created, but we cannot completely rely on it to initialise options. // This callback is called when an editor is created, but we cannot completely rely on it to initialise options.
// We can find the currently selected editor, which we can use as the opening editor, and we're given the new // We can find the currently selected editor, which we can use as the opening editor, and we're given the new
// editor, but we don't know enough about it - this function is called before the new editor is added to an // editor, but we don't know enough about it - this function is called before the new editor is added to an
@@ -413,7 +341,7 @@ internal object VimListenerManager {
openingEditor == null -> LocalOptionInitialisationScenario.EDIT openingEditor == null -> LocalOptionInitialisationScenario.EDIT
else -> LocalOptionInitialisationScenario.NEW else -> LocalOptionInitialisationScenario.NEW
} }
EditorListeners.add(event.editor, openingEditor?.vim ?: injector.fallbackWindow, scenario) add(event.editor, openingEditor?.vim ?: injector.fallbackWindow, scenario)
firstEditorInitialised = true firstEditorInitialised = true
} }
else { else {
@@ -439,10 +367,11 @@ internal object VimListenerManager {
event.editor.putUserData(openingEditorKey, OpeningEditor(openingEditor, owningEditorWindow, isPreview, canBeReused)) event.editor.putUserData(openingEditorKey, OpeningEditor(openingEditor, owningEditorWindow, isPreview, canBeReused))
} }
VimStandalonePluginUpdateChecker.instance.pluginUsed()
} }
override fun editorReleased(event: EditorFactoryEvent) { override fun editorReleased(event: EditorFactoryEvent) {
if (vimDisabled(event.editor)) return
val vimEditor = event.editor.vim val vimEditor = event.editor.vim
injector.listenersNotifier.notifyEditorReleased(vimEditor) injector.listenersNotifier.notifyEditorReleased(vimEditor)
injector.markService.editorReleased(vimEditor) injector.markService.editorReleased(vimEditor)
@@ -466,8 +395,6 @@ internal object VimListenerManager {
// editor is modified // editor is modified
editorsWithProviders.forEach { editorsWithProviders.forEach {
(it.fileEditor as? TextEditor)?.editor?.let { editor -> (it.fileEditor as? TextEditor)?.editor?.let { editor ->
if (vimDisabled(editor)) return@let
val openingEditor = editor.removeUserData(openingEditorKey) val openingEditor = editor.removeUserData(openingEditorKey)
val owningEditorWindow = getOwningEditorWindow(editor) val owningEditorWindow = getOwningEditorWindow(editor)
val isInSameSplit = owningEditorWindow == openingEditor?.owningEditorWindow val isInSameSplit = owningEditorWindow == openingEditor?.owningEditorWindow
@@ -488,7 +415,7 @@ internal object VimListenerManager {
(openingEditor.canBeReused || openingEditor.isPreview) && isInSameSplit && openingEditorIsClosed -> LocalOptionInitialisationScenario.EDIT (openingEditor.canBeReused || openingEditor.isPreview) && isInSameSplit && openingEditorIsClosed -> LocalOptionInitialisationScenario.EDIT
else -> LocalOptionInitialisationScenario.NEW else -> LocalOptionInitialisationScenario.NEW
} }
EditorListeners.add(editor, openingEditor?.editor?.vim ?: injector.fallbackWindow, scenario) add(editor, openingEditor?.editor?.vim ?: injector.fallbackWindow, scenario)
firstEditorInitialised = true firstEditorInitialised = true
} }
} }
@@ -503,16 +430,12 @@ internal object VimListenerManager {
} }
} }
/**
* Callback for when an editor's text selection changes. Only registered for editors that we're interested in (so only
* local editors). Fixes incorrect mouse selection at end of line, and synchronises selections across other editors.
*/
private object EditorSelectionHandler : SelectionListener { private object EditorSelectionHandler : SelectionListener {
/** /**
* This event is executed for each caret using [com.intellij.openapi.editor.CaretModel.runForEachCaret] * This event is executed for each caret using [com.intellij.openapi.editor.CaretModel.runForEachCaret]
*/ */
override fun selectionChanged(selectionEvent: SelectionEvent) { override fun selectionChanged(selectionEvent: SelectionEvent) {
if (selectionEvent.editor.isIdeaVimDisabledHere) return
VimVisualTimer.drop() VimVisualTimer.drop()
val editor = selectionEvent.editor val editor = selectionEvent.editor
val document = editor.document val document = editor.document
@@ -532,22 +455,20 @@ internal object VimListenerManager {
val startOffset = selectionEvent.newRange.startOffset val startOffset = selectionEvent.newRange.startOffset
val endOffset = selectionEvent.newRange.endOffset val endOffset = selectionEvent.newRange.endOffset
// TODO: It is very confusing that this logic is split between EditorSelectionHandler and EditorMouseHandler if (skipNDragEvents < skipEvents && lineStart != lineEnd && startOffset == caretOffset) {
if (MouseEventsDataHolder.dragEventCount < MouseEventsDataHolder.allowedSkippedDragEvents
&& lineStart != lineEnd && startOffset == caretOffset) {
if (lineEnd == endOffset - 1) { if (lineEnd == endOffset - 1) {
// When starting on an empty line and dragging vertically upwards onto // When starting on an empty line and dragging vertically upwards onto
// another line, the selection should include the entirety of the empty line // another line, the selection should include the entirety of the empty line
caret.setSelection( caret.setSelection(
ijVimEditor.coerceOffset(endOffset + 1), ijVimEditor.coerceOffset(endOffset + 1).point,
ijVimEditor.coerceOffset(startOffset), ijVimEditor.coerceOffset(startOffset).point,
) )
} else if (lineEnd == startOffset + 1 && startOffset == endOffset) { } else if (lineEnd == startOffset + 1 && startOffset == endOffset) {
// When dragging left from EOL on a non-empty line, the selection // When dragging left from EOL on a non-empty line, the selection
// should include the last character on the line // should include the last character on the line
caret.setSelection( caret.setSelection(
ijVimEditor.coerceOffset(lineEnd), ijVimEditor.coerceOffset(lineEnd).point,
ijVimEditor.coerceOffset(lineEnd - 1), ijVimEditor.coerceOffset(lineEnd - 1).point,
) )
} }
} }
@@ -564,24 +485,13 @@ internal object VimListenerManager {
} }
} }
/**
* Listener for mouse events registered with editors that we are interested (so only local editors). Responsible for:
* * Hiding ex entry and output panels when clicking inside editor area (but not when right-clicking)
* * Removing secondary carets on mouse click (such as visual block selection)
* * Exiting visual or select mode on mouse click
* * Resets the dragEventCount on mouse press + release
* * Fix up Vim selected mode on mouse release, after dragging
* * Force bar cursor while dragging, which looks better because IntelliJ selects a character once selection has got
* over halfway through the char, while Vim selects when it enters the character bounding box
*
* @see ComponentMouseListener
*/
// TODO: Can we merge this with ComponentMouseListener to fully handle all mouse actions in one place?
private object EditorMouseHandler : EditorMouseListener, EditorMouseMotionListener { private object EditorMouseHandler : EditorMouseListener, EditorMouseMotionListener {
private var mouseDragging = false private var mouseDragging = false
private var cutOffFixed = false private var cutOffFixed = false
override fun mouseDragged(e: EditorMouseEvent) { override fun mouseDragged(e: EditorMouseEvent) {
if (e.editor.isIdeaVimDisabledHere) return
val caret = e.editor.caretModel.primaryCaret val caret = e.editor.caretModel.primaryCaret
clearFirstSelectionEvents(e) clearFirstSelectionEvents(e)
@@ -633,7 +543,7 @@ internal object VimListenerManager {
} }
} }
} }
MouseEventsDataHolder.dragEventCount -= 1 skipNDragEvents -= 1
} }
/** /**
@@ -648,7 +558,7 @@ internal object VimListenerManager {
* (Both with mouse and with v$. IdeaVim treats v$ as an exclusive selection) * (Both with mouse and with v$. IdeaVim treats v$ as an exclusive selection)
*/ */
private fun clearFirstSelectionEvents(e: EditorMouseEvent) { private fun clearFirstSelectionEvents(e: EditorMouseEvent) {
if (MouseEventsDataHolder.dragEventCount > 0) { if (skipNDragEvents > 0) {
logger.debug("Mouse dragging") logger.debug("Mouse dragging")
VimVisualTimer.swingTimer?.stop() VimVisualTimer.swingTimer?.stop()
if (!mouseDragging) { if (!mouseDragging) {
@@ -674,7 +584,9 @@ internal object VimListenerManager {
} }
override fun mousePressed(event: EditorMouseEvent) { override fun mousePressed(event: EditorMouseEvent) {
MouseEventsDataHolder.dragEventCount = MouseEventsDataHolder.allowedSkippedDragEvents if (event.editor.isIdeaVimDisabledHere) return
skipNDragEvents = skipEvents
SelectionVimListenerSuppressor.reset() SelectionVimListenerSuppressor.reset()
} }
@@ -685,10 +597,12 @@ internal object VimListenerManager {
* - Click-hold and switch editor (ctrl-tab) * - Click-hold and switch editor (ctrl-tab)
*/ */
override fun mouseReleased(event: EditorMouseEvent) { override fun mouseReleased(event: EditorMouseEvent) {
if (event.editor.isIdeaVimDisabledHere) return
SelectionVimListenerSuppressor.unlock() SelectionVimListenerSuppressor.unlock()
clearFirstSelectionEvents(event) clearFirstSelectionEvents(event)
MouseEventsDataHolder.dragEventCount = MouseEventsDataHolder.allowedSkippedDragEvents skipNDragEvents = skipEvents
if (mouseDragging) { if (mouseDragging) {
logger.debug("Release mouse after dragging") logger.debug("Release mouse after dragging")
val editor = event.editor val editor = event.editor
@@ -708,6 +622,7 @@ internal object VimListenerManager {
} }
override fun mouseClicked(event: EditorMouseEvent) { override fun mouseClicked(event: EditorMouseEvent) {
if (event.editor.isIdeaVimDisabledHere) return
logger.debug("Mouse clicked") logger.debug("Mouse clicked")
if (event.area == EditorMouseEventArea.EDITING_AREA) { if (event.area == EditorMouseEventArea.EDITING_AREA) {
@@ -753,21 +668,13 @@ internal object VimListenerManager {
} }
} }
/**
* A mouse listener registered to the editor component for editors that we are interested in (so only local editors).
* Fixes some issues with mouse selection, namely:
* * Clicking at the end of the line will place the caret on the last character rather than after it
* * Double-clicking a word will place the caret on the last character rather than after it
*
* @see EditorMouseHandler
*/
// TODO: Can we merge this with ComponentMouseListener to fully handle all mouse actions in one place?
private object ComponentMouseListener : MouseAdapter() { private object ComponentMouseListener : MouseAdapter() {
var cutOffEnd = false var cutOffEnd = false
override fun mousePressed(e: MouseEvent?) { override fun mousePressed(e: MouseEvent?) {
val editor = (e?.component as? EditorComponentImpl)?.editor ?: return val editor = (e?.component as? EditorComponentImpl)?.editor ?: return
if (editor.isIdeaVimDisabledHere) return
val predictedMode = IdeaSelectionControl.predictMode(editor, SelectionSource.MOUSE) val predictedMode = IdeaSelectionControl.predictMode(editor, SelectionSource.MOUSE)
when (e.clickCount) { when (e.clickCount) {
1 -> { 1 -> {
@@ -804,22 +711,10 @@ internal object VimListenerManager {
} }
} }
/**
* Caret listener registered only for editors that we're interested in. Used to update caret shapes when carets are
* added/removed. Also tracks the expected last column location of the caret.
*/
private object EditorCaretHandler : CaretListener { private object EditorCaretHandler : CaretListener {
override fun caretPositionChanged(event: CaretEvent) { override fun caretPositionChanged(event: CaretEvent) {
event.caret?.resetVimLastColumn() event.caret?.resetVimLastColumn()
} }
override fun caretAdded(event: CaretEvent) {
event.editor.updateCaretsVisualAttributes()
}
override fun caretRemoved(event: CaretEvent) {
event.editor.updateCaretsVisualAttributes()
}
} }
enum class SelectionSource { enum class SelectionSource {
@@ -834,6 +729,6 @@ internal object VimListenerTestObject {
} }
private object MouseEventsDataHolder { private object MouseEventsDataHolder {
const val allowedSkippedDragEvents = 3 const val skipEvents = 3
var dragEventCount = allowedSkippedDragEvents var skipNDragEvents = skipEvents
} }

View File

@@ -12,8 +12,16 @@ import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.util.Key import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.util.UserDataHolder
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
internal open class IjEditorExecutionContext(override val context: DataContext) : ExecutionContext internal open class IjEditorExecutionContext(override val context: DataContext) : ExecutionContext.Editor {
override fun updateEditor(editor: VimEditor): ExecutionContext {
return IjEditorExecutionContext(injector.executionContextManager.onEditor(editor, context.vim).ij)
}
}
internal class IjCaretAndEditorExecutionContext(override val context: DataContext) : IjEditorExecutionContext(context), ExecutionContext.CaretAndEditor
// This key is stored in data context when the action is started from vim // This key is stored in data context when the action is started from vim
internal val runFromVimKey = Key.create<Boolean>("RunFromVim") internal val runFromVimKey = Key.create<Boolean>("RunFromVim")

View File

@@ -9,15 +9,23 @@
package com.maddyhome.idea.vim.newapi package com.maddyhome.idea.vim.newapi
import com.intellij.openapi.components.Service import com.intellij.openapi.components.Service
import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.editor.actionSystem.CaretSpecificDataContext
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.ExecutionContextManagerBase import com.maddyhome.idea.vim.api.ExecutionContextManagerBase
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.helper.EditorDataContext import com.maddyhome.idea.vim.helper.EditorDataContext
@Service @Service
internal class IjExecutionContextManager : ExecutionContextManagerBase() { internal class IjExecutionContextManager : ExecutionContextManagerBase() {
override fun getEditorExecutionContext(editor: VimEditor): ExecutionContext { override fun onEditor(editor: VimEditor, prevContext: ExecutionContext?): ExecutionContext.Editor {
return EditorUtil.getEditorDataContext(editor.ij).vim if (prevContext is ExecutionContext.CaretAndEditor) {
return prevContext
}
return IjEditorExecutionContext(EditorDataContext.init((editor as IjVimEditor).editor, prevContext?.ij))
}
override fun onCaret(caret: VimCaret, prevContext: ExecutionContext.Editor): ExecutionContext.CaretAndEditor {
return IjCaretAndEditorExecutionContext(CaretSpecificDataContext.create(prevContext.ij, caret.ij))
} }
} }

View File

@@ -10,10 +10,12 @@ package com.maddyhome.idea.vim.newapi
import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.editor.RangeMarker
import com.maddyhome.idea.vim.common.LiveRange import com.maddyhome.idea.vim.common.LiveRange
import com.maddyhome.idea.vim.common.Offset
import com.maddyhome.idea.vim.common.offset
internal class IjLiveRange(val marker: RangeMarker) : LiveRange { internal class IjLiveRange(val marker: RangeMarker) : LiveRange {
override val startOffset: Int override val startOffset: Offset
get() = marker.startOffset get() = marker.startOffset.offset
} }
public val RangeMarker.vim: LiveRange public val RangeMarker.vim: LiveRange

View File

@@ -34,8 +34,4 @@ internal class IjNativeActionManager : NativeActionManager {
public val AnAction.vim: IjNativeAction public val AnAction.vim: IjNativeAction
get() = IjNativeAction(this) get() = IjNativeAction(this)
public class IjNativeAction(override val action: AnAction) : NativeAction { public class IjNativeAction(override val action: AnAction) : NativeAction
override fun toString(): String {
return "IjNativeAction(action=$action)"
}
}

View File

@@ -58,6 +58,10 @@ internal class IjVimApplication : VimApplicationBase() {
} }
} }
override fun localEditors(): List<VimEditor> {
return com.maddyhome.idea.vim.helper.localEditors().map { IjVimEditor(it) }
}
override fun runWriteCommand(editor: VimEditor, name: String?, groupId: Any?, command: Runnable) { override fun runWriteCommand(editor: VimEditor, name: String?, groupId: Any?, command: Runnable) {
RunnableHelper.runWriteCommand((editor as IjVimEditor).editor.project, command, name, groupId) RunnableHelper.runWriteCommand((editor as IjVimEditor).editor.project, command, name, groupId)
} }
@@ -82,12 +86,6 @@ internal class IjVimApplication : VimApplicationBase() {
com.maddyhome.idea.vim.helper.runAfterGotFocus(runnable) com.maddyhome.idea.vim.helper.runAfterGotFocus(runnable)
} }
override fun isOctopusEnabled(): Boolean {
val property = System.getProperty("octopus.handler") ?: "true"
if (property.isBlank()) return true
return property.toBoolean()
}
private fun createKeyEvent(stroke: KeyStroke, component: Component): KeyEvent { private fun createKeyEvent(stroke: KeyStroke, component: Component): KeyEvent {
return KeyEvent( return KeyEvent(
component, component,

View File

@@ -11,6 +11,7 @@ package com.maddyhome.idea.vim.newapi
import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.editor.VisualPosition import com.intellij.openapi.editor.VisualPosition
import com.intellij.openapi.util.Disposer
import com.maddyhome.idea.vim.api.BufferPosition import com.maddyhome.idea.vim.api.BufferPosition
import com.maddyhome.idea.vim.api.CaretRegisterStorage import com.maddyhome.idea.vim.api.CaretRegisterStorage
import com.maddyhome.idea.vim.api.CaretRegisterStorageBase import com.maddyhome.idea.vim.api.CaretRegisterStorageBase
@@ -21,7 +22,10 @@ import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimCaretBase import com.maddyhome.idea.vim.api.VimCaretBase
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimVisualPosition import com.maddyhome.idea.vim.api.VimVisualPosition
import com.maddyhome.idea.vim.common.EditorLine
import com.maddyhome.idea.vim.common.LiveRange import com.maddyhome.idea.vim.common.LiveRange
import com.maddyhome.idea.vim.common.Offset
import com.maddyhome.idea.vim.common.offset
import com.maddyhome.idea.vim.group.visual.VisualChange import com.maddyhome.idea.vim.group.visual.VisualChange
import com.maddyhome.idea.vim.helper.lastSelectionInfo import com.maddyhome.idea.vim.helper.lastSelectionInfo
import com.maddyhome.idea.vim.helper.markStorage import com.maddyhome.idea.vim.helper.markStorage
@@ -38,6 +42,14 @@ import com.maddyhome.idea.vim.state.mode.SelectionType
internal class IjVimCaret(val caret: Caret) : VimCaretBase() { internal class IjVimCaret(val caret: Caret) : VimCaretBase() {
init {
if (caret.isValid) {
Disposer.register(caret) {
(registerStorage as CaretRegisterStorageBase).clearListener()
}
}
}
override val registerStorage: CaretRegisterStorage override val registerStorage: CaretRegisterStorage
get() { get() {
var storage = this.caret.registerStorage var storage = this.caret.registerStorage
@@ -75,8 +87,8 @@ internal class IjVimCaret(val caret: Caret) : VimCaretBase() {
} }
override val editor: VimEditor override val editor: VimEditor
get() = IjVimEditor(caret.editor) get() = IjVimEditor(caret.editor)
override val offset: Int override val offset: Offset
get() = caret.offset get() = caret.offset.offset
override var vimLastColumn: Int override var vimLastColumn: Int
get() = caret.vimLastColumn get() = caret.vimLastColumn
set(value) { set(value) {
@@ -115,8 +127,8 @@ internal class IjVimCaret(val caret: Caret) : VimCaretBase() {
this.caret.moveToLogicalPosition(LogicalPosition(position.line, position.column, position.leansForward)) this.caret.moveToLogicalPosition(LogicalPosition(position.line, position.column, position.leansForward))
} }
override fun getLine(): Int { override fun getLine(): EditorLine.Pointer {
return caret.logicalPosition.line return EditorLine.Pointer.init(caret.logicalPosition.line, editor)
} }
override fun hasSelection(): Boolean { override fun hasSelection(): Boolean {
@@ -161,8 +173,8 @@ internal class IjVimCaret(val caret: Caret) : VimCaretBase() {
return this return this
} }
override fun setSelection(start: Int, end: Int) { override fun setSelection(start: Offset, end: Offset) {
caret.setSelection(start, end) caret.setSelection(start.point, end.point)
} }
override fun removeSelection() { override fun removeSelection() {

View File

@@ -14,6 +14,7 @@ import com.intellij.openapi.editor.event.DocumentListener
import com.maddyhome.idea.vim.api.VimDocument import com.maddyhome.idea.vim.api.VimDocument
import com.maddyhome.idea.vim.common.ChangesListener import com.maddyhome.idea.vim.common.ChangesListener
import com.maddyhome.idea.vim.common.LiveRange import com.maddyhome.idea.vim.common.LiveRange
import com.maddyhome.idea.vim.common.Offset
internal class IjVimDocument(val document: Document) : VimDocument { internal class IjVimDocument(val document: Document) : VimDocument {
@@ -40,7 +41,7 @@ internal class IjVimDocument(val document: Document) : VimDocument {
document.removeDocumentListener(nativeListener) document.removeDocumentListener(nativeListener)
} }
override fun getOffsetGuard(offset: Int): LiveRange? { override fun getOffsetGuard(offset: Offset): LiveRange? {
return document.getOffsetGuard(offset)?.vim return document.getOffsetGuard(offset.point)?.vim
} }
} }

View File

@@ -35,11 +35,13 @@ import com.maddyhome.idea.vim.api.VimScrollingModel
import com.maddyhome.idea.vim.api.VimSelectionModel import com.maddyhome.idea.vim.api.VimSelectionModel
import com.maddyhome.idea.vim.api.VimVisualPosition import com.maddyhome.idea.vim.api.VimVisualPosition
import com.maddyhome.idea.vim.api.VirtualFile import com.maddyhome.idea.vim.api.VirtualFile
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.common.EditorLine
import com.maddyhome.idea.vim.common.IndentConfig import com.maddyhome.idea.vim.common.IndentConfig
import com.maddyhome.idea.vim.common.LiveRange import com.maddyhome.idea.vim.common.LiveRange
import com.maddyhome.idea.vim.common.Offset
import com.maddyhome.idea.vim.common.TextRange import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.common.offset
import com.maddyhome.idea.vim.group.visual.vimSetSystemBlockSelectionSilently import com.maddyhome.idea.vim.group.visual.vimSetSystemBlockSelectionSilently
import com.maddyhome.idea.vim.helper.EditorHelper import com.maddyhome.idea.vim.helper.EditorHelper
import com.maddyhome.idea.vim.helper.StrictMode import com.maddyhome.idea.vim.helper.StrictMode
@@ -49,6 +51,8 @@ import com.maddyhome.idea.vim.helper.fileSize
import com.maddyhome.idea.vim.helper.getTopLevelEditor import com.maddyhome.idea.vim.helper.getTopLevelEditor
import com.maddyhome.idea.vim.helper.inExMode import com.maddyhome.idea.vim.helper.inExMode
import com.maddyhome.idea.vim.helper.isTemplateActive import com.maddyhome.idea.vim.helper.isTemplateActive
import com.maddyhome.idea.vim.helper.updateCaretsVisualAttributes
import com.maddyhome.idea.vim.helper.updateCaretsVisualPosition
import com.maddyhome.idea.vim.helper.vimChangeActionSwitchMode import com.maddyhome.idea.vim.helper.vimChangeActionSwitchMode
import com.maddyhome.idea.vim.helper.vimLastSelectionType import com.maddyhome.idea.vim.helper.vimLastSelectionType
import com.maddyhome.idea.vim.state.mode.Mode import com.maddyhome.idea.vim.state.mode.Mode
@@ -88,18 +92,18 @@ internal class IjVimEditor(editor: Editor) : MutableLinearEditor() {
return editor.document.lineCount return editor.document.lineCount
} }
override fun deleteRange(leftOffset: Int, rightOffset: Int) { override fun deleteRange(leftOffset: Offset, rightOffset: Offset) {
editor.document.deleteString(leftOffset, rightOffset) editor.document.deleteString(leftOffset.point, rightOffset.point)
} }
override fun addLine(atPosition: Int): Int { override fun addLine(atPosition: EditorLine.Offset): EditorLine.Pointer {
val offset: Int = if (atPosition < lineCount()) { val offset: Int = if (atPosition.line < lineCount()) {
// The new line character is inserted before the new line char of the previous line. So it works line an enter // The new line character is inserted before the new line char of the previous line. So it works line an enter
// on a line end. I believe that the correct implementation would be to insert the new line char after the // on a line end. I believe that the correct implementation would be to insert the new line char after the
// \n of the previous line, however at the moment this won't update the mark on this line. // \n of the previous line, however at the moment this won't update the mark on this line.
// https://youtrack.jetbrains.com/issue/IDEA-286587 // https://youtrack.jetbrains.com/issue/IDEA-286587
val lineStart = (editor.document.getLineStartOffset(atPosition) - 1).coerceAtLeast(0) val lineStart = (editor.document.getLineStartOffset(atPosition.line) - 1).coerceAtLeast(0)
val guard = editor.document.getOffsetGuard(lineStart) val guard = editor.document.getOffsetGuard(lineStart)
if (guard != null && guard.endOffset == lineStart + 1) { if (guard != null && guard.endOffset == lineStart + 1) {
// Dancing around guarded blocks. It may happen that this concrete position is locked, but the next // Dancing around guarded blocks. It may happen that this concrete position is locked, but the next
@@ -114,11 +118,11 @@ internal class IjVimEditor(editor: Editor) : MutableLinearEditor() {
fileSize().toInt() fileSize().toInt()
} }
editor.document.insertString(offset, "\n") editor.document.insertString(offset, "\n")
return atPosition return EditorLine.Pointer.init(atPosition.line, this)
} }
override fun insertText(atPosition: Int, text: CharSequence) { override fun insertText(atPosition: Offset, text: CharSequence) {
editor.document.insertString(atPosition, text) editor.document.insertString(atPosition.point, text)
} }
override fun replaceString(start: Int, end: Int, newString: String) { override fun replaceString(start: Int, end: Int, newString: String) {
@@ -126,13 +130,13 @@ internal class IjVimEditor(editor: Editor) : MutableLinearEditor() {
} }
// TODO: 30.12.2021 Is end offset inclusive? // TODO: 30.12.2021 Is end offset inclusive?
override fun getLineRange(line: Int): Pair<Int, Int> { override fun getLineRange(line: EditorLine.Pointer): Pair<Offset, Offset> {
// TODO: 30.12.2021 getLineEndOffset returns the same value for "xyz" and "xyz\n" // TODO: 30.12.2021 getLineEndOffset returns the same value for "xyz" and "xyz\n"
return editor.document.getLineStartOffset(line) to editor.document.getLineEndOffset(line) return editor.document.getLineStartOffset(line.line).offset to editor.document.getLineEndOffset(line.line).offset
} }
override fun getLine(offset: Int): Int { override fun getLine(offset: Offset): EditorLine.Pointer {
return editor.offsetToLogicalPosition(offset).line return EditorLine.Pointer.init(editor.offsetToLogicalPosition(offset.point).line, this)
} }
override fun carets(): List<VimCaret> { override fun carets(): List<VimCaret> {
@@ -201,15 +205,15 @@ internal class IjVimEditor(editor: Editor) : MutableLinearEditor() {
return editor.isOneLineMode return editor.isOneLineMode
} }
override fun getText(left: Int, right: Int): CharSequence { override fun getText(left: Offset, right: Offset): CharSequence {
return editor.document.charsSequence.subSequence(left, right) return editor.document.charsSequence.subSequence(left.point, right.point)
} }
override fun search( override fun search(
pair: Pair<Int, Int>, pair: Pair<Offset, Offset>,
editor: VimEditor, editor: VimEditor,
shiftType: LineDeleteShift, shiftType: LineDeleteShift,
): Pair<Pair<Int, Int>, LineDeleteShift>? { ): Pair<Pair<Offset, Offset>, LineDeleteShift>? {
val ijEditor = (editor as IjVimEditor).editor val ijEditor = (editor as IjVimEditor).editor
return when (shiftType) { return when (shiftType) {
LineDeleteShift.NO_NL -> if (pair.noGuard(ijEditor)) return pair to shiftType else null LineDeleteShift.NO_NL -> if (pair.noGuard(ijEditor)) return pair to shiftType else null
@@ -239,6 +243,14 @@ internal class IjVimEditor(editor: Editor) : MutableLinearEditor() {
} }
} }
override fun updateCaretsVisualAttributes() {
editor.updateCaretsVisualAttributes()
}
override fun updateCaretsVisualPosition() {
editor.updateCaretsVisualPosition()
}
override fun offsetToVisualPosition(offset: Int): VimVisualPosition { override fun offsetToVisualPosition(offset: Int): VimVisualPosition {
return editor.offsetToVisualPosition(offset).let { VimVisualPosition(it.line, it.column, it.leansRight) } return editor.offsetToVisualPosition(offset).let { VimVisualPosition(it.line, it.column, it.leansRight) }
} }
@@ -356,10 +368,10 @@ internal class IjVimEditor(editor: Editor) : MutableLinearEditor() {
return EditorHelper.getVirtualFile(editor)?.getUrl()?.let { VirtualFileManager.extractProtocol(it) } return EditorHelper.getVirtualFile(editor)?.getUrl()?.let { VirtualFileManager.extractProtocol(it) }
} }
override val projectId = editor.project?.let { injector.file.getProjectId(it) } ?: DEFAULT_PROJECT_ID override val projectId = editor.project?.basePath ?: DEFAULT_PROJECT_ID
override fun visualPositionToOffset(position: VimVisualPosition): Int { override fun visualPositionToOffset(position: VimVisualPosition): Offset {
return editor.visualPositionToOffset(VisualPosition(position.line, position.column, position.leansRight)) return editor.visualPositionToOffset(VisualPosition(position.line, position.column, position.leansRight)).offset
} }
override fun exitInsertMode(context: ExecutionContext, operatorArguments: OperatorArguments) { override fun exitInsertMode(context: ExecutionContext, operatorArguments: OperatorArguments) {
@@ -415,8 +427,8 @@ internal class IjVimEditor(editor: Editor) : MutableLinearEditor() {
return visualPosition.run { VimVisualPosition(line, column, leansRight) } return visualPosition.run { VimVisualPosition(line, column, leansRight) }
} }
override fun createLiveMarker(start: Int, end: Int): LiveRange { override fun createLiveMarker(start: Offset, end: Offset): LiveRange {
return editor.document.createRangeMarker(start, end).vim return editor.document.createRangeMarker(start.point, end.point).vim
} }
/** /**
@@ -454,10 +466,10 @@ internal class IjVimEditor(editor: Editor) : MutableLinearEditor() {
ijFoldRegion.isExpanded = value ijFoldRegion.isExpanded = value
} }
} }
override val startOffset: Int override val startOffset: Offset
get() = ijFoldRegion.startOffset get() = Offset(ijFoldRegion.startOffset)
override val endOffset: Int override val endOffset: Offset
get() = ijFoldRegion.endOffset get() = Offset(ijFoldRegion.endOffset)
} }
} }
@@ -466,17 +478,17 @@ internal class IjVimEditor(editor: Editor) : MutableLinearEditor() {
return caret return caret
} }
private fun Pair<Int, Int>.noGuard(editor: Editor): Boolean { private fun Pair<Offset, Offset>.noGuard(editor: Editor): Boolean {
return editor.document.getRangeGuard(this.first, this.second) == null return editor.document.getRangeGuard(this.first.point, this.second.point) == null
} }
private inline fun Pair<Int, Int>.shift( private inline fun Pair<Offset, Offset>.shift(
shiftStart: Int = 0, shiftStart: Int = 0,
shiftEnd: Int = 0, shiftEnd: Int = 0,
action: Pair<Int, Int>.() -> Unit, action: Pair<Offset, Offset>.() -> Unit,
) { ) {
val data = val data =
(this.first + shiftStart).coerceAtLeast(0) to (this.second + shiftEnd).coerceAtLeast(0) (this.first.point + shiftStart).coerceAtLeast(0).offset to (this.second.point + shiftEnd).coerceAtLeast(0).offset
data.action() data.action()
} }
@@ -498,6 +510,3 @@ public val Editor.vim: VimEditor
get() = IjVimEditor(this) get() = IjVimEditor(this)
public val VimEditor.ij: Editor public val VimEditor.ij: Editor
get() = (this as IjVimEditor).editor get() = (this as IjVimEditor).editor
public val com.intellij.openapi.util.TextRange.vim: TextRange
get() = TextRange(this.startOffset, this.endOffset)

View File

@@ -42,7 +42,6 @@ import com.maddyhome.idea.vim.api.VimMessages
import com.maddyhome.idea.vim.api.VimMotionGroup import com.maddyhome.idea.vim.api.VimMotionGroup
import com.maddyhome.idea.vim.api.VimOptionGroup import com.maddyhome.idea.vim.api.VimOptionGroup
import com.maddyhome.idea.vim.api.VimProcessGroup import com.maddyhome.idea.vim.api.VimProcessGroup
import com.maddyhome.idea.vim.api.VimPsiService
import com.maddyhome.idea.vim.api.VimRegexpService import com.maddyhome.idea.vim.api.VimRegexpService
import com.maddyhome.idea.vim.api.VimScrollGroup import com.maddyhome.idea.vim.api.VimScrollGroup
import com.maddyhome.idea.vim.api.VimSearchGroup import com.maddyhome.idea.vim.api.VimSearchGroup
@@ -66,7 +65,6 @@ import com.maddyhome.idea.vim.group.FileGroup
import com.maddyhome.idea.vim.group.GlobalIjOptions import com.maddyhome.idea.vim.group.GlobalIjOptions
import com.maddyhome.idea.vim.group.HistoryGroup import com.maddyhome.idea.vim.group.HistoryGroup
import com.maddyhome.idea.vim.group.IjVimOptionGroup import com.maddyhome.idea.vim.group.IjVimOptionGroup
import com.maddyhome.idea.vim.group.IjVimPsiService
import com.maddyhome.idea.vim.group.MacroGroup import com.maddyhome.idea.vim.group.MacroGroup
import com.maddyhome.idea.vim.group.MotionGroup import com.maddyhome.idea.vim.group.MotionGroup
import com.maddyhome.idea.vim.group.SearchGroup import com.maddyhome.idea.vim.group.SearchGroup
@@ -82,11 +80,11 @@ import com.maddyhome.idea.vim.helper.UndoRedoHelper
import com.maddyhome.idea.vim.helper.VimCommandLineHelper import com.maddyhome.idea.vim.helper.VimCommandLineHelper
import com.maddyhome.idea.vim.helper.vimStateMachine import com.maddyhome.idea.vim.helper.vimStateMachine
import com.maddyhome.idea.vim.history.VimHistory import com.maddyhome.idea.vim.history.VimHistory
import com.maddyhome.idea.vim.impl.state.VimStateMachineImpl
import com.maddyhome.idea.vim.macro.VimMacro import com.maddyhome.idea.vim.macro.VimMacro
import com.maddyhome.idea.vim.put.VimPut import com.maddyhome.idea.vim.put.VimPut
import com.maddyhome.idea.vim.register.VimRegisterGroup import com.maddyhome.idea.vim.register.VimRegisterGroup
import com.maddyhome.idea.vim.state.VimStateMachine import com.maddyhome.idea.vim.state.VimStateMachine
import com.maddyhome.idea.vim.impl.state.VimStateMachineImpl
import com.maddyhome.idea.vim.ui.VimRcFileState import com.maddyhome.idea.vim.ui.VimRcFileState
import com.maddyhome.idea.vim.undo.VimUndoRedo import com.maddyhome.idea.vim.undo.VimUndoRedo
import com.maddyhome.idea.vim.vimscript.Executor import com.maddyhome.idea.vim.vimscript.Executor
@@ -149,8 +147,6 @@ internal class IjVimInjector : VimInjectorBase() {
get() = service<MacroGroup>() get() = service<MacroGroup>()
override val undo: VimUndoRedo override val undo: VimUndoRedo
get() = service<UndoRedoHelper>() get() = service<UndoRedoHelper>()
override val psiService: VimPsiService
get() = service<IjVimPsiService>()
override val commandLineHelper: VimCommandLineHelper override val commandLineHelper: VimCommandLineHelper
get() = service<CommandLineHelper>() get() = service<CommandLineHelper>()
override val nativeActionManager: NativeActionManager override val nativeActionManager: NativeActionManager
@@ -211,7 +207,7 @@ internal class IjVimInjector : VimInjectorBase() {
override fun commandStateFor(editor: VimEditor): VimStateMachine { override fun commandStateFor(editor: VimEditor): VimStateMachine {
var res = editor.ij.vimStateMachine var res = editor.ij.vimStateMachine
if (res == null) { if (res == null) {
res = VimStateMachineImpl() res = VimStateMachineImpl(editor)
editor.ij.vimStateMachine = res editor.ij.vimStateMachine = res
} }
return res return res

View File

@@ -11,7 +11,6 @@ package com.maddyhome.idea.vim.newapi
import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.Ref import com.intellij.openapi.util.Ref
import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.Options import com.maddyhome.idea.vim.api.Options
import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
@@ -27,11 +26,13 @@ import com.maddyhome.idea.vim.helper.shouldIgnoreCase
import com.maddyhome.idea.vim.helper.updateSearchHighlights import com.maddyhome.idea.vim.helper.updateSearchHighlights
import com.maddyhome.idea.vim.options.GlobalOptionChangeListener import com.maddyhome.idea.vim.options.GlobalOptionChangeListener
import com.maddyhome.idea.vim.ui.ModalEntry import com.maddyhome.idea.vim.ui.ModalEntry
import com.maddyhome.idea.vim.vimscript.model.expressions.Expression
import com.maddyhome.idea.vim.vimscript.model.functions.handlers.SubmatchFunctionHandler import com.maddyhome.idea.vim.vimscript.model.functions.handlers.SubmatchFunctionHandler
import com.maddyhome.idea.vim.vimscript.parser.VimscriptParser.parseExpression
import org.jetbrains.annotations.TestOnly import org.jetbrains.annotations.TestOnly
import javax.swing.KeyStroke import javax.swing.KeyStroke
public abstract class IjVimSearchGroup : VimSearchGroupBase() { public open class IjVimSearchGroup : VimSearchGroupBase() {
init { init {
// TODO: Investigate migrating these listeners to use the effective value change listener // TODO: Investigate migrating these listeners to use the effective value change listener
@@ -81,7 +82,6 @@ public abstract class IjVimSearchGroup : VimSearchGroupBase() {
override fun confirmChoice( override fun confirmChoice(
editor: VimEditor, editor: VimEditor,
context: ExecutionContext,
match: String, match: String,
caret: VimCaret, caret: VimCaret,
startOffset: Int, startOffset: Int,
@@ -121,6 +121,7 @@ public abstract class IjVimSearchGroup : VimSearchGroupBase() {
// 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
val exEntryPanel: com.maddyhome.idea.vim.ui.ex.ExEntryPanel = val exEntryPanel: com.maddyhome.idea.vim.ui.ex.ExEntryPanel =
com.maddyhome.idea.vim.ui.ex.ExEntryPanel.getInstanceWithoutShortcuts() com.maddyhome.idea.vim.ui.ex.ExEntryPanel.getInstanceWithoutShortcuts()
val context = injector.executionContextManager.onEditor(editor, null)
exEntryPanel.activate( exEntryPanel.activate(
editor.ij, editor.ij,
(context as IjEditorExecutionContext).context, (context as IjEditorExecutionContext).context,
@@ -135,6 +136,10 @@ public abstract class IjVimSearchGroup : VimSearchGroupBase() {
return result.get() return result.get()
} }
override fun parseVimScriptExpression(expressionString: String): Expression? {
return parseExpression(expressionString)
}
override fun addSubstitutionConfirmationHighlight(editor: VimEditor, startOffset: Int, endOffset: Int) { override fun addSubstitutionConfirmationHighlight(editor: VimEditor, startOffset: Int, endOffset: Int) {
val hl = addSubstitutionConfirmationHighlight( val hl = addSubstitutionConfirmationHighlight(
(editor as IjVimEditor).editor, (editor as IjVimEditor).editor,
@@ -173,4 +178,4 @@ public abstract class IjVimSearchGroup : VimSearchGroupBase() {
showSearchHighlight = false showSearchHighlight = false
updateSearchHighlights(false) updateSearchHighlights(false)
} }
} }

View File

@@ -13,31 +13,144 @@ import com.intellij.openapi.diagnostic.Logger
import com.maddyhome.idea.vim.api.ImmutableVimCaret import com.maddyhome.idea.vim.api.ImmutableVimCaret
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimSearchHelperBase import com.maddyhome.idea.vim.api.VimSearchHelperBase
import com.maddyhome.idea.vim.api.anyNonWhitespace
import com.maddyhome.idea.vim.api.getLineEndOffset
import com.maddyhome.idea.vim.api.getLineStartForOffset
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.api.normalizeOffset
import com.maddyhome.idea.vim.common.Direction
import com.maddyhome.idea.vim.common.TextRange import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.helper.CharacterHelper
import com.maddyhome.idea.vim.helper.CharacterHelper.charType
import com.maddyhome.idea.vim.helper.PsiHelper import com.maddyhome.idea.vim.helper.PsiHelper
import com.maddyhome.idea.vim.helper.SearchHelper import com.maddyhome.idea.vim.helper.SearchHelper
import com.maddyhome.idea.vim.helper.SearchOptions import com.maddyhome.idea.vim.helper.SearchOptions
import com.maddyhome.idea.vim.helper.checkInString
import com.maddyhome.idea.vim.helper.fileSize
import com.maddyhome.idea.vim.state.VimStateMachine.Companion.getInstance
import com.maddyhome.idea.vim.state.mode.Mode.VISUAL
import it.unimi.dsi.fastutil.ints.IntComparator import it.unimi.dsi.fastutil.ints.IntComparator
import it.unimi.dsi.fastutil.ints.IntComparators import it.unimi.dsi.fastutil.ints.IntComparators
import java.util.* import java.util.*
import java.util.function.Function
import java.util.regex.Pattern
import kotlin.math.abs
import kotlin.math.max
@Service @Service
internal class IjVimSearchHelper : VimSearchHelperBase() { internal class IjVimSearchHelper : VimSearchHelperBase() {
companion object { companion object {
private const val BLOCK_CHARS = "{}()[]<>"
private val logger = Logger.getInstance(IjVimSearchHelper::class.java.name) private val logger = Logger.getInstance(IjVimSearchHelper::class.java.name)
} }
override fun findSection(
editor: VimEditor,
caret: ImmutableVimCaret,
type: Char,
direction: Int,
count: Int,
)
: Int {
val documentText: CharSequence = editor.ij.document.charsSequence
var currentLine: Int = caret.ij.logicalPosition.line + direction
var resultOffset = -1
var remainingTargets = count
while (currentLine in 1 until editor.lineCount() && remainingTargets > 0) {
val lineStartOffset = editor.getLineStartOffset(currentLine)
if (lineStartOffset < documentText.length) {
val currentChar = documentText[lineStartOffset]
if (currentChar == type || currentChar == '\u000C') {
resultOffset = lineStartOffset
remainingTargets--
}
}
currentLine += direction
}
if (resultOffset == -1) {
resultOffset = if (direction < 0) 0 else documentText.length - 1
}
return resultOffset
}
override fun findMethodEnd(editor: VimEditor, caret: ImmutableVimCaret, count: Int): Int { override fun findMethodEnd(editor: VimEditor, caret: ImmutableVimCaret, count: Int): Int {
// TODO add it to PsiService
return PsiHelper.findMethodEnd(editor.ij, caret.ij.offset, count) return PsiHelper.findMethodEnd(editor.ij, caret.ij.offset, count)
} }
override fun findMethodStart(editor: VimEditor, caret: ImmutableVimCaret, count: Int): Int { override fun findMethodStart(editor: VimEditor, caret: ImmutableVimCaret, count: Int): Int {
// TODO add it to PsiService
return PsiHelper.findMethodStart(editor.ij, caret.ij.offset, count) return PsiHelper.findMethodStart(editor.ij, caret.ij.offset, count)
} }
override fun findUnmatchedBlock(editor: VimEditor, caret: ImmutableVimCaret, type: Char, count: Int): Int {
val chars: CharSequence = editor.ij.document.charsSequence
var pos: Int = caret.ij.offset
val loc = BLOCK_CHARS.indexOf(type)
// What direction should we go now (-1 is backward, 1 is forward)
val dir = if (loc % 2 == 0) Direction.BACKWARDS else Direction.FORWARDS
// Which character did we find and which should we now search for
val match = BLOCK_CHARS[loc]
val found = BLOCK_CHARS[loc - dir.toInt()]
if (pos < chars.length && chars[pos] == type) {
pos += dir.toInt()
}
return findBlockLocation(chars, found, match, dir, pos, count)
}
private fun findBlockLocation(
chars: CharSequence,
found: Char,
match: Char,
dir: Direction,
pos: Int,
cnt: Int,
): Int {
var position = pos
var count = cnt
var res = -1
val initialPos = position
val initialInString = checkInString(chars, position, true)
val inCheckPosF =
Function { x: Int -> if (dir === Direction.BACKWARDS && x > 0) x - 1 else x + 1 }
val inCheckPos = inCheckPosF.apply(position)
var inString = checkInString(chars, inCheckPos, true)
var inChar = checkInString(chars, inCheckPos, false)
var stack = 0
// Search to start or end of file, as appropriate
val charsToSearch: Set<Char> = HashSet(listOf('\'', '"', '\n', match, found))
while (position >= 0 && position < chars.length && count > 0) {
val (c, second) = SearchHelper.findPositionOfFirstCharacter(chars, position, charsToSearch, true, dir) ?: return -1
position = second
// If we found a match and we're not in a string...
if (c == match && (!inString) && !inChar) {
// We found our match
if (stack == 0) {
res = position
count--
} else {
stack--
}
} else if (c == '\n') {
inString = false
inChar = false
} else if (position != initialPos) {
// We found another character like our original - belongs to another pair
if (!inString && !inChar && c == found) {
stack++
} else if (!inChar) {
inString = checkInString(chars, inCheckPosF.apply(position), true)
} else if (!inString) {
inChar = checkInString(chars, inCheckPosF.apply(position), false)
}
}
position += dir.toInt()
}
return res
}
override fun findPattern( override fun findPattern(
editor: VimEditor, editor: VimEditor,
pattern: String?, pattern: String?,
@@ -60,6 +173,525 @@ internal class IjVimSearchHelper : VimSearchHelperBase() {
else SearchHelper.findAll(editor.ij, pattern, startLine, endLine, ignoreCase) else SearchHelper.findAll(editor.ij, pattern, startLine, endLine, ignoreCase)
} }
override fun findNextCharacterOnLine(editor: VimEditor, caret: ImmutableVimCaret, count: Int, ch: Char): Int {
val line: Int = caret.ij.logicalPosition.line
val start = editor.getLineStartOffset(line)
val end = editor.getLineEndOffset(line, true)
val chars: CharSequence = editor.ij.document.charsSequence
var found = 0
val step = if (count >= 0) 1 else -1
var pos: Int = caret.ij.offset + step
while (pos in start until end && pos < chars.length) {
if (chars[pos] == ch) {
found++
if (found == abs(count)) {
break
}
}
pos += step
}
return if (found == abs(count)) {
pos
} else {
-1
}
}
override fun findWordUnderCursor(
editor: VimEditor,
caret: ImmutableVimCaret,
count: Int,
dir: Int,
isOuter: Boolean,
isBig: Boolean,
hasSelection: Boolean,
): TextRange {
if (logger.isDebugEnabled) {
logger.debug("count=$count")
logger.debug("dir=$dir")
logger.debug("isOuter=$isOuter")
logger.debug("isBig=$isBig")
logger.debug("hasSelection=$hasSelection")
}
val chars: CharSequence = editor.ij.document.charsSequence
//int min = EditorHelper.getLineStartOffset(editor, EditorHelper.getCurrentLogicalLine(editor));
//int max = EditorHelper.getLineEndOffset(editor, EditorHelper.getCurrentLogicalLine(editor), true);
val min = 0
val max: Int = editor.ij.fileSize
if (max == 0) return TextRange(0, 0)
if (logger.isDebugEnabled) {
logger.debug("min=$min")
logger.debug("max=$max")
}
val pos: Int = caret.ij.offset
if (chars.length <= pos) return TextRange(chars.length - 1, chars.length - 1)
val startSpace = charType(editor, chars[pos], isBig) === CharacterHelper.CharacterType.WHITESPACE
// Find word start
val onWordStart = pos == min ||
charType(editor, chars[pos - 1], isBig) !==
charType(editor, chars[pos], isBig)
var start = pos
if (logger.isDebugEnabled) {
logger.debug("pos=$pos")
logger.debug("onWordStart=$onWordStart")
}
if (!onWordStart && !(startSpace && isOuter) || hasSelection || count > 1 && dir == -1) {
start = if (dir == 1) {
findNextWord(editor, pos, -1, isBig, !isOuter)
} else {
findNextWord(
editor,
pos,
-(count - if (onWordStart && !hasSelection) 1 else 0),
isBig,
!isOuter
)
}
start = editor.normalizeOffset(start, false)
}
if (logger.isDebugEnabled) logger.debug("start=$start")
// Find word end
// Find word end
val onWordEnd = pos >= max - 1 ||
charType(editor, chars[pos + 1], isBig) !==
charType(editor, chars[pos], isBig)
if (logger.isDebugEnabled) logger.debug("onWordEnd=$onWordEnd")
var end = pos
if (!onWordEnd || hasSelection || count > 1 && dir == 1 || startSpace && isOuter) {
end = if (dir == 1) {
val c = count - if (onWordEnd && !hasSelection && (!(startSpace && isOuter) || startSpace && !isOuter)) 1 else 0
findNextWordEnd(editor, pos, c, isBig, !isOuter)
} else {
findNextWordEnd(editor, pos, 1, isBig, !isOuter)
}
}
if (logger.isDebugEnabled) logger.debug("end=$end")
var goBack = startSpace && !hasSelection || !startSpace && hasSelection && !onWordStart
if (dir == 1 && isOuter) {
var firstEnd = end
if (count > 1) {
firstEnd = findNextWordEnd(editor, pos, 1, isBig, false)
}
if (firstEnd < max - 1) {
if (charType(editor, chars[firstEnd + 1], false) !== CharacterHelper.CharacterType.WHITESPACE) {
goBack = true
}
}
}
if (dir == -1 && isOuter && startSpace) {
if (pos > min) {
if (charType(editor, chars[pos - 1], false) !== CharacterHelper.CharacterType.WHITESPACE) {
goBack = true
}
}
}
var goForward = dir == 1 && isOuter && (!startSpace && !onWordEnd || startSpace && onWordEnd && hasSelection)
if (!goForward && dir == 1 && isOuter) {
var firstEnd = end
if (count > 1) {
firstEnd = findNextWordEnd(editor, pos, 1, isBig, false)
}
if (firstEnd < max - 1) {
if (charType(editor, chars[firstEnd + 1], false) !== CharacterHelper.CharacterType.WHITESPACE) {
goForward = true
}
}
}
if (!goForward && dir == 1 && isOuter && !startSpace && !hasSelection) {
if (end < max - 1) {
if (charType(editor, chars[end + 1], !isBig) !==
charType(editor, chars[end], !isBig)
) {
goForward = true
}
}
}
if (logger.isDebugEnabled) {
logger.debug("goBack=$goBack")
logger.debug("goForward=$goForward")
}
if (goForward) {
if (editor.anyNonWhitespace(end, 1)) {
while (end + 1 < max &&
charType(editor, chars[end + 1], false) === CharacterHelper.CharacterType.WHITESPACE
) {
end++
}
}
}
if (goBack) {
if (editor.anyNonWhitespace(start, -1)) {
while (start > min &&
charType(editor, chars[start - 1], false) === CharacterHelper.CharacterType.WHITESPACE
) {
start--
}
}
}
if (logger.isDebugEnabled) {
logger.debug("start=$start")
logger.debug("end=$end")
}
// End offset is exclusive
return TextRange(start, end + 1)
}
override fun findBlockTagRange(editor: VimEditor, caret: ImmutableVimCaret, count: Int, isOuter: Boolean): TextRange? {
var counter = count
var isOuterVariable = isOuter
val position: Int = caret.ij.offset
val sequence: CharSequence = editor.ij.document.charsSequence
val selectionStart: Int = caret.ij.selectionStart
val selectionEnd: Int = caret.ij.selectionEnd
val isRangeSelection = selectionEnd - selectionStart > 1
var searchStartPosition: Int
searchStartPosition = if (!isRangeSelection) {
val line: Int = caret.ij.logicalPosition.line
val lineBegin: Int = editor.ij.document.getLineStartOffset(line)
ignoreWhitespaceAtLineStart(sequence, lineBegin, position)
} else {
selectionEnd
}
if (isInHTMLTag(sequence, searchStartPosition, false)) {
// caret is inside opening tag. Move to closing '>'.
while (searchStartPosition < sequence.length && sequence[searchStartPosition] != '>') {
searchStartPosition++
}
} else if (isInHTMLTag(sequence, searchStartPosition, true)) {
// caret is inside closing tag. Move to starting '<'.
while (searchStartPosition > 0 && sequence[searchStartPosition] != '<') {
searchStartPosition--
}
}
while (true) {
val (closingTagTextRange, tagName) = findUnmatchedClosingTag(sequence, searchStartPosition, counter)
?: return null
val openingTag = findUnmatchedOpeningTag(sequence, closingTagTextRange.startOffset, tagName)
?: return null
if (isRangeSelection && openingTag.endOffset - 1 >= selectionStart) {
// If there was already some text selected and the new selection would not extend further, we try again
searchStartPosition = closingTagTextRange.endOffset
counter = 1
continue
}
var selectionEndWithoutNewline = selectionEnd
while (selectionEndWithoutNewline < sequence.length && sequence[selectionEndWithoutNewline] == '\n') {
selectionEndWithoutNewline++
}
val mode = getInstance(editor).mode
if (mode is VISUAL) {
if (closingTagTextRange.startOffset == selectionEndWithoutNewline &&
openingTag.endOffset == selectionStart
) {
// 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
isOuterVariable = true
} else if (openingTag.endOffset == closingTagTextRange.startOffset &&
selectionStart == openingTag.endOffset
) {
// Special case: for an empty tag pair (e.g. <a></a>) the whole tag is selected if the caret is in the middle.
isOuterVariable = true
}
}
return if (isOuterVariable) {
TextRange(openingTag.startOffset, closingTagTextRange.endOffset)
} else {
TextRange(openingTag.endOffset, closingTagTextRange.startOffset)
}
}
}
/**
* returns new position which ignore whitespaces at beginning of the line
*/
private fun ignoreWhitespaceAtLineStart(seq: CharSequence, lineStart: Int, pos: Int): Int {
var position = pos
if (seq.subSequence(lineStart, position).chars().allMatch { codePoint: Int ->
Character.isWhitespace(
codePoint
)
}) {
while (position < seq.length && seq[position] != '\n' && Character.isWhitespace(seq[position])) {
position++
}
}
return position
}
/**
* Returns true if there is a html at the given position. Ignores tags with a trailing slash like <aaa></aaa>.
*/
private fun isInHTMLTag(sequence: CharSequence, position: Int, isEndtag: Boolean): Boolean {
var openingBracket = -1
run {
var i = position
while (i >= 0 && i < sequence.length) {
if (sequence[i] == '<') {
openingBracket = i
break
}
if (sequence[i] == '>' && i != position) {
return false
}
i--
}
}
if (openingBracket == -1) {
return false
}
val hasSlashAfterOpening = openingBracket + 1 < sequence.length && sequence[openingBracket + 1] == '/'
if (isEndtag && !hasSlashAfterOpening || !isEndtag && hasSlashAfterOpening) {
return false
}
var closingBracket = -1
for (i in openingBracket until sequence.length) {
if (sequence[i] == '>') {
closingBracket = i
break
}
}
return closingBracket != -1 && sequence[closingBracket - 1] != '/'
}
private fun findUnmatchedOpeningTag(
sequence: CharSequence,
position: Int,
tagName: String,
): TextRange? {
val quotedTagName = Pattern.quote(tagName)
val patternString = ("(</%s>)" // match closing tags
+
"|(<%s" // or opening tags starting with tagName
+
"(\\s([^>]*" // After at least one whitespace there might be additional text in the tag. E.g. <html lang="en">
+
"[^/])?)?>)") // Slash is not allowed as last character (this would be a self closing tag).
val tagPattern =
Pattern.compile(String.format(patternString, quotedTagName, quotedTagName), Pattern.CASE_INSENSITIVE)
val matcher = tagPattern.matcher(sequence.subSequence(0, position + 1))
val openTags: Deque<TextRange> = ArrayDeque()
while (matcher.find()) {
val match = TextRange(matcher.start(), matcher.end())
if (sequence[matcher.start() + 1] == '/') {
if (!openTags.isEmpty()) {
openTags.pop()
}
} else {
openTags.push(match)
}
}
return if (openTags.isEmpty()) {
null
} else {
openTags.pop()
}
}
private fun findUnmatchedClosingTag(
sequence: CharSequence,
position: Int,
count: Int,
): Pair<TextRange, String>? {
// The tag name may contain any characters except slashes, whitespace and '>'
var counter = count
val tagNamePattern = "([^/\\s>]+)"
// An opening tag consists of '<' followed by a tag name, optionally some additional text after whitespace and a '>'
val openingTagPattern = String.format("<%s(?:\\s[^>]*)?>", tagNamePattern)
val closingTagPattern = String.format("</%s>", tagNamePattern)
val tagPattern = Pattern.compile(String.format("(?:%s)|(?:%s)", openingTagPattern, closingTagPattern))
val matcher = tagPattern.matcher(sequence.subSequence(position, sequence.length))
val openTags: Deque<String> = ArrayDeque()
while (matcher.find()) {
val isClosingTag = matcher.group(1) == null
if (isClosingTag) {
val tagName = matcher.group(2)
// Ignore unmatched open tags. Either the file is malformed or it might be a tag like <br> that does not need to be closed.
while (!openTags.isEmpty() && !openTags.peek().equals(tagName, ignoreCase = true)) {
openTags.pop()
}
if (openTags.isEmpty()) {
if (counter <= 1) {
return Pair(TextRange(position + matcher.start(), position + matcher.end()), tagName)
} else {
counter--
}
} else {
openTags.pop()
}
} else {
val tagName = matcher.group(1)
openTags.push(tagName)
}
}
return null
}
override fun findBlockRange(
editor: VimEditor,
caret: ImmutableVimCaret,
type: Char,
count: Int,
isOuter: Boolean,
): TextRange? {
val chars: CharSequence = editor.ij.document.charsSequence
var pos: Int = caret.ij.offset
var start: Int = caret.ij.selectionStart
var end: Int = caret.ij.selectionEnd
val loc = BLOCK_CHARS.indexOf(type)
val close = BLOCK_CHARS[loc + 1]
// extend the range for blank line after type and before close, as they are excluded when inner match
if (!isOuter) {
if (start > 1 && chars[start - 2] == type && chars[start - 1] == '\n') {
start--
}
if (end < chars.length && chars[end] == '\n') {
var isSingleLineAllWhiteSpaceUntilClose = false
var countWhiteSpaceCharacter = 1
while (end + countWhiteSpaceCharacter < chars.length) {
if (Character.isWhitespace(chars[end + countWhiteSpaceCharacter]) &&
chars[end + countWhiteSpaceCharacter] != '\n'
) {
countWhiteSpaceCharacter++
continue
}
if (chars[end + countWhiteSpaceCharacter] == close) {
isSingleLineAllWhiteSpaceUntilClose = true
}
break
}
if (isSingleLineAllWhiteSpaceUntilClose) {
end += countWhiteSpaceCharacter
}
}
}
var rangeSelection = end - start > 1
if (rangeSelection && start == 0) // early return not only for optimization
{
return null // but also not to break the interval semantic on this edge case (see below)
}
/* In case of successive inner selection. We want to break out of
* the block delimiter of the current inner selection.
* In other terms, for the rest of the algorithm, a previous inner selection of a block
* if equivalent to an outer one. */
/* In case of successive inner selection. We want to break out of
* the block delimiter of the current inner selection.
* In other terms, for the rest of the algorithm, a previous inner selection of a block
* if equivalent to an outer one. */if (!isOuter && start - 1 >= 0 && type == chars[start - 1] && end < chars.length && close == chars[end]) {
start -= 1
pos = start
rangeSelection = true
}
/* when one char is selected, we want to find the enclosing block of (start,end]
* although when a range of characters is selected, we want the enclosing block of [start, end]
* shifting the position allow to express which kind of interval we work on */
/* when one char is selected, we want to find the enclosing block of (start,end]
* although when a range of characters is selected, we want the enclosing block of [start, end]
* shifting the position allow to express which kind of interval we work on */if (rangeSelection) pos =
max(0.0, (start - 1).toDouble()).toInt()
val initialPosIsInString = checkInString(chars, pos, true)
var bstart = -1
var bend = -1
var startPosInStringFound = false
if (initialPosIsInString) {
val quoteRange = injector.searchHelper
.findBlockQuoteInLineRange(editor, caret, '"', false)
if (quoteRange != null) {
val startOffset = quoteRange.startOffset
val endOffset = quoteRange.endOffset
val subSequence = chars.subSequence(startOffset, endOffset)
val inQuotePos = pos - startOffset
var inQuoteStart =
findBlockLocation(subSequence, close, type, Direction.BACKWARDS, inQuotePos, count)
if (inQuoteStart == -1) {
inQuoteStart =
findBlockLocation(subSequence, close, type, Direction.FORWARDS, inQuotePos, count)
}
if (inQuoteStart != -1) {
startPosInStringFound = true
val inQuoteEnd =
findBlockLocation(subSequence, type, close, Direction.FORWARDS, inQuoteStart, 1)
if (inQuoteEnd != -1) {
bstart = inQuoteStart + startOffset
bend = inQuoteEnd + startOffset
}
}
}
}
if (!startPosInStringFound) {
bstart = findBlockLocation(chars, close, type, Direction.BACKWARDS, pos, count)
if (bstart == -1) {
bstart = findBlockLocation(chars, close, type, Direction.FORWARDS, pos, count)
}
if (bstart != -1) {
bend = findBlockLocation(chars, type, close, Direction.FORWARDS, bstart, 1)
}
}
if (bstart == -1 || bend == -1) {
return null
}
if (!isOuter) {
bstart++
// exclude first line break after start for inner match
if (chars[bstart] == '\n') {
bstart++
}
val o = editor.getLineStartForOffset(bend)
var allWhite = true
for (i in o until bend) {
if (!Character.isWhitespace(chars[i])) {
allWhite = false
break
}
}
if (allWhite) {
bend = o - 2
} else {
bend--
}
}
// End offset exclusive
return TextRange(bstart, bend + 1)
}
override fun findMisspelledWord(editor: VimEditor, caret: ImmutableVimCaret, count: Int): Int { override fun findMisspelledWord(editor: VimEditor, caret: ImmutableVimCaret, count: Int): Int {
val startOffset: Int val startOffset: Int
val endOffset: Int val endOffset: Int
@@ -68,18 +700,17 @@ internal class IjVimSearchHelper : VimSearchHelperBase() {
if (count < 0) { if (count < 0) {
startOffset = 0 startOffset = 0
endOffset = caret.offset - 1 endOffset = caret.offset.point - 1
skipCount = -count - 1 skipCount = -count - 1
offsetOrdering = IntComparators.OPPOSITE_COMPARATOR offsetOrdering = IntComparators.OPPOSITE_COMPARATOR
} }
else { else {
startOffset = caret.offset + 1 startOffset = caret.offset.point + 1
endOffset = editor.ij.document.textLength endOffset = editor.ij.document.textLength
skipCount = count - 1 skipCount = count - 1
offsetOrdering = IntComparators.NATURAL_COMPARATOR offsetOrdering = IntComparators.NATURAL_COMPARATOR
} }
// TODO add it to PsiService
return SearchHelper.findMisspelledWords(editor.ij, startOffset, endOffset, skipCount, offsetOrdering) return SearchHelper.findMisspelledWords(editor.ij, startOffset, endOffset, skipCount, offsetOrdering)
} }
} }

View File

@@ -14,7 +14,17 @@ import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
internal class ActionTracker : CounterUsagesCollector() { internal class ActionTracker : CounterUsagesCollector() {
object Util { companion object {
private val GROUP = EventLogGroup("vim.actions", 1, "FUS")
private val TRACKED_ACTIONS = GROUP.registerEvent(
"tracked",
EventFields.StringValidatedByCustomRule("action_id", ActionRuleValidator::class.java),
)
private val COPIED_ACTIONS = GROUP.registerEvent(
"copied",
EventFields.StringValidatedByCustomRule("action_id", ActionRuleValidator::class.java),
)
fun logTrackedAction(actionId: String) { fun logTrackedAction(actionId: String) {
TRACKED_ACTIONS.log(actionId) TRACKED_ACTIONS.log(actionId)
} }
@@ -26,14 +36,3 @@ internal class ActionTracker : CounterUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP override fun getGroup(): EventLogGroup = GROUP
} }
private val GROUP = EventLogGroup("vim.actions", 1)
private val TRACKED_ACTIONS = GROUP.registerEvent(
"tracked",
EventFields.StringValidatedByCustomRule("action_id", ActionRuleValidator::class.java),
)
private val COPIED_ACTIONS = GROUP.registerEvent(
"copied",
EventFields.StringValidatedByCustomRule("action_id", ActionRuleValidator::class.java),
)

View File

@@ -47,28 +47,28 @@ internal class OptionsState : ApplicationUsagesCollector() {
) )
} }
} companion object {
private val GROUP = EventLogGroup("vim.options", 1, "FUS")
private val GROUP = EventLogGroup("vim.options", 1) private val IDEAJOIN = BooleanEventField(IjOptions.ideajoin.name)
private val IDEAJOIN = BooleanEventField(IjOptions.ideajoin.name) private val IDEAMARKS = BooleanEventField(IjOptions.ideamarks.name)
private val IDEAMARKS = BooleanEventField(IjOptions.ideamarks.name) private val IDEAREFACTOR = EventFields.String(IjOptions.idearefactormode.name, IjOptionConstants.ideaRefactorModeValues.toList())
private val IDEAREFACTOR = private val IDEAPUT = BooleanEventField(OptionConstants.clipboard_ideaput)
EventFields.String(IjOptions.idearefactormode.name, IjOptionConstants.ideaRefactorModeValues.toList()) private val IDEASTATUSICON = EventFields.String(IjOptions.ideastatusicon.name, IjOptionConstants.ideaStatusIconValues.toList())
private val IDEAPUT = BooleanEventField(OptionConstants.clipboard_ideaput) private val IDEAWRITE = EventFields.String(IjOptions.ideawrite.name, IjOptionConstants.ideaWriteValues.toList())
private val IDEASTATUSICON = private val IDEASELECTION = BooleanEventField(OptionConstants.selectmode_ideaselection)
EventFields.String(IjOptions.ideastatusicon.name, IjOptionConstants.ideaStatusIconValues.toList()) private val IDEAVIMSUPPORT = EventFields.StringList(IjOptions.ideavimsupport.name, IjOptionConstants.ideavimsupportValues.toList())
private val IDEAWRITE = EventFields.String(IjOptions.ideawrite.name, IjOptionConstants.ideaWriteValues.toList())
private val IDEASELECTION = BooleanEventField(OptionConstants.selectmode_ideaselection) private val OPTIONS: VarargEventId = GROUP.registerVarargEvent(
private val IDEAVIMSUPPORT = "vim.options",
EventFields.StringList(IjOptions.ideavimsupport.name, IjOptionConstants.ideavimsupportValues.toList()) IDEAJOIN,
private val OPTIONS: VarargEventId = GROUP.registerVarargEvent( IDEAMARKS,
"vim.options", IDEAREFACTOR,
IDEAJOIN, IDEAPUT,
IDEAMARKS, IDEASTATUSICON,
IDEAREFACTOR, IDEAWRITE,
IDEAPUT, IDEASELECTION,
IDEASTATUSICON, IDEAVIMSUPPORT,
IDEAWRITE, )
IDEASELECTION, }
IDEAVIMSUPPORT, }
)

View File

@@ -14,8 +14,6 @@ import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.VarargEventId import com.intellij.internal.statistic.eventLog.events.VarargEventId
import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector
import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.statistic.PluginState.Util.enabledExtensions
import com.maddyhome.idea.vim.statistic.PluginState.Util.extensionNames
import com.maddyhome.idea.vim.ui.JoinEap import com.maddyhome.idea.vim.ui.JoinEap
internal class PluginState : ApplicationUsagesCollector() { internal class PluginState : ApplicationUsagesCollector() {
@@ -32,32 +30,21 @@ internal class PluginState : ApplicationUsagesCollector() {
) )
} }
object Util { companion object {
internal val extensionNames = listOf( private val GROUP = EventLogGroup("vim.common", 1, "FUS")
"textobj-entire",
"argtextobj", val extensionNames = listOf("textobj-entire", "argtextobj", "ReplaceWithRegister", "vim-paragraph-motion", "highlightedyank", "multiple-cursors", "exchange", "NERDTree", "surround", "commentary", "matchit", "textobj-indent")
"ReplaceWithRegister", val enabledExtensions = HashSet<String>()
"vim-paragraph-motion",
"highlightedyank", private val PLUGIN_ENABLED = EventFields.Boolean("is_plugin_enabled")
"multiple-cursors", private val IS_EAP = EventFields.Boolean("is_EAP_active")
"exchange", private val ENABLED_EXTENSIONS = EventFields.StringList("enabled_extensions", extensionNames)
"NERDTree",
"surround", private val PLUGIN_STATE: VarargEventId = GROUP.registerVarargEvent(
"commentary", "vim.common",
"matchit", PLUGIN_ENABLED,
"textobj-indent" IS_EAP,
ENABLED_EXTENSIONS,
) )
internal val enabledExtensions = HashSet<String>()
} }
} }
private val GROUP = EventLogGroup("vim.common", 1)
private val PLUGIN_ENABLED = EventFields.Boolean("is_plugin_enabled")
private val IS_EAP = EventFields.Boolean("is_EAP_active")
private val ENABLED_EXTENSIONS = EventFields.StringList("enabled_extensions", extensionNames)
private val PLUGIN_STATE: VarargEventId = GROUP.registerVarargEvent(
"vim.common",
PLUGIN_ENABLED,
IS_EAP,
ENABLED_EXTENSIONS,
)

View File

@@ -70,6 +70,95 @@ internal class ShortcutConflictState : ApplicationUsagesCollector() {
} }
} }
} }
companion object {
private val GROUP = EventLogGroup("vim.handlers", 1, "FUS")
private val keyStrokes = listOf(
KeyStroke.getKeyStroke('1'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('2'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('3'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('4'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('5'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('6'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('7'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('8'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('9'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('0'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('1'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('2'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('3'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('4'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('5'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('6'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('7'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('8'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('9'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('0'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('A'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('B'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('C'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('D'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('E'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('F'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('G'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('H'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('I'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('J'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('K'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('L'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('M'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('N'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('O'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('P'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('Q'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('R'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('S'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('T'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('U'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('V'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('W'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('X'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('Y'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('Z'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('['.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke(']'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('A'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('B'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('C'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('D'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('E'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('F'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('G'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('H'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('I'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('J'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('K'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('L'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('M'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('N'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('O'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('P'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('Q'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('R'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('S'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('T'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('U'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('V'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('W'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('X'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('Y'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('Z'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('['.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke(']'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
)
private val KEY_STROKE = EventFields.String("key_stroke", keyStrokes.map { it.toReadableString() })
private val HANDLER_MODE = EventFields.Enum<HandledModes>("handler")
private val HANDLER = GROUP.registerEvent("vim.handler", KEY_STROKE, HANDLER_MODE)
}
} }
private fun KeyStroke.toReadableString(): String { private fun KeyStroke.toReadableString(): String {
@@ -98,89 +187,3 @@ private enum class HandledModes {
VISUAL_AND_SELECT_IDE, VISUAL_AND_SELECT_IDE,
VISUAL_AND_SELECT_VIM, VISUAL_AND_SELECT_VIM,
} }
private val GROUP = EventLogGroup("vim.handlers", 1)
private val keyStrokes = listOf(
KeyStroke.getKeyStroke('1'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('2'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('3'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('4'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('5'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('6'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('7'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('8'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('9'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('0'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('1'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('2'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('3'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('4'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('5'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('6'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('7'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('8'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('9'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('0'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('A'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('B'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('C'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('D'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('E'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('F'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('G'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('H'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('I'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('J'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('K'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('L'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('M'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('N'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('O'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('P'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('Q'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('R'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('S'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('T'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('U'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('V'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('W'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('X'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('Y'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('Z'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('['.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke(']'.code, CTRL_DOWN_MASK),
KeyStroke.getKeyStroke('A'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('B'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('C'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('D'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('E'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('F'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('G'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('H'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('I'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('J'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('K'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('L'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('M'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('N'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('O'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('P'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('Q'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('R'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('S'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('T'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('U'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('V'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('W'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('X'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('Y'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('Z'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke('['.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
KeyStroke.getKeyStroke(']'.code, CTRL_DOWN_MASK + SHIFT_DOWN_MASK),
)
private val KEY_STROKE = EventFields.String("key_stroke", keyStrokes.map { it.toReadableString() })
private val HANDLER_MODE = EventFields.Enum<HandledModes>("handler")
private val HANDLER = GROUP.registerEvent("vim.handler", KEY_STROKE, HANDLER_MODE)

View File

@@ -13,7 +13,6 @@ import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.VarargEventId import com.intellij.internal.statistic.eventLog.events.VarargEventId
import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector
import com.maddyhome.idea.vim.statistic.PluginState.Util.extensionNames
import com.maddyhome.idea.vim.vimscript.services.VimRcService import com.maddyhome.idea.vim.vimscript.services.VimRcService
internal class VimscriptState : ApplicationUsagesCollector() { internal class VimscriptState : ApplicationUsagesCollector() {
@@ -23,56 +22,56 @@ internal class VimscriptState : ApplicationUsagesCollector() {
override fun getMetrics(): Set<MetricEvent> { override fun getMetrics(): Set<MetricEvent> {
return setOf( return setOf(
VIMSCRIPT.metric( VIMSCRIPT.metric(
SOURCED_FILES with Util.sourcedFiles.size, SOURCED_FILES with sourcedFiles.size,
IDEAVIMRC_SIZE with (VimRcService.findIdeaVimRc()?.readLines()?.filter { !it.matches(Regex("\\s*\".*")) && it.isNotBlank() }?.size ?: -1), IDEAVIMRC_SIZE with (VimRcService.findIdeaVimRc()?.readLines()?.filter { !it.matches(Regex("\\s*\".*")) && it.isNotBlank() }?.size ?: -1),
EXTENSIONS_ENABLED_BY_SET with (PluginState.Util.enabledExtensions - Util.extensionsEnabledWithPlug).toList(), EXTENSIONS_ENABLED_BY_SET with (PluginState.enabledExtensions - extensionsEnabledWithPlug).toList(),
EXTENSIONS_ENABLED_BY_PLUG with Util.extensionsEnabledWithPlug.toList(), EXTENSIONS_ENABLED_BY_PLUG with extensionsEnabledWithPlug.toList(),
IS_IDE_SPECIFIC_CONFIGURATION_USED with Util.isIDESpecificConfigurationUsed, IS_IDE_SPECIFIC_CONFIGURATION_USED with isIDESpecificConfigurationUsed,
IS_LOOP_USED with Util.isLoopUsed, IS_LOOP_USED with isLoopUsed,
IS_IF_USED with Util.isIfUsed, IS_IF_USED with isIfUsed,
IS_MAP_EXPR_USED with Util.isMapExprUsed, IS_MAP_EXPR_USED with isMapExprUsed,
IS_FUNCTION_DEF_USED with Util.isFunctionDeclarationUsed, IS_FUNCTION_DEF_USED with isFunctionDeclarationUsed,
IS_FUNCTION_CALL_USED with Util.isFunctionCallUsed, IS_FUNCTION_CALL_USED with isFunctionCallUsed,
), ),
) )
} }
object Util { companion object {
private val GROUP = EventLogGroup("vim.vimscript", 1, "FUS")
val sourcedFiles = HashSet<String>() val sourcedFiles = HashSet<String>()
val extensionsEnabledWithPlug = HashSet<String>() val extensionsEnabledWithPlug = HashSet<String>()
var isIDESpecificConfigurationUsed = false var isIDESpecificConfigurationUsed = false
var isLoopUsed = false var isLoopUsed = false
var isIfUsed = false var isIfUsed = false
var isMapExprUsed = false var isMapExprUsed = false
var isFunctionDeclarationUsed = false var isFunctionDeclarationUsed = false
var isFunctionCallUsed = false var isFunctionCallUsed = false
private val SOURCED_FILES = EventFields.RoundedInt("number_of_sourced_files")
private val IDEAVIMRC_SIZE = EventFields.RoundedInt("ideavimrc_size")
private val EXTENSIONS_ENABLED_BY_SET = EventFields.StringList("extensions_enabled_by_set", PluginState.extensionNames)
private val EXTENSIONS_ENABLED_BY_PLUG = EventFields.StringList("extensions_enabled_by_plug", PluginState.extensionNames)
private val IS_IDE_SPECIFIC_CONFIGURATION_USED = EventFields.Boolean("is_IDE-specific_configuration_used")
private val IS_LOOP_USED = EventFields.Boolean("is_loop_used")
private val IS_IF_USED = EventFields.Boolean("is_if_used")
private val IS_MAP_EXPR_USED = EventFields.Boolean("is_map_expr_used")
private val IS_FUNCTION_DEF_USED = EventFields.Boolean("is_function_declaration_used")
private val IS_FUNCTION_CALL_USED = EventFields.Boolean("is_function_call_used")
private val VIMSCRIPT: VarargEventId = GROUP.registerVarargEvent(
"vim.vimscript",
SOURCED_FILES,
IDEAVIMRC_SIZE,
EXTENSIONS_ENABLED_BY_SET,
EXTENSIONS_ENABLED_BY_PLUG,
IS_IDE_SPECIFIC_CONFIGURATION_USED,
IS_LOOP_USED,
IS_IF_USED,
IS_MAP_EXPR_USED,
IS_FUNCTION_DEF_USED,
IS_FUNCTION_CALL_USED,
)
} }
} }
private val GROUP = EventLogGroup("vim.vimscript", 1)
private val SOURCED_FILES = EventFields.RoundedInt("number_of_sourced_files")
private val IDEAVIMRC_SIZE = EventFields.RoundedInt("ideavimrc_size")
private val EXTENSIONS_ENABLED_BY_SET = EventFields.StringList("extensions_enabled_by_set", extensionNames)
private val EXTENSIONS_ENABLED_BY_PLUG = EventFields.StringList("extensions_enabled_by_plug", extensionNames)
private val IS_IDE_SPECIFIC_CONFIGURATION_USED = EventFields.Boolean("is_IDE-specific_configuration_used")
private val IS_LOOP_USED = EventFields.Boolean("is_loop_used")
private val IS_IF_USED = EventFields.Boolean("is_if_used")
private val IS_MAP_EXPR_USED = EventFields.Boolean("is_map_expr_used")
private val IS_FUNCTION_DEF_USED = EventFields.Boolean("is_function_declaration_used")
private val IS_FUNCTION_CALL_USED = EventFields.Boolean("is_function_call_used")
private val VIMSCRIPT: VarargEventId = GROUP.registerVarargEvent(
"vim.vimscript",
SOURCED_FILES,
IDEAVIMRC_SIZE,
EXTENSIONS_ENABLED_BY_SET,
EXTENSIONS_ENABLED_BY_PLUG,
IS_IDE_SPECIFIC_CONFIGURATION_USED,
IS_LOOP_USED,
IS_IF_USED,
IS_MAP_EXPR_USED,
IS_FUNCTION_DEF_USED,
IS_FUNCTION_CALL_USED,
)

Some files were not shown because too many files have changed in this diff Show More