# Event loop # SPDX-FileCopyrightText: 2025 Nguyễn Gia Phong # SPDX-License-Identifier: GPL-3.0-or-later (defn kay/select/move [buf direction] (let [selection (buf :selection)] (struct ;(kvs buf) :selection (match selection {:head head :tail tail} (struct ;(kvs selection) :head (direction head buf) :tail (direction tail buf)))))) (defn kay/select/head [buf direction] (let [selection (buf :selection)] (struct ;(kvs buf) :selection (match selection {:head head :tail tail} (struct ;(kvs selection) :head (direction head buf) :tail tail))))) (defn kay/select/flip [buf] (struct ;(kvs buf) :selection (match (buf :selection) {:head head :tail tail} {:head tail :tail head}))) (defn handle [event buf] (match event {:winsize ws} (do (:resize kay/env ws) [[] buf]) {:key-press key} (cond (:matches key (chr "c") {:ctrl true}) [[:quit] buf] (:matches key (chr "y") {}) (do (:yank kay/env buf) [[] buf]) (:matches key (chr "i") {}) (do (:request-paste kay/env) [[] buf]) (:matches key (chr "p") {}) [[] (struct ;(kvs buf) :scroll-row (max 0 (dec (buf :scroll-row))))] (:matches key (chr "n") {}) [[] (struct ;(kvs buf) :scroll-row (inc (buf :scroll-row)))] (:matches key (chr "h") {}) [[] (kay/select/move buf :up)] (:matches key (chr "j") {}) [[] (kay/select/move buf :right)] (:matches key (chr "k") {}) [[] (kay/select/move buf :left)] (:matches key (chr "l") {}) [[] (kay/select/move buf :down)] (:matches key (chr "h") {:shift true}) [[] (kay/select/head buf :up)] (:matches key (chr "j") {:shift true}) [[] (kay/select/head buf :right)] (:matches key (chr "k") {:shift true}) [[] (kay/select/head buf :left)] (:matches key (chr "l") {:shift true}) [[] (kay/select/head buf :down)] (:matches key (chr ";") {}) [[] (kay/select/flip buf)] [[] buf]) {:paste paste} [[] (:paste kay/env buf paste)])) (defn run [events buf] (if-let [event (array/pop events)] (unless (= :quit event) (let [[next-events next-buf] (handle event buf)] (:render kay/env next-buf) (run (array/join events next-events) next-buf))) (run @[(:next-event kay/env)] buf))) (with [buf (kay/open (if-with [f (file/open (string kay/path))] (buffer (:read f :all)) @"\n") kay/path)] (run @[] buf))