Skip to content

Commit

Permalink
Auto-insert matching brackets
Browse files Browse the repository at this point in the history
  • Loading branch information
vlaaad committed Mar 24, 2021
1 parent 42952f3 commit f870e0a
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/vlaaad/reveal/action_popup.clj
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@
:on-cancel on-cancel
:desc {:fx/type fx/ext-let-refs
:refs (into {::text-field {:fx/type :text-field
:text-formatter rfx/code-text-formatter
:style-class "reveal-text-field"
:text text
:on-focused-changed {::event/type ::on-text-focused
Expand Down
54 changes: 52 additions & 2 deletions src/vlaaad/reveal/fx.clj
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
(ns vlaaad.reveal.fx
(:require [cljfx.lifecycle :as fx.lifecycle]
[cljfx.component :as fx.component])
(:import [java.util UUID]))
(:import [java.util UUID]
[java.util.function UnaryOperator]
[javafx.scene.control TextFormatter$Change]))

(def ext-with-process
"Extension lifecycle that provides \"local mutable state\" capability
Expand Down Expand Up @@ -43,4 +45,52 @@
(delete [_ component opts]
(when-let [stop-fn (:stop-fn component)]
(stop-fn))
(fx.lifecycle/delete fx.lifecycle/dynamic (:child component) opts))))
(fx.lifecycle/delete fx.lifecycle/dynamic (:child component) opts))))

(defn- format! [^TextFormatter$Change change]
(when (.isContentChange change)
(let [range-start (.getRangeStart change)
range-end (.getRangeEnd change)
control-text (.getControlText change)
inputs-char (and (pos? range-start)
(= \\ (.charAt control-text (dec range-start))))
move-right? (fn [char]
(and (not (.isDeleted change))
(< range-end (.length control-text))
(= char (.charAt control-text range-end))))
move-right! (fn []
(.setText change "")
(.selectRange change (inc range-end) (inc range-end)))]
(cond
(not (.isAdded change))
(when (and (= 1 (- range-end range-start))
(< range-end (.length control-text)))
(let [deleted-char (.charAt control-text range-start)
next-char (.charAt control-text range-end)]
(case [deleted-char next-char]
([\" \"] [\{ \}] [\[ \]] [\( \)])
(.setRange change range-start (inc range-end))
nil)))

inputs-char
nil

:else
(case (.getText change)
"\"" (if (move-right? \") (move-right!) (.setText change "\"\""))
"[" (.setText change "[]")
"]" (when (move-right? \]) (move-right!))
"{" (.setText change "{}")
"}" (when (move-right? \}) (move-right!))
"(" (.setText change "()")
")" (when (move-right? \)) (move-right!))
nil)))))

(def code-text-formatter-filter
(reify UnaryOperator
(apply [_ v]
(doto v format!))))

(def code-text-formatter
{:fx/type :text-formatter
:filter code-text-formatter-filter})

0 comments on commit f870e0a

Please sign in to comment.