Klimi's new dotfiles with stow.
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1002 lines
42 KiB

  1. ;;; sesman.el --- Generic Session Manager -*- lexical-binding: t -*-
  2. ;;
  3. ;; Copyright (C) 2018, Vitalie Spinu
  4. ;; Author: Vitalie Spinu
  5. ;; URL: https://github.com/vspinu/sesman
  6. ;; Keywords: process
  7. ;; Version: 0.3.3-DEV
  8. ;; Package-Requires: ((emacs "25"))
  9. ;; Keywords: processes, tools, vc
  10. ;;
  11. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  12. ;;
  13. ;; This file is *NOT* part of GNU Emacs.
  14. ;;
  15. ;; This program is free software; you can redistribute it and/or
  16. ;; modify it under the terms of the GNU General Public License as
  17. ;; published by the Free Software Foundation; either version 3, or
  18. ;; (at your option) any later version.
  19. ;;
  20. ;; This program is distributed in the hope that it will be useful,
  21. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  23. ;; General Public License for more details.
  24. ;;
  25. ;; You should have received a copy of the GNU General Public License
  26. ;; along with this program; see the file COPYING. If not, write to
  27. ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth
  28. ;; Floor, Boston, MA 02110-1301, USA.
  29. ;;
  30. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  31. ;;
  32. ;;; Commentary:
  33. ;;
  34. ;; Sesman provides facilities for session management and interactive session
  35. ;; association with the current contexts (project, directory, buffers etc). See
  36. ;; project's readme for more details.
  37. ;;
  38. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  39. ;;
  40. ;;; Code:
  41. (require 'cl-generic)
  42. (require 'seq)
  43. (require 'subr-x)
  44. (require 'vc)
  45. (defgroup sesman nil
  46. "Generic Session Manager."
  47. :prefix "sesman-"
  48. :group 'tools
  49. :link '(url-link :tag "GitHub" "https://github.com/vspinu/sesman"))
  50. (defface sesman-project-face
  51. '((default (:inherit font-lock-doc-face)))
  52. "Face used to mark projects."
  53. :group 'sesman)
  54. (defface sesman-directory-face
  55. '((default (:inherit font-lock-type-face)))
  56. "Face used to mark directories."
  57. :group 'sesman)
  58. (defface sesman-buffer-face
  59. '((default (:inherit font-lock-preprocessor-face)))
  60. "Face used to mark buffers."
  61. :group 'sesman)
  62. (defcustom sesman-use-friendly-sessions t
  63. "If non-nil consider friendly sessions when looking for current sessions.
  64. The definition of friendly sessions is system dependent but usually means
  65. sessions running in dependent projects."
  66. :group 'sesman
  67. :type 'boolean
  68. :package-version '(sesman . "0.3.2"))
  69. (defcustom sesman-follow-symlinks 'vc
  70. "When non-nil, follow symlinks during the file expansion.
  71. When nil, don't follow symlinks. When 'vc, follow symlinks only when
  72. `vc-follow-symlinks' is non-nil. When t, always follow symlinks."
  73. :group 'sesman
  74. :type '(choice (const :tag "Comply with `vc-follow-symlinks'" vc)
  75. (const :tag "Don't follow symlinks" nil)
  76. (const :tag "Follow symlinks" t))
  77. :package-version '(sesman . "0.3.3"))
  78. (put 'sesman-follow-symlinks 'safe-local-variable (lambda (x) (memq x '(vc nil t))))
  79. ;; (defcustom sesman-disambiguate-by-relevance t
  80. ;; "If t choose most relevant session in ambiguous situations, otherwise ask.
  81. ;; Ambiguity arises when multiple sessions are associated with current context. By
  82. ;; default only projects could be associated with multiple sessions. See
  83. ;; `sesman-single-link-contexts' in order to change that. Relevance is decided by
  84. ;; system's implementation, see `sesman-more-relevant-p'."
  85. ;; :group 'sesman
  86. ;; :type 'boolean)
  87. (defcustom sesman-single-link-context-types '(buffer)
  88. "List of context types to which at most one session can be linked."
  89. :group 'sesman
  90. :type '(repeat symbol)
  91. :package-version '(sesman . "0.1.0"))
  92. ;; FIXME:
  93. ;; (defcustom sesman-abbreviate-paths 2
  94. ;; "Abbreviate paths to that many parents.
  95. ;; When set to nil, don't abbreviate directories."
  96. ;; :group 'sesman
  97. ;; :type '(choice number
  98. ;; (const :tag "Don't abbreviate" nil)))
  99. (defvar sesman-sessions-hashmap (make-hash-table :test #'equal)
  100. "Hash-table of all sesman sessions.
  101. Key is a cons (system-name . session-name).")
  102. (defvar sesman-links-alist nil
  103. "An alist of all sesman links.
  104. Each element is of the form (key cxt-type cxt-value) where
  105. \"key\" is of the form (system-name . session-name). system-name
  106. and cxt-type must be symbols.")
  107. (defvar-local sesman-system nil
  108. "Name of the system managed by `sesman'.
  109. Can be either a symbol, or a function returning a symbol.")
  110. (put 'sesman-system 'permanent-local 't)
  111. ;; Internal Utilities
  112. (defun sesman--on-C-u-u-sessions (system which)
  113. (cond
  114. ((null which)
  115. (let ((ses (sesman-current-session system)))
  116. (when ses
  117. (list ses))))
  118. ((or (equal which '(4)) (eq which 'linked))
  119. (sesman--linked-sessions system 'sort))
  120. ((or (equal which '(16)) (eq which 'all) (eq which t))
  121. (sesman--all-system-sessions system 'sort))
  122. ;; session itself
  123. ((and (listp which)
  124. (or (stringp (car which))
  125. (symbolp (car which))))
  126. (list which))
  127. ;; session name
  128. ((or (stringp which)
  129. (symbolp which)
  130. (gethash (cons system which) sesman-sessions-hashmap)))
  131. (t (error "Invalid which argument (%s)" which))))
  132. (defun sesman--cap-system-name (system)
  133. (let ((name (symbol-name system)))
  134. (if (string-match-p "^[[:upper:]]" name)
  135. name
  136. (capitalize name))))
  137. (defun sesman--least-specific-context (system)
  138. (seq-some (lambda (ctype)
  139. (when-let (val (sesman-context ctype system))
  140. (cons ctype val)))
  141. (reverse (sesman-context-types system))))
  142. (defun sesman--link-session-interactively (session cxt-type cxt-val)
  143. (let ((system (sesman--system)))
  144. (unless cxt-type
  145. (let ((cxt (sesman--least-specific-context system)))
  146. (setq cxt-type (car cxt)
  147. cxt-val (cdr cxt))))
  148. (let ((cxt-name (symbol-name cxt-type)))
  149. (if (member cxt-type (sesman-context-types system))
  150. (let ((session (or session
  151. (sesman-ask-for-session
  152. system
  153. (format "Link with %s %s: "
  154. cxt-name (sesman--abbrev-path-maybe
  155. (sesman-context cxt-type system)))
  156. (sesman--all-system-sessions system 'sort)
  157. 'ask-new))))
  158. (sesman-link-session system session cxt-type cxt-val))
  159. (error (format "%s association not allowed for this system (%s)"
  160. (capitalize cxt-name)
  161. system))))))
  162. ;; FIXME: incorporate `sesman-abbreviate-paths'
  163. (defun sesman--abbrev-path-maybe (obj)
  164. (if (stringp obj)
  165. (abbreviate-file-name obj)
  166. obj))
  167. (defun sesman--system-in-buffer (&optional buffer)
  168. (with-current-buffer (or buffer (current-buffer))
  169. (if (functionp sesman-system)
  170. (funcall sesman-system)
  171. sesman-system)))
  172. (defun sesman--system ()
  173. (if sesman-system
  174. (if (functionp sesman-system)
  175. (funcall sesman-system)
  176. sesman-system)
  177. (error "No `sesman-system' in buffer `%s'" (current-buffer))))
  178. (defun sesman--linked-sessions (system &optional sort cxt-types)
  179. (let* ((system (or system (sesman--system)))
  180. (cxt-types (or cxt-types (sesman-context-types system))))
  181. ;; just in case some links are lingering due to user errors
  182. (sesman--clear-links)
  183. (delete-dups
  184. (mapcar (lambda (assoc)
  185. (gethash (car assoc) sesman-sessions-hashmap))
  186. (sesman-current-links system nil sort cxt-types)))))
  187. (defun sesman--friendly-sessions (system &optional sort)
  188. (let ((sessions (seq-filter (lambda (ses) (sesman-friendly-session-p system ses))
  189. (sesman--all-system-sessions system))))
  190. (if sort
  191. (sesman--sort-sessions system sessions)
  192. sessions)))
  193. (defun sesman--all-system-sessions (&optional system sort)
  194. "Return a list of sessions registered with SYSTEM.
  195. If SORT is non-nil, sort in relevance order."
  196. (let ((system (or system (sesman--system)))
  197. sessions)
  198. (maphash
  199. (lambda (k s)
  200. (when (eql (car k) system)
  201. (push s sessions)))
  202. sesman-sessions-hashmap)
  203. (if sort
  204. (sesman--sort-sessions system sessions)
  205. sessions)))
  206. ;; FIXME: make this a macro
  207. (defun sesman--link-lookup-fn (&optional system ses-name cxt-type cxt-val x)
  208. (let ((system (or system (caar x)))
  209. (ses-name (or ses-name (cdar x)))
  210. (cxt-type (or cxt-type (nth 1 x)))
  211. (cxt-val (or cxt-val (nth 2 x))))
  212. (lambda (el)
  213. (and (or (null system) (eq (caar el) system))
  214. (or (null ses-name) (equal (cdar el) ses-name))
  215. (or (null cxt-type)
  216. (if (listp cxt-type)
  217. (member (nth 1 el) cxt-type)
  218. (eq (nth 1 el) cxt-type)))
  219. (or (null cxt-val) (equal (nth 2 el) cxt-val))))))
  220. (defun sesman--unlink (x)
  221. (setq sesman-links-alist
  222. (seq-remove (sesman--link-lookup-fn nil nil nil nil x)
  223. sesman-links-alist)))
  224. (defun sesman--clear-links ()
  225. (setq sesman-links-alist
  226. (seq-filter (lambda (x)
  227. (gethash (car x) sesman-sessions-hashmap))
  228. sesman-links-alist)))
  229. (defun sesman--format-session-objects (system session &optional sep)
  230. (let ((info (sesman-session-info system session)))
  231. (if (and (listp info)
  232. (keywordp (car info)))
  233. (let ((ses-name (car session))
  234. (sep (or sep " "))
  235. (strings (or (plist-get info :strings)
  236. (mapcar (lambda (x) (format "%s" x))
  237. (plist-get info :objects)))))
  238. (mapconcat (lambda (str)
  239. (replace-regexp-in-string ses-name "..." str nil t))
  240. strings sep))
  241. (format "%s" info))))
  242. (defun sesman--format-session (system ses &optional prefix)
  243. (format (propertize "%s%s [%s] linked-to %s" 'face 'bold)
  244. (or prefix "")
  245. (propertize (car ses) 'face 'bold)
  246. (propertize (sesman--format-session-objects system ses ", ") 'face 'italic)
  247. (sesman-grouped-links system ses t t)))
  248. (defun sesman--format-link (link)
  249. (let* ((system (sesman--lnk-system-name link))
  250. (session (gethash (car link) sesman-sessions-hashmap)))
  251. (format "%s(%s) -> %s [%s]"
  252. (sesman--lnk-context-type link)
  253. (propertize (format "%s" (sesman--abbrev-path-maybe (sesman--lnk-value link)))
  254. 'face 'bold)
  255. (propertize (sesman--lnk-session-name link) 'face 'bold)
  256. (if session
  257. (sesman--format-session-objects system session)
  258. "invalid"))))
  259. (defun sesman--ask-for-link (prompt links &optional ask-all)
  260. (let* ((name.keys (mapcar (lambda (link)
  261. (cons (sesman--format-link link) link))
  262. links))
  263. (name.keys (append name.keys
  264. (when (and ask-all (> (length name.keys) 1))
  265. '(("*all*")))))
  266. (nms (mapcar #'car name.keys))
  267. (sel (completing-read prompt nms nil t nil nil (car nms))))
  268. (cond ((string= sel "*all*")
  269. links)
  270. (ask-all
  271. (list (cdr (assoc sel name.keys))))
  272. (t
  273. (cdr (assoc sel name.keys))))))
  274. (defun sesman--sort-sessions (system sessions)
  275. (seq-sort (lambda (x1 x2)
  276. (sesman-more-relevant-p system x1 x2))
  277. sessions))
  278. (defun sesman--sort-links (system links)
  279. (seq-sort (lambda (x1 x2)
  280. (sesman-more-relevant-p system
  281. (gethash (car x1) sesman-sessions-hashmap)
  282. (gethash (car x2) sesman-sessions-hashmap)))
  283. links))
  284. ;; link data structure accessors
  285. (defun sesman--lnk-system-name (lnk)
  286. (caar lnk))
  287. (defun sesman--lnk-session-name (lnk)
  288. (cdar lnk))
  289. (defun sesman--lnk-context-type (lnk)
  290. (cadr lnk))
  291. (defun sesman--lnk-value (lnk)
  292. (nth 2 lnk))
  293. ;;; User Interface
  294. (defun sesman-post-command-hook nil
  295. "Normal hook ran after every state-changing Sesman command.")
  296. ;;;###autoload
  297. (defun sesman-start ()
  298. "Start a Sesman session."
  299. (interactive)
  300. (let ((system (sesman--system)))
  301. (message "Starting new %s session ..." system)
  302. (prog1 (sesman-start-session system)
  303. (run-hooks 'sesman-post-command-hook))))
  304. ;;;###autoload
  305. (defun sesman-restart (&optional which)
  306. "Restart sesman session.
  307. When WHICH is nil, restart the current session; when a single universal
  308. argument or 'linked, restart all linked sessions; when a double universal
  309. argument, t or 'all, restart all sessions. For programmatic use, WHICH can also
  310. be a session or a name of the session, in which case that session is restarted."
  311. (interactive "P")
  312. (let* ((system (sesman--system))
  313. (sessions (sesman--on-C-u-u-sessions system which)))
  314. (if (null sessions)
  315. (message "No %s sessions found" system)
  316. (with-temp-message (format "Restarting %s %s %s" system
  317. (if (= 1 (length sessions)) "session" "sessions")
  318. (mapcar #'car sessions))
  319. (mapc (lambda (s)
  320. (sesman-restart-session system s))
  321. sessions))
  322. ;; restarting is not guaranteed to finish here, but what can we do?
  323. (run-hooks 'sesman-post-command-hook))))
  324. ;;;###autoload
  325. (defun sesman-quit (&optional which)
  326. "Terminate a Sesman session.
  327. When WHICH is nil, kill only the current session; when a single universal
  328. argument or 'linked, kill all linked sessions; when a double universal argument,
  329. t or 'all, kill all sessions. For programmatic use, WHICH can also be a session
  330. or a name of the session, in which case that session is killed."
  331. (interactive "P")
  332. (let* ((system (sesman--system))
  333. (sessions (sesman--on-C-u-u-sessions system which)))
  334. (if (null sessions)
  335. (message "No %s sessions found" system)
  336. (with-temp-message (format "Killing %s %s %s" system
  337. (if (= 1 (length sessions)) "session" "sessions")
  338. (mapcar #'car sessions))
  339. (mapc (lambda (s)
  340. (sesman-unregister system s)
  341. (sesman-quit-session system s))
  342. sessions))
  343. (run-hooks 'sesman-post-command-hook))))
  344. ;;;###autoload
  345. (defun sesman-info (&optional all)
  346. "Display info for all current sessions (`sesman-current-sessions').
  347. In the resulting minibuffer display linked sessions are numbered and the
  348. other (friendly) sessions are not. When ALL is non-nil, show info for all
  349. sessions."
  350. (interactive "P")
  351. (let* ((system (sesman--system))
  352. (i 1)
  353. (sessions (if all
  354. (sesman-sessions system t)
  355. (sesman-current-sessions system)))
  356. (empty-prefix (if (> (length sessions) 1) " " "")))
  357. (if sessions
  358. (message (mapconcat (lambda (ses)
  359. (let ((prefix (if (sesman-relevant-session-p system ses)
  360. (prog1 (format "%d " i)
  361. (setq i (1+ i)))
  362. empty-prefix)))
  363. (sesman--format-session system ses prefix)))
  364. sessions
  365. "\n"))
  366. (message "No %s%s sessions"
  367. (if all "" "current ")
  368. system))))
  369. ;;;###autoload
  370. (defun sesman-link-with-buffer (&optional buffer session)
  371. "Ask for SESSION and link with BUFFER.
  372. BUFFER defaults to current buffer. On universal argument, or if BUFFER is 'ask,
  373. ask for buffer."
  374. (interactive "P")
  375. (let ((buf (if (or (eq buffer 'ask)
  376. (equal buffer '(4)))
  377. (let ((this-system (sesman--system)))
  378. (read-buffer "Link buffer: " (current-buffer) t
  379. (lambda (buf-cons)
  380. (equal this-system
  381. (sesman--system-in-buffer (cdr buf-cons))))))
  382. (or buffer (current-buffer)))))
  383. (sesman--link-session-interactively session 'buffer buf)))
  384. ;;;###autoload
  385. (defun sesman-link-with-directory (&optional dir session)
  386. "Ask for SESSION and link with DIR.
  387. DIR defaults to `default-directory'. On universal argument, or if DIR is 'ask,
  388. ask for directory."
  389. (interactive "P")
  390. (let ((dir (if (or (eq dir 'ask)
  391. (equal dir '(4)))
  392. (read-directory-name "Link directory: ")
  393. (or dir default-directory))))
  394. (sesman--link-session-interactively session 'directory dir)))
  395. ;;;###autoload
  396. (defun sesman-link-with-project (&optional project session)
  397. "Ask for SESSION and link with PROJECT.
  398. PROJECT defaults to current project. On universal argument, or if PROJECT is
  399. 'ask, ask for the project. SESSION defaults to the current session."
  400. (interactive "P")
  401. (let* ((system (sesman--system))
  402. (project (expand-file-name
  403. (if (or (eq project 'ask)
  404. (equal project '(4)))
  405. ;; FIXME: should be a completion over all known projects for this system
  406. (read-directory-name "Project: " (sesman-project system))
  407. (or project (sesman-project system))))))
  408. (sesman--link-session-interactively session 'project project)))
  409. ;;;###autoload
  410. (defun sesman-link-with-least-specific (&optional session)
  411. "Ask for SESSION and link with the least specific context available.
  412. Normally the least specific context is the project. If not in a project, link
  413. with the `default-directory'. If `default-directory' is nil, link with current
  414. buffer."
  415. (interactive "P")
  416. (sesman--link-session-interactively session nil nil))
  417. ;;;###autoload
  418. (defun sesman-unlink ()
  419. "Break any of the previously created links."
  420. (interactive)
  421. (let* ((system (sesman--system))
  422. (links (or (sesman-current-links system)
  423. (user-error "No %s links found" system))))
  424. (mapc #'sesman--unlink
  425. (sesman--ask-for-link "Unlink: " links 'ask-all)))
  426. (run-hooks 'sesman-post-command-hook))
  427. (declare-function sesman-browser "sesman-browser")
  428. ;;;###autoload (autoload 'sesman-map "sesman" "Session management prefix keymap." t 'keymap)
  429. (defvar sesman-map
  430. (let (sesman-map)
  431. (define-prefix-command 'sesman-map)
  432. (define-key sesman-map (kbd "C-i") #'sesman-info)
  433. (define-key sesman-map (kbd "i") #'sesman-info)
  434. (define-key sesman-map (kbd "C-w") #'sesman-browser)
  435. (define-key sesman-map (kbd "w") #'sesman-browser)
  436. (define-key sesman-map (kbd "C-s") #'sesman-start)
  437. (define-key sesman-map (kbd "s") #'sesman-start)
  438. (define-key sesman-map (kbd "C-r") #'sesman-restart)
  439. (define-key sesman-map (kbd "r") #'sesman-restart)
  440. (define-key sesman-map (kbd "C-q") #'sesman-quit)
  441. (define-key sesman-map (kbd "q") #'sesman-quit)
  442. (define-key sesman-map (kbd "C-l") #'sesman-link-with-least-specific)
  443. (define-key sesman-map (kbd "l") #'sesman-link-with-least-specific)
  444. (define-key sesman-map (kbd "C-b") #'sesman-link-with-buffer)
  445. (define-key sesman-map (kbd "b") #'sesman-link-with-buffer)
  446. (define-key sesman-map (kbd "C-d") #'sesman-link-with-directory)
  447. (define-key sesman-map (kbd "d") #'sesman-link-with-directory)
  448. (define-key sesman-map (kbd "C-p") #'sesman-link-with-project)
  449. (define-key sesman-map (kbd "p") #'sesman-link-with-project)
  450. (define-key sesman-map (kbd "C-u") #'sesman-unlink)
  451. (define-key sesman-map (kbd " u") #'sesman-unlink)
  452. sesman-map)
  453. "Session management prefix keymap.")
  454. (defvar sesman-menu
  455. '("Sesman"
  456. ["Show Session Info" sesman-info]
  457. "--"
  458. ["Start" sesman-start]
  459. ["Restart" sesman-restart :active (sesman-current-session (sesman--system))]
  460. ["Quit" sesman-quit :active (sesman-current-session (sesman--system))]
  461. "--"
  462. ["Link with Buffer" sesman-link-with-buffer :active (sesman-current-session (sesman--system))]
  463. ["Link with Directory" sesman-link-with-directory :active (sesman-current-session (sesman--system))]
  464. ["Link with Project" sesman-link-with-project :active (sesman-current-session (sesman--system))]
  465. "--"
  466. ["Unlink" sesman-unlink :active (sesman-current-session (sesman--system))])
  467. "Sesman Menu.")
  468. (defun sesman-install-menu (map)
  469. "Install `sesman-menu' into MAP."
  470. (easy-menu-do-define 'seman-menu-open
  471. map
  472. (get 'sesman-menu 'variable-documentation)
  473. sesman-menu))
  474. ;;; System Generic
  475. (cl-defgeneric sesman-start-session (system)
  476. "Start and return SYSTEM SESSION.")
  477. (cl-defgeneric sesman-quit-session (system session)
  478. "Terminate SYSTEM SESSION.")
  479. (cl-defgeneric sesman-restart-session (system session)
  480. "Restart SYSTEM SESSION.
  481. By default, calls `sesman-quit-session' and then
  482. `sesman-start-session'."
  483. (let ((old-name (car session)))
  484. (sesman-quit-session system session)
  485. (let ((new-session (sesman-start-session system)))
  486. (setcar new-session old-name))))
  487. (cl-defgeneric sesman-session-info (_system session)
  488. "Return a plist with :objects key containing user \"visible\" objects.
  489. Optional :strings value is a list of string representations of objects. Optional
  490. :map key is a local keymap to place on every object in the session browser.
  491. Optional :buffers is a list of buffers which will be used for navigation from
  492. the session browser. If :buffers is missing, buffers from :objects are used
  493. instead."
  494. (list :objects (cdr session)))
  495. (cl-defgeneric sesman-project (_system)
  496. "Retrieve project root in current directory (`default-directory') for SYSTEM.
  497. Return a string or nil if no project has been found."
  498. nil)
  499. (cl-defgeneric sesman-more-relevant-p (_system session1 session2)
  500. "Return non-nil if SESSION1 should be sorted before SESSION2.
  501. By default, sort by session name. Systems should overwrite this method to
  502. provide a more meaningful ordering. If your system objects are buffers you can
  503. use `sesman-more-recent-p' utility in this method."
  504. (not (string-greaterp (car session1) (car session2))))
  505. (cl-defgeneric sesman-friendly-session-p (_system _session)
  506. "Return non-nil if SESSION is a friendly session in current context.
  507. The \"friendship\" is system dependent but usually means sessions running in
  508. dependent projects. Unless SYSTEM has defined a method for this generic, there
  509. are no friendly sessions."
  510. nil)
  511. (cl-defgeneric sesman-context-types (_system)
  512. "Return a list of context types understood by SYSTEM.
  513. Contexts must be sorted from most specific to least specific."
  514. '(buffer directory project))
  515. ;;; System API
  516. (defun sesman-session (system session-name)
  517. "Retrieve SYSTEM's session with SESSION-NAME from global hash."
  518. (let ((system (or system (sesman--system))))
  519. (gethash (cons system session-name) sesman-sessions-hashmap)))
  520. (defun sesman-sessions (system &optional sort type cxt-types)
  521. "Return a list of sessions registered with SYSTEM.
  522. When TYPE is either 'all or nil return all sessions registered with the SYSTEM,
  523. when 'linked, only linked to the current context sessions, when 'friendly - only
  524. friendly sessions. If SORT is non-nil, sessions are sorted in the relevance
  525. order with linked sessions leading the list. CXT-TYPES is a list of context
  526. types to consider for linked sessions."
  527. (let ((system (or system (sesman--system))))
  528. (cond
  529. ((eq type 'linked)
  530. (sesman--linked-sessions system sort cxt-types))
  531. ((eq type 'friendly)
  532. (sesman--friendly-sessions system sort))
  533. ((memq type '(all nil))
  534. (if sort
  535. (delete-dups
  536. (append (sesman--linked-sessions system 'sort cxt-types)
  537. (sesman--all-system-sessions system 'sort)))
  538. (sesman--all-system-sessions system)))
  539. (t (error "Invalid session TYPE argument %s" type)))))
  540. (defun sesman-current-sessions (system &optional cxt-types)
  541. "Return a list of SYSTEM sessions active in the current context.
  542. Sessions are ordered by the relevance order and linked sessions come first. If
  543. `sesman-use-friendly-sessions' current sessions consist of linked and friendly
  544. sessions, otherwise only of linked sessions. CXT-TYPES is a list of context
  545. types to consider. Defaults to the list returned from `sesman-context-types'."
  546. (if sesman-use-friendly-sessions
  547. (delete-dups
  548. (append (sesman--linked-sessions system 'sort cxt-types)
  549. (sesman--friendly-sessions system 'sort)))
  550. (sesman--linked-sessions system 'sort cxt-types)))
  551. (defun sesman-current-session (system &optional cxt-types)
  552. "Get the most relevant current session for the SYSTEM.
  553. CXT-TYPES is a list of context types to consider."
  554. (or (car (sesman--linked-sessions system 'sort cxt-types))
  555. (car (sesman--friendly-sessions system 'sort))))
  556. (defun sesman-ensure-session (system &optional cxt-types)
  557. "Get the most relevant linked session for SYSTEM or throw if none exists.
  558. CXT-TYPES is a list of context types to consider."
  559. (or (sesman-current-session system cxt-types)
  560. (user-error "No linked %s sessions" system)))
  561. (defun sesman-has-sessions-p (system)
  562. "Return t if there is at least one session registered with SYSTEM."
  563. (let ((system (or system (sesman--system)))
  564. (found))
  565. (condition-case nil
  566. (maphash (lambda (k _)
  567. (when (eq (car k) system)
  568. (setq found t)
  569. (throw 'found nil)))
  570. sesman-sessions-hashmap)
  571. (error))
  572. found))
  573. (defvar sesman--select-session-history nil)
  574. (defun sesman-ask-for-session (system prompt &optional sessions ask-new ask-all)
  575. "Ask for a SYSTEM session with PROMPT.
  576. SESSIONS defaults to value returned from `sesman-sessions'. If
  577. ASK-NEW is non-nil, offer *new* option to start a new session. If
  578. ASK-ALL is non-nil offer *all* option. If ASK-ALL is non-nil,
  579. return a list of sessions, otherwise a single session."
  580. (let* ((sessions (or sessions (sesman-sessions system)))
  581. (name.syms (mapcar (lambda (s)
  582. (let ((name (car s)))
  583. (cons (if (symbolp name) (symbol-name name) name)
  584. name)))
  585. sessions))
  586. (nr (length name.syms))
  587. (syms (if (and (not ask-new) (= nr 0))
  588. (error "No %s sessions found" system)
  589. (append name.syms
  590. (when ask-new '(("*new*")))
  591. (when (and ask-all (> nr 1))
  592. '(("*all*"))))))
  593. (def (caar syms))
  594. ;; (def (if (assoc (car sesman--select-session-history) syms)
  595. ;; (car sesman--select-session-history)
  596. ;; (caar syms)))
  597. (sel (completing-read
  598. prompt (mapcar #'car syms) nil t nil 'sesman--select-session-history def)))
  599. (cond
  600. ((string= sel "*new*")
  601. (let ((ses (sesman-start-session system)))
  602. (message "Started %s" (car ses))
  603. (if ask-all (list ses) ses)))
  604. ((string= sel "*all*")
  605. sessions)
  606. (t
  607. (let* ((sym (cdr (assoc sel syms)))
  608. (ses (assoc sym sessions)))
  609. (if ask-all (list ses) ses))))))
  610. (defvar sesman--cxt-abbrevs '(buffer "buf" project "proj" directory "dir"))
  611. (defun sesman--format-context (cxt-type cxt-val extra-face)
  612. (let* ((face (intern (format "sesman-%s-face" cxt-type)))
  613. (short-type (propertize (or (plist-get sesman--cxt-abbrevs cxt-type)
  614. (symbol-value cxt-type))
  615. 'face (list (if (facep face)
  616. face
  617. 'font-lock-function-name-face)
  618. extra-face))))
  619. (concat short-type
  620. (propertize (format "(%s)" cxt-val)
  621. 'face extra-face))))
  622. (defun sesman-grouped-links (system session &optional current-first as-string)
  623. "Retrieve all links for SYSTEM's SESSION from the global `sesman-links-alist'.
  624. Return an alist of the form
  625. ((buffer buffers..)
  626. (directory directories...)
  627. (project projects...)).
  628. When `CURRENT-FIRST' is non-nil, a cons of two lists as above is returned with
  629. car containing links relevant in current context and cdr all other links. If
  630. AS-STRING is non-nil, return an equivalent string representation."
  631. (let* ((system (or system (sesman--system)))
  632. (session (or session (sesman-current-session system)))
  633. (ses-name (car session))
  634. (links (thread-last sesman-links-alist
  635. (seq-filter (sesman--link-lookup-fn system ses-name))
  636. (sesman--sort-links system)
  637. (reverse)))
  638. (out (mapcar (lambda (x) (list x))
  639. (sesman-context-types system)))
  640. (out-rel (when current-first
  641. (copy-alist out))))
  642. (mapc (lambda (link)
  643. (let* ((type (sesman--lnk-context-type link))
  644. (entry (if (and current-first
  645. (sesman-relevant-link-p link))
  646. (assoc type out-rel)
  647. (assoc type out))))
  648. (when entry
  649. (setcdr entry (cons link (cdr entry))))))
  650. links)
  651. (let ((out (delq nil (mapcar (lambda (el) (and (cdr el) el)) out)))
  652. (out-rel (delq nil (mapcar (lambda (el) (and (cdr el) el)) out-rel))))
  653. (if as-string
  654. (let ((fmt-fn (lambda (typed-links)
  655. (let* ((type (car typed-links)))
  656. (mapconcat (lambda (lnk)
  657. (let ((val (sesman--abbrev-path-maybe
  658. (sesman--lnk-value lnk))))
  659. (sesman--format-context type val 'italic)))
  660. (cdr typed-links)
  661. ", ")))))
  662. (if out-rel
  663. (concat (mapconcat fmt-fn out-rel ", ")
  664. (when out " | ")
  665. (mapconcat fmt-fn out ", "))
  666. (mapconcat fmt-fn out ", ")))
  667. (if current-first
  668. (cons out-rel out)
  669. out)))))
  670. (defun sesman-link-session (system session &optional cxt-type cxt-val)
  671. "Link SYSTEM's SESSION to context give by CXT-TYPE and CXT-VAL.
  672. If CXT-TYPE is nil, use the least specific type available in the current
  673. context. If CXT-TYPE is non-nil, and CXT-VAL is not given, retrieve it with
  674. `sesman-context'. See also `sesman-link-with-project',
  675. `sesman-link-with-directory' and `sesman-link-with-buffer'."
  676. (let* ((ses-name (or (car-safe session)
  677. (error "SESSION must be a headed list")))
  678. (cxt-val (or cxt-val
  679. (or (if cxt-type
  680. (sesman-context cxt-type system)
  681. (let ((cxt (sesman--least-specific-context system)))
  682. (setq cxt-type (car cxt))
  683. (cdr cxt)))
  684. (error "No local context of type %s" cxt-type))))
  685. (cxt-val (if (stringp cxt-val)
  686. (expand-file-name cxt-val)
  687. cxt-val))
  688. (key (cons system ses-name))
  689. (link (list key cxt-type cxt-val)))
  690. (if (member cxt-type sesman-single-link-context-types)
  691. (thread-last sesman-links-alist
  692. (seq-remove (sesman--link-lookup-fn system nil cxt-type cxt-val))
  693. (cons link)
  694. (setq sesman-links-alist))
  695. (unless (seq-filter (sesman--link-lookup-fn system ses-name cxt-type cxt-val)
  696. sesman-links-alist)
  697. (setq sesman-links-alist (cons link sesman-links-alist))))
  698. (run-hooks 'sesman-post-command-hook)
  699. link))
  700. (defun sesman-links (system &optional session-or-name cxt-types sort)
  701. "Retrieve all links for SYSTEM, SESSION-OR-NAME and CXT-TYPES.
  702. SESSION-OR-NAME can be either a session or a name of the session. If SORT is
  703. non-nil links are sorted in relevance order and `sesman-current-links' lead the
  704. list, otherwise links are returned in the creation order."
  705. (let* ((ses-name (if (listp session-or-name)
  706. (car session-or-name)
  707. session-or-name))
  708. (lfn (sesman--link-lookup-fn system ses-name cxt-types)))
  709. (if sort
  710. (delete-dups (append
  711. (sesman-current-links system ses-name)
  712. (sesman--sort-links system (seq-filter lfn sesman-links-alist))))
  713. (seq-filter lfn sesman-links-alist))))
  714. (defun sesman-current-links (system &optional session-or-name sort cxt-types)
  715. "Retrieve all active links in current context for SYSTEM and SESSION-OR-NAME.
  716. SESSION-OR-NAME can be either a session or a name of the session. CXT-TYPES is a
  717. list of context types to consider. Returned links are a subset of
  718. `sesman-links-alist' sorted in order of relevance if SORT is non-nil."
  719. ;; mapcan is a built-in in 26.1; don't want to require cl-lib for one function
  720. (let ((ses-name (if (listp session-or-name)
  721. (car session-or-name)
  722. session-or-name)))
  723. (seq-mapcat
  724. (lambda (cxt-type)
  725. (let* ((lfn (sesman--link-lookup-fn system ses-name cxt-type))
  726. (links (seq-filter (lambda (l)
  727. (and (funcall lfn l)
  728. (sesman-relevant-context-p cxt-type (sesman--lnk-value l))))
  729. sesman-links-alist)))
  730. (if sort
  731. (sesman--sort-links system links)
  732. links)))
  733. (or cxt-types (sesman-context-types system)))))
  734. (defun sesman-has-links-p (system &optional cxt-types)
  735. "Return t if there is at least one linked session.
  736. CXT-TYPES defaults to `sesman-context-types' for current SYSTEM."
  737. (let ((cxt-types (or cxt-types (sesman-context-types system)))
  738. (found))
  739. (condition-case nil
  740. (mapc (lambda (l)
  741. (when (eq system (sesman--lnk-system-name l))
  742. (let ((cxt (sesman--lnk-context-type l)))
  743. (when (and (member cxt cxt-types)
  744. (sesman-relevant-context-p cxt (sesman--lnk-value l)))
  745. (setq found t)
  746. (throw 'found nil)))))
  747. sesman-links-alist)
  748. (error))
  749. found))
  750. (defun sesman-register (system session)
  751. "Register SESSION into `sesman-sessions-hashmap' and `sesman-links-alist'.
  752. SYSTEM defaults to current system. If a session with same name is already
  753. registered in `sesman-sessions-hashmap', change the name by appending \"#1\",
  754. \"#2\" ... to the name. This function should be called by system-specific
  755. connection initializers (\"run-xyz\", \"xyz-jack-in\" etc.)."
  756. (let* ((system (or system (sesman--system)))
  757. (ses-name (car session))
  758. (ses-name0 (car session))
  759. (i 1))
  760. (while (sesman-session system ses-name)
  761. (setq ses-name (format "%s#%d" ses-name0 i)
  762. i (1+ i)))
  763. (setq session (cons ses-name (cdr session)))
  764. (puthash (cons system ses-name) session sesman-sessions-hashmap)
  765. (sesman-link-session system session)
  766. session))
  767. (defun sesman-unregister (system session)
  768. "Unregister SESSION.
  769. SYSTEM defaults to current system. Remove session from
  770. `sesman-sessions-hashmap' and `sesman-links-alist'."
  771. (let ((ses-key (cons system (car session))))
  772. (remhash ses-key sesman-sessions-hashmap)
  773. (sesman--clear-links)
  774. session))
  775. (defun sesman-add-object (system session-name object &optional allow-new)
  776. "Add (destructively) OBJECT to session SESSION-NAME of SYSTEM.
  777. If ALLOW-NEW is nil and session with SESSION-NAME does not exist
  778. throw an error, otherwise register a new session with
  779. session (list SESSION-NAME OBJECT)."
  780. (let* ((system (or system (sesman--system)))
  781. (session (sesman-session system session-name)))
  782. (if session
  783. (setcdr session (cons object (cdr session)))
  784. (if allow-new
  785. (sesman-register system (list session-name object))
  786. (error "%s session '%s' does not exist"
  787. (sesman--cap-system-name system) session-name)))))
  788. (defun sesman-remove-object (system session-name object &optional auto-unregister no-error)
  789. "Remove (destructively) OBJECT from session SESSION-NAME of SYSTEM.
  790. If SESSION-NAME is nil, retrieve the session with
  791. `sesman-session-for-object'. If OBJECT is the last object in sesman
  792. session, `sesman-unregister' the session. If AUTO-UNREGISTER is non-nil
  793. unregister sessions of length 0 and remove all the links with the session.
  794. If NO-ERROR is non-nil, don't throw an error if OBJECT is not found in any
  795. session. This is useful if there are several \"concurrent\" parties which
  796. can remove the object."
  797. (let* ((system (or system (sesman--system)))
  798. (session (if session-name
  799. (sesman-session system session-name)
  800. (sesman-session-for-object system object no-error)))
  801. (new-session (delete object session)))
  802. (cond ((null new-session))
  803. ((= (length new-session) 1)
  804. (when auto-unregister
  805. (sesman-unregister system session)))
  806. (t
  807. (puthash (cons system (car session)) new-session sesman-sessions-hashmap)))))
  808. (defun sesman-session-for-object (system object &optional no-error)
  809. "Retrieve SYSTEM session which contains OBJECT.
  810. When NO-ERROR is non-nil, don't throw an error if OBJECT is not part of any
  811. session. In such case, return nil."
  812. (let* ((system (or system (sesman--system)))
  813. (sessions (sesman--all-system-sessions system)))
  814. (or (seq-find (lambda (ses)
  815. (seq-find (lambda (x) (equal object x)) (cdr ses)))
  816. sessions)
  817. (unless no-error
  818. (error "%s is not part of any %s sessions"
  819. object system)))))
  820. (defun sesman-session-name-for-object (system object &optional no-error)
  821. "Retrieve the name of the SYSTEM's session containing OBJECT.
  822. When NO-ERROR is non-nil, don't throw an error if OBJCECT is not part of
  823. any session. In such case, return nil."
  824. (car (sesman-session-for-object system object no-error)))
  825. (defun sesman-more-recent-p (bufs1 bufs2)
  826. "Return t if BUFS1 is more recent than BUFS2.
  827. BUFS1 and BUFS2 are either buffers or lists of buffers. When lists of
  828. buffers, most recent buffers from each list are considered. To be used
  829. primarily in `sesman-more-relevant-p' methods when session objects are
  830. buffers."
  831. (let ((bufs1 (if (bufferp bufs1) (list bufs1) bufs1))
  832. (bufs2 (if (bufferp bufs2) (list bufs2) bufs2)))
  833. (eq 1 (seq-some (lambda (b)
  834. (if (member b bufs1)
  835. 1
  836. (when (member b bufs2)
  837. -1)))
  838. (buffer-list)))))
  839. ;; path caching because file-truename is very slow
  840. (defvar sesman--path-cache (make-hash-table :test #'equal))
  841. (defun sesman-expand-path (path)
  842. "Expand PATH with optionally follow symlinks.
  843. Whether symlinks are followed is controlled by `sesman-follow-symlinks' custom
  844. variable. Always return the expansion without the trailing directory slash."
  845. (directory-file-name
  846. (if sesman-follow-symlinks
  847. (let ((true-name (or (gethash path sesman--path-cache)
  848. (puthash path (file-truename path) sesman--path-cache))))
  849. (if (or (eq sesman-follow-symlinks t)
  850. vc-follow-symlinks)
  851. true-name
  852. ;; sesman-follow-symlinks is 'vc but vc-follow-symlinks is nil
  853. (expand-file-name path)))
  854. (expand-file-name path))))
  855. ;;; Contexts
  856. (cl-defgeneric sesman-context (_cxt-type _system)
  857. "Given SYSTEM and context type CXT-TYPE return the context.")
  858. (cl-defmethod sesman-context ((_cxt-type (eql buffer)) _system)
  859. "Return current buffer."
  860. (current-buffer))
  861. (cl-defmethod sesman-context ((_cxt-type (eql directory)) _system)
  862. "Return current directory."
  863. (sesman-expand-path default-directory))
  864. (cl-defmethod sesman-context ((_cxt-type (eql project)) system)
  865. "Return current project."
  866. (let* ((default-directory (sesman-expand-path default-directory))
  867. (proj (or
  868. (sesman-project (or system (sesman--system)))
  869. ;; Normally we would use (project-roots (project-current)) but currently
  870. ;; project-roots fails on nil and doesn't work on custom `('foo .
  871. ;; "path/to/project"). So, use vc as a fallback and don't use project.el at
  872. ;; all for now.
  873. ;; NB: `vc-root-dir' doesn't work from symlinked files. Emacs Bug?
  874. (vc-root-dir))))
  875. (when proj
  876. (expand-file-name proj))))
  877. (cl-defgeneric sesman-relevant-context-p (_cxt-type cxt)
  878. "Non-nil if context CXT is relevant to current context of type CXT-TYPE.")
  879. (cl-defmethod sesman-relevant-context-p ((_cxt-type (eql buffer)) buf)
  880. "Non-nil if BUF is `current-buffer'."
  881. (eq (current-buffer) buf))
  882. (cl-defmethod sesman-relevant-context-p ((_cxt-type (eql directory)) dir)
  883. "Non-nil if DIR is the parent or equals the `default-directory'."
  884. (when (and dir default-directory)
  885. (string-match-p (concat "^" (sesman-expand-path dir))
  886. (sesman-expand-path default-directory))))
  887. (cl-defmethod sesman-relevant-context-p ((_cxt-type (eql project)) proj)
  888. "Non-nil if PROJ is the parent or equal to the `default-directory'."
  889. (when (and proj default-directory)
  890. (string-match-p (concat "^" (sesman-expand-path proj))
  891. (sesman-expand-path default-directory))))
  892. (defun sesman-relevant-link-p (link &optional cxt-types)
  893. "Return non-nil if LINK is relevant to the current context.
  894. If CXT-TYPES is non-nil, only check relevance for those contexts."
  895. (when (or (null cxt-types)
  896. (member (sesman--lnk-context-type link) cxt-types))
  897. (sesman-relevant-context-p
  898. (sesman--lnk-context-type link)
  899. (sesman--lnk-value link))))
  900. (defun sesman-relevant-session-p (system session &optional cxt-types)
  901. "Return non-nil if SYSTEM's SESSION is relevant to the current context.
  902. If CXT-TYPES is non-nil, only check relevance for those contexts."
  903. (seq-some #'sesman-relevant-link-p
  904. (sesman-links system session cxt-types)))
  905. (define-obsolete-function-alias 'sesman-linked-sessions 'sesman--linked-sessions "v0.3.2")
  906. (provide 'sesman)
  907. ;;; sesman.el ends here