diff --git a/README.de.md b/README.de.md new file mode 100644 index 0000000..930ac3a --- /dev/null +++ b/README.de.md @@ -0,0 +1,98 @@ +# Textual TCSS Support für PyCharm + +Dieses Projekt ist ein PyCharm-Plugin für Textual CSS. Es ordnet Dateien mit der Endung `.tcss` einer eigenen Sprache zu und behandelt außerdem String-Werte von `CSS` und `DEFAULT_CSS`-Zuweisungen in Python-Dateien als TCSS. Beide Varianten unterstützen Syntaxfarben, Strukturprüfung, Vervollständigung und Dokumentation. + +## Funktionen + +- Syntaxfarben für Selektoren, Eigenschaftsnamen, Werte, Variablen, Zahlen, Kommentare und Klammern. +- Prüfung von Regeln und Deklarationen. Fehler wie fehlende `{`, `}`, `:` oder `;` werden im Editor markiert. +- Warnung bei Eigenschaftsnamen, die nicht in der eingebauten Textual-Styles-Referenz stehen. +- Completion für die dokumentierten Textual-Stile und häufige Werte. +- Quick Documentation für Stil-Eigenschaften mit Beschreibungen in der gewählten Meldungssprache. Je nach PyCharm-Einstellung erscheint sie beim Hover oder über **View | Quick Documentation** (`Ctrl+Q`, auf macOS `F1`). +- Farbschema-Einträge unter **Settings | Editor | Color Scheme | Textual CSS**. +- TCSS-Unterstützung in Python-Strings, die `CSS` oder `DEFAULT_CSS` zugewiesen werden. Andere Python-Strings bleiben unverändert. +- Eigene Syntaxfarben für Eigenschaftsnamen, Werte und Maßeinheiten wie `fr` oder `%`. +- TCSS-Variablendeklarationen wie `$border: wide green;`, mit Warnungen bei mehrfach deklarierten Variablen. +- Variablen in `margin`- und `padding`-Werten werden für die Prüfung der erlaubten Gesamtanzahl aufgelöst. +- Eigene Syntaxfarbe für `!important`. +- Einstellbare Sprache für Parser- und Prüfmeldungen: Englisch (Standard) oder Deutsch. Die Einstellung **Textual TCSS** ist in den PyCharm-Einstellungen auffindbar. +- Prüfung auf die in der Textual-8.2.8-Quellcode-Referenz aufgeführten Properties, gültige Werte und erlaubte Wertanzahlen. Eingebaute und im TCSS definierte Variablen werden als Werte akzeptiert. + +Die Prüfung umfasst die 93 Style-Properties aus `textual_8_2_8_tcss_style_reference_source.md` sowie `margin-top`, `margin-right`, `margin-bottom`, `margin-left` und die entsprechenden vier `padding-*`-Properties, die Textuals Parser ebenfalls unterstützt. Eigenschaftswerte und Wertanzahlen werden anhand der Referenz geprüft. + +## Voraussetzungen + +- PyCharm 2024.3 oder neuer (Community-Funktionen sind ausreichend). +- Für den Plugin-Build: JDK 21 und Internetzugriff für den ersten Gradle-Build. +- Für die Installation des fertigen Plugins: keine separate Python- oder Textual-Installation. + +Das Plugin benötigt weder einen Textual-Laufzeitprozess noch das Python-Plugin. Es prüft TCSS-Regeln lokal anhand der Editor-Syntax und der eingebauten Eigenschaftsliste. + +## Plugin bauen + +Im Projektordner ausführen: + +```bash +./gradlew buildPlugin +``` + +Unter Windows: + +```powershell +.\gradlew.bat buildPlugin +``` + +Das installierbare Plugin-ZIP entsteht hier: + +```text +build/distributions/textual-tcss-1.2.10.zip +``` + +Gradle lädt beim ersten Build die benötigten Gradle- und PyCharm-Komponenten herunter. Der Build kann einige Minuten dauern. Für einen lokalen Entwicklungslauf steht außerdem `./gradlew runIde` beziehungsweise `.gradlew.bat runIde` bereit. + +## Plugin in PyCharm installieren + +1. Baue das Plugin wie oben beschrieben oder besorge die Datei `textual-tcss-1.2.10.zip` aus `build/distributions/`. +2. Öffne PyCharm. +3. Öffne **Settings** (Windows/Linux: **File | Settings**, macOS: **PyCharm | Settings**). +4. Wähle **Plugins**. +5. Öffne das Zahnrad-Menü und wähle **Install Plugin from Disk…**. +6. Wähle `textual-tcss-1.2.10.zip`. Die ZIP-Datei vorher nicht entpacken. +7. Bestätige die Installation und starte PyCharm neu, wenn PyCharm dazu auffordert. +8. Öffne eine `.tcss`-Datei oder eine Python-Datei mit einer `CSS`- oder `DEFAULT_CSS`-Zuweisung. PyCharm sollte die entsprechenden TCSS-Inhalte mit Textual-CSS-Unterstützung anzeigen. + +Alternativ kann eine ZIP-Datei auch auf der Plugin-Seite unter **Plugins | Installed | ⚙ | Install Plugin from Disk…** ausgewählt werden. Die Menübezeichnungen unterscheiden sich je nach PyCharm-Sprache leicht. + +## Kurzes Beispiel + +```css +#dialog .button:hover { + width: 1fr; + height: 3; + color: $text; + border: round cyan; +} +``` + +In Python kann TCSS beispielsweise so eingebettet werden: + +```python +class MyApp: + CSS = """ + Screen { align: center middle; } + """ + + DEFAULT_CSS = """ + Button { color: $text; } + """ +``` + +## Entwicklung + +- Hauptquellcode: `src/main/java/de/textualtcss/intellij/` +- Plugin-Registrierung: `src/main/resources/META-INF/plugin.xml` +- Plugin-ID: `de.textualtcss.intellij` +- Version: `1.2.10` +- TCSS-Eigenschaftskatalog: Textual `8.2.8` + +Die IntelliJ Platform Gradle Plugin-Tasks (`buildPlugin`, `runIde`) verwalten Verpackung und lokale IDE-Sandbox. diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..34978e1 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,38 @@ +plugins { + id("org.jetbrains.intellij.platform") version "2.19.0" +} + +group = "de.textualtcss" +version = "1.2.10" + +repositories { + mavenCentral() + intellijPlatform { defaultRepositories() } +} + +dependencies { + intellijPlatform { + // Unified PyCharm (2025.3+) is the target IDE. No Python plugin dependency is needed. + pycharm("2025.2.4") + } +} + +intellijPlatform { + pluginConfiguration { + name = "Textual TCSS Support" + version = project.version.toString() + description = "Syntax highlighting, Textual 8.2.8 property and value validation, completion and quick documentation for .tcss and Python CSS/DEFAULT_CSS strings." + ideaVersion { + sinceBuild = "243" + } + vendor { + name = "Textual TCSS Community" + } + } +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..df1fac8 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 +org.gradle.caching=true +org.gradle.configuration-cache=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..2c35211 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..23449a2 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9b42019 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..9c065d4 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,8 @@ +pluginManagement { + repositories { + gradlePluginPortal() + mavenCentral() + } +} + +rootProject.name = "textual-tcss" diff --git a/src/main/java/de/textualtcss/intellij/TcssAnnotator.java b/src/main/java/de/textualtcss/intellij/TcssAnnotator.java new file mode 100644 index 0000000..8ff48a9 --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssAnnotator.java @@ -0,0 +1,128 @@ +package de.textualtcss.intellij; + +import com.intellij.lang.annotation.AnnotationHolder; +import com.intellij.lang.annotation.Annotator; +import com.intellij.lang.annotation.HighlightSeverity; +import com.intellij.psi.PsiElement; +import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.psi.tree.IElementType; +import org.jetbrains.annotations.NotNull; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +public final class TcssAnnotator implements Annotator { + @Override public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { + if (element instanceof TcssVariableDeclaration declaration) { + warnOnDuplicateVariable(declaration, holder); + Map definitions = variableDefinitions(declaration); + String variableProblem = TcssValueValidator.validateVariableReferences( + declaration.getValueText(), definitions.keySet()); + if (variableProblem != null) { + holder.newAnnotation(HighlightSeverity.WARNING, variableProblem) + .range(declaration.getValueRange()) + .create(); + } + return; + } + if (element instanceof TcssSelector) { + holder.newSilentAnnotation(HighlightSeverity.INFORMATION) + .range(element.getTextRange()) + .textAttributes(TcssSyntaxHighlighter.SELECTOR) + .create(); + return; + } + if (!(element instanceof TcssDeclaration declaration)) return; + + highlightDeclaration(declaration, holder); + String property = declaration.getPropertyName(); + if (property.isEmpty()) return; + if (TcssStyles.description(property) == null) { + holder.newAnnotation(HighlightSeverity.WARNING, TcssMessages.message("validation.unknownProperty", property)) + .range(declaration.getPropertyRange()) + .create(); + return; + } + + Map definitions = variableDefinitions(declaration); + String valueProblem = TcssValueValidator.validate(property, declaration.getValueText(), definitions.keySet(), definitions); + if (valueProblem != null) { + holder.newAnnotation(HighlightSeverity.WARNING, valueProblem) + .range(declaration.getValueRange()) + .create(); + } + } + + private static Map variableDefinitions(PsiElement element) { + Map definitions = new LinkedHashMap<>(); + for (TcssVariableDeclaration variable : PsiTreeUtil.findChildrenOfType(element.getContainingFile(), TcssVariableDeclaration.class)) { + definitions.putIfAbsent(variable.getVariableName(), variable.getValueText()); + } + return definitions; + } + + private static void warnOnDuplicateVariable(TcssVariableDeclaration declaration, AnnotationHolder holder) { + String name = declaration.getVariableName(); + PsiElement variableToken = declaration.getVariableToken(); + if (name.isEmpty() || variableToken == null) return; + + int declarationOffset = declaration.getTextRange().getStartOffset(); + for (TcssVariableDeclaration other : PsiTreeUtil.findChildrenOfType(declaration.getContainingFile(), TcssVariableDeclaration.class)) { + if (other == declaration || !name.equals(other.getVariableName())) continue; + if (other.getTextRange().getStartOffset() < declarationOffset) { + holder.newAnnotation(HighlightSeverity.WARNING, TcssMessages.message("validation.duplicateVariable", name)) + .range(variableToken.getTextRange()) + .create(); + return; + } + } + } + + private static void highlightDeclaration(TcssDeclaration declaration, AnnotationHolder holder) { + boolean inValue = false; + PsiElement previousToken = null; + boolean propertyHighlighted = false; + + for (PsiElement child = declaration.getFirstChild(); child != null; child = child.getNextSibling()) { + IElementType type = child.getNode().getElementType(); + if (type == TcssTypes.COLON) { + inValue = true; + previousToken = child; + continue; + } + if (child.getTextLength() == 0 || child.getText().isBlank()) continue; + + if (!inValue) { + if (!propertyHighlighted && type == TcssTypes.IDENTIFIER) { + holder.newSilentAnnotation(HighlightSeverity.INFORMATION) + .range(child.getTextRange()) + .textAttributes(TcssSyntaxHighlighter.PROPERTY) + .create(); + propertyHighlighted = true; + } + previousToken = child; + continue; + } + + if (type == TcssTypes.IDENTIFIER) { + boolean unit = previousToken != null + && previousToken.getNode().getElementType() == TcssTypes.NUMBER + && previousToken.getTextRange().getEndOffset() == child.getTextRange().getStartOffset(); + holder.newSilentAnnotation(HighlightSeverity.INFORMATION) + .range(child.getTextRange()) + .textAttributes(unit ? TcssSyntaxHighlighter.UNIT : TcssSyntaxHighlighter.VALUE) + .create(); + } else if (type == TcssTypes.OPERATOR && "%".equals(child.getText()) + && previousToken != null + && previousToken.getNode().getElementType() == TcssTypes.NUMBER + && previousToken.getTextRange().getEndOffset() == child.getTextRange().getStartOffset()) { + holder.newSilentAnnotation(HighlightSeverity.INFORMATION) + .range(child.getTextRange()) + .textAttributes(TcssSyntaxHighlighter.UNIT) + .create(); + } + previousToken = child; + } + } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssColorSettingsPage.java b/src/main/java/de/textualtcss/intellij/TcssColorSettingsPage.java new file mode 100644 index 0000000..3cd4ad1 --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssColorSettingsPage.java @@ -0,0 +1,38 @@ +package de.textualtcss.intellij; + +import com.intellij.openapi.fileTypes.SyntaxHighlighter; +import com.intellij.openapi.options.colors.AttributesDescriptor; +import com.intellij.openapi.options.colors.ColorDescriptor; +import com.intellij.openapi.options.colors.ColorSettingsPage; +import com.intellij.openapi.editor.colors.TextAttributesKey; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.Icon; +import java.util.Map; + +public final class TcssColorSettingsPage implements ColorSettingsPage { + private static final AttributesDescriptor[] ATTRIBUTES = { + new AttributesDescriptor("Selector", TcssSyntaxHighlighter.SELECTOR), + new AttributesDescriptor("Property", TcssSyntaxHighlighter.PROPERTY), + new AttributesDescriptor("Value", TcssSyntaxHighlighter.VALUE), + new AttributesDescriptor("Measurement unit", TcssSyntaxHighlighter.UNIT), + new AttributesDescriptor("!important", TcssSyntaxHighlighter.IMPORTANT), + new AttributesDescriptor("Variable", TcssSyntaxHighlighter.VARIABLE), + new AttributesDescriptor("Number", TcssSyntaxHighlighter.NUMBER), + new AttributesDescriptor("Comment", TcssSyntaxHighlighter.COMMENT), + new AttributesDescriptor("Braces", TcssSyntaxHighlighter.BRACES), + new AttributesDescriptor("Operator", TcssSyntaxHighlighter.OPERATOR), + new AttributesDescriptor("Invalid character", TcssSyntaxHighlighter.BAD) + }; + + @Override public @Nullable Icon getIcon() { return null; } + @Override public @NotNull SyntaxHighlighter getHighlighter() { return new TcssSyntaxHighlighter(); } + @Override public @NotNull String getDisplayName() { return "Textual CSS"; } + @Override public @NotNull AttributesDescriptor[] getAttributeDescriptors() { return ATTRIBUTES; } + @Override public @NotNull ColorDescriptor[] getColorDescriptors() { return ColorDescriptor.EMPTY_ARRAY; } + @Override public @NotNull String getDemoText() { + return "/* Textual CSS */\n$border: wide green;\n#dialog .button {\n width: 1fr;\n height: 3;\n color: $text;\n border: round cyan !important;\n}\n"; + } + @Override public @Nullable Map getAdditionalHighlightingTagToDescriptorMap() { return null; } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssCompletionContributor.java b/src/main/java/de/textualtcss/intellij/TcssCompletionContributor.java new file mode 100644 index 0000000..e2d3aed --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssCompletionContributor.java @@ -0,0 +1,26 @@ +package de.textualtcss.intellij; + +import com.intellij.codeInsight.completion.CompletionContributor; +import com.intellij.codeInsight.completion.CompletionParameters; +import com.intellij.codeInsight.completion.CompletionProvider; +import com.intellij.codeInsight.completion.CompletionResultSet; +import com.intellij.codeInsight.completion.CompletionType; +import com.intellij.codeInsight.lookup.LookupElementBuilder; +import com.intellij.patterns.PlatformPatterns; +import com.intellij.util.ProcessingContext; +import org.jetbrains.annotations.NotNull; + +public final class TcssCompletionContributor extends CompletionContributor { + public TcssCompletionContributor() { + extend(CompletionType.BASIC, PlatformPatterns.psiElement().withLanguage(TcssLanguage.INSTANCE), new CompletionProvider<>() { + @Override protected void addCompletions(@NotNull CompletionParameters parameters, @NotNull ProcessingContext context, @NotNull CompletionResultSet result) { + for (var entry : TcssStyles.all().entrySet()) { + result.addElement(LookupElementBuilder.create(entry.getKey()).withTypeText("Textual style").withTailText(" " + entry.getValue(), true)); + } + for (String value : new String[]{"auto", "none", "solid", "round", "heavy", "dashed", "top", "right", "bottom", "left", "horizontal", "vertical", "center", "middle", "bold", "italic", "underline", "hidden", "visible", "scroll", "overlay", "relative", "absolute"}) { + result.addElement(LookupElementBuilder.create(value).withTypeText("Textual value")); + } + } + }); + } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssConfigurable.java b/src/main/java/de/textualtcss/intellij/TcssConfigurable.java new file mode 100644 index 0000000..8d04f8a --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssConfigurable.java @@ -0,0 +1,79 @@ +package de.textualtcss.intellij; + +import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; +import com.intellij.openapi.options.Configurable; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.project.ProjectManager; +import org.jetbrains.annotations.Nls; +import org.jetbrains.annotations.Nullable; + +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import java.awt.BorderLayout; + +public final class TcssConfigurable implements Configurable { + private JPanel panel; + private JComboBox languageCombo; + + @Override public @Nls String getDisplayName() { + return "Textual TCSS"; + } + + @Override public @Nullable JComponent createComponent() { + panel = new JPanel(new BorderLayout(8, 0)); + panel.add(new JLabel("Diagnostic language / Sprache der Fehlermeldungen:"), BorderLayout.WEST); + languageCombo = new JComboBox<>(new LanguageOption[]{ + new LanguageOption(TcssSettings.GERMAN, "Deutsch"), + new LanguageOption(TcssSettings.ENGLISH, "English") + }); + panel.add(languageCombo, BorderLayout.CENTER); + return panel; + } + + @Override public boolean isModified() { + LanguageOption selected = (LanguageOption) languageCombo.getSelectedItem(); + return selected != null && !selected.code.equals(TcssSettings.getInstance().getDiagnosticLanguage()); + } + + @Override public void apply() { + LanguageOption selected = (LanguageOption) languageCombo.getSelectedItem(); + if (selected == null) return; + TcssSettings settings = TcssSettings.getInstance(); + if (selected.code.equals(settings.getDiagnosticLanguage())) return; + settings.setDiagnosticLanguage(selected.code); + for (Project project : ProjectManager.getInstance().getOpenProjects()) { + if (!project.isDisposed()) DaemonCodeAnalyzer.getInstance(project).restart(); + } + } + + @Override public void reset() { + String language = TcssSettings.getInstance().getDiagnosticLanguage(); + for (int i = 0; i < languageCombo.getItemCount(); i++) { + if (language.equals(languageCombo.getItemAt(i).code)) { + languageCombo.setSelectedIndex(i); + return; + } + } + } + + @Override public void disposeUIResources() { + panel = null; + languageCombo = null; + } + + private static final class LanguageOption { + private final String code; + private final String label; + + private LanguageOption(String code, String label) { + this.code = code; + this.label = label; + } + + @Override public String toString() { + return label; + } + } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssDeclaration.java b/src/main/java/de/textualtcss/intellij/TcssDeclaration.java new file mode 100644 index 0000000..737da2d --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssDeclaration.java @@ -0,0 +1,64 @@ +package de.textualtcss.intellij; + +import com.intellij.extapi.psi.ASTWrapperPsiElement; +import com.intellij.lang.ASTNode; +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.PsiElement; +import org.jetbrains.annotations.NotNull; + +public final class TcssDeclaration extends ASTWrapperPsiElement { + public TcssDeclaration(@NotNull ASTNode node) { super(node); } + public String getPropertyName() { + StringBuilder name = new StringBuilder(); + for (PsiElement child = getFirstChild(); child != null; child = child.getNextSibling()) { + if (child.getNode().getElementType() == TcssTypes.COLON) break; + if (!child.getText().isBlank()) name.append(child.getText()); + } + return name.toString().toLowerCase(java.util.Locale.ROOT); + } + + public TextRange getPropertyRange() { + PsiElement first = null; + PsiElement last = null; + for (PsiElement child = getFirstChild(); child != null; child = child.getNextSibling()) { + if (child.getNode().getElementType() == TcssTypes.COLON) break; + if (child.getText().isBlank()) continue; + if (first == null) first = child; + last = child; + } + return first == null ? getTextRange() : new TextRange(first.getTextRange().getStartOffset(), last.getTextRange().getEndOffset()); + } + + public String getValueText() { + StringBuilder value = new StringBuilder(); + boolean inValue = false; + for (PsiElement child = getFirstChild(); child != null; child = child.getNextSibling()) { + if (child.getNode().getElementType() == TcssTypes.COLON) { + inValue = true; + continue; + } + if (!inValue) continue; + if (child.getNode().getElementType() == TcssTypes.SEMICOLON) break; + value.append(child.getText()); + } + return value.toString(); + } + + public TextRange getValueRange() { + PsiElement first = null; + PsiElement last = null; + boolean inValue = false; + for (PsiElement child = getFirstChild(); child != null; child = child.getNextSibling()) { + if (child.getNode().getElementType() == TcssTypes.COLON) { + inValue = true; + continue; + } + if (!inValue) continue; + if (child.getNode().getElementType() == TcssTypes.SEMICOLON) break; + if (child.getText().isBlank()) continue; + if (first == null) first = child; + last = child; + } + return first == null ? getTextRange() : new TextRange(first.getTextRange().getStartOffset(), last.getTextRange().getEndOffset()); + } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssDocumentationProvider.java b/src/main/java/de/textualtcss/intellij/TcssDocumentationProvider.java new file mode 100644 index 0000000..0ac4835 --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssDocumentationProvider.java @@ -0,0 +1,44 @@ +package de.textualtcss.intellij; + +import com.intellij.lang.documentation.AbstractDocumentationProvider; +import com.intellij.psi.PsiElement; +import org.jetbrains.annotations.Nullable; + +public final class TcssDocumentationProvider extends AbstractDocumentationProvider { + @Override + public @Nullable String generateDoc(PsiElement element, @Nullable PsiElement originalElement) { + String name = element.getText().trim(); + if (element.getParent() instanceof TcssDeclaration declaration) name = declaration.getPropertyName(); + String description = TcssStyles.description(name); + if (description == null) description = valueDescription(name); + if (description == null) return null; + String slug = name.toLowerCase(java.util.Locale.ROOT); + String url = TcssStyles.description(name) == null + ? "https://textual.textualize.io/guide/CSS/" + : "https://textual.textualize.io/styles/" + slug + "/"; + return "" + escape(name) + "

" + escape(description) + "

" + + escape(TcssMessages.message("documentation.link")) + "

"; + } + + @Override + public @Nullable String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) { + String doc = generateDoc(element, originalElement); + return doc == null ? null : doc.replaceAll("<[^>]+>", " ").replaceAll("\\s+", " ").trim(); + } + + private static String valueDescription(String raw) { + return switch (raw.toLowerCase(java.util.Locale.ROOT)) { + case "1fr" -> TcssMessages.message("documentation.value.fr"); + case "auto" -> TcssMessages.message("documentation.value.auto"); + case "!important" -> TcssMessages.message("documentation.value.important"); + case "hover" -> TcssMessages.message("documentation.value.hover"); + case "focus" -> TcssMessages.message("documentation.value.focus"); + case "dark", "light" -> TcssMessages.message("documentation.value.themeColor"); + default -> null; + }; + } + + private static String escape(String value) { + return value.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """); + } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssFile.java b/src/main/java/de/textualtcss/intellij/TcssFile.java new file mode 100644 index 0000000..161a69f --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssFile.java @@ -0,0 +1,11 @@ +package de.textualtcss.intellij; + +import com.intellij.extapi.psi.PsiFileBase; +import com.intellij.psi.FileViewProvider; +import org.jetbrains.annotations.NotNull; + +public final class TcssFile extends PsiFileBase { + protected TcssFile(@NotNull FileViewProvider viewProvider) { super(viewProvider, TcssLanguage.INSTANCE); } + @Override public @NotNull TcssFileType getFileType() { return TcssFileType.INSTANCE; } + @Override public String toString() { return "Textual CSS file"; } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssFileType.java b/src/main/java/de/textualtcss/intellij/TcssFileType.java new file mode 100644 index 0000000..b2f9754 --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssFileType.java @@ -0,0 +1,19 @@ +package de.textualtcss.intellij; + +import com.intellij.openapi.fileTypes.LanguageFileType; +import org.jetbrains.annotations.NotNull; + +import javax.swing.Icon; + +public final class TcssFileType extends LanguageFileType { + public static final TcssFileType INSTANCE = new TcssFileType(); + + private TcssFileType() { + super(TcssLanguage.INSTANCE); + } + + @Override public @NotNull String getName() { return "Textual CSS"; } + @Override public @NotNull String getDescription() { return "Textual CSS stylesheet"; } + @Override public @NotNull String getDefaultExtension() { return "tcss"; } + @Override public Icon getIcon() { return null; } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssLanguage.java b/src/main/java/de/textualtcss/intellij/TcssLanguage.java new file mode 100644 index 0000000..98265cf --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssLanguage.java @@ -0,0 +1,11 @@ +package de.textualtcss.intellij; + +import com.intellij.lang.Language; + +public final class TcssLanguage extends Language { + public static final TcssLanguage INSTANCE = new TcssLanguage(); + + private TcssLanguage() { + super("TCSS"); + } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssLexer.java b/src/main/java/de/textualtcss/intellij/TcssLexer.java new file mode 100644 index 0000000..3741bb7 --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssLexer.java @@ -0,0 +1,96 @@ +package de.textualtcss.intellij; + +import com.intellij.lexer.LexerBase; +import com.intellij.psi.TokenType; +import com.intellij.psi.tree.IElementType; +import com.intellij.util.text.CharArrayUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import static de.textualtcss.intellij.TcssTypes.*; + +public final class TcssLexer extends LexerBase { + private CharSequence buffer = ""; + private int endOffset; + private int tokenStart; + private int tokenEnd; + private IElementType tokenType; + + @Override public void start(@NotNull CharSequence buffer, int startOffset, int endOffset, int initialState) { + this.buffer = buffer; + this.endOffset = endOffset; + this.tokenStart = startOffset; + locateToken(); + } + + private void locateToken() { + if (tokenStart >= endOffset) { + tokenType = null; + tokenEnd = endOffset; + return; + } + char c = buffer.charAt(tokenStart); + tokenEnd = tokenStart + 1; + if (Character.isWhitespace(c)) { + tokenEnd = tokenStart + 1; + while (tokenEnd < endOffset && Character.isWhitespace(buffer.charAt(tokenEnd))) tokenEnd++; + tokenType = TokenType.WHITE_SPACE; + } else if (c == '/' && tokenStart + 1 < endOffset && buffer.charAt(tokenStart + 1) == '*') { + int close = CharArrayUtil.indexOf(buffer, "*/", tokenStart + 2, endOffset); + tokenEnd = close < 0 ? endOffset : close + 2; + tokenType = COMMENT; + } else if (c == '!' && isImportantAt(tokenStart)) { + tokenEnd = tokenStart + "!important".length(); + tokenType = IMPORTANT; + } else if (c == '"' || c == '\'') { + char quote = c; + boolean escaped = false; + while (tokenEnd < endOffset) { + char next = buffer.charAt(tokenEnd++); + if (next == quote && !escaped) break; + if (next == '\\' && !escaped) escaped = true; else escaped = false; + } + tokenType = STRING; + } else if (c == '$') { + while (tokenEnd < endOffset && isName(buffer.charAt(tokenEnd))) tokenEnd++; + tokenType = VARIABLE; + } else if (Character.isDigit(c) || (c == '.' && tokenStart + 1 < endOffset && Character.isDigit(buffer.charAt(tokenStart + 1)))) { + while (tokenEnd < endOffset && (Character.isDigit(buffer.charAt(tokenEnd)) || buffer.charAt(tokenEnd) == '.')) tokenEnd++; + tokenType = NUMBER; + } else if (isName(c)) { + while (tokenEnd < endOffset && isName(buffer.charAt(tokenEnd))) tokenEnd++; + tokenType = IDENTIFIER; + } else { + tokenType = switch (c) { + case '{', '}' -> BRACES; + case '(', ')' -> PARENTHESES; + case '.' -> DOT; + case '#' -> HASH; + case ':' -> COLON; + case ';' -> SEMICOLON; + case ',' -> COMMA; + case '>', '+', '~', '&', '*', '!', '/', '%', '=', '@' -> OPERATOR; + default -> BAD_CHARACTER; + }; + } + } + + private static boolean isName(char c) { + return Character.isLetterOrDigit(c) || c == '-' || c == '_' || c >= 128; + } + + private boolean isImportantAt(int offset) { + String keyword = "!important"; + int keywordEnd = offset + keyword.length(); + if (keywordEnd > endOffset || !buffer.subSequence(offset, keywordEnd).toString().equalsIgnoreCase(keyword)) return false; + return keywordEnd == endOffset || !isName(buffer.charAt(keywordEnd)); + } + + @Override public int getState() { return 0; } + @Override public @Nullable IElementType getTokenType() { return tokenType; } + @Override public int getTokenStart() { return tokenStart; } + @Override public int getTokenEnd() { return tokenEnd; } + @Override public void advance() { tokenStart = tokenEnd; locateToken(); } + @Override public @NotNull CharSequence getBufferSequence() { return buffer; } + @Override public int getBufferEnd() { return endOffset; } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssMessages.java b/src/main/java/de/textualtcss/intellij/TcssMessages.java new file mode 100644 index 0000000..53f7006 --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssMessages.java @@ -0,0 +1,33 @@ +package de.textualtcss.intellij; + +import java.util.Locale; +import java.util.ResourceBundle; + +public final class TcssMessages { + private TcssMessages() {} + + public static String message(String key, Object... parameters) { + String template = bundle().getString(key); + return format(template, parameters); + } + + public static String localizedOrDefault(String key, String defaultValue) { + ResourceBundle bundle = bundle(); + return bundle.containsKey(key) ? bundle.getString(key) : defaultValue; + } + + private static String format(String template, Object... parameters) { + for (int i = 0; i < parameters.length; i++) { + template = template.replace("{" + i + "}", String.valueOf(parameters[i])); + } + return template; + } + + private static ResourceBundle bundle() { + String language = TcssSettings.getInstance().getDiagnosticLanguage(); + Locale locale = Locale.forLanguageTag(language); + ResourceBundle.Control noLocaleFallback = ResourceBundle.Control.getNoFallbackControl(ResourceBundle.Control.FORMAT_DEFAULT); + return ResourceBundle.getBundle("messages.TcssMessages", locale, + TcssMessages.class.getClassLoader(), noLocaleFallback); + } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssParser.java b/src/main/java/de/textualtcss/intellij/TcssParser.java new file mode 100644 index 0000000..b16f4e3 --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssParser.java @@ -0,0 +1,107 @@ +package de.textualtcss.intellij; + +import com.intellij.lang.PsiBuilder; +import com.intellij.lang.PsiParser; +import com.intellij.psi.tree.IElementType; +import com.intellij.psi.tree.TokenSet; +import org.jetbrains.annotations.NotNull; + +import static de.textualtcss.intellij.TcssTypes.*; + +public final class TcssParser implements PsiParser { + private static final TokenSet TRIVIA = TokenSet.create(com.intellij.psi.TokenType.WHITE_SPACE, COMMENT); + + @Override + public @NotNull com.intellij.lang.ASTNode parse(@NotNull IElementType root, @NotNull PsiBuilder builder) { + PsiBuilder.Marker file = builder.mark(); + while (!builder.eof()) { + skipTrivia(builder); + if (builder.eof()) break; + if (is(builder, "}")) { + builder.error(TcssMessages.message("parser.unexpectedClosingBrace")); + builder.advanceLexer(); + } else if (builder.getTokenType() == VARIABLE) { + parseVariableDeclaration(builder); + } else { + parseRule(builder); + } + } + file.done(FILE); + return builder.getTreeBuilt(); + } + + private static void parseVariableDeclaration(PsiBuilder builder) { + PsiBuilder.Marker declaration = builder.mark(); + builder.advanceLexer(); // variable name + boolean colonSeen = false; + while (!builder.eof() && !is(builder, ";") && !is(builder, "{") && !is(builder, "}")) { + if (is(builder, ":")) colonSeen = true; + builder.advanceLexer(); + } + if (!colonSeen) builder.error(TcssMessages.message("parser.variableColon")); + if (!consume(builder, ";")) builder.error(TcssMessages.message("parser.variableSemicolon")); + declaration.done(VARIABLE_DECLARATION); + } + + private static void parseRule(PsiBuilder builder) { + PsiBuilder.Marker rule = builder.mark(); + PsiBuilder.Marker selector = builder.mark(); + boolean selectorContent = false; + while (!builder.eof() && !is(builder, "{") && !is(builder, "}")) { + if (!TRIVIA.contains(builder.getTokenType())) selectorContent = true; + builder.advanceLexer(); + } + if (!selectorContent) selector.error(TcssMessages.message("parser.missingSelector")); else selector.done(SELECTOR); + if (!consume(builder, "{")) { + builder.error(TcssMessages.message("parser.expectedOpeningBrace")); + rule.done(RULE); + if (!builder.eof()) builder.advanceLexer(); + return; + } + + while (!builder.eof() && !is(builder, "}")) { + skipTrivia(builder); + if (builder.eof() || is(builder, "}")) break; + parseDeclaration(builder); + } + if (!consume(builder, "}")) builder.error(TcssMessages.message("parser.missingClosingBrace")); + rule.done(RULE); + } + + private static void parseDeclaration(PsiBuilder builder) { + PsiBuilder.Marker declaration = builder.mark(); + boolean colonSeen = false; + boolean contentSeen = false; + while (!builder.eof() && !is(builder, ";") && !is(builder, "}")) { + if (is(builder, "{")) { + declaration.rollbackTo(); + parseRule(builder); + return; + } + if (is(builder, ":")) colonSeen = true; + if (!TRIVIA.contains(builder.getTokenType())) contentSeen = true; + builder.advanceLexer(); + } + if (!contentSeen) { + declaration.drop(); + return; + } + if (!colonSeen) builder.error(TcssMessages.message("parser.declarationColon")); + if (!consume(builder, ";")) builder.error(TcssMessages.message("parser.declarationSemicolon")); + declaration.done(DECLARATION); + } + + private static void skipTrivia(PsiBuilder builder) { + while (!builder.eof() && TRIVIA.contains(builder.getTokenType())) builder.advanceLexer(); + } + + private static boolean is(PsiBuilder builder, String text) { + return !builder.eof() && text.equals(builder.getTokenText()); + } + + private static boolean consume(PsiBuilder builder, String text) { + if (!is(builder, text)) return false; + builder.advanceLexer(); + return true; + } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssParserDefinition.java b/src/main/java/de/textualtcss/intellij/TcssParserDefinition.java new file mode 100644 index 0000000..7cda250 --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssParserDefinition.java @@ -0,0 +1,33 @@ +package de.textualtcss.intellij; + +import com.intellij.lang.ASTNode; +import com.intellij.lang.ParserDefinition; +import com.intellij.lang.PsiParser; +import com.intellij.lexer.Lexer; +import com.intellij.openapi.project.Project; +import com.intellij.psi.FileViewProvider; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import com.intellij.psi.tree.IFileElementType; +import com.intellij.psi.tree.TokenSet; +import org.jetbrains.annotations.NotNull; + +import static de.textualtcss.intellij.TcssTypes.*; + +public final class TcssParserDefinition implements ParserDefinition { + @Override public @NotNull Lexer createLexer(Project project) { return new TcssLexer(); } + @Override public @NotNull PsiParser createParser(Project project) { return new TcssParser(); } + @Override public @NotNull IFileElementType getFileNodeType() { return FILE; } + @Override public @NotNull TokenSet getCommentTokens() { return TokenSet.create(COMMENT); } + @Override public @NotNull TokenSet getStringLiteralElements() { return TokenSet.create(STRING); } + @Override public @NotNull PsiElement createElement(@NotNull ASTNode node) { + if (node.getElementType() == DECLARATION) return new TcssDeclaration(node); + if (node.getElementType() == VARIABLE_DECLARATION) return new TcssVariableDeclaration(node); + if (node.getElementType() == SELECTOR) return new TcssSelector(node); + return new com.intellij.extapi.psi.ASTWrapperPsiElement(node); + } + @Override public @NotNull PsiFile createFile(@NotNull FileViewProvider viewProvider) { return new TcssFile(viewProvider); } + @Override public @NotNull SpaceRequirements spaceExistanceTypeBetweenTokens(ASTNode left, ASTNode right) { + return SpaceRequirements.MAY; + } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssPythonStringInjector.java b/src/main/java/de/textualtcss/intellij/TcssPythonStringInjector.java new file mode 100644 index 0000000..ca09e69 --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssPythonStringInjector.java @@ -0,0 +1,69 @@ +package de.textualtcss.intellij; + +import com.intellij.lang.Language; +import com.intellij.lang.injection.MultiHostInjector; +import com.intellij.lang.injection.MultiHostRegistrar; +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.ElementManipulators; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiLanguageInjectionHost; +import org.jetbrains.annotations.NotNull; + +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** Injects TCSS into Textual's in-code CSS declarations, without affecting other Python strings. */ +public final class TcssPythonStringInjector implements MultiHostInjector { + private static final Pattern CSS_ASSIGNMENT = Pattern.compile("^(?:CSS|DEFAULT_CSS)\\s*(?::[^=]+)?="); + + @Override + public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) { + if (!(context instanceof PsiLanguageInjectionHost host) + || !host.isValidHost() + || !context.getLanguage().isKindOf("Python")) { + return; + } + + PsiElement assignment = findCssAssignment(context); + if (assignment == null || !isOnRightHandSide(context, assignment)) { + return; + } + + TextRange valueRange = ElementManipulators.getValueTextRange(context); + if (valueRange.isEmpty()) { + return; + } + + registrar.startInjecting(TcssLanguage.INSTANCE); + registrar.addPlace(null, null, host, valueRange); + registrar.doneInjecting(); + } + + private static PsiElement findCssAssignment(PsiElement element) { + for (PsiElement current = element.getParent(); current != null; current = current.getParent()) { + String text = current.getText(); + Matcher matcher = CSS_ASSIGNMENT.matcher(text); + if (matcher.find()) { + return current; + } + // An enclosing class or function cannot be the assignment we're looking for. + if (text.indexOf('\n') >= 0 && !text.startsWith(" ") && !text.startsWith("\t")) { + return null; + } + } + return null; + } + + private static boolean isOnRightHandSide(PsiElement element, PsiElement assignment) { + int assignmentOffset = assignment.getTextRange().getStartOffset(); + int elementOffset = element.getTextRange().getStartOffset(); + Matcher matcher = CSS_ASSIGNMENT.matcher(assignment.getText()); + return matcher.find() && elementOffset >= assignmentOffset + matcher.end(); + } + + @Override + public @NotNull List> elementsToInjectIn() { + return List.of(PsiLanguageInjectionHost.class); + } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssSelector.java b/src/main/java/de/textualtcss/intellij/TcssSelector.java new file mode 100644 index 0000000..dae0bbf --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssSelector.java @@ -0,0 +1,9 @@ +package de.textualtcss.intellij; + +import com.intellij.extapi.psi.ASTWrapperPsiElement; +import com.intellij.lang.ASTNode; +import org.jetbrains.annotations.NotNull; + +public final class TcssSelector extends ASTWrapperPsiElement { + public TcssSelector(@NotNull ASTNode node) { super(node); } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssSettings.java b/src/main/java/de/textualtcss/intellij/TcssSettings.java new file mode 100644 index 0000000..295f863 --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssSettings.java @@ -0,0 +1,41 @@ +package de.textualtcss.intellij; + +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.components.PersistentStateComponent; +import com.intellij.openapi.components.State; +import com.intellij.openapi.components.Storage; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@State(name = "TextualTcssSettings", storages = @Storage("TextualTcssSettings.xml")) +public final class TcssSettings implements PersistentStateComponent { + public static final String GERMAN = "de"; + public static final String ENGLISH = "en"; + + public static class State { + public String diagnosticLanguage = ENGLISH; + } + + private State state = new State(); + + public static TcssSettings getInstance() { + return ApplicationManager.getApplication().getService(TcssSettings.class); + } + + public String getDiagnosticLanguage() { + return state.diagnosticLanguage; + } + + public void setDiagnosticLanguage(String language) { + state.diagnosticLanguage = GERMAN.equals(language) ? GERMAN : ENGLISH; + } + + @Override public @NotNull State getState() { + return state; + } + + @Override public void loadState(@NotNull State state) { + this.state = state; + setDiagnosticLanguage(state.diagnosticLanguage); + } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssStyles.java b/src/main/java/de/textualtcss/intellij/TcssStyles.java new file mode 100644 index 0000000..0692693 --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssStyles.java @@ -0,0 +1,159 @@ +package de.textualtcss.intellij; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; +import java.util.TreeMap; + +/** Textual 8.2.8 RulesMap properties plus side-specific spacing properties supported by its CSS parser. */ +public final class TcssStyles { + public static final String TEXTUAL_REFERENCE_VERSION = "8.2.8"; + private static final String GENERIC_DESCRIPTION = "__generic_description__"; + + private static final Map STYLES = new TreeMap<>(); + private TcssStyles() {} + + static { + // Property names are transcribed from the attached Textual 8.2.8 RULE_NAMES reference. + // The Python source's snake_case names are exposed to TCSS as kebab-case names. + addNames(""" + display visibility layout auto-color color background text-style background-tint + opacity text-opacity padding margin offset position border border-top border-right + border-bottom border-left border-title-align border-subtitle-align outline outline-top + outline-right outline-bottom outline-left keyline box-sizing width height min-width + min-height max-width max-height dock split overflow-x overflow-y layers layer transitions + tint scrollbar-color scrollbar-color-hover scrollbar-color-active scrollbar-corner-color + scrollbar-background scrollbar-background-hover scrollbar-background-active scrollbar-gutter + scrollbar-size-vertical scrollbar-size-horizontal scrollbar-visibility align-horizontal + align-vertical align content-align-horizontal content-align-vertical content-align + grid-rows grid-columns grid-size-columns grid-size-rows grid-gutter-horizontal + grid-gutter-vertical row-span column-span text-align link-color auto-link-color + link-background link-style link-color-hover auto-link-color-hover link-background-hover + link-style-hover auto-border-title-color border-title-color border-title-background + border-title-style auto-border-subtitle-color border-subtitle-color + border-subtitle-background border-subtitle-style hatch overlay constrain-x constrain-y + text-wrap text-overflow expand line-pad pointer + """); + + // The Textual stylesheet parser also supports these individual spacing edges. + addNames(""" + margin-top margin-right margin-bottom margin-left + padding-top padding-right padding-bottom padding-left + """); + + describe("align", "Align a widget horizontally and vertically in its container."); + describe("align-horizontal", "Horizontal alignment of a widget: left, center or right."); + describe("align-vertical", "Vertical alignment of a widget: top, middle or bottom."); + describe("auto-border-subtitle-color", "Automatically choose a contrasting subtitle color."); + describe("auto-border-title-color", "Automatically choose a contrasting title color."); + describe("auto-color", "Automatically choose a readable foreground color for the background."); + describe("auto-link-color", "Automatically choose a link color with sufficient contrast."); + describe("auto-link-color-hover", "Automatically choose a contrasting link color while hovered."); + describe("background", "Background color of the widget."); + describe("background-tint", "Tint applied over the widget background."); + describe("border", "Set the border on all four sides."); + describe("border-bottom", "Border style and color for the bottom edge."); + describe("border-left", "Border style and color for the left edge."); + describe("border-right", "Border style and color for the right edge."); + describe("border-top", "Border style and color for the top edge."); + describe("box-sizing", "Choose whether width and height include padding and border."); + describe("color", "Foreground color of the widget content."); + describe("constrain-x", "Constrain a widget horizontally within its parent or screen."); + describe("constrain-y", "Constrain a widget vertically within its parent or screen."); + describe("content-align", "Align content horizontally and vertically inside the widget."); + describe("content-align-horizontal", "Horizontal alignment of the widget's content."); + describe("content-align-vertical", "Vertical alignment of the widget's content."); + describe("display", "Show or remove the widget from layout using block or none."); + describe("dock", "Dock a widget to an edge: top, right, bottom or left."); + describe("expand", "Choose how the widget expands to use available layout space."); + describe("grid-columns", "Column sizes used by a grid layout."); + describe("grid-gutter-horizontal", "Horizontal spacing between grid columns."); + describe("grid-gutter-vertical", "Vertical spacing between grid rows."); + describe("grid-rows", "Row sizes used by a grid layout."); + describe("grid-size-columns", "Number of columns in the grid."); + describe("grid-size-rows", "Number of rows in the grid."); + describe("hatch", "Pattern and color used to hatch an area."); + describe("height", "Widget height in cells, fractions, percentages or auto."); + describe("keyline", "Draw a keyline between children in a horizontal or vertical layout."); + describe("layer", "Name of the layer used to render the widget."); + describe("layers", "Ordered layer names available to the screen."); + describe("layout", "Layout strategy for the widget's children, such as vertical, horizontal, grid or stream."); + describe("line-pad", "Additional horizontal padding applied to each text line."); + describe("link-background", "Background color of links."); + describe("link-background-hover", "Background color of links while hovered."); + describe("link-color", "Text color of links."); + describe("link-color-hover", "Text color of links while hovered."); + describe("link-style", "Text style of links."); + describe("link-style-hover", "Text style of links while hovered."); + describe("margin", "Outer spacing; accepts one, two or four values."); + describe("margin-top", "Top outer spacing of the widget."); + describe("margin-right", "Right outer spacing of the widget."); + describe("margin-bottom", "Bottom outer spacing of the widget."); + describe("margin-left", "Left outer spacing of the widget."); + describe("max-height", "Maximum widget height."); + describe("max-width", "Maximum widget width."); + describe("min-height", "Minimum widget height."); + describe("min-width", "Minimum widget width."); + describe("offset", "Move a widget from its normal position."); + describe("opacity", "Opacity from 0 (transparent) to 1 (opaque), or a percentage."); + describe("outline", "Set the outline on all four sides outside the border."); + describe("outline-bottom", "Outline style and color for the bottom edge."); + describe("outline-left", "Outline style and color for the left edge."); + describe("outline-right", "Outline style and color for the right edge."); + describe("outline-top", "Outline style and color for the top edge."); + describe("overflow-x", "How overflowing content is handled horizontally."); + describe("overflow-y", "How overflowing content is handled vertically."); + describe("overlay", "Render a widget as an overlay, optionally over the screen."); + describe("padding", "Inner spacing; accepts one, two or four values."); + describe("padding-top", "Top inner spacing between the border and content."); + describe("padding-right", "Right inner spacing between the border and content."); + describe("padding-bottom", "Bottom inner spacing between the border and content."); + describe("padding-left", "Left inner spacing between the border and content."); + describe("pointer", "Mouse pointer shape shown when hovering over a widget."); + describe("position", "Choose relative or absolute positioning."); + describe("scrollbar-background", "Scrollbar track background color."); + describe("scrollbar-background-active", "Scrollbar track color while active."); + describe("scrollbar-background-hover", "Scrollbar track color while hovered."); + describe("scrollbar-color", "Scrollbar thumb color."); + describe("scrollbar-color-active", "Scrollbar thumb color while active."); + describe("scrollbar-color-hover", "Scrollbar thumb color while hovered."); + describe("scrollbar-corner-color", "Color of the corner where scrollbars meet."); + describe("scrollbar-gutter", "Choose whether space is reserved for scrollbars."); + describe("scrollbar-size-horizontal", "Horizontal scrollbar thickness in cells."); + describe("scrollbar-size-vertical", "Vertical scrollbar thickness in cells."); + describe("scrollbar-visibility", "Control whether scrollbars are visible."); + describe("split", "Split a container from a docked edge."); + describe("text-align", "Align text within the widget."); + describe("text-opacity", "Opacity applied to text without fading the widget background."); + describe("text-overflow", "How text is shortened when it does not fit."); + describe("text-style", "Apply bold, italic, underline, strike, reverse or no text styling."); + describe("text-wrap", "Choose whether text wraps at the widget boundary."); + describe("tint", "Tint applied over the widget contents."); + describe("transitions", "Configure animated transitions for supported style properties."); + describe("visibility", "Show or hide the widget while retaining its layout space."); + describe("width", "Widget width in cells, fractions, percentages or auto."); + } + + private static void addNames(String names) { + for (String name : names.trim().split("\\s+")) { + STYLES.put(name, GENERIC_DESCRIPTION); + } + } + + private static void describe(String name, String description) { STYLES.put(name, description); } + + public static Map all() { + Map localized = new LinkedHashMap<>(); + for (String name : STYLES.keySet()) localized.put(name, description(name)); + return Collections.unmodifiableMap(localized); + } + + public static String description(String name) { + String key = name.toLowerCase(Locale.ROOT); + String description = STYLES.get(key); + if (description == null) return null; + if (GENERIC_DESCRIPTION.equals(description)) return TcssMessages.message("style.generic", TEXTUAL_REFERENCE_VERSION); + return TcssMessages.localizedOrDefault("style." + key, description); + } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssSyntaxHighlighter.java b/src/main/java/de/textualtcss/intellij/TcssSyntaxHighlighter.java new file mode 100644 index 0000000..1107062 --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssSyntaxHighlighter.java @@ -0,0 +1,43 @@ +package de.textualtcss.intellij; + +import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; +import com.intellij.openapi.editor.HighlighterColors; +import com.intellij.openapi.editor.colors.TextAttributesKey; +import com.intellij.openapi.fileTypes.SyntaxHighlighterBase; +import com.intellij.psi.TokenType; +import com.intellij.psi.tree.IElementType; +import org.jetbrains.annotations.NotNull; + +import static de.textualtcss.intellij.TcssTypes.*; + +public final class TcssSyntaxHighlighter extends SyntaxHighlighterBase { + public static final TextAttributesKey SELECTOR = TextAttributesKey.createTextAttributesKey("TCSS_SELECTOR", DefaultLanguageHighlighterColors.CLASS_NAME); + public static final TextAttributesKey PROPERTY = TextAttributesKey.createTextAttributesKey("TCSS_PROPERTY", DefaultLanguageHighlighterColors.INSTANCE_FIELD); + public static final TextAttributesKey VALUE = TextAttributesKey.createTextAttributesKey("TCSS_VALUE", DefaultLanguageHighlighterColors.STRING); + public static final TextAttributesKey UNIT = TextAttributesKey.createTextAttributesKey("TCSS_UNIT", DefaultLanguageHighlighterColors.KEYWORD); + public static final TextAttributesKey IMPORTANT = TextAttributesKey.createTextAttributesKey("TCSS_IMPORTANT", DefaultLanguageHighlighterColors.METADATA); + public static final TextAttributesKey VARIABLE = TextAttributesKey.createTextAttributesKey("TCSS_VARIABLE", DefaultLanguageHighlighterColors.METADATA); + public static final TextAttributesKey NUMBER = TextAttributesKey.createTextAttributesKey("TCSS_NUMBER", DefaultLanguageHighlighterColors.NUMBER); + public static final TextAttributesKey COMMENT = TextAttributesKey.createTextAttributesKey("TCSS_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT); + public static final TextAttributesKey BRACES = TextAttributesKey.createTextAttributesKey("TCSS_BRACES", DefaultLanguageHighlighterColors.BRACES); + public static final TextAttributesKey DOT = TextAttributesKey.createTextAttributesKey("TCSS_DOT", DefaultLanguageHighlighterColors.DOT); + public static final TextAttributesKey HASH = TextAttributesKey.createTextAttributesKey("TCSS_HASH", DefaultLanguageHighlighterColors.OPERATION_SIGN); + public static final TextAttributesKey OPERATOR = TextAttributesKey.createTextAttributesKey("TCSS_OPERATOR", DefaultLanguageHighlighterColors.OPERATION_SIGN); + public static final TextAttributesKey BAD = TextAttributesKey.createTextAttributesKey("TCSS_BAD_CHARACTER", HighlighterColors.BAD_CHARACTER); + + @Override public @NotNull com.intellij.lexer.Lexer getHighlightingLexer() { return new TcssLexer(); } + @Override public @NotNull TextAttributesKey[] getTokenHighlights(IElementType tokenType) { + if (tokenType == IDENTIFIER) return pack(VALUE); + if (tokenType == TcssTypes.VARIABLE) return pack(VARIABLE); + if (tokenType == TcssTypes.NUMBER) return pack(NUMBER); + if (tokenType == TcssTypes.IMPORTANT) return pack(IMPORTANT); + if (tokenType == STRING) return pack(VALUE); + if (tokenType == TcssTypes.COMMENT) return pack(COMMENT); + if (tokenType == TcssTypes.BRACES || tokenType == TcssTypes.PARENTHESES) return pack(BRACES); + if (tokenType == TcssTypes.DOT) return pack(DOT); + if (tokenType == TcssTypes.HASH) return pack(HASH); + if (tokenType == TcssTypes.OPERATOR || tokenType == TcssTypes.COLON || tokenType == TcssTypes.SEMICOLON || tokenType == TcssTypes.COMMA) return pack(OPERATOR); + if (tokenType == BAD_CHARACTER || tokenType == TokenType.BAD_CHARACTER) return pack(BAD); + return TextAttributesKey.EMPTY_ARRAY; + } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssSyntaxHighlighterFactory.java b/src/main/java/de/textualtcss/intellij/TcssSyntaxHighlighterFactory.java new file mode 100644 index 0000000..ecc8861 --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssSyntaxHighlighterFactory.java @@ -0,0 +1,14 @@ +package de.textualtcss.intellij; + +import com.intellij.openapi.fileTypes.SyntaxHighlighter; +import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public final class TcssSyntaxHighlighterFactory extends SyntaxHighlighterFactory { + @Override public @NotNull SyntaxHighlighter getSyntaxHighlighter(@Nullable Project project, @Nullable VirtualFile virtualFile) { + return new TcssSyntaxHighlighter(); + } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssTypes.java b/src/main/java/de/textualtcss/intellij/TcssTypes.java new file mode 100644 index 0000000..d2f3d4f --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssTypes.java @@ -0,0 +1,27 @@ +package de.textualtcss.intellij; + +import com.intellij.psi.tree.IElementType; +import com.intellij.psi.tree.IFileElementType; + +public interface TcssTypes { + IFileElementType FILE = new IFileElementType(TcssLanguage.INSTANCE); + IElementType RULE = new IElementType("TCSS_RULE", TcssLanguage.INSTANCE); + IElementType SELECTOR = new IElementType("TCSS_SELECTOR", TcssLanguage.INSTANCE); + IElementType DECLARATION = new IElementType("TCSS_DECLARATION", TcssLanguage.INSTANCE); + IElementType VARIABLE_DECLARATION = new IElementType("TCSS_VARIABLE_DECLARATION", TcssLanguage.INSTANCE); + IElementType IDENTIFIER = new IElementType("TCSS_IDENTIFIER", TcssLanguage.INSTANCE); + IElementType VARIABLE = new IElementType("TCSS_VARIABLE", TcssLanguage.INSTANCE); + IElementType NUMBER = new IElementType("TCSS_NUMBER", TcssLanguage.INSTANCE); + IElementType STRING = new IElementType("TCSS_STRING", TcssLanguage.INSTANCE); + IElementType COMMENT = new IElementType("TCSS_COMMENT", TcssLanguage.INSTANCE); + IElementType BRACES = new IElementType("TCSS_BRACES", TcssLanguage.INSTANCE); + IElementType PARENTHESES = new IElementType("TCSS_PARENTHESES", TcssLanguage.INSTANCE); + IElementType DOT = new IElementType("TCSS_DOT", TcssLanguage.INSTANCE); + IElementType HASH = new IElementType("TCSS_HASH", TcssLanguage.INSTANCE); + IElementType COLON = new IElementType("TCSS_COLON", TcssLanguage.INSTANCE); + IElementType SEMICOLON = new IElementType("TCSS_SEMICOLON", TcssLanguage.INSTANCE); + IElementType COMMA = new IElementType("TCSS_COMMA", TcssLanguage.INSTANCE); + IElementType OPERATOR = new IElementType("TCSS_OPERATOR", TcssLanguage.INSTANCE); + IElementType IMPORTANT = new IElementType("TCSS_IMPORTANT", TcssLanguage.INSTANCE); + IElementType BAD_CHARACTER = new IElementType("TCSS_BAD_CHARACTER", TcssLanguage.INSTANCE); +} diff --git a/src/main/java/de/textualtcss/intellij/TcssValueValidator.java b/src/main/java/de/textualtcss/intellij/TcssValueValidator.java new file mode 100644 index 0000000..5de9221 --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssValueValidator.java @@ -0,0 +1,388 @@ +package de.textualtcss.intellij; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** Value and arity checks transcribed from the Textual 8.2.8 TCSS style reference. */ +public final class TcssValueValidator { + private static final String VARIABLE_VALUE = "__tcss_variable_value__"; + private static final Pattern VARIABLE = Pattern.compile("\\$[A-Za-z0-9_-]+"); + private static final Pattern SCALAR = Pattern.compile("-?\\d+\\.?\\d*(?:fr|%|w|h|vw|vh)?|auto", Pattern.CASE_INSENSITIVE); + private static final Pattern INTEGER = Pattern.compile("-?\\d+"); + private static final Pattern PERCENT = Pattern.compile("\\d+(?:\\.\\d+)?%"); + private static final Pattern RGB = Pattern.compile("rgba?\\(\\s*[-+]?\\d+(?:\\.\\d+)?\\s*,\\s*[-+]?\\d+(?:\\.\\d+)?\\s*,\\s*[-+]?\\d+(?:\\.\\d+)?(?:\\s*,\\s*[-+]?\\d+(?:\\.\\d+)?\\s*)?\\)", Pattern.CASE_INSENSITIVE); + private static final Pattern HSL = Pattern.compile("hsla?\\(\\s*[-+]?\\d+(?:\\.\\d+)?\\s*,\\s*\\d+(?:\\.\\d+)?%\\s*,\\s*\\d+(?:\\.\\d+)?%(?:\\s*,\\s*[-+]?\\d+(?:\\.\\d+)?\\s*)?\\)", Pattern.CASE_INSENSITIVE); + private static final Pattern IMPORTANT_SUFFIX = Pattern.compile("\\s*!important\\s*$", Pattern.CASE_INSENSITIVE); + + private static final Set BOOLEANS = Set.of("true", "false"); + private static final Set LAYOUTS = Set.of("vertical", "horizontal", "grid", "stream"); + private static final Set ALIGN_X = Set.of("left", "center", "right"); + private static final Set ALIGN_Y = Set.of("top", "middle", "bottom"); + private static final Set ALIGN_TEXT = Set.of("start", "end", "left", "right", "center", "justify"); + private static final Set BORDER_STYLES = Set.of("ascii", "blank", "dashed", "double", "heavy", "hidden", "hkey", "inner", "none", "outer", "panel", "round", "solid", "tall", "tab", "thick", "block", "vkey", "wide"); + private static final Set TEXT_STYLES = Set.of("b", "bold", "blink", "dim", "i", "italic", "none", "not", "o", "overline", "reverse", "strike", "u", "underline", "uu"); + private static final Set HATCHES = Set.of("left", "right", "cross", "horizontal", "vertical"); + private static final Set POINTERS = Set.of("alias", "cell", "copy", "crosshair", "default", "e-resize", "ew-resize", "grab", "grabbing", "help", "move", "n-resize", "ne-resize", "nesw-resize", "no-drop", "not-allowed", "ns-resize", "nw-resize", "nwse-resize", "pointer", "progress", "s-resize", "se-resize", "sw-resize", "text", "vertical-text", "w-resize", "wait", "zoom-in", "zoom-out"); + private static final Set EASING = Set.of("none", "round", "linear", "in_sine", "in_out_sine", "out_sine", "in_quad", "in_out_quad", "out_quad", "in_cubic", "in_out_cubic", "out_cubic", "in_quart", "in_out_quart", "out_quart", "in_quint", "in_out_quint", "out_quint", "in_expo", "in_out_expo", "out_expo", "in_circ", "in_out_circ", "out_circ", "in_back", "in_out_back", "out_back", "in_elastic", "in_out_elastic", "out_elastic", "in_bounce", "in_out_bounce", "out_bounce"); + private static final Set COLORS = words( + "transparent black silver gray grey white maroon red purple fuchsia magenta green lime olive yellow navy blue teal aqua cyan orange " + + "aliceblue antiquewhite aquamarine azure beige bisque blanchedalmond blueviolet brown burlywood cadetblue chartreuse chocolate coral " + + "cornflowerblue cornsilk crimson darkblue darkcyan darkgoldenrod darkgray darkgrey darkgreen darkkhaki darkmagenta darkolivegreen " + + "darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkslategrey darkturquoise darkviolet deeppink " + + "deepskyblue dimgray dimgrey dodgerblue firebrick floralwhite forestgreen gainsboro ghostwhite gold goldenrod greenyellow gray honeydew hotpink " + + "indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow " + + "lightgray lightgrey lightgreen lightpink lightsalmon lightseagreen lightskyblue lightslategray lightslategrey lightsteelblue " + + "lightyellow limegreen linen mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue " + + "mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite oldlace olivedrab " + + "orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue rosybrown " + + "rebeccapurple royalblue saddlebrown salmon sandybrown seagreen seashell sienna skyblue slateblue slategray slategrey snow springgreen " + + "steelblue tan thistle tomato turquoise violet wheat whitesmoke yellowgreen ansi_default ansi_black ansi_red ansi_green ansi_yellow " + + "ansi_blue ansi_magenta ansi_cyan ansi_white ansi_bright_black ansi_bright_red ansi_bright_green ansi_bright_yellow ansi_bright_blue " + + "ansi_bright_magenta ansi_bright_cyan ansi_bright_white" + ); + + private static final Set BUILTIN_VARIABLES = builtInVariables(); + private static final Set ANIMATABLE = Set.of( + "offset", "padding", "margin", "width", "height", "min-width", "min-height", "max-width", "max-height", "auto-color", + "color", "background", "background-tint", "opacity", "position", "text-opacity", "tint", "scrollbar-color", + "scrollbar-color-hover", "scrollbar-color-active", "scrollbar-background", "scrollbar-background-hover", + "scrollbar-background-active", "scrollbar-visibility", "link-color", "link-background", "link-color-hover", + "link-background-hover", "text-wrap", "text-overflow", "line-pad"); + + private TcssValueValidator() {} + + public static Set builtInVariables() { + Set variables = new HashSet<>(); + for (String base : List.of("primary", "secondary", "accent", "foreground", "background", "surface", "panel", "boost", "success", "warning", "error")) { + variables.add("$" + base); + for (String shade : List.of("lighten", "darken")) { + for (int level = 1; level <= 3; level++) variables.add("$" + base + "-" + shade + "-" + level); + } + } + variables.addAll(List.of( + "$foreground-muted", "$foreground-disabled", "$text", "$text-muted", "$text-disabled", "$text-primary", "$text-secondary", + "$text-accent", "$text-warning", "$text-error", "$text-success", "$primary-muted", "$secondary-muted", "$accent-muted", + "$warning-muted", "$error-muted", "$success-muted", "$border", "$border-blurred", "$block-cursor-foreground", + "$block-cursor-background", "$block-cursor-text-style", "$block-cursor-blurred-foreground", "$block-cursor-blurred-background", + "$block-cursor-blurred-text-style", "$block-hover-background", "$input-cursor-background", "$input-cursor-foreground", + "$input-cursor-text-style", "$input-selection-background", "$scrollbar", "$scrollbar-hover", "$scrollbar-active", + "$scrollbar-background", "$scrollbar-corner-color", "$scrollbar-background-hover", "$scrollbar-background-active", + "$link-background", "$link-background-hover", "$link-color", "$link-style", "$link-color-hover", "$link-style-hover", + "$footer-foreground", "$footer-background", "$footer-key-foreground", "$footer-key-background", + "$footer-description-foreground", "$footer-description-background", "$footer-item-background", "$button-foreground", + "$button-color-foreground", "$button-focus-text-style")); + return Set.copyOf(variables); + } + + /** Returns null when valid, otherwise a concise diagnostic message. */ + public static String validate(String property, String source, Set declaredVariables) { + return validate(property, source, declaredVariables, Map.of()); + } + + /** Returns null when valid, otherwise a concise diagnostic message. */ + public static String validate(String property, String source, Set declaredVariables, Map variableDefinitions) { + String value = IMPORTANT_SUFFIX.matcher(source).replaceFirst("").replaceAll("(?s)/\\*.*?\\*/", "").trim(); + List values = splitValues(value); + if (values.isEmpty()) return TcssMessages.message("validation.missingValue"); + + Matcher variableMatcher = VARIABLE.matcher(value); + Set validVariables = new HashSet<>(BUILTIN_VARIABLES); + validVariables.addAll(declaredVariables); + while (variableMatcher.find()) { + String variable = variableMatcher.group(); + if (!validVariables.contains(variable)) { + return TcssMessages.message("validation.unknownVariable", variable); + } + } + for (int i = 0; i < values.size(); i++) { + if (validVariables.contains(values.get(i))) values.set(i, VARIABLE_VALUE); + } + // A sole variable may expand to an arbitrary typed value or multi-part shorthand. + boolean spacingProperty = Set.of("margin", "padding").contains(property.toLowerCase(Locale.ROOT)); + if (!spacingProperty && values.size() == 1 && values.get(0).equals(VARIABLE_VALUE)) return null; + if (values.size() == 1 && values.get(0).equalsIgnoreCase("initial")) return null; + + String key = property.toLowerCase(Locale.ROOT); + if (isBooleanProperty(key)) return oneOf(values, BOOLEANS, key); + if (isColorProperty(key)) return colorValue(values, key, permitsAutoColor(key)); + if (key.equals("background-tint") || key.equals("tint")) return colorValue(values, key, false); + if (key.equals("opacity") || key.equals("text-opacity")) return opacity(values, key); + + return switch (key) { + case "display" -> oneOf(values, Set.of("block", "none"), key); + case "visibility", "scrollbar-visibility" -> oneOf(values, Set.of("visible", "hidden"), key); + case "layout" -> oneOf(values, LAYOUTS, key); + case "position" -> oneOf(values, Set.of("relative", "absolute"), key); + case "box-sizing" -> oneOf(values, Set.of("border-box", "content-box"), key); + case "dock", "split" -> oneOf(values, Set.of("top", "right", "bottom", "left", "none"), key); + case "overflow-x", "overflow-y" -> oneOf(values, Set.of("scroll", "hidden", "auto"), key); + case "scrollbar-gutter" -> oneOf(values, Set.of("auto", "stable"), key); + case "align-horizontal", "content-align-horizontal", "border-title-align", "border-subtitle-align" -> oneOf(values, ALIGN_X, key); + case "align-vertical", "content-align-vertical" -> oneOf(values, ALIGN_Y, key); + case "align", "content-align" -> pairOf(values, ALIGN_X, ALIGN_Y, key); + case "text-align" -> oneOf(values, ALIGN_TEXT, key); + case "text-wrap" -> oneOf(values, Set.of("wrap", "nowrap"), key); + case "text-overflow" -> oneOf(values, Set.of("clip", "fold", "ellipsis"), key); + case "expand" -> oneOf(values, Set.of("greedy", "optimal"), key); + case "overlay" -> oneOf(values, Set.of("none", "screen"), key); + case "constrain-x", "constrain-y" -> oneOf(values, Set.of("none", "inside", "inflect"), key); + case "pointer" -> oneOf(values, POINTERS, key); + case "text-style", "link-style", "link-style-hover", "border-title-style", "border-subtitle-style" -> textStyle(values, key); + case "padding", "margin" -> spacing(values, key, value, variableDefinitions); + case "padding-top", "padding-right", "padding-bottom", "padding-left", + "margin-top", "margin-right", "margin-bottom", "margin-left" -> singleInteger(values, key); + case "offset" -> scalars(values, 2, 2, key, true); + case "width", "height" -> scalars(values, 1, 1, key, true); + case "min-width", "min-height", "max-width", "max-height" -> scalars(values, 1, 1, key, false); + case "grid-rows", "grid-columns" -> scalars(values, 1, Integer.MAX_VALUE, key, true); + case "scrollbar-size-vertical", "scrollbar-size-horizontal", "grid-size-columns", "grid-size-rows", + "grid-gutter-horizontal", "grid-gutter-vertical", "row-span", "column-span", "line-pad" -> integers(values, key); + case "border", "outline" -> border(values, key, true); + case "border-top", "border-right", "border-bottom", "border-left", "outline-top", "outline-right", "outline-bottom", "outline-left" -> border(values, key, false); + case "keyline" -> keyline(values, key); + case "hatch" -> hatch(values, key); + case "layer" -> exactCount(values, 1, key); + case "layers" -> null; // Layer names are user-defined. + case "transitions" -> transitions(value); + default -> null; + }; + } + + public static String validateVariableReferences(String source, Set declaredVariables) { + Matcher matcher = VARIABLE.matcher(source); + while (matcher.find()) { + String variable = matcher.group(); + if (!BUILTIN_VARIABLES.contains(variable) && !declaredVariables.contains(variable)) { + return TcssMessages.message("validation.unknownVariable", variable); + } + } + return null; + } + + private static boolean isBooleanProperty(String key) { + return Set.of("auto-color", "auto-link-color", "auto-link-color-hover", "auto-border-title-color", "auto-border-subtitle-color").contains(key); + } + + private static boolean isColorProperty(String key) { + return Set.of("color", "background", "link-color", "link-background", "link-color-hover", "link-background-hover", + "border-title-color", "border-title-background", "border-subtitle-color", "border-subtitle-background", + "scrollbar-color", "scrollbar-color-hover", "scrollbar-color-active", "scrollbar-background", + "scrollbar-background-hover", "scrollbar-background-active", "scrollbar-corner-color").contains(key); + } + + private static String oneOf(List values, Set allowed, String property) { + if (values.size() == 1 && (isVariableValue(values.get(0)) || allowed.contains(lower(values.get(0))))) return null; + return TcssMessages.message("validation.invalidEnum", property, String.join(", ", allowed)); + } + + private static String pairOf(List values, Set first, Set second, String property) { + if (values.size() == 2 && (isVariableValue(values.get(0)) || first.contains(lower(values.get(0)))) + && (isVariableValue(values.get(1)) || second.contains(lower(values.get(1))))) return null; + return TcssMessages.message("validation.expectedAlignmentPair", property); + } + + private static String colorValue(List values, String property, boolean allowAuto) { + if (allowAuto && values.size() == 1 && lower(values.get(0)).equals("auto")) return null; + if (values.size() < 1 || values.size() > 2 || !isColor(values.get(0))) return TcssMessages.message("validation.invalidColor", property); + if (values.size() == 2 && !isVariableValue(values.get(1)) && !PERCENT.matcher(values.get(1)).matches()) return TcssMessages.message("validation.alphaMustBePercent", property); + return null; + } + + private static boolean permitsAutoColor(String property) { + return Set.of("color", "link-color", "link-color-hover", "border-title-color", "border-subtitle-color").contains(property); + } + + private static boolean isColor(String value) { + String color = lower(value); + return isVariableValue(value) || COLORS.contains(color) + || color.matches("ansi_(?:bright_)?(?:black|red|green|yellow|blue|magenta|cyan|white)") + || color.matches("#[0-9a-f]{3,4}|#[0-9a-f]{6}|#[0-9a-f]{8}") + || RGB.matcher(value).matches() + || HSL.matcher(value).matches(); + } + + private static String opacity(List values, String property) { + if (values.size() != 1) return TcssMessages.message("validation.expectedOneValue", property); + String value = values.get(0); + try { + if (value.endsWith("%")) { + double percent = Double.parseDouble(value.substring(0, value.length() - 1)); + if (percent >= 0 && percent <= 100) return null; + } else { + double opacity = Double.parseDouble(value); + if (opacity >= 0 && opacity <= 1) return null; + } + } catch (NumberFormatException ignored) { } + return TcssMessages.message("validation.opacityRange", property); + } + + private static String textStyle(List values, String property) { + if (values.isEmpty()) return TcssMessages.message("validation.expectedTextStyle", property); + boolean hasNone = false; + for (String value : values) { + String style = lower(value); + if (!isVariableValue(value) && !TEXT_STYLES.contains(style)) return TcssMessages.message("validation.invalidTextStyle", value, property); + if (style.equals("none")) hasNone = true; + } + if (hasNone && values.size() > 1) return TcssMessages.message("validation.noneMustStandAlone", property); + return null; + } + + private static String spacing(List values, String property, String source, Map variableDefinitions) { + int expandedCount = expandedValueCount(source, variableDefinitions, new HashSet<>()); + if (!Set.of(1, 2, 4).contains(expandedCount) || values.stream().anyMatch(value -> !isVariableValue(value) && !INTEGER.matcher(value).matches())) { + return TcssMessages.message("validation.spacingValues", property); + } + return null; + } + + private static int expandedValueCount(String source, Map definitions, Set resolving) { + String value = IMPORTANT_SUFFIX.matcher(source).replaceFirst("").replaceAll("(?s)/\\*.*?\\*/", "").trim(); + int count = 0; + for (String token : splitValues(value)) { + if (BUILTIN_VARIABLES.contains(token)) { + count++; + continue; + } + String definition = definitions.get(token); + if (definition == null || !resolving.add(token)) { + count++; + continue; + } + count += expandedValueCount(definition, definitions, resolving); + resolving.remove(token); + } + return count; + } + + private static String singleInteger(List values, String property) { + if (values.size() != 1 || (!isVariableValue(values.get(0)) && !INTEGER.matcher(values.get(0)).matches())) { + return TcssMessages.message("validation.expectedOneInteger", property); + } + return null; + } + + private static String scalars(List values, int min, int max, String property, boolean allowAuto) { + if (values.size() < min || values.size() > max) return TcssMessages.message("validation.invalidValueCount", property); + for (String value : values) { + if (!isVariableValue(value) && (!SCALAR.matcher(value).matches() || (!allowAuto && value.equalsIgnoreCase("auto")))) { + return TcssMessages.message("validation.invalidScalar", value, property); + } + } + return null; + } + + private static String integers(List values, String property) { + if (values.size() != 1 || (!isVariableValue(values.get(0)) && !INTEGER.matcher(values.get(0)).matches())) return TcssMessages.message("validation.expectedOneInteger", property); + if (isVariableValue(values.get(0))) return null; + String integer = values.get(0); + if (integer.startsWith("-") || (!property.startsWith("scrollbar-size-") && integer.equals("0"))) { + return TcssMessages.message("validation.integerRange", property, property.startsWith("scrollbar-size-") + ? TcssMessages.message("validation.nonNegative") : TcssMessages.message("validation.positive")); + } + return null; + } + + private static String border(List values, String property, boolean shorthand) { + if (values.size() == 1 && Set.of("none", "hidden").contains(lower(values.get(0)))) return null; + int definitions = 0; + for (int index = 0; index < values.size();) { + if (index + 1 >= values.size() || (!isVariableValue(values.get(index)) && !BORDER_STYLES.contains(lower(values.get(index)))) || !isColor(values.get(index + 1))) { + return TcssMessages.message("validation.borderNeedsStyleColor", property); + } + index += 2; + if (index < values.size() && PERCENT.matcher(values.get(index)).matches()) index++; + definitions++; + } + if (shorthand ? !Set.of(1, 2, 4).contains(definitions) : definitions != 1) { + return shorthand ? TcssMessages.message("validation.borderShorthandCount", property) + : TcssMessages.message("validation.borderSideCount", property); + } + return null; + } + + private static String keyline(List values, String property) { + if (values.isEmpty() || values.size() > 3) return TcssMessages.message("validation.keylineCount", property); + for (String value : values) { + String item = lower(value); + if (!isVariableValue(value) && !Set.of("none", "thin", "heavy", "double").contains(item) && !isColor(value) && !PERCENT.matcher(value).matches()) { + return TcssMessages.message("validation.invalidKeyline", value); + } + } + return null; + } + + private static String hatch(List values, String property) { + if (values.size() == 1 && lower(values.get(0)).equals("none")) return null; + if ((values.size() == 2 || values.size() == 3) && (isVariableValue(values.get(0)) || HATCHES.contains(lower(values.get(0)))) && isColor(values.get(1)) + && (values.size() == 2 || isVariableValue(values.get(2)) || PERCENT.matcher(values.get(2)).matches())) return null; + return TcssMessages.message("validation.invalidHatch", property); + } + + private static String transitions(String source) { + String[] entries = source.split(","); + for (String entry : entries) { + List parts = splitValues(entry.trim()); + if (parts.size() < 2 || parts.size() > 4 || !ANIMATABLE.contains(lower(parts.get(0))) + || !parts.get(1).matches("\\d+(?:\\.\\d+)?(?:ms|s|)")) { + return TcssMessages.message("validation.invalidTransition"); + } + if (parts.size() >= 3 && !EASING.contains(lower(parts.get(2)))) return TcssMessages.message("validation.unknownEasing", parts.get(2)); + if (parts.size() == 4 && !parts.get(3).matches("\\d+(?:\\.\\d+)?(?:ms|s|)")) return TcssMessages.message("validation.invalidTransitionDelay", parts.get(3)); + } + return null; + } + + private static String exactCount(List values, int count, String property) { + return values.size() == count ? null : TcssMessages.message("validation.expectedCount", property, count); + } + + private static boolean isVariableValue(String value) { + return VARIABLE_VALUE.equals(value); + } + + private static List splitValues(String value) { + List result = new ArrayList<>(); + StringBuilder token = new StringBuilder(); + int depth = 0; + char quote = 0; + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (quote != 0) { + token.append(c); + if (c == quote && (i == 0 || value.charAt(i - 1) != '\\')) quote = 0; + } else if (c == '\'' || c == '"') { + quote = c; + token.append(c); + } else if (c == '(') { + depth++; + token.append(c); + } else if (c == ')') { + depth--; + token.append(c); + } else if (Character.isWhitespace(c) && depth == 0) { + if (!token.isEmpty()) { + result.add(token.toString()); + token.setLength(0); + } + } else { + token.append(c); + } + } + if (!token.isEmpty()) result.add(token.toString()); + return result; + } + + private static String lower(String value) { return value.toLowerCase(Locale.ROOT); } + + private static Set words(String words) { + return Set.copyOf(Arrays.asList(words.toLowerCase(Locale.ROOT).trim().split("\\s+"))); + } +} diff --git a/src/main/java/de/textualtcss/intellij/TcssVariableDeclaration.java b/src/main/java/de/textualtcss/intellij/TcssVariableDeclaration.java new file mode 100644 index 0000000..3f54a7a --- /dev/null +++ b/src/main/java/de/textualtcss/intellij/TcssVariableDeclaration.java @@ -0,0 +1,58 @@ +package de.textualtcss.intellij; + +import com.intellij.extapi.psi.ASTWrapperPsiElement; +import com.intellij.lang.ASTNode; +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.PsiElement; +import org.jetbrains.annotations.NotNull; + +public final class TcssVariableDeclaration extends ASTWrapperPsiElement { + public TcssVariableDeclaration(@NotNull ASTNode node) { + super(node); + } + + public PsiElement getVariableToken() { + for (PsiElement child = getFirstChild(); child != null; child = child.getNextSibling()) { + if (child.getNode().getElementType() == TcssTypes.VARIABLE) return child; + } + return null; + } + + public String getVariableName() { + PsiElement token = getVariableToken(); + return token == null ? "" : token.getText(); + } + + public String getValueText() { + StringBuilder value = new StringBuilder(); + boolean inValue = false; + for (PsiElement child = getFirstChild(); child != null; child = child.getNextSibling()) { + if (child.getNode().getElementType() == TcssTypes.COLON) { + inValue = true; + continue; + } + if (!inValue) continue; + if (child.getNode().getElementType() == TcssTypes.SEMICOLON) break; + value.append(child.getText()); + } + return value.toString(); + } + + public TextRange getValueRange() { + PsiElement first = null; + PsiElement last = null; + boolean inValue = false; + for (PsiElement child = getFirstChild(); child != null; child = child.getNextSibling()) { + if (child.getNode().getElementType() == TcssTypes.COLON) { + inValue = true; + continue; + } + if (!inValue) continue; + if (child.getNode().getElementType() == TcssTypes.SEMICOLON) break; + if (child.getText().isBlank()) continue; + if (first == null) first = child; + last = child; + } + return first == null ? getTextRange() : new TextRange(first.getTextRange().getStartOffset(), last.getTextRange().getEndOffset()); + } +} diff --git a/src/main/resources/META-INF/plugin.xml b/src/main/resources/META-INF/plugin.xml new file mode 100644 index 0000000..9656c94 --- /dev/null +++ b/src/main/resources/META-INF/plugin.xml @@ -0,0 +1,25 @@ + + de.textualtcss.intellij + Textual TCSS + ikoch + + + + com.intellij.modules.platform + + + + + + + + + + + + + + diff --git a/src/main/resources/META-INF/pluginIcon.svg b/src/main/resources/META-INF/pluginIcon.svg new file mode 100644 index 0000000..e43c183 --- /dev/null +++ b/src/main/resources/META-INF/pluginIcon.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/src/main/resources/messages/TcssMessages.properties b/src/main/resources/messages/TcssMessages.properties new file mode 100644 index 0000000..ed78c50 --- /dev/null +++ b/src/main/resources/messages/TcssMessages.properties @@ -0,0 +1,46 @@ +parser.unexpectedClosingBrace=Unexpected closing brace '}' +parser.variableColon=Variable name and value must be separated by ':' +parser.variableSemicolon=Expected ';' at the end of the variable declaration +parser.missingSelector=Missing selector +parser.expectedOpeningBrace=Expected '{' after the selector +parser.missingClosingBrace=Missing closing brace '}' +parser.declarationColon=Property and value must be separated by ':' +parser.declarationSemicolon=Expected ';' at the end of the declaration +validation.unknownProperty=Unknown Textual property '{0}'. +validation.duplicateVariable=TCSS variable '{0}' is declared more than once. +validation.missingValue=Value is missing. +validation.unknownVariable=Unknown TCSS variable '{0}'. +validation.invalidEnum=Invalid value for '{0}'; expected one of: {1}. +validation.expectedAlignmentPair='{0}' expects exactly two values: horizontal and vertical alignment. +validation.invalidColor=Invalid color value for '{0}'. +validation.alphaMustBePercent=The optional alpha value for '{0}' must be a percentage. +validation.expectedOneValue='{0}' expects exactly one value. +validation.opacityRange='{0}' must be between 0 and 1 or between 0% and 100%. +validation.expectedTextStyle='{0}' expects at least one text style. +validation.invalidTextStyle=Invalid text style '{0}' for '{1}'. +validation.noneMustStandAlone='none' cannot be combined with other styles in '{0}'. +validation.spacingValues='{0}' expects 1, 2, or 4 integer values. +validation.expectedOneInteger='{0}' expects exactly one integer value. +validation.invalidValueCount=Invalid number of values for '{0}'. +validation.invalidScalar=Invalid scalar '{0}' for '{1}'. +validation.integerRange='{0}' expects a {1} integer value. +validation.nonNegative=non-negative +validation.positive=positive +validation.borderNeedsStyleColor=Each border definition for '{0}' needs a valid style and color. +validation.borderShorthandCount='{0}' expects 1, 2, or 4 border definitions. +validation.borderSideCount='{0}' expects one border style and one color. +validation.keylineCount='{0}' expects at most three values. +validation.invalidKeyline=Invalid keyline style or color value '{0}'. +validation.invalidHatch='{0}' expects 'none' or a direction, color, and optional alpha percentage. +validation.invalidTransition='transitions' expects animatable style names with a duration, e.g. background 200ms. +validation.unknownEasing=Unknown easing function '{0}'. +validation.invalidTransitionDelay=Invalid transition delay '{0}'. +validation.expectedCount='{0}' expects exactly {1} value(s). +style.generic=Valid Textual {0} style property. +documentation.link=Textual documentation +documentation.value.fr=A fractional unit that divides available space proportionally. +documentation.value.auto=Textual calculates the size or position automatically. +documentation.value.important=Gives this declaration precedence over selector specificity. +documentation.value.hover=Pseudo-class for widgets currently under the mouse pointer. +documentation.value.focus=Pseudo-class for the widget that currently has focus. +documentation.value.themeColor=Textual color name from the built-in palette. diff --git a/src/main/resources/messages/TcssMessages_de.properties b/src/main/resources/messages/TcssMessages_de.properties new file mode 100644 index 0000000..3c30ba8 --- /dev/null +++ b/src/main/resources/messages/TcssMessages_de.properties @@ -0,0 +1,137 @@ +parser.unexpectedClosingBrace=Unerwartete schließende Klammer '}' +parser.variableColon=Variablenname und Wert müssen durch ':' getrennt sein +parser.variableSemicolon=';' am Ende der Variablendeklaration erwartet +parser.missingSelector=Selektor fehlt +parser.expectedOpeningBrace='{' nach dem Selektor erwartet +parser.missingClosingBrace=Schließende Klammer '}' fehlt +parser.declarationColon=Eigenschaft und Wert müssen durch ':' getrennt sein +parser.declarationSemicolon=';' am Ende der Deklaration erwartet +validation.unknownProperty=Unbekannte Textual-Eigenschaft '{0}'. +validation.duplicateVariable=TCSS-Variable '{0}' ist mehrfach deklariert. +validation.missingValue=Wert fehlt. +validation.unknownVariable=Unbekannte TCSS-Variable '{0}'. +validation.invalidEnum=Ungültiger Wert für '{0}'; erwartet: {1}. +validation.expectedAlignmentPair='{0}' erwartet genau zwei Werte: horizontale und vertikale Ausrichtung. +validation.invalidColor=Ungültiger Farbwert für '{0}'. +validation.alphaMustBePercent=Der optionale Alpha-Wert für '{0}' muss ein Prozentwert sein. +validation.expectedOneValue='{0}' erwartet genau einen Wert. +validation.opacityRange='{0}' muss zwischen 0 und 1 oder zwischen 0% und 100% liegen. +validation.expectedTextStyle='{0}' erwartet mindestens einen Textstil. +validation.invalidTextStyle=Ungültiger Textstil '{0}' für '{1}'. +validation.noneMustStandAlone='none' darf bei '{0}' nicht mit anderen Stilen kombiniert werden. +validation.spacingValues='{0}' erwartet 1, 2 oder 4 ganzzahlige Werte. +validation.expectedOneInteger='{0}' erwartet genau einen ganzzahligen Wert. +validation.invalidValueCount=Ungültige Anzahl Werte für '{0}'. +validation.invalidScalar=Ungültiger Scalar '{0}' für '{1}'. +validation.integerRange='{0}' erwartet einen {1} ganzzahligen Wert. +validation.nonNegative=nichtnegativen +validation.positive=positiven +validation.borderNeedsStyleColor=Jede Borderdefinition für '{0}' benötigt einen gültigen Stil und eine Farbe. +validation.borderShorthandCount='{0}' erwartet 1, 2 oder 4 Borderdefinitionen. +validation.borderSideCount='{0}' erwartet einen Borderstil und eine Farbe. +validation.keylineCount='{0}' erwartet höchstens drei Werte. +validation.invalidKeyline=Ungültiger Keyline-Stil oder Farbwert '{0}'. +validation.invalidHatch='{0}' erwartet none oder eine Richtung mit Farbe und optionalem Alpha-Prozentwert. +validation.invalidTransition='transitions' erwartet animierbare Style-Namen mit einer Dauer, z. B. background 200ms. +validation.unknownEasing=Unbekannte Easing-Funktion '{0}'. +validation.invalidTransitionDelay=Ungültige Transition-Verzögerung '{0}'. +validation.expectedCount='{0}' erwartet genau {1} Wert(e). +style.generic=Gültige Textual-Style-Property der Version {0}. +style.align=Richtet ein Widget horizontal und vertikal in seinem Container aus. +style.align-horizontal=Horizontale Ausrichtung eines Widgets: links, zentriert oder rechts. +style.align-vertical=Vertikale Ausrichtung eines Widgets: oben, mittig oder unten. +style.auto-border-subtitle-color=Wählt automatisch eine kontrastreiche Untertitelfarbe. +style.auto-border-title-color=Wählt automatisch eine kontrastreiche Titelfarbe. +style.auto-color=Wählt automatisch eine gut lesbare Vordergrundfarbe für den Hintergrund. +style.auto-link-color=Wählt automatisch eine ausreichend kontrastreiche Linkfarbe. +style.auto-link-color-hover=Wählt beim Darüberfahren automatisch eine kontrastreiche Linkfarbe. +style.background=Hintergrundfarbe des Widgets. +style.background-tint=Farbton, der über den Widget-Hintergrund gelegt wird. +style.border=Legt den Rahmen auf allen vier Seiten fest. +style.border-bottom=Rahmenstil und -farbe für die untere Kante. +style.border-left=Rahmenstil und -farbe für die linke Kante. +style.border-right=Rahmenstil und -farbe für die rechte Kante. +style.border-top=Rahmenstil und -farbe für die obere Kante. +style.box-sizing=Legt fest, ob Breite und Höhe Innenabstand und Rahmen einschließen. +style.color=Vordergrundfarbe des Widget-Inhalts. +style.constrain-x=Begrenzt ein Widget horizontal innerhalb des Eltern-Widgets oder Bildschirms. +style.constrain-y=Begrenzt ein Widget vertikal innerhalb des Eltern-Widgets oder Bildschirms. +style.content-align=Richtet Inhalte horizontal und vertikal innerhalb des Widgets aus. +style.content-align-horizontal=Horizontale Ausrichtung des Widget-Inhalts. +style.content-align-vertical=Vertikale Ausrichtung des Widget-Inhalts. +style.display=Blendet das Widget mit block ein oder mit none aus. +style.dock=Dockt ein Widget an einer Kante an: oben, rechts, unten oder links. +style.expand=Legt fest, wie das Widget den verfügbaren Layout-Platz nutzt. +style.grid-columns=Spaltengrößen eines Grid-Layouts. +style.grid-gutter-horizontal=Horizontaler Abstand zwischen Grid-Spalten. +style.grid-gutter-vertical=Vertikaler Abstand zwischen Grid-Zeilen. +style.grid-rows=Zeilengrößen eines Grid-Layouts. +style.grid-size-columns=Anzahl der Spalten im Grid. +style.grid-size-rows=Anzahl der Zeilen im Grid. +style.hatch=Muster und Farbe für eine Schraffurfläche. +style.height=Widget-Höhe in Zellen, Bruchteilen, Prozent oder auto. +style.keyline=Zeichnet eine Trennlinie zwischen Kindern in einem horizontalen oder vertikalen Layout. +style.layer=Name der Ebene, auf der das Widget dargestellt wird. +style.layers=Geordnete Ebenennamen, die für den Bildschirm verfügbar sind. +style.layout=Layout-Strategie für die Kinder des Widgets, etwa vertical, horizontal, grid oder stream. +style.line-pad=Zusätzlicher horizontaler Abstand für jede Textzeile. +style.link-background=Hintergrundfarbe von Links. +style.link-background-hover=Hintergrundfarbe von Links beim Darüberfahren. +style.link-color=Textfarbe von Links. +style.link-color-hover=Textfarbe von Links beim Darüberfahren. +style.link-style=Textstil von Links. +style.link-style-hover=Textstil von Links beim Darüberfahren. +style.margin=Außenabstand; akzeptiert einen, zwei oder vier Werte. +style.margin-top=Oberer Außenabstand des Widgets. +style.margin-right=Rechter Außenabstand des Widgets. +style.margin-bottom=Unterer Außenabstand des Widgets. +style.margin-left=Linker Außenabstand des Widgets. +style.max-height=Maximale Höhe des Widgets. +style.max-width=Maximale Breite des Widgets. +style.min-height=Minimale Höhe des Widgets. +style.min-width=Minimale Breite des Widgets. +style.offset=Verschiebt ein Widget aus seiner normalen Position. +style.opacity=Deckkraft von 0 (transparent) bis 1 (deckend) oder als Prozentwert. +style.outline=Legt die Kontur außerhalb des Rahmens auf allen vier Seiten fest. +style.outline-bottom=Konturstil und -farbe für die untere Kante. +style.outline-left=Konturstil und -farbe für die linke Kante. +style.outline-right=Konturstil und -farbe für die rechte Kante. +style.outline-top=Konturstil und -farbe für die obere Kante. +style.overflow-x=Legt fest, wie horizontal überlaufende Inhalte behandelt werden. +style.overflow-y=Legt fest, wie vertikal überlaufende Inhalte behandelt werden. +style.overlay=Zeigt ein Widget als Overlay an, optional über dem Bildschirm. +style.padding=Innenabstand; akzeptiert einen, zwei oder vier Werte. +style.padding-top=Oberer Innenabstand zwischen Rahmen und Inhalt. +style.padding-right=Rechter Innenabstand zwischen Rahmen und Inhalt. +style.padding-bottom=Unterer Innenabstand zwischen Rahmen und Inhalt. +style.padding-left=Linker Innenabstand zwischen Rahmen und Inhalt. +style.pointer=Zeigerform, die beim Darüberfahren über ein Widget angezeigt wird. +style.position=Legt relative oder absolute Positionierung fest. +style.scrollbar-background=Hintergrund der Scrollbar-Spur. +style.scrollbar-background-active=Farbe der Scrollbar-Spur bei Aktivität. +style.scrollbar-background-hover=Farbe der Scrollbar-Spur beim Darüberfahren. +style.scrollbar-color=Farbe des Scrollbar-Griffs. +style.scrollbar-color-active=Farbe des Scrollbar-Griffs bei Aktivität. +style.scrollbar-color-hover=Farbe des Scrollbar-Griffs beim Darüberfahren. +style.scrollbar-corner-color=Farbe der Ecke, an der Scrollbars zusammentreffen. +style.scrollbar-gutter=Legt fest, ob Platz für Scrollbars reserviert wird. +style.scrollbar-size-horizontal=Dicke der horizontalen Scrollbar in Zellen. +style.scrollbar-size-vertical=Dicke der vertikalen Scrollbar in Zellen. +style.scrollbar-visibility=Steuert, ob Scrollbars sichtbar sind. +style.split=Teilt einen Container von einer angedockten Kante aus. +style.text-align=Richtet Text innerhalb des Widgets aus. +style.text-opacity=Deckkraft des Textes, ohne den Widget-Hintergrund auszublenden. +style.text-overflow=Legt fest, wie Text gekürzt wird, wenn er nicht hineinpasst. +style.text-style=Wendet fett, kursiv, unterstrichen, durchgestrichen, invertiert oder keinen Textstil an. +style.text-wrap=Legt fest, ob Text am Widget-Rand umgebrochen wird. +style.tint=Farbton, der über den Widget-Inhalt gelegt wird. +style.transitions=Konfiguriert animierte Übergänge für unterstützte Style-Properties. +style.visibility=Blendet das Widget ein oder aus, wobei sein Layout-Platz erhalten bleibt. +style.width=Widget-Breite in Zellen, Bruchteilen, Prozent oder auto. +documentation.link=Textual-Dokumentation +documentation.value.fr=Eine fractionale Einheit: Der verfügbare Platz wird proportional aufgeteilt. +documentation.value.auto=Textual berechnet Größe oder Position automatisch. +documentation.value.important=Gibt dieser Deklaration Vorrang vor der Selektor-Spezifität. +documentation.value.hover=Pseudo-Klasse für Widgets, über denen sich der Mauszeiger befindet. +documentation.value.focus=Pseudo-Klasse für das aktuell fokussierte Widget. +documentation.value.themeColor=Textual-Farbname aus der eingebauten Farbpalette.