+(defun avy--de-bruijn (keys n)
+ "De Bruijn sequence for alphabet KEYS and subsequences of length N."
+ (let* ((k (length keys))
+ (a (make-list (* n k) 0))
+ sequence)
+ (cl-labels ((db (T p)
+ (if (> T n)
+ (if (eq (% n p) 0)
+ (setq sequence
+ (append sequence
+ (cl-subseq a 1 (1+ p)))))
+ (setf (nth T a) (nth (- T p) a))
+ (db (1+ T) p)
+ (cl-loop for j from (1+ (nth (- T p) a)) to (1- k) do
+ (setf (nth T a) j)
+ (db (1+ T) T)))))
+ (db 1 1)
+ (mapcar (lambda (n)
+ (nth n keys))
+ sequence))))
+
+(defun avy--path-alist-1 (lst seq-len keys)
+ "Build a De Bruin sequence from LST.
+SEQ-LEN is how many elements of KEYS it takes to identify a match."
+ (let ((db-seq (avy--de-bruijn keys seq-len))
+ prev-pos prev-seq prev-win path-alist)
+ ;; The De Bruijn seq is cyclic, so append the seq-len - 1 first chars to
+ ;; the end.
+ (setq db-seq (nconc db-seq (cl-subseq db-seq 0 (1- seq-len))))
+ (cl-labels ((subseq-and-pop ()
+ (when (nth (1- seq-len) db-seq)
+ (prog1 (cl-subseq db-seq 0 seq-len)
+ (pop db-seq)))))
+ (while lst
+ (let* ((cur (car lst))
+ (pos (cond
+ ;; ace-window has matches of the form (pos . wnd)
+ ((integerp (car cur)) (car cur))
+ ;; avy-jump have form ((start . end) . wnd)
+ ((consp (car cur)) (caar cur))
+ (t (error "Unexpected match representation: %s" cur))))
+ (win (cdr cur))
+ (path (if prev-pos
+ (let ((diff (if (eq win prev-win)
+ (- pos prev-pos)
+ 0)))
+ (when (and (> diff 0) (< diff seq-len))
+ (while (and (nth (1- seq-len) db-seq)
+ (not
+ (eq 0 (cl-search
+ (cl-subseq prev-seq diff)
+ (cl-subseq db-seq 0 seq-len)))))
+ (pop db-seq)))
+ (subseq-and-pop))
+ (subseq-and-pop))))
+ (if (not path)
+ (setq lst nil
+ path-alist nil)
+ (push (cons path (car lst)) path-alist)
+ (setq prev-pos pos
+ prev-seq path
+ prev-win win
+ lst (cdr lst))))))
+ (nreverse path-alist)))
+