Changeset - ad5ac55c1141
[Not reviewed]
0 6 0
Sergey Pashinin - 11 years ago 2014-08-23 12:10:21
sergey@pashinin.com
Replaced wg-aif
6 files changed with 11 insertions and 16 deletions:
0 comments (0 inline, 0 general)
src/workgroups-association.el
Show inline comments
 
;;; workgroups-association.el --- buffer for workgroup
 
;;; Commentary:
 
;;; Code:
 

	
 
(require 'workgroups-structs)
 
(require 'workgroups-variables)
 
(require 'workgroups-session)
 

	
 
(defvar wg-buffer-workgroup nil
 
  "Associating each buffer with the workgroup.
 
In which it most recently appeared.")
 
(make-variable-buffer-local 'wg-buffer-workgroup)
 

	
 
(defun wg-workgroup-associated-buf-uids (workgroup)
 
  "Return a new list containing all of WORKGROUP's associated buf uids."
 
  (append (wg-workgroup-strong-buf-uids workgroup)
 
          (wg-workgroup-weak-buf-uids workgroup)))
 

	
 
(defun wg-workgroup-associated-bufs (workgroup)
 
  "Return a new list containing all of WORKGROUP's associated bufs."
 
  (delete nil (mapcar 'wg-find-buf-by-uid
 
                      (wg-workgroup-associated-buf-uids workgroup))))
 

	
 
(defun wg-workgroup-associated-buffers (workgroup)
 
  "Return a new list containing all of WORKGROUP's associated buffer objects."
 
  (delete nil (mapcar 'wg-restore-buffer
 
                      (wg-workgroup-associated-bufs workgroup))))
 

	
 
(defun wg-workgroup-strongly-associate-bufobj (workgroup bufobj)
 
  "Strongly associate BUFOBJ with WORKGROUP."
 
  (let* ((uid (wg-bufobj-uid-or-add bufobj))
 
         (remp (wg-removef-p uid (wg-workgroup-weak-buf-uids workgroup)
 
                             :test 'string=))
 
         (addp (wg-pushnew-p uid (wg-workgroup-strong-buf-uids workgroup)
 
                             :test 'string=)))
 
    (when (or remp addp)
 
      (wg-flag-workgroup-modified workgroup)
 
      bufobj)))
 

	
 
(defun wg-workgroup-weakly-associate-bufobj (workgroup bufobj)
 
  "Weakly associate BUFOBJ with WORKGROUP."
 
  (let* ((uid (wg-bufobj-uid-or-add bufobj))
 
         (remp (wg-removef-p uid (wg-workgroup-strong-buf-uids workgroup)
 
                             :test 'string=))
 
         (addp (wg-pushnew-p uid (wg-workgroup-weak-buf-uids workgroup)
 
                             :test 'string=)))
 
    (when (or remp addp)
 
      (wg-flag-workgroup-modified workgroup)
 
      bufobj)))
 

	
 
(defun wg-workgroup-associate-bufobj (workgroup bufobj &optional weak)
 
  "Associate BUFOBJ with WORKGROUP.
 
WEAK non-nil means weakly associate it.  Otherwise strongly associate it."
 
  (if weak (wg-workgroup-weakly-associate-bufobj workgroup bufobj)
 
    (wg-workgroup-strongly-associate-bufobj workgroup bufobj)))
 

	
 
(defun wg-workgroup-dissociate-bufobj (workgroup bufobj)
 
  "Dissociate BUFOBJ from WORKGROUP."
 
  (let* ((uid (wg-bufobj-uid-or-add bufobj))
 
         (rem1p (wg-removef-p uid (wg-workgroup-strong-buf-uids workgroup)
 
                              :test 'string=))
 
         (rem2p (wg-removef-p uid (wg-workgroup-weak-buf-uids workgroup)
 
                              :test 'string=)))
 
    (when (or rem1p rem2p)
 
      (wg-flag-workgroup-modified workgroup)
 
      bufobj)))
 

	
 
(defun wg-workgroup-dissociate-weakly-associated-buffers (workgroup)
 
  "Dissociate from WORKGROUP all weakly associated buffers."
 
  (when (wg-workgroup-weak-buf-uids workgroup)
 
    (wg-flag-workgroup-modified workgroup)
 
    (setf (wg-workgroup-weak-buf-uids workgroup) nil)))
 

	
 
(defun wg-workgroup-dissociate-strongly-associated-buffers (workgroup)
 
  "Dissociate from WORKGROUP all strongly associated buffers."
 
  (when (wg-workgroup-strong-buf-uids workgroup)
 
    (wg-flag-workgroup-modified workgroup)
 
    (setf (wg-workgroup-strong-buf-uids workgroup) nil)))
 

	
 
(defun wg-workgroup-dissociate-all-buffers (workgroup)
 
  "Dissociate from WORKGROUP all its associated buffers."
 
  (wg-workgroup-dissociate-weakly-associated-buffers workgroup)
 
  (wg-workgroup-dissociate-strongly-associated-buffers workgroup))
 

	
 
(defun wg-auto-dissociate-buffer-hook ()
 
  "`kill-buffer-hook' that automatically dissociates buffers from workgroups."
 
  (when wg-dissociate-buffer-on-kill-buffer
 
    (wg-awhen (wg-current-workgroup t)
 
      (wg-workgroup-dissociate-bufobj it (current-buffer)))))
 

	
 
(defun wg-associate-buffer-with-workgroup (&optional workgroup buffer weak)
 
  "Associate BUFFER with WORKGROUP.
 
WEAK non-nil means weakly associate BUFFER."
 
  (interactive (list nil nil current-prefix-arg))
 
  (let* ((workgroup (wg-get-workgroup workgroup))
 
         (buffer (or buffer (current-buffer)))
 
         (bname (buffer-name buffer))
 
         (wgname (wg-workgroup-name workgroup)))
 
    (if (wg-workgroup-associate-bufobj workgroup buffer weak)
 
        (wg-message "%s-associated %S with %s"
 
                    (if weak "Weakly" "Strongly") bname wgname)
 
      (wg-message "%S is already associated with %s" bname wgname))))
 

	
 
(defun wg-associate-visible-buffers-with-workgroup (&optional workgroup weak)
 
  "Associate all buffers visible in `selected-frame' with WORKGROUP.
 
WEAK non-nil means weakly associate them.  Otherwise strongly
 
associate them."
 
  (interactive (list nil current-prefix-arg))
 
  (let ((workgroup (wg-get-workgroup workgroup))
 
        (buffers (mapcar 'window-buffer (window-list))))
 
    (dolist (buffer buffers)
 
      (wg-workgroup-associate-bufobj workgroup buffer weak))
 
    (wg-fontified-message
 
      (:cmd (format "%s associated: " (if weak "Weakly" "Strongly")))
 
      (wg-buffer-list-display buffers))))
 

	
 
(defun wg-dissociate-buffer-from-workgroup (&optional workgroup buffer)
 
  "Dissociate BUFFER from WORKGROUP."
 
  (interactive (list nil nil))
 
  (let ((workgroup (wg-get-workgroup workgroup))
 
        (buffer (or buffer (current-buffer))))
 
    (wg-message
 
     (if (wg-workgroup-dissociate-bufobj workgroup buffer)
 
         "Dissociated %S from %s" "%S isn't associated with %s")
 
     (wg-buffer-name buffer)
 
     (wg-workgroup-name workgroup))))
 

	
 
(defun wg-associate-buffers (workgroup window-or-emacs-window-tree)
 
  "Associate the buffers visible in window elements of
 
WINDOW-OR-EMACS-WINDOW-TREE with the given WORKGROUP.
 
WINDOW-OR-EMACS-WINDOW-TREE must be either a window or a tree of
 
the form produced by `(car (window-tree))'."
 
  (wg-aif (windowp window-or-emacs-window-tree)
 
  (if (windowp window-or-emacs-window-tree)
 
      (with-current-buffer (window-buffer window-or-emacs-window-tree)
 
        (setq wg-buffer-workgroup workgroup))
 
    (dolist (w (cddr window-or-emacs-window-tree))
 
      (when w (wg-associate-buffers workgroup w)))))
 

	
 
(defun wg-workgroup-bufobj-association-type (workgroup bufobj)
 
  "Return BUFOBJ's association-type in WORKGROUP, or nil if unassociated."
 
  (let ((uid (wg-bufobj-uid-or-add bufobj)))
 
    (or (and (member uid (wg-workgroup-strong-buf-uids workgroup)) 'strong)
 
        (and (member uid (wg-workgroup-weak-buf-uids workgroup)) 'weak))))
 

	
 
(defun wg-associate-frame-buffers ()
 
  "Associate visible buffers with the current workgroup.
 
Unless it is currently being deactivated."
 
  (wg-awhen (wg-current-workgroup :noerror)
 
    (unless (member it wg-deactivation-list)
 
      (wg-associate-buffers it (car (window-tree))))))
 

	
 
;; (switch-to-buffer)   -> (read-buffer-to-switch "Asd")
 
;; -> internal-complete-buffer-except -> internal-complete-buffer
 
;; minibuffer-complete  minibuffer-completion-table
 
;; ido-switch-buffer  -> buffer-list
 
;;(global-set-key "\C-d" delete-char)
 
;; fdefinition
 
;; (buffer-list)
 
;; jit-lock-context-fontify
 
;; (wg-workgroup-weak-buf-uids (wg-current-workgroup))
 
;; (wg-workgroup-associated-buf-uids (wg-current-workgroup))
 
;; (wg-workgroup-associated-bufs (wg-current-workgroup))
 
;; (wg-workgroup-associated-buffers (wg-current-workgroup))
 
;; (wg-associate-frame-buffers)
 

	
 
;; (wg-workgroup-dissociate-all-buffers (wg-current-workgroup))
 
;;(fmakunbound 'buffer-list)
 
;;(define-key (current-global-map) [remap buffer-list] 'wg-buffer-list)
 
;; (wg-buffer-list)
 
;;(defun buffer-list (&optional frame)
 
;;  (list (current-buffer)))
 

	
 

	
 
(provide 'workgroups-association)
 
;;; workgroups-association.el ends here
src/workgroups-buf.el
Show inline comments
 
;;; workgroups-buf.el --- BUFFER class
 
;;; Commentary:
 
;;
 
;; Workgroups Data Structures:
 
;;   https://github.com/pashinin/workgroups2/wiki/Workgroups-data-structures
 
;;
 
;;
 
;; BUFFER is the most low level part Workgroups operates with (except
 
;; serializing Emacs objects functions).
 
;;
 
;; Different buffers we have:
 
;;  - live buffers     (just switch-to them)
 
;;  - files/dirs       (open them)
 
;;  - special buffers  (shells, unknown modes - write support for them)
 
;;
 
;; Another different types of "buffers":
 
;;  - standard Emacs buffer (as you know it)
 
;;  - Workgroups Buffer object (Elisp object, a representation of Emacs buffer)
 
;;; Code:
 

	
 
(require 'workgroups-pickel)
 
(require 'workgroups-specialbufs)
 
(require 'workgroups-structs)
 

	
 
;;; Variables
 

	
 
(defvar wg-buffer-workgroup nil
 
  "A workgroup in which this buffer most recently appeared.
 
Buffer-local.")
 
(make-variable-buffer-local 'wg-buffer-workgroup)
 

	
 
(defcustom wg-default-buffer "*scratch*"
 
  "Show this in case everything else fails.
 
When a buffer can't be restored, when creating a blank wg."
 
  :type 'string
 
  :group 'workgroups)
 

	
 

	
 
;;; Functions
 

	
 
(defmacro wg-buf-list ()
 
  "Setf'able `wg-current-session' buf-list slot accessor."
 
  `(wg-session-buf-list (wg-current-session)))
 

	
 
(defun wg-restore-default-buffer (&optional switch)
 
  "Return `wg-default-buffer' and maybe SWITCH to it."
 
  (if switch
 
      (switch-to-buffer wg-default-buffer t)
 
    (get-buffer-create wg-default-buffer)))
 

	
 
(defun wg-restore-existing-buffer (buf &optional switch)
 
  "Return existing buffer from BUF and maybe SWITCH to it."
 
  (wg-when-let ((b (wg-find-buf-in-buffer-list buf (wg-buffer-list-emacs))))
 
    (if switch (switch-to-buffer b t))
 
    (with-current-buffer b
 
      (wg-set-buffer-uid-or-error (wg-buf-uid buf))
 
      b)))
 

	
 
(defun wg-restore-file-buffer (buf &optional switch)
 
  "Restore BUF by finding its file and maybe SWITCH to it.
 
Return the created buffer.
 
If BUF's file doesn't exist, call `wg-restore-default-buffer'"
 
  ;;(wg-when-let ((file-name (wg-buf-file-name buf)))
 
  (let ((file-name (wg-buf-file-name buf)))
 
    (when (and file-name
 
               (or wg-restore-remote-buffers
 
                   (not (file-remote-p file-name))))
 
      (cond ((file-exists-p file-name)
 
             ;; jit ignore errors
 
             ;;(ignore-errors
 
             (condition-case err
 
                 (let ((b (find-file-noselect file-name nil nil nil)))
 
                   (with-current-buffer b
 
                     (rename-buffer (wg-buf-name buf) t)
 
                     (wg-set-buffer-uid-or-error (wg-buf-uid buf))
 
                     (when wg-restore-mark
 
                       (set-mark (wg-buf-mark buf))
 
                       (deactivate-mark))
 
                     (wg-deserialize-buffer-local-variables buf)
 
                     )
 
                   (if switch (switch-to-buffer b))
 
                   b)
 
               (error
 
                (message "Error while restoring a file %s:\n  %s" file-name (error-message-string err))
 
                nil)))
 
            (t
 
             ;; try directory
 
             (if (file-directory-p (file-name-directory file-name))
 
                 (dired (file-name-directory file-name))
 
               (progn
 
                 (message "Attempt to restore nonexistent file: %S" file-name)
 
                 nil))
 
             )))))
 

	
 
(defun wg-restore-special-buffer (buf &optional switch)
 
  "Restore a buffer BUF with DESERIALIZER-FN and maybe SWITCH to it."
 
  (wg-when-let
 
      ((special-data (wg-buf-special-data buf))
 
       (buffer (save-window-excursion
 
                 (condition-case err
 
                     (funcall (car special-data) buf)
 
                   (error (message "Error deserializing %S: %S" (wg-buf-name buf) err)
 
                          nil)))))
 
    (if switch (switch-to-buffer buffer t))
 
    (with-current-buffer buffer
 
      (wg-set-buffer-uid-or-error (wg-buf-uid buf)))
 
    buffer))
 

	
 
(defun wg-restore-buffer (buf &optional switch)
 
  "Restore BUF, return it and maybe SWITCH to it."
 
  (fset 'buffer-list wg-buffer-list-original)
 
  (prog1
 
      (or (wg-restore-existing-buffer buf switch)
 
          (wg-restore-special-buffer buf switch)  ;; non existent dired problem
 
          (wg-restore-file-buffer buf switch)
 
          (progn (wg-restore-default-buffer switch) nil))
 
    (if wg-mess-with-buffer-list
 
        (fset 'buffer-list wg-buffer-list-function))))
 

	
 

	
 

	
 
;;; buffer object utils
 

	
 
(defun wg-buffer-uid (buffer-or-name)
 
  "Return BUFFER-OR-NAME's buffer-local value of `wg-buffer-uid'."
 
  (buffer-local-value 'wg-buffer-uid (wg-get-buffer buffer-or-name)))
 

	
 
(defun wg-bufobj-uid (bufobj)
 
  "Return BUFOBJ's uid."
 
  (cl-etypecase bufobj
 
    (buffer (wg-buffer-uid bufobj))
 
    (wg-buf (wg-buf-uid bufobj))
 
    (string (wg-bufobj-uid (wg-get-buffer bufobj)))))
 

	
 
(defun wg-bufobj-name (bufobj)
 
  "Return BUFOBJ's buffer name."
 
  (cl-etypecase bufobj
 
    (buffer (buffer-name bufobj))
 
    (wg-buf (wg-buf-name bufobj))
 
    (string (wg-buffer-name bufobj))))
 

	
 
(defun wg-bufobj-file-name (bufobj)
 
  "Return BUFOBJ's filename."
 
  (cl-etypecase bufobj
 
    (buffer (buffer-file-name bufobj))
 
    (wg-buf (wg-buf-file-name bufobj))
 
    (string (wg-bufobj-file-name (wg-get-buffer bufobj)))))
 

	
 
(defun wg-buf-major-mode (buf)
 
  "Return BUF's `major-mode'.
 
It's stored in BUF's local-vars list, since it's a local variable."
 
  (wg-aget (wg-buf-local-vars buf) 'major-mode))
 

	
 
(defun wg-buffer-major-mode (bufobj)
 
  "Return BUFOBJ's `major-mode'.
 
It works with Emacs buffer, Workgroups buffer object and a simple string."
 
  (cl-etypecase bufobj
 
    (buffer (wg-buffer-major-mode bufobj))
 
    (wg-buf (wg-buf-major-mode bufobj))
 
    (string (wg-buffer-major-mode bufobj))))
 

	
 
;; `wg-equal-bufobjs' and `wg-find-bufobj' may need to be made a lot smarter
 
(defun wg-equal-bufobjs (bufobj1 bufobj2)
 
  "Return t if BUFOBJ1 is \"equal\" to BUFOBJ2."
 
  (let ((fname1 (wg-bufobj-file-name bufobj1))
 
        (fname2 (wg-bufobj-file-name bufobj2)))
 
    (cond ((and fname1 fname2) (string= fname1 fname2))
 
          ((or fname1 fname2) nil)
 
          ((string= (wg-bufobj-name bufobj1) (wg-bufobj-name bufobj2)) t))))
 

	
 
(defun wg-find-bufobj (bufobj bufobj-list)
 
  "Find BUFOBJ in BUFOBJ-LIST, testing with `wg-equal-bufobjs'."
 
  (cl-find bufobj bufobj-list :test 'wg-equal-bufobjs))
 

	
 
(defun wg-find-bufobj-by-uid (uid bufobj-list)
 
  "Find the bufobj in BUFOBJ-LIST with uid UID."
 
  (cl-find uid bufobj-list :test 'string= :key 'wg-bufobj-uid))
 

	
 
(defun wg-find-buf-in-buf-list (buf buf-list)
 
  "Find BUF in BUF-LIST.
 
This is only here for completeness."
 
  (cl-find buf buf-list))
 

	
 
(defun wg-find-buffer-in-buffer-list (buffer-or-name buffer-list)
 
  "Find BUFFER-OR-NAME in BUFFER-LIST."
 
  (cl-find (wg-get-buffer buffer-or-name) buffer-list :key 'wg-get-buffer))
 

	
 
(defun wg-find-buffer-in-buf-list (buffer-or-name buf-list)
 
  "Find BUFFER-OR-NAME in BUF-LIST."
 
  (wg-aif (wg-buffer-uid buffer-or-name)
 
  (aif (wg-buffer-uid buffer-or-name)
 
      (wg-find-bufobj-by-uid it buf-list)
 
    (wg-find-bufobj buffer-or-name buf-list)))
 

	
 
(defun wg-find-buf-in-buffer-list (buf buffer-list)
 
  "Find BUF in BUFFER-LIST."
 
  (or (wg-find-bufobj-by-uid (wg-buf-uid buf) buffer-list)
 
      (wg-find-bufobj buf buffer-list)))
 

	
 
(defun wg-find-buf-by-uid (uid)
 
  "Find a buf in `wg-buf-list' by UID."
 
  (wg-find-bufobj-by-uid uid (wg-buf-list)))
 

	
 
(defun wg-set-buffer-uid-or-error (uid &optional buffer)
 
  "Set BUFFER's buffer local value of `wg-buffer-uid' to UID.
 
If BUFFER already has a buffer local value of `wg-buffer-uid',
 
and it's not equal to UID, error."
 
  (if wg-buffer-uid
 
      ;;(if (string= wg-buffer-uid uid) uid
 
      ;;  (error "uids don't match %S and %S" uid wg-buffer-uid))
 
      (setq wg-buffer-uid uid)))
 

	
 

	
 
(defun wg-buffer-special-data (buffer)
 
  "Return BUFFER's auxiliary serialization, or nil."
 
  (cl-some (lambda (fn) (funcall fn buffer)) wg-special-buffer-serdes-functions))
 

	
 

	
 
(defun wg-serialize-buffer-local-variables ()
 
  "Return an alist of buffer-local variable symbols and their values.
 
See `wg-buffer-local-variables-alist' for details."
 
  (wg-docar (entry wg-buffer-local-variables-alist)
 
    (wg-dbind (var ser des) entry
 
      (when (local-variable-p var)
 
        (cons var (if ser (funcall ser) (symbol-value var)))))))
 

	
 
(defun wg-buffer-to-buf (buffer)
 
  "Return the serialization (a wg-buf) of Emacs buffer BUFFER."
 
  (with-current-buffer buffer
 
    (wg-make-buf
 
     :name           (buffer-name)
 
     :file-name      (buffer-file-name)
 
     :point          (point)
 
     :mark           (mark)
 
     :local-vars     (wg-serialize-buffer-local-variables)
 
     :special-data   (wg-buffer-special-data buffer))))
 

	
 
(defun wg-add-buffer-to-buf-list (buffer)
 
  "Make a buf from BUFFER, and add it to `wg-buf-list' if necessary.
 
If there isn't already a buf corresponding to BUFFER in
 
`wg-buf-list', make one and add it.  Return BUFFER's uid
 
in either case."
 
  (with-current-buffer buffer
 
    (setq wg-buffer-uid
 
          (wg-aif (wg-find-buffer-in-buf-list buffer (wg-buf-list))
 
          (aif (wg-find-buffer-in-buf-list buffer (wg-buf-list))
 
              (wg-buf-uid it)
 
            (let ((buf (wg-buffer-to-buf buffer)))
 
              (push buf (wg-buf-list))
 
              (wg-buf-uid buf))))))
 

	
 
(defun wg-buffer-uid-or-add (buffer)
 
  "Return BUFFER's uid.
 
If there isn't already a buf corresponding to BUFFER in
 
`wg-buf-list', make one and add it."
 
  (or (wg-buffer-uid buffer) (wg-add-buffer-to-buf-list buffer)))
 

	
 
(defun wg-bufobj-uid-or-add (bufobj)
 
  "If BUFOBJ is a wg-buf, return its uid.
 
If BUFOBJ is a buffer or a buffer name, see `wg-buffer-uid-or-add'."
 
  (cl-etypecase bufobj
 
    (wg-buf (wg-buf-uid bufobj)) ;; possibly also add to `wg-buf-list'
 
    (buffer (wg-buffer-uid-or-add bufobj))
 
    (string (wg-bufobj-uid-or-add (wg-get-buffer bufobj)))))
 

	
 

	
 
(defun wg-reset-buffer (buffer)
 
  "Return BUFFER.
 
Currently only sets BUFFER's `wg-buffer-uid' to nil."
 
  (with-current-buffer buffer (setq wg-buffer-uid nil)))
 

	
 

	
 

	
 
;;; buffer-list-filter commands
 

	
 
(defun wg-next-buffer-internal (buffer-list &optional prev noerror)
 
  "Switch to the next buffer in Workgroups' filtered buffer list."
 
  (when buffer-list
 
    (let* ((cur (current-buffer))
 
           (next (or (wg-cyclic-nth-from-elt cur buffer-list (if prev -1 1))
 
                     (car buffer-list))))
 
      (unless (eq cur next)
 
        (switch-to-buffer next)
 
        (unless prev (bury-buffer cur))
 
        next))))
 

	
 
(defun wg-next-buffer (&optional prev)
 
  "Switch to the next buffer in Workgroups' filtered buffer list.
 
In the post-command message the current buffer is rotated to the
 
middle of the list to more easily see where `wg-previous-buffer'
 
will take you."
 
  (interactive)
 
  (let ((command (if prev 'previous-buffer 'next-buffer)))
 
    (if (not (wg-filter-buffer-list-p))
 
        (call-interactively (wg-prior-mapping workgroups-mode command))
 
      (wg-with-buffer-list-filters command
 
        (wg-awhen (wg-filtered-buffer-list) (wg-next-buffer-internal it prev))
 
        (wg-message (wg-buffer-command-display))))))
 

	
 
(defun wg-update-buffer-in-buf-list (&optional buffer)
 
  "Update BUFFER's corresponding buf in `wg-buf-list'.
 
BUFFER nil defaults to `current-buffer'."
 
  (let ((buffer (or buffer (current-buffer))))
 
    (wg-when-let ((uid (wg-buffer-uid buffer))
 
                  (old-buf (wg-find-buf-by-uid uid))
 
                  (new-buf (wg-buffer-to-buf buffer)))
 
      (setf (wg-buf-uid new-buf) (wg-buf-uid old-buf))
 
      (wg-asetf (wg-buf-list) (cons new-buf (remove old-buf it))))))
 

	
 
(defun wg-update-buf-list (&optional buffer-list)
 
  "Update all bufs in `wg-buf-list' corresponding to buffers in BUFFER-LIST."
 
  (mapc 'wg-update-buffer-in-buf-list (or buffer-list (wg-buffer-list-emacs))))
 

	
 

	
 

	
 

	
 
(defun wg-buffer-list-display (buffer-list)
 
  "Return the BUFFER-LIST display string."
 
  (wg-display-internal
 
   'wg-buffer-display
 
   (if wg-center-rotate-buffer-list-display
 
       (wg-center-rotate-list buffer-list) buffer-list)))
 

	
 
(defun wg-buffer-list-filter-display (&optional workgroup blf-id)
 
  "Return a buffer-list-filter display string from WORKGROUP and BLF-ID."
 
  (wg-fontify
 
    "("
 
    (wg-workgroup-name (wg-get-workgroup workgroup))
 
    ":"
 
    (wg-get-buffer-list-filter-val blf-id 'indicator)
 
    ")"))
 

	
 
(defun wg-buffer-list-filter-prompt (prompt &optional workgroup blf-id)
 
  "Return a prompt string from PROMPT indicating WORKGROUP and BLF-ID."
 
  (wg-fontify
 
    prompt " "
 
    (wg-buffer-list-filter-display workgroup blf-id)
 
    ": "))
 

	
 
(defun wg-buffer-command-display (&optional buffer-list)
 
  "Return the buffer command display string."
 
  (concat
 
   (wg-buffer-list-filter-display) ": "
 
   (wg-buffer-list-display (or buffer-list (wg-filtered-buffer-list)))))
 

	
 

	
 
(defun wg-read-buffer (prompt &optional default require-match)
 
  "Workgroups' version of `read-buffer'.
 
Read with PROMT DEFAULT REQUIRE-MATCH."
 
  (if (not (wg-filter-buffer-list-p))
 
      (funcall (wg-read-buffer-function) prompt default require-match)
 
    (wg-with-buffer-list-filters 'read-buffer
 
      (funcall (wg-read-buffer-function)
 
               (wg-buffer-list-filter-prompt
 
                (wg-aif (string-match ": *$" prompt)
 
                (aif (string-match ": *$" prompt)
 
                    (substring prompt 0 it) prompt))
 
               default require-match))))
 

	
 

	
 

	
 
;;; filtered buffer-list construction
 

	
 
(defun wg-get-buffer-list-filter-id-flexibly (blf-id)
 
  "Return a buffer-list-filter-id one way or another."
 
  (or blf-id wg-current-buffer-list-filter-id 'all))
 

	
 
(defun wg-get-buffer-list-filter-val (id key &optional noerror)
 
  "Return ID's KEY's value in `wg-buffer-list-filter-definitions'.
 
Lots of possible errors here because
 
`wg-buffer-list-filter-definitions' can be modified by the user."
 
  (let ((slot-num (cl-case key (symbol 0) (indicator 1) (constructor 2))))
 
    (if (not slot-num)
 
        (unless noerror
 
          (error "`%S' is not a valid buffer-list-filter definition slot" key))
 
      (let* ((id (wg-get-buffer-list-filter-id-flexibly id))
 
             (entry (assq id (wg-local-value
 
                              'wg-buffer-list-filter-definitions))))
 
        (if (not entry)
 
            (unless noerror
 
              (error "`%S' is an undefined buffer-list-filter" id))
 
          (or (nth slot-num entry)
 
              (unless noerror
 
                (error "Slot `%S' is undefined in `%S's definition"
 
                       key id))))))))
 

	
 
(defun wg-filtered-buffer-list (&optional names workgroup bfl-id initial)
 
  "Return a filtered buffer-list from NAMES, WORKGROUP, BLF-ID and INITIAL.
 
NAMES non-nil means return a list of buffer-names instead of buffer objects.
 
WORKGROUP non-nil should be any workgroup identifier accepted by
 
`wg-get-workgroup'.
 
BLF-ID non-nil should be the identifier of a defined buffer-list-filter.
 
It defaults to `wg-get-buffer-list-filter-val'.
 
INITIAL non-nil should be an initial buffer-list to filter.  It defaults to
 
`wg-interesting-buffers'."
 
  (let ((buffer-list (funcall (wg-get-buffer-list-filter-val
 
                               (wg-get-buffer-list-filter-id-flexibly bfl-id)
 
                               'constructor)
 
                              (wg-get-workgroup workgroup)
 
                              (or initial (wg-interesting-buffers)))))
 
    (if names (mapcar 'wg-buffer-name buffer-list) buffer-list)))
 

	
 

	
 
;; buffer-list filters
 

	
 
(defun wg-buffer-list-filter-all (workgroup initial)
 
  "Return all buffers in INITIAL."
 
  initial)
 

	
 
(defun wg-filter-buffer-list-by-regexp (regexp buffer-list)
 
  "Return only those buffers in BUFFER-LIST with names matching REGEXP."
 
  (cl-remove-if-not (lambda (bname) (string-match regexp bname))
 
                    buffer-list :key 'buffer-name))
 

	
 
(defun wg-filter-buffer-list-by-root-dir (root-dir buffer-list)
 
  "Return only those buffers in BUFFER-LIST visiting files undo ROOT-DIR."
 
  (cl-remove-if-not (lambda (f) (when f (wg-file-under-root-path-p root-dir f)))
 
                    buffer-list :key 'buffer-file-name))
 

	
 
(defun wg-filter-buffer-list-by-major-mode (major-mode buffer-list)
 
  "Return only those buffers in BUFFER-LIST in major-mode MAJOR-MODE."
 
  (cl-remove-if-not (lambda (mm) (eq mm major-mode))
 
                    buffer-list :key 'wg-buffer-major-mode))
 

	
 

	
 
;; Example custom buffer-list-filters
 

	
 
(defun wg-buffer-list-filter-irc (workgroup buffer-list)
 
  "Return only those buffers in BUFFER-LIST with names starting in \"#\"."
 
  (wg-filter-buffer-list-by-regexp "^#" buffer-list))
 

	
 
(defun wg-buffer-list-filter-home-dir (workgroup buffer-list)
 
  "Return only those buffers in BUFFER-LIST visiting files under ~/."
 
  (wg-filter-buffer-list-by-root-dir "~/" buffer-list))
 

	
 

	
 

	
 
;; buffer-list-filter context
 

	
 
(defun wg-buffer-list-filter-order (command)
 
  "Return WORKGROUP's buffer-list-filter order for COMMAND, or a default."
 
  (let ((bfo (wg-local-value 'wg-buffer-list-filter-order-alist)))
 
    (or (wg-aget bfo command) (wg-aget bfo 'default))))
 

	
 
(defmacro wg-prior-mapping (mode command)
 
  "Return whatever COMMAND would call if MODE wasn't on."
 
  `(or (let (,mode) (command-remapping ,command)) ,command))
 

	
 
(defun wg-filter-buffer-list-p ()
 
  "Return the current workgroup when buffer-list-filters are on."
 
  (and workgroups-mode wg-buffer-list-filtration-on (wg-current-workgroup t)))
 

	
 
(defmacro wg-with-buffer-list-filters (command &rest body)
 
  "Create buffer-list filter context for COMMAND, and eval BODY.
 
Binds `wg-current-buffer-list-filter-id' in BODY."
 
  (declare (indent 1))
 
  (wg-with-gensyms (order status)
 
    `(let* ((wg-previous-minibuffer-contents nil)
 
            (,order (wg-buffer-list-filter-order ,command)))
 
       (catch 'wg-result
 
         (while 'your-mom
 
           (let* ((wg-current-buffer-list-filter-id (car ,order))
 
                  (,status (catch 'wg-action (list 'done (progn ,@body)))))
 
             (cl-case (car ,status)
 
               (done (throw 'wg-result (cadr ,status)))
 
               (next (setq ,order (wg-rotate-list ,order 1))
 
                     (setq wg-previous-minibuffer-contents (cadr ,status)))
 
               (prev (setq ,order (wg-rotate-list ,order -1))
 
                     (setq wg-previous-minibuffer-contents
 
                           (cadr ,status))))))))))
 

	
 
(defun wg-toggle-buffer-list-filtration ()
 
  "Toggle `wg-buffer-list-filtration-on'."
 
  (interactive)
 
  (wg-toggle-and-message 'wg-buffer-list-filtration-on))
 

	
 

	
 
(provide 'workgroups-buf)
 
;;; workgroups-buf.el ends here
src/workgroups-specialbufs.el
Show inline comments
 
;;; workgroups-specialbufs --- special buffers serialization
 
;;; Commentary:
 
;;
 
;; TODO:
 
;;  1. Add more special buffers support (that you use)
 
;;  2. Improve existing
 
;;
 
;;; Code:
 

	
 
(require 'workgroups-variables)
 
(require 'workgroups-utils-basic)
 

	
 
(defcustom wg-special-buffer-serdes-functions
 
  '(wg-serialize-comint-buffer
 
    wg-serialize-speedbar-buffer)
 
  "Functions providing serialization/deserialization for complex buffers.
 

	
 
Use `wg-support' macro and this variable will be filled
 
automatically.
 

	
 
An entry should be either a function symbol or a lambda, and should
 
accept a single Emacs buffer object as an argument.
 

	
 
When a buffer is to be serialized, it is passed to each of these
 
functions in turn until one returns non-nil, or the list ends.  A
 
return value of nil indicates that the function can't handle
 
buffers of that type.  A non-nil return value indicates that it
 
can.  The first non-nil return value becomes the buffer's special
 
serialization data.  The return value should be a cons, with a
 
deserialization function (a function symbol or a lambda) as the car,
 
and any other serialization data as the cdr.
 

	
 
When it comes time to deserialize the buffer, the deserialization
 
function (the car of the cons mentioned above) is passed the
 
wg-buf object, from which it should restore the buffer.  The
 
special serialization data itself can be accessed
 
with (cdr (wg-buf-special-data <wg-buf>)).  The deserialization
 
function must return the restored Emacs buffer object.
 

	
 
See the definitions of the functions in this list for examples of
 
how to write your own."
 
  :type 'alist
 
  :group 'workgroups)
 

	
 
;; Dired
 
(wg-support 'dired-mode 'dired
 
            `((deserialize . ,(lambda (buffer vars)
 
                                (when (or wg-restore-remote-buffers
 
                                          (not (file-remote-p default-directory)))
 
                                  (let ((d (wg-get-first-existing-dir)))
 
                                    (if (file-directory-p d) (dired d))))))))
 

	
 
;; `Info-mode'     C-h i
 
(wg-support 'Info-mode 'info
 
            `((save . (Info-current-file Info-current-node))
 
              (deserialize . ,(lambda (buffer vars)
 
                                ;;(with-current-buffer
 
                                ;;    (get-buffer-create (wg-buf-name buffer))
 
                                (wg-aif vars
 
                                (aif vars
 
                                    (if (fboundp 'Info-find-node)
 
                                        (apply #'Info-find-node it))
 
                                  (info)
 
                                  (get-buffer (wg-buf-name buffer)))))))
 

	
 
;; `help-mode'
 
;; Bug: https://github.com/pashinin/workgroups2/issues/29
 
(if nil
 
(wg-support 'help-mode 'help-mode
 
            `((save . (help-xref-stack-item help-xref-stack help-xref-forward-stack))
 
              (deserialize . ,(lambda (buffer vars)
 
                               (wg-dbind (item stack forward-stack) vars
 
                                 (condition-case err
 
                                     (apply (car item) (cdr item))
 
                                   (error (message "%s" err)))
 
                                 (wg-awhen (get-buffer "*Help*")
 
                                   (set-buffer it)
 
                                   (wg-when-boundp (help-xref-stack help-xref-forward-stack)
 
                                     (setq help-xref-stack stack
 
                                           help-xref-forward-stack forward-stack))))))))
 
)
 

	
 
;; ielm
 
(wg-support 'inferior-emacs-lisp-mode 'ielm
 
            `((deserialize . ,(lambda (buffer vars)
 
                                (ielm) (get-buffer "*ielm*")))))
 

	
 
;; Magit status
 
(wg-support 'magit-status-mode 'magit
 
            `((deserialize . ,(lambda (buffer vars)
 
                                (if (file-directory-p default-directory)
 
                                    (magit-status default-directory)
 
                                  (let ((d (wg-get-first-existing-dir)))
 
                                    (if (file-directory-p d) (dired d))))))))
 

	
 
;; Shell
 
(wg-support 'shell-mode 'shell
 
            `((deserialize . ,(lambda (buffer vars)
 
                                (shell (wg-buf-name buffer))))))
 

	
 
;; org-agenda buffer
 
(defun wg-get-org-agenda-view-commands ()
 
  "Return commands to restore the state of Agenda buffer.
 
Can be restored using \"(eval commands)\"."
 
  (interactive)
 
  (when (boundp 'org-agenda-buffer-name)
 
    (if (get-buffer org-agenda-buffer-name)
 
        (with-current-buffer org-agenda-buffer-name
 
          (let* ((p (or (and (looking-at "\\'") (1- (point))) (point)))
 
                 (series-redo-cmd (get-text-property p 'org-series-redo-cmd)))
 
            (if series-redo-cmd
 
                (get-text-property p 'org-series-redo-cmd)
 
              (get-text-property p 'org-redo-cmd)))))))
 

	
 
(defun wg-run-agenda-cmd (f)
 
  "Run commands F in Agenda buffer.
 
You can get these commands using `wg-get-org-agenda-view-commands'."
 
  (when (and (boundp 'org-agenda-buffer-name)
 
             (fboundp 'org-current-line)
 
             (fboundp 'org-goto-line))
 
    (if (get-buffer org-agenda-buffer-name)
 
        (save-window-excursion
 
          (with-current-buffer org-agenda-buffer-name
 
            (let* ((line (org-current-line)))
 
              (if f (eval f))
 
              (org-goto-line line)))))))
 

	
 
(wg-support 'org-agenda-mode 'org-agenda
 
            '((serialize . (lambda (buffer)
 
                             (wg-get-org-agenda-view-commands)))
 
              (deserialize . (lambda (buffer vars)
 
                               (org-agenda-list)
 
                               (wg-awhen (get-buffer org-agenda-buffer-name)
 
                                 (with-current-buffer it
 
                                   (wg-run-agenda-cmd vars))
 
                                 it)))))
 

	
 
;; eshell
 
(wg-support 'eshell-mode 'esh-mode
 
            '((deserialize . (lambda (buffer vars)
 
                               (prog1 (eshell t)
 
                                 (rename-buffer (wg-buf-name buffer) t))))))
 

	
 
;; term-mode
 
;;
 
;; This should work for `ansi-term's, too, as there doesn't seem to
 
;; be any difference between the two except how the name of the
 
;; buffer is generated.
 
;;
 
(wg-support 'term-mode 'term
 
            `((serialize . ,(lambda (buffer)
 
                              (if (get-buffer-process buffer)
 
                                  (wg-last1 (process-command (get-buffer-process buffer)))
 
                                "/bin/bash")))
 
              (deserialize . ,(lambda (buffer vars)
 
                                (cl-labels ((term-window-width () 80)
 
                                            (window-height () 24))
 
                                  (prog1 (term vars)
 
                                    (rename-buffer (wg-buf-name buffer) t)))))))
 

	
 
;; Python
 
(wg-support 'inferior-python-mode 'python
 
            `((save . (python-shell-interpreter python-shell-interpreter-args))
 
              (deserialize . ,(lambda (buffer vars)
 
                                (wg-dbind (pythoncmd pythonargs) vars
 
                                  (run-python (concat pythoncmd " " pythonargs))
 
                                  (wg-awhen (get-buffer (process-buffer
 
                                                         (python-shell-get-or-create-process)))
 
                                    (with-current-buffer it (goto-char (point-max)))
 
                                    it))))))
 

	
 

	
 
;; Sage shell ;;
 
(wg-support 'inferior-sage-mode 'sage-mode
 
            `((deserialize . ,(lambda (buffer vars)
 
                                (save-window-excursion
 
                                  (if (boundp' sage-command)
 
                                      (run-sage t sage-command t)))
 
                                (if (boundp 'sage-buffer)
 
                                    (wg-awhen (and
 
                                               sage-buffer)
 
                                      (set-buffer it)
 
                                      (switch-to-buffer sage-buffer)
 
                                      (goto-char (point-max))))))))
 

	
 
;; `inferior-ess-mode'     M-x R
 
(wg-support 'inferior-ess-mode 'ess-inf
 
            `((save . (inferior-ess-program))
 
              (deserialize . ,(lambda (buffer vars)
 
                                (wg-dbind (cmd) vars
 
                                  (let ((ess-ask-about-transfile nil)
 
                                        (ess-ask-for-ess-directory nil)
 
                                        (ess-history-file nil))
 
                                    (R)
 
                                    (get-buffer (wg-buf-name buffer))))))))
 

	
 
;; `inferior-octave-mode'
 
(wg-support 'inferior-octave-mode 'octave
 
            `((deserialize . ,(lambda (buffer vars)
 
                                (prog1 (run-octave)
 
                                  (rename-buffer (wg-buf-name buffer) t))))))
 

	
 
;; `prolog-inferior-mode'
 
(wg-support 'prolog-inferior-mode 'prolog
 
            `((deserialize . ,(lambda (buffer vars)
 
                                (save-window-excursion
 
                                  (run-prolog nil))
 
                                (switch-to-buffer "*prolog*")
 
                                (goto-char (point-max))))))
 

	
 
;; `ensime-inf-mode'
 
(wg-support 'ensime-inf-mode 'ensime
 
            `((deserialize . ,(lambda (buffer vars)
 
                                (save-window-excursion
 
                                  (ensime-inf-switch))
 
                                (when (boundp 'ensime-inf-buffer-name)
 
                                  (switch-to-buffer ensime-inf-buffer-name)
 
                                  (goto-char (point-max)))))))
 

	
 
;; compilation-mode
 
;;
 
;; I think it's not a good idea to compile a program just to switch
 
;; workgroups. So just restoring a buffer name.
 
(wg-support 'compilation-mode 'compile
 
            `((serialize . ,(lambda (buffer)
 
                              (if (boundp' compilation-arguments) compilation-arguments)))
 
              (deserialize . ,(lambda (buffer vars)
 
                                (save-window-excursion
 
                                  (get-buffer-create (wg-buf-name buffer)))
 
                                (with-current-buffer (wg-buf-name buffer)
 
                                  (when (boundp' compilation-arguments)
 
                                    (make-local-variable 'compilation-arguments)
 
                                    (setq compilation-arguments vars)))
 
                                (switch-to-buffer (wg-buf-name buffer))
 
                                (goto-char (point-max))))))
 

	
 
;; grep-mode
 
;; see grep.el - `compilation-start' - it is just a compilation buffer
 
;; local variables:
 
;; `compilation-arguments' == (cmd mode nil nil)
 
(wg-support 'grep-mode 'grep
 
            `((serialize . ,(lambda (buffer)
 
                              (if (boundp' compilation-arguments) compilation-arguments)))
 
              (deserialize . ,(lambda (buffer vars)
 
                                (compilation-start (car vars) (nth 1 vars))
 
                                (switch-to-buffer "*grep*")))))
 

	
 

	
 
;; speedbar-mode
 
(defun wg-deserialize-speedbar-buffer (buf)
 
  "Deserialize speedbar-buffer BUF."
 
  (when (and (require 'speedbar nil 'noerror)
 
             (require 'dframe nil 'noerror))
 
    (wg-dbind (this-function args) (wg-buf-special-data buf)
 
      (let ((default-directory (car args))
 
            bufname)
 
        (if (boundp 'sr-speedbar-buffer-name)
 
            (setq bufname sr-speedbar-buffer-name)
 
          (setq bufname "*SPEEDBAR*"))
 
        (when (and (fboundp 'speedbar-mode)
 
                   (fboundp 'speedbar-reconfigure-keymaps)
 
                   (fboundp 'speedbar-update-contents)
 
                   (fboundp 'speedbar-set-timer))
 
          (with-no-warnings
 
            (setq speedbar-buffer (get-buffer-create bufname))
 
            (setq speedbar-frame (selected-frame)
 
                  dframe-attached-frame (selected-frame)
 
                  speedbar-select-frame-method 'attached
 
                  speedbar-verbosity-level 0
 
                  speedbar-last-selected-file nil)
 
            (set-buffer speedbar-buffer)
 
            (speedbar-mode)
 
            (speedbar-reconfigure-keymaps)
 
            (speedbar-update-contents)
 
            (speedbar-set-timer 1)
 
            (set-window-dedicated-p (get-buffer-window bufname) t)
 
            (switch-to-buffer bufname)))
 
        (current-buffer)
 
        ))))
 

	
 

	
 
(defun wg-serialize-speedbar-buffer (buffer)
 
  "Serialize speedbar BUFFER."
 
  (with-current-buffer buffer
 
    (if (fboundp 'speedbar-mode)
 
        (when (eq major-mode 'speedbar-mode)
 
          (list 'wg-deserialize-speedbar-buffer
 
                (list default-directory)
 
                )))))
 

	
 

	
 
(defun wg-deserialize-slime-buffer (buf)
 
  "Deserialize `slime' buffer BUF."
 
  (when (require 'slime nil 'noerror)
 
    (wg-dbind (this-function args) (wg-buf-special-data buf)
 
      (let ((default-directory (car args))
 
            (arguments (nth 1 args)))
 
        (when (and (fboundp 'slime-start*)
 
                   (fboundp 'slime-process))
 
          (save-window-excursion
 
            (slime-start* arguments))
 
          (switch-to-buffer (process-buffer (slime-process)))
 
          (current-buffer))))))
 

	
 
;; `comint-mode'  (general mode for all shells)
 
;;
 
;; It may have different shells. So we need to determine which shell is
 
;; now in `comint-mode' and how to restore it.
 
;;
 
;; Just executing `comint-exec' may be not enough because we can miss
 
;; some hooks or any other stuff that is executed when you run a
 
;; specific shell.
 
(defun wg-serialize-comint-buffer (buffer)
 
  "Serialize comint BUFFER."
 
  (with-current-buffer buffer
 
    (if (fboundp 'comint-mode)
 
        (when (eq major-mode 'comint-mode)
 
          ;; `slime-inferior-lisp-args' var is used when in `slime'
 
          (when (and (boundp 'slime-inferior-lisp-args)
 
                     slime-inferior-lisp-args)
 
            (list 'wg-deserialize-slime-buffer
 
                  (list default-directory slime-inferior-lisp-args)
 
                ))))))
 

	
 
;; inf-mongo
 
;; https://github.com/tobiassvn/inf-mongo
 
;; `mongo-command' - command used to start inferior mongo
 
(wg-support 'inf-mongo-mode 'inf-mongo
 
            `((serialize . ,(lambda (buffer)
 
                              (if (boundp 'inf-mongo-command) inf-mongo-command)))
 
              (deserialize . ,(lambda (buffer vars)
 
                                (save-window-excursion
 
                                  (when (fboundp 'inf-mongo)
 
                                    (inf-mongo vars)))
 
                                (when (get-buffer "*mongo*")
 
                                  (switch-to-buffer "*mongo*")
 
                                  (goto-char (point-max)))))))
 

	
 
(defun wg-temporarily-rename-buffer-if-exists (buffer)
 
  "Rename BUFFER if it exists."
 
  (when (get-buffer buffer)
 
    (with-current-buffer buffer
 
      (rename-buffer "*wg--temp-buffer*" t))))
 

	
 
;; SML shell
 
;; Functions to serialize deserialize inferior sml buffer
 
;; `inf-sml-program' is the program run as inferior sml, is the
 
;; `inf-sml-args' are the extra parameters passed, `inf-sml-host'
 
;; is the host on which sml was running when serialized
 
(wg-support 'inferior-sml-mode 'sml-mode
 
            `((serialize . ,(lambda (buffer)
 
                              (list (if (boundp 'sml-program-name) sml-program-name)
 
                                    (if (boundp 'sml-default-arg) sml-default-arg)
 
                                    (if (boundp 'sml-host-name) sml-host-name))))
 
              (deserialize . ,(lambda (buffer vars)
 
                                (wg-dbind (program args host) vars
 
                                  (save-window-excursion
 
                                    ;; If a inf-sml buffer already exists rename it temporarily
 
                                    ;; otherwise `run-sml' will simply switch to the existing
 
                                    ;; buffer, however we want to create a separate buffer with
 
                                    ;; the serialized name
 
                                    (let* ((inf-sml-buffer-name (concat "*"
 
                                                                        (file-name-nondirectory program)
 
                                                                        "*"))
 
                                           (existing-sml-buf (wg-temporarily-rename-buffer-if-exists
 
                                                              inf-sml-buffer-name)))
 
                                      (with-current-buffer (run-sml program args host)
 
                                        ;; Rename the buffer
 
                                        (rename-buffer (wg-buf-name buffer) t)
 

	
 
                                        ;; Now we can re-rename the previously renamed buffer
 
                                        (when existing-sml-buf
 
                                          (with-current-buffer existing-sml-buf
 
                                            (rename-buffer inf-sml-buffer-name t))))))
 
                                  (switch-to-buffer (wg-buf-name buffer))
 
                                  (goto-char (point-max)))))))
 

	
 
;; Geiser repls
 
;; http://www.nongnu.org/geiser/
 
(wg-support 'geiser-repl-mode 'geiser
 
            `((save . (geiser-impl--implementation))
 
              (deserialize . ,(lambda (buffer vars)
 
                                (when (fboundp 'run-geiser)
 
                                  (wg-dbind (impl) vars
 
                                    (run-geiser impl)
 
                                    (goto-char (point-max))))
 
                                (switch-to-buffer (wg-buf-name buffer))))))
 

	
 
;; w3m-mode
 
(wg-support 'w3m-mode 'w3m
 
            `((save . (w3m-current-url))
 
              (deserialize . ,(lambda (buffer vars)
 
                                (wg-dbind (url) vars
 
                                  (w3m-goto-url url))))))
 

	
 
;; notmuch
 
(wg-support 'notmuch-hello-mode 'notmuch
 
            `((deserialize . ,(lambda (buffer vars)
 
                                (notmuch)
 
                                (get-buffer (wg-buf-name buffer))))))
 

	
 
;; Wanderlust modes:
 
;; WL - folders
 
;;(defun wg-deserialize-wl-folders-buffer (buf)
 
;;  ""
 
;;  (if (fboundp 'wl)
 
;;      (wg-dbind (this-function) (wg-buf-special-data buf)
 
;;        ;;(when (not (eq major-mode 'wl-folder-mode))
 
;;        (wl)
 
;;        (goto-char (point-max))
 
;;        (current-buffer)
 
;;        )))
 
;;
 
;;(defun wg-serialize-wl-folders-buffer (buffer)
 
;;  ""
 
;;  (if (fboundp 'wl)
 
;;      (with-current-buffer buffer
 
;;        (when (eq major-mode 'wl-folder-mode)
 
;;          (list 'wg-deserialize-wl-folders-buffer
 
;;                )))))
 

	
 
;; WL - summary mode (list of mails)
 
;;(defun wg-deserialize-wl-summary-buffer (buf)
 
;;  ""
 
;;  (interactive)
 
;;  (if (fboundp 'wl)
 
;;      (wg-dbind (this-function param-list) (wg-buf-special-data buf)
 
;;        (when (not (eq major-mode 'wl-summary-mode))
 
;;          (let ((fld-name (car param-list)))
 
;;            ;;(switch-to-buffer "*scratch*")
 
;;            ;;(wl)
 
;;            ;;(wl-folder-jump-folder fld-name)
 
;;            ;;(message fld-name)
 
;;            ;;(goto-char (point-max))
 
;;            ;;(insert fld-name)
 
;;            (current-buffer)
 
;;          )))))
 
;;
 
;;(defun wg-serialize-wl-summary-buffer (buffer)
 
;;  ""
 
;;  (if (fboundp 'wl)
 
;;      (with-current-buffer buffer
 
;;        (when (eq major-mode 'wl-summary-mode)
 
;;          (list 'wg-deserialize-wl-summary-buffer
 
;;                (wg-take-until-unreadable (list wl-summary-buffer-folder-name))
 
;;                )))))
 
;;
 
;;
 
;;;; mime-view-mode
 
;;
 
;;(defun wg-deserialize-mime-view-buffer (buf)
 
;;  ""
 
;;  (wg-dbind (this-function) (wg-buf-special-data buf)
 
;;    (when (not (eq major-mode 'mime-view-mode))
 
;;      ;;(wl-summary-enter-handler 3570)     ; only in wl-summary-mode
 
;;      ;;(wl-summary-enter-handler)     ; only in wl-summary-mode
 
;;      (current-buffer)
 
;;      )))
 
;;
 
;;(defun wg-serialize-mime-view-buffer (buffer)
 
;;  ""
 
;;  (with-current-buffer buffer
 
;;    (when (eq major-mode 'mime-view-mode)
 
;;      (list 'wg-deserialize-mime-view-buffer
 
;;            ))))
 

	
 

	
 
;; emms-playlist-mode
 
;;
 
;; Help me on this one:
 
;; 1. How to start emms without any user interaction?
 
;;
 
;;(defun wg-deserialize-emms-buffer (buf)
 
;;  "Deserialize emms-playlist buffer BUF."
 
;;  (when (require 'emms-setup nil 'noerror)
 
;;    (require 'emms-player-mplayer)
 
;;    (emms-standard)
 
;;    (emms-default-players)
 
;;    (if (fboundp 'emms-playlist-mode)
 
;;        (wg-dbind (this-function args) (wg-buf-special-data buf)
 
;;          (let ((default-directory (car args)))
 
;;            (save-window-excursion
 
;;              ;;(emms)
 
;;              (if (or (null emms-playlist-buffer)
 
;;                      (not (buffer-live-p emms-playlist-buffer)))
 
;;                  ;;(call-interactively 'emms-add-file)
 
;;                  (emms-source-directory "/usr/data/disk_3/Music/SORT/")
 
;;                ))
 
;;            ;; (emms)
 
;;            ;;(with-current-buffer emms-playlist-buffer-name
 
;;            ;;(emms-source-playlist-directory-tree "/usr/data/disk_3/Music/SORT/")
 
;;            ;;(emms-source-directory "/usr/data/disk_3/Music/SORT")
 
;;            ;;(switch-to-buffer emms-playlist-buffer-name)
 
;;            (emms-playlist-mode-go)
 
;;            (current-buffer)
 
;;            )))))
 
;;
 
;;(defun wg-serialize-emms-buffer (buffer)
 
;;  "Serialize emms BUFFER."
 
;;  (with-current-buffer buffer
 
;;    (if (fboundp 'emms-playlist-mode)
 
;;        (when (eq major-mode 'emms-playlist-mode)
 
;;          (list 'wg-deserialize-emms-buffer
 
;;                (wg-take-until-unreadable (list default-directory))
 
;;                )))))
 

	
 

	
 
;;; buffer-local variable serdes
 

	
 
(defun wg-serialize-buffer-mark-ring ()
 
  "Return a new list of the positions of the marks in `mark-ring'."
 
  (mapcar 'marker-position mark-ring))
 

	
 
(defun wg-deserialize-buffer-mark-ring (positions)
 
  "Set `mark-ring' to a new list of markers created from POSITIONS."
 
  (setq mark-ring
 
        (mapcar (lambda (pos) (set-marker (make-marker) pos))
 
                positions)))
 

	
 
(defun wg-deserialize-buffer-major-mode (major-mode-symbol)
 
  "Conditionally retore MAJOR-MODE-SYMBOL in `current-buffer'."
 
  (and (fboundp major-mode-symbol)
 
       (not (eq major-mode-symbol major-mode))
 
       (funcall major-mode-symbol)))
 

	
 
(defun wg-deserialize-buffer-local-variables (buf)
 
  "Restore BUF's buffer local variables in `current-buffer'."
 
  (cl-loop for ((var . val) . rest) on (wg-buf-local-vars buf)
 
           do (wg-awhen (assq var wg-buffer-local-variables-alist)
 
                (wg-dbind (var ser des) it
 
                  (if des (funcall des val)
 
                    (set var val))))))
 

	
 
(provide 'workgroups-specialbufs)
 
;;; workgroups-specialbufs.el ends here
src/workgroups-utils-basic.el
Show inline comments
 
;;; workgroups-utils.el --- Utilities used by Workgroups
 
;;; Commentary:
 
;;
 
;; A bunch of general purpose-ish utilities used by Workgroups.
 
;;
 
;;; Code:
 

	
 
;;; utils used in macros
 

	
 
(require 'cl-lib)
 
(require 'anaphora)
 
(require 'workgroups-faces)
 
(require 'workgroups-variables)
 

	
 
(defmacro wg-with-gensyms (syms &rest body)
 
  "Bind all symbols in SYMS to `gensym's, and eval BODY."
 
  (declare (indent 1))
 
  `(let (,@(mapcar (lambda (sym) `(,sym (cl-gensym))) syms)) ,@body))
 

	
 
(defmacro wg-dbind (args expr &rest body)
 
  "Bind the variables in ARGS to the result of EXPR and execute BODY.
 
Abbreviation of `destructuring-bind'."
 
  (declare (indent 2))
 
  `(cl-destructuring-bind ,args ,expr ,@body))
 

	
 
(defun wg-partition (list &optional n step)
 
  "Take LIST, return a list of N length sublists, offset by STEP.
 
N defaults to 2, and STEP defaults to N.
 
Iterative to prevent stack overflow."
 
  (let* ((n (or n 2)) (step (or step n)) acc)
 
    (while list
 
      (push (wg-take list n) acc)
 
      (setq list (nthcdr step list)))
 
    (nreverse acc)))
 

	
 

	
 

	
 
;;; bindings
 

	
 
(defmacro wg-if-let (cond-form then &rest else)
 
  "Bind VAR to the return value of COND.  If VAR is non-nil, do THEN.
 
Else do ELSE...
 

	
 
\(fn ((VAR COND) THEN ELSE...)"
 
  (declare (indent 2))
 
  `(let (,cond-form)
 
     (if ,(car cond-form) ,then ,@else)))
 

	
 
(defmacro wg-when-let (binds &rest body)
 
  "Like `let*' but when all BINDS are non-nil - eval BODY."
 
  (declare (indent 1))
 
  (wg-dbind (bind . binds) binds
 
    (when (consp bind)
 
      `(let (,bind)
 
         (when ,(car bind)
 
           ,(if (not binds) `(progn ,@body)
 
              `(wg-when-let ,binds ,@body)))))))
 

	
 
(defmacro wg-when-boundp (symbols &rest body)
 
  "When all SYMBOLS are bound, `eval' BODY."
 
  (declare (indent 1))
 
  `(when (and ,@(mapcar (lambda (sym) `(boundp ',sym)) symbols))
 
     ,@body))
 

	
 

	
 

	
 
;;; do-style wrappers
 

	
 
(defmacro wg-docar (spec &rest body)
 
  "do-style wrapper for `mapcar'.
 

	
 
\(fn (VAR LIST) BODY...)"
 
  (declare (indent 1))
 
  `(mapcar (lambda (,(car spec)) ,@body) ,(cadr spec)))
 

	
 
(defmacro wg-dohash (spec &rest body)
 
  "do-style wrapper for `maphash'.
 

	
 
\(fn (KEY VALUE TABLE [RESULT]) BODY...)"
 
  (declare (indent 1))
 
  (wg-dbind (key val table &optional result) spec
 
    `(progn (maphash (lambda (,key ,val) ,@body) ,table) ,result)))
 

	
 
(defmacro wg-doconcat (spec &rest body)
 
  "do-style wrapper for `mapconcat'.
 

	
 
\(fn (VAR SEQ [SEPARATOR]) BODY...)"
 
  (declare (indent 1))
 
  (wg-dbind (elt seq &optional sep) spec
 
    `(mapconcat (lambda (,elt) ,@body) ,seq (or ,sep ""))))
 

	
 

	
 

	
 
;;; anaphora
 

	
 
(defmacro wg-aif (test then &rest else)
 
  "Anaphoric `if'."
 
  (declare (indent 2))
 
  `(let ((it ,test)) (if it ,then ,@else)))
 

	
 
(defmacro wg-awhen (test &rest body)
 
  "Anaphoric `when'."
 
  (declare (indent 1))
 
  `(wg-aif ,test (progn ,@body)))
 
  `(aif ,test (progn ,@body)))
 

	
 
(defmacro wg-asetf (&rest places-and-values)
 
  "Anaphoric `setf'."
 
  `(progn ,@(mapcar (lambda (pv) `(let ((it ,(car pv))) (setf ,@pv)))
 
                    (wg-partition places-and-values 2))))
 

	
 

	
 

	
 
;;; other control structures
 

	
 
(defmacro wg-destructuring-dolist (spec &rest body)
 
  "Loop over a list.
 
Evaluate BODY, destructuring LIST into SPEC, then evaluate RESULT
 
to get a return value, defaulting to nil.  The only hitch is that
 
spec must end in dotted style, collecting the rest of the list
 
into a var, like so: (a (b c) . rest)
 

	
 
\(fn (SPEC LIST [RESULT]) BODY...)"
 
  (declare (indent 1))
 
  (wg-dbind (loopspec list &optional result) spec
 
    (let ((rest (cdr (last loopspec))))
 
      (wg-with-gensyms (list-sym)
 
        `(let ((,list-sym ,list))
 
           (while ,list-sym
 
             (wg-dbind ,loopspec ,list-sym
 
               ,@body
 
               (setq ,list-sym ,rest)))
 
           ,result)))))
 

	
 

	
 
;;; numbers
 

	
 
(defun wg-step-to (n m step)
 
  "Increment or decrement N toward M by STEP.
 
Return M when the difference between N and M is less than STEP."
 
  (cond ((= n m) n)
 
        ((< n m) (min (+ n step) m))
 
        ((> n m) (max (- n step) m))))
 

	
 
(defun wg-within (num lo hi &optional hi-inclusive)
 
  "Return t when NUM is within bounds LO and HI.
 
HI-INCLUSIVE non-nil means the HI bound is inclusive."
 
  (and (>= num lo) (if hi-inclusive (<= num hi) (< num hi))))
 

	
 
(defun wg-int-to-b36-one-digit (i)
 
  "Return a character in 0..9 or A..Z from I, and integer 0<=I<32.
 
Cribbed from `org-id-int-to-b36-one-digit'."
 
  (cond ((not (wg-within i 0 36))
 
         (error "%s out of range" i))
 
        ((< i 10) (+ ?0 i))
 
        ((< i 36) (+ ?A i -10))))
 

	
 
(defun wg-b36-to-int-one-digit (i)
 
  "Turn a character 0..9, A..Z, a..z into a number 0..61.
 
The input I may be a character, or a single-letter string.
 
Cribbed from `org-id-b36-to-int-one-digit'."
 
  (and (stringp i) (setq i (string-to-char i)))
 
  (cond ((and (>= i ?0) (<= i ?9)) (- i ?0))
 
        ((and (>= i ?A) (<= i ?Z)) (+ (- i ?A) 10))
 
        (t (error "Invalid b36 character"))))
 

	
 
(defun wg-int-to-b36 (i &optional length)
 
  "Return a base 36 string from I."
 
  (let ((base 36) b36)
 
    (cl-labels ((add-digit () (push (wg-int-to-b36-one-digit (mod i base)) b36)
 
                         (setq i (/ i base))))
 
      (add-digit)
 
      (while (> i 0) (add-digit))
 
      (setq b36 (cl-map 'string 'identity b36))
 
      (if (not length) b36
 
        (concat (make-string (max 0 (- length (length b36))) ?0) b36)))))
 

	
 
(defun wg-b36-to-int (str)
 
  "Convert STR, a base-36 string, into the corresponding integer.
 
Cribbed from `org-id-b36-to-int'."
 
  (let ((result 0))
 
    (mapc (lambda (i)
 
            (setq result (+ (* result 36)
 
                            (wg-b36-to-int-one-digit i))))
 
          str)
 
    result))
 

	
 

	
 

	
 
;;; lists
 

	
 
(defmacro wg-removef-p (item seq-place &rest keys)
 
  "If ITEM is a `member*' of SEQ-PLACE, remove it from SEQ-PLACE and return t.
 
Otherwise return nil.  KEYS can be any keywords accepted by `remove*'."
 
  `(> (length ,seq-place)
 
      (length (setf ,seq-place (cl-remove ,item ,seq-place ,@keys)))))
 

	
 
(defmacro wg-pushnew-p (item seq-place &rest keys)
 
  "If ITEM is not a `member' of SEQ-PLACE, push it to SEQ-PLACE and return t.
 
Otherwise return nil.  KEYS can be any keyword args accepted by `pushnew'."
 
  `(< (length ,seq-place)
 
      (length (cl-pushnew ,item ,seq-place ,@keys))))
 

	
 
(defun wg-last1 (list)
 
  "Return the last element of LIST."
 
  (car (last list)))
 

	
 
(defun wg-take (list n)
 
  "Return a list of the first N elts in LIST."
 
  (butlast list (- (length list) n)))
 

	
 
(defun wg-leave (list n)
 
  "Return a list of the last N elts in LIST."
 
  (nthcdr (- (length list) n) list))
 

	
 
(defun wg-rnth (n list)
 
  "Return the Nth element of LIST, counting from the end."
 
  (nth (- (length list) n 1) list))
 

	
 
(defun wg-take-until-fail (pred list)
 
  "Take elements from LIST up to the first element on which PRED fails."
 
  (let (taken)
 
    (catch 'result
 
      (dolist (elt list (nreverse taken))
 
        (if (funcall pred elt) (push elt taken)
 
          (throw 'result (nreverse taken)))))))
 

	
 
(defun wg-range (start end)
 
  "Return a list of integers from START up to but not including END."
 
  (let (accum)
 
    (dotimes (i (- end start) (nreverse accum))
 
      (push (+ start i) accum))))
 

	
 
(defun wg-rotate-list (list &optional offset)
 
  "Rotate LIST by OFFSET.  Positive OFFSET rotates left, negative right."
 
  (when list
 
    (let ((split (mod (or offset 1) (length list))))
 
      (append (nthcdr split list) (wg-take list split)))))
 

	
 
(defun wg-center-rotate-list (list)
 
  "Rotate LIST so it's first elt is in the center.  When LIST's
 
length is even, the first elt is left nearer the front."
 
  (wg-rotate-list list (- (/ (1- (length list)) 2))))
 

	
 
(defun wg-insert-after (elt list index)
 
  "Insert ELT into LIST after INDEX."
 
  (let ((new-list (cl-copy-list list)))
 
    (push elt (cdr (nthcdr index new-list)))
 
    new-list))
 

	
 
(defun wg-insert-before (elt list index)
 
  "Insert ELT into LIST before INDEX."
 
  (if (zerop index) (cons elt list)
 
    (wg-insert-after elt list (1- index))))
 

	
 
(defun wg-move-elt (elt list index &rest keys)
 
  "Move ELT before INDEX in LIST.
 
KEYS is passed to `remove*'."
 
  (wg-insert-before elt (apply 'cl-remove elt list keys) index))
 

	
 
(defun wg-cyclic-nth (list n)
 
  "Return the Nth element of LIST, modded by the length of list."
 
  (nth (mod n (length list)) list))
 

	
 
(defun wg-cyclic-offset-elt (elt list n)
 
  "Cyclically offset ELT's position in LIST by N."
 
  (wg-when-let ((pos (cl-position elt list)))
 
    (wg-move-elt elt list (mod (+ n pos) (length list)))))
 

	
 
(defun wg-cyclic-nth-from-elt (elt list n &rest keys)
 
  "Return the elt in LIST N places cyclically from ELT.
 
If ELT is not present is LIST, return nil.
 
KEYS is passed to `position'."
 
  (wg-when-let ((pos (apply 'cl-position elt list keys)))
 
    (wg-cyclic-nth list (+ pos n))))
 

	
 
(defun wg-util-swap (elt1 elt2 list)
 
  "Return a copy of LIST with ELT1 and ELT2 swapped.
 
Return nil when ELT1 and ELT2 aren't both present."
 
  (wg-when-let ((p1 (cl-position elt1 list))
 
                (p2 (cl-position elt2 list)))
 
    (wg-move-elt elt1 (wg-move-elt elt2 list p1) p2)))
 

	
 
(defun wg-dups-p (list &rest keys)
 
  "Return non-nil when LIST contains duplicate elements.
 

	
 
Keywords supported: :test :key
 

	
 
\(fn LIST [KEYWORD VALUE]...)"
 
  (let ((test (or (plist-get keys :test) 'eq))
 
        (key (or (plist-get keys :key) 'identity)))
 
    (cl-loop for (elt . rest) on list
 
             for elt = (funcall key elt)
 
             when (cl-find elt rest :test test :key key) return elt)))
 

	
 
(defun wg-string-list-union (&optional list1 list2)
 
  "Return the `union' of LIST1 and LIST2, using `string=' as the test.
 
This only exists to get rid of duplicate lambdas in a few reductions."
 
  (cl-union list1 list2 :test 'string=))
 

	
 

	
 

	
 
;;; alists
 

	
 
(defun wg-make-alist (&rest kvps)
 
  "Return a new alist from KVPS."
 
  (let (alist)
 
    (while kvps
 
      (push (cons (car kvps) (cadr kvps)) alist)
 
      (setq kvps (cddr kvps)))
 
    (nreverse alist)))
 

	
 
(defun wg-aget (alist key &optional default)
 
  "Return the value of KEY in ALIST. Uses `assq'.
 
If PARAM is not found, return DEFAULT which defaults to nil."
 
  (wg-aif (assq key alist) (cdr it) default))
 
  (aif (assq key alist) (cdr it) default))
 

	
 
(defun wg-acopy (alist)
 
  "Return a copy of ALIST's toplevel list structure."
 
  (mapcar (lambda (kvp) (cons (car kvp) (cdr kvp))) alist))
 

	
 
(defun wg-aput (alist key value)
 
  "Return a new alist from ALIST with KEY's value set to VALUE."
 
  (let* ((found nil)
 
         (new (wg-docar (kvp alist)
 
                (if (not (eq key (car kvp))) kvp
 
                  (setq found (cons key value))))))
 
    (if found new (cons (cons key value) new))))
 

	
 
(defun wg-aremove (alist key)
 
  "`remove' KEY's key-value-pair from ALIST."
 
  (remove (assoc key alist) alist))
 

	
 

	
 
;;; symbols and strings
 

	
 
(defun wg-toggle (symbol)
 
  "Toggle SYMBOL's truthiness."
 
  (set symbol (not (symbol-value symbol))))
 

	
 
(defun wg-symcat (&rest symbols-and-strings)
 
  "Return a new interned symbol by concatenating SYMBOLS-AND-STRINGS."
 
  (intern (mapconcat (lambda (obj) (if (symbolp obj) (symbol-name obj) obj))
 
                     symbols-and-strings "")))
 

	
 
(defun wg-make-string (times string &optional separator)
 
  "Like `make-string', but includes a separator."
 
  (mapconcat 'identity (make-list times string) (or separator "")))
 

	
 

	
 

	
 
;;; buffers
 

	
 
(defun wg-get-buffer (buffer-or-name)
 
  "Return BUFFER-OR-NAME's buffer, or error."
 
  (or (get-buffer buffer-or-name)
 
      (error "%S does not identify a buffer" buffer-or-name)))
 

	
 
(defun wg-buffer-name (buffer-or-name)
 
  "Return BUFFER-OR-NAME's `buffer-name', or error."
 
  (buffer-name (wg-get-buffer buffer-or-name)))
 

	
 
(defun wg-buffer-file-name (buffer-or-name)
 
  "Return BUFFER-OR-NAME's `buffer-file-name', or error."
 
  (buffer-file-name (wg-get-buffer buffer-or-name)))
 

	
 
(defun wg-buffer-major-mode (buffer-or-name)
 
  "Return BUFFER's major-mode."
 
  (with-current-buffer buffer-or-name major-mode))
 

	
 
(defun wg-current-buffer-p (buffer-or-name)
 
  "Return t if BUFFER-OR-NAME is the current buffer, nil otherwise."
 
  (eq (wg-get-buffer buffer-or-name) (current-buffer)))
 

	
 
(defmacro wg-buffer-local-setq (buffer var value)
 
  "`setq' VAR to VALUE while BUFFER is current.
 
Note that this won't make VAR buffer-local if it isn't already."
 
  `(with-current-buffer ,buffer (setq ,var ,value)))
 

	
 
(defun wg-interesting-buffers ()
 
  "Return a list of only the interesting buffers in `buffer-list'."
 
  (cl-remove-if (lambda (bname) (string-match "^ " bname))
 
                (wg-buffer-list-emacs) :key 'buffer-name))
 

	
 
(defun wg-get-first-buffer-matching-regexp (regexp &optional buffer-list)
 
  "Return the first buffer in BUFFER-LIST with a name matching REGEXP.
 
BUFFER-LIST should contain buffer objects and/or buffer names."
 
  (cl-find regexp (or buffer-list (wg-buffer-list-emacs))
 
           :test 'string-match :key 'wg-buffer-name))
 

	
 

	
 

	
 
;;; files
 

	
 
(defun wg-write-sexp-to-file (sexp file)
 
  "Write the printable representation of SEXP to FILE."
 
  (with-temp-buffer
 
    (let ((print-level nil)  (print-length nil))
 
      (insert (format "%S" sexp)))
 
    (write-file file)))
 

	
 
(defun wg-read-sexp-from-file (file)
 
  "Return a Lisp object from FILE."
 
  (with-temp-buffer
 
    (insert-file-contents file)
 
    (goto-char (point-min))
 
    (read (current-buffer))))
 
(defalias 'wg-lisp-object-from-file 'wg-read-sexp-from-file)
 

	
 
(defun wg-file-under-root-path-p (root-path file-path)
 
  "Return t when FILE-PATH is under ROOT-PATH, nil otherwise."
 
  (string-match (concat "^" (regexp-quote (expand-file-name root-path)))
 
                (expand-file-name file-path)))
 

	
 

	
 

	
 
;;; frames
 

	
 
(defun wg-cyclic-nth-from-frame (&optional n frame)
 
  "Return the frame N places away from FRAME in `frame-list' cyclically.
 
N defaults to 1, and FRAME defaults to `selected-frame'."
 
  (wg-cyclic-nth-from-elt
 
   (or frame (selected-frame)) (frame-list) (or n 1)))
 

	
 

	
 

	
 
;;; namespace-prefixed defstruct
 

	
 
(defmacro wg-defstruct (prefix name-form &rest slot-defs)
 
  "`defstruct' wrapper that namespace-prefixes all generated functions.
 
Note: this doesn't yet work with :conc-name, and possibly other
 
options."
 
  (declare (indent 2))
 
  (let* ((name (if (consp name-form) (car name-form) name-form))
 
         (prefixed-name (wg-symcat prefix "-" name)))
 
    (cl-labels ((rebind (opstr)
 
                      (let ((oldfnsym (wg-symcat opstr "-" prefix "-" name)))
 
                        `((fset ',(wg-symcat prefix "-" opstr "-" name)
 
                                (symbol-function ',oldfnsym))
 
                          (fmakunbound ',oldfnsym)))))
 
      ;; `eval-and-compile' gets rid of byte-comp warnings ("function `foo' not
 
      ;; known to be defined").  We can accomplish this with `declare-function'
 
      ;; too, but it annoyingly requires inclusion of the function's arglist,
 
      ;; which gets ugly.
 
      `(eval-and-compile
 
         (cl-defstruct ,(if (symbolp name-form) prefixed-name
 
                       `(,prefixed-name ,@(cdr name-form)))
 
           ,@slot-defs)
 
         ,@(rebind "make")
 
         ,@(rebind "copy")
 
         ',prefixed-name))))
 

	
 
(defmacro wg-with-slots (obj slot-bindings &rest body)
 
  "Bind OBJ's slot values to symbols in BINDS, then eval BODY.
 
The car of each element of SLOT-BINDINGS is the bound symbol, and
 
the cadr as the accessor function."
 
  (declare (indent 2))
 
  (wg-with-gensyms (objsym)
 
    `(let* ((,objsym ,obj)
 
            ,@(wg-docar (slot slot-bindings)
 
                `(,(car slot) (,(cadr slot) ,objsym))))
 
       ,@body)))
 

	
 

	
 

	
 
;;; misc
 

	
 

	
 
(defun wg-fill-keymap (keymap &rest binds)
 
  "Return KEYMAP after defining in it all keybindings in BINDS."
 
  (while binds
 
    (define-key keymap (car binds) (cadr binds))
 
    (setq binds (cddr binds)))
 
  keymap)
 

	
 
(defun wg-add-or-remove-hooks (remove &rest pairs)
 
  "Add FUNCTION to or remove it from HOOK, depending on REMOVE."
 
  (dolist (pair (wg-partition pairs 2))
 
    (funcall (if remove 'remove-hook 'add-hook)
 
             (car pair) (cadr pair))))
 

	
 

	
 

	
 
(defmacro wg-set-parameter (place parameter value)
 
  "Set PARAMETER to VALUE at PLACE.
 
This needs to be a macro to allow specification of a setf'able place."
 
  (wg-with-gensyms (p v)
 
    `(let ((,p ,parameter) (,v ,value))
 
       (wg-pickelable-or-error ,p)
 
       (wg-pickelable-or-error ,v)
 
       (setf ,place (wg-aput ,place ,p ,v))
 
       ,v)))
 

	
 

	
 
;;; uid utils
 

	
 
(defun wg-time-to-b36 ()
 
  "Convert `current-time' into a b36 string."
 
  (apply 'concat (wg-docar (time (current-time))
 
                   (wg-int-to-b36 time 4))))
 

	
 
(defun wg-b36-to-time (b36)
 
  "Parse the time in B36 string from UID."
 
  (cl-loop for i from 0 to 8 by 4
 
           collect (wg-b36-to-int (cl-subseq b36 i (+ i 4)))))
 
(defalias 'wg-uid-to-time 'wg-b36-to-time)
 

	
 
(defun wg-generate-uid (&optional prefix)
 
  "Return a new uid, optionally prefixed by PREFIX."
 
  (concat prefix (wg-time-to-b36) "-" (wg-int-to-b36 string-chars-consed)))
 

	
 
(defun wg-uid-to-seconds (uid)
 
  "Return the `float-time' parsed from UID with `wg-uid-to-time'."
 
  (float-time (wg-uid-to-time uid)))
 

	
 

	
 
(defun wg-get-value (arg)
 
  "Get a value of ARG if it exists."
 
  (if (boundp `,arg) (eval arg)))
 

	
 
(defmacro wg-support (mode pkg params)
 
  "Macro to create (de)serialization functions for a buffer.
 
You need to save/restore a specific MODE which is loaded from a
 
package PKG.  In PARAMS you give local variables to save and a
 
deserialization function."
 
  `(let ((mode-str (symbol-name ,mode))
 
         (args ,params))
 

	
 
     (eval `(defun ,(intern (format "wg-deserialize-%s-buffer" mode-str)) (buffer)
 
              "DeSerialization function created with `wg-support'.
 
Gets saved variables and runs code to restore a BUFFER."
 
              (when (require ',,pkg nil 'noerror)
 
                (wg-dbind (this-function variables) (wg-buf-special-data buffer)
 
                  (let ((default-directory (car variables))
 
                        (df (cdr (assoc 'deserialize ',,params)))
 
                        (user-vars (car (cdr variables))))
 
                    (if df
 
                        (funcall df buffer user-vars)
 
                      (get-buffer-create wg-default-buffer))
 
                    )))))
 

	
 
     (eval `(defun ,(intern (format "wg-serialize-%s-buffer" mode-str)) (buffer)
 
              "Serialization function created with `wg-support'.
 
Saves some variables to restore a BUFFER later."
 
              (when (get-buffer buffer)
 
                (with-current-buffer buffer
 
                  (when (eq major-mode ',,mode)
 
                    (let ((sf (cdr (assoc 'serialize ',,params)))
 
                          (save (cdr (assoc 'save ',,params))))
 
                      (list ',(intern (format "wg-deserialize-%s-buffer" mode-str))
 
                            (list default-directory
 
                                  (if sf (funcall sf buffer)
 
                                    (if save (mapcar 'wg-get-value save)))
 
                                  ))))))))
 
     ;; Maybe change a docstring for functions
 
     ;;(put (intern (format "wg-serialize-%s-buffer" (symbol-name mode)))
 
     ;;     'function-documentation
 
     ;;     (format "A function created by `wg-support'."))
 

	
 
     ;; Add function to `wg-special-buffer-serdes-functions' variable
 
     (eval `(add-to-list 'wg-special-buffer-serdes-functions
 
                         ',(intern (format "wg-serialize-%s-buffer" mode-str)) t))
 
     ))
 

	
 
(defvar wg-current-session nil "Current session object.")
 
(defun wg-current-session (&optional noerror)
 
  "Return `wg-current-session' or scream unless NOERROR."
 
  (or wg-current-session
 
      (unless noerror
 
        (error "No session is defined"))))
 

	
 

	
 
(defun wg-read-buffer-mode ()
 
  "Return the buffer switching package (ido or iswitchb) to use, or nil."
 
  (if (eq wg-current-buffer-list-filter-id 'fallback) 'fallback
 
    (cl-case (let (workgroups-mode) (command-remapping 'switch-to-buffer))
 
      (ido-switch-buffer 'ido)
 
      (otherwise 'fallback))))
 

	
 
(defun wg-read-buffer-function (&optional mode)
 
  "Return MODE's or `wg-read-buffer-mode's `read-buffer' function."
 
  (cl-case (or mode (wg-read-buffer-mode))
 
    (ido 'ido-read-buffer)
 
    (fallback (lambda (prompt &optional default require-match)
 
                (let (read-buffer-function)
 
                  (read-buffer prompt default require-match))))))
 

	
 
(defun wg-completing-read
 
    (prompt choices &optional pred require-match initial-input history default)
 
  "Do a completing read.  The function called depends on what's on."
 
  (cl-ecase (wg-read-buffer-mode)
 
    (ido
 
     (ido-completing-read prompt choices pred require-match
 
                          initial-input history default))
 
    (fallback
 
     (completing-read prompt choices pred require-match
 
                      initial-input history default))))
 

	
 
;; locate-dominating-file
 
(defun wg-get-first-existing-dir (&optional dir)
 
  "Test if DIR exists and return it.
 
If not - try to go to the parent dir and do the same."
 
  (let* ((d (or dir default-directory)))
 
    (if (file-directory-p d) d
 
      (let* ((cur d) (parent (file-name-directory (directory-file-name cur))))
 
        (while (and (> (length cur) (length parent))
 
                    (not (file-directory-p parent)))
 
          (message "Test %s" parent)
 
          (setq cur parent)
 
          (setq parent (file-name-directory (directory-file-name cur))))
 
        parent))))
 

	
 
(provide 'workgroups-utils-basic)
 
;;; workgroups-utils-basic.el ends here
src/workgroups-workgroup.el
Show inline comments
 
;;; workgroups-workgroup.el --- workgroup functions
 
;;; Commentary:
 
;;; Code:
 

	
 
(require 'ring)
 
(require 'workgroups-wconfig)
 
(require 'workgroups-minibuffer)
 

	
 
;;
 
;; Variables
 
;;
 
(defvar wg-deactivation-list nil
 
  "A stack of workgroups that are currently being switched away from.
 
Used to avoid associating the old workgroup's buffers with the
 
new workgroup during a switch.")
 

	
 
(defcustom wg-confirm-on-get-workgroup-create nil
 
  "Non-nil means request confirmation before creating a new
 
workgroup when `wg-get-workgroup-create' is called with a string
 
that doesn't name an existing workgroup."
 
  :type 'boolean
 
  :group 'workgroups)
 

	
 
(defun wg-flag-workgroup-modified (workgroup)
 
  "Set WORKGROUP's and the current session's modified flags."
 
  (when wg-flag-modified
 
    (setf (wg-workgroup-modified workgroup) t)
 
    (setf (wg-session-modified (wg-current-session)) t)))
 

	
 

	
 
(defun wg-current-workgroup (&optional noerror frame)
 
  "Return the current workgroup in FRAME, or error unless NOERROR."
 
  (or wg-current-workgroup
 
      (wg-aif (frame-parameter frame 'wg-current-workgroup-uid)
 
      (aif (frame-parameter frame 'wg-current-workgroup-uid)
 
          (wg-find-workgroup-by :uid it noerror)
 
        (unless noerror (error "No current workgroup in this frame")))))
 

	
 
(defun wg-previous-workgroup (&optional noerror frame)
 
  "Return the previous workgroup in FRAME, or error unless NOERROR."
 
  (wg-aif (frame-parameter frame 'wg-previous-workgroup-uid)
 
  (aif (frame-parameter frame 'wg-previous-workgroup-uid)
 
      (wg-find-workgroup-by :uid it noerror)
 
    (unless noerror (error "No previous workgroup in this frame"))))
 

	
 
(defun wg-set-current-workgroup (workgroup &optional frame)
 
  "Set the current workgroup to WORKGROUP.
 
WORKGROUP should be a workgroup or nil."
 
  (set-frame-parameter frame 'wg-current-workgroup-uid
 
                       (when workgroup (wg-workgroup-uid workgroup))))
 

	
 
(defun wg-set-previous-workgroup (workgroup &optional frame)
 
  "Set the previous workgroup to WORKGROUP.
 
WORKGROUP should be a workgroup or nil."
 
  (set-frame-parameter frame 'wg-previous-workgroup-uid
 
                       (when workgroup (wg-workgroup-uid workgroup))))
 

	
 
(defun wg-current-workgroup-p (workgroup &optional frame)
 
  "Return t when WORKGROUP is the current workgroup, nil otherwise."
 
  (wg-awhen (wg-current-workgroup t frame)
 
    (eq workgroup it)))
 

	
 
(defun wg-previous-workgroup-p (workgroup &optional frame)
 
  "Return t when WORKGROUP is the previous workgroup, nil otherwise."
 
  (wg-awhen (wg-previous-workgroup t frame)
 
    (eq workgroup it)))
 

	
 
(defmacro wg-with-current-workgroup (workgroup &rest body)
 
  "Execute forms in BODY with WORKGROUP temporarily current.
 
WORKGROUP should be any workgroup identifier accepted by
 
`wg-get-workgroup'.  The value returned is the last form
 
in BODY."
 
  (declare (indent 1))
 
  `(let ((wg-current-workgroup (wg-get-workgroup ,workgroup)))
 
     ,@body))
 

	
 
(defun wg-get-workgroup (obj &optional noerror)
 
  "Return a workgroup from OBJ.
 
If OBJ is a workgroup, return it.
 
If OBJ is a string, return the workgroup named OBJ, or error unless NOERROR.
 
If OBJ is nil, return the current workgroup, or error unless NOERROR."
 
  (cond ((wg-workgroup-p obj) obj)
 
        ((stringp obj) (wg-find-workgroup-by :name obj noerror))
 
        ((null obj) (wg-current-workgroup noerror))
 
        (t (error "Can't get workgroup from type:: %S" (type-of obj)))))
 

	
 

	
 

	
 
;;; workgroup parameters
 
;;
 
;; Quick test:
 
;; (wg-workgroup-parameters (wg-current-workgroup))
 
;; (wg-set-workgroup-parameter (wg-current-workgroup) 'test1 t)
 
;; (wg-workgroup-parameter (wg-current-workgroup) 'test1)
 
(defun wg-workgroup-parameter (workgroup parameter &optional default)
 
  "Return WORKGROUP's value for PARAMETER.
 
If PARAMETER is not found, return DEFAULT which defaults to nil.
 
WORKGROUP should be accepted by `wg-get-workgroup'."
 
  (wg-aget (wg-workgroup-parameters (wg-get-workgroup workgroup))
 
           parameter default))
 

	
 
(defun wg-set-workgroup-parameter (workgroup parameter value)
 
  "Set WORKGROUP's value of PARAMETER to VALUE.
 
WORKGROUP should be a value accepted by `wg-get-workgroup'.
 
Return VALUE."
 
  (let ((workgroup (wg-get-workgroup workgroup)))
 
    (wg-set-parameter (wg-workgroup-parameters workgroup) parameter value)
 
    (wg-flag-workgroup-modified workgroup)
 
    value))
 

	
 
(defun wg-remove-workgroup-parameter (workgroup parameter)
 
  "Remove PARAMETER from WORKGROUP's parameters."
 
  (let ((workgroup (wg-get-workgroup workgroup)))
 
    (wg-flag-workgroup-modified workgroup)
 
    (wg-asetf (wg-workgroup-parameters workgroup) (wg-aremove it parameter))))
 

	
 
(defun wg-workgroup-local-value (variable &optional workgroup)
 
  "Return the value of VARIABLE in WORKGROUP.
 
WORKGROUP nil defaults to the current workgroup.  If there is no
 
current workgroup, or if VARIABLE does not have a workgroup-local
 
binding in WORKGROUP, resolve VARIABLE with `wg-session-local-value'."
 
  (let ((workgroup (wg-get-workgroup workgroup t)))
 
    (if (not workgroup) (wg-session-local-value variable)
 
      (let* ((undefined (cl-gensym))
 
             (value (wg-workgroup-parameter workgroup variable undefined)))
 
        (if (not (eq value undefined)) value
 
          (wg-session-local-value variable))))))
 

	
 
(defalias 'wg-local-value 'wg-workgroup-local-value)
 

	
 

	
 
;;; workgroup saved wconfigs
 

	
 
(defun wg-workgroup-saved-wconfig-names (workgroup)
 
  "Return a new list of the names of all WORKGROUP's saved wconfigs."
 
  (mapcar 'wg-wconfig-name (wg-workgroup-saved-wconfigs workgroup)))
 

	
 
(defun wg-workgroup-get-saved-wconfig (workgroup wconfig-or-name)
 
  "Return the wconfig in WORKGROUP's saved wconfigs named WCONFIG-OR-NAME.
 
WCONFIG-OR-NAME must be either a string or a wconfig.  If
 
WCONFIG-OR-NAME is a string and there is no saved wconfig with
 
that name, return nil.  If WCONFIG-OR-NAME is a wconfig, and it
 
is a member of WORKGROUP's saved wconfigs, return is as given.
 
Otherwise return nil."
 
  (let ((wconfigs (wg-workgroup-saved-wconfigs workgroup)))
 
    (cl-etypecase wconfig-or-name
 
      (wg-wconfig (car (memq wconfig-or-name wconfigs)))
 
      (string (cl-find wconfig-or-name wconfigs
 
                       :key 'wg-wconfig-name
 
                       :test 'string=)))))
 

	
 
(defun wg-workgroup-save-wconfig (workgroup wconfig)
 
  "Add WCONFIG to WORKGROUP's saved wconfigs.  WCONFIG must have
 
a name.  If there's already a wconfig with the same name in
 
WORKGROUP's saved wconfigs, replace it."
 
  (let ((name (wg-wconfig-name wconfig)))
 
    (unless name (error "Attempt to save a nameless wconfig"))
 
    (setf (wg-workgroup-modified workgroup) t)
 
    (wg-asetf (wg-workgroup-saved-wconfigs workgroup)
 
              (cons wconfig (cl-remove name it
 
                                       :key 'wg-wconfig-name
 
                                       :test 'string=)))))
 

	
 
(defun wg-workgroup-kill-saved-wconfig (workgroup wconfig-or-name)
 
  "Delete WCONFIG-OR-NAME from WORKGROUP's saved wconfigs.
 
WCONFIG-OR-NAME is resolved with `wg-workgroup-get-saved-wconfig'."
 
  (wg-when-let ((wconfig (wg-workgroup-get-saved-wconfig
 
                          workgroup wconfig-or-name)))
 
    (wg-asetf (wg-workgroup-saved-wconfigs workgroup) (remq wconfig it)
 
              (wg-workgroup-modified workgroup) t)))
 

	
 

	
 

	
 
(defun wg-workgroup-base-wconfig-buf-uids (workgroup)
 
  "Return a new list of all unique buf uids in WORKGROUP's working wconfig."
 
  (wg-wconfig-buf-uids (wg-workgroup-base-wconfig workgroup)))
 

	
 
(defun wg-workgroup-saved-wconfigs-buf-uids (workgroup)
 
  "Return a new list of all unique buf uids in WORKGROUP's base wconfig."
 
  (cl-reduce 'wg-string-list-union
 
             (wg-workgroup-saved-wconfigs workgroup)
 
             :key 'wg-wconfig-buf-uids))
 

	
 
(defun wg-workgroup-all-wconfig-buf-uids (workgroup)
 
  "Return a new list of all unique buf uids in WORKGROUP's wconfigs."
 
  (cl-union (wg-workgroup-base-wconfig-buf-uids workgroup)
 
            (wg-workgroup-saved-wconfigs-buf-uids workgroup)
 
            :test 'string=))
 

	
 
(defun wg-workgroup-all-buf-uids (workgroup)
 
  "Return a new list of all unique buf uids in WORKGROUP."
 
  (cl-reduce 'wg-string-list-union
 
             (list (wg-workgroup-base-wconfig-buf-uids workgroup)
 
                   (wg-workgroup-saved-wconfigs-buf-uids workgroup))))
 

	
 

	
 

	
 
;;; workgroup restoration
 

	
 
(defun wg-restore-workgroup (workgroup)
 
  "Restore WORKGROUP in `selected-frame'."
 
  (let (wg-flag-modified)
 
    (wg-restore-wconfig-undoably (wg-workgroup-working-wconfig workgroup) t)))
 

	
 

	
 
(defun wg-workgroup-list-or-error (&optional noerror)
 
  "Return the value of `wg-current-session's :workgroup-list slot.
 
Or scream unless NOERROR."
 
  (or (wg-workgroup-list)
 
      (unless noerror
 
        (error "No workgroups are defined"))))
 

	
 
(defun wg-find-workgroup-by (slotkey value &optional noerror)
 
  "Return the workgroup on which ACCESSOR returns VALUE or error."
 
  (let ((accessor (cl-ecase slotkey
 
                    (:name 'wg-workgroup-name)
 
                    (:uid  'wg-workgroup-uid))))
 
    (or (cl-find value (wg-workgroup-list-or-error noerror) :test 'equal :key accessor)
 
        (unless noerror
 
          (error "No are no workgroups with a %S of %S"
 
                 accessor value)))))
 

	
 
(defun wg-first-workgroup ()
 
  "Return a first workgroup."
 
  (car (wg-workgroup-list-or-error)))
 

	
 
(defun wg-cyclic-nth-from-workgroup (workgroup &optional n)
 
  "Return the workgroup N places from WORKGROUP in `wg-workgroup-list'."
 
  (wg-cyclic-nth-from-elt workgroup (wg-workgroup-list-or-error) (or n 1)))
 

	
 

	
 
(defun wg-read-workgroup-name (&optional require-match)
 
  "Read a workgroup with `wg-completing-read'."
 
  (wg-completing-read
 
   "Workgroup: " (wg-workgroup-names) nil require-match nil nil
 
   (wg-awhen (wg-current-workgroup t) (wg-workgroup-name it))))
 

	
 
(defun wg-new-default-workgroup-name ()
 
  "Return a new, unique, default workgroup name."
 
  (let ((names (wg-workgroup-names t)) (index -1) result)
 
    (while (not result)
 
      (let ((new-name (format "wg%s" (cl-incf index))))
 
        (unless (member new-name names)
 
          (setq result new-name))))
 
    result))
 

	
 
(defun wg-unique-workgroup-name-p (new-name)
 
  "Return t if NEW-NAME is unique in `wg-workgroup-list', nil otherwise."
 
  (cl-every (lambda (existing-name) (not (equal new-name existing-name)))
 
            (wg-workgroup-names t)))
 

	
 
(defun wg-read-saved-wconfig-name (workgroup &optional prompt require-match)
 
  "Read the name of a saved wconfig, completing on the names of
 
WORKGROUP's saved wconfigs."
 
  (wg-completing-read
 
   (or prompt "Saved wconfig name: ")
 
   (wg-workgroup-saved-wconfig-names workgroup)
 
   nil require-match))
 

	
 
(defun wg-read-saved-wconfig (workgroup)
 
  "Read the name of and return one of WORKGROUP's saved wconfigs."
 
  (wg-workgroup-get-saved-wconfig
 
   workgroup (wg-read-saved-wconfig-name workgroup nil t)))
 

	
 

	
 
;;; workgroup-list reorganization commands
 

	
 
(defun wg-swap-workgroups ()
 
  "Swap the previous and current workgroups."
 
  (interactive)
 
  (wg-swap-workgroups-in-workgroup-list
 
   (wg-current-workgroup) (wg-previous-workgroup))
 
  (wg-fontified-message
 
    (:cmd "Swapped:  ")
 
    (wg-workgroup-list-display)))
 

	
 
(defun wg-offset-workgroup-left (&optional workgroup n)
 
  "Offset WORKGROUP leftward in `wg-workgroup-list' cyclically."
 
  (interactive (list nil current-prefix-arg))
 
  (wg-cyclic-offset-workgroup (wg-get-workgroup workgroup) (or n -1))
 
  (wg-fontified-message
 
    (:cmd "Offset left: ")
 
    (wg-workgroup-list-display)))
 

	
 
(defun wg-offset-workgroup-right (&optional workgroup n)
 
  "Offset WORKGROUP rightward in `wg-workgroup-list' cyclically."
 
  (interactive (list nil current-prefix-arg))
 
  (wg-cyclic-offset-workgroup (wg-get-workgroup workgroup) (or n 1))
 
  (wg-fontified-message
 
    (:cmd "Offset right: ")
 
    (wg-workgroup-list-display)))
 

	
 

	
 
;;; undo/redo commands
 

	
 
(defun wg-undo-wconfig-change (&optional workgroup)
 
  "Undo a change to the current workgroup's window-configuration."
 
  (interactive)
 
  (let* ((workgroup (wg-get-workgroup workgroup))
 
         (undid? (wg-workgroup-offset-position-in-undo-list workgroup 1)))
 
    (wg-fontified-message
 
      (:cmd "Undo")
 
      (:cur (if undid? "" "  No more undo info")))))
 

	
 
(defun wg-redo-wconfig-change (&optional workgroup)
 
  "Redo a change to the current workgroup's window-configuration."
 
  (interactive)
 
  (let* ((workgroup (wg-get-workgroup workgroup))
 
         (redid? (wg-workgroup-offset-position-in-undo-list workgroup -1)))
 
    (wg-fontified-message
 
      (:cmd "Redo")
 
      (:cur (if redid? "" "  No more redo info")))))
 

	
 
(defun wg-undo-once-all-workgroups ()
 
  "Do what the name says.  Useful for instance when you
 
accidentally call `wg-revert-all-workgroups' and want to return
 
all workgroups to their un-reverted state."
 
  (interactive)
 
  (mapc 'wg-undo-wconfig-change (wg-workgroup-list-or-error))
 
  (wg-message "Undid once on all workgroups."))
 

	
 
(defun wg-redo-once-all-workgroups ()
 
  "Do what the name says.  Probably useless.  Included for
 
symetry with `wg-undo-once-all-workgroups'."
 
  (interactive)
 
  (mapc 'wg-redo-wconfig-change (wg-workgroup-list-or-error))
 
  (wg-message "Redid once on all workgroups."))
 

	
 

	
 

	
 
;;; window-tree commands
 
;;
 
;; TODO: These are half-hearted.  Clean them up; allow specification of the
 
;; window-tree depth at which to operate; add complex window creation commands;
 
;; and add window splitting, deletion and locking commands.
 

	
 
(defun wg-reverse-frame-horizontally (&optional workgroup)
 
  "Reverse the order of all horizontally split wtrees."
 
  (interactive)
 
  (wg-restore-wconfig-undoably
 
   (wg-reverse-wconfig
 
    (wg-workgroup-working-wconfig
 
     (wg-get-workgroup workgroup)))))
 

	
 
(defun wg-reverse-frame-vertically (&optional workgroup)
 
  "Reverse the order of all vertically split wtrees."
 
  (interactive)
 
  (wg-restore-wconfig-undoably
 
   (wg-reverse-wconfig
 
    (wg-workgroup-working-wconfig
 
     (wg-get-workgroup workgroup))
 
    t)))
 

	
 
(defun wg-reverse-frame-horizontally-and-vertically (&optional workgroup)
 
  "Reverse the order of all wtrees."
 
  (interactive)
 
  (wg-restore-wconfig-undoably
 
   (wg-reverse-wconfig
 
    (wg-workgroup-working-wconfig
 
     (wg-get-workgroup workgroup))
 
    'both)))
 

	
 

	
 
;;; misc commands
 

	
 
(defun wg-rename-workgroup (workgroup newname)
 
  "Rename WORKGROUP to NEWNAME."
 
  (interactive (list nil (wg-read-new-workgroup-name "New name: ")))
 
  (let* ((workgroup (wg-get-workgroup workgroup))
 
         (oldname (wg-workgroup-name workgroup)))
 
    (setf (wg-workgroup-name workgroup) newname)
 
    (wg-flag-workgroup-modified workgroup)
 
    (wg-fontified-message
 
      (:cmd "Renamed: ")
 
      (:cur oldname)
 
      (:msg " to ")
 
      (:cur (wg-workgroup-name workgroup)))))
 

	
 
(defun wg-reset (&optional force)
 
  "Reset Workgroups.
 
Resets all frame parameters, buffer-local vars, the current
 
Workgroups session object, etc."
 
  (interactive "P")
 
  (unless (or force wg-no-confirm-on-destructive-operation
 
              (y-or-n-p "Really reset Workgroups? "))
 
    (error "Canceled"))
 
  (wg-reset-internal)
 
  (wg-fontified-message (:cmd "Reset: ") (:msg "Workgroups")))
 

	
 

	
 
(defun wg-query-and-save-if-modified ()
 
  "Query for save when `wg-modified-p'."
 
  (or (not (wg-modified-p))
 
      (when (y-or-n-p "Save modified workgroups? ")
 
        (wg-save-session))))
 

	
 

	
 
;;; workgroup creation commands
 

	
 
(defun wg-create-workgroup (name &optional blank)
 
  "Create and add a workgroup named NAME.
 
Optional argument BLANK non-nil (set interactively with a prefix
 
arg) means use a blank, one window window-config.  Otherwise use
 
the current window-configuration.  Keep in mind that even though
 
the current window-config may be used, other parameters of the
 
current workgroup are not copied to the created workgroup.  For
 
that, use `wg-clone-workgroup'."
 
  (interactive (list (wg-read-new-workgroup-name) current-prefix-arg))
 
  (wg-switch-to-workgroup (wg-make-and-add-workgroup name blank))
 
  (wg-fontified-message
 
    (:cmd "Created: ") (:cur name) "  " (wg-workgroup-list-display)))
 

	
 
(defun wg-clone-workgroup (workgroup name)
 
  "Create and add a clone of WORKGROUP named NAME.
 
Keep in mind that only WORKGROUP's top-level alist structure is
 
copied, so destructive operations on the keys or values of
 
WORKGROUP will be reflected in the clone, and vice-versa.  Be
 
safe -- don't mutate them."
 
  (interactive (list nil (wg-read-new-workgroup-name)))
 
  (let* ((workgroup (wg-get-workgroup workgroup))
 
         (clone (wg-copy-workgroup workgroup)))
 
    (setf (wg-workgroup-name clone) name
 
          (wg-workgroup-uid clone) (wg-generate-uid))
 
    (when (wg-check-and-add-workgroup clone)
 
      (wg-flag-workgroup-modified clone))
 
    (wg-set-workgroup-working-wconfig
 
     clone (wg-workgroup-working-wconfig workgroup))
 
    (wg-switch-to-workgroup clone)
 
    (wg-fontified-message
 
      (:cmd "Cloned: ")
 
      (:cur (wg-workgroup-name workgroup))
 
      (:msg " to ")
 
      (:cur name) "  "
 
      (wg-workgroup-list-display))))
 

	
 

	
 

	
 
;;; workgroup switching commands
 
(defun wg-switch-to-workgroup (workgroup &optional noerror)
 
  "Switch to WORKGROUP.
 
NOERROR means fail silently."
 
  (interactive (list (wg-read-workgroup-name)))
 

	
 
  (fset 'buffer-list wg-buffer-list-original)
 

	
 
  ;; Mark if ECB is active
 
  (if (wg-current-workgroup t)
 
      (wg-set-workgroup-parameter (wg-current-workgroup t) 'ecb (and (boundp 'ecb-minor-mode)
 
                                                                     ecb-minor-mode)))
 
  ;;(wg-set-workgroup-parameter (wg-current-workgroup t) 'ecb-win-config (ecb-current-window-configuration))
 
  ;; (type-of (ecb-current-window-configuration))
 
  ;; (type-of (car (ecb-current-window-configuration)))
 
  ;; (type-of (car (nthcdr 3 (ecb-current-window-configuration))))
 
  ;; (wg-pickelable-or-error (ecb-current-window-configuration))
 
  ;;(ecb-current-window-configuration)
 
  ;;)
 

	
 
  (let ((workgroup (wg-get-workgroup-create workgroup))
 
        (current (wg-current-workgroup t)))
 
    (when (and (eq workgroup current) (not noerror))
 
      (error "Already on: %s" (wg-workgroup-name current)))
 
    (when current (push current wg-deactivation-list))
 
    (unwind-protect
 
        (progn
 
          ;; Before switching - turn off ECB
 
          ;; https://github.com/pashinin/workgroups2/issues/34
 
          (if (and (boundp 'ecb-minor-mode)
 
                   (boundp 'ecb-frame)
 
                   (fboundp 'ecb-deactivate)
 
                   ecb-minor-mode
 
                   (equal ecb-frame (selected-frame)))
 
              (let ((ecb-split-edit-window-after-start 'before-deactivation))
 
                (ecb-deactivate)))
 

	
 
          (wg-restore-workgroup workgroup)
 
          (wg-set-previous-workgroup current)
 
          (wg-set-current-workgroup workgroup)
 

	
 
          ;; Save "last-workgroup" to the session params
 
          (if (and (wg-current-session t)
 
                   (wg-current-workgroup t))
 
              (wg-set-session-parameter (wg-current-session t)
 
                                        'last-workgroup
 
                                        (wg-workgroup-name (wg-current-workgroup))))
 

	
 
          ;; If a workgroup had ECB - turn it on
 
          (if (and (boundp 'ecb-minor-mode)
 
                   (not ecb-minor-mode)
 
                   (fboundp 'ecb-activate)
 
                   (wg-workgroup-parameter (wg-current-workgroup t) 'ecb nil))
 
              (let ((ecb-split-edit-window-after-start 'before-deactivation))
 
                (ecb-activate)))
 
          ;;(ecb-last-window-config-before-deactivation
 
          ;; (wg-workgroup-parameter (wg-current-workgroup t) 'ecb-win-config nil)))
 

	
 
          (run-hooks 'wg-switch-to-workgroup-hook)
 

	
 
          (if wg-mess-with-buffer-list
 
              (fset 'buffer-list wg-buffer-list-function))
 
          (wg-fontified-message
 
            (:cmd "Switched: ")
 
            (wg-workgroup-name (wg-current-workgroup t))
 
            ))
 
      (when current (pop wg-deactivation-list)))))
 

	
 
(defun wg-switch-to-workgroup-other-frame (workgroup &optional n)
 
  "Switch to WORKGROUP in the frame N places cyclically from `selected-frame'.
 
Use `current-prefix-arg' for N if non-nil.  Otherwise N defaults to 1."
 
  (interactive (list (wg-read-workgroup-name) current-prefix-arg))
 
  (with-selected-frame (wg-cyclic-nth-from-frame (or n 1))
 
    (wg-switch-to-workgroup workgroup)))
 

	
 
(defun wg-switch-to-workgroup-at-index (index)
 
  "Switch to the workgroup at INDEX in `wg-workgroup-list'."
 
  (interactive (list (or current-prefix-arg (wg-read-workgroup-index))))
 
  (let ((wl (wg-workgroup-list-or-error)))
 
    (wg-switch-to-workgroup
 
     (or (nth index wl) (error "There are only %d workgroups" (length wl))))))
 

	
 
(cl-macrolet
 
    ((define-range-of-switch-to-workgroup-at-index (num)
 
       `(progn
 
          ,@(wg-docar (i (wg-range 0 num))
 
              `(defun ,(intern (format "wg-switch-to-workgroup-at-index-%d" i)) ()
 
                 ,(format "Switch to the workgroup at index %d." i)
 
                 (interactive)
 
                 (wg-switch-to-workgroup-at-index ,i))))))
 
  (define-range-of-switch-to-workgroup-at-index 10))
 

	
 
(defun wg-switch-to-cyclic-nth-from-workgroup (workgroup n)
 
  "Switch N workgroups cyclically from WORKGROUP in `wg-workgroup-list.'"
 
  (let ((workgroup-list (wg-workgroup-list-or-error))
 
        (workgroup (wg-get-workgroup workgroup t)))
 
    (wg-switch-to-workgroup
 
     (cond ((not workgroup) (car workgroup-list))
 
           ((= 1 (length workgroup-list)) (error "There's only one workgroup"))
 
           (t (wg-cyclic-nth-from-workgroup workgroup n))))))
 

	
 
(defun wg-switch-to-workgroup-left (&optional workgroup n)
 
  "Switch to the workgroup (- N) places from WORKGROUP in `wg-workgroup-list'.
 
Use `current-prefix-arg' for N if non-nil.  Otherwise N defaults to 1."
 
  (interactive (list nil current-prefix-arg))
 
  (wg-switch-to-cyclic-nth-from-workgroup workgroup (- (or n 1))))
 

	
 
(defun wg-switch-to-workgroup-right (&optional workgroup n)
 
  "Switch to the workgroup N places from WORKGROUP in `wg-workgroup-list'.
 
Use `current-prefix-arg' for N if non-nil.  Otherwise N defaults to 1."
 
  (interactive (list nil current-prefix-arg))
 
  (wg-switch-to-cyclic-nth-from-workgroup workgroup (or n 1)))
 

	
 
(defun wg-switch-to-previous-workgroup ()
 
  "Switch to the previous workgroup."
 
  (interactive)
 
  (wg-switch-to-workgroup (wg-previous-workgroup)))
 

	
 

	
 

	
 
;;; workgroup killing commands
 

	
 
(defun wg-wconfig-kill-ring ()
 
  "Return `wg-wconfig-kill-ring', creating it first if necessary."
 
  (or wg-wconfig-kill-ring
 
      (setq wg-wconfig-kill-ring (make-ring wg-wconfig-kill-ring-max))))
 

	
 
(defun wg-add-to-wconfig-kill-ring (wconfig)
 
  "Add WCONFIG to `wg-wconfig-kill-ring'."
 
  (ring-insert (wg-wconfig-kill-ring) wconfig))
 

	
 
(defun wg-kill-workgroup (&optional workgroup)
 
  "Kill WORKGROUP, saving its working-wconfig to the kill ring."
 
  (interactive)
 
  (let* ((workgroup (wg-get-workgroup workgroup))
 
         (to (or (wg-previous-workgroup t)
 
                 (wg-cyclic-nth-from-workgroup workgroup))))
 
    (wg-add-to-wconfig-kill-ring (wg-workgroup-working-wconfig workgroup))
 
    (wg-delete-workgroup workgroup)
 
    (if (eq workgroup to) (wg-restore-wconfig (wg-make-blank-wconfig))
 
      (wg-switch-to-workgroup to))
 
    (wg-fontified-message
 
      (:cmd "Killed: ")
 
      (:cur (wg-workgroup-name workgroup)) "  "
 
      (wg-workgroup-list-display))))
 

	
 
(defun wg-kill-ring-save-base-wconfig (&optional workgroup)
 
  "Save WORKGROUP's base wconfig to the kill ring."
 
  (interactive)
 
  (let ((workgroup (wg-get-workgroup workgroup)))
 
    (wg-add-to-wconfig-kill-ring (wg-workgroup-base-wconfig workgroup))
 
    (wg-fontified-message
 
      (:cmd "Saved: ") (:cur (wg-workgroup-name workgroup))
 
      (:cur "'s ") (:msg "base wconfig to the kill ring"))))
 

	
 
(defun wg-kill-ring-save-working-wconfig (&optional workgroup)
 
  "Save WORKGROUP's working-wconfig to `wg-wconfig-kill-ring'."
 
  (interactive)
 
  (let ((workgroup (wg-get-workgroup workgroup)))
 
    (wg-add-to-wconfig-kill-ring (wg-workgroup-working-wconfig workgroup))
 
    (wg-fontified-message
 
      (:cmd "Saved: ") (:cur (wg-workgroup-name workgroup))
 
      (:cur "'s ") (:msg "working-wconfig to the kill ring"))))
 

	
 
(defun wg-yank-wconfig ()
 
  "Restore a wconfig from `wg-wconfig-kill-ring'.
 
Successive yanks restore wconfigs sequentially from the kill
 
ring, starting at the front."
 
  (interactive)
 
  (when (zerop (ring-length (wg-wconfig-kill-ring)))
 
    (error "The kill-ring is empty"))
 
  (let ((pos (if (not (eq real-last-command 'wg-yank-wconfig)) 0
 
               (1+ (or (get 'wg-yank-wconfig :position) 0)))))
 
    (put 'wg-yank-wconfig :position pos)
 
    (wg-restore-wconfig-undoably (ring-ref (wg-wconfig-kill-ring) pos))
 
    (wg-fontified-message
 
      (:cmd "Yanked: ")
 
      (:msg (format "%S" pos)) "  "
 
      (wg-workgroup-list-display))))
 

	
 
(defun wg-kill-workgroup-and-buffers (&optional workgroup)
 
  "Kill WORKGROUP and the buffers in its working-wconfig."
 
  (interactive)
 
  (let* ((workgroup (wg-get-workgroup workgroup))
 
         (bufs (save-window-excursion
 
                 (wg-restore-workgroup workgroup)
 
                 (mapcar #'window-buffer (window-list)))))
 
    (wg-kill-workgroup workgroup)
 
    (mapc #'kill-buffer bufs)
 
    (wg-fontified-message
 
      (:cmd "Killed: ")
 
      (:cur (wg-workgroup-name workgroup))
 
      (:msg " and its buffers ") "\n"
 
      (wg-workgroup-list-display))))
 

	
 
(defun wg-delete-other-workgroups (&optional workgroup)
 
  "Delete all workgroups but WORKGROUP."
 
  (interactive)
 
  (let ((workgroup (wg-get-workgroup workgroup)))
 
    (unless (or wg-no-confirm-on-destructive-operation
 
                (y-or-n-p "Really delete all other workgroups? "))
 
      (error "Cancelled"))
 
    (dolist (w (wg-workgroup-list-or-error))
 
      (unless (eq w workgroup)
 
        (wg-delete-workgroup w)))
 
    (unless (wg-current-workgroup-p workgroup)
 
      (wg-switch-to-workgroup workgroup))
 
    (wg-fontified-message
 
      (:cmd "Deleted: ")
 
      (:msg "All workgroups but ")
 
      (:cur (wg-workgroup-name workgroup)))))
 

	
 

	
 

	
 
;;; workgroup updating and reverting commands
 

	
 
(defun wg-revert-workgroup (&optional workgroup)
 
  "Restore WORKGROUP's window configuration to its state at the last save."
 
  (interactive)
 
  (let* ((workgroup (wg-get-workgroup workgroup))
 
         (base-wconfig (wg-workgroup-base-wconfig workgroup)))
 
    (if (wg-current-workgroup-p workgroup)
 
        (wg-restore-wconfig-undoably base-wconfig)
 
      (wg-add-wconfig-to-undo-list workgroup base-wconfig))
 
    (wg-fontified-message
 
      (:cmd "Reverted: ")
 
      (:cur (wg-workgroup-name workgroup)))))
 

	
 
(defun wg-revert-all-workgroups ()
 
  "Revert all workgroups to their base wconfigs.
 
Only workgroups' working-wconfigs in `selected-frame' are
 
reverted."
 
  (interactive)
 
  (mapc #'wg-revert-workgroup (wg-workgroup-list-or-error))
 
  (wg-fontified-message
 
    (:cmd "Reverted: ")
 
    (:msg "All")))
 

	
 

	
 

	
 
;;; workgroup working-wconfig and wconfig undo/redo
 

	
 
(defun wg-workgroup-state-table (&optional frame)
 
  "Return FRAME's workgroup table, creating it first if necessary."
 
  (or (frame-parameter frame 'wg-workgroup-state-table)
 
      (let ((wtree (make-hash-table :test 'equal)))
 
        (set-frame-parameter frame 'wg-workgroup-state-table wtree)
 
        wtree)))
 

	
 
(defun wg-get-workgroup-state (workgroup &optional frame)
 
  "Return WORKGROUP's state table in a FRAME."
 
  (let ((uid (wg-workgroup-uid workgroup))
 
        (state-table (wg-workgroup-state-table frame)))
 
    (or (gethash uid state-table)
 
        (let ((wgs (wg-make-workgroup-state
 
                    :undo-pointer 0
 
                    :undo-list
 
                    (list (or (wg-workgroup-selected-frame-wconfig workgroup)
 
                              (wg-workgroup-base-wconfig workgroup))))))
 
          (puthash uid wgs state-table)
 
          wgs))))
 

	
 
(defmacro wg-with-undo (workgroup spec &rest body)
 
  "Bind WORKGROUP's undo state to SPEC and eval BODY."
 
  (declare (indent 2))
 
  (wg-dbind (state undo-pointer undo-list) spec
 
    `(let* ((,state (wg-get-workgroup-state ,workgroup))
 
            (,undo-pointer (wg-workgroup-state-undo-pointer ,state))
 
            (,undo-list (wg-workgroup-state-undo-list ,state)))
 
       ,@body)))
 

	
 
(defun wg-flag-just-exited-minibuffer ()
 
  "Added to `minibuffer-exit-hook'."
 
  (setq wg-just-exited-minibuffer t))
 

	
 
(defun wg-flag-window-configuration-changed ()
 
  "Set `wg-window-configuration-changed' to t.
 
But only if not the minibuffer was just exited.  Added to
 
`window-configuration-change-hook'."
 
  (if wg-just-exited-minibuffer
 
      (setq wg-just-exited-minibuffer nil)
 
    (setq wg-window-configuration-changed t)))
 

	
 
(defun wg-unflag-undoify-window-configuration-change ()
 
  "Set `wg-undoify-window-configuration-change' to nil, exempting
 
from undoification any window-configuration changes caused by the
 
current command."
 
  (setq wg-undoify-window-configuration-change nil))
 

	
 
(defun wg-set-workgroup-working-wconfig (workgroup wconfig)
 
  "Set the working-wconfig of WORKGROUP to WCONFIG."
 
  (wg-flag-workgroup-modified workgroup)
 
  (setf (wg-workgroup-selected-frame-wconfig workgroup) wconfig)
 
  (wg-with-undo workgroup (state undo-pointer undo-list)
 
    (setcar (nthcdr undo-pointer undo-list) wconfig)))
 

	
 
(defun wg-add-wconfig-to-undo-list (workgroup wconfig)
 
  "Add WCONFIG to WORKGROUP's undo list, truncating its future if necessary."
 
  (wg-with-undo workgroup (state undo-pointer undo-list)
 
    (let ((undo-list (cons nil (nthcdr undo-pointer undo-list))))
 
      (wg-awhen (nthcdr wg-wconfig-undo-list-max undo-list) (setcdr it nil))
 
      (setf (wg-workgroup-state-undo-list state) undo-list))
 
    (setf (wg-workgroup-state-undo-pointer state) 0))
 
  (wg-set-workgroup-working-wconfig workgroup wconfig))
 

	
 
(defun wg-workgroup-working-wconfig (workgroup &optional noupdate)
 
  "Return WORKGROUP's working-wconfig.
 
If WORKGROUP is the current workgroup in `selected-frame', and
 
NOUPDATE is nil, set its working wconfig in `selected-frame' to
 
`wg-current-wconfig' and return the updated wconfig.  Otherwise
 
return WORKGROUP's current undo state."
 
  (if (and (not noupdate) (wg-current-workgroup-p workgroup))
 
      (wg-set-workgroup-working-wconfig workgroup (wg-current-wconfig))
 
    (wg-with-undo workgroup (state undo-pointer undo-list)
 
      (nth undo-pointer undo-list))))
 

	
 
(defun wg-update-current-workgroup-working-wconfig ()
 
  "Update `selected-frame's current workgroup's working-wconfig with `wg-current-wconfig'."
 
  (wg-awhen (wg-current-workgroup t)
 
    (wg-set-workgroup-working-wconfig it (wg-current-wconfig))))
 

	
 
(defun wg-restore-wconfig-undoably (wconfig &optional noundo)
 
  "Restore WCONFIG in `selected-frame', saving undo information.
 
Skip undo when NOUNDO."
 
  (when noundo (wg-unflag-undoify-window-configuration-change))
 
  (wg-update-current-workgroup-working-wconfig)
 
  (wg-restore-wconfig wconfig))
 

	
 
(defun wg-workgroup-offset-position-in-undo-list (workgroup increment)
 
  "Increment WORKGROUP's undo-pointer by INCREMENT.
 
Also restore the wconfig at the incremented undo-pointer if
 
WORKGROUP is current."
 
  (wg-with-undo workgroup (state undo-pointer undo-list)
 
    (let ((new-pointer (+ undo-pointer increment)))
 
      (when (wg-within new-pointer 0 (length undo-list))
 
        (when (wg-current-workgroup-p workgroup)
 
          (wg-restore-wconfig-undoably (nth new-pointer undo-list) t))
 
        (setf (wg-workgroup-state-undo-pointer state) new-pointer)))))
 

	
 
(defun wg-undoify-window-configuration-change ()
 
  "Conditionally `wg-add-wconfig-to-undo-list'.
 
Added to `post-command-hook'."
 
  (when (and
 
         wg-window-configuration-changed         ;; When the window config has changed,
 
         wg-undoify-window-configuration-change  ;; and undoification is still on for the current command
 
         (wg-minibuffer-inactive-p))             ;; and the change didn't occur while the minibuffer is active,
 
    (wg-when-let ((workgroup (wg-current-workgroup t)))  ;; and there's a current workgroup,
 
      ;; add the current wconfig to that workgroup's undo list:
 
      (wg-add-wconfig-to-undo-list workgroup (wg-current-wconfig))))
 
  ;; Reset all flags no matter what:
 
  (setq wg-window-configuration-changed nil
 
        wg-undoify-window-configuration-change t
 
        wg-already-updated-working-wconfig nil))
 

	
 
(defun wg-update-working-wconfig-hook ()
 
  "Used in before advice on all functions that trigger `window-configuration-change-hook'.
 
To save up to date undo info before the change."
 
  (when (and (not wg-already-updated-working-wconfig)
 
             (wg-minibuffer-inactive-p))
 
    (wg-update-current-workgroup-working-wconfig)
 
    (setq wg-already-updated-working-wconfig t)))
 

	
 

	
 
(defun wg-workgroup-gc-buf-uids (workgroup)
 
  "Remove buf uids from WORKGROUP that have no referent in `wg-buf-list'."
 
  (wg-asetf (wg-workgroup-strong-buf-uids workgroup)
 
            (cl-remove-if-not 'wg-find-buf-by-uid it)
 
            (wg-workgroup-weak-buf-uids workgroup)
 
            (cl-remove-if-not 'wg-find-buf-by-uid it)))
 

	
 
(defun wg-gc-buf-uids ()
 
  "Remove from all workgroups those buf uids that have no referent in `wg-buf-list'."
 
  (mapc 'wg-workgroup-gc-buf-uids (wg-workgroup-list)))
src/workgroups-wtree.el
Show inline comments
 
;;; workgroups-wtree.el --- window-tree "class"
 
;;; Commentary:
 
;;
 
;; `window-tree' - several opened windows, their sizes and position is
 
;; what you want to save.
 
;;
 
;;; Code:
 

	
 
(require 'workgroups-win)
 

	
 
(defun wg-w-edges (w)
 
  "Return W's edge list."
 
  (cl-etypecase w
 
    (wg-win (wg-win-edges w))
 
    (wg-wtree (wg-wtree-edges w))))
 

	
 
(defun wg-copy-w (w)
 
  "Return a copy of W.  W should be a wg-win or a wg-wtree."
 
  (cl-etypecase w
 
    (wg-win (wg-copy-win w))
 
    (wg-wtree (wg-copy-wtree w))))
 

	
 
(defun wg-set-edges (w edges)
 
  "Set W's edge list, and return W."
 
  (cl-etypecase w
 
    (wg-win (setf (wg-win-edges w) edges))
 
    (wg-wtree (setf (wg-wtree-edges w) edges)))
 
  w)
 

	
 

	
 
(defun wg-equal-wtrees (w1 w2)
 
  "Return t when W1 and W2 have equal structure."
 
  (cond ((and (wg-win-p w1) (wg-win-p w2))
 
         (equal (wg-w-edges w1) (wg-w-edges w2)))
 
        ((and (wg-wtree-p w1) (wg-wtree-p w2))
 
         (and (eq (wg-wtree-dir w1) (wg-wtree-dir w2))
 
              (equal (wg-wtree-edges w1) (wg-wtree-edges w2))
 
              (cl-every #'wg-equal-wtrees
 
                        (wg-wtree-wlist w1)
 
                        (wg-wtree-wlist w2))))))
 

	
 
(defun wg-normalize-wtree (wtree)
 
  "Clean up and return a new wtree from WTREE.
 
Recalculate the edge lists of all subwins, and remove subwins
 
outside of WTREE's bounds.  If there's only one element in the
 
new wlist, return it instead of a new wtree."
 
  (if (wg-win-p wtree) wtree
 
    (wg-with-slots wtree ((dir wg-wtree-dir)
 
                          (wlist wg-wtree-wlist))
 
      (wg-with-bounds wtree dir (ls1 hs1 lb1 hb1)
 
        (let* ((min-size (wg-min-size dir))
 
               (max (- hb1 1 min-size))
 
               (lastw (wg-last1 wlist)))
 
          (cl-labels
 
              ((mapwl
 
                (wl)
 
                (wg-dbind (sw . rest) wl
 
                  (cons (wg-normalize-wtree
 
                         (wg-set-bounds
 
                          sw dir ls1 hs1 lb1
 
                          (setq lb1 (if (eq sw lastw) hb1
 
                                      (let ((hb2 (+ lb1 (wg-w-size sw dir))))
 
                                        (if (>= hb2 max) hb1 hb2))))))
 
                        (when (< lb1 max) (mapwl rest))))))
 
            (let ((new (mapwl wlist)))
 
              (if (not (cdr new)) (car new)
 
                (setf (wg-wtree-wlist wtree) new)
 
                wtree))))))))
 

	
 
(defun wg-scale-wtree (wtree wscale hscale)
 
  "Return a copy of WTREE with its dimensions scaled by WSCALE and HSCALE.
 
All WTREE's subwins are scaled as well."
 
  (let ((scaled (wg-scale-w-size wtree wscale hscale)))
 
    (if (wg-win-p wtree) scaled
 
      (wg-asetf (wg-wtree-wlist scaled)
 
                (wg-docar (sw it) (wg-scale-wtree sw wscale hscale)))
 
      scaled)))
 

	
 

	
 
(defun wg-resize-frame-scale-wtree (wconfig)
 
  "Set FRAME's size to WCONFIG's, returning a possibly scaled wtree.
 
If the frame size was set correctly, return WCONFIG's wtree
 
unchanged.  If it wasn't, return a copy of WCONFIG's wtree scaled
 
with `wg-scale-wconfigs-wtree' to fit the frame as it exists."
 
  (let ((frame (selected-frame)))
 
    (wg-with-slots wconfig ((wcwidth wg-wconfig-width)
 
                            (wcheight wg-wconfig-height))
 
      (when window-system (set-frame-size frame wcwidth wcheight))
 
      (let ((fwidth  (frame-parameter frame 'width))
 
            (fheight (frame-parameter frame 'height)))
 
        (if (and (= wcwidth fwidth) (= wcheight fheight))
 
            (wg-wconfig-wtree wconfig)
 
          (wg-scale-wconfigs-wtree wconfig fwidth fheight))))))
 

	
 

	
 
(defun wg-wtree-buf-uids (wtree)
 
  "Return a new list of the buf uids of all wins in WTREE."
 
  (if (not wtree)
 
      (error "WTREE is nil in `wg-wtree-buf-uids'!"))
 
  (wg-flatten-wtree wtree 'wg-win-buf-uid))
 

	
 
(defun wg-wtree-unique-buf-uids (wtree)
 
  "Return a list of the unique buf uids of all wins in WTREE."
 
  (cl-remove-duplicates (wg-wtree-buf-uids wtree) :test 'string=))
 

	
 

	
 

	
 

	
 
(defun wg-reset-window-tree ()
 
  "Delete all but one window in `selected-frame', and reset
 
various parameters of that window in preparation for restoring
 
a wtree."
 
  (delete-other-windows)
 
  (set-window-dedicated-p nil nil))
 

	
 
(defun wg-restore-window-tree-helper (w)
 
  "Recursion helper for `wg-restore-window-tree'."
 
  (if (wg-wtree-p w)
 
      (cl-loop with dir = (wg-wtree-dir w)
 
               for (win . rest) on (wg-wtree-wlist w)
 
               do (when rest (split-window nil (wg-w-size win dir) (not dir)))
 
               do (wg-restore-window-tree-helper win))
 
    (wg-restore-window w)
 
    (when (wg-win-selected w)
 
      (setq wg-window-tree-selected-window (selected-window)))
 
    (when (wg-win-minibuffer-scroll w)
 
      (setq minibuffer-scroll-window (selected-window)))
 
    (other-window 1)))
 

	
 
(defun wg-restore-window-tree (wtree)
 
  "Restore WTREE in `selected-frame'."
 
  (let ((window-min-width wg-window-min-width)
 
        (window-min-height wg-window-min-height)
 
        (wg-window-tree-selected-window nil))
 
    (wg-reset-window-tree)
 
    (wg-restore-window-tree-helper wtree)
 
    (wg-awhen wg-window-tree-selected-window (select-window it))))
 

	
 

	
 
;; (wg-window-tree-to-wtree (window-tree))
 
(defun wg-window-tree-to-wtree (window-tree)
 
  "Return the serialization (a wg-wtree) of Emacs window tree WINDOW-TREE."
 
  (wg-barf-on-active-minibuffer)
 
  (cl-labels
 
      ((inner (w) (if (windowp w) (wg-window-to-win w)
 
                    (wg-dbind (dir edges . wins) w
 
                      (wg-make-wtree
 
                       :dir    dir
 
                       :edges  edges
 
                       :wlist  (mapcar #'inner wins))))))
 
    (let ((w (car window-tree)))
 
      (when (and (windowp w) (window-minibuffer-p w))
 
        (error "Workgroups can't operate on minibuffer-only frames."))
 
      (inner w))))
 

	
 

	
 
(defun wg-flatten-wtree (wtree &optional key)
 
  "Return a new list by flattening WTREE.
 
KEY non returns returns a list of WTREE's wins.
 
KEY non-nil returns a list of the results of calling KEY on each win."
 
  (cl-labels
 
      ((inner (w) (if (wg-win-p w) (list (if key (funcall key w) w))
 
                    (cl-mapcan #'inner (wg-wtree-wlist w)))))
 
    (inner wtree)))
 

	
 
(defun wg-win-list (wtree)
 
  "Construct and return a list of all wg-wins in WTREE."
 
  (wg-flatten-wtree wtree))
 

	
 

	
 
(defun wg-reverse-wlist (w &optional dir)
 
  "Reverse W's wlist and those of all its sub-wtrees in direction DIR.
 
If DIR is nil, reverse WTREE horizontally.
 
If DIR is 'both, reverse WTREE both horizontally and vertically.
 
Otherwise, reverse WTREE vertically."
 
  (cl-labels
 
      ((inner (w) (if (wg-win-p w) w
 
                    (wg-with-slots w ((d1 wg-wtree-dir))
 
                      (wg-make-wtree
 
                       :dir d1
 
                       :edges (wg-wtree-edges w)
 
                       :wlist (let ((wl2 (mapcar #'inner (wg-wtree-wlist w))))
 
                                (if (or (eq dir 'both) (eq dir d1))
 
                                    (nreverse wl2)
 
                                  wl2)))))))
 
    (wg-normalize-wtree (inner w))))
 

	
 
(defun wg-wtree-move-window (wtree offset)
 
  "Offset `selected-window' OFFSET places in WTREE."
 
  (cl-labels
 
      ((inner (w) (if (wg-win-p w) w
 
                    (wg-with-slots w ((wlist wg-wtree-wlist))
 
                      (wg-make-wtree
 
                       :dir (wg-wtree-dir w)
 
                       :edges (wg-wtree-edges w)
 
                       :wlist (wg-aif (cl-find t wlist :key 'wg-win-selected)
 
                       :wlist (aif (cl-find t wlist :key 'wg-win-selected)
 
                                  (wg-cyclic-offset-elt it wlist offset)
 
                                (mapcar #'inner wlist)))))))
 
    (wg-normalize-wtree (inner wtree))))
 

	
 

	
 

	
 
(provide 'workgroups-wtree)
 
;;; workgroups-wtree.el ends here
0 comments (0 inline, 0 general)