 (defn whitespace? [ch]
   (re-find #"[\s,]" ch))
 
+(defn insert-string
+  [orig idx insert]
+  (str (subs orig 0 idx)
+       insert
+       (subs orig idx)))
+
 (defn close-delims
   ([result] (close-delims result 0))
-  ([result x-pos]
-   ;; TODO: close all delimiters that are >= x-pos, and insert at insertion point
-   (assoc result :track-indent? false)))
+  ([result indent-x]
+   (let [[stack delims] (loop [stack (:stack result), delims ""]
+                          (if-not (seq stack)
+                            [stack delims]
+                            (let [[x ch] (peek stack)]
+                              (if (>= x indent-x)
+                                (recur (pop stack) (str delims (matching-delim ch)))
+                                [stack delims]))))
+         {:keys [line-no x-pos]} (:insert result)
+         result (-> result
+                    (update-in [:lines line-no] insert-string x-pos delims)
+                    (assoc :track-indent? false
+                           :stack stack))]
+     result)))
 
 (defn push-char
   [{:keys [stack track-indent? line-no] :as result} [x-pos ch]]

                          (update-text! (.-selectionStart target) (.-value target))))
           :value (:text data)}]
         [:pre.internal
          (:text data)
          ]]))))

(om/root
  root-comp

                          (in-code? stack)
                          (not (whitespace? ch)))
                 {:line-no line-no
                  :x-pos (inc x-pos)})
        result (cond-> result insert (assoc :insert insert))]
    result))

