Исправил работу со списком переменных из всплывающего окна. Теперь там можно выбрать из списка стрелками и вставить по Enter.

This commit is contained in:
svk
2026-01-29 14:22:55 +03:00
parent 1c7c2ec90e
commit 3de27dac4f
2 changed files with 94 additions and 28 deletions

View File

@@ -404,7 +404,14 @@ namespace eval Editor {
} }
proc ReleaseKey {k txt fileType} { proc ReleaseKey {k txt fileType} {
global cfgVariables lexers global cfgVariables lexers returnProcessed
# Если Return уже обработан в SelectFromList, пропускаем
# puts "$returnProcessed $k"
if {$k eq "Return" && [info exists returnProcessed]} {
unset returnProcessed
return
}
#
set pos [$txt index insert] set pos [$txt index insert]
set lineNum [lindex [split $pos "."] 0] set lineNum [lindex [split $pos "."] 0]
set posNum [lindex [split $pos "."] 1] set posNum [lindex [split $pos "."] 1]
@@ -508,10 +515,68 @@ namespace eval Editor {
if {$cfgVariables(variableHelper) eq "true"} { if {$cfgVariables(variableHelper) eq "true"} {
if {[dict exists $lexers $fileType variableSymbol] != 0} { if {[dict exists $lexers $fileType variableSymbol] != 0} {
set varSymbol [dict get $lexers $fileType variableSymbol] set varSymbol [dict get $lexers $fileType variableSymbol]
set lastSymbol [string last $varSymbol [$txt get $lineNum.0 $pos]] set lineText [$txt get $lineNum.0 $pos]
# # Ищем переменную с помощью регулярного выражения
# # Паттерн ищет $ за которым идет имя переменной И курсор сразу после имени
# if {[regexp "(\\$)(\[a-zA-Z_:\]\[a-zA-Z0-9_:\]*)\$" $lineText -> symbol varName]} {
# # Проверяем, что найденный $ - это действительно начало переменной
# # (а не часть строки или другого символа)
# DebugPuts "Found variable: $symbol$varName"
#
# # Дополнительная проверка: перед $ не должно быть обратного слэша (экранирование)
# set posOfVarSymbol [string last $varSymbol $lineText]
# if {$posOfVarSymbol > 0} {
# set charBefore [string index $lineText [expr {$posOfVarSymbol - 1}]]
# if {$charBefore eq "\\"} {
# DebugPuts "Dollar sign is escaped, skipping"
# return
# }
# }
# Helper::VarHelper $box_x $box_y $txt $varName vars
# }
DebugPuts "Line text: '$lineText'"
# Проверяем, есть ли $ в строке
set lastSymbol [string last $varSymbol $lineText]
if {$lastSymbol ne "-1"} { if {$lastSymbol ne "-1"} {
set word [string trim [$txt get $lineNum.[expr $lastSymbol + 1] $pos]] # Проверяем экранирование
Helper::VarHelper $box_x $box_y $txt $word vars if {$lastSymbol > 0} {
set charBefore [string index $lineText [expr {$lastSymbol - 1}]]
if {$charBefore eq "\\"} {
DebugPuts "Dollar sign is escaped, skipping"
return
}
}
# Берем текст после $
set afterDollar [string range $lineText [expr {$lastSymbol + 1}] end]
DebugPuts "Text after $varSymbol: '$afterDollar'"
# Если после $ ничего нет (только что ввели $) - показываем все переменные
if {$afterDollar eq ""} {
DebugPuts "Just typed $varSymbol, showing all variables"
Helper::VarHelper $box_x $box_y $txt "" vars
return
}
# Проверяем, что введено после $
if {[regexp {^([a-zA-Z_:][a-zA-Z0-9_:]*)?$} $afterDollar -> varName]} {
# Вариант 1: regexp с концом строки - курсор сразу после (возможного) имени
DebugPuts "Cursor after variable name (or $varSymbol only): '$varName'"
Helper::VarHelper $box_x $box_y $txt $varName vars
} elseif {[regexp {^([a-zA-Z_:][a-zA-Z0-9_:]*)} $afterDollar -> varName]} {
# Вариант 2: есть имя переменной, но курсор не обязательно сразу после
DebugPuts "Found variable name: '$varName'"
# Проверяем позицию курсора
set varEndPos [expr {[string length $varName] + 1}] ; # +1 для $
if {$varEndPos == [string length $lineText]} {
# Курсор сразу после имени
Helper::VarHelper $box_x $box_y $txt $varName vars
} else {
DebugPuts "Cursor not immediately after variable name, skipping"
}
} else {
# После $ что-то недопустимое (например, цифра, скобка и т.д.)
DebugPuts "Invalid characters after $varSymbol"
}
} }
} else { } else {
set ind [$txt search -backwards -regexp {\W} $pos {insert linestart}] set ind [$txt search -backwards -regexp {\W} $pos {insert linestart}]
@@ -523,6 +588,7 @@ namespace eval Editor {
# set ind [$txt search -backwards -regexp {^} $pos {insert linestart}] # set ind [$txt search -backwards -regexp {^} $pos {insert linestart}]
set word [$txt get {insert linestart} $pos] set word [$txt get {insert linestart} $pos]
} }
DebugPuts "> Extracted word: '$word'"
if {$word ne ""} { if {$word ne ""} {
Helper::VarHelper $box_x $box_y $txt $word {} Helper::VarHelper $box_x $box_y $txt $word {}
} }

View File

@@ -294,43 +294,43 @@ namespace eval Helper {
} }
proc SelectFromList {txt} { proc SelectFromList {txt} {
global returnProcessed editors lexers
set win .varhelper set win .varhelper
puts "[dict get $editors $txt fileType]"
DebugPuts "SelectFromList called" puts "[dict get $lexers [dict get $editors $txt fileType] variableSymbol]"
if {![winfo exists $win]} { if {![winfo exists $win]} {
DebugPuts "Window doesn't exist"
return return
} }
# Получаем выбранный элемент
set selected [$win.lBox curselection] set selected [$win.lBox curselection]
DebugPuts "Selected index: $selected"
if {$selected ne ""} { if {$selected ne ""} {
set text [$win.lBox get $selected] set text [string trim [$win.lBox get $selected]]
DebugPuts "Selected text: $text" set varSymbol [dict get $lexers [dict get $editors $txt fileType] variableSymbol]
# Опеределяем что символ перед позицией вставки равен символу переменной из настроек lexers
# Вставляем выбранный текст в текстовое поле # если равен то вставляем выбранное из списка сразу за ним
# если нет то удаляем введенный текст до этого символа и вставляем выбранное из списка
if {[$txt get "insert - 1 char" "insert"] eq $varSymbol} {
$txt insert "insert" $text
} else {
$txt delete "insert - 1 chars wordstart" "insert wordend - 1 chars" $txt delete "insert - 1 chars wordstart" "insert wordend - 1 chars"
$txt insert "insert" $text $txt insert "insert" $text
}
# Закрываем окно списка # Закрываем окно
destroy $win destroy $win
set ::listActive 0 set ::listActive 0
Helper::VarHelperBindingsRestore $txt Helper::VarHelperBindingsRestore $txt
set ::previousInput "" set ::previousInput ""
# Возвращаем фокус # Устанавливаем флаг, что Return уже обработан
set returnProcessed 1
# after 10 {catch {unset returnProcessed}}
focus $txt.t focus $txt.t
} }
} }
proc DebugPuts {msg} { proc DebugPuts {msg} {
puts "DEBUG: $msg" puts "DEBUG: $msg"
} }
} }